Mail relay: review round 2 — the store is keyed by host, a copied database does not enrol by itself

- Q-1 one entry per host (iapl:mail-relay:site:<host>); a read never deletes or writes; another host's
  entry is neither used nor touched (a developer's process on the live database, www and apex, a copy)
- a database that holds another host's connection and none of this site's does not enrol by itself:
  "Connect again" does, once; mail.relay.otherHosts ('wait' | 'enrol' | the site's own other hosts);
  panel text and doctor finding; a site with an empty store enrols by itself as before
- Q-2 the file limit answers from what is stored and never asks the service
- Q-3 a file whose mail was not confirmed is not reported as a wrong file, and no notice mail follows
- Q-4 its own text when the access-key field is off
- D-1 docs for open enrolment; staging, copies and several hosts

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 23:14:11 +01:00
co-authored by Claude Fable 5.2
parent edee3a321f
commit 85ed92bb89
31 changed files with 467 additions and 211 deletions
+5
View File
@@ -686,6 +686,11 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () =>
expect(await run(mail({ relay: relay({ state: 'pending' }) }))).toEqual(['mail-relay-state:warning'])
expect(await run(mail({ relay: relay({ connected: false, reason: 'redirect', refusal: 'callback-failed', state: undefined }) }))).toEqual(['mail-relay-state:warning'])
expect(await run(mail({ relay: relay({ connected: false, state: undefined }) }))).toEqual(['mail-relay-state:info'])
// a copy of another site's database: it does not connect by itself, and the finding says what to do
const copy = await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail({ relay: relay({ connected: false, reason: 'client.pl', refusal: 'client-other-host', state: undefined }) }) } })
expect(rules(copy)).toEqual(['mail-relay-state:warning'])
expect(copy.findings[0].message).toContain('client.pl')
expect(copy.findings[0].fix).toContain('otherHosts')
expect(await run(mail({ relay: relay({ nameReplaced: true }) }))).toEqual(['mail-relay-state:warning'])
})
+158 -35
View File
@@ -12,7 +12,7 @@ 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 { relayAdapter, relayAttachmentLimit } from '../src/modules/email/relay/adapter.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'
@@ -22,6 +22,8 @@ import { mailPanelState } from '../src/modules/email/relay/panel.js'
import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.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 { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../src/modules/notifications/defaults.js'
import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js'
import { setRateLimitStore } from '../src/modules/shared/rateLimit.js'
import { callConfirmRoute, relayPayload, relaySite } from './mailRelay/helpers.js'
@@ -652,41 +654,162 @@ describe('the token over time', () => {
expect((await readRelayStore(payload)).manual).toBe(true)
})
test('a database copied to another host does not use the first site\'s token: the copy starts unenrolled and enrols as itself', async () => {
// one service, two sites: it calls each back at its own host
const staging = relayPayload({ serverURL: 'https://staging.example.com' })
const sites: Record<string, ReturnType<typeof callConfirmRoute>> = {}
const production = relaySite({
fake: { allow: [HOST, 'staging.example.com'], callSite: (url, init) => sites[new URL(url).host](url, init) },
integrations: { smtpFromName: 'Example' },
})
sites[HOST] = callConfirmRoute(production.payload)
sites['staging.example.com'] = callConfirmRoute(staging.payload)
await sendThroughRelay(production.payload, production.options, MESSAGE)
const token = (await readRelayStore(production.payload)).token!
// the copy: the same key-value entries, another serverURL
for (const [key, value] of production.store) {staging.store.set(key, structuredClone(value))}
const options = resolveRelayOptions(staging.payload, { fetchImpl: production.fake.fetch, url: production.fake.url })!
expect((await readRelayStore(staging.payload)).token).toBe(token) // it is there …
const seen: string[] = []
production.fake.intercept = (request) => void seen.push(request.headers.get('authorization') ?? '')
describe('one database, several hosts (review round 2, Q-1; the store is keyed by host)', () => {
/** One service and any number of sites on ONE key-value store; the service calls each back at its own host. */
const shared = (fakeOptions: Parameters<typeof relaySite>[0] = {}) => {
const sites: Record<string, ReturnType<typeof callConfirmRoute>> = {}
const first = relaySite({ ...fakeOptions, fake: { allow: ['*'], callSite: (url, init) => sites[new URL(url).host](url, init), ...fakeOptions.fake } })
sites[new URL(fakeOptions.serverURL ?? `https://${HOST}`).host] = callConfirmRoute(first.payload)
const another = (serverURL: string, own: Parameters<typeof resolveRelayOptions>[1] = {}) => {
const site = relayPayload({ serverURL })
;(site.payload as unknown as { kv: unknown }).kv = (first.payload as unknown as { kv: unknown }).kv
sites[new URL(serverURL).host] = callConfirmRoute(site.payload)
return { ...site, options: resolveRelayOptions(site.payload, { fetchImpl: first.fake.fetch, retryBackoffMs: 1, url: first.fake.url, ...(own || {}) })! }
}
return { ...first, another }
}
const everything = (store: Map<string, unknown>) => JSON.stringify([...store.entries()].sort())
// … and is not shown as this site's, not used, and not revoked
expect(await mailPanelState({ payload: staging.payload }, options)).toMatchObject({ relay: { connected: false, host: 'staging.example.com' } })
expect((await readRelayStore(staging.payload)).token).toBeUndefined()
expect(staging.logger.warn.mock.calls.map((c) => String(c[0])).join()).toMatch(/belongs to "example\.com", this site is "staging\.example\.com"/)
await disconnectRelay(staging.payload, options) // even "Disconnect" on the copy
expect(production.fake.requests.filter((r) => r.path === '/v1/revoke')).toEqual([])
expect((await enrolRelay(staging.payload, options, { force: true })).ok).toBe(true)
expect((await sendThroughRelay(staging.payload, options, { ...MESSAGE, subject: 'From staging' })).sent).toBe(true)
expect(production.fake.outbox.at(-1)).toMatchObject({ host: 'staging.example.com', subject: 'From staging' })
const own = (await readRelayStore(staging.payload)).token
expect(own).not.toBe(token)
expect(seen.every((header) => !header.includes(token))).toBe(true)
expect(JSON.stringify(staging.logger.warn.mock.calls)).not.toContain('ims_')
// production is untouched and still sends with its own token
expect((await readRelayStore(production.payload)).token).toBe(token)
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'From production' })).sent).toBe(true)
test.each([
['enrolled by the call-back', false],
['with a token issued by hand', true],
])('a developer\'s process on the live database (%s): reading the state, the limit, the doctor\'s view and a send change NOTHING', async (_name, byHand) => {
const production = shared()
if (byHand) {await setRelayToken(production.payload, production.fake.issueToken(HOST))}
expect((await sendThroughRelay(production.payload, production.options, MESSAGE)).sent).toBe(true)
const before = everything(production.store)
const requests = production.fake.requests.length
const dev = production.another('http://localhost:3000', { url: undefined })
expect(await mailPanelState({ payload: dev.payload }, dev.options)).toMatchObject({ relay: { connected: false, host: 'localhost:3000', refusal: { code: 'host-not-allowed' } } })
expect(await getRelayStatus(dev.payload, dev.options)).toMatchObject({ connected: false })
expect(await relayAttachmentLimit(dev.payload, dev.options)).toBeNull()
expect(await sendThroughRelay(dev.payload, dev.options, MESSAGE)).toMatchObject({ code: 'relay-refused', sent: false })
expect(await rotateRelayToken(dev.payload, dev.options)).toBe('not-due')
await refreshRelayStatus(dev.payload, dev.options)
expect(everything(production.store)).toBe(before)
expect(production.fake.requests).toHaveLength(requests)
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'Still here' })).sent).toBe(true)
expect(production.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(byHand ? 0 : 1)
})
test('`client.pl` and `www.client.pl` on one database, mail in turn: one enrolment each, not one a mail', async () => {
const apex = shared({ serverURL: 'https://client.pl' })
const www = apex.another('https://www.client.pl')
const apexOptions = resolveRelayOptions(apex.payload, { fetchImpl: apex.fake.fetch, retryBackoffMs: 1, url: apex.fake.url })!
for (let i = 0; i < 4; i++) {
expect((await sendThroughRelay(apex.payload, apexOptions, { ...MESSAGE, subject: `apex ${i}` })).sent).toBe(true)
expect((await sendThroughRelay(www.payload, www.options, { ...MESSAGE, subject: `www ${i}` })).sent).toBe(true)
}
expect(apex.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(2)
expect(apex.fake.outbox.map((m) => m.host)).toEqual(['client.pl', 'www.client.pl', 'client.pl', 'www.client.pl', 'client.pl', 'www.client.pl', 'client.pl', 'www.client.pl'])
expect([...apex.store.keys()].filter((k) => k.includes(':site:')).sort()).toEqual(['iapl:mail-relay:site:client.pl', 'iapl:mail-relay:site:www.client.pl'])
})
test('a copy of production\'s database on a staging host does not enrol by itself — and uses, changes and revokes nothing of production\'s', async () => {
const production = shared({ integrations: { smtpFromName: 'Example' } })
await sendThroughRelay(production.payload, production.options, MESSAGE)
const token = (await readRelayStore(production.payload)).token!
const before = everything(production.store)
const staging = production.another('https://staging.example.com')
const seen: string[] = []
// what the copy's requests carry (production's own later request is not the copy's)
production.fake.intercept = (request) => void (request.headers.get('x-intecion-site') !== HOST && seen.push(request.headers.get('authorization') ?? ''))
// a form on the copy, with production's data in it: nothing is sent, nothing is asked
const requests = production.fake.requests.length
const held = await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, to: '[email protected]' })
expect(held).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', confirmed: true, sent: false })
expect(held.sent === false && held.detail).toContain('example.com')
expect(production.fake.requests).toHaveLength(requests)
expect(production.fake.outbox).toHaveLength(1)
// the panel and the doctor say why, before and after that send
expect(await mailPanelState({ payload: staging.payload }, staging.options)).toMatchObject({ relay: { connected: false, host: 'staging.example.com', refusal: { code: 'client-other-host', reason: HOST } } })
const untouched = production.another('https://staging-2.example.com')
expect((await mailPanelState({ payload: untouched.payload }, untouched.options)).relay?.refusal).toMatchObject({ code: 'client-other-host', reason: HOST })
// "Disconnect" on the copy revokes nothing of production's
await disconnectRelay(untouched.payload, untouched.options)
expect(production.fake.requests.filter((r) => r.path === '/v1/revoke')).toEqual([])
expect((await readRelayStore(production.payload)).token).toBe(token)
// an admin decides that the copy sends: "Connect again", once — then it is a site of its own and heals by itself
expect(await enrolRelay(staging.payload, staging.options, { force: true })).toEqual({ ok: true, state: 'active' })
expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'From staging' })).sent).toBe(true)
expect(production.fake.outbox.at(-1)).toMatchObject({ host: 'staging.example.com', subject: 'From staging' })
const own = (await readRelayStore(staging.payload)).token!
expect(own).not.toBe(token)
await production.fake.handle(new Request(`${production.fake.url}/v1/revoke`, { headers: { authorization: `Bearer ${own}`, 'x-intecion-site': 'staging.example.com' }, method: 'POST' }))
expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'Healed' })).sent).toBe(true)
// also when its token is gone altogether (another container rotated it away): it has been connected, so it enrols
await updateRelayStore(staging.payload, (c) => ({ ...c, token: undefined }))
expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'Healed again' })).sent).toBe(true)
// a token the service delivers for ONE host waits beside that host's token only: the other host never tries it
const nonce = `stg${'n'.repeat(40)}`
await holdNonce(staging.payload, nonce, 60_000)
await callConfirmRoute(staging.payload)('https://staging.example.com/api/iapl/mail-relay/confirm', { body: JSON.stringify({ nonce, state: 'active', token: `ims_${'s'.repeat(43)}` }), headers: {} })
expect((await readRelayCandidate(staging.payload))?.token).toBe(`ims_${'s'.repeat(43)}`)
expect(await readRelayCandidate(production.payload)).toBeNull()
const sends = production.fake.requests.length
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'Its own token' })).sent).toBe(true)
expect(production.fake.requests.slice(sends).map((r) => r.path)).toEqual(['/v1/send'])
expect(seen.every((header) => !header.includes(token))).toBe(true)
expect(JSON.stringify([staging.logger.warn.mock.calls, staging.logger.error.mock.calls])).not.toContain('ims_')
// production's entry is byte for byte what it was, and production sends on
expect((await readRelayStore(production.payload)).token).toBe(token)
expect(JSON.parse(before).find(([key]: [string]) => key === `iapl:mail-relay:site:${HOST}`)).toEqual([`iapl:mail-relay:site:${HOST}`, production.store.get(`iapl:mail-relay:site:${HOST}`)])
production.fake.intercept = undefined
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'From production' })).sent).toBe(true)
})
test('a moved domain, a second domain, or a project that wants copies to enrol: `otherHosts`', async () => {
const old = shared()
await sendThroughRelay(old.payload, old.options, MESSAGE)
// the same data under a new domain: waits by default …
const moved = old.another('https://example.org')
expect(await sendThroughRelay(moved.payload, moved.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false })
// … named as the site's own old host, it enrols by itself
const named = old.another('https://example.net', { otherHosts: ['example.com'] })
expect((await sendThroughRelay(named.payload, named.options, MESSAGE)).sent).toBe(true)
// (the list names hosts: a third one in the way still stops it — example.net is now there too)
const third = old.another('https://example.info', { otherHosts: ['example.com'] })
expect(await sendThroughRelay(third.payload, third.options, MESSAGE)).toMatchObject({ cause: 'client-other-host' })
const any = old.another('https://copy.example.dev', { otherHosts: 'enrol' })
expect((await sendThroughRelay(any.payload, any.options, MESSAGE)).sent).toBe(true)
// a site before launch — an empty store — enrols by itself, as ever
const fresh = relaySite({ fake: { allow: [HOST] } })
expect((await sendThroughRelay(fresh.payload, fresh.options, MESSAGE)).sent).toBe(true)
})
})
test('Q-2: the file limit is answered from what is stored and never waits for the service', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST], limits: { maxAttachmentBytes: 4242 } } })
await sendThroughRelay(payload, options, MESSAGE) // the status is read after the first send
// an hour and more later, with the service hanging: the stored answer, at once, and no request
await updateRelayStore(payload, (c) => ({ ...c, service: { ...c.service!, fetchedAt: new Date(Date.now() - 3 * 60 * 60_000).toISOString() } }))
const hanging = (async (_input: unknown, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError'))))) as typeof fetch
const requests = fake.requests.length
const started = Date.now()
for (let i = 0; i < 3; i++) {expect(await relayAttachmentLimit(payload, { ...options, fetchImpl: hanging })).toBe(4242)}
expect(Date.now() - started).toBeLessThan(200)
expect(fake.requests).toHaveLength(requests)
// renewed by the next send, not by a read
fake.limits.maxAttachmentBytes = 1000
await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Renews it' })
expect(await relayAttachmentLimit(payload, options)).toBe(1000)
})
test('Q-3: a file whose mail was not confirmed is not reported as a wrong file', () => {
const texts = NOTIFICATION_FALLBACK.form
const failed = { field: 'cv', file: 'cv.pdf', reason: 'delivery', success: false } as const
expect(resolveFormMessage(failed, texts)).toContain('Choose a smaller file')
const unconfirmed = resolveFormMessage({ ...failed, unconfirmed: true }, texts)
expect(unconfirmed).toContain('cv.pdf')
expect(unconfirmed).toMatch(/could not confirm/)
expect(unconfirmed).not.toMatch(/try again|smaller file/)
expect(resolveFormMessage({ ...failed, unconfirmed: true }, NOTIFICATION_FALLBACK_PL.form)).toMatch(/Nie wysyłaj go ponownie/)
})
test('a token issued by hand is stored the same way; enrol: "manual" and enrol: false never enrol by themselves', async () => {
+1
View File
@@ -40,6 +40,7 @@ export function relayPayload({ custom, endpoints = [relayConfirmEndpoint()], int
kv: {
delete: async (key: string) => void store.delete(key),
get: async (key: string) => (store.has(key) ? structuredClone(store.get(key)) : null),
keys: async () => [...store.keys()],
set: async (key: string, value: object) => void store.set(key, structuredClone(value)),
},
logger,
+6 -2
View File
@@ -30,6 +30,8 @@ vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHe
const PASSWORD = 'a-long-test-password-1'
const HOST = 'example.com'
const CONFIRM = `/api${RELAY_CONFIRM_PATH}`
/** The site's entry: one per host. */
const SITE_KEY = `${RELAY_KV_KEY}:site:${HOST}`
let server: TestServer
let payload: Payload
@@ -139,7 +141,7 @@ describe('the token cannot be reached from outside', () => {
test('it is in the key-value store', async () => {
token = (await readRelayStore(payload)).token ?? ''
expect(token).toMatch(/^ims_[\w-]{43}$/)
const rows = await payload.db.find({ collection: 'payload-kv', limit: 0, pagination: false, where: { key: { equals: RELAY_KV_KEY } } })
const rows = await payload.db.find({ collection: 'payload-kv', limit: 0, pagination: false, where: { key: { equals: SITE_KEY } } })
expect(rows.docs).toHaveLength(1)
id = (rows.docs[0] as { id: number | string }).id
expect(JSON.stringify(rows.docs[0])).toContain(token)
@@ -150,7 +152,7 @@ describe('the token cannot be reached from outside', () => {
const answers = [
await api('/payload-kv', headers),
await api(`/payload-kv/${id}`, headers),
await api(`/payload-kv?where[key][equals]=${encodeURIComponent(RELAY_KV_KEY)}&depth=0`, headers),
await api(`/payload-kv?where[key][equals]=${encodeURIComponent(SITE_KEY)}&depth=0`, headers),
await api('/payload-kv', headers, { body: JSON.stringify({ data: { token: 'x' }, key: `${RELAY_KV_KEY}:x` }), method: 'POST' }),
await api(`/payload-kv/${id}`, headers, { body: JSON.stringify({ data: {} }), method: 'PATCH' }),
await api(`/payload-kv/${id}`, headers, { method: 'DELETE' }),
@@ -213,6 +215,8 @@ describe('the state routes are for admins', () => {
expect(((await (await api('/iapl/mail-relay/status', admin)).json()) as { accessKeyField?: boolean }).accessKeyField).toBeUndefined()
const closed = await post('/iapl/mail-relay/connect', admin, { token: fake.issueToken(HOST) })
expect(closed.status).toBe(403)
// said as what it is — not "only an administrator can do this" to an administrator
expect(((await closed.json()) as { error: string }).error).toMatch(/set by the site's developer/)
expect((await readRelayStore(payload)).token).toBe(mine)
// a project switches the field on: mail.relay.accessKeyField
relayOptions.accessKeyField = true