From 536f35ab55d24e8b5b92af3b1b89115f6b27c89c Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Mon, 23 Nov 2026 14:14:09 +0000 Subject: [PATCH] fix(server): stop 431 on /api for browsers with large session cookies --- Dockerfile.frontend | 3 ++ config.yaml.example | 1 + helm/gohoarder/templates/configmap.yaml | 1 + helm/gohoarder/values.yaml | 1 + lean4/FINDINGS.md | 3 ++ pkg/app/app.go | 9 ++-- pkg/app/read_buffer_test.go | 37 ++++++++++++++++ pkg/config/config.go | 19 ++++++--- scripts/check_frontend_cookie_strip.sh | 57 +++++++++++++++++++++++++ 9 files changed, 122 insertions(+), 9 deletions(-) create mode 100644 pkg/app/read_buffer_test.go create mode 100755 scripts/check_frontend_cookie_strip.sh diff --git a/Dockerfile.frontend b/Dockerfile.frontend index 9038b18..59aaa94 100644 --- a/Dockerfile.frontend +++ b/Dockerfile.frontend @@ -85,6 +85,8 @@ server { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_set_header Connection ""; + # The backend authenticates by API-key header; browser session cookies only bloat the request. + proxy_set_header Cookie ""; # Timeouts for long-running operations proxy_connect_timeout 60s; @@ -122,6 +124,7 @@ server { 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 Cookie ""; # WebSocket timeouts proxy_connect_timeout 7d; diff --git a/config.yaml.example b/config.yaml.example index e026874..4765ac3 100644 --- a/config.yaml.example +++ b/config.yaml.example @@ -10,6 +10,7 @@ server: host: "0.0.0.0" port: 8080 # Backend API server port read_timeout: "5m" + read_buffer_size: 16384 # Bytes for the request line plus headers; larger requests get 431 write_timeout: "5m" idle_timeout: "2m" # Origins allowed to call /api from a browser and to open the WebSocket. Exact diff --git a/helm/gohoarder/templates/configmap.yaml b/helm/gohoarder/templates/configmap.yaml index b9e17e8..2141869 100644 --- a/helm/gohoarder/templates/configmap.yaml +++ b/helm/gohoarder/templates/configmap.yaml @@ -10,6 +10,7 @@ data: host: {{ .Values.server.host | quote }} port: {{ .Values.server.port }} read_timeout: {{ .Values.server.readTimeout | quote }} + read_buffer_size: {{ .Values.server.readBufferSize }} write_timeout: {{ .Values.server.writeTimeout | quote }} idle_timeout: {{ .Values.server.idleTimeout | quote }} allowed_origins: {{ .Values.server.allowedOrigins | default list | toJson }} diff --git a/helm/gohoarder/values.yaml b/helm/gohoarder/values.yaml index a90326c..ab78e9b 100644 --- a/helm/gohoarder/values.yaml +++ b/helm/gohoarder/values.yaml @@ -91,6 +91,7 @@ server: host: "0.0.0.0" port: 8080 readTimeout: "5m" + readBufferSize: 16384 # Bytes for the request line plus headers; larger requests get 431 writeTimeout: "5m" idleTimeout: "2m" # Browser origins allowed to use /api and /ws; empty = same-origin only diff --git a/lean4/FINDINGS.md b/lean4/FINDINGS.md index 74c8593..ecc7529 100644 --- a/lean4/FINDINGS.md +++ b/lean4/FINDINGS.md @@ -26,6 +26,7 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`. | GH-19 | SSRF | every redirect hop passes the upstream allowlist, the scheme rule and a non-private address check | security, CWE-918 | medium | `Access.redirect_escapes_allowlist`, `fixed_redirect_stays_allowlisted` / `TestRedirectToDisallowedHostRefused`, `TestRedirectToLoopbackRefused`, `TestRedirectToPrivateLiteralRefused`, `TestRedirectAllowedToAllowedWorks`, `TestRedirectHopsCapped`, `TestSidecarRedirectOffAllowlistRefused` | 787c757 | | GH-20 | stats, sqlite | SQLite upserts hourly and daily rows as PostgreSQL does, one row per bucket | correctness | low (SQLite only) | `Stats.old_sqlite_duplicates_rows`, `fixed_sqlite_package_row_keeps_late_events` / `TestSQLiteHourlyTotalsMatchPostgresSemantics`, `TestPostgresHourlyTotalsMatchSQLite`, `TestSQLiteDailyRollupIsIdempotent`, `TestSQLiteStatsDedupeMigration` | f46e079 | | GH-21 | scan retry | a scan retry on S3 or SMB storage reads the stored blob instead of a removed temp file | correctness | low (file-based scanners on remote storage) | `Security.old_remote_retry_unreadable`, `fixed_retry_always_readable` / `TestScanRetryOnRemoteStorageReadsBlobAgain` | 31db940 | +| GH-22 | dashboard API | an OIDC-logged-in browser can call `/api` with a long URL; the proxy hop neither forwards session cookies nor exceeds the read buffer | availability | medium (every `/api` call returned 431 for OIDC users) | not modelled (header size, no decision logic) / `TestLargeRequestHeadersAreAccepted`, `TestReadBufferSizeIsConfigurable`, `scripts/check_frontend_cookie_strip.sh` | this change | ### Exploit paths and reach @@ -58,6 +59,8 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`. 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-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. diff --git a/pkg/app/app.go b/pkg/app/app.go index f63552c..ff0ec24 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -391,10 +391,11 @@ func (a *App) initializeComponents() error { func (a *App) setupServer() error { // Create Fiber app a.app = fiber.New(fiber.Config{ - ReadTimeout: a.config.Server.ReadTimeout, - WriteTimeout: a.config.Server.WriteTimeout, - ServerHeader: "GoHoarder", - AppName: "GoHoarder v1.0", + ReadTimeout: a.config.Server.ReadTimeout, + WriteTimeout: a.config.Server.WriteTimeout, + ReadBufferSize: a.config.Server.ReadBufferSize, + ServerHeader: "GoHoarder", + AppName: "GoHoarder v1.0", }) // Auth middleware factories. Built once, reused on every gated route. diff --git a/pkg/app/read_buffer_test.go b/pkg/app/read_buffer_test.go new file mode 100644 index 0000000..f7c5418 --- /dev/null +++ b/pkg/app/read_buffer_test.go @@ -0,0 +1,37 @@ +package app + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/lukaszraczylo/gohoarder/pkg/config" +) + +const recentPackagesURL = "/api/packages?page=1&page_size=10&sort=cached_at&order=desc" + +// Fiber v3 defaults to an 8192-byte read buffer; OIDC session cookies plus a long Referer exceed it. +func TestLargeRequestHeadersAreAccepted(t *testing.T) { + a := newTestApp(t, nil) + headers := map[string]string{ + "Cookie": "session=" + strings.Repeat("a", 5000), + "Referer": "https://dash.example.com/" + strings.Repeat("r", 5000), + } + code, _, body := doRequest(t, a, recentPackagesURL, headers) + if code != http.StatusOK { + t.Fatalf("GET with ~10KB of headers = %d %q, want 200", code, body) + } +} + +func TestReadBufferSizeIsConfigurable(t *testing.T) { + if got := config.Default().Server.ReadBufferSize; got != 16384 { + t.Fatalf("default server.read_buffer_size = %d, want 16384", got) + } + a := newTestApp(t, func(c *config.Config) { c.Server.ReadBufferSize = 4096 }) + req := httptest.NewRequest(http.MethodGet, recentPackagesURL, nil) + req.Header.Set("Cookie", "session="+strings.Repeat("a", 6000)) + if _, err := a.app.Test(req); err == nil || !strings.Contains(err.Error(), "small read buffer") { + t.Errorf("6KB header with a 4096 buffer: err = %v, want a small-read-buffer rejection", err) + } +} diff --git a/pkg/config/config.go b/pkg/config/config.go index 839f282..aeab417 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -35,6 +35,7 @@ type ServerConfig struct { ReadTimeout time.Duration `mapstructure:"read_timeout" json:"read_timeout"` WriteTimeout time.Duration `mapstructure:"write_timeout" json:"write_timeout"` IdleTimeout time.Duration `mapstructure:"idle_timeout" json:"idle_timeout"` + ReadBufferSize int `mapstructure:"read_buffer_size" json:"read_buffer_size"` // bytes; caps the request line plus headers } // TLSConfig contains TLS/HTTPS configuration @@ -137,6 +138,10 @@ type MySQLConfig struct { // release-age gate clients apply, so a cached page never hides the entries the gate reads. const DefaultMetadataTTL = 24 * time.Hour +// DefaultReadBufferSize is the HTTP server read buffer. Fiber's own 8192 rejects browsers +// that send OIDC session cookies plus a long Referer or URL with 431. +const DefaultReadBufferSize = 16384 + // DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it. const DefaultIdleTTL = 7 * 24 * time.Hour @@ -334,11 +339,12 @@ type PyPIHandlerConfig struct { func Default() *Config { return &Config{ Server: ServerConfig{ - Host: "0.0.0.0", - Port: 8080, - ReadTimeout: 5 * time.Minute, - WriteTimeout: 5 * time.Minute, - IdleTimeout: 2 * time.Minute, + Host: "0.0.0.0", + Port: 8080, + ReadTimeout: 5 * time.Minute, + WriteTimeout: 5 * time.Minute, + IdleTimeout: 2 * time.Minute, + ReadBufferSize: DefaultReadBufferSize, TLS: TLSConfig{ Enabled: false, }, @@ -511,6 +517,9 @@ func (c *Config) Validate() error { } // Validate cache + if c.Server.ReadBufferSize < 0 { + return fmt.Errorf("server.read_buffer_size cannot be negative") + } if c.Cache.DefaultTTL < 0 { return fmt.Errorf("cache.default_ttl cannot be negative") } diff --git a/scripts/check_frontend_cookie_strip.sh b/scripts/check_frontend_cookie_strip.sh new file mode 100755 index 0000000..424aadb --- /dev/null +++ b/scripts/check_frontend_cookie_strip.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# Builds the frontend image from a Dockerfile and checks that /api and /ws do not forward the +# browser's Cookie header to the backend. Usage: scripts/check_frontend_cookie_strip.sh [Dockerfile] +set -eu + +dockerfile="${1:-Dockerfile.frontend}" +root="$(git rev-parse --show-toplevel)" +work="$(mktemp -d)" +tag="gohoarder-frontend-cookie-check:$$" +net="gohoarder-cookie-check-$$" +stub="$net-backend" +front="$net-frontend" + +cleanup() { + docker rm -f "$front" "$stub" >/dev/null 2>&1 || true + docker network rm "$net" >/dev/null 2>&1 || true + docker rmi "$tag" >/dev/null 2>&1 || true + rm -rf "$work" +} +trap cleanup EXIT + +mkdir -p "$work/frontend/dist" +echo '' >"$work/frontend/dist/index.html" +cp "$root/$dockerfile" "$work/Dockerfile" +docker build -q --load -t "$tag" "$work" >/dev/null + +cat >"$work/stub.conf" <<'CONF' +server { + listen 8080; + location / { default_type text/plain; return 200 "cookie=[$http_cookie]"; } +} +CONF + +docker network create "$net" >/dev/null +docker run -d --name "$stub" --network "$net" -v "$work/stub.conf:/etc/nginx/conf.d/default.conf:ro" nginx:alpine >/dev/null +docker run -d --name "$front" --network "$net" -e BACKEND_HOST="$stub" -e BACKEND_PORT=8080 "$tag" >/dev/null + +cookie="session=$(head -c 8000 /dev/zero | tr '\0' 'a')" +status=0 +for path in /api/packages /ws; do + ok=no + for _ in 1 2 3 4 5 6 7 8 9 10; do + body="$(docker exec "$front" wget -qO- --header "Cookie: $cookie" "http://127.0.0.1$path" 2>/dev/null || true)" + [ -n "$body" ] && ok=yes && break + sleep 1 + done + if [ "$ok" = no ]; then + echo "FAIL: $path returned no body" + status=1 + elif [ "$body" = "cookie=[]" ]; then + echo "ok: $path forwards no Cookie" + else + echo "FAIL: $path forwarded a Cookie header ($(printf '%s' "$body" | wc -c) bytes)" + status=1 + fi +done +exit "$status"