mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-12-03 07:15:22 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d31e535ff | ||
|
|
fe2d9f8b3a | ||
|
|
a84f080b79 | ||
|
|
9b4659218c | ||
|
|
1256756057 | ||
|
|
262771d224 |
@@ -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:
|
||||
|
||||
+2
-2
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
+9
-5
@@ -51,18 +51,22 @@ 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_<id>.<secret>`; 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
|
||||
legacy path. Production holds none.
|
||||
- **GH-20.** SQLite startup merges old duplicate rows (package rows add up, derived rows keep one) and creates the unique indexes.
|
||||
- **GH-21.** `RescanWorker` still skips remote storage ("No local file path available"); that is a separate, unchanged behaviour.
|
||||
- **GH-21.** `RescanWorker` reads each blob through the cache `ScanFile` source, so periodic rescans cover S3 and SMB as well as
|
||||
local storage. A remote blob is copied to a temp file for the scan and removed after it. Test: `TestRescanWorkerScansRemoteStorage`.
|
||||
- **GH-22.** Frontend nginx dropped the `Cookie` header on `/api/` and `/ws` (the backend reads none; keys travel in `Authorization` / `X-API-Key`).
|
||||
The server read buffer is `server.read_buffer_size`, default 16384 (Fiber's default is 8192): a long Referer or `Authorization` no longer gets 431.
|
||||
- **GH-17 cleanup.** The per-handler `Access-Control-Allow-Origin: *` lines in `pkg/app/handlers*.go` are now overridden by the
|
||||
guard and are dead; remove them once the API performance work lands.
|
||||
- **GH-17 cleanup.** The per-handler `Access-Control-*` lines in `pkg/app/handlers*.go` are removed; `apiOriginGuard` is the only CORS
|
||||
source. `TestHandlersSetNoCORSHeaders` and `TestAPIResponsesNeverCarryWildcardOrigin` guard it.
|
||||
|
||||
## Not fixed
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+2
-1
@@ -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,
|
||||
@@ -313,7 +314,7 @@ func (a *App) initializeComponents() error {
|
||||
// Initialize rescan worker if enabled
|
||||
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
|
||||
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.storage, a.config.Security.RescanInterval)
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval)
|
||||
}
|
||||
|
||||
// Initialize WebSocket server
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ func apiOriginGuard(allowed []string) fiber.Handler {
|
||||
|
||||
err := c.Next()
|
||||
|
||||
// Handlers set a wildcard grant; replace it with the allowlist decision.
|
||||
// Drop any grant a handler or upstream set; the allowlist decides.
|
||||
c.Response().Header.Del(headerACAllowOrigin)
|
||||
c.Response().Header.Del(headerACAllowMethods)
|
||||
c.Response().Header.Del(headerACAllowHeaders)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
// Handlers must not set CORS headers themselves: apiOriginGuard owns the decision.
|
||||
func TestHandlersSetNoCORSHeaders(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fset := token.NewFileSet()
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f, "_test.go") || f == "cors.go" {
|
||||
continue
|
||||
}
|
||||
parsed, err := parser.ParseFile(fset, f, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("parse %s: %v", f, err)
|
||||
}
|
||||
ast.Inspect(parsed, func(n ast.Node) bool {
|
||||
lit, ok := n.(*ast.BasicLit)
|
||||
if !ok || lit.Kind != token.STRING {
|
||||
return true
|
||||
}
|
||||
if v, err := strconv.Unquote(lit.Value); err == nil && strings.HasPrefix(v, "Access-Control-") {
|
||||
t.Errorf("%s: handler sets %q; apiOriginGuard owns CORS", fset.Position(lit.Pos()), v)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIResponsesNeverCarryWildcardOrigin(t *testing.T) {
|
||||
const dashboard = "https://dash.example.com"
|
||||
a := newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = []string{dashboard} })
|
||||
targets := []string{
|
||||
"/api/stats", "/api/info", "/api/config", "/api/packages",
|
||||
"/api/analytics/top", "/api/analytics/trending", "/api/analytics/trends", "/api/analytics/total",
|
||||
"/api/analytics/search?q=x", "/api/stats/timeseries",
|
||||
}
|
||||
for _, origin := range []string{"", dashboard, "https://evil.example.net"} {
|
||||
for _, target := range targets {
|
||||
hdr := map[string]string{}
|
||||
if origin != "" {
|
||||
hdr["Origin"] = origin
|
||||
}
|
||||
code, h, _ := doRequest(t, a, target, hdr)
|
||||
if code == http.StatusNotFound {
|
||||
t.Errorf("GET %s = 404, route missing", target)
|
||||
}
|
||||
if got := h.Get("Access-Control-Allow-Origin"); got == "*" {
|
||||
t.Errorf("GET %s Origin=%q carries Access-Control-Allow-Origin: *", target, origin)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
func doDelete(t *testing.T, a *App, target string) (int, string) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodDelete, target, nil)
|
||||
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 40 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatalf("DELETE %s: %v", target, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
return resp.StatusCode, string(body)
|
||||
}
|
||||
|
||||
func TestDeleteMissingPackageIs404(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
for _, target := range []string{
|
||||
"/api/packages/npm/nope/1.0.0",
|
||||
"/api/packages/pypi/nope/1.0.0",
|
||||
"/api/packages/go/example.com/nope/v1.0.0",
|
||||
} {
|
||||
code, body := doDelete(t, a, target)
|
||||
if code != http.StatusNotFound {
|
||||
t.Errorf("DELETE %s = %d %s, want 404", target, code, body)
|
||||
}
|
||||
var out map[string]string
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil || out["error"] == "" {
|
||||
t.Errorf("DELETE %s body %q is not a JSON error", target, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteExistingPackageIs200(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
ctx := context.Background()
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.0.0", StorageKey: "npm/left-pad/1.0.0",
|
||||
Size: 10, CachedAt: time.Now(), LastAccessed: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
|
||||
code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0")
|
||||
if code != http.StatusOK || !strings.Contains(body, `"deleted":true`) {
|
||||
t.Fatalf("DELETE existing = %d %s, want 200 deleted", code, body)
|
||||
}
|
||||
if code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0"); code != http.StatusNotFound {
|
||||
t.Errorf("second DELETE = %d %s, want 404", code, body)
|
||||
}
|
||||
}
|
||||
+6
-15
@@ -2,11 +2,13 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
apperrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
|
||||
@@ -16,9 +18,6 @@ import (
|
||||
// handlePackages handles /api/packages endpoint
|
||||
func (a *App) handlePackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -291,6 +290,10 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
} else {
|
||||
// For NPM and PyPI, delete directly
|
||||
if err := a.cache.Delete(ctx, registry, name, version); err != nil {
|
||||
var appErr *apperrors.Error
|
||||
if stderrors.As(err, &appErr) && appErr.Code == apperrors.ErrCodeNotFound {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
|
||||
}
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", registry).
|
||||
@@ -330,9 +333,6 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
// handleStats handles /api/stats endpoint
|
||||
func (a *App) handleStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -410,9 +410,6 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
// Returns time-series download statistics for charts
|
||||
func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -452,9 +449,6 @@ func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
|
||||
// Returns runtime configuration for the frontend
|
||||
func (a *App) handleConfig(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -486,9 +480,6 @@ func (a *App) handleConfig(c fiber.Ctx) error {
|
||||
// handleInfo handles /api/info endpoint
|
||||
func (a *App) handleInfo(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -45,9 +45,6 @@ func (a *App) requireAdmin(c fiber.Ctx) error {
|
||||
// handleAdminBypasses handles /api/admin/bypasses endpoint
|
||||
func (a *App) handleAdminBypasses(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
// handleAnalyticsTopPackages returns the most downloaded packages
|
||||
func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// Get limit from query params (default: 10)
|
||||
limit := 10
|
||||
@@ -31,7 +30,6 @@ func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
// handleAnalyticsTrendingPackages returns trending packages
|
||||
func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// Get limit from query params (default: 10)
|
||||
limit := 10
|
||||
@@ -52,7 +50,6 @@ func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
// handleAnalyticsTrends returns download trends over time
|
||||
func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
trends := a.analyticsEngine.GetTrends()
|
||||
|
||||
@@ -64,7 +61,6 @@ func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
|
||||
// handleAnalyticsTotalStats returns overall statistics
|
||||
func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
stats := a.analyticsEngine.GetTotalStats()
|
||||
|
||||
@@ -74,7 +70,6 @@ func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsRegistryStats returns per-registry statistics
|
||||
func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
registry := c.Params("registry")
|
||||
if registry == "" {
|
||||
@@ -91,7 +86,6 @@ func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsPackageStats returns statistics for a specific package
|
||||
func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
registry := c.Params("registry")
|
||||
name := c.Params("name")
|
||||
@@ -117,7 +111,6 @@ func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsSearch searches for packages matching a query
|
||||
func (a *App) handleAnalyticsSearch(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
query := c.Query("q")
|
||||
if query == "" {
|
||||
|
||||
@@ -11,9 +11,6 @@ import (
|
||||
// handleVulnerabilities handles /api/packages/{registry}/{name}/{version}/vulnerabilities endpoint
|
||||
func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
func listTree(t *testing.T, dir string) string {
|
||||
t.Helper()
|
||||
var names []string
|
||||
err := filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error {
|
||||
if err == nil {
|
||||
names = append(names, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.Join(names, "\n")
|
||||
}
|
||||
|
||||
// Shutdown must leave nothing running against the data directory: a late SQLite close deletes
|
||||
// its -wal/-shm files after Shutdown returned and breaks the removal of the directory.
|
||||
func TestShutdownLeavesDataDirectoryStable(t *testing.T) {
|
||||
for i := 0; i < 40; i++ {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default()
|
||||
cfg.Storage.Backend = "filesystem"
|
||||
cfg.Storage.Path = filepath.Join(dir, "store")
|
||||
cfg.Metadata.Backend = "sqlite"
|
||||
cfg.Metadata.SQLite.Path = filepath.Join(dir, "meta", "meta.db")
|
||||
if err := os.MkdirAll(filepath.Dir(cfg.Metadata.SQLite.Path), 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Security.Enabled = false
|
||||
cfg.Prewarming.Enabled = false
|
||||
cfg.Auth.Enabled = false
|
||||
a, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
doRequest(t, a, "/api/stats", nil)
|
||||
if err := a.Shutdown(); err != nil {
|
||||
t.Fatalf("Shutdown: %v", err)
|
||||
}
|
||||
before := listTree(t, dir)
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if after := listTree(t, dir); before != after {
|
||||
t.Fatalf("iteration %d: data directory changed after Shutdown:\nbefore:\n%s\nafter:\n%s", i, before, after)
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-6
@@ -16,15 +16,23 @@ func TestWorkersDrainTheBroadcastChannel(t *testing.T) {
|
||||
defer cancel()
|
||||
a.startWorkers(ctx)
|
||||
|
||||
const events = 1000
|
||||
for i := 0; i < events; i++ {
|
||||
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
|
||||
if i%200 == 0 {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
// Bursts stay under the 256-slot channel and wait for the loop to drain between them, so the
|
||||
// result depends on the loop running, not on how fast the scheduler runs it.
|
||||
const (
|
||||
bursts = 10
|
||||
burstLen = 100
|
||||
)
|
||||
for b := 0; b < bursts; b++ {
|
||||
for i := 0; i < burstLen; i++ {
|
||||
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
|
||||
}
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for a.wsServer.Pending() > 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
if dropped := a.wsServer.Dropped(); dropped != 0 {
|
||||
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, events)
|
||||
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, bursts*burstLen)
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+19
-10
@@ -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
|
||||
|
||||
Vendored
+75
@@ -0,0 +1,75 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// listingMetadata adds the full listing the rescan worker walks.
|
||||
type listingMetadata struct{ scanMetadata }
|
||||
|
||||
func (m listingMetadata) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return m.list(0, func(*metadata.Package) bool { return true }, func(a, b *metadata.Package) bool { return a.Name < b.Name }), nil
|
||||
}
|
||||
|
||||
// bodyScanner reports the bytes it can read at the path it is given.
|
||||
type bodyScanner struct{ seen chan string }
|
||||
|
||||
func (*bodyScanner) Name() string { return "body-scanner" }
|
||||
func (*bodyScanner) Health(context.Context) error { return nil }
|
||||
func (s *bodyScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
s.seen <- "unreadable"
|
||||
return nil, err
|
||||
}
|
||||
s.seen <- string(body)
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: s.Name(), Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
|
||||
// A backend with no local path (S3, SMB) must still be rescanned: the worker reads the blob
|
||||
// through the cache's file source instead of skipping the package.
|
||||
func TestRescanWorkerScansRemoteStorage(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage() // no GetLocalPath, like S3 and SMB
|
||||
meta := listingMetadata{scanMetadata{newMemMetadata(clock)}}
|
||||
|
||||
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true}, meta)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(scanMgr.Stop)
|
||||
bs := &bodyScanner{seen: make(chan string, 8)}
|
||||
scanMgr.RegisterScanner(bs)
|
||||
|
||||
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
scanMgr.SetFileSource(mgr.ScanFile)
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, store.Put(ctx, "npm/left-pad/1.3.0", strings.NewReader("tarball-bytes"), nil))
|
||||
require.NoError(t, meta.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
CachedAt: clock.Now(), LastAccessed: clock.Now(),
|
||||
}))
|
||||
|
||||
worker := scanner.NewRescanWorker(scanMgr, meta, time.Hour)
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
done := make(chan struct{})
|
||||
go func() { worker.Start(runCtx); close(done) }()
|
||||
t.Cleanup(func() { cancel(); <-done })
|
||||
|
||||
select {
|
||||
case got := <-bs.seen:
|
||||
require.Equal(t, "tarball-bytes", got)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("rescan never scanned the remote-storage package")
|
||||
}
|
||||
}
|
||||
Vendored
+38
@@ -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")
|
||||
}
|
||||
+20
-5
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
@@ -17,6 +18,8 @@ type AggregationWorker struct {
|
||||
stopChan chan struct{}
|
||||
ticker *time.Ticker
|
||||
now func() time.Time // nil means time.Now
|
||||
wg sync.WaitGroup
|
||||
stopOnce sync.Once
|
||||
}
|
||||
|
||||
// NewAggregationWorker creates a new aggregation worker
|
||||
@@ -36,6 +39,15 @@ func (w *AggregationWorker) clock() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// StartAsync runs Start in a goroutine that Stop waits for.
|
||||
func (w *AggregationWorker) StartAsync() {
|
||||
w.wg.Add(1)
|
||||
go func() {
|
||||
defer w.wg.Done()
|
||||
w.Start()
|
||||
}()
|
||||
}
|
||||
|
||||
// Start begins the aggregation worker
|
||||
func (w *AggregationWorker) Start() {
|
||||
log.Info().Msg("Starting aggregation worker")
|
||||
@@ -68,9 +80,10 @@ func (w *AggregationWorker) Start() {
|
||||
}
|
||||
}
|
||||
|
||||
// Stop stops the aggregation worker
|
||||
// Stop stops the aggregation worker and waits for a started one to exit. Safe to call repeatedly.
|
||||
func (w *AggregationWorker) Stop() {
|
||||
close(w.stopChan)
|
||||
w.stopOnce.Do(func() { close(w.stopChan) })
|
||||
w.wg.Wait()
|
||||
}
|
||||
|
||||
// AggregateHourly aggregates download events into hourly stats
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package gormstore
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCloseIsIdempotent(t *testing.T) {
|
||||
store := openFileStore(t, true)
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatalf("first Close: %v", err)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatalf("second Close: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -128,7 +128,7 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
|
||||
// Start aggregation worker (skip for in-memory databases used in tests)
|
||||
if !strings.Contains(cfg.DSN, ":memory:") {
|
||||
store.aggregationWorker = NewAggregationWorker(db)
|
||||
go store.aggregationWorker.Start()
|
||||
store.aggregationWorker.StartAsync()
|
||||
} else {
|
||||
// For tests: create worker but don't start it
|
||||
store.aggregationWorker = NewAggregationWorker(db)
|
||||
|
||||
+17
-29
@@ -6,14 +6,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/storage"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// RescanWorker handles periodic re-scanning of cached packages
|
||||
type RescanWorker struct {
|
||||
metadataStore metadata.MetadataStore
|
||||
storage storage.StorageBackend
|
||||
manager *Manager
|
||||
stopCh chan struct{}
|
||||
stopOnce sync.Once
|
||||
@@ -21,11 +19,10 @@ type RescanWorker struct {
|
||||
}
|
||||
|
||||
// NewRescanWorker creates a new rescan worker
|
||||
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, storageBackend storage.StorageBackend, interval time.Duration) *RescanWorker {
|
||||
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration) *RescanWorker {
|
||||
return &RescanWorker{
|
||||
manager: manager,
|
||||
metadataStore: metadataStore,
|
||||
storage: storageBackend,
|
||||
interval: interval,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
@@ -123,7 +120,6 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
|
||||
Str("version", pkg.Version).
|
||||
Msg("Package needs rescanning")
|
||||
|
||||
// Get file path from storage using the storage key from the package metadata
|
||||
if pkg.StorageKey == "" {
|
||||
log.Warn().
|
||||
Str("registry", pkg.Registry).
|
||||
@@ -134,7 +130,18 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
|
||||
filePath, err := w.getPackageFilePath(ctx, pkg.StorageKey)
|
||||
source := w.manager.currentFileSource()
|
||||
if source == nil {
|
||||
log.Debug().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("No file source configured, skipping rescan")
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
filePath, cleanup, err := source(ctx, pkg.Registry, pkg.Name, pkg.Version)
|
||||
if err != nil {
|
||||
log.Warn().
|
||||
Err(err).
|
||||
@@ -142,23 +149,15 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Str("storage_key", pkg.StorageKey).
|
||||
Msg("Failed to get package file path, skipping rescan")
|
||||
Msg("Failed to read package file, skipping rescan")
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
|
||||
if filePath == "" {
|
||||
log.Debug().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("No local file path available, skipping rescan")
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
// Perform the actual scan
|
||||
if err := w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath); err != nil {
|
||||
err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath)
|
||||
cleanup()
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", pkg.Registry).
|
||||
@@ -210,14 +209,3 @@ func (w *RescanWorker) needsRescan(ctx context.Context, pkg *metadata.Package) (
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// getPackageFilePath retrieves the local file path for a package from storage
|
||||
func (w *RescanWorker) getPackageFilePath(ctx context.Context, storageKey string) (string, error) {
|
||||
// Check if storage backend supports local paths
|
||||
if localProvider, ok := w.storage.(storage.LocalPathProvider); ok {
|
||||
return localProvider.GetLocalPath(ctx, storageKey)
|
||||
}
|
||||
|
||||
// If storage doesn't support local paths (S3, SMB), we can't rescan
|
||||
return "", nil
|
||||
}
|
||||
|
||||
@@ -65,6 +65,12 @@ func (m *Manager) SetFileSource(fs FileSource) {
|
||||
m.stateMu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Manager) currentFileSource() FileSource {
|
||||
m.stateMu.Lock()
|
||||
defer m.stateMu.Unlock()
|
||||
return m.fileSource
|
||||
}
|
||||
|
||||
// Manager manages multiple security scanners
|
||||
type Manager struct {
|
||||
metadataStore metadata.MetadataStore
|
||||
|
||||
@@ -251,6 +251,11 @@ func (s *Server) Dropped() uint64 {
|
||||
return s.dropped.Load()
|
||||
}
|
||||
|
||||
// Pending returns how many events wait in the broadcast channel.
|
||||
func (s *Server) Pending() int {
|
||||
return len(s.broadcast)
|
||||
}
|
||||
|
||||
// BroadcastEvent satisfies the events.Broadcaster contract used by
|
||||
// cache/scanner sub-systems. It accepts a string event type and an
|
||||
// arbitrary payload (typically map[string]any) and forwards to the
|
||||
|
||||
Reference in New Issue
Block a user