From 16da8d522f5d97facb3e700c38e7d0a9ddf4400e Mon Sep 17 00:00:00 2001 From: Aaron Brethorst Date: Sat, 14 Nov 2026 01:42:36 -0800 Subject: [PATCH 1/9] SC-28: reject trailing data after a JSON request body decodeJSONBody stopped after the first JSON value and ignored the rest, so {"a":1}{"a":2} decoded as the first object. Require the decoder to hit io.EOF after the value (whitespace is still fine) and answer 400 otherwise. --- README.md | 7 ++++ internal/httpapi/json.go | 17 ++++++++ internal/httpapi/json_test.go | 74 +++++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+) create mode 100644 internal/httpapi/json_test.go diff --git a/README.md b/README.md index 98bb407..a8c3bcd 100644 --- a/README.md +++ b/README.md @@ -637,6 +637,13 @@ compatibility shim for the old shape -- a bookmark to `/admin/alerts/42` from before this change shows the SPA's ordinary not-found page rather than redirecting. +### Admin API hardening + +- **One JSON value per body.** Every JSON body on `/api/admin/v1` (and the + gorush webhook and the donations endpoint) must be exactly one JSON value; + trailing data after it -- a second object, stray bytes -- is a `400`. + Trailing whitespace is fine. + ### Region API keys and service principals The admin API above is session-authenticated when a browser is driving it, diff --git a/internal/httpapi/json.go b/internal/httpapi/json.go index 652d50d..e3f57cc 100644 --- a/internal/httpapi/json.go +++ b/internal/httpapi/json.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "log/slog" "net/http" @@ -104,9 +105,25 @@ func decodeJSONBody(w http.ResponseWriter, r *http.Request, maxBytes int64, dst } return fmt.Errorf("invalid JSON body: %w", err) } + // A body is exactly one JSON value (SC-28). Decode stops after the first + // value and leaves the rest unread, so without this `{"a":1}{"a":2}` + // would be accepted as the first object -- a parser disagreement with + // anything in front of the sidecar that reads the last one. Trailing + // whitespace is consumed by the decoder and still ends in io.EOF. + if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + return errBodyTooLarge + } + return errTrailingJSON + } return nil } +// errTrailingJSON is the caller-safe message for a body that carries more +// than one JSON value. +var errTrailingJSON = errors.New("invalid JSON body: unexpected data after the JSON value") + // writeServerError logs op against the region id and writes a bare, empty // 500. Every {regionId} feed handler shares this one function for the same // reason they share writeRegionNotFound: three independent copies is how one diff --git a/internal/httpapi/json_test.go b/internal/httpapi/json_test.go new file mode 100644 index 0000000..2d7d6dc --- /dev/null +++ b/internal/httpapi/json_test.go @@ -0,0 +1,74 @@ +package httpapi + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// TestDecodeJSONBody_RejectsTrailingData pins SC-28: a body is exactly one +// JSON value. encoding/json's Decoder stops after the first value and leaves +// the rest unread, so `{"a":1}{"a":2}` used to decode as the first object and +// silently drop the second -- the kind of parser disagreement a proxy or WAF +// in front of the sidecar can be steered around. Trailing whitespace is still +// fine (curl and most encoders append a newline). +func TestDecodeJSONBody_RejectsTrailingData(t *testing.T) { + t.Parallel() + + type doc struct { + A int `json:"a"` + } + tests := []struct { + name string + body string + strict bool + wantErr bool + wantEOF bool + }{ + {name: "single object", body: `{"a":1}`}, + {name: "trailing newline", body: "{\"a\":1}\n"}, + {name: "trailing whitespace", body: "{\"a\":1} \r\n\t "}, + {name: "second object", body: `{"a":1}{"a":2}`, wantErr: true}, + {name: "second object strict", body: `{"a":1}{"a":2}`, strict: true, wantErr: true}, + {name: "trailing garbage", body: `{"a":1} x`, wantErr: true}, + {name: "trailing scalar", body: `{"a":1} 2`, wantErr: true}, + {name: "empty body stays io.EOF", body: ``, wantErr: true, wantEOF: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/", strings.NewReader(tt.body)) + var got doc + err := decodeJSONBody(httptest.NewRecorder(), req, 1024, &got, tt.strict) + if (err != nil) != tt.wantErr { + t.Fatalf("err = %v, wantErr %v", err, tt.wantErr) + } + if tt.wantEOF && !errors.Is(err, io.EOF) { + // The push-create handler treats io.EOF as "empty body means + // {}"; trailing-data detection must not disturb that. + t.Errorf("err = %v, want io.EOF", err) + } + if !tt.wantErr && got.A != 1 { + t.Errorf("decoded a = %d, want 1", got.A) + } + }) + } +} + +// TestLogin_TrailingJSONRejected walks SC-28 through a real route. +func TestLogin_TrailingJSONRejected(t *testing.T) { + t.Parallel() + + f := newLoginFixture(t) + rec := f.postLogin(credentials("admin", testPassword)+`{"username":"other"}`, nil) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", rec.Code, rec.Body.String()) + } + if f.repo.sessionCount() != 0 { + t.Error("a session was created from a body with trailing data") + } +} From d011ddd316d0b004fd8d650419ac12d9824a58e4 Mon Sep 17 00:00:00 2001 From: Aaron Brethorst Date: Sat, 14 Nov 2026 01:44:01 -0800 Subject: [PATCH 2/9] SC-26: cap argon2 parameters accepted from a stored hash VerifyPassword ran whatever m/t/p, salt and key length a PHC string named, so a tampered or foreign row could make one login allocate gigabytes or run for seconds. Refuse anything past 64 MiB, 10 passes, 8 lanes, a 64-byte salt or key, or a 256-byte string before deriving anything. --- README.md | 5 +++++ internal/auth/password.go | 31 +++++++++++++++++++++++++-- internal/auth/password_test.go | 38 +++++++++++++++++++++++++++++++++- 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a8c3bcd..191329f 100644 --- a/README.md +++ b/README.md @@ -643,6 +643,11 @@ redirecting. gorush webhook and the donations endpoint) must be exactly one JSON value; trailing data after it -- a second object, stray bytes -- is a `400`. Trailing whitespace is fine. +- **Bounded password-hash cost.** Verification uses the argon2id parameters + stored in each user row, so it refuses a stored hash naming more than + 64 MiB, 10 passes, or 8 lanes (or an out-of-range salt/key length) instead + of running it. The defaults (19 MiB, 2 passes, 1 lane) leave room to raise + them without a code change. ### Region API keys and service principals diff --git a/internal/auth/password.go b/internal/auth/password.go index 0667e3c..5639de3 100644 --- a/internal/auth/password.go +++ b/internal/auth/password.go @@ -22,6 +22,23 @@ const ( keyLen = 32 ) +// Verification ceilings (SC-26). VerifyPassword honours the parameters a +// stored hash names, so these bound what a tampered or foreign row can make +// one login cost. They sit well above the defaults (about 3x memory, 5x +// passes) so the defaults can still be raised without a code change; the +// salt and key minimums are RFC 9106's. +const ( + maxArgonMemoryKiB = 64 * 1024 + maxArgonTime = 10 + maxArgonThreads = 8 + minSaltLen = 8 + maxSaltLen = 64 + minKeyLen = 4 + maxKeyLen = 64 + // maxPHCLen bounds the whole string before it is split or decoded. + maxPHCLen = 256 +) + // Password length bounds (spec section 4.1). Max exists because argon2 input // length is attacker-controlled CPU cost. const ( @@ -66,6 +83,9 @@ func encodePHC(password string, salt []byte, m uint32, t uint32, p uint8) string // using the parameters stored in the hash itself. A malformed hash is an // error; a clean mismatch is (false, nil). func VerifyPassword(phc, password string) (bool, error) { + if len(phc) > maxPHCLen { + return false, errors.New("auth: malformed password hash") + } parts := strings.Split(phc, "$") // "" / "argon2id" / "v=19" / "m=..,t=..,p=.." / salt / hash if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" { @@ -80,12 +100,19 @@ func VerifyPassword(phc, password string) (bool, error) { parts[3] != fmt.Sprintf("m=%d,t=%d,p=%d", m, t, p) || t < 1 || p < 1 { return false, errors.New("auth: malformed hash parameters") } + // The row names its own cost, and verification runs it unconditionally, + // so a hash naming 4 GiB or a thousand passes is a memory/CPU bomb the + // next login attempt detonates (SC-26). Refuse anything past the ceiling + // before deriving a single byte. + if m > maxArgonMemoryKiB || t > maxArgonTime || p > maxArgonThreads { + return false, errors.New("auth: hash parameters exceed the verification ceiling") + } salt, err := base64.RawStdEncoding.DecodeString(parts[4]) - if err != nil { + if err != nil || len(salt) < minSaltLen || len(salt) > maxSaltLen { return false, errors.New("auth: malformed hash salt") } want, err := base64.RawStdEncoding.DecodeString(parts[5]) - if err != nil || len(want) == 0 { + if err != nil || len(want) < minKeyLen || len(want) > maxKeyLen { // An empty segment decodes to zero bytes; argon2 cannot derive a // zero-length key and would panic. return false, errors.New("auth: malformed hash value") diff --git a/internal/auth/password_test.go b/internal/auth/password_test.go index 287d0a5..d77239b 100644 --- a/internal/auth/password_test.go +++ b/internal/auth/password_test.go @@ -92,7 +92,7 @@ func TestVerifyRejectsZeroParams(t *testing.T) { // An empty hash segment decodes to zero bytes without error. Deriving a // zero-length key panics inside x/crypto, so it must be rejected as malformed. func TestVerifyRejectsEmptyHash(t *testing.T) { - phc := "$argon2id$v=19$m=19456,t=2,p=1$AAAA$" + phc := "$argon2id$v=19$m=19456,t=2,p=1$AAAAAAAAAAAAAAAAAAAAAA$" _, err := VerifyPassword(phc, "x") if err == nil || err.Error() != "auth: malformed hash value" { t.Errorf("VerifyPassword with empty hash segment: got %v, want malformed hash value", err) @@ -133,3 +133,39 @@ func hashWithParams(password string, m uint32, t uint32, p uint8) string { } return encodePHC(password, salt, m, t, p) } + +// TestVerifyRejectsOversizedParameters pins SC-26: VerifyPassword runs +// whatever cost the stored PHC string names, so an unbounded m/t/p (or an +// enormous salt or key) in a row is a memory/CPU bomb the next login +// detonates. Each case must be refused before any key derivation -- the m +// case would try to allocate 4 GiB if it were not. +func TestVerifyRejectsOversizedParameters(t *testing.T) { + salt := "AAAAAAAAAAAAAAAAAAAAAA" // 16 bytes + key := "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" // 32 bytes + long := strings.Repeat("A", 4096) + cases := map[string]string{ + "memory 4 GiB": "$argon2id$v=19$m=4194304,t=2,p=1$" + salt + "$" + key, + "memory > cap": "$argon2id$v=19$m=65537,t=2,p=1$" + salt + "$" + key, + "time 1000": "$argon2id$v=19$m=19456,t=1000,p=1$" + salt + "$" + key, + "threads 255": "$argon2id$v=19$m=19456,t=2,p=255$" + salt + "$" + key, + "salt 3 KiB": "$argon2id$v=19$m=19456,t=2,p=1$" + long + "$" + key, + "key 3 KiB": "$argon2id$v=19$m=19456,t=2,p=1$" + salt + "$" + long, + "short salt": "$argon2id$v=19$m=19456,t=2,p=1$AAAA$" + key, + "short key": "$argon2id$v=19$m=19456,t=2,p=1$" + salt + "$AAAA", + "whole string >": "$argon2id$v=19$m=19456,t=2,p=1$" + salt + "$" + key + long, + } + for name, phc := range cases { + t.Run(name, func(t *testing.T) { + if ok, err := VerifyPassword(phc, "whatever password"); err == nil || ok { + t.Fatalf("VerifyPassword = %v, %v; want an error", ok, err) + } + }) + } + + // The bounds must leave room above today's defaults, so raising them + // later (the reason the parameters live in the row) still verifies. + raised := hashWithParams("raised password!", 2*argonMemoryKiB, 3, 2) + if ok, err := VerifyPassword(raised, "raised password!"); err != nil || !ok { + t.Fatalf("raised-cost hash: ok=%v err=%v; want a match", ok, err) + } +} From 12e02b253178a50a41bf69645de2dcb230dc3a91 Mon Sep 17 00:00:00 2001 From: Aaron Brethorst Date: Sat, 14 Nov 2026 01:45:06 -0800 Subject: [PATCH 3/9] SC-30: restrict username charset and bound the logged username ValidateUsername now accepts only lowercase ASCII letters, digits and ._@+- (create only, so existing accounts still sign in). The failed-login Warn line logs LogSafeUsername: normalized, non-printing runes replaced, cut to 64 characters, instead of up to 8 KB of caller text. --- README.md | 5 +++ internal/auth/username.go | 52 ++++++++++++++++++++++-- internal/auth/username_test.go | 32 ++++++++++++++- internal/httpapi/login_hardening_test.go | 36 ++++++++++++++++ internal/httpapi/session.go | 2 +- internal/store/storetest/authtest.go | 3 ++ 6 files changed, 123 insertions(+), 7 deletions(-) create mode 100644 internal/httpapi/login_hardening_test.go diff --git a/README.md b/README.md index 191329f..64fd51e 100644 --- a/README.md +++ b/README.md @@ -648,6 +648,11 @@ redirecting. 64 MiB, 10 passes, or 8 lanes (or an out-of-range salt/key length) instead of running it. The defaults (19 MiB, 2 passes, 1 lane) leave room to raise them without a code change. +- **Username charset.** `sidecar-admin user create` accepts 1-64 characters + of lowercase ASCII letters, digits, and `._@+-` (input is trimmed and + lowercased first). Accounts created before this rule keep signing in; the + rule applies to new accounts only. A failed sign-in logs the attempted + username cut to 64 characters with control characters replaced. ### Region API keys and service principals diff --git a/internal/auth/username.go b/internal/auth/username.go index ec84872..024b987 100644 --- a/internal/auth/username.go +++ b/internal/auth/username.go @@ -5,25 +5,69 @@ import ( "fmt" "strings" "unicode" + "unicode/utf8" ) +// MaxUsernameLen is the longest username ValidateUsername accepts, in bytes +// (every accepted character is one byte). +const MaxUsernameLen = 64 + +// usernamePunctuation is the punctuation ValidateUsername accepts beside +// lowercase ASCII letters and digits: enough for "first.last", "ops-1" and an +// email address, nothing that means anything to a shell, a log parser, or +// HTML. +const usernamePunctuation = "._@+-" + // NormalizeUsername trims and lowercases, in Go rather than SQL collation so // SQLite and Postgres agree (spec section 3.2). func NormalizeUsername(s string) string { return strings.ToLower(strings.TrimSpace(s)) } -// ValidateUsername checks an already-normalized username: 1-64 characters, -// no whitespace. +// ValidateUsername checks an already-normalized username: 1-64 characters +// drawn from lowercase ASCII letters, digits, and "._@+-". The charset is +// deliberately narrow (SC-30): a username is echoed into logs, the CLI's +// tables, and the admin UI, so control characters, bidi overrides, and +// look-alike Unicode have no business in one. It applies on create only -- +// login looks a name up as typed, so an account created before this rule +// still signs in. func ValidateUsername(s string) error { if s == "" { return errors.New("username must not be empty") } - if len(s) > 64 { - return fmt.Errorf("username must be at most 64 characters, got %d", len(s)) + if len(s) > MaxUsernameLen { + return fmt.Errorf("username must be at most %d characters, got %d", MaxUsernameLen, len(s)) } if strings.IndexFunc(s, unicode.IsSpace) >= 0 { return errors.New("username must not contain whitespace") } + for _, r := range s { + if (r < 'a' || r > 'z') && (r < '0' || r > '9') && !strings.ContainsRune(usernamePunctuation, r) { + return fmt.Errorf("username may contain only lowercase letters, digits, and %q", usernamePunctuation) + } + } return nil } + +// LogSafeUsername is the form of a caller-supplied username that may be +// written to a log line (SC-30): normalized, every control or non-printing +// rune replaced with '?', and cut to MaxUsernameLen runes with a marker, so a +// failed login cannot write 8 KB of attacker text -- or a forged log line -- +// per request. +func LogSafeUsername(s string) string { + s = NormalizeUsername(s) + var b strings.Builder + n := 0 + for i, r := range s { + if n == MaxUsernameLen { + b.WriteString("...(truncated, " + fmt.Sprint(utf8.RuneCountInString(s[i:])) + " more)") + break + } + if r == utf8.RuneError || !unicode.IsPrint(r) { + r = '?' + } + b.WriteRune(r) + n++ + } + return b.String() +} diff --git a/internal/auth/username_test.go b/internal/auth/username_test.go index 6531325..435f2b8 100644 --- a/internal/auth/username_test.go +++ b/internal/auth/username_test.go @@ -12,14 +12,42 @@ func TestNormalizeUsername(t *testing.T) { } func TestValidateUsername(t *testing.T) { - for _, bad := range []string{"", "has space", "a\tb", strings.Repeat("x", 65)} { + for _, bad := range []string{ + "", "has space", "a\tb", strings.Repeat("x", 65), + // SC-30: control characters, bidi overrides, and anything outside + // the conservative ASCII set end up in logs and the admin UI. + "a\x00b", "a\x1b[31mb", "a\u202eb", "a\u200bb", "jos\u00e9", "a/b", "a", "a\"b", "a;b", + } { if err := ValidateUsername(NormalizeUsername(bad)); err == nil { t.Errorf("ValidateUsername(%q) should fail", bad) } } - for _, good := range []string{"admin", "a", "kaylee.frye", strings.Repeat("x", 64)} { + for _, good := range []string{ + "admin", "a", "kaylee.frye", strings.Repeat("x", 64), + "ops-1", "first_last", "ops+sidecar@example.org", "0123456789", + } { if err := ValidateUsername(NormalizeUsername(good)); err != nil { t.Errorf("ValidateUsername(%q): %v", good, err) } } } + +// TestLogSafeUsername pins the other half of SC-30: the failed-login log line +// records whatever the caller typed, up to the 8 KB body cap, so it is +// truncated and stripped of control characters before it is logged. +func TestLogSafeUsername(t *testing.T) { + long := strings.Repeat("a", 8000) + got := LogSafeUsername(long) + if len(got) > 100 { + t.Errorf("len(LogSafeUsername(8000 bytes)) = %d, want <= 100", len(got)) + } + if !strings.HasPrefix(got, strings.Repeat("a", 64)) { + t.Errorf("LogSafeUsername(long) = %q, want the first 64 characters kept", got) + } + if got := LogSafeUsername(" Admin\x1b[2J\r\nfake line "); strings.ContainsAny(got, "\x1b\r\n") { + t.Errorf("LogSafeUsername kept a control character: %q", got) + } + if got := LogSafeUsername(" Admin "); got != "admin" { + t.Errorf("LogSafeUsername(%q) = %q, want the normalized form", " Admin ", got) + } +} diff --git a/internal/httpapi/login_hardening_test.go b/internal/httpapi/login_hardening_test.go new file mode 100644 index 0000000..ca91453 --- /dev/null +++ b/internal/httpapi/login_hardening_test.go @@ -0,0 +1,36 @@ +package httpapi + +import ( + "bytes" + "log/slog" + "net/http" + "strings" + "testing" +) + +// TestLogin_FailedLoginLogTruncatesUsername pins SC-30 at the HTTP layer: +// the username in the failed-login Warn line is whatever the caller sent, up +// to the 8 KB body cap, so it must be cut down before it is logged. +func TestLogin_FailedLoginLogTruncatesUsername(t *testing.T) { + t.Parallel() + + var buf bytes.Buffer + sleeps := &sleepRecorder{} + h := newTestRouter(newStubAuth(), func(d *Deps) { + d.Logger = slog.New(slog.NewTextHandler(&buf, nil)) + d.Sleep = sleeps.sleep + }) + f := &loginFixture{handler: h} + long := strings.Repeat("a", 7000) + rec := f.postLogin(credentials(long, "wrong password!!"), nil) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want 401; body = %s", rec.Code, rec.Body.String()) + } + logged := buf.String() + if !strings.Contains(logged, "failed login") { + t.Fatalf("no failed-login line logged: %q", logged) + } + if strings.Contains(logged, strings.Repeat("a", 65)) { + t.Errorf("failed-login line carries more than 64 characters of the username (%d bytes logged)", len(logged)) + } +} diff --git a/internal/httpapi/session.go b/internal/httpapi/session.go index 03b5822..2d2dc0b 100644 --- a/internal/httpapi/session.go +++ b/internal/httpapi/session.go @@ -41,7 +41,7 @@ func (h *sessionHandler) login(w http.ResponseWriter, r *http.Request) { fail := func() { h.deps.Sleep(h.deps.FailDelay) h.deps.Logger.Warn("httpapi: failed login", - "username", auth.NormalizeUsername(req.Username), "remote", h.deps.clientIP(r)) + "username", auth.LogSafeUsername(req.Username), "remote", h.deps.clientIP(r)) writeJSONError(w, h.deps.Logger, http.StatusUnauthorized, "invalid credentials") } diff --git a/internal/store/storetest/authtest.go b/internal/store/storetest/authtest.go index a0d291e..07508f2 100644 --- a/internal/store/storetest/authtest.go +++ b/internal/store/storetest/authtest.go @@ -290,6 +290,9 @@ func testCreateRejectsInvalidUsername(t *testing.T, newRepo newAuthRepoFunc) { {"embedded space", "has space"}, {"embedded tab", "has\ttab"}, {"too long", strings.Repeat("a", 65)}, + {"control character", "ad\x00min"}, + {"escape sequence", "ad\x1b[31mmin"}, + {"non-ascii", "jos\u00e9"}, } for _, tc := range cases { if _, err := repo.CreateUser(ctx, tc.username, testPasswordHash, base); err == nil { From 2248615af2fc3d568123cd7603928db34fe6a5be Mon Sep 17 00:00:00 2001 From: Aaron Brethorst Date: Sat, 14 Nov 2026 01:45:56 -0800 Subject: [PATCH 4/9] SC-18: keep the gorush address out of push transport errors A failed request to gorush wrapped net/http's *url.Error, whose text names the full gateway URL (and the inner *net.OpError names host:port). The dispatcher stores that as last_error and the admin API returns it. Wrap transport failures in an error whose text names only the failure class (refused, timed out, ...) and that still unwraps to the cause. --- internal/push/gorush.go | 40 +++++++++++++++++++++++++++++++++++- internal/push/gorush_test.go | 37 +++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/internal/push/gorush.go b/internal/push/gorush.go index fafb972..28da5e6 100644 --- a/internal/push/gorush.go +++ b/internal/push/gorush.go @@ -11,8 +11,10 @@ import ( "errors" "fmt" "io" + "net" "net/http" "strings" + "syscall" "time" "github.com/OneBusAway/sidecar/internal/httpx" @@ -170,7 +172,7 @@ func (g *Gorush) post(ctx context.Context, batch any) ([]byte, error) { req.Header.Set("Content-Type", "application/json") resp, err := g.http.Do(req) if err != nil { - return nil, fmt.Errorf("push: gorush request: %w", err) + return nil, &transportError{err: err} } defer resp.Body.Close() // Read (rather than discard) the body so the connection is reused and @@ -237,3 +239,39 @@ func (g *Gorush) SendLiveActivity(ctx context.Context, p LiveActivityPush) error _, err := g.post(ctx, map[string]any{"notifications": []gorushLiveActivity{n}}) return err } + +// transportError is a failed request to gorush with the gateway's address +// kept out of its text (SC-18). net/http's *url.Error prints the full URL, +// and the *net.OpError inside it prints the dialled host:port; the alert +// push dispatcher stores this text as last_error and the admin API returns +// it to every region key holder, so neither may reach Error(). The cause is +// still reachable through Unwrap, so errors.Is(err, context.DeadlineExceeded) +// and friends behave exactly as before. +type transportError struct{ err error } + +func (e *transportError) Error() string { + return "push: gorush request failed: " + describeTransportFailure(e.err) +} + +func (e *transportError) Unwrap() error { return e.err } + +// describeTransportFailure names the class of a transport failure in words +// that carry no address. +func describeTransportFailure(err error) string { + var dnsErr *net.DNSError + var netErr net.Error + switch { + case errors.Is(err, context.Canceled): + return "canceled" + case errors.Is(err, context.DeadlineExceeded), errors.As(err, &netErr) && netErr.Timeout(): + return "timed out" + case errors.Is(err, syscall.ECONNREFUSED): + return "connection refused" + case errors.Is(err, syscall.ECONNRESET): + return "connection reset" + case errors.As(err, &dnsErr): + return "host lookup failed" + default: + return "transport error" + } +} diff --git a/internal/push/gorush_test.go b/internal/push/gorush_test.go index 14df8df..3355e89 100644 --- a/internal/push/gorush_test.go +++ b/internal/push/gorush_test.go @@ -3,12 +3,14 @@ package push import ( "context" "encoding/json" + "errors" "io" "net/http" "net/http/httptest" "reflect" "strings" "sync/atomic" + "syscall" "testing" "time" ) @@ -593,3 +595,38 @@ func TestGorushSendBatchErrorNeverEchoesBody(t *testing.T) { t.Errorf("error %q echoes the response body", err) } } + +// TestGorushTransportErrorOmitsURL pins SC-18: a transport failure used to +// wrap net/http's *url.Error, whose text is `Post "http://gorush.internal:8088/api/push": ...`. +// The dispatcher stores that text as the push's last_error and the admin API +// returns it, so every region key holder learned the deployment's internal +// gateway address. The error must keep its cause (errors.Is still works) and +// drop the URL. +func TestGorushTransportErrorOmitsURL(t *testing.T) { + // A listener that is closed before the request: connection refused. + server := httptest.NewServer(http.NotFoundHandler()) + base := server.URL + server.Close() + + g := NewGorush(base+"/secret-path-segment", "com.example.app", http.DefaultClient) + n := Notification{Tokens: []string{"tok1"}, Platform: PlatformAndroid, Title: "T", Message: "M"} + + _, batchErr := g.SendBatch(context.Background(), n, "alert-push-1") + sendErr := g.Send(context.Background(), n) + laErr := g.SendLiveActivity(context.Background(), LiveActivityPush{ + Token: "tok1", Event: "update", Timestamp: time.Unix(1700000000, 0), ContentState: map[string]any{}, + }) + host := strings.TrimPrefix(base, "http://") + for name, err := range map[string]error{"SendBatch": batchErr, "Send": sendErr, "SendLiveActivity": laErr} { + if err == nil { + t.Fatalf("%s against a closed port returned nil", name) + } + msg := err.Error() + if strings.Contains(msg, host) || strings.Contains(msg, "secret-path-segment") || strings.Contains(msg, "/api/push") { + t.Errorf("%s error leaks the gateway URL: %q", name, msg) + } + if !errors.Is(err, syscall.ECONNREFUSED) || !strings.Contains(msg, "connection refused") { + t.Errorf("%s error lost its cause: %q", name, msg) + } + } +} From b08d876a930f9e9be8f95c938b9708ba44c2e15a Mon Sep 17 00:00:00 2001 From: Aaron Brethorst Date: Sat, 14 Nov 2026 01:52:56 -0800 Subject: [PATCH 5/9] SC-02: throttle failed admin logins and bound concurrent argon2 work POST /api/admin/v1/session had no rate limit, and every attempt (unknown users included) ran a 19 MiB argon2id derivation. Failed logins are now charged to per-address (10/15min) and per-username (20/15min) budgets; a spent budget is a 429 with Retry-After decided before any hashing and identical for real and unknown accounts. The username budget only refuses addresses that have themselves failed, so hammering a username cannot lock its operator out. Verifications run under a process-wide semaphore (2 slots, 10s queue, then 503). ratelimit gains read-only Count/Exhausted probes for charge-on-failure use; bearer auth keeps its own bucket. --- README.md | 23 ++ internal/httpapi/login_hardening_test.go | 334 +++++++++++++++++++++++ internal/httpapi/router.go | 17 ++ internal/httpapi/session.go | 121 +++++++- internal/ratelimit/ratelimit.go | 21 ++ internal/ratelimit/ratelimit_test.go | 32 +++ 6 files changed, 541 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 64fd51e..99a643b 100644 --- a/README.md +++ b/README.md @@ -639,6 +639,29 @@ redirecting. ### Admin API hardening +- **Sign-in throttling.** `POST /api/admin/v1/session` charges every + *failed* sign-in to two fixed 15-minute budgets: 10 per client address + (the same address the other per-IP throttles use; see `SIDECAR_TRUSTED_PROXY` + under Deployment) and 20 per username (normalized, so `Admin` and `admin` + share one). A spent budget answers `429` with a `Retry-After` header and + the SPA shows "too many failed sign-in attempts; try again later" -- + decided before any password hashing, and identically for real and unknown + usernames. Successful sign-ins are never charged. Password verification + itself runs at most 2 at a time process-wide (each argon2id derivation + holds ~19 MiB); a sign-in that waits more than 10 seconds for a slot gets + `503`. Bearer-key authentication is unaffected: it keeps its own + failure-only bucket (60/minute per address). + + The per-username budget is a throttle, not a lockout, by design. Once it + is spent, only addresses that have themselves failed in the window are + refused; an address with a clean record still gets its attempt checked. + So someone hammering an operator's username from many addresses cannot + keep that operator out -- the operator signs in from any address that has + not been guessing -- and the price is that an attacker gets one guess per + fresh address per window once the username budget is spent (each failure + marks that address). An operator who shares a NAT address with the + attacker, or who mistypes during an attack, waits out the 15-minute + window. - **One JSON value per body.** Every JSON body on `/api/admin/v1` (and the gorush webhook and the donations endpoint) must be exactly one JSON value; trailing data after it -- a second object, stray bytes -- is a `400`. diff --git a/internal/httpapi/login_hardening_test.go b/internal/httpapi/login_hardening_test.go index ca91453..aed3699 100644 --- a/internal/httpapi/login_hardening_test.go +++ b/internal/httpapi/login_hardening_test.go @@ -2,10 +2,18 @@ package httpapi import ( "bytes" + "context" "log/slog" "net/http" + "net/http/httptest" + "runtime" + "strconv" "strings" + "sync" "testing" + "time" + + "github.com/OneBusAway/sidecar/internal/ratelimit" ) // TestLogin_FailedLoginLogTruncatesUsername pins SC-30 at the HTTP layer: @@ -34,3 +42,329 @@ func TestLogin_FailedLoginLogTruncatesUsername(t *testing.T) { t.Errorf("failed-login line carries more than 64 characters of the username (%d bytes logged)", len(logged)) } } + +// testIPHeader lets a login test choose the client address per request; the +// fixtures below install a ClientIP resolver that reads it. +const testIPHeader = "X-Test-Client-Ip" + +func fromIP(ip string) func(*http.Request) { + return func(r *http.Request) { r.Header.Set(testIPHeader, ip) } +} + +// newThrottleFixture is newLoginFixture with the login throttles and the +// client-address resolver under the test's control. +func newThrottleFixture(t *testing.T, mutate func(*Deps)) *loginFixture { + t.Helper() + repo := newStubAuth() + sleeps := &sleepRecorder{} + verifies := &verifyRecorder{} + h := newTestRouter(repo, func(d *Deps) { + d.FailDelay = testFailDelay + d.Sleep = sleeps.sleep + d.VerifyPassword = verifies.verify + d.ClientIP = func(r *http.Request) string { return r.Header.Get(testIPHeader) } + if mutate != nil { + mutate(d) + } + }) + f := &loginFixture{handler: h, repo: repo, sleeps: sleeps, verifies: verifies} + f.user = repo.addUser("admin", testHash()) + return f +} + +const wrongPassword = "definitely-not-it" + +// assertThrottled checks the SC-02 contract for a refused attempt: 429, no +// password verification, no failure delay, no session. +func assertThrottled(t *testing.T, label string, f *loginFixture, rec *httptest.ResponseRecorder, verifiesBefore, sleepsBefore int) { + t.Helper() + if rec.Code != http.StatusTooManyRequests { + t.Fatalf("%s: status = %d, want 429; body = %s", label, rec.Code, rec.Body.String()) + } + if got := len(f.verifies.recorded()); got != verifiesBefore { + t.Errorf("%s: VerifyPassword ran (%d -> %d calls); a throttled attempt must be refused before hashing", label, verifiesBefore, got) + } + if got := len(f.sleeps.durations()); got != sleepsBefore { + t.Errorf("%s: failure delay applied to a throttled attempt; it would pin a goroutine per flood request", label) + } + if rec.Header().Get("Retry-After") == "" { + t.Errorf("%s: no Retry-After on a 429", label) + } + if got := bodyText(rec); !strings.Contains(got, `"error"`) { + t.Errorf("%s: body = %q, want the {\"error\": ...} shape the SPA displays", label, got) + } +} + +// TestLogin_ThrottlesFailuresPerIP: SC-02's per-address brake. Only failures +// are charged, and the attempt after the budget is spent is refused BEFORE +// any argon2 work -- even when it carries the right password. +func TestLogin_ThrottlesFailuresPerIP(t *testing.T) { + t.Parallel() + + f := newThrottleFixture(t, func(d *Deps) { + d.LoginIPLimiter = ratelimit.New(3, 15*time.Minute) + d.LoginUserLimiter = ratelimit.New(1000, 15*time.Minute) + }) + for i := range 3 { + if rec := f.postLogin(credentials("admin", wrongPassword), fromIP("198.51.100.1")); rec.Code != http.StatusUnauthorized { + t.Fatalf("failure %d: status = %d, want 401", i+1, rec.Code) + } + } + v, s := len(f.verifies.recorded()), len(f.sleeps.durations()) + rec := f.postLogin(credentials("admin", testPassword), fromIP("198.51.100.1")) + assertThrottled(t, "4th attempt from the same address", f, rec, v, s) + if f.repo.sessionCount() != 0 { + t.Error("a throttled attempt created a session") + } + + // Unknown usernames are throttled identically, so the 429 is no oracle. + rec = f.postLogin(credentials("nobody-here", wrongPassword), fromIP("198.51.100.1")) + assertThrottled(t, "unknown user from the throttled address", f, rec, v, s) + + // Another address has its own budget. + if rec := f.postLogin(credentials("admin", testPassword), fromIP("198.51.100.2")); rec.Code != http.StatusOK { + t.Fatalf("other address: status = %d, want 200", rec.Code) + } +} + +// TestLogin_SuccessIsNotCharged: a working operator signing in repeatedly +// spends nothing. +func TestLogin_SuccessIsNotCharged(t *testing.T) { + t.Parallel() + + f := newThrottleFixture(t, func(d *Deps) { + d.LoginIPLimiter = ratelimit.New(1, 15*time.Minute) + d.LoginUserLimiter = ratelimit.New(1, 15*time.Minute) + }) + for i := range 5 { + if rec := f.postLogin(credentials("admin", testPassword), fromIP("198.51.100.1")); rec.Code != http.StatusOK { + t.Fatalf("login %d: status = %d, want 200", i+1, rec.Code) + } + } +} + +// TestLogin_ThrottlesFailuresPerUsername: the distributed-guessing brake, +// and the property that keeps it from becoming a lockout weapon. Once a +// username's failure budget is spent, an address that has itself failed is +// refused before hashing -- but an address with a clean record still gets +// its attempt verified, so a legitimate operator is never locked out by +// someone else hammering their username. Each such clean address gets one +// guess per window, after which its own failure marks it. +func TestLogin_ThrottlesFailuresPerUsername(t *testing.T) { + t.Parallel() + + f := newThrottleFixture(t, func(d *Deps) { + d.LoginIPLimiter = ratelimit.New(1000, 15*time.Minute) + d.LoginUserLimiter = ratelimit.New(3, 15*time.Minute) + }) + for _, ip := range []string{"203.0.113.1", "203.0.113.2", "203.0.113.3"} { + if rec := f.postLogin(credentials("admin", wrongPassword), fromIP(ip)); rec.Code != http.StatusUnauthorized { + t.Fatalf("failure from %s: status = %d, want 401", ip, rec.Code) + } + } + + v, s := len(f.verifies.recorded()), len(f.sleeps.durations()) + rec := f.postLogin(credentials("admin", testPassword), fromIP("203.0.113.1")) + assertThrottled(t, "an address that already failed, username exhausted", f, rec, v, s) + + // The username key is the normalized form: case and padding do not + // mint a fresh bucket. + rec = f.postLogin(credentials(" ADMIN ", wrongPassword), fromIP("203.0.113.2")) + assertThrottled(t, "same username, different spelling", f, rec, v, s) + + // The operator, from an address that has not failed, still signs in. + if got := f.postLogin(credentials("admin", testPassword), fromIP("192.0.2.50")); got.Code != http.StatusOK { + t.Fatalf("operator from a clean address: status = %d, want 200 (no lockout)", got.Code) + } + + // A clean attacker address gets exactly one verified guess. + if got := f.postLogin(credentials("admin", wrongPassword), fromIP("192.0.2.66")); got.Code != http.StatusUnauthorized { + t.Fatalf("first guess from a clean address: status = %d, want 401", got.Code) + } + v, s = len(f.verifies.recorded()), len(f.sleeps.durations()) + rec = f.postLogin(credentials("admin", wrongPassword), fromIP("192.0.2.66")) + assertThrottled(t, "second guess from that address", f, rec, v, s) + + // Another username is unaffected. + f.repo.addUser("second", testHash()) + if rec := f.postLogin(credentials("second", testPassword), fromIP("203.0.113.1")); rec.Code != http.StatusOK { + t.Fatalf("another username: status = %d, want 200", rec.Code) + } +} + +// TestLogin_DefaultThrottle pins NewRouter's default per-address budget, so +// a deployment that wires nothing still has the brake. +func TestLogin_DefaultThrottle(t *testing.T) { + t.Parallel() + + f := newThrottleFixture(t, nil) + for i := range loginFailuresPerIP { + if rec := f.postLogin(credentials("admin", wrongPassword), fromIP("198.51.100.9")); rec.Code != http.StatusUnauthorized { + t.Fatalf("failure %d: status = %d, want 401", i+1, rec.Code) + } + } + v, s := len(f.verifies.recorded()), len(f.sleeps.durations()) + rec := f.postLogin(credentials("admin", wrongPassword), fromIP("198.51.100.9")) + assertThrottled(t, "default budget spent", f, rec, v, s) +} + +// blockingVerifier is a VerifyPassword stand-in that parks every call until +// released, recording the peak number in flight. +type blockingVerifier struct { + mu sync.Mutex + inFlight int + peak int + calls int + entered chan struct{} + release chan struct{} + once sync.Once +} + +// unblock releases every parked and future call; safe to call twice, so a +// test can both release explicitly and register it as a cleanup that keeps a +// failing assertion from hanging the suite. +func (b *blockingVerifier) unblock() { b.once.Do(func() { close(b.release) }) } + +func newBlockingVerifier() *blockingVerifier { + return &blockingVerifier{entered: make(chan struct{}, 64), release: make(chan struct{})} +} + +func (b *blockingVerifier) verify(phc, password string) (bool, error) { + b.mu.Lock() + b.inFlight++ + b.calls++ + if b.inFlight > b.peak { + b.peak = b.inFlight + } + b.mu.Unlock() + b.entered <- struct{}{} + <-b.release + b.mu.Lock() + b.inFlight-- + b.mu.Unlock() + return false, nil +} + +func (b *blockingVerifier) snapshot() (inFlight, peak, calls int) { + b.mu.Lock() + defer b.mu.Unlock() + return b.inFlight, b.peak, b.calls +} + +// TestLogin_VerificationConcurrencyBounded: SC-02's global semaphore. Each +// argon2id verification costs ~19 MiB, so N concurrent logins from N +// addresses (which no per-address limit sees) must still never run more +// than K derivations at once. +func TestLogin_VerificationConcurrencyBounded(t *testing.T) { + t.Parallel() + + const slots, logins = 2, 6 + bv := newBlockingVerifier() + t.Cleanup(bv.unblock) + f := newThrottleFixture(t, func(d *Deps) { + d.LoginVerifySlots = slots + d.LoginVerifyWait = time.Minute + d.VerifyPassword = bv.verify + }) + + var wg sync.WaitGroup + codes := make(chan int, logins) + for i := range logins { + wg.Add(1) + go func() { + defer wg.Done() + ip := "198.51.100." + strconv.Itoa(10+i) + codes <- f.postLogin(credentials("admin", wrongPassword), fromIP(ip)).Code + }() + } + for range slots { + <-bv.entered + } + // The slots are full; give the other goroutines every chance to + // (wrongly) start a derivation before checking. + for range 20 { + runtime.Gosched() + time.Sleep(time.Millisecond) + } + if inFlight, _, _ := bv.snapshot(); inFlight != slots { + t.Fatalf("in flight = %d with %d slots full", inFlight, slots) + } + bv.unblock() + wg.Wait() + close(codes) + for c := range codes { + if c != http.StatusUnauthorized { + t.Errorf("queued login status = %d, want 401 (queued, not dropped)", c) + } + } + if _, peak, calls := bv.snapshot(); peak > slots || calls != logins { + t.Errorf("peak concurrent verifications = %d (calls %d), want <= %d (calls %d)", peak, calls, slots, logins) + } +} + +// TestLogin_VerificationQueueTimeout: a login that cannot get a verification +// slot in time is a 503, not an unbounded wait, and never hashes. +func TestLogin_VerificationQueueTimeout(t *testing.T) { + t.Parallel() + + bv := newBlockingVerifier() + t.Cleanup(bv.unblock) + f := newThrottleFixture(t, func(d *Deps) { + d.LoginVerifySlots = 1 + d.LoginVerifyWait = 20 * time.Millisecond + d.VerifyPassword = bv.verify + }) + done := make(chan struct{}) + go func() { + defer close(done) + f.postLogin(credentials("admin", wrongPassword), fromIP("198.51.100.1")) + }() + <-bv.entered + + // Without a semaphore this second login would park in the verifier; + // release it after a beat so the failure is an assertion, not a hang. + go func() { + time.Sleep(2 * time.Second) + bv.unblock() + }() + rec := f.postLogin(credentials("admin", testPassword), fromIP("198.51.100.2")) + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503; body = %s", rec.Code, rec.Body.String()) + } + if _, _, calls := bv.snapshot(); calls != 1 { + t.Errorf("verifications = %d, want 1 (the queued login must not hash)", calls) + } + bv.unblock() + <-done +} + +// TestLogin_ThrottleLeavesBearerAuthAlone: the login buckets are their own. +// An address that has exhausted its sign-in budget still authenticates by +// region key, and a bad bearer key from it is still the bearer path's 401. +func TestLogin_ThrottleLeavesBearerAuthAlone(t *testing.T) { + t.Parallel() + + f := newAdminFixtureWithDeps(t, func(d *Deps) { + d.LoginIPLimiter = ratelimit.New(1, 15*time.Minute) + d.Sleep = func(time.Duration) {} + }) + key := f.mintRegionKey(t, regionTampa) + login := func() int { + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, + "/api/admin/v1/session", strings.NewReader(credentials("admin", wrongPassword))) + req.Host = "sidecar.test" + rec := httptest.NewRecorder() + f.handler.ServeHTTP(rec, req) + return rec.Code + } + login() + if code := login(); code != http.StatusTooManyRequests { + t.Fatalf("second failed login = %d, want 429", code) + } + if rec := sendBearer(f.handler, http.MethodGet, "/api/admin/v1/regions/0/alerts", "", "Bearer "+key); rec.Code != http.StatusOK { + t.Errorf("valid region key after login throttle: status = %d, want 200", rec.Code) + } + if rec := sendBearer(f.handler, http.MethodGet, "/api/admin/v1/regions/0/alerts", "", "Bearer obask_0_nope"); rec.Code != http.StatusUnauthorized { + t.Errorf("bad region key after login throttle: status = %d, want 401", rec.Code) + } +} diff --git a/internal/httpapi/router.go b/internal/httpapi/router.go index 4296ff2..20eb50f 100644 --- a/internal/httpapi/router.go +++ b/internal/httpapi/router.go @@ -161,6 +161,22 @@ type Deps struct { // the response -- only a recorder can prove it still happens. VerifyPassword func(phc, password string) (bool, error) + // LoginIPLimiter and LoginUserLimiter bound FAILED admin logins per + // client address and per normalized username (SC-02). A spent budget is + // a 429 before any argon2 work. NewRouter defaults both; successful + // logins are never charged. See sessionHandler.throttled for how the + // username bucket avoids becoming a lockout weapon. + LoginIPLimiter *ratelimit.Limiter + LoginUserLimiter *ratelimit.Limiter + // LoginVerifySlots caps concurrent password verifications process-wide + // (each argon2id derivation holds ~19 MiB); LoginVerifyWait is how long + // a login queues for a slot before answering 503. NewRouter defaults + // both. + LoginVerifySlots int + LoginVerifyWait time.Duration + // loginSlots is the semaphore NewRouter builds from LoginVerifySlots. + loginSlots chan struct{} + // AdminUI is the built admin SPA, served under /admin. Nil means the // binary was built without it and those routes are not registered. AdminUI fs.FS @@ -398,6 +414,7 @@ func NewRouter(deps Deps) http.Handler { if deps.BearerFailLimiter == nil { deps.BearerFailLimiter = ratelimit.New(bearerFailuresPerMinute, time.Minute) } + applyLoginDefaults(&deps) // The alert push routes count the audience before they enqueue // (design spec §2.9); Alerts, Regions and Now are already guaranteed // above, so the registry is the one thing left that would nil-deref diff --git a/internal/httpapi/session.go b/internal/httpapi/session.go index 2d2dc0b..eb490fc 100644 --- a/internal/httpapi/session.go +++ b/internal/httpapi/session.go @@ -1,11 +1,14 @@ package httpapi import ( + "context" "errors" "net/http" + "strconv" "time" "github.com/OneBusAway/sidecar/internal/auth" + "github.com/OneBusAway/sidecar/internal/ratelimit" ) // maxAuthBody caps the request body on the auth endpoints at 8 KB. Credentials @@ -31,6 +34,13 @@ type loginRequest struct { // password changed while it was being verified -- returns the same status and // the same bytes after the same argon2 cost and the same fixed delay, so the // endpoint cannot be used to discover which accounts exist (design spec §4.3). +// +// Failures are also charged to a per-address and a per-username budget, and +// a spent budget is a 429 before anything is hashed (SC-02); the 429 is +// decided on the address and the typed username alone, so it is identical +// for real and unknown accounts. Verifications themselves run under a +// process-wide semaphore, so a flood from many addresses cannot run more +// than LoginVerifySlots argon2 derivations at once. func (h *sessionHandler) login(w http.ResponseWriter, r *http.Request) { var req loginRequest if err := decodeJSON(w, r, maxAuthBody, &req); err != nil { @@ -38,20 +48,40 @@ func (h *sessionHandler) login(w http.ResponseWriter, r *http.Request) { return } + ip, userKey := h.deps.clientIP(r), loginUserKey(req.Username) + if h.throttled(ip, userKey) { + h.deps.Logger.Debug("httpapi: login throttled", "remote", ip) + w.Header().Set("Retry-After", strconv.Itoa(int(loginFailureWindow/time.Second))) + writeJSONError(w, h.deps.Logger, http.StatusTooManyRequests, "too many failed sign-in attempts; try again later") + return + } + fail := func() { + // Charged before the delay, so a burst of concurrent guesses is + // counted as soon as each one is known to have failed. + h.deps.LoginIPLimiter.Allow(ip, h.deps.Now()) + h.deps.LoginUserLimiter.Allow(userKey, h.deps.Now()) h.deps.Sleep(h.deps.FailDelay) h.deps.Logger.Warn("httpapi: failed login", - "username", auth.LogSafeUsername(req.Username), "remote", h.deps.clientIP(r)) + "username", auth.LogSafeUsername(req.Username), "remote", ip) writeJSONError(w, h.deps.Logger, http.StatusUnauthorized, "invalid credentials") } ctx := r.Context() user, err := h.deps.Auth.GetUserByUsername(ctx, req.Username) - if err != nil { - if !errors.Is(err, auth.ErrNotFound) { - serverErrorJSON(w, h.deps.Logger, "get user", err) - return - } + if err != nil && !errors.Is(err, auth.ErrNotFound) { + serverErrorJSON(w, h.deps.Logger, "get user", err) + return + } + known := err == nil + + release, ok := h.acquireVerifySlot(ctx) + if !ok { + h.deps.Logger.Warn("httpapi: login verification queue full", "remote", ip) + writeJSONError(w, h.deps.Logger, http.StatusServiceUnavailable, "sign-in is busy; try again shortly") + return + } + if !known { // Burn the same argon2 cost as a real verification so response timing // does not reveal which usernames exist (design spec §4.3). This runs // through the injected Deps.VerifyPassword purely so a test can prove @@ -63,11 +93,13 @@ func (h *sessionHandler) login(w http.ResponseWriter, r *http.Request) { // something invalid, which silently removes the timing defence. h.deps.Logger.Error("httpapi: dummy password hash is unusable", "err", dummyErr) } + release() fail() return } - ok, err := h.deps.VerifyPassword(user.PasswordHash, req.Password) + ok, err = h.deps.VerifyPassword(user.PasswordHash, req.Password) + release() if err != nil { serverErrorJSON(w, h.deps.Logger, "verify password", err) return @@ -167,3 +199,78 @@ func sessionCookie(r *http.Request, value string, maxAge int) *http.Cookie { Secure: r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https", } } + +// throttled reports whether a login from ip for userKey must be refused +// before hashing (SC-02). +// +// The address budget is a plain brake: an address that has spent it waits +// out the window. The username budget is what stops a guesser spreading one +// account's attempts across many addresses -- but applied the same way it +// would let anyone lock the operator out of their own account, forever, by +// hammering the username. So it is a throttle, not a lockout: once a +// username's budget is spent, only addresses that have themselves failed +// recently are refused. An address with a clean record still has its attempt +// verified, which is one guess per clean address per window for an attacker +// (each failure marks the address) and no lockout for an operator signing in +// from somewhere that has not been guessing. The trade-off is documented in +// the README (Admin API hardening). +func (h *sessionHandler) throttled(ip, userKey string) bool { + now := h.deps.Now() + if h.deps.LoginIPLimiter.Exhausted(ip, now) { + return true + } + return h.deps.LoginUserLimiter.Exhausted(userKey, now) && h.deps.LoginIPLimiter.Count(ip, now) > 0 +} + +// acquireVerifySlot takes one of the LoginVerifySlots verification slots, +// waiting at most LoginVerifyWait (or until the client goes away). It +// returns the release function and true, or false when no slot came free. +func (h *sessionHandler) acquireVerifySlot(ctx context.Context) (func(), bool) { + ctx, cancel := context.WithTimeout(ctx, h.deps.LoginVerifyWait) + defer cancel() + select { + case h.deps.loginSlots <- struct{}{}: + return func() { <-h.deps.loginSlots }, true + case <-ctx.Done(): + return nil, false + } +} + +// loginUserKey is the per-username bucket key: the normalized form, so case +// and padding cannot mint fresh buckets, cut to the longest valid username +// so an 8 KB "username" cannot become an 8 KB map key. (Every name longer +// than that is invalid, so the cut only ever merges invalid names.) +func loginUserKey(username string) string { + u := auth.NormalizeUsername(username) + if len(u) > auth.MaxUsernameLen { + u = u[:auth.MaxUsernameLen] + } + return u +} + +// applyLoginDefaults fills the SC-02 throttle and semaphore settings a +// caller left zero, and builds the semaphore. +func applyLoginDefaults(d *Deps) { + if d.LoginIPLimiter == nil { + d.LoginIPLimiter = ratelimit.New(loginFailuresPerIP, loginFailureWindow) + } + if d.LoginUserLimiter == nil { + d.LoginUserLimiter = ratelimit.New(loginFailuresPerUser, loginFailureWindow) + } + if d.LoginVerifySlots <= 0 { + d.LoginVerifySlots = loginVerifySlots + } + if d.LoginVerifyWait <= 0 { + d.LoginVerifyWait = loginVerifyWait + } + d.loginSlots = make(chan struct{}, d.LoginVerifySlots) +} + +// Login throttle defaults (SC-02). Fixed windows, charged on failure only. +const ( + loginFailuresPerIP = 10 + loginFailuresPerUser = 20 + loginFailureWindow = 15 * time.Minute + loginVerifySlots = 2 + loginVerifyWait = 10 * time.Second +) diff --git a/internal/ratelimit/ratelimit.go b/internal/ratelimit/ratelimit.go index 9cea5b8..d2ec6ad 100644 --- a/internal/ratelimit/ratelimit.go +++ b/internal/ratelimit/ratelimit.go @@ -64,6 +64,27 @@ func (l *Limiter) Allow(key string, now time.Time) bool { return true } +// Count reports how many admissions key has spent in its current window at +// now, without counting anything. Zero for an unseen key or an expired +// window. +func (l *Limiter) Count(key string, now time.Time) int { + l.mu.Lock() + defer l.mu.Unlock() + b := l.buckets[key] + if b == nil || now.Sub(b.start) >= l.window { + return 0 + } + return b.count +} + +// Exhausted reports whether Allow would deny key at now, without counting +// anything. It is the check half of a charge-on-failure throttle (the admin +// login, SC-02): refuse up front when the budget is spent, and call Allow +// only once the expensive operation has actually failed. +func (l *Limiter) Exhausted(key string, now time.Time) bool { + return l.Count(key, now) >= l.limit +} + // Len reports the number of live buckets; test-only observability. func (l *Limiter) Len() int { l.mu.Lock() diff --git a/internal/ratelimit/ratelimit_test.go b/internal/ratelimit/ratelimit_test.go index d287474..a4a144c 100644 --- a/internal/ratelimit/ratelimit_test.go +++ b/internal/ratelimit/ratelimit_test.go @@ -46,3 +46,35 @@ func TestSweepBoundsMemory(t *testing.T) { t.Fatalf("Len() = %d after sweep; want <= 1", got) } } + +// TestCountAndExhaustedDoNotCharge pins the read-only probes the login +// throttle uses (SC-02): it must decide "refuse before hashing" without +// spending budget, and charge only once a verification has actually failed. +func TestCountAndExhaustedDoNotCharge(t *testing.T) { + t.Parallel() + l := ratelimit.New(2, time.Minute) + + if got := l.Count("k", base); got != 0 { + t.Fatalf("Count on an unseen key = %d, want 0", got) + } + for range 5 { + if l.Exhausted("k", base) { + t.Fatal("Exhausted on an unseen key; probing must not charge") + } + } + l.Allow("k", base) + if got := l.Count("k", base); got != 1 { + t.Fatalf("Count after one Allow = %d, want 1", got) + } + l.Allow("k", base) + if !l.Exhausted("k", base.Add(30*time.Second)) { + t.Fatal("Exhausted = false at the limit") + } + // The window rolls over exactly as Allow sees it. + if l.Exhausted("k", base.Add(time.Minute)) || l.Count("k", base.Add(time.Minute)) != 0 { + t.Fatal("an expired window still reads as charged") + } + if !l.Allow("k", base.Add(time.Minute)) { + t.Fatal("Allow denied in a fresh window") + } +} From 3997719f11b14e4c70c3973b7e18cc6bc5b16f5b Mon Sep 17 00:00:00 2001 From: Aaron Brethorst Date: Sat, 14 Nov 2026 02:00:00 -0800 Subject: [PATCH 6/9] SC-25: idle timeout, shorter lifetime, __Host- cookie, session CLI Admin sessions lasted 30 days with no idle timeout, the cookie was never prefixed, and operators had no way to see or revoke sessions short of a password change. Sessions now end 24h after sign-in (checked against created_at on every request, so existing longer sessions end too) and after 2h unused; activity slides expires_at, written at most once per 1/20 of the idle window. Both are configurable (--admin-session-lifetime, --admin-session-idle-timeout). Over HTTPS the cookie is __Host-sidecar_session and only that name authenticates (one forced re-login); plain HTTP keeps sidecar_session. New repository methods ExtendSession and ListSessions back sidecar-admin user sessions and user revoke --session/--username. --- .env.example | 6 + README.md | 31 +++ cmd/sidecar-admin/users.go | 125 ++++++++++- cmd/sidecar-admin/users_test.go | 72 ++++++ cmd/sidecar/main.go | 29 +++ cmd/sidecar/main_test.go | 46 ++++ internal/auth/auth.go | 26 ++- internal/httpapi/middleware.go | 51 ++++- internal/httpapi/middleware_test.go | 33 ++- internal/httpapi/router.go | 6 + internal/httpapi/session.go | 64 +++++- internal/httpapi/session_lifetime_test.go | 246 +++++++++++++++++++++ internal/httpapi/session_test.go | 21 +- internal/store/sqlite/auth.go | 25 +++ internal/store/sqlite/gen/sessions.sql.go | 50 +++++ internal/store/sqlite/queries/sessions.sql | 7 + internal/store/storetest/authtest.go | 60 +++++ 17 files changed, 874 insertions(+), 24 deletions(-) create mode 100644 internal/httpapi/session_lifetime_test.go diff --git a/.env.example b/.env.example index 2ff0ef0..e3b65db 100644 --- a/.env.example +++ b/.env.example @@ -32,6 +32,12 @@ SIDECAR_TRUSTED_PROXY= SIDECAR_TRUSTED_PROXY_SECRET= SIDECAR_TRUSTED_PROXY_CIDRS= +# Admin UI sessions: absolute lifetime from sign-in, and how long an unused +# session survives. Go durations; the idle timeout must not exceed the +# lifetime. Defaults shown. +#SIDECAR_ADMIN_SESSION_LIFETIME=24h +#SIDECAR_ADMIN_SESSION_IDLE_TIMEOUT=2h + # --- gorush / APNs ----------------------------------------------------------- # Defaults to true in compose.yaml; set to false to run without an Apple key. # With iOS enabled and no key, gorush exits at startup and `make up` fails diff --git a/README.md b/README.md index 99a643b..3f9abe8 100644 --- a/README.md +++ b/README.md @@ -662,6 +662,37 @@ redirecting. marks that address). An operator who shares a NAT address with the attacker, or who mistypes during an attack, waits out the 15-minute window. +- **Session lifetime.** An admin UI session ends 24 hours after sign-in + however busy it is (`--admin-session-lifetime` / + `SIDECAR_ADMIN_SESSION_LIFETIME`), and earlier if it goes unused for 2 + hours (`--admin-session-idle-timeout` / + `SIDECAR_ADMIN_SESSION_IDLE_TIMEOUT`, at most the lifetime). Activity + slides the idle deadline, written at most once per twentieth of the idle + window. The lifetime is checked against each session's sign-in time on + every request, so lowering it -- or upgrading from the old 30-day, + no-idle-timeout sessions -- ends existing sessions that are already older. +- **`__Host-` cookie over HTTPS.** Over HTTPS (direct TLS or + `X-Forwarded-Proto: https` from the proxy) the session cookie is + `__Host-sidecar_session`: always `Secure`, `Path=/`, no `Domain`, so a + sibling subdomain or a plain-HTTP response cannot plant or overwrite it. + Plain-HTTP development keeps `sidecar_session` (browsers reject a + non-`Secure` `__Host-` cookie). Over HTTPS only the prefixed name + authenticates -- accepting the old name there would reopen the hole the + prefix closes -- so **every operator signs in once more after upgrading**; + the old cookie is cleared on that sign-in. +- **Listing and revoking sessions.** `sidecar-admin user sessions + [--username NAME]` lists live sessions (a 12-character id -- a prefix of + the token's SHA-256, never the token -- the username, sign-in time, and + current idle deadline). `sidecar-admin user revoke --session ID` ends one + (at least 8 characters, matching exactly one session); `user revoke + --username NAME` ends all of one account's. `user passwd` and `user + delete` already revoke an account's sessions. +- **Bearer keys do not expire.** Region keys (`obask_`) and service + principals (`obasp_`) are valid until revoked; OBACloud rotates region + keys itself. Treat the `obasp_` principal as deployment-root in practice: + it can mint a push-scoped key for any region (see below), so store it + like a root credential and revoke it (`sidecar-admin principal revoke`) + if it may have leaked. - **One JSON value per body.** Every JSON body on `/api/admin/v1` (and the gorush webhook and the donations endpoint) must be exactly one JSON value; trailing data after it -- a second object, stray bytes -- is a `400`. diff --git a/cmd/sidecar-admin/users.go b/cmd/sidecar-admin/users.go index e463e4e..1a48785 100644 --- a/cmd/sidecar-admin/users.go +++ b/cmd/sidecar-admin/users.go @@ -26,7 +26,7 @@ import ( // so `user create` is what makes the admin UI reachable at all. func runUser(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer, store *sqlite.Store, now time.Time, args []string) error { if len(args) == 0 { - return errors.New("user requires a subcommand: create, passwd, list, delete") + return errors.New("user requires a subcommand: create, passwd, list, delete, sessions, revoke") } cmd, cmdArgs := args[0], args[1:] switch cmd { @@ -38,8 +38,12 @@ func runUser(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer, sto return userList(ctx, stdout, store, cmdArgs) case "delete": return userDelete(ctx, stdout, store, cmdArgs) + case "sessions": + return userSessions(ctx, stdout, store, now, cmdArgs) + case "revoke": + return userRevoke(ctx, stdout, store, now, cmdArgs) default: - return fmt.Errorf("unknown user subcommand %q; expected create, passwd, list, or delete", cmd) + return fmt.Errorf("unknown user subcommand %q; expected create, passwd, list, delete, sessions, or revoke", cmd) } } @@ -242,3 +246,120 @@ func userDelete(ctx context.Context, stdout io.Writer, store *sqlite.Store, args fmt.Fprintf(stdout, "deleted user %s\n", normalized) return nil } + +// sessionIDLen is how much of a session's token hash `user sessions` shows +// and `user revoke --session` matches on; minSessionIDLen is the shortest +// prefix revoke accepts. The hash is SHA-256 of the cookie token, so even +// the whole value grants nothing -- the prefix is just shorter to type. +const ( + sessionIDLen = 12 + minSessionIDLen = 8 +) + +// userSessions prints one line per live admin session (SC-25): id, a tab, +// username, created-at, and the current idle deadline, all RFC 3339 UTC. +func userSessions(ctx context.Context, stdout io.Writer, store *sqlite.Store, now time.Time, args []string) error { + fs := flag.NewFlagSet("user sessions", flag.ContinueOnError) + fs.SetOutput(io.Discard) + username := fs.String("username", "", "only this account's sessions") + if err := fs.Parse(args); err != nil { + return err + } + sessions, names, err := liveSessions(ctx, store, now) + if err != nil { + return fmt.Errorf("user sessions: %w", err) + } + filter := auth.NormalizeUsername(*username) + for _, s := range sessions { + if filter != "" && names[s.UserID] != filter { + continue + } + fmt.Fprintf(stdout, "%s\t%s\t%s\t%s\n", s.TokenHash[:sessionIDLen], names[s.UserID], + s.CreatedAt.UTC().Format(time.RFC3339), s.ExpiresAt.UTC().Format(time.RFC3339)) + } + return nil +} + +// userRevoke ends one session (--session ) or every session of one +// account (--username). Exactly one selector is required; an id must be at +// least minSessionIDLen characters and match exactly one live session. +func userRevoke(ctx context.Context, stdout io.Writer, store *sqlite.Store, now time.Time, args []string) error { + fs := flag.NewFlagSet("user revoke", flag.ContinueOnError) + fs.SetOutput(io.Discard) + id := fs.String("session", "", "id (token-hash prefix) from `user sessions`") + username := fs.String("username", "", "revoke every session of this account") + if err := fs.Parse(args); err != nil { + return err + } + if (*id == "") == (*username == "") { + return errors.New("user revoke requires exactly one of --session or --username") + } + if *username != "" { + normalized := auth.NormalizeUsername(*username) + user, err := store.Auth().GetUserByUsername(ctx, normalized) + if err != nil { + if errors.Is(err, auth.ErrNotFound) { + return fmt.Errorf("user revoke: user %q not found", normalized) + } + return fmt.Errorf("user revoke: %w", err) + } + n, err := store.Auth().DeleteUserSessions(ctx, user.ID) + if err != nil { + return fmt.Errorf("user revoke: %w", err) + } + fmt.Fprintf(stdout, "revoked %d session(s) for %s\n", n, normalized) + return nil + } + + prefix := strings.ToLower(*id) + if len(prefix) < minSessionIDLen { + return fmt.Errorf("user revoke: --session needs at least %d characters of the id", minSessionIDLen) + } + sessions, _, err := liveSessions(ctx, store, now) + if err != nil { + return fmt.Errorf("user revoke: %w", err) + } + var match []auth.Session + for _, s := range sessions { + if strings.HasPrefix(s.TokenHash, prefix) { + match = append(match, s) + } + } + switch len(match) { + case 0: + return fmt.Errorf("user revoke: no live session with id %q", prefix) + case 1: + default: + return fmt.Errorf("user revoke: id %q matches %d sessions; give more characters", prefix, len(match)) + } + if err := store.Auth().DeleteSession(ctx, match[0].TokenHash); err != nil { + return fmt.Errorf("user revoke: %w", err) + } + fmt.Fprintf(stdout, "revoked session %s\n", match[0].TokenHash[:sessionIDLen]) + return nil +} + +// liveSessions returns the sessions still live at now (an expired row awaits +// the next sign-in's sweep and is not worth showing) and a user-id to +// username map. +func liveSessions(ctx context.Context, store *sqlite.Store, now time.Time) ([]auth.Session, map[int64]string, error) { + all, err := store.Auth().ListSessions(ctx) + if err != nil { + return nil, nil, err + } + users, err := store.Auth().ListUsers(ctx) + if err != nil { + return nil, nil, err + } + names := make(map[int64]string, len(users)) + for _, u := range users { + names[u.ID] = u.Username + } + live := all[:0] + for _, s := range all { + if s.ExpiresAt.After(now) { + live = append(live, s) + } + } + return live, names, nil +} diff --git a/cmd/sidecar-admin/users_test.go b/cmd/sidecar-admin/users_test.go index 19897b1..0b5b50c 100644 --- a/cmd/sidecar-admin/users_test.go +++ b/cmd/sidecar-admin/users_test.go @@ -410,3 +410,75 @@ func TestUserDelete_UnknownUserRejected(t *testing.T) { t.Fatal("user delete of an unknown username: want error, got nil (silent success is never acceptable here)") } } + +// TestUserSessions_ListsAndRevokes pins SC-25's operator tooling: `user +// sessions` lists live admin sessions by a short id (a token-hash prefix, +// never the token), and `user revoke` ends one session by that id or every +// session of one account. +func TestUserSessions_ListsAndRevokes(t *testing.T) { + t.Parallel() + dbPath, store := newDB(t) + ctx := context.Background() + aliceHash, now := createUserWithSession(t, dbPath, store, "alice", "alice-token-1") + bobHash, _ := createUserWithSession(t, dbPath, store, "bob", "bob-token-1") + bob, err := store.Auth().GetUserByUsername(ctx, "bob") + if err != nil { + t.Fatal(err) + } + bob2 := auth.HashToken("bob-token-2") + if err = store.Auth().CreateSession(ctx, bob2, bob.ID, bob.PasswordHash, now, now.Add(time.Hour)); err != nil { + t.Fatal(err) + } + + stdout, _, err := cli(t, dbPath, "user", "sessions") + if err != nil { + t.Fatalf("user sessions: %v", err) + } + lines := strings.Split(strings.TrimRight(stdout, "\n"), "\n") + if len(lines) != 3 { + t.Fatalf("user sessions printed %d lines, want 3: %q", len(lines), stdout) + } + if !strings.Contains(stdout, aliceHash[:12]) || strings.Contains(stdout, aliceHash) { + t.Errorf("user sessions should show a 12-char id, not the full hash: %q", stdout) + } + if strings.Contains(stdout, "alice-token-1") { + t.Error("user sessions printed a raw token") + } + + filtered, _, err := cli(t, dbPath, "user", "sessions", "--username", "bob") + if err != nil { + t.Fatalf("user sessions --username: %v", err) + } + if n := strings.Count(filtered, "\tbob\t"); n != 2 || strings.Contains(filtered, "alice") { + t.Errorf("user sessions --username bob = %q, want bob's two sessions only", filtered) + } + + if _, _, err = cli(t, dbPath, "user", "revoke", "--session", aliceHash[:12]); err != nil { + t.Fatalf("user revoke --session: %v", err) + } + if _, gerr := store.Auth().GetSession(ctx, aliceHash, now); !errors.Is(gerr, auth.ErrNotFound) { + t.Errorf("alice's session after revoke = %v, want ErrNotFound", gerr) + } + + if _, _, err = cli(t, dbPath, "user", "revoke", "--username", "bob"); err != nil { + t.Fatalf("user revoke --username: %v", err) + } + for _, h := range []string{bobHash, bob2} { + if _, gerr := store.Auth().GetSession(ctx, h, now); !errors.Is(gerr, auth.ErrNotFound) { + t.Errorf("bob's session after revoke --username = %v, want ErrNotFound", gerr) + } + } + + // Refusals: a too-short or unknown id, and neither/both selectors. + for _, args := range [][]string{ + {"user", "revoke", "--session", "abc"}, + {"user", "revoke", "--session", "ffffffffffff"}, + {"user", "revoke"}, + {"user", "revoke", "--session", aliceHash[:12], "--username", "bob"}, + {"user", "revoke", "--username", "nobody"}, + } { + if _, _, rerr := cli(t, dbPath, args...); rerr == nil { + t.Errorf("%v succeeded, want an error", args) + } + } +} diff --git a/cmd/sidecar/main.go b/cmd/sidecar/main.go index 4e246ed..7891466 100644 --- a/cmd/sidecar/main.go +++ b/cmd/sidecar/main.go @@ -27,6 +27,7 @@ import ( "github.com/OneBusAway/sidecar/internal/alarms" "github.com/OneBusAway/sidecar/internal/alertpush" + "github.com/OneBusAway/sidecar/internal/auth" "github.com/OneBusAway/sidecar/internal/cache" "github.com/OneBusAway/sidecar/internal/clientip" "github.com/OneBusAway/sidecar/internal/donations" @@ -165,6 +166,10 @@ func run(stdout, stderr io.Writer, args []string) (err error) { "id of the live Stripe product recurring donations bill against (prod_...)") stripeTestProduct := fs.String("stripe-test-recurring-product-id", envOrDefault("SIDECAR_STRIPE_TEST_RECURRING_PRODUCT_ID", ""), "id of the test-mode Stripe product recurring donations bill against") + sessionLifetime := fs.String("admin-session-lifetime", envOrDefault("SIDECAR_ADMIN_SESSION_LIFETIME", auth.SessionLifetime.String()), + "absolute lifetime of an admin UI session from sign-in; activity never extends it") + sessionIdle := fs.String("admin-session-idle-timeout", envOrDefault("SIDECAR_ADMIN_SESSION_IDLE_TIMEOUT", auth.SessionIdleTimeout.String()), + "an admin UI session unused for this long expires; must not exceed --admin-session-lifetime") apnsTopic := fs.String("apns-topic", envOrDefault("SIDECAR_APNS_TOPIC", ""), "APNs topic (the iOS app's bundle id) stamped on every iOS push; required for pushes to be accepted under .p8 token auth") @@ -195,6 +200,11 @@ func run(stdout, stderr io.Writer, args []string) (err error) { return errors.New("--gorush-webhook-secret/SIDECAR_GORUSH_WEBHOOK_SECRET must not contain ':' or whitespace (gorush splits its header setting on ':')") } + sessionTTL, sessionIdleTTL, err := parseSessionDurations(*sessionLifetime, *sessionIdle) + if err != nil { + return err + } + // --refresh=0 is a natural way to try to disable directory sync, and // --refresh=nonsense is already rejected by fs.Parse above; a // non-positive value that parses cleanly must be rejected here at boot @@ -343,6 +353,7 @@ func run(stdout, stderr io.Writer, args []string) (err error) { // constructing a second one. deps := buildDeps(store, logger, *obaAPIKey, *pirateKey, *webhookSecret, waker) deps.ClientIP = resolveClientIP + deps.SessionLifetime, deps.SessionIdleTimeout = sessionTTL, sessionIdleTTL deps.Donations, err = newDonations(logger, *stripeKey, *stripeTestKey, *stripeProduct, *stripeTestProduct) if err != nil { return err @@ -501,6 +512,24 @@ func serve(ctx context.Context, server *http.Server, logger *slog.Logger) error } } +// parseSessionDurations validates the two admin session settings (SC-25): +// both positive, and the idle timeout no longer than the lifetime (a longer +// one could never fire, so it is almost certainly the two values swapped). +func parseSessionDurations(lifetime, idle string) (time.Duration, time.Duration, error) { + l, err := time.ParseDuration(lifetime) + if err != nil || l <= 0 { + return 0, 0, fmt.Errorf("--admin-session-lifetime/SIDECAR_ADMIN_SESSION_LIFETIME must be a positive duration, got %q", lifetime) + } + i, err := time.ParseDuration(idle) + if err != nil || i <= 0 { + return 0, 0, fmt.Errorf("--admin-session-idle-timeout/SIDECAR_ADMIN_SESSION_IDLE_TIMEOUT must be a positive duration, got %q", idle) + } + if i > l { + return 0, 0, fmt.Errorf("--admin-session-idle-timeout (%s) must not exceed --admin-session-lifetime (%s)", i, l) + } + return l, i, nil +} + // envOrDefault returns the value of the environment variable key, or def if // key is unset or empty. // defaultListenAddr resolves the --addr default from the environment: diff --git a/cmd/sidecar/main_test.go b/cmd/sidecar/main_test.go index c09f49a..012de40 100644 --- a/cmd/sidecar/main_test.go +++ b/cmd/sidecar/main_test.go @@ -88,6 +88,26 @@ func TestRun_ArgHandling(t *testing.T) { wantErr: true, wantStdoutLen: 0, }, + { + name: "non-positive admin session lifetime returns an error", + args: []string{"--admin-session-lifetime=0"}, + wantErr: true, + wantStdoutLen: 0, + }, + { + name: "unparseable admin session idle timeout returns an error", + args: []string{"--admin-session-idle-timeout=soon"}, + wantErr: true, + wantStdoutLen: 0, + }, + { + // An idle timeout longer than the lifetime can never fire; it is + // almost certainly the two values swapped. + name: "idle timeout longer than the session lifetime returns an error", + args: []string{"--admin-session-lifetime=1h", "--admin-session-idle-timeout=2h"}, + wantErr: true, + wantStdoutLen: 0, + }, { name: "unknown flag returns an error and writes nothing to stdout", args: []string{"--bogus-flag"}, @@ -564,3 +584,29 @@ func TestNewDonations(t *testing.T) { t.Fatalf("both keys: %+v ids=%q,%q", svc, first, second) } } + +// TestRun_AdminSessionFlags pins SC-25's two session settings: they exist, +// and a bad value is rejected at boot by name (not as an unknown flag). +func TestRun_AdminSessionFlags(t *testing.T) { + t.Parallel() + + var stdout, stderr bytes.Buffer + if err := run(&stdout, &stderr, []string{"--help"}); err != nil { + t.Fatalf("--help: %v", err) + } + for _, flag := range []string{"admin-session-lifetime", "admin-session-idle-timeout"} { + if !strings.Contains(stdout.String(), flag) { + t.Errorf("--help does not list --%s", flag) + } + } + for _, args := range [][]string{ + {"--admin-session-lifetime=0"}, + {"--admin-session-idle-timeout=soon"}, + {"--admin-session-lifetime=1h", "--admin-session-idle-timeout=2h"}, + } { + err := run(&bytes.Buffer{}, &bytes.Buffer{}, args) + if err == nil || !strings.Contains(err.Error(), "admin-session") { + t.Errorf("run(%v) = %v, want an error naming the admin session setting", args, err) + } + } +} diff --git a/internal/auth/auth.go b/internal/auth/auth.go index f8c86c4..56a8299 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -10,12 +10,23 @@ import ( "time" ) -// CookieName is the session cookie the HTTP layer sets and reads. +// CookieName is the session cookie the HTTP layer sets and reads on plain +// HTTP (local development). const CookieName = "sidecar_session" -// SessionLifetime is the absolute session duration; there is no sliding -// renewal (spec section 4.2). -const SessionLifetime = 30 * 24 * time.Hour +// SecureCookieName is the session cookie over HTTPS (SC-25). The __Host- +// prefix makes the browser refuse it unless it is Secure, Path=/ and carries +// no Domain, so a sibling subdomain or a plain-HTTP response cannot plant or +// overwrite it (session fixation by cookie tossing). +const SecureCookieName = "__Host-" + CookieName + +// SessionLifetime is the default absolute session duration, measured from +// login; activity never extends a session past it (SC-25). +const SessionLifetime = 24 * time.Hour + +// SessionIdleTimeout is the default idle timeout: a session unused for this +// long expires, however much of its absolute lifetime remains (SC-25). +const SessionIdleTimeout = 2 * time.Hour // ErrNotFound is returned when a user or session lookup finds no live row. var ErrNotFound = errors.New("user or session not found") @@ -94,4 +105,11 @@ type Repository interface { // does not need it: UpdatePassword revokes the sessions itself. DeleteUserSessions(ctx context.Context, userID int64) (int64, error) DeleteExpiredSessions(ctx context.Context, now time.Time) (int64, error) + // ExtendSession sets a session's expires_at, forward or back; it is the + // write behind the idle timeout (SC-25). created_at never moves. An + // unknown token is ErrNotFound. + ExtendSession(ctx context.Context, tokenHash string, expiresAt time.Time) error + // ListSessions returns every stored session, oldest first (then by + // token hash), expired rows included until something reaps them. + ListSessions(ctx context.Context) ([]Session, error) } diff --git a/internal/httpapi/middleware.go b/internal/httpapi/middleware.go index e51b683..f7e4d5c 100644 --- a/internal/httpapi/middleware.go +++ b/internal/httpapi/middleware.go @@ -1,11 +1,13 @@ package httpapi import ( + "cmp" "context" "errors" "log/slog" "net/http" "net/url" + "time" "github.com/OneBusAway/sidecar/internal/auth" ) @@ -114,14 +116,16 @@ func (h *authMiddleware) requirePrincipal(allowed principalSet, next http.Handle // GetSession's contract folds expiry into ErrNotFound (and deletes the row on // the way), so there is nothing here to distinguish. func (h *authMiddleware) authenticateSession(w http.ResponseWriter, r *http.Request) (principal, bool) { - cookie, err := r.Cookie(auth.CookieName) + cookie, err := r.Cookie(sessionCookieName(r)) if err != nil { h.unauthorized(w, "no session cookie") return principal{}, false } ctx := r.Context() - session, err := h.deps.Auth.GetSession(ctx, auth.HashToken(cookie.Value), h.deps.Now()) + now := h.deps.Now() + tokenHash := auth.HashToken(cookie.Value) + session, err := h.deps.Auth.GetSession(ctx, tokenHash, now) if err != nil { if !errors.Is(err, auth.ErrNotFound) { // A broken store is not a logged-out user. Saying 401 here @@ -133,6 +137,9 @@ func (h *authMiddleware) authenticateSession(w http.ResponseWriter, r *http.Requ h.unauthorized(w, "no live session for cookie") return principal{}, false } + if !h.liveAndSlid(r, w, session, now) { + return principal{}, false + } user, err := h.deps.Auth.GetUserByID(ctx, session.UserID) if err != nil { @@ -156,3 +163,43 @@ func (h *authMiddleware) unauthorized(w http.ResponseWriter, reason string) { h.deps.Logger.Debug("httpapi: authentication required", "reason", reason) writeJSONError(w, h.deps.Logger, http.StatusUnauthorized, "authentication required") } + +// liveAndSlid applies SC-25's two clocks to a session GetSession reported +// live. The absolute lifetime is measured from created_at here, at request +// time, rather than trusted from expires_at, so lowering +// --admin-session-lifetime also ends sessions minted under a longer one. The +// idle timeout lives in expires_at, which this slides forward to now+idle +// (capped at the absolute deadline). The write is skipped unless it would +// move the deadline by more than a twentieth of the idle window -- or pull +// it in, which a row minted under longer settings needs once -- so a burst +// of requests costs one UPDATE, not one each. A failed slide is logged and +// the request proceeds: the session is live right now, and the worst case +// is that it idles out up to one granule early. +// +// It writes the 401 itself and reports false when the session is past its +// absolute lifetime. +func (h *authMiddleware) liveAndSlid(r *http.Request, w http.ResponseWriter, s auth.Session, now time.Time) bool { + ctx := r.Context() + // Zero means a hand-built middleware (tests); NewRouter always sets both. + lifetime := cmp.Or(h.deps.SessionLifetime, auth.SessionLifetime) + idle := cmp.Or(h.deps.SessionIdleTimeout, auth.SessionIdleTimeout) + hardDeadline := s.CreatedAt.Add(lifetime) + if !now.Before(hardDeadline) { + if err := h.deps.Auth.DeleteSession(ctx, s.TokenHash); err != nil && !errors.Is(err, auth.ErrNotFound) { + h.deps.Logger.Warn("httpapi: delete session past its lifetime", "err", err) + } + h.unauthorized(w, "session past its absolute lifetime") + return false + } + next := now.Add(idle) + if next.After(hardDeadline) { + next = hardDeadline + } + granule := max(idle/20, time.Second) + if next.Sub(s.ExpiresAt) >= granule || next.Before(s.ExpiresAt) { + if err := h.deps.Auth.ExtendSession(ctx, s.TokenHash, next); err != nil { + h.deps.Logger.Warn("httpapi: slide session idle deadline", "err", err) + } + } + return true +} diff --git a/internal/httpapi/middleware_test.go b/internal/httpapi/middleware_test.go index 499db31..94f358b 100644 --- a/internal/httpapi/middleware_test.go +++ b/internal/httpapi/middleware_test.go @@ -43,7 +43,8 @@ type stubAuth struct { deleteSessionErr error // Call counters. - gcCalls int + gcCalls int + extendCalls int } func newStubAuth() *stubAuth { @@ -646,3 +647,33 @@ func TestPrincipalFrom_NoPrincipal(t *testing.T) { t.Errorf("principalFrom(background).kind = %v, want the zero kind", p.kind) } } + +func (s *stubAuth) ExtendSession(_ context.Context, tokenHash string, expiresAt time.Time) error { + s.mu.Lock() + defer s.mu.Unlock() + sess, ok := s.sessions[tokenHash] + if !ok { + return auth.ErrNotFound + } + sess.ExpiresAt = expiresAt + s.sessions[tokenHash] = sess + s.extendCalls++ + return nil +} + +func (s *stubAuth) ListSessions(context.Context) ([]auth.Session, error) { + return nil, errStubUnused +} + +func (s *stubAuth) extendCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.extendCalls +} + +func (s *stubAuth) session(tokenHash string) (auth.Session, bool) { + s.mu.Lock() + defer s.mu.Unlock() + sess, ok := s.sessions[tokenHash] + return sess, ok +} diff --git a/internal/httpapi/router.go b/internal/httpapi/router.go index 20eb50f..e3fb33a 100644 --- a/internal/httpapi/router.go +++ b/internal/httpapi/router.go @@ -177,6 +177,12 @@ type Deps struct { // loginSlots is the semaphore NewRouter builds from LoginVerifySlots. loginSlots chan struct{} + // SessionLifetime is the absolute admin session lifetime from login and + // SessionIdleTimeout the idle timeout (SC-25). NewRouter defaults them to + // auth.SessionLifetime and auth.SessionIdleTimeout. + SessionLifetime time.Duration + SessionIdleTimeout time.Duration + // AdminUI is the built admin SPA, served under /admin. Nil means the // binary was built without it and those routes are not registered. AdminUI fs.FS diff --git a/internal/httpapi/session.go b/internal/httpapi/session.go index eb490fc..b0c0ee1 100644 --- a/internal/httpapi/session.go +++ b/internal/httpapi/session.go @@ -115,7 +115,10 @@ func (h *sessionHandler) login(w http.ResponseWriter, r *http.Request) { return } now := h.deps.Now() - if err := h.deps.Auth.CreateSession(ctx, tokenHash, user.ID, user.PasswordHash, now, now.Add(auth.SessionLifetime)); err != nil { + // The row's expires_at is the idle deadline (never past the absolute + // one); every authenticated request slides it (SC-25). + expiresAt := now.Add(min(h.deps.SessionIdleTimeout, h.deps.SessionLifetime)) + if err := h.deps.Auth.CreateSession(ctx, tokenHash, user.ID, user.PasswordHash, now, expiresAt); err != nil { if errors.Is(err, auth.ErrPasswordChanged) || errors.Is(err, auth.ErrNotFound) { // `user passwd` or `user delete` committed while this login was // verifying, so the password it checked no longer opens the @@ -134,16 +137,29 @@ func (h *sessionHandler) login(w http.ResponseWriter, r *http.Request) { h.deps.Logger.Warn("httpapi: sweep expired sessions", "err", err) } - http.SetCookie(w, sessionCookie(r, token, int(auth.SessionLifetime/time.Second))) + http.SetCookie(w, sessionCookie(r, sessionCookieName(r), token, int(h.deps.SessionLifetime/time.Second))) + if isHTTPS(r) { + // Retire a pre-SC-25 unprefixed cookie so the browser stops sending + // a credential nothing reads any more. + http.SetCookie(w, sessionCookie(r, auth.CookieName, "", -1)) + } writeJSON(w, h.deps.Logger, http.StatusOK, map[string]string{"username": user.Username}) } // logout handles DELETE /api/admin/v1/session. It is idempotent: logging out // without a live session is a success, because the SPA calls it to tidy up // after a 401. +// +// Both cookie names are honoured here, unlike in authentication: revoking +// the session a presented token names is exactly what its holder is asking +// for, whichever name it arrived under, and both are cleared. func (h *sessionHandler) logout(w http.ResponseWriter, r *http.Request) { - if cookie, err := r.Cookie(auth.CookieName); err == nil { - err := h.deps.Auth.DeleteSession(r.Context(), auth.HashToken(cookie.Value)) + for _, name := range []string{auth.SecureCookieName, auth.CookieName} { + cookie, err := r.Cookie(name) + if err != nil { + continue + } + err = h.deps.Auth.DeleteSession(r.Context(), auth.HashToken(cookie.Value)) if err != nil && !errors.Is(err, auth.ErrNotFound) { // The row is still there, so the token is still live. Clearing // the cookie now would take away the only handle the operator has @@ -153,7 +169,10 @@ func (h *sessionHandler) logout(w http.ResponseWriter, r *http.Request) { } } - http.SetCookie(w, sessionCookie(r, "", -1)) + http.SetCookie(w, sessionCookie(r, sessionCookieName(r), "", -1)) + if isHTTPS(r) { + http.SetCookie(w, sessionCookie(r, auth.CookieName, "", -1)) + } w.WriteHeader(http.StatusNoContent) } @@ -188,18 +207,37 @@ func (h *sessionHandler) whoami(w http.ResponseWriter, r *http.Request) { // terminated at a reverse proxy that says so with X-Forwarded-Proto -- because // a Secure cookie on a plain-HTTP development server is one the browser will // accept and then never send back. -func sessionCookie(r *http.Request, value string, maxAge int) *http.Cookie { +func sessionCookie(r *http.Request, name, value string, maxAge int) *http.Cookie { return &http.Cookie{ - Name: auth.CookieName, + Name: name, Value: value, Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: maxAge, - Secure: r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https", + Secure: isHTTPS(r), } } +// isHTTPS reports whether r arrived over TLS, directly or through a +// terminating proxy that says so (the README's Deployment section covers +// trusting X-Forwarded-Proto). +func isHTTPS(r *http.Request) bool { + return r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" +} + +// sessionCookieName is the one cookie name that sets and authenticates a +// session on r's scheme: __Host- prefixed over HTTPS, plain over HTTP +// (browsers refuse a __Host- cookie that is not Secure). Authentication +// reads only this name, never the other, so an unprefixed cookie planted on +// an HTTPS deployment is ignored (SC-25). +func sessionCookieName(r *http.Request) string { + if isHTTPS(r) { + return auth.SecureCookieName + } + return auth.CookieName +} + // throttled reports whether a login from ip for userKey must be refused // before hashing (SC-02). // @@ -248,9 +286,15 @@ func loginUserKey(username string) string { return u } -// applyLoginDefaults fills the SC-02 throttle and semaphore settings a -// caller left zero, and builds the semaphore. +// applyLoginDefaults fills the SC-02 throttle and semaphore settings and +// the SC-25 session lifetimes a caller left zero, and builds the semaphore. func applyLoginDefaults(d *Deps) { + if d.SessionLifetime <= 0 { + d.SessionLifetime = auth.SessionLifetime + } + if d.SessionIdleTimeout <= 0 { + d.SessionIdleTimeout = auth.SessionIdleTimeout + } if d.LoginIPLimiter == nil { d.LoginIPLimiter = ratelimit.New(loginFailuresPerIP, loginFailureWindow) } diff --git a/internal/httpapi/session_lifetime_test.go b/internal/httpapi/session_lifetime_test.go new file mode 100644 index 0000000..b8864ec --- /dev/null +++ b/internal/httpapi/session_lifetime_test.go @@ -0,0 +1,246 @@ +package httpapi + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/OneBusAway/sidecar/internal/auth" +) + +// testClock is a settable Deps.Now for the session-lifetime tests. +type testClock struct { + mu sync.Mutex + t time.Time +} + +func (c *testClock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *testClock) set(t time.Time) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = t +} + +func newSessionClockFixture(t *testing.T, lifetime, idle time.Duration) (*loginFixture, *testClock) { + t.Helper() + clock := &testClock{t: testNow} + repo := newStubAuth() + h := newTestRouter(repo, func(d *Deps) { + d.Now = clock.now + d.Sleep = func(time.Duration) {} + d.SessionLifetime = lifetime + d.SessionIdleTimeout = idle + }) + f := &loginFixture{handler: h, repo: repo, sleeps: &sleepRecorder{}, verifies: &verifyRecorder{}} + f.user = repo.addUser("admin", testHash()) + return f, clock +} + +func viaHTTPS(r *http.Request) { r.Header.Set("X-Forwarded-Proto", "https") } + +// whoamiAt sends GET /session with the cookie at the clock's instant. +func (f *loginFixture) whoamiWith(cookie *http.Cookie, mutate func(*http.Request)) int { + req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/admin/v1/session", nil) + req.Host = "sidecar.test" + if mutate != nil { + mutate(req) + } + if cookie != nil { + req.AddCookie(&http.Cookie{Name: cookie.Name, Value: cookie.Value}) + } + rec := httptest.NewRecorder() + f.handler.ServeHTTP(rec, req) + return rec.Code +} + +// TestSession_IdleTimeout pins SC-25's idle timeout: a session used within +// the idle window keeps sliding forward; one left alone for longer than it +// dies, long before its absolute lifetime. +func TestSession_IdleTimeout(t *testing.T) { + t.Parallel() + + f, clock := newSessionClockFixture(t, 24*time.Hour, 2*time.Hour) + c := f.login(t) + + clock.set(testNow.Add(2*time.Hour - time.Minute)) + if code := f.whoamiWith(c, nil); code != http.StatusOK { + t.Fatalf("inside the first idle window: status = %d, want 200", code) + } + // Past the ORIGINAL idle deadline: alive only because the last request + // slid it. + clock.set(testNow.Add(3*time.Hour + 50*time.Minute)) + if code := f.whoamiWith(c, nil); code != http.StatusOK { + t.Fatalf("after activity slid the deadline: status = %d, want 200", code) + } + clock.set(testNow.Add(3*time.Hour + 50*time.Minute + 2*time.Hour + time.Second)) + if code := f.whoamiWith(c, nil); code != http.StatusUnauthorized { + t.Fatalf("idle for longer than the timeout: status = %d, want 401", code) + } +} + +// TestSession_AbsoluteLifetime: activity cannot keep a session alive past +// its absolute lifetime, and the lifetime is measured from created_at at +// request time -- so lowering it also ends sessions minted under a longer +// one (the 30-day sessions that predate SC-25). +func TestSession_AbsoluteLifetime(t *testing.T) { + t.Parallel() + + f, clock := newSessionClockFixture(t, 4*time.Hour, 2*time.Hour) + c := f.login(t) + for h := 1; h < 4; h++ { + clock.set(testNow.Add(time.Duration(h) * time.Hour)) + if code := f.whoamiWith(c, nil); code != http.StatusOK { + t.Fatalf("active at +%dh: status = %d, want 200", h, code) + } + } + clock.set(testNow.Add(4 * time.Hour)) + if code := f.whoamiWith(c, nil); code != http.StatusUnauthorized { + t.Fatalf("at the absolute lifetime: status = %d, want 401", code) + } + if n := f.repo.sessionCount(); n != 0 { + t.Errorf("sessions after absolute expiry = %d, want 0 (the row must be deleted)", n) + } + + // A pre-SC-25 row: minted 25 hours ago with a 30-day expiry. + f2, _ := newSessionClockFixture(t, auth.SessionLifetime, auth.SessionIdleTimeout) + token, hash, err := auth.NewToken() + if err != nil { + t.Fatal(err) + } + f2.repo.mu.Lock() + f2.repo.sessions[hash] = auth.Session{TokenHash: hash, UserID: f2.user.ID, + CreatedAt: testNow.Add(-25 * time.Hour), ExpiresAt: testNow.Add(29 * 24 * time.Hour)} + f2.repo.mu.Unlock() + if code := f2.whoamiWith(&http.Cookie{Name: auth.CookieName, Value: token}, nil); code != http.StatusUnauthorized { + t.Errorf("legacy 30-day session older than the default lifetime: status = %d, want 401", code) + } +} + +// TestSession_SlidingIsThrottled: the idle timeout must not put an UPDATE in +// front of every admin request. +func TestSession_SlidingIsThrottled(t *testing.T) { + t.Parallel() + + f, clock := newSessionClockFixture(t, 24*time.Hour, 2*time.Hour) + c := f.login(t) + for i := range 5 { + clock.set(testNow.Add(time.Duration(i) * time.Second)) + if code := f.whoamiWith(c, nil); code != http.StatusOK { + t.Fatalf("request %d: status = %d", i, code) + } + } + if n := f.repo.extendCount(); n != 0 { + t.Errorf("ExtendSession calls for five requests within seconds of login = %d, want 0", n) + } + clock.set(testNow.Add(time.Hour)) + f.whoamiWith(c, nil) + if n := f.repo.extendCount(); n != 1 { + t.Errorf("ExtendSession calls an hour later = %d, want 1", n) + } + sess, ok := f.repo.session(auth.HashToken(c.Value)) + if !ok || !sess.ExpiresAt.Equal(testNow.Add(3*time.Hour)) { + t.Errorf("expires_at after sliding = %v, want %v", sess.ExpiresAt, testNow.Add(3*time.Hour)) + } +} + +// findSetCookie returns the named cookie from a response, or nil. +func findSetCookie(rec *httptest.ResponseRecorder, name string) *http.Cookie { + for _, c := range rec.Result().Cookies() { + if c.Name == name { + return c + } + } + return nil +} + +// TestLogin_HostPrefixedCookieOverHTTPS pins SC-25's cookie hardening: over +// HTTPS the session cookie is __Host- prefixed (Secure, Path=/, no Domain -- +// so a sibling subdomain cannot plant or overwrite it), and the legacy +// unprefixed cookie is cleared. Plain-HTTP development keeps the plain name, +// since browsers reject a __Host- cookie that is not Secure. +func TestLogin_HostPrefixedCookieOverHTTPS(t *testing.T) { + t.Parallel() + + f, _ := newSessionClockFixture(t, 24*time.Hour, 2*time.Hour) + rec := f.postLogin(credentials("admin", testPassword), viaHTTPS) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d; body = %s", rec.Code, rec.Body.String()) + } + c := findSetCookie(rec, auth.SecureCookieName) + if c == nil { + t.Fatalf("no %s cookie; Set-Cookie = %v", auth.SecureCookieName, rec.Header().Values("Set-Cookie")) + } + if !strings.HasPrefix(auth.SecureCookieName, "__Host-") { + t.Errorf("SecureCookieName = %q, want the __Host- prefix", auth.SecureCookieName) + } + if !c.Secure || c.Path != "/" || c.Domain != "" || !c.HttpOnly || c.Value == "" { + t.Errorf("__Host- cookie = %+v, want Secure, HttpOnly, Path=/, no Domain", c) + } + if c.MaxAge != int((24 * time.Hour).Seconds()) { + t.Errorf("Max-Age = %d, want the absolute lifetime (%d)", c.MaxAge, int((24 * time.Hour).Seconds())) + } + if legacy := findSetCookie(rec, auth.CookieName); legacy == nil || legacy.MaxAge >= 0 { + t.Errorf("legacy %s cookie not cleared over HTTPS: %+v", auth.CookieName, legacy) + } + + plain := f.postLogin(credentials("admin", testPassword), nil) + if findSetCookie(plain, auth.SecureCookieName) != nil { + t.Error("a __Host- cookie was set over plain HTTP; browsers reject it and the operator could never sign in") + } + if pc := findSetCookie(plain, auth.CookieName); pc == nil || pc.Value == "" || pc.Secure { + t.Errorf("plain-HTTP login cookie = %+v, want %s, not Secure", pc, auth.CookieName) + } +} + +// TestSession_CookieNameFollowsScheme: over HTTPS only the __Host- cookie +// authenticates -- accepting the unprefixed name there would hand back the +// cookie-tossing hole the prefix closes, so pre-SC-25 HTTPS sessions sign in +// again once (documented in the README) -- and over HTTP only the plain one. +func TestSession_CookieNameFollowsScheme(t *testing.T) { + t.Parallel() + + f, _ := newSessionClockFixture(t, 24*time.Hour, 2*time.Hour) + rec := f.postLogin(credentials("admin", testPassword), viaHTTPS) + secure := findSetCookie(rec, auth.SecureCookieName) + if secure == nil { + t.Fatal("no secure cookie") + } + if code := f.whoamiWith(secure, viaHTTPS); code != http.StatusOK { + t.Errorf("__Host- cookie over HTTPS: status = %d, want 200", code) + } + legacy := &http.Cookie{Name: auth.CookieName, Value: secure.Value} + if code := f.whoamiWith(legacy, viaHTTPS); code != http.StatusUnauthorized { + t.Errorf("unprefixed cookie over HTTPS: status = %d, want 401", code) + } + if code := f.whoamiWith(secure, nil); code != http.StatusUnauthorized { + t.Errorf("__Host- cookie over plain HTTP: status = %d, want 401", code) + } + + // Logout over HTTPS revokes the prefixed session and clears both names. + req := httptest.NewRequestWithContext(context.Background(), http.MethodDelete, "/api/admin/v1/session", nil) + req.Host = "sidecar.test" + viaHTTPS(req) + req.AddCookie(&http.Cookie{Name: secure.Name, Value: secure.Value}) + out := httptest.NewRecorder() + f.handler.ServeHTTP(out, req) + if out.Code != http.StatusNoContent { + t.Fatalf("logout status = %d", out.Code) + } + if _, ok := f.repo.session(auth.HashToken(secure.Value)); ok { + t.Error("logout over HTTPS left the __Host- session alive") + } + for _, name := range []string{auth.SecureCookieName, auth.CookieName} { + if c := findSetCookie(out, name); c == nil || c.MaxAge >= 0 { + t.Errorf("logout did not clear %s: %+v", name, c) + } + } +} diff --git a/internal/httpapi/session_test.go b/internal/httpapi/session_test.go index 4205189..6759feb 100644 --- a/internal/httpapi/session_test.go +++ b/internal/httpapi/session_test.go @@ -155,12 +155,23 @@ func quote(s string) string { return `"` + s + `"` } // the test if it is absent. func responseSessionCookie(t *testing.T, rec *httptest.ResponseRecorder) *http.Cookie { t.Helper() + // Over HTTPS the live cookie is the __Host- one and the plain name is + // only cleared (SC-25), so a clearing Set-Cookie never counts here. + // Logout's clearing form is still returned when it is all there is. + var clearing *http.Cookie for _, c := range rec.Result().Cookies() { - if c.Name == auth.CookieName { + if c.Name != auth.CookieName && c.Name != auth.SecureCookieName { + continue + } + if c.MaxAge >= 0 { return c } + clearing = c + } + if clearing != nil { + return clearing } - t.Fatalf("no %s cookie in response; Set-Cookie = %v", auth.CookieName, rec.Header().Values("Set-Cookie")) + t.Fatalf("no live session cookie in response; Set-Cookie = %v", rec.Header().Values("Set-Cookie")) return nil } @@ -199,8 +210,8 @@ func TestLogin_Success(t *testing.T) { if want := int(auth.SessionLifetime / time.Second); c.MaxAge != want { t.Errorf("Max-Age = %d, want %d", c.MaxAge, want) } - if c.MaxAge != 2592000 { - t.Errorf("Max-Age = %d, want 2592000 (30 days)", c.MaxAge) + if c.MaxAge != 86400 { + t.Errorf("Max-Age = %d, want 86400 (the 24-hour default lifetime)", c.MaxAge) } if c.Secure { t.Error("Secure set on a plain-HTTP request; the cookie would never be sent back") @@ -710,7 +721,7 @@ func (f *loginFixture) do(method, target string, cookie *http.Cookie) *httptest. // TestLogout_DeletesSessionAndClearsCookie: the session row must actually go // away -- clearing the cookie alone would leave a live token that anyone -// holding a copy could keep using for 30 days. +// holding a copy could keep using until it expired. func TestLogout_DeletesSessionAndClearsCookie(t *testing.T) { t.Parallel() diff --git a/internal/store/sqlite/auth.go b/internal/store/sqlite/auth.go index ae8366e..d689b5b 100644 --- a/internal/store/sqlite/auth.go +++ b/internal/store/sqlite/auth.go @@ -304,3 +304,28 @@ func (r *authRepo) DeleteExpiredSessions(ctx context.Context, now time.Time) (in } return n, nil } + +// ExtendSession sets expires_at; zero affected rows is auth.ErrNotFound. +func (r *authRepo) ExtendSession(ctx context.Context, tokenHash string, expiresAt time.Time) error { + n, err := r.q.ExtendSession(ctx, gen.ExtendSessionParams{ExpiresAt: expiresAt.Unix(), TokenHash: tokenHash}) + if err != nil { + return fmt.Errorf("sqlite: extend session: %w", err) + } + if n == 0 { + return fmt.Errorf("sqlite: extend session: %w", auth.ErrNotFound) + } + return nil +} + +// ListSessions returns every session row, oldest first. +func (r *authRepo) ListSessions(ctx context.Context) ([]auth.Session, error) { + rows, err := r.q.ListSessions(ctx) + if err != nil { + return nil, fmt.Errorf("sqlite: list sessions: %w", err) + } + out := make([]auth.Session, 0, len(rows)) + for _, row := range rows { + out = append(out, sessionFromRow(row)) + } + return out, nil +} diff --git a/internal/store/sqlite/gen/sessions.sql.go b/internal/store/sqlite/gen/sessions.sql.go index 7c14090..3cf0a83 100644 --- a/internal/store/sqlite/gen/sessions.sql.go +++ b/internal/store/sqlite/gen/sessions.sql.go @@ -67,6 +67,24 @@ func (q *Queries) DeleteUserSessions(ctx context.Context, userID int64) (int64, return result.RowsAffected() } +const extendSession = `-- name: ExtendSession :execrows +UPDATE sessions SET expires_at = ?1 WHERE token_hash = ?2 +` + +type ExtendSessionParams struct { + ExpiresAt int64 + TokenHash string +} + +// The idle-timeout write: the middleware slides expires_at (spec SC-25). +func (q *Queries) ExtendSession(ctx context.Context, arg ExtendSessionParams) (int64, error) { + result, err := q.db.ExecContext(ctx, extendSession, arg.ExpiresAt, arg.TokenHash) + if err != nil { + return 0, err + } + return result.RowsAffected() +} + const getSessionRow = `-- name: GetSessionRow :one SELECT token_hash, user_id, created_at, expires_at FROM sessions WHERE token_hash = ? ` @@ -84,3 +102,35 @@ func (q *Queries) GetSessionRow(ctx context.Context, tokenHash string) (Session, ) return i, err } + +const listSessions = `-- name: ListSessions :many +SELECT token_hash, user_id, created_at, expires_at FROM sessions ORDER BY created_at, token_hash +` + +func (q *Queries) ListSessions(ctx context.Context) ([]Session, error) { + rows, err := q.db.QueryContext(ctx, listSessions) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Session{} + for rows.Next() { + var i Session + if err := rows.Scan( + &i.TokenHash, + &i.UserID, + &i.CreatedAt, + &i.ExpiresAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/store/sqlite/queries/sessions.sql b/internal/store/sqlite/queries/sessions.sql index ffea2ca..0e32aa4 100644 --- a/internal/store/sqlite/queries/sessions.sql +++ b/internal/store/sqlite/queries/sessions.sql @@ -15,3 +15,10 @@ DELETE FROM sessions WHERE user_id = ?; -- name: DeleteExpiredSessions :execrows DELETE FROM sessions WHERE expires_at <= ?; + +-- The idle-timeout write: the middleware slides expires_at (spec SC-25). +-- name: ExtendSession :execrows +UPDATE sessions SET expires_at = sqlc.arg(expires_at) WHERE token_hash = sqlc.arg(token_hash); + +-- name: ListSessions :many +SELECT * FROM sessions ORDER BY created_at, token_hash; diff --git a/internal/store/storetest/authtest.go b/internal/store/storetest/authtest.go index 07508f2..6579d94 100644 --- a/internal/store/storetest/authtest.go +++ b/internal/store/storetest/authtest.go @@ -70,6 +70,66 @@ func RunAuthRepository(t *testing.T, newRepo newAuthRepoFunc) { testCreateSessionUnknownUserIsErrNotFound(t, newRepo) }) t.Run("TimestampsSurvive32BitBoundary", func(t *testing.T) { testTimestampsSurvive32BitBoundary(t, newRepo) }) + t.Run("ExtendSessionMovesExpiry", func(t *testing.T) { testExtendSessionMovesExpiry(t, newRepo) }) + t.Run("ListSessionsReturnsLiveRows", func(t *testing.T) { testListSessionsReturnsLiveRows(t, newRepo) }) +} + +// testExtendSessionMovesExpiry pins the write behind the idle timeout +// (SC-25): the middleware slides a live session's expires_at forward (or +// pulls it in), and GetSession must then honour the new value -- in both +// directions, since a lowered lifetime shortens rows minted under the old +// one. created_at must not move: it anchors the absolute lifetime. +func testExtendSessionMovesExpiry(t *testing.T, newRepo newAuthRepoFunc) { + repo := newRepo(t) + ctx := context.Background() + user := mustCreateUser(t, repo, "admin") + _, hash := mustCreateSession(t, repo, user, base, base.Add(time.Hour)) + + later := base.Add(3 * time.Hour) + if err := repo.ExtendSession(ctx, hash, later); err != nil { + t.Fatalf("ExtendSession: %v", err) + } + got, err := repo.GetSession(ctx, hash, base.Add(2*time.Hour)) + if err != nil { + t.Fatalf("GetSession after extension, past the old expiry: %v", err) + } + assertInstant(t, "extended ExpiresAt", got.ExpiresAt, later) + assertInstant(t, "CreatedAt after extension", got.CreatedAt, base) + + if err := repo.ExtendSession(ctx, hash, base.Add(30*time.Minute)); err != nil { + t.Fatalf("ExtendSession (shorten): %v", err) + } + if _, err := repo.GetSession(ctx, hash, base.Add(2*time.Hour)); !errors.Is(err, auth.ErrNotFound) { + t.Errorf("GetSession after shortening below now = %v, want ErrNotFound", err) + } + + if err := repo.ExtendSession(ctx, "no-such-token-hash", later); !errors.Is(err, auth.ErrNotFound) { + t.Errorf("ExtendSession(unknown) = %v, want ErrNotFound", err) + } +} + +// testListSessionsReturnsLiveRows backs `sidecar-admin user sessions`: every +// session row, with its user id and both timestamps, oldest first. +func testListSessionsReturnsLiveRows(t *testing.T, newRepo newAuthRepoFunc) { + repo := newRepo(t) + ctx := context.Background() + alice := mustCreateUser(t, repo, "alice") + bob := mustCreateUser(t, repo, "bob") + _, h2 := mustCreateSession(t, repo, bob, base.Add(time.Minute), base.Add(time.Hour)) + _, h1 := mustCreateSession(t, repo, alice, base, base.Add(2*time.Hour)) + + got, err := repo.ListSessions(ctx) + if err != nil { + t.Fatalf("ListSessions: %v", err) + } + if len(got) != 2 { + t.Fatalf("ListSessions = %d rows, want 2", len(got)) + } + if got[0].TokenHash != h1 || got[0].UserID != alice.ID || got[1].TokenHash != h2 || got[1].UserID != bob.ID { + t.Errorf("ListSessions = %+v, want alice's then bob's (oldest first)", got) + } + assertInstant(t, "listed CreatedAt", got[0].CreatedAt, base) + assertInstant(t, "listed ExpiresAt", got[0].ExpiresAt, base.Add(2*time.Hour)) } // assertInstant checks both that got names the same instant as want AND that From 5be64b48468f8ea7f35119172988b0bcf4b52acc Mon Sep 17 00:00:00 2001 From: Aaron Brethorst Date: Sat, 14 Nov 2026 02:05:42 -0800 Subject: [PATCH 7/9] SC-17: security headers on the admin SPA and admin API Neither /admin nor /api/admin/ sent CSP, nosniff, framing or referrer headers, and admin JSON had no Cache-Control. A middleware ahead of the mux now adds nosniff, Referrer-Policy no-referrer, X-Frame-Options DENY and HSTS (HTTPS only) to every admin response, including 401/404/405; admin JSON is no-store with a default-src 'none' CSP. The SPA's CSP is 'self'-only with no 'unsafe-inline': the inline bootstrap script and SvelteKit's route-announcer style are allowed by hashes computed from the embedded build at boot. app.html's style="display: contents" becomes a class. Verified in a real browser: sign-in, region picker and alerts page load with no violations. --- README.md | 14 ++ internal/httpapi/adminui/csp_test.go | 82 +++++++++++ internal/httpapi/router.go | 2 +- internal/httpapi/security_headers.go | 142 ++++++++++++++++++ internal/httpapi/security_headers_test.go | 167 ++++++++++++++++++++++ web/admin/src/app.html | 2 +- web/admin/src/routes/+layout.svelte | 6 + 7 files changed, 413 insertions(+), 2 deletions(-) create mode 100644 internal/httpapi/adminui/csp_test.go create mode 100644 internal/httpapi/security_headers.go create mode 100644 internal/httpapi/security_headers_test.go diff --git a/README.md b/README.md index 3f9abe8..c811db0 100644 --- a/README.md +++ b/README.md @@ -693,6 +693,20 @@ redirecting. it can mint a push-scoped key for any region (see below), so store it like a root credential and revoke it (`sidecar-admin principal revoke`) if it may have leaked. +- **Security headers.** Every response under `/admin` and `/api/admin/` + -- including `401`s, `404`s and `405`s -- carries + `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, + `X-Frame-Options: DENY`, a Content-Security-Policy, and, when the request + arrived over HTTPS, `Strict-Transport-Security: max-age=31536000` (never + over plain HTTP, so local development is unaffected). Admin JSON and CSV + are `Cache-Control: no-store`, and their CSP is `default-src 'none'`. The + SPA's CSP is `'self'`-only with no `'unsafe-inline'`: SvelteKit's inline + bootstrap script is allowed by its SHA-256, and the route announcer's + fixed `style` attribute by its hash under `'unsafe-hashes'`, both computed + at boot from the embedded build, so a rebuild cannot fall out of step. + `web/admin/src/app.html` therefore must not carry inline styles or event + handlers; `go test ./internal/httpapi/adminui` (part of `make check`) + fails if the built SPA does. Rider-facing routes are unchanged. - **One JSON value per body.** Every JSON body on `/api/admin/v1` (and the gorush webhook and the donations endpoint) must be exactly one JSON value; trailing data after it -- a second object, stray bytes -- is a `400`. diff --git a/internal/httpapi/adminui/csp_test.go b/internal/httpapi/adminui/csp_test.go new file mode 100644 index 0000000..0721fed --- /dev/null +++ b/internal/httpapi/adminui/csp_test.go @@ -0,0 +1,82 @@ +package adminui_test + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "io/fs" + "log/slog" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "testing" + + "github.com/OneBusAway/sidecar/internal/httpapi" + "github.com/OneBusAway/sidecar/internal/httpapi/adminui" +) + +// TestBuiltSPAFitsTheCSP pins SC-17 against the real SvelteKit build, not a +// fixture: every inline `).FindAllSubmatch(index, -1) + inline := 0 + for _, m := range scripts { + if strings.Contains(strings.ToLower(string(m[1])), "src=") { + continue + } + inline++ + sum := sha256.Sum256(m[2]) + if h := "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"; !strings.Contains(csp, h) { + t.Errorf("inline script %q is not allowed by the CSP (want %s in %q)", m[2], h, csp) + } + } + if inline == 0 { + t.Error("no inline script found; SvelteKit's bootstrap moved -- re-check that the SPA still boots under the CSP") + } + if regexp.MustCompile(`(?i)\sstyle\s*=`).Match(index) || regexp.MustCompile(`(?i) element; a src attribute marks an +// external one, which 'self' already covers. +var inlineScript = regexp.MustCompile(`(?is)]*)>(.*?)`) + +// styleAttr matches a style attribute literal inside a built JS chunk. +// SvelteKit's root component renders its route announcer (the visually +// hidden aria-live region) from a template string carrying one; the browser +// treats that as an inline style. +var styleAttr = regexp.MustCompile(`style="([^"]*)"`) + +// spaCSP builds the admin SPA's policy (SC-17). Everything is 'self'; the +// only script allowance beyond that is the SHA-256 of each inline script in +// index.html -- SvelteKit's bootstrap, whose content changes every build -- +// computed from the embedded file itself, so a rebuild can never silently +// fall out of step with the header. There is no 'unsafe-inline' for scripts +// or styles. index.html carries no inline style (web/admin/src/app.html +// uses a class), and the one style attribute SvelteKit's runtime writes -- +// the route announcer's, a fixed string in its source -- is allowed by its +// exact hash under 'unsafe-hashes', found by scanning the built chunks, so +// it covers that value and nothing else. The adminui package test checks +// the real build against this policy. +func spaCSP(ui fs.FS) string { + scripts := []string{"'self'"} + styles := []string{"'self'"} + if ui != nil { + if index, err := fs.ReadFile(ui, "index.html"); err == nil { + for _, m := range inlineScript.FindAllSubmatch(index, -1) { + if strings.Contains(strings.ToLower(string(m[1])), "src=") { + continue + } + scripts = append(scripts, cspHash(m[2])) + } + } + styles = append(styles, chunkStyleHashes(ui)...) + } + return strings.Join([]string{ + "default-src 'self'", + "script-src " + strings.Join(scripts, " "), + "style-src " + strings.Join(styles, " "), + "img-src 'self' data:", + "font-src 'self'", + "connect-src 'self'", + "object-src 'none'", + "base-uri 'none'", + "form-action 'self'", + "frame-ancestors 'none'", + }, "; ") +} + +// cspHash is the CSP source expression for content's SHA-256. +func cspHash(content []byte) string { + sum := sha256.Sum256(content) + return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'" +} + +// chunkStyleHashes returns 'unsafe-hashes' plus the hash of every distinct +// style attribute literal in the built JS under _app/, or nothing when there +// is none. +func chunkStyleHashes(ui fs.FS) []string { + seen := map[string]bool{} + var out []string + //nolint:errcheck // a walk error just stops early with fewer allowances: the page can lose a style, never gain one + _ = fs.WalkDir(ui, "_app", func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() || !strings.HasSuffix(p, ".js") { + return nil + } + b, readErr := fs.ReadFile(ui, p) + if readErr != nil { + return readErr + } + for _, m := range styleAttr.FindAllSubmatch(b, -1) { + if h := cspHash(m[1]); !seen[h] { + seen[h] = true + out = append(out, h) + } + } + return nil + }) + if len(out) == 0 { + return nil + } + return append([]string{"'unsafe-hashes'"}, out...) +} + +// securityHeaders adds SC-17's headers to the admin surface -- the SPA under +// /admin and the JSON API under /api/admin/ -- before the mux routes the +// request, so every response carries them: handler output, the mux's own +// 404 and 405, and a 401 from the auth middleware alike. Rider-facing routes +// are untouched; apps and monitors, not browsers, consume them. +// +// Admin JSON is additionally no-store: it carries tenant data and is fetched +// with ambient credentials, and no intermediary or browser cache should keep +// it. The SPA keeps spa.go's own cache rules (immutable hashed assets, +// no-cache shell). +func securityHeaders(ui fs.FS, next http.Handler) http.Handler { + spaPolicy := spaCSP(ui) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + p := r.URL.Path + isAPI := strings.HasPrefix(p, "/api/admin/") + isSPA := p == "/admin" || strings.HasPrefix(p, "/admin/") + if isAPI || isSPA { + h := w.Header() + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Referrer-Policy", "no-referrer") + h.Set("X-Frame-Options", "DENY") + if isHTTPS(r) { + h.Set("Strict-Transport-Security", hstsValue) + } + if isAPI { + h.Set("Content-Security-Policy", adminAPICSP) + h.Set("Cache-Control", "no-store") + } else { + h.Set("Content-Security-Policy", spaPolicy) + } + } + next.ServeHTTP(w, r) + }) +} diff --git a/internal/httpapi/security_headers_test.go b/internal/httpapi/security_headers_test.go new file mode 100644 index 0000000..ef791d3 --- /dev/null +++ b/internal/httpapi/security_headers_test.go @@ -0,0 +1,167 @@ +package httpapi + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "net/http" + "net/http/httptest" + "strings" + "testing" + "testing/fstest" +) + +// assertAdminAPIHeaders is SC-17's contract for every /api/admin/ response, +// whatever its status: no caching of admin JSON, no MIME sniffing, no +// framing, no referrer, and a CSP that lets the body do nothing if a browser +// ever renders it. +func assertAdminAPIHeaders(t *testing.T, label string, rec *httptest.ResponseRecorder) { + t.Helper() + h := rec.Header() + want := map[string]string{ + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "X-Frame-Options": "DENY", + } + for k, v := range want { + if got := h.Get(k); got != v { + t.Errorf("%s (status %d): %s = %q, want %q", label, rec.Code, k, got, v) + } + } + csp := h.Get("Content-Security-Policy") + for _, d := range []string{"default-src 'none'", "frame-ancestors 'none'"} { + if !strings.Contains(csp, d) { + t.Errorf("%s (status %d): CSP %q lacks %q", label, rec.Code, csp, d) + } + } + if h.Get("Strict-Transport-Security") != "" { + t.Errorf("%s: HSTS sent on a plain-HTTP request", label) + } +} + +// TestSecurityHeaders_EveryAdminRoute walks the whole admin route table, +// signed out and signed in, plus the mux's own 404 and 405 under the prefix: +// headers that only some handlers set are how one JSON body ends up cached +// by a shared proxy. +func TestSecurityHeaders_EveryAdminRoute(t *testing.T) { + t.Parallel() + + f := newFullAdminFixture(t) + // A 200 with a body, explicitly -- first, since the walk below includes + // logout, which ends the fixture's session. + rec := sendTo(f.handler, http.MethodGet, "/api/admin/v1/session", "", f.cookie) + if rec.Code != http.StatusOK { + t.Fatalf("whoami: status %d", rec.Code) + } + assertAdminAPIHeaders(t, "whoami 200", rec) + for _, rt := range adminRoutes(f.deps) { + method, target := concreteRoute(t, rt.pattern) + assertAdminAPIHeaders(t, rt.pattern+" signed out", sendTo(f.handler, method, target, "", nil)) + assertAdminAPIHeaders(t, rt.pattern+" signed in", sendTo(f.handler, method, target, "", f.cookie)) + } + if rec := sendTo(f.handler, http.MethodGet, "/api/admin/v1/no-such-route", "", f.cookie); rec.Code != http.StatusNotFound { + t.Errorf("unknown admin route: status %d, want 404", rec.Code) + } else { + assertAdminAPIHeaders(t, "unknown admin route", rec) + } + if rec := sendTo(f.handler, http.MethodPut, "/api/admin/v1/session", "", nil); rec.Code != http.StatusMethodNotAllowed { + t.Errorf("wrong method: status %d, want 405", rec.Code) + } else { + assertAdminAPIHeaders(t, "wrong method", rec) + } +} + +// TestSecurityHeaders_HSTSOnlyOverHTTPS: HSTS over plain-HTTP local +// development would be ignored at best and, on a real hostname, pin a +// browser to an HTTPS port that is not there. +func TestSecurityHeaders_HSTSOnlyOverHTTPS(t *testing.T) { + t.Parallel() + + f := newAdminFixture(t) + for _, target := range []string{"/api/admin/v1/session", "/admin"} { + req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, target, nil) + req.Host = "sidecar.test" + req.Header.Set("X-Forwarded-Proto", "https") + rec := httptest.NewRecorder() + f.handler.ServeHTTP(rec, req) + if got := rec.Header().Get("Strict-Transport-Security"); !strings.HasPrefix(got, "max-age=") { + t.Errorf("%s over HTTPS: Strict-Transport-Security = %q, want max-age=...", target, got) + } + } +} + +// TestSecurityHeaders_RiderRoutesUntouched: the rider-facing API and health +// check are consumed by apps and monitors, not browsers; SC-17 is scoped to +// the admin surface and must not change them. +func TestSecurityHeaders_RiderRoutesUntouched(t *testing.T) { + t.Parallel() + + f := newAdminFixture(t) + for _, target := range []string{"/healthz", "/api/v1/regions/1/alerts.pbtext"} { + rec := sendTo(f.handler, http.MethodGet, target, "", nil) + if csp := rec.Header().Get("Content-Security-Policy"); csp != "" { + t.Errorf("%s: CSP %q set on a rider route", target, csp) + } + } +} + +const spaInlineScript = "\n\t\t\t\t{ __sveltekit_x = {base: \"/admin\"}; boot(); }\n\t\t\t" + +func spaHeaderFS() fstest.MapFS { + return fstest.MapFS{ + "index.html": {Data: []byte("" + + `` + + "
\n\t\t\t\n\t\t
")}, + "_app/immutable/chunk.abc.js": {Data: []byte("console.log('chunk')")}, + "_app/immutable/entry/app.js": {Data: []byte("x=`
`")}, + } +} + +const spaAnnouncerStyle = "position: absolute; width: 1px" + +// TestSecurityHeaders_SPA: the admin SPA gets a strict CSP whose only +// script allowance beyond 'self' is the hash of the one inline bootstrap +// script SvelteKit writes into index.html, computed from the embedded file +// so a rebuild cannot silently break the page. No 'unsafe-inline' anywhere. +func TestSecurityHeaders_SPA(t *testing.T) { + t.Parallel() + + sum := sha256.Sum256([]byte(spaInlineScript)) + wantHash := "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'" + styleSum := sha256.Sum256([]byte(spaAnnouncerStyle)) + wantStyle := "style-src 'self' 'unsafe-hashes' 'sha256-" + base64.StdEncoding.EncodeToString(styleSum[:]) + "'" + h := NewRouter(Deps{AdminUI: spaHeaderFS(), Logger: discardLogger()}) + + for _, target := range []string{"/admin", "/admin/regions/1/alerts", "/admin/_app/immutable/chunk.abc.js"} { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequestWithContext(context.Background(), http.MethodGet, target, nil)) + if rec.Code != http.StatusOK { + t.Fatalf("%s: status %d", target, rec.Code) + } + csp := rec.Header().Get("Content-Security-Policy") + for _, d := range []string{ + "default-src 'self'", "script-src 'self' " + wantHash, wantStyle, + "object-src 'none'", "base-uri 'none'", "form-action 'self'", "frame-ancestors 'none'", + } { + if !strings.Contains(csp, d) { + t.Errorf("%s: CSP %q lacks %q", target, csp, d) + } + } + if strings.Contains(csp, "unsafe-inline") || strings.Contains(csp, "unsafe-eval") { + t.Errorf("%s: CSP %q allows unsafe-inline/unsafe-eval", target, csp) + } + for k, v := range map[string]string{"X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", "X-Frame-Options": "DENY"} { + if got := rec.Header().Get(k); got != v { + t.Errorf("%s: %s = %q, want %q", target, k, got, v) + } + } + } + + // The SPA keeps its own cache rules: no-store is for admin JSON only. + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/admin/_app/immutable/chunk.abc.js", nil)) + if got := rec.Header().Get("Cache-Control"); !strings.Contains(got, "immutable") { + t.Errorf("immutable asset Cache-Control = %q, want the long immutable cache kept", got) + } +} diff --git a/web/admin/src/app.html b/web/admin/src/app.html index ef5a667..1d3a73d 100644 --- a/web/admin/src/app.html +++ b/web/admin/src/app.html @@ -7,6 +7,6 @@ %sveltekit.head% -
%sveltekit.body%
+
%sveltekit.body%
diff --git a/web/admin/src/routes/+layout.svelte b/web/admin/src/routes/+layout.svelte index 3cb31b4..6304423 100644 --- a/web/admin/src/routes/+layout.svelte +++ b/web/admin/src/routes/+layout.svelte @@ -69,6 +69,12 @@