iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

secrets: an OAuth token request and each refresh name the resource #7

merged oauth-token-resource was squashed into main as 236e53a by jonas, 2026-11-26 16:36 UTC. jonas opened it 2026-11-26 16:35 UTC.

Relanded from iterate/private#1428 (head `07f360d6d`): core/ of iterate/private is frozen, and a platform change is a pull here. The diff applied to this repository's `core/` with no change. Checked here: typecheck and tests of `core/secrets-worker` (420), `core/auth-worker` (572) and `core/lib` (1091).

Jonas, typed in Claude session 34855f3c on beelink at 16:13:58 UTC, 26 Nov 2026: "the things that are open that we have said we want to merge ... need to be merged and taken care of. I want as little open stuff as possible. I'm okay to just like fast forward through the MCP stuff".

The vault's OAuth client sends `resource` in the token request and in each refresh, not only in the authorization request. RFC 8707 and the MCP authorization spec ask for it in all three.

## What happened

`itx.config.mcpConnect({ server: "https://petshop.iterate.com/mcp" })` began a sign-in with `extra: { resource: "https://petshop.iterate.com/mcp" }`. Jonas consented with his passkey. The callback then said: "Storing the tokens for /secrets/petshop-iterate-com-124f8dcd-mcp failed: oauth: the token endpoint answered 400".

## The cause

- `beginSecretOAuth` puts `extra` in the authorization URL only.
- `completeSecretOAuth` sent `grant_type`, `code`, `redirect_uri`, `code_verifier` and `client_id`, with no `resource`.
- The issuer's `tokenEndpointResponse` (`core/auth-worker/src/oauth.ts`) picks its authorization server by the form's `resource`. With none, it picks the stack's default server, which does not know the grant for a mind hostname, and answers 400.
- The issuer's own self-test, Claude and ChatGPT send `resource` in the token request, so their sign-ins to the same issuer work.

## The change

- `completeSecretOAuth`: when the attempt's `extra` names `resource`, the token request carries it.
- The `oauth-refresh-token` record keeps that `resource` (`SecretRefresh` in `core/lib/src/api.ts`, and the strict stored schema in `secret/contract.ts`). `refreshSecretMaterial` sends it with each `refresh_token` grant. A record without one refreshes as before.
- `oauthTokenRequest` sends no param that has no value, so callers write `resource` directly.

A secret that is already stored has no `resource` and refreshes as today. The pet shop's failed attempt stored nothing, so a new sign-in link is needed after the deploy.

## Review

`/agents/reviewer` read the first head (`d633ee21a`) and found two faults, both fixed in `07f360d6d`:

1. An authorization endpoint that carries its own `resource` query, with no `extra.resource`: the token request left it out. Now the token request's resource is the one the authorization URL carried: `extra`'s, or else the endpoint's own.
2. `extra.resource: ""`: the authorization URL left it out, but the refresh record kept `""`, which the stored schema refused after the tokens came. An empty resource is now none. The stored schema takes any non-empty string, so no resource that the token request sent can make a record that does not store.

A new test covers both cases.

The reviewer then read `07f360d6d` and found one more case: an authorization endpoint whose own query has two `resource` parameters, with no `extra.resource`. The token request then names only the first. I do not change this, because it is no fault:

- RFC 8707 §2.2 lets a token request name fewer resources than the authorization request did. The issuer then gives a token for those alone. The grant keeps the others.
- A vault secret holds one grant for one server, pinned to that server's hosts. One resource fits it.
- Before this change the token request named no resource at all, so nothing gets worse.
- No caller configures an authorization endpoint with a `resource` in its address: `mcpConnect` and the other callers use `extra.resource`.

## Live proof

The coordinator session ran this on the dev mind `iterate.blummit.com`, which runs `main` (`7efba8ca0`) plus this pull request's head (`07f360d6d`):

- `itx.config.mcpConnect({ server: "https://guestbook.blummit.com/mcp" })`. The guestbook is a host resource of the mind's own issuer: the case that gave the 400.
- The agent seat consented. The vault stored `/secrets/guestbook-blummit-com-aa370a1e-mcp` with refresh `oauth-refresh-token`.
- `connectToMcp` with that secret: `initialize` answered 200, the tool list had 3 tools, and `list_entries` ran.

## Why in core

The vault's OAuth client is `core/secrets-worker`. The bug is there, and a userland caller cannot reach the token request. This is a small core fix (Jonas: "core fixes always fine unless super big / complex").

## Tests

- `core/secrets-worker/src/secret-oauth-resource.test.ts` (new): with `extra.resource`, the authorization URL, the token request and the refresh request carry it, and the record keeps it. Without it, none of them do. Against `main`'s `secret-oauth.ts` the test fails: `expected null to be 'https://petshop.iterate.com/mcp'`.
- `core/auth-worker/src/oauth.test.ts`: a code for a mind hostname is refused with 400 when the token request leaves out `resource`, and is taken (200, a member's token) when it names it. This is the field failure, reproduced on the issuer.

Ran locally: `core/secrets-worker` 419 tests, `core/auth-worker` 567, `core/lib` 1622; the whole-repo typecheck, lint on the touched packages, format and knip.

Risk: low. A token request and a refresh gain one form field when the attempt named a resource. A provider that rejects an unknown `resource` would have rejected the authorization request first.

Session: claude 610825ae-c273-4d70-8290-b835b0d884b6 on beelink

Conversation

Nobody has said anything yet.

Sign in to comment or to merge.

Files

6 files changed

M core/auth-worker/src/oauth.test.ts
@@ -159,6 +159,23 @@
   expect(await whoIs(stack, token, HOST)).toBeNull();
 });
 
+test("a code for a mind hostname is taken only when the token request names the resource too, as RFC 8707 says", async () => {
+  const stack = stackOf({ zones: ["example.com"] });
+  // the vault's client before the fix: the authorization request named the resource, the token
+  // request did not, so the stack's default server took the code and did not know it
+  const withoutResource = async (request: Request) => {
+    const form = new URLSearchParams(await request.text());
+    form.delete("resource");
+    return tokenEndpointResponse(stack, tokenRequest(Object.fromEntries(form)), ctx);
+  };
+  const refused = await exchanged(stack, HOST, owner, "app", withoutResource);
+  expect(refused.answer).toMatchObject({ status: 400 });
+  const taken = await exchanged(stack, HOST, owner);
+  expect(taken.answer).toMatchObject({ status: 200 });
+  const { access_token: token } = TokenAnswer.parse(await taken.answer.json());
+  expect(await whoIs(stack, token, HOST)).toMatchObject({ member: true });
+});
+
 test("a path on a mind hostname names the host, as an MCP client names its server; nothing else changes", () => {
   const known = (resource: string) => knownResourceOf(env, resource);
   expect(known("https://guestbook.example.com/mcp")).toBe("https://guestbook.example.com");
M core/lib/src/api.ts
@@ -480,6 +480,10 @@
        *  the provider: a refresh whose answer names a scope outside it, or names none, is refused,
        *  and the new tokens are not kept. */
       grantedWithin?: string[];
+      /** RFC 8707: the resource the grant is for (an MCP server's URL), as the authorization
+       *  request named it in `extra.resource`. Each refresh sends it again: an issuer that serves
+       *  more than one resource picks its authorization server by it. */
+      resource?: string;
       /** `cloud`: the client is that of the iterate Cloud at `origin`, and `tokenEndpoint` is that
        *  Cloud's broker, which adds the client secret. The refresh token in the material is sealed
        *  for this deployment and means nothing anywhere else. `stack`: the stack's former client
A core/secrets-worker/src/secret-oauth-resource.test.ts
@@ -0,0 +1,86 @@
+import { expect, test } from "vitest";
+import { beginSecretOAuth, completeSecretOAuth, normalizeSecretOAuth } from "./secret-oauth.ts";
+import { refreshSecretMaterial } from "./secrets.ts";
+
+// RFC 8707 and the MCP authorization spec: a client names the resource in the authorization
+// request AND in the token requests. The mind's issuer picks its authorization server by the
+// token request's `resource`: with none, the stack's default one refuses a pet shop's code (400).
+test("the resource that the authorization request named goes in the token request and in each refresh, and none goes when none was named", async () => {
+  for (const resource of ["https://petshop.iterate.com/mcp", undefined]) {
+    const options = normalizeSecretOAuth({
+      authorizationEndpoint: "https://iterate.iterate.com/oauth/authorize",
+      tokenEndpoint: "https://iterate.iterate.com/oauth/token",
+      clientId: "client",
+      urls: ["https://petshop.iterate.com", "https://iterate.iterate.com"],
+      extra: resource ? { resource } : {},
+    });
+    const { pending, authorizationUrl } = await beginSecretOAuth(options, {
+      redirectUri: "https://iterate.iterate.com/secrets/callback",
+      state: "state",
+      nonce: "nonce",
+    });
+    expect(new URL(authorizationUrl).searchParams.get("resource")).toBe(resource || null);
+
+    const forms: URLSearchParams[] = [];
+    const tokenEndpoint = async (request: Request) => {
+      forms.push(new URLSearchParams(await request.text()));
+      return Response.json({ access_token: "a", refresh_token: "r", expires_in: 3600 });
+    };
+    const plain = async (secret: string) => secret;
+    const record = await completeSecretOAuth(pending, "code", tokenEndpoint, plain);
+    expect(forms[0]?.get("grant_type")).toBe("authorization_code");
+    expect(forms[0]?.get("resource")).toBe(resource || null);
+
+    // the record keeps it, and the refresh sends it again
+    const refresh = record.refresh;
+    if (refresh?.kind !== "oauth-refresh-token") throw new Error("no oauth refresh");
+    expect(refresh).toMatchObject({ resource });
+    await refreshSecretMaterial(refresh, record.material, tokenEndpoint, plain);
+    expect(forms[1]?.get("grant_type")).toBe("refresh_token");
+    expect(forms[1]?.get("resource")).toBe(resource || null);
+  }
+});
+
+test("the resource is the one the authorization URL carried: the endpoint's own when extra names none, and none when extra's is empty", async () => {
+  const cases = [
+    {
+      endpoint:
+        "https://iterate.iterate.com/oauth/authorize?resource=https%3A%2F%2Fpetshop.iterate.com%2Fmcp",
+      extra: {},
+      sent: "https://petshop.iterate.com/mcp",
+    },
+    {
+      endpoint: "https://iterate.iterate.com/oauth/authorize",
+      extra: { resource: "" },
+      sent: null,
+    },
+  ];
+  for (const { endpoint, extra, sent } of cases) {
+    const options = normalizeSecretOAuth({
+      authorizationEndpoint: endpoint,
+      tokenEndpoint: "https://iterate.iterate.com/oauth/token",
+      clientId: "client",
+      urls: ["https://petshop.iterate.com", "https://iterate.iterate.com"],
+      extra,
+    });
+    const { pending, authorizationUrl } = await beginSecretOAuth(options, {
+      redirectUri: "https://iterate.iterate.com/secrets/callback",
+      state: "state",
+      nonce: "nonce",
+    });
+    expect(new URL(authorizationUrl).searchParams.get("resource")).toBe(sent);
+    const forms: URLSearchParams[] = [];
+    const record = await completeSecretOAuth(
+      pending,
+      "code",
+      async (request) => {
+        forms.push(new URLSearchParams(await request.text()));
+        return Response.json({ access_token: "a", refresh_token: "r" });
+      },
+      async (secret) => secret,
+    );
+    expect(forms[0]?.get("resource")).toBe(sent);
+    // the record holds a resource the stored schema takes, or none
+    expect(record.refresh).toMatchObject({ resource: sent || undefined });
+  }
+});
M core/secrets-worker/src/secret-oauth.ts
@@ -500,6 +500,15 @@
 ): Promise<SecretRecord> {
   const { options } = pending;
   const { cloud } = options;
+  // RFC 8707 and the MCP authorization spec: the resource goes in the token request too. An issuer
+  // that serves more than one resource (a mind's own, for each of its hostnames) picks its
+  // authorization server by it, and refuses a code that the default one did not grant.
+  // It is the one the authorization URL carried: `extra`'s, or else the endpoint's own query's.
+  // An empty one is none, as it was in the authorization URL.
+  const resource =
+    options.extra.resource ||
+    new URL(options.authorizationEndpoint).searchParams.get("resource") ||
+    undefined;
   const response = await fetchFn(
     oauthTokenRequest({
       tokenEndpoint: options.tokenEndpoint,
@@ -513,6 +522,7 @@
           redirect_uri: pending.redirectUri,
           code_verifier: pending.codeVerifier,
         }),
+        resource,
         ...(cloud && { cloud_proof: cloudProof }),
       },
     }),
@@ -524,6 +534,7 @@
     clientAuth: options.clientAuth,
     // the ceiling holds at each refresh too
     grantedWithin: options.grantedWithin,
+    resource,
     // the Cloud that the attempt named is the secret's Cloud from here on
     ...(cloud && { client: { cloud: cloud.name, origin: cloud.origin } }),
   };
M core/secrets-worker/src/secret/contract.ts
@@ -34,6 +34,8 @@
     clientAuth: z.enum(["client_secret_basic", "client_secret_post", "none"]),
     /** The grant's scope ceiling, checked again at each refresh (../secret-oauth.ts). */
     grantedWithin: z.array(z.string().min(1)).optional(),
+    /** RFC 8707: the resource the grant is for, sent again at each refresh (../secret-oauth.ts). */
+    resource: z.string().min(1).optional(),
     /** The iterate Cloud's client that brokers the refresh, and that Cloud's origin, when the
      *  grant was connected through one (../cloud-client.ts). Or the stack's own client at
      *  Cloudflare, which the stack does not make: such a grant is read, and does not refresh. */
M core/secrets-worker/src/secrets.ts
@@ -654,16 +654,17 @@
   return isRecord(body) ? body : {};
 }
 
-// A client with no secret is sent as `none`, whatever it declared.
+// A client with no secret is sent as `none`, whatever it declared. A param with no value is not sent.
 export function oauthTokenRequest(input: {
   tokenEndpoint: string;
   clientId: string;
   clientSecret: string;
   clientAuth: ClientAuth;
-  params: Record<string, string>;
+  params: Record<string, string | undefined>;
 }): Request {
   const method = input.clientSecret ? input.clientAuth : "none";
-  const body = new URLSearchParams(input.params);
+  const body = new URLSearchParams();
+  for (const [key, value] of Object.entries(input.params)) if (value) body.set(key, value);
   if (method !== "client_secret_basic") body.set("client_id", input.clientId);
   if (method === "client_secret_post") body.set("client_secret", input.clientSecret);
   return new Request(input.tokenEndpoint, {
@@ -751,7 +752,12 @@
     clientId,
     clientSecret: await clientSecretOf(clientSecret, refresh.tokenEndpoint),
     clientAuth: refresh.clientAuth || "client_secret_basic",
-    params: { grant_type: "refresh_token", refresh_token: refreshToken },
+    params: {
+      grant_type: "refresh_token",
+      refresh_token: refreshToken,
+      // RFC 8707: the resource that the authorization request named (./secret-oauth.ts)
+      resource: refresh.resource,
+    },
   });
   const response = await fetchFn(request).catch((error: unknown) => {
     throw new RefreshUnanswered(