iterate.com / kernel

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

kernel / core / auth-worker / src / host-tokens.test.tsmain at 949894f

import { calculatePKCECodeChallenge, generateRandomCodeVerifier } from "oauth4webapi";
import { expect, test } from "vitest";
import { z } from "zod";
import type { Env } from "./env.ts";
import { hostTokenResponse, TOKEN_EXCHANGE_GRANT } from "./host-tokens.ts";
import { keyTokenIdentity } from "./key-tokens.ts";
import { type GrantProps, oauthHelpers, tokenEndpointResponse } from "./oauth.ts";
import { configVars } from "./test-support.ts";
import { whoIs } from "./who-is.ts";

const ISSUER = "https://iterate.example.com";
const API = `${ISSUER}/api`;
const GIT = "https://git.example.com";
const OWNER = "owner@elsewhere.test";
const owner: GrantProps = {
  userId: "user_owner",
  email: OWNER,
  method: "passkey",
  standingByMethod: true,
};
const ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token";

test("a member's session for the API is exchanged for a token that is that member at one hostname, and nowhere else", async () => {
  const stack = stackOf();
  const session = await signedIn(stack, owner);
  const answer = await exchanged(stack, { subject_token: session.access_token, resource: GIT });
  expect(answer).toMatchObject({
    status: 200,
    body: { token_type: "Bearer", issued_token_type: ACCESS_TOKEN },
  });
  // it ends with the session's own token, which lasts an hour
  expect(answer.body.expires_in).toBeGreaterThan(3500);
  expect(answer.body.expires_in).toBeLessThanOrEqual(3600);
  const token = String(answer.body.access_token);
  expect(await whoIs(stack, token, GIT)).toEqual({
    principal: { actor: "user_owner", email: OWNER },
    grant: session.grantId,
    expiresAt: expect.any(Number),
    member: true,
    method: "passkey",
  });
  // for that hostname alone: no other hostname, and never the API or the MCP server
  expect(await whoIs(stack, token, "https://guestbook.example.com")).toBeNull();
  expect(await whoIs(stack, token, API)).toBeNull();
  expect(await whoIs(stack, token, `${ISSUER}/mcp`)).toBeNull();
  expect(await keyTokenIdentity(stack, token, API)).toBeNull();
});

test("the token stops at its next use when the session is ended, and when its person is no member", async () => {
  const kv = new Map<string, string>();
  const stack = stackOf({}, kv);
  const session = await signedIn(stack, owner);
  const { body } = await exchanged(stack, { subject_token: session.access_token, resource: GIT });
  const token = String(body.access_token);
  // the person is removed: the same store, a config that names another owner
  const removed = stackOf({ ownerEmails: ["someone@elsewhere.test"] }, kv);
  expect(await whoIs(removed, token, GIT)).toBeNull();
  expect(await whoIs(stack, token, GIT)).toMatchObject({ member: true });
  // the sign-in is ended, as /sessions and a sign-out end it
  await oauthHelpers(stack).revokeGrant(session.grantId, owner.userId);
  expect(await whoIs(stack, token, GIT)).toBeNull();
  expect(
    await exchanged(stack, { subject_token: session.access_token, resource: GIT }),
  ).toMatchObject({ status: 400, body: { error: "invalid_request" } });
});

test("what is not a member's live session for the API gets no token", async () => {
  const stack = stackOf();
  const session = await signedIn(stack, owner);
  const refusal = async (form: Record<string, string>) => {
    const { status, body } = await exchanged(stack, form);
    return [status, body.error];
  };
  // a made-up token, a refresh token, and a host token itself: nothing is exchanged twice
  const host = await exchanged(stack, { subject_token: session.access_token, resource: GIT });
  for (const subject_token of [
    "user_owner:grant:secret",
    session.refresh_token,
    String(host.body.access_token).slice(0, 256),
  ])
    expect(await refusal({ subject_token, resource: GIT })).toEqual([400, "invalid_request"]);
  // a resource that is no hostname of the mind: another site, the issuer's own, the API
  for (const resource of ["https://git.elsewhere.test", ISSUER, API, "http://git.example.com"])
    expect(await refusal({ subject_token: session.access_token, resource })).toEqual([
      400,
      "invalid_target",
    ]);
  expect(await refusal({ subject_token: session.access_token })).toEqual([400, "invalid_request"]);
  expect(
    await refusal({
      subject_token: session.access_token,
      resource: GIT,
      subject_token_type: "urn:ietf:params:oauth:token-type:refresh_token",
    }),
  ).toEqual([400, "invalid_request"]);
});

test("a sign-in that names no way of signing in gets no token: a hostname stamps nobody without one", async () => {
  const stack = stackOf();
  // the old stack's grant from before 13 Nov 2026 (./oauth.ts `GrantProps.method`)
  const session = await signedIn(stack, { userId: "user_owner", email: OWNER });
  expect(await whoIs(stack, session.access_token, API)).toMatchObject({ member: true });
  const answer = await exchanged(stack, { subject_token: session.access_token, resource: GIT });
  expect(answer).toMatchObject({ status: 400, body: { error: "invalid_request" } });
  expect(String(answer.body.error_description)).toContain("Sign in again");
});

test("any other grant type is the library's to answer", async () => {
  const stack = stackOf();
  const request = tokenRequest({ grant_type: "refresh_token", refresh_token: "x", client_id: "y" });
  expect(await hostTokenResponse(stack, request)).toBeNull();
});

const ctx = { waitUntil() {}, passThroughOnException() {} } as unknown as ExecutionContext;
const TokenAnswer = z.object({ access_token: z.string(), refresh_token: z.string() });

/** A stack whose owner is `OWNER`, with `config` over that, the OAuth library's store in `kv`, and
 *  a database in which nobody was added and nobody is blocked. */
function stackOf(
  config: Parameters<typeof configVars>[0] = {},
  kv = new Map<string, string>(),
): Env {
  return {
    ...configVars({ ownerEmails: [OWNER], ...config }),
    OAUTH_KV: {
      get: async (key: string, type?: unknown) => {
        const kept = kv.get(key) ?? null;
        const json = type === "json" || (type as { type?: string } | undefined)?.type === "json";
        return kept && json ? JSON.parse(kept) : kept;
      },
      put: async (key: string, value: string) => void kv.set(key, value),
      delete: async (key: string) => void kv.delete(key),
      list: async ({ prefix = "" }: { prefix?: string } = {}) => ({
        keys: [...kv.keys()].filter((key) => key.startsWith(prefix)).map((name) => ({ name })),
        list_complete: true,
      }),
    },
    DB: { prepare: () => ({ bind: () => ({ first: async () => null }) }) },
    // the cast: a token's checks read these bindings and no other
  } as unknown as Env;
}

/** A session for the API as the CLI holds one: a grant of `props`, and the tokens for its code. */
async function signedIn(stack: Env, props: GrantProps) {
  const helpers = oauthHelpers(stack);
  const redirectUri = "http://127.0.0.1:7777/callback";
  const { clientId } = await helpers.createClient({
    redirectUris: [redirectUri],
    tokenEndpointAuthMethod: "none",
    grantTypes: ["authorization_code", "refresh_token"],
    responseTypes: ["code"],
  });
  const verifier = generateRandomCodeVerifier();
  const query = new URLSearchParams({
    response_type: "code",
    client_id: clientId,
    redirect_uri: redirectUri,
    resource: API,
    scope: "iterate",
    code_challenge: await calculatePKCECodeChallenge(verifier),
    code_challenge_method: "S256",
  });
  const request = await helpers.parseAuthRequest(new Request(`${ISSUER}/oauth2/auth?${query}`));
  const { redirectTo } = await helpers.completeAuthorization({
    request,
    userId: props.userId,
    metadata: { clientName: "iterate CLI" },
    scope: request.scope,
    revokeExistingGrants: false,
    props,
  });
  const code = new URL(redirectTo).searchParams.get("code")!;
  const answer = await tokenEndpointResponse(
    stack,
    tokenRequest({
      grant_type: "authorization_code",
      code,
      redirect_uri: redirectUri,
      client_id: clientId,
      code_verifier: verifier,
      resource: API,
    }),
    ctx,
  );
  // the library's codes are `<userId>:<grantId>:<secret>`
  return { ...TokenAnswer.parse(await answer.json()), grantId: code.split(":")[1]! };
}

/** The token endpoint's answer to a token exchange with `form` over the fields that every one has. */
async function exchanged(stack: Env, form: Record<string, string>) {
  const answer = await hostTokenResponse(
    stack,
    tokenRequest({
      grant_type: TOKEN_EXCHANGE_GRANT,
      subject_token_type: ACCESS_TOKEN,
      ...form,
    }),
  );
  return {
    status: answer!.status,
    body: z.record(z.string(), z.unknown()).parse(await answer!.json()),
  };
}

const tokenRequest = (form: Record<string, string>) =>
  new Request(`${ISSUER}/oauth2/token`, {
    method: "POST",
    headers: { "content-type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams(form),
  });