Mail relay: the built-in client for the Intecion Notifications Webservice
Transport, enrolment with the confirm route, token and state in payload-kv, rotation, the panel's state block, doctor rules, the fake service and the copied contract 1.5.0. Tests against the contract's runner and the fake. Docs and HTTP tests follow. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
9efd86a06f
commit
ea9703f8e3
@@ -0,0 +1,617 @@
|
||||
/**
|
||||
* The site's side of the Intecion Notifications Webservice, against the fake service: which transport
|
||||
* a send takes, enrolment and the confirm route, what happens to the token, one key and one encoding
|
||||
* per message across retries, "not confirmed", rotation, the limits the site keeps itself, and that
|
||||
* no token ever reaches a log.
|
||||
*/
|
||||
import type { PayloadEmailAdapter } from 'payload'
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { mailAdapter, resetGraphDeprecationWarning, resolveMailTransport } from '../src/modules/email/mailAdapter.js'
|
||||
import { relayAdapter } from '../src/modules/email/relay/adapter.js'
|
||||
import { 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 { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.js'
|
||||
import { disconnectRelay, enrolRelay, getRelayStatus, 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'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const MESSAGE = { html: '<p>Hello.</p>', subject: 'New enquiry', to: '[email protected]' }
|
||||
const HOST = 'example.com'
|
||||
const GRAPH_ENV = ['GRAPH_TENANT_ID', 'GRAPH_CLIENT_ID', 'GRAPH_CLIENT_SECRET', 'GRAPH_SENDER']
|
||||
|
||||
/** Each test counts from zero: a rate-limit store of its own. */
|
||||
function clearRateLimits(): void {
|
||||
const buckets = new Map<string, { count: number; resetAt: number }>()
|
||||
setRateLimitStore({
|
||||
hit: async (id: string, cost: number, windowMs: number) => {
|
||||
const now = Date.now()
|
||||
const current = buckets.get(id)
|
||||
const bucket = current && current.resetAt > now ? current : { count: 0, resetAt: now + windowMs }
|
||||
bucket.count += cost
|
||||
buckets.set(id, bucket)
|
||||
return bucket
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const adapterOf = (factory: PayloadEmailAdapter, payload: unknown) => factory({ payload } as never) as { attachmentLimit?: () => Promise<null | number> } & ReturnType<PayloadEmailAdapter>
|
||||
const everythingLogged = (logger: Record<string, { mock: { calls: unknown[][] } }>) => JSON.stringify(Object.values(logger).flatMap((fn) => fn.mock.calls))
|
||||
|
||||
beforeEach(() => {
|
||||
clearUnconfirmedRelayMessages()
|
||||
clearRateLimits()
|
||||
resetGraphDeprecationWarning()
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, '')}
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
setRateLimitStore(null)
|
||||
})
|
||||
|
||||
describe('which transport a send takes', () => {
|
||||
const smtp = { smtpHost: 'smtp.example.com', smtpPassword: 'secret', smtpUser: '[email protected]' }
|
||||
|
||||
test.each([
|
||||
['nothing set', {}, false, true, 'relay'],
|
||||
['nothing set, relay switched off', {}, false, false, 'none'],
|
||||
['SMTP filled in', smtp, false, true, 'smtp'],
|
||||
['SMTP filled in, relay off', smtp, false, false, 'smtp'],
|
||||
['SMTP half filled in', { smtpHost: 'smtp.example.com' }, false, true, 'relay'],
|
||||
['Graph chosen with its variables', { emailTransport: 'graph' }, true, true, 'graph'],
|
||||
['Graph chosen with its variables and SMTP (today: Graph, SMTP for large files)', { ...smtp, emailTransport: 'graph' }, true, true, 'graph'],
|
||||
['Graph chosen, variables missing, SMTP filled in', { ...smtp, emailTransport: 'graph' }, false, true, 'smtp'],
|
||||
['Graph chosen, variables missing, no SMTP', { emailTransport: 'graph' }, false, true, 'relay'],
|
||||
['Graph variables set, panel on automatic, no SMTP', {}, true, true, 'graph'],
|
||||
['Graph variables set, panel on automatic, SMTP filled in', smtp, true, true, 'smtp'],
|
||||
] as const)('%s → %s', (_name, settings, graphEnv, relay, expected) => {
|
||||
expect(resolveMailTransport(settings, { graphEnv, relay })).toBe(expected)
|
||||
})
|
||||
|
||||
test('a site with SMTP filled in never contacts the service', async () => {
|
||||
const { fake, payload } = relaySite({ integrations: { smtpHost: '127.0.0.1', smtpPassword: 'x', smtpPort: 1, smtpUser: 'u' } })
|
||||
const adapter = adapterOf(mailAdapter({ relay: { fetchImpl: fake.fetch, url: fake.url } }), payload)
|
||||
const result = (await adapter.sendEmail(MESSAGE)) as { sent: boolean }
|
||||
expect(result.sent).toBe(false) // nothing listens on port 1
|
||||
expect(fake.requests).toEqual([])
|
||||
expect(await adapter.attachmentLimit?.()).toBeNull()
|
||||
})
|
||||
|
||||
test('relay: false leaves a site without SMTP "not configured", as before 1.17.0', async () => {
|
||||
const { fake, payload } = relaySite()
|
||||
const result = (await adapterOf(mailAdapter({ relay: false }), payload).sendEmail(MESSAGE)) as { code: string; sent: boolean }
|
||||
expect(result).toMatchObject({ code: 'not-configured', sent: false })
|
||||
expect(fake.requests).toEqual([])
|
||||
})
|
||||
|
||||
test('the plugin option switches it off for mailAdapter() too, and the adapter\'s own argument wins', async () => {
|
||||
const off = relaySite({ custom: { iapl: { mail: { relay: false } } } })
|
||||
expect(resolveRelayOptions(off.payload, undefined)).toBeNull()
|
||||
expect(resolveRelayOptions(off.payload, {})?.url).toBe('https://webservices.intecion.net/mail')
|
||||
expect(resolveRelayOptions(off.payload, { url: 'https://relay.example.net/mail/' })).toMatchObject({ ownUrl: true, url: 'https://relay.example.net/mail' })
|
||||
const on = relaySite({ custom: { iapl: { mail: { relay: { host: 'www.example.com' } } } } })
|
||||
expect(resolveRelayOptions(on.payload, undefined)?.host).toBe('www.example.com')
|
||||
expect(resolveRelayOptions(on.payload, false)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the first send', () => {
|
||||
test('enrols through the confirm route, then sends — with the panel\'s name, the reply address and the kind', async () => {
|
||||
const { fake, logger, payload, settings, store } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpFromAddress: '[email protected]', smtpFromName: 'Kancelaria Example' } })
|
||||
const adapter = adapterOf(mailAdapter({ relay: { fetchImpl: fake.fetch, url: fake.url } }), payload)
|
||||
|
||||
const result = (await adapter.sendEmail(withMailKind(MESSAGE, 'form-notification'))) as Record<string, unknown>
|
||||
expect(result).toMatchObject({ kind: 'form-notification', replayed: false, senderName: 'Kancelaria Example', sent: true, transport: 'relay', warnings: [] })
|
||||
expect(fake.requests.map((r) => `${r.method} ${r.path}`).slice(0, 2)).toEqual(['POST /v1/enrol', 'POST /v1/send'])
|
||||
expect(fake.outbox).toHaveLength(1)
|
||||
expect(fake.outbox[0]).toMatchObject({
|
||||
from: '[email protected]', fromName: 'Kancelaria Example', headers: { 'X-Intecion-Product': 'iapl', 'X-Intecion-Site': HOST },
|
||||
kind: 'form-notification', replyTo: '[email protected]', subject: 'New enquiry', to: ['[email protected]'],
|
||||
})
|
||||
// the token is in the key-value store and nowhere else: not in a log, not in the result, not in the global
|
||||
const stored = await readRelayStore(payload)
|
||||
expect(stored.token).toMatch(/^ims_[\w-]{43}$/)
|
||||
expect(stored).toMatchObject({ host: HOST, source: 'enrolment', state: 'active' })
|
||||
expect([...store.keys()].filter((k) => k.includes(':nonce:'))).toEqual([])
|
||||
expect(await readRelayCandidate(payload)).toBeNull()
|
||||
for (const text of [everythingLogged(logger), JSON.stringify(result), JSON.stringify(settings)]) {expect(text).not.toContain('ims_')}
|
||||
|
||||
// the second send does not enrol again
|
||||
await adapter.sendEmail(MESSAGE)
|
||||
expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1)
|
||||
expect(fake.outbox[1].kind).toBe('system') // a message nobody marked
|
||||
})
|
||||
|
||||
test('the sender name falls back to the site name; a message\'s own reply address wins', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpFromAddress: '[email protected]' }, siteName: 'Example Sp. z o.o.' })
|
||||
const adapter = adapterOf(mailAdapter({ relay: options }), payload)
|
||||
await adapter.sendEmail({ ...MESSAGE, replyTo: 'Jan Kowalski <[email protected]>' })
|
||||
expect(fake.outbox[0]).toMatchObject({ fromName: 'Example Sp. z o.o.', replyTo: '[email protected]' })
|
||||
// no name anywhere: the mail leaves under the site's host
|
||||
const bare = relaySite({ fake: { allow: [HOST] } })
|
||||
await adapterOf(mailAdapter({ relay: bare.options }), bare.payload).sendEmail(MESSAGE)
|
||||
expect(bare.fake.outbox[0].fromName).toBe(HOST)
|
||||
expect(bare.fake.outbox[0].replyTo).toBeUndefined()
|
||||
})
|
||||
|
||||
test('a host Intecion has not listed waits for approval; the same token works once approved', async () => {
|
||||
const { fake, options, payload, settings } = relaySite()
|
||||
const adapter = adapterOf(mailAdapter({ relay: options }), payload)
|
||||
const waiting = (await adapter.sendEmail(MESSAGE)) as Record<string, unknown>
|
||||
expect(waiting).toMatchObject({ code: 'relay-pending', confirmed: true, sent: false })
|
||||
expect(settings.emailStatus).toMatchObject({ code: 'relay-pending', state: 'degraded' })
|
||||
expect((await readRelayStore(payload)).state).toBe('pending')
|
||||
const token = (await readRelayStore(payload)).token
|
||||
|
||||
fake.allow(HOST)
|
||||
expect(((await adapter.sendEmail(MESSAGE)) as { sent: boolean }).sent).toBe(true)
|
||||
expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1)
|
||||
expect(await readRelayStore(payload)).toMatchObject({ state: 'active', token })
|
||||
expect(settings.emailStatus).toMatchObject({ state: 'ok' })
|
||||
})
|
||||
|
||||
test('a site that does not know its address, or runs on a private one, is refused here — nothing leaves the server', async () => {
|
||||
const calls: string[] = []
|
||||
const fetchImpl = (async (input: string) => {
|
||||
calls.push(String(input))
|
||||
return Response.json({ ok: true })
|
||||
}) as unknown as typeof fetch
|
||||
for (const serverURL of ['', 'http://localhost:3000', 'https://shop.internal', 'https://192.0.2.10']) {
|
||||
const { payload } = relayPayload({ serverURL })
|
||||
const options = resolveRelayOptions(payload, { fetchImpl })!
|
||||
const result = await sendThroughRelay(payload, options, MESSAGE)
|
||||
expect(result).toMatchObject({ code: 'relay-refused', sent: false })
|
||||
}
|
||||
expect(calls).toEqual([])
|
||||
expect(isPublicHost('example.com')).toBe(true)
|
||||
expect(relayHost({ config: { serverURL: 'https://WWW.Example.com:443/pl' } } as never, {})).toBe('www.example.com')
|
||||
})
|
||||
|
||||
test('two sends at once enrol once', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
const results = await Promise.all([sendThroughRelay(payload, options, MESSAGE), sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Second' })])
|
||||
expect(results.map((r) => r.sent)).toEqual([true, true])
|
||||
expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the confirm route', () => {
|
||||
test('answers 404 and stores nothing for a nonce the site does not hold, an expired one, a reused one and a malformed call', async () => {
|
||||
const { payload } = relayPayload()
|
||||
const confirm = callConfirmRoute(payload)
|
||||
const url = `https://${HOST}/api/iapl/mail-relay/confirm`
|
||||
const token = `ims_${'a'.repeat(43)}`
|
||||
const call = (body: unknown) => confirm(url, { body: typeof body === 'string' ? body : JSON.stringify(body), headers: {} })
|
||||
const nonce = 'n'.repeat(43)
|
||||
|
||||
expect((await call({ nonce, state: 'active', token })).status).toBe(404) // unsolicited
|
||||
await holdNonce(payload, nonce, -1)
|
||||
expect((await call({ nonce, state: 'active', token })).status).toBe(404) // expired
|
||||
await holdNonce(payload, nonce, 60_000)
|
||||
for (const bad of ['not json', '[]', { nonce, state: 'active' }, { nonce, state: 'active', token: 'ims_short' }, { nonce, state: 'owner', token }, { nonce: 'short', state: 'active', token }]) {
|
||||
expect((await call(bad)).status).toBe(404)
|
||||
}
|
||||
expect(await readRelayCandidate(payload)).toBeNull()
|
||||
const good = await call({ nonce, state: 'active', token })
|
||||
expect(good.status).toBe(200)
|
||||
expect(good.headers.get('content-type')).toBe('application/json')
|
||||
expect((await call({ nonce, state: 'active', token: `ims_${'b'.repeat(43)}` })).status).toBe(404) // single use
|
||||
expect((await readRelayCandidate(payload))?.token).toBe(token)
|
||||
})
|
||||
|
||||
test('never replaces the token in use: a delivered token waits beside it until the service accepts it', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
const working = (await readRelayStore(payload)).token
|
||||
// somebody who knows a live nonce delivers a token the service never issued
|
||||
const nonce = 'q'.repeat(43)
|
||||
await holdNonce(payload, nonce, 60_000)
|
||||
await callConfirmRoute(payload)(`https://${HOST}/api/iapl/mail-relay/confirm`, { body: JSON.stringify({ nonce, state: 'active', token: `ims_${'z'.repeat(43)}` }), headers: {} })
|
||||
expect((await readRelayStore(payload)).token).toBe(working)
|
||||
// the next send tries it, hears invalid-token, and goes back to the working token — without enrolling again
|
||||
const before = fake.requests.length
|
||||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'After' })).sent).toBe(true)
|
||||
expect(fake.requests.slice(before).map((r) => r.path)).toEqual(['/v1/send', '/v1/send'])
|
||||
expect(await readRelayCandidate(payload)).toBeNull()
|
||||
expect((await readRelayStore(payload)).token).toBe(working)
|
||||
})
|
||||
|
||||
test('is rate-limited per address', async () => {
|
||||
const { payload } = relayPayload()
|
||||
const confirm = callConfirmRoute(payload)
|
||||
const statuses: number[] = []
|
||||
for (let i = 0; i < 12; i++) {statuses.push((await confirm(`https://${HOST}/api/iapl/mail-relay/confirm`, { body: '{}', headers: {} })).status)}
|
||||
expect(statuses.slice(0, 10).every((s) => s === 404)).toBe(true)
|
||||
expect(statuses.slice(10)).toEqual([429, 429])
|
||||
})
|
||||
})
|
||||
|
||||
describe('when the service asks the site to enrol again', () => {
|
||||
test('a new server address (401 reverify): one enrolment, then the message goes out', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
fake.clientAddress = '198.51.100.20'
|
||||
const before = fake.requests.length
|
||||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Moved' })).sent).toBe(true)
|
||||
expect(fake.requests.slice(before).map((r) => r.path)).toEqual(['/v1/send', '/v1/enrol', '/v1/send'])
|
||||
expect(fake.outbox).toHaveLength(2)
|
||||
})
|
||||
|
||||
test('a token the service no longer knows (401 invalid-token): the same', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
const old = (await readRelayStore(payload)).token!
|
||||
await fake.handle(new Request(`${fake.url}/v1/revoke`, { headers: { authorization: `Bearer ${old}` }, method: 'POST' }))
|
||||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Again' })).sent).toBe(true)
|
||||
expect((await readRelayStore(payload)).token).not.toBe(old)
|
||||
})
|
||||
|
||||
test('a site enrols at most once per message, and a refused enrolment is not asked again for a while', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST], callSite: async () => new Response(null, { status: 404 }) } })
|
||||
const first = await sendThroughRelay(payload, options, MESSAGE)
|
||||
expect(first).toMatchObject({ cause: 'callback-failed', code: 'relay-refused', sent: false })
|
||||
expect(first.sent === false && first.detail).toContain('confirm address')
|
||||
expect(fake.requests.map((r) => r.path)).toEqual(['/v1/enrol'])
|
||||
// the next message does not make the service call back again (a time-out there costs 8 seconds a message)
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
expect(fake.requests.map((r) => r.path)).toEqual(['/v1/enrol'])
|
||||
expect((await getRelayStatus(payload, options)).refusal).toMatchObject({ code: 'callback-failed', reason: 'status' })
|
||||
// "Connect again" asks at once
|
||||
expect((await enrolRelay(payload, options, { force: true })).ok).toBe(false)
|
||||
expect(fake.requests.map((r) => r.path)).toEqual(['/v1/enrol', '/v1/enrol'])
|
||||
})
|
||||
|
||||
test('the answer to /v1/enrol is lost: the delivered token is tried next and becomes the token once the service accepts it', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
fake.intercept = async (request) => {
|
||||
if (!request.url.endsWith('/v1/enrol')) {return undefined}
|
||||
fake.intercept = undefined
|
||||
await fake.handle(request) // the service does everything, call-back included …
|
||||
return 'drop' // … and its answer never arrives
|
||||
}
|
||||
// The enrolment has no answer, but the call-back did deliver a token: the message's next attempt tries it,
|
||||
// the service accepts it, and it becomes the token — without a second enrolment.
|
||||
const first = await sendThroughRelay(payload, options, MESSAGE)
|
||||
expect(first.sent).toBe(true)
|
||||
expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1)
|
||||
expect(fake.outbox).toHaveLength(1)
|
||||
expect((await readRelayStore(payload)).token).toMatch(/^ims_/)
|
||||
expect(await readRelayCandidate(payload)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('one message: one key, one encoding, three attempts', () => {
|
||||
const capture = (fake: ReturnType<typeof relaySite>['fake'], answers: Array<'drop' | 'pass' | Response>) => {
|
||||
const sends: { body: string; key: null | string }[] = []
|
||||
fake.intercept = async (request) => {
|
||||
if (!request.url.endsWith('/v1/send')) {return undefined}
|
||||
sends.push({ body: await request.clone().text(), key: request.headers.get('idempotency-key') })
|
||||
const next = answers.shift() ?? 'pass'
|
||||
return next === 'pass' ? undefined : next
|
||||
}
|
||||
return sends
|
||||
}
|
||||
const failing = (status: number, body: Record<string, unknown>) => Response.json({ message: 'x', ok: false, ...body }, { status })
|
||||
const ready = async () => {
|
||||
const site = relaySite({ fake: { allow: [HOST] } })
|
||||
await enrolRelay(site.payload, site.options)
|
||||
return site
|
||||
}
|
||||
|
||||
test('a retryable failure is tried again with the same key and the same bytes; the third attempt is the last', async () => {
|
||||
const { fake, options, payload } = await ready()
|
||||
const sends = capture(fake, [failing(502, { code: 'backend-failed', retryable: true }), failing(503, { code: 'unavailable', retryable: true })])
|
||||
const result = await sendThroughRelay(payload, options, MESSAGE)
|
||||
expect(result.sent).toBe(true)
|
||||
expect(sends).toHaveLength(3)
|
||||
expect(new Set(sends.map((s) => s.key)).size).toBe(1)
|
||||
expect(sends[0].key).toMatch(/^[\w-]{16,128}$/)
|
||||
expect(new Set(sends.map((s) => s.body)).size).toBe(1)
|
||||
expect(fake.outbox).toHaveLength(1)
|
||||
|
||||
const more = capture(fake, [1, 2, 3, 4].map(() => failing(502, { code: 'backend-failed', retryable: true })))
|
||||
const failed = await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Other' })
|
||||
expect(more).toHaveLength(3)
|
||||
expect(failed).toMatchObject({ cause: 'backend-failed', code: 'relay-unreachable', confirmed: true, sent: false })
|
||||
expect(failed.sent === false && failed.detail).toMatch(/^Probably not sent/)
|
||||
})
|
||||
|
||||
test('an answer that is not retryable is final: one request', async () => {
|
||||
const { fake, options, payload } = await ready()
|
||||
for (const [status, body, code] of [
|
||||
[429, { code: 'quota-exceeded', limit: 'hour', retryable: false }, 'relay-quota'],
|
||||
[422, { code: 'recipient-suppressed', retryable: false }, 'relay-recipient-suppressed'],
|
||||
[413, { code: 'too-large', limit: 'attachments', retryable: false }, 'relay-too-large'],
|
||||
[422, { code: 'attachment-refused', field: 'attachments[0]', retryable: false }, 'relay-attachment-refused'],
|
||||
[400, { code: 'invalid-request', field: 'subject', retryable: false }, 'relay-error'],
|
||||
[418, { code: 'a-code-of-next-year', retryable: false }, 'relay-error'],
|
||||
] as const) {
|
||||
const sends = capture(fake, [failing(status, body)])
|
||||
expect(await sendThroughRelay(payload, options, { ...MESSAGE, subject: code })).toMatchObject({ code, confirmed: true, sent: false })
|
||||
expect(sends).toHaveLength(1)
|
||||
}
|
||||
})
|
||||
|
||||
test('the ten seconds win over retryAfter: a long wait is not waited, the message is reported at once', async () => {
|
||||
const { fake, options, payload } = await ready()
|
||||
const sends = capture(fake, [Response.json({ code: 'rate-limited', message: 'x', ok: false, retryable: true, retryAfter: 60 }, { headers: { 'retry-after': '60' }, status: 429 })])
|
||||
const started = Date.now()
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ cause: 'rate-limited', code: 'relay-unreachable', sent: false })
|
||||
expect(sends).toHaveLength(1)
|
||||
expect(Date.now() - started).toBeLessThan(2000)
|
||||
})
|
||||
|
||||
test('an answer that is not JSON (an error page of the network in front) is "unavailable": retried, then not sent', async () => {
|
||||
const { fake, options, payload } = await ready()
|
||||
const page = () => new Response('<html>502 Bad Gateway</html>', { headers: { 'content-type': 'text/html' }, status: 502 })
|
||||
const sends = capture(fake, [page(), page(), page()])
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ cause: 'unavailable', code: 'relay-unreachable', confirmed: true, sent: false })
|
||||
expect(sends).toHaveLength(3)
|
||||
// also a 200 whose body is not the contract's
|
||||
const odd = capture(fake, [new Response('', { status: 200 }), Response.json(['ok']), Response.json({ ok: true }, { status: 201 })])
|
||||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Odd' })).sent).toBe(false)
|
||||
expect(odd).toHaveLength(3)
|
||||
})
|
||||
|
||||
test('no answer at all is "not confirmed", never "not sent" — and the same message later goes out under the same key', async () => {
|
||||
const { fake, options, payload, settings } = await ready()
|
||||
const adapter = adapterOf(mailAdapter({ relay: options }), payload)
|
||||
// the service takes the message; the connection breaks before its answer arrives, three times
|
||||
const lose = async (request: Request) => {
|
||||
if (!request.url.endsWith('/v1/send')) {return undefined}
|
||||
await fake.handle(request)
|
||||
return 'drop' as const
|
||||
}
|
||||
const keys: (null | string)[] = []
|
||||
fake.intercept = async (request) => {
|
||||
if (request.url.endsWith('/v1/send')) {keys.push(request.headers.get('idempotency-key'))}
|
||||
const saved = fake.intercept
|
||||
fake.intercept = undefined
|
||||
try {
|
||||
return await lose(request)
|
||||
} finally {
|
||||
fake.intercept = saved
|
||||
}
|
||||
}
|
||||
const result = (await adapter.sendEmail(MESSAGE)) as Record<string, unknown>
|
||||
expect(result).toMatchObject({ code: 'relay-not-confirmed', confirmed: false, sent: false })
|
||||
expect(String(result.error)).toMatch(/may not have been sent/)
|
||||
expect(settings.emailStatus).toMatchObject({ code: 'relay-not-confirmed', state: 'degraded' })
|
||||
expect(keys).toHaveLength(3)
|
||||
expect(fake.outbox).toHaveLength(1) // it did go out, once
|
||||
|
||||
// somebody sends the same message again: same key, the service answers with the first result — no second mail
|
||||
fake.intercept = async (request) => void (request.url.endsWith('/v1/send') && keys.push(request.headers.get('idempotency-key')))
|
||||
const again = (await adapter.sendEmail(MESSAGE)) as Record<string, unknown>
|
||||
expect(again).toMatchObject({ replayed: true, sent: true })
|
||||
expect(new Set(keys).size).toBe(1)
|
||||
expect(fake.outbox).toHaveLength(1)
|
||||
// once confirmed, the same content is a new message again
|
||||
await adapter.sendEmail(MESSAGE)
|
||||
expect(new Set(keys).size).toBe(2)
|
||||
expect(fake.outbox).toHaveLength(2)
|
||||
})
|
||||
|
||||
test('409 in-progress is "not confirmed" too', async () => {
|
||||
const { fake, options, payload } = await ready()
|
||||
capture(fake, [1, 2, 3].map(() => Response.json({ code: 'in-progress', message: 'x', ok: false, retryable: true, retryAfter: 1 }, { status: 409 })))
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-not-confirmed', confirmed: false, sent: false })
|
||||
}, 15_000)
|
||||
|
||||
test('one attempt has a time-out, and a timed-out attempt is "no answer"', async () => {
|
||||
const { fake, options, payload } = await ready()
|
||||
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 result = await sendThroughRelay(payload, { ...options, fetchImpl: hanging, timeoutMs: 20 }, MESSAGE)
|
||||
expect(result).toMatchObject({ code: 'relay-not-confirmed', confirmed: false, sent: false })
|
||||
expect(fake.outbox).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('what the site sends', () => {
|
||||
test('bare addresses only, a subject without what the service refuses, files as base64, nothing else', () => {
|
||||
expect(bareAddresses('Anna Nowak <[email protected]>, "Kowalski, Jan" <[email protected]>; [email protected]').addresses).toEqual(['[email protected]', '[email protected]', '[email protected]'])
|
||||
expect(bareAddresses([{ name: 'A', address: '[email protected]' }, '[email protected]', 'not an address', 'info@żółw.pl'])).toEqual({ addresses: ['[email protected]', '[email protected]'], dropped: 1 })
|
||||
expect(cleanSubject('Hello\r\nBcc: [email protected]')).toBe('Hello Bcc: [email protected]')
|
||||
expect(cleanSubject('Invoice fdp.exe')).toBe('Invoice fdp.exe')
|
||||
expect(cleanSubject('\u{1F469}\u{1F4BB} Straßenbahn')).toBe('\u{1F469}\u{1F4BB} Straßenbahn')
|
||||
expect(cleanSubject('[Intecion Notifications Webservice] example.com waits for approval')).toBe('Intecion Notifications Webservice] example.com waits for approval')
|
||||
expect([...cleanSubject('x'.repeat(400))]).toHaveLength(300)
|
||||
expect(cleanSubject(' \n ')).toBe('(no subject)')
|
||||
|
||||
const built = buildRelayMessage(
|
||||
{
|
||||
attachments: [{ content: Buffer.from('%PDF-1.7'), contentType: 'application/pdf; name="cv.pdf"', filename: '../"cv".pdf' }, { content: Buffer.alloc(0), filename: 'empty.txt' }],
|
||||
bcc: '[email protected]', cc: ['[email protected]'], from: '[email protected]', headers: { 'Return-Path': '[email protected]' }, html: '<p>Hi</p>', replyTo: '[email protected], [email protected]', subject: 'Hi', text: 'Hi', to: '[email protected]',
|
||||
} as never,
|
||||
{ kind: 'form-notification', senderName: ' Kancelaria Example ' },
|
||||
)
|
||||
expect(built.ok && built.request).toEqual({
|
||||
attachments: [{ content: Buffer.from('%PDF-1.7').toString('base64'), contentType: 'application/pdf', filename: '_cv_.pdf' }],
|
||||
bcc: ['[email protected]'], cc: ['[email protected]'], html: '<p>Hi</p>', kind: 'form-notification', product: 'iapl', productVersion: expect.stringMatching(/^\d+\.\d+\.\d+/) as string,
|
||||
replyTo: '[email protected]', senderName: 'Kancelaria Example', subject: 'Hi', text: 'Hi', to: ['[email protected]'],
|
||||
})
|
||||
expect(buildRelayMessage({ subject: 'x', to: 'nobody' } as never)).toMatchObject({ ok: false })
|
||||
expect(buildRelayMessage({ subject: 'x', to: '[email protected]' } as never)).toMatchObject({ ok: false })
|
||||
expect(buildRelayMessage({ html: 'x', subject: 'x' } as never, { kind: 'security-alert' })).toMatchObject({ ok: true })
|
||||
})
|
||||
|
||||
test('a message the service would refuse for its shape still goes out (a visitor\'s words in the subject)', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
const result = await sendThroughRelay(payload, options, { html: '<p>x</p>', subject: 'Pytanie\r\nBcc: [email protected] ', to: 'Biuro <[email protected]>' })
|
||||
expect(result.sent).toBe(true)
|
||||
expect(fake.outbox[0]).toMatchObject({ subject: 'Pytanie Bcc: [email protected]', to: ['[email protected]'] })
|
||||
})
|
||||
|
||||
test('a sender name the service does not accept: the mail goes out under the host, and the panel is told', async () => {
|
||||
const { fake, logger, options, payload, settings } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpFromName: 'PayPal Support' } })
|
||||
const adapter = adapterOf(mailAdapter({ relay: options }), payload)
|
||||
const result = (await adapter.sendEmail(MESSAGE)) as Record<string, unknown>
|
||||
expect(result).toMatchObject({ senderName: HOST, sent: true, warnings: ['sender-name-replaced'] })
|
||||
expect(settings.emailStatus).toBeUndefined() // a warning, not a failure
|
||||
expect((await getRelayStatus(payload, options)).nameReplaced).toMatchObject({ asked: 'PayPal Support', used: HOST })
|
||||
expect(logger.warn).toHaveBeenCalledTimes(1)
|
||||
await adapter.sendEmail(MESSAGE)
|
||||
expect(logger.warn).toHaveBeenCalledTimes(1) // said once, not on every message
|
||||
// a better name clears it
|
||||
settings.smtpFromName = 'Kancelaria Example'
|
||||
await adapter.sendEmail(MESSAGE)
|
||||
expect((await getRelayStatus(payload, options)).nameReplaced).toBeUndefined()
|
||||
expect(fake.outbox[2].fromName).toBe('Kancelaria Example')
|
||||
})
|
||||
|
||||
test('the limit on files comes from the service, and a file over it is not uploaded to hear so', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST], limits: { maxAttachmentBytes: 1000 } } })
|
||||
const adapter = adapterOf(mailAdapter({ relay: options }), payload)
|
||||
expect(await adapter.attachmentLimit?.()).toBeNull() // not enrolled yet: no number of the plugin's own
|
||||
await adapter.sendEmail(MESSAGE)
|
||||
expect(await adapter.attachmentLimit?.()).toBe(1000)
|
||||
const before = fake.requests.length
|
||||
const result = (await adapter.sendEmail({ ...MESSAGE, attachments: [{ content: Buffer.alloc(1001), filename: 'big.bin' }] })) as Record<string, unknown>
|
||||
expect(result).toMatchObject({ code: 'relay-too-large', sent: false })
|
||||
expect(fake.requests.slice(before).filter((r) => r.path === '/v1/send')).toHaveLength(0)
|
||||
expect(((await adapter.sendEmail({ ...MESSAGE, attachments: [{ content: Buffer.alloc(1000), filename: 'ok.bin' }] })) as { sent: boolean }).sent).toBe(true)
|
||||
expect(fake.outbox.at(-1)?.attachments).toEqual([{ bytes: 1000, contentType: 'application/octet-stream', filename: 'ok.bin' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('account mail is limited by the site itself', () => {
|
||||
test('per address: the sixth "forgot password" for one address within the hour is held back, without a request', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
const send = (to: string) => sendThroughRelay(payload, options, withMailKind({ html: 'reset', subject: 'Reset your password', to }, 'account'))
|
||||
for (let i = 0; i < 5; i++) {expect((await send('[email protected]')).sent).toBe(true)}
|
||||
const before = fake.requests.length
|
||||
expect(await send('[email protected]')).toMatchObject({ cause: 'client-account-mail-limit', code: 'relay-quota', sent: false })
|
||||
expect(fake.requests.length).toBe(before)
|
||||
expect((await send('[email protected]')).sent).toBe(true) // another account holder is not affected
|
||||
expect(fake.outbox.every((m) => m.kind === 'account')).toBe(true)
|
||||
})
|
||||
|
||||
test('the limit is the project\'s to change or switch off, and other kinds are not counted', async () => {
|
||||
const strict = relaySite({ fake: { allow: [HOST] }, options: { accountMail: { perAddress: 1 } } })
|
||||
const account = withMailKind({ html: 'x', subject: 'Reset', to: '[email protected]' }, 'account')
|
||||
expect((await sendThroughRelay(strict.payload, strict.options, account)).sent).toBe(true)
|
||||
expect((await sendThroughRelay(strict.payload, strict.options, account)).sent).toBe(false)
|
||||
clearRateLimits()
|
||||
const off = relaySite({ fake: { allow: [HOST], limits: { messagesPerHour: 100 } }, options: { accountMail: false } })
|
||||
for (let i = 0; i < 8; i++) {expect((await sendThroughRelay(off.payload, off.options, { ...account, subject: `Reset ${i}` })).sent).toBe(true)}
|
||||
clearRateLimits()
|
||||
const forms = relaySite({ fake: { allow: [HOST] } })
|
||||
for (let i = 0; i < 8; i++) {expect((await sendThroughRelay(forms.payload, forms.options, withMailKind({ ...MESSAGE, subject: `Form ${i}` }, 'form-notification'))).sent).toBe(true)}
|
||||
})
|
||||
})
|
||||
|
||||
describe('the token over time', () => {
|
||||
test('rotation when the service says the token is due; the new token is stored at once', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
await refreshRelayStatus(payload, options)
|
||||
const first = (await readRelayStore(payload)).token
|
||||
expect((await readRelayStore(payload)).service?.rotateAfter).toBeTruthy()
|
||||
expect(await rotateRelayToken(payload, options)).toBe('not-due')
|
||||
await updateRelayStore(payload, (c) => ({ ...c, service: { ...c.service!, rotateAfter: new Date(Date.now() - 1000).toISOString() } }))
|
||||
const before = fake.requests.length
|
||||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Day 91' })).sent).toBe(true)
|
||||
expect(fake.requests.slice(before).map((r) => r.path).slice(0, 2)).toEqual(['/v1/rotate', '/v1/send'])
|
||||
const second = (await readRelayStore(payload)).token
|
||||
expect(second).not.toBe(first)
|
||||
expect(second).toMatch(/^ims_/)
|
||||
})
|
||||
|
||||
test('two containers of one site: one rotation wins, the other reads the shared store and carries on', async () => {
|
||||
const a = relaySite({ fake: { allow: [HOST] } })
|
||||
// the second container: its own process, the same database
|
||||
const b = relayPayload()
|
||||
;(b.payload as unknown as { kv: unknown }).kv = (a.payload as unknown as { kv: unknown }).kv
|
||||
await sendThroughRelay(a.payload, a.options, MESSAGE)
|
||||
const old = (await readRelayStore(a.payload)).token!
|
||||
expect(await rotateRelayToken(a.payload, a.options, { force: true })).toBe('rotated')
|
||||
const fresh = (await readRelayStore(b.payload)).token
|
||||
expect(fresh).not.toBe(old)
|
||||
// a container that still held the old token asks too: already-rotated — the store has the newer one, nothing is lost
|
||||
const late = await a.fake.handle(new Request(`${a.fake.url}/v1/rotate`, { headers: { authorization: `Bearer ${old}` }, method: 'POST' }))
|
||||
expect(((await late.json()) as { code: string }).code).toBe('already-rotated')
|
||||
expect((await sendThroughRelay(b.payload, a.options, { ...MESSAGE, subject: 'From B' })).sent).toBe(true)
|
||||
expect((await readRelayStore(a.payload)).token).toBe(fresh)
|
||||
})
|
||||
|
||||
test('already-rotated with no newer token in the store: the token is dropped and the next send enrols at once', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
const old = (await readRelayStore(payload)).token!
|
||||
// another process rotated and its answer was lost: the store still has the old token
|
||||
await fake.handle(new Request(`${fake.url}/v1/rotate`, { headers: { authorization: `Bearer ${old}` }, method: 'POST' }))
|
||||
expect(await rotateRelayToken(payload, options, { force: true })).toBe('failed')
|
||||
expect((await readRelayStore(payload)).token).toBeUndefined()
|
||||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Healed' })).sent).toBe(true)
|
||||
expect((await readRelayStore(payload)).token).not.toBe(old)
|
||||
})
|
||||
|
||||
test('"Disconnect" gives the token up and stops the site from enrolling by itself; "Connect again" brings it back', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
const old = (await readRelayStore(payload)).token!
|
||||
await disconnectRelay(payload, options)
|
||||
expect(await readRelayStore(payload)).toEqual({ disconnected: true, v: 1 })
|
||||
const refusedByService = await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${old}` } }))
|
||||
expect(refusedByService.status).toBe(401)
|
||||
const before = fake.requests.length
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-disconnected', sent: false })
|
||||
expect(fake.requests.length).toBe(before)
|
||||
expect((await enrolRelay(payload, options, { force: true })).ok).toBe(true)
|
||||
expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true)
|
||||
})
|
||||
|
||||
test('a token issued by hand is stored the same way; enrol: "manual" and enrol: false never enrol by themselves', async () => {
|
||||
const manual = relaySite({ options: { enrol: 'manual' } })
|
||||
expect(await sendThroughRelay(manual.payload, manual.options, MESSAGE)).toMatchObject({ code: 'relay-refused', sent: false })
|
||||
expect(manual.fake.requests).toEqual([])
|
||||
await expect(setRelayToken(manual.payload, 'not-a-token')).rejects.toThrow()
|
||||
await setRelayToken(manual.payload, manual.fake.issueToken(HOST))
|
||||
expect((await sendThroughRelay(manual.payload, manual.options, MESSAGE)).sent).toBe(true)
|
||||
expect(manual.fake.requests.map((r) => r.path)).not.toContain('/v1/enrol')
|
||||
expect((await getRelayStatus(manual.payload, manual.options)).tokenSource).toBe('manual')
|
||||
|
||||
// a relay of one's own with a token from the deployment: nothing stored, nothing enrolled
|
||||
const own = relaySite()
|
||||
const token = own.fake.issueToken(HOST)
|
||||
const options = { ...own.options, enrol: false as const, token: () => token }
|
||||
expect((await sendThroughRelay(own.payload, options, MESSAGE)).sent).toBe(true)
|
||||
expect((await readRelayStore(own.payload)).token).toBeUndefined()
|
||||
expect((await getRelayStatus(own.payload, options)).tokenSource).toBe('option')
|
||||
expect(await sendThroughRelay(own.payload, { ...own.options, token: () => undefined }, MESSAGE)).toMatchObject({ code: 'relay-refused', sent: false })
|
||||
})
|
||||
})
|
||||
|
||||
describe('the adapter on its own, and the deprecated Graph line', () => {
|
||||
test('relayAdapter() is a whole e-mail adapter', async () => {
|
||||
const { fake, payload } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpFromName: 'Kancelaria Example' } })
|
||||
const adapter = adapterOf(relayAdapter({ fetchImpl: fake.fetch, url: fake.url }), payload)
|
||||
expect(adapter).toMatchObject({ name: 'iapl-relay', defaultFromAddress: '[email protected]' })
|
||||
expect(((await adapter.sendEmail(MESSAGE)) as { sent: boolean }).sent).toBe(true)
|
||||
expect(fake.outbox[0].fromName).toBe('Kancelaria Example')
|
||||
})
|
||||
|
||||
test('a site on Microsoft Graph is told once per process that the transport is deprecated, and can silence it', async () => {
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
const fetchImpl = (async () => Response.json({ access_token: 'a.b.c', expires_in: 3600 })) as unknown as typeof fetch
|
||||
const loud = relaySite({ integrations: { emailTransport: 'graph', smtpFromAddress: '[email protected]' } })
|
||||
const adapter = adapterOf(mailAdapter({ graph: { fetchImpl }, relay: loud.options }), loud.payload)
|
||||
await adapter.sendEmail(MESSAGE)
|
||||
await adapter.sendEmail(MESSAGE)
|
||||
const warnings = loud.logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('deprecated'))
|
||||
expect(warnings).toHaveLength(1)
|
||||
expect(warnings[0]).toContain('removed in 2.0')
|
||||
expect(loud.fake.requests).toEqual([]) // Graph in use: the service is not contacted
|
||||
|
||||
resetGraphDeprecationWarning()
|
||||
const quiet = relaySite({ custom: { iapl: { mail: { graphDeprecationWarning: false, relay: {} } } }, integrations: { emailTransport: 'graph' } })
|
||||
await adapterOf(mailAdapter({ graph: { fetchImpl } }), quiet.payload).sendEmail(MESSAGE)
|
||||
expect(quiet.logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('deprecated'))).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { vi } from 'vitest'
|
||||
|
||||
import type { FakeRelayOptions } from '../../src/modules/email/relay/fake.js'
|
||||
import type { RelayOptions, ResolvedRelayOptions } from '../../src/modules/email/relay/options.js'
|
||||
|
||||
import { relayConfirmEndpoint } from '../../src/modules/email/relay/confirm.js'
|
||||
import { createFakeRelay } from '../../src/modules/email/relay/fake.js'
|
||||
import { resolveRelayOptions } from '../../src/modules/email/relay/options.js'
|
||||
|
||||
export const CONTRACT_DIR = path.resolve(import.meta.dirname, '../../contracts/mail-relay')
|
||||
|
||||
export type ContractExample = {
|
||||
client?: { reEnrol?: boolean; retry?: boolean; status?: null | string }
|
||||
direction?: string
|
||||
given?: Record<string, boolean | string>
|
||||
id: string
|
||||
request: { body?: unknown; headers?: Record<string, string>; method: string; path: string; schema?: string }
|
||||
response: { body?: Record<string, unknown>; schema?: string; status: number }
|
||||
then?: { mail?: Record<string, unknown>; mails?: number }
|
||||
}
|
||||
|
||||
export const contractExamples = (): ContractExample[] =>
|
||||
readdirSync(path.join(CONTRACT_DIR, 'examples'))
|
||||
.filter((f) => f.endsWith('.json'))
|
||||
.sort()
|
||||
.map((f) => JSON.parse(readFileSync(path.join(CONTRACT_DIR, 'examples', f), 'utf8')) as ContractExample)
|
||||
|
||||
/** The slice of Payload the relay client touches: the key-value store, the config, the logger, the two globals. */
|
||||
export function relayPayload({ custom, integrations = {}, serverURL = 'https://example.com', siteName = '' }: { custom?: object; integrations?: Record<string, unknown>; serverURL?: string; siteName?: string } = {}) {
|
||||
const store = new Map<string, unknown>()
|
||||
const logger = { error: vi.fn(), info: vi.fn(), warn: vi.fn() }
|
||||
const settings = { ...integrations }
|
||||
const payload = {
|
||||
config: { custom: custom ?? {}, globals: [{ slug: 'site-integrations' }, { slug: 'site-settings' }], routes: { api: '/api' }, serverURL },
|
||||
findGlobal: vi.fn(async ({ slug }: { slug: string }) => (slug === 'site-settings' ? { siteName } : settings)),
|
||||
kv: {
|
||||
delete: async (key: string) => void store.delete(key),
|
||||
get: async (key: string) => (store.has(key) ? structuredClone(store.get(key)) : null),
|
||||
set: async (key: string, value: object) => void store.set(key, structuredClone(value)),
|
||||
},
|
||||
logger,
|
||||
updateGlobal: vi.fn(async ({ data }: { data: Record<string, unknown> }) => Object.assign(settings, data)),
|
||||
}
|
||||
return { logger, payload: payload as unknown as BasePayload, settings, store }
|
||||
}
|
||||
|
||||
/** How the fake service reaches this site's confirm route: straight into the endpoint's handler. */
|
||||
export function callConfirmRoute(payload: BasePayload) {
|
||||
const endpoint = relayConfirmEndpoint()
|
||||
return async (url: string, init: { body: string; headers: Record<string, string> }): Promise<Response> => {
|
||||
const target = new URL(url)
|
||||
if (target.pathname !== '/api/iapl/mail-relay/confirm') {return new Response(null, { status: 404 })}
|
||||
const req = { headers: new Headers({ ...init.headers, 'x-forwarded-for': '198.51.100.7' }), payload, text: async () => init.body, url }
|
||||
return (await endpoint.handler(req as never))
|
||||
}
|
||||
}
|
||||
|
||||
/** A site (the payload double) and a fake service that can call it back. */
|
||||
export function relaySite({ fake: fakeOptions, options: own, ...site }: { fake?: FakeRelayOptions; options?: RelayOptions } & Parameters<typeof relayPayload>[0] = {}) {
|
||||
const made = relayPayload(site)
|
||||
const fake = createFakeRelay({ callSite: callConfirmRoute(made.payload), ...fakeOptions })
|
||||
const options = resolveRelayOptions(made.payload, { fetchImpl: fake.fetch, retryBackoffMs: 1, url: fake.url, ...own }) as ResolvedRelayOptions
|
||||
return { ...made, fake, options }
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
/**
|
||||
* The plugin's copy of the wire contract of the Intecion Notifications Webservice (contracts/mail-relay,
|
||||
* copied from the IWDL repository), and both sides of it as the plugin has them:
|
||||
* - the copy is unedited (checksums) and is the version the client says it speaks;
|
||||
* - the fake service (createFakeRelay) passes every example, through the contract's own runner;
|
||||
* - the client does with each canned answer what the example's `client` block says: retry or not,
|
||||
* enrol again or not, and the site status it reports;
|
||||
* - the site's confirm route answers the call-back examples.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { RELAY_BASE_URL, RELAY_CONFIRM_PATH, RELAY_CONTRACT_VERSION, RELAY_STATUS_CODES } from '../src/modules/email/relay/constants.js'
|
||||
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
|
||||
import { sendThroughRelay } from '../src/modules/email/relay/send.js'
|
||||
import { enrolRelay, refreshRelayStatus } from '../src/modules/email/relay/session.js'
|
||||
import { holdNonce, readRelayCandidate, updateRelayStore } from '../src/modules/email/relay/store.js'
|
||||
// the contract's runner is plain JavaScript, copied as it is
|
||||
import { CONTRACT_VERSION, expand, runCallbackExample, runExample } from '../contracts/mail-relay/runner.mjs'
|
||||
import { callConfirmRoute, CONTRACT_DIR, contractExamples, relayPayload, relaySite } from './mailRelay/helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const schema = JSON.parse(readFileSync(path.join(CONTRACT_DIR, 'schema.json'), 'utf8')) as { $defs: Record<string, Schema> }
|
||||
type Schema = { [key: string]: unknown }
|
||||
|
||||
/** The part of JSON Schema 2020-12 the contract uses. Returns the problems found. */
|
||||
function validate(node: Schema, value: unknown, at = 'value'): string[] {
|
||||
const out: string[] = []
|
||||
if (typeof node.$ref === 'string') {return validate(schema.$defs[node.$ref.replace('#/$defs/', '')], value, at)}
|
||||
if ('const' in node && value !== node.const) {out.push(`${at}: not ${JSON.stringify(node.const)}`)}
|
||||
if (Array.isArray(node.enum) && !node.enum.includes(value)) {out.push(`${at}: not one of ${node.enum.join(', ')}`)}
|
||||
const type = node.type as string | undefined
|
||||
const actual = Array.isArray(value) ? 'array' : value === null ? 'null' : Number.isInteger(value) ? 'integer' : typeof value
|
||||
if (type && type !== actual && !(type === 'number' && actual === 'integer')) {return [...out, `${at}: ${actual}, expected ${type}`]}
|
||||
if (typeof value === 'string') {
|
||||
if (typeof node.minLength === 'number' && [...value].length < node.minLength) {out.push(`${at}: too short`)}
|
||||
if (typeof node.maxLength === 'number' && [...value].length > node.maxLength) {out.push(`${at}: too long`)}
|
||||
if (typeof node.pattern === 'string' && !new RegExp(node.pattern, 'u').test(value)) {out.push(`${at}: does not match ${node.pattern}`)}
|
||||
}
|
||||
if (typeof value === 'number' && typeof node.minimum === 'number' && value < node.minimum) {out.push(`${at}: below ${node.minimum}`)}
|
||||
if (Array.isArray(value)) {
|
||||
if (typeof node.minItems === 'number' && value.length < node.minItems) {out.push(`${at}: too few items`)}
|
||||
if (typeof node.maxItems === 'number' && value.length > node.maxItems) {out.push(`${at}: too many items`)}
|
||||
if (node.items) {value.forEach((item, i) => out.push(...validate(node.items as Schema, item, `${at}[${i}]`)))}
|
||||
}
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
const object = value as Record<string, unknown>
|
||||
const properties = (node.properties ?? {}) as Record<string, Schema>
|
||||
for (const name of (node.required ?? []) as string[]) {
|
||||
if (!(name in object)) {out.push(`${at}: ${name} is missing`)}
|
||||
}
|
||||
for (const [name, child] of Object.entries(properties)) {
|
||||
if (name in object) {out.push(...validate(child, object[name], `${at}.${name}`))}
|
||||
}
|
||||
if (node.additionalProperties === false) {
|
||||
for (const name of Object.keys(object)) {
|
||||
if (!(name in properties)) {out.push(`${at}: unknown field ${name}`)}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const part of (node.allOf ?? []) as Schema[]) {out.push(...validate(part, value, at))}
|
||||
if (Array.isArray(node.anyOf) && !(node.anyOf as Schema[]).some((part) => validate(part, value, at).length === 0)) {out.push(`${at}: matches none of anyOf`)}
|
||||
if (node.not && validate(node.not as Schema, value, at).length === 0) {out.push(`${at}: matches what it must not`)}
|
||||
if (node.if) {
|
||||
const branch = validate(node.if as Schema, value, at).length === 0 ? node.then : node.else
|
||||
if (branch) {out.push(...validate(branch as Schema, value, at))}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const examples = contractExamples()
|
||||
const toService = examples.filter((e) => e.direction !== 'service-to-site')
|
||||
const HOST = 'example.com'
|
||||
const RECIPIENT = '[email protected]'
|
||||
const ALERTS = '[email protected]'
|
||||
const sha = async (text: string) => Buffer.from(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).toString('hex')
|
||||
|
||||
describe('the copied contract', () => {
|
||||
test('is unedited: every file matches CHECKSUMS', () => {
|
||||
const out = execFileSync('node', [path.join(CONTRACT_DIR, 'checksums.mjs'), '--check'], { encoding: 'utf8' })
|
||||
expect(out).toMatch(/files match CHECKSUMS/)
|
||||
})
|
||||
|
||||
test('is the version the client says it speaks, with the client\'s constants', () => {
|
||||
const version = readFileSync(path.join(CONTRACT_DIR, 'VERSION'), 'utf8').trim()
|
||||
expect(RELAY_CONTRACT_VERSION).toBe(version)
|
||||
expect(CONTRACT_VERSION).toBe(version)
|
||||
const readme = readFileSync(path.join(CONTRACT_DIR, 'README.md'), 'utf8')
|
||||
expect(readme).toContain(`**Base address: \`${RELAY_BASE_URL}\`**`)
|
||||
// the confirm path the service calls for this product, under Payload's default API route
|
||||
expect(readme).toContain(`| \`iapl\` | \`POST https://<host>/api${RELAY_CONFIRM_PATH}\` |`)
|
||||
expect(examples.find((e) => e.id === 'callback-confirm')?.request.path).toBe(`/api${RELAY_CONFIRM_PATH}`)
|
||||
})
|
||||
|
||||
test('has the examples this file expects', () => {
|
||||
expect(examples.length).toBeGreaterThanOrEqual(55)
|
||||
expect(toService.length).toBeGreaterThanOrEqual(52)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the fake service speaks the contract (the contract\'s runner, every example)', () => {
|
||||
for (const example of toService) {
|
||||
test(example.id, async () => {
|
||||
const given = example.given ?? {}
|
||||
const calls = { confirm: 0 }
|
||||
const fake = createFakeRelay({
|
||||
alertRecipient: ALERTS,
|
||||
callSite: async (_url, init) => {
|
||||
calls.confirm += 1
|
||||
const { nonce, token } = JSON.parse(init.body) as { nonce: string; token: string }
|
||||
switch (given.callback) {
|
||||
case 'no-content':
|
||||
return new Response(null, { status: 204 })
|
||||
case 'not-found':
|
||||
return new Response(null, { status: 404 })
|
||||
case 'redirect':
|
||||
return new Response(null, { headers: { location: 'https://www.example.com/' }, status: 301 })
|
||||
case 'wrong-confirmation':
|
||||
return Response.json({ confirmation: await sha(`${token}.${nonce}`) })
|
||||
default:
|
||||
return Response.json({ confirmation: await sha(`${nonce}.${token}`) })
|
||||
}
|
||||
},
|
||||
})
|
||||
let outboxStart = 0
|
||||
const driver = {
|
||||
arrange: async () => {
|
||||
let token = `ims_${'x'.repeat(43)}`
|
||||
if (given.listed === true) {fake.allow(HOST)}
|
||||
if (given.site && given.site !== 'none') {
|
||||
token = fake.setSite(HOST, given.site as 'active')
|
||||
if (given.token === 'previous') {
|
||||
// the token in {{token}} was replaced a moment ago
|
||||
const rotated = await fake.handle(new Request(`${fake.url}/v1/rotate`, { headers: { authorization: `Bearer ${token}` }, method: 'POST' }))
|
||||
expect(rotated.status).toBe(200)
|
||||
}
|
||||
if (given.token === 'unknown') {token = `ims_${'u'.repeat(43)}`}
|
||||
}
|
||||
const site = fake.site(HOST)
|
||||
if (site && given.quota === 'hour-exhausted') {site.hourOther = fake.limits.messagesPerHour}
|
||||
if (site && given.quota === 'day-exhausted') {site.dayOther = fake.limits.messagesPerDay}
|
||||
if (site && given.quota === 'hour-share-used') {site.hourOther = Math.floor((fake.limits.messagesPerHour * 4) / 5)}
|
||||
if (site && given.quota === 'recipient-exhausted') {site.confirmations.set(RECIPIENT, fake.limits.perRecipientPerDay)}
|
||||
if (given.backend) {fake.backend = given.backend as 'failure'}
|
||||
const vars = { alertRecipient: ALERTS, host: HOST, idempotencyKey: randomBytes(18).toString('base64url'), nonce: randomBytes(32).toString('base64url'), recipient: RECIPIENT, senderAddress: '[email protected]', token }
|
||||
if (given.idempotency === 'sent-same' || given.idempotency === 'sent-other') {
|
||||
const body = expand(example.request.body, vars, example.id) as Record<string, unknown>
|
||||
const first = await fake.handle(new Request(`${fake.url}/v1/send`, {
|
||||
body: JSON.stringify(given.idempotency === 'sent-same' ? body : { ...body, subject: 'Another message' }),
|
||||
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'idempotency-key': vars.idempotencyKey },
|
||||
method: 'POST',
|
||||
}))
|
||||
expect(first.status).toBe(200)
|
||||
}
|
||||
outboxStart = fake.outbox.length
|
||||
return vars
|
||||
},
|
||||
mails: async () => fake.outbox.slice(outboxStart),
|
||||
request: async ({ body, headers, method, path: route }: { body?: unknown; headers: Record<string, string>; method: string; path: string }) => {
|
||||
const response = await fake.handle(new Request(`${fake.url}${route}`, {
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
headers: { ...headers, ...(given.address === 'unknown' ? { 'x-fake-client-address': '198.51.100.99' } : {}) },
|
||||
method,
|
||||
}))
|
||||
return { body: (await response.json().catch(() => null)) as unknown, headers: Object.fromEntries(response.headers), status: response.status }
|
||||
},
|
||||
validate: (name: string, value: unknown) => validate(schema.$defs[name], value),
|
||||
}
|
||||
await runExample(example, driver)
|
||||
// a suspended site is not called back; a refused request never reaches the site either
|
||||
if (example.response.status === 403 || example.response.status === 400) {expect(calls.confirm).toBe(0)}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
describe('the client acts on each answer as the example says (canned answers)', () => {
|
||||
const KNOWN = new Set<string>(RELAY_STATUS_CODES)
|
||||
|
||||
for (const example of toService.filter((e) => e.client)) {
|
||||
test(example.id, async () => {
|
||||
const client = example.client!
|
||||
const route = example.request.path
|
||||
const canned: Record<string, unknown> = { message: 'canned', retryable: client.retry === true, ...example.response.body }
|
||||
// /v1/send answers `ok: true` in full when the example only states part of it
|
||||
const full: Record<string, unknown> = canned.ok === true && route === '/v1/send' ? { id: 'm1', quota: {}, replayed: false, senderName: HOST, warnings: [], ...canned } : canned
|
||||
const seen: string[] = []
|
||||
const { options, payload } = relaySite({
|
||||
options: {
|
||||
fetchImpl: (async (input: Request | string | URL) => {
|
||||
const target = String(input instanceof Request ? input.url : input)
|
||||
const called = target.slice(target.indexOf('/mail') + 5)
|
||||
seen.push(called)
|
||||
// the answer under test comes from the example's own route; an enrolment on the way is refused, so it shows
|
||||
if (called === route) {return Response.json(full, { status: example.response.status })}
|
||||
return Response.json({ code: 'enrolment-closed', message: 'closed', ok: false, retryable: false }, { status: 403 })
|
||||
}) as typeof fetch,
|
||||
},
|
||||
})
|
||||
if (route !== '/v1/enrol') {await updateRelayStore(payload, (c) => ({ ...c, host: HOST, state: 'active', token: `ims_${'t'.repeat(43)}` }))}
|
||||
|
||||
let status: null | string = null
|
||||
if (route === '/v1/send') {
|
||||
const result = await sendThroughRelay(payload, options, { html: '<p>Hello.</p>', subject: 'New enquiry', to: RECIPIENT })
|
||||
status = result.sent ? (result.warnings.includes('sender-name-replaced') ? 'relay-name-replaced' : null) : result.code
|
||||
expect(result.sent).toBe(full.ok === true)
|
||||
// retried with the same request exactly when the example says so — three attempts in all, never more
|
||||
expect(seen.filter((p) => p === '/v1/send').length).toBe(client.retry ? 3 : 1)
|
||||
} else if (route === '/v1/enrol') {
|
||||
const result = await enrolRelay(payload, options)
|
||||
// the canned `200` carries no call-back, so no token arrived: only the refusals say something here
|
||||
status = full.ok === true ? (full.state === 'pending' ? 'relay-pending' : null) : result.ok ? null : result.status
|
||||
expect(seen.filter((p) => p === '/v1/enrol').length).toBe(1)
|
||||
} else if (route === '/v1/status') {
|
||||
const { error, stored } = await refreshRelayStatus(payload, options)
|
||||
status = error ? null : stored.state === 'pending' ? 'relay-pending' : null
|
||||
} else {
|
||||
return // rotate, revoke: nothing a site reports
|
||||
}
|
||||
// enrols again exactly when the example says so
|
||||
if (route !== '/v1/enrol') {expect(seen.includes('/v1/enrol')).toBe(client.reEnrol === true)}
|
||||
if (client.status) {
|
||||
expect(status).toBe(client.status)
|
||||
// every status the contract suggests has a text of its own in the panel, or is the name warning
|
||||
expect(KNOWN.has(client.status)).toBe(true)
|
||||
} else if (full.ok !== true && !client.reEnrol && route === '/v1/send') {
|
||||
// "report a bug" answers: not sent, and said so
|
||||
expect(status).toBe('relay-error')
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
describe('the site\'s confirm route answers the call-back examples', () => {
|
||||
const ours = examples.filter((e) => e.direction === 'service-to-site' && e.request.path === `/api${RELAY_CONFIRM_PATH}`)
|
||||
|
||||
test('both IAPL examples are here', () => {
|
||||
expect(ours.map((e) => e.id).sort()).toEqual(['callback-confirm', 'callback-unknown-nonce'])
|
||||
})
|
||||
|
||||
for (const example of ours) {
|
||||
test(example.id, async () => {
|
||||
const { payload } = relayPayload()
|
||||
const confirm = callConfirmRoute(payload)
|
||||
let raw = ''
|
||||
const response = await runCallbackExample(example, {
|
||||
confirm: async (request: { body: unknown; headers: Record<string, string>; path: string }) => {
|
||||
const answer = await confirm(`https://${HOST}${request.path}`, { body: JSON.stringify(request.body), headers: request.headers })
|
||||
raw = await answer.text()
|
||||
return { body: raw ? (JSON.parse(raw) as unknown) : null, status: answer.status }
|
||||
},
|
||||
prepare: async (body: { held: boolean; nonce: string }) => {
|
||||
if (body.held) {await holdNonce(payload, body.nonce, 60_000)}
|
||||
},
|
||||
})
|
||||
const sent = example.request.body as { nonce: string; token: string }
|
||||
if (response.status === 200) {
|
||||
// exactly this object and nothing else
|
||||
expect(raw).toBe(JSON.stringify(example.response.body))
|
||||
expect(validate(schema.$defs.CallbackResponse, JSON.parse(raw))).toEqual([])
|
||||
expect((await readRelayCandidate(payload))?.token).toBe(sent.token)
|
||||
// single use: the same call again is a 404 and changes nothing
|
||||
expect((await confirm(`https://${HOST}/api${RELAY_CONFIRM_PATH}`, { body: JSON.stringify(sent), headers: {} })).status).toBe(404)
|
||||
} else {
|
||||
expect(raw).toBe('')
|
||||
expect(await readRelayCandidate(payload)).toBeNull()
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user