Compare commits

...
5 Commits
Author SHA1 Message Date
lukaszraczylo 380b3b9d1c fix(frontend): keep package endpoints off the dashboard proxy
The dashboard image forwarded /npm, /pypi, /go and /metrics to the
backend, so exposing the dashboard also exposed the package cache. Those
paths now return 404. The WebSocket location also matches /ws, the path
the backend serves.
2026-11-23 00:32:47 +00:00
lukaszraczylo a313ac1096 fix(proxy): serve escaped npm scopes and unscanned packages
npm and pnpm request scoped packages as @scope%2fname. Fiber's adaptor
answers 404 to an escaped slash, so a route middleware now rewrites the
scope separator before the adaptor runs.

With scanning off, the cache still waited 30 s for a scan result and then
refused the package. A scanner that is off is now treated as absent.

A scan that fails on infrastructure (timeout, network error, upstream 5xx)
no longer blocks the package until its entry expires. The package is
served and the scan is retried every scan_retry_interval. Set
security.fail_closed to refuse such packages.

The OSV api_url default and the docs named the host, which answers 404 to a
query. They now name https://api.osv.dev/v1/query, and a bare host is
completed with the query path.
2026-11-23 00:31:47 +00:00
lukaszraczylo 65b2f23486 fix(pypi): serve the PEP 691 JSON simple API with upload-time
The proxy returned HTML pages only. uv with --exclude-newer drops files
that carry no upload time, so every file was filtered out. The handler
now negotiates the representation from the Accept header, as PyPI does.
It passes the upstream JSON through, including PEP 700 upload-time, and
rewrites only the file URLs. HTML clients keep HTML. The handler also
fetches the PEP 658 metadata sidecar and trusts the configured upstream
host for file URLs.
2026-11-23 00:31:40 +00:00
lukaszraczylo cfab914a24 fix(sqlite): take the write lock at transaction start
Read-then-write transactions began deferred. SQLite returns SQLITE_BUSY
for these at once and ignores busy_timeout, so concurrent requests logged
"database is locked". The DSN now sets _txlock=immediate and a 15 s
busy_timeout, so writers queue. A concurrency test covers this.
2026-11-23 00:31:37 +00:00
github-actions[bot]andGitHub 00a2d2f6ed chore(deps): update dependencies
Automated dependency update. All tests passed.
2026-11-22 03:15:48 +00:00
26 changed files with 1196 additions and 67 deletions
+6 -29
View File
@@ -106,38 +106,15 @@ server {
access_log off;
}
# Metrics endpoint
location /metrics {
proxy_pass http://backend/metrics;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
# Package download endpoints
location ~ ^/(npm|pypi|go)/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
# Extended timeouts for package downloads
proxy_connect_timeout 60s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
# Large buffer for package downloads
proxy_buffering on;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
# The package endpoints are not part of the dashboard and stay on the
# backend Service. A catch-all 404 keeps them off the SPA fallback below.
location ~ ^/(npm|pypi|go|metrics)(/|$) {
return 404;
}
# WebSocket support
location /ws/ {
proxy_pass http://backend/ws/;
location /ws {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
+5 -1
View File
@@ -103,6 +103,10 @@ security:
block_on_severity: "high" # none, low, medium, high, critical
scan_on_download: true # Scan packages on first download
rescan_interval: "24h" # How often to re-scan packages (e.g., 24h, 168h for weekly)
# When a scan fails on infrastructure (timeout, upstream 5xx) the package is served and the
# scan is retried every scan_retry_interval. Set fail_closed to refuse such packages instead.
fail_closed: false
scan_retry_interval: "5m"
update_db_on_startup: false # Update vulnerability databases on startup
allowed_packages: [] # Packages that bypass security checks (format: "registry/name@version")
ignored_cves: [] # CVE IDs to ignore globally (e.g., "CVE-2021-23337")
@@ -125,7 +129,7 @@ security:
# Supports: npm, PyPI, Go, Maven, NuGet, etc.
osv:
enabled: false
api_url: "https://api.osv.dev"
api_url: "https://api.osv.dev/v1/query" # full query endpoint, not the host
timeout: "30s"
# Grype - Multi-ecosystem vulnerability scanner from Anchore
+4 -4
View File
@@ -39,7 +39,7 @@ importers:
version: 2.11.0([email protected]([email protected]))
tailwind-merge:
specifier: ^3.4.0
version: 3.7.0
version: 3.7.1
tailwindcss-animate:
specifier: ^1.0.7
version: 1.0.7([email protected])
@@ -1554,8 +1554,8 @@ packages:
resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
engines: {node: '>=8'}
[email protected].0:
resolution: {integrity: sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==}
[email protected].1:
resolution: {integrity: sha512-v7y4BV4FUlO8exj/4M5UXKeoowDiuugVUg3tkMNIyOUCOHy5xp8+5aWQeXCtZ2491sUV1YPsVeM9EveZ6/xuZQ==}
[email protected]:
resolution: {integrity: sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==}
@@ -3235,7 +3235,7 @@ snapshots:
dependencies:
has-flag: 4.0.0
[email protected].0: {}
[email protected].1: {}
[email protected]([email protected]):
dependencies:
+3 -3
View File
@@ -4,8 +4,8 @@ go 1.26.0
require (
github.com/aws/aws-sdk-go-v2 v1.48.0
github.com/aws/aws-sdk-go-v2/config v1.33.20
github.com/aws/aws-sdk-go-v2/credentials v1.21.2
github.com/aws/aws-sdk-go-v2/config v1.33.21
github.com/aws/aws-sdk-go-v2/credentials v1.21.3
github.com/aws/aws-sdk-go-v2/service/s3 v1.116.0
github.com/cloudsoda/go-smb2 v0.0.0-20261105190815-95be04a983b8
github.com/go-gormigrate/gormigrate/v2 v2.1.7
@@ -48,7 +48,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/signin v1.14.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.52.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 // indirect
github.com/aws/smithy-go v1.28.9 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
+6 -6
View File
@@ -12,10 +12,10 @@ github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk
github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 h1:3dMP9eEmHVosFN1QiD24IJBKVY8m6iUfVYXqRCT118Q=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27/go.mod h1:KH4PKcqtjy1m0656eqQV2v53xE04ddJzuNloEKqlHkI=
github.com/aws/aws-sdk-go-v2/config v1.33.20 h1:tcppf3ihhY8KsiVN5NJAN4uMlHc9NZrPRhkSuBTkqag=
github.com/aws/aws-sdk-go-v2/config v1.33.20/go.mod h1:WErTFkC327Fgt5x4SZHD2t1L64HTRb2kW42SqzEWxnA=
github.com/aws/aws-sdk-go-v2/credentials v1.21.2 h1:PWB8NaorQv2OzyNjXMy6RjBh+HzneyxY2ECC58jV600=
github.com/aws/aws-sdk-go-v2/credentials v1.21.2/go.mod h1:N/A5a+8LDrdI9pcr4ZjuHuQIHU5km3rtDuVzt+xW2C4=
github.com/aws/aws-sdk-go-v2/config v1.33.21 h1:NY1d3yXmplUSYnUAue0sR88svD+SJiaI+YJGp8TxSNg=
github.com/aws/aws-sdk-go-v2/config v1.33.21/go.mod h1:pVJNXUXaCLu9a/4/liTklg9zR3yO0xm/XBEQhgg5nzc=
github.com/aws/aws-sdk-go-v2/credentials v1.21.3 h1:bh+9VoJ4eDzJVEY6jfdNTBa0Dx7tdr+lWSPNovU1vXc=
github.com/aws/aws-sdk-go-v2/credentials v1.21.3/go.mod h1:4CNs0EBvjDEpyaXSYCdNeNRhFjHFX2Y373tFUaeTYXA=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9 h1:oH1E0tjN0g+ZRusbX1dsuat4FJ0z05l8hWaycSbDuNc=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9/go.mod h1:3ZaQGigIoaS45x9HgnLZ4sP475Fs7QoxU3IsZX/J3h4=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA=
@@ -40,8 +40,8 @@ github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 h1:ANAoa+qt3/9kXnvQVgUyxcTzhzZf
github.com/aws/aws-sdk-go-v2/service/sso v1.39.5/go.mod h1:vsMi+SSR7xGQXtV430LVi49qbv/R+U+upHHSp1W/+QI=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 h1:uIOBLMhef4N16WguadoHKuBy9etdz+RKTeqzchXErAI=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5/go.mod h1:NwWmkFLtsTVyXQpbzPOlYLwEoANkdCFjJRtrNcbg/vY=
github.com/aws/aws-sdk-go-v2/service/sts v1.52.0 h1:IaBLmJWiIEtKkjXMgMbYGZk7WKXbYA8148wCMCXq9hU=
github.com/aws/aws-sdk-go-v2/service/sts v1.52.0/go.mod h1:MG6N8U9+lY4LqchrlHPqCOSr7hyxw70XU0Et2YR3eNA=
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 h1:my9Y6lxcqvPV5k4OTqnxr8XbiTDDRos1leEh050Z93U=
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0/go.mod h1:MG6N8U9+lY4LqchrlHPqCOSr7hyxw70XU0Et2YR3eNA=
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
+1 -1
View File
@@ -406,7 +406,7 @@ security:
osv:
enabled: false
apiUrl: "https://api.osv.dev"
apiUrl: "https://api.osv.dev/v1/query"
timeout: "30s"
grype:
+12
View File
@@ -234,6 +234,7 @@ func (a *App) initializeComponents() error {
DefaultTTL: a.config.Cache.DefaultTTL,
CleanupInterval: cleanupInterval,
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
FailClosed: a.config.Security.FailClosed,
})
if err != nil {
return fmt.Errorf("failed to initialize cache: %w", err)
@@ -528,6 +529,12 @@ func (a *App) setupServer() error {
Upstream: npmUpstream,
})
npmProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/npm", npmProxyHandler))
a.app.Use("/npm", func(c fiber.Ctx) error {
if canonical := npm.CanonicalPath(c.Path()); canonical != c.Path() {
c.Path(canonical)
}
return c.Next()
})
if authEnabled {
a.app.All("/npm/*", mwAuth, adaptor.HTTPHandler(npmProxyWithCDN))
} else {
@@ -673,6 +680,11 @@ func (a *App) Shutdown() error {
a.rescanWorker.Stop()
}
// Cancel pending scan retries before the backends close.
if a.scanManager != nil {
a.scanManager.Stop()
}
// Close analytics engine
a.analyticsEngine.Close() // #nosec G104 -- Cleanup, error not critical
+286
View File
@@ -0,0 +1,286 @@
package app
import (
"archive/zip"
"bytes"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"testing"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/config"
)
// newTestApp builds a full App on temp storage with the given config tweaks.
func newTestApp(t *testing.T, mutate func(*config.Config)) *App {
t.Helper()
cfg := config.Default()
cfg.Storage.Backend = "filesystem"
cfg.Storage.Path = t.TempDir()
cfg.Metadata.Backend = "sqlite"
cfg.Metadata.SQLite.Path = t.TempDir() + "/meta.db"
cfg.Security.Enabled = false
cfg.Prewarming.Enabled = false
cfg.Auth.Enabled = false
if mutate != nil {
mutate(cfg)
}
a, err := New(cfg)
if err != nil {
t.Fatalf("app.New: %v", err)
}
t.Cleanup(func() { _ = a.Shutdown() })
return a
}
func doRequest(t *testing.T, a *App, target string, headers map[string]string) (int, http.Header, string) {
t.Helper()
req := httptest.NewRequest(http.MethodGet, target, nil)
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 40 * time.Second})
if err != nil {
t.Fatalf("GET %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, resp.Header, string(body)
}
func TestNPMScopedNames(t *testing.T) {
const tarball = "TARBALL-BYTES"
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/@types/node":
_, _ = w.Write([]byte(`{"name":"@types/node","versions":{"1.0.0":{"dist":{"tarball":"` + "http://" + r.Host + `/@types/node/-/node-1.0.0.tgz"}}}}`)) // #nosec G705 -- test upstream, JSON body
case "/@types/node/-/node-1.0.0.tgz":
_, _ = w.Write([]byte(tarball))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(upstream.Close)
a := newTestApp(t, func(c *config.Config) { c.Handlers.NPM.UpstreamRegistry = upstream.URL })
packuments := []string{"/npm/@types%2fnode", "/npm/@types%2Fnode", "/npm/@types/node"}
for _, target := range packuments {
t.Run("packument "+target, func(t *testing.T) {
code, _, body := doRequest(t, a, target, nil)
if code != http.StatusOK {
t.Fatalf("status = %d, want 200; body %q", code, body)
}
if !strings.Contains(body, `"name":"@types/node"`) {
t.Errorf("unexpected packument body %q", body)
}
})
}
tarballs := []string{
"/npm/@types%2fnode/-/node-1.0.0.tgz",
"/npm/@types%2Fnode/-/node-1.0.0.tgz",
"/npm/@types/node/-/node-1.0.0.tgz",
}
for _, target := range tarballs {
t.Run("tarball "+target, func(t *testing.T) {
code, _, body := doRequest(t, a, target, nil)
if code != http.StatusOK {
t.Fatalf("status = %d, want 200; body %q", code, body)
}
if body != tarball {
t.Errorf("tarball body = %q, want %q", body, tarball)
}
})
}
}
const (
pypiJSONType = "application/vnd.pypi.simple.v1+json"
pypiWheel = "foo-1.0.0-py3-none-any.whl"
pypiUploaded = "2020-01-02T03:04:05.678901Z"
)
// buildWheel returns a minimal valid wheel for distribution "foo" 1.0.0.
func buildWheel(t *testing.T) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
files := map[string]string{
"foo/__init__.py": "",
"foo-1.0.0.dist-info/METADATA": "Metadata-Version: 2.1\nName: foo\nVersion: 1.0.0\n",
"foo-1.0.0.dist-info/WHEEL": "Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
"foo-1.0.0.dist-info/RECORD": "",
"foo-1.0.0.dist-info/top_level.txt": "foo\n",
}
for name, content := range files {
w, err := zw.Create(name)
if err != nil {
t.Fatal(err)
}
_, _ = w.Write([]byte(content))
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
// newPyPIUpstream mimics pypi.org: JSON for PEP 691 clients, HTML otherwise.
func newPyPIUpstream(t *testing.T) (*httptest.Server, []byte) {
t.Helper()
wheel := buildWheel(t)
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/simple/foo/":
fileURL := srv.URL + "/packages/" + pypiWheel
if strings.Contains(r.Header.Get("Accept"), pypiJSONType) {
w.Header().Set("Content-Type", pypiJSONType)
_, _ = w.Write([]byte(`{"meta":{"api-version":"1.1"},"name":"foo","versions":["1.0.0"],"files":[{"filename":"` + pypiWheel +
`","url":"` + fileURL + `","hashes":{"sha256":"abc"},"requires-python":">=3.8","size":` + strconv.Itoa(len(wheel)) +
`,"upload-time":"` + pypiUploaded + `","yanked":false,"core-metadata":true}]}`))
return
}
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte(`<html><body><a href="` + fileURL + `#sha256=abc" data-requires-python="&gt;=3.8">` + pypiWheel + `</a></body></html>`))
case "/packages/" + pypiWheel:
_, _ = w.Write(wheel)
case "/packages/" + pypiWheel + ".metadata":
_, _ = w.Write([]byte("Metadata-Version: 2.1\nName: foo\nVersion: 1.0.0\n"))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv, wheel
}
func TestPyPISimpleJSON(t *testing.T) {
upstream, _ := newPyPIUpstream(t)
a := newTestApp(t, func(c *config.Config) { c.Handlers.PyPI.SimpleAPIURL = upstream.URL + "/simple" })
t.Run("json with upload-time passed through", func(t *testing.T) {
code, hdr, body := doRequest(t, a, "/pypi/simple/foo/", map[string]string{"Accept": pypiJSONType + ", text/html;q=0.01"})
if code != http.StatusOK {
t.Fatalf("status = %d, body %q", code, body)
}
if ct := hdr.Get("Content-Type"); ct != pypiJSONType {
t.Errorf("Content-Type = %q, want %q", ct, pypiJSONType)
}
var doc struct {
Meta map[string]string `json:"meta"`
Name string `json:"name"`
Files []map[string]any `json:"files"`
}
if err := json.Unmarshal([]byte(body), &doc); err != nil {
t.Fatalf("invalid JSON %q: %v", body, err)
}
if doc.Meta["api-version"] != "1.1" || doc.Name != "foo" || len(doc.Files) != 1 {
t.Fatalf("unexpected document: %+v", doc)
}
f := doc.Files[0]
if f["upload-time"] != pypiUploaded {
t.Errorf("upload-time = %v, want %s", f["upload-time"], pypiUploaded)
}
if f["requires-python"] != ">=3.8" || f["filename"] != pypiWheel {
t.Errorf("file fields not passed through: %v", f)
}
fileURL, _ := f["url"].(string)
if !strings.Contains(fileURL, "/pypi/foo/"+pypiWheel) || strings.HasPrefix(fileURL, upstream.URL) {
t.Errorf("file url %q must point at the proxy", fileURL)
}
})
t.Run("html kept for html clients", func(t *testing.T) {
for _, accept := range []string{"", "text/html", "*/*"} {
headers := map[string]string{}
if accept != "" {
headers["Accept"] = accept
}
code, hdr, body := doRequest(t, a, "/pypi/simple/foo/", headers)
if code != http.StatusOK || !strings.HasPrefix(hdr.Get("Content-Type"), "text/html") || !strings.Contains(body, "<a href=") {
t.Errorf("Accept %q: status %d type %q body %q", accept, code, hdr.Get("Content-Type"), body)
}
}
})
t.Run("unsupported accept is 406", func(t *testing.T) {
code, _, _ := doRequest(t, a, "/pypi/simple/foo/", map[string]string{"Accept": "application/xml"})
if code != http.StatusNotAcceptable {
t.Errorf("status = %d, want 406", code)
}
})
t.Run("core metadata sidecar fetches the metadata file", func(t *testing.T) {
_, _, body := doRequest(t, a, "/pypi/simple/foo/", map[string]string{"Accept": pypiJSONType})
var doc struct {
Files []struct {
URL string `json:"url"`
} `json:"files"`
}
if err := json.Unmarshal([]byte(body), &doc); err != nil {
t.Fatal(err)
}
u, err := url.Parse(doc.Files[0].URL)
if err != nil {
t.Fatal(err)
}
u.Path += ".metadata"
code, _, meta := doRequest(t, a, u.RequestURI(), nil)
if code != http.StatusOK || !strings.HasPrefix(meta, "Metadata-Version:") {
t.Errorf("metadata sidecar: status %d body %q", code, meta)
}
})
}
// uv with --exclude-newer drops files that carry no upload-time, so resolving
// through the proxy proves the PEP 700 field survives.
func TestPyPI_UVExcludeNewerResolvesThroughProxy(t *testing.T) {
uvPath, err := exec.LookPath("uv")
if err != nil {
t.Skip("uv not installed")
}
upstream, _ := newPyPIUpstream(t)
a := newTestApp(t, func(c *config.Config) { c.Handlers.PyPI.SimpleAPIURL = upstream.URL + "/simple" })
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
go func() { _ = a.app.Listener(ln, fiber.ListenConfig{DisableStartupMessage: true}) }()
base := "http://" + ln.Addr().String()
cutoff := "2021-01-01T00:00:00Z"
run := func(exclude string) (string, error) {
// #nosec G204 -- uvPath comes from LookPath; arguments are test constants
cmd := exec.Command(uvPath, "pip", "compile", "-", "--no-header", "--no-annotate", "--no-config", "--no-cache",
"--index-url", base+"/pypi/simple/", "--exclude-newer", exclude)
cmd.Stdin = strings.NewReader("foo\n")
cmd.Env = append(os.Environ(), "UV_CACHE_DIR="+t.TempDir())
out, runErr := cmd.CombinedOutput()
return string(out), runErr
}
out, err := run(cutoff)
if err != nil || !strings.Contains(out, "foo==1.0.0") {
t.Fatalf("uv --exclude-newer %s did not resolve foo: %v\n%s", cutoff, err, out)
}
out, err = run("2019-01-01T00:00:00Z")
if err == nil {
t.Fatalf("uv resolved foo although it was uploaded after the cutoff:\n%s", out)
}
}
+30 -7
View File
@@ -84,6 +84,15 @@ type Config struct {
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
// scannerToggle is implemented by scanners that can be switched off.
type scannerToggle interface {
Enabled() bool
}
// CacheEntry represents a cached package
@@ -126,6 +135,12 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
return nil, errors.New(errors.ErrCodeInvalidConfig, "metadata store is required")
}
// A scanner that is switched off never records a result, so waiting for
// one would stall every first download until the wait times out.
if toggle, ok := scanner.(scannerToggle); ok && !toggle.Enabled() {
scanner = nil
}
// Scanner is optional - can be nil if security scanning is disabled
if scanner != nil {
log.Info().Msg("Cache manager initialized with security scanning enabled")
@@ -152,6 +167,10 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
config.MaxConcurrent = 100
}
if config.ScanWaitTimeout == 0 {
config.ScanWaitTimeout = defaultScanWaitTimeout
}
if config.MaxPackageSize == 0 {
config.MaxPackageSize = 2 * 1024 * 1024 * 1024 // 2GB default
}
@@ -345,10 +364,10 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
// Wait briefly for initial scan to complete if scanner is enabled
// This prevents serving vulnerable packages on first request.
// SECURITY: timeouts MUST fail closed — never serve unscanned content.
// A wait that times out serves the package unless FailClosed is set; the
// scan keeps running and records its result for later requests.
if m.scanner != nil && !isMetadataEntry {
// Wait up to 30 seconds for scan to complete
scanCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
scanCtx, cancel := context.WithTimeout(ctx, m.config.ScanWaitTimeout)
defer cancel()
ticker := time.NewTicker(100 * time.Millisecond)
@@ -358,13 +377,17 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
for {
select {
case <-scanCtx.Done():
// Fail closed: do NOT serve unscanned packages on timeout/cancel.
// Package remains cached; subsequent requests can retry once
// the scan completes.
if ctx.Err() == nil && !m.config.FailClosed {
log.Warn().
Str("package", name).
Str("version", version).
Msg("Scan wait timed out - serving package, scan continues in background")
break scanWait
}
log.Warn().
Str("package", name).
Str("version", version).
Msg("Scan timeout - refusing to serve unscanned package (fail-closed)")
Msg("Scan wait ended - refusing to serve unscanned package (fail-closed)")
return nil, errors.New(errors.ErrCodeServiceUnavailable, "package scan in progress, retry shortly")
case <-ticker.C:
+84
View File
@@ -0,0 +1,84 @@
package cache
import (
"context"
"errors"
"io"
"strings"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/storage"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
// stubScanner never records a scan result, like a scanner that is off or hung.
type stubScanner struct {
enabled bool
}
func (s *stubScanner) Enabled() bool { return s.enabled }
func (s *stubScanner) ScanPackage(context.Context, string, string, string, string) error {
return nil
}
func (s *stubScanner) CheckVulnerabilities(context.Context, string, string, string) (bool, string, error) {
return false, "", nil
}
func newMissManager(t *testing.T, sc ScannerInterface, cfg Config) *Manager {
t.Helper()
mockStorage := &MockStorageBackend{}
mockMetadata := &MockMetadataStore{}
mockMetadata.On("GetPackage", mock.Anything, "npm", "lodash", "4.17.21").Return(nil, errors.New("not found")).Once()
mockMetadata.On("GetPackage", mock.Anything, "npm", "lodash", "4.17.21").
Return(&metadata.Package{Registry: "npm", Name: "lodash", Version: "4.17.21", StorageKey: "npm/lodash/4.17.21"}, nil)
mockStorage.On("GetQuota", mock.Anything).Return(&storage.QuotaInfo{Used: 100, Available: 900, Limit: 1000}, nil)
mockStorage.On("Put", mock.Anything, "npm/lodash/4.17.21", mock.Anything, mock.Anything).Return(nil)
mockMetadata.On("SavePackage", mock.Anything, mock.Anything).Return(nil)
mockStorage.On("Get", mock.Anything, "npm/lodash/4.17.21").Return(io.NopCloser(strings.NewReader("data")), nil)
mockMetadata.On("UpdateDownloadCount", mock.Anything, "npm", "lodash", "4.17.21").Return(nil)
mockStorage.On("Close").Return(nil)
mockMetadata.On("Close").Return(nil)
manager, err := New(mockStorage, mockMetadata, sc, nil, cfg)
require.NoError(t, err)
t.Cleanup(func() { _ = manager.Close() })
return manager
}
func fetchLodash(context.Context) (*FetchResult, error) {
return &FetchResult{Data: io.NopCloser(strings.NewReader("data")), UpstreamURL: "https://registry.npmjs.org/lodash"}, nil
}
// With scanning disabled the first download must not wait for a scan result.
func TestGet_DisabledScannerServesWithoutWaiting(t *testing.T) {
manager := newMissManager(t, &stubScanner{enabled: false}, Config{ScanWaitTimeout: 5 * time.Second})
start := time.Now()
entry, err := manager.Get(context.Background(), "npm", "lodash", "4.17.21", fetchLodash)
require.NoError(t, err)
require.NotNil(t, entry)
assert.Less(t, time.Since(start), 2*time.Second, "disabled scanner must not delay the first download")
}
// A scan that does not finish in time is an infrastructure problem: serve it
// unless the operator chose fail-closed.
func TestGet_ScanWaitTimeoutServesByDefault(t *testing.T) {
manager := newMissManager(t, &stubScanner{enabled: true}, Config{ScanWaitTimeout: 200 * time.Millisecond})
entry, err := manager.Get(context.Background(), "npm", "lodash", "4.17.21", fetchLodash)
require.NoError(t, err)
require.NotNil(t, entry)
}
func TestGet_ScanWaitTimeoutRefusesWhenFailClosed(t *testing.T) {
manager := newMissManager(t, &stubScanner{enabled: true}, Config{ScanWaitTimeout: 200 * time.Millisecond, FailClosed: true})
_, err := manager.Get(context.Background(), "npm", "lodash", "4.17.21", fetchLodash)
require.Error(t, err)
}
+3 -1
View File
@@ -150,6 +150,8 @@ type SecurityConfig struct {
Scanners ScannersConfig `mapstructure:"scanners" json:"scanners"`
BlockThresholds VulnerabilityThresholds `mapstructure:"block_thresholds" json:"block_thresholds"`
RescanInterval time.Duration `mapstructure:"rescan_interval" json:"rescan_interval"`
ScanRetryInterval time.Duration `mapstructure:"scan_retry_interval" json:"scan_retry_interval"` // wait before retrying a scan that failed on infrastructure; 0 = 5m
FailClosed bool `mapstructure:"fail_closed" json:"fail_closed"` // refuse packages whose scan failed on infrastructure
Enabled bool `mapstructure:"enabled" json:"enabled"`
ScanOnDownload bool `mapstructure:"scan_on_download" json:"scan_on_download"`
UpdateDBOnStartup bool `mapstructure:"update_db_on_startup" json:"update_db_on_startup"`
@@ -380,7 +382,7 @@ func Default() *Config {
},
OSV: OSVConfig{
Enabled: false,
APIURL: "https://api.osv.dev",
APIURL: "https://api.osv.dev/v1/query",
Timeout: 30 * time.Second,
},
Static: StaticConfig{
+7
View File
@@ -374,3 +374,10 @@ func TestConfigEdgeCases(t *testing.T) {
})
}
}
func TestDefaultOSVAPIURLIsQueryEndpoint(t *testing.T) {
const want = "https://api.osv.dev/v1/query"
if got := Default().Security.Scanners.OSV.APIURL; got != want {
t.Errorf("default OSV api_url = %q, want %q", got, want)
}
}
+10 -3
View File
@@ -68,13 +68,20 @@ func BuildMySQLDSN(host string, port int, user, password, database, charset stri
user, password, host, port, database, charset)
}
// BuildSQLiteDSN builds SQLite DSN with pragmas
// sqliteBusyTimeoutMs is how long a writer waits for the write lock before
// SQLite reports "database is locked".
const sqliteBusyTimeoutMs = 15000
// BuildSQLiteDSN builds SQLite DSN with pragmas.
// _txlock=immediate takes the write lock when a transaction begins. A deferred
// transaction that reads and then writes cannot wait for the lock (SQLite
// returns SQLITE_BUSY at once, ignoring busy_timeout), so it must not be used.
func BuildSQLiteDSN(path string, walMode bool) string {
if path == "" {
path = "gohoarder.db"
}
if walMode {
return fmt.Sprintf("%s?_journal_mode=WAL&_busy_timeout=5000&_synchronous=NORMAL&_cache_size=2000", path)
return fmt.Sprintf("%s?_journal_mode=WAL&_busy_timeout=%d&_txlock=immediate&_synchronous=NORMAL&_cache_size=2000", path, sqliteBusyTimeoutMs)
}
return fmt.Sprintf("%s?_journal_mode=DELETE&_busy_timeout=5000&_synchronous=NORMAL", path)
return fmt.Sprintf("%s?_journal_mode=DELETE&_busy_timeout=%d&_txlock=immediate&_synchronous=NORMAL", path, sqliteBusyTimeoutMs)
}
@@ -0,0 +1,99 @@
package gormstore
import (
"context"
"fmt"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
// openFileStore opens a store the way the app does for the sqlite backend.
func openFileStore(t *testing.T, walMode bool) *GORMStoreV2 {
t.Helper()
store, err := NewV2(Config{
Driver: "sqlite",
DSN: BuildSQLiteDSN(filepath.Join(t.TempDir(), "meta.db"), walMode),
LogLevel: "silent",
})
if err != nil {
t.Fatalf("NewV2: %v", err)
}
t.Cleanup(func() { _ = store.Close() })
return store
}
func TestBuildSQLiteDSN_Pragmas(t *testing.T) {
for _, walMode := range []bool{true, false} {
dsn := BuildSQLiteDSN("x.db", walMode)
wants := []string{"_busy_timeout=", "_txlock=immediate"}
if walMode {
wants = append(wants, "_journal_mode=WAL")
}
for _, want := range wants {
if !strings.Contains(dsn, want) {
t.Errorf("BuildSQLiteDSN(wal=%v) = %q, missing %q", walMode, dsn, want)
}
}
}
}
// Concurrent readers and writers must not surface "database is locked".
func TestSQLite_ConcurrentWritesDoNotLock(t *testing.T) {
store := openFileStore(t, true)
ctx := context.Background()
const packages = 8
for i := 0; i < packages; i++ {
now := time.Now()
if err := store.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: fmt.Sprintf("pkg-%d", i), Version: "1.0.0",
StorageKey: fmt.Sprintf("npm/pkg-%d/1.0.0", i), CachedAt: now, LastAccessed: now,
}); err != nil {
t.Fatalf("seed: %v", err)
}
}
const workers, iterations = 32, 25
var wg sync.WaitGroup
errs := make(chan error, workers*iterations*2)
for w := 0; w < workers; w++ {
wg.Add(1)
go func(w int) {
defer wg.Done()
for i := 0; i < iterations; i++ {
name := fmt.Sprintf("pkg-%d", (w+i)%packages)
if err := store.UpdateDownloadCount(ctx, "npm", name, "1.0.0"); err != nil {
errs <- fmt.Errorf("UpdateDownloadCount: %w", err)
}
now := time.Now()
if err := store.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: name, Version: "1.0.0",
StorageKey: "npm/" + name + "/1.0.0", CachedAt: now, LastAccessed: now,
}); err != nil {
errs <- fmt.Errorf("SavePackage: %w", err)
}
if _, err := store.GetPackage(ctx, "npm", name, "1.0.0"); err != nil {
errs <- fmt.Errorf("GetPackage: %w", err)
}
}
}(w)
}
wg.Wait()
close(errs)
failures := 0
for err := range errs {
failures++
if failures <= 5 {
t.Errorf("%v", err)
}
}
if failures > 0 {
t.Fatalf("%d operations failed under concurrency", failures)
}
}
+29
View File
@@ -19,6 +19,9 @@ import (
"github.com/rs/zerolog/log"
)
// routePrefix is where the handler is mounted.
const routePrefix = "/npm/"
// Handler implements the NPM registry protocol
type Handler struct {
cache *cache.Manager
@@ -75,6 +78,32 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
// CanonicalPath turns the escaped scope separator npm and pnpm send
// (/npm/@scope%2fname) into the literal form (/npm/@scope/name). Fiber's
// net/http adaptor answers 404 to any escaped slash, so the rewrite must
// happen before the adaptor. Only the first escape in the first segment is
// rewritten, so a name cannot smuggle extra path segments.
func CanonicalPath(path string) string {
rest, ok := strings.CutPrefix(path, routePrefix)
if !ok {
return path
}
segment, tail, _ := strings.Cut(rest, "/")
if !strings.HasPrefix(segment, "@") {
return path
}
for _, escaped := range []string{"%2f", "%2F"} {
if scope, name, found := strings.Cut(segment, escaped); found {
canonical := routePrefix + scope + "/" + name
if rest != segment {
canonical += "/" + tail
}
return canonical
}
}
return path
}
// handleMetadata handles package metadata requests
func (h *Handler) handleMetadata(ctx context.Context, w http.ResponseWriter, r *http.Request, path string) {
url := h.upstream + path
+18
View File
@@ -79,3 +79,21 @@ func TestExtractTarballInfo_Scoped(t *testing.T) {
})
}
}
func TestCanonicalPath(t *testing.T) {
tests := []struct{ in, want string }{
{"/npm/@types%2fnode", "/npm/@types/node"},
{"/npm/@types%2Fnode", "/npm/@types/node"},
{"/npm/@types%2fnode/-/node-1.0.0.tgz", "/npm/@types/node/-/node-1.0.0.tgz"},
{"/npm/@types/node", "/npm/@types/node"},
{"/npm/express", "/npm/express"},
{"/npm/express/-/express-4.0.0.tgz", "/npm/express/-/express-4.0.0.tgz"},
{"/npm/@a%2f..%2fb", "/npm/@a/..%2fb"},
{"/go/@a%2fb", "/go/@a%2fb"},
}
for _, tt := range tests {
if got := CanonicalPath(tt.in); got != tt.want {
t.Errorf("CanonicalPath(%q) = %q, want %q", tt.in, got, tt.want)
}
}
}
+32
View File
@@ -0,0 +1,32 @@
package pypi
import "testing"
func TestNegotiateFormat(t *testing.T) {
tests := []struct {
name string
accept string
want format
wantOK bool
}{
{"no header serves html", "", formatHTML, true},
{"wildcard serves html", "*/*", formatHTML, true},
{"browser", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", formatHTML, true},
{"uv", "application/vnd.pypi.simple.v1+json, application/vnd.pypi.simple.v1+html;q=0.2, text/html;q=0.01", formatJSON, true},
{"pip", "application/vnd.pypi.simple.v1+json, application/vnd.pypi.simple.v1+html; q=0.1, text/html; q=0.01", formatJSON, true},
{"explicit html", "application/vnd.pypi.simple.v1+html", formatHTML, true},
{"latest json alias", "application/vnd.pypi.simple.latest+json", formatJSON, true},
{"html preferred by q", "application/vnd.pypi.simple.v1+json;q=0.1, text/html", formatHTML, true},
{"json q zero refused", "application/vnd.pypi.simple.v1+json;q=0, text/html;q=0.5", formatHTML, true},
{"unsupported only", "application/xml", formatHTML, false},
{"tie prefers json", "text/html, application/vnd.pypi.simple.v1+json", formatJSON, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, ok := negotiateFormat(tt.accept)
if ok != tt.wantOK || (ok && got != tt.want) {
t.Errorf("negotiateFormat(%q) = (%v, %v), want (%v, %v)", tt.accept, got, ok, tt.want, tt.wantOK)
}
})
}
}
+43 -4
View File
@@ -80,6 +80,10 @@ func New(cacheManager *cache.Manager, client *network.Client, config Config) *Ha
if len(allowed) == 0 {
allowed = defaultAllowedPyPIHosts
}
// A private index serves its files from its own host.
if parsed, err := url.Parse(config.Upstream); err == nil && parsed.Hostname() != "" {
allowed = append(append([]string(nil), allowed...), parsed.Hostname())
}
return &Handler{
cache: cacheManager,
@@ -156,10 +160,24 @@ func (h *Handler) handleIndex(ctx context.Context, w http.ResponseWriter, r *htt
// handlePackagePage handles package page requests
func (h *Handler) handlePackagePage(ctx context.Context, w http.ResponseWriter, r *http.Request, path string) {
pageFormat, ok := negotiateFormat(r.Header.Get("Accept"))
if !ok {
http.Error(w, "No acceptable simple API representation", http.StatusNotAcceptable)
return
}
url := h.upstream + path
packageName := extractPackageName(path)
entry, err := h.cache.Get(ctx, "pypi", packageName, "page", func(ctx context.Context) (*cache.FetchResult, error) {
body, statusCode, err := h.client.Get(ctx, url, nil)
cacheVersion := "page"
var upstreamHeaders map[string]string
if pageFormat == formatJSON {
cacheVersion = jsonPageVersion
upstreamHeaders = map[string]string{"Accept": contentTypeJSON}
}
entry, err := h.cache.Get(ctx, "pypi", packageName, cacheVersion, func(ctx context.Context) (*cache.FetchResult, error) {
body, statusCode, err := h.client.Get(ctx, url, upstreamHeaders)
if err != nil {
return nil, err
}
@@ -194,10 +212,24 @@ func (h *Handler) handlePackagePage(ctx context.Context, w http.ResponseWriter,
// Rewrite package file URLs to point to our proxy
proxyBaseURL := getProxyBaseURL(r)
w.Header().Add("Vary", "Accept")
if pageFormat == formatJSON {
rewritten, err := rewriteJSONPage(buf.Bytes(), packageName, url, proxyBaseURL)
if err != nil {
log.Error().Err(err).Str("url", url).Msg("Failed to rewrite package page JSON")
http.Error(w, "Failed to parse package page", http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", contentTypeJSON)
_, _ = w.Write(rewritten) // #nosec G104 -- HTTP response write
return
}
modifiedHTML := rewritePackagePageURLs(buf.String(), packageName, proxyBaseURL)
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
_, _ = w.Write([]byte(modifiedHTML)) // #nosec G104 -- Websocket buffer write
w.Header().Set("Content-Type", contentTypeHTML)
_, _ = w.Write([]byte(modifiedHTML)) // #nosec G104 -- HTTP response write
}
// handlePackageFile handles package file download requests
@@ -241,6 +273,13 @@ func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter,
http.Error(w, "Invalid original_url", http.StatusBadRequest)
return
}
// The page links the wheel; a PEP 658 sidecar request appends
// ".metadata" to the proxy path, so the upstream URL needs it too.
if strings.HasSuffix(path, metadataSuffix) && !strings.HasSuffix(parsed.Path, metadataSuffix) {
parsed.Path += metadataSuffix
parsed.RawPath = ""
originalURL = parsed.String()
}
if !isAllowedPyPIHost(parsed.Host, h.allowedHosts) {
log.Warn().
Str("original_url", originalURL).
+131
View File
@@ -0,0 +1,131 @@
package pypi
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
)
type format int
const (
formatHTML format = iota
formatJSON
)
const (
// contentTypeJSON is the PEP 691 media type of the JSON simple API.
contentTypeJSON = "application/vnd.pypi.simple.v1+json"
contentTypeHTML = "text/html; charset=UTF-8"
// jsonPageVersion is the cache version of the upstream JSON page. It is on
// the cache's metadata-entry list, so the page is never security-scanned.
jsonPageVersion = "metadata"
metadataSuffix = ".metadata"
)
// negotiateFormat picks the simple-API representation for an Accept header the
// way PyPI does: the highest q wins, JSON wins a tie, and a client that states
// no preference (or only wildcards) gets HTML. ok is false when the client
// accepts none of the supported types.
func negotiateFormat(accept string) (format, bool) {
if strings.TrimSpace(accept) == "" {
return formatHTML, true
}
bestQ := -1.0
best := formatHTML
for _, part := range strings.Split(accept, ",") {
mediaType, q := parseMediaRange(part)
if q <= 0 {
continue
}
var candidate format
switch mediaType {
case "application/vnd.pypi.simple.v1+json", "application/vnd.pypi.simple.latest+json":
candidate = formatJSON
case "application/vnd.pypi.simple.v1+html", "application/vnd.pypi.simple.latest+html",
"text/html", "text/*", "*/*":
candidate = formatHTML
default:
continue
}
if q > bestQ || (q == bestQ && candidate == formatJSON) {
bestQ, best = q, candidate
}
}
return best, bestQ > 0
}
// parseMediaRange returns the lowercase media type and q-value of one Accept entry.
func parseMediaRange(entry string) (string, float64) {
fields := strings.Split(entry, ";")
mediaType := strings.ToLower(strings.TrimSpace(fields[0]))
q := 1.0
for _, param := range fields[1:] {
name, value, found := strings.Cut(strings.TrimSpace(param), "=")
if !found || !strings.EqualFold(strings.TrimSpace(name), "q") {
continue
}
if parsed, err := strconv.ParseFloat(strings.TrimSpace(value), 64); err == nil {
q = parsed
}
}
return mediaType, q
}
// rewriteJSONPage points every file URL of a PEP 691 page at the proxy. All
// other fields, including PEP 700 upload-time, pass through untouched.
func rewriteJSONPage(page []byte, packageName, pageURL, proxyBaseURL string) ([]byte, error) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(page, &doc); err != nil {
return nil, fmt.Errorf("parse simple JSON page: %w", err)
}
rawFiles, ok := doc["files"]
if !ok {
return page, nil
}
var files []map[string]json.RawMessage
if err := json.Unmarshal(rawFiles, &files); err != nil {
return nil, fmt.Errorf("parse simple JSON files: %w", err)
}
base, err := url.Parse(pageURL)
if err != nil {
return nil, fmt.Errorf("parse page URL: %w", err)
}
for _, file := range files {
var filename, fileURL string
if json.Unmarshal(file["filename"], &filename) != nil || filename == "" {
continue
}
if json.Unmarshal(file["url"], &fileURL) != nil || fileURL == "" {
continue
}
original := fileURL
if ref, parseErr := url.Parse(fileURL); parseErr == nil {
original = base.ResolveReference(ref).String()
}
proxied := fmt.Sprintf("%s/%s/%s?original_url=%s", proxyBaseURL, packageName, url.PathEscape(filename), url.QueryEscape(original))
encoded, marshalErr := json.Marshal(proxied)
if marshalErr != nil {
return nil, fmt.Errorf("encode file url: %w", marshalErr)
}
file["url"] = encoded
}
rewrittenFiles, err := json.Marshal(files)
if err != nil {
return nil, fmt.Errorf("encode simple JSON files: %w", err)
}
doc["files"] = rewrittenFiles
out, err := json.Marshal(doc)
if err != nil {
return nil, fmt.Errorf("encode simple JSON page: %w", err)
}
return out, nil
}
+2 -1
View File
@@ -15,6 +15,7 @@ import (
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -164,7 +165,7 @@ func (s *Scanner) queryAdvisories(ctx context.Context, ecosystem, packageName st
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("github api returned status %d: %s", resp.StatusCode, string(body))
return nil, &scanerr.StatusError{Service: "github api", Code: resp.StatusCode, Body: string(body)}
}
var advisories []GHSAAdvisory
+15 -5
View File
@@ -13,6 +13,7 @@ import (
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -94,10 +95,7 @@ type OSVEvent struct {
// New creates a new OSV scanner
func New(cfg config.OSVConfig) *Scanner {
apiURL := cfg.APIURL
if apiURL == "" {
apiURL = defaultOSVAPIURL
}
cfg.APIURL = queryURL(cfg.APIURL)
timeout := cfg.Timeout
if timeout == 0 {
@@ -113,6 +111,18 @@ func New(cfg config.OSVConfig) *Scanner {
}
// Name returns the scanner name
// queryURL returns the OSV query endpoint. A bare host is what older docs
// listed as api_url, and it answers 404 to a POST, so the path is added.
func queryURL(apiURL string) string {
if apiURL == "" {
return defaultOSVAPIURL
}
if strings.TrimRight(apiURL, "/") == "" || !strings.Contains(strings.TrimPrefix(strings.TrimPrefix(apiURL, "https://"), "http://"), "/") {
return strings.TrimRight(apiURL, "/") + "/v1/query"
}
return apiURL
}
func (s *Scanner) Name() string {
return ScannerName
}
@@ -169,7 +179,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
// Check status code
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("OSV API returned status %d: %s", resp.StatusCode, string(body))
return nil, &scanerr.StatusError{Service: "OSV API", Code: resp.StatusCode, Body: string(body)}
}
// Parse response
+46
View File
@@ -0,0 +1,46 @@
package osv
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
)
// A host-only api_url (the previously documented value) must still reach the
// query endpoint.
func TestScan_HostOnlyAPIURLUsesQueryEndpoint(t *testing.T) {
var gotPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
_, _ = w.Write([]byte(`{}`))
}))
t.Cleanup(srv.Close)
s := New(config.OSVConfig{APIURL: srv.URL})
if _, err := s.Scan(context.Background(), "npm", "left-pad", "1.0.0", ""); err != nil {
t.Fatalf("Scan: %v", err)
}
if gotPath != "/v1/query" {
t.Errorf("request path = %q, want /v1/query", gotPath)
}
}
func TestScan_FullQueryURLIsKept(t *testing.T) {
var gotPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
_, _ = w.Write([]byte(`{}`))
}))
t.Cleanup(srv.Close)
s := New(config.OSVConfig{APIURL: srv.URL + "/v1/query"})
if _, err := s.Scan(context.Background(), "npm", "left-pad", "1.0.0", ""); err != nil {
t.Fatalf("Scan: %v", err)
}
if gotPath != "/v1/query" {
t.Errorf("request path = %q, want /v1/query", gotPath)
}
}
+46
View File
@@ -0,0 +1,46 @@
// Package scanerr classifies scanner failures so callers can tell an
// unavailable scanner from a scan that found the package unsafe.
package scanerr
import (
"context"
"errors"
"fmt"
"net"
"net/http"
)
// ErrInfrastructure marks a failure of the scanning machinery (timeout,
// unreachable service) as opposed to a verdict on the package.
var ErrInfrastructure = errors.New("scanner infrastructure failure")
// StatusError is an HTTP status returned by a scanner's backing service.
type StatusError struct {
Service string
Body string
Code int
}
func (e *StatusError) Error() string {
return fmt.Sprintf("%s returned status %d: %s", e.Service, e.Code, e.Body)
}
// IsInfrastructure reports whether err means the scanner could not run
// (timeout, network failure, upstream 5xx or rate limit).
func IsInfrastructure(err error) bool {
if err == nil {
return false
}
if errors.Is(err, ErrInfrastructure) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return true
}
var netErr net.Error
if errors.As(err, &netErr) {
return true
}
var statusErr *StatusError
if errors.As(err, &statusErr) {
return statusErr.Code >= http.StatusInternalServerError || statusErr.Code == http.StatusTooManyRequests
}
return false
}
+42
View File
@@ -0,0 +1,42 @@
package scanerr
import (
"context"
"errors"
"fmt"
"net"
"net/url"
"testing"
)
func TestIsInfrastructure(t *testing.T) {
tests := []struct {
err error
name string
want bool
}{
{name: "nil", err: nil, want: false},
{name: "deadline", err: fmt.Errorf("scan: %w", context.DeadlineExceeded), want: true},
{name: "canceled", err: fmt.Errorf("scan: %w", context.Canceled), want: true},
{name: "net error", err: &url.Error{Op: "Post", URL: "http://x", Err: &net.OpError{Op: "dial", Err: errors.New("refused")}}, want: true},
{name: "upstream 503", err: fmt.Errorf("wrapped: %w", &StatusError{Service: "OSV API", Code: 503}), want: true},
{name: "upstream 429", err: &StatusError{Service: "OSV API", Code: 429}, want: true},
{name: "upstream 404", err: &StatusError{Service: "OSV API", Code: 404}, want: false},
{name: "marked", err: fmt.Errorf("trivy: %w", ErrInfrastructure), want: true},
{name: "plain", err: errors.New("scanner exploded"), want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsInfrastructure(tt.err); got != tt.want {
t.Errorf("IsInfrastructure(%v) = %v, want %v", tt.err, got, tt.want)
}
})
}
}
func TestStatusErrorMessage(t *testing.T) {
err := &StatusError{Service: "OSV API", Code: 500, Body: "boom"}
if got, want := err.Error(), "OSV API returned status 500: boom"; got != want {
t.Errorf("Error() = %q, want %q", got, want)
}
}
+113 -2
View File
@@ -20,6 +20,7 @@ import (
"github.com/lukaszraczylo/gohoarder/pkg/scanner/npmaudit"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/osv"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/pipaudit"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/trivy"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
@@ -43,14 +44,88 @@ type DatabaseUpdater interface {
UpdateDatabase(ctx context.Context) error
}
const (
// DetailInfrastructureError marks a stored scan-error result as caused by
// scanner infrastructure (timeout, upstream 5xx) rather than by the package.
DetailInfrastructureError = "infrastructure_error"
defaultScanRetryInterval = 5 * time.Minute
maxScanRetries = 6
)
// Manager manages multiple security scanners
type Manager struct {
metadataStore metadata.MetadataStore
broadcaster events.Broadcaster
retryTimers map[string]*time.Timer
inflight map[string]int
scanners []Scanner
config config.SecurityConfig
bcMu sync.RWMutex
stateMu sync.Mutex
enabled bool
stopped bool
}
// Enabled reports whether security scanning is on.
func (m *Manager) Enabled() bool {
return m.enabled
}
// Stop cancels pending scan retries.
func (m *Manager) Stop() {
m.stateMu.Lock()
defer m.stateMu.Unlock()
m.stopped = true
for key, timer := range m.retryTimers {
timer.Stop()
delete(m.retryTimers, key)
}
}
func scanKey(registry, packageName, version string) string {
return registry + "/" + packageName + "@" + version
}
func (m *Manager) markInflight(key string, delta int) {
m.stateMu.Lock()
defer m.stateMu.Unlock()
m.inflight[key] += delta
if m.inflight[key] <= 0 {
delete(m.inflight, key)
}
}
func (m *Manager) isInflight(key string) bool {
m.stateMu.Lock()
defer m.stateMu.Unlock()
return m.inflight[key] > 0
}
// scheduleRetry rescans a package whose scan failed on infrastructure.
func (m *Manager) scheduleRetry(registry, packageName, version, filePath string, attempt int) {
interval := m.config.ScanRetryInterval
if interval <= 0 {
interval = defaultScanRetryInterval
}
key := scanKey(registry, packageName, version)
m.stateMu.Lock()
defer m.stateMu.Unlock()
if m.stopped {
return
}
if old, ok := m.retryTimers[key]; ok {
old.Stop()
}
m.retryTimers[key] = time.AfterFunc(interval, func() {
m.stateMu.Lock()
delete(m.retryTimers, key)
m.stateMu.Unlock()
if err := m.scan(context.Background(), registry, packageName, version, filePath, attempt); err != nil {
log.Warn().Err(err).Str("package", packageName).Int("attempt", attempt).Msg("Scan retry failed")
}
})
}
// SetBroadcaster wires an events.Broadcaster onto the scanner so scan
@@ -81,6 +156,8 @@ func New(cfg config.SecurityConfig, metadataStore metadata.MetadataStore) (*Mana
enabled: cfg.Enabled,
config: cfg,
metadataStore: metadataStore,
retryTimers: make(map[string]*time.Timer),
inflight: make(map[string]int),
}
if !cfg.Enabled {
@@ -165,10 +242,20 @@ func (m *Manager) RegisterScanner(scanner Scanner) {
// ScanPackage scans a package using all registered scanners and saves results
func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, version string, filePath string) error {
return m.scan(ctx, registry, packageName, version, filePath, 0)
}
// scan runs every applicable scanner. attempt is 0 for the first scan and
// counts retries after an infrastructure failure.
func (m *Manager) scan(ctx context.Context, registry, packageName, version string, filePath string, attempt int) error {
if !m.enabled {
return nil
}
key := scanKey(registry, packageName, version)
m.markInflight(key, 1)
defer m.markInflight(key, -1)
log.Info().
Str("registry", registry).
Str("package", packageName).
@@ -178,6 +265,7 @@ func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, versio
// Collect results from all scanners
var scanResults []*metadata.ScanResult
scannerNames := make([]string, 0)
var infraFailures, otherFailures int
for _, scanner := range m.scanners {
// Skip scanners that don't support this registry
@@ -196,6 +284,11 @@ func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, versio
Str("scanner", scanner.Name()).
Str("package", packageName).
Msg("Scanner failed")
if scanerr.IsInfrastructure(err) {
infraFailures++
} else {
otherFailures++
}
continue
}
@@ -214,9 +307,16 @@ func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, versio
// fail closed (no scan == blocked) rather than silently leaving
// SecurityScanned=false which would allow the package to be served.
if len(scanResults) == 0 {
infraOnly := infraFailures > 0 && otherFailures == 0
if attempt > 0 && !infraOnly {
// Keep the earlier infrastructure-error result rather than
// replacing it with a failure the package did not cause.
return nil
}
log.Warn().
Str("package", packageName).
Msg("All scanners failed, saving scan-error result for fail-closed enforcement")
Bool("infrastructure", infraOnly).
Msg("All scanners failed, saving scan-error result")
errResult := &metadata.ScanResult{
ID: uuid.New().String(),
@@ -229,7 +329,8 @@ func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, versio
VulnerabilityCount: 0,
Vulnerabilities: []metadata.Vulnerability{},
Details: map[string]interface{}{
"error": "all configured scanners failed for this package",
"error": "all configured scanners failed for this package",
DetailInfrastructureError: infraOnly,
},
}
if err := m.metadataStore.SaveScanResult(ctx, errResult); err != nil {
@@ -246,6 +347,9 @@ func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, versio
"status": string(errResult.Status),
"vulnerability_count": errResult.VulnerabilityCount,
})
if infraOnly && attempt < maxScanRetries {
m.scheduleRetry(registry, packageName, version, filePath, attempt+1)
}
return nil
}
@@ -468,6 +572,9 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
if err != nil {
var hErr *hoardererrors.Error
if stderrors.As(err, &hErr) && hErr.Code == hoardererrors.ErrCodeNotFound {
if !m.config.FailClosed && m.isInflight(scanKey(registry, packageName, version)) {
return false, "", nil
}
return true, "no scan available - fail closed", nil
}
// Real backend error (DB transient, etc.) — also block.
@@ -486,6 +593,10 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
// block. A scan-error record means we don't actually know whether the
// package is safe.
if result.Status == metadata.ScanStatusError {
if infra, _ := result.Details[DetailInfrastructureError].(bool); infra && !m.config.FailClosed {
log.Warn().Str("package", packageName).Msg("Scan failed on infrastructure, serving package; scan will be retried")
return false, "", nil
}
return true, "scan failed - fail closed", nil
}
+123
View File
@@ -3,6 +3,7 @@ package scanner
import (
"context"
"errors"
"fmt"
"sync"
"testing"
"time"
@@ -330,3 +331,125 @@ func TestCheckVulnerabilities_GoPackageBypassNotFound(t *testing.T) {
require.NoError(t, err)
assert.True(t, blocked, "a non-matching bypass should not unblock the package")
}
// resultStore returns a fixed scan result from GetScanResult and records saves.
type resultStore struct {
*stubMetadataStore
scan *metadata.ScanResult
}
func (m *resultStore) GetScanResult(context.Context, string, string, string) (*metadata.ScanResult, error) {
return m.scan, nil
}
func (m *resultStore) saved() []*metadata.ScanResult {
m.mu.Lock()
defer m.mu.Unlock()
return append([]*metadata.ScanResult(nil), m.savedResults...)
}
func TestScanPackage_InfrastructureErrorIsMarked(t *testing.T) {
store := &stubMetadataStore{}
mgr := newTestManager(t, store)
mgr.RegisterScanner(&stubScanner{name: "osv", err: fmt.Errorf("OSV API request failed: %w", context.DeadlineExceeded)})
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
require.Len(t, store.savedResults, 1)
assert.Equal(t, metadata.ScanStatusError, store.savedResults[0].Status)
assert.Equal(t, true, store.savedResults[0].Details[DetailInfrastructureError])
}
func TestScanPackage_NonInfrastructureErrorIsNotMarked(t *testing.T) {
store := &stubMetadataStore{}
mgr := newTestManager(t, store)
mgr.RegisterScanner(&stubScanner{name: "broken", err: errors.New("scanner exploded")})
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
require.Len(t, store.savedResults, 1)
assert.NotEqual(t, true, store.savedResults[0].Details[DetailInfrastructureError])
}
func infraErrorScan() *metadata.ScanResult {
return &metadata.ScanResult{
ID: "r", Scanner: "all", ScannedAt: time.Now(), Status: metadata.ScanStatusError,
Details: map[string]interface{}{DetailInfrastructureError: true},
}
}
func TestCheckVulnerabilities_InfrastructureErrorServesByDefault(t *testing.T) {
store := &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: infraErrorScan()}
mgr := newTestManager(t, store)
blocked, reason, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
require.NoError(t, err)
assert.False(t, blocked, "infrastructure scan error must not block, got reason %q", reason)
}
func TestCheckVulnerabilities_InfrastructureErrorBlocksWhenFailClosed(t *testing.T) {
store := &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: infraErrorScan()}
mgr, err := New(config.SecurityConfig{Enabled: true, FailClosed: true}, store)
require.NoError(t, err)
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
require.NoError(t, err)
assert.True(t, blocked)
}
func TestCheckVulnerabilities_PlainScanErrorStillBlocks(t *testing.T) {
scan := infraErrorScan()
scan.Details = map[string]interface{}{}
store := &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: scan}
mgr := newTestManager(t, store)
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
require.NoError(t, err)
assert.True(t, blocked)
}
// flakyScanner fails with an infrastructure error until failures is exhausted.
type flakyScanner struct {
failures int
calls int
mu sync.Mutex
}
func (f *flakyScanner) Name() string { return "osv" }
func (f *flakyScanner) Scan(_ context.Context, registry, name, version, _ string) (*metadata.ScanResult, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.calls++
if f.calls <= f.failures {
return nil, fmt.Errorf("OSV API request failed: %w", context.DeadlineExceeded)
}
return &metadata.ScanResult{
ID: "ok", Registry: registry, PackageName: name, PackageVersion: version,
Scanner: "osv", ScannedAt: time.Now(), Status: metadata.ScanStatusClean,
}, nil
}
func (f *flakyScanner) Health(context.Context) error { return nil }
func TestScanPackage_InfrastructureErrorIsRetried(t *testing.T) {
store := &stubMetadataStore{}
mgr, err := New(config.SecurityConfig{Enabled: true, ScanRetryInterval: 10 * time.Millisecond}, store)
require.NoError(t, err)
t.Cleanup(mgr.Stop)
mgr.RegisterScanner(&flakyScanner{failures: 1})
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
require.Eventually(t, func() bool {
store.mu.Lock()
defer store.mu.Unlock()
n := len(store.savedResults)
return n == 2 && store.savedResults[1].Status == metadata.ScanStatusClean
}, 2*time.Second, 10*time.Millisecond, "retry must save a clean result after the infrastructure error")
}
func TestScanner_DisabledReportsNotEnabled(t *testing.T) {
mgr, err := New(config.SecurityConfig{Enabled: false}, &stubMetadataStore{})
require.NoError(t, err)
assert.False(t, mgr.Enabled())
assert.True(t, newTestManager(t, &stubMetadataStore{}).Enabled())
}