iterate.com / cloud

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

cloud / internal-packages / installer / test / mcp-relay.mjsmain at aacbc74

// mcp-relay.mjs — the relay (worker/mcp-relay.js) against a fake deployment: a stubbed fetch that
// answers as a deployment's identity provider and MCP server, and an in-memory KV. It shows what
// the relay keeps, which token reaches the deployment, and that a connection the deployment ended
// is removed. Run: node test/mcp-relay.mjs
import assert from "node:assert/strict";
import { createHash, randomBytes } from "node:crypto";
import { registerHooks } from "node:module";
import { test } from "node:test";

// The OAuth library imports the Workers runtime's `WorkerEntrypoint`, which Node does not have.
registerHooks({
  resolve: (specifier, context, next) =>
    specifier === "cloudflare:workers"
      ? { url: "data:text/javascript,export class WorkerEntrypoint {}", shortCircuit: true }
      : next(specifier, context),
});
const { default: relay, deploymentOf } = await import("../worker/mcp-relay.js");

const RELAY = "https://cloud.test";
// The installer's own KV: the relay is given it, as on a deployed Worker, and must leave it empty.
const installerKv = memoryKv();
const ISSUER = "https://iterate.example.com";
const REDIRECT = "https://app.test/callback";

/** KV in memory, as much of it as the OAuth library uses. */
function memoryKv() {
  const rows = new Map();
  return {
    rows,
    get: async (key, options) => {
      const value = rows.get(key);
      if (value === undefined) return null;
      return (options?.type || options) === "json" ? JSON.parse(value) : value;
    },
    put: async (key, value) => void rows.set(key, value),
    delete: async (key) => void rows.delete(key),
    list: async ({ prefix = "" } = {}) => ({
      keys: [...rows.keys()].filter((key) => key.startsWith(prefix)).map((name) => ({ name })),
      list_complete: true,
    }),
  };
}

/** The deployment: its metadata, its token endpoint and its MCP server. `seen` is what reached
 *  it; `ended` makes it refuse a refresh, as it does when a member's grant is gone. */
function fakeDeployment() {
  const seen = { tokenRequests: [], mcp: [] };
  const state = { ended: false, issued: 0 };
  const json = (body, status = 200) => Response.json(body, { status });
  globalThis.fetch = async (input, init = {}) => {
    const url = new URL(input instanceof Request ? input.url : input);
    if (url.href === `${ISSUER}/.well-known/oauth-protected-resource/mcp`)
      return json({ resource: `${ISSUER}/mcp`, authorization_servers: [ISSUER] });
    if (url.href === `${ISSUER}/.well-known/oauth-authorization-server`)
      return json({
        issuer: ISSUER,
        authorization_endpoint: `${ISSUER}/oauth2/auth`,
        token_endpoint: `${ISSUER}/oauth2/token`,
        client_id_metadata_document_supported: true,
        code_challenge_methods_supported: ["S256"],
      });
    if (url.href === `${ISSUER}/oauth2/token`) {
      const fields = Object.fromEntries(new URLSearchParams(String(init.body)));
      seen.tokenRequests.push(fields);
      if (state.ended) return json({ error: "invalid_grant" }, 400);
      state.issued += 1;
      return json({
        access_token: `deployment-access-${state.issued}`,
        refresh_token: `deployment-refresh-${state.issued}`,
        expires_in: 3600,
      });
    }
    if (url.href === `${ISSUER}/mcp`) {
      seen.mcp.push(new Headers(init.headers).get("authorization"));
      return json({ jsonrpc: "2.0", id: 1, result: {} });
    }
    return new Response("not the deployment\n", { status: 404 });
  };
  return { seen, state };
}

test("the relay keeps no token it can read, sends the deployment its own token, and removes a connection the deployment ended", async () => {
  const kv = memoryKv();
  const { seen, state } = fakeDeployment();
  const cookies = [];
  const ask = async (path, init = {}) => {
    const headers = new Headers(init.headers);
    if (cookies.length) headers.set("cookie", cookies.join("; "));
    const answer = await relay.fetch(
      new Request(`${RELAY}${path}`, { ...init, headers, redirect: "manual" }),
      { RELAY: kv, SESSIONS: installerKv },
      { waitUntil() {}, passThroughOnException() {} },
    );
    for (const cookie of answer.headers.getSetCookie()) cookies.push(cookie.split(";")[0]);
    return answer;
  };
  const form = (fields) => ({ method: "POST", body: new URLSearchParams(fields) });

  // the app registers, and the person names the deployment
  const client = await (
    await ask("/oauth2/register", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ redirect_uris: [REDIRECT], token_endpoint_auth_method: "none" }),
    })
  ).json();
  const verifier = randomBytes(32).toString("base64url");
  const authorize = `/oauth2/auth?${new URLSearchParams({
    response_type: "code",
    client_id: client.client_id,
    redirect_uri: REDIRECT,
    scope: "iterate",
    resource: `${RELAY}/mcp`,
    state: "app-state",
    code_challenge: createHash("sha256").update(verifier).digest("base64url"),
    code_challenge_method: "S256",
  })}`;
  const handle = /name="handle" value="([^"]+)"/.exec(await (await ask(authorize)).text())[1];
  const named = await ask(authorize, form({ handle, decision: "approve", domain: "example.com" }));
  const there = new URL(named.headers.get("location"));
  assert.equal(there.origin + there.pathname, `${ISSUER}/oauth2/auth`);
  assert.equal(there.searchParams.get("client_id"), `${RELAY}/oauth2/client.json`);
  assert.equal(there.searchParams.get("resource"), `${ISSUER}/mcp`);

  // the deployment sends the person back with its code, and the app gets the relay's tokens
  const back = await ask(
    `/oauth2/callback?${new URLSearchParams({ code: "deployment-code", state: there.searchParams.get("state"), iss: ISSUER })}`,
  );
  const home = new URL(back.headers.get("location"));
  assert.equal(home.origin + home.pathname, REDIRECT);
  const token = async (fields) => {
    const answer = await ask(
      "/oauth2/token",
      form({ ...fields, client_id: client.client_id, resource: `${RELAY}/mcp` }),
    );
    return { status: answer.status, ...(await answer.json()) };
  };
  const first = await token({
    grant_type: "authorization_code",
    code: home.searchParams.get("code"),
    redirect_uri: REDIRECT,
    code_verifier: verifier,
  });
  assert.equal(first.status, 200);

  // WHERE THE RELAY KEEPS IT: in its own namespace, and nothing beside the installer's sign-ins
  assert.ok(kv.rows.size > 0);
  assert.deepEqual([...installerKv.rows.keys()], []);
  // WHAT THE RELAY KEEPS: no token of the deployment and none of the app, in any row
  const kept = () => [...kv.rows.entries()].map(([key, value]) => `${key}=${value}`).join("\n");
  for (const secret of ["deployment-access-1", "deployment-refresh-1", first.access_token])
    assert.ok(!kept().includes(secret), `a row holds ${secret.slice(0, 18)}…`);
  assert.ok(!kept().includes(first.refresh_token), "a row holds the app's refresh token");
  const grant = [...kv.rows.keys()].find((key) => key.startsWith("grant:"));
  assert.deepEqual(JSON.parse(kv.rows.get(grant)).metadata, { domain: "example.com" });

  // the deployment gets its own token, never the app's
  const call = await ask("/mcp", {
    method: "POST",
    headers: { authorization: `Bearer ${first.access_token}`, "content-type": "application/json" },
    body: "{}",
  });
  assert.equal(call.status, 200);
  assert.deepEqual(seen.mcp, ["Bearer deployment-access-1"]);

  // a refresh at the relay refreshes at the deployment
  const second = await token({ grant_type: "refresh_token", refresh_token: first.refresh_token });
  assert.equal(second.status, 200);
  assert.equal(seen.tokenRequests.at(-1).refresh_token, "deployment-refresh-1");

  // the deployment ended the grant: the refresh is refused and the connection is removed
  state.ended = true;
  const third = await token({ grant_type: "refresh_token", refresh_token: second.refresh_token });
  assert.equal(third.status, 400);
  assert.equal(third.error, "invalid_grant");
  assert.deepEqual(
    [...kv.rows.keys()].filter((key) => key.startsWith("grant:") || key.startsWith("token:")),
    [],
  );
});

test("a typed domain cannot name another deployment's sign-in: the identity provider is the domain's own host", async () => {
  const VICTIM = "https://iterate.victim.example";
  const honest = (issuer) => ({
    issuer,
    authorization_endpoint: `${issuer}/oauth2/auth`,
    token_endpoint: `${issuer}/oauth2/token`,
    client_id_metadata_document_supported: true,
    code_challenge_methods_supported: ["S256"],
  });
  /** `deploymentOf("evil.example")`, with the hostile domain's two documents as given. */
  const named = (resourceDocument, providerDocument) => {
    const EVIL = "https://iterate.evil.example";
    const documents = {
      [`${EVIL}/.well-known/oauth-protected-resource/mcp`]: resourceDocument(EVIL),
      [`${EVIL}/.well-known/oauth-authorization-server`]: providerDocument(EVIL),
      [`${VICTIM}/.well-known/oauth-authorization-server`]: honest(VICTIM),
    };
    globalThis.fetch = async (input) => {
      const document = documents[String(input instanceof Request ? input.url : input)];
      return document ? Response.json(document) : new Response("no\n", { status: 404 });
    };
    return deploymentOf("evil.example");
  };
  const own = (issuer) => ({ resource: `${issuer}/mcp`, authorization_servers: [issuer] });

  // an honest deployment is found
  assert.equal(
    (await named(own, honest))?.tokenEndpoint,
    "https://iterate.evil.example/oauth2/token",
  );
  // the victim's whole identity provider, named by the hostile domain's resource document
  assert.equal(
    await named((evil) => ({ resource: `${evil}/mcp`, authorization_servers: [VICTIM] }), honest),
    null,
  );
  // the victim's sign-in page with the hostile domain's own token endpoint
  assert.equal(
    await named(own, (evil) => ({
      ...honest(evil),
      authorization_endpoint: `${VICTIM}/oauth2/auth`,
    })),
    null,
  );
  // the hostile domain's sign-in page with a token endpoint elsewhere
  assert.equal(
    await named(own, (evil) => ({
      ...honest(evil),
      token_endpoint: "https://elsewhere.example/t",
    })),
    null,
  );
});

test("a domain named iterate.<tld> is never read at its own host, which serves the deployment's loaded code", async () => {
  const asked = [];
  const answer = (issuer) => ({
    [`${issuer}/.well-known/oauth-protected-resource/mcp`]: {
      resource: `${issuer}/mcp`,
      authorization_servers: [issuer],
    },
    [`${issuer}/.well-known/oauth-authorization-server`]: {
      issuer,
      authorization_endpoint: `${issuer}/oauth2/auth`,
      token_endpoint: `${issuer}/oauth2/token`,
      client_id_metadata_document_supported: true,
      code_challenge_methods_supported: ["S256"],
    },
  });
  // loaded code on the apex answers as a deployment would; so does the real platform
  const documents = { ...answer("https://iterate.com"), ...answer("https://iterate.iterate.com") };
  globalThis.fetch = async (input) => {
    const url = String(input instanceof Request ? input.url : input);
    asked.push(new URL(url).host);
    return documents[url] ? Response.json(documents[url]) : new Response("no\n", { status: 404 });
  };
  assert.equal((await deploymentOf("iterate.com"))?.domain, "iterate.com");
  assert.deepEqual([...new Set(asked)], ["iterate.iterate.com"]);
  // a platform's own hostname is still taken as typed
  asked.length = 0;
  Object.assign(documents, answer("https://iterate.example.com"));
  assert.equal((await deploymentOf("iterate.example.com"))?.domain, "example.com");
});

/** One request to the relay with its own empty storage, and no cookie kept. */
const askRelay = (kv, path, init = {}) =>
  relay.fetch(
    new Request(`${RELAY}${path}`, { ...init, redirect: "manual" }),
    { RELAY: kv, SESSIONS: installerKv },
    { waitUntil() {}, passThroughOnException() {} },
  );
const authorizeFor = (clientId) =>
  `/oauth2/auth?${new URLSearchParams({
    response_type: "code",
    client_id: clientId,
    redirect_uri: REDIRECT,
    scope: "iterate",
    resource: `${RELAY}/mcp`,
    state: "app-state",
  })}`;

test("an app that registered with a secret is held to PKCE with S256 too", async () => {
  const kv = memoryKv();
  const client = await (
    await askRelay(kv, "/oauth2/register", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        redirect_uris: [REDIRECT],
        token_endpoint_auth_method: "client_secret_basic",
      }),
    })
  ).json();
  const answer = await askRelay(kv, authorizeFor(client.client_id));
  assert.equal(answer.status, 302);
  assert.equal(
    new URL(answer.headers.get("location")).searchParams.get("error"),
    "invalid_request",
  );
});

test("a form whose handle the page did not give this browser makes no request to the domain it names", async () => {
  const fetched = [];
  globalThis.fetch = async (input) => {
    fetched.push(String(input instanceof Request ? input.url : input));
    return new Response("no\n", { status: 404 });
  };
  const kv = memoryKv();
  const send = (headers, handle) =>
    askRelay(kv, authorizeFor("any"), {
      method: "POST",
      headers,
      body: new URLSearchParams({ handle, decision: "approve", domain: "example.com" }),
    });
  // the cookie the library would set for a handle: named by the handle's hash, with the hash in it
  const cookieOf = (handle) => {
    const hash = createHash("sha256").update(handle).digest("hex");
    return `__Host-oauth-consent-${hash.slice(0, 16)}=${hash}`;
  };
  // no cookie at all, and the page's prefix only inside another cookie's value
  for (const headers of [{}, { cookie: "other=__Host-oauth-consent" }])
    assert.equal((await send(headers, "x")).status, 400);
  // A made-up handle with the cookie that fits it: anybody can make both, and no page made a row.
  assert.equal((await send({ cookie: cookieOf("made-up") }, "made-up")).status, 400);
  // a cookie of the page's kind for another handle
  assert.equal((await send({ cookie: cookieOf("another") }, "made-up")).status, 400);
  assert.deepEqual(fetched, []);

  // A handle the page gave: without its cookie no request, with it the domain is read. A domain
  // that does not answer leaves the handle good, so the same form can be sent again.
  const client = await (
    await askRelay(kv, "/oauth2/register", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ redirect_uris: [REDIRECT], token_endpoint_auth_method: "none" }),
    })
  ).json();
  const authorize = `${authorizeFor(client.client_id)}&code_challenge=${"c".repeat(43)}&code_challenge_method=S256`;
  const asked = await askRelay(kv, authorize);
  const handle = /name="handle" value="([^"]+)"/.exec(await asked.text())[1];
  const given = asked.headers.getSetCookie()[0].split(";")[0];
  assert.equal(given, cookieOf(handle), "the library binds a handle as `waits` reads it");
  assert.equal((await send({}, handle)).status, 400);
  assert.deepEqual(fetched, []);
  for (let n = 1; n <= 2; n++) {
    const answer = await send({ cookie: given }, handle);
    assert.equal(answer.status, 400);
    assert.match(await answer.text(), /No iterate deployment answered/);
    assert.equal(fetched.length, n);
  }
  assert.equal(fetched[0], "https://iterate.example.com/.well-known/oauth-protected-resource/mcp");
});

test("an address at its registration limit is refused and uses up nobody else's", async () => {
  const kv = memoryKv();
  const registerFrom = (address) =>
    askRelay(kv, "/oauth2/register", {
      method: "POST",
      headers: { "content-type": "application/json", "cf-connecting-ip": address },
      body: JSON.stringify({ redirect_uris: [REDIRECT], token_endpoint_auth_method: "none" }),
    });
  for (let n = 0; n < 20; n++) assert.equal((await registerFrom("192.0.2.1")).status, 201);
  for (let n = 0; n < 5; n++) assert.equal((await registerFrom("192.0.2.1")).status, 429);
  // the count of all registrations holds the 20 that were made, not the 5 that were refused
  const inAll = [...kv.rows.entries()].find(([key]) => /^registrations:\d+$/.test(key));
  assert.equal(inAll[1], "20");
  assert.equal((await registerFrom("192.0.2.2")).status, 201);
});