iterate.com / cloud

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

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

// service.mjs — what the Cloud's app may ask of the Worker (worker/service.js): who may call, and
// that the two operations answer the Worker's own records. Run: node test/service.mjs
import assert from "node:assert/strict";
import { registerHooks } from "node:module";
import { test } from "node:test";
import { Installation } from "../worker/installation.js";
import { handle, handles } from "../worker/service.js";

const ORIGIN = "https://cloud.test";
const TOKEN = "the-apps-bearer";
const kv = (rows) => ({
  get: async (key) => rows[key] ?? null,
  put: async (key, value) => void (rows[key] = value),
  delete: async (key) => void delete rows[key],
});
const call = (env, path, { token = TOKEN, headers = {}, ...init } = {}) =>
  handle(
    new Request(ORIGIN + path, {
      ...init,
      headers: { ...(token && { authorization: `Bearer ${token}` }), ...headers },
    }),
    env,
  );

test("only the app's bearer is let in, and never a browser", async () => {
  const env = { SESSIONS: kv({}), SERVICE_TOKEN: TOKEN };
  assert.equal(handles(new URL(`${ORIGIN}/service/handover`)), true);
  assert.equal(handles(new URL(`${ORIGIN}/services`)), false);
  const path = "/service/installation?domain=example.com";
  // no token configured: the paths do not exist
  assert.equal((await call({ SESSIONS: kv({}) }, path)).status, 404);
  assert.equal((await call(env, path, { token: "" })).status, 401);
  assert.equal((await call(env, path, { token: "another" })).status, 401);
  // a browser's request, even with the right bearer
  assert.equal((await call(env, path, { headers: { origin: ORIGIN } })).status, 403);
  assert.equal((await call(env, path, { headers: { cookie: "__Host-sid=x" } })).status, 403);
  assert.equal((await call(env, path)).status, 200);
  assert.equal((await call(env, "/service/other")).status, 404);
  assert.equal((await call(env, "/service/handover")).status, 404); // a GET
});

test("the installation's state is the Worker's own records", async () => {
  const rows = {};
  const env = { SESSIONS: kv(rows), SERVICE_TOKEN: TOKEN };
  const state = async () => (await call(env, "/service/installation?domain=example.com")).json();
  assert.deepEqual(await state(), { domain: "example.com", enrolled: false, handedOver: false });
  rows["enrolled:example.com"] = JSON.stringify({ domain: "example.com", key: "k" });
  rows["handover:example.com"] = JSON.stringify({ handover: "h", installation: "i" });
  assert.deepEqual(await state(), { domain: "example.com", enrolled: true, handedOver: false });
  rows["handover:example.com"] = JSON.stringify({ handover: "h", installation: "i", accepted: 1 });
  assert.deepEqual(await state(), { domain: "example.com", enrolled: true, handedOver: true });
  assert.equal((await call(env, "/service/installation?domain=evil.com/x")).status, 400);
  // the answer carries nothing of the rows but the two facts
  assert.equal(JSON.stringify(await state()).includes('"key"'), false);
});

test("a handover names an installation, never a domain, and waits for its deploy", async () => {
  const env = { SESSIONS: kv({}), SERVICE_TOKEN: TOKEN, DEPLOYER: deployers() };
  const post = (body) =>
    call(env, "/service/handover", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body,
    });
  assert.equal((await post("not json")).status, 400);
  // the old shape, with a domain of the caller's: not an installation
  const old = await post(
    JSON.stringify({ domain: "example.com", installation: "/installations/1", summary: "Hello." }),
  );
  assert.deepEqual([old.status, (await old.json()).field], [400, "installation"]);
  const made = await (
    await call(env, "/service/installations", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        deployment: "dep-1",
        owner: { email: "ada@example.com", userId: "app-user-1" },
      }),
    })
  ).json();
  for (const name of [{ installation: made.installation }, { deployment: "dep-1" }]) {
    const early = await post(JSON.stringify({ ...name, summary: "Hello." }));
    assert.deepEqual(
      [early.status, await early.json()],
      [409, { error: "That installation has not deployed a mind." }],
    );
  }
  const nameless = await post(JSON.stringify({ summary: "Hello." }));
  assert.deepEqual([nameless.status, (await nameless.json()).field], [400, "deployment"]);
});

/** A DEPLOYER namespace of installations in memory, whose phases never run. */
function deployers() {
  const objects = new Map();
  return {
    getByName: (name) => {
      if (!objects.has(name)) {
        const data = new Map();
        objects.set(
          name,
          new Installation({
            storage: {
              get: async (key) => structuredClone(data.get(key)),
              put: async (key, value) => void data.set(key, structuredClone(value)),
              delete: async (key) => void data.delete(key),
              setAlarm: async () => {},
              deleteAlarm: async () => {},
            },
            env: {},
            runner: {
              launch: async () => ({}),
              poll: async () => ({ done: false, lines: [] }),
              stop: async () => {},
            },
          }),
        );
      }
      const installation = objects.get(name);
      return { install: async (op, args) => structuredClone(await installation[op](args)) };
    },
  };
}

test("every installation route takes the bearer alone, and checks what it is given", async () => {
  const env = { SESSIONS: kv({}), SERVICE_TOKEN: TOKEN, DEPLOYER: deployers() };
  const json = (method, path, body, options = {}) =>
    call(env, path, {
      method,
      ...options,
      headers: { "content-type": "application/json", ...options.headers },
      body: body === undefined ? undefined : typeof body === "string" ? body : JSON.stringify(body),
    });
  const ada = { email: "ada@example.com", userId: "app-user-1" };
  const created = await json("POST", "/service/installations", { deployment: "dep-1", owner: ada });
  const { installation: id } = await created.json();
  const routes = [
    ["POST", "/service/installations", { deployment: "dep-1", owner: ada }],
    ["GET", `/service/installations/${id}`],
    ["PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" }],
    ["POST", `/service/installations/${id}/links`, { kind: "consent" }],
    ["POST", `/service/installations/${id}/poke`],
    ["GET", `/service/installations/${id}/resources`],
    ["POST", "/service/handover", { installation: id, summary: "Hi." }],
  ];
  for (const [method, path, body] of routes) {
    assert.equal((await json(method, path, body, { token: "" })).status, 401, path);
    assert.equal((await json(method, path, body, { token: "wrong" })).status, 401, path);
    assert.equal(
      (await json(method, path, body, { headers: { origin: "https://cloud.test" } })).status,
      403,
      path,
    );
    assert.equal(
      (await json(method, path, body, { headers: { cookie: "inst-x=1" } })).status,
      403,
      path,
    );
    assert.equal((await call({ SESSIONS: kv({}) }, path, { method })).status, 404, path);
  }
  // bad bodies: 400, with the field at fault
  for (const [body, field] of [
    [{ deployment: "a b", owner: ada }, "deployment"],
    [{ deployment: "x".repeat(65), owner: ada }, "deployment"],
    [{ deployment: "dep-1", owner: { ...ada, email: "not an email" } }, "owner"],
    [{ deployment: "dep-1", owner: { email: ada.email } }, "owner"],
    [{ deployment: "dep-1" }, "owner"],
  ]) {
    const answer = await json("POST", "/service/installations", body);
    assert.deepEqual([answer.status, (await answer.json()).field], [400, field]);
  }
  for (const [body, field, status = 400] of [
    [{ name: "Ada" }, "name"],
    [{ name: "a" }, "name"],
    [{ name: "ada-" }, "name"],
    [{ ownerEmail: "nope" }, "ownerEmail"],
    [{ telemetry: "yes" }, "telemetry"],
    [{ domain: { zone: "not a domain" } }, "domain"],
    [{ domain: { zone: "iterate.example.com" } }, "domain"],
    [{ accountId: "0".repeat(32) }, "accountId"],
    [{ other: 1 }, undefined],
  ]) {
    const answer = await json("PATCH", `/service/installations/${id}/choices`, body);
    assert.deepEqual(
      [answer.status, (await answer.json()).field],
      [status, field],
      JSON.stringify(body),
    );
  }
  assert.equal((await json("PATCH", `/service/installations/${id}/choices`, "nope")).status, 400);
  const kind = await json("POST", `/service/installations/${id}/links`, { kind: "money" });
  assert.deepEqual([kind.status, (await kind.json()).field], [409, "kind"]);
  // an id that is not an installation's, or one nobody made
  assert.equal((await json("GET", "/service/installations/inst_nope")).status, 404);
  assert.equal((await json("GET", `/service/installations/inst_${"a".repeat(26)}`)).status, 404);
  assert.equal((await json("PUT", `/service/installations/${id}`)).status, 404);
  // the same deployment, the same installation; of another owner, refused
  const again = await json("POST", "/service/installations", { deployment: "dep-1", owner: ada });
  assert.deepEqual(await again.json(), { installation: id, deployment: "dep-1", created: false });
  const bob = await json("POST", "/service/installations", {
    deployment: "dep-1",
    owner: { email: "bob@example.com", userId: "app-user-2" },
  });
  assert.equal(bob.status, 409);
  // another mind's bearer names other installations: the same deployment is another one
  const theirs = await call(
    { ...env, SERVICE_MIND: "templestein.family" },
    "/service/installations",
    {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ deployment: "dep-1", owner: ada }),
    },
  );
  assert.notEqual((await theirs.json()).installation, id);
});

test("the owner's count fails closed: no count, no installation", async () => {
  const objects = deployers();
  const env = {
    SESSIONS: kv({}),
    SERVICE_TOKEN: TOKEN,
    DEPLOYER: {
      getByName: (name) =>
        name.startsWith("owner:")
          ? { install: async () => Promise.reject(new Error("the object is overloaded")) }
          : objects.getByName(name),
    },
  };
  const answer = await call(env, "/service/installations", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      deployment: "dep-1",
      owner: { email: "ada@example.com", userId: "app-user-1" },
    }),
  });
  assert.equal(answer.status, 503);
});

test("an owner who loses the race to make a deployment gets the place back", async () => {
  const objects = deployers();
  let racing = true;
  const env = {
    SESSIONS: kv({}),
    SERVICE_TOKEN: TOKEN,
    DEPLOYER: {
      getByName: (name) => {
        const stub = objects.getByName(name);
        // the race: Bob's look finds no installation, then Ada's create lands before Bob's
        return {
          install: async (op, args) =>
            racing && op === "expectedUser" && name.startsWith("inst:")
              ? null
              : stub.install(op, args),
        };
      },
    },
  };
  const create = (deployment, email) =>
    call(env, "/service/installations", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ deployment, owner: { email, userId: email } }),
    });
  assert.equal((await create("dep-1", "ada@example.com")).status, 200);
  assert.equal((await create("dep-1", "bob@example.com")).status, 409);
  racing = false;
  // Bob still has all ten places
  for (let i = 1; i <= 10; i++)
    assert.equal((await create(`bob-${i}`, "bob@example.com")).status, 200);
  assert.equal((await create("bob-11", "bob@example.com")).status, 409);
});

// ── the Service entrypoint (main.js), as the mind's `itx.services.cloud` calls it ───────────────

// main.js imports the Workers runtime, which Node does not have: a stand-in of what it uses
const RUNTIME =
  "export class WorkerEntrypoint { constructor(ctx, env) { this.ctx = ctx; this.env = env; } } export class DurableObject { constructor(ctx, env) { this.ctx = ctx; this.env = env; } } export const env = {}; export const waitUntil = () => {};";
registerHooks({
  resolve: (specifier, context, next) =>
    specifier === "cloudflare:workers"
      ? { url: `data:text/javascript,${encodeURIComponent(RUNTIME)}`, shortCircuit: true }
      : next(specifier, context),
});
const { Service } = await import("../worker/main.js");

/** What the iterate mind's Worker puts first (iterate/principal `ServiceCaller`). */
const callerOf = (call, mind = "iterate.com") => ({
  mind,
  path: "/agents/cloud",
  call,
  principal: { actor: "usr_1", email: "jonas@example.com" },
});
const codeOf = (promise) =>
  promise.then(
    () => "no error",
    (error) => ({ code: error.code, field: error.data?.field }),
  );

test("the Service's methods are the routes' operations, for the iterate mind alone", async () => {
  const env = {
    SESSIONS: kv({}),
    DEPLOYER: deployers(),
    SERVICE_TOKEN: TOKEN,
    CLOUD_ORIGIN: "https://cloud.test/",
  };
  const cloud = new Service({}, env);
  const ada = { email: "ada@example.com", userId: "app-user-1" };
  const made = await cloud.installationCreate(callerOf("installationCreate"), {
    deployment: "dep-1",
    owner: ada,
  });
  assert.equal(made.created, true);
  // the bearer route names the same installation
  const routed = await call(env, "/service/installations", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ deployment: "dep-1", owner: ada }),
  });
  assert.deepEqual(await routed.json(), { ...made, created: false });

  const named = { deployment: "dep-1" };
  let s = await cloud.installationStatus(callerOf("installationStatus"), named);
  assert.equal(s.installation, made.installation);
  // who asked: the context and its principal
  assert.deepEqual(
    s.asked.map(({ call, path, principal }) => [call, path, principal.email]),
    [
      ["installationCreate", "/agents/cloud", "jonas@example.com"],
      ["installationStatus", "/agents/cloud", "jonas@example.com"],
    ],
  );
  s = await cloud.installationChoose(callerOf("installationChoose"), {
    ...named,
    choices: { name: "ada-labs" },
  });
  assert.equal(s.choices.name, "ada-labs");
  const link = await cloud.installationLink(callerOf("installationLink"), {
    ...named,
    kind: "consent",
  });
  assert.match(link.url, new RegExp(`^https://cloud\\.test/i/${made.installation}/consent\\?n=`));
  assert.equal(
    (await cloud.installationPoke(callerOf("installationPoke"), named)).installation,
    made.installation,
  );
  assert.deepEqual(await cloud.installationResources(callerOf("installationResources"), named), {
    resources: [],
  });
  assert.deepEqual(await cloud.deploymentAt(callerOf("deploymentAt"), { domain: "example.com" }), {
    domain: "example.com",
    enrolled: false,
    handedOver: false,
  });

  // refusals cross as codes, with the field at fault
  for (const [asked, expected] of [
    [
      () => cloud.installationStatus(callerOf("installationStatus", "evil.com"), named),
      { code: "FORBIDDEN" },
    ],
    [() => cloud.installationStatus(undefined, named), { code: "INVALID_INPUT" }],
    [() => cloud.installationStatus({ mind: "iterate.com" }, named), { code: "INVALID_INPUT" }],
    [
      () => cloud.installationStatus(callerOf("installationStatus"), { deployment: "dep-2" }),
      { code: "NOT_FOUND" },
    ],
    [
      () => cloud.installationStatus(callerOf("installationStatus"), {}),
      { code: "INVALID_INPUT", field: "deployment" },
    ],
    [
      () =>
        cloud.installationCreate(callerOf("installationCreate"), { deployment: "a b", owner: ada }),
      { code: "INVALID_INPUT", field: "deployment" },
    ],
    [
      () =>
        cloud.installationCreate(callerOf("installationCreate"), {
          deployment: "dep-1",
          owner: { ...ada, email: "bob@example.com" },
        }),
      { code: "CONFLICT", field: "owner" },
    ],
    [
      () =>
        cloud.installationChoose(callerOf("installationChoose"), {
          ...named,
          choices: { name: "A" },
        }),
      { code: "INVALID_INPUT", field: "name" },
    ],
    [
      () => cloud.installationLink(callerOf("installationLink"), { ...named, kind: "money" }),
      { code: "CONFLICT", field: "kind" },
    ],
    [
      () => cloud.deploymentAt(callerOf("deploymentAt"), { domain: "nope" }),
      { code: "INVALID_INPUT", field: "domain" },
    ],
    [
      () => cloud.handover(callerOf("handover"), { ...named, summary: "Hi." }),
      { code: "CONFLICT", field: undefined },
    ],
  ])
    assert.deepEqual(await codeOf(asked()), { field: undefined, ...expected });

  // a Cloud with no origin of its own makes no links
  const lost = new Service({}, { ...env, CLOUD_ORIGIN: undefined });
  assert.deepEqual(await codeOf(lost.installationStatus(callerOf("installationStatus"), named)), {
    code: "UNAVAILABLE",
    field: undefined,
  });
});

// ── a deployment made elsewhere, enrolment, forgetting ─────────────────────────────────────────

/** A Cloud with a key, and the deployments it may call: `serving` serve their key, `statements`
 *  is what was sent to them. */
async function cloudWithKey() {
  const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
    "sign",
    "verify",
  ]);
  const jwk = await crypto.subtle.exportKey("jwk", pair.privateKey);
  const rows = {};
  const env = {
    SESSIONS: kv(rows),
    SERVICE_TOKEN: TOKEN,
    DEPLOYER: deployers(),
    CLOUD_KEY: JSON.stringify(jwk),
    CLOUD_ORIGIN: ORIGIN,
  };
  const serving = new Set();
  // how a host that is not serving answers: 404 (gone), or `answers[host]`: a status or "timeout"
  const answers = {};
  const statements = [];
  globalThis.fetch = async (input, init = {}) => {
    const url = new URL(input);
    if (url.pathname === "/keys/stack.json") {
      if (serving.has(url.hostname)) return Response.json({});
      const how = answers[url.hostname];
      if (how === "timeout") throw Object.assign(new Error("timed out"), { name: "TimeoutError" });
      if (how === "no host") throw new TypeError("fetch failed");
      return new Response("gone", { status: how ?? 404 });
    }
    if (url.pathname === "/statements") {
      statements.push({ host: url.hostname, ...JSON.parse(init.body) });
      return new Response("ok");
    }
    return new Response("not found", { status: 404 });
  };
  const api = async (method, path, body) => {
    const answer = await call(env, path, {
      method,
      headers: { "content-type": "application/json" },
      body: body === undefined ? undefined : JSON.stringify(body),
    });
    return { status: answer.status, body: await answer.json() };
  };
  const enrolled = (domain) =>
    (rows[`enrolled:${domain}`] = JSON.stringify({ domain, key: `key-${domain}` }));
  const made = async (deployment, email = "ada@example.com") =>
    (await api("POST", "/service/installations", { deployment, owner: { email, userId: email } }))
      .body.installation;
  return { env, rows, jwk, serving, answers, statements, api, enrolled, made };
}

test("a deployment made elsewhere is tied to its installation only when enrolled, to one installation, and then the handover goes", async () => {
  const c = await cloudWithKey();
  const one = await c.made("dep-1");
  const two = await c.made("dep-2");
  const three = await c.made("dep-3");
  const at = (id, domain) => c.api("POST", `/service/installations/${id}/deployed`, { domain });
  // not enrolled: the deployment has not shown that it trusts the Cloud's key
  assert.deepEqual(
    [(await at(one, "ada.com")).status, (await at(one, "ada.com")).body.field],
    [409, "domain"],
  );
  assert.equal((await at(one, "not a domain")).status, 400);
  c.enrolled("ada.com");
  c.enrolled("bob.com");
  const tied = await at(one, "ada.com");
  assert.equal(tied.status, 200);
  assert.equal(tied.body.deployedAt.zone, "ada.com");
  assert.equal((await at(one, "ada.com")).status, 200);
  // one zone for an installation, one installation for a zone
  assert.equal((await at(one, "bob.com")).status, 409);
  assert.equal((await at(three, "ada.com")).status, 409);
  // the refused claim of bob.com was given back
  assert.equal((await at(two, "bob.com")).status, 200);

  // the handover goes to the tied deployment, once
  const handed = await c.api("POST", "/service/handover", { deployment: "dep-1", summary: "Hi." });
  assert.deepEqual([handed.status, handed.body.sent], [200, true]);
  assert.deepEqual(
    c.statements.map((s) => s.host),
    ["iterate.ada.com"],
  );
  const again = await c.api("POST", "/service/handover", { deployment: "dep-1", summary: "Hi." });
  assert.deepEqual([again.status, again.body.sent, c.statements.length], [200, false, 1]);

  // forgotten: the installation goes, the zone and the owner's place are free again
  assert.deepEqual((await c.api("DELETE", `/service/installations/${one}`)).body, {
    ok: true,
    installation: one,
  });
  assert.equal((await c.api("GET", `/service/installations/${one}`)).status, 404);
  // its handover went with it
  assert.equal(c.rows["handover:ada.com"], undefined);
  assert.equal((await c.api("DELETE", `/service/installations/${one}`)).status, 404);
  assert.equal((await at(three, "ada.com")).status, 200);
  // the deployment itself was not touched
  assert.ok(c.rows["enrolled:ada.com"]);
});

test("forgetting an installation frees the owner's place", async () => {
  const c = await cloudWithKey();
  const ids = [];
  for (let i = 1; i <= 10; i++) ids.push(await c.made(`d${i}`, "bob@example.com"));
  const over = await c.api("POST", "/service/installations", {
    deployment: "d11",
    owner: { email: "bob@example.com", userId: "bob" },
  });
  assert.equal(over.status, 409);
  const listed = await c.api("GET", "/service/installations?owner=Bob@Example.com");
  assert.deepEqual(listed.body, { email: "bob@example.com", installations: ids });
  assert.equal((await c.api("GET", "/service/installations?owner=nope")).status, 400);
  assert.equal((await c.api("DELETE", `/service/installations/${ids[0]}`)).status, 200);
  assert.deepEqual(
    (await c.api("GET", "/service/installations?owner=bob@example.com")).body.installations,
    ids.slice(1),
  );
  assert.ok(await c.made("d11", "bob@example.com"));
});

test("the app enrols a deployment and reads the Cloud's key; an enrolment is forgotten only when the deployment is gone", async () => {
  const c = await cloudWithKey();
  // a deployment that serves no key is not enrolled; the refusal carries no secret
  const refused = await c.api("POST", "/service/enrol", { domain: "ada.com" });
  assert.deepEqual([refused.status, refused.body.field], [409, "domain"]);
  assert.match(refused.body.error, /serves no key/);
  assert.equal((await c.api("POST", "/service/enrol", { domain: "x" })).status, 400);

  const key = await c.api("GET", "/service/cloud-key");
  assert.equal(key.status, 200);
  assert.deepEqual(
    key.body.keys.map(({ actor, label, paths }) => ({ actor, label, paths })),
    [{ actor: "iterate-cloud", label: "iterate Cloud", paths: ["/integrations/"] }],
  );
  assert.equal(JSON.stringify(key.body).includes(c.jwk.d), false);

  c.enrolled("ada.com");
  c.serving.add("iterate.ada.com");
  const live = await c.api("POST", "/service/forget-enrolment", { domain: "ada.com" });
  assert.deepEqual([live.status, live.body.field], [409, "domain"]);
  assert.ok(c.rows["enrolled:ada.com"]);
  c.serving.delete("iterate.ada.com");
  // no proof that it is gone: a 5xx, or no answer in time
  for (const how of [503, "timeout"]) {
    c.answers["iterate.ada.com"] = how;
    const unsure = await c.api("POST", "/service/forget-enrolment", { domain: "ada.com" });
    assert.equal(unsure.status, 409, String(how));
  }
  assert.ok(c.rows["enrolled:ada.com"]);
  c.answers["iterate.ada.com"] = "no host";
  c.rows["handover:ada.com"] = JSON.stringify({ handover: "h", installation: "i", accepted: 1 });
  assert.deepEqual((await c.api("POST", "/service/forget-enrolment", { domain: "ada.com" })).body, {
    ok: true,
    domain: "ada.com",
  });
  assert.equal(c.rows["enrolled:ada.com"], undefined);
  assert.equal(c.rows["handover:ada.com"], undefined);
  assert.equal(
    (await c.api("POST", "/service/forget-enrolment", { domain: "ada.com" })).status,
    404,
  );
});

test("the Service's new methods are the same operations", async () => {
  const c = await cloudWithKey();
  const cloud = new Service({}, c.env);
  await c.made("dep-1");
  c.enrolled("ada.com");
  const s = await cloud.installationDeployedAt(callerOf("installationDeployedAt"), {
    deployment: "dep-1",
    domain: "ada.com",
  });
  assert.equal(s.deployedAt.zone, "ada.com");
  assert.equal(s.asked.at(-1).call, "installationDeployedAt");
  assert.equal((await cloud.cloudKey(callerOf("cloudKey"))).keys[0].actor, "iterate-cloud");
  assert.deepEqual(await codeOf(cloud.enrol(callerOf("enrol"), { domain: "bob.com" })), {
    code: "CONFLICT",
    field: "domain",
  });
  assert.deepEqual(await codeOf(cloud.cloudKey(callerOf("cloudKey", "evil.com"))), {
    code: "FORBIDDEN",
    field: undefined,
  });
  assert.deepEqual(
    await cloud.forgetEnrolment(callerOf("forgetEnrolment"), { domain: "ada.com" }),
    {
      ok: true,
      domain: "ada.com",
    },
  );
  assert.equal(
    (await cloud.installationForget(callerOf("installationForget"), { deployment: "dep-1" })).ok,
    true,
  );
  assert.deepEqual(
    await codeOf(cloud.installationStatus(callerOf("installationStatus"), { deployment: "dep-1" })),
    { code: "NOT_FOUND", field: undefined },
  );
});

test("a forget that stopped half way refuses the same deployment until it is asked again", async () => {
  const c = await cloudWithKey();
  const id = await c.made("dep-1");
  // the object forgot, and then the Worker stopped before it freed the places
  assert.equal((await c.env.DEPLOYER.getByName(`inst:${id}`).install("forget")).ok, true);
  const early = await c.api("POST", "/service/installations", {
    deployment: "dep-1",
    owner: { email: "ada@example.com", userId: "ada" },
  });
  assert.equal(early.status, 409);
  assert.equal((await c.api("DELETE", `/service/installations/${id}`)).status, 200);
  assert.equal(await c.made("dep-1"), id);
  const listed = await c.api("GET", "/service/installations?owner=ada@example.com");
  assert.deepEqual(listed.body.installations, [id]);
});