iterate.com / cloud

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

cloud / internal-packages / installer / test / ticket-asker.mjsmain at aacbc74

// The first owner's ticket goes to the person who started the run, and to no other member of the
// Cloudflare account. Every member may watch a run (GET /api/deploy), a read-only one too: the
// ticket makes its holder the deployment's owner. A run belongs to the request that began it, and
// it works on the zone that the person named: Cloudflare says the zone's id, the request does not.
//   node test/ticket-asker.mjs
import assert from "node:assert/strict";
import test from "node:test";
import worker from "../worker/index.js";

const CLOUD = "https://cloud.iterate.com";
const ACCOUNT = "0123456789abcdef0123456789abcdef";
const ZONE_ID = "fedcba9876543210fedcba9876543210";
const ZONE = "example.com";
// another zone that the person's token reads (a zone of another account of theirs): it serves a
// stack of another name
const OTHER_ZONE_ID = "00000000000000000000000000000001";

/** A Cloud with two sessions of two members of one account, and one run object that notes how
 *  its state was asked for. */
function cloud() {
  const session = (user) =>
    JSON.stringify({
      level: "full",
      until: Date.now() + 3600_000,
      accounts: [{ id: ACCOUNT, name: "Ada's account" }],
      ...(user ? { user: { id: user, email: `${user}@example.com`, name: user } } : {}),
    });
  const token = JSON.stringify({ token: "TOKEN", expiresAt: Date.now() + 3600_000 });
  const rows = new Map([
    ["s:starter", session("ada")],
    ["t:starter", token],
    ["s:other", session("eve")],
    ["t:other", token],
    ["s:nobody", session(null)],
    ["t:nobody", token],
  ]);
  const shown = [];
  let state = { status: "idle" };
  /** The next look at the run came before the other request's start: it still says idle. */
  let lookedBefore = false;
  const starts = [];
  const run = {
    claim: async () => true, // the object `sign-ins`: nobody claimed this sign-in's token before
    // as deploy-run.js: a run that already runs is left alone, and `began` says so
    start: async (args) => {
      const began = state.status !== "running";
      starts.push({ began, zoneId: args.zoneId });
      if (began) state = { status: "running", lines: [] };
      return { began, state };
    },
    status: async (show = false) => {
      if (lookedBefore) {
        lookedBefore = false;
        return { status: "idle" };
      }
      shown.push(show);
      return show && state.status === "succeeded"
        ? { ...state, result: { firstOwnerTicket: "TICKET" } }
        : state;
    },
  };
  const env = {
    CLIENT_ID: "client",
    CLIENT_SECRET: "secret",
    SESSIONS: {
      get: async (key) => rows.get(key) ?? null,
      put: async (key, value) => void rows.set(key, value),
      delete: async (key) => void rows.delete(key),
    },
    DEPLOYER: { getByName: () => run },
    CF_SERVICE: {
      fetch: async (input, init = {}) => {
        const asked = new URL(input);
        if (asked.pathname === "/oauth2/revoke") {
          revoked.push(new URLSearchParams(String(init.body)).get("token"));
          return new Response(null, { status: 200 });
        }
        // Cloudflare names the zone's id, for the zone's name in this account
        if (asked.pathname.endsWith("/zones"))
          return Response.json({
            success: true,
            result:
              asked.searchParams.get("name") === ZONE &&
              asked.searchParams.get("account.id") === ACCOUNT
                ? [{ id: ZONE_ID, name: ZONE }]
                : [],
          });
        if (asked.pathname.endsWith(`/zones/${OTHER_ZONE_ID}/workers/routes`))
          return Response.json({
            success: true,
            result: [{ pattern: `iterate.${ZONE}/*`, script: "iterate-eves-boundary" }],
          });
        return Response.json({ success: true, result: [] });
      },
    },
  };
  const revoked = [];
  const call = (sid, method, body) =>
    worker.fetch(
      new Request(
        `${CLOUD}/api/deploy${method === "GET" ? `?account=${ACCOUNT}&zone=${ZONE}` : ""}`,
        {
          method,
          headers: {
            cookie: `__Host-sid=${sid}`,
            origin: CLOUD,
            ...(body ? { "content-type": "application/json" } : {}),
          },
          body: body ? JSON.stringify(body) : undefined,
        },
      ),
      env,
    );
  const deploy = (sid, { zoneId = ZONE_ID, email = "ada@example.com" } = {}) =>
    call(sid, "POST", { account: ACCOUNT, zone: ZONE, zoneId, email });
  return {
    rows,
    shown,
    starts,
    revoked,
    call,
    deploy,
    succeed: () => (state = { status: "succeeded", lines: [] }),
    lookBefore: () => (lookedBefore = true),
  };
}

test("another member of the account sees the run and never the first owner's ticket", async () => {
  const { rows, shown, call, deploy, succeed } = cloud();
  const started = await deploy("starter");
  assert.equal(started.status, 200, await started.clone().text());
  assert.equal(JSON.parse(rows.get(`dep:${ACCOUNT}:example-com`)).by, "ada");
  succeed();

  shown.length = 0;
  const others = await (await call("other", "GET")).json();
  assert.equal(others.state.status, "succeeded");
  assert.equal(others.state.result, undefined);
  assert.deepEqual(shown, [false]);

  shown.length = 0;
  const own = await (await call("starter", "GET")).json();
  assert.equal(own.state.result.firstOwnerTicket, "TICKET");
  assert.deepEqual(shown, [true]);
});

test("a run from before this rule, with no starter kept, gives the ticket to nobody", async () => {
  const { rows, shown, call, succeed } = cloud();
  rows.set(`dep:${ACCOUNT}:example-com`, JSON.stringify({ zone: ZONE, owner: "ada@example.com" }));
  succeed();
  for (const sid of ["starter", "other", "nobody"])
    assert.equal((await (await call(sid, "GET")).json()).state.result, undefined, sid);
  assert.deepEqual(shown, [false, false, false]);
});

test("no first deploy starts for a session that does not know who its person is", async () => {
  const { rows, deploy } = cloud();
  const answer = await deploy("nobody");
  // the page then asks the person to sign in to Cloudflare again, and that sign-in reads who they are
  assert.equal(answer.status, 401);
  assert.deepEqual(await answer.json(), {
    error: "not connected",
    detail: "iterate could not read who you are at Cloudflare",
  });
  assert.equal(rows.has(`dep:${ACCOUNT}:example-com`), false);
});

test("a request that did not begin the run keeps nothing of it: the row and the ticket stay the starter's", async () => {
  const { rows, shown, starts, revoked, call, deploy, succeed, lookBefore } = cloud();
  const started = await deploy("starter");
  assert.equal(started.status, 200, await started.clone().text());
  const row = rows.get(`dep:${ACCOUNT}:example-com`);
  assert.deepEqual(revoked, []);

  // eve's request looked at the run before ada's start, and its own start comes after it
  lookBefore();
  const second = await deploy("other", { email: "eve@example.com" });
  assert.equal(second.status, 200, await second.clone().text());
  const said = await second.json();
  assert.equal(said.state.status, "running");
  assert.equal(said.owner, undefined);
  assert.equal(said.connected, false);
  assert.deepEqual(
    starts.map((each) => each.began),
    [true, false],
  );
  // the row is ada's, word for word: no `by` and no `owner` of the second caller
  assert.equal(rows.get(`dep:${ACCOUNT}:example-com`), row);
  assert.equal(JSON.parse(row).by, "ada");
  assert.equal(JSON.parse(row).owner, "ada@example.com");
  // eve's token went to no run: it left the session and Cloudflare was told to end it
  assert.equal(rows.has("t:other"), false);
  assert.deepEqual(revoked, ["TOKEN"]);

  succeed();
  shown.length = 0;
  assert.equal((await (await call("other", "GET")).json()).state.result, undefined);
  assert.equal(
    (await (await call("starter", "GET")).json()).state.result.firstOwnerTicket,
    "TICKET",
  );
  assert.deepEqual(shown, [false, true]);
});

test("no run starts on a zone id that Cloudflare does not name for the domain in this account", async () => {
  const { rows, starts, revoked, deploy } = cloud();
  for (const zoneId of [OTHER_ZONE_ID, "f".repeat(32)]) {
    const answer = await deploy("starter", { zoneId });
    assert.equal(answer.status, 400, zoneId);
    assert.equal(
      (await answer.json()).error,
      `${ZONE} is not a domain of this Cloudflare account`,
      zoneId,
    );
  }
  assert.deepEqual(starts, []);
  // nothing was kept under the domain's name: no stack that the other zone's routes name, no run
  assert.equal(rows.has(`stack:${ACCOUNT}:${ZONE}`), false);
  assert.equal(rows.has(`dep:${ACCOUNT}:example-com`), false);
  // the access stays with the person: no run took it, and nothing ended it
  assert.equal(rows.has("t:starter"), true);
  assert.deepEqual(revoked, []);

  // the same request with the zone's own id starts the run, on that id
  assert.equal((await deploy("starter")).status, 200);
  assert.deepEqual(starts, [{ began: true, zoneId: ZONE_ID }]);
});