Email for professionals and teams
fix(inbound): key stored raw on a content hash, not the sender's Message-ID
Hieu Nguyen (Jack)9d556920993b
diff --git a/src/lib/email/inbound-id.ts b/src/lib/email/inbound-id.tsindex 1ce95d2..0d26ed0 100644--- a/src/lib/email/inbound-id.ts+++ b/src/lib/email/inbound-id.ts@@ -18,41 +18,14 @@ async function sha256Hex(parts: (string | Uint8Array)[]): Promise<string> {}/**- * Reads the RFC 5322 `Message-ID` header from a raw message without a full MIME- * parse. The header name is case-insensitive and folded continuation lines are- * unfolded. Returns null when the header is absent.- */-export function extractMessageIdHeader(raw: ArrayBuffer): string | null {- const bytes = new Uint8Array(raw);- let headerEnd = bytes.length;- for (let i = 0; i + 1 < bytes.length; i++) {- if (bytes[i] === 0x0a && bytes[i + 1] === 0x0a) {- headerEnd = i + 1;- break;- }- if (bytes[i] === 0x0d && bytes[i + 1] === 0x0a && i + 3 < bytes.length && bytes[i + 2] === 0x0d && bytes[i + 3] === 0x0a) {- headerEnd = i + 2;- break;- }- }- const headerBlock = new TextDecoder("latin1").decode(bytes.subarray(0, headerEnd));- const unfolded = headerBlock.replace(/\r?\n[ \t]/g, " ");- for (const line of unfolded.split("\n")) {- const match = line.replace(/\r$/, "").match(/^message-id:[ \t]*(.*)$/i);- if (match) return match[1].trim();- }- return null;-}--/**- * Deterministic storage key for an inbound message. A relay retry delivers the- * same RFC `Message-ID`, so keying on it (scoped by mailbox) makes a retry- * overwrite the same object; the inbound queue consumer already dedupes by- * `(mailboxId, rawR2Key)`. Messages without a `Message-ID` fall back to a- * content hash so identical deliveries are still idempotent.+ * Deterministic storage key for an inbound message, derived from the mailbox+ * and the raw bytes. A relay retry replays identical bytes, so it overwrites+ * the same object and the inbound queue consumer, which dedupes by+ * `(mailboxId, rawR2Key)`, skips it. Sender-controlled headers such as+ * `Message-ID` are deliberately not part of the key: a third party who knows+ * a message's `Message-ID` could otherwise overwrite its stored raw MIME or+ * make the real delivery look like a duplicate.*/export async function inboundStorageKey(raw: ArrayBuffer, mailboxId?: string): Promise<string> {- const messageId = extractMessageIdHeader(raw);- if (messageId) return `inbound/${await sha256Hex([mailboxId ?? "", messageId])}.eml`;- return `inbound/${await sha256Hex([mailboxId ?? "", new Uint8Array(raw)])}.eml`;+ return `inbound/${await sha256Hex([mailboxId ?? "", "\0", new Uint8Array(raw)])}.eml`;}diff --git a/src/lib/email/intake.ts b/src/lib/email/intake.tsindex be0f320..76a2cf2 100644--- a/src/lib/email/intake.ts+++ b/src/lib/email/intake.ts@@ -32,9 +32,8 @@ export async function intakeIncomingMail(env: CloudflareEnv, input: IntakeInput,if (destination) await actions.forward?.(destination, { [MAILFLARE_FORWARDED_HEADER]: "1" });}- // A relay retry replays the same message, so key the object on its RFC- // Message-ID (scoped by mailbox) instead of a fresh timestamp: the consumer- // dedupes by `(mailboxId, rawR2Key)`, making a retried delivery idempotent.+ // A relay retry replays the same bytes, so key the object on a content hash+ // (scoped by mailbox): the consumer dedupes by `(mailboxId, rawR2Key)`.const rawR2Key = await inboundStorageKey(input.raw, decision?.mailbox?.mailboxId);await env.BUCKET.put(rawR2Key, input.raw, {httpMetadata: { contentType: "message/rfc822" },diff --git a/tests/inbound-key.test.mjs b/tests/inbound-key.test.mjsindex a2d644c..2b10d66 100644--- a/tests/inbound-key.test.mjs+++ b/tests/inbound-key.test.mjs@@ -13,7 +13,7 @@ after(() => rmSync(outDir, { recursive: true, force: true }));await build({stdin: {- contents: `export { extractMessageIdHeader, inboundMessageId, inboundStorageKey } from "./src/lib/email/inbound-id.ts";`,+ contents: `export { inboundMessageId, inboundStorageKey } from "./src/lib/email/inbound-id.ts";`,resolveDir: root,sourcefile: "inbound-key-test-entry.js",},@@ -26,52 +26,32 @@ await build({logLevel: "silent",});-const { extractMessageIdHeader, inboundMessageId, inboundStorageKey } = await import(pathToFileURL(join(outDir, "inbound-key.mjs")).href);+const { inboundMessageId, inboundStorageKey } = await import(pathToFileURL(join(outDir, "inbound-key.mjs")).href);-function raw(headers) {- return new TextEncoder().encode(`${headers}\r\n\r\nBody.\r\n`).buffer;+function raw(headers, body = "Body.") {+ return new TextEncoder().encode(`${headers}\r\n\r\n${body}\r\n`).buffer;}-test("extractMessageIdHeader reads a case-insensitive Message-ID", () => {- assert.equal(extractMessageIdHeader(raw("From: a@b\r\nmessage-id: <[email protected]>\r\nSubject: hi")), "<[email protected]>");-});--test("extractMessageIdHeader unfolds a folded Message-ID", () => {- assert.equal(extractMessageIdHeader(raw("Message-ID: <abc\r\n @example.com>")), "<abc @example.com>");-});--test("extractMessageIdHeader returns null when absent", () => {- assert.equal(extractMessageIdHeader(raw("From: a@b\r\nSubject: hi")), null);-});--test("inboundStorageKey is stable for the same mailbox and Message-ID", async () => {+test("inboundStorageKey is stable for identical bytes in the same mailbox", async () => {const a = await inboundStorageKey(raw("Message-ID: <x@y>"), "mb1");const b = await inboundStorageKey(raw("Message-ID: <x@y>"), "mb1");assert.equal(a, b);assert.match(a, /^inbound\/[0-9a-f]{64}\.eml$/);});-test("inboundStorageKey differs per mailbox for the same Message-ID", async () => {+test("inboundStorageKey differs per mailbox for identical bytes", async () => {const a = await inboundStorageKey(raw("Message-ID: <x@y>"), "mb1");const b = await inboundStorageKey(raw("Message-ID: <x@y>"), "mb2");assert.notEqual(a, b);});-test("inboundStorageKey differs for different Message-IDs", async () => {- const a = await inboundStorageKey(raw("Message-ID: <x@y>"), "mb1");- const b = await inboundStorageKey(raw("Message-ID: <z@y>"), "mb1");- assert.notEqual(a, b);-});--test("inboundStorageKey falls back to a content hash when Message-ID is absent", async () => {- const a = await inboundStorageKey(raw("From: a@b\r\nSubject: hi"), "mb1");- const b = await inboundStorageKey(raw("From: a@b\r\nSubject: hi"), "mb1");- assert.equal(a, b);- const c = await inboundStorageKey(raw("From: a@b\r\nSubject: bye"), "mb1");- assert.notEqual(a, c);+test("a forged message reusing a Message-ID cannot land on the original's key", async () => {+ const real = await inboundStorageKey(raw("Message-ID: <x@y>", "real"), "mb1");+ const forged = await inboundStorageKey(raw("Message-ID: <x@y>", "forged"), "mb1");+ assert.notEqual(real, forged);});-test("inboundMessageId still derives a stable id from the key", async () => {+test("inboundMessageId derives a stable id from the key", async () => {const key = await inboundStorageKey(raw("Message-ID: <x@y>"), "mb1");assert.equal(await inboundMessageId(key), await inboundMessageId(key));});