iterate.com / kernel

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

kernel / core / secrets-worker / src / secret / durable-object.test.tsmain at 949894f

import { timingSafeEqual } from "node:crypto";
import {
  SECRET_HELD_HEADER,
  SECRET_USE_HEADER,
  VAULT_ANSWER_HEADER,
} from "iterate/secret-placeholder";
import { decodeFacts, FACTS_HEADER } from "iterate/facts";
import { env as vaultEnv } from "cloudflare:workers";
import { expect, onTestFinished, test, vi } from "vitest";
import { z } from "zod";
import type { Envelope } from "iterate/signed";
import { hmacSha256Hex } from "../secrets.ts";
import { encryptSecretMaterial } from "../secret-at-rest.ts";
import {
  APPROVED,
  HOLD_MS,
  MAX_WAITING,
  REJECTED,
  RULE_CONFIGURED,
  SecretDurableObject,
} from "./durable-object.ts";
import { PinnedOutbound } from "./exchange-jail.ts";

// workerd's own comparison, which Node's Web Crypto has not got
Object.assign(crypto.subtle, { timingSafeEqual });

const PATH = "/secrets/gmail";
const MEMBER = "key-member";
const UNCHECKED = "key-member-unchecked";
const GMAIL = ["https://gmail.googleapis.com"];

/** A sealed cell in this code's shape that another vault's key sealed: its value opens nowhere
 *  here. */
const cellOfAnotherVault = {
  cell: {
    context: PATH,
    urls: GMAIL,
    refresh: null,
    version: 1,
    nonce: "nonce-of-the-other-vault",
    material: { algorithm: "AES-256-GCM+SECRET-V1", iv: "AAAA", ciphertext: "AAAA" },
    placement: "header",
    operations: [],
    lendTo: [],
  },
};

test("a matching request is held at once with its fact, and the wait call sends it once with the real value", async () => {
  const { secret, sent, approve } = await vault();
  const first = await secret.fetch(gmailPost("hello"));
  const { digest } = (await first.clone().json()) as { digest: string };
  expect({
    status: first.status,
    kind: first.headers.get(VAULT_ANSWER_HEADER),
    facts: decodeFacts(first.headers.get(FACTS_HEADER) || ""),
    sent,
  }).toMatchObject({
    status: 202,
    kind: "held",
    facts: [
      {
        path: PATH,
        events: [
          {
            type: "events.iterate.com/secret/approval-requested",
            payload: { digest, method: "POST" },
          },
          { payload: { status: 202 } },
        ],
      },
    ],
    sent: [],
  });
  const waited = secret.fetch(waitCall(digest));
  await approve(digest);
  expect({ status: (await waited).status, sent }).toEqual({
    status: 200,
    sent: [{ authorization: "Bearer real-token-aaaa", body: '{"raw":"hello"}', extra: null }],
  });
  const again = await secret.fetch(gmailPost("hello"));
  expect({
    status: again.status,
    kind: again.headers.get(VAULT_ANSWER_HEADER),
    sends: sent.length,
  }).toEqual({
    status: 409,
    kind: "sent-before",
    sends: 1,
  });
});

test("a wait call sends the stored text, not the body or headers it carries itself", async () => {
  const { secret, sent, approve } = await vault();
  const digest = await held(secret, "stored");
  const waited = secret.fetch(
    waitCall(digest, { body: '{"raw":"other"}', headers: { "x-extra": "1" } }),
  );
  await approve(digest);
  await waited;
  expect(sent).toEqual([
    { authorization: "Bearer real-token-aaaa", body: '{"raw":"stored"}', extra: null },
  ]);
});

test("a wait call for a digest that does not wait in this secret is refused", async () => {
  const other = await vault();
  const digest = await held(other.secret, "elsewhere");
  const { secret, sent } = await vault();
  const answer = await secret.fetch(waitCall(digest));
  expect({
    status: answer.status,
    kind: answer.headers.get(VAULT_ANSWER_HEADER),
    sends: sent.length,
  }).toEqual({
    status: 404,
    kind: "refused",
    sends: 0,
  });
});

test("two wait calls for one request send it once", async () => {
  const { secret, sent, approve } = await vault();
  const digest = await held(secret, "twice");
  const both = [secret.fetch(waitCall(digest)), secret.fetch(waitCall(digest))];
  await approve(digest);
  const statuses = (await Promise.all(both)).map((answer) => answer.status).sort();
  expect({ statuses, sends: sent.length }).toEqual({ statuses: [200, 409], sends: 1 });
});

test("an approved request with no wait call is never sent, and the identical retry sends it at once", async () => {
  const { secret, sent, approve } = await vault();
  const digest = await held(secret, "later");
  await approve(digest);
  // nothing asks for it: a caller that never makes the wait call sends nothing
  expect(sent).toEqual([]);
  expect({ status: (await secret.fetch(gmailPost("later"))).status, sends: sent.length }).toEqual({
    status: 200,
    sends: 1,
  });
});

test("a rejection answers the wait call 403 with the reason, and nothing is sent", async () => {
  const { secret, sent, decide } = await vault();
  const digest = await held(secret, "no");
  const waited = secret.fetch(waitCall(digest));
  await decide(MEMBER, { type: REJECTED, about: [digest], payload: { reason: "not this one" } });
  const answer = await waited;
  expect({
    status: answer.status,
    kind: answer.headers.get(VAULT_ANSWER_HEADER),
    text: await answer.text(),
    sends: sent.length,
  }).toMatchObject({
    status: 403,
    kind: "rejected",
    text: expect.stringContaining("not this one"),
    sends: 0,
  });
});

test.for([
  {
    name: "a service's key, such as the Cloud's, approves nothing",
    key: "key-cloud",
    about: true,
    path: PATH,
    refused: "only a member's key",
  },
  {
    name: "a statement for another secret approves nothing",
    key: MEMBER,
    about: true,
    path: "/secrets/other",
    refused: "is about /secrets/other",
  },
  {
    name: "a statement with no digests approves nothing",
    key: MEMBER,
    about: false,
    path: PATH,
    refused: "names no request",
  },
])("$name, and the wait call runs out", async ({ key, about, path, refused }) => {
  vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  try {
    const { secret, sent, decide } = await vault();
    const digest = await held(secret, "wait");
    const waited = secret.fetch(waitCall(digest));
    const answer = await decide(key, { type: APPROVED, about: about ? [digest] : [], path });
    // the wait call holds once its timer is set
    await vi.waitFor(() => expect(vi.getTimerCount()).toEqual(1));
    await vi.advanceTimersByTimeAsync(HOLD_MS);
    const expired = await waited;
    expect({
      refusal: answer.result.error,
      status: expired.status,
      kind: expired.headers.get(VAULT_ANSWER_HEADER),
      sends: sent.length,
    }).toMatchObject({
      refusal: expect.stringContaining(refused),
      status: 403,
      kind: "waiting",
      sends: 0,
    });
  } finally {
    vi.useRealTimers();
  }
});

test("a rule set while a request is being sent holds it: the rule is read again right before it leaves", async () => {
  const { secret, sent, state } = await vault();
  const get = useRequest("https://gmail.googleapis.com/gmail/v1/users/me/messages", {
    method: "GET",
  });
  // the rule names POST when the request arrives, and GET too by the time it would leave
  const read = state.storage.kv.get;
  let reads = 0;
  state.storage.kv.get = (key: string) =>
    key === "approval-rule" && ++reads > 1
      ? { methods: ["GET", "POST"], hosts: ["gmail.googleapis.com"] }
      : read(key);
  const answer = await secret.fetch(get);
  expect({
    status: answer.status,
    kind: answer.headers.get(VAULT_ANSWER_HEADER),
    sent,
  }).toEqual({ status: 409, kind: "refused", sent: [] });
});

test("a flood of requests is refused past the limit, and nothing is stored for it", async () => {
  const { secret, sent } = await vault();
  for (let n = 0; n < MAX_WAITING; n += 1) await held(secret, `message ${n}`);
  const over = await secret.fetch(gmailPost("one too many"));
  expect({
    status: over.status,
    kind: over.headers.get(VAULT_ANSWER_HEADER),
    sent,
  }).toMatchObject({ status: 429, kind: "refused", sent: [] });
});

test("a request the rule does not match is sent at once, and an upstream's copy of the vault's header goes", async () => {
  const { secret, upstream } = await vault();
  upstream.mockResolvedValue(new Response("ok", { headers: { [VAULT_ANSWER_HEADER]: "waiting" } }));
  const answer = await secret.fetch(
    useRequest("https://gmail.googleapis.com/gmail/v1/users/me/messages", { method: "GET" }),
  );
  expect({
    status: answer.status,
    header: answer.headers.get(VAULT_ANSWER_HEADER),
    sends: upstream.mock.calls.length,
  }).toEqual({
    status: 200,
    header: null,
    sends: 1,
  });
});

// ── THE VAULT'S LAST HOP WITH AN EGRESS GATEWAY (iterate/lib `fetchLeavingTheStack`) ──

test("a request with a secret is pinned, then substituted, then handed to the gateway once: the gateway gets the value, and the caller's answer has it redacted", async () => {
  const { secret, upstream } = await vault();
  const carried = gatewayOf(
    (request) =>
      new Response("ok", { headers: { "x-echo": request.headers.get("authorization") ?? "" } }),
  );
  const answer = await secret.fetch(useRequest(MESSAGES, { method: "GET" }));
  expect({ status: answer.status, echo: answer.headers.get("x-echo") }).toEqual({
    status: 200,
    echo: "Bearer [redacted]",
  });
  expect(carried).toEqual([
    { url: MESSAGES, authorization: "Bearer real-token-aaaa", redirect: "manual" },
  ]);
  expect(upstream).not.toHaveBeenCalled();
});

test("a request that the pin refuses, and one that waits for an approval, never reach the gateway", async () => {
  const { secret, upstream } = await vault();
  const carried = gatewayOf(() => new Response("carried"));
  const outside = await secret.fetch(useRequest("https://example.net/steal", { method: "GET" }));
  expect(outside).toMatchObject({ status: 403 });
  const held = await secret.fetch(gmailPost("hello"));
  expect([held.status, held.headers.get(VAULT_ANSWER_HEADER)]).toEqual([202, "held"]);
  expect(carried).toEqual([]);
  expect(upstream).not.toHaveBeenCalled();
});

test("a gateway's 502 is the request's failure: nothing is sent by the platform's fetch", async () => {
  const { secret, upstream } = await vault();
  const carried = gatewayOf(
    () =>
      new Response("no way out\n", {
        status: 502,
        headers: { "iterate-egress-gateway": "failed" },
      }),
  );
  const answer = await secret.fetch(useRequest(MESSAGES, { method: "GET" }));
  expect([answer.status, answer.headers.get("iterate-egress-gateway")]).toEqual([502, "failed"]);
  // and a gateway that throws is a failure too, in the vault's own words, with a log line that
  // names the origin and no URL
  const thrown = gatewayOf(() => Promise.reject(new Error("the gateway broke")));
  const logged = vi.spyOn(console, "error").mockImplementation(() => {});
  const refused = await secret.fetch(useRequest(MESSAGES, { method: "GET" }));
  expect(logged).toHaveBeenCalledWith({
    event: "secret.send-failed",
    origin: "https://gmail.googleapis.com",
    code: undefined,
  });
  expect([refused.status, await refused.text()]).toEqual([
    403,
    "itx.fetch: the pinned host https://gmail.googleapis.com could not be reached\n",
  ]);
  expect([carried.length, thrown.length]).toEqual([1, 1]);
  expect(upstream).not.toHaveBeenCalled();
});

test("no head from the gateway in 50 seconds is a 504", async () => {
  vi.useFakeTimers();
  const { secret, upstream } = await vault();
  // the gateway takes the request and never answers
  const handed = Promise.withResolvers<void>();
  gatewayOf(() => {
    handed.resolve();
    return new Promise(() => {});
  });
  const answered = secret.fetch(useRequest(MESSAGES, { method: "GET" }));
  await handed.promise;
  await vi.advanceTimersByTimeAsync(49_999);
  await vi.advanceTimersByTimeAsync(1);
  const answer = await answered;
  expect(answer).toMatchObject({ status: 504 });
  expect(await answer.text()).toContain("sent no answer within 50 s");
  expect(upstream).not.toHaveBeenCalled();
  vi.useRealTimers();
});

test("a secret's exchange code sends through the gateway, and an origin outside the pin is refused before it", async () => {
  const platform = vi.fn(async () => new Response("by the platform's fetch"));
  vi.stubGlobal("fetch", platform);
  const carried = gatewayOf(() => new Response("through the gateway"));
  // The Workers shim's entrypoint has no constructor: the test gives it its props, the pin.
  const jail = Object.assign(new PinnedOutbound(undefined as never, undefined as never), {
    ctx: { props: { urls: ["https://oauth.example.net"] } },
    env: vaultEnv,
  });
  const exchanged = await jail.fetch(
    new Request("https://oauth.example.net/token", { method: "POST", body: "code" }),
  );
  expect(await exchanged.text()).toBe("through the gateway");
  const outside = await jail.fetch(new Request("https://example.org/token", { method: "POST" }));
  expect(outside).toMatchObject({ status: 403 });
  expect(carried).toMatchObject([{ url: "https://oauth.example.net/token", redirect: "manual" }]);
  expect(platform).not.toHaveBeenCalled();
});

test("a rule with strings of the body lets a read go with its body whole, and holds a send", async () => {
  const { secret, sent, decide } = await vault();
  // holds less than the rule before it, so a member signs it
  await decide(MEMBER, {
    type: "events.iterate.com/secret/approval-rule-configured",
    payload: {
      rule: { methods: ["POST"], hosts: ["gmail.googleapis.com"], jsonStrings: ["messages/send"] },
    },
  });
  const post = (body: string) =>
    secret.fetch(
      useRequest("https://gmail.googleapis.com/batch", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body,
      }),
    );
  const read = JSON.stringify({ calls: ["messages/list"] });
  const answers = [
    await post(read),
    await post(JSON.stringify({ calls: ["messages/send"] })),
    await post("not JSON"),
  ];
  expect({
    statuses: answers.map((answer) => answer.status),
    kinds: answers.map((answer) => answer.headers.get(VAULT_ANSWER_HEADER)),
    sent,
  }).toEqual({
    statuses: [200, 202, 202],
    kinds: [null, "held", "held"],
    sent: [{ authorization: "Bearer real-token-aaaa", body: read, extra: null }],
  });
});

test("a member's passkey that did not check its user approves no request and changes no rule", async () => {
  const { secret, sent, decide } = await vault();
  const digest = await held(secret, "hello");
  const answers = [
    await decide(UNCHECKED, { type: APPROVED, about: [digest] }),
    await decide(UNCHECKED, {
      type: "events.iterate.com/secret/approval-rule-configured",
      payload: { rule: null },
    }),
  ];
  expect(answers.map((answer) => answer.result.error)).toEqual([
    expect.stringContaining("did not check that it is you"),
    expect.stringContaining("did not check that it is you"),
  ]);
  expect({ sent, approvals: await secret.approvals(PATH) }).toMatchObject({
    sent: [],
    approvals: { rule: { methods: ["POST"] }, held: [{ digest, state: "waiting" }] },
  });
});

test("a collection form's description is at most 4,000 characters: the page's Markdown is slow on a long hostile line", async () => {
  const { secret } = await vault();
  const ask = (description: string) =>
    secret.secret(PATH, "collectFromUser", {
      egress: { urls: ["https://gmail.googleapis.com"] },
      description,
    });
  await expect(ask("[".repeat(4001))).rejects.toThrow(/4000/);
  await expect(ask("a".repeat(4000))).resolves.toMatchObject({ url: expect.any(String) });
});

test("a delete that comes in while a new value is being sealed is the later word: the value is not stored", async () => {
  const { secret } = await vault();
  // not awaited: it has reserved its version and seals
  const set = secret.secret(PATH, "set", {
    material: "newer-token-bbbb",
    urls: ["https://gmail.googleapis.com"],
  });
  const stored = expect(set).rejects.toThrow("deleted while this value was being stored");
  await secret.secret(PATH, "delete", {});
  await stored;
  expect(await secret.secret(PATH, "describe", {})).toEqual({ path: PATH, set: false });
  // a value set after the delete is kept
  await secret.secret(PATH, "set", { material: "newest", urls: ["https://gmail.googleapis.com"] });
  expect(await secret.secret(PATH, "describe", {})).toMatchObject({ set: true });
});

test("a secret's object keeps its own row in the vault's list of set secrets: there when it is set, gone when it is deleted, and right when the two cross", async () => {
  const { secret, listedAsSet } = await vault();
  const value = { material: "newer-token-bbbb", urls: ["https://gmail.googleapis.com"] };
  expect(listedAsSet()).toEqual([PATH]);
  await secret.secret(PATH, "delete", {});
  expect(listedAsSet()).toEqual([]);
  // a set that a delete overtakes stores nothing, and leaves no row
  await secret.secret(PATH, "set", value);
  const lost = expect(secret.secret(PATH, "set", value)).rejects.toThrow("deleted while");
  await secret.secret(PATH, "delete", {});
  await lost;
  expect(await secret.secret(PATH, "describe", {})).toEqual({ path: PATH, set: false });
  expect(listedAsSet()).toEqual([]);
  await secret.secret(PATH, "set", value);
  expect(listedAsSet()).toEqual([PATH]);
  // the vault's list asks for this when a row and its object disagree: the object writes what it is
  await secret.keepListed(PATH);
  expect(listedAsSet()).toEqual([PATH]);
});

test("a set whose value a delete took while the vault's list was written is refused, and no fact says that the secret is set", async () => {
  const { secret, listedAsSet, holdListCall } = await vault();
  const value = { material: "newer-token-bbbb", urls: ["https://gmail.googleapis.com"] };
  // a write calls the list once before it stores and once after: the second call is held open
  const afterTheStore = holdListCall(2);
  const set = secret.secret(PATH, "set", value).then(
    () => "set",
    (error: unknown) => (error instanceof Error ? error.message : String(error)),
  );
  const letGo = await afterTheStore;
  // the value is stored now, and the delete takes it
  const deleted = await secret.secret(PATH, "delete", {});
  letGo();

  expect(await set).toContain("deleted while this value was being stored");
  expect(deleted).toMatchObject({
    facts: [{ path: PATH, events: [{ type: "events.iterate.com/secret/deleted" }] }],
  });
  expect(await secret.secret(PATH, "describe", {})).toEqual({ path: PATH, set: false });
  expect(listedAsSet()).toEqual([]);
});

test("a delete that a set overtook while the vault's list was written gives no fact: the set's own fact is the last word", async () => {
  const { secret, listedAsSet, holdListCall } = await vault();
  const value = { material: "newer-token-bbbb", urls: ["https://gmail.googleapis.com"] };
  // a delete clears the object and then calls the list: that call is held open
  const afterTheClear = holdListCall(1);
  const deleted = secret.secret(PATH, "delete", {});
  const letGo = await afterTheClear;
  // nothing is held now, and the set stores a value
  const set = await secret.secret(PATH, "set", value);
  letGo();

  expect(await deleted).toMatchObject({ result: { path: PATH }, facts: [] });
  expect(set).toMatchObject({
    facts: [{ path: PATH, events: [{ type: "events.iterate.com/secret/set" }] }],
  });
  expect(await secret.secret(PATH, "describe", {})).toMatchObject({ set: true });
  expect(listedAsSet()).toEqual([PATH]);
});

test("an import with no proof keeps nothing of the cell: the cell with its proof still gets as far as its value after it", async () => {
  const { secret } = await vault();
  // a cell of another vault: its value does not open here, which the proof does not depend on
  const cell = JSON.stringify(cellOfAnotherVault);
  const proof = await hmacSha256Hex("at-rest-key-for-tests-only", JSON.stringify([PATH, cell]));
  const importing = (given: string) => secret.secret(PATH, "importSealed", { cell, proof: given });

  // whoever does not hold the at-rest key names the cell and proves nothing
  await expect(importing("0".repeat(64))).rejects.toThrow("no proof under the at-rest key");
  // The cell's own import is not shut out by that: it gets as far as the value.
  await expect(importing(proof)).rejects.toThrow("does not open under this stack's at-rest key");
  // a cell that does not open was not imported: asked again, it gets as far as the value again
  await expect(importing(proof)).rejects.toThrow("does not open under this stack's at-rest key");
});

test("the sealed cell leaves the vault only for a caller that proves the at-rest key, as ciphertext, and one fact says that it left", async () => {
  const { secret } = await vault();

  // whoever does not hold the at-rest key gets no ciphertext to keep for a day when the key leaks
  await expect(
    secret.secret(PATH, "exportSealed", { proof: "0".repeat(64), until: Date.now() + 60_000 }),
  ).rejects.toThrow("no proof under the at-rest key");
  const exported = await handedOut(secret);

  expect(exported).toEqual({
    result: { sealed: expect.not.stringContaining("real-token-aaaa") },
    facts: [
      {
        path: PATH,
        events: [{ type: "events.iterate.com/secret/exported", payload: { path: PATH } }],
      },
    ],
  });
  expect(JSON.parse(exported.result.sealed)).toMatchObject({
    cell: { context: PATH, urls: ["https://gmail.googleapis.com"], version: 1 },
  });
});

test.for([
  ["that is past", -1_000],
  ["more than five minutes ahead", 6 * 60_000],
] as const)(
  "an export's proof names a time %s: it hands nothing out, though the key made it",
  async ([, from]) => {
    const { secret } = await vault();

    // a proof that was read in a log, on a later day, pulls no ciphertext
    await expect(handedOut(secret, Date.now() + from)).rejects.toThrow("the proof's time");
  },
);

test("an export's proof whose time is text is refused, though the key made it and the text spells a good time", async () => {
  const { secret } = await vault();
  const until = String(Date.now() + 60_000);
  const proof = await hmacSha256Hex(
    "at-rest-key-for-tests-only",
    JSON.stringify([PATH, "exportSealed", until]),
  );

  await expect(secret.secret(PATH, "exportSealed", { proof, until })).rejects.toThrow(
    "the proof's time",
  );
});

test("a cell that the vault handed out is taken back after a delete, once, and the secret works as it did", async () => {
  const { secret, sent } = await vault();
  const { sealed } = (await handedOut(secret)).result;
  await secret.secret(PATH, "delete", undefined);
  const proof = await hmacSha256Hex("at-rest-key-for-tests-only", JSON.stringify([PATH, sealed]));
  const importing = () => secret.secret(PATH, "importSealed", { cell: sealed, proof });

  const imported = await importing();
  // a read: the harness's rule holds a POST, which is not what this test is about
  await secret.fetch(useRequest("https://gmail.googleapis.com/gmail/v1/users/me/profile", {}));

  expect(imported).toMatchObject({
    result: { path: PATH },
    facts: [
      {
        path: PATH,
        events: [
          {
            type: "events.iterate.com/secret/set",
            // the use it had, not an import's wider one
            payload: {
              imported: true,
              urls: ["https://gmail.googleapis.com"],
              placement: "header",
            },
          },
        ],
      },
    ],
  });
  expect(sent).toMatchObject([{ authorization: "Bearer real-token-aaaa" }]);
  await expect(importing()).rejects.toThrow("imported once already");
});

test("a handed-out cell whose pin was changed does not open: an import cannot widen where a secret goes", async () => {
  const { secret } = await vault();
  const { sealed } = (await handedOut(secret)).result;
  await secret.secret(PATH, "delete", undefined);
  const stored = JSON.parse(sealed);
  const widened = JSON.stringify({
    ...stored,
    cell: { ...stored.cell, urls: ["https://evil.example.com"] },
  });

  await expect(
    secret.secret(PATH, "importSealed", {
      cell: widened,
      proof: await hmacSha256Hex("at-rest-key-for-tests-only", JSON.stringify([PATH, widened])),
    }),
  ).rejects.toThrow("does not open under this stack's at-rest key");
  expect(await secret.secret(PATH, "describe", {})).toMatchObject({ set: false });
  // The changed cell has the true cell's nonce. It wrote nothing, so it does not shut the true
  // cell out: a damaged copy of a backup, tried first, must not lock out the good one.
  expect(
    await secret.secret(PATH, "importSealed", {
      cell: sealed,
      proof: await hmacSha256Hex("at-rest-key-for-tests-only", JSON.stringify([PATH, sealed])),
    }),
  ).toMatchObject({ result: { path: PATH } });
});

test("an import whose write did not end with the value stored leaves the cell free: a restore can try it again", async () => {
  const { secret, holdListCall } = await vault();
  const { sealed } = (await handedOut(secret)).result;
  await secret.secret(PATH, "delete", undefined);
  const proof = await hmacSha256Hex("at-rest-key-for-tests-only", JSON.stringify([PATH, sealed]));
  const importing = () => secret.secret(PATH, "importSealed", { cell: sealed, proof });
  // a write calls the list once before it stores and once after: the second call is held open
  const afterTheStore = holdListCall(2);
  const first = importing().then(
    () => "imported",
    (error: unknown) => (error instanceof Error ? error.message : String(error)),
  );
  const letGo = await afterTheStore;
  // the value is stored now, and a delete takes it
  await secret.secret(PATH, "delete", undefined);
  letGo();

  expect(await first).toContain("deleted while this value was being stored");
  // the person holds no other copy of this cell: it must not be spent by a write that failed
  expect(await importing()).toMatchObject({ result: { path: PATH } });
  await expect(importing()).rejects.toThrow("imported once already");
});

test("an import takes the public fields that stand beside the cell only when each is a field of the cell it opened, with that value", async () => {
  const { secret } = await vault();
  await secret.secret(PATH, "set", {
    material: { clientId: "the-real-client", clientSecret: "real-secret-bbbb" },
    urls: ["https://gmail.googleapis.com"],
    public: ["clientId"],
  });
  const { sealed } = (await handedOut(secret)).result;
  await secret.secret(PATH, "delete", undefined);
  // `public` is beside the cell and outside its seal: whoever changes a backup can write another
  const withPublic = async (fields: Record<string, string>) => {
    const changed = JSON.stringify({ ...JSON.parse(sealed), public: fields });
    return secret.secret(PATH, "importSealed", {
      cell: changed,
      proof: await hmacSha256Hex("at-rest-key-for-tests-only", JSON.stringify([PATH, changed])),
    });
  };

  // another value for a public field: the catalog would say what the secret is not
  await expect(withPublic({ clientId: "someone-else" })).rejects.toThrow("public fields");
  // the name of a SECRET field: its value would go into the fact and the catalog. Whoever
  // changed the copy does not know that value, so the copy cannot say it.
  await expect(
    withPublic({ clientId: "the-real-client", clientSecret: "a-guess" }),
  ).rejects.toThrow("public fields");
  expect(await secret.secret(PATH, "describe", {})).toMatchObject({ set: false });
  // the copy as the vault handed it out comes back with its public field
  await secret.secret(PATH, "importSealed", {
    cell: sealed,
    proof: await hmacSha256Hex("at-rest-key-for-tests-only", JSON.stringify([PATH, sealed])),
  });
  expect(await secret.secret(PATH, "describe", {})).toMatchObject({
    set: true,
    public: { clientId: "the-real-client" },
  });
});

test("a rule with a path that never waits lets a file go there, and refuses the same bytes at the API's own address", async () => {
  const { secret, upstream, decide } = await vault();
  await decide(MEMBER, {
    type: "events.iterate.com/secret/approval-rule-configured",
    payload: {
      rule: {
        methods: ["POST"],
        hosts: ["gmail.googleapis.com"],
        jsonStrings: ["messages/send"],
        freePaths: ["/upload/"],
      },
    },
  });
  // the first bytes of a JPEG: no text, so no JSON
  const file = (path: string) =>
    secret.fetch(
      useRequest(`https://gmail.googleapis.com${path}`, {
        method: "POST",
        headers: { "content-type": "image/jpeg" },
        body: new Uint8Array([0xff, 0xd8, 0xff, 0xe0]),
      }),
    );
  const answers = [await file("/upload/u1/"), await file("/batch"), await file("/upload/u%31/")];
  expect({
    statuses: answers.map((answer) => answer.status),
    kinds: answers.map((answer) => answer.headers.get(VAULT_ANSWER_HEADER)),
    sends: upstream.mock.calls.length,
  }).toEqual({ statuses: [200, 415, 415], kinds: [null, "refused", "refused"], sends: 1 });
});

test("a POST that a header makes a DELETE is held by a rule for DELETE, and a plain POST is not", async () => {
  const { secret, sent, decide } = await vault();
  await decide(MEMBER, {
    type: "events.iterate.com/secret/approval-rule-configured",
    payload: { rule: { methods: ["DELETE"], hosts: ["gmail.googleapis.com"] } },
  });
  const post = (headers: Record<string, string>) =>
    secret.fetch(
      useRequest("https://gmail.googleapis.com/gmail/v1/users/me/messages/m1", {
        method: "POST",
        headers,
        body: "{}",
      }),
    );
  const answers = [await post({}), await post({ "X-HTTP-Method-Override": "DELETE" })];
  expect({
    statuses: answers.map((answer) => answer.status),
    kinds: answers.map((answer) => answer.headers.get(VAULT_ANSWER_HEADER)),
    sends: sent.length,
  }).toEqual({ statuses: [200, 202], kinds: [null, "held"], sends: 1 });
});

test("a secret made to lend to every secret says so when described, and is the same after it is set again with what it said", async () => {
  const { secret } = await vault();
  const made = { material: "client-secret-aaaa", urls: ["https://gmail.googleapis.com"] };
  await secret.secret(PATH, "set", { ...made, lendTo: null });
  const described = await secret.secret(PATH, "describe", undefined);
  expect(described).toMatchObject({ lendTo: null, placement: "header", operations: [] });
  // set again from what `describe` answered: nothing is narrowed
  const { lendTo, placement, operations } = described as Record<string, unknown>;
  await secret.secret(PATH, "set", { ...made, lendTo, placement, operations });
  expect(await secret.secret(PATH, "describe", undefined)).toMatchObject({
    lendTo: null,
    placement: "header",
    operations: [],
  });
  // and with no word on it, a secret lends to no other
  await secret.secret(PATH, "set", made);
  expect(await secret.secret(PATH, "describe", undefined)).toMatchObject({ lendTo: [] });
});

test("a secret with an approval rule signs nothing on the side, and still checks a signature", async () => {
  const { secret, decide } = await vault();
  await secret.secret(PATH, "set", {
    material: "signing-key-aaaa",
    urls: ["https://gmail.googleapis.com"],
    operations: ["signHmac", "verifyHmac"],
  });
  const signed = () => secret.secret(PATH, "signHmac", { payload: "pay 5 to jo" });
  // the rule of `vault()` stands: what the secret signed would leave in a request it never sees
  expect(await signed()).toMatchObject({
    refused: { code: "FORBIDDEN", message: expect.stringContaining("has an approval rule") },
  });
  expect(
    await secret.secret(PATH, "verifyHmac", { payload: "pay 5 to jo", signature: "00" }),
  ).toMatchObject({ result: false });
  await decide(MEMBER, {
    type: "events.iterate.com/secret/approval-rule-configured",
    payload: { rule: null },
  });
  expect(await signed()).toMatchObject({ result: expect.stringMatching(/^[0-9a-f]{64}$/) });
});

test("an ask of the Cloud that the secret's rule names is held, and is sent once a member approves it", async () => {
  const CLOUD = "https://cloud.example.com";
  const { secret, upstream, approve } = await vault({
    cloud: CLOUD,
    rule: { methods: ["POST"], hosts: ["cloud.example.com"] },
  });
  const ask = () =>
    useRequest(`${CLOUD}/clients/github/ask/reply`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ text: "an answer for a person" }),
    });
  const first = await secret.fetch(ask());
  const { digest } = (await first.clone().json()) as { digest: string };
  // held as any request the rule names: nothing has gone to the Cloud
  expect({
    status: first.status,
    kind: first.headers.get(VAULT_ANSWER_HEADER),
    sends: upstream.mock.calls.length,
  }).toEqual({ status: 202, kind: "held", sends: 0 });
  const waited = secret.fetch(
    useRequest(`${CLOUD}/clients/github/ask/reply`, {
      method: "POST",
      headers: { [SECRET_HELD_HEADER]: digest },
    }),
  );
  await approve(digest);
  const answer = await waited;
  const [sent] = upstream.mock.calls.map(([request]) => request);
  expect({
    status: answer.status,
    sends: upstream.mock.calls.length,
    url: sent?.url,
    // the Cloud gets the stack's signed statement and no header that names the secret
    namesTheSecret: sent?.headers.get("authorization"),
    facts: decodeFacts(answer.headers.get(FACTS_HEADER) || "")[0]?.events.at(-1),
  }).toMatchObject({
    status: 200,
    sends: 1,
    url: `${CLOUD}/clients/github/ask/reply`,
    namesTheSecret: null,
    facts: { type: "events.iterate.com/secret/used", payload: { status: 200, digest } },
  });
});

test("an ask of the Cloud that the rule does not name goes at once, with no value of the secret", async () => {
  const CLOUD = "https://cloud.example.com";
  // the rule names the provider's host, not the Cloud's
  const { secret, upstream } = await vault({ cloud: CLOUD });
  const answer = await secret.fetch(
    useRequest(`${CLOUD}/clients/github/ask/reply`, { method: "POST", body: "{}" }),
  );
  expect({
    status: answer.status,
    sends: upstream.mock.calls.length,
    namesTheSecret: upstream.mock.calls[0]?.[0].headers.get("authorization"),
  }).toEqual({ status: 200, sends: 1, namesTheSecret: null });
});

test("a person's grant that the Cloud brokers is refreshed on word: the Cloud is asked with the stack's statement, and the secret holds what the provider gave", async () => {
  const { secret } = await vault({ cloud: CLOUD_OF_GRANTS, material: GRANT });
  const cloud = cloudThatAnswers(() =>
    Response.json({ access_token: "new-access", refresh_token: "new-refresh", expires_in: 28800 }),
  );

  vi.useFakeTimers({ toFake: ["Date"] });
  expect(await secret.refreshGrant(PATH)).toEqual({
    result: { outcome: "refreshed" },
    facts: [{ path: PATH, events: [REFRESHED(true)] }],
  });
  // within the hour it is fresh: a refresh token works once, and one is not spent for nothing
  expect(await secret.refreshGrant(PATH)).toEqual({ result: { outcome: "fresh" }, facts: [] });
  // an hour later the next refresh sends the token that the first one brought
  vi.setSystemTime(Date.now() + 61 * 60_000);
  await secret.refreshGrant(PATH);
  vi.useRealTimers();

  expect(cloud).toMatchObject({
    asked: [
      { url: `${CLOUD_OF_GRANTS}/clients/github/token`, refreshToken: "old-refresh", signed: true },
      { url: `${CLOUD_OF_GRANTS}/clients/github/token`, refreshToken: "new-refresh", signed: true },
    ],
  });
});

test.for<{ secret: string; own: boolean }>([
  { secret: "a grant connected through the Cloud", own: false },
  { secret: "a grant with a client of the mind's own", own: true },
])(
  "of $secret, a request that names the refresh token, the client's id or its secret is refused before anything is sent, and the access token still goes",
  async ({ own }) => {
    const material = { ...GRANT, clientSecret: "the-client-secret" };
    // the provider's host is the pin, and no rule holds a GET
    const { secret, upstream, sent } = await vault(
      own ? { material } : { cloud: CLOUD_OF_GRANTS, material },
    );
    if (own)
      await secret.secret(PATH, "set", {
        material,
        urls: GMAIL,
        refresh: { kind: "oauth-refresh-token", tokenEndpoint: `${GMAIL[0]}/token` },
      });
    const named = (field: string) =>
      secret.fetch(
        new Request(`${GMAIL[0]}/gmail/v1/users/me/profile`, {
          headers: {
            [SECRET_USE_HEADER]: PATH,
            authorization: `Bearer getSecret("${PATH}", { field: "accessToken" })`,
            "x-extra": `getSecret("${PATH}", { field: "${field}" })`,
          },
        }),
      );
    for (const field of ["refreshToken", "clientId", "clientSecret"]) {
      const answer = await named(field);
      expect({
        status: answer.status,
        kind: answer.headers.get(VAULT_ANSWER_HEADER),
        text: await answer.text(),
      }).toEqual({
        status: 403,
        kind: "refused",
        text: `itx.fetch: "${field}" of ${PATH} is what the secret's oauth-refresh-token refresh reads to make a new access token: it is given to that refresh alone\n`,
      });
    }
    expect(upstream).not.toHaveBeenCalled();
    // the token that the refresh makes is the one a request carries
    expect(await named("accessToken")).toMatchObject({ status: 200 });
    expect(sent).toEqual([{ authorization: "Bearer old-access", body: "", extra: "old-access" }]);

    // and no other secret's refresh borrows such a field
    const lent = await secret.clientSecretFor(PATH, {
      borrower: "/secrets/another",
      origin: GMAIL[0]!,
      field: "refreshToken",
    });
    expect(lent).toMatchObject({
      refused: {
        code: "FORBIDDEN",
        message: expect.stringContaining('"refreshToken" of /secrets/gmail is what the secret'),
      },
    });
  },
);

test("a refresh on word that the provider refuses says so, and the secret is as it was", async () => {
  const { secret } = await vault({ cloud: CLOUD_OF_GRANTS, material: GRANT });
  const cloud = cloudThatAnswers(() => new Response("bad_refresh_token", { status: 401 }));

  const refused = await secret.refreshGrant(PATH);
  // it deletes nothing: the secret is set, and the next try sends the same refresh token
  await secret.refreshGrant(PATH);

  // a refusal is the provider's answer: it is not said as a lost one, and one call asks once
  expect(refused).toEqual({
    result: { outcome: "failed", error: expect.stringContaining("answered 401") },
    facts: [
      {
        path: PATH,
        events: [
          {
            type: "events.iterate.com/secret/refreshed",
            payload: {
              kind: "oauth-refresh-token",
              ok: false,
              answerLost: false,
              error: expect.stringContaining("answered 401"),
            },
          },
        ],
      },
    ],
  });
  expect(await secret.secret(PATH, "describe", {})).toMatchObject({ set: true });
  expect(cloud.asked.map((ask) => ask.refreshToken)).toEqual(["old-refresh", "old-refresh"]);
});

test("a refresh on word whose answer does not arrive is tried once more with the same refresh token, and the log has both", async () => {
  const { secret } = await vault({ cloud: CLOUD_OF_GRANTS, material: GRANT });
  const answers = [
    () => {
      throw new Error("Network connection lost.");
    },
    () => Response.json({ access_token: "new-access", refresh_token: "new-refresh" }),
  ];
  const cloud = cloudThatAnswers(() => answers.shift()!());

  expect(await secret.refreshGrant(PATH)).toEqual({
    result: { outcome: "refreshed" },
    facts: [
      {
        path: PATH,
        events: [
          {
            type: "events.iterate.com/secret/refreshed",
            payload: {
              kind: "oauth-refresh-token",
              ok: false,
              answerLost: true,
              error: expect.stringContaining("Network connection lost."),
            },
          },
          REFRESHED(true),
        ],
      },
    ],
  });
  expect(cloud.asked.map((ask) => ask.refreshToken)).toEqual(["old-refresh", "old-refresh"]);
});

test("a refresh on word that is answered 502 twice says that the answer was lost, asks no third time, and the secret is as it was", async () => {
  const { secret } = await vault({ cloud: CLOUD_OF_GRANTS, material: GRANT });
  const cloud = cloudThatAnswers(() => new Response("no decision", { status: 502 }));

  const lost = await secret.refreshGrant(PATH);
  // the next day's try sends the same refresh token: only the provider knows if it is spent
  await secret.refreshGrant(PATH);

  expect(lost).toMatchObject({
    result: { outcome: "failed", answerLost: true, error: expect.stringContaining("answered 502") },
    facts: [
      {
        path: PATH,
        events: [
          { payload: { ok: false, answerLost: true } },
          { payload: { ok: false, answerLost: true } },
        ],
      },
    ],
  });
  expect(await secret.secret(PATH, "describe", {})).toMatchObject({ set: true });
  expect(cloud.asked.map((ask) => ask.refreshToken)).toEqual([
    "old-refresh",
    "old-refresh",
    "old-refresh",
    "old-refresh",
  ]);
});

test.for([
  [429, "the provider said that it gets too many requests"],
  [
    504,
    "the Cloud's call to the provider goes on, and a second one would show a token that is in use",
  ],
] as const)(
  "a refresh on word that is answered %i is not asked again at once: %s",
  async ([status]) => {
    const { secret } = await vault({ cloud: CLOUD_OF_GRANTS, material: GRANT });
    const cloud = cloudThatAnswers(() => new Response("not now", { status }));

    expect(await secret.refreshGrant(PATH)).toMatchObject({
      // no decision on the grant came, so it is no refusal: the next run asks again
      result: {
        outcome: "failed",
        answerLost: true,
        error: expect.stringContaining(`answered ${status}`),
      },
      facts: [{ path: PATH, events: [{ payload: { ok: false, answerLost: true } }] }],
    });
    expect(cloud.asked.map((ask) => ask.refreshToken)).toEqual(["old-refresh"]);
  },
);

test("a grant of the Cloud's whose provider gave no refresh token has nothing to refresh: nobody is asked, and no failure is said", async () => {
  // a Slack workspace that does not rotate its tokens gives one bot token that does not end
  const { secret } = await vault({
    cloud: CLOUD_OF_GRANTS,
    material: { accessToken: "a-bot-token", clientId: "slack.client" },
  });
  const cloud = cloudThatAnswers(() => Response.json({}));

  expect(await secret.refreshGrant(PATH)).toEqual({
    result: { outcome: "not-a-brokered-grant" },
    facts: [],
  });
  expect(cloud).toMatchObject({ asked: [] });
});

test("a refresh on word of a secret that is no grant of the Cloud's asks nobody", async () => {
  // a plain token; and a grant with a client of the mind's own would refresh when its provider asks
  const { secret } = await vault();
  const cloud = cloudThatAnswers(() => Response.json({}));

  expect(await secret.refreshGrant(PATH)).toEqual({
    result: { outcome: "not-a-brokered-grant" },
    facts: [],
  });
  await secret.secret(PATH, "delete", {});
  expect(await secret.refreshGrant(PATH)).toMatchObject({
    result: { outcome: "not-a-brokered-grant" },
  });
  expect(cloud).toMatchObject({ asked: [] });
});

test("the Cloud mints no installation token for a secret pinned beyond the hosts it names for the App, and the token goes to no such host", async () => {
  const cloud = cloudWithGithubApp();
  await cloud.set([...GITHUB_HOSTS, ELSEWHERE]);
  const beyond = await cloud.use(`${ELSEWHERE}/`);
  const mintedBeyond = cloud.minted;
  await cloud.set(GITHUB_HOSTS);
  const within = await cloud.use("https://api.github.com/installation/repositories");
  expect({
    beyond: { status: beyond.status, text: await beyond.text(), minted: mintedBeyond },
    within: within.status,
    sent: cloud.sent,
  }).toEqual({
    beyond: { status: 502, text: expect.stringContaining(`not ${ELSEWHERE}`), minted: 0 },
    within: 200,
    sent: [
      {
        url: "https://api.github.com/installation/repositories",
        authorization: "Bearer installation-token-aaaa",
      },
    ],
  });
});

test("a secret made with one Cloud sends nothing to another, whatever a later call names: an ask, a new connect and a refresh", async () => {
  const OTHER = "https://other-cloud.example";
  const { secret } = await vault({ cloud: CLOUD_OF_GRANTS, material: GRANT });
  const seen: { url: string; method: string; statement: boolean; body: string }[] = [];
  vi.stubGlobal("fetch", async (input: Request | string, init?: RequestInit) => {
    const request = new Request(input, init);
    const { origin, pathname } = new URL(request.url);
    seen.push({
      url: request.url,
      method: request.method,
      statement: request.headers.has("iterate-auth-statement"),
      body: await request.text(),
    });
    // the other Cloud publishes a client of the same name, with every address on its own origin
    if (pathname === "/.well-known/iterate-cloud")
      return Response.json({
        clients: {
          github: {
            clientId: "Iv1.other",
            authorizationEndpoint: "https://provider.example/authorize",
            redirectUri: `${origin}/clients/github/callback`,
            tokenEndpoint: `${origin}/clients/github/token`,
            urls: GMAIL,
          },
        },
      });
    return Response.json({ access_token: "new-access", refresh_token: "new-refresh" });
  });
  // 1. an ask that names the other Cloud's address is no ask: it is a request with the secret
  //    for a host outside its pin, and it is refused
  const asked = await secret.fetch(
    useRequest(`${OTHER}/clients/github/ask/reply`, { method: "POST", body: "{}" }),
  );
  // 2. a new connect on the same path that names the other Cloud begins a new secret: the
  //    other Cloud's public document is read, and nothing of the secret that stands goes there
  const begun = await secret.secret(PATH, "beginOAuth", {
    client: { cloud: "github", origin: OTHER },
  });
  // 3. the refresh of the secret that stands goes to its own Cloud
  const refreshed = await secret.refreshGrant(PATH);
  const to = (origin: string) => seen.filter(({ url }) => new URL(url).origin === origin);
  expect({
    asked: asked.status,
    begun: z.object({ result: z.object({ nonce: z.string() }) }).safeParse(begun).success,
    refreshed: refreshed.result,
    other: to(OTHER),
    own: to(CLOUD_OF_GRANTS).map(({ url, statement, body }) => ({
      url,
      statement,
      refreshToken: new URLSearchParams(body).get("refresh_token"),
    })),
  }).toEqual({
    asked: 403,
    begun: true,
    refreshed: { outcome: "refreshed" },
    other: [
      { url: `${OTHER}/.well-known/iterate-cloud`, method: "GET", statement: false, body: "" },
    ],
    own: [
      {
        url: `${CLOUD_OF_GRANTS}/clients/github/token`,
        statement: true,
        refreshToken: "old-refresh",
      },
    ],
  });
});

test("a cell whose broker is not at its own Cloud's origin refreshes nowhere: nothing is signed or sent", async () => {
  const { secret } = await vault({
    cloud: CLOUD_OF_GRANTS,
    broker: "https://other-cloud.example",
    material: GRANT,
  });
  const cloud = cloudThatAnswers(() => Response.json({ access_token: "new-access" }));
  expect((await secret.refreshGrant(PATH)).result).toMatchObject({
    outcome: "failed",
    error: expect.stringContaining("is not this secret's Cloud"),
  });
  expect(cloud).toMatchObject({ asked: [] });
});

test.for([
  "http://cloud.example.com",
  "https://cloud.example.com/",
  "https://cloud.example.com/clients",
  "cloud.example.com",
  undefined,
])(
  "a Cloud named as %s is refused, at a connect and at an installation's secret, and nobody is asked",
  async (origin) => {
    const { secret } = await vault();
    const cloud = cloudThatAnswers(() => Response.json({}));
    await expect(
      secret.secret(PATH, "beginOAuth", { client: { cloud: "github", origin } }),
    ).rejects.toThrow("a Cloud is named by its origin");
    await expect(
      cloudWithGithubApp().set(GITHUB_HOSTS, { cloud: "github", origin }),
    ).rejects.toThrow("a Cloud is named by its origin");
    expect(cloud).toMatchObject({ asked: [] });
  },
);

test("a rule cannot be loosened without a signature, and a member's signed statement removes it", async () => {
  const { secret, decide } = await vault();
  const by = { userId: "user_aaaa", email: "member@example.com" };
  await expect(
    secret.tightenRule(PATH, { rule: { methods: ["PUT"], hosts: ["gmail.googleapis.com"] }, by }),
  ).rejects.toThrow(
    `That takes your key, whether the rules for mail and calls are locked or not: go back, and press "Save with passkey" in the block of ${PATH}`,
  );
  await decide(MEMBER, {
    type: "events.iterate.com/secret/approval-rule-configured",
    payload: { rule: null },
  });
  expect(await secret.approvals(PATH)).toEqual({ rule: null, held: [] });
});

test.for([
  { error: "access_denied", status: "declined" },
  { error: "server_error", status: "failed" },
])(
  "the provider's $error is the attempt's answer at once ($status), not pending until the attempt runs out",
  async ({ error, status }) => {
    const { secret } = await vault();
    // the object's verbs answer untyped
    const { nonce } = z.object({ result: z.object({ nonce: z.string() }) }).parse(
      await secret.secret(PATH, "beginOAuth", {
        authorizationEndpoint: "https://provider.example/authorize",
        tokenEndpoint: "https://provider.example/token",
        clientId: "client",
      }),
    ).result;
    const result = () => secret.secret(PATH, "oauthResult", { nonce });
    const member = { userId: "user_aaaa", email: "member@example.com", member: true };
    const before = await result();
    const refused = await Promise.all(
      [
        secret.recordOAuthError(PATH, { nonce: "another", error, by: member }),
        secret.recordOAuthError(PATH, { nonce, error, by: null }),
      ].map((recorded) =>
        recorded.then(
          () => "recorded",
          (reason: Error) => reason.message,
        ),
      ),
    );
    const recorded = await secret.recordOAuthError(PATH, { nonce, error, by: member });
    expect({ before, refused, recorded, after: await result() }).toEqual({
      before: { status: "pending" },
      refused: [
        "no pending attempt matches this callback — begin again",
        "only a member of the mind, signed in, may answer this attempt",
      ],
      recorded: { status, next: null },
      after: { status, error },
    });
  },
);

test("an attempt begun straightToProvider tells the start link so, and one begun without it does not", async () => {
  const { secret } = await vault();
  const startTarget = async (options: object) => {
    const { nonce } = z.object({ result: z.object({ nonce: z.string() }) }).parse(
      await secret.secret(PATH, "beginOAuth", {
        authorizationEndpoint: "https://provider.example/authorize",
        tokenEndpoint: "https://provider.example/token",
        clientId: "client",
        ...options,
      }),
    ).result;
    return await secret.oauthStartTarget(PATH, { nonce });
  };
  expect([
    (await startTarget({ straightToProvider: true }))?.straightToProvider,
    await startTarget({}),
  ]).toEqual([true, expect.not.objectContaining({ straightToProvider: expect.anything() })]);
});

test("an attempt may come back to any hostname of any zone of the mind, or to the control-plane hostname, and nowhere else", async () => {
  const { secret } = await vault();
  const begun = (next: string) =>
    secret.secret(PATH, "beginOAuth", {
      authorizationEndpoint: "https://provider.example/authorize",
      tokenEndpoint: "https://provider.example/token",
      clientId: "client",
      next,
    });
  for (const next of [
    "https://iterate.example.com/keys",
    "https://dash.example.com/",
    "https://second.example/done",
    "https://shop.second.example/done",
  ])
    expect(await begun(next)).toMatchObject({
      result: { authorizationUrl: expect.stringContaining("https://iterate.example.com/") },
    });
  for (const next of [
    "https://elsewhere.test/",
    "https://notsecond.example/",
    "http://dash.example.com/",
  ])
    await expect(begun(next)).rejects.toThrow("next is an absolute URL on");
});

test.for([
  ["a field that this code does not write", { ...cellOfAnotherVault.cell, client: "github" }],
  [
    "a refresh through a client that this code does not know",
    {
      ...cellOfAnotherVault.cell,
      refresh: {
        kind: "oauth-refresh-token",
        tokenEndpoint: "https://provider.example/token",
        clientAuth: "none",
        client: { broker: "github" },
      },
    },
  ],
  [
    "a refresh over http",
    {
      ...cellOfAnotherVault.cell,
      refresh: {
        kind: "oauth-refresh-token",
        tokenEndpoint: "http://provider.example/token",
        clientAuth: "none",
      },
    },
  ],
  ["no word of what it may be used for", { ...cellOfAnotherVault.cell, placement: undefined }],
] as const)("a sealed cell with %s is no cell: the import refuses its shape", async ([, cell]) => {
  const { secret } = await vault();
  const text = JSON.stringify({ cell });
  const proof = await hmacSha256Hex("at-rest-key-for-tests-only", JSON.stringify([PATH, text]));
  await expect(secret.secret(PATH, "importSealed", { cell: text, proof })).rejects.toThrow(
    z.ZodError,
  );
  // the proof was not asked: nothing of the cell was kept
  expect(await secret.secret(PATH, "describe", {})).toMatchObject({ set: true, urls: GMAIL });
});

test.for([
  ["a token endpoint over http", { tokenEndpoint: "http://provider.example/token" }],
  ["an authorization endpoint over http", { authorizationEndpoint: "http://provider.example/a" }],
  [
    "an account lookup over http",
    { account: { url: "http://provider.example/me", id: "id" }, urls: ["http://provider.example"] },
  ],
] as const)("an attempt with %s is refused, and no attempt waits", async ([, options]) => {
  const { secret, state } = await vault();
  await expect(
    secret.secret(PATH, "beginOAuth", {
      authorizationEndpoint: "https://provider.example/authorize",
      tokenEndpoint: "https://provider.example/token",
      clientId: "client",
      ...options,
    }),
  ).rejects.toThrow(/https/);
  expect(state.storage.kv.get("pending")).toBeUndefined();
});

test("a refresh endpoint over http is refused when a secret is set", async () => {
  const { secret } = await vault();
  await expect(
    secret.secret(PATH, "set", {
      material: { refreshToken: "r", clientId: "c" },
      urls: ["http://provider.example"],
      refresh: { kind: "oauth-refresh-token", tokenEndpoint: "http://provider.example/token" },
    }),
  ).rejects.toThrow("must be an https URL");
});

/** What a request is told that would open a WebSocket with a secret that has a rule. */
const NO_WEBSOCKET = `itx.fetch: ${PATH} has an approval rule, so it opens no WebSocket\n`;

/** A request whose headers say what it is, for a secret with a rule: what the secret holds when
 *  a plain token is not enough, and what the request is told. */
type SaysWhatItIs = {
  name: string;
  material?: Record<string, string>;
  method?: string;
  headers: Record<string, string>;
  text: string;
};

test.for<SaysWhatItIs>([
  {
    name: "a request that is written as a WebSocket",
    headers: { upgrade: "websocket" },
    text: NO_WEBSOCKET,
  },
  {
    name: "a request whose Upgrade header a field of the secret would fill",
    material: { token: "real-token-aaaa", word: "websocket" },
    headers: { upgrade: fieldOf("word") },
    text: noPlaceholder("its upgrade header"),
  },
  {
    name: "a request whose method-override header a field of the secret would fill",
    material: { token: "real-token-aaaa", word: "DELETE" },
    headers: { "x-http-method-override": fieldOf("word") },
    text: noPlaceholder("its x-http-method-override header"),
  },
])(
  "under a rule, $name is refused when it arrives: no member is asked, and nothing leaves",
  async ({ material, headers, text }) => {
    // the rule names POST, and each of these is a POST: without the refusal it would wait
    const { secret, upstream } = await vault({ material });
    const answer = await secret.fetch(
      material ? withFields(headers, "POST") : useRequest(LABELS, { method: "POST", headers }),
    );
    const facts = decodeFacts(answer.headers.get(FACTS_HEADER) || "")[0]?.events ?? [];
    expect({
      status: answer.status,
      kind: answer.headers.get(VAULT_ANSWER_HEADER),
      text: await answer.text(),
      facts: facts.map((fact) => fact.type),
      held: (await secret.approvals(PATH)).held.length,
      sends: upstream.mock.calls.length,
    }).toEqual({
      status: 403,
      kind: "refused",
      text,
      // no fact asks a member for an approval that could never send the request
      facts: ["events.iterate.com/secret/used"],
      held: 0,
      sends: 0,
    });
  },
);

test.for<SaysWhatItIs>([
  {
    name: "a request that is written as a WebSocket",
    method: "GET",
    headers: { upgrade: "websocket" },
    text: NO_WEBSOCKET,
  },
  {
    name: "a request whose Upgrade header a field of the secret fills",
    material: { token: "real-token-aaaa", word: "websocket" },
    method: "GET",
    headers: { upgrade: fieldOf("word") },
    text: NO_WEBSOCKET,
  },
  {
    name: "the same with the word in another letter case",
    material: { token: "real-token-aaaa", word: "WebSocket" },
    method: "GET",
    headers: { upgrade: fieldOf("word") },
    text: NO_WEBSOCKET,
  },
  {
    name: "a request whose method-override header a field of the secret fills",
    material: { token: "real-token-aaaa", word: "DELETE" },
    method: "POST",
    headers: { "x-http-method-override": fieldOf("word") },
    text: noPlaceholder("a header that names another method"),
  },
])(
  "a rule that is set while a request is on its way reads the request that leaves: $name is refused with the reason, and nothing leaves",
  async ({ material, method, headers, text }) => {
    const { secret, state, upstream, decide } = await vault({ material });
    await decide(MEMBER, { type: RULE_CONFIGURED, payload: { rule: null } });
    // no rule when the request arrives, and one that names DELETE alone by the time it would leave
    const read = state.storage.kv.get;
    let reads = 0;
    state.storage.kv.get = (key: string) =>
      key === "approval-rule" && ++reads > 1
        ? { methods: ["DELETE"], hosts: ["gmail.googleapis.com"] }
        : read(key);
    const answer = await secret.fetch(
      material ? withFields(headers, method) : useRequest(LABELS, { method, headers }),
    );
    expect({
      status: answer.status,
      kind: answer.headers.get(VAULT_ANSWER_HEADER),
      text: await answer.text(),
      sends: upstream.mock.calls.length,
    }).toEqual({ status: 403, kind: "refused", text, sends: 0 });
  },
);

test("with no rule, a request whose Upgrade header the secret fills leaves as a WebSocket: the refusal is the rule's", async () => {
  const { secret, upstream, decide } = await vault({
    material: { token: "real-token-aaaa", transport: "websocket" },
  });
  await decide(MEMBER, { type: RULE_CONFIGURED, payload: { rule: null } });
  const answer = await secret.fetch(withFields({ upgrade: fieldOf("transport") }));
  expect({
    status: answer.status,
    upgrade: upstream.mock.calls.map(([request]) => request.headers.get("upgrade")),
  }).toEqual({ status: 200, upgrade: ["websocket"] });
});

test.for([
  // the rule holds DELETE: as written, this header names no method that the rule knows
  { name: "a method that the rule holds", verb: "DELETE" },
  // refused by where the placeholder stands, whatever the field holds
  { name: "a method that the rule does not hold", verb: "PUT" },
])(
  "under a rule that does not name the request as it is written, a header that names another method still takes no placeholder: one that the secret would fill with $name is refused, and nothing leaves",
  async ({ verb }) => {
    const { secret, upstream } = await vault({
      rule: { methods: ["DELETE"], hosts: ["gmail.googleapis.com"] },
      material: { token: "real-token-aaaa", verb },
    });
    const filled = await secret.fetch(
      withFields({ "x-http-method-override": fieldOf("verb") }, "POST"),
    );
    // written plainly, the rule reads it: the request waits
    const written = await secret.fetch(withFields({ "x-http-method-override": "DELETE" }, "POST"));
    expect({
      filled: [filled.status, filled.headers.get(VAULT_ANSWER_HEADER), await filled.text()],
      written: [written.status, written.headers.get(VAULT_ANSWER_HEADER)],
      sends: upstream.mock.calls.length,
    }).toEqual({
      filled: [403, "refused", noPlaceholder("its x-http-method-override header")],
      written: [202, "held"],
      sends: 0,
    });
  },
);

/** A path of the pinned host that the tests' rules do not hold for a GET. */
const LABELS = "https://gmail.googleapis.com/gmail/v1/users/me/labels";

/** What a request is told when a secret with a rule would fill a header that says what it is. */
function noPlaceholder(where: string) {
  return `itx.fetch: ${PATH} has an approval rule, which reads a request as it is written: ${where} takes no placeholder\n`;
}

/** The placeholder of one field of the secret, for a secret that holds several. */
function fieldOf(name: string) {
  return `getSecret("${PATH}", { field: "${name}" })`;
}

/** A request with a secret that holds several fields: its `token` in the Authorization header,
 *  and `headers` beside it. */
function withFields(headers: Record<string, string>, method = "GET") {
  return new Request(LABELS, {
    method,
    headers: { authorization: `Bearer ${fieldOf("token")}`, [SECRET_USE_HEADER]: PATH, ...headers },
  });
}

/** The Worker's variables: the config of a mind at `iterate.example.com`, and an at-rest key. */
const VARS = {
  ITERATE: JSON.stringify({
    mindId: "a".repeat(64),
    controlPlaneHostname: "iterate.example.com",
    zones: ["example.com", "second.example"],
    ownerEmails: ["owner@example.net"],
    topology: "full-cloudflare",
  }),
  ITERATE__AT_REST_KEY: "at-rest-key-for-tests-only",
  // a stack whose deploy made no OAuth client at Cloudflare (../stack-client.test.ts has one)
  // a stack whose deploy made no SFU app or TURN key (../stack-secrets.test.ts has them)
  ITERATE__CLOUDFLARE_REALTIME: JSON.stringify({
    sfu: { refusal: "Authentication error" },
    turn: { refusal: "Authentication error" },
  }),
};

/** A vault with one secret and its rule. With `cloud`, the secret is one connected through the
 *  client `github` of the Cloud at that origin, which the secret's record keeps, and the stack
 *  signs what it asks of that Cloud. No variable of the Worker names a Cloud. */
async function vault(
  options: {
    cloud?: string;
    /** A cell that no connect writes: its token endpoint is at this origin, not at `cloud`. */
    broker?: string;
    rule?: { methods: string[]; hosts: string[] };
    /** What the secret holds, when a plain token is not enough: a grant's tokens. */
    material?: Record<string, string>;
  } = {},
) {
  const sent: { authorization: string | null; body: string; extra: string | null }[] = [];
  const upstream = vi.fn(async (request: Request) => {
    sent.push({
      authorization: request.headers.get("authorization"),
      body: await request.text(),
      extra: request.headers.get("x-extra"),
    });
    return new Response("sent");
  });
  vi.stubGlobal("fetch", upstream);
  const sets = new Map<string, Set<string>>();
  const list: { calls: number; wait?: (call: number) => Promise<void> } = { calls: 0 };
  const env = {
    ...VARS,
    // the vault's sets of paths, by name: "index" (a rule or a held request) and "set"
    APPROVALS: {
      getByName: (name: string) => {
        const paths = sets.get(name) ?? new Set<string>();
        sets.set(name, paths);
        // A call of the list is a call of another object: it lets another call of the secret's
        // object in. A test holds one call open to put a set or a delete into that moment.
        const called = async () => {
          list.calls += 1;
          await list.wait?.(list.calls);
        };
        return {
          add: async (path: string) => {
            await called();
            paths.add(path);
          },
          remove: async (path: string) => {
            await called();
            paths.delete(path);
          },
        };
      },
    },
    // believes the statement: who signed is the key the envelope names
    AUTH: {
      sign: async (input: object) => ({
        statement: JSON.stringify(input),
        signature: { format: "p256", key: "key-stack", sig: "sig" },
      }),
      verify: async (envelope: Envelope) => ({
        signer: {
          principal: { actor: envelope.signature.key },
          key: envelope.signature.key,
          label: "test key",
          member: envelope.signature.key.startsWith(MEMBER),
          // a passkey says whether it checked its user; this one did not
          ...(envelope.signature.key === UNCHECKED && { userVerified: false }),
        },
        statement: JSON.parse(envelope.statement),
      }),
    },
  };
  // the cast: the object reads only the bindings above
  const state = fakeState(PATH);
  const secret = new SecretDurableObject(state as never, env as never);
  await secret.secret(PATH, "set", {
    material: options.material || "real-token-aaaa",
    urls: ["https://gmail.googleapis.com"],
  });
  if (options.cloud) {
    // Only a connect through the Cloud's own page makes such a secret (`set` refuses a client):
    // the stored cell is given what that connect writes: the client's name, its Cloud's origin
    // and its broker.
    // The value is sealed again with it: a cell opens only as the thing it was sealed as.
    // the cast: the stored cell, as the object's own seal wrote it a moment ago
    const current = state.storage.kv.get("current") as {
      cell: {
        context: string;
        urls: string[];
        version: number;
        nonce: string;
        material: unknown;
        refresh: unknown;
        placement: string;
        operations: string[];
        lendTo: string[] | null;
      };
    };
    const {
      context,
      urls,
      version,
      nonce,
      material: _sealed,
      refresh: _none,
      ...use
    } = current.cell;
    const refresh = {
      kind: "oauth-refresh-token" as const,
      tokenEndpoint: `${options.broker || options.cloud}/clients/github/token`,
      client: { cloud: "github", origin: options.cloud },
    };
    const material = await encryptSecretMaterial(
      options.material || "real-token-aaaa",
      { context, urls, refresh, version, nonce, use },
      env.ITERATE__AT_REST_KEY,
    );
    state.storage.kv.put("current", { ...current, cell: { ...current.cell, refresh, material } });
  }
  await secret.tightenRule(PATH, {
    rule: options.rule || { methods: ["POST"], hosts: ["gmail.googleapis.com"] },
    by: { userId: "user_aaaa", email: "member@example.com" },
  });
  const decide = (
    key: string,
    fields: { type: string; about?: string[]; payload?: object; path?: string },
  ) =>
    secret.decide(PATH, {
      statement: JSON.stringify({
        mind: "iterate.example.com",
        path: PATH,
        at: 0,
        expires: 1,
        nonce: "n",
        ...fields,
      }),
      signature: { format: "p256", key, sig: "sig" },
    });
  return {
    secret,
    state,
    upstream,
    sent,
    decide,
    approve: (digest: string) => decide(MEMBER, { type: APPROVED, about: [digest] }),
    /** The paths in the vault's set of secrets that are set. */
    listedAsSet: () => [...(sets.get("set") ?? [])],
    /** Holds the list's call that is `after` calls from now open. Answers a promise that settles
     *  when that call has come, with the function that lets it go on. */
    holdListCall: (after: number) => {
      const at = list.calls + after;
      return new Promise<() => void>((reached) => {
        list.wait = (call) =>
          call === at ? new Promise<void>((go) => reached(go)) : Promise.resolve();
      });
    },
  };
}

async function held(secret: SecretDurableObject, raw: string): Promise<string> {
  const answer = await secret.fetch(gmailPost(raw));
  return ((await answer.json()) as { digest: string }).digest;
}

function waitCall(digest: string, init: { body?: string; headers?: Record<string, string> } = {}) {
  return useRequest("https://gmail.googleapis.com/gmail/v1/users/me/messages/send", {
    method: "POST",
    headers: { "content-type": "application/json", [SECRET_HELD_HEADER]: digest, ...init.headers },
    body: init.body,
  });
}

/** The secret's stored cell, as the vault hands it out to a caller that proves the at-rest key. */
async function handedOut(secret: SecretDurableObject, until = Date.now() + 60_000) {
  const proof = await hmacSha256Hex(
    "at-rest-key-for-tests-only",
    JSON.stringify([PATH, "exportSealed", until]),
  );
  // the object's verbs answer untyped
  return z
    .object({ result: z.object({ sealed: z.string() }), facts: z.array(z.unknown()) })
    .parse(await secret.secret(PATH, "exportSealed", { proof, until }));
}

function useRequest(url: string, init: RequestInit) {
  const headers = new Headers(init.headers);
  headers.set("authorization", `Bearer getSecret("${PATH}")`);
  headers.set(SECRET_USE_HEADER, PATH);
  return new Request(url, { ...init, headers });
}

function gmailPost(raw: string) {
  return useRequest("https://gmail.googleapis.com/gmail/v1/users/me/messages/send", {
    method: "POST",
    headers: { "content-type": "application/json", traceparent: `00-${crypto.randomUUID()}-01` },
    body: JSON.stringify({ raw }),
  });
}

// ordered as SQLite's
function fakeState(name: string) {
  const store = new Map<string, unknown>();
  return {
    id: { name },
    exports: {},
    storage: {
      kv: {
        get: (key: string) => structuredClone(store.get(key)),
        put: (key: string, value: unknown) => void store.set(key, structuredClone(value)),
        delete: (key: string) => store.delete(key),
        list: ({ prefix = "" }: { prefix?: string } = {}) =>
          [...store.entries()]
            .filter(([key]) => key.startsWith(prefix))
            .sort(([a], [b]) => (a < b ? -1 : 1))
            .map(([key, value]) => [key, structuredClone(value)]),
      },
    },
  };
}

const CLOUD_OF_GRANTS = "https://cloud.example.com";
/** A person's grant as a connect through the Cloud leaves it: the tokens and the client's id. */
const GRANT = { accessToken: "old-access", refreshToken: "old-refresh", clientId: "Iv1.client" };
const REFRESHED = (ok: boolean) => ({
  type: "events.iterate.com/secret/refreshed",
  payload: { kind: "oauth-refresh-token", ok },
});

/** The Cloud's token route, standing in for `fetch`: what each call asked, and `answer` to it. */
function cloudThatAnswers(answer: () => Response) {
  const asked: { url: string; refreshToken: string | null; signed: boolean }[] = [];
  vi.stubGlobal("fetch", async (request: Request) => {
    asked.push({
      url: request.url,
      refreshToken: new URLSearchParams(await request.text()).get("refresh_token"),
      signed: request.headers.has("iterate-auth-statement"),
    });
    return answer();
  });
  return { asked };
}

const INSTALLATION = "/secrets/github-installation-1";
const GITHUB_HOSTS = ["https://api.github.com", "https://github.com"];
const ELSEWHERE = "https://elsewhere.example";

/** A Cloud at `CLOUD_OF_GRANTS` that has the GitHub App `github`, and an installation's secret that names it: the Cloud names GitHub's hosts as the App's
 *  and mints an installation's token. The Cloud and every other host stand in for `fetch`:
 *  `minted` counts the tokens the Cloud gave, and `sent` is what reached another host. */
function cloudWithGithubApp() {
  const cloud = { minted: 0, sent: [] as { url: string; authorization: string | null }[] };
  // the Cloud's facts are fetched by their URL alone
  vi.stubGlobal("fetch", async (input: Request | string) => {
    const request = new Request(input);
    const { origin, pathname } = new URL(request.url);
    if (origin === CLOUD_OF_GRANTS && pathname === "/.well-known/iterate-cloud")
      return Response.json({
        clients: {
          github: {
            clientId: "Iv1.client",
            authorizationEndpoint: "https://github.com/login/oauth/authorize",
            redirectUri: `${CLOUD_OF_GRANTS}/clients/github/callback`,
            tokenEndpoint: `${CLOUD_OF_GRANTS}/clients/github/token`,
            urls: GITHUB_HOSTS,
            installationTokenEndpoint: `${CLOUD_OF_GRANTS}/clients/github/installation-token`,
          },
        },
      });
    if (origin === CLOUD_OF_GRANTS) {
      cloud.minted += 1;
      return Response.json({ token: "installation-token-aaaa" });
    }
    cloud.sent.push({ url: request.url, authorization: request.headers.get("authorization") });
    return new Response("sent");
  });
  const env = {
    ...VARS,
    APPROVALS: { getByName: () => ({ add: async () => {}, remove: async () => {} }) },
    AUTH: {
      sign: async (input: object) => ({
        statement: JSON.stringify(input),
        signature: { format: "p256", key: "key-stack", sig: "sig" },
      }),
    },
  };
  // the cast: the object reads only the bindings above
  const secret = new SecretDurableObject(fakeState(INSTALLATION) as never, env as never);
  return Object.assign(cloud, {
    set: (urls: string[], client: object = { cloud: "github", origin: CLOUD_OF_GRANTS }) =>
      secret.secret(INSTALLATION, "set", {
        material: {},
        urls,
        refresh: {
          kind: "github-app-installation",
          apiOrigin: "https://api.github.com",
          installationId: "1",
          client,
        },
      }),
    use: (url: string) =>
      secret.fetch(
        new Request(url, {
          headers: {
            authorization: `Bearer getSecret("${INSTALLATION}", { field: "accessToken" })`,
            [SECRET_USE_HEADER]: INSTALLATION,
          },
        }),
      ),
  });
}

/** The stack's deploy named an egress gateway: the vault's `EGRESS_GATEWAY` for one test. It says
 *  what it was handed, and answers `answer`. */
function gatewayOf(answer: (request: Request) => Promise<Response> | Response) {
  const carried: { url: string; authorization: string | null; redirect?: string }[] = [];
  const bindings = vaultEnv as { EGRESS_GATEWAY?: unknown };
  bindings.EGRESS_GATEWAY = {
    fetch: async (request: Request, init?: RequestInit) => {
      carried.push({
        url: request.url,
        authorization: request.headers.get("authorization"),
        redirect: init?.redirect,
      });
      return answer(request);
    },
  };
  onTestFinished(() => void delete bindings.EGRESS_GATEWAY);
  return carried;
}
const MESSAGES = "https://gmail.googleapis.com/gmail/v1/users/me/messages";