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]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
450d65116f
commit
3563549e86
@@ -1,4 +1,4 @@
|
||||
import type { AddressInfo } from "node:net";
|
||||
import type { AddressInfo, Socket } from "node:net";
|
||||
import { createServer, type Server } from "node:net";
|
||||
import { SMTPServer } from "smtp-server";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
@@ -25,6 +25,8 @@ interface CapturedMessage {
|
||||
readonly from: string;
|
||||
readonly to: readonly string[];
|
||||
readonly data: string;
|
||||
/** The argument this client actually sent in `EHLO`, lowercased by the server. */
|
||||
readonly greetedAs: string;
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
@@ -52,6 +54,14 @@ interface HarnessOptions {
|
||||
readonly rejectRecipients?: readonly string[];
|
||||
/** Advertises STARTTLS. Off by default, so a `starttls` client must refuse to continue. */
|
||||
readonly offerStartTls?: boolean;
|
||||
/**
|
||||
* Refuses any client whose `EHLO` argument is not exactly this name, as a relay that requires a
|
||||
* fully qualified client identity does.
|
||||
*
|
||||
* The refusal is a `421`, the same class of response the real relay returned: a temporary failure
|
||||
* that closes the connection before a message is offered.
|
||||
*/
|
||||
readonly requireGreeting?: string;
|
||||
}
|
||||
|
||||
async function startSmtpServer(options: HarnessOptions = {}): Promise<Harness> {
|
||||
@@ -81,11 +91,26 @@ async function startSmtpServer(options: HarnessOptions = {}): Promise<Harness> {
|
||||
captured.push({
|
||||
data,
|
||||
from: session.envelope.mailFrom === false ? "" : session.envelope.mailFrom.address,
|
||||
greetedAs: session.hostNameAppearsAs,
|
||||
to: session.envelope.rcptTo.map((entry) => entry.address),
|
||||
});
|
||||
callback();
|
||||
});
|
||||
},
|
||||
onMailFrom(_address, session, callback) {
|
||||
if (
|
||||
options.requireGreeting !== undefined &&
|
||||
session.hostNameAppearsAs !== options.requireGreeting.toLowerCase()
|
||||
) {
|
||||
const error = new Error("Try again later, closing connection.") as Error & {
|
||||
responseCode?: number;
|
||||
};
|
||||
error.responseCode = 421;
|
||||
callback(error);
|
||||
return;
|
||||
}
|
||||
callback();
|
||||
},
|
||||
onRcptTo(address, _session, callback) {
|
||||
if (options.rejectRecipients?.includes(address.address)) {
|
||||
// 550 is a permanent refusal of this mailbox, which is what a real relay returns.
|
||||
@@ -107,6 +132,64 @@ async function startSmtpServer(options: HarnessOptions = {}): Promise<Harness> {
|
||||
return { captured, close, port: address.port };
|
||||
}
|
||||
|
||||
/**
|
||||
* A relay that refuses the greeting itself, byte for byte as the real one did.
|
||||
*
|
||||
* `smtp-server` exposes no `EHLO` hook — its earliest usable one is `MAIL FROM`, which
|
||||
* `transporter.verify()` never reaches — so modelling this failure at the point it actually happens
|
||||
* needs a socket that speaks the handful of SMTP verbs involved. That matters: the whole reason the
|
||||
* defect was hard to diagnose is that it aborts the session *before* a message is offered, which is
|
||||
* also why Doctor's send-nothing probe can see it.
|
||||
*/
|
||||
async function startGreetingStrictRelay(expected: string): Promise<Harness> {
|
||||
const sockets = new Set<Socket>();
|
||||
const server = createServer((socket) => {
|
||||
sockets.add(socket);
|
||||
socket.on("close", () => sockets.delete(socket));
|
||||
socket.on("error", () => undefined);
|
||||
socket.write("220 relay.invalid ESMTP\r\n");
|
||||
let buffer = "";
|
||||
socket.on("data", (chunk: Buffer) => {
|
||||
buffer += chunk.toString("utf8");
|
||||
let index = buffer.indexOf("\r\n");
|
||||
while (index !== -1) {
|
||||
const line = buffer.slice(0, index);
|
||||
buffer = buffer.slice(index + 2);
|
||||
const [verb = "", argument = ""] = line.split(" ");
|
||||
if (verb.toUpperCase() === "EHLO" || verb.toUpperCase() === "HELO") {
|
||||
if (argument.toLowerCase() !== expected.toLowerCase()) {
|
||||
// The exact shape the deployment saw: a 421 naming no reason, then the door shut.
|
||||
socket.write("421-4.7.0 Try again later, closing connection. (EHLO)\r\n");
|
||||
socket.write("421 4.7.0 Goodbye\r\n");
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
socket.write("250-relay.invalid\r\n250 OK\r\n");
|
||||
} else if (verb.toUpperCase() === "QUIT") {
|
||||
socket.write("221 Bye\r\n");
|
||||
socket.end();
|
||||
return;
|
||||
} else {
|
||||
socket.write("250 OK\r\n");
|
||||
}
|
||||
index = buffer.indexOf("\r\n");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address() as AddressInfo;
|
||||
const close = async (): Promise<void> => {
|
||||
// `close()` waits for open sockets, and a refused client may still be holding one.
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
};
|
||||
openHarnesses.push(close);
|
||||
return { captured: [], close, port: address.port };
|
||||
}
|
||||
|
||||
function config(port: number, overrides: Record<string, unknown> = {}): MailProviderConfig {
|
||||
const built = createMailProviderConfig(
|
||||
{
|
||||
@@ -355,3 +438,94 @@ describe.sequential("live SMTP transport", () => {
|
||||
expect(harness.captured).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("SMTP client identity on the wire", () => {
|
||||
/**
|
||||
* The regression guard for a real production defect.
|
||||
*
|
||||
* A deployment relaying through an IP-authorized relay could not send at all: every attempt
|
||||
* surfaced as `MAIL_PROVIDER_UNAVAILABLE`. The relay was healthy — `swaks` sent from the same
|
||||
* machine — and the cause was the greeting. 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. The relay closed the
|
||||
* connection on it with a `421`.
|
||||
*
|
||||
* These tests are written against the wire rather than against the transport options, because the
|
||||
* defect was invisible in the options: everything about the configuration looked correct.
|
||||
*/
|
||||
it("greets with the configured name, exactly as configured", async () => {
|
||||
const harness = await startSmtpServer();
|
||||
const mail = provider(config(harness.port, { heloName: "mail.example.org" }));
|
||||
|
||||
await mail.send(
|
||||
validateMailMessage({ subject: "Greeting", text: "Body.", to: "[email protected]" }),
|
||||
);
|
||||
|
||||
expect(harness.captured[0]?.greetedAs).toBe("mail.example.org");
|
||||
});
|
||||
|
||||
it("never greets as the address literal when a name is configured", async () => {
|
||||
const harness = await startSmtpServer();
|
||||
const mail = provider(config(harness.port, { heloName: "mail.example.org" }));
|
||||
|
||||
await mail.send(
|
||||
validateMailMessage({ subject: "Greeting", text: "Body.", to: "[email protected]" }),
|
||||
);
|
||||
|
||||
// The exact greeting the relay refused.
|
||||
expect(harness.captured[0]?.greetedAs).not.toBe("[127.0.0.1]");
|
||||
});
|
||||
|
||||
it("delivers to a relay that demands a fully qualified greeting", async () => {
|
||||
const harness = await startSmtpServer({ requireGreeting: "mail.example.org" });
|
||||
const mail = provider(config(harness.port, { heloName: "mail.example.org" }));
|
||||
|
||||
await mail.send(
|
||||
validateMailMessage({ subject: "Accepted", text: "Body.", to: "[email protected]" }),
|
||||
);
|
||||
|
||||
expect(harness.captured).toHaveLength(1);
|
||||
expect(harness.captured[0]?.greetedAs).toBe("mail.example.org");
|
||||
});
|
||||
|
||||
it("is refused by that same relay when no name is configured", async () => {
|
||||
const harness = await startGreetingStrictRelay("mail.example.org");
|
||||
const mail = provider(config(harness.port));
|
||||
|
||||
// Deterministic regardless of what this machine is called: the server accepts exactly one name,
|
||||
// and Nodemailer's derivation cannot produce `mail.example.org` on any host.
|
||||
await expect(
|
||||
mail.send(validateMailMessage({ subject: "Refused", text: "Body.", to: "[email protected]" })),
|
||||
).rejects.toMatchObject({ code: "MAIL_PROVIDER_UNAVAILABLE" });
|
||||
expect(harness.captured).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("carries the refused greeting into no error a caller can see", async () => {
|
||||
const harness = await startGreetingStrictRelay("mail.example.org");
|
||||
const mail = provider(config(harness.port));
|
||||
|
||||
const failure = await mail
|
||||
.send(validateMailMessage({ subject: "Refused", text: "Body.", to: "[email protected]" }))
|
||||
.catch((error: unknown) => error);
|
||||
|
||||
// A `421` is SMTP's "try later", so it stays `MAIL_PROVIDER_UNAVAILABLE` rather than becoming a
|
||||
// permanent rejection — and the server's response text never reaches the caller.
|
||||
const serialized = `${(failure as Error).message} ${(failure as Error).stack ?? ""}`;
|
||||
expect(serialized).not.toContain("Try again later");
|
||||
expect(serialized).not.toContain("closing connection");
|
||||
});
|
||||
|
||||
it("still verifies through the same greeting Doctor's probe will use", async () => {
|
||||
const harness = await startGreetingStrictRelay("mail.example.org");
|
||||
const configured = provider(config(harness.port, { heloName: "mail.example.org" }));
|
||||
const unconfigured = provider(config(harness.port));
|
||||
|
||||
// Doctor builds its provider from the identical validated configuration, so an operator whose
|
||||
// relay refuses the greeting sees it in `pnpm doctor` rather than only when a reset email
|
||||
// silently fails to arrive.
|
||||
await expect(configured.verify()).resolves.toBeUndefined();
|
||||
await expect(unconfigured.verify()).rejects.toMatchObject({
|
||||
code: "MAIL_PROVIDER_UNAVAILABLE",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user