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]>
618 lines
39 KiB
TypeScript
618 lines
39 KiB
TypeScript
/**
|
||
* 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([])
|
||
})
|
||
})
|