iterate.com / cloud

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

cloud / internal-packages / installer / test / proof-worker / prove.mjsmain at aacbc74

// prove.mjs — ONE DEPLOY RUN THROUGH THE PROOF WORKER (./worker.js), as the installer would start
// it, with a Cloudflare token of the caller's own in place of a person's consent. It prints each
// step as it starts, the run's last lines, and what the run's object keeps. Exit 0: succeeded.
//
//   CLOUDFLARE_API_TOKEN=… CLOUDFLARE_ACCOUNT_ID=… OPERATOR_TOKEN=… \
//     node test/proof-worker/prove.mjs <zone> <zone id> <owner email | update | recover:<owner email>> [proof worker's origin]
//
// A first deploy also proves the first owner's ticket: the page's first answer carries it once, no
// log line holds it, https://iterate.<zone>/keys/first takes it once (200 with a session cookie,
// then 403), and the auth Worker has FIRST_OWNER_TICKET bound. An update gives no ticket and
// leaves no such binding.
//
// With `recover:<owner email>` the run is an update that the owner asked for to get back in: no
// config, and a ticket for that address, checked as a first deploy's is (the stack takes it once
// although it has users and keys).
//
// With `update` in place of the owner's email the run writes no config: the stack deploys from the
// one it keeps beside its state. NO_CLOUD_KEY=1 leaves the Cloud's key out of a first config.
//
// The tokens are read from the environment and sent in the request alone: never an argument.
const [
  ,
  ,
  zone,
  zoneId,
  ownerEmail,
  origin = "https://iterate-access-proof.iterate-dev-preview.workers.dev",
] = process.argv;
const {
  CLOUDFLARE_API_TOKEN: token,
  CLOUDFLARE_ACCOUNT_ID: accountId,
  OPERATOR_TOKEN: operator,
} = process.env;
if (!zone || !zoneId || !ownerEmail || !token || !accountId || !operator) {
  console.error("usage: see the head of this file");
  process.exit(2);
}
// `recover:<address>` is a recovery run: an update with no config that makes a ticket for the owner
// who lost their passkey. It is checked as a first deploy's ticket is.
const recoverOwner = ownerEmail.startsWith("recover:") ? ownerEmail.slice(8) : null;
const name = zone.replaceAll(".", "-");
const run = encodeURIComponent(`${accountId}:${name}`);
const call = async (path, init, query = "") => {
  const answer = await fetch(`${origin}${path}?run=${run}${query}`, {
    ...init,
    headers: { authorization: `Bearer ${operator}`, ...init?.headers },
  });
  if (!answer.ok)
    throw new Error(`${path} answered ${answer.status}: ${(await answer.text()).slice(0, 300)}`);
  return answer.json();
};

// The Cloud's public key, as this Worker's own enrol page names it: the deployment's config trusts
// it from its first deploy, as a deployment the wizard makes does.
const enrolPage = await (await fetch(`${origin}/enrol?domain=${zone}`)).text();
const publicKey = /[?&;]publicKey=([A-Za-z0-9_-]+)/.exec(enrolPage)?.[1];
const keys =
  publicKey && !process.env.NO_CLOUD_KEY
    ? [{ actor: "iterate-cloud", publicKey, label: "iterate Cloud", paths: ["/integrations/"] }]
    : undefined;
console.log(`the config trusts the Cloud's key: ${Boolean(keys)}`);

const started = await call("/proof/start", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({
    accountId,
    zone,
    zoneId,
    name,
    ...(recoverOwner
      ? { recoverOwner }
      : ownerEmail === "update"
        ? {}
        : { ownerEmails: [ownerEmail], trustedClients: [], keys }),
    token,
    tokenExpiresAt: Date.now() + 3600_000,
  }),
});
console.log(`run ${name}: ${started.status}`);
let seen = 0;
let state = started;
while (state.status === "running") {
  await new Promise((resolve) => setTimeout(resolve, 5000));
  state = await call("/proof/status");
  for (const line of state.lines.slice(seen))
    if (line.startsWith("== step") || /^(account|zone|stack|iterate\.)/.test(line))
      console.log(line);
  seen = state.lines.length;
}
console.log(`ended: ${state.status}`, JSON.stringify(state.result));
console.log(state.lines.slice(-6).join("\n"));
const kept = await call("/proof/kept");
console.log("kept:", JSON.stringify(kept));
// THE FIRST OWNER'S TICKET (../../worker/first-owner.js). The run got its hash alone; the person's
// page gets the ticket once. It is held here in memory, used once, and never printed.
const authBindings = async () => {
  const answer = await fetch(
    `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/iterate-${name}-auth/settings`,
    { headers: { authorization: `Bearer ${token}` } },
  );
  return ((await answer.json()).result?.bindings || []).map((binding) => binding.name);
};
const bound = (await authBindings()).includes("FIRST_OWNER_TICKET");
console.log(`the auth Worker has FIRST_OWNER_TICKET bound: ${bound}`);
let ticketFailed = false;
if (state.status === "succeeded") {
  const shown = await call("/proof/status", undefined, "&shown=1");
  const ticket = shown.result?.firstOwnerTicket;
  const again = await call("/proof/status", undefined, "&shown=1");
  if (ownerEmail === "update") {
    // a plain update: no ticket, and the stack drops the binding it had
    console.log(`an update gives no ticket: ${!ticket}`);
    ticketFailed = Boolean(ticket) || bound;
  } else {
    const issuer = `https://iterate.${zone}`;
    const post = () =>
      fetch(`${issuer}/keys/first`, {
        method: "POST",
        headers: { origin: issuer, "content-type": "application/json" },
        body: JSON.stringify({ ticket }),
      });
    const everything = JSON.stringify([state, shown.lines, again, kept]);
    const first = ticket ? await post() : null;
    const cookie = first?.headers.get("set-cookie") || "";
    const second = ticket ? await post() : null;
    const maxAge = Number(/Max-Age=(\d+)/i.exec(cookie)?.[1]);
    console.log(
      `the ticket's session cookie lives ${Number.isFinite(maxAge) ? `${maxAge} s` : "for the browser's session (no Max-Age)"}`,
    );
    const checks = {
      "the page's first answer carries a ticket": Boolean(ticket),
      "it ends within 15 minutes": shown.result?.firstOwnerTicketEnds - Date.now() < 15 * 60_000,
      "a second answer carries none": !again.result?.firstOwnerTicket,
      "no line of the run's log, and nothing the run keeps, holds the ticket":
        Boolean(ticket) && !everything.includes(ticket),
      "the first POST to /keys/first answers 200": first?.status === 200,
      "with a session cookie (HttpOnly, Secure)":
        /HttpOnly/i.test(cookie) && /Secure/i.test(cookie),
      "the second POST answers 403": second?.status === 403,
    };
    for (const [check, pass] of Object.entries(checks))
      console.log(`${pass ? "ok  " : "FAIL"} ${check}`);
    ticketFailed = !bound || Object.values(checks).includes(false);
  }
}
if (ticketFailed) process.exitCode = 1;

if (JSON.stringify([state, kept]).includes(token)) {
  console.error("THE TOKEN IS IN AN ANSWER");
  process.exit(1);
}
process.exit(state.status === "succeeded" && !ticketFailed ? 0 : 1);