Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions workers/mcp/src/agent-connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ function exactField(value: string): string {
return trimmed;
}

/** Only the displayed name may be shortened: the page shows it as plain text, at most 60 characters. */
/** Only the displayed name may be shortened (to the API's 200-character limit); the page itself shows at most 60. */
function displayField(value: string): string {
const trimmed = value.trim();
if (!trimmed) throw new ConsentFieldError("empty client name");
Expand Down Expand Up @@ -135,7 +135,10 @@ export function returnParams(url: URL): { state: string; code: string } | null {
return { state, code };
}

export type ExchangeResult = { ok: true; apiKey: string; scopes: string[] } | { ok: false; status: number };
export type ExchangeResult =
| { ok: true; apiKey: string; scopes: string[] }
// keyCreated: the API answered 200, so it has created the key, but its body is unusable.
| { ok: false; status: number; keyCreated?: boolean };

/** Server-to-server exchange of the single-use code for the agent key. */
export async function exchangeCode(
Expand All @@ -161,10 +164,10 @@ export async function exchangeCode(
if (response.status !== 200) return { ok: false, status: response.status };
try {
const body = (await response.json()) as { api_key?: unknown; scopes?: unknown };
if (typeof body.api_key !== "string" || !body.api_key) return { ok: false, status: 502 };
if (typeof body.api_key !== "string" || !body.api_key) return { ok: false, status: 502, keyCreated: true };
const scopes = Array.isArray(body.scopes) ? body.scopes.filter((s): s is string => typeof s === "string") : [];
return { ok: true, apiKey: body.api_key, scopes };
} catch {
return { ok: false, status: 502 };
return { ok: false, status: 502, keyCreated: true };
}
}
6 changes: 4 additions & 2 deletions workers/mcp/src/consent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,8 @@ export async function handleAuthorize(
}

const RESTART = "<p>La connexion n'a pas abouti. Relancez-la depuis votre agent. Aucune clé n'a été créée.</p>";
// After a successful exchange the API has created the agent key: never claim otherwise.
const RESTART_AFTER_EXCHANGE = "<p>La connexion n'a pas abouti. Relancez-la depuis votre agent.</p>";

function grantedScopes(form: FormData): string[] {
return form
Expand Down Expand Up @@ -326,7 +328,7 @@ async function handleReturn(
return page(RESTART, 400, finished.headers);
}
const exchanged = await exchangeCode(baseUrl, config, params, fetchImpl);
if (!exchanged.ok) return page(RESTART, 400, finished.headers);
if (!exchanged.ok) return page(exchanged.keyCreated ? RESTART_AFTER_EXCHANGE : RESTART, 400, finished.headers);
const apiKey = exchanged.apiKey;
const stored = (finished.data ?? {}) as { scope?: unknown };
// Scopes: what the user granted here, the client asked for, AND the API recorded for this key (IMPL-3).
Expand All @@ -336,7 +338,7 @@ async function handleReturn(
finished.request.scope.includes(name) &&
exchanged.scopes.includes(name),
);
if (!scope.includes("mcp:read")) return page(RESTART, 400, finished.headers);
if (!scope.includes("mcp:read")) return page(RESTART_AFTER_EXCHANGE, 400, finished.headers);
// userId is stored in the clear by the OAuth library. It must not be the key or its hash.
const completed = await oauth.completeAuthorization({
request: finished.request,
Expand Down
35 changes: 35 additions & 0 deletions workers/mcp/test/agent-connect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,3 +279,38 @@ test("IMPL-3: the granted scopes are also limited to those the API recorded for
assert.equal(response.status, 302);
assert.deepEqual(calls.complete[0].scope, ["mcp:read"]);
});

test("the exchange never follows a redirect: the dedicated secret is not re-sent to another host", async () => {
const calls: Calls = { begin: 0, finish: 0, complete: [] };
const oauth = fakeOauth(calls, async () => ({ request: AUTH, data: { scope: ["mcp:read"] }, headers: new Headers() }));
const seen: RequestInit[] = [];
const impl = (async (_url: string | URL | Request, init?: RequestInit) => {
seen.push(init ?? {});
if (init?.redirect !== "manual") throw new Error("the exchange must not follow redirects");
return new Response(null, { status: 302, headers: { Location: "https://evil.example/collect" } });
}) as typeof fetch;
const response = await handleAuthorize(new Request(RETURN), oauth, BASE, impl, CONFIG);
assert.equal(response.status, 400);
assert.equal(seen.length, 1);
assert.equal(seen[0].redirect, "manual");
assert.equal(calls.complete.length, 0);
});

test("after a 200 exchange, a failure never claims that no key was created", async () => {
for (const body of ["not json", JSON.stringify({ scopes: ["mcp:read"] })]) {
const calls: Calls = { begin: 0, finish: 0, complete: [] };
const oauth = fakeOauth(calls, async () => ({ request: AUTH, data: { scope: ["mcp:read"] }, headers: new Headers() }));
const impl = (async () => new Response(body, { status: 200 })) as typeof fetch;
const response = await handleAuthorize(new Request(RETURN), oauth, BASE, impl, CONFIG);
assert.equal(response.status, 400);
const text = await response.text();
assert.match(text, /Relancez-la depuis votre agent/);
assert.doesNotMatch(text, /Aucune clé/);
}
// Same when the exchange succeeds but the final scope lacks mcp:read.
const calls: Calls = { begin: 0, finish: 0, complete: [] };
const oauth = fakeOauth(calls, async () => ({ request: AUTH, data: { scope: ["mcp:read"] }, headers: new Headers() }));
const impl = (async () => new Response(JSON.stringify({ api_key: AGENT_KEY, scopes: ["mcp:write"] }), { status: 200 })) as typeof fetch;
const text = await (await handleAuthorize(new Request(RETURN), oauth, BASE, impl, CONFIG)).text();
assert.doesNotMatch(text, /Aucune clé/);
});