mirror of
https://gh-proxy.org/https://github.com/klinsmaya/multica.git
synced 2026-11-09 09:56:47 +08:00
* 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]>
256 lines
10 KiB
Go
256 lines
10 KiB
Go
package auth
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
// Sliding session renewal (MUL-7436).
|
|
//
|
|
// A UI session token used to have its lifetime fixed at login: `exp` was
|
|
// stamped once and never moved, so every continuously active user was logged
|
|
// out on a schedule — 30 days after login, always while they were mid-task.
|
|
// Renewal turns that into an IDLE bound instead: a token inside its renewal
|
|
// window is re-signed with a fresh `exp` on the next authenticated request.
|
|
//
|
|
// The model is deliberately stateless. Renewal copies the identity claims of
|
|
// a token we ourselves signed and moves `exp`; there is no session row, no
|
|
// refresh token, and no DB read on the hot path. What that buys in
|
|
// simplicity it gives up in revocation — which the JWT path never had
|
|
// anyway (logout clears the cookie; the token itself stays valid until
|
|
// `exp`). Real revocation needs server-side session records and is tracked
|
|
// separately.
|
|
//
|
|
// The idle bound is approximate, and the approximation is one-sided: a
|
|
// session is renewed only once it drops below half its TTL, so the guarantee
|
|
// is "at least TTL/2 of idleness is survivable", not "exactly TTL after the
|
|
// last request". A token signed on day 0 and last used on day 14 was not yet
|
|
// eligible, so it still expires on day 30 — 16 idle days, not 30. Sessions
|
|
// used at any point inside the second half of their lifetime get the full
|
|
// TTL from that moment.
|
|
|
|
const (
|
|
// sessionIDClaim carries a per-login identifier that is STABLE across
|
|
// renewals and changes only when the user authenticates again. It is
|
|
// what the CSRF token is bound to, so re-signing the auth cookie does
|
|
// not invalidate CSRF tokens other tabs are already holding.
|
|
sessionIDClaim = "sid"
|
|
|
|
// sessionRenewCheckDivisor derives the client-side re-check cadence
|
|
// from the configured TTL: a client that checks every TTL/10 gets
|
|
// roughly five attempts inside the renewal window, so several
|
|
// consecutive failures still leave the session recoverable. At the
|
|
// default 30-day TTL this is 3 days, matching the daemon's PAT
|
|
// renewal cadence (DefaultTokenRenewalInterval).
|
|
sessionRenewCheckDivisor = 10
|
|
|
|
// minSessionRenewCheckInterval is a pure anti-busy-loop floor, not a
|
|
// policy. With MinAuthTokenTTL enforced the smallest cadence this can
|
|
// ever produce is six seconds, so this floor never actually binds; it
|
|
// stays as a backstop, and the window cap below outranks it either way,
|
|
// because an interval that cannot fit inside the renewal window is not a
|
|
// cadence, it is a guaranteed logout.
|
|
//
|
|
// Every client floor must be at or below this value, or the client would
|
|
// silently override a cadence the server chose for correctness. See
|
|
// packages/core/platform/session-renewal.ts and
|
|
// apps/mobile/data/session-renewal.ts.
|
|
minSessionRenewCheckInterval = 5 * time.Second
|
|
|
|
// maxSessionRenewCheckInterval bounds the other end: a client that has
|
|
// not asked in a week is far enough from its own state that checking is
|
|
// cheap insurance, whatever the TTL says.
|
|
maxSessionRenewCheckInterval = 7 * 24 * time.Hour
|
|
)
|
|
|
|
// ErrNotSessionToken is returned by RenewSessionToken when handed something
|
|
// that is not one of our own UI session JWTs. PATs (mul_), agent task tokens
|
|
// (mat_) and cloud-node PATs (mcn_) authenticate fine at the middleware but
|
|
// must never be exchanged for an interactive session.
|
|
var ErrNotSessionToken = errors.New("not an interactive session token")
|
|
|
|
// AuthRenewThreshold is the remaining lifetime at or below which a session
|
|
// token becomes eligible for renewal. Half the TTL is the largest threshold
|
|
// that still leaves renewal rare (one re-sign per TTL/2 of continuous use)
|
|
// while giving an intermittently used client a window measured in days
|
|
// rather than minutes to land a successful renewal.
|
|
func AuthRenewThreshold() time.Duration { return AuthTokenTTL() / 2 }
|
|
|
|
// SessionRenewCheckInterval is how long a token-mode client should wait
|
|
// before asking whether its session is renewable again. Derived from the
|
|
// configured TTL so a deployment that shortens AUTH_TOKEN_TTL automatically
|
|
// gets proportionally more frequent checks — clients must never hardcode a
|
|
// cadence tuned for the 30-day default.
|
|
//
|
|
// The cadence has one hard requirement: it must fit inside the renewal
|
|
// window, or a client that follows it can miss the window entirely and be
|
|
// logged out while actively using the app. Capping at half the threshold
|
|
// guarantees at least two attempts inside it, so a single failed check is
|
|
// never fatal. That cap is applied last, after both clamps, because it is
|
|
// the correctness constraint and they are only guard rails.
|
|
func SessionRenewCheckInterval() time.Duration {
|
|
interval := AuthTokenTTL() / sessionRenewCheckDivisor
|
|
if interval < minSessionRenewCheckInterval {
|
|
interval = minSessionRenewCheckInterval
|
|
}
|
|
if interval > maxSessionRenewCheckInterval {
|
|
interval = maxSessionRenewCheckInterval
|
|
}
|
|
if cap := AuthRenewThreshold() / 2; interval > cap {
|
|
interval = cap
|
|
}
|
|
return interval
|
|
}
|
|
|
|
// ShouldRenewSession reports whether a token expiring at expiresAt is inside
|
|
// the renewal window at now.
|
|
//
|
|
// An already-expired token is never renewable: `exp` in the past means the
|
|
// credential is dead, and renewal must not be a way to resurrect one. The
|
|
// middleware rejects those before this is ever reached; this is the second
|
|
// lock on the same door.
|
|
func ShouldRenewSession(now, expiresAt time.Time) bool {
|
|
if expiresAt.IsZero() {
|
|
return false
|
|
}
|
|
remaining := expiresAt.Sub(now)
|
|
if remaining <= 0 {
|
|
return false
|
|
}
|
|
return remaining <= AuthRenewThreshold()
|
|
}
|
|
|
|
// NewSessionID mints the per-login identifier stamped into the `sid` claim.
|
|
func NewSessionID() (string, error) {
|
|
b := make([]byte, 16)
|
|
if _, err := rand.Read(b); err != nil {
|
|
return "", fmt.Errorf("generate session id: %w", err)
|
|
}
|
|
return hex.EncodeToString(b), nil
|
|
}
|
|
|
|
// SessionExpiry reads the `exp` claim as a time. Zero when absent or
|
|
// malformed — callers treat that as "not renewable" rather than "never
|
|
// expires", because a session token we signed always has one.
|
|
func SessionExpiry(claims jwt.MapClaims) time.Time {
|
|
exp, err := claims.GetExpirationTime()
|
|
if err != nil || exp == nil {
|
|
return time.Time{}
|
|
}
|
|
return exp.Time
|
|
}
|
|
|
|
func parseSignedToken(tokenString string, opts ...jwt.ParserOption) (jwt.MapClaims, error) {
|
|
token, err := jwt.Parse(tokenString, func(t *jwt.Token) (any, error) {
|
|
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, jwt.ErrSignatureInvalid
|
|
}
|
|
return JWTSecret(), nil
|
|
}, opts...)
|
|
if err != nil || !token.Valid {
|
|
return nil, ErrNotSessionToken
|
|
}
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|
if !ok {
|
|
return nil, ErrNotSessionToken
|
|
}
|
|
return claims, nil
|
|
}
|
|
|
|
// ParseSessionToken verifies a raw token string as one of our UI session
|
|
// JWTs and returns its claims. Anything that is not a validly signed,
|
|
// unexpired HS256 JWT — including every opaque token prefix — comes back as
|
|
// ErrNotSessionToken.
|
|
//
|
|
// This is the AUTHENTICATION parser: use it wherever the answer decides
|
|
// whether the caller is logged in or whether a session may be extended.
|
|
func ParseSessionToken(tokenString string) (jwt.MapClaims, error) {
|
|
return parseSignedToken(tokenString)
|
|
}
|
|
|
|
// SessionIDFromToken returns the `sid` claim of a token we signed, or "" for
|
|
// anything else — an opaque PAT, a forged string, or one of the pre-MUL-7436
|
|
// JWTs minted before the claim existed. "" is the signal to fall back to the
|
|
// legacy CSRF binding; see ValidateCSRF.
|
|
//
|
|
// Expiry is deliberately NOT enforced here, and that distinction is
|
|
// load-bearing. This function answers "which session does this cookie
|
|
// belong to", not "may this cookie authenticate" — the signature alone
|
|
// settles the first question, and the auth middleware settles the second a
|
|
// few lines later. Enforcing expiry here instead meant an EXPIRED cookie
|
|
// lost its `sid`, so its perfectly valid CSRF token failed to verify and the
|
|
// user's first action after expiry was answered with 403 "CSRF validation
|
|
// failed" rather than the 401 that ends the session and sends them to the
|
|
// login page. A rejected CSRF token must never be how a user learns their
|
|
// session ended.
|
|
func SessionIDFromToken(tokenString string) string {
|
|
claims, err := parseSignedToken(tokenString, jwt.WithoutClaimsValidation())
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
sid, _ := claims[sessionIDClaim].(string)
|
|
return sid
|
|
}
|
|
|
|
// RenewSessionToken re-signs the identity carried by claims with a fresh
|
|
// lifetime, returning the new token and its expiry.
|
|
//
|
|
// Only `exp` and `iat` move. `sub`, `email`, `name` and `sid` are copied
|
|
// forward verbatim, which is what makes renewal free of any database read:
|
|
// the claims were signed by this server, so they are already authoritative
|
|
// for exactly the fields the auth middleware reads back out.
|
|
//
|
|
// A pre-MUL-7436 token carries no `sid`. Renewal mints one, which is the
|
|
// migration path for sessions that predate this code — and the one moment
|
|
// where a CSRF token already read by another tab stops matching. It happens
|
|
// once per legacy session, on a safe-method request; clients retry a CSRF
|
|
// rejection once (packages/core/api/client.ts).
|
|
func RenewSessionToken(claims jwt.MapClaims) (string, time.Time, error) {
|
|
sub, _ := claims["sub"].(string)
|
|
if sub == "" {
|
|
return "", time.Time{}, ErrNotSessionToken
|
|
}
|
|
email, _ := claims["email"].(string)
|
|
|
|
// A user disabled since their token was signed must not have that token
|
|
// extended — renewal is the one place a live session's lifetime is
|
|
// decided after login, so the check belongs here as much as at issuance.
|
|
if IsTemporarilyDisabledUser(sub, email) {
|
|
return "", time.Time{}, ErrTemporarilyDisabledUser
|
|
}
|
|
|
|
sid, _ := claims[sessionIDClaim].(string)
|
|
if sid == "" {
|
|
var err error
|
|
if sid, err = NewSessionID(); err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
}
|
|
|
|
now := time.Now()
|
|
expiresAt := now.Add(AuthTokenTTL())
|
|
next := jwt.MapClaims{
|
|
"sub": sub,
|
|
"exp": expiresAt.Unix(),
|
|
"iat": now.Unix(),
|
|
sessionIDClaim: sid,
|
|
}
|
|
if email != "" {
|
|
next["email"] = email
|
|
}
|
|
if name, ok := claims["name"].(string); ok && name != "" {
|
|
next["name"] = name
|
|
}
|
|
|
|
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, next).SignedString(JWTSecret())
|
|
if err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
return signed, expiresAt, nil
|
|
}
|