Mail relay: review of 7d766b6 — R-1 to R-12, four mutations, two sentences

- R-1 a delivered token becomes the one in use only on 200 or a refusal given after authentication
- R-2 a token of another site is refused by what /v1/status says (access-key field, scripts); docs for staging
- R-3 the confirm route looks the nonce up first and counts only refused calls
- R-4 one budget of time per message (10 s, 30 s with files), enrolment and retries included
- R-5 'Disconnect' without the service's answer is not confirmed and keeps the token to try again
- R-6 no enrolment without the confirm route in the config
- R-7 half an SMTP set-up: one log line and a hint in the panel
- R-8 to R-10, R-12 docs; R-11 the last failure stays in the state block
- tests for redirect: manual, the candidate's nonce, the expectation taken back, one recipient only

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 22:07:10 +01:00
co-authored by Claude Fable 5.2
parent 0ee74ab2a4
commit a2b07b1dc1
23 changed files with 584 additions and 69 deletions
+256 -3
View File
@@ -11,14 +11,16 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { buildSmtpFields } from '../src/globals/SiteIntegrations/fields/smtp.js'
import { adminTexts } from '../src/modules/admin-i18n/index.js'
import { mailAdapter, resetGraphDeprecationWarning, resolveMailTransport } from '../src/modules/email/mailAdapter.js'
import { withAccountMailMark } from '../src/modules/email/relay/accountMail.js'
import { relayAdapter } from '../src/modules/email/relay/adapter.js'
import { RELAY_SHORT_NAME } from '../src/modules/email/relay/constants.js'
import { withMailKind } from '../src/modules/email/relay/kinds.js'
import { relayRequest } from '../src/modules/email/relay/client.js'
import { RELAY_DEFAULTS, RELAY_SHORT_NAME } from '../src/modules/email/relay/constants.js'
import { dropExpectedMail, expectMailTo, takeExpectedMail, withMailKind } from '../src/modules/email/relay/kinds.js'
import { bareAddresses, buildRelayMessage, cleanSubject } from '../src/modules/email/relay/message.js'
import { isPublicHost, relayHost, resolveRelayOptions } from '../src/modules/email/relay/options.js'
import { mailPanelState } from '../src/modules/email/relay/panel.js'
import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.js'
import { disconnectRelay, enrolRelay, getRelayStatus, refreshRelayStatus, rotateRelayToken, setRelayToken } from '../src/modules/email/relay/session.js'
import { disconnectRelay, enrolRelay, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken } from '../src/modules/email/relay/session.js'
import { holdNonce, readRelayCandidate, readRelayStore, updateRelayStore } from '../src/modules/email/relay/store.js'
import { setRateLimitStore } from '../src/modules/shared/rateLimit.js'
import { callConfirmRoute, relayPayload, relaySite } from './mailRelay/helpers.js'
@@ -708,6 +710,257 @@ describe('the token over time', () => {
})
})
describe('review of 7d766b6: R-1 to R-7, R-11, and four mutations it found uncaught', () => {
const html = (status: number) => new Response('<html></html>', { headers: { 'content-type': 'text/html' }, status })
const refusalOf = (status: number, code: string, retryable = false) => Response.json({ code, message: 'x', ok: false, retryable }, { status })
/** A site with a working token and, beside it, a token the service never made valid. */
const withBadCandidate = async (own: Parameters<typeof relaySite>[0] = {}) => {
const site = relaySite({ fake: { allow: [HOST] }, ...own })
expect((await enrolRelay(site.payload, site.options, { force: true })).ok).toBe(true)
const working = (await readRelayStore(site.payload)).token!
const nonce = `bad${'c'.repeat(40)}`
await holdNonce(site.payload, nonce, 60_000)
await callConfirmRoute(site.payload)(`https://${HOST}/api/iapl/mail-relay/confirm`, { body: JSON.stringify({ nonce, state: 'active', token: `ims_${'z'.repeat(43)}` }), headers: {} })
expect((await readRelayCandidate(site.payload))?.token).toBe(`ims_${'z'.repeat(43)}`)
return { ...site, working }
}
describe('R-1: a delivered token never replaces a working one before the service has accepted it', () => {
const silent: Array<[string, () => 'drop' | Response]> = [
['an error page (502)', () => html(502)],
['no answer', () => 'drop'],
['429 rate-limited (the gate in front of the token check)', () => refusalOf(429, 'rate-limited', true)],
['403 browser-not-allowed', () => refusalOf(403, 'browser-not-allowed')],
['503 unavailable', () => refusalOf(503, 'unavailable', true)],
['400 invalid-request', () => refusalOf(400, 'invalid-request')],
]
for (const enrol of ['auto', 'manual'] as const) {
test.each(silent)(`enrol: '${enrol}', first answer %s: the working token is kept, and the next send goes out with it`, async (_name, first) => {
const { fake, options, payload, working } = await withBadCandidate({ options: { enrol } })
let answered = false
fake.intercept = (request) => {
if (answered || !request.url.endsWith('/v1/send')) {return undefined}
answered = true
return first()
}
await sendThroughRelay(payload, { ...options, totalTimeoutMs: 400 }, MESSAGE)
expect((await readRelayStore(payload)).token).toBe(working)
fake.intercept = undefined
// later: the candidate is tried, the service says invalid-token, it is dropped, the working token sends
const before = fake.requests.filter((r) => r.path === '/v1/enrol').length
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Later' })).sent).toBe(true)
expect((await readRelayStore(payload)).token).toBe(working)
expect(await readRelayCandidate(payload)).toBeNull()
expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(before)
})
}
test('answers the service gives after it has checked the token do promote a delivered one', async () => {
expect(provesToken({ body: {}, ok: true, status: 200 })).toBe(true)
const answer = (code: string, noAnswer = false) => ({ code, message: '', noAnswer, ok: false as const, retryable: false, status: 0 })
for (const code of ['site-pending', 'site-suspended', 'quota-exceeded', 'too-many-recipients', 'attachment-refused', 'recipient-suppressed', 'backend-failed', 'in-progress', 'idempotency-conflict', 'reverify', 'already-rotated']) {
expect(provesToken(answer(code)), code).toBe(true)
}
for (const code of ['invalid-token', 'rate-limited', 'browser-not-allowed', 'unavailable', 'internal', 'invalid-request', 'too-large', 'not-found', 'a-code-of-next-year']) {
expect(provesToken(answer(code)), code).toBe(false)
}
expect(provesToken(answer('quota-exceeded', true))).toBe(false)
// a real one: the enrolment's answer is lost, the site is pending — `site-pending` proves the delivered token
const { fake, options, payload } = relaySite()
fake.intercept = async (request) => {
if (!request.url.endsWith('/v1/enrol')) {return undefined}
fake.intercept = undefined
await fake.handle(request)
return 'drop'
}
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-pending' })
expect((await readRelayStore(payload)).token).toMatch(/^ims_/)
expect(await readRelayCandidate(payload)).toBeNull()
})
})
test('R-2: a token of another site, stored by hand, is refused by what /v1/status says — nothing is sent, nothing is revoked', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
const foreign = fake.issueToken('other-client.example.org')
await setRelayToken(payload, foreign) // a script, or the access-key field
const result = await sendThroughRelay(payload, options, MESSAGE)
expect(result).toMatchObject({ cause: 'client-foreign-token', code: 'relay-refused', sent: false })
expect(fake.outbox).toHaveLength(0)
expect(fake.requests.map((r) => r.path)).toEqual(['/v1/status'])
expect((await readRelayStore(payload)).token).toBeUndefined()
expect((await getRelayStatus(payload, options)).refusal).toMatchObject({ code: 'client-foreign-token' })
// the other site's token still works there
expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${foreign}` } }))).status).toBe(200)
// the site's own token, issued by hand for its host, passes the same check
await setRelayToken(payload, fake.issueToken(HOST))
expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true)
expect(await readRelayStore(payload)).toMatchObject({ host: HOST, hostChecked: true, manual: true })
// when the service cannot be asked, a token stored by hand is not used unchecked
await setRelayToken(payload, fake.issueToken(HOST))
fake.intercept = () => 'drop'
expect(await sendThroughRelay(payload, { ...options, totalTimeoutMs: 300 }, MESSAGE)).toMatchObject({ code: 'relay-unreachable', confirmed: true, sent: false })
})
test('R-3: junk calls to the confirm route do not keep the site\'s own enrolment out', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
const confirm = callConfirmRoute(payload) // every call comes from one address, as the service's does
const url = `https://${HOST}/api/iapl/mail-relay/confirm`
const junk = () => confirm(url, { body: JSON.stringify({ nonce: 'j'.repeat(43), state: 'active', token: `ims_${'j'.repeat(43)}` }), headers: {} })
const statuses: number[] = []
for (let i = 0; i < 14; i++) {statuses.push((await junk()).status)}
expect(statuses.slice(0, 10)).toEqual(Array(10).fill(404))
expect(statuses.slice(10)).toEqual([429, 429, 429, 429]) // refused calls are limited …
// … and the call that carries a nonce the site holds is answered all the same
expect(await enrolRelay(payload, options)).toEqual({ ok: true, state: 'active' })
expect((await getRelayStatus(payload, options)).refusal).toBeUndefined()
expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true)
expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1)
})
describe('R-4: one message has one budget of time', () => {
const hanging = (async (_input: unknown, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError'))))) as typeof fetch
test('the defaults: ten seconds, thirty with files', () => {
expect(RELAY_DEFAULTS).toMatchObject({ attempts: 3, attemptTimeoutMs: 30_000, totalTimeoutMs: 10_000, totalTimeoutWithFilesMs: 30_000 })
})
test('a service that accepts the connection and says nothing: the visitor waits the budget, not three time-outs', async () => {
const { options, payload } = relaySite({ fake: { allow: [HOST] } })
await enrolRelay(payload, options)
const started = Date.now()
const result = await sendThroughRelay(payload, { ...options, fetchImpl: hanging, timeoutMs: 30_000, totalTimeoutMs: 500 }, MESSAGE)
const took = Date.now() - started
// cut off while the service may have been handling it: not confirmed
expect(result).toMatchObject({ code: 'relay-not-confirmed', confirmed: false, sent: false })
expect(took).toBeGreaterThanOrEqual(450)
expect(took).toBeLessThan(1500)
})
test('the budget covers an enrolment on the way, and a message with files has its own', async () => {
const { options, payload } = relaySite({ fake: { allow: [HOST] } }) // not enrolled: the first call is /v1/enrol
let started = Date.now()
const result = await sendThroughRelay(payload, { ...options, fetchImpl: hanging, totalTimeoutMs: { files: 900, plain: 300 } }, MESSAGE)
// the message never left the site: not sent, and said so
expect(result).toMatchObject({ code: 'relay-unreachable', confirmed: true, sent: false })
expect(Date.now() - started).toBeLessThan(800)
started = Date.now()
await sendThroughRelay(payload, { ...options, fetchImpl: hanging, totalTimeoutMs: { files: 900, plain: 300 } }, { ...MESSAGE, attachments: [{ content: Buffer.from('x'), filename: 'a.txt' }] })
expect(Date.now() - started).toBeGreaterThanOrEqual(850)
expect(Date.now() - started).toBeLessThan(1900)
})
test('retries stop when the time is up, and a wait that would pass it is not waited', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
await enrolRelay(payload, options)
let sends = 0
fake.intercept = (request) => (request.url.endsWith('/v1/send') ? (sends++, refusalOf(503, 'unavailable', true)) : undefined)
const started = Date.now()
await sendThroughRelay(payload, { ...options, retryBackoffMs: 400, totalTimeoutMs: 300 }, MESSAGE)
expect(sends).toBe(1)
expect(Date.now() - started).toBeLessThan(300)
})
})
test('R-5: "Disconnect" while the service is down is not confirmed: the token is kept to try again, and not used', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
await sendThroughRelay(payload, options, MESSAGE)
const token = (await readRelayStore(payload)).token!
fake.intercept = () => html(502)
expect(await disconnectRelay(payload, options)).toEqual({ revoked: false })
expect(await readRelayStore(payload)).toMatchObject({ disconnected: true, revokePending: true, token })
expect(await getRelayStatus(payload, options)).toMatchObject({ connected: false, disconnected: true, revokePending: true })
fake.intercept = undefined
// the token still works at the service — that is why the panel must not say "done"
expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${token}` } }))).status).toBe(200)
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-disconnected', sent: false })
// pressed again with the service back: revoked and forgotten
expect(await disconnectRelay(payload, options)).toEqual({ revoked: true })
expect(await readRelayStore(payload)).toEqual({ disconnected: true, v: 1 })
expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${token}` } }))).status).toBe(401)
})
test('R-6: without the confirm route in the config the site does not ask to be enrolled', async () => {
const { fake, options, payload } = relaySite({ endpoints: [], fake: { allow: [HOST] } })
const result = await sendThroughRelay(payload, options, MESSAGE)
expect(result).toMatchObject({ cause: 'client-no-route', code: 'relay-refused', sent: false })
expect(result.sent === false && result.detail).toContain('relayConfirmEndpoint()')
expect(fake.requests).toEqual([])
// a token from elsewhere needs no route
const token = fake.issueToken(HOST)
expect((await sendThroughRelay(payload, { ...options, enrol: false, token }, MESSAGE)).sent).toBe(true)
})
test('R-7: half an SMTP set-up is said, once in the log and in the panel', async () => {
const { fake, logger, options, payload } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpHost: 'smtp.example.com', smtpUser: '[email protected]' } })
const adapter = adapterOf(mailAdapter({ relay: options }), payload)
expect(((await adapter.sendEmail(MESSAGE)) as { transport?: string }).transport).toBe('relay')
await adapter.sendEmail(MESSAGE)
expect(logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('SMTP settings in Site integrations are incomplete'))).toHaveLength(1)
expect(await mailPanelState({ payload }, options)).toMatchObject({ smtpIncomplete: true, transport: 'relay' })
expect((await mailPanelState(relayPayload(), {})).smtpIncomplete).toBeUndefined()
expect(fake.outbox).toHaveLength(2)
})
test('R-11: a mail that was not sent stays visible after the next one went out', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
await sendThroughRelay(payload, options, MESSAGE)
fake.backend = 'recipient-suppressed'
await sendThroughRelay(payload, options, withMailKind({ ...MESSAGE, subject: 'Lost' }, 'form-confirmation'))
fake.backend = 'ok'
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Fine' })).sent).toBe(true)
const status = await getRelayStatus(payload, options)
expect(status.lastFailure).toMatchObject({ code: 'relay-recipient-suppressed', kind: 'form-confirmation' })
expect(Date.parse(status.lastFailure!.at)).toBeGreaterThan(Date.now() - 5000)
})
test('the token never follows a redirect, and the service\'s words are one clean line', async () => {
const seen: RequestInit[] = []
const fetchImpl = (async (_input: unknown, init?: RequestInit) => {
seen.push(init ?? {})
return Response.json({ code: 'quota-exceeded', message: 'Line one\u202E\u0007 of it\nsecond line', ok: false, retryable: false }, { status: 429 })
}) as typeof fetch
const answer = await relayRequest({ fetchImpl, method: 'POST', path: '/v1/send', token: `ims_${'t'.repeat(43)}`, url: 'https://relay.example.net/mail' })
expect(seen[0].redirect).toBe('manual')
expect(answer).toMatchObject({ message: 'Line one of it', ok: false })
const headers = new Headers(seen[0].headers)
expect(headers.has('origin')).toBe(false)
expect(headers.has('sec-fetch-site')).toBe(false)
})
test('an enrolment is not taken for done when the token that arrived belongs to another nonce', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
// a token delivered for some OTHER enrolment is in the store; the service answers 200 to this one without calling back
const other = `oth${'e'.repeat(40)}`
await holdNonce(payload, other, 60_000)
await callConfirmRoute(payload)(`https://${HOST}/api/iapl/mail-relay/confirm`, { body: JSON.stringify({ nonce: other, state: 'active', token: `ims_${'o'.repeat(43)}` }), headers: {} })
fake.intercept = (request) => (request.url.endsWith('/v1/enrol') ? Response.json({ ok: true, state: 'active' }) : undefined)
expect(await enrolRelay(payload, options)).toMatchObject({ code: 'callback-failed', ok: false })
expect((await readRelayStore(payload)).token).toBeUndefined()
})
test('what an operation said about its mail is for one recipient and is taken back when it sent none', () => {
expectMailTo('[email protected]', 'account', { visitor: '198.51.100.9' })
expect(takeExpectedMail(['[email protected]', '[email protected]'])).toBeUndefined() // a mail to several is not that mail
expect(takeExpectedMail(['[email protected]'])).toEqual({ kind: 'account', visitor: '198.51.100.9' })
expect(takeExpectedMail(['[email protected]'])).toBeUndefined() // used up
expectMailTo('[email protected]', 'account')
dropExpectedMail(' [email protected] ')
expect(takeExpectedMail(['[email protected]'])).toBeUndefined()
// the hook pair on an auth collection does exactly that around an operation
const marked = withAccountMailMark({ slug: 'users', auth: true, fields: [] })
const before = marked.hooks!.beforeOperation!.at(-1) as (args: object) => unknown
const after = marked.hooks!.afterOperation!.at(-1) as (args: object) => unknown
const args = { args: { data: { email: '[email protected]' } }, operation: 'forgotPassword', req: { headers: new Headers() } }
before(args)
after({ ...args, result: null })
expect(takeExpectedMail(['[email protected]'])).toBeUndefined()
before(args)
expect(takeExpectedMail(['[email protected]'])?.kind).toBe('account')
expect(withAccountMailMark(marked)).toBe(marked) // not added twice
})
})
describe('what the panel is told', () => {
test('the panel calls the service by its short name, IWSN, in both languages — one constant, never another name', () => {
expect(RELAY_SHORT_NAME).toBe('IWSN')