iterate.com / cloud

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

cloud / internal-packages / installer / test / takeover.mjsmain at aacbc74

// takeover.mjs — "Erase and replace" (container/takeover.mjs) against a Cloudflare in memory: what
// the list holds and leaves out, what stops an erase before it starts, and which calls an erase
// makes. A call that this Cloudflare does not know is refused, so an erase that reaches for
// anything else fails here. Run: node test/takeover.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import {
  CATALOG,
  eraseAll,
  isMindToken,
  inventoryOf,
  keptOf,
  refusalsOf,
  SINKS_END_MS,
} from "../container/takeover.mjs";

const ACCOUNT = "a".repeat(32);
const ZONE_ID = "z".repeat(32);
const ZONE = "example.com";
const NAME = "example-com";
const z = `/zones/${ZONE_ID}`;
const a = `/accounts/${ACCOUNT}`;

/** A zone with a website, mail, rules and an earlier iterate on it, and an account with more. */
function cloudflare(change = (w) => w) {
  const w = change({
    records: [
      { id: "r-soa", type: "SOA", name: ZONE, content: "ns1.cloudflare.com. dns.cloudflare.com." },
      { id: "r-ns1", type: "NS", name: ZONE, content: "ada.ns.cloudflare.com" },
      { id: "r-ns2", type: "NS", name: `lab.${ZONE}`, content: "ns.elsewhere.example" },
      { id: "r-www", type: "CNAME", name: `www.${ZONE}`, content: "shop.example.net" },
      {
        id: "r-mx",
        type: "MX",
        name: ZONE,
        content: "route1.mx.cloudflare.net",
        meta: { email_routing: true },
      },
      { id: "r-apex", type: "AAAA", name: ZONE, content: "100::" },
    ],
    routes: [
      { id: "rt-1", pattern: `${ZONE}/*`, script: `iterate-${NAME}-ingress` },
      // a route that turns Workers off for an address: no Worker of anybody's is on it
      { id: "rt-2", pattern: `shop.${ZONE}/*` },
      { id: "rt-3", pattern: `*.${ZONE}/*`, script: "iterate" },
    ],
    domains: [{ id: "d-1", hostname: `app.${ZONE}`, service: `iterate-${NAME}-mind` }],
    routing: { enabled: true },
    mailRules: [
      {
        tag: "m-all",
        enabled: true,
        matchers: [{ type: "all" }],
        actions: [{ type: "worker", value: [`iterate-${NAME}-ingress`] }],
      },
    ],
    rulesets: [
      {
        id: "rs-redirect",
        kind: "zone",
        phase: "http_request_dynamic_redirect",
        rules: [{ description: "old shop to new shop" }],
      },
      { id: "rs-empty", kind: "zone", phase: "http_request_origin", rules: [] },
      {
        id: "rs-managed",
        kind: "managed",
        phase: "ddos_l7",
        rules: [{ description: "Cloudflare's own" }],
      },
    ],
    spectrum: [],
    scripts: [
      `iterate-${NAME}-ingress`,
      `iterate-${NAME}-boundary`,
      `iterate-${NAME}-auth`,
      `iterate-${NAME}-project`,
      `iterate-${NAME}-mind`,
      `iterate-${NAME}-state`,
      `iterate-${NAME}-extra`,
      "iterate-example-company-auth",
      "iterate",
      "shop",
    ].map((id) => ({ id })),
    d1: [
      { uuid: "db-1", name: `iterate-${NAME}-auth-db` },
      { uuid: "db-2", name: `iterate-${NAME}-auth-db-copy` },
    ],
    kv: [
      { id: "kv-1", title: `iterate-${NAME}-auth-kv` },
      { id: "kv-2", title: "shop-kv" },
      { id: "kv-3", title: `iterate-${NAME}-project-kv` },
    ],
    pages: [{ name: "docs", domains: [`docs.${ZONE}`, "docs.example.net"] }],
    buckets: [{ name: `iterate-${NAME}-files` }, { name: `iterate-${NAME}-files-backup` }],
    objects: { [`iterate-${NAME}-files`]: ["a.txt", "dir/b c.txt"] },
    // per bucket: the files that a log pipeline's sinks write now (uploads in parts that are not
    // ended), the uploads that nothing will end, the files that land after a list, the rules
    writing: {},
    uploads: {},
    late: {},
    lifecycle: {},
    repos: {},
    pipelines: { pipelines: [], sinks: [], streams: [] },
    destinations: [],
    catalogs: {},
    // the tables of a bucket's data catalog: Cloudflare keeps them when the bucket goes
    tables: {},
    tokens: [],
    refuse: {},
    calls: [],
  });
  const ok = (result) => ({ status: 200, success: true, result });
  const no = (status, code, message) => ({ status, success: false, errors: [{ code, message }] });
  const drop = (list, key, id) => {
    const at = list.findIndex((x) => x[key] === id);
    if (at < 0) return no(404, 404, "not found");
    list.splice(at, 1);
    return ok(null);
  };
  const routes = [
    ["GET", /^Z\/dns_records\?/, () => ok(w.records)],
    ["DELETE", /^Z\/dns_records\/(.+)$/, (id) => drop(w.records, "id", id)],
    ["GET", /^Z\/workers\/routes$/, () => ok(w.routes)],
    ["DELETE", /^Z\/workers\/routes\/(.+)$/, (id) => drop(w.routes, "id", id)],
    ["GET", /^A\/workers\/domains\?zone_id=/, () => ok(w.domains)],
    ["DELETE", /^A\/workers\/domains\/(.+)$/, (id) => drop(w.domains, "id", id)],
    ["GET", /^Z\/custom_hostnames\/fallback_origin$/, () => no(404, 1551, "none")],
    ["GET", /^Z\/spectrum\/apps$/, () => ok(w.spectrum)],
    ["GET", /^Z\/email\/routing$/, () => ok(w.routing)],
    ["POST", /^Z\/email\/routing\/disable$/, () => ((w.routing = { enabled: false }), ok(null))],
    [
      "DELETE",
      /^Z\/email\/routing\/dns$/,
      () => ((w.records = w.records.filter((r) => !r.meta?.email_routing)), ok(null)),
    ],
    ["GET", /^Z\/email\/routing\/rules\?/, () => ok(w.mailRules)],
    [
      "PUT",
      /^Z\/email\/routing\/rules\/catch_all$/,
      (body) => ((w.mailRules = [{ tag: "m-all", ...body }]), ok(null)),
    ],
    ["GET", /^Z\/rulesets$/, () => ok(w.rulesets.map(({ rules: _, ...set }) => set))],
    ["GET", /^Z\/rulesets\/(.+)$/, (id) => ok(w.rulesets.find((s) => s.id === id))],
    [
      "PUT",
      /^Z\/rulesets\/(.+)$/,
      (id, body) => ((w.rulesets.find((s) => s.id === id).rules = body.rules), ok(null)),
    ],
    ["GET", /^Z\/pagerules$/, () => no(403, 1011, "this token cannot read page rules")],
    ["GET", /^Z\/bot_management$/, () => ok({ fight_mode: false })],
    ["GET", /^A\/pages\/projects\?/, () => ok(w.pages)],
    [
      "DELETE",
      /^A\/pages\/projects\/([^/]+)\/domains\/(.+)$/,
      (site, domain) => {
        const found = w.pages.find((p) => p.name === site);
        found.domains = found.domains.filter((d) => d !== domain);
        return ok(null);
      },
    ],
    ["GET", /^A\/workers\/scripts$/, () => ok(w.scripts)],
    ["DELETE", /^A\/workers\/scripts\/([^?]+)\?force=true$/, (id) => drop(w.scripts, "id", id)],
    ["GET", /^A\/d1\/database\?/, () => ok(w.d1)],
    ["DELETE", /^A\/d1\/database\/(.+)$/, (id) => drop(w.d1, "uuid", id)],
    ["GET", /^A\/storage\/kv\/namespaces\?/, () => ok(w.kv)],
    ["DELETE", /^A\/storage\/kv\/namespaces\/(.+)$/, (id) => drop(w.kv, "id", id)],
    ["GET", /^A\/r2\/buckets\?/, () => ok({ buckets: w.buckets })],
    [
      "GET",
      /^A\/r2\/buckets\/([^/]+)\/objects\?/,
      (bucket) => ok((w.objects[bucket] || []).map((key) => ({ key }))),
    ],
    [
      "DELETE",
      /^A\/r2\/buckets\/([^/]+)\/objects\/(.+)$/,
      (bucket, key) => {
        w.objects[bucket] = w.objects[bucket].filter((k) => k !== decodeURIComponent(key));
        return ok(null);
      },
    ],
    [
      "DELETE",
      /^A\/r2\/buckets\/([^/]+)$/,
      (bucket) => {
        // something that still writes puts a file there after the list was empty
        const late = w.late[bucket]?.shift();
        if (late) w.objects[bucket] = [...(w.objects[bucket] || []), late];
        // as R2 does: an unfinished upload holds the bucket, and no list of its files shows one
        return (w.objects[bucket] || []).length > 0 || w.uploads[bucket] > 0
          ? no(409, 10008, "the bucket is not empty")
          : w.catalogs[bucket] === "active"
            ? no(409, 10073, "the bucket has a data catalog")
            : drop(w.buckets, "name", bucket);
      },
    ],
    ["GET", /^A\/r2\/buckets\/([^/]+)\/lifecycle$/, (b) => ok({ rules: w.lifecycle[b] || [] })],
    [
      "PUT",
      /^A\/r2\/buckets\/([^/]+)\/lifecycle$/,
      (bucket, body) => ((w.lifecycle[bucket] = body.rules), ok({})),
    ],
    // the telemetry part: Cloudflare refuses a sink or a stream that a pipeline uses, and a
    // destination that a Worker names
    ["GET", /^A\/pipelines\/v1\/(pipelines|sinks|streams)\?/, (kind) => ok(w.pipelines[kind])],
    [
      "DELETE",
      /^A\/pipelines\/v1\/(pipelines|sinks|streams)\/(.+)$/,
      (kind, id) => {
        const it = w.pipelines[kind].find((p) => p.id === id);
        const user = kind !== "pipelines" && w.pipelines.pipelines.find((p) => p.uses.includes(id));
        // a pipeline that goes in the middle of a file leaves the upload unfinished
        if (kind === "pipelines" && it?.bucket && w.writing[it.bucket] > 0) {
          w.uploads[it.bucket] = (w.uploads[it.bucket] || 0) + w.writing[it.bucket];
          w.writing[it.bucket] = 0;
        }
        return user
          ? no(409, 1002, `in use by ${user.name}`)
          : drop(w.pipelines[kind], "id", it?.id);
      },
    ],
    ["GET", /^A\/workers\/observability\/destinations$/, () => ok(w.destinations)],
    [
      "DELETE",
      /^A\/workers\/observability\/destinations\/(.+)$/,
      (slug) =>
        w.scripts.some((x) => x.id === `iterate-${NAME}-auth`)
          ? no(409, 1003, "a Worker sends to this destination")
          : drop(w.destinations, "slug", slug),
    ],
    [
      "GET",
      /^A\/r2-catalog\/([^/]+)$/,
      (bucket) =>
        w.catalogs[bucket]
          ? ok({ status: w.catalogs[bucket], id: `wh-${bucket}` })
          : no(404, 40401, "no warehouse"),
    ],
    [
      "GET",
      /^A\/r2-catalog\/([^/]+)\/namespaces\/telemetry\/tables$/,
      (bucket) =>
        w.catalogs[bucket] !== "active"
          ? no(400, 40402, "Warehouse inactive")
          : w.tables[bucket]
            ? ok({
                identifiers: w.tables[bucket].map((name) => ({ namespace: ["telemetry"], name })),
              })
            : no(404, 40404, "no such namespace"),
    ],
    [
      "DELETE",
      // the catalog's own address, with the catalog's id in the path
      new RegExp(`^${CATALOG}/${ACCOUNT}/([^/]+)/v1/wh-\\1/namespaces/telemetry/tables/([^/?#]+)$`),
      (bucket, table) => {
        if (w.catalogs[bucket] !== "active") return no(404, 404, "Warehouse not found");
        if (w.tablesStay || !w.tables[bucket]?.includes(table))
          return no(403, 403, "Table not found or action can_drop forbidden for Anonymous");
        w.tables[bucket] = w.tables[bucket].filter((name) => name !== table);
        return ok(null);
      },
    ],
    [
      "DELETE",
      new RegExp(`^${CATALOG}/${ACCOUNT}/([^/]+)/v1/wh-\\1/namespaces/telemetry$`),
      (bucket) =>
        w.catalogs[bucket] !== "active"
          ? no(404, 404, "Warehouse not found")
          : w.tables[bucket]?.length > 0
            ? no(409, 409, "Namespace is not empty")
            : (delete w.tables[bucket], ok(null)),
    ],
    [
      "POST",
      /^A\/r2-catalog\/([^/]+)\/disable$/,
      (bucket) => ((w.catalogs[bucket] = "inactive"), ok(null)),
    ],
    [
      "GET",
      /^A\/tokens\?/,
      () => (w.tokens ? ok(w.tokens) : no(403, 9109, "Unauthorized to access requested resource")),
    ],
    [
      "DELETE",
      /^A\/tokens\/(.+)$/,
      (id) =>
        w.tokensStay
          ? no(403, 9109, "Unauthorized to access requested resource")
          : drop(w.tokens, "id", id),
    ],
    [
      "GET",
      /^A\/artifacts\/namespaces\?/,
      () => ok(Object.keys(w.repos).map((namespace) => ({ namespace }))),
    ],
    [
      "GET",
      /^A\/artifacts\/namespaces\/([^/]+)\/repos\?/,
      (ns) => ok(w.repos[ns].map((name) => ({ name }))),
    ],
    [
      "DELETE",
      // one path part: a name that is not encoded reaches another path, and no route here
      /^A\/artifacts\/namespaces\/([^/]+)\/repos\/([^/?#]+)$/,
      (ns, name) => {
        if (!w.repos[ns].includes(decodeURIComponent(name))) return no(404, 404, "not found");
        w.repos[ns] = w.repos[ns].filter((r) => r !== decodeURIComponent(name));
        return ok(null);
      },
    ],
    [
      "DELETE",
      /^A\/artifacts\/namespaces\/([^/]+)$/,
      (ns) =>
        w.repos[ns].length > 0
          ? no(409, 409, "the namespace has repos")
          : (delete w.repos[ns], ok(null)),
    ],
  ];
  const cf = async (method, asked, body) => {
    w.calls.push([method, asked, body]);
    // as `fetch` does (erase.mjs `cf`): an address is resolved before it is sent, so a path part
    // `.` or `..`, percent-encoded or not, is gone from it and names another place
    const path = asked.startsWith("/") ? resolved(asked) : asked;
    const short = path.replace(z, "Z").replace(a, "A");
    if (w.refuse[`${method} ${short}`]) return no(403, 10000, "Authentication error");
    for (const [m, pattern, answer] of routes) {
      const hit = m === method && pattern.exec(short);
      if (hit) return answer(...hit.slice(1), body);
    }
    // every other list is empty; every other change is one this test does not expect
    return method === "GET" ? ok([]) : no(400, 7003, `no such call here: ${method} ${short}`);
  };
  return { w, cf, changes: () => w.calls.filter(([method]) => method !== "GET") };
}
/** The path and query of an address as a URL parser leaves them, without its changes to other
 *  characters: only the dot parts go. */
function resolved(asked) {
  const [path, query] = asked.split(/\?(.*)/s);
  const parts = [];
  for (const part of path.split("/")) {
    const dots = part.replace(/%2e/gi, ".");
    if (dots === ".") continue;
    if (dots === "..") parts.pop();
    else parts.push(part);
  }
  const last = path.split("/").at(-1).replace(/%2e/gi, ".");
  const folder = last === "." || last === "..";
  return `${parts.join("/")}${folder ? "/" : ""}${query === undefined ? "" : `?${query}`}`;
}
const given = (cf) => ({ cf, accountId: ACCOUNT, zoneId: ZONE_ID, zone: ZONE, name: NAME });
const quick = { say: () => {}, wait: async () => {} };

test("the list: what is on the domain and the stack's own things, by their exact names", async () => {
  const { cf } = cloudflare();
  const found = await inventoryOf(given(cf));
  const ids = found.items.map((i) => `${i.kind} ${i.id}`).sort();
  assert.deepEqual(ids, [
    "d1_database db-1",
    "dns_record r-apex",
    "dns_record r-mx",
    "dns_record r-ns2",
    "dns_record r-www",
    "email_routing email_routing",
    "email_routing_catch_all m-all",
    "kv_namespace kv-1",
    "kv_namespace kv-3",
    `pages_custom_domain docs/docs.${ZONE}`,
    `r2_bucket iterate-${NAME}-files`,
    `state_store iterate-${NAME}-state`,
    `worker iterate-${NAME}-auth`,
    `worker iterate-${NAME}-boundary`,
    `worker iterate-${NAME}-ingress`,
    `worker iterate-${NAME}-mind`,
    `worker iterate-${NAME}-project`,
    "workers_custom_domain d-1",
    "workers_route rt-1",
    "workers_route rt-2",
    "workers_route rt-3",
    "zone_ruleset rs-redirect",
  ]);
  assert.match(found.digest, /^[0-9a-f]{24}$/);
  // a list that Cloudflare refuses and that the erase can go without is said, and stops nothing
  assert.deepEqual(
    found.unread.map((u) => [u.what, u.must]),
    [["the page rules", false]],
  );
  assert.deepEqual(refusalsOf(found), []);
});

test("the zone's own SOA and nameserver records are not in the list; a delegation under it is", async () => {
  const { cf } = cloudflare();
  const names = (await inventoryOf(given(cf))).items
    .filter((i) => i.kind === "dns_record")
    .map((i) => i.name);
  assert.ok(!names.includes(`SOA ${ZONE}`) && !names.includes(`NS ${ZONE}`), names.join());
  assert.ok(names.includes(`NS lab.${ZONE}`));
});

test("the erase: the agreed list goes, in order, and reads empty; nothing else is touched", async () => {
  const { w, cf, changes } = cloudflare();
  const { digest } = await inventoryOf(given(cf));
  const said = [];
  const done = await eraseAll({
    ...given(cf),
    agreed: digest,
    say: (l) => said.push(l),
    wait: quick.wait,
  });
  assert.deepEqual(done, { ok: true });
  assert.match(said.at(-2), /^Read again: nothing is left on example\.com\.$/);
  // the Worker that an earlier wizard named "iterate" loses its route here and is itself left
  assert.match(said.at(-1), /^Note: .*Worker “iterate”.*the Worker itself is left/);
  const made = changes().map(
    ([method, path]) => `${method} ${path.replace(z, "Z").replace(a, "A")}`,
  );
  // a phase's entry point is emptied, never deleted; Cloudflare's own sets are left alone
  assert.ok(made.includes("PUT Z/rulesets/rs-redirect"));
  assert.ok(!made.some((c) => /^DELETE Z\/rulesets/.test(c) || /rs-managed|rs-empty/.test(c)));
  assert.deepEqual(
    w.rulesets.map((s) => [s.id, s.rules.length]),
    [
      ["rs-redirect", 0],
      ["rs-empty", 0],
      ["rs-managed", 1],
    ],
  );
  // what holds a name first, the records after it, the stack's own resources last
  const at = (call) => made.findIndex((c) => c.startsWith(call));
  assert.ok(at("DELETE A/workers/domains/d-1") < at("DELETE Z/workers/routes/rt-1"));
  assert.ok(at("DELETE Z/workers/routes/rt-2") < at("DELETE Z/dns_records/r-www"));
  assert.ok(at("DELETE Z/dns_records/r-www") < at(`DELETE A/workers/scripts/iterate-${NAME}-auth`));
  assert.ok(made.at(-1).startsWith(`DELETE A/workers/scripts/iterate-${NAME}-state`));
  // what stays: the zone's own records, other people's Workers and stores, things with longer names
  assert.deepEqual(
    w.records.map((r) => r.id),
    ["r-soa", "r-ns1"],
  );
  assert.deepEqual(
    w.scripts.map((s) => s.id),
    [`iterate-${NAME}-extra`, "iterate-example-company-auth", "iterate", "shop"],
  );
  assert.deepEqual(
    w.d1.map((d) => d.uuid),
    ["db-2"],
  );
  assert.deepEqual(
    w.kv.map((k) => k.id),
    ["kv-2"],
  );
  // a site on Pages keeps its other names
  assert.deepEqual(w.pages, [{ name: "docs", domains: ["docs.example.net"] }]);
  assert.deepEqual(
    w.buckets.map((b) => b.name),
    [`iterate-${NAME}-files-backup`],
  );
  assert.ok(!made.some((c) => /^DELETE Z$|dnssec|members|tokens/.test(c)));
});

test("a repo's name is one part of the path that deletes it, whatever characters it has", async () => {
  const names = ["config", "notes/2026", "../../workers/scripts/shop", "a?force=true#b", "x y"];
  const { w, cf, changes } = cloudflare((world) => ({
    ...world,
    repos: { [`iterate-${NAME}-repos`]: [...names], "shop-repos": ["site"] },
  }));
  const { digest } = await inventoryOf(given(cf));
  assert.deepEqual(await eraseAll({ ...given(cf), agreed: digest, ...quick }), { ok: true });
  assert.deepEqual(w.repos, { "shop-repos": ["site"] });
  const gone = changes()
    .map(([, path]) => path.replace(a, "A"))
    .filter((path) => path.includes("/repos/"));
  assert.deepEqual(
    gone,
    names.map((n) => `A/artifacts/namespaces/iterate-${NAME}-repos/repos/${encodeURIComponent(n)}`),
  );
  assert.ok(w.scripts.some((s) => s.id === "shop"));
});

/** The stack with a telemetry part, in an account that has another telemetry of its own. */
const withTelemetry = (world) => {
  const tables = ["events", "logs", "spans"].map((t) => `iterate_example_com_telemetry_${t}`);
  const made = (names, at) => names.map((name, i) => ({ id: `${at}-${i}`, name }));
  const other = ["telemetry_events", "iterate_example_com_x_telemetry_events"];
  return {
    ...world,
    scripts: [...world.scripts, { id: `iterate-${NAME}-telemetry` }],
    buckets: [
      ...world.buckets,
      { name: `iterate-${NAME}-telemetry` },
      { name: "iterate-telemetry" },
    ],
    objects: { ...world.objects, [`iterate-${NAME}-telemetry`]: ["__r2_data_catalog/a.parquet"] },
    catalogs: { [`iterate-${NAME}-telemetry`]: "active", "iterate-telemetry": "active" },
    tables: {
      [`iterate-${NAME}-telemetry`]: ["logs", "events", "spans"],
      "iterate-telemetry": ["events", "logs", "spans"],
    },
    pipelines: {
      pipelines: [
        ...tables.map((name, i) => ({
          id: `p-${i}`,
          name,
          uses: [`si-${i}`, `st-${i}`],
          bucket: `iterate-${NAME}-telemetry`,
        })),
        ...other.map((name, i) => ({ id: `po-${i}`, name, uses: [`sio-${i}`, `sto-${i}`] })),
      ],
      sinks: [
        ...made(
          tables.map((t) => `${t}_sink`),
          "si",
        ),
        ...made(
          other.map((t) => `${t}_sink`),
          "sio",
        ),
      ],
      streams: [
        ...made(
          tables.map((t) => `${t}_stream`),
          "st",
        ),
        ...made(
          other.map((t) => `${t}_stream`),
          "sto",
        ),
      ],
    },
    destinations: [
      `iterate-${NAME}-telemetry-logs`,
      `iterate-${NAME}-telemetry-traces`,
      "telemetry-logs",
    ].map((name) => ({ slug: name, name })),
    // Cloudflare lets two tokens have one name: the erase takes each token of the stack's names
    tokens: [
      { id: "t-1", name: `iterate-${NAME}-telemetry-catalog` },
      { id: "t-2", name: `iterate-${NAME}-telemetry-analytics` },
      { id: "t-3", name: `iterate-${NAME}-telemetry-catalog` },
      { id: "t-4", name: `iterate-${NAME}-telemetry-analytics` },
      { id: "t-5", name: "iterate-telemetry-catalog" },
      // the mind's own token, and another stack's whose name starts with this one's
      { id: "t-6", name: `iterate-${NAME}-cloudflare` },
      { id: "t-7", name: `iterate-${NAME}-x-cloudflare` },
    ],
  };
};
/** What the pretend account still has of telemetry: the stack's own must be gone. */
const telemetryLeft = (w) => ({
  pipelines: w.pipelines.pipelines.map((p) => p.name),
  sinks: w.pipelines.sinks.map((p) => p.name),
  streams: w.pipelines.streams.map((p) => p.name),
  destinations: w.destinations.map((d) => d.name),
  catalogs: w.catalogs,
  buckets: w.buckets.map((b) => b.name).filter((name) => name.includes("telemetry")),
});
const othersTelemetry = {
  pipelines: ["telemetry_events", "iterate_example_com_x_telemetry_events"],
  sinks: ["telemetry_events_sink", "iterate_example_com_x_telemetry_events_sink"],
  streams: ["telemetry_events_stream", "iterate_example_com_x_telemetry_events_stream"],
  destinations: ["telemetry-logs"],
  catalogs: { [`iterate-${NAME}-telemetry`]: "inactive", "iterate-telemetry": "active" },
  buckets: ["iterate-telemetry"],
};

test("a stack with telemetry: its pipelines, catalog, bucket, destinations and tokens are in the list and go", async () => {
  const { w, cf } = cloudflare(withTelemetry);
  const found = await inventoryOf(given(cf));
  assert.deepEqual(refusalsOf(found), []);
  const kinds = (kind) => found.items.filter((i) => i.kind === kind).map((i) => i.name);
  assert.equal(kinds("pipeline").length, 3);
  assert.equal(kinds("pipeline_sink").length, 3);
  assert.equal(kinds("pipeline_stream").length, 3);
  assert.deepEqual(kinds("r2_catalog"), [`iterate-${NAME}-telemetry`]);
  assert.deepEqual(kinds("r2_catalog_table").sort(), [
    "telemetry.events",
    "telemetry.logs",
    "telemetry.spans",
  ]);
  assert.deepEqual(kinds("r2_catalog_namespace"), ["telemetry"]);
  assert.deepEqual(kinds("observability_destination"), [
    `iterate-${NAME}-telemetry-logs`,
    `iterate-${NAME}-telemetry-traces`,
  ]);
  // telemetry's four, and the mind's own by its name
  assert.equal(kinds("api_token").length, 5);
  assert.ok(kinds("api_token").includes(`iterate-${NAME}-cloudflare`));
  const said = [];
  const done = await eraseAll({
    ...given(cf),
    agreed: found.digest,
    say: (l) => said.push(l),
    wait: quick.wait,
  });
  // the pretend Cloudflare refuses a wrong order, so { ok: true } says that the order is right
  assert.deepEqual(done, { ok: true });
  assert.deepEqual(telemetryLeft(w), othersTelemetry);
  assert.deepEqual(w.tokens, [
    { id: "t-5", name: "iterate-telemetry-catalog" },
    { id: "t-7", name: `iterate-${NAME}-x-cloudflare` },
  ]);
  assert.ok(!said.some((l) => /API token/.test(l) && /^Note|^Left/.test(l)));
  // the catalog's tables go before the catalog is turned off: only the other catalog's are left
  assert.deepEqual(w.tables, { "iterate-telemetry": ["events", "logs", "spans"] });
  assert.ok(!said.some((l) => /^(Note|Left).*(Table|Namespace|data catalog)/.test(l)));
  assert.equal(said.filter((l) => /^Erased: (Table|Namespace) telemetry/.test(l)).length, 4);
});

test("the tables of the stack's data catalog: one that Cloudflare does not let the erase drop is left and said, and the erase goes through", async () => {
  const { w, cf } = cloudflare(withTelemetry);
  w.tablesStay = true;
  const said = [];
  const done = await eraseAll({ ...given(cf), say: (l) => said.push(l), wait: quick.wait });
  assert.deepEqual(done, { ok: true });
  assert.equal(
    said.filter((l) => /^Left: Table telemetry\.(events|logs|spans) /.test(l)).length,
    3,
  );
  assert.equal(said.filter((l) => /^Left: Namespace telemetry /.test(l)).length, 1);
  const notes = said.filter((l) => /^Note: .*data catalog/.test(l));
  assert.equal(notes.length, 1);
  assert.match(notes[0], new RegExp(`R2 bucket iterate-${NAME}-telemetry: `));
  for (const name of ["telemetry.events", "telemetry.logs", "telemetry.spans", "telemetry\\."])
    assert.match(notes[0], new RegExp(name));
  assert.match(notes[0], /gets no telemetry/);
  // the rest of the telemetry part went all the same
  assert.deepEqual(telemetryLeft(w), othersTelemetry);
  assert.equal(w.tables[`iterate-${NAME}-telemetry`].length, 3);
});

test("the tables of the stack's data catalog: a list that Cloudflare refuses is said before the erase and after it, and the erase goes through", async () => {
  const BUCKET = `iterate-${NAME}-telemetry`;
  const { w, cf } = cloudflare((world) => ({
    ...withTelemetry(world),
    refuse: { [`GET A/r2-catalog/${BUCKET}/namespaces/telemetry/tables`]: true },
  }));
  const found = await inventoryOf(given(cf));
  assert.deepEqual(refusalsOf(found), []);
  // the page takes a list only when each entry of `unread` says `must` (src/erase.ts)
  for (const u of found.unread) assert.equal(typeof u.must, "boolean");
  assert.deepEqual(
    found.unread.filter((u) => /tables/.test(u.what)).map((u) => u.must),
    [false],
  );
  const kinds = found.items.map((i) => i.kind);
  assert.ok(kinds.includes("r2_catalog"));
  assert.ok(!kinds.includes("r2_catalog_table") && !kinds.includes("r2_catalog_namespace"));
  const said = [];
  const done = await eraseAll({
    ...given(cf),
    agreed: found.digest,
    say: (l) => said.push(l),
    wait: quick.wait,
  });
  assert.deepEqual(done, { ok: true });
  const notes = said.filter((l) => /^Note: .*data catalog/.test(l));
  assert.equal(notes.length, 1);
  assert.match(notes[0], new RegExp(`did not let iterate read the tables .* R2 bucket ${BUCKET},`));
  assert.match(notes[0], /telemetry\.events, telemetry\.logs, telemetry\.spans/);
  assert.match(notes[0], /gets no telemetry/);
  // no call went to the catalog's own address, and the rest of the telemetry part went
  assert.deepEqual(
    w.calls.filter(([, path]) => path.startsWith("https://")),
    [],
  );
  assert.deepEqual(telemetryLeft(w), othersTelemetry);
  assert.equal(w.tables[BUCKET].length, 3);
});

test("the tables of the stack's data catalog: a table of another name stays, and so does the namespace", async () => {
  const BUCKET = `iterate-${NAME}-telemetry`;
  const { w, cf } = cloudflare((world) => {
    const made = withTelemetry(world);
    return { ...made, tables: { ...made.tables, [BUCKET]: ["logs", "mine", "spans"] } };
  });
  const found = await inventoryOf(given(cf));
  const names = (kind) => found.items.filter((i) => i.kind === kind).map((i) => i.name);
  assert.deepEqual(names("r2_catalog_table").sort(), ["telemetry.logs", "telemetry.spans"]);
  assert.deepEqual(names("r2_catalog_namespace"), []);
  const done = await eraseAll({ ...given(cf), agreed: found.digest, ...quick });
  assert.deepEqual(done, { ok: true });
  assert.deepEqual(w.tables[BUCKET], ["mine"]);
  // every call to the catalog's own address names the stack's bucket and one of its tables
  const elsewhere = w.calls.filter(([, path]) => path.startsWith("https://"));
  assert.equal(elsewhere.length, 2);
  for (const [method, path] of elsewhere) {
    assert.equal(method, "DELETE");
    assert.match(
      path,
      new RegExp(
        `^${CATALOG}/${ACCOUNT}/${BUCKET}/v1/wh-${BUCKET}/namespaces/telemetry/tables/(logs|spans)$`,
      ),
    );
  }
});

test("a sign-in that may not read API tokens: the erase goes through and says that the tokens can be left", async () => {
  const { w, cf } = cloudflare((world) => ({ ...withTelemetry(world), tokens: null }));
  const found = await inventoryOf(given(cf));
  assert.deepEqual(refusalsOf(found), []);
  assert.deepEqual(
    found.unread.map((u) => [u.what, u.must]),
    [
      ["the page rules", false],
      ["the account's API tokens", false],
    ],
  );
  const said = [];
  const done = await eraseAll({
    ...given(cf),
    agreed: found.digest,
    say: (l) => said.push(l),
    wait: quick.wait,
  });
  assert.deepEqual(done, { ok: true });
  assert.deepEqual(telemetryLeft(w), othersTelemetry);
  const note = said.find((l) => /^Note: This deployment had telemetry/.test(l));
  assert.match(
    note,
    new RegExp(
      `iterate-${NAME}-telemetry-catalog, iterate-${NAME}-telemetry-analytics\\), and iterate-${NAME}-cloudflare if its mind had a Cloudflare connection, can be left`,
    ),
  );
  assert.match(note, /Manage account, Account API tokens/);
});

test("a sign-in that reads API tokens and may not delete them: the erase goes through and names them", async () => {
  const { w, cf } = cloudflare((world) => ({ ...withTelemetry(world), tokensStay: true }));
  const { digest } = await inventoryOf(given(cf));
  const said = [];
  const done = await eraseAll({
    ...given(cf),
    agreed: digest,
    say: (l) => said.push(l),
    wait: quick.wait,
  });
  assert.deepEqual(done, { ok: true });
  assert.deepEqual(telemetryLeft(w), othersTelemetry);
  assert.equal(w.tokens.length, 7);
  assert.equal(said.filter((l) => /^Left: API token /.test(l)).length, 5);
  // each token is asked for once, not again on each pass
  assert.equal(
    w.calls.filter(([method, path]) => method === "DELETE" && /\/tokens\//.test(path)).length,
    5,
  );
  const stayed = said.find((l) => /^Note: Cloudflare did not let iterate delete/.test(l));
  assert.match(stayed, /5 API tokens of this deployment \(/);
  for (const use of ["telemetry-analytics", "telemetry-catalog", "cloudflare"])
    assert.ok(stayed.includes(`iterate-${NAME}-${use}`), use);
  assert.ok(!stayed.includes(`iterate-${NAME}-x-cloudflare`));
});

const BUCKET = `iterate-${NAME}-telemetry`;
const short = ([method, path]) => `${method} ${path.replace(z, "Z").replace(a, "A")}`;

test("log pipelines that write a file: the erase waits for the sinks after the Workers and before a pipeline, and the bucket goes", async () => {
  const { w, cf } = cloudflare((world) => ({ ...withTelemetry(world), writing: { [BUCKET]: 2 } }));
  const { digest } = await inventoryOf(given(cf));
  const said = [];
  const done = await eraseAll({
    ...given(cf),
    agreed: digest,
    say: (l) => said.push(l),
    // as the sinks do: with nothing that writes to them, they end their files in that time
    wait: async (ms) => {
      w.calls.push(["WAIT", String(ms)]);
      const writes =
        w.scripts.some((s) => s.id === BUCKET) ||
        w.destinations.some((d) => d.name !== "telemetry-logs");
      if (ms >= SINKS_END_MS && !writes && w.writing[BUCKET] > 0) {
        w.objects[BUCKET].push("__r2_data_catalog/b.parquet", "__r2_data_catalog/c.parquet");
        w.writing[BUCKET] = 0;
      }
    },
  });
  assert.deepEqual(done, { ok: true });
  assert.deepEqual(telemetryLeft(w), othersTelemetry);
  assert.equal(said.filter((l) => /^Waiting 120 seconds: the log pipelines/.test(l)).length, 1);
  const calls = w.calls.map(short);
  const waited = calls.indexOf(`WAIT ${SINKS_END_MS}`);
  const last = (pattern) => calls.findLastIndex((c) => pattern.test(c));
  assert.equal(calls.filter((c) => c === `WAIT ${SINKS_END_MS}`).length, 1);
  // the state store's Worker goes at the very end, and writes to no pipeline
  assert.ok(last(/^DELETE A\/workers\/scripts\/(?!.*-state\?)/) < waited);
  assert.ok(last(/^DELETE A\/workers\/observability\/destinations\//) < waited);
  assert.ok(calls.findIndex((c) => /^DELETE A\/pipelines\/v1\/pipelines\//.test(c)) > waited);
  assert.ok(!said.some((l) => /^Left: /.test(l)));
});

test("a bucket that R2 calls not empty with no file in its list: it is left with a rule, said, and the erase goes through", async () => {
  const kept = { id: "keep", enabled: true, conditions: { prefix: "old/" } };
  const { w, cf } = cloudflare((world) => ({
    ...withTelemetry(world),
    uploads: { [BUCKET]: 2 },
    lifecycle: { [BUCKET]: [kept, { id: "iterate-erase-unfinished-uploads", enabled: false }] },
  }));
  const { digest } = await inventoryOf(given(cf));
  const said = [];
  const done = await eraseAll({
    ...given(cf),
    agreed: digest,
    say: (l) => said.push(l),
    wait: quick.wait,
  });
  assert.deepEqual(done, { ok: true });
  // everything else of the stack is gone; the bucket is there, with no file
  assert.deepEqual(telemetryLeft(w), {
    ...othersTelemetry,
    buckets: [BUCKET, "iterate-telemetry"],
  });
  assert.deepEqual(w.objects[BUCKET], []);
  assert.deepEqual(
    w.buckets.map((b) => b.name),
    [`iterate-${NAME}-files-backup`, BUCKET, "iterate-telemetry"],
  );
  assert.deepEqual(w.lifecycle[BUCKET], [
    kept,
    {
      id: "iterate-erase-unfinished-uploads",
      enabled: true,
      conditions: { prefix: "" },
      abortMultipartUploadsTransition: { condition: { type: "Age", maxAge: 86400 } },
    },
  ]);
  assert.deepEqual(
    said.filter((l) => /^Left: /.test(l)),
    [
      `Left: R2 bucket ${BUCKET}. No file is in it, and Cloudflare holds an unfinished upload in it (10008: the bucket is not empty).`,
    ],
  );
  const note = said.find((l) => /^Note: The R2 bucket /.test(l));
  assert.match(
    note,
    new RegExp(`^Note: The R2 bucket ${BUCKET} is left in your Cloudflare account`),
  );
  assert.match(
    note,
    /iterate set a rule on the bucket that removes unfinished uploads after a day/,
  );
  assert.ok(!said.some((l) => /API token/.test(l) && /^Note|^Left/.test(l)));
  // four tries on the first pass, none on a later one; no other bucket's rules are touched
  const calls = w.calls.map(short);
  assert.equal(calls.filter((c) => c === `DELETE A/r2/buckets/${BUCKET}`).length, 4);
  assert.deepEqual(
    calls.filter((c) => /\/lifecycle$/.test(c)),
    [`GET A/r2/buckets/${BUCKET}/lifecycle`, `PUT A/r2/buckets/${BUCKET}/lifecycle`],
  );

  // a day later Cloudflare has removed the uploads: the next erase lists the bucket and takes it
  w.uploads = {};
  const again = await inventoryOf(given(cf));
  assert.deepEqual(
    again.items.map((i) => [i.kind, i.name]),
    [["r2_bucket", BUCKET]],
  );
  assert.deepEqual(await eraseAll({ ...given(cf), agreed: again.digest, ...quick }), { ok: true });
  assert.deepEqual(telemetryLeft(w), othersTelemetry);
});

test("a bucket that is left, and Cloudflare refuses the rule: the erase goes through and claims no rule", async () => {
  const { w, cf } = cloudflare((world) => ({
    ...withTelemetry(world),
    uploads: { [BUCKET]: 1 },
    refuse: { [`PUT A/r2/buckets/${BUCKET}/lifecycle`]: true },
  }));
  const { digest } = await inventoryOf(given(cf));
  const said = [];
  const done = await eraseAll({
    ...given(cf),
    agreed: digest,
    say: (l) => said.push(l),
    wait: quick.wait,
  });
  assert.deepEqual(done, { ok: true });
  assert.deepEqual(w.lifecycle, {});
  const note = said.find((l) => /^Note: The R2 bucket /.test(l));
  assert.match(note, /Cloudflare removes an unfinished upload after some days/);
  assert.doesNotMatch(note, /iterate set a rule/);
});

test("a file that lands in a bucket after its list was empty: the erase looks again and the bucket goes", async () => {
  const files = `iterate-${NAME}-files`;
  const { w, cf } = cloudflare((world) => ({ ...world, late: { [files]: ["late-1", "late-2"] } }));
  const { digest } = await inventoryOf(given(cf));
  const said = [];
  const done = await eraseAll({
    ...given(cf),
    agreed: digest,
    say: (l) => said.push(l),
    wait: quick.wait,
  });
  assert.deepEqual(done, { ok: true });
  assert.ok(!w.buckets.some((b) => b.name === files));
  assert.ok(!said.some((l) => /^Left: /.test(l)));
  assert.equal(w.calls.map(short).filter((c) => c === `DELETE A/r2/buckets/${files}`).length, 3);
});

test("a file whose key is `.` or `..`: no address names it, so the erase sends none, leaves the bucket, says so, and goes through", async () => {
  const files = `iterate-${NAME}-files`;
  const { w, cf } = cloudflare((world) => ({
    ...world,
    objects: { [files]: [".", "..", "a.txt", "dir/b c.txt"] },
  }));
  // what a URL parser makes of the two addresses, which is why they cannot be sent
  assert.equal(resolved(`${a}/r2/buckets/${files}/objects/.`), `${a}/r2/buckets/${files}/objects/`);
  assert.equal(resolved(`${a}/r2/buckets/${files}/objects/%2E%2e`), `${a}/r2/buckets/${files}/`);
  const { digest } = await inventoryOf(given(cf));
  const said = [];
  const done = await eraseAll({
    ...given(cf),
    agreed: digest,
    say: (l) => said.push(l),
    wait: quick.wait,
  });
  assert.deepEqual(done, { ok: true });
  // every file with a name an address can carry is gone; the two others and their bucket stay
  assert.deepEqual(w.objects[files], [".", ".."]);
  assert.ok(w.buckets.some((b) => b.name === files));
  // every call that was sent names what it was meant for: none resolves to another address
  assert.deepEqual(
    w.calls.filter(([, asked]) => asked.startsWith("/") && resolved(asked) !== asked),
    [],
  );
  // the bucket is asked to go once, never while the erase knows it holds a file
  assert.equal(w.calls.map(short).filter((c) => c === `DELETE A/r2/buckets/${files}`).length, 0);
  assert.deepEqual(
    said.filter((l) => /^Left: /.test(l)),
    [
      `Left: R2 bucket ${files}. 2 files in it have a name that no address can carry ("." and ".."), so iterate cannot remove them.`,
    ],
  );
  const note = said.find((l) => /^Note: The R2 bucket /.test(l));
  assert.match(
    note,
    new RegExp(`^Note: The R2 bucket ${files} is left in your Cloudflare account`),
  );
  assert.match(note, /"\." and "\.\."/);
  // the rest of the list went as ever
  assert.ok(said.includes("Read again: nothing is left on example.com."));
  assert.deepEqual(w.lifecycle, {});
});

test("the lists of telemetry: one that Cloudflare refuses stops the erase of a stack with telemetry, and no other", async () => {
  const refuse = { "GET A/pipelines/v1/sinks?page=1&per_page=50": true };
  const plain = cloudflare((world) => ({ ...world, tokens: null, refuse }));
  const found = await inventoryOf(given(plain.cf));
  assert.deepEqual(refusalsOf(found), []);
  assert.deepEqual(
    found.unread.map((u) => u.what),
    ["the page rules"],
  );
  const { digest } = found;
  assert.deepEqual(await eraseAll({ ...given(plain.cf), agreed: digest, ...quick }), { ok: true });

  const { cf, changes } = cloudflare((world) => ({ ...withTelemetry(world), refuse }));
  const done = await eraseAll({ ...given(cf), ...quick });
  assert.equal(done.ok, false);
  assert.equal(done.erased, false);
  assert.match(done.why, /did not let iterate read the pipeline sinks/);
  assert.deepEqual(changes(), []);
});

test("a list that changed after the person saw it: nothing is erased", async () => {
  const { w, cf, changes } = cloudflare();
  const { digest } = await inventoryOf(given(cf));
  w.records.push({ id: "r-new", type: "A", name: `new.${ZONE}`, content: "192.0.2.1" });
  const done = await eraseAll({ ...given(cf), agreed: digest, ...quick });
  assert.equal(done.ok, false);
  assert.equal(done.erased, false);
  assert.match(done.why, /changed after you saw the list/);
  assert.deepEqual(changes(), []);
});

test("something the run cannot erase stops it before anything is erased", async () => {
  for (const change of [
    (w) => (w.spectrum.push({ id: "sp-1", dns: { name: `ssh.${ZONE}` } }), w),
    (w) => (
      w.records.push({
        id: "r-fixed",
        type: "CNAME",
        name: `x.${ZONE}`,
        content: "y",
        meta: { read_only: true },
      }),
      w
    ),
  ]) {
    const { cf, changes } = cloudflare(change);
    const found = await inventoryOf(given(cf));
    assert.equal(refusalsOf(found).length, 1);
    const done = await eraseAll({ ...given(cf), agreed: found.digest, ...quick });
    assert.equal(done.ok, false);
    assert.equal(done.erased, false);
    assert.match(done.why, /so it erased nothing/);
    assert.deepEqual(changes(), []);
  }
});

test("a domain that serves another Worker is never erased: its route or custom domain stops the erase", async () => {
  for (const [change, address] of [
    [
      (w) => (w.routes.push({ id: "rt-9", pattern: `shop.${ZONE}/*`, script: "shop" }), w),
      "shop.example.com/*",
    ],
    [
      (w) => (w.domains.push({ id: "d-9", hostname: `app2.${ZONE}`, service: "shop" }), w),
      "app2.example.com",
    ],
    // the stack of a longer name is another stack
    [
      (w) => (
        w.routes.push({ id: "rt-9", pattern: `x.${ZONE}/*`, script: `iterate-${NAME}-x-boundary` }),
        w
      ),
      "x.example.com/*",
    ],
  ]) {
    const { cf, changes } = cloudflare(change);
    const found = await inventoryOf(given(cf));
    const refusals = refusalsOf(found);
    assert.equal(refusals.length, 1);
    assert.ok(refusals[0].startsWith(`${address} is served by the Worker `), refusals[0]);
    assert.match(refusals[0], /never erases a domain that serves another Worker/);
    const done = await eraseAll({ ...given(cf), agreed: found.digest, ...quick });
    assert.equal(done.ok, false);
    assert.equal(done.erased, false);
    assert.deepEqual(changes(), []);
  }
  // the stack's own Workers under both names, the wizard's older Worker and a route with no
  // Worker stop nothing: the first world has all of them
  assert.deepEqual(refusalsOf(await inventoryOf(given(cloudflare().cf))), []);
});

test("a list the erase needs and cannot read stops it before anything is erased", async () => {
  const { cf, changes } = cloudflare((w) => ((w.refuse["GET Z/workers/routes"] = true), w));
  const found = await inventoryOf(given(cf));
  assert.match(refusalsOf(found)[0], /did not let iterate read the Workers routes/);
  const done = await eraseAll({ ...given(cf), agreed: found.digest, ...quick });
  assert.equal(done.ok, false);
  assert.deepEqual(changes(), []);
});

test("a refusal in the middle says that other things are erased already", async () => {
  const { cf } = cloudflare((w) => ((w.refuse["DELETE Z/dns_records/r-www"] = true), w));
  const { digest } = await inventoryOf(given(cf));
  const done = await eraseAll({ ...given(cf), agreed: digest, ...quick });
  assert.equal(done.ok, false);
  assert.equal(done.erased, true);
  assert.match(done.why, /did not let iterate remove this: CNAME www\.example\.com/);
  assert.match(done.why, /Other things on example\.com are erased already/);
});

test("the domains that are never erased, and the domain the page is served from", async () => {
  for (const zone of ["iterate.com", "iterate.app", "garple.com", "templestein.family"])
    assert.match(keptOf(zone), /never erases/);
  assert.match(keptOf("example.com", "cloud.example.com"), /served from example\.com/);
  assert.match(keptOf("example.com", "example.com"), /served from example\.com/);
  assert.equal(keptOf("example.com", "cloud.iterate.com"), null);
  assert.equal(keptOf("notgarple.com", "cloud.iterate.com"), null);
  assert.equal(keptOf("iterate2.app", "cloud.iterate.com"), null);
  const { cf, w } = cloudflare();
  const done = await eraseAll({ ...given(cf), zone: "garple.com", agreed: "x", ...quick });
  assert.equal(done.ok, false);
  assert.equal(done.erased, false);
  assert.deepEqual(w.calls, []);
});

test("the mind's own API token is found under its name, with the edition of its list or without", () => {
  const names = { cloudflareToken: "iterate-example-cloudflare" };
  for (const name of ["iterate-example-cloudflare", "iterate-example-cloudflare-3"])
    assert.ok(isMindToken(names, name), name);
  // another stack whose name starts with this one's, and a name that ends in no edition
  for (const name of [
    "iterate-example-x-cloudflare",
    "iterate-example-cloudflare-x",
    "iterate-example-cloudflare-",
    "iterate-example-cloudflare-3-more",
  ])
    assert.ok(!isMindToken(names, name), name);
});