diff --git a/README.md b/README.md index 02d2984..3ec4531 100644 --- a/README.md +++ b/README.md @@ -236,6 +236,8 @@ security: cache: default_ttl: 24h # Freshness window for metadata pages (version lists, package documents) idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables + ttl_overrides: # Per-registry metadata freshness (npm, pypi, go); replaces default_ttl, never applies to artifacts + pypi: 12h cleanup_interval: 1h logging: diff --git a/config.yaml.example b/config.yaml.example index 4765ac3..f6aab43 100644 --- a/config.yaml.example +++ b/config.yaml.example @@ -99,9 +99,9 @@ cache: idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables max_size_bytes: 536870912000 # 500GB per_project_quota: 53687091200 # 50GB - ttl_overrides: + ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go npm: "24h" - pip: "24h" + pypi: "24h" go: "24h" security: diff --git a/helm/gohoarder/values.yaml b/helm/gohoarder/values.yaml index ab78e9b..ecfdb06 100644 --- a/helm/gohoarder/values.yaml +++ b/helm/gohoarder/values.yaml @@ -383,9 +383,9 @@ cache: idleTTL: "168h" # Remove cached items not requested for this long; "0" disables maxSizeBytes: 536870912000 # 500GB perProjectQuota: 53687091200 # 50GB - ttlOverrides: + ttlOverrides: # Per-registry metadata freshness; replaces defaultTTL for that registry. Keys: npm, pypi, go npm: "24h" - pip: "24h" + pypi: "24h" go: "24h" # Security scanning configuration diff --git a/lean4/FINDINGS.md b/lean4/FINDINGS.md index 529d5a0..544623b 100644 --- a/lean4/FINDINGS.md +++ b/lean4/FINDINGS.md @@ -51,8 +51,11 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`. ### Notes on the fixed rows -- **GH-15.** `cache.ttl_overrides` has no consumer in the Go code (`grep TTLOverrides pkg cmd`: the field and its compiled default - only). The per-registry keys are kept and now default to 24h; they change nothing until something reads them. +- **GH-15.** `cache.ttl_overrides` now has a consumer: `cache.Config.TTLOverrides` sets the metadata freshness per registry + (`npm`, `pypi`, `go`; `pip` is an alias of `pypi`), and a registry without an override keeps `default_ttl`. Artifacts keep no + age expiry. Defaults hold no override, so lowering `default_ttl` still applies everywhere. Config load rejects an unknown + registry key or a non-positive value. Tests: `TestMetadataTTLOverridesApplyPerRegistry`, `TestMetadataTTLOverridesSkipArtifacts`, + `TestNPMMetadataTTLOverrideReachesCache`, `TestTTLOverridesValidation`. - **GH-18.** New keys read `ghk_.`; the hash covers the secret and one lookup selects the stored key. A miss compares a dummy hash. Keys minted before are accepted through a legacy path capped at 4 concurrent bcrypt compares. They cannot be migrated: the raw key holds no id and the stored hash covers the whole raw key. Re-issue them to leave the diff --git a/lean4/Gohoarder/Release.lean b/lean4/Gohoarder/Release.lean index 976d4d8..da65542 100644 --- a/lean4/Gohoarder/Release.lean +++ b/lean4/Gohoarder/Release.lean @@ -56,6 +56,27 @@ theorem old_default_ttl_exceeded_gate : ∃ gate ttl now s t : ℤ, now - s ≤ ttl ∧ s < t ∧ gateAccepts gate now t ∧ ttl = 168 ∧ gate = 72 := by exact ⟨72, 168, 200, 100, 116, by decide, by decide, by unfold gateAccepts; decide, rfl, rfl⟩ +/-! ### Per-registry override (`cache.ttl_overrides`, `Manager.metadataTTL`) -/ + +/-- The freshness window of a metadata entry: the registry's override when set, else `default_ttl`. -/ +def effectiveTtl (override : Option ℤ) (default : ℤ) : ℤ := override.getD default + +/-- The staleness bound holds for a registry exactly when its effective window is within the gate. -/ +theorem override_within_gate_hides_only_gated (gate default now s t : ℤ) (override : Option ℤ) + (hcfg : effectiveTtl override default ≤ gate) (hstale : now - s ≤ effectiveTtl override default) + (hnew : s < t) : ¬ gateAccepts gate now t := + stale_hides_only_gated gate _ now s t hstale hcfg hnew + +/-- An override replaces `default_ttl`; it does not add to it, and an absent override keeps it. -/ +theorem override_replaces_default (default o : ℤ) : + effectiveTtl (some o) default = o ∧ effectiveTtl none default = default := ⟨rfl, rfl⟩ + +/-- An override above the gate loses the bound: operator choice, not enforced by config load. -/ +theorem override_above_gate_breaks_bound : + ∃ gate default now s t : ℤ, effectiveTtl (some 168) default = 168 ∧ now - s ≤ 168 ∧ s < t ∧ + gateAccepts gate now t ∧ gate = 72 := by + exact ⟨72, 24, 200, 100, 116, rfl, by decide, by decide, by unfold gateAccepts; decide, rfl⟩ + /-- Publish times never change, so a version present in a stale snapshot is gated identically to a fresh one. -/ theorem listed_versions_gated_identically (gate now t : ℤ) : gateAccepts gate now t ↔ gateAccepts gate now t := Iff.rfl diff --git a/pkg/app/app.go b/pkg/app/app.go index ff0ec24..d2f7d02 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -232,6 +232,7 @@ func (a *App) initializeComponents() error { } a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{ DefaultTTL: a.config.Cache.DefaultTTL, + TTLOverrides: a.config.Cache.MetadataTTLOverrides(), CleanupInterval: cleanupInterval, IdleTTL: a.config.Cache.IdleTTL, MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize, diff --git a/pkg/app/proxy_integration_test.go b/pkg/app/proxy_integration_test.go index 30b79f4..5ef88f2 100644 --- a/pkg/app/proxy_integration_test.go +++ b/pkg/app/proxy_integration_test.go @@ -3,6 +3,7 @@ package app import ( "archive/zip" "bytes" + "context" "encoding/json" "io" "net" @@ -18,6 +19,7 @@ import ( "github.com/gofiber/fiber/v3" "github.com/lukaszraczylo/gohoarder/pkg/config" + "github.com/lukaszraczylo/gohoarder/pkg/metadata" ) // newTestApp builds a full App on temp storage with the given config tweaks. @@ -284,3 +286,33 @@ func TestPyPI_UVExcludeNewerResolvesThroughProxy(t *testing.T) { t.Fatalf("uv resolved foo although it was uploaded after the cutoff:\n%s", out) } } + +func TestNPMMetadataTTLOverrideReachesCache(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"name":"left-pad","versions":{}}`)) + })) + t.Cleanup(upstream.Close) + + a := newTestApp(t, func(c *config.Config) { + c.Handlers.NPM.UpstreamRegistry = upstream.URL + c.Cache.TTLOverrides = map[string]time.Duration{"npm": 90 * time.Minute} + }) + if code, _, body := doRequest(t, a, "/npm/left-pad", nil); code != http.StatusOK { + t.Fatalf("status = %d, body %q", code, body) + } + + pkgs, err := a.metadata.ListPackages(context.Background(), &metadata.ListOptions{Registry: "npm"}) + if err != nil { + t.Fatal(err) + } + for _, p := range pkgs { + if p.ExpiresAt == nil { + continue + } + if got := p.ExpiresAt.Sub(p.CachedAt); got < 89*time.Minute || got > 91*time.Minute { + t.Errorf("npm metadata freshness = %s, want 90m from cache.ttl_overrides", got) + } + return + } + t.Fatalf("no npm metadata entry with an expiry among %d packages", len(pkgs)) +} diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index 527890b..8490c6a 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -80,15 +80,16 @@ func (m *Manager) emit(eventType string, payload map[string]interface{}) { // Config holds cache manager configuration type Config struct { - Now func() time.Time // Clock; nil means time.Now - DefaultTTL time.Duration // Freshness TTL for metadata entries - CleanupInterval time.Duration // How often to run cleanup - IdleTTL time.Duration // Remove entries not requested for this long (0 = off) - EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0) - MaxConcurrent int // Max concurrent upstream fetches - MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB) - ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s) - FailClosed bool // Refuse a package whose scan did not finish in time + Now func() time.Time // Clock; nil means time.Now + TTLOverrides map[string]time.Duration // Per-registry metadata freshness TTL; falls back to DefaultTTL + DefaultTTL time.Duration // Freshness TTL for metadata entries + CleanupInterval time.Duration // How often to run cleanup + IdleTTL time.Duration // Remove entries not requested for this long (0 = off) + EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0) + MaxConcurrent int // Max concurrent upstream fetches + MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB) + ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s) + FailClosed bool // Refuse a package whose scan did not finish in time } const defaultScanWaitTimeout = 30 * time.Second @@ -586,7 +587,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer // entries must refresh and keep a freshness expiry. var expiresAt *time.Time if isMetadataEntry { - exp := now.Add(m.config.DefaultTTL) + exp := now.Add(m.metadataTTL(registry)) expiresAt = &exp } @@ -737,6 +738,14 @@ func (m *Manager) Delete(ctx context.Context, registry, name, version string) er return m.deletePackage(ctx, pkg) } +// metadataTTL returns the freshness window for a registry's metadata entries. +func (m *Manager) metadataTTL(registry string) time.Duration { + if ttl, ok := m.config.TTLOverrides[registry]; ok { + return ttl + } + return m.config.DefaultTTL +} + // deletePackage deletes a package from both storage and metadata func (m *Manager) deletePackage(ctx context.Context, pkg *metadata.Package) error { // Delete from storage diff --git a/pkg/cache/ttl_overrides_test.go b/pkg/cache/ttl_overrides_test.go new file mode 100644 index 0000000..173ed38 --- /dev/null +++ b/pkg/cache/ttl_overrides_test.go @@ -0,0 +1,38 @@ +package cache + +import ( + "context" + "io" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func (h *idleHarness) getFrom(t *testing.T, registry, name, version string) *CacheEntry { + t.Helper() + entry, err := h.mgr.Get(context.Background(), registry, name, version, func(context.Context) (*FetchResult, error) { + return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil + }) + require.NoError(t, err) + _ = entry.Data.Close() + return entry +} + +func TestMetadataTTLOverridesApplyPerRegistry(t *testing.T) { + h := newIdleHarness(t, Config{ + DefaultTTL: 6 * time.Hour, + TTLOverrides: map[string]time.Duration{"npm": time.Hour, "go": 12 * time.Hour}, + }) + + require.Equal(t, time.Hour, h.getFrom(t, "npm", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now())) + require.Equal(t, 12*time.Hour, h.getFrom(t, "go", "example.com/m/@v/list", "list").Package.ExpiresAt.Sub(h.clock.Now())) + require.Equal(t, 6*time.Hour, h.getFrom(t, "pypi", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()), "registry without override keeps default_ttl") +} + +func TestMetadataTTLOverridesSkipArtifacts(t *testing.T) { + h := newIdleHarness(t, Config{TTLOverrides: map[string]time.Duration{"npm": time.Hour}}) + + require.Nil(t, h.getFrom(t, "npm", "left-pad", artifactVer).Package.ExpiresAt, "artifacts have no age expiry") +} diff --git a/pkg/config/config.go b/pkg/config/config.go index aeab417..1f3eead 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -142,6 +142,18 @@ const DefaultMetadataTTL = 24 * time.Hour // that send OIDC session cookies plus a long Referer or URL with 431. const DefaultReadBufferSize = 16384 +// ttlOverrideRegistries maps each accepted cache.ttl_overrides key to its registry name. +var ttlOverrideRegistries = map[string]string{"npm": "npm", "pypi": "pypi", "pip": "pypi", "go": "go"} + +// MetadataTTLOverrides returns the per-registry metadata freshness TTLs keyed by registry name. +func (c CacheConfig) MetadataTTLOverrides() map[string]time.Duration { + out := make(map[string]time.Duration, len(c.TTLOverrides)) + for key, ttl := range c.TTLOverrides { + out[ttlOverrideRegistries[key]] = ttl + } + return out +} + // DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it. const DefaultIdleTTL = 7 * 24 * time.Hour @@ -370,11 +382,6 @@ func Default() *Config { IdleTTL: DefaultIdleTTL, MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB - TTLOverrides: map[string]time.Duration{ - "npm": DefaultMetadataTTL, - "pip": DefaultMetadataTTL, - "go": DefaultMetadataTTL, - }, }, Security: SecurityConfig{ Enabled: false, @@ -526,6 +533,14 @@ func (c *Config) Validate() error { if c.Cache.IdleTTL < 0 { return fmt.Errorf("cache.idle_ttl cannot be negative") } + for key, ttl := range c.Cache.TTLOverrides { + if _, ok := ttlOverrideRegistries[key]; !ok { + return fmt.Errorf("cache.ttl_overrides: unknown registry %q (want npm, pypi or go)", key) + } + if ttl <= 0 { + return fmt.Errorf("cache.ttl_overrides.%s must be positive, got %s", key, ttl) + } + } if c.Cache.MaxSizeBytes < 0 { return fmt.Errorf("cache.max_size_bytes cannot be negative") } diff --git a/pkg/config/default_ttl_test.go b/pkg/config/default_ttl_test.go index d7b229d..8d3453e 100644 --- a/pkg/config/default_ttl_test.go +++ b/pkg/config/default_ttl_test.go @@ -2,6 +2,7 @@ package config import ( "os" + "path/filepath" "regexp" "testing" "time" @@ -37,3 +38,51 @@ func TestShippedExamplesKeepMetadataTTLWithinGate(t *testing.T) { } } } + +func TestTTLOverridesValidation(t *testing.T) { + for name, tc := range map[string]struct { + overrides map[string]time.Duration + wantErr string + }{ + "known registries": {map[string]time.Duration{"npm": time.Hour, "pypi": time.Hour, "go": time.Hour}, ""}, + "pip alias": {map[string]time.Duration{"pip": time.Hour}, ""}, + "unknown registry": {map[string]time.Duration{"cargo": time.Hour}, "cache.ttl_overrides"}, + "zero": {map[string]time.Duration{"npm": 0}, "cache.ttl_overrides"}, + "negative": {map[string]time.Duration{"go": -time.Hour}, "cache.ttl_overrides"}, + } { + t.Run(name, func(t *testing.T) { + c := Default() + c.Cache.TTLOverrides = tc.overrides + err := c.Validate() + if tc.wantErr == "" { + require.NoError(t, err) + return + } + require.ErrorContains(t, err, tc.wantErr) + }) + } +} + +func TestMetadataTTLOverridesNormalisesPip(t *testing.T) { + c := CacheConfig{TTLOverrides: map[string]time.Duration{"pip": time.Hour, "npm": 2 * time.Hour}} + require.Equal(t, map[string]time.Duration{"pypi": time.Hour, "npm": 2 * time.Hour}, c.MetadataTTLOverrides()) +} + +func TestDefaultsKeepNoTTLOverrides(t *testing.T) { + require.Empty(t, Default().Cache.TTLOverrides, "an unset override must not shadow default_ttl") +} + +func TestLoadReadsTTLOverridesFromYAML(t *testing.T) { + write := func(body string) string { + path := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(path, []byte(body), 0o600)) + return path + } + + cfg, err := Load(write("cache:\n ttl_overrides:\n npm: 2h\n pip: 30m\n")) + require.NoError(t, err) + require.Equal(t, map[string]time.Duration{"npm": 2 * time.Hour, "pypi": 30 * time.Minute}, cfg.Cache.MetadataTTLOverrides()) + + _, err = Load(write("cache:\n ttl_overrides:\n cargo: 2h\n")) + require.ErrorContains(t, err, "cache.ttl_overrides") +}