Sign-in finishes on any replica #113

Merged
jcoffey-dev merged 1 commits from fix/signin-across-replicas into main 2026-11-18 21:59:21 +00:00
4 changed files with 86 additions and 28 deletions

No files matched your search

+4 -4
View File
@@ -591,14 +591,14 @@ export function createApp(basePath = config.basePath): Hono<Env> {
if (refused) return c.redirect(`${basePath}/?account_error=${refused}`, 302);
}
try {
const { location, state } = await startSignIn({
const { location, cookie } = await startSignIn({
username,
base: upstreamFor(username),
remember: c.req.query("remember") === "1",
adding: front !== null,
theme: signInTheme(c.req.query("theme")),
});
setCookie(c, OAUTH_STATE_COOKIE, state, { httpOnly: true, sameSite: "Lax", secure: isSecureRequest(c), path: `${basePath}/api/auth`, maxAge: 600 });
setCookie(c, OAUTH_STATE_COOKIE, cookie, { httpOnly: true, sameSite: "Lax", secure: isSecureRequest(c), path: `${basePath}/api/auth`, maxAge: 600 });
return c.redirect(location, 302);
} catch (err) {
console.warn("[ihasmail] could not start sign-in:", failureReason(err));
@@ -608,7 +608,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
api.get("/auth/callback", async (c) => {
if (!oauthEnabled()) return c.json({ error: "not_found" }, 404);
const boundState = getCookie(c, OAUTH_STATE_COOKIE);
const boundCookie = getCookie(c, OAUTH_STATE_COOKIE);
deleteCookie(c, OAUTH_STATE_COOKIE, { path: `${basePath}/api/auth` });
const fail = (code: string) => c.redirect(`${basePath}/?signin_error=${code}`, 302);
const rateIp = rateLimitKey(clientIp(c));
@@ -619,7 +619,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
if (!code || c.req.query("error")) return fail("cancelled");
let result;
try {
result = await finishSignIn({ state, boundState, code });
result = await finishSignIn({ state, boundCookie, code });
} catch (err) {
if (err instanceof SignInError) return fail(err.code);
console.warn("[ihasmail] sign-in exchange failed:", failureReason(err));
Binary file not shown.
+44 -5
View File
@@ -116,7 +116,12 @@ test("start sends the browser to the server's page with PKCE and a bound state",
assert.match(to.searchParams.get("code_challenge") ?? "", /^[\w-]{43}$/);
assert.equal(to.searchParams.get("login_hint"), "[email protected]");
assert.equal(to.searchParams.get("scope"), "openid offline_access");
assert.equal(jar.get("ihm_session_signin"), to.searchParams.get("state"), "the state is bound to this browser");
// The state, bound to this browser, and the sign-in in progress, sealed:
// nothing in it (the PKCE verifier, the address) is readable
const bound = jar.get("ihm_session_signin")!;
assert.ok(bound.startsWith(`${to.searchParams.get("state")}.`), "the state is bound to this browser");
assert.ok(!bound.includes("demo"));
assert.ok(bound.length < 1024, `the cookie is ${bound.length} bytes`);
});
test("start passes on the light or dark look for the server's page, and nothing else", async () => {
@@ -151,13 +156,47 @@ test("a callback from a sign-in this browser didn't start is refused", async ()
assert.equal(jar.get("ihm_session"), undefined);
});
test("a state is good for one attempt", async () => {
test("a sign-in is good for one attempt", async () => {
const back = await goToServerAndBack();
const state = jar.get("ihm_session_signin")!;
const bound = jar.get("ihm_session_signin")!;
await call(`/api/auth/callback${back.search}`);
jar = new Map([["ihm_session_signin", state]]);
// The callback deleted the cookie; a copy of it, replayed with the same
// code, finds the code spent at the server
jar = new Map([["ihm_session_signin", bound]]);
const again = await call(`/api/auth/callback${back.search}`);
assert.equal(again.headers.get("location"), "/?signin_error=state_mismatch");
assert.equal(again.headers.get("location"), "/?signin_error=exchange_failed");
assert.equal(jar.get("ihm_session"), undefined);
});
test("the sign-in rides in the browser's cookie, so another replica can finish it", async () => {
const back = await goToServerAndBack();
// What this process remembered of the sign-in is gone, as on a replica
// that never saw the start
resetOAuthState();
const res = await call(`/api/auth/callback${back.search}`);
assert.equal(res.headers.get("location"), "/");
assert.ok(jar.get("ihm_session"));
});
test("a state cookie that was altered, or names another state, is refused", async () => {
const back = await goToServerAndBack();
const bound = jar.get("ihm_session_signin")!;
const dot = bound.indexOf(".");
const sealed = bound.slice(dot + 1);
const flipped = sealed.slice(0, -2) + (sealed.at(-2) === "A" ? "B" : "A") + sealed.at(-1);
const state = bound.slice(0, dot);
// A changed byte, a stray character, and the state alone with nothing sealed
for (const cookie of [`${state}.${flipped}`, `${state}.${sealed}x`, state]) {
jar = new Map([["ihm_session_signin", cookie]]);
const res = await call(`/api/auth/callback${back.search}`);
assert.equal(res.headers.get("location"), "/?signin_error=state_mismatch", cookie.slice(0, 20));
}
// The genuine cookie for a different state than the URL's
await call("/api/auth/oauth/[email protected]");
const other = jar.get("ihm_session_signin")!;
jar = new Map([["ihm_session_signin", other]]);
const res = await call(`/api/auth/callback${back.search}`);
assert.equal(res.headers.get("location"), "/?signin_error=state_mismatch");
});
test("cancelling on the server's page comes back as an error, not a session", async () => {
+38 -19
View File
@@ -26,7 +26,7 @@
*/
import { createHash } from "node:crypto";
import { config } from "./config.js";
import { randomToken } from "./crypto.js";
import { open, randomToken, safeEqual, seal, signInKey } from "./crypto.js";
import { UpstreamError, absoluteUpstream } from "./upstream.js";
export interface TokenSet {
@@ -49,7 +49,6 @@ export const REFRESH_MARGIN_MS = 5 * 60_000;
/** How long a sign-in may take between leaving and coming back. */
const PENDING_TTL_MS = 10 * 60_000;
const METADATA_TTL_MS = 60 * 60_000;
const MAX_PENDING = 10_000;
export function oauthEnabled(): boolean {
return Boolean(config.oauthClientSecret);
@@ -96,7 +95,13 @@ async function metadataFor(base: string): Promise<Metadata> {
return metadata;
}
/**
* A sign-in between leaving for the server's page and coming back. It travels
* sealed in the browser's state cookie rather than in this process, so the
* callback can land on any replica that holds the same APP_SECRET (K-C3).
*/
interface Pending {
state: string;
verifier: string;
base: string;
username: string;
@@ -106,10 +111,26 @@ interface Pending {
createdAt: number;
}
const pending = new Map<string, Pending>();
/** The state cookie: `<state>.<the pending sign-in, sealed>`. */
function sealPending(p: Pending): string {
return `${p.state}.${seal(JSON.stringify(p), signInKey(config.appSecret))}`;
}
function sweepPending(now = Date.now()) {
for (const [state, p] of pending) if (now - p.createdAt > PENDING_TTL_MS) pending.delete(state);
/** The pending sign-in a state cookie holds, under the current key or a retired one. */
function openPending(cookie: string): Pending | null {
const dot = cookie.indexOf(".");
if (dot < 1) return null;
const sealed = cookie.slice(dot + 1);
for (const secret of [config.appSecret, ...config.appSecretPrevious]) {
const json = open(sealed, signInKey(secret));
if (json === null) continue;
try {
return JSON.parse(json) as Pending;
} catch {
return null;
}
}
return null;
}
function challengeOf(verifier: string): string {
@@ -117,16 +138,14 @@ function challengeOf(verifier: string): string {
}
/**
* Begin a sign-in. Returns where to send the browser, and the state to bind
* to it in a cookie.
* Begin a sign-in. Returns where to send the browser, and the cookie that
* binds the sign-in to it: the state, and the pending sign-in sealed.
*/
export async function start(params: { username: string; base: string; remember: boolean; adding?: boolean; theme?: "light" | "dark" }): Promise<{ location: string; state: string }> {
export async function start(params: { username: string; base: string; remember: boolean; adding?: boolean; theme?: "light" | "dark" }): Promise<{ location: string; cookie: string }> {
const metadata = await metadataFor(params.base);
sweepPending();
if (pending.size >= MAX_PENDING) throw new UpstreamError("Too many sign-ins in progress", 503);
const state = randomToken(24);
const verifier = randomToken(48);
pending.set(state, { verifier, base: params.base, username: params.username, remember: params.remember, adding: Boolean(params.adding), createdAt: Date.now() });
const cookie = sealPending({ state, verifier, base: params.base, username: params.username, remember: params.remember, adding: Boolean(params.adding), createdAt: Date.now() });
const scope = ["openid", "offline_access"].filter((s) => metadata.scopes.length === 0 || metadata.scopes.includes(s)).join(" ");
const url = new URL(metadata.authorizationEndpoint);
url.searchParams.set("response_type", "code");
@@ -143,7 +162,7 @@ export async function start(params: { username: string; base: string; remember:
// inbuxa-server #375: the server's page shows the light or dark look the
// reader has here; a server that doesn't know the parameter ignores it
if (params.theme) url.searchParams.set("theme", params.theme);
return { location: url.toString(), state };
return { location: url.toString(), cookie };
}
/**
@@ -186,15 +205,16 @@ export class SignInError extends Error {
}
/**
* Finish a sign-in: `state` as it came back in the URL, `boundState` as the
* browser's cookie holds it. Each state is good for one attempt.
* Finish a sign-in: `state` as it came back in the URL, `boundCookie` as the
* browser's state cookie holds it. The callback deletes the cookie, and the
* server takes each code once and only with this sign-in's PKCE verifier, so
* each sign-in is good for one attempt.
*/
export async function finish(params: { state: string; boundState: string | undefined; code: string }): Promise<{ tokens: TokenSet; base: string; username: string; remember: boolean; adding: boolean }> {
const p = pending.get(params.state);
if (!p || !params.boundState || params.boundState !== params.state) {
export async function finish(params: { state: string; boundCookie: string | undefined; code: string }): Promise<{ tokens: TokenSet; base: string; username: string; remember: boolean; adding: boolean }> {
const p = params.boundCookie ? openPending(params.boundCookie) : null;
if (!p || typeof p.state !== "string" || !params.state || !safeEqual(p.state, params.state)) {
throw new SignInError("state_mismatch", "This sign-in didn't start in this browser. Try again.");
}
pending.delete(params.state);
if (Date.now() - p.createdAt > PENDING_TTL_MS) throw new SignInError("expired", "The sign-in took too long. Try again.");
const metadata = await metadataFor(p.base);
const tokens = await tokenRequest(metadata.tokenEndpoint, {
@@ -283,6 +303,5 @@ export function needsRefresh(tokens: TokenSet, now = Date.now()): boolean {
/** For tests. */
export function resetOAuthState(): void {
pending.clear();
metadataCache.clear();
}