Repository navigation
fix(auth): harden session refresh and logout - #119
Conversation
The refresh route ended a session only on 401, while RFC 6749 5.2 answers an expired, revoked or reused refresh token with 400 invalid_grant, and 401 with invalid_client meant a rotated client secret wiped every session. It also answered 401 to every failure. Now 400 invalid_grant and 401 (except invalid_client) end the session and delete all its cookies (401 session_ended), unless a concurrent refresh just succeeded (409). Provider, network and settings errors keep the session (503 unavailable); without a refresh token, only token_expires_at is deleted (401 no_refresh_token). A refreshed ID token must name the session's sub and iss (OIDC Core 12.2). token_expires_at now holds the real expiry and, like id_token, lives as long as the session; without a new ID token on refresh, the session's is set again. The refresh_token max-age is capped at 30 days, and the refresh route checks the Origin like the logout. Refs #111 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The refresh hook sent the tab to /auth/login on any refresh error, so a short provider outage, or a stale token_expires_at of an anonymous visitor, led to the login page, and unsaved input was lost. It also refreshed about 10 minutes early. The new refresher (src/lib/token-refresh.ts) refreshes 5 minutes before the real expiry, leaves the page only on session_ended, stops on no_refresh_token, and retries other failures with backoff (5 s, doubling, at most 5 min). All tabs of a browser share a Web Lock, so only one refreshes at a time and the others pick up its cookies. Refs #111 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A refresh whose response arrived after the logout's set the session cookies again: its guard read the request's own cookie jar, the token and user-info routes ignored logout_marker, and the logout didn't wait for refreshes in flight. The logout now stops the page's refresher and runs under the refresh lock, so it waits for a refresh in any tab. It revokes the refresh token when discovery lists a revocation_endpoint (RFC 7009), and logout_marker lives 30 days (or until the next login): the refresh, token and user-info routes refuse a session that carries it, and the refresh route deletes its cookies again. The logout also deletes oidc_provider. Closes #106 Refs #111 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The mock provider answered every refresh token grant with 200, so no end-to-end test could show how Krini handles refresh failures. /mock/refresh now sets an error status and error, and a delay, until /mock/reset; the mock also revokes refresh tokens (/oidc/revoke) and answers revoked ones with 400 invalid_grant. New tests: a session that the provider ended leads to the login page once and leaves no cookies; a provider outage keeps the session and the refresh is retried; visitors with a stale expiry stay on the page; and a refresh in flight in another tab doesn't undo the logout. Refs #111 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Login guide: how Krini handles each answer of the token endpoint to a refresh, the ID token's lifetime, the tabs' lock, the Origin check of the refresh, and what the logout does (wait, revoke, logout_marker). Helm chart guide, upgrade guide and values.yaml: with the lock, several pods no longer race; only browsers without Web Locks (or tabs of older images) can still end a session that way, which sends the user to the login page rather than "logging out". Privacy notice: the new lifetimes of id_token, token_expires_at and logout_marker, and what the marker does. Refs #111 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Refresh short-lived tokens at half their lifetime (at most 5 min before expiry): token_expires_at now stores "<expiry>:<lifetime>" in ms, so 5-minute tokens no longer refresh every 30 s in every tab. Old values without a lifetime still parse. - Cap the wait between checks at a day (setTimeout overflows at 24.8 days) and time out a refresh request after 30 s, as the lock is held meanwhile and logouts wait for it. - Treat 401 unauthorized_client like invalid_client: keep the session. - Without refresh and access token, the refresh route deletes all the session's cookies, so no ID token outlives the session. - One helper for the logout marker (hasLoggedOut, LOGOUT_MARKER) and for the cookie options; docstrings in the refresh route. - e2e: assert that the logout request goes out only after the other tab's refresh answered, instead of a fixed wait; a new test restores the session's cookies after the logout and checks that they are void; forgiveProblems() for server errors a test provokes. Refs #111 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The client's 30 s timeout equalled the refresh route's worst case (discovery, token and JWKS requests of 10 s each): the route could rotate the refresh token after the browser gave up on the answer, and the next refresh would then end the session. Wait 60 s instead. Also rewrap two comments and reword a test comment. Refs #111 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Reviewer's GuideData structuresDefine shared session-cookie lifetimes, logout-marker handling, and the OIDC revocation endpoint used by the routes.
APIHarden refresh, logout, token, and user-info endpoints, including origin checks and session invalidation.
Uses of the APIWire the shared client refresher into page lifecycle and serialize logout behind any in-flight refresh.
ImplementationImplement browser-side expiry scheduling, cross-tab locking, refresh retries, and origin validation helpers used by the routes and client.
UIUpdate the privacy page to explain the revised session-cookie and logout-marker lifetimes.
ConfigurationRevise the replica guidance to reflect browser refresh locking and the remaining multi-pod race conditions.
DocumentationDocument refresh and logout behavior, Origin requirements, cookie lifetimes, replica guidance, and the corrected registry URL.
TestsAdd route and refresher tests for failure handling, cookie semantics, origin checks, locking, revocation, and logout races.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #119 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 23 25 +2
Lines 591 699 +108
Branches 163 196 +33
==========================================
+ Hits 591 699 +108 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit 74019da #106 fix: a refresh in flight can undo the logout · 0 of 1 met
#111 fix: harden session refresh and logout · 9 of 9 met
|
There was a problem hiding this comment.
Hey - I've found 14 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/app/auth/api/callback/route.ts" line_range="44" />
<code_context>
function expireLoginArtifacts(response: NextResponse, state: string) {
response.cookies.delete(`authState-${state}`);
- response.cookies.delete("logout_marker");
+ response.cookies.delete(LOGOUT_MARKER);
}
</code_context>
<issue_to_address>
**Failed login restores logged-out access**
When a refresh restores session cookies after logout and a callback with a valid state then fails, `redirectError` calls `expireLoginArtifacts`, which deletes `LOGOUT_MARKER` without clearing the restored session cookies. The token and user-info routes then accept those cookies, so the user regains access despite having logged out.
Preserve `LOGOUT_MARKER` when cleaning up artifacts for a failed callback.
Also at `src/app/auth/api/logout/route.ts:110`.
</issue_to_address>
### Comment 2
<location path="src/app/auth/api/logout/route.ts" line_range="110" />
<code_context>
+ // may rotate the refresh token.
+ response.cookies.set(LOGOUT_MARKER, Date.now().toString(), {
+ ...baseCookieOptions(),
+ maxAge: THIRTY_DAYS_SECONDS,
});
</code_context>
<issue_to_address>
**Delayed refresh outlives logout marker**
When a refresh response restores session cookies after the logout response, the restored cookies can remain valid after `LOGOUT_MARKER` expires 30 days after logout: refresh cookies get a fresh 30-day lifetime, and access-token cookies can last longer than 30 days. The token routes then accept the session again, undoing logout.
Make the logout marker last at least as long as any session cookie a delayed refresh can restore.
Also at `src/lib/session-cookies.ts:88-91`, `src/lib/session-cookies.ts:107-135`.
</issue_to_address>
### Comment 3
<location path="src/app/auth/api/refresh/route.ts" line_range="254-260" />
<code_context>
+ // without a new ID token, the session's stays, with the session's
+ // new lifetime
+ {
+ ...response.data,
+ id_token: typeof id_token === "string" ? id_token : idToken,
+ },
+ provider.id,
+ { keepRefreshToken: true },
+ );
+ noteRefreshSuccess(refreshToken);
- return response;
</code_context>
<issue_to_address>
**Late refresh replaces a newer login**
When a refresh response for an old session arrives after another tab completes a login, `applySessionCookies` can replace the new login’s cookies with the old session’s tokens and provider, while `failure()` can clear the new session’s cookies. The browser ends up in the wrong account or logged out.
Prevent a refresh response from changing cookies after a newer login has established a session.
Also at `src/app/auth/api/callback/route.ts:44`, `src/app/auth/api/refresh/route.ts:59`.
</issue_to_address>
### Comment 4
<location path="src/app/auth/api/token/route.ts" line_range="7-9" />
<code_context>
export async function GET() {
const cookieStore = await cookies();
- const accessToken = cookieStore.get("access_token")?.value;
+ const accessToken = hasLoggedOut(cookieStore)
+ ? undefined
+ : cookieStore.get("access_token")?.value;
if (!accessToken) {
</code_context>
<issue_to_address>
**Legacy pods accept logged-out cookies**
When old and new pods overlap and a legacy tab’s refresh response sets session cookies after a logout, the marker checks in these handlers only protect requests served by updated pods. If an older pod’s in-flight refresh restores session cookies after logout during a rolling upgrade, its token and user-info handlers ignore the marker and accept those cookies, so requests routed to that pod still see the user as logged in.
Account for marker-unaware pods during rollout, or ensure logout cannot be overtaken by refreshes from legacy clients until those pods have drained.
Also at `src/app/auth/api/user-info/route.ts:13-15`.
</issue_to_address>
### Comment 5
<location path="src/app/auth/api/refresh/route.ts" line_range="137" />
<code_context>
+ provider,
+ null,
+ );
+ if (!payload) {
+ console.error(
+ `OIDC refresh error: category=id_token_validation_failed, endpoint=${endpoints.tokenEndpoint}`,
</code_context>
<issue_to_address>
**Rotation lost on validation failure**
When the provider rotates the refresh token but ID-token validation fails transiently, the provider can rotate and invalidate the submitted refresh token in a successful response, but `validateIdToken` can fail transiently (for example, while JWKS is unavailable). The route returns `unavailable` before `applySessionCookies` stores the rotated token; a retry then sends the invalidated token, gets `invalid_grant`, and ends the session.
Preserve a rotated refresh token from an otherwise successful provider response before returning a retryable validation failure, while continuing to reject the unvalidated ID token and access token.
</issue_to_address>
### Comment 6
<location path="src/app/auth/api/refresh/route.ts" line_range="202-203" />
<code_context>
);
+ } catch (err) {
+ logTokenError("OIDC refresh error", err, endpoints.tokenEndpoint);
+ if (!refreshTokenRejected(err)) {
+ return failure("unavailable", "Failed to refresh token");
+ }
+ if (refreshSucceededRecently(refreshToken)) {
</code_context>
<issue_to_address>
**Rotated refresh token is lost**
When the provider rotates and invalidates the old refresh token, but its response times out after processing or contains an invalid token response, the route returns `unavailable` without saving the provider's rotated refresh token. The browser retries with the old token, which the provider rejects as `invalid_grant`, so the route ends the session and sends the user to login.
Use provider-supported rotation grace or idempotency for ambiguous refresh outcomes, and handle invalid responses without leaving the browser with only the consumed refresh token.
Also at `src/app/auth/api/refresh/route.ts:213-218`, `src/app/auth/api/refresh/route.ts:231-235`.
</issue_to_address>
### Comment 7
<location path="src/app/auth/api/logout/route.ts" line_range="72" />
<code_context>
let endSessionUrl: string | null = null;
if (provider) {
const endpoints = await getEndpoints(provider);
+ if (endpoints?.revocationEndpoint && refreshToken) {
+ await revokeRefreshToken(
+ endpoints.revocationEndpoint,
</code_context>
<issue_to_address>
**Provider logout failures go unnoticed**
When the provider’s discovery request fails during logout, `getEndpoints` returns null when discovery fails, so the endpoint checks are skipped and logout still returns success without a log. The provider session remains active, and a later login can silently sign the user back in.
Log discovery failure during logout and make the response or UI distinguish local logout from failure to end the provider session.
</issue_to_address>
### Comment 8
<location path="src/app/auth/api/refresh/route.ts" line_range="211" />
<code_context>
+ return failure("session_ended", "Failed to refresh token");
+ }
- const { access_token, id_token } = response.data;
+ const { access_token, id_token } = response.data;
</code_context>
<issue_to_address>
**Malformed response crashes refresh**
When the token endpoint responds with HTTP 200 and a JSON `null` body, `response.data` is `null`, so destructuring `access_token` throws outside the token-request `try` block; the route returns an unhandled 500 instead of the documented 503 `unavailable`, and the user sees a server error.
Validate that `response.data` is a non-null object before destructuring and return the invalid-response failure otherwise.
</issue_to_address>
### Comment 9
<location path="src/app/auth/api/refresh/route.ts" line_range="255" />
<code_context>
+ // new lifetime
+ {
+ ...response.data,
+ id_token: typeof id_token === "string" ? id_token : idToken,
+ },
+ provider.id,
</code_context>
<issue_to_address>
**Older sessions lose user identity**
When a session created by an older image has outlived its ID-token cookie and the provider omits an ID token on refresh, `idToken` is undefined, so `applySessionCookies` sets no ID-token cookie when the provider omits one. `getUserSession` then cannot match the user-info subject and returns no session, so a refreshed session from an older image no longer identifies its user.
Handle sessions without either an existing or newly issued ID token explicitly, rather than returning a successful refresh that cannot identify the user.
</issue_to_address>
### Comment 10
<location path="src/app/auth/api/refresh/route.ts" line_range="205-260" />
<code_context>
+ if (refreshSucceededRecently(refreshToken)) {
</code_context>
<issue_to_address>
**Lost refresh response ends session**
When a rotating provider accepts the refresh but the response is lost before the browser receives its cookies, the provider rotates the refresh token and Krini records the success, but a lost HTTP response leaves the browser holding the old token. Retried requests receive `concurrent_refresh` without the replacement cookies; after the success window expires, the retry ends the session and redirects the user to login.
Make retries recover the successful result, for example by temporarily retaining and replaying the replacement-cookie result for that refresh token.
Also at `src/lib/token-refresh.ts:178`.
</issue_to_address>
### Comment 11
<location path="src/lib/session-cookies.ts" line_range="107" />
<code_context>
});
+ } else if (options.keepRefreshToken) {
+ // not rotated: the refresh token's remaining lifetime is unknown
+ sessionMaxAge = THIRTY_DAYS_SECONDS;
+ } else {
+ response.cookies.delete("refresh_token");
</code_context>
<issue_to_address>
**Identity cookie outlives session**
When a provider omits both `refresh_token` and `refresh_expires_in` on refresh, while the existing refresh cookie has a finite remaining lifetime, `applySessionCookies` gives the ID token a 30-day lifetime when a refresh omits a new refresh token, but leaves the existing refresh cookie’s earlier expiry unchanged. After that cookie expires, the session can end while the ID token remains in the browser for up to 30 days.
Preserve the known session end across refreshes, or otherwise ensure the ID token expires no later than the refresh/access session.
</issue_to_address>
### Comment 12
<location path="src/lib/token-refresh.ts" line_range="169-173" />
<code_context>
+ scheduleNext();
+ return;
+ }
+ if (result.status === 401) {
+ // `no_refresh_token`: the server deleted `token_expires_at`,
+ // and the access token, if any, stays until it expires
+ if (result.code === "session_ended") deps.onSessionEnded();
+ return;
+ }
+ // the provider is unavailable, a concurrent refresh won, or no
</code_context>
<issue_to_address>
**Legacy refresh errors stop retries**
When a new client sends a refresh to an old server during a rolling upgrade and that server answers a transient failure with its legacy generic 401, a legacy server returns a generic 401 without a `code` for a transient refresh failure. The client returns without scheduling a retry or leaving the page, so the access token eventually expires and the session stays unusable until another page load or login.
Treat an unrecognized 401 response as transient during compatibility windows, or version the refresh response contract so the client can distinguish legacy failures.
</issue_to_address>
### Comment 13
<location path="e2e/session.spec.ts" line_range="127" />
<code_context>
+
+ // e.g. a browser without Web Locks: a refresh that the logout
+ // overtook sets the session's cookies again
+ await context.addCookies(session);
+ expect((await page.request.get("/auth/api/token")).status()).toBe(401);
+ expect((await page.request.get("/auth/api/user-info")).status()).toBe(401);
</code_context>
<issue_to_address>
**Exercise the response race**
The test restores pre-logout cookies after logout and verifies that the marker makes them unusable. It does not reproduce the requested ordering of a logout response followed by an in-flight refresh response; add a regression test that exercises that ordering.
</issue_to_address>
### Comment 14
<location path="src/lib/request-origin.ts" line_range="19" />
<code_context>
+ { status: 500 },
+ );
+ }
+ if (req.headers.get("origin") !== appOrigin) {
+ return NextResponse.json(
+ { error: "Invalid request origin" },
</code_context>
<issue_to_address>
**Deployment guide omits refresh protection**
Operators reading the Origin validation section see only the logout endpoint described as checking `APP_ORIGIN`, while this check also protects refresh requests; the deployment guide therefore gives an incomplete account of the app's CSRF protections.
Update the deployment guide's Origin validation section to include the refresh endpoint.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 13 findings to address first, and if the refresh or logout checks mishandle a session, someone could retain access or be logged out, and logout may also revoke the provider’s refresh token. Reverting restores the old code but cannot undo access already used or restore a refresh token the provider revoked.
Blocking findings: src/app/auth/api/callback/route.ts:44, src/app/auth/api/logout/route.ts:110, src/app/auth/api/refresh/route.ts:260, src/app/auth/api/token/route.ts:9, src/app/auth/api/refresh/route.ts:137, and 8 more
Keep the logout marker on failed logins, cap the access token cookie at 30 days so the marker outlives every session cookie, keep a rotated refresh token when the rest of the token response is invalid, reject non-object token responses with 503, end sessions that would be left without an ID token, and retry plain 401s from pods of older versions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Helm chart example set cloudRegistryUrl to the registry's host; Krini needs the base URL of the GA4GH Service Registry API. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The security recommendations in the deployment guide named only the logout endpoint as checked against APP_ORIGIN; since #119, token refreshes are checked the same way (rejectForeignOrigin). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Fixes the session handling findings of the 0.1.0 pre-release review (#111), including #106.
Refresh route (
POST /auth/api/refresh), per RFC 6749 §5.2:invalid_grant(expired, revoked, reused refresh token)session_ended, all session cookies deleted (409concurrent_refreshwithin the replay window)invalid_client)invalid_grantinvalid_client(rotated secret), 5xx, timeouts, discovery or token response errorsunavailable, session kept, error loggedtoken_expires_atof a visitor)no_refresh_token, onlytoken_expires_atdeleted, no redirectsub/isssession_ended(OIDC Core 12.2)The route also checks the
Originlike the logout (sharedrejectForeignOrigin()).Client (
src/lib/token-refresh.ts, used byuseTokenRefresh): refreshes 5 minutes before the real expiry, or at half the token lifetime if shorter (no double margin;token_expires_atis now<expiry>:<lifetime>in ms), leaves the page only onsession_ended, stops onno_refresh_token, retries everything else with backoff (5 s, doubling, max 5 min). All tabs share a Web Lock, so only one refreshes at a time (this also removes the multi-pod race of #93/#107 for browsers with Web Locks).Logout: stops the page's refresher and runs under the same lock, so it waits for a refresh in flight in any tab; revokes the refresh token when discovery lists a
revocation_endpoint(RFC 7009);logout_markernow lives 30 days (or until the next login), and the refresh, token and user-info routes refuse a session that carries it, so cookies restored by an overtaken refresh are void. The logout now also deletesoidc_provider.Cookies:
token_expires_atholds the real expiry; it andid_tokenlive as long as the session (refresh token lifetime, max 30 days; access token lifetime without a refresh token); without a new ID token on refresh, the session's is set again.refresh_tokenmax-age is capped at 30 days, as the privacy notice says.Tests: unit tests for every status mapping, the cookie lifetimes, Origin check, revocation, logout marker, and the refresher (timing, backoff, lock, stop during a refresh). The e2e mock gets a refresh failure mode (
/mock/refresh: status, error, delay) and token revocation; five new Playwright tests ine2e/session.spec.ts.Docs:
login.md(Sessions and logout, with a table of the answers),helm-chart.md(Pods),upgrading.md,configuration.md(APP_ORIGIN),deployment/values.yaml(replicas), privacy notice (lifetimes,logout_marker).Not in this PR:
docs/operator-guide/deployment.md("Origin validation" mentions only the logout) is left to the security headers PR, which owns that file.Verification
bun run lint(biome check): cleanbunx next typegen && bunx tsc --noEmit: cleannpx vitest run --coverage: 346 tests passed (after mergingdev), 100 % coveragenpx playwright test --project chromium: 24 passed after mergingdev(incl. 5 new ine2e/session.spec.ts), with no CSP violations under the fixture from fix: send security response headers #120mkdocs build --strict: cleandev, 74019da): all checks pass, includingCI passed, e2e on Chromium, Firefox and the image, chart install, CodeQL, Trivy, Codecov, Read the Docs, Sourcery and Vercel.Declined review findings
Two review rounds (adversarial + quality); all high/medium findings fixed (relative refresh margin for short-lived tokens, e2e ordering assertion instead of a fixed wait, overtaken-refresh e2e test, shared marker/cookie helpers,
unauthorized_client, refresh timeout 60 s, daily check cap, no cookie outliving an ended session). Declined:Unit tests for
useTokenRefreshand the sidebar logout handler (quality, medium): the repo has no React component test stack, and coverage is scoped tosrc/liband the routes by design. The logic lives insrc/lib/token-refresh.ts(unit-tested to 100 %), the hook only wires browser APIs, and the logout path is covered end to end.End the session on 401 only with
invalid_grant/invalid_token(adversarial, low): a 401 without anerrorbody still ends the session, as some providers answer bad refresh tokens that way and fix: harden session refresh and logout #111 asks for it;invalid_clientandunauthorized_clientkeep it.Store the session's end time for non-rotating refreshes (adversarial, low): handled more simply: once neither refresh nor access token is left, the refresh route deletes all session cookies.
Unit test that a timed-out refresh request returns status 0 (quality, low): the timeout signal is asserted, and a rejected fetch returning status 0 is tested; faking
AbortSignal.timeoutadds little.Exact count of 503s in the outage e2e test (quality, low): the retry count isn't deterministic; the test checks the first answer was 503 and that the retry renewed the token.
Sourcery review: fixed the failed-login marker, the 30-day cap of the access token cookie, rotated refresh tokens in invalid responses, non-object responses, sessions left without an ID token and plain 401s from older pods (6b7aec7). Declined, with reasons in the threads: a late refresh overtaking a new login in another tab (needs a session generation id), marker-unaware old pods during a rolling upgrade (rollout window only), lost responses with rotating providers (needs server state; provider reuse grace covers it), distinguishing a failed provider logout in the UI, the unknown remaining lifetime of a non-rotated refresh token, and an e2e reproduction of the response race (both halves are covered). The
deployment.mdOrigin note is left for a follow-up, as that file was owned by another PR.Unrelated fixes
docs/operator-guide/helm-chart.md: the examplecloudRegistryUrlnow has the API path (/ga4gh/registry/v1).Open questions
None.
Closes #111
Closes #106
Refs #93, #107
🤖 Generated with Claude Code