Public: anyone can read this; the crew can change it.
An expired OAuth access token's grant stays listed and revocable until its refresh token is gone #15000
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/14904-an-expired-oauth-access-token-s-grant-st → main 4 commits fork 4 threads · 4 unresolved
7 files
changed +152
−21
docs/features/oauth-grants.md +8 −3
| @@ -13,7 +13,9 @@ through the MCP's OAuth sign-in: Claude, an editor, or another harness. | ||
| 13 | 13 | - its scope (`ro` or `rw`) and any OpenID scopes (`openid`, `profile`, `email`); |
| 14 | 14 | - when you granted it: the first consent, kept across every refresh; |
| 15 | 15 | - when it was last used, to the minute, or "never used"; |
| 16 | - when its token ends or renews, for a grant that expires. | |
| 16 | - when its token ends or renews, for a grant that expires; | |
| 17 | - "idle · refresh good until <date>" when its access token has expired and | |
| 18 | been pruned but its refresh token is still good; its next call renews it. | |
| 17 | 19 | |
| 18 | 20 | Last used is written at most once a minute per token, so a busy agent costs |
| 19 | 21 | one write a minute, not one per call. A refresh keeps both dates. |
| @@ -23,12 +25,15 @@ one write a minute, not one per call. A refresh keeps both dates. | ||
| 23 | 25 | Revoke is one tap: a same-origin `POST /settings/grants/<id>/revoke`. The |
| 24 | 26 | token and its refresh tokens go at once, so the agent's next call to `/mcp` or |
| 25 | 27 | `/api/v1` gets `401`, and it cannot refresh its way back. The page says what it |
| 26 | ended. A `token.deleted` event lands in the audit trail. | |
| 28 | ended. Revoking an idle grant ends its whole refresh family, so the refresh | |
| 29 | token is refused too. A `token.deleted` event lands in the audit trail; for an | |
| 30 | idle grant it names the family. | |
| 27 | 31 | |
| 28 | 32 | Only your own grants are listed and only they can be revoked here. Tokens you |
| 29 | 33 | made by hand are under Settings › Access codes. |
| 30 | 34 | |
| 31 | 35 | ## In the terminal |
| 32 | 36 | |
| 33 | `Connected agents` in the palette lists the same rows; `x` revokes the | |
| 37 | `Connected agents` in the palette lists the same rows, idle ones | |
| 38 | included and worded the same; `x` revokes the | |
| 34 | 39 | selected one after a confirm and says the same receipt. |
src/actions/oauth_grants.ts +18 −4
| @@ -5,9 +5,13 @@ | ||
| 5 | 5 | * hand-made token is not a grant (Settings › Access codes ends those). |
| 6 | 6 | * Revoking goes through `deleteToken`, so the refresh family goes with the |
| 7 | 7 | * token and `token.deleted` is emitted; the next call with it is refused, |
| 8 | * since `verifyToken` reads the row on every call. | |
| 8 | * since `verifyToken` reads the row on every call. An idle grant (its access | |
| 9 | * token expired and pruned, #14904) has no token to delete: its refresh | |
| 10 | * family is ended (`endGrantFamily`), and the `token.deleted` it emits names | |
| 11 | * the family, since there is no live token to name. | |
| 9 | 12 | */ |
| 10 | 13 | import type { App } from "../app.ts"; |
| 14 | import { endGrantFamily } from "../core/oauth.ts"; | |
| 11 | 15 | import { listOAuthGrants, oauthGrantOf, type OAuthGrant } from "../core/oauth_grants.ts"; |
| 12 | 16 | import type { User } from "../core/users.ts"; |
| 13 | 17 | import { err, ok, type Result } from "../kernel/result.ts"; |
| @@ -25,13 +29,23 @@ export function myOAuthGrants(app: App, actor: User | undefined): OAuthGrant[] { | ||
| 25 | 29 | export function revokeOAuthGrant( |
| 26 | 30 | app: App, |
| 27 | 31 | actor: User | undefined, |
| 28 | tokenId: string, | |
| 32 | id: string, | |
| 29 | 33 | ): Result<OAuthGrant, "not_found"> { |
| 30 | 34 | const user = requireUser(actor); |
| 31 | 35 | if (!user.ok || user.value.kind !== "user") return err("not_found"); |
| 32 | const grant = oauthGrantOf(app.db, user.value.id, tokenId); | |
| 36 | const grant = oauthGrantOf(app.db, user.value.id, id); | |
| 33 | 37 | if (grant === null) return err("not_found"); |
| 34 | if (!deleteToken(app, user.value, tokenId).ok) return err("not_found"); | |
| 38 | if (grant.tokenId !== null) { | |
| 39 | if (!deleteToken(app, user.value, grant.tokenId).ok) return err("not_found"); | |
| 40 | return ok(grant); | |
| 41 | } | |
| 42 | const ended = endGrantFamily(app.db, user.value.id, grant.id); | |
| 43 | if (ended === null) return err("not_found"); | |
| 44 | app.bus.append({ | |
| 45 | kind: "token.deleted", | |
| 46 | actorId: user.value.id, | |
| 47 | payload: { family: grant.id, tokenIds: ended, via: "grant_revoke" }, | |
| 48 | }); | |
| 35 | 49 | return ok(grant); |
| 36 | 50 | } |
| 37 | 51 |
src/core/oauth.ts +17
| @@ -383,6 +383,23 @@ function endFamily(db: Database, family: string): { userId: string; tokenIds: st | ||
| 383 | 383 | return { userId: rows[0]?.user_id ?? "", tokenIds }; |
| 384 | 384 | } |
| 385 | 385 | |
| 386 | /** | |
| 387 | * End one of a person's refresh families by its id (#14904): the grant a | |
| 388 | * person revokes on Settings › Connected agents when its access token has | |
| 389 | * already expired and been pruned. Every access token the family bought goes | |
| 390 | * with it. Returns the access token ids it ended (often none: the last one | |
| 391 | * was pruned), or null when the family is not theirs, or is gone. | |
| 392 | */ | |
| 393 | export function endGrantFamily(db: Database, userId: string, family: string): string[] | null { | |
| 394 | return db.transaction(() => { | |
| 395 | const owner = db | |
| 396 | .query<{ user_id: string }, [string]>("SELECT user_id FROM oauth_refresh WHERE family = ?1 LIMIT 1") | |
| 397 | .get(family); | |
| 398 | if (owner === null || owner.user_id !== userId) return null; | |
| 399 | return endFamily(db, family)?.tokenIds ?? null; | |
| 400 | })(); | |
| 401 | } | |
| 402 | ||
| 386 | 403 | /** |
| 387 | 404 | * Exchange a code for a token. The code is spent before anything else is |
| 388 | 405 | * decided, so a replay, a wrong verifier or a wrong redirect all find it |
src/core/oauth_grants.ts +57 −6
| @@ -6,13 +6,24 @@ | ||
| 6 | 6 | * `refreshGrant`). `last_used_at` is the token's own, written at most once an |
| 7 | 7 | * hour per token by `verifyToken` (`TOUCH_EVERY_MS`), so a busy harness |
| 8 | 8 | * costs one write an hour, not one per call. |
| 9 | * | |
| 10 | * A grant is its refresh family when it has one (#14904): `pruneTokens` | |
| 11 | * removes an access token past its expiry, and with it the mark that named | |
| 12 | * the client, while the family's refresh token still buys the next one. Such | |
| 13 | * a grant is listed `idle` — no live access token, renews on the client's | |
| 14 | * next call — under its family id, and revoking it ends the family. | |
| 9 | 15 | */ |
| 10 | 16 | import type { Database } from "bun:sqlite"; |
| 17 | import { REFRESH_TTL_MS } from "./oauth.ts"; | |
| 11 | 18 | import type { TokenScope } from "./tokens.ts"; |
| 12 | 19 | |
| 13 | 20 | export interface OAuthGrant { |
| 14 | /** The access token's id: what revoking ends. */ | |
| 15 | readonly tokenId: string; | |
| 21 | /** What revoking names: the live access token's id, or the family's when it is idle. */ | |
| 22 | readonly id: string; | |
| 23 | /** The live access token's id; null when the grant is idle. */ | |
| 24 | readonly tokenId: string | null; | |
| 25 | /** No live access token: the last one expired, and the refresh token buys the next. */ | |
| 26 | readonly idle: boolean; | |
| 16 | 27 | /** The client's registered name, untrusted text: escape it on every door. */ |
| 17 | 28 | readonly client: string; |
| 18 | 29 | readonly scope: TokenScope; |
| @@ -53,8 +64,10 @@ export function listOAuthGrants(db: Database, userId: string): OAuthGrant[] { | ||
| 53 | 64 | ORDER BY COALESCE(t.last_used_at, '') DESC, t.id`, |
| 54 | 65 | ) |
| 55 | 66 | .all(userId); |
| 56 | return rows.map((r) => ({ | |
| 67 | const live = rows.map((r) => ({ | |
| 68 | id: r.id, | |
| 57 | 69 | tokenId: r.id, |
| 70 | idle: false, | |
| 58 | 71 | client: r.client, |
| 59 | 72 | scope: r.scope, |
| 60 | 73 | oidcScopes: r.oidc === null || r.oidc === "" ? [] : r.oidc.split(" "), |
| @@ -63,11 +76,49 @@ export function listOAuthGrants(db: Database, userId: string): OAuthGrant[] { | ||
| 63 | 76 | expiresAt: r.expires_at, |
| 64 | 77 | renews: r.renews === 1, |
| 65 | 78 | })); |
| 79 | return [...live, ...idleGrants(db, userId)]; | |
| 66 | 80 | } |
| 67 | 81 | |
| 68 | 82 | /** |
| 69 | * One of a person's grants by its token id, or null when it is not theirs or not an OAuth grant. | |
| 83 | * A person's refresh families whose access token is gone (#14904): the | |
| 84 | * unspent, unexpired refresh token of each, with no token row behind it. The | |
| 85 | * family's earliest kept rotation stands in for when it was granted, since | |
| 86 | * the mark that kept the start went with the token. Bounded by the | |
| 87 | * refresh table, which `mintRefresh` keeps to two rows a family. | |
| 70 | 88 | */ |
| 71 | export function oauthGrantOf(db: Database, userId: string, tokenId: string): OAuthGrant | null { | |
| 72 | return listOAuthGrants(db, userId).find((g) => g.tokenId === tokenId) ?? null; | |
| 89 | function idleGrants(db: Database, userId: string, now: Date = new Date()): OAuthGrant[] { | |
| 90 | const rows = db | |
| 91 | .query< | |
| 92 | { family: string; client: string; scope: TokenScope; oidc: string; expires_at: string; first: string }, | |
| 93 | [string, string] | |
| 94 | >( | |
| 95 | `SELECT r.family, c.name AS client, r.scope, r.oidc_scopes AS oidc, r.expires_at, | |
| 96 | (SELECT MIN(f.expires_at) FROM oauth_refresh f WHERE f.family = r.family) AS first | |
| 97 | FROM oauth_refresh r | |
| 98 | JOIN oauth_client c ON c.id = r.client_id | |
| 99 | WHERE r.user_id = ?1 AND r.spent = 0 AND r.expires_at > ?2 | |
| 100 | AND NOT EXISTS (SELECT 1 FROM token t WHERE t.id = r.token_id) | |
| 101 | ORDER BY r.expires_at DESC, r.family`, | |
| 102 | ) | |
| 103 | .all(userId, now.toISOString()); | |
| 104 | return rows.map((r) => ({ | |
| 105 | id: r.family, | |
| 106 | tokenId: null, | |
| 107 | idle: true, | |
| 108 | client: r.client, | |
| 109 | scope: r.scope, | |
| 110 | oidcScopes: r.oidc === "" ? [] : r.oidc.split(" "), | |
| 111 | grantedAt: new Date(Date.parse(r.first) - REFRESH_TTL_MS).toISOString(), | |
| 112 | lastUsedAt: null, | |
| 113 | expiresAt: r.expires_at, | |
| 114 | renews: true, | |
| 115 | })); | |
| 116 | } | |
| 117 | ||
| 118 | /** | |
| 119 | * One of a person's grants by its id (a token's or an idle family's), or null when it is not | |
| 120 | * theirs or not an OAuth grant. | |
| 121 | */ | |
| 122 | export function oauthGrantOf(db: Database, userId: string, id: string): OAuthGrant | null { | |
| 123 | return listOAuthGrants(db, userId).find((g) => g.id === id) ?? null; | |
| 73 | 124 | } |
src/tui/screens/oauthgrants.ts +2 −2
| @@ -20,7 +20,7 @@ export function grantRows(grants: readonly OAuthGrant[]): ListRow[] { | ||
| 20 | 20 | return grants.map((g) => ({ |
| 21 | 21 | title: g.client, |
| 22 | 22 | secondary: [g.scope, ...g.oidcScopes].join(" "), |
| 23 | meta: `granted ${g.grantedAt.slice(0, 10)} · ${g.lastUsedAt === null ? "never used" : `last used ${ago(g.lastUsedAt)}`}`, | |
| 23 | meta: `granted ${g.grantedAt.slice(0, 10)} · ${g.idle ? `idle · refresh good until ${g.expiresAt?.slice(0, 10) ?? "?"}` : g.lastUsedAt === null ? "never used" : `last used ${ago(g.lastUsedAt)}`}`, | |
outdated
New idle wording on the terminal has no test; add one for grantRows. |
||
| 24 | 24 | })); |
| 25 | 25 | } |
| 26 | 26 | |
| @@ -36,7 +36,7 @@ export function oauthGrantsScreen(f: Session, ctx: Ctx): Screen { | ||
| 36 | 36 | actions: [{ label: "Keep", variant: "ghost" }, { label: "Revoke", variant: "danger" }], |
| 37 | 37 | onChoose: (i) => { |
| 38 | 38 | if (i < 1) return; |
| 39 | const done = revokeOAuthGrant(f.app, f.user, picked.tokenId); | |
| 39 | const done = revokeOAuthGrant(f.app, f.user, picked.id); | |
| 40 | 40 | note = done.ok ? revokedWords(done.value) : "That grant is already gone."; |
| 41 | 41 | ctx.invalidate(); |
| 42 | 42 | }, |
src/web/pages/grants.ts +7 −3
| @@ -22,17 +22,21 @@ export const GRANTS_PATH = "/settings/grants"; | ||
| 22 | 22 | |
| 23 | 23 | /** Last used, in words a glance answers: never, or the time. */ |
| 24 | 24 | const lastUsed = (g: OAuthGrant): Html => |
| 25 | g.lastUsedAt === null ? html`never used` : html`last used ${time(g.lastUsedAt)}`; | |
| 25 | g.idle | |
Principle 1 and 8: "renews" appears twice in one row (here and in "can renew until"). Say it once, plainly. |
||
| 26 | ? html`idle` | |
| 27 | : g.lastUsedAt === null | |
| 28 | ? html`never used` | |
| 29 | : html`last used ${time(g.lastUsedAt)}`; | |
| 26 | 30 | |
| 27 | 31 | function grantRow(g: OAuthGrant): Html { |
| 28 | 32 | return row({ |
| 29 | 33 | title: html`<strong>${g.client}</strong> ${badge(g.scope)} ${g.oidcScopes.map((s) => badge(s))}`, |
| 30 | 34 | meta: html`granted ${time(g.grantedAt)} · ${lastUsed(g)}${when( |
| 31 | 35 | g.expiresAt, |
| 32 | (at) => html` · ${g.renews ? "renews" : "ends"} ${time(at)}`, | |
| 36 | (at) => html` · ${g.idle ? "refresh good until" : g.renews ? "renews" : "ends"} ${time(at)}`, | |
| 33 | 37 | )}`, |
| 34 | 38 | trail: confirmAction({ |
| 35 | action: `${GRANTS_PATH}/${encodeURIComponent(g.tokenId)}/revoke`, | |
| 39 | action: `${GRANTS_PATH}/${encodeURIComponent(g.id)}/revoke`, | |
| 36 | 40 | verb: "Revoke", |
| 37 | 41 | size: "sm", |
| 38 | 42 | label: `Revoke ${g.client}`, |
test/oauth-grants.test.ts +43 −3
| @@ -14,7 +14,7 @@ import { revokeOAuthGrant } from "../src/actions/oauth_grants.ts"; | ||
| 14 | 14 | import { createApp, type App } from "../src/app.ts"; |
| 15 | 15 | import { createClient, issueCode, parseAuthRequest, redeemCode, refreshGrant } from "../src/core/oauth.ts"; |
| 16 | 16 | import { listOAuthGrants } from "../src/core/oauth_grants.ts"; |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 17 | import { createToken, pruneTokens } from "../src/core/tokens.ts"; | |
| 18 | 18 | import { createUser, type User } from "../src/core/users.ts"; |
| 19 | 19 | import { serve, type Servers } from "../src/http/server.ts"; |
| 20 | 20 | import { createAgent } from "../src/actions/crew.ts"; |
| @@ -111,7 +111,7 @@ const page = async (extra = ""): Promise<string> => | ||
| 111 | 111 | const idOf = (user: User, client: string): string => { |
| 112 | 112 | const found = listOAuthGrants(app.db, user.id).find((g) => g.client === client); |
| 113 | 113 | if (found === undefined) throw new Error(`no grant for ${client}`); |
| 114 | return found.tokenId; | |
| 114 | return found.id; | |
| 115 | 115 | }; |
| 116 | 116 | |
| 117 | 117 | test("each grant is one row with its client, scope, granted and last used; a hand-made token is not one", async () => { |
| @@ -182,6 +182,46 @@ test("a revoked grant with a refresh token cannot refresh its way back", async ( | ||
| 182 | 182 | expect(refreshGrant(app.db, { refreshToken: refresh!, clientId, scope: "" }).ok).toBe(false); |
| 183 | 183 | }); |
| 184 | 184 | |
| 185 | test("a grant whose access token expired and was pruned is listed idle, and revoking it ends the refresh (#14904)", async () => { | |
| 186 | const { token, refresh, clientId } = await grant(alice, "Sleeping harness", 86_400); | |
| 187 | const live = listOAuthGrants(app.db, alice.id).find((g) => g.client === "Sleeping harness")!; | |
| 188 | app.db.query("UPDATE token SET expires_at = ?1 WHERE id = ?2").run(new Date(Date.now() - 1000).toISOString(), live.tokenId); | |
| 189 | expect(pruneTokens(app.db)).toBeGreaterThanOrEqual(1); | |
| 190 | expect((await mcp(token)).status).toBe(401); | |
| 191 | const idle = listOAuthGrants(app.db, alice.id).filter((g) => g.client === "Sleeping harness"); | |
| 192 | expect(idle).toHaveLength(1); | |
| 193 | expect(idle[0]!.idle).toBe(true); | |
| 194 | expect(idle[0]!.tokenId).toBeNull(); | |
| 195 | expect(idle[0]!.renews).toBe(true); | |
| 196 | const shown = await page(); | |
| 197 | expect(shown).toContain("<strong>Sleeping harness</strong>"); | |
| 198 | expect(shown).toContain("idle · refresh good until"); | |
| 199 | expect(shown).not.toContain("renews on its next call"); | |
| 200 | // The terminal says the same, once and plainly. | |
| 201 | const tuiRow = grantRows(idle).find((r) => r.title === "Sleeping harness")!; | |
| 202 | expect(tuiRow.meta).toContain(`idle · refresh good until ${idle[0]!.expiresAt!.slice(0, 10)}`); | |
| 203 | expect(tuiRow.meta).not.toContain("last used"); | |
| 204 | expect(shown).toContain(encodeURIComponent(`/settings/grants/${idle[0]!.id}/revoke`)); | |
| 205 | // Bob cannot end it by naming its id. | |
| 206 | expect(revokeOAuthGrant(app, bob, idle[0]!.id).ok).toBe(false); | |
| 207 | const res = await fetch(`${servers.url}/settings/grants/${encodeURIComponent(idle[0]!.id)}/revoke`, { | |
| 208 | method: "POST", | |
| 209 | headers: { cookie, origin: servers.url }, | |
| 210 | redirect: "manual", | |
| 211 | }); | |
| 212 | expect(res.status).toBe(303); | |
| 213 | // The audit trail names who ended the family. | |
| 214 | const audit = app.db | |
| 215 | .query<{ actor_id: string; payload: string }, []>( | |
| 216 | "SELECT actor_id, payload FROM event WHERE kind = 'token.deleted' ORDER BY seq DESC LIMIT 1", | |
| 217 | ) | |
| 218 | .get()!; | |
| 219 | expect(audit.actor_id).toBe(alice.id); | |
| 220 | expect(JSON.parse(audit.payload)).toMatchObject({ family: idle[0]!.id, via: "grant_revoke" }); | |
| 221 | expect(listOAuthGrants(app.db, alice.id).some((g) => g.client === "Sleeping harness")).toBe(false); | |
| 222 | expect(refreshGrant(app.db, { refreshToken: refresh!, clientId, scope: "" }).ok).toBe(false); | |
| 223 | }); | |
| 224 | ||
| 185 | 225 | test("a refresh keeps when the grant began and when it was last used", async () => { |
| 186 | 226 | const { token, refresh, clientId } = await grant(alice, "Rotating harness", 86_400); |
| 187 | 227 | await mcp(token); |
| @@ -242,7 +282,7 @@ function terminal(user: User | undefined) { | ||
| 242 | 282 | } |
| 243 | 283 | |
| 244 | 284 | test("the terminal's x asks first; Keep ends nothing, Revoke ends the grant and the MCP answers 401", async () => { |
| 245 | for (const g of listOAuthGrants(app.db, alice.id)) revokeOAuthGrant(app, alice, g.tokenId); | |
| 285 | for (const g of listOAuthGrants(app.db, alice.id)) revokeOAuthGrant(app, alice, g.id); | |
| 246 | 286 | const { token } = await grant(alice, "Terminal harness"); |
| 247 | 287 | const t = terminal(alice); |
| 248 | 288 | expect(t.draw()).toContain("Terminal harness"); |
new above
offline
No audit event for an idle revoke. Emit one naming the family so the trail shows who ended the grant.