iterate.com / kernel

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

kernel / core / mind-worker / src / integrations / email.test.tsmain at 949894f

import type { ItxHostRootContext, ReachableContext } from "core-itx";
import type { GateAnswer } from "iterate/acts";
import type { EmailSendInput } from "iterate/api";
import type { Door } from "iterate/workers";
import { expect, test } from "vitest";
import { emailRoot, senderOf } from "./email.ts";

test("a held mail keeps no reservation while it waits, so a retry of its delivery is not refused", async () => {
  const mind = mindWith([held, { sent: true, messageId: "<m1@example.com>" }]);
  const recorded = await mind.send();
  expect(mind).toMatchObject({
    asked: [
      { wait: false, reserved: ["delivery-1"] },
      // the wait for a member's answer: the reservation is given up before it
      { wait: true, reserved: [] },
    ],
  });
  expect(recorded).toMatchObject({ type: "events.iterate.com/email/sent" });
});

test("a mail no rule holds is reserved while it goes, and a held mail nobody approves leaves no reservation", async () => {
  const free = mindWith([{ sent: true, messageId: "<m2@example.com>" }]);
  await free.send();
  expect(free).toMatchObject({ asked: [{ wait: false, reserved: ["delivery-1"] }] });

  const waiting: GateAnswer = { state: "waiting", digest: "d".repeat(64), facts: [] };
  const unanswered = mindWith([held, { sent: false, error: "it waits", gate: waiting }]);
  await expect(unanswered.send()).rejects.toThrow("waits for a member's approval");
  expect(unanswered.reservations()).toEqual([]);
});

test("a recipient that is no single address is refused before anything is reserved or asked", async () => {
  const mind = mindWith([{ sent: true, messageId: "<m3@example.com>" }]);
  await expect(mind.send('"<safe@example.org>" <leak@example.net>')).rejects.toThrow(
    "its address alone",
  );
  expect({ asked: mind.asked, reserved: mind.reservations() }).toEqual({ asked: [], reserved: [] });
});

test("a subject with a line break is refused before anything is reserved or asked: a header is one line", async () => {
  const mind = mindWith([{ sent: true, messageId: "<m4@example.com>" }]);
  await expect(mind.send("jo@elsewhere.example", "Hello\r\nBcc: leak@example.net")).rejects.toThrow(
    "the subject has a line break",
  );
  expect({ asked: mind.asked, reserved: mind.reservations() }).toEqual({ asked: [], reserved: [] });
});

test("an answer to a mail whose subject arrived as two lines goes with that subject on one line", async () => {
  const mind = mindWith([{ sent: true, messageId: "<m5@example.com>" }], {
    stored: {
      type: "events.iterate.com/email/sent",
      payload: {
        messageId: "m0@example.org",
        from: "mind@example.com",
        to: ["jo@elsewhere.example"],
        cc: [],
        subject: "Hello\r\nBcc: leak@example.net",
        text: "A mail.",
        html: null,
        inReplyTo: null,
        references: [],
        attachments: [],
      },
    },
  });
  await mind.answer(7);
  expect(mind.sent.map((message) => message.subject)).toEqual(["Re: Hello Bcc: leak@example.net"]);
});

test("a mail the provider refuses is said on the mail log, and the caller still gets the refusal", async () => {
  const mind = mindWith([
    { sent: false, error: "the recipient is suppressed", code: "E_RECIPIENT_SUPPRESSED" },
  ]);
  await expect(mind.send()).rejects.toThrow(
    "itx.email.send: the boundary refused it: the recipient is suppressed",
  );
  expect(mind.appended).toMatchObject([
    {
      event: {
        type: "events.iterate.com/email/send-failed",
        payload: {
          from: "mind@example.com",
          to: ["jo@elsewhere.example"],
          cc: [],
          subject: "Hello",
          error: "the recipient is suppressed",
          code: "E_RECIPIENT_SUPPRESSED",
        },
      },
      // as the platform, from the context that sent it
      caller: { platform: true, path: "/agents/one" },
    },
  ]);
  expect(mind.reservations()).toEqual([]);
});

test("a refusal whose fact does not land still reaches the caller as the provider's refusal", async () => {
  const mind = mindWith([{ sent: false, error: "the provider is down" }], { appendFails: true });
  await expect(mind.send()).rejects.toMatchObject({
    code: "UNAVAILABLE",
    message: "itx.email.send: the boundary refused it: the provider is down",
  });
});

test("a mail an approval rule refuses records no send-failed fact: the gate's facts say it", async () => {
  const rejected: GateAnswer = {
    state: "rejected",
    digest: "d".repeat(64),
    facts: [],
    by: "jo@elsewhere.example",
    reason: "no",
  };
  const mind = mindWith([{ sent: false, error: "rejected", gate: rejected }]);
  await expect(mind.send()).rejects.toThrow("rejected");
  expect(mind).toMatchObject({ appended: [] });
});

test("a mail that answers no mail goes as the first hop", async () => {
  const mind = mindWith([{ sent: true, messageId: "<m6@example.com>" }]);
  await mind.send();
  expect(mind.sent).toMatchObject([{ headers: { "X-Iterate-Mail-Hops": "1" } }]);
});

test("an answer in a thread where another mind's mail came at hop 3 goes as hop 4", async () => {
  const mind = mindWith([{ sent: true, messageId: "<m7@example.com>" }], {
    stored: { type: "events.iterate.com/email/received", payload: received({ hops: 3 }) },
    mindHops: 3,
  });
  await mind.answer(7);
  expect(mind.sent).toMatchObject([
    { to: ["agent@other.example"], headers: { "X-Iterate-Mail-Hops": "4" } },
  ]);
});

test("an answer to a person's mail goes as the first hop", async () => {
  const mind = mindWith([{ sent: true, messageId: "<m8@example.com>" }], {
    stored: { type: "events.iterate.com/email/received", payload: received(null) },
  });
  await mind.answer(7);
  expect(mind.sent).toMatchObject([{ headers: { "X-Iterate-Mail-Hops": "1" } }]);
});

test("a mail with no sender is refused, with words that say to give one: a mind has no default sender", async () => {
  const mind = mindWith([{ sent: true, messageId: "<m6@example.com>" }]);
  // the input arrives over the wire, where nothing holds a caller to the type
  const withoutSender = (input: Omit<EmailSendInput, "from">) =>
    mind.root.send(input as EmailSendInput);
  await expect(
    withoutSender({ to: "jo@elsewhere.example", subject: "Hello", text: "A mail." }),
  ).rejects.toMatchObject({
    code: "INVALID_INPUT",
    message: expect.stringContaining("give the sender, `from`"),
  });
  // an answer to a mail names its sender too
  await expect(withoutSender({ inReplyToOffset: 7, text: "An answer." })).rejects.toMatchObject({
    code: "INVALID_INPUT",
  });
  expect({ asked: mind.asked, reserved: mind.reservations() }).toEqual({ asked: [], reserved: [] });
});

test("in one delivery, the same mail from another sender is another mail, and the same sender again is not sent twice", async () => {
  const mind = mindWith([
    { sent: true, messageId: "<m7@example.com>" },
    { sent: true, messageId: "<m8@example.org>" },
  ]);
  const mail = { to: "jo@elsewhere.example", subject: "Hello", text: "A mail." };
  await mind.root.send({ ...mail, from: "billing@example.com" });
  await mind.root.send({ ...mail, from: "support@example.org" });
  // the sender is one address whatever its case: this is the first mail again
  await expect(mind.root.send({ ...mail, from: "Billing@Example.com" })).rejects.toMatchObject({
    code: "PERMANENT_FAILURE",
  });
  expect(mind.sent).toMatchObject([
    { from: { email: "billing@example.com" } },
    { from: { email: "support@example.org" } },
  ]);
});

test("a mail leaves from an address at any zone of the mind, and from no other", () => {
  const config = { zones: ["example.com", "example.org"] };
  expect(senderOf(" Agent@Example.ORG ", config)).toBe("agent@example.org");
  expect(senderOf("agent@example.com", config)).toBe("agent@example.com");
  for (const from of [
    "agent@elsewhere.example",
    "agent@notexample.com",
    "Ada <ada@example.com>",
    "agent@example.com.",
    "a@outside.test@example.org",
    "agent@example.com, eve@example.com",
  ])
    expect(() => senderOf(from, config), from).toThrow("at one of its zones");
});

type Outcome = Awaited<ReturnType<Door["sendEmail"]>>;

const held: Outcome = {
  sent: false,
  error: "it waits",
  gate: { state: "held", digest: "d".repeat(64), facts: [] },
};

/** A mind whose boundary answers `outcomes` in turn. `asked` keeps, for each call of the boundary,
 *  whether it waits and which reservations stand at that moment. `stored` is the event at any
 *  offset that is asked for; the `email` facet puts it in one thread, whose `mindHops` is given. */
function mindWith(
  outcomes: Outcome[],
  options: {
    stored?: { type: string; payload: unknown };
    mindHops?: number;
    appendFails?: boolean;
  } = {},
) {
  const reservations = new Set<string>();
  const appended: { event: unknown; caller: unknown }[] = [];
  const asked: { wait: boolean; reserved: string[] }[] = [];
  const sent: {
    from: { email: string };
    subject: string;
    to: string[];
    headers: Record<string, string>;
  }[] = [];
  const emailContext = {
    reserveSend: async (key: string) => {
      if (reservations.has(key)) return { reserved: false };
      reservations.add(key);
      return { reserved: true };
    },
    releaseSend: async (key: string) => void reservations.delete(key),
    invoke: async (expression: unknown[], _args: unknown[], caller: unknown) => {
      const [verb, event] = [expression.at(-1)].flat();
      if (verb === "append") {
        if (options.appendFails) throw new Error("the log is unreachable");
        appended.push({ event, caller });
        return [{ ...Object(event), offset: 1 }];
      }
      if (verb === "readEvents")
        return { events: [{ offset: Number(event) + 1, ...options.stored }] };
      if (verb === "snapshot")
        return {
          state: {
            threads: {
              "7": { subject: "Hello", messageOffsets: [7], mindHops: options.mindHops },
            },
            threadOffsetByMessageId: {},
          },
        };
      return undefined;
    },
  };
  const context = {
    path: "/agents/one",
    caller: () => ({
      principal: null,
      cause: { chain: "/agents/one#1", depth: 1, at: 0, writeKey: "delivery" },
    }),
    context: () => emailContext,
  };
  const egress = {
    sendEmail: async (message: (typeof sent)[number], options?: { wait?: boolean }) => {
      sent.push(message);
      asked.push({
        wait: Boolean(options?.wait),
        reserved: [...reservations].map((key) => key.replace(/:email\.send:.*/, "-1")),
      });
      return outcomes.shift()!;
    },
  };
  const root = emailRoot(
    // A test's stand-in: `emailRoot` reads only `path`, `caller` and `context` of the root, and
    // `reserveSend`, `releaseSend` and `invoke` of a context.
    context as unknown as ItxHostRootContext & { context: () => ReachableContext },
    {
      // no attachment is named, so no file is read
      files: {} as R2Bucket,
      egress: () => egress,
      config: {
        controlPlaneHostname: "iterate.example.com",
        zones: ["example.com", "example.org"],
      },
    },
  );
  return {
    asked,
    appended,
    reservations: () => [...reservations],
    sent,
    send: (to = "jo@elsewhere.example", subject = "Hello") =>
      root.send({ from: "mind@example.com", to, subject, text: "A mail." }),
    answer: (inReplyToOffset: number) =>
      root.send({ from: "mind@example.com", inReplyToOffset, text: "An answer." }),
    root,
  };
}

/** A mail that reached this mind: another mind's agent's at `mind.hops`, or a person's. */
function received(mind: { hops: number } | null) {
  return {
    messageId: "m0@other.example",
    from: "agent@other.example",
    to: ["mind@example.com"],
    cc: [],
    subject: "Hello",
    text: "A mail.",
    html: null,
    inReplyTo: null,
    references: [],
    attachments: [],
    envelope: { from: "agent@other.example", to: "mind@example.com" },
    sender: { verified: true, member: false, direct: true },
    automated: Boolean(mind),
    authentication: { spf: "pass", dkim: "pass", dmarc: "pass" },
    mind,
  };
}