Files
multica/server/internal/auth/cookie_test.go
1fcdff78d0 MUL-7436 feat(auth): slide UI session expiry instead of forcing a re-login every 30 days (#8486)
* feat(auth): slide UI session expiry instead of fixing it at login

A session token's exp was stamped once at login and never moved, so every
continuously active user was logged out 30 days later, always mid-task. The
session now re-issues itself once it drops below half its TTL, turning that
scheduled logout into an idle bound.

Renewal is stateless: it copies the claims of a token we signed and moves
exp, so there is no session table and no DB read on the hot path.

- Browsers are renewed inline by middleware.Auth on safe requests, keeping
  the session HttpOnly — no client change and no multi-tab coordination.
- Clients holding the session as a string (Desktop, mobile) get
  POST /api/auth/refresh, which only ever accepts a UI JWT. PATs, agent task
  tokens and cloud-node PATs are refused: a machine credential must not
  become an interactive session. An expired JWT cannot be revived.
- CSRF tokens are now bound to a new sid claim, stable across renewals, so
  re-issuing the auth cookie no longer invalidates a CSRF token another tab
  already read. The pre-existing binding stays valid so sessions that
  predate this keep working until they renew.
- CloudFront cookies are re-signed alongside a renewal, so the CDN policy
  cannot outlive its session.

The idle bound is one-sided and the comments say so: a session last used
while it still had over half its TTL left is not extended, so the
guaranteed survivable gap is TTL/2, not TTL.

Refs MUL-7436

Co-authored-by: multica-agent <[email protected]>

* feat(auth): renew the session on Desktop, mobile, and legacy token-mode web

Completes the client half of sliding sessions. Browsers on cookie auth need
nothing — the server re-issues their cookie inline — so this covers the
clients that carry the session as a string and have to persist a new one.

Renewal follows use, not a clock. Checks run at launch, on returning to the
foreground, and on interaction; there is deliberately no interval timer,
because a timer would keep an abandoned but still-open window (or a
backgrounded phone) signed in forever. The server decides whether a session
is renewable and tells the client when to ask again, derived from the
deployment's configured TTL — so no client reads exp, hardcodes a cadence,
or has to reason about clock skew.

Renewal is not a session event, and each step protects that:
- Concurrent triggers collapse into one request, so two valid tokens never
  race to be the one stored. On mobile the single-flight flag is set before
  the first await, since reading the Keychain is itself async.
- A response that lands after logout or an account switch is discarded by
  comparing against the session the attempt started from; writing it back
  would resurrect a session the app has already torn down.
- Offline, 5xx and an unreadable body all keep the current session, which is
  still valid for at least another half TTL. Only a real 401 ends a session,
  and that path is untouched — nothing here can clear tabs or drafts.
- WebSocket clients now read the token at connect time instead of pinning
  the one captured when they were built, so a reconnect after a renewal
  authenticates with the current credential.

Web also retries a rejected CSRF token once. Session-bound CSRF makes that
unreachable in the steady state; it covers the single transition where a
session predating that binding is renewed for the first time.

Refs MUL-7436

Co-authored-by: multica-agent <[email protected]>

* fix(auth): address review blockers on sliding session renewal

Six fixes from review, each with a regression test that fails without it.

An expired session was answered 403, not 401. The CSRF gate runs before the
JWT is validated, and it read `sid` through the expiry-enforcing parser — so
an expired cookie lost its sid, its perfectly good CSRF token failed to
verify, and the user's first action after expiry was a rejected write instead
of a return to the login page. Reading the session id and deciding access are
now different questions with different parsers: the first only needs the
signature, the second still enforces expiry.

Rolling back was not survivable. A previous release can verify only the
token-bound CSRF binding, so once a session was issued or renewed by this
one, a rollback left every signed-in user able to read and unable to write,
with no client retry able to help. Both bindings are now issued: clients echo
both, the server accepts either, and the token-bound cookie is re-minted on
every renewal so a rollback taken at any moment still finds a usable pair.

Mobile could resurrect a session it had just ended. Keychain deletes are
async, so a renewal that sampled storage after logout began but before the
delete landed would write its replacement back. A session epoch, incremented
synchronously at the start of logout, a 401 teardown and a new sign-in, closes
the window comparing tokens cannot — including the case where logout lands
during the renewal's own write, which is now undone rather than left behind.

Mobile only checked at launch and on foreground, so an app held in the
foreground and used continuously would never check again and could expire
under the user's hands. Every touch now passes through a capture-phase
responder that declines the gesture it observes.

CloudFront cookies were re-signed by a middleware not every renewing route
mounts — the plugin bridge renews without it, and would have slid the session
forward while leaving the CDN policy behind. Re-signing moved next to the
renewal itself, so the two cannot diverge by route.

The renewal check interval could exceed the window it has to land in: a flat
five-minute floor meant any TTL under ten minutes produced a cadence longer
than the renewal window, logging out clients that followed it exactly. The
cadence is now capped at half the threshold, which outranks both clamps.

Refs MUL-7436

Co-authored-by: multica-agent <[email protected]>

* fix(auth): close the CORS, credential-write and short-TTL gaps

Three blockers from the second review round.

The two CSRF values now travel in one header instead of two. A second header
name would have to be in the server's CORS allowlist, and that list is
version-specific: a browser holding a cookie this release issued, talking to a
rolled-back server, would send a header that server never allowlisted. The
preflight fails, the request never reaches a handler, and no retry helps —
precisely the half-logged-in state the second cookie exists to prevent. With
one header name the server just tries both bindings, and the client switches
to the token-bound value when a server rejects the session-bound one. It
switches back as soon as the cookie changes, keyed on the rejected value
rather than a flag, so it cannot oscillate once per renewal. A test now pins
the CSRF header to the allowlist so a future second header fails here rather
than in production.

Mobile credential writes are serialized, and a stale renewal is refused rather
than undone. Compensating after the fact meant deleting whatever was stored —
which, after a logout and a fresh sign-in, is the new account's token: the app
would be logged in in memory and signed out on the next launch. The check and
the write now happen inside one serialized unit, so a logout or a sign-in
cannot land between them and a refusal writes nothing at all.

AUTH_TOKEN_TTL has a documented one-minute minimum. Clients are told when to
check again in whole seconds, so a shorter TTL asks the wire to carry a
sub-second cadence: it truncates, and below about four seconds it serialises
to 0. Values under the minimum are clamped up with a startup warning rather
than honoured. Mobile's floors were never actually lowered in the previous
commit — 1h/1m, not the 5s/5m claimed — so both clients now floor at 5s, below
anything the server can send, and fall back to 30s, which fits the smallest
supported window. The cadence tests assert the serialised integer a client
actually receives, not the internal time.Duration.

Refs MUL-7436

Co-authored-by: multica-agent <[email protected]>

* fix(auth): keep a failed renewal cheap and a renewed token shared

Two blockers from the full-PR review, plus the documentation the config
change owes.

A failed check no longer consumes the normal cadence. The two were one
number, so a single 503 spent whatever the server had last suggested — with
the 30-day default that is three days. A client told to check again in three
days on day 12, returning on day 29 with one day of session left and hitting
one 503, would not have been allowed to retry until day 32: two days after the
session it was trying to save had expired. Failures now buy a short backing-off
delay of their own, reset by the next success, so recovery follows the network
rather than the cadence.

The bearer token is read from shared storage per request instead of cached per
client. Desktop runs one ApiClient per window over one localStorage, so a
session renewed in one window left the others sending a credential on its way
out until it expired and took the whole session down. A 401 is also now matched
against the credential that produced it: a request that went out just before a
renewal can be answered after it, and treating that as expiry would tear down a
session that is demonstrably alive, clearing tabs and drafts with it.

Documentation catches up with both the behaviour and the new minimum, in all
four languages: sessions are an idle bound rather than a countdown from
sign-in, the bound is one-sided, and AUTH_TOKEN_TTL clamps up at 60s. The
rationale for that minimum is corrected too — it is the 5s floor every client
applies to the derived cadence, not whole-second serialisation, which only
binds far below it.

Also removes two claims that were not true: that a failed renewal leaves at
least half a TTL (it happens inside the window, so less), and that an open
untouched window never renews (cookie-mode sessions slide on any authenticated
request, background polling included).

Refs MUL-7436

Co-authored-by: multica-agent <[email protected]>

* fix(auth): back off on a renewal response that carries no cadence

A 200 whose body fails schema validation does not throw — parseWithFallback
returns zeroes — so both clients reset the failure count without moving the
next-check deadline, and every subsequent interaction fired another request at
a server already answering badly. A missing cadence is now treated as a
failure and takes the same short backoff; a token that did arrive is still
applied.

Also settles the documentation wording: the 30 days is not an idle timer.
Renewal only happens past the halfway point, so an unused session can end
sooner than 30 days after its last use, and saying otherwise promised
precision the design does not have.

Refs MUL-7436

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-09-16 18:44:59 +08:00

390 lines
14 KiB
Go

package auth
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestIsSecureCookie(t *testing.T) {
cases := []struct {
name string
frontendOrigin string
want bool
}{
{"https origin → Secure", "https://app.example.com", true},
{"https with port", "https://app.example.com:8443", true},
{"http origin → not Secure", "http://192.168.5.5:13000", false},
{"http localhost → not Secure", "http://localhost:3000", false},
{"empty → not Secure", "", false},
{"malformed → not Secure", "::not-a-url", false},
{"uppercase scheme still matches", "HTTPS://app.example.com", true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("FRONTEND_ORIGIN", tc.frontendOrigin)
if got := isSecureCookie(); got != tc.want {
t.Errorf("isSecureCookie() = %v, want %v (FRONTEND_ORIGIN=%q)", got, tc.want, tc.frontendOrigin)
}
})
}
}
func TestCookieDomain(t *testing.T) {
cases := []struct {
name string
env string
want string
}{
{"empty", "", ""},
{"whitespace only", " ", ""},
{"real domain", ".example.com", ".example.com"},
{"bare domain", "example.com", "example.com"},
{"IPv4 rejected", "192.168.5.5", ""},
{"IPv4 with leading dot rejected", ".192.168.5.5", ""},
{"IPv6 rejected", "::1", ""},
{"IPv6 bracketed is not a valid IP literal → passthrough", "[::1]", "[::1]"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("COOKIE_DOMAIN", tc.env)
if got := cookieDomain(); got != tc.want {
t.Errorf("cookieDomain() = %q, want %q (COOKIE_DOMAIN=%q)", got, tc.want, tc.env)
}
})
}
}
// TestSetAuthCookies_HTTPSelfHost covers the exact misconfiguration that
// shipped to users on LAN self-host: COOKIE_DOMAIN=<ip> + HTTP FRONTEND_ORIGIN.
// The cookie must land with no Domain attribute and Secure=false so browsers
// actually store it.
func TestSetAuthCookies_HTTPSelfHost(t *testing.T) {
t.Setenv("FRONTEND_ORIGIN", "http://192.168.5.5:13000")
t.Setenv("COOKIE_DOMAIN", "192.168.5.5")
rec := httptest.NewRecorder()
if err := SetAuthCookies(rec, "test-token"); err != nil {
t.Fatalf("SetAuthCookies: %v", err)
}
cookies := rec.Result().Cookies()
if len(cookies) != 2 {
t.Fatalf("expected 2 cookies (auth + csrf), got %d", len(cookies))
}
for _, c := range cookies {
if c.Secure {
t.Errorf("cookie %q has Secure=true on HTTP origin; browser would reject it", c.Name)
}
if c.Domain != "" {
t.Errorf("cookie %q has Domain=%q; IP-address Domain would be rejected by the browser (RFC 6265)", c.Name, c.Domain)
}
}
}
func TestParseAuthTokenTTL(t *testing.T) {
cases := []struct {
name string
raw string
wantDur time.Duration
wantOK bool
}{
{"empty string", "", 0, false},
{"valid 3600", "3600", time.Hour, true},
{"valid 86400", "86400", 24 * time.Hour, true},
{"negative", "-100", 0, false},
{"zero", "0", 0, false},
{"non-numeric", "abc", 0, false},
{"whitespace trimmed", " 7200 ", 2 * time.Hour, true},
{"duration hours", "8760h", 8760 * time.Hour, true},
{"duration compound", "720h30m", 720*time.Hour + 30*time.Minute, true},
{"duration minutes", "90m", 90 * time.Minute, true},
{"duration negative", "-1h", 0, false},
{"duration zero", "0s", 0, false},
{"integer overflow", "9999999999", 0, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, ok := parseAuthTokenTTL(tc.raw)
if ok != tc.wantOK || got != tc.wantDur {
t.Errorf("parseAuthTokenTTL(%q) = (%v, %v), want (%v, %v)", tc.raw, got, ok, tc.wantDur, tc.wantOK)
}
})
}
}
func TestSetAuthCookies_HTTPSProduction(t *testing.T) {
t.Setenv("FRONTEND_ORIGIN", "https://app.example.com")
t.Setenv("COOKIE_DOMAIN", "app.example.com")
rec := httptest.NewRecorder()
if err := SetAuthCookies(rec, "test-token"); err != nil {
t.Fatalf("SetAuthCookies: %v", err)
}
for _, c := range rec.Result().Cookies() {
if !c.Secure {
t.Errorf("cookie %q missing Secure flag on HTTPS origin", c.Name)
}
if c.Domain != "app.example.com" {
t.Errorf("cookie %q Domain = %q, want %q", c.Name, c.Domain, "app.example.com")
}
}
}
// csrfHeaderFor builds the request a browser would send: the auth cookie the
// server set, plus the CSRF cookie's value echoed in the header.
// csrfRequest presents authToken as the auth cookie and echoes csrfValue in
// the single CSRF header. Which of the two cookie values a client puts there
// is the client's choice; the server tries both bindings either way.
func csrfRequest(t *testing.T, authToken, csrfValue string) *http.Request {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/issues", nil)
req.AddCookie(&http.Cookie{Name: AuthCookieName, Value: authToken})
req.Header.Set(CSRFHeaderName, csrfValue)
return req
}
// legacyCSRFRequest is the same request; the name records that the value came
// from the token-bound cookie — what a client that has not picked up the new
// cookie sends, and what a rolled-back server would be verifying.
func legacyCSRFRequest(t *testing.T, authToken, csrfValue string) *http.Request {
t.Helper()
return csrfRequest(t, authToken, csrfValue)
}
// cookieValues runs the real cookie-setting path and returns the readable
// cookies by name.
func cookieValues(t *testing.T, authToken string) map[string]string {
t.Helper()
rec := httptest.NewRecorder()
if err := SetAuthCookies(rec, authToken); err != nil {
t.Fatalf("SetAuthCookies: %v", err)
}
out := map[string]string{}
for _, c := range rec.Result().Cookies() {
out[c.Name] = c.Value
}
return out
}
// setAuthCookiesFor runs the real cookie-setting path and returns the CSRF
// token it minted, so tests exercise the same code the login and renewal
// paths use rather than reimplementing the token format.
func setAuthCookiesFor(t *testing.T, authToken string) string {
t.Helper()
values := cookieValues(t, authToken)
if v := values[SessionCSRFCookieName]; v != "" {
return v
}
t.Fatal("no session-bound CSRF cookie was set")
return ""
}
// The point of binding CSRF to `sid` instead of to the token string: sliding
// renewal re-issues the auth cookie mid-session, and a CSRF token another tab
// read before that must keep working afterwards (MUL-7436).
func TestValidateCSRF_SurvivesSessionRenewal(t *testing.T) {
sid, err := NewSessionID()
if err != nil {
t.Fatalf("NewSessionID: %v", err)
}
claims := sessionClaims(t, time.Now().Add(20*24*time.Hour), sid)
original := signSession(t, claims)
// A tab reads the CSRF cookie...
csrfToken := setAuthCookiesFor(t, original)
// ...the session is renewed on another tab's GET, producing a different
// auth token for the same session...
renewed, _, err := RenewSessionToken(claims)
if err != nil {
t.Fatalf("RenewSessionToken: %v", err)
}
if renewed == original {
t.Fatal("renewal must produce a different token")
}
// ...and the first tab's POST still validates against the new cookie.
if !ValidateCSRF(csrfRequest(t, renewed, csrfToken)) {
t.Error("CSRF token issued before renewal must stay valid after it")
}
// The reverse also holds: a token minted after renewal works, so both
// tabs converge without either having to reload.
if !ValidateCSRF(csrfRequest(t, renewed, setAuthCookiesFor(t, renewed))) {
t.Error("CSRF token issued after renewal must validate")
}
}
// Binding to the session must not become a way to use one session's CSRF
// token against another's cookie.
func TestValidateCSRF_RejectsTokenFromAnotherSession(t *testing.T) {
sidA, _ := NewSessionID()
sidB, _ := NewSessionID()
tokenA := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), sidA))
tokenB := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), sidB))
csrfA := setAuthCookiesFor(t, tokenA)
if ValidateCSRF(csrfRequest(t, tokenB, csrfA)) {
t.Error("a CSRF token from another session must not validate")
}
}
// Everyone signed in when this ships holds a cookie pair minted under the old
// binding. Those must keep working until that session renews, or the deploy
// logs the whole userbase out of every state-changing action.
func TestValidateCSRF_AcceptsTokenBinding(t *testing.T) {
legacy := signSession(t, sessionClaims(t, time.Now().Add(20*24*time.Hour), ""))
values := cookieValues(t, legacy)
if values[SessionCSRFCookieName] != "" {
t.Error("a token without `sid` has no session to bind to; no session cookie should be set")
}
if !ValidateCSRF(legacyCSRFRequest(t, legacy, values[CSRFCookieName])) {
t.Error("a pre-MUL-7436 cookie pair must still validate")
}
// And the token binding stays bound: it is keyed by the token itself, so
// it must not validate against a different one.
other := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), ""))
if ValidateCSRF(legacyCSRFRequest(t, other, values[CSRFCookieName])) {
t.Error("a token-bound CSRF value must not validate against a different auth token")
}
}
// Rolling BACK past MUL-7436 must not strand signed-in users able to read and
// unable to write. A previous release verifies only the token binding, so
// every cookie set here has to include one — that is the sole reason it is
// still issued alongside the session binding.
func TestSetAuthCookies_KeepsTokenBindingForRollback(t *testing.T) {
sid, _ := NewSessionID()
token := signSession(t, sessionClaims(t, time.Now().Add(20*24*time.Hour), sid))
values := cookieValues(t, token)
if values[CSRFCookieName] == "" {
t.Fatal("the token-bound cookie must still be issued; without it a rollback cannot verify any write")
}
if values[SessionCSRFCookieName] == "" {
t.Fatal("the session-bound cookie must be issued")
}
if values[CSRFCookieName] == values[SessionCSRFCookieName] {
t.Error("the two cookies must carry different bindings")
}
// Exactly what a rolled-back server does: verify the token-bound value
// against the auth cookie, knowing nothing about `sid`.
if !verifyCSRFToken(values[CSRFCookieName], func(nonce []byte) []byte {
return tokenCSRFSignature(token, nonce)
}) {
t.Error("the token-bound cookie must verify under the pre-MUL-7436 scheme")
}
// And a current server accepts it too, so a client that only ever sends
// the token-bound header keeps working.
if !ValidateCSRF(legacyCSRFRequest(t, token, values[CSRFCookieName])) {
t.Error("a current server must still accept the token-bound header")
}
}
// After a renewal the token-bound cookie is re-minted for the NEW token, so a
// rollback taken at any point still finds a usable pair — that is what makes
// the rollback path complete rather than only true at login.
func TestSetAuthCookies_TokenBindingTracksRenewal(t *testing.T) {
sid, _ := NewSessionID()
claims := sessionClaims(t, time.Now().Add(20*24*time.Hour), sid)
renewed, _, err := RenewSessionToken(claims)
if err != nil {
t.Fatalf("RenewSessionToken: %v", err)
}
values := cookieValues(t, renewed)
if !verifyCSRFToken(values[CSRFCookieName], func(nonce []byte) []byte {
return tokenCSRFSignature(renewed, nonce)
}) {
t.Error("the renewed token-bound cookie must be keyed to the renewed token")
}
}
// One header, two acceptable bindings: whichever cookie value a client
// chooses to echo, the server has to recognise it. This is what lets the
// single header name serve every client/server version combination without a
// CORS change — see CSRFHeaderName.
func TestValidateCSRF_AcceptsEitherCookieValueInTheOneHeader(t *testing.T) {
sid, _ := NewSessionID()
token := signSession(t, sessionClaims(t, time.Now().Add(20*24*time.Hour), sid))
values := cookieValues(t, token)
if !ValidateCSRF(csrfRequest(t, token, values[SessionCSRFCookieName])) {
t.Error("the session-bound value must validate")
}
if !ValidateCSRF(csrfRequest(t, token, values[CSRFCookieName])) {
t.Error("the token-bound value must validate")
}
// After a renewal the token-bound value from BEFORE it is stale, and the
// session-bound one is not — which is the whole reason clients prefer it.
renewed, _, err := RenewSessionToken(sessionClaims(t, time.Now().Add(20*24*time.Hour), sid))
if err != nil {
t.Fatalf("RenewSessionToken: %v", err)
}
if !ValidateCSRF(csrfRequest(t, renewed, values[SessionCSRFCookieName])) {
t.Error("a session-bound value must survive renewal")
}
if ValidateCSRF(csrfRequest(t, renewed, values[CSRFCookieName])) {
t.Error("a pre-renewal token-bound value must NOT still validate; clients fall back to the re-minted one")
}
}
// Expiry is not this gate's business. SessionIDFromToken reads `sid` without
// enforcing it, so an expired-but-genuine cookie still validates here and the
// auth middleware answers with the 401 that ends the session.
func TestValidateCSRF_IgnoresExpirySoAuthCanAnswer(t *testing.T) {
sid, _ := NewSessionID()
live := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), sid))
expired := signSession(t, sessionClaims(t, time.Now().Add(-time.Hour), sid))
csrf := setAuthCookiesFor(t, live)
if !ValidateCSRF(csrfRequest(t, expired, csrf)) {
t.Error("an expired session must fail authentication, not CSRF — a 403 here never reaches the session-expiry path")
}
}
func TestValidateCSRF_RejectsMalformedAndMissing(t *testing.T) {
sid, _ := NewSessionID()
token := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), sid))
cases := map[string]string{
"empty": "",
"no separator": "abcdef",
"bad nonce hex": "zz.00",
"bad sig hex": "00.zz",
"wrong sig": "0011223344556677889900112233445566.00",
"extra segments": "00.11.22",
}
for name, csrf := range cases {
t.Run(name, func(t *testing.T) {
if ValidateCSRF(csrfRequest(t, token, csrf)) {
t.Errorf("malformed CSRF token %q must not validate", csrf)
}
})
}
// No auth cookie at all: nothing to bind to, so nothing validates.
req := httptest.NewRequest(http.MethodPost, "/api/issues", nil)
req.Header.Set("X-CSRF-Token", setAuthCookiesFor(t, token))
if ValidateCSRF(req) {
t.Error("CSRF must not validate without an auth cookie")
}
}
func TestValidateCSRF_SafeMethodsSkipTheCheck(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodOptions} {
req := httptest.NewRequest(method, "/api/issues", nil)
if !ValidateCSRF(req) {
t.Errorf("%s must not require a CSRF token", method)
}
}
}