From 2bdce907763174a493b9124a8f80be73b9838dc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=85=E8=86=80?= Date: Fri, 23 Oct 2026 23:22:52 +0800 Subject: [PATCH] fix(auth): revoke stale sessions and tokens Revoked or rotated credentials must stop working despite stale KV replicas. Track the live token and revocations in D1 and preserve immutable identity bindings rather than trusting a recycled login. --- server/lib/github/oauth.ts | 19 ++-- server/lib/github/store.ts | 216 ++++++++++++++++++++++++++++++++++++- server/lib/web/actions.ts | 2 +- server/lib/web/auth.ts | 3 +- server/lib/web/session.ts | 67 ++++++++++-- 5 files changed, 285 insertions(+), 22 deletions(-) diff --git a/server/lib/github/oauth.ts b/server/lib/github/oauth.ts index 69a37a7..78e89f7 100644 --- a/server/lib/github/oauth.ts +++ b/server/lib/github/oauth.ts @@ -1,5 +1,5 @@ import { Octokit } from "octokit"; -import { saveToken, getToken } from "./store"; +import { saveToken, getToken, type TokenSource } from "./store"; export function getOAuthURL(clientId: string, state: string): string { // `read:org` lets the install flow check organization admin rights. @@ -126,6 +126,7 @@ export async function handleOAuthCallback( code: string, _state: string, kv: KVNamespace, + db?: D1Database, ): Promise<{ userId: string; login: string } | null> { const res = await fetch("https://github.com/login/oauth/access_token", { method: "POST", @@ -154,12 +155,12 @@ export async function handleOAuthCallback( const octokit = new Octokit({ auth: data.access_token }); const { data: user } = await octokit.rest.users.getAuthenticated(); - await saveToken(kv, user.id.toString(), data.access_token, 3600 * 10); + await saveToken(kv, user.id.toString(), data.access_token, 3600 * 10, db); return { userId: user.id.toString(), login: user.login }; } -export async function getUserOctokit(userId: string, kv: KVNamespace): Promise { +export async function getUserOctokit(userId: string, kv: TokenSource): Promise { const token = await getToken(kv, userId); if (!token) return null; return new Octokit({ auth: token }); @@ -213,7 +214,7 @@ async function requireOctokit(kv: KVNamespace, githubUserId: string): Promise { @@ -12,11 +21,93 @@ async function hashToken(token: string): Promise { .join(""); } +/** + * Tokens are revoked (on removal and rotation) in the idempotency store (D1) + * as well as deleted from KV, whose deletes take a while to reach every + * location: a revoked token must stop authenticating at once. + */ +function revokedTokenKey(tokenHash: string): string { + return `token-revoked:${tokenHash}`; +} + +/** + * The user's live token, in D1. KV can hand a node a stale copy of the user's + * token, so a removal or rotation working from that copy would miss the + * newer token: dropping every live record of the user covers it whatever + * copy was read. + */ +function liveTokenKey(userId: string, tokenHash: string): string { + return `${liveTokenPrefix(userId)}${tokenHash}`; +} + +function liveTokenPrefix(userId: string): string { + return `token-live:${userId}:`; +} + +/** Statement dropping the user's live records (all, or all but `keep`). */ +function dropLive(db: D1Database, userId: string, keep = ""): D1PreparedStatement { + // A range over the prefix (`;` follows `:`), never a LIKE pattern. + return db + .prepare("DELETE FROM dedup_keys WHERE key >= ? AND key < ? AND key <> ?") + .bind(liveTokenPrefix(userId), `token-live:${userId};`, keep); +} + +/** + * Record `tokenHash` as the user's only live token, in one D1 batch. Returns + * false where the D1 table does not exist yet (the token then follows the + * revocation records alone). + */ +async function markLive( + db: D1Database, + userId: string, + tokenHash: string, + ttlSeconds: number, +): Promise { + const now = Date.now(); + const key = liveTokenKey(userId, tokenHash); + try { + await db.batch([ + dropLive(db, userId, key), + db + .prepare( + `INSERT INTO dedup_keys (key, claimed_at, expires_at) VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET + claimed_at = excluded.claimed_at, expires_at = excluded.expires_at`, + ) + .bind(key, now, now + ttlSeconds * 1000), + ]); + return true; + } catch (err) { + if (isMissingTable(err)) return false; + throw err; + } +} + +/** Whether a stored token may still be used (expiry aside). */ +async function usable( + db: D1Database | undefined, + kv: KVNamespace, + t: StoredToken, + tokenHash: string, +): Promise { + if (!db) return true; + const claims = idempotencyStore(db, kv); + if (await claims.has(revokedTokenKey(tokenHash))) return false; + if (t.live && !(await claims.has(liveTokenKey(t.userId, tokenHash)))) return false; + return true; +} + +async function revokeToken(db: D1Database, kv: KVNamespace, t: StoredToken): Promise { + const ttl = Math.max(60, Math.ceil((t.expiresAt - Date.now()) / 1000)); + await idempotencyStore(db, kv).claim(revokedTokenKey(await hashToken(t.accessToken)), ttl); +} + export async function saveToken( kv: KVNamespace, userId: string, accessToken: string, expiresInSeconds: number, + db?: D1Database, ): Promise { const token: StoredToken = { userId, @@ -24,13 +115,36 @@ export async function saveToken( expiresAt: Date.now() + expiresInSeconds * 1000, }; const ttl = Math.max(Math.floor(expiresInSeconds * 0.9), 60); + const tokenHash = await hashToken(accessToken); + // Rotation: the previous token's reverse index must stop resolving to this + // user, or the old token would keep acting with the new one. + // A failed read aborts the rotation: the old token must be revoked, and + // "none" cannot be assumed. + const previous = await kv.get(`token:${userId}`, "json"); + const rotated = previous?.accessToken && previous.accessToken !== accessToken; + // Revoked before it is overwritten: should this fail, the old token is + // still on record and a retry revokes it then. + if (rotated && db) await revokeToken(db, kv, previous); + // The only live token from here on — whichever older one some node's KV + // still shows. + if (db && canUseD1(db) && (await markLive(db, userId, tokenHash, expiresInSeconds))) { + token.live = true; + } await kv.put(`token:${userId}`, JSON.stringify(token), { expirationTtl: ttl }); - const tokenHash = await hashToken(accessToken); await kv.put(`token-reverse:${tokenHash}`, userId, { expirationTtl: ttl }); + if (rotated) await kv.delete(`token-reverse:${await hashToken(previous.accessToken)}`); } -export async function getToken(kv: KVNamespace, userId: string): Promise { +/** Where tokens are read from: KV alone, or KV with D1 (revocations honored). */ +export type TokenSource = KVNamespace | { KV: KVNamespace; DB?: D1Database }; + +function sourceOf(source: TokenSource): { kv: KVNamespace; db?: D1Database } { + return "KV" in source ? { kv: source.KV, db: source.DB } : { kv: source }; +} + +export async function getToken(source: TokenSource, userId: string): Promise { + const { kv, db } = sourceOf(source); const raw = await kv.get(`token:${userId}`, "json"); if (!raw) return null; const t = raw as StoredToken; @@ -38,25 +152,119 @@ export async function getToken(kv: KVNamespace, userId: string): Promise { +export async function removeToken(kv: KVNamespace, userId: string, db?: D1Database): Promise { + // First, and whatever KV shows here: a newer token than the copy read below + // stops too. + if (db && canUseD1(db)) { + try { + await dropLive(db, userId).run(); + } catch (err) { + if (!isMissingTable(err)) throw err; + } + } const raw = await kv.get(`token:${userId}`, "json"); if (raw) { const t = raw as StoredToken; + if (db) await revokeToken(db, kv, t); const tokenHash = await hashToken(t.accessToken); await kv.delete(`token-reverse:${tokenHash}`); } await kv.delete(`token:${userId}`); } +/** + * The GitHub user whose *current* stored token is `accessToken`. The reverse + * index only narrows the lookup; the stored token must match too, so a token + * that was rotated, revoked or expired never authenticates (even while a stale + * reverse key is still around). + */ export async function findUserIdByToken( kv: KVNamespace, accessToken: string, + db?: D1Database, ): Promise { const tokenHash = await hashToken(accessToken); - return await kv.get(`token-reverse:${tokenHash}`, "text"); + if (db && (await idempotencyStore(db, kv).has(revokedTokenKey(tokenHash)))) return null; + const userId = await kv.get(`token-reverse:${tokenHash}`, "text"); + if (!userId) return null; + const stored = await kv.get(`token:${userId}`, "json"); + if (!stored || Date.now() >= stored.expiresAt) return null; + if ((await hashToken(stored.accessToken)) !== tokenHash) return null; + if (!(await usable(db, kv, stored, tokenHash))) return null; + return userId; +} + +export type LinkPlatform = "discord" | "telegram" | "feishu"; + +const LINK_TABLES: Record = { + discord: { table: "discord_links", column: "discord_user_id" }, + telegram: { table: "telegram_links", column: "telegram_user_id" }, + feishu: { table: "feishu_links", column: "feishu_user_id" }, +}; + +/** Statement linking a chat account to a GitHub account (for a batch). */ +export function linkStatement( + db: D1Database, + platform: LinkPlatform, + chatUserId: string, + githubUserId: string, +): D1PreparedStatement { + const { table, column } = LINK_TABLES[platform]; + return db + .prepare(`INSERT OR REPLACE INTO ${table} (${column}, github_user_id) VALUES (?, ?)`) + .bind(chatUserId, githubUserId); +} + +/** Statement removing a chat account's link (for a batch). */ +export function unlinkStatement( + db: D1Database, + platform: LinkPlatform, + chatUserId: string, +): D1PreparedStatement { + const { table, column } = LINK_TABLES[platform]; + return db.prepare(`DELETE FROM ${table} WHERE ${column} = ?`).bind(chatUserId); +} + +/** + * Unlink as a bot command: the command's "done" record (`done`) commits in + * the same D1 transaction, so an unlink that went through — even one whose + * answer was lost — is never run again by a redelivery (which by then could + * remove a link made since). + */ +export async function unlinkAsCommand( + env: { DB: D1Database; KV: KVNamespace }, + platform: LinkPlatform, + chatUserId: string, + done?: { key: string; ttl: number }, +): Promise { + if (!done || !canUseD1(env.DB)) { + await unlinkStatement(env.DB, platform, chatUserId).run(); + return; + } + try { + await env.DB.batch([ + // Done already (another run took over this command after ours outlived + // its claim): nothing is removed — the link may be a new one by now. + unrecordedGuard(env.DB, done.key), + unlinkStatement(env.DB, platform, chatUserId), + recordStatement(env.DB, done.key, done.ttl), + ]); + } catch (err) { + // Recorded — committed here after all (its answer lost), or by another + // run before: done either way. + if ( + !(await idempotencyStore(env.DB, env.KV) + .has(done.key) + .catch(() => false)) + ) + throw err; + } } /** diff --git a/server/lib/web/actions.ts b/server/lib/web/actions.ts index fe00b47..5280d0c 100644 --- a/server/lib/web/actions.ts +++ b/server/lib/web/actions.ts @@ -33,7 +33,7 @@ async function userOctokit( event: H3Event, userId: string, ): Promise>> { - return getUserOctokit(userId, cfEnv(event).KV); + return getUserOctokit(userId, cfEnv(event)); } function fail(event: H3Event, status: number, error: string): Record { diff --git a/server/lib/web/auth.ts b/server/lib/web/auth.ts index c4f90e4..328fdc4 100644 --- a/server/lib/web/auth.ts +++ b/server/lib/web/auth.ts @@ -99,7 +99,8 @@ export async function bearerUserId(event: H3Event): Promise { const auth = getHeader(event, "authorization"); if (!auth?.startsWith("Bearer ")) throw createError({ statusCode: 401, statusMessage: "Missing authorization" }); - const userId = await findUserIdByToken(env.KV, auth.slice(7)); + // Resolves only the user's *current* token: a rotated or revoked one fails. + const userId = await findUserIdByToken(env.KV, auth.slice(7), env.DB); if (!userId) throw createError({ statusCode: 401, statusMessage: "Invalid or expired token" }); return userId; } diff --git a/server/lib/web/session.ts b/server/lib/web/session.ts index 386afb5..c0188b0 100644 --- a/server/lib/web/session.ts +++ b/server/lib/web/session.ts @@ -1,4 +1,5 @@ import type { Env } from "../types"; +import { idempotencyStore } from "../lib/idempotency"; const SESSION_COOKIE = "wh_admin_session"; const SESSION_TTL = 24 * 3600; @@ -6,6 +7,33 @@ const SESSION_TTL = 24 * 3600; export interface AdminSession { userId: string; login: string; + /** + * False when the login was first seen with another GitHub account (a name + * released by a rename and taken over since): identity checks then match + * this session by its user id only, never by the login. + */ + loginTrusted?: boolean; +} + +/** The login identity checks may use for this session ("" — by user id only). */ +export function authLogin(session: AdminSession): string { + return session.loginTrusted === false ? "" : session.login; +} + +/** + * Whether `login` belongs to `userId` as far as this deployment knows: the + * first account seen with a login owns it here (`login-owner:{login}`). A + * GitHub login can be renamed away and registered by someone else; that + * newcomer then never inherits what was granted to the login (an admin + * entry, a member entry not yet bound to an id). + */ +export async function claimLogin(kv: KVNamespace, userId: string, login: string): Promise { + const key = `login-owner:${login.toLowerCase()}`; + const owner = await kv.get(key); + if (owner) return owner === userId; + await kv.put(key, userId); + // Read back: of two first sign-ins racing, only the one stored wins. + return (await kv.get(key)) === userId; } export function isDebugMode(env: Env): boolean { @@ -20,14 +48,24 @@ export function isDebugMode(env: Env): boolean { return false; } +/** + * Whether one configured identity names this user. An all-digit entry is a + * GitHub user id, anything else a login (case-insensitive) — one string is + * never matched both ways, so a user whose login is digits can never pass for + * the user with that id. + */ +export function identityEntryMatches(entry: string, userId: string, login: string): boolean { + const e = entry.trim(); + if (!e) return false; + if (/^\d+$/.test(e)) return e === userId; + return e.toLowerCase() === login.toLowerCase(); +} + export function isAdminUser(env: Env, userId: string, login: string): boolean { if (isDebugMode(env)) return true; - const ids = (env.ADMIN_USER_IDS ?? "") + return (env.ADMIN_USER_IDS ?? "") .split(",") - .map((s) => s.trim()) - .filter(Boolean); - if (ids.length === 0) return false; - return ids.includes(userId) || ids.some((id) => id.toLowerCase() === login.toLowerCase()); + .some((entry) => identityEntryMatches(entry, userId, login)); } function generateSessionId(): string { @@ -42,9 +80,10 @@ export async function createAdminSession( kv: KVNamespace, userId: string, login: string, + loginTrusted = true, ): Promise { const sessionId = generateSessionId(); - const session: AdminSession = { userId, login }; + const session: AdminSession = loginTrusted ? { userId, login } : { userId, login, loginTrusted }; await kv.put(`session:${sessionId}`, JSON.stringify(session), { expirationTtl: SESSION_TTL, }); @@ -70,21 +109,35 @@ function parseCookies(header: string | undefined): Record { return out; } +/** + * Sessions are revoked in the idempotency store (D1) as well as deleted from + * KV: a KV delete takes a while to reach every location, and a stolen cookie + * must stop working at once. + */ +function revokedSessionKey(sessionId: string): string { + return `session-revoked:${sessionId}`; +} + export async function getAdminSession( kv: KVNamespace, cookieHeader: string | undefined, + db?: D1Database, ): Promise { const sessionId = parseCookies(cookieHeader)[SESSION_COOKIE]; if (!sessionId) return null; const raw = await kv.get(`session:${sessionId}`, "json"); if (!raw) return null; + if (db && (await idempotencyStore(db, kv).has(revokedSessionKey(sessionId)))) return null; return raw; } export async function destroyAdminSession( kv: KVNamespace, cookieHeader: string | undefined, + db?: D1Database, ): Promise { const sessionId = parseCookies(cookieHeader)[SESSION_COOKIE]; - if (sessionId) await kv.delete(`session:${sessionId}`); + if (!sessionId) return; + if (db) await idempotencyStore(db, kv).claim(revokedSessionKey(sessionId), SESSION_TTL); + await kv.delete(`session:${sessionId}`); }