Files
multica/server/internal/auth/cookie.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

389 lines
14 KiB
Go

package auth
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"log/slog"
"math"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
)
const (
AuthCookieName = "multica_auth"
// CSRFCookieName carries the token-bound CSRF value, and keeps carrying
// it: every server that has ever run this code understands this cookie,
// which is what makes rolling BACK past MUL-7436 safe. See
// SessionCSRFCookieName.
CSRFCookieName = "multica_csrf"
// SessionCSRFCookieName carries the session-bound CSRF value added by
// MUL-7436. It is the one the server prefers, because it survives a
// sliding renewal; the token-bound cookie above cannot, since renewal
// replaces the very token it is keyed to.
SessionCSRFCookieName = "multica_csrf_session"
// CSRFHeaderName is where clients echo ONE of the two cookies back, and
// there is deliberately only one header name.
//
// A second header would have to be added to corsAllowedHeaders, and that
// list is version-specific: a browser holding a cookie issued by this
// release, talking to a rolled-back server, would send a header that
// server does not allowlist. The preflight fails, the request never
// reaches a handler, and no amount of client retrying helps — which is
// exactly the half-logged-in state the second cookie exists to prevent.
// Keeping one header name means the rollback path has no preflight
// dependency at all; the server simply tries both bindings against
// whatever value arrives.
CSRFHeaderName = "X-CSRF-Token"
defaultAuthTokenTTL = 30 * 24 * time.Hour // 30 days
// MinAuthTokenTTL is the shortest session lifetime this system can serve
// correctly, and what sets it is the CLIENT FLOOR, not the wire format.
//
// The renewal cadence is TTL/10, and every client floors what the server
// sends at five seconds so a nonsense value cannot turn activity into a
// request per event. Once TTL/10 drops below that floor the floor wins,
// and the client is checking on a schedule the server did not choose —
// which is exactly how a cadence ends up longer than the window it has to
// land in. TTL/10 >= 5s means TTL >= 50 seconds; one minute is that bound
// rounded to something an operator would actually write, and it leaves
// the cadence (six seconds) comfortably above the floor.
//
// Whole-second serialisation (RefreshSessionResponse.CheckAgainInSeconds)
// is a second, looser constraint: it only bites below about four seconds
// of cadence, i.e. a TTL under 40 seconds, so the client floor is the one
// that actually decides this number.
//
// Anything shorter is clamped up rather than honoured, because honouring
// it would mean silently logging active users out.
MinAuthTokenTTL = time.Minute
)
var (
ipCookieDomainWarnOnce sync.Once
authTokenTTLOnce sync.Once
authTokenTTLCached time.Duration
)
// parseAuthTokenTTL parses a raw AUTH_TOKEN_TTL value into a duration.
// It first tries time.ParseDuration (e.g. "8760h", "720h30m"), then falls
// back to parsing as integer seconds. Returns the parsed duration and true
// on success; zero and false when the input is empty or invalid.
func parseAuthTokenTTL(raw string) (time.Duration, bool) {
raw = strings.TrimSpace(raw)
if raw == "" {
return 0, false
}
// Try Go duration string first (e.g. "8760h", "720h30m").
if d, err := time.ParseDuration(raw); err == nil {
if d <= 0 {
return 0, false
}
if d > 10*365*24*time.Hour {
slog.Warn("AUTH_TOKEN_TTL exceeds 10 years; accepting but verify this is intentional",
"value", raw, "hours", d.Hours())
}
return d, true
}
// Fall back to plain integer seconds.
secs, err := strconv.ParseInt(raw, 10, 64)
if err != nil || secs <= 0 {
return 0, false
}
if secs > int64(math.MaxInt64/int64(time.Second)) {
return 0, false
}
d := time.Duration(secs) * time.Second
if d > 10*365*24*time.Hour {
slog.Warn("AUTH_TOKEN_TTL exceeds 10 years; accepting but verify this is intentional",
"value", raw, "hours", d.Hours())
}
return d, true
}
// AuthTokenTTL returns the configured auth token lifetime. It reads the
// AUTH_TOKEN_TTL environment variable (Go duration string or integer seconds) on first call and caches
// the result. When the variable is unset or invalid the default of 30 days
// is used.
func AuthTokenTTL() time.Duration {
authTokenTTLOnce.Do(func() {
raw := os.Getenv("AUTH_TOKEN_TTL")
if ttl, ok := parseAuthTokenTTL(raw); ok {
if ttl < MinAuthTokenTTL {
// Clamping up, not falling back to the default: someone who
// asked for 30 seconds is far better served by 1 minute than
// by the 30-day default they did not ask for, and the warning
// says exactly what happened.
slog.Warn("AUTH_TOKEN_TTL is below the shortest supported session lifetime; using the minimum",
"value", raw, "minimum_seconds", int(MinAuthTokenTTL.Seconds()),
"reason", "a shorter TTL derives a renewal cadence below the floor every client applies, so clients would check on a schedule this server did not choose")
ttl = MinAuthTokenTTL
}
authTokenTTLCached = ttl
slog.Info("auth token TTL configured", "seconds", int(ttl.Seconds()))
return
}
authTokenTTLCached = defaultAuthTokenTTL
if strings.TrimSpace(raw) != "" {
slog.Warn("AUTH_TOKEN_TTL is not a valid duration or positive integer; using default",
"value", raw, "default_seconds", int(defaultAuthTokenTTL.Seconds()))
}
})
return authTokenTTLCached
}
// cookieDomain returns the trimmed COOKIE_DOMAIN env value, or "" if it looks
// like an IP address. RFC 6265 §4.1.2.3 forbids IP literals in the cookie
// Domain attribute, so browsers silently drop Set-Cookie headers that carry
// one. An IP value here is almost always a misconfiguration.
func cookieDomain() string {
raw := strings.TrimSpace(os.Getenv("COOKIE_DOMAIN"))
if raw == "" {
return ""
}
// A leading dot ("." for subdomain matching) is legal syntax but doesn't
// change whether the remainder is an IP literal.
if ip := net.ParseIP(strings.TrimPrefix(raw, ".")); ip != nil {
ipCookieDomainWarnOnce.Do(func() {
slog.Warn(
"COOKIE_DOMAIN looks like an IP address; ignoring. RFC 6265 forbids IP literals in the cookie Domain attribute, so browsers would drop the Set-Cookie. Leave COOKIE_DOMAIN empty for single-host deployments, or use a real domain.",
"value", raw,
)
})
return ""
}
return raw
}
// isSecureCookie reports whether session cookies should carry the Secure flag.
// Derived from the scheme of FRONTEND_ORIGIN — browsers silently drop Secure
// cookies received on a plain-HTTP page, so the flag has to track the actual
// user-facing scheme rather than a coarser environment name.
func isSecureCookie() bool {
raw := strings.TrimSpace(os.Getenv("FRONTEND_ORIGIN"))
if raw == "" {
return false
}
u, err := url.Parse(raw)
if err != nil {
return false
}
return strings.EqualFold(u.Scheme, "https")
}
// Two CSRF bindings exist side by side, and the pair is deliberate.
//
// - Session-bound: HMAC-SHA256 keyed by the server's JWT secret over
// (sessionID, nonce). `sid` survives renewal, so re-signing the auth
// cookie leaves every CSRF token already issued for that session valid —
// which is what keeps sliding renewal from racing other tabs (MUL-7436).
// This is the HMAC-based Token Pattern OWASP recommends.
// - Token-bound: HMAC-SHA256 keyed by the auth token itself over the nonce.
// This is the original scheme, and it is still ISSUED, not merely still
// accepted. A server running the previous release can verify only this
// one, so dropping it would make a rollback strand every signed-in user
// able to read but unable to write: their session would authenticate on
// GET and 403 on every POST, with no client-side retry able to help. It
// is the only binding either version can agree on, so both are written.
//
// Both defend the same thing: an attacker who can write cookies on a sibling
// subdomain cannot produce a CSRF value matching the auth cookie without
// already holding the session it belongs to.
//
// The token-bound cookie becomes removable one release after this ships, when
// no deployable version still needs it.
func sessionCSRFSignature(sessionID string, nonce []byte) []byte {
mac := hmac.New(sha256.New, JWTSecret())
mac.Write([]byte(sessionID))
// Domain separator: without it a (sessionID, nonce) pair could be
// re-split, letting one session's token be read as another's.
mac.Write([]byte{0})
mac.Write(nonce)
return mac.Sum(nil)
}
func tokenCSRFSignature(authToken string, nonce []byte) []byte {
mac := hmac.New(sha256.New, []byte(authToken))
mac.Write(nonce)
return mac.Sum(nil)
}
// csrfToken formats a CSRF value as hex(nonce) + "." + hex(signature).
func csrfToken(sign func(nonce []byte) []byte) (string, error) {
nonce := make([]byte, 16)
if _, err := rand.Read(nonce); err != nil {
return "", err
}
return hex.EncodeToString(nonce) + "." + hex.EncodeToString(sign(nonce)), nil
}
// verifyCSRFToken checks a presented "nonce.signature" value against sign.
func verifyCSRFToken(presented string, sign func(nonce []byte) []byte) bool {
parts := strings.SplitN(presented, ".", 2)
if len(parts) != 2 {
return false
}
nonce, err := hex.DecodeString(parts[0])
if err != nil {
return false
}
sig, err := hex.DecodeString(parts[1])
if err != nil {
return false
}
return hmac.Equal(sign(nonce), sig)
}
// SetAuthCookies sets the HttpOnly auth cookie and both readable CSRF cookies
// on the response.
func SetAuthCookies(w http.ResponseWriter, token string) error {
secure := isSecureCookie()
domain := cookieDomain()
ttl := AuthTokenTTL()
now := time.Now()
readable := func(name, value string) {
http.SetCookie(w, &http.Cookie{
Name: name,
Value: value,
Path: "/",
Domain: domain,
MaxAge: int(ttl.Seconds()),
Expires: now.Add(ttl),
HttpOnly: false,
Secure: secure,
SameSite: http.SameSiteStrictMode,
})
}
http.SetCookie(w, &http.Cookie{
Name: AuthCookieName,
Value: token,
Path: "/",
Domain: domain,
MaxAge: int(ttl.Seconds()),
Expires: now.Add(ttl),
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteStrictMode,
})
tokenBound, err := csrfToken(func(nonce []byte) []byte {
return tokenCSRFSignature(token, nonce)
})
if err != nil {
return err
}
readable(CSRFCookieName, tokenBound)
// Only a token carrying `sid` can have a session-bound value. A token
// minted before MUL-7436 has none until it renews, and until then the
// token-bound cookie above is the only one it can use.
if sid := SessionIDFromToken(token); sid != "" {
sessionBound, err := csrfToken(func(nonce []byte) []byte {
return sessionCSRFSignature(sid, nonce)
})
if err != nil {
return err
}
readable(SessionCSRFCookieName, sessionBound)
}
return nil
}
// ClearAuthCookies removes the auth cookie and both CSRF cookies.
func ClearAuthCookies(w http.ResponseWriter) {
domain := cookieDomain()
secure := isSecureCookie()
expire := func(name string, httpOnly bool) {
http.SetCookie(w, &http.Cookie{
Name: name,
Value: "",
Path: "/",
Domain: domain,
MaxAge: -1,
Expires: time.Unix(0, 0),
HttpOnly: httpOnly,
Secure: secure,
SameSite: http.SameSiteStrictMode,
})
}
expire(AuthCookieName, true)
expire(CSRFCookieName, false)
// Logout must clear BOTH, or a stale session-bound value survives the
// logout and is presented alongside the next login's cookies.
expire(SessionCSRFCookieName, false)
}
// IsSafeMethod reports whether a method is read-only under RFC 9110, i.e. one
// that carries no CSRF requirement. Exported because the session-renewal
// middleware reuses it: re-issuing the auth cookie is itself a write to the
// client's cookie jar, and doing it only on safe requests keeps a rotation
// from ever racing the CSRF token of the request that triggered it.
func IsSafeMethod(method string) bool {
switch method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
return true
}
return false
}
// ValidateCSRF checks the CSRF header against the auth cookie. The value is
// HMAC-signed, so the server verifies a signature rather than comparing
// cookie == header.
// Returns true if validation passes (including for safe methods that don't need CSRF).
//
// One header, two acceptable bindings. Clients prefer the session-bound
// cookie, which survives a sliding renewal; a client that has not picked up
// that cookie, or is talking to us right after a rollback, sends the
// token-bound one. Trying both here is what lets a single header name serve
// every combination of client and server version — see CSRFHeaderName.
//
// The `sid` is read from the cookie WITHOUT enforcing expiry
// (SessionIDFromToken). That is what keeps an expired session from failing
// here: this function must not be the thing that answers a user whose session
// just ended, because a 403 leaves the client retrying a write instead of
// returning them to the login page. Authentication — and the 401 — happens
// immediately after, in the auth middleware.
func ValidateCSRF(r *http.Request) bool {
if IsSafeMethod(r.Method) {
return true
}
presented := r.Header.Get(CSRFHeaderName)
if presented == "" {
return false
}
authCookie, err := r.Cookie(AuthCookieName)
if err != nil || authCookie.Value == "" {
return false
}
if sid := SessionIDFromToken(authCookie.Value); sid != "" {
if verifyCSRFToken(presented, func(nonce []byte) []byte {
return sessionCSRFSignature(sid, nonce)
}) {
return true
}
}
return verifyCSRFToken(presented, func(nonce []byte) []byte {
return tokenCSRFSignature(authCookie.Value, nonce)
})
}