mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-07-14 05:06:14 +00:00
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:
+283
-25
@@ -1,20 +1,48 @@
|
||||
// Package auth implements API key issuance, validation, and credential
|
||||
// extraction for upstream-registry pass-through authentication.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/rs/zerolog/log"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// Manager handles authentication and authorization
|
||||
// Config controls Manager behaviour. Zero value is valid: bcrypt cost defaults
|
||||
// to bcrypt.DefaultCost, store is nil (in-memory only).
|
||||
type Config struct {
|
||||
// BcryptCost is the cost parameter passed to bcrypt.GenerateFromPassword.
|
||||
// 0 means use bcrypt.DefaultCost. Tests typically use bcrypt.MinCost.
|
||||
BcryptCost int
|
||||
}
|
||||
|
||||
// Manager handles authentication and authorization.
|
||||
//
|
||||
// Persistence model:
|
||||
// - All keys live in an in-memory map keyed by APIKey.ID for O(1) revoke
|
||||
// and fast bcrypt iteration during validation.
|
||||
// - When a metadata.MetadataStore is wired in via NewWithStore, mutations
|
||||
// (Generate, Revoke) are mirrored to the store synchronously and
|
||||
// LastUsedAt updates are flushed asynchronously to avoid blocking the
|
||||
// hot validation path on a DB round-trip.
|
||||
// - When the store is nil, Manager is purely in-memory (back-compat for
|
||||
// tests and unconfigured deployments).
|
||||
type Manager struct {
|
||||
keys map[string]*APIKey
|
||||
mu sync.RWMutex
|
||||
keys map[string]*APIKey
|
||||
store metadata.MetadataStore
|
||||
cfg Config
|
||||
mu sync.RWMutex
|
||||
bgWG sync.WaitGroup
|
||||
closed bool
|
||||
}
|
||||
|
||||
// APIKey represents an API key
|
||||
@@ -23,6 +51,7 @@ type APIKey struct {
|
||||
Name string
|
||||
HashedKey string
|
||||
Role Role
|
||||
Project string
|
||||
CreatedAt time.Time
|
||||
ExpiresAt *time.Time
|
||||
LastUsedAt time.Time
|
||||
@@ -38,6 +67,15 @@ const (
|
||||
RoleAdmin Role = "admin"
|
||||
)
|
||||
|
||||
// Persistent role identifiers stored in metadata.APIKey.Role. Different from
|
||||
// the in-memory Role values for backward compatibility with existing API
|
||||
// surfaces while matching the storage schema described in the spec.
|
||||
const (
|
||||
storedRoleReadOnly = "read_only"
|
||||
storedRoleReadWrite = "read_write"
|
||||
storedRoleAdmin = "admin"
|
||||
)
|
||||
|
||||
// Permission represents a specific permission
|
||||
type Permission string
|
||||
|
||||
@@ -52,14 +90,63 @@ const (
|
||||
PermissionManageBypasses Permission = "bypasses:manage"
|
||||
)
|
||||
|
||||
// New creates a new authentication manager
|
||||
// New creates a new authentication manager (in-memory only).
|
||||
// Equivalent to NewWithStore(Config{}, nil).
|
||||
func New() *Manager {
|
||||
return NewWithStore(Config{}, nil)
|
||||
}
|
||||
|
||||
// NewWithStore creates a Manager backed by an optional metadata store.
|
||||
// Pass store=nil for purely in-memory mode (tests, ephemeral setups).
|
||||
func NewWithStore(cfg Config, store metadata.MetadataStore) *Manager {
|
||||
if cfg.BcryptCost == 0 {
|
||||
cfg.BcryptCost = bcrypt.DefaultCost
|
||||
}
|
||||
return &Manager{
|
||||
keys: make(map[string]*APIKey),
|
||||
keys: make(map[string]*APIKey),
|
||||
store: store,
|
||||
cfg: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateAPIKey generates a new API key
|
||||
// Load pulls all non-revoked keys from the store into the in-memory map.
|
||||
// Safe to call multiple times: it replaces the in-memory snapshot.
|
||||
// No-op when store is nil or returns ErrNotImplemented.
|
||||
func (m *Manager) Load(ctx context.Context) error {
|
||||
if m.store == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
stored, err := m.store.ListAPIKeys(ctx)
|
||||
if err != nil {
|
||||
if stderrors.Is(err, metadata.ErrNotImplemented) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
loaded := make(map[string]*APIKey, len(stored))
|
||||
for _, k := range stored {
|
||||
if k == nil || k.Revoked {
|
||||
continue
|
||||
}
|
||||
loaded[k.ID] = storedToMemory(k)
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
m.keys = loaded
|
||||
m.mu.Unlock()
|
||||
|
||||
log.Info().Int("count", len(loaded)).Msg("Loaded API keys from metadata store")
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenerateAPIKey generates a new API key.
|
||||
//
|
||||
// When a store is configured, the key is persisted before returning. If the
|
||||
// store rejects the write the in-memory state is rolled back and the error
|
||||
// is propagated; we never return a key the caller cannot actually use after
|
||||
// a restart.
|
||||
func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duration) (*APIKey, string, error) {
|
||||
// Generate random key
|
||||
keyBytes := make([]byte, 32)
|
||||
@@ -69,8 +156,8 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
|
||||
rawKey := base64.URLEncoding.EncodeToString(keyBytes)
|
||||
|
||||
// Hash the key
|
||||
hashedKey, err := bcrypt.GenerateFromPassword([]byte(rawKey), bcrypt.DefaultCost)
|
||||
// Hash the key with the configured cost.
|
||||
hashedKey, err := bcrypt.GenerateFromPassword([]byte(rawKey), m.cfg.BcryptCost)
|
||||
if err != nil {
|
||||
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to hash key")
|
||||
}
|
||||
@@ -95,24 +182,57 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
m.keys[apiKey.ID] = apiKey
|
||||
m.mu.Unlock()
|
||||
|
||||
if m.store != nil {
|
||||
stored := memoryToStored(apiKey)
|
||||
if err := m.store.SaveAPIKey(context.Background(), stored); err != nil {
|
||||
if !stderrors.Is(err, metadata.ErrNotImplemented) {
|
||||
// Rollback in-memory insert so caller sees a consistent failure.
|
||||
m.mu.Lock()
|
||||
delete(m.keys, apiKey.ID)
|
||||
m.mu.Unlock()
|
||||
return nil, "", errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to persist api key")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return apiKey, rawKey, nil
|
||||
}
|
||||
|
||||
// ValidateAPIKey validates an API key and returns the associated key object
|
||||
// ValidateAPIKey validates an API key and returns the associated key object.
|
||||
// Hot path: snapshots candidates, runs bcrypt without holding the lock.
|
||||
// LastUsedAt is updated in-memory under the write lock and flushed to the
|
||||
// store via a fire-and-forget goroutine.
|
||||
func (m *Manager) ValidateAPIKey(ctx context.Context, rawKey string) (*APIKey, error) {
|
||||
// Phase 1: snapshot non-expired candidates under RLock. We hold pointers
|
||||
// to APIKey; APIKey.HashedKey is an immutable string so reading it
|
||||
// without a lock is safe even if the key is later removed from the map.
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
candidates := make([]*APIKey, 0, len(m.keys))
|
||||
now := time.Now()
|
||||
for _, apiKey := range m.keys {
|
||||
// Check if key is expired
|
||||
if apiKey.ExpiresAt != nil && time.Now().After(*apiKey.ExpiresAt) {
|
||||
if apiKey.ExpiresAt != nil && now.After(*apiKey.ExpiresAt) {
|
||||
continue
|
||||
}
|
||||
candidates = append(candidates, apiKey)
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
|
||||
// Compare hashed key
|
||||
// Phase 2: run bcrypt comparisons without holding any lock so concurrent
|
||||
// auth checks can proceed in parallel.
|
||||
for _, apiKey := range candidates {
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(apiKey.HashedKey), []byte(rawKey)); err == nil {
|
||||
// Update last used
|
||||
apiKey.LastUsedAt = time.Now()
|
||||
// Phase 3: briefly take the write lock to update LastUsedAt.
|
||||
// Re-check the key still exists in the map to avoid resurrecting
|
||||
// a revoked key's metadata.
|
||||
usedAt := time.Now()
|
||||
m.mu.Lock()
|
||||
if _, ok := m.keys[apiKey.ID]; ok {
|
||||
apiKey.LastUsedAt = usedAt
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// Async store update: never block validation on a DB write.
|
||||
m.persistLastUsedAsync(apiKey.ID, usedAt)
|
||||
return apiKey, nil
|
||||
}
|
||||
}
|
||||
@@ -120,16 +240,63 @@ func (m *Manager) ValidateAPIKey(ctx context.Context, rawKey string) (*APIKey, e
|
||||
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key")
|
||||
}
|
||||
|
||||
// RevokeAPIKey revokes an API key
|
||||
func (m *Manager) RevokeAPIKey(keyID string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if _, exists := m.keys[keyID]; !exists {
|
||||
return errors.NotFound("API key not found")
|
||||
// persistLastUsedAsync flushes a LastUsedAt update to the store off the hot
|
||||
// path. Errors are logged but not propagated — the validation succeeded
|
||||
// in-memory and that is the source of truth for liveness.
|
||||
func (m *Manager) persistLastUsedAsync(id string, t time.Time) {
|
||||
if m.store == nil {
|
||||
return
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
if m.closed {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
m.bgWG.Add(1)
|
||||
m.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
defer m.bgWG.Done()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := m.store.UpdateAPIKeyLastUsed(ctx, id, t); err != nil {
|
||||
if !stderrors.Is(err, metadata.ErrNotImplemented) {
|
||||
log.Warn().Err(err).Str("key_id", id).Msg("Failed to persist api key LastUsedAt")
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// RevokeAPIKey revokes an API key. With a store configured, revocation is
|
||||
// persisted (Revoked=true) so the key remains queryable for audit but never
|
||||
// authenticates again.
|
||||
func (m *Manager) RevokeAPIKey(keyID string) error {
|
||||
m.mu.Lock()
|
||||
existing, ok := m.keys[keyID]
|
||||
if !ok {
|
||||
m.mu.Unlock()
|
||||
return errors.NotFound("API key not found")
|
||||
}
|
||||
delete(m.keys, keyID)
|
||||
m.mu.Unlock()
|
||||
|
||||
if m.store != nil {
|
||||
stored := memoryToStored(existing)
|
||||
stored.Revoked = true
|
||||
if err := m.store.SaveAPIKey(context.Background(), stored); err != nil {
|
||||
if !stderrors.Is(err, metadata.ErrNotImplemented) {
|
||||
// Rollback: re-add to memory so subsequent validation still
|
||||
// sees it (rather than silently leaving a window where the
|
||||
// key works in-memory only on this replica).
|
||||
m.mu.Lock()
|
||||
m.keys[keyID] = existing
|
||||
m.mu.Unlock()
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to persist revocation")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -145,6 +312,19 @@ func (m *Manager) ListAPIKeys() []*APIKey {
|
||||
return keys
|
||||
}
|
||||
|
||||
// Close waits for any in-flight background writes (LastUsedAt updates) to
|
||||
// finish. Safe to call multiple times.
|
||||
func (m *Manager) Close() {
|
||||
m.mu.Lock()
|
||||
if m.closed {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
m.closed = true
|
||||
m.mu.Unlock()
|
||||
m.bgWG.Wait()
|
||||
}
|
||||
|
||||
// HasPermission checks if an API key has a specific permission
|
||||
func (k *APIKey) HasPermission(permission Permission) bool {
|
||||
for _, p := range k.Permissions {
|
||||
@@ -185,9 +365,87 @@ func getPermissionsForRole(role Role) []Permission {
|
||||
}
|
||||
}
|
||||
|
||||
// generateID generates a unique ID
|
||||
// generateID generates a unique ID. Panics on crypto/rand failure: a
|
||||
// zero-byte ID would be a security catastrophe (collisions, predictability).
|
||||
func generateID() string {
|
||||
b := make([]byte, 16)
|
||||
_, _ = rand.Read(b) // #nosec G104 -- Rand read always succeeds
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(fmt.Sprintf("auth: crypto/rand read failed: %v", err))
|
||||
}
|
||||
return base64.URLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// memoryToStored converts an in-memory APIKey to its metadata-layer form.
|
||||
// Permissions are deliberately not encoded here: they are derived from Role
|
||||
// at load time, keeping the persisted representation compact.
|
||||
func memoryToStored(k *APIKey) *metadata.APIKey {
|
||||
var lastUsed *time.Time
|
||||
if !k.LastUsedAt.IsZero() {
|
||||
t := k.LastUsedAt
|
||||
lastUsed = &t
|
||||
}
|
||||
|
||||
return &metadata.APIKey{
|
||||
ID: k.ID,
|
||||
KeyHash: k.HashedKey,
|
||||
Project: k.Project,
|
||||
Role: roleToStored(k.Role),
|
||||
CreatedAt: k.CreatedAt,
|
||||
ExpiresAt: k.ExpiresAt,
|
||||
LastUsedAt: lastUsed,
|
||||
Revoked: false,
|
||||
}
|
||||
}
|
||||
|
||||
// storedToMemory converts a metadata.APIKey to its runtime form. Permissions
|
||||
// are derived from Role to keep storage minimal.
|
||||
func storedToMemory(k *metadata.APIKey) *APIKey {
|
||||
role := storedToRole(k.Role)
|
||||
out := &APIKey{
|
||||
ID: k.ID,
|
||||
Name: "", // not persisted
|
||||
HashedKey: k.KeyHash,
|
||||
Role: role,
|
||||
Project: k.Project,
|
||||
CreatedAt: k.CreatedAt,
|
||||
ExpiresAt: k.ExpiresAt,
|
||||
Permissions: getPermissionsForRole(role),
|
||||
}
|
||||
if k.LastUsedAt != nil {
|
||||
out.LastUsedAt = *k.LastUsedAt
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// roleToStored maps the in-memory Role enum to its persisted string form.
|
||||
func roleToStored(r Role) string {
|
||||
switch r {
|
||||
case RoleReadOnly:
|
||||
return storedRoleReadOnly
|
||||
case RoleReadWrite:
|
||||
return storedRoleReadWrite
|
||||
case RoleAdmin:
|
||||
return storedRoleAdmin
|
||||
default:
|
||||
return string(r)
|
||||
}
|
||||
}
|
||||
|
||||
// storedToRole inverts roleToStored. Unknown values fall back to RoleReadOnly
|
||||
// (least-privilege) rather than failing — guards against schema drift.
|
||||
func storedToRole(s string) Role {
|
||||
switch s {
|
||||
case storedRoleAdmin:
|
||||
return RoleAdmin
|
||||
case storedRoleReadWrite:
|
||||
return RoleReadWrite
|
||||
case storedRoleReadOnly:
|
||||
return RoleReadOnly
|
||||
}
|
||||
// Tolerate legacy in-memory values that may have been persisted.
|
||||
switch Role(s) {
|
||||
case RoleAdmin, RoleReadWrite, RoleReadOnly:
|
||||
return Role(s)
|
||||
}
|
||||
return RoleReadOnly
|
||||
}
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// fakeStore is a minimal in-memory metadata.MetadataStore. Only the API key
|
||||
// methods are exercised; everything else returns ErrNotImplemented to make
|
||||
// accidental calls obvious.
|
||||
type fakeStore struct {
|
||||
keys map[string]*metadata.APIKey
|
||||
saveErr error
|
||||
listErr error
|
||||
updateErr error
|
||||
mu sync.Mutex
|
||||
saveCalls int
|
||||
updateCalls int
|
||||
disabled bool // when true, every API key method returns ErrNotImplemented
|
||||
}
|
||||
|
||||
func newFakeStore() *fakeStore {
|
||||
return &fakeStore{keys: make(map[string]*metadata.APIKey)}
|
||||
}
|
||||
|
||||
func (f *fakeStore) SaveAPIKey(ctx context.Context, key *metadata.APIKey) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.disabled {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
f.saveCalls++
|
||||
if f.saveErr != nil {
|
||||
return f.saveErr
|
||||
}
|
||||
cp := *key
|
||||
f.keys[key.ID] = &cp
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetAPIKey(ctx context.Context, id string) (*metadata.APIKey, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.disabled {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
k, ok := f.keys[id]
|
||||
if !ok {
|
||||
return nil, stderrors.New("not found")
|
||||
}
|
||||
cp := *k
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) ListAPIKeys(ctx context.Context) ([]*metadata.APIKey, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.disabled {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
if f.listErr != nil {
|
||||
return nil, f.listErr
|
||||
}
|
||||
out := make([]*metadata.APIKey, 0, len(f.keys))
|
||||
for _, k := range f.keys {
|
||||
cp := *k
|
||||
out = append(out, &cp)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) DeleteAPIKey(ctx context.Context, id string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.disabled {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
delete(f.keys, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) UpdateAPIKeyLastUsed(ctx context.Context, id string, t time.Time) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.disabled {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
f.updateCalls++
|
||||
if f.updateErr != nil {
|
||||
return f.updateErr
|
||||
}
|
||||
if k, ok := f.keys[id]; ok {
|
||||
tt := t
|
||||
k.LastUsedAt = &tt
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// All other methods are unreachable from auth.Manager — return ErrNotImplemented
|
||||
// so accidental usage in future tests fails loudly.
|
||||
func (f *fakeStore) SavePackage(context.Context, *metadata.Package) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetPackage(context.Context, string, string, string) (*metadata.Package, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) DeletePackage(context.Context, string, string, string) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) UpdateDownloadCount(context.Context, string, string, string) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetStats(context.Context, string) (*metadata.Stats, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) SaveScanResult(context.Context, *metadata.ScanResult) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetScanResult(context.Context, string, string, string) (*metadata.ScanResult, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) SaveCVEBypass(context.Context, *metadata.CVEBypass) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetActiveCVEBypasses(context.Context) ([]*metadata.CVEBypass, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) ListCVEBypasses(context.Context, *metadata.BypassListOptions) ([]*metadata.CVEBypass, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) DeleteCVEBypass(context.Context, string) error { return metadata.ErrNotImplemented }
|
||||
func (f *fakeStore) CleanupExpiredBypasses(context.Context) (int, error) {
|
||||
return 0, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) Count(context.Context) (int, error) { return 0, metadata.ErrNotImplemented }
|
||||
func (f *fakeStore) Health(context.Context) error { return metadata.ErrNotImplemented }
|
||||
func (f *fakeStore) GetTimeSeriesStats(context.Context, string, string) (*metadata.TimeSeriesStats, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) AggregateDownloadData(context.Context) error { return metadata.ErrNotImplemented }
|
||||
func (f *fakeStore) Close() error { return nil }
|
||||
|
||||
// fastCfg uses bcrypt.MinCost so tests that hash multiple keys stay snappy.
|
||||
func fastCfg() Config { return Config{BcryptCost: bcrypt.MinCost} }
|
||||
|
||||
func TestManager_GenerateAPIKey_PersistsToStore(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
m := NewWithStore(fastCfg(), store)
|
||||
defer m.Close()
|
||||
|
||||
apiKey, raw, err := m.GenerateAPIKey("svc-token", RoleReadWrite, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateAPIKey: %v", err)
|
||||
}
|
||||
if raw == "" {
|
||||
t.Fatalf("raw key empty")
|
||||
}
|
||||
if apiKey.ID == "" {
|
||||
t.Fatalf("apiKey.ID empty")
|
||||
}
|
||||
|
||||
if store.saveCalls != 1 {
|
||||
t.Errorf("saveCalls = %d, want 1", store.saveCalls)
|
||||
}
|
||||
persisted, err := store.GetAPIKey(context.Background(), apiKey.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAPIKey persisted: %v", err)
|
||||
}
|
||||
if persisted.Role != storedRoleReadWrite {
|
||||
t.Errorf("persisted Role = %q, want %q", persisted.Role, storedRoleReadWrite)
|
||||
}
|
||||
if persisted.Revoked {
|
||||
t.Errorf("persisted Revoked = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_GenerateAPIKey_StoreFailure_RollsBack(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
store.saveErr = stderrors.New("disk full")
|
||||
m := NewWithStore(fastCfg(), store)
|
||||
defer m.Close()
|
||||
|
||||
_, _, err := m.GenerateAPIKey("svc", RoleReadOnly, nil)
|
||||
if err == nil {
|
||||
t.Fatalf("want error from store, got nil")
|
||||
}
|
||||
if got := len(m.ListAPIKeys()); got != 0 {
|
||||
t.Errorf("in-memory keys = %d, want 0 after rollback", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_RevokeAPIKey_PersistsRevocation(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
m := NewWithStore(fastCfg(), store)
|
||||
defer m.Close()
|
||||
|
||||
key, _, err := m.GenerateAPIKey("svc", RoleAdmin, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
|
||||
if revokeErr := m.RevokeAPIKey(key.ID); revokeErr != nil {
|
||||
t.Fatalf("Revoke: %v", revokeErr)
|
||||
}
|
||||
persisted, err := store.GetAPIKey(context.Background(), key.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAPIKey after revoke: %v", err)
|
||||
}
|
||||
if !persisted.Revoked {
|
||||
t.Errorf("persisted Revoked = false, want true")
|
||||
}
|
||||
if got := len(m.ListAPIKeys()); got != 0 {
|
||||
t.Errorf("in-memory keys after revoke = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_RevokeAPIKey_StoreFailure_KeepsInMemory(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
m := NewWithStore(fastCfg(), store)
|
||||
defer m.Close()
|
||||
|
||||
key, _, err := m.GenerateAPIKey("svc", RoleAdmin, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
|
||||
store.saveErr = stderrors.New("DB exploded")
|
||||
if err := m.RevokeAPIKey(key.ID); err == nil {
|
||||
t.Fatalf("want error from Revoke, got nil")
|
||||
}
|
||||
if got := len(m.ListAPIKeys()); got != 1 {
|
||||
t.Errorf("in-memory keys = %d, want 1 (rollback)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_Load_HydratesFromStore(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
|
||||
// Pre-populate the store directly.
|
||||
for _, tc := range []struct {
|
||||
id string
|
||||
role string
|
||||
revoked bool
|
||||
}{
|
||||
{"a", storedRoleAdmin, false},
|
||||
{"b", storedRoleReadOnly, false},
|
||||
{"c", storedRoleReadWrite, true}, // revoked: should be skipped
|
||||
} {
|
||||
_ = store.SaveAPIKey(context.Background(), &metadata.APIKey{
|
||||
ID: tc.id, KeyHash: "h", Role: tc.role, Revoked: tc.revoked, CreatedAt: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
m := NewWithStore(fastCfg(), store)
|
||||
defer m.Close()
|
||||
|
||||
if err := m.Load(context.Background()); err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
keys := m.ListAPIKeys()
|
||||
if len(keys) != 2 {
|
||||
t.Fatalf("loaded %d keys, want 2 (revoked excluded)", len(keys))
|
||||
}
|
||||
for _, k := range keys {
|
||||
if k.Role != RoleAdmin && k.Role != RoleReadOnly {
|
||||
t.Errorf("unexpected role %q", k.Role)
|
||||
}
|
||||
if len(k.Permissions) == 0 {
|
||||
t.Errorf("permissions empty for role %q (should be derived)", k.Role)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_Load_NilStore_NoOp(t *testing.T) {
|
||||
m := NewWithStore(fastCfg(), nil)
|
||||
defer m.Close()
|
||||
if err := m.Load(context.Background()); err != nil {
|
||||
t.Fatalf("Load with nil store: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_Load_NotImplemented_NoOp(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
store.disabled = true
|
||||
m := NewWithStore(fastCfg(), store)
|
||||
defer m.Close()
|
||||
if err := m.Load(context.Background()); err != nil {
|
||||
t.Fatalf("Load with disabled store: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_ValidateAPIKey_AsyncLastUsed(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
m := NewWithStore(fastCfg(), store)
|
||||
defer m.Close()
|
||||
|
||||
_, raw, err := m.GenerateAPIKey("svc", RoleReadOnly, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
|
||||
if _, err := m.ValidateAPIKey(context.Background(), raw); err != nil {
|
||||
t.Fatalf("Validate: %v", err)
|
||||
}
|
||||
|
||||
// Wait for the fire-and-forget goroutine.
|
||||
m.Close()
|
||||
|
||||
if store.updateCalls < 1 {
|
||||
t.Errorf("UpdateAPIKeyLastUsed not called (calls=%d)", store.updateCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_ValidateAPIKey_RejectsUnknown(t *testing.T) {
|
||||
m := NewWithStore(fastCfg(), nil)
|
||||
defer m.Close()
|
||||
if _, err := m.ValidateAPIKey(context.Background(), "no-such-key"); err == nil {
|
||||
t.Fatalf("Validate(unknown): want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_InMemoryMode_StillWorks(t *testing.T) {
|
||||
// Back-compat: the legacy New() constructor must continue working
|
||||
// without a store.
|
||||
m := New()
|
||||
defer m.Close()
|
||||
apiKey, raw, err := m.GenerateAPIKey("legacy", RoleReadOnly, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
got, err := m.ValidateAPIKey(context.Background(), raw)
|
||||
if err != nil {
|
||||
t.Fatalf("Validate: %v", err)
|
||||
}
|
||||
if got.ID != apiKey.ID {
|
||||
t.Errorf("validated wrong key: got %q want %q", got.ID, apiKey.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_RoleRoundTrip(t *testing.T) {
|
||||
cases := []struct {
|
||||
role Role
|
||||
stored string
|
||||
}{
|
||||
{RoleReadOnly, storedRoleReadOnly},
|
||||
{RoleReadWrite, storedRoleReadWrite},
|
||||
{RoleAdmin, storedRoleAdmin},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(string(tc.role), func(t *testing.T) {
|
||||
if got := roleToStored(tc.role); got != tc.stored {
|
||||
t.Errorf("roleToStored(%q) = %q, want %q", tc.role, got, tc.stored)
|
||||
}
|
||||
if got := storedToRole(tc.stored); got != tc.role {
|
||||
t.Errorf("storedToRole(%q) = %q, want %q", tc.stored, got, tc.role)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if got := storedToRole("garbage"); got != RoleReadOnly {
|
||||
t.Errorf("storedToRole(garbage) = %q, want least-privilege RoleReadOnly", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/rs/zerolog/log"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// BootstrapAdminEnvVar is the env var consulted by BootstrapAdminFromEnv.
|
||||
// Exported so callers and operators can reference a single source of truth.
|
||||
const BootstrapAdminEnvVar = "GOHOARDER_BOOTSTRAP_ADMIN_KEY"
|
||||
|
||||
// bootstrapProject is the marker project assigned to the env-bootstrapped
|
||||
// admin key. Callers can list keys filtered by this project to inventory
|
||||
// bootstrap-origin credentials.
|
||||
const bootstrapProject = "bootstrap"
|
||||
|
||||
// BootstrapAdminFromEnv creates an initial admin API key from the
|
||||
// GOHOARDER_BOOTSTRAP_ADMIN_KEY environment variable when no admin key
|
||||
// already exists in the store.
|
||||
//
|
||||
// Behaviour matrix:
|
||||
// - env unset/empty -> no-op, nil
|
||||
// - store nil -> no-op, nil (caller must provide a store)
|
||||
// - store has any non-revoked
|
||||
// admin key -> log and return nil (idempotent)
|
||||
// - else -> bcrypt-hash env value, persist as admin
|
||||
//
|
||||
// The env var holds the RAW key the operator wants to use; we hash it with
|
||||
// the configured bcrypt cost (default DefaultCost) before storing. The
|
||||
// operator is expected to clear the env var after first successful boot.
|
||||
func BootstrapAdminFromEnv(ctx context.Context, store metadata.MetadataStore, cfg Config) error {
|
||||
rawKey := os.Getenv(BootstrapAdminEnvVar)
|
||||
if rawKey == "" {
|
||||
return nil
|
||||
}
|
||||
if store == nil {
|
||||
log.Warn().Msg("Bootstrap admin key requested but no metadata store configured; skipping")
|
||||
return nil
|
||||
}
|
||||
|
||||
cost := cfg.BcryptCost
|
||||
if cost == 0 {
|
||||
cost = bcrypt.DefaultCost
|
||||
}
|
||||
|
||||
// Idempotency: if any non-revoked admin already exists, skip.
|
||||
existing, err := store.ListAPIKeys(ctx)
|
||||
if err != nil {
|
||||
if stderrors.Is(err, metadata.ErrNotImplemented) {
|
||||
log.Warn().Msg("Bootstrap admin: store does not implement API key persistence; skipping")
|
||||
return nil
|
||||
}
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "bootstrap admin: failed to list existing keys")
|
||||
}
|
||||
|
||||
for _, k := range existing {
|
||||
if k == nil || k.Revoked {
|
||||
continue
|
||||
}
|
||||
if k.Role == storedRoleAdmin {
|
||||
log.Info().Msg("Bootstrap admin skipped — admin key already exists")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte(rawKey), cost)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, errors.ErrCodeInternalServer, "bootstrap admin: failed to hash key")
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
key := &metadata.APIKey{
|
||||
ID: generateID(),
|
||||
KeyHash: string(hashed),
|
||||
Project: bootstrapProject,
|
||||
Role: storedRoleAdmin,
|
||||
CreatedAt: now,
|
||||
Revoked: false,
|
||||
}
|
||||
|
||||
if err := store.SaveAPIKey(ctx, key); err != nil {
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "bootstrap admin: failed to save key")
|
||||
}
|
||||
|
||||
// SECURITY: never log the raw key or its hash.
|
||||
log.Info().
|
||||
Str("key_id", key.ID).
|
||||
Str("project", bootstrapProject).
|
||||
Msg("Bootstrap admin created — delete " + BootstrapAdminEnvVar + " after first run")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestBootstrapAdminFromEnv_EnvEmpty_NoOp(t *testing.T) {
|
||||
t.Setenv(BootstrapAdminEnvVar, "")
|
||||
store := newFakeStore()
|
||||
|
||||
if err := BootstrapAdminFromEnv(context.Background(), store, fastCfg()); err != nil {
|
||||
t.Fatalf("BootstrapAdminFromEnv: %v", err)
|
||||
}
|
||||
if got := len(store.keys); got != 0 {
|
||||
t.Errorf("store has %d keys, want 0 when env empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapAdminFromEnv_NilStore_NoOp(t *testing.T) {
|
||||
t.Setenv(BootstrapAdminEnvVar, "secret")
|
||||
if err := BootstrapAdminFromEnv(context.Background(), nil, fastCfg()); err != nil {
|
||||
t.Fatalf("BootstrapAdminFromEnv(nil store): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapAdminFromEnv_FreshStore_CreatesAdmin(t *testing.T) {
|
||||
const raw = "super-secret-bootstrap-key"
|
||||
t.Setenv(BootstrapAdminEnvVar, raw)
|
||||
store := newFakeStore()
|
||||
|
||||
if err := BootstrapAdminFromEnv(context.Background(), store, fastCfg()); err != nil {
|
||||
t.Fatalf("BootstrapAdminFromEnv: %v", err)
|
||||
}
|
||||
|
||||
if got := len(store.keys); got != 1 {
|
||||
t.Fatalf("store has %d keys, want 1", got)
|
||||
}
|
||||
|
||||
var created *metadata.APIKey
|
||||
for _, k := range store.keys {
|
||||
created = k
|
||||
break
|
||||
}
|
||||
if created.Role != storedRoleAdmin {
|
||||
t.Errorf("Role = %q, want %q", created.Role, storedRoleAdmin)
|
||||
}
|
||||
if created.Project != bootstrapProject {
|
||||
t.Errorf("Project = %q, want %q", created.Project, bootstrapProject)
|
||||
}
|
||||
if created.Revoked {
|
||||
t.Errorf("Revoked = true, want false")
|
||||
}
|
||||
if created.ID == "" {
|
||||
t.Errorf("ID empty")
|
||||
}
|
||||
// Hash must verify against the raw env value.
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(created.KeyHash), []byte(raw)); err != nil {
|
||||
t.Errorf("bcrypt mismatch: %v", err)
|
||||
}
|
||||
// Hash must NOT equal the raw key (would indicate plaintext storage).
|
||||
if created.KeyHash == raw {
|
||||
t.Errorf("KeyHash equals raw key — plaintext storage bug")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapAdminFromEnv_AdminAlreadyExists_Idempotent(t *testing.T) {
|
||||
t.Setenv(BootstrapAdminEnvVar, "another-secret")
|
||||
store := newFakeStore()
|
||||
// Pre-existing admin.
|
||||
_ = store.SaveAPIKey(context.Background(), &metadata.APIKey{
|
||||
ID: "existing-admin",
|
||||
KeyHash: "$2a$04$dummy",
|
||||
Role: storedRoleAdmin,
|
||||
Project: "default",
|
||||
CreatedAt: time.Now(),
|
||||
})
|
||||
|
||||
if err := BootstrapAdminFromEnv(context.Background(), store, fastCfg()); err != nil {
|
||||
t.Fatalf("BootstrapAdminFromEnv: %v", err)
|
||||
}
|
||||
if got := len(store.keys); got != 1 {
|
||||
t.Errorf("store has %d keys, want 1 (no new admin created)", got)
|
||||
}
|
||||
if _, ok := store.keys["existing-admin"]; !ok {
|
||||
t.Errorf("existing admin was removed/overwritten")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapAdminFromEnv_RevokedAdmin_StillCreatesNewOne(t *testing.T) {
|
||||
t.Setenv(BootstrapAdminEnvVar, "fresh-secret")
|
||||
store := newFakeStore()
|
||||
// Revoked admin should NOT count as "admin already exists".
|
||||
_ = store.SaveAPIKey(context.Background(), &metadata.APIKey{
|
||||
ID: "old-admin",
|
||||
KeyHash: "x",
|
||||
Role: storedRoleAdmin,
|
||||
Project: "bootstrap",
|
||||
Revoked: true,
|
||||
CreatedAt: time.Now(),
|
||||
})
|
||||
|
||||
if err := BootstrapAdminFromEnv(context.Background(), store, fastCfg()); err != nil {
|
||||
t.Fatalf("BootstrapAdminFromEnv: %v", err)
|
||||
}
|
||||
if got := len(store.keys); got != 2 {
|
||||
t.Errorf("store has %d keys, want 2 (revoked + fresh)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapAdminFromEnv_NonAdminKeysIgnored(t *testing.T) {
|
||||
t.Setenv(BootstrapAdminEnvVar, "secret-x")
|
||||
store := newFakeStore()
|
||||
_ = store.SaveAPIKey(context.Background(), &metadata.APIKey{
|
||||
ID: "reader",
|
||||
KeyHash: "x",
|
||||
Role: storedRoleReadOnly,
|
||||
Project: "default",
|
||||
CreatedAt: time.Now(),
|
||||
})
|
||||
|
||||
if err := BootstrapAdminFromEnv(context.Background(), store, fastCfg()); err != nil {
|
||||
t.Fatalf("BootstrapAdminFromEnv: %v", err)
|
||||
}
|
||||
if got := len(store.keys); got != 2 {
|
||||
t.Errorf("store has %d keys, want 2 (read-only existing + new admin)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapAdminFromEnv_StoreNotImplemented_NoOp(t *testing.T) {
|
||||
t.Setenv(BootstrapAdminEnvVar, "secret-y")
|
||||
store := newFakeStore()
|
||||
store.disabled = true
|
||||
|
||||
if err := BootstrapAdminFromEnv(context.Background(), store, fastCfg()); err != nil {
|
||||
t.Fatalf("BootstrapAdminFromEnv: %v", err)
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -14,16 +14,18 @@ func NewCredentialHasher() *CredentialHasher {
|
||||
return &CredentialHasher{}
|
||||
}
|
||||
|
||||
// Hash generates a short hash of credentials for use in cache keys
|
||||
// Returns "public" if no credentials provided
|
||||
// Hash generates a hash of credentials for use in cache keys.
|
||||
// Returns "public" if no credentials provided.
|
||||
// Returns the full 64-char SHA256 hex digest otherwise: truncating to 8 bytes
|
||||
// gives a ~2^32 birthday bound which is unsafe for a security-sensitive
|
||||
// cache key (cross-credential cache poisoning).
|
||||
func (h *CredentialHasher) Hash(credentials string) string {
|
||||
if credentials == "" {
|
||||
return "public"
|
||||
}
|
||||
|
||||
// Use SHA256 and take first 16 characters (8 bytes)
|
||||
hash := sha256.Sum256([]byte(credentials))
|
||||
return hex.EncodeToString(hash[:8])
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
// GenerateCacheKey generates a cache key that includes credential hash
|
||||
|
||||
@@ -14,16 +14,20 @@ type ValidationResult struct {
|
||||
|
||||
// ValidationCache caches credential validation results to reduce upstream checks
|
||||
type ValidationCache struct {
|
||||
cache map[string]*ValidationResult
|
||||
mu sync.RWMutex
|
||||
ttl time.Duration
|
||||
cache map[string]*ValidationResult
|
||||
stopCh chan struct{}
|
||||
stopOnce sync.Once
|
||||
mu sync.RWMutex
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// NewValidationCache creates a new validation cache
|
||||
// NewValidationCache creates a new validation cache. Callers must call Stop()
|
||||
// during shutdown to terminate the background cleanup goroutine.
|
||||
func NewValidationCache(ttl time.Duration) *ValidationCache {
|
||||
vc := &ValidationCache{
|
||||
cache: make(map[string]*ValidationResult),
|
||||
ttl: ttl,
|
||||
cache: make(map[string]*ValidationResult),
|
||||
stopCh: make(chan struct{}),
|
||||
ttl: ttl,
|
||||
}
|
||||
|
||||
// Start cleanup goroutine
|
||||
@@ -32,25 +36,42 @@ func NewValidationCache(ttl time.Duration) *ValidationCache {
|
||||
return vc
|
||||
}
|
||||
|
||||
// Stop terminates the background cleanup goroutine. Safe to call multiple
|
||||
// times; subsequent calls are no-ops.
|
||||
func (vc *ValidationCache) Stop() {
|
||||
vc.stopOnce.Do(func() {
|
||||
close(vc.stopCh)
|
||||
})
|
||||
}
|
||||
|
||||
// Get retrieves a validation result from cache
|
||||
// Returns (allowed bool, cached bool, reason string)
|
||||
func (vc *ValidationCache) Get(credHash, packageURL string) (bool, bool, string) {
|
||||
vc.mu.RLock()
|
||||
defer vc.mu.RUnlock()
|
||||
|
||||
key := credHash + ":" + packageURL
|
||||
|
||||
// Fast path: read-locked lookup.
|
||||
vc.mu.RLock()
|
||||
result, exists := vc.cache[key]
|
||||
|
||||
if !exists {
|
||||
vc.mu.RUnlock()
|
||||
return false, false, ""
|
||||
}
|
||||
|
||||
// Check if expired
|
||||
if time.Now().After(result.ExpiresAt) {
|
||||
return false, false, ""
|
||||
expired := time.Now().After(result.ExpiresAt)
|
||||
if !expired {
|
||||
allowed, reason := result.Allowed, result.Reason
|
||||
vc.mu.RUnlock()
|
||||
return allowed, true, reason
|
||||
}
|
||||
vc.mu.RUnlock()
|
||||
|
||||
return result.Allowed, true, result.Reason
|
||||
// Expired: drop it under the write lock so callers don't all stampede
|
||||
// the upstream while waiting for the periodic cleanup goroutine.
|
||||
vc.mu.Lock()
|
||||
if cur, ok := vc.cache[key]; ok && time.Now().After(cur.ExpiresAt) {
|
||||
delete(vc.cache, key)
|
||||
}
|
||||
vc.mu.Unlock()
|
||||
return false, false, ""
|
||||
}
|
||||
|
||||
// Set stores a validation result in cache
|
||||
@@ -91,19 +112,25 @@ func (vc *ValidationCache) Size() int {
|
||||
return len(vc.cache)
|
||||
}
|
||||
|
||||
// cleanupExpired removes expired entries periodically
|
||||
// cleanupExpired removes expired entries periodically. Exits when Stop is
|
||||
// called.
|
||||
func (vc *ValidationCache) cleanupExpired() {
|
||||
ticker := time.NewTicker(1 * time.Minute)
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
vc.mu.Lock()
|
||||
now := time.Now()
|
||||
for key, result := range vc.cache {
|
||||
if now.After(result.ExpiresAt) {
|
||||
delete(vc.cache, key)
|
||||
for {
|
||||
select {
|
||||
case <-vc.stopCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
vc.mu.Lock()
|
||||
now := time.Now()
|
||||
for key, result := range vc.cache {
|
||||
if now.After(result.ExpiresAt) {
|
||||
delete(vc.cache, key)
|
||||
}
|
||||
}
|
||||
vc.mu.Unlock()
|
||||
}
|
||||
vc.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
+27
-27
@@ -50,11 +50,11 @@ func (v *NPMValidator) ValidateAccess(ctx context.Context, packageURL string, cr
|
||||
|
||||
resp, err := v.client.Do(req)
|
||||
if err != nil {
|
||||
// Network error - allow cache fallback with warning
|
||||
log.Warn().Err(err).Str("url", packageURL).Msg("Validation request failed, allowing cache fallback")
|
||||
return true, fmt.Errorf("validation failed: %w (allowing cache fallback)", err)
|
||||
// Network error - fail closed. Caller decides any fallback policy.
|
||||
log.Warn().Err(err).Str("url", packageURL).Msg("Validation request failed, denying access")
|
||||
return false, fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close() // #nosec G104 -- Cleanup, error not critical
|
||||
defer func() { _ = resp.Body.Close() }() // #nosec G104 -- Cleanup, error not critical
|
||||
|
||||
// Check status code
|
||||
switch resp.StatusCode {
|
||||
@@ -65,9 +65,9 @@ func (v *NPMValidator) ValidateAccess(ctx context.Context, packageURL string, cr
|
||||
// Access denied
|
||||
return false, fmt.Errorf("access denied: HTTP %d", resp.StatusCode)
|
||||
default:
|
||||
// Unexpected status - allow cache fallback with warning
|
||||
log.Warn().Int("status", resp.StatusCode).Str("url", packageURL).Msg("Unexpected validation status, allowing cache fallback")
|
||||
return true, fmt.Errorf("unexpected status %d (allowing cache fallback)", resp.StatusCode)
|
||||
// Unexpected status - fail closed.
|
||||
log.Warn().Int("status", resp.StatusCode).Str("url", packageURL).Msg("Unexpected validation status, denying access")
|
||||
return false, fmt.Errorf("unexpected status %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,11 +101,11 @@ func (v *PyPIValidator) ValidateAccess(ctx context.Context, packageURL string, c
|
||||
|
||||
resp, err := v.client.Do(req)
|
||||
if err != nil {
|
||||
// Network error - allow cache fallback with warning
|
||||
log.Warn().Err(err).Str("url", packageURL).Msg("Validation request failed, allowing cache fallback")
|
||||
return true, fmt.Errorf("validation failed: %w (allowing cache fallback)", err)
|
||||
// Network error - fail closed. Caller decides any fallback policy.
|
||||
log.Warn().Err(err).Str("url", packageURL).Msg("Validation request failed, denying access")
|
||||
return false, fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close() // #nosec G104 -- Cleanup, error not critical
|
||||
defer func() { _ = resp.Body.Close() }() // #nosec G104 -- Cleanup, error not critical
|
||||
|
||||
// Check status code
|
||||
switch resp.StatusCode {
|
||||
@@ -116,9 +116,9 @@ func (v *PyPIValidator) ValidateAccess(ctx context.Context, packageURL string, c
|
||||
// Access denied
|
||||
return false, fmt.Errorf("access denied: HTTP %d", resp.StatusCode)
|
||||
default:
|
||||
// Unexpected status - allow cache fallback with warning
|
||||
log.Warn().Int("status", resp.StatusCode).Str("url", packageURL).Msg("Unexpected validation status, allowing cache fallback")
|
||||
return true, fmt.Errorf("unexpected status %d (allowing cache fallback)", resp.StatusCode)
|
||||
// Unexpected status - fail closed.
|
||||
log.Warn().Int("status", resp.StatusCode).Str("url", packageURL).Msg("Unexpected validation status, denying access")
|
||||
return false, fmt.Errorf("unexpected status %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,13 +171,13 @@ func (v *GoValidator) validateGitHub(ctx context.Context, modulePath, credential
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
defer func() { _ = os.RemoveAll(tempDir) }()
|
||||
|
||||
// Create .netrc file with credentials
|
||||
netrcPath := filepath.Join(tempDir, ".netrc")
|
||||
netrcContent := fmt.Sprintf("machine github.com\nlogin oauth2\npassword %s\n", token)
|
||||
if err := os.WriteFile(netrcPath, []byte(netrcContent), 0600); err != nil {
|
||||
return false, err
|
||||
if writeErr := os.WriteFile(netrcPath, []byte(netrcContent), 0600); writeErr != nil {
|
||||
return false, writeErr
|
||||
}
|
||||
|
||||
// Run git ls-remote (lightweight, just checks access)
|
||||
@@ -199,9 +199,9 @@ func (v *GoValidator) validateGitHub(ctx context.Context, modulePath, credential
|
||||
return false, fmt.Errorf("access denied: %s", strings.TrimSpace(errMsg))
|
||||
}
|
||||
|
||||
// Other error (network, etc.) - allow cache fallback
|
||||
log.Warn().Err(err).Str("module", modulePath).Msg("Git validation failed, allowing cache fallback")
|
||||
return true, fmt.Errorf("validation error (allowing cache): %w", err)
|
||||
// Other error (network, etc.) - fail closed.
|
||||
log.Warn().Err(err).Str("module", modulePath).Msg("Git validation failed, denying access")
|
||||
return false, fmt.Errorf("validation error: %w", err)
|
||||
}
|
||||
|
||||
// Success - repository accessible
|
||||
@@ -227,13 +227,13 @@ func (v *GoValidator) validateGitLab(ctx context.Context, modulePath, credential
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
defer func() { _ = os.RemoveAll(tempDir) }()
|
||||
|
||||
// Create .netrc file with credentials
|
||||
netrcPath := filepath.Join(tempDir, ".netrc")
|
||||
netrcContent := fmt.Sprintf("machine gitlab.com\nlogin oauth2\npassword %s\n", token)
|
||||
if err := os.WriteFile(netrcPath, []byte(netrcContent), 0600); err != nil {
|
||||
return false, err
|
||||
if writeErr := os.WriteFile(netrcPath, []byte(netrcContent), 0600); writeErr != nil {
|
||||
return false, writeErr
|
||||
}
|
||||
|
||||
// Run git ls-remote
|
||||
@@ -252,8 +252,8 @@ func (v *GoValidator) validateGitLab(ctx context.Context, modulePath, credential
|
||||
return false, fmt.Errorf("access denied: %s", strings.TrimSpace(errMsg))
|
||||
}
|
||||
|
||||
log.Warn().Err(err).Str("module", modulePath).Msg("Git validation failed, allowing cache fallback")
|
||||
return true, fmt.Errorf("validation error (allowing cache): %w", err)
|
||||
log.Warn().Err(err).Str("module", modulePath).Msg("Git validation failed, denying access")
|
||||
return false, fmt.Errorf("validation error: %w", err)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
@@ -276,8 +276,8 @@ func (v *GoValidator) validateGit(ctx context.Context, modulePath, credentials s
|
||||
return false, fmt.Errorf("access denied: %s", strings.TrimSpace(errMsg))
|
||||
}
|
||||
|
||||
log.Warn().Err(err).Str("module", modulePath).Msg("Git validation failed, allowing cache fallback")
|
||||
return true, fmt.Errorf("validation error (allowing cache): %w", err)
|
||||
log.Warn().Err(err).Str("module", modulePath).Msg("Git validation failed, denying access")
|
||||
return false, fmt.Errorf("validation error: %w", err)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
|
||||
Reference in New Issue
Block a user