Public: anyone can read this; the crew can change it.

OAuth refresh-token reuse revokes the grant, with a test and a line in /settings #15987

Merged opened this

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

Merged

scout/forge:scout/15974-oauth-refresh-token-reuse-revokes-the-gr → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/15974-oauth-refresh-token-reuse-revokes-the-gr was merged into main as 1f8a3a0.

Review

Sign in to review this change.
9 files changed +120 −15
docs/features/oauth-refresh.md +4 −1
@@ -15,7 +15,10 @@ curl -X POST https://<forge>/oauth/token \
1515
1616 - The answer is a new `access_token` and a new `refresh_token`; the old pair stops working.
1717 - A spent refresh token presented again ends the whole family (OAuth 2.1 §4.3.1)
18 and leaves a `token.deleted` event with `via: oauth_refresh_reuse`.
18 and leaves a `token.deleted` event with `via: oauth_refresh_reuse` (RFC 9700 §4.14.2).
19 Every replay revokes; there is no grace for a lost response. The ended grant is listed under "Revoked after a token was
20 reused" on Settings › Connected agents (`/settings/grants`), and named on the
21 terminal's Connected agents screen.
1922 - `scope` may only narrow (`rw` to `ro`); more is `invalid_scope` and spends nothing.
2023 - `POST /oauth/revoke` with either token ends the family.
2124 - Deleting the access token on Settings › Tokens (or through the API, the terminal,
src/actions/oauth_grants.ts +12 −5
@@ -12,19 +12,26 @@
1212 */
1313 import type { App } from "../app.ts";
1414 import { endGrantFamily } from "../core/oauth.ts";
15 import { listOAuthGrants, oauthGrantOf, type OAuthGrant } from "../core/oauth_grants.ts";
15 import { listOAuthGrants, listReusedGrants, oauthGrantOf, type OAuthGrant, type ReusedGrant } from "../core/oauth_grants.ts";
1616 import type { User } from "../core/users.ts";
1717 import { err, ok, type Result } from "../kernel/result.ts";
1818 import { requireUser } from "./access.ts";
1919 import { deleteToken } from "./users.ts";
2020
21 /** The asker's grants; empty for a guest or an agent, who grant nothing. */
22 export function myOAuthGrants(app: App, actor: User | undefined): OAuthGrant[] {
21 /** What `read` finds for the asker; empty for a guest or an agent, who grant nothing. */
22 function ownGrants<T>(actor: User | undefined, read: (userId: string) => T[]): T[] {
2323 const user = requireUser(actor);
24 if (!user.ok || user.value.kind !== "user") return [];
25 return listOAuthGrants(app.db, user.value.id);
24 return !user.ok || user.value.kind !== "user" ? [] : read(user.value.id);
2625 }
2726
27 /** The asker's grants. */
28 export const myOAuthGrants = (app: App, actor: User | undefined): OAuthGrant[] =>
29 ownGrants(actor, (id) => listOAuthGrants(app.db, id));
30
31 /** The asker's grants ended by refresh-token reuse (#15974). */
32 export const myReusedGrants = (app: App, actor: User | undefined): ReusedGrant[] =>
33 ownGrants(actor, (id) => listReusedGrants(app.db, id));
34
2835 /** End one of the asker's grants; returns what was ended, for the receipt. */
2936 export function revokeOAuthGrant(
3037 app: App,
src/core/migration-pins/20261123130000-oauth-reuse.pin added +1
@@ -0,0 +1,1 @@
1 e84ff8e3565f992a75817c098a363d621a9d72abed25c346e2fdc31bf55a8a0a
src/core/migrations/20261123130000-oauth-reuse.ts added +12
@@ -0,0 +1,12 @@
1 // A refresh token presented twice ends its grant (#15974); the grant is kept as one line so
2 // Settings can say so. Additive.
3 export default `
4 CREATE TABLE oauth_reuse (
5 family TEXT PRIMARY KEY,
6 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
7 client TEXT NOT NULL,
8 scope TEXT NOT NULL,
9 revoked_at TEXT NOT NULL
10 );
11 CREATE INDEX oauth_reuse_user ON oauth_reuse(user_id, revoked_at);
12 `;
src/core/oauth.ts +15 −2
@@ -2,6 +2,11 @@
22 * OAuth for the MCP: clients (RFC 7591), the authorization request a person
33 * consents to, the one-time code, and its PKCE exchange for the same token
44 * Settings mints.
5 *
6 * Refresh-token reuse follows RFC 9700 (OAuth 2.0 Security BCP) §4.14.2: a
7 * rotated refresh token presented again means it leaked, so every token of
8 * the grant is revoked, every time, with no grace, and the grant is kept as
9 * a line in `oauth_reuse` for Settings.
510 */
611 import type { Database } from "bun:sqlite";
712 import { sha256 } from "../kernel/hash.ts";
@@ -513,8 +518,9 @@ const SCOPE_RANK: Readonly<Record<OAuthScope, number>> = { ro: 0, rw: 1 };
513518 */
514519 export function refreshGrant(
515520 db: Database,
516 input: { refreshToken: string; clientId: string; scope: string },
521 input: { refreshToken: string; clientId: string; scope: string; now?: number },
517522 ): Result<Minted, RefreshRefusal> & { reuse?: FamilyRevoked } {
523 const now = input.now ?? Date.now();
518524 const row = db
519525 .query<
520526 {
@@ -534,10 +540,17 @@ export function refreshGrant(
534540 .get(sha256(input.refreshToken));
535541 if (row === null || row.client_id !== input.clientId) return err("invalid_grant");
536542 if (row.spent === 1) {
543 const client = db
544 .query<{ name: string }, [string]>("SELECT name FROM oauth_client WHERE id = ?1")
545 .get(row.client_id);
537546 const ended = endFamily(db, row.family);
547 if (ended !== null)
548 db.query(
549 "INSERT OR REPLACE INTO oauth_reuse (family, user_id, client, scope, revoked_at) VALUES (?1, ?2, ?3, ?4, ?5)",
550 ).run(row.family, row.user_id, client?.name ?? "", row.scope, new Date(now).toISOString());
outdated

HIGH: this returns invalid_grant without revoking when a rotated token is replayed within 10s. A thief replaying a leaked token right away keeps the grant alive, and box 1 says every presentation of a rotated token revokes. Remove the window, REPLAY_WINDOW_MS, spent_at, and the test workaround in oauth-refresh.test.ts.

538551 return { ...err("invalid_grant"), ...(ended === null ? {} : { reuse: ended }) };
539552 }
540 if (Date.parse(row.expires_at) <= Date.now()) {
553 if (Date.parse(row.expires_at) <= now) {
541554 endFamily(db, row.family);
542555 return err("invalid_grant");
543556 }
src/core/oauth_grants.ts +18
@@ -122,3 +122,21 @@ function idleGrants(db: Database, userId: string, now: Date = new Date()): OAuth
122122 export function oauthGrantOf(db: Database, userId: string, id: string): OAuthGrant | null {
123123 return listOAuthGrants(db, userId).find((g) => g.id === id) ?? null;
124124 }
125
126 /** A grant ended because a rotated refresh token was presented again (RFC 9700 §4.14.2). */
127 export interface ReusedGrant {
128 /** The client's registered name, untrusted text: escape it. */
129 readonly client: string;
130 readonly scope: TokenScope;
131 readonly revokedAt: string;
132 }
133
134 /** A person's grants ended by refresh-token reuse, newest first, at most 20. */
135 export function listReusedGrants(db: Database, userId: string): ReusedGrant[] {
136 return db
137 .query<{ client: string; scope: TokenScope; revoked_at: string }, [string]>(
138 "SELECT client, scope, revoked_at FROM oauth_reuse WHERE user_id = ?1 ORDER BY revoked_at DESC LIMIT 20",
139 )
140 .all(userId)
141 .map((r) => ({ client: r.client, scope: r.scope, revokedAt: r.revoked_at }));
142 }
src/tui/screens/oauthgrants.ts +10 −2
@@ -5,7 +5,7 @@
55 * `revokeOAuthGrant` (the page's action and gate: your own grants only) and
66 * says the page's receipt. An agent and a guest see nothing to revoke.
77 */
8 import { myOAuthGrants, revokeOAuthGrant, revokedWords } from "../../actions/oauth_grants.ts";
8 import { myOAuthGrants, myReusedGrants, revokeOAuthGrant, revokedWords } from "../../actions/oauth_grants.ts";
99 import type { OAuthGrant } from "../../core/oauth_grants.ts";
1010 import type { Ctx, Screen } from "../app/app.ts";
1111 import { binding } from "../app/keys.ts";
@@ -15,6 +15,9 @@ import type { Session } from "../session.ts";
1515 import { fill, len, split } from "../ui/layout.ts";
1616 import { ListState, ago, confirmScreen, drawList, type ListRow } from "./common.ts";
1717
18 /** A client's registered name is untrusted: control characters become a space. */
19 const plain = (s: string): string => s.replace(/[\x00-\x1f\x7f-\x9f]+/g, " ").trim();
20
1821 /** One row per grant, in the page's words. */
1922 export function grantRows(grants: readonly OAuthGrant[]): ListRow[] {
2023 return grants.map((g) => ({
@@ -50,7 +53,8 @@ export function oauthGrantsScreen(f: Session, ctx: Ctx): Screen {
5053 render(area, s) {
5154 const c = ctx.theme.c;
5255 const all = myOAuthGrants(f.app, f.user);
53 const [head, body] = split(area, "v", [len(1), fill(1)]);
56 const reused = myReusedGrants(f.app, f.user);
57 const [head, reuse, body] = split(area, "v", [len(1), len(reused.length === 0 ? 0 : 1), fill(1)]);
5458 const text =
5559 note !== ""
5660 ? note
@@ -60,6 +64,10 @@ export function oauthGrantsScreen(f: Session, ctx: Ctx): Screen {
6064 ? "No agent is connected through OAuth."
6165 : "Agents you let in through the MCP's sign-in. x revokes one.";
6266 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
67 if (reused.length > 0) {
68 const names = reused.map((g) => plain(g.client)).join(", ");
69 s.text(reuse!.x, reuse!.y, truncate(`Revoked after a token was reused: ${names}`, reuse!.w), style(c.mutedFg, c.bg), reuse!.x + reuse!.w);
70 }
6371 drawList(s, body!, c, state, grantRows(all));
6472 },
6573 key(e) {
src/web/pages/grants.ts +18 −5
@@ -7,16 +7,16 @@
77 * rows and the gate are `actions/oauth_grants.ts`, which the terminal's
88 * `screens/oauthgrants.ts` shares.
99 */
10 import { myOAuthGrants, revokeOAuthGrant, revokedWords } from "../../actions/oauth_grants.ts";
10 import { myOAuthGrants, myReusedGrants, revokeOAuthGrant, revokedWords } from "../../actions/oauth_grants.ts";
1111 import { emptyNote } from "../empty_words.ts";
12 import type { OAuthGrant } from "../../core/oauth_grants.ts";
12 import type { OAuthGrant, ReusedGrant } from "../../core/oauth_grants.ts";
1313 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1414 import type { Ctx } from "../../http/context.ts";
1515 import { signInFirst } from "../chrome.ts";
1616 import { readForm } from "../form.ts";
1717 import { html, when, type Html } from "../html.ts";
1818 import { flashTo } from "../layout.ts";
19 import { badge, confirmAction, row, time } from "../ui.ts";
19 import { badge, confirmAction, listCard, row, time } from "../ui.ts";
2020 import { accountShell } from "./account.ts";
2121
2222 export const GRANTS_PATH = "/settings/grants";
@@ -45,7 +45,14 @@ function grantRow(g: OAuthGrant): Html {
4545 });
4646 }
4747
48 function grantsView(grants: readonly OAuthGrant[]): Html {
48 function reusedRow(g: ReusedGrant): Html {
49 return row({
50 title: html`<strong>${g.client}</strong> ${badge(g.scope)}`,
51 meta: html`${time(g.revokedAt)}`,
outdated

Principle 1 (nothing explains itself twice): the h3 already says 'Revoked after a token was reused'; every row then repeats the reason in a long sentence. Keep one short line, e.g. 'reused token'. Principle 7: check that listCard is rows and not a box.

52 });
53 }
54
55 function grantsView(grants: readonly OAuthGrant[], reused: readonly ReusedGrant[]): Html {
4956 const list =
5057 grants.length === 0
5158 ? emptyNote("noAgentIsConnected")
@@ -58,6 +65,11 @@ function grantsView(grants: readonly OAuthGrant[]): Html {
5865 The agents you let in through sign-in; tokens you made are under <a href="/settings/tokens">Access codes</a>.
5966 </p>
6067 ${list}
68 ${when(
69 reused.length === 0 ? null : reused,
70 (r) => html`<h3>Revoked after a token was reused</h3>
71 ${listCard(r.map(reusedRow))}`,
72 )}
6173 </section>`;
6274 }
6375
@@ -66,8 +78,9 @@ export function grantsPage(ctx: Ctx): Response {
6678 if (!ctx.auth.user) return signInFirst(ctx);
6779 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
6880 const grants = timePhase(ctx.request, "grants", () => myOAuthGrants(ctx.app, ctx.auth.user));
81 const reused = myReusedGrants(ctx.app, ctx.auth.user);
6982 return timePhase(ctx.request, "render", () =>
70 accountShell(ctx, "grants", "Connected agents", grantsView(grants)),
83 accountShell(ctx, "grants", "Connected agents", grantsView(grants, reused)),
7184 );
7285 }
7386
test/oauth-grants.test.ts +30
@@ -316,3 +316,33 @@ test("in the terminal a guest and an agent see no rows and x revokes nothing", a
316316 expect(listOAuthGrants(app.db, alice.id).map((g) => g.client)).toContain("Still mine");
317317 expect((await mcp(token)).status).not.toBe(401);
318318 });
319
320 test("a rotated refresh token replayed at once revokes the grant, the new token dies too, and Settings says so (RFC 9700)", async () => {
321 const g = await grant(alice, "Replayed <b>Agent</b>", 86_400);
322 const input = { clientId: g.clientId, scope: "" };
323 const rotated = refreshGrant(app.db, { ...input, refreshToken: g.refresh! });
324 if (!rotated.ok) throw new Error("no rotation");
325 const fresh = rotated.value.refreshToken!;
326 expect((await mcp(rotated.value.token!)).status).not.toBe(401);
327 const replay = refreshGrant(app.db, { ...input, refreshToken: g.refresh! });
328 expect(replay).toMatchObject({ ok: false, error: "invalid_grant" });
329 expect("reuse" in replay).toBe(true);
330 expect((await mcp(rotated.value.token!)).status).toBe(401);
331 expect(refreshGrant(app.db, { ...input, refreshToken: fresh }).ok).toBe(false);
332 const html = await page();
333 expect(html).toContain("Revoked after a token was reused");
334 expect(html).toContain("Replayed &lt;b&gt;Agent&lt;/b&gt;");
335 expect(html).not.toContain("<b>Agent</b>");
336 expect(html).not.toContain("already used was presented");
337 });
338
339 test("the terminal's grants screen names a grant ended by token reuse, on its own row, control characters stripped", async () => {
340 const g = await grant(alice, "Reused\x1b[31m in terminal", 86_400);
341 const input = { clientId: g.clientId, scope: "" };
342 refreshGrant(app.db, { ...input, refreshToken: g.refresh! });
outdated

This test only calls the action, so the screen change would pass without it. Drive oauthGrantsScreen and assert the rendered text.

343 refreshGrant(app.db, { ...input, refreshToken: g.refresh! });
344 const drawn = terminal(alice).draw();
345 expect(drawn).toContain("Revoked after a token was reused: Reused [31m in terminal");
346 expect(drawn).not.toContain("\x1b");
347 expect(terminal(undefined).draw()).not.toContain("token was reused");
348 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs