From 12567560571dd2717f8e7775e56c43cf652b3c9f Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Mon, 23 Nov 2026 14:08:35 +0000 Subject: [PATCH] fix(api): drop dead per-handler CORS headers --- lean4/FINDINGS.md | 4 +- pkg/app/cors.go | 2 +- pkg/app/cors_wildcard_test.go | 67 +++++++++++++++++++++++++++++ pkg/app/handlers.go | 15 ------- pkg/app/handlers_admin.go | 3 -- pkg/app/handlers_analytics.go | 7 --- pkg/app/handlers_vulnerabilities.go | 3 -- 7 files changed, 70 insertions(+), 31 deletions(-) create mode 100644 pkg/app/cors_wildcard_test.go diff --git a/lean4/FINDINGS.md b/lean4/FINDINGS.md index ecc7529..529d5a0 100644 --- a/lean4/FINDINGS.md +++ b/lean4/FINDINGS.md @@ -61,8 +61,8 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`. - **GH-21.** `RescanWorker` still skips remote storage ("No local file path available"); that is a separate, unchanged behaviour. - **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 diff --git a/pkg/app/cors.go b/pkg/app/cors.go index 58cae93..5a82583 100644 --- a/pkg/app/cors.go +++ b/pkg/app/cors.go @@ -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) diff --git a/pkg/app/cors_wildcard_test.go b/pkg/app/cors_wildcard_test.go new file mode 100644 index 0000000..cfede1e --- /dev/null +++ b/pkg/app/cors_wildcard_test.go @@ -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) + } + } + } +} diff --git a/pkg/app/handlers.go b/pkg/app/handlers.go index dcd509a..836a9bb 100644 --- a/pkg/app/handlers.go +++ b/pkg/app/handlers.go @@ -18,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) @@ -336,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) @@ -416,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) @@ -458,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) @@ -492,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) diff --git a/pkg/app/handlers_admin.go b/pkg/app/handlers_admin.go index 73e1675..a58733f 100644 --- a/pkg/app/handlers_admin.go +++ b/pkg/app/handlers_admin.go @@ -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) diff --git a/pkg/app/handlers_analytics.go b/pkg/app/handlers_analytics.go index 4eb1ee6..6e179e9 100644 --- a/pkg/app/handlers_analytics.go +++ b/pkg/app/handlers_analytics.go @@ -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 == "" { diff --git a/pkg/app/handlers_vulnerabilities.go b/pkg/app/handlers_vulnerabilities.go index 42d17bc..7f8073d 100644 --- a/pkg/app/handlers_vulnerabilities.go +++ b/pkg/app/handlers_vulnerabilities.go @@ -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)