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

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/14904-an-expired-oauth-access-token-s-grant-st → main 4 commits fork 4 threads · 4 unresolved

  • Merged. torque/14904-an-expired-oauth-access-token-s-grant-st was merged into main as e43693b.

Review

Sign in to review this change.
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.
1313 - its scope (`ro` or `rw`) and any OpenID scopes (`openid`, `profile`, `email`);
1414 - when you granted it: the first consent, kept across every refresh;
1515 - 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.
1719
1820 Last used is written at most once a minute per token, so a busy agent costs
1921 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.
2325 Revoke is one tap: a same-origin `POST /settings/grants/<id>/revoke`. The
2426 token and its refresh tokens go at once, so the agent's next call to `/mcp` or
2527 `/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.
2731
2832 Only your own grants are listed and only they can be revoked here. Tokens you
2933 made by hand are under Settings › Access codes.
3034
3135 ## In the terminal
3236
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
3439 selected one after a confirm and says the same receipt.
src/actions/oauth_grants.ts +18 −4
@@ -5,9 +5,13 @@
55 * hand-made token is not a grant (Settings › Access codes ends those).
66 * Revoking goes through `deleteToken`, so the refresh family goes with the
77 * 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.
912 */
1013 import type { App } from "../app.ts";
14 import { endGrantFamily } from "../core/oauth.ts";
1115 import { listOAuthGrants, oauthGrantOf, type OAuthGrant } from "../core/oauth_grants.ts";
1216 import type { User } from "../core/users.ts";
1317 import { err, ok, type Result } from "../kernel/result.ts";
@@ -25,13 +29,23 @@ export function myOAuthGrants(app: App, actor: User | undefined): OAuthGrant[] {
2529 export function revokeOAuthGrant(
2630 app: App,
2731 actor: User | undefined,
28 tokenId: string,
32 id: string,
2933 ): Result<OAuthGrant, "not_found"> {
3034 const user = requireUser(actor);
3135 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);
3337 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);
outdated

No audit event for an idle revoke. Emit one naming the family so the trail shows who ended the grant.

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 });
3549 return ok(grant);
3650 }
3751
src/core/oauth.ts +17
@@ -383,6 +383,23 @@ function endFamily(db: Database, family: string): { userId: string; tokenIds: st
383383 return { userId: rows[0]?.user_id ?? "", tokenIds };
384384 }
385385
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
386403 /**
387404 * Exchange a code for a token. The code is spent before anything else is
388405 * 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 @@
66 * `refreshGrant`). `last_used_at` is the token's own, written at most once an
77 * hour per token by `verifyToken` (`TOUCH_EVERY_MS`), so a busy harness
88 * 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.
915 */
1016 import type { Database } from "bun:sqlite";
17 import { REFRESH_TTL_MS } from "./oauth.ts";
1118 import type { TokenScope } from "./tokens.ts";
1219
1320 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;
1627 /** The client's registered name, untrusted text: escape it on every door. */
1728 readonly client: string;
1829 readonly scope: TokenScope;
@@ -53,8 +64,10 @@ export function listOAuthGrants(db: Database, userId: string): OAuthGrant[] {
5364 ORDER BY COALESCE(t.last_used_at, '') DESC, t.id`,
5465 )
5566 .all(userId);
56 return rows.map((r) => ({
67 const live = rows.map((r) => ({
68 id: r.id,
5769 tokenId: r.id,
70 idle: false,
5871 client: r.client,
5972 scope: r.scope,
6073 oidcScopes: r.oidc === null || r.oidc === "" ? [] : r.oidc.split(" "),
@@ -63,11 +76,49 @@ export function listOAuthGrants(db: Database, userId: string): OAuthGrant[] {
6376 expiresAt: r.expires_at,
6477 renews: r.renews === 1,
6578 }));
79 return [...live, ...idleGrants(db, userId)];
6680 }
6781
6882 /**
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.
7088 */
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;
73124 }
src/tui/screens/oauthgrants.ts +2 −2
@@ -20,7 +20,7 @@ export function grantRows(grants: readonly OAuthGrant[]): ListRow[] {
2020 return grants.map((g) => ({
2121 title: g.client,
2222 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.

2424 }));
2525 }
2626
@@ -36,7 +36,7 @@ export function oauthGrantsScreen(f: Session, ctx: Ctx): Screen {
3636 actions: [{ label: "Keep", variant: "ghost" }, { label: "Revoke", variant: "danger" }],
3737 onChoose: (i) => {
3838 if (i < 1) return;
39 const done = revokeOAuthGrant(f.app, f.user, picked.tokenId);
39 const done = revokeOAuthGrant(f.app, f.user, picked.id);
4040 note = done.ok ? revokedWords(done.value) : "That grant is already gone.";
4141 ctx.invalidate();
4242 },
src/web/pages/grants.ts +7 −3
@@ -22,17 +22,21 @@ export const GRANTS_PATH = "/settings/grants";
2222
2323 /** Last used, in words a glance answers: never, or the time. */
2424 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)}`;
2630
2731 function grantRow(g: OAuthGrant): Html {
2832 return row({
2933 title: html`<strong>${g.client}</strong> ${badge(g.scope)} ${g.oidcScopes.map((s) => badge(s))}`,
3034 meta: html`granted ${time(g.grantedAt)} · ${lastUsed(g)}${when(
3135 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)}`,
3337 )}`,
3438 trail: confirmAction({
35 action: `${GRANTS_PATH}/${encodeURIComponent(g.tokenId)}/revoke`,
39 action: `${GRANTS_PATH}/${encodeURIComponent(g.id)}/revoke`,
3640 verb: "Revoke",
3741 size: "sm",
3842 label: `Revoke ${g.client}`,
test/oauth-grants.test.ts +43 −3
@@ -14,7 +14,7 @@ import { revokeOAuthGrant } from "../src/actions/oauth_grants.ts";
1414 import { createApp, type App } from "../src/app.ts";
1515 import { createClient, issueCode, parseAuthRequest, redeemCode, refreshGrant } from "../src/core/oauth.ts";
1616 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";
1818 import { createUser, type User } from "../src/core/users.ts";
1919 import { serve, type Servers } from "../src/http/server.ts";
2020 import { createAgent } from "../src/actions/crew.ts";
@@ -111,7 +111,7 @@ const page = async (extra = ""): Promise<string> =>
111111 const idOf = (user: User, client: string): string => {
112112 const found = listOAuthGrants(app.db, user.id).find((g) => g.client === client);
113113 if (found === undefined) throw new Error(`no grant for ${client}`);
114 return found.tokenId;
114 return found.id;
115115 };
116116
117117 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 (
182182 expect(refreshGrant(app.db, { refreshToken: refresh!, clientId, scope: "" }).ok).toBe(false);
183183 });
184184
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
185225 test("a refresh keeps when the grant began and when it was last used", async () => {
186226 const { token, refresh, clientId } = await grant(alice, "Rotating harness", 86_400);
187227 await mcp(token);
@@ -242,7 +282,7 @@ function terminal(user: User | undefined) {
242282 }
243283
244284 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);
246286 const { token } = await grant(alice, "Terminal harness");
247287 const t = terminal(alice);
248288 expect(t.draw()).toContain("Terminal harness");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs