iterate.com / cloud

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

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

// prove-mind.mjs — IS THIS A WHOLE MIND, AND DID AN UPDATE KEEP WHAT IT HELD? Read only: it asks
// Cloudflare's API and the stack's public addresses, and changes nothing.
//
//   CLOUDFLARE_API_TOKEN=… CLOUDFLARE_ACCOUNT_ID=… node test/prove-mind.mjs <domain>
//     [--name <stack>]     the stack's name; without it, read from the route that serves iterate.<domain>
//     [--out <file>]       write what was counted, to compare after an update
//     [--before <file>]    compare with a file that --out wrote before the update
//     [--cloud <origin>]   the Cloud that the stack must name (default https://cloud.iterate.com)
//     [--no-cloud]         a stack that names no Cloud: O1 is not asked
//   ITERATE_SESSION_COOKIE: a member's `cookie` header for iterate.<domain>; with it the self-test's
//   server half is asked (R3). Never printed.
//
// One line per check: `pass <id> …`, `FAIL <id> …` or `skip <id> …`. Exit 1 when a check failed.
// The file of --out holds counts, names of Workers and repos, version ids and one hash. It holds
// no secret, no email address and no stored value.
//
//   R1  the Workers of a mind exist, and none of an older stack is left
//   R2  the sign-in's discovery document answers with the right issuer
//   R3  every result of /self-test/facts passes (needs the cookie)
//   O1  the stored config names the Cloud, and one of its keys is the Cloud's
//   U4  after an update: each Worker runs a new version, made after the file of --before
//   U6  after an update: the same members, keys, secrets, files and repos as before
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { readFileSync, writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";

const API = "https://api.cloudflare.com/client/v4";
const token = process.env.CLOUDFLARE_API_TOKEN;
const account = process.env.CLOUDFLARE_ACCOUNT_ID;
const args = process.argv.slice(2);
const flag = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined);
const domain = args[0];
if (!token || !account || !domain || domain.startsWith("--")) {
  console.error("usage: see the top of test/prove-mind.mjs");
  process.exit(2);
}

let failed = 0;
const say = (verdict, id, text) => {
  if (verdict === "FAIL") failed++;
  console.log(`${verdict} ${id} ${text}`);
};

/** One call of Cloudflare's API. It throws when Cloudflare says no: a read that failed is not "none". */
async function cf(path, body) {
  const answer = await fetch(`${API}${path}`, {
    method: body ? "POST" : "GET",
    headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
    body: body && JSON.stringify(body),
    signal: AbortSignal.timeout(30_000),
  });
  const data = await answer.json().catch(() => ({}));
  if (!answer.ok || data.success === false)
    throw new Error(`${path.split("?")[0]} answered ${answer.status}`);
  return data;
}
/** Every page of a list that counts pages. */
async function all(path) {
  const found = [];
  for (let page = 1; page <= 50; page++) {
    const data = await cf(`${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`);
    found.push(...data.result);
    if (data.result.length < 100) break;
  }
  return found;
}
/** How many entries a list with a cursor holds, and how many of them `kept` takes. */
async function counted(path, kept = () => true) {
  let cursor = "";
  let n = 0;
  for (let page = 1; page <= 200; page++) {
    const data = await cf(`${path}${cursor && `&cursor=${encodeURIComponent(cursor)}`}`);
    n += data.result.filter(kept).length;
    cursor = data.result_info?.cursor || "";
    if (!cursor || data.result_info?.is_truncated === false) break;
  }
  return n;
}

// The stack's name: the Worker that serves iterate.<domain>, as the Cloud finds it.
const [zone] = (await cf(`/zones?name=${domain}&account.id=${account}`)).result;
if (!zone) {
  say("FAIL", "R1", `the account holds no zone ${domain}`);
  process.exit(1);
}
const routes = (await cf(`/zones/${zone.id}/workers/routes`)).result;
const serving = [`iterate.${domain}/*`, `*.${domain}/*`]
  .map((pattern) => routes.find((route) => route.pattern === pattern)?.script)
  .find(Boolean);
const name = flag("--name") || /^iterate-(.+)-boundary$/.exec(serving || "")?.[1];
if (!name) {
  say("FAIL", "R1", `no Worker of a mind serves iterate.${domain} (the route names ${serving})`);
  process.exit(1);
}
const prefix = `iterate-${name}-`;

// The config that the stack keeps beside its state. Only facts of it are printed, never the config.
function storedConfig() {
  const alchemy = fileURLToPath(new URL("../../../core/alchemy", import.meta.url));
  const read = spawnSync(
    "node",
    ["node_modules/alchemy/bin/cli.js", "state", "read", `mind/${name}/output`].concat([
      "--backend",
      "cloudflare",
      "--name",
      `${prefix}state`,
    ]),
    { cwd: alchemy, encoding: "utf8", timeout: 120_000, env: { ...process.env, CI: "true" } },
  );
  const start = read.stdout?.search(/^\{$/m) ?? -1;
  if (read.status !== 0 || start < 0) return null;
  try {
    return JSON.parse(read.stdout.slice(start)).config || null;
  } catch {
    return null;
  }
}
const config = storedConfig();
const provided = config?.mind?.provided === true;

// R1 and the version that each Worker runs
const scripts = (await all(`/accounts/${account}/workers/scripts`)).map((script) => script.id);
const mine = scripts.filter((id) => id.startsWith(prefix));
const wanted = ["boundary", "auth", "secrets", ...(provided ? [] : ["mind"])];
const missing = wanted.filter((part) => !mine.includes(prefix + part));
const old = mine.filter((id) => /-(ingress|project)$/.test(id));
const extra =
  provided && mine.includes(`${prefix}mind`) ? ["a provided mind has a -mind Worker"] : [];
const wrong = [
  ...missing.map((part) => `${prefix}${part} is missing`),
  ...old.map((id) => `${id} is left from an older stack`),
  ...extra,
];
say(
  wrong.length ? "FAIL" : "pass",
  "R1",
  wrong.join("; ") || `the stack ${name} serves ${domain}: ${wanted.join(", ")}`,
);
const workers = {};
for (const id of mine.filter((id) => !id.endsWith("-state"))) {
  const [live] = (await cf(`/accounts/${account}/workers/scripts/${id}/deployments`)).result
    .deployments;
  const version = live?.versions.toSorted((a, b) => b.percentage - a.percentage)[0]?.version_id;
  workers[id] = { version, madeAt: live?.created_on, source: live?.source };
}

// R2
const issuer = `https://iterate.${domain}`;
const ask = (path, init) =>
  fetch(`${issuer}${path}`, { redirect: "manual", signal: AbortSignal.timeout(20_000), ...init });
const discovery = await ask("/.well-known/oauth-authorization-server").catch(() => null);
const said = discovery?.ok ? (await discovery.json().catch(() => ({}))).issuer : undefined;
const oidc = await ask("/.well-known/openid-configuration").catch(() => null);
say(
  said === issuer && oidc?.status === 404 ? "pass" : "FAIL",
  "R2",
  `the discovery document answered ${discovery?.status ?? "nothing"} with issuer ${said}; ` +
    `openid-configuration answered ${oidc?.status ?? "nothing"} (404 is right)`,
);

// R3
if (process.env.ITERATE_SESSION_COOKIE) {
  const facts = await ask("/self-test/facts", {
    headers: { cookie: process.env.ITERATE_SESSION_COOKIE },
  }).catch(() => null);
  const results = facts?.ok ? (await facts.json()).results || [] : [];
  const bad = results.filter((result) => result.pass === false).map((result) => result.id);
  say(
    facts?.ok && bad.length === 0 ? "pass" : "FAIL",
    "R3",
    facts?.ok
      ? `${results.length - bad.length} of ${results.length} self-test results pass${bad.length ? `; failed: ${bad.join(", ")}` : ""}`
      : `/self-test/facts answered ${facts?.status ?? "nothing"}`,
  );
} else say("skip", "R3", "no ITERATE_SESSION_COOKIE: the self-test needs a member's session");

// O1
const cloud = flag("--cloud") || "https://cloud.iterate.com";
if (args.includes("--no-cloud")) say("skip", "O1", "not asked (--no-cloud)");
else if (!config) say("FAIL", "O1", "the stored config could not be read");
else {
  const published = await fetch(`${cloud}/.well-known/iterate-cloud`)
    .then((answer) => answer.json())
    .catch(() => ({}));
  const key = (config.auth?.keys || []).find((entry) => entry.actor === published.actor);
  const same = Boolean(key) && key.publicKey === published.publicKey;
  say(
    config.cloud?.origin === cloud && same ? "pass" : "FAIL",
    "O1",
    `the stored config names the Cloud ${config.cloud?.origin}; ` +
      (same
        ? "its key is the Cloud's"
        : key
          ? "its key is NOT the Cloud's"
          : "it holds no key of the Cloud"),
  );
}

// What the stack holds
const sql = async (database, text) =>
  (await cf(`/accounts/${account}/d1/database/${database}/query`, { sql: text })).result[0].results;
const rows = {};
let members = null;
const [database] = (await cf(`/accounts/${account}/d1/database?name=${prefix}auth-db`)).result;
if (database) {
  const tables = (
    await sql(database.uuid, "select name from sqlite_master where type = 'table' order by name")
  ).map((row) => row.name);
  for (const table of tables.filter((table) => /^[a-z_]+$/.test(table) && !table.startsWith("_")))
    rows[table] = (await sql(database.uuid, `select count(*) as n from ${table}`))[0].n;
  if (tables.includes("keys"))
    rows["keys in use"] = (
      await sql(database.uuid, "select count(*) as n from keys where revoked_at is null")
    )[0].n;
  if (tables.includes("members")) {
    const emails = (await sql(database.uuid, "select email from members order by email")).map(
      (row) => row.email,
    );
    members = createHash("sha256").update(emails.join("\n")).digest("hex").slice(0, 16);
  }
}
const kv = {};
for (const space of (await all(`/accounts/${account}/storage/kv/namespaces`)).filter((space) =>
  space.title.startsWith(prefix),
)) {
  // a key with an expiry is a cache entry: it is not counted
  kv[space.title] = await counted(
    `/accounts/${account}/storage/kv/namespaces/${space.id}/keys?limit=1000`,
    (key) => !key.expiration,
  );
}
const files = {};
for (const bucket of (await cf(`/accounts/${account}/r2/buckets?name_contains=${prefix}`)).result
  .buckets)
  files[bucket.name] = await counted(
    `/accounts/${account}/r2/buckets/${bucket.name}/objects?per_page=1000`,
  );
const repos = await cf(`/accounts/${account}/artifacts/namespaces/${prefix}repos/repos`)
  .then((data) => data.result.map((repo) => repo.name).toSorted())
  .catch(() => null);
const objects = {};
for (const space of (await all(`/accounts/${account}/workers/durable_objects/namespaces`)).filter(
  (space) => space.script?.startsWith(prefix) && !space.script.endsWith("-state"),
))
  objects[`${space.script.slice(prefix.length)} ${space.class}`] = await counted(
    `/accounts/${account}/workers/durable_objects/namespaces/${space.id}/objects?limit=1000`,
  );

const now = {
  at: new Date().toISOString(),
  domain,
  name,
  provided,
  workers,
  rows,
  members,
  kv,
  files,
  repos,
  objects,
};
console.log(
  `holds ${Object.keys(workers).length} Workers; rows ${JSON.stringify(rows)}; kv ${JSON.stringify(kv)}; ` +
    `files ${JSON.stringify(files)}; repos ${JSON.stringify(repos)}; objects ${JSON.stringify(objects)}`,
);
for (const [id, worker] of Object.entries(workers))
  console.log(`version ${id} ${worker.version} made ${worker.madeAt} by ${worker.source}`);
if (flag("--out")) writeFileSync(flag("--out"), `${JSON.stringify(now, null, 1)}\n`);

// U4 and U6: against the file from before the update
if (flag("--before")) {
  const before = JSON.parse(readFileSync(flag("--before"), "utf8"));
  const stale = Object.entries(now.workers)
    .filter(([id, worker]) => {
      const was = before.workers[id];
      return !was || was.version === worker.version || !(worker.madeAt > before.at);
    })
    .map(([id]) => id);
  const gone = Object.keys(before.workers).filter((id) => !now.workers[id]);
  say(
    stale.length || gone.length ? "FAIL" : "pass",
    "U4",
    stale.length || gone.length
      ? [
          ...stale.map((id) => `${id} runs no new version`),
          ...gone.map((id) => `${id} is gone`),
        ].join("; ")
      : `each of the ${Object.keys(now.workers).length} Workers runs a version made after ${before.at}`,
  );
  // What a person put in must be there after. A cache, a challenge or a spent ticket may change.
  const KEPT_ROWS = ["members", "users", "identities", "keys in use", "stack_key"];
  const kept = (state) => ({
    members: state.members,
    ...Object.fromEntries(KEPT_ROWS.map((table) => [`rows of ${table}`, state.rows[table]])),
    ...Object.fromEntries(Object.entries(state.files).map(([k, v]) => [`files in ${k}`, v])),
    repos: (state.repos || []).join(", "),
    secrets: state.objects["secrets SecretDurableObject"],
  });
  const [was, is] = [kept(before), kept(now)];
  const changed = Object.keys({ ...was, ...is }).filter((key) => was[key] !== is[key]);
  say(
    changed.length ? "FAIL" : "pass",
    "U6",
    changed.length
      ? changed.map((key) => `${key}: ${was[key]} before, ${is[key]} now`).join("; ")
      : `the same members, ${is["rows of keys in use"]} keys in use, ${is.secrets} secrets, files and repos (${is.repos}) as before`,
  );
  const other = (state) => ({ ...state.kv, ...state.objects, ...state.rows });
  const [o1, o2] = [other(before), other(now)];
  const moved = Object.keys({ ...o1, ...o2 }).filter((key) => o1[key] !== o2[key]);
  if (moved.length)
    console.log(
      `note ${moved.map((key) => `${key}: ${o1[key]} before, ${o2[key]} now`).join("; ")}`,
    );
}
process.exit(failed ? 1 : 0);