Files
Ekklesia/core/tests/mail-contract.test.ts
T
ekklesiaandClaude Opus 5 3563549e86
CI / verify (pull_request) Successful in 42s
CI / infrastructure-smoke (pull_request) Successful in 20s
CI / migration-smoke (pull_request) Successful in 1m41s
fix: let a deployment name itself in the SMTP greeting
A real deployment could not send mail through an IP-authorized relay.
Every attempt surfaced as MAIL_PROVIDER_UNAVAILABLE while the relay was
healthy and swaks sent from the same machine.

The cause was the greeting, and it is generic rather than tied to any
provider. An SMTP client identifies itself in EHLO, and with nothing
configured Nodemailer derives that from the machine hostname —
substituting the address literal [127.0.0.1] whenever the hostname is
not fully qualified, which is the normal state of a container. The relay
closed the connection on it with a 421 before any message was offered,
which is indistinguishable from the relay being down.

EKKLESIA_SMTP_HELO_NAME now lets the deployment say what to greet as. It
is validated as a fully qualified domain name — no scheme, port,
brackets, whitespace, or control characters, and at least one dot, since
a single unqualified label is exactly the input Nodemailer already
discards. It is not a credential: it travels in the clear on every
connection, so Doctor prints it where an operator can compare it against
what the relay expects, and Doctor's probe performs the same greeting the
runtime does.

Absent preserves Nodemailer's behaviour exactly. It is deliberately not
defaulted to the sender's domain: a machine whose hostname is already a
valid FQDN may be greeting correctly, and some relays check that against
reverse DNS, so replacing it silently would trade one deployment's bug
for another's.

The regression guard is a raw SMTP server that refuses any greeting but
the expected one, because smtp-server exposes no EHLO hook and its
earliest hook is never reached by a send-nothing probe.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-25 20:28:30 -05:00

438 lines
17 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
createMailProviderConfig,
describeMailProvider,
MailConfigError,
} from "../src/mail/config.js";
import {
MAIL_MAX_HTML_BYTES,
MAIL_MAX_RECIPIENTS,
MAIL_MAX_SUBJECT_LENGTH,
MAIL_MAX_TEXT_BYTES,
MailError,
validateMailMessage,
} from "../src/mail/message.js";
/**
* The mail contract's boundary, with no provider and no network.
*
* Most of these are negative: the contract's job is to make an impossible message impossible to
* construct, so what it *refuses* is the interesting part (ADR 0037).
*/
const password = "sup3r-secret-relay-password";
const validConfig = {
fromAddress: "[email protected]",
fromName: "Ekklesia",
host: "smtp.example.org",
security: "starttls",
};
describe("host mail configuration", () => {
it("treats an absent host as an installation that sends no email", () => {
// The whole platform must still start. Nothing sends mail yet, so this is a complete deployment.
expect(createMailProviderConfig(undefined)).toBeUndefined();
expect(createMailProviderConfig({})).toBeUndefined();
expect(createMailProviderConfig({ host: " " })).toBeUndefined();
});
it("accepts a relay with no credentials, which is how Google Workspace is usually deployed", () => {
const config = createMailProviderConfig(validConfig);
// Requiring a username and password — as most SMTP examples do — would make the intended
// production arrangement, a relay authorized by source IP, unconfigurable.
expect(config).toEqual({
fromAddress: "[email protected]",
fromName: "Ekklesia",
host: "smtp.example.org",
port: 587,
security: "starttls",
});
expect(config?.username).toBeUndefined();
expect(config?.password).toBeUndefined();
});
it("defaults the port per security mode, and defaults the mode to an encrypted one", () => {
expect(createMailProviderConfig({ ...validConfig, security: undefined })?.security).toBe(
"starttls",
);
expect(createMailProviderConfig({ ...validConfig, security: "implicit-tls" })?.port).toBe(465);
expect(createMailProviderConfig({ ...validConfig, security: "starttls" })?.port).toBe(587);
expect(createMailProviderConfig({ ...validConfig, port: "2525" })?.port).toBe(2525);
});
it("refuses half a credential pair in either direction", () => {
expect(() =>
createMailProviderConfig({ ...validConfig, username: "[email protected]" }),
).toThrow(expect.objectContaining({ code: "MAIL_USERNAME_WITHOUT_PASSWORD" }));
expect(() => createMailProviderConfig({ ...validConfig, password })).toThrow(
expect.objectContaining({ code: "MAIL_PASSWORD_WITHOUT_USERNAME" }),
);
// Both together is the authenticated case and is accepted.
expect(
createMailProviderConfig({ ...validConfig, password, username: "[email protected]" })
?.username,
).toBe("[email protected]");
});
it.each([
["a scheme", "smtp://smtp.example.org"],
["a port", "smtp.example.org:587"],
["credentials", "user:[email protected]"],
["a path", "smtp.example.org/relay"],
["a space", "smtp example org"],
["nothing but dots", "..."],
])("refuses an SMTP host containing %s", (_label, host) => {
// A host is a hostname, never a connection string — a connection string is how a password ends
// up in a log.
expect(() => createMailProviderConfig({ ...validConfig, host })).toThrow(
expect.objectContaining({ code: "MAIL_HOST_INVALID" }),
);
});
it.each([
["0"],
["65536"],
["-1"],
["587.5"],
["not-a-port"],
])("refuses the malformed port %s", (port) => {
expect(() => createMailProviderConfig({ ...validConfig, port })).toThrow(
expect.objectContaining({ code: "MAIL_PORT_INVALID" }),
);
});
it("treats an empty port as unset rather than malformed", () => {
expect(createMailProviderConfig({ ...validConfig, port: "" })?.port).toBe(587);
});
it("refuses an unknown security mode rather than guessing one", () => {
for (const security of ["tls", "ssl", "none", "STARTTLS", "true"]) {
expect(() => createMailProviderConfig({ ...validConfig, security }), security).toThrow(
expect.objectContaining({ code: "MAIL_SECURITY_INVALID" }),
);
}
});
it("refuses plaintext SMTP in production but allows it in development", () => {
expect(() =>
createMailProviderConfig(
{ ...validConfig, security: "plaintext" },
{ environment: "production" },
),
).toThrow(expect.objectContaining({ code: "MAIL_SECURITY_INSECURE_IN_PRODUCTION" }));
expect(
createMailProviderConfig(
{ ...validConfig, security: "plaintext" },
{ environment: "development" },
)?.security,
).toBe("plaintext");
});
it("requires a valid sender address and refuses an injectable display name", () => {
expect(() => createMailProviderConfig({ ...validConfig, fromAddress: undefined })).toThrow(
expect.objectContaining({ code: "MAIL_FROM_ADDRESS_MISSING" }),
);
for (const fromAddress of [
"not-an-address",
"a@b",
"a@@b.org",
"a [email protected]",
"<[email protected]>",
]) {
expect(() => createMailProviderConfig({ ...validConfig, fromAddress }), fromAddress).toThrow(
expect.objectContaining({ code: "MAIL_FROM_ADDRESS_INVALID" }),
);
}
for (const fromName of ['Ekklesia"', "Ekklesia\\", "Ekklesia\r\nBcc: [email protected]"]) {
expect(() => createMailProviderConfig({ ...validConfig, fromName })).toThrow(
expect.objectContaining({ code: "MAIL_FROM_NAME_INVALID" }),
);
}
});
it("never puts a credential into a configuration error or a description", () => {
const configured = createMailProviderConfig({
...validConfig,
password,
username: "[email protected]",
});
if (!configured) {
throw new Error("The mail configuration fixture produced no configuration.");
}
const described = describeMailProvider(configured);
// An operator sees where mail goes and whether it authenticates — never with what.
expect(described).toContain("smtp.example.org:587");
expect(described).toContain("starttls");
expect(described).toContain("[email protected]");
expect(described).toContain("authenticated");
expect(described).not.toContain(password);
expect(described).not.toContain("[email protected]");
const unauthenticated = createMailProviderConfig(validConfig);
if (!unauthenticated) {
throw new Error("The mail configuration fixture produced no configuration.");
}
expect(describeMailProvider(unauthenticated)).toContain("unauthenticated relay");
let caught: unknown;
try {
createMailProviderConfig({
...validConfig,
host: "smtp://bad",
password,
username: "[email protected]",
});
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(MailConfigError);
const rendered = `${String(caught)} ${JSON.stringify(caught)} ${(caught as Error).stack ?? ""}`;
expect(rendered).not.toContain(password);
expect(rendered).not.toContain("smtp://bad");
});
});
describe("SMTP client identity (HELO name)", () => {
/**
* A real deployment defect, and a generic one.
*
* An SMTP client must greet the server with its own identity. Nodemailer derives that from the
* machine hostname and falls back to the address literal `[127.0.0.1]` when the hostname is not
* fully qualified — the normal state of a container. Some relays close the connection on that
* greeting with a `421` before any message is offered, which reaches a caller as an
* indistinguishable `MAIL_PROVIDER_UNAVAILABLE`. The deployment can now say what to greet as.
*/
it("omits the setting entirely when the deployment configures none", () => {
const config = createMailProviderConfig(validConfig);
// Absent means Nodemailer's own derivation, unchanged. The key is not present at all rather
// than present-and-undefined, so nothing downstream can mistake it for a configured empty name.
expect(config).not.toHaveProperty("heloName");
expect(createMailProviderConfig({ ...validConfig, heloName: "" })).not.toHaveProperty(
"heloName",
);
expect(createMailProviderConfig({ ...validConfig, heloName: undefined })).not.toHaveProperty(
"heloName",
);
});
it.each([
["a two-label domain", "example.org"],
["a subdomain", "mail.example.org"],
["a deep subdomain", "smtp.relay.mail.example.org"],
["hyphens inside labels", "out-bound.example-church.org"],
["digits", "mx1.example2.org"],
["mixed case", "Mail.Example.ORG"],
])("accepts %s", (_label, heloName) => {
expect(createMailProviderConfig({ ...validConfig, heloName })).toMatchObject({ heloName });
});
it.each([
["a scheme", "smtp://example.org"],
["a port", "example.org:587"],
["a path", "example.org/relay"],
["a space", "example org"],
["a leading space", " example.org"],
["a trailing space", "example.org "],
["a carriage return", "example.org\r"],
["a line feed", "example.org\nEHLO evil.example.net"],
["a tab", "example.org\t"],
["a comma", "example.org,evil.example.net"],
["an unqualified single label", "localhost"],
["a machine name with no domain", "ekklesia-host"],
["a bracketed address literal", "[127.0.0.1]"],
["a bare IPv4 address", "192.0.2.1"],
["a trailing dot", "example.org."],
["a leading dot", ".example.org"],
["consecutive dots", "example..org"],
["a leading hyphen in a label", "-example.org"],
["a trailing hyphen in a label", "example-.org"],
["an email address", "[email protected]"],
["prose", "our church mail server"],
["nothing but dots", "..."],
["an over-long name", `${"a".repeat(250)}.example.org`],
])("refuses %s", (_label, heloName) => {
expect(() => createMailProviderConfig({ ...validConfig, heloName })).toThrow(
expect.objectContaining({ code: "MAIL_HELO_NAME_INVALID" }),
);
});
it("refuses an unqualified name, because that is the input the fallback already rejects", () => {
// Configuring a single label would reproduce the very failure this setting exists to fix:
// Nodemailer discards a non-FQDN hostname and substitutes the address literal.
expect(() => createMailProviderConfig({ ...validConfig, heloName: "ekklesia" })).toThrow(
MailConfigError,
);
});
it("never carries the offending value in the error", () => {
try {
createMailProviderConfig({ ...validConfig, heloName: "smtp://secret-internal-name:2525" });
throw new Error("expected a refusal");
} catch (error) {
const serialized = `${(error as Error).message} ${(error as Error).stack ?? ""}`;
expect(serialized).not.toContain("secret-internal-name");
expect(serialized).not.toContain("2525");
}
});
it("is described to an operator, because it is infrastructure rather than a credential", () => {
const described = describeMailProvider(
createMailProviderConfig({
...validConfig,
heloName: "mail.example.org",
password,
username: "[email protected]",
}) as Parameters<typeof describeMailProvider>[0],
);
// It is announced in the clear on every connection, so printing it leaks nothing — and it is
// exactly what an operator needs when a relay has refused the greeting.
expect(described).toContain("HELO mail.example.org");
expect(described).not.toContain(password);
expect(described).not.toContain("[email protected]");
});
it("says nothing about a HELO name when none is configured", () => {
const described = describeMailProvider(
createMailProviderConfig(validConfig) as Parameters<typeof describeMailProvider>[0],
);
expect(described).not.toContain("HELO");
});
});
describe("transactional message validation", () => {
const message = {
subject: "Verify your email address",
text: "Open the link to continue.",
to: "[email protected]",
};
it("accepts one recipient and normalizes it to a list", () => {
expect(validateMailMessage(message)).toEqual({
subject: "Verify your email address",
text: "Open the link to continue.",
to: ["[email protected]"],
});
});
it("has no sender field at all, so no caller can choose one", () => {
const validated = validateMailMessage({ ...message, html: "<p>Hi</p>", replyTo: "[email protected]" });
// The load-bearing structural fact: the sender comes from host configuration and there is
// nowhere in a message to put one.
expect(Object.keys(validated).sort()).toEqual(["html", "replyTo", "subject", "text", "to"]);
expect(validated).not.toHaveProperty("from");
});
it.each([
["a display name", "Person <[email protected]>"],
["a second address", "[email protected], [email protected]"],
["a semicolon list", "[email protected];[email protected]"],
["a line feed", "[email protected]\nBcc: [email protected]"],
["a carriage return", "[email protected]\r"],
["no domain dot", "person@localhost"],
["no local part", "@example.org"],
["nothing", ""],
])("refuses a recipient containing %s", (_label, to) => {
expect(() => validateMailMessage({ ...message, to })).toThrow(
expect.objectContaining({ code: "MAIL_RECIPIENT_INVALID" }),
);
});
it("bounds the recipient list and refuses duplicates", () => {
const many = Array.from(
{ length: MAIL_MAX_RECIPIENTS + 1 },
(_value, index) => `person${index}@example.org`,
);
expect(() => validateMailMessage({ ...message, to: many })).toThrow(
expect.objectContaining({ code: "MAIL_RECIPIENT_INVALID" }),
);
expect(() => validateMailMessage({ ...message, to: [] })).toThrow(
expect.objectContaining({ code: "MAIL_RECIPIENT_INVALID" }),
);
// Case-insensitively: the same mailbox twice would send one person two copies.
expect(() =>
validateMailMessage({ ...message, to: ["[email protected]", "[email protected]"] }),
).toThrow(expect.objectContaining({ code: "MAIL_RECIPIENT_INVALID" }));
expect(
validateMailMessage({ ...message, to: many.slice(0, MAIL_MAX_RECIPIENTS) }).to,
).toHaveLength(MAIL_MAX_RECIPIENTS);
});
it("refuses a subject carrying a header break or no content", () => {
for (const subject of [
"Reset\r\nBcc: [email protected]",
"Reset\nX-Injected: 1",
" ",
"",
]) {
expect(() => validateMailMessage({ ...message, subject })).toThrow(
expect.objectContaining({ code: "MAIL_MESSAGE_INVALID" }),
);
}
});
it("bounds the subject and both bodies", () => {
expect(() =>
validateMailMessage({ ...message, subject: "x".repeat(MAIL_MAX_SUBJECT_LENGTH + 1) }),
).toThrow(expect.objectContaining({ code: "MAIL_MESSAGE_INVALID" }));
expect(() =>
validateMailMessage({ ...message, text: "x".repeat(MAIL_MAX_TEXT_BYTES + 1) }),
).toThrow(expect.objectContaining({ code: "MAIL_MESSAGE_INVALID" }));
expect(() =>
validateMailMessage({
html: "x".repeat(MAIL_MAX_HTML_BYTES + 1),
subject: message.subject,
to: message.to,
}),
).toThrow(expect.objectContaining({ code: "MAIL_MESSAGE_INVALID" }));
// Exactly at the bound is accepted, so the limit is the limit.
expect(
validateMailMessage({ ...message, subject: "x".repeat(MAIL_MAX_SUBJECT_LENGTH) }).subject,
).toHaveLength(MAIL_MAX_SUBJECT_LENGTH);
});
it("requires at least one body, and accepts either alone", () => {
expect(() => validateMailMessage({ subject: message.subject, to: message.to })).toThrow(
expect.objectContaining({ code: "MAIL_MESSAGE_INVALID" }),
);
expect(() => validateMailMessage({ ...message, text: "" })).toThrow(
expect.objectContaining({ code: "MAIL_MESSAGE_INVALID" }),
);
expect(
validateMailMessage({ html: "<p>Hi</p>", subject: message.subject, to: message.to }).html,
).toBe("<p>Hi</p>");
});
it("refuses an injectable reply-to", () => {
expect(() =>
validateMailMessage({
...message,
replyTo: "[email protected]\r\nBcc: [email protected]",
}),
).toThrow(expect.objectContaining({ code: "MAIL_MESSAGE_INVALID" }));
expect(validateMailMessage({ ...message, replyTo: "[email protected]" }).replyTo).toBe(
"[email protected]",
);
});
it("never echoes the message into the error", () => {
let caught: unknown;
try {
validateMailMessage({
...message,
subject: `secret-${password}` + "\r\nBcc: [email protected]",
});
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(MailError);
const rendered = `${String(caught)} ${JSON.stringify(caught)} ${(caught as Error).stack ?? ""}`;
expect(rendered).not.toContain(password);
expect(rendered).not.toContain("[email protected]");
});
});