mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-07-15 05:25:45 +00:00
e39d6a0f0d
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).
236 lines
6.2 KiB
Go
236 lines
6.2 KiB
Go
// Package cdn provides CDN-friendly HTTP middleware (ETag, Cache-Control)
|
|
// for proxying cached package responses.
|
|
package cdn
|
|
|
|
import (
|
|
"crypto/md5" // #nosec G501 -- MD5 used for ETag generation, not cryptographic security
|
|
"encoding/hex"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// CacheControl represents cache control directives
|
|
type CacheControl struct {
|
|
MaxAge int // max-age in seconds
|
|
SMaxAge int // s-maxage in seconds (for shared caches)
|
|
Public bool // public directive
|
|
Private bool // private directive
|
|
NoCache bool // no-cache directive
|
|
NoStore bool // no-store directive
|
|
MustRevalidate bool // must-revalidate directive
|
|
ProxyRevalidate bool // proxy-revalidate directive
|
|
Immutable bool // immutable directive
|
|
StaleWhileRevalidate int // stale-while-revalidate in seconds
|
|
}
|
|
|
|
// String returns the Cache-Control header value
|
|
func (cc CacheControl) String() string {
|
|
var parts []string
|
|
|
|
if cc.Public {
|
|
parts = append(parts, "public")
|
|
}
|
|
if cc.Private {
|
|
parts = append(parts, "private")
|
|
}
|
|
if cc.NoCache {
|
|
parts = append(parts, "no-cache")
|
|
}
|
|
if cc.NoStore {
|
|
parts = append(parts, "no-store")
|
|
}
|
|
if cc.MustRevalidate {
|
|
parts = append(parts, "must-revalidate")
|
|
}
|
|
if cc.ProxyRevalidate {
|
|
parts = append(parts, "proxy-revalidate")
|
|
}
|
|
if cc.Immutable {
|
|
parts = append(parts, "immutable")
|
|
}
|
|
if cc.MaxAge > 0 {
|
|
parts = append(parts, fmt.Sprintf("max-age=%d", cc.MaxAge))
|
|
}
|
|
if cc.SMaxAge > 0 {
|
|
parts = append(parts, fmt.Sprintf("s-maxage=%d", cc.SMaxAge))
|
|
}
|
|
if cc.StaleWhileRevalidate > 0 {
|
|
parts = append(parts, fmt.Sprintf("stale-while-revalidate=%d", cc.StaleWhileRevalidate))
|
|
}
|
|
|
|
result := ""
|
|
for i, part := range parts {
|
|
if i > 0 {
|
|
result += ", "
|
|
}
|
|
result += part
|
|
}
|
|
return result
|
|
}
|
|
|
|
// Middleware provides CDN and HTTP caching functionality
|
|
type Middleware struct {
|
|
defaultCacheControl CacheControl
|
|
enableETag bool
|
|
enableVary bool
|
|
}
|
|
|
|
// Config holds CDN middleware configuration
|
|
type Config struct {
|
|
DefaultCacheControl CacheControl
|
|
EnableETag bool
|
|
EnableVary bool
|
|
}
|
|
|
|
// NewMiddleware creates a new CDN middleware
|
|
func NewMiddleware(cfg Config) *Middleware {
|
|
return &Middleware{
|
|
defaultCacheControl: cfg.DefaultCacheControl,
|
|
enableETag: cfg.EnableETag,
|
|
enableVary: cfg.EnableVary,
|
|
}
|
|
}
|
|
|
|
// Handler wraps an HTTP handler with CDN caching support
|
|
func (m *Middleware) Handler(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Wrap response writer to capture response for ETag generation
|
|
rw := &responseWriter{
|
|
ResponseWriter: w,
|
|
statusCode: http.StatusOK,
|
|
body: nil,
|
|
}
|
|
|
|
// Call next handler
|
|
next.ServeHTTP(rw, r)
|
|
|
|
// Apply caching headers if successful response
|
|
if rw.statusCode >= 200 && rw.statusCode < 300 {
|
|
m.applyCachingHeaders(rw, r)
|
|
}
|
|
})
|
|
}
|
|
|
|
// applyCachingHeaders applies appropriate caching headers to the response
|
|
func (m *Middleware) applyCachingHeaders(w *responseWriter, r *http.Request) {
|
|
// Set Cache-Control header if not already set
|
|
if w.Header().Get("Cache-Control") == "" {
|
|
w.Header().Set("Cache-Control", m.defaultCacheControl.String())
|
|
}
|
|
|
|
// Set Vary header for content negotiation
|
|
if m.enableVary {
|
|
m.setVaryHeader(w, r)
|
|
}
|
|
|
|
// Generate and check ETag if enabled
|
|
if m.enableETag && w.body != nil {
|
|
m.handleETag(w, r)
|
|
}
|
|
}
|
|
|
|
// setVaryHeader sets the Vary header based on request
|
|
func (m *Middleware) setVaryHeader(w *responseWriter, r *http.Request) {
|
|
varies := []string{}
|
|
|
|
// Vary on Accept-Encoding for compression
|
|
if r.Header.Get("Accept-Encoding") != "" {
|
|
varies = append(varies, "Accept-Encoding")
|
|
}
|
|
|
|
// Vary on Authorization for authenticated requests
|
|
if r.Header.Get("Authorization") != "" {
|
|
varies = append(varies, "Authorization")
|
|
}
|
|
|
|
// Vary on Accept for content negotiation
|
|
if r.Header.Get("Accept") != "" {
|
|
varies = append(varies, "Accept")
|
|
}
|
|
|
|
if len(varies) > 0 {
|
|
varyHeader := ""
|
|
for i, v := range varies {
|
|
if i > 0 {
|
|
varyHeader += ", "
|
|
}
|
|
varyHeader += v
|
|
}
|
|
w.Header().Set("Vary", varyHeader)
|
|
}
|
|
}
|
|
|
|
// handleETag generates ETag and handles conditional requests
|
|
func (m *Middleware) handleETag(w *responseWriter, r *http.Request) {
|
|
// Generate ETag from response body
|
|
etag := m.generateETag(w.body)
|
|
w.Header().Set("ETag", etag)
|
|
|
|
// Handle conditional requests
|
|
if ifNoneMatch := r.Header.Get("If-None-Match"); ifNoneMatch != "" {
|
|
if ifNoneMatch == etag {
|
|
// ETag matches - return 304 Not Modified
|
|
w.WriteHeader(http.StatusNotModified)
|
|
w.body = nil // Clear body for 304 response
|
|
log.Debug().
|
|
Str("path", r.URL.Path).
|
|
Str("etag", etag).
|
|
Msg("ETag match - returning 304 Not Modified")
|
|
return
|
|
}
|
|
}
|
|
|
|
// Handle If-Modified-Since
|
|
if lastModified := w.Header().Get("Last-Modified"); lastModified != "" {
|
|
if ifModifiedSince := r.Header.Get("If-Modified-Since"); ifModifiedSince != "" {
|
|
lastModTime, err := http.ParseTime(lastModified)
|
|
if err == nil {
|
|
ifModTime, err := http.ParseTime(ifModifiedSince)
|
|
if err == nil && !lastModTime.After(ifModTime) {
|
|
// Not modified - return 304
|
|
w.WriteHeader(http.StatusNotModified)
|
|
w.body = nil
|
|
log.Debug().
|
|
Str("path", r.URL.Path).
|
|
Time("last_modified", lastModTime).
|
|
Msg("Not modified - returning 304")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// generateETag creates an ETag for HTTP caching
|
|
// NOTE: MD5 is used for content fingerprinting (ETag), not cryptographic security
|
|
func (m *Middleware) generateETag(body []byte) string {
|
|
if body == nil {
|
|
return ""
|
|
}
|
|
hash := md5.Sum(body) // #nosec G401 -- MD5 used for ETag, not cryptographic security
|
|
return `"` + hex.EncodeToString(hash[:]) + `"`
|
|
}
|
|
|
|
// responseWriter wraps http.ResponseWriter to capture response
|
|
type responseWriter struct {
|
|
http.ResponseWriter
|
|
body []byte
|
|
statusCode int
|
|
}
|
|
|
|
func (rw *responseWriter) WriteHeader(statusCode int) {
|
|
rw.statusCode = statusCode
|
|
rw.ResponseWriter.WriteHeader(statusCode)
|
|
}
|
|
|
|
func (rw *responseWriter) Write(b []byte) (int, error) {
|
|
// Capture body for ETag generation
|
|
if rw.body == nil {
|
|
rw.body = make([]byte, 0, len(b))
|
|
}
|
|
rw.body = append(rw.body, b...)
|
|
return rw.ResponseWriter.Write(b)
|
|
}
|