feat: comprehensive audit + Tier 3 wiring (security/correctness/features)

Multi-agent audit + fix pass covering bugs, security, dead config wiring,
and missing features. All quality gates green: build/vet/test -race/govulncheck/
golangci-lint. Frontend tests 47/47.

SECURITY & CORRECTNESS

- Scanner pipeline fail-closed: cache.go scan timeout now 503 (was goto servePkg);
  scanner.go all-scanners-fail saves ScanStatusError; CheckVulnerabilities blocks
  on missing/error result instead of allowing.
- Scanner argv corrections: govulncheck source-mode + go.mod discovery;
  npm-audit generates lockfile via npm install --package-lock-only --ignore-scripts;
  pip-audit per-extension dispatch (wheel direct / sdist extract+pyproject).
- GHSA version-range filtering implemented (was always-include); url.QueryEscape
  on package name.
- pypi SSRF closed via host allowlist on original_url; url.QueryEscape on
  rewriteURL output.
- Path traversal: cache temp file uses os.CreateTemp; smb keyToPath sanitized;
  filesystem keyToPath returns error + filepath.Abs prefix-verify.
- Goroutine leaks plugged: cache.cleanupWorker stop channel; auth.ValidationCache
  Stop() with sync.Once; ws.unregister buffered with non-blocking send.
- WebSocket double-close panic fixed via sync.Once Client.closeSend().
- Race conditions: gormstore.registryCache sync.RWMutex (was concurrent map
  panic); auth.LastUsedAt no longer mutated under RLock; analytics strict
  lock-ordering invariant (statsMu before downloadsMu).
- Auth validator fails CLOSED on transport/unknown-status errors (was returning
  true,err 'allow cache fallback').
- Credential cache hash full SHA256 (was 8-byte truncate; eliminates 2^32
  collision risk).
- filesystem.fs.used incremented after successful rename (no quota inflation
  race).
- gormstore aggregation events deleted in same tx as insert (no double-counting).
- gormstore.SavePackage uses Updates(map) so zero-value security flags
  (RequiresAuth=false) can be cleared.
- partition_manager validates partition name regex before DROP TABLE.
- vcs/git: version regex validation rejects --option-injection; checkout uses
  --detach -- separator; removed TrimPrefix(repo,'v') that corrupted vault/
  vitess/vim-go.
- WebSocket CheckOrigin allowlist (was return true; CSWSH closed); same-origin
  default + ServerConfig.AllowedOrigins.
- fiber CVE GO-2026-4543 patched (v2.52.10 -> v2.52.12).

FUNCTIONAL FEATURES

- API key DB persistence: APIKeyModel + migration 202604280002, full CRUD,
  async LastUsedAt updates with WaitGroup-tracked goroutines drained on Close.
- Admin bootstrap via GOHOARDER_BOOTSTRAP_ADMIN_KEY env var; idempotent
  (skipped when non-revoked admin already exists).
- Auth middleware factory in pkg/app: RequireAuth, RequireRole, RequirePermission,
  OptionalAuth. Mounted on proxy + read APIs when Auth.Enabled=true.
  DELETE /api/packages/* requires admin role. /health public for k8s probes.
- NFS storage backend: pkg/storage/nfs wraps filesystem with /proc/mounts
  detection (Linux), post-write fsync, read-after-write health probe.
- WebSocket real-time pipeline: pkg/events Broadcaster interface; cache + scanner
  managers emit EventPackageCached / EventPackageDownloaded / EventScanComplete;
  app.go runs 30s EventStatsUpdate ticker. Frontend has full WS client (reconnect
  with exponential backoff 1s->30s, 25s heartbeat, subscriber pattern), Pinia
  realtime store, Dashboard live indicator + activity feed + reactive stats
  override.
- TLS termination: fiber.ListenTLS when Server.TLS.Enabled.
- Pre-warming: Prewarming.Enabled flag wired (was hardcoded false); Interval,
  MaxConcurrent, TopPackages plumbed.
- NetworkConfig wired (timeouts, retry, rate-limit, circuit-breaker).
- AuthConfig.BcryptCost wired.
- Security.Scanners.Static.MaxPackageSize plumbed to cache.io.LimitReader.
- Handlers.{Go,NPM,PyPI}.Enabled gates route mounting.
- Graceful shutdown: authManager.Close drains async writes.

LINT/HYGIENE

- 80 golangci-lint issues resolved: errcheck (Close/Write/RemoveAll wrapped),
  gofmt, gosec G104/G306, govet shadow renames + fieldalignment reorders,
  staticcheck ST1000 pkg comments + QF1003 tagged switches + QF1008 embedded
  field selectors + QF1001 De Morgan's law.

BEHAVIOR CHANGES

- Scanner now fail-closed: deployments without scanner binaries
  (trivy/govulncheck/npm-audit/pip-audit/grype) BLOCK packages instead of
  serving unscanned. Add binaries or plan a future allow-on-scan-error flag.
- WS origin defaults to same-origin; cross-origin dashboards must set
  server.allowed_origins.
- Validator no longer fails open; private packages won't serve from cache when
  validation can't be performed.
- download_events retention dropped from 24h to ~5min (deleted in agg tx).
  Migration 202604280001 purges pre-upgrade events.
- DELETE /api/packages/* requires admin role when auth enabled.

NEW PACKAGES

- pkg/events  - Broadcaster interface
- pkg/storage/nfs  - NFS-aware filesystem wrapper

DEFERRED (out of scope this pass)

- Static scanner implementation (config defines AllowedLicenses/MaxPackageSize/
  BlockSuspicious but pkg/scanner/static/ does not exist).
- AuthConfig.AuditLog wiring (no audit log infra yet).
- CacheConfig.TTLOverrides passthrough (would touch cache.Config beyond
  integrator scope).
This commit is contained in:
2026-04-29 00:57:56 +01:00
parent 3c8b3eb46c
commit e39d6a0f0d
80 changed files with 6383 additions and 661 deletions
+83 -45
View File
@@ -1,3 +1,5 @@
// Package filesystem implements the local-disk Storage backend used for
// development and single-node deployments.
package filesystem
import (
@@ -55,7 +57,11 @@ func (fs *FilesystemStorage) Get(ctx context.Context, key string) (io.ReadCloser
default:
}
path := fs.keyToPath(key)
path, err := fs.keyToPath(key)
if err != nil {
metrics.RecordStorageOperation("filesystem", "get", "error")
return nil, err
}
file, err := os.Open(path) // #nosec G304 -- Path is sanitized storage key
if err != nil {
@@ -80,13 +86,17 @@ func (fs *FilesystemStorage) Put(ctx context.Context, key string, data io.Reader
default:
}
path := fs.keyToPath(key)
path, err := fs.keyToPath(key)
if err != nil {
metrics.RecordStorageOperation("filesystem", "put", "error")
return err
}
dir := filepath.Dir(path)
// Create directory
if err := os.MkdirAll(dir, 0750); err != nil {
if mkErr := os.MkdirAll(dir, 0750); mkErr != nil {
metrics.RecordStorageOperation("filesystem", "put", "error")
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to create directory")
return errors.Wrap(mkErr, errors.ErrCodeStorageFailure, "failed to create directory")
}
// Create temp file for atomic write
@@ -105,7 +115,7 @@ func (fs *FilesystemStorage) Put(ctx context.Context, key string, data io.Reader
written, err := io.Copy(multiWriter, data)
if err != nil {
tempFile.Close() // #nosec G104 -- Cleanup, error not critical
_ = tempFile.Close() // #nosec G104 -- Cleanup, error not critical
_ = os.Remove(tempPath) // #nosec G104 -- Cleanup, error not critical
metrics.RecordStorageOperation("filesystem", "put", "error")
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to write data")
@@ -117,17 +127,6 @@ func (fs *FilesystemStorage) Put(ctx context.Context, key string, data io.Reader
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to close temp file")
}
// Check quota
fs.mu.Lock()
if fs.quota > 0 && fs.used+written > fs.quota {
fs.mu.Unlock()
_ = os.Remove(tempPath) // #nosec G104 -- Cleanup, error not critical
metrics.RecordStorageOperation("filesystem", "put", "quota_exceeded")
return errors.QuotaExceeded(fs.quota)
}
fs.used += written
fs.mu.Unlock()
// Verify checksums if provided
if opts != nil {
md5Sum := hex.EncodeToString(md5Hash.Sum(nil))
@@ -146,21 +145,25 @@ func (fs *FilesystemStorage) Put(ctx context.Context, key string, data io.Reader
}
}
// Atomic rename
if err := os.Rename(tempPath, path); err != nil {
_ = os.Remove(tempPath) // #nosec G104 -- Cleanup, error not critical
fs.mu.Lock()
fs.used -= written
currentUsed := fs.used
// Atomic rename and quota update under lock so that fs.used reflects
// only successfully renamed files. Quota check happens before increment
// to avoid transient inflation seen by concurrent Puts.
fs.mu.Lock()
if fs.quota > 0 && fs.used+written > fs.quota {
fs.mu.Unlock()
_ = os.Remove(tempPath) // #nosec G104 -- Cleanup, error not critical
metrics.RecordStorageOperation("filesystem", "put", "quota_exceeded")
return errors.QuotaExceeded(fs.quota)
}
if err := os.Rename(tempPath, path); err != nil {
fs.mu.Unlock()
_ = os.Remove(tempPath) // #nosec G104 -- Cleanup, error not critical
metrics.RecordStorageOperation("filesystem", "put", "error")
metrics.UpdateCacheSize("filesystem", currentUsed)
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to rename temp file")
}
fs.mu.RLock()
fs.used += written
currentUsed := fs.used
fs.mu.RUnlock()
fs.mu.Unlock()
metrics.RecordStorageOperation("filesystem", "put", "success")
metrics.UpdateCacheSize("filesystem", currentUsed)
@@ -175,7 +178,11 @@ func (fs *FilesystemStorage) Delete(ctx context.Context, key string) error {
default:
}
path := fs.keyToPath(key)
path, err := fs.keyToPath(key)
if err != nil {
metrics.RecordStorageOperation("filesystem", "delete", "error")
return err
}
// Get size before deletion
info, err := os.Stat(path)
@@ -213,8 +220,11 @@ func (fs *FilesystemStorage) Exists(ctx context.Context, key string) (bool, erro
default:
}
path := fs.keyToPath(key)
_, err := os.Stat(path)
path, err := fs.keyToPath(key)
if err != nil {
return false, err
}
_, err = os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
@@ -232,10 +242,13 @@ func (fs *FilesystemStorage) List(ctx context.Context, prefix string, opts *stor
default:
}
searchPath := fs.keyToPath(prefix)
searchPath, err := fs.keyToPath(prefix)
if err != nil {
return nil, err
}
var objects []storage.StorageObject
err := filepath.Walk(searchPath, func(path string, info os.FileInfo, err error) error {
err = filepath.Walk(searchPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil // Skip errors
}
@@ -284,7 +297,10 @@ func (fs *FilesystemStorage) Stat(ctx context.Context, key string) (*storage.Sto
default:
}
path := fs.keyToPath(key)
path, err := fs.keyToPath(key)
if err != nil {
return nil, err
}
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
@@ -331,7 +347,7 @@ func (fs *FilesystemStorage) Health(ctx context.Context) error {
if err != nil {
return errors.Wrap(err, errors.ErrCodeStorageFailure, "cannot write to storage")
}
f.Close() // #nosec G104 -- Cleanup, error not critical
_ = f.Close() // #nosec G104 -- Cleanup, error not critical
_ = os.Remove(tempPath) // #nosec G104 -- Cleanup, error not critical
return nil
@@ -352,7 +368,10 @@ func (fs *FilesystemStorage) GetLocalPath(ctx context.Context, key string) (stri
default:
}
path := fs.keyToPath(key)
path, err := fs.keyToPath(key)
if err != nil {
return "", err
}
// Verify file exists
if _, err := os.Stat(path); err != nil {
@@ -365,27 +384,46 @@ func (fs *FilesystemStorage) GetLocalPath(ctx context.Context, key string) (stri
return path, nil
}
// keyToPath converts a storage key to filesystem path
func (fs *FilesystemStorage) keyToPath(key string) string {
// keyToPath converts a storage key to filesystem path.
// It sanitizes the key to prevent path traversal and verifies that the
// resulting absolute path stays within the configured base directory as a
// defense-in-depth check on top of filepath.Clean/Join semantics.
func (fs *FilesystemStorage) keyToPath(key string) (string, error) {
// Sanitize key to prevent path traversal
key = filepath.Clean(key)
cleaned := filepath.Clean(key)
// Remove any leading slashes or dots
key = strings.TrimPrefix(key, "/")
cleaned = strings.TrimPrefix(cleaned, "/")
// Keep removing ../ until there are no more
for strings.HasPrefix(key, "../") || strings.HasPrefix(key, "..\\") {
key = strings.TrimPrefix(key, "../")
key = strings.TrimPrefix(key, "..\\")
for strings.HasPrefix(cleaned, "../") || strings.HasPrefix(cleaned, "..\\") {
cleaned = strings.TrimPrefix(cleaned, "../")
cleaned = strings.TrimPrefix(cleaned, "..\\")
}
// Final clean and ensure it's within base path
key = filepath.Clean(key)
if key == ".." || strings.HasPrefix(key, "../") || strings.HasPrefix(key, "..\\") {
key = ""
cleaned = filepath.Clean(cleaned)
if cleaned == ".." || strings.HasPrefix(cleaned, "../") || strings.HasPrefix(cleaned, "..\\") {
cleaned = ""
}
return filepath.Join(fs.basePath, key)
target := filepath.Join(fs.basePath, cleaned)
// Defense-in-depth: verify the resolved absolute path is contained
// within the base directory.
targetAbs, err := filepath.Abs(target)
if err != nil {
return "", errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to resolve path")
}
baseAbs, err := filepath.Abs(fs.basePath)
if err != nil {
return "", errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to resolve base path")
}
if targetAbs != baseAbs && !strings.HasPrefix(targetAbs, baseAbs+string(os.PathSeparator)) {
return "", errors.New(errors.ErrCodeStorageFailure, fmt.Sprintf("path traversal rejected: %s", key))
}
return target, nil
}
// calculateUsage calculates current storage usage