fix(api): restrict CORS to allowed origins, refuse cross-origin writes

This commit is contained in:
2026-11-23 13:38:38 +00:00
parent 549d56e0a1
commit f2049383cb
7 changed files with 251 additions and 3 deletions
+1
View File
@@ -193,6 +193,7 @@ server:
host: "0.0.0.0" host: "0.0.0.0"
read_timeout: "5m" read_timeout: "5m"
write_timeout: "5m" write_timeout: "5m"
allowed_origins: [] # Browser origins allowed to use /api and /ws; empty = same-origin only
storage: storage:
backend: "filesystem" # Options: filesystem, s3, smb backend: "filesystem" # Options: filesystem, s3, smb
+4
View File
@@ -12,6 +12,10 @@ server:
read_timeout: "5m" read_timeout: "5m"
write_timeout: "5m" write_timeout: "5m"
idle_timeout: "2m" idle_timeout: "2m"
# Origins allowed to call /api from a browser and to open the WebSocket. Exact
# ("https://gohoarder.example.com") or wildcard ("https://*.example.com").
# Empty: same-origin only. A cross-origin DELETE/POST/PATCH is refused with 403.
allowed_origins: []
tls: tls:
enabled: false enabled: false
cert_file: "" cert_file: ""
+1
View File
@@ -12,6 +12,7 @@ data:
read_timeout: {{ .Values.server.readTimeout | quote }} read_timeout: {{ .Values.server.readTimeout | quote }}
write_timeout: {{ .Values.server.writeTimeout | quote }} write_timeout: {{ .Values.server.writeTimeout | quote }}
idle_timeout: {{ .Values.server.idleTimeout | quote }} idle_timeout: {{ .Values.server.idleTimeout | quote }}
allowed_origins: {{ .Values.server.allowedOrigins | default list | toJson }}
tls: tls:
enabled: false enabled: false
+2
View File
@@ -93,6 +93,8 @@ server:
readTimeout: "5m" readTimeout: "5m"
writeTimeout: "5m" writeTimeout: "5m"
idleTimeout: "2m" idleTimeout: "2m"
# Browser origins allowed to use /api and /ws; empty = same-origin only
allowedOrigins: []
# Additional environment variables for server container # Additional environment variables for server container
# Use this to override config via environment variables # Use this to override config via environment variables
+5 -3
View File
@@ -413,6 +413,8 @@ func (a *App) setupServer() error {
_ = mwOptional // reserved for future endpoints with anonymous fallback _ = mwOptional // reserved for future endpoints with anonymous fallback
} }
a.app.Use("/api", apiOriginGuard(a.config.Server.AllowedOrigins))
// Health endpoints — ALWAYS public (k8s liveness/readiness probes). // Health endpoints — ALWAYS public (k8s liveness/readiness probes).
a.app.Get("/health", adaptor.HTTPHandlerFunc(a.healthChecker.HealthHandler())) a.app.Get("/health", adaptor.HTTPHandlerFunc(a.healthChecker.HealthHandler()))
a.app.Get("/health/ready", adaptor.HTTPHandlerFunc(a.healthChecker.ReadyHandler())) a.app.Get("/health/ready", adaptor.HTTPHandlerFunc(a.healthChecker.ReadyHandler()))
@@ -890,13 +892,13 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
} }
ou, err := url.Parse(origin) ou, err := url.Parse(origin)
if err != nil || ou.Scheme == "" || ou.Host == "" { if err != nil || ou.Scheme == "" || ou.Host == "" {
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header") log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
return false return false
} }
originScheme := strings.ToLower(ou.Scheme) originScheme := strings.ToLower(ou.Scheme)
originHost, ok := normalizeOriginHost(originScheme, ou.Host) originHost, ok := normalizeOriginHost(originScheme, ou.Host)
if !ok { if !ok {
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header") log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
return false return false
} }
@@ -927,7 +929,7 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
log.Warn(). log.Warn().
Str("origin", origin). Str("origin", origin).
Str("host", r.Host). Str("host", r.Host).
Msg("Rejecting WebSocket upgrade: Origin not in allowlist") Msg("Rejecting origin: Origin not in allowlist")
return false return false
} }
} }
+94
View File
@@ -0,0 +1,94 @@
package app
import (
"net/http"
"net/url"
"strings"
"github.com/gofiber/fiber/v3"
"github.com/rs/zerolog/log"
)
const (
headerOrigin = "Origin"
corsAllowedMethods = "GET, POST, PATCH, DELETE, OPTIONS"
corsAllowedHeaders = "Content-Type, Authorization, X-API-Key"
corsPreflightMaxAge = "600"
headerACRMethod = "Access-Control-Request-Method"
headerACAllowOrigin = "Access-Control-Allow-Origin"
headerACAllowMethods = "Access-Control-Allow-Methods"
headerACAllowHeaders = "Access-Control-Allow-Headers"
headerACMaxAge = "Access-Control-Max-Age"
)
// apiOriginGuard enforces server.allowed_origins on /api. A browser at another origin cannot
// read responses (no CORS grant) and cannot change state (403), whatever the handlers set.
// With nothing configured only the request's own host counts as same-origin.
// Requests with neither Origin nor Referer come from non-browser clients and pass.
func apiOriginGuard(allowed []string) fiber.Handler {
check := buildCheckOrigin(allowed)
originAllowed := func(c fiber.Ctx, origin string) bool {
r := &http.Request{Header: http.Header{headerOrigin: {origin}}, Host: c.Host()}
return check(r)
}
return func(c fiber.Ctx) error {
origin := c.Get(headerOrigin)
method := c.Method()
if method == http.MethodOptions && origin != "" && c.Get(headerACRMethod) != "" {
if !originAllowed(c, origin) {
return c.SendStatus(fiber.StatusForbidden)
}
setCORSGrant(c, origin)
c.Set(headerACMaxAge, corsPreflightMaxAge)
return c.SendStatus(fiber.StatusNoContent)
}
if !isSafeMethod(method) {
source := origin
if source == "" {
source = refererOrigin(c.Get(fiber.HeaderReferer))
}
if source != "" && !originAllowed(c, source) {
log.Warn().Str("method", method).Str("path", c.Path()).Str("origin", source).Msg("Rejecting cross-origin state-changing request")
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "cross-origin request not allowed"})
}
}
err := c.Next()
// Handlers set a wildcard grant; replace it with the allowlist decision.
c.Response().Header.Del(headerACAllowOrigin)
c.Response().Header.Del(headerACAllowMethods)
c.Response().Header.Del(headerACAllowHeaders)
c.Vary(headerOrigin)
if origin != "" && originAllowed(c, origin) {
setCORSGrant(c, origin)
}
return err
}
}
func setCORSGrant(c fiber.Ctx, origin string) {
c.Set(headerACAllowOrigin, origin)
c.Set(headerACAllowMethods, corsAllowedMethods)
c.Set(headerACAllowHeaders, corsAllowedHeaders)
c.Vary(headerOrigin)
}
func isSafeMethod(m string) bool {
return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions
}
// refererOrigin returns scheme://host of a Referer, or "" when it is absent or malformed.
func refererOrigin(referer string) string {
if strings.TrimSpace(referer) == "" {
return ""
}
u, err := url.Parse(referer)
if err != nil || u.Scheme == "" || u.Host == "" {
return "null" // present but unusable: never matches the allowlist
}
return u.Scheme + "://" + u.Host
}
+144
View File
@@ -0,0 +1,144 @@
package app
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/cache"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const dashboardOrigin = "https://gohoarder.example.com"
func seedPackage(t *testing.T, a *App) {
t.Helper()
entry, err := a.cache.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*cache.FetchResult, error) {
return &cache.FetchResult{Data: io.NopCloser(strings.NewReader("tarball"))}, nil
})
require.NoError(t, err)
_ = entry.Data.Close()
}
func apiCall(t *testing.T, a *App, method, target string, headers map[string]string) *http.Response {
t.Helper()
req := httptest.NewRequest(method, target, nil)
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 10 * time.Second})
require.NoError(t, err)
t.Cleanup(func() { _ = resp.Body.Close() })
return resp
}
func corsApp(t *testing.T, origins ...string) *App {
return newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = origins })
}
const deletePath = "/api/packages/npm/left-pad/1.3.0"
func TestAPIDeleteFromDisallowedOriginForbidden(t *testing.T) {
a := corsApp(t, dashboardOrigin)
seedPackage(t, a)
for _, h := range []map[string]string{
{"Origin": "https://evil.example.net"},
{"Origin": "null"},
{"Referer": "https://evil.example.net/page"},
{"Origin": "https://evil.example.net", "Referer": dashboardOrigin + "/x"},
} {
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
assert.Equal(t, http.StatusForbidden, resp.StatusCode, "%v", h)
}
resp := apiCall(t, a, http.MethodGet, "/api/packages/npm", nil)
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
assert.NoError(t, err, "a refused request must not delete")
}
func TestAPIDeleteFromAllowedOriginWorks(t *testing.T) {
for name, h := range map[string]map[string]string{
"origin": {"Origin": dashboardOrigin},
"referer": {"Referer": dashboardOrigin + "/packages"},
"no-fetch": nil, // curl and server-to-server callers send neither header
} {
t.Run(name, func(t *testing.T) {
a := corsApp(t, dashboardOrigin)
seedPackage(t, a)
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
assert.Equal(t, http.StatusOK, resp.StatusCode)
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
assert.Error(t, err, "package must be gone")
})
}
}
func TestAPIPostFromDisallowedOriginForbidden(t *testing.T) {
a := corsApp(t, dashboardOrigin)
resp := apiCall(t, a, http.MethodPost, "/api/admin/prewarming/trigger", map[string]string{"Origin": "https://evil.example.net"})
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
}
func TestAPIGetStaysPublicWithoutWildcardCORS(t *testing.T) {
a := corsApp(t, dashboardOrigin)
resp := apiCall(t, a, http.MethodGet, "/api/stats", nil)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": dashboardOrigin})
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, dashboardOrigin, resp.Header.Get("Access-Control-Allow-Origin"))
assert.Contains(t, resp.Header.Values("Vary"), "Origin")
// Served, but a browser at a foreign origin cannot read it.
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": "https://evil.example.net"})
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
}
func TestAPIPreflightAnswersOnlyAllowedOrigins(t *testing.T) {
a := corsApp(t, dashboardOrigin)
preflight := func(origin string) *http.Response {
return apiCall(t, a, http.MethodOptions, deletePath, map[string]string{
"Origin": origin, "Access-Control-Request-Method": "DELETE",
})
}
ok := preflight(dashboardOrigin)
assert.Equal(t, http.StatusNoContent, ok.StatusCode)
assert.Equal(t, dashboardOrigin, ok.Header.Get("Access-Control-Allow-Origin"))
assert.Contains(t, ok.Header.Get("Access-Control-Allow-Methods"), "DELETE")
bad := preflight("https://evil.example.net")
assert.Equal(t, http.StatusForbidden, bad.StatusCode)
assert.Empty(t, bad.Header.Get("Access-Control-Allow-Origin"))
}
// With nothing configured, only the host the request was sent to counts as same-origin.
func TestAPISameOriginRuleWhenNoOriginsConfigured(t *testing.T) {
a := corsApp(t)
seedPackage(t, a)
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://evil.example.net"})
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "http://example.com"}) // httptest.NewRequest Host
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func TestAPIOriginMatchingUsesAllowlistRules(t *testing.T) {
a := corsApp(t, "https://*.example.org")
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://ui.example.org"})
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://example.org.evil.net"})
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
}