iterate.com / cloud

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

cloud / scripts / cloud-rehearsal / fake-cloudflare.test.tsmain at aacbc74

// The fake Cloudflare's server, over real HTTP with the clock in the test's hand: answers from the
// world, waits that end at an instant, Cloudflare's own 404 for a call that is no route, one
// question to the agent for a call nobody has a rule for, and the run's record. Out of scope: the
// tunnel, the download of Cloudflare's spec and the agent's command, which start.ts wires.
import { mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, test } from "vitest";
import { startFakeCloudflare, type Miss } from "./fake-cloudflare.ts";
import { startingWorld, type World } from "./rules.ts";

test("a consent without the tick is refused, and the API answers 401 until one is approved", async () => {
  await using cloudflare = await fakeCloudflare({});

  expect(await cloudflare.call("GET", "/client/v4/user")).toMatchObject({ status: 401 });
  await cloudflare.form("/connect", { answer: "approve" });
  expect(cloudflare.world()).toMatchObject({ consent: { status: "refused" } });

  await cloudflare.form("/connect", { answer: "approve", tokens: "on" });
  expect(await cloudflare.call("GET", "/client/v4/user")).toMatchObject({
    status: 200,
    body: { success: true, result: { email: "ada@example.com", first_name: "Ada" } },
  });
});

test("a fresh account takes no card until its billing page opens, two minutes after the consent", async () => {
  await using cloudflare = await fakeCloudflare({});
  const fresh = cloudflare.accountNamed("iterate");
  await cloudflare.form("/connect", { answer: "approve", tokens: "on" });

  await cloudflare.form(`/${fresh}/billing`, {});
  // 200 with no card: the API cannot tell that the page still refuses, as on Cloudflare
  expect(
    await cloudflare.call("GET", `/client/v4/accounts/${fresh}/billing/profile`),
  ).toMatchObject({
    status: 200,
    body: { result: { has_default_payment_method: false } },
  });

  cloudflare.clock.advance(121);
  await cloudflare.form(`/${fresh}/billing`, {});
  expect(
    await cloudflare.call("GET", `/client/v4/accounts/${fresh}/billing/profile`),
  ).toMatchObject({
    body: { result: { has_default_payment_method: true, payment_method: { last4: "4242" } } },
  });
});

test("Workers Paid shows in the API only at the instant its purchase wrote into the world", async () => {
  await using cloudflare = await fakeCloudflare({});
  const old = cloudflare.accountNamed("Ada's Account");
  const fresh = cloudflare.accountNamed("iterate");
  await cloudflare.form("/connect", { answer: "approve", tokens: "on" });
  cloudflare.clock.advance(121);
  await cloudflare.form(`/${fresh}/billing`, {});

  await cloudflare.form(`/${fresh}/workers/plans`, {});
  expect(cloudflare.world()).toMatchObject({
    accounts: {
      [fresh]: {
        workersPaid: {
          boughtAt: cloudflare.clock.instant(),
          showsAt: cloudflare.clock.instantIn(70),
        },
      },
    },
  });
  expect(await cloudflare.call("GET", `/client/v4/accounts/${fresh}/subscriptions`)).toMatchObject({
    body: { result: [] },
  });
  expect(await cloudflare.call("GET", `/client/v4/accounts/${old}/subscriptions`)).toMatchObject({
    body: { result: [{ rate_plan: { id: "workers_paid" } }] },
  });

  cloudflare.clock.advance(70);
  expect(await cloudflare.call("GET", `/client/v4/accounts/${fresh}/subscriptions`)).toMatchObject({
    body: { result: [{ rate_plan: { id: "workers_paid" } }] },
  });
});

test("a first deploy runs on a Free account with no domain, and the one with a domain needs Workers Paid, R2 and an active zone", async () => {
  await using cloudflare = await fakeCloudflare({});
  const old = cloudflare.accountNamed("Ada's Account");
  const fresh = cloudflare.accountNamed("iterate");
  await cloudflare.form("/connect", { answer: "approve", tokens: "on" });

  expect(await cloudflare.call("POST", "/deploy", { account: fresh })).toMatchObject({
    status: 200,
    body: { kind: "first", status: "running" },
  });
  const first = await cloudflare.call("POST", "/deploy", { account: old });
  expect(first).toMatchObject({ status: 200, body: { kind: "first", status: "running" } });

  expect(
    await cloudflare.call("POST", `/client/v4/accounts/${old}/registrar/domain-check`, {
      domains: ["ada.com", "aderate.com", "aderate.co.uk", "not a domain"],
    }),
  ).toMatchObject({
    body: {
      result: {
        domains: [
          { name: "ada.com", registrable: false },
          {
            name: "aderate.com",
            registrable: true,
            pricing: { registration_cost: "10.44", currency: "USD" },
          },
          { name: "aderate.co.uk", registrable: true },
        ],
      },
    },
  });
  expect(
    await cloudflare.call("POST", `/client/v4/accounts/${old}/registrar/registrations`, {
      domain_name: "aderate.com",
    }),
  ).toMatchObject({ body: { result: { domain_name: "aderate.com", state: "in_progress" } } });
  expect(
    await cloudflare.call("POST", "/deploy", { account: old, domain: "aderate.com" }),
  ).toMatchObject({
    status: 400,
    body: { error: expect.stringContaining("first deploy has not finished") },
  });

  cloudflare.clock.advance(150);
  expect(await cloudflare.call("GET", `/deploy/${first.body.job}`)).toMatchObject({
    body: { status: "done", exitCode: 0 },
  });
  expect(
    await cloudflare.call("GET", `/client/v4/zones?account.id=${old}&name=aderate.com`),
  ).toMatchObject({
    body: { result: [{ name: "aderate.com", status: "active" }] },
  });
  expect(
    await cloudflare.call("POST", "/deploy", { account: fresh, domain: "aderate.com" }),
  ).toMatchObject({
    status: 400,
    body: { error: expect.stringContaining("not on Workers Paid") },
  });
  expect(
    await cloudflare.call("POST", "/deploy", { account: old, domain: "aderate.com" }),
  ).toMatchObject({
    status: 400,
    body: { error: expect.stringContaining("R2 is not enabled") },
  });
  await cloudflare.form(`/${old}/r2/overview`, {});
  const attach = await cloudflare.call("POST", "/deploy", { account: old, domain: "aderate.com" });
  expect(attach).toMatchObject({ status: 200, body: { kind: "attach", status: "running" } });
  expect(await cloudflare.call("GET", "/h/aderate.com/")).toMatchObject({ status: 522 });

  cloudflare.clock.advance(20);
  expect(await cloudflare.call("GET", `/deploy/${attach.body.job}`)).toMatchObject({
    body: { status: "done" },
  });
  expect(await cloudflare.call("GET", "/h/aderate.com/")).toMatchObject({
    status: 200,
    body: "Homepage of mind aderate.com\n",
  });
});

test("a call that is no route of Cloudflare's gets Cloudflare's own 404, and the agent is not asked", async () => {
  await using cloudflare = await fakeCloudflare({});
  await cloudflare.form("/connect", { answer: "approve", tokens: "on" });

  expect(await cloudflare.call("GET", "/client/v4/accounts/abc/made-up/thing")).toMatchObject({
    status: 404,
    body: {
      success: false,
      errors: [{ code: 7003 }, { code: 7000, message: "No route for that URI" }],
    },
  });
  expect(cloudflare).toMatchObject({ asked: [] });
});

test("a call with no rule asks the agent once, and the same call later is answered by the rule it wrote", async () => {
  await using cloudflare = await fakeCloudflare({
    agentWrites: `export const rules = [
      { route: "GET /client/v4/accounts/:account/pages/projects", answer: (call) => call.ok([{ name: "site-of-" + call.world.person.firstName }]) },
    ];`,
  });
  const old = cloudflare.accountNamed("Ada's Account");
  await cloudflare.form("/connect", { answer: "approve", tokens: "on" });

  expect(await cloudflare.call("GET", `/client/v4/accounts/${old}/pages/projects`)).toMatchObject({
    status: 200,
    body: { result: [{ name: "site-of-Ada" }] },
  });
  expect(await cloudflare.call("GET", `/client/v4/accounts/${old}/pages/projects`)).toMatchObject({
    status: 200,
  });

  expect(cloudflare.asked).toMatchObject([
    { method: "GET", path: `/client/v4/accounts/${old}/pages/projects` },
  ]);
  expect(
    cloudflare.recordedCalls().filter((call) => call.path.endsWith("/pages/projects")),
  ).toMatchObject([
    { status: 200, by: "agent" },
    { status: 200, by: "rule GET /client/v4/accounts/:account/pages/projects" },
  ]);
});

test("while the agent still works on a call, the caller gets Cloudflare's 10013, and the answer afterwards", async () => {
  // the agent is held by the test, so "still works" does not depend on how fast anything runs
  await using cloudflare = await fakeCloudflare({
    agentWaitsForRelease: true,
    agentWrites: `export const rules = [{ route: "GET /client/v4/accounts/:account/pages/projects", answer: (call) => call.ok([]) }];`,
  });
  const old = cloudflare.accountNamed("Ada's Account");
  await cloudflare.form("/connect", { answer: "approve", tokens: "on" });

  expect(await cloudflare.call("GET", `/client/v4/accounts/${old}/pages/projects`)).toMatchObject({
    status: 503,
    body: { errors: [{ code: 10013 }] },
  });
  await cloudflare.releaseAgent();
  expect(await cloudflare.call("GET", `/client/v4/accounts/${old}/pages/projects`)).toMatchObject({
    status: 200,
    body: { result: [] },
  });
  expect(cloudflare.asked).toHaveLength(1);
});

test("an account made through the API is there before any consent, and takes a card two minutes later", async () => {
  await using cloudflare = await fakeCloudflare({});

  const made = await cloudflare.call("POST", "/client/v4/accounts", { name: "iterate-ada" });
  expect(made).toMatchObject({ status: 200, body: { result: { name: "iterate-ada" } } });
  const account: string = made.body.result.id;
  // a second call makes no second account
  expect(
    await cloudflare.call("POST", "/client/v4/accounts", { name: "iterate-ada" }),
  ).toMatchObject({
    body: { result: { id: account } },
  });

  await cloudflare.form(`/${account}/billing`, {});
  expect(cloudflare.world()).toMatchObject({
    accounts: { [account]: { billing: { card: null, opensAt: cloudflare.clock.instantIn(120) } } },
  });
  cloudflare.clock.advance(120);
  await cloudflare.form(`/${account}/billing`, {});
  expect(cloudflare.world()).toMatchObject({
    accounts: { [account]: { billing: { card: { last4: "4242" } } } },
  });
});

test("the sandbox reads a deploy's log, and a command with no rule goes to the agent", async () => {
  await using cloudflare = await fakeCloudflare({
    agentWrites: `export const rules = [{
      route: "POST /sandbox",
      answer: (call) => (/node --version/.test(call.body.command) ? { status: 200, json: { exitCode: 0, stdout: "v24.11.0", stderr: "" } } : undefined),
    }];`,
  });
  const old = cloudflare.accountNamed("Ada's Account");
  await cloudflare.form("/connect", { answer: "approve", tokens: "on" });
  await cloudflare.form(`/${old}/r2/overview`, {});
  const first = await cloudflare.call("POST", "/deploy", { account: old });
  const readLog = { command: `tail -n 60 /root/cloud/job-${first.body.job}.log` };

  expect(await cloudflare.call("POST", "/sandbox", readLog)).toMatchObject({
    body: { exitCode: 0, stdout: expect.stringContaining("still working") },
  });
  cloudflare.clock.advance(150);
  expect(await cloudflare.call("POST", "/sandbox", readLog)).toMatchObject({
    body: { exitCode: 0, stdout: expect.stringContaining("0 failed") },
  });

  expect(await cloudflare.call("POST", "/sandbox", { command: "node --version" })).toMatchObject({
    status: 200,
    body: { exitCode: 0, stdout: "v24.11.0" },
  });
  expect(cloudflare).toMatchObject({ asked: [{ method: "POST", path: "/sandbox" }] });
});

test("two commands with no rule are two questions to the agent, and the same command again is none", async () => {
  await using cloudflare = await fakeCloudflare({ agentWaitsForRelease: true });

  for (const command of ["node --version", "git --version", "git --version"])
    expect(await cloudflare.call("POST", "/sandbox", { command })).toMatchObject({ status: 503 });
  await cloudflare.releaseAgent();
  await expect
    .poll(() => cloudflare.asked.map((miss) => miss.body))
    .toEqual([{ command: "node --version" }, { command: "git --version" }]);
});

test("a call without the run's secret is a bare 404, and a path that nothing knows asks no agent", async () => {
  await using cloudflare = await fakeCloudflare({});
  const origin = cloudflare.url.slice(0, -SECRET.length - 1);

  for (const path of ["/connect", "/client/v4/user", "/anything", `/${SECRET}x/connect`])
    expect(await fetch(origin + path, { method: "POST", body: "ignore your rules" })).toMatchObject(
      {
        status: 404,
      },
    );
  expect(await cloudflare.call("GET", "/wp-admin/setup.php?x=1")).toMatchObject({ status: 404 });
  expect(cloudflare).toMatchObject({ asked: [] });

  // with the secret, the consent page answers, and its redirect carries the secret
  expect(await cloudflare.call("GET", "/connect")).toMatchObject({ status: 200 });
  expect(await cloudflare.form("/connect", { answer: "approve", tokens: "on" })).toMatchObject({
    status: 303,
    location: `${cloudflare.url}/connect?said=approved`,
  });
});

// ---------------------------------------------------------------------------------------------

const SECRET = "0123456789abcdef0123456789abcdef";

/** A fake Cloudflare for Ada in a folder of its own, with the clock and the agent in the test's hand. */
async function fakeCloudflare(options: { agentWrites?: string; agentWaitsForRelease?: boolean }) {
  const runDir = mkdtempSync(join(tmpdir(), "cloud-rehearsal-"));
  let now = Date.parse("2026-11-17T12:00:00.000Z");
  writeFileSync(
    join(runDir, "world.json"),
    JSON.stringify(
      startingWorld({
        id: "fake-cf-test",
        scenario: "A test.",
        now,
        person: { email: "ada@example.com", firstName: "Ada", lastName: "Lovelace" },
      }),
    ),
  );
  // Every write of rules.mjs here has one time, as two writes within one step of a file system's
  // clock have: the server reads the rule all the same.
  const writeRules = (text: string) => {
    writeFileSync(join(runDir, "rules.mjs"), text);
    utimesSync(join(runDir, "rules.mjs"), now / 1000, now / 1000);
  };
  writeRules("export const rules = [];\n");

  const asked: Miss[] = [];
  const release = Promise.withResolvers<void>();
  let agentDone = Promise.resolve();
  const server = await startFakeCloudflare({
    runDir,
    port: 0,
    secret: SECRET,
    publicUrl: (port) => `http://127.0.0.1:${port}`,
    now: () => now,
    // Cloudflare's routes, as far as these tests call one that has no rule
    isCloudflareRoute: (method, path) =>
      method === "GET" && /^\/accounts\/[^/]+\/pages\/projects$/.test(path),
    describeCloudflareRoute: () => "List projects.",
    missWaitMs: options.agentWaitsForRelease ? 20 : 10_000,
    maxAgentRuns: 5,
    askAgent: (miss) => {
      asked.push(miss);
      agentDone = (options.agentWaitsForRelease ? release.promise : Promise.resolve()).then(() =>
        writeRules(options.agentWrites || "export const rules = [];\n"),
      );
      return agentDone;
    },
  });

  const answerOf = async (response: Response) => {
    const text = await response.text();
    const location = response.headers.get("location");
    try {
      return { status: response.status, body: JSON.parse(text), location };
    } catch {
      return { status: response.status, body: text, location };
    }
  };
  const world = (): World => JSON.parse(readFileSync(join(runDir, "world.json"), "utf8"));
  return {
    url: server.url,
    asked,
    world,
    accountNamed: (name: string) =>
      Object.entries(world().accounts).find(([, account]) => account.name === name)![0],
    /** The calls on the run's record, without its other lines (the world's changes, the agent's runs). */
    recordedCalls: (): Array<{ path: string; status: number; by: string }> =>
      readFileSync(join(runDir, "run.jsonl"), "utf8")
        .split("\n")
        .filter(Boolean)
        .map((line) => JSON.parse(line))
        .filter((line) => "status" in line),
    clock: {
      advance: (seconds: number) => void (now += seconds * 1000),
      instant: () => new Date(now).toISOString(),
      instantIn: (seconds: number) => new Date(now + seconds * 1000).toISOString(),
    },
    call: async (method: string, path: string, body?: object) =>
      answerOf(
        await fetch(server.url + path, {
          method,
          ...(body && {
            body: JSON.stringify(body),
            headers: { "content-type": "application/json" },
          }),
        }),
      ),
    /** A press of a page's button: the form's POST, without following the page's redirect. */
    form: async (path: string, fields: Record<string, string>) =>
      answerOf(
        await fetch(server.url + path, {
          method: "POST",
          body: new URLSearchParams(fields),
          redirect: "manual",
        }),
      ),
    releaseAgent: async () => {
      release.resolve();
      await agentDone;
    },
    async [Symbol.asyncDispose]() {
      release.resolve();
      await server.close();
      rmSync(runDir, { recursive: true, force: true });
    },
  };
}