mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-07-14 05:06:14 +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).
250 lines
6.6 KiB
Go
250 lines
6.6 KiB
Go
// Package vcs provides Git/VCS helpers for resolving Go modules and
|
|
// extracting repository credentials.
|
|
package vcs
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// CredentialStore manages git credentials for different repository patterns
|
|
type CredentialStore struct {
|
|
credentials []CredentialEntry
|
|
}
|
|
|
|
// CredentialEntry represents credentials for a specific pattern
|
|
type CredentialEntry struct {
|
|
Pattern string `json:"pattern"` // Glob pattern: "github.com/myorg/*"
|
|
Host string `json:"host"` // Git host: "github.com"
|
|
Username string `json:"username"` // Usually "oauth2" for tokens
|
|
Token string `json:"token"` // Access token
|
|
Fallback bool `json:"fallback"` // Use as fallback if no match
|
|
}
|
|
|
|
// CredentialConfig represents the JSON configuration format
|
|
type CredentialConfig struct {
|
|
Credentials []CredentialEntry `json:"credentials"`
|
|
}
|
|
|
|
// NewCredentialStore creates a new credential store
|
|
func NewCredentialStore() *CredentialStore {
|
|
return &CredentialStore{
|
|
credentials: make([]CredentialEntry, 0),
|
|
}
|
|
}
|
|
|
|
// LoadFromFile loads credentials from a JSON file
|
|
func (cs *CredentialStore) LoadFromFile(path string) error {
|
|
if path == "" {
|
|
log.Debug().Msg("No credential file specified, using system git config")
|
|
return nil
|
|
}
|
|
|
|
// Check if file exists
|
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
|
log.Warn().Str("path", path).Msg("Credential file not found, using system git config")
|
|
return nil
|
|
}
|
|
|
|
data, err := os.ReadFile(path) // #nosec G304 -- Path is from config, not user input
|
|
if err != nil {
|
|
return fmt.Errorf("failed to read credential file: %w", err)
|
|
}
|
|
|
|
var config CredentialConfig
|
|
if err := json.Unmarshal(data, &config); err != nil {
|
|
return fmt.Errorf("failed to parse credential file: %w", err)
|
|
}
|
|
|
|
cs.credentials = config.Credentials
|
|
|
|
log.Info().
|
|
Str("file", path).
|
|
Int("credentials", len(cs.credentials)).
|
|
Msg("Loaded git credentials from file")
|
|
|
|
// Log patterns (not tokens!) for debugging
|
|
for i, cred := range cs.credentials {
|
|
log.Debug().
|
|
Int("index", i).
|
|
Str("pattern", cred.Pattern).
|
|
Str("host", cred.Host).
|
|
Bool("fallback", cred.Fallback).
|
|
Msg("Registered credential pattern")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GetCredentialsForModule finds the best matching credentials for a module path
|
|
// Returns (username, token, found)
|
|
func (cs *CredentialStore) GetCredentialsForModule(modulePath string) (string, string, bool) {
|
|
if len(cs.credentials) == 0 {
|
|
// No credentials configured, rely on system git config
|
|
return "", "", false
|
|
}
|
|
|
|
// Find best match
|
|
var bestMatch *CredentialEntry
|
|
var fallbackMatch *CredentialEntry
|
|
bestMatchLen := 0
|
|
|
|
for i := range cs.credentials {
|
|
cred := &cs.credentials[i]
|
|
|
|
// Check for fallback
|
|
if cred.Fallback {
|
|
fallbackMatch = cred
|
|
continue
|
|
}
|
|
|
|
// Check if pattern matches
|
|
if cs.matchPattern(cred.Pattern, modulePath) {
|
|
// Use longest matching pattern (most specific)
|
|
if len(cred.Pattern) > bestMatchLen {
|
|
bestMatch = cred
|
|
bestMatchLen = len(cred.Pattern)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Use best match if found
|
|
if bestMatch != nil {
|
|
log.Debug().
|
|
Str("module", modulePath).
|
|
Str("pattern", bestMatch.Pattern).
|
|
Str("host", bestMatch.Host).
|
|
Msg("Matched credential pattern")
|
|
return bestMatch.Username, bestMatch.Token, true
|
|
}
|
|
|
|
// Use fallback if available
|
|
if fallbackMatch != nil {
|
|
log.Debug().
|
|
Str("module", modulePath).
|
|
Str("pattern", fallbackMatch.Pattern).
|
|
Msg("Using fallback credentials")
|
|
return fallbackMatch.Username, fallbackMatch.Token, true
|
|
}
|
|
|
|
// No match found
|
|
log.Debug().
|
|
Str("module", modulePath).
|
|
Msg("No credential pattern matched, using system git config")
|
|
return "", "", false
|
|
}
|
|
|
|
// matchPattern checks if a module path matches a credential pattern
|
|
// Supports glob-style patterns:
|
|
// - github.com/myorg/* matches github.com/myorg/repo1, github.com/myorg/repo2
|
|
// - github.com/myorg/repo matches exactly github.com/myorg/repo
|
|
// - * matches everything
|
|
func (cs *CredentialStore) matchPattern(pattern, modulePath string) bool {
|
|
// Exact match
|
|
if pattern == modulePath {
|
|
return true
|
|
}
|
|
|
|
// Wildcard match all
|
|
if pattern == "*" {
|
|
return true
|
|
}
|
|
|
|
// Glob-style matching
|
|
matched, err := filepath.Match(pattern, modulePath)
|
|
if err != nil {
|
|
log.Warn().Err(err).Str("pattern", pattern).Msg("Invalid pattern")
|
|
return false
|
|
}
|
|
|
|
if matched {
|
|
return true
|
|
}
|
|
|
|
// Prefix matching with /*
|
|
if strings.HasSuffix(pattern, "/*") {
|
|
prefix := strings.TrimSuffix(pattern, "/*")
|
|
return strings.HasPrefix(modulePath, prefix+"/")
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// CreateNetrcContent creates .netrc file content for a specific host
|
|
func (cs *CredentialStore) CreateNetrcContent(host, username, token string) string {
|
|
return fmt.Sprintf("machine %s\nlogin %s\npassword %s\n", host, username, token)
|
|
}
|
|
|
|
// GetCredentialsForHost finds credentials for a specific git host (e.g., "github.com")
|
|
// This is useful when you need credentials for a host but don't have a full module path
|
|
func (cs *CredentialStore) GetCredentialsForHost(host string) (string, string, bool) {
|
|
if len(cs.credentials) == 0 {
|
|
return "", "", false
|
|
}
|
|
|
|
// Look for exact host match first
|
|
for i := range cs.credentials {
|
|
cred := &cs.credentials[i]
|
|
if cred.Host == host && !cred.Fallback {
|
|
log.Debug().
|
|
Str("host", host).
|
|
Str("pattern", cred.Pattern).
|
|
Msg("Found credentials for host")
|
|
return cred.Username, cred.Token, true
|
|
}
|
|
}
|
|
|
|
// Try fallback
|
|
for i := range cs.credentials {
|
|
cred := &cs.credentials[i]
|
|
if cred.Fallback {
|
|
log.Debug().
|
|
Str("host", host).
|
|
Msg("Using fallback credentials for host")
|
|
return cred.Username, cred.Token, true
|
|
}
|
|
}
|
|
|
|
return "", "", false
|
|
}
|
|
|
|
// ValidateConfig validates the credential configuration
|
|
func (cs *CredentialStore) ValidateConfig() error {
|
|
hostPatterns := make(map[string]bool)
|
|
|
|
for i, cred := range cs.credentials {
|
|
// Check required fields
|
|
if cred.Pattern == "" {
|
|
return fmt.Errorf("credential entry %d: pattern is required", i)
|
|
}
|
|
if cred.Host == "" && cred.Pattern != "*" {
|
|
return fmt.Errorf("credential entry %d: host is required (pattern: %s)", i, cred.Pattern)
|
|
}
|
|
if cred.Token == "" {
|
|
return fmt.Errorf("credential entry %d: token is required (pattern: %s)", i, cred.Pattern)
|
|
}
|
|
|
|
// Set default username if not provided
|
|
if cred.Username == "" {
|
|
cs.credentials[i].Username = "oauth2"
|
|
}
|
|
|
|
// Check for duplicate patterns
|
|
key := cred.Pattern + ":" + cred.Host
|
|
if hostPatterns[key] && !cred.Fallback {
|
|
log.Warn().
|
|
Str("pattern", cred.Pattern).
|
|
Str("host", cred.Host).
|
|
Msg("Duplicate credential pattern, last one wins")
|
|
}
|
|
hostPatterns[key] = true
|
|
}
|
|
|
|
return nil
|
|
}
|