fix(mail-ingest): enhance header processing to prioritize X-Forwarded-To for IMAP

This commit is contained in:
Luffy
2026-12-04 12:33:17 +08:00
committed by Maurice
parent a4bd40cb0a
commit b15cd49833
5 changed files with 79 additions and 11 deletions
@@ -72,6 +72,7 @@ describe('walkMail: the envelope and the body', () => {
'Authentication-Results: relay.example; dkim=fail',
'Delivered-To: in+token@trek.example',
'X-Original-To: in+token@trek.example',
'x-forwarded-to: Forwarded Recipient <in+token@trek.example>',
'From: =?utf-8?B?QW5hIE3DvGxsZXI=?= <ana@example.org>',
'To: in+token@trek.example',
'Cc: ben@example.org',
@@ -96,6 +97,7 @@ describe('walkMail: the envelope and the body', () => {
messageId: '<abc@example.org>',
deliveredTo: 'in+token@trek.example',
xOriginalTo: 'in+token@trek.example',
xForwardedTo: 'Forwarded Recipient <in+token@trek.example>',
listUnsubscribe: '<https://airline.example/unsubscribe>',
precedence: 'bulk',
autoSubmitted: 'auto-generated',
@@ -112,6 +114,7 @@ describe('walkMail: the envelope and the body', () => {
const walked = walk(mail('From: a@example.org', 'Content-Type: text/plain', '', 'Hotel', ''));
expect(walked.subject).toBeNull();
expect(walked.envelope.to).toBeNull();
expect(walked.envelope.xForwardedTo).toBeNull();
expect(walked.envelope.authenticationResults).toBeNull();
});
});
@@ -52,8 +52,8 @@ afterAll(async () => {
});
const tokenIn = (address: string) => /^trek\+([a-z2-7]+)@/.exec(address)?.[1] ?? '';
function mailTo(address: string, id: string): Buffer {
const lines = ['From: mia@example.com', `To: ${address}`, 'Subject: Booking', `Message-ID: <${id}@x>`];
function mailTo(address: string, id: string, headers: readonly string[] = []): Buffer {
const lines = ['From: mia@example.com', `To: ${address}`, 'Subject: Booking', `Message-ID: <${id}@x>`, ...headers];
return Buffer.from(`${lines.join('\r\n')}\r\n\r\nBooking ABC123`);
}
@@ -151,17 +151,17 @@ describe('a mail to several addresses', () => {
expect(await findRow(orm(), MailIngestMessages, { user: noah.id })).toBeNull();
});
it('reads on to To when the delivery header names the box without its token, as Stalwart writes it', async () => {
it('reads on to To without a delivery token and gives To priority over X-Forwarded-To', async () => {
const { user: mia } = await makeUser(orm());
const { user: noah } = await makeUser(orm());
const miaOwn = (await addresses().renewOwn(mia.id))?.address ?? '';
const noahOwn = (await addresses().renewOwn(noah.id))?.address ?? '';
const box = miaOwn.replace(/\+[^@]+@/, '@');
const headers = [`Delivered-To: ${box}`, `To: <${miaOwn}>`, 'From: x@example.com'];
const raw = Buffer.from(
`${headers.join('\r\n')}\r\nSubject: WG: Booking\r\nMessage-ID: <fwd@x>\r\n\r\nBooking ABC123`,
);
const raw = mailTo(`<${miaOwn}>`, 'fwd', [`Delivered-To: ${box}`, `X-Forwarded-To: ${noahOwn}`]);
expect(await t.get(MailIngestIntakeService).receive(raw, 'imap')).toEqual({ status: 'accepted' });
expect(await findRow(orm(), MailIngestMessages, { user: mia.id })).not.toBeNull();
expect(await findRow(orm(), MailIngestMessages, { user: noah.id })).toBeNull();
const nobody = Buffer.from(`Delivered-To: ${box}\r\nTo: ${box}\r\nSubject: Hi\r\nMessage-ID: <none@x>\r\n\r\nHi`);
expect(await t.get(MailIngestIntakeService).receive(nobody, 'imap')).toEqual({
@@ -169,6 +169,57 @@ describe('a mail to several addresses', () => {
reason: 'unknown_address',
});
});
it('routes IMAP mail to the trip in the topmost X-Forwarded-To when earlier headers do not match', async () => {
const { user: owner } = await makeUser(orm());
const { user: other } = await makeUser(orm());
const trip = await makeTrip(orm(), owner.id);
const tripAddress = await addresses().renewTripAddress(owner.id, trip.id);
const otherAddress = await addresses().renewOwn(other.id);
const box = 'trek@mail.example.com';
const raw = mailTo(box, 'forwarded-trip', [
`Delivered-To: ${box}`,
`X-Original-To: ${box}`,
`X-Forwarded-To: Trip <${tripAddress?.address}>`,
`X-Forwarded-To: ${otherAddress?.address}`,
]);
expect(await t.get(MailIngestIntakeService).receive(raw, 'imap')).toEqual({ status: 'accepted' });
expect(await findRow(orm(), MailIngestMessages, { user: owner.id, trip: trip.id })).not.toBeNull();
expect(await findRow(orm(), MailIngestMessages, { user: other.id })).toBeNull();
});
it('refuses empty, malformed and retired X-Forwarded-To values', async () => {
const { user } = await makeUser(orm());
const retired = await addresses().renewOwn(user.id);
const active = await addresses().renewOwn(user.id);
const box = 'trek@mail.example.com';
const intake = t.get(MailIngestIntakeService);
const samples = [
mailTo(box, 'empty', ['X-Forwarded-To:', `X-Forwarded-To: ${active?.address}`]),
mailTo(box, 'malformed', [`X-Forwarded-To: <${active?.address.split('@')[0]}>`]),
mailTo(box, 'retired', [`X-Forwarded-To: ${retired?.address}`]),
];
const results = await Promise.all(samples.map((raw) => intake.receive(raw, 'imap')));
const refused = { status: 'refused', reason: 'unknown_address' };
expect(results).toEqual([refused, refused, refused]);
expect(await countRows(orm(), MailIngestMessages, {})).toBe(0);
});
it('uses X-Forwarded-To only for IMAP without an envelope recipient', async () => {
const { user } = await makeUser(orm());
const own = await addresses().renewOwn(user.id);
const box = 'trek@mail.example.com';
const raw = mailTo(box, 'forwarded-imap-only', [`X-Forwarded-To: ${own?.address}`]);
const intake = t.get(MailIngestIntakeService);
const refused = { status: 'refused', reason: 'unknown_address' };
expect(await intake.receive(raw, 'webhook')).toEqual(refused);
expect(await intake.receive(raw, 'cloud')).toEqual(refused);
expect(await intake.receive(raw, 'imap', [box])).toEqual(refused);
expect(await countRows(orm(), MailIngestMessages, {})).toBe(0);
});
});
describe('a trip address', () => {