mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-25 06:35:21 +00:00
fix(server): stop 431 on /api for browsers with large session cookies
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
+5
-4
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+14
-5
@@ -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")
|
||||
}
|
||||
|
||||
Executable
+57
@@ -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 '<html></html>' >"$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"
|
||||
Reference in New Issue
Block a user