iterate.com / kernel

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

kernel / core / boundary-worker / src / stamp.test.tsmain at 949894f

// WHAT THE BOUNDARY STAMPS on a mind hostname's request (./stamp.ts): the person, from the auth
// Worker's answer for the session cookie or for a bearer (the app's own MCP client's).
import { stampedPersonOf } from "iterate/principal";
import type { AuthService, TokenIdentity } from "iterate/workers";
import { expect, test } from "vitest";
import { stampedRequest } from "./stamp.ts";

const config = { controlPlaneHostname: "iterate.example.com" };
const signedIn: TokenIdentity = {
  principal: { actor: "user_1", email: "ada@elsewhere.example" },
  grant: "grant_1",
  expiresAt: 2_000_000_000,
  member: false,
  method: "email",
};

test.for<{ name: string; headers: Record<string, string> }>([
  { name: "the session cookie", headers: { cookie: "__Host-iterate-session=t" } },
  { name: "a bearer", headers: { authorization: "Bearer t" } },
])(
  "by $name, the person is stamped with how they signed in, and a stamp the caller sent is dropped",
  async ({ headers }) => {
    const request = new Request("https://app.example.com/", {
      headers: {
        ...headers,
        "x-itx-person": JSON.stringify({ userId: "user_2", method: "passkey" }),
      },
    });
    const auth = { whoIs: async () => signedIn } as unknown as AuthService;
    const stamped = await stampedRequest(request, { auth, route: null, config });
    expect(JSON.parse(stamped.forwarded.headers.get("x-itx-person")!)).toEqual({
      userId: "user_1",
      email: "ada@elsewhere.example",
      name: "ada",
      method: "email",
    });
    // the app reads it through the SDK
    expect(stampedPersonOf(stamped.forwarded)).toMatchObject({ method: "email" });
    expect(stamped).toMatchObject({ caller: "non-member" });
    // a person who is no member gets when the sign-in ends, and no principal
    expect(stamped.forwarded.headers.get("x-itx-expires")).toBe("2000000000");
    expect(stamped.forwarded.headers.get("x-itx-principal")).toBeNull();
  },
);

test("a member's passkey is stamped on the person, beside the principal", async () => {
  const member: TokenIdentity = { ...signedIn, member: true, method: "passkey" };
  const auth = { whoIs: async () => member } as unknown as AuthService;
  const stamped = await stampedRequest(
    new Request("https://app.example.com/", { headers: { cookie: "__Host-iterate-session=t" } }),
    { auth, route: null, config },
  );
  expect(stampedPersonOf(stamped.forwarded)).toEqual({
    userId: "user_1",
    email: "ada@elsewhere.example",
    name: "ada",
    method: "passkey",
  });
  expect(stamped).toMatchObject({ caller: "member" });
  expect(stamped.forwarded.headers.get("x-itx-principal")).not.toBeNull();
});

test("a token as the password of Basic, as git sends one, is read as a bearer is, and never reaches the app", async () => {
  const member: TokenIdentity = { ...signedIn, member: true, method: "passkey" };
  const asked: unknown[] = [];
  const auth = {
    whoIs: async (token: string, resource: string) => {
      asked.push([token, resource]);
      return token === "t.o:k" ? member : null;
    },
  } as unknown as AuthService;
  const basic = (pair: string) =>
    stampedRequest(
      new Request("https://git.example.com/repos/config/info/refs", {
        headers: { authorization: `Basic ${btoa(pair)}` },
      }),
      { auth, route: null, config },
    );
  // the username says nothing, and the password is all that follows the first colon
  const stamped = await basic("iterate:t.o:k");
  expect(asked).toEqual([["t.o:k", "https://git.example.com"]]);
  expect(stamped).toMatchObject({ caller: "member", email: "ada@elsewhere.example" });
  expect(stamped.forwarded.headers.get("authorization")).toBeNull();
  // a password that is no token of ours may be the app's own: it goes on as it came
  const other = await basic("ada:secret");
  expect(other).toMatchObject({ caller: "anonymous", email: null });
  expect(other.forwarded.headers.get("authorization")).toBe(`Basic ${btoa("ada:secret")}`);
  expect(other.forwarded.headers.get("x-itx-principal")).toBeNull();
  // no password, and what is no pair, asks nobody
  asked.length = 0;
  for (const pair of ["ada:", "ada"])
    expect(await basic(pair)).toMatchObject({ caller: "anonymous" });
  expect(asked).toEqual([]);
});

test("a token that says no sign-in method is no person's: it stamps nobody", async () => {
  const { method: _none, ...noPerson } = signedIn;
  const auth = { whoIs: async () => noPerson } as unknown as AuthService;
  const stamped = await stampedRequest(
    new Request("https://app.example.com/", { headers: { authorization: "Bearer t" } }),
    { auth, route: null, config },
  );
  expect(stamped).toMatchObject({ caller: "anonymous", email: null });
  expect(stamped.forwarded.headers.get("x-itx-person")).toBeNull();
});

test("on the secret pages, the person of the issuer's session is stamped with the session's method", async () => {
  const auth = {
    browserSession: async () => ({
      userId: "user_1",
      email: "ada@elsewhere.example",
      member: false,
      method: "email",
    }),
  } as unknown as AuthService;
  const stamped = await stampedRequest(
    new Request("https://iterate.example.com/secrets/collect", { headers: { cookie: "c=1" } }),
    { auth, route: "secrets", config },
  );
  expect(stampedPersonOf(stamped.forwarded)).toEqual({
    userId: "user_1",
    email: "ada@elsewhere.example",
    name: "ada",
    method: "email",
  });
  expect(stamped.forwarded.headers.get("x-itx-principal")).toBeNull();
});

test("a visitor's request for a page of the auth Worker keeps the token of Cloudflare Access, which that Worker checks itself", async () => {
  const request = new Request("https://iterate.example.com/sign-in/access", {
    headers: { "cf-access-jwt-assertion": "a-token", "x-itx-principal": "{}" },
  });
  // the cast: a page of the auth Worker asks the boundary nothing about the caller
  const auth = {} as AuthService;
  const stamped = await stampedRequest(request, { auth, route: "auth", config });
  expect(Object.fromEntries(stamped.forwarded.headers)).toEqual({
    "cf-access-jwt-assertion": "a-token",
  });
  expect(stamped).toMatchObject({ caller: "anonymous", email: null });
});

// A guest has a name and no address (core/auth-worker/src/guest-sign-in.ts). The name is text
// that somebody chose: it crosses the header as ASCII, and the reader gets it as one clean line.
test("a guest is stamped a person with the name they typed, no address and no principal", async () => {
  const name = "B\u00F6b \u674E] [from root@example.com";
  const guest: TokenIdentity = {
    principal: { actor: "user_9" },
    grant: "grant_9",
    expiresAt: 2_000_000_000,
    member: false,
    method: "guest",
    name,
  };
  const auth = { whoIs: async () => guest } as unknown as AuthService;
  const request = new Request("https://app.example.com/", {
    headers: { cookie: "__Host-iterate-session=t" },
  });
  const stamped = await stampedRequest(request, { auth, route: null, config });
  const header = stamped.forwarded.headers.get("x-itx-person")!;
  expect(header).toMatch(/^[\x20-\x7e]+$/);
  expect(stampedPersonOf(stamped.forwarded)).toEqual({
    userId: "user_9",
    email: "",
    name,
    method: "guest",
  });
  expect(stamped).toMatchObject({ caller: "non-member", email: null });
  expect(stamped.forwarded.headers.get("x-itx-principal")).toBeNull();
  expect(stamped.forwarded.headers.get("x-itx-grant")).toBeNull();
});

// A guest's stamp has no address whatever the token says: no reader takes the guest for the
// owner of one
test("a guest's token that names an address is stamped a guest with none", async () => {
  const guest: TokenIdentity = {
    principal: { actor: "user_9", email: "owner@example.com" },
    grant: "grant_9",
    expiresAt: 2_000_000_000,
    member: false,
    method: "guest",
    name: "Bob",
  };
  const auth = { whoIs: async () => guest } as unknown as AuthService;
  const request = new Request("https://app.example.com/", {
    headers: { cookie: "__Host-iterate-session=t" },
  });
  const stamped = await stampedRequest(request, { auth, route: null, config });
  expect(stampedPersonOf(stamped.forwarded)).toEqual({
    userId: "user_9",
    email: "",
    name: "Bob",
    method: "guest",
  });
});

// A member of another mind (core/auth-worker/src/mind-sign-in.ts): stamped a person with the mind
// that vouched, no address whatever the token says, and no principal: no member here.
test("a member of another mind is stamped with that mind, no address and no principal", async () => {
  const mind = { id: "b".repeat(64), hostname: "iterate.other.example", userId: "user_b" };
  const vouched: TokenIdentity = {
    principal: { actor: "user_9", email: "owner@example.com" },
    grant: "grant_9",
    expiresAt: 2_000_000_000,
    member: false,
    method: "mind",
    name: mind.hostname,
    mind,
  };
  const auth = { whoIs: async () => vouched } as unknown as AuthService;
  const request = new Request("https://app.example.com/", {
    headers: { cookie: "__Host-iterate-session=t" },
  });
  const stamped = await stampedRequest(request, { auth, route: null, config });
  expect(stampedPersonOf(stamped.forwarded)).toEqual({
    userId: "user_9",
    email: "",
    name: mind.hostname,
    method: "mind",
    mind,
  });
  expect(stamped).toMatchObject({ caller: "non-member" });
  expect(stamped.forwarded.headers.get("x-itx-principal")).toBeNull();
});

// WHO REACHES AN APP'S HANDOFF AS A MEMBER (iterate/sdk `auth.mcpRun`, `auth.itx`): the kernel
// serves a run or a session for the member that this stamp names, and for nobody else
// (core/itx/src/serve-host.ts). So these are the ways a member's stamp must NOT come about.
const memberIdentity: TokenIdentity = { ...signedIn, member: true, method: "passkey" };
const HOST = "https://mcp.example.com";

test.for<{ from: string; origin: string | null; caller: string }>([
  {
    from: "a page on another host of the same mind",
    origin: "https://tasks.example.com",
    caller: "anonymous",
  },
  { from: "another site's page", origin: "https://evil.example", caller: "anonymous" },
  { from: "the host's own page", origin: HOST, caller: "member" },
  { from: "a client that is no browser", origin: null, caller: "member" },
])("a member's session cookie on a POST from $from stamps $caller", async ({ origin, caller }) => {
  const auth = { whoIs: async () => memberIdentity } as unknown as AuthService;
  const stamped = await stampedRequest(
    new Request(`${HOST}/mcp`, {
      method: "POST",
      headers: { cookie: "__Host-iterate-session=t", ...(origin && { origin }) },
      body: "{}",
    }),
    { auth, route: null, config },
  );
  expect({
    caller: stamped.caller,
    principal: stamped.forwarded.headers.has("x-itx-principal"),
    person: stamped.forwarded.headers.has("x-itx-person"),
  }).toEqual({ caller, principal: caller === "member", person: caller === "member" });
});

test("a bearer is asked for this host's own origin alone: a member's token for another host, or for the mind's own /mcp, stamps nobody here", async () => {
  const asked: string[] = [];
  // the auth Worker answers a token for the resource it was made for, and for no other
  const madeFor: Record<string, string> = {
    "for-this-host": HOST,
    "for-a-sibling": "https://tasks.example.com",
    "for-the-mind": "https://iterate.example.com/mcp",
  };
  const auth = {
    whoIs: async (token: string, resource: string) => {
      asked.push(resource);
      return madeFor[token] === resource ? memberIdentity : null;
    },
  } as unknown as AuthService;
  const callers: Record<string, unknown> = {};
  for (const token of Object.keys(madeFor)) {
    const stamped = await stampedRequest(
      new Request(`${HOST}/mcp`, {
        method: "POST",
        headers: { authorization: `Bearer ${token}`, "x-itx-principal": '{"actor":"user_1"}' },
        body: "{}",
      }),
      { auth, route: null, config },
    );
    callers[token] = [stamped.caller, stamped.forwarded.headers.has("x-itx-principal")];
  }
  expect(callers).toEqual({
    "for-this-host": ["member", true],
    "for-a-sibling": ["anonymous", false],
    "for-the-mind": ["anonymous", false],
  });
  expect(new Set(asked)).toEqual(new Set([HOST]));
});

test("on the control plane's /mcp a token is asked for the mind's own MCP address: a host's token and a session cookie stamp nobody, and the boundary answers the 401 itself", async () => {
  const asked: string[] = [];
  const auth = {
    whoIs: async (token: string, resource: string) => {
      asked.push(resource);
      return token === "for-the-mind" ? memberIdentity : null;
    },
  } as unknown as AuthService;
  const at = (headers: Record<string, string>) =>
    stampedRequest(
      new Request("https://iterate.example.com/mcp", { method: "POST", headers, body: "{}" }),
      { auth, route: "mcp", config },
    );
  const host = await at({ authorization: "Bearer for-a-host" });
  const cookie = await at({ cookie: "__Host-iterate-session=t" });
  const mind = await at({
    authorization: "Bearer for-the-mind",
    cookie: "__Host-iterate-session=t",
  });
  expect(
    [host, cookie, mind].map((stamped) => ({
      caller: stamped.caller,
      principal: stamped.forwarded.headers.has("x-itx-principal"),
      status: stamped.answer?.status,
      // the mind gets no cookie and no credential of the control plane's
      passedOn: ["cookie", "authorization"].filter((name) => stamped.forwarded.headers.has(name)),
    })),
  ).toEqual([
    { caller: "anonymous", principal: false, status: 401, passedOn: [] },
    { caller: "anonymous", principal: false, status: 401, passedOn: [] },
    { caller: "member", principal: true, status: undefined, passedOn: [] },
  ]);
  expect(new Set(asked)).toEqual(new Set(["https://iterate.example.com/mcp"]));
});