/** * 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 { buildSmtpFields } from '../src/globals/SiteIntegrations/fields/smtp.js' import { adminTexts } from '../src/modules/admin-i18n/index.js' import { mailAdapter, resetGraphDeprecationWarning, resolveMailTransport } from '../src/modules/email/mailAdapter.js' import { withAccountMailMark } from '../src/modules/email/relay/accountMail.js' import { relayAdapter } from '../src/modules/email/relay/adapter.js' import { relayRequest } from '../src/modules/email/relay/client.js' import { RELAY_DEFAULTS, RELAY_SHORT_NAME } from '../src/modules/email/relay/constants.js' import { dropExpectedMail, expectMailTo, takeExpectedMail, withMailKind } from '../src/modules/email/relay/kinds.js' import { bareAddresses, buildRelayMessage, cleanSubject } from '../src/modules/email/relay/message.js' import { isPublicHost, relayHost, resolveRelayOptions } from '../src/modules/email/relay/options.js' import { mailPanelState } from '../src/modules/email/relay/panel.js' import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.js' import { disconnectRelay, enrolRelay, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken } from '../src/modules/email/relay/session.js' import { holdNonce, readRelayCandidate, readRelayStore, updateRelayStore } from '../src/modules/email/relay/store.js' import { setRateLimitStore } from '../src/modules/shared/rateLimit.js' import { callConfirmRoute, relayPayload, relaySite } from './mailRelay/helpers.js' vi.mock('server-only', () => ({})) const MESSAGE = { html: '

Hello.

', subject: 'New enquiry', to: 'office@example.org' } 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() 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 } & ReturnType const everythingLogged = (logger: Record) => 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: 'info@example.com' } 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: 'biuro@example.com', 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 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: 'notification@webservices.intecion.net', fromName: 'Kancelaria Example', headers: { 'X-Intecion-Product': 'iapl', 'X-Intecion-Site': HOST }, kind: 'form-notification', replyTo: 'biuro@example.com', subject: 'New enquiry', to: ['office@example.org'], }) // 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: 'biuro@example.com' }, siteName: 'Example Sp. z o.o.' }) const adapter = adapterOf(mailAdapter({ relay: options }), payload) await adapter.sendEmail({ ...MESSAGE, replyTo: 'Jan Kowalski ' }) expect(fake.outbox[0]).toMatchObject({ fromName: 'Example Sp. z o.o.', replyTo: 'jan@example.org' }) // 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 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}`, 'x-intecion-site': HOST }, method: 'POST' })) expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Again' })).sent).toBe(true) expect((await readRelayStore(payload)).token).not.toBe(old) }) test('a service that keeps refusing the token: one enrolment for the message, not a loop', async () => { const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) await sendThroughRelay(payload, options, MESSAGE) fake.intercept = (request) => request.url.endsWith('/v1/send') ? Response.json({ code: 'invalid-token', message: 'x', ok: false, retryable: false }, { status: 401 }) : undefined const before = fake.requests.length const result = await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Refused twice' }) expect(result).toMatchObject({ cause: 'invalid-token', code: 'relay-refused', sent: false }) expect(fake.requests.slice(before).filter((r) => r.path === '/v1/enrol')).toHaveLength(1) }) 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 service cannot be reached at all: one enrolment is tried, nothing is sent, and the status says "unreachable"', async () => { const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) fake.intercept = () => 'drop' const result = await sendThroughRelay(payload, options, MESSAGE) // the message never left the site, so it is "not sent" (confirmed), not "may have been sent" expect(result).toMatchObject({ cause: 'unavailable', code: 'relay-unreachable', confirmed: true, sent: false }) expect(fake.outbox).toHaveLength(0) // not a refusal: the next message tries again at once fake.intercept = undefined expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true) }) 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['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) => 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 the service\'s JSON: retried; "not confirmed" unless its status is 400 to 499 (contract 1.6.0)', async () => { const { fake, options, payload } = await ready() const page = (status = 502) => new Response(`${status}`, { headers: { 'content-type': 'text/html' }, status }) // an error page of the network in front, after the service may have handled the request: it may be out const sends = capture(fake, [page(), page(), page()]) expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ cause: 'unavailable', code: 'relay-not-confirmed', confirmed: false, sent: false }) expect(sends).toHaveLength(3) // turned away before the service handled it (a firewall's 403, a proxy's 404): not sent, and said so for (const status of [400, 403, 404, 499]) { const refusedInFront = capture(fake, [page(status), page(status), page(status)]) expect(await sendThroughRelay(payload, options, { ...MESSAGE, subject: `Blocked ${status}` })).toMatchObject({ cause: 'unavailable', code: 'relay-unreachable', confirmed: true, sent: false }) expect(refusedInFront).toHaveLength(3) } // a 200 whose body was cut off, a 500 page, a redirect: the same as no answer for (const answer of [new Response('{"ok":tr', { status: 200 }), page(500), new Response(null, { headers: { location: 'https://elsewhere.example' }, status: 302 })]) { capture(fake, [answer, answer.clone(), answer.clone()]) expect(await sendThroughRelay(payload, options, { ...MESSAGE, subject: `Lost ${answer.status}` })).toMatchObject({ code: 'relay-not-confirmed', confirmed: false }) } // an error page says nothing about what the service did: the same message sent again keeps its key const again = capture(fake, []) expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true) expect(again[0].key).toBe(sends[0].key) // a final refusal does not: the next try is a new message const refused = capture(fake, [failing(429, { code: 'quota-exceeded', limit: 'hour', retryable: false })]) await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Refused' }) const after = capture(fake, []) await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Refused' }) expect(after[0].key).not.toBe(refused[0].key) // 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 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 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((_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 , "Kowalski, Jan" ; biuro@example.org').addresses).toEqual(['anna@example.org', 'jan@example.org', 'biuro@example.org']) expect(bareAddresses([{ name: 'A', address: 'a@example.org' }, 'a@example.org', 'not an address', 'info@żółw.pl'])).toEqual({ addresses: ['a@example.org', 'info@xn--w-uga1v8h.pl'], dropped: 1 }) expect(cleanSubject('Hello\r\nBcc: victim@example.net')).toBe('Hello Bcc: victim@example.net') expect(cleanSubject('Invoice ‮fdp.exe​')).toBe('Invoice fdp.exe') expect(cleanSubject('\u{1F469}‍\u{1F4BB} Straßen­bahn')).toBe('\u{1F469}‍\u{1F4BB} Straßen­bahn') 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: 'c@example.org', cc: ['b@example.org'], from: 'ceo@example.com', headers: { 'Return-Path': 'x@example.net' }, html: '

Hi

', replyTo: 'r@example.org, other@example.org', subject: 'Hi', text: 'Hi', to: 'a@example.org', } 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: ['c@example.org'], cc: ['b@example.org'], html: '

Hi

', kind: 'form-notification', product: 'iapl', productVersion: expect.stringMatching(/^\d+\.\d+\.\d+/) as string, replyTo: 'r@example.org', senderName: 'Kancelaria Example', subject: 'Hi', text: 'Hi', to: ['a@example.org'], }) expect(buildRelayMessage({ subject: 'x', to: 'nobody' } as never)).toMatchObject({ ok: false }) expect(buildRelayMessage({ subject: 'x', to: 'a@example.org' } 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: '

x

', subject: 'Pytanie\r\nBcc: x@example.net ‮', to: 'Biuro ' }) expect(result.sent).toBe(true) expect(fake.outbox[0]).toMatchObject({ subject: 'Pytanie Bcc: x@example.net', to: ['office@example.org'] }) }) 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 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 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('anna@example.org')).sent).toBe(true)} const before = fake.requests.length expect(await send('Anna@Example.org')).toMatchObject({ cause: 'client-account-mail-limit', code: 'relay-quota', sent: false }) expect(fake.requests.length).toBe(before) expect((await send('jan@example.org')).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: 'anna@example.org' }, '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}`, 'x-intecion-site': HOST }, 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}`, 'x-intecion-site': HOST }, 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}`, 'x-intecion-site': HOST } })) expect(refusedByService.status).toBe(401) const before = fake.requests.length expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-disconnected', sent: false }) // nor does anything else enrol the site by itself (a script, a status read): only "Connect again" does expect(await enrolRelay(payload, options)).toMatchObject({ ok: false, status: 'relay-disconnected' }) await refreshRelayStatus(payload, options) 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 site with a token issued by hand does not enrol to heal: it stops and says what to ask for (contract 1.6.0)', async () => { // the site CAN be called back here (the fake would confirm it) — it still must not enrol by itself const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) await setRelayToken(payload, fake.issueToken(HOST), { host: HOST }) expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true) const token = (await readRelayStore(payload)).token fake.clientAddress = '198.51.100.30' // the site moved, or a second server sends const moved = await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Moved' }) expect(moved).toMatchObject({ cause: 'reverify', code: 'relay-refused', confirmed: true, sent: false }) expect(moved.sent === false && moved.detail).toMatch(/ask Intecion to add this server's address/) expect((await getRelayStatus(payload, options)).refusal).toMatchObject({ code: 'reverify' }) expect(await mailPanelState({ payload }, options)).toMatchObject({ relay: { connected: true, refusal: { code: 'reverify' }, tokenSource: 'manual' } }) fake.clientAddress = '203.0.113.10' await fake.handle(new Request(`${fake.url}/v1/revoke`, { headers: { authorization: `Bearer ${token}`, 'x-intecion-site': HOST }, method: 'POST' })) const gone = await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Gone' }) expect(gone).toMatchObject({ cause: 'invalid-token', code: 'relay-refused', sent: false }) expect(gone.sent === false && gone.detail).toMatch(/ask Intecion for a new token/) // not one enrolment, and the token was kept expect(fake.requests.map((r) => r.path)).not.toContain('/v1/enrol') expect((await readRelayStore(payload)).token).toBe(token) // a new token from Intecion, or "Connect again" by an admin (when the site can be called back), heals it await setRelayToken(payload, fake.issueToken(HOST), { host: HOST }) expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'New token' })).sent).toBe(true) expect((await getRelayStatus(payload, options)).refusal).toBeUndefined() // rotation does not make it a site that enrols: it is still hand-issued expect(await rotateRelayToken(payload, options, { force: true })).toBe('rotated') expect((await readRelayStore(payload)).manual).toBe(true) }) test('a database copied to another host does not use the first site\'s token: the copy starts unenrolled and enrols as itself', async () => { // one service, two sites: it calls each back at its own host const staging = relayPayload({ serverURL: 'https://staging.example.com' }) const sites: Record> = {} const production = relaySite({ fake: { allow: [HOST, 'staging.example.com'], callSite: (url, init) => sites[new URL(url).host](url, init) }, integrations: { smtpFromName: 'Example' }, }) sites[HOST] = callConfirmRoute(production.payload) sites['staging.example.com'] = callConfirmRoute(staging.payload) await sendThroughRelay(production.payload, production.options, MESSAGE) const token = (await readRelayStore(production.payload)).token! // the copy: the same key-value entries, another serverURL for (const [key, value] of production.store) {staging.store.set(key, structuredClone(value))} const options = resolveRelayOptions(staging.payload, { fetchImpl: production.fake.fetch, url: production.fake.url })! expect((await readRelayStore(staging.payload)).token).toBe(token) // it is there … const seen: string[] = [] production.fake.intercept = (request) => void seen.push(request.headers.get('authorization') ?? '') // … and is not shown as this site's, not used, and not revoked expect(await mailPanelState({ payload: staging.payload }, options)).toMatchObject({ relay: { connected: false, host: 'staging.example.com' } }) expect((await readRelayStore(staging.payload)).token).toBeUndefined() expect(staging.logger.warn.mock.calls.map((c) => String(c[0])).join()).toMatch(/belongs to "example\.com", this site is "staging\.example\.com"/) await disconnectRelay(staging.payload, options) // even "Disconnect" on the copy expect(production.fake.requests.filter((r) => r.path === '/v1/revoke')).toEqual([]) expect((await enrolRelay(staging.payload, options, { force: true })).ok).toBe(true) expect((await sendThroughRelay(staging.payload, options, { ...MESSAGE, subject: 'From staging' })).sent).toBe(true) expect(production.fake.outbox.at(-1)).toMatchObject({ host: 'staging.example.com', subject: 'From staging' }) const own = (await readRelayStore(staging.payload)).token expect(own).not.toBe(token) expect(seen.every((header) => !header.includes(token))).toBe(true) expect(JSON.stringify(staging.logger.warn.mock.calls)).not.toContain('ims_') // production is untouched and still sends with its own token expect((await readRelayStore(production.payload)).token).toBe(token) expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'From production' })).sent).toBe(true) }) test('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('review of 7d766b6: R-1 to R-7, R-11, and four mutations it found uncaught', () => { const html = (status: number) => new Response('', { headers: { 'content-type': 'text/html' }, status }) const refusalOf = (status: number, code: string, retryable = false) => Response.json({ code, message: 'x', ok: false, retryable }, { status }) /** A site with a working token and, beside it, a token the service never made valid. */ const withBadCandidate = async (own: Parameters[0] = {}) => { const site = relaySite({ fake: { allow: [HOST] }, ...own }) expect((await enrolRelay(site.payload, site.options, { force: true })).ok).toBe(true) const working = (await readRelayStore(site.payload)).token! const nonce = `bad${'c'.repeat(40)}` await holdNonce(site.payload, nonce, 60_000) await callConfirmRoute(site.payload)(`https://${HOST}/api/iapl/mail-relay/confirm`, { body: JSON.stringify({ nonce, state: 'active', token: `ims_${'z'.repeat(43)}` }), headers: {} }) expect((await readRelayCandidate(site.payload))?.token).toBe(`ims_${'z'.repeat(43)}`) return { ...site, working } } describe('R-1: a delivered token never replaces a working one before the service has accepted it', () => { const silent: Array<[string, () => 'drop' | Response]> = [ ['an error page (502)', () => html(502)], ['no answer', () => 'drop'], ['429 rate-limited (the gate in front of the token check)', () => refusalOf(429, 'rate-limited', true)], ['403 browser-not-allowed', () => refusalOf(403, 'browser-not-allowed')], ['503 unavailable', () => refusalOf(503, 'unavailable', true)], ['400 invalid-request', () => refusalOf(400, 'invalid-request')], ] for (const enrol of ['auto', 'manual'] as const) { test.each(silent)(`enrol: '${enrol}', first answer %s: the working token is kept, and the next send goes out with it`, async (_name, first) => { const { fake, options, payload, working } = await withBadCandidate({ options: { enrol } }) let answered = false fake.intercept = (request) => { if (answered || !request.url.endsWith('/v1/send')) {return undefined} answered = true return first() } await sendThroughRelay(payload, { ...options, totalTimeoutMs: 400 }, MESSAGE) expect((await readRelayStore(payload)).token).toBe(working) fake.intercept = undefined // later: the candidate is tried, the service says invalid-token, it is dropped, the working token sends const before = fake.requests.filter((r) => r.path === '/v1/enrol').length expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Later' })).sent).toBe(true) expect((await readRelayStore(payload)).token).toBe(working) expect(await readRelayCandidate(payload)).toBeNull() expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(before) }) } test('answers the service gives after it has checked the token do promote a delivered one', async () => { expect(provesToken({ body: {}, ok: true, status: 200 })).toBe(true) const answer = (code: string, noAnswer = false) => ({ code, message: '', noAnswer, ok: false as const, retryable: false, status: 0 }) for (const code of ['site-pending', 'site-suspended', 'quota-exceeded', 'too-many-recipients', 'attachment-refused', 'recipient-suppressed', 'backend-failed', 'in-progress', 'idempotency-conflict', 'reverify', 'already-rotated']) { expect(provesToken(answer(code)), code).toBe(true) } for (const code of ['invalid-token', 'rate-limited', 'browser-not-allowed', 'unavailable', 'internal', 'invalid-request', 'too-large', 'not-found', 'a-code-of-next-year']) { expect(provesToken(answer(code)), code).toBe(false) } expect(provesToken(answer('quota-exceeded', true))).toBe(false) // a real one: the enrolment's answer is lost, the site is pending — `site-pending` proves the delivered token const { fake, options, payload } = relaySite() fake.intercept = async (request) => { if (!request.url.endsWith('/v1/enrol')) {return undefined} fake.intercept = undefined await fake.handle(request) return 'drop' } expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-pending' }) expect((await readRelayStore(payload)).token).toMatch(/^ims_/) expect(await readRelayCandidate(payload)).toBeNull() }) }) test('R-2: a token of another site, stored by hand, is refused by what /v1/status says — nothing is sent, nothing is revoked', async () => { const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) const foreign = fake.issueToken('other-client.example.org') await setRelayToken(payload, foreign) // a script, or the access-key field const result = await sendThroughRelay(payload, options, MESSAGE) expect(result).toMatchObject({ cause: 'client-foreign-token', code: 'relay-refused', sent: false }) expect(fake.outbox).toHaveLength(0) expect(fake.requests.map((r) => r.path)).toEqual(['/v1/status']) expect((await readRelayStore(payload)).token).toBeUndefined() expect((await getRelayStatus(payload, options)).refusal).toMatchObject({ code: 'client-foreign-token' }) // the other site's token still works there expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${foreign}`, 'x-intecion-site': 'other-client.example.org' } }))).status).toBe(200) // the site's own token, issued by hand for its host, passes the same check await setRelayToken(payload, fake.issueToken(HOST)) expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true) expect(await readRelayStore(payload)).toMatchObject({ host: HOST, hostChecked: true, manual: true }) // when the service cannot be asked, a token stored by hand is not used unchecked await setRelayToken(payload, fake.issueToken(HOST)) fake.intercept = () => 'drop' expect(await sendThroughRelay(payload, { ...options, totalTimeoutMs: 300 }, MESSAGE)).toMatchObject({ code: 'relay-unreachable', confirmed: true, sent: false }) }) test('contract 1.7.0: every request with a token names the site, and 403 host-mismatch means "not yours: enrol as yourself"', async () => { const { fake, options, payload } = relaySite({ fake: { allow: [HOST, 'other-client.example.org'] } }) const headers: (null | string)[] = [] fake.intercept = (request) => void (request.headers.has('authorization') && headers.push(request.headers.get('x-intecion-site'))) await sendThroughRelay(payload, options, MESSAGE) await refreshRelayStatus(payload, options) await rotateRelayToken(payload, options, { force: true }) expect(headers.length).toBeGreaterThanOrEqual(3) expect(new Set(headers)).toEqual(new Set([HOST])) // a token of another site sits in the store under this site's host (the comparison of hosts cannot see it) const foreign = fake.issueToken('other-client.example.org') await updateRelayStore(payload, (current) => ({ ...current, token: foreign })) const before = fake.requests.length expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'As myself' })).sent).toBe(true) expect(fake.requests.slice(before).map((r) => r.path)).toEqual(['/v1/send', '/v1/enrol', '/v1/send']) expect(fake.outbox.at(-1)).toMatchObject({ host: HOST, subject: 'As myself' }) expect((await readRelayStore(payload)).token).not.toBe(foreign) // forgotten here, not revoked there expect(fake.requests.map((r) => r.path)).not.toContain('/v1/revoke') expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${foreign}`, 'x-intecion-site': 'other-client.example.org' } }))).status).toBe(200) }) test('R-3: junk calls to the confirm route do not keep the site\'s own enrolment out', async () => { const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) const confirm = callConfirmRoute(payload) // every call comes from one address, as the service's does const url = `https://${HOST}/api/iapl/mail-relay/confirm` const junk = () => confirm(url, { body: JSON.stringify({ nonce: 'j'.repeat(43), state: 'active', token: `ims_${'j'.repeat(43)}` }), headers: {} }) const statuses: number[] = [] for (let i = 0; i < 14; i++) {statuses.push((await junk()).status)} expect(statuses.slice(0, 10)).toEqual(Array(10).fill(404)) expect(statuses.slice(10)).toEqual([429, 429, 429, 429]) // refused calls are limited … // … and the call that carries a nonce the site holds is answered all the same expect(await enrolRelay(payload, options)).toEqual({ ok: true, state: 'active' }) expect((await getRelayStatus(payload, options)).refusal).toBeUndefined() expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true) expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1) }) describe('R-4: one message has one budget of time', () => { const hanging = (async (_input: unknown, init?: RequestInit) => new Promise((_resolve, reject) => init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError'))))) as typeof fetch test('the defaults: ten seconds, thirty with files', () => { expect(RELAY_DEFAULTS).toMatchObject({ attempts: 3, attemptTimeoutMs: 30_000, totalTimeoutMs: 10_000, totalTimeoutWithFilesMs: 30_000 }) }) test('a service that accepts the connection and says nothing: the visitor waits the budget, not three time-outs', async () => { const { options, payload } = relaySite({ fake: { allow: [HOST] } }) await enrolRelay(payload, options) const started = Date.now() const result = await sendThroughRelay(payload, { ...options, fetchImpl: hanging, timeoutMs: 30_000, totalTimeoutMs: 500 }, MESSAGE) const took = Date.now() - started // cut off while the service may have been handling it: not confirmed expect(result).toMatchObject({ code: 'relay-not-confirmed', confirmed: false, sent: false }) expect(took).toBeGreaterThanOrEqual(450) expect(took).toBeLessThan(1500) }) test('the budget covers an enrolment on the way, and a message with files has its own', async () => { const { options, payload } = relaySite({ fake: { allow: [HOST] } }) // not enrolled: the first call is /v1/enrol let started = Date.now() const result = await sendThroughRelay(payload, { ...options, fetchImpl: hanging, totalTimeoutMs: { files: 900, plain: 300 } }, MESSAGE) // the message never left the site: not sent, and said so expect(result).toMatchObject({ code: 'relay-unreachable', confirmed: true, sent: false }) expect(Date.now() - started).toBeLessThan(800) started = Date.now() await sendThroughRelay(payload, { ...options, fetchImpl: hanging, totalTimeoutMs: { files: 900, plain: 300 } }, { ...MESSAGE, attachments: [{ content: Buffer.from('x'), filename: 'a.txt' }] }) expect(Date.now() - started).toBeGreaterThanOrEqual(850) expect(Date.now() - started).toBeLessThan(1900) }) test('retries stop when the time is up, and a wait that would pass it is not waited', async () => { const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) await enrolRelay(payload, options) let sends = 0 fake.intercept = (request) => (request.url.endsWith('/v1/send') ? (sends++, refusalOf(503, 'unavailable', true)) : undefined) const started = Date.now() await sendThroughRelay(payload, { ...options, retryBackoffMs: 400, totalTimeoutMs: 300 }, MESSAGE) expect(sends).toBe(1) expect(Date.now() - started).toBeLessThan(300) }) }) test('R-5: "Disconnect" while the service is down is not confirmed: the token is kept to try again, and not used', async () => { const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) await sendThroughRelay(payload, options, MESSAGE) const token = (await readRelayStore(payload)).token! fake.intercept = () => html(502) expect(await disconnectRelay(payload, options)).toEqual({ revoked: false }) expect(await readRelayStore(payload)).toMatchObject({ disconnected: true, revokePending: true, token }) expect(await getRelayStatus(payload, options)).toMatchObject({ connected: false, disconnected: true, revokePending: true }) fake.intercept = undefined // the token still works at the service — that is why the panel must not say "done" expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${token}`, 'x-intecion-site': HOST } }))).status).toBe(200) expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-disconnected', sent: false }) // pressed again with the service back: revoked and forgotten expect(await disconnectRelay(payload, options)).toEqual({ revoked: true }) expect(await readRelayStore(payload)).toEqual({ disconnected: true, v: 1 }) expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${token}`, 'x-intecion-site': HOST } }))).status).toBe(401) }) test('R-6: without the confirm route in the config the site does not ask to be enrolled', async () => { const { fake, options, payload } = relaySite({ endpoints: [], fake: { allow: [HOST] } }) const result = await sendThroughRelay(payload, options, MESSAGE) expect(result).toMatchObject({ cause: 'client-no-route', code: 'relay-refused', sent: false }) expect(result.sent === false && result.detail).toContain('relayConfirmEndpoint()') expect(fake.requests).toEqual([]) // a token from elsewhere needs no route const token = fake.issueToken(HOST) expect((await sendThroughRelay(payload, { ...options, enrol: false, token }, MESSAGE)).sent).toBe(true) }) test('R-7: half an SMTP set-up is said, once in the log and in the panel', async () => { const { fake, logger, options, payload } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpHost: 'smtp.example.com', smtpUser: 'info@example.com' } }) const adapter = adapterOf(mailAdapter({ relay: options }), payload) expect(((await adapter.sendEmail(MESSAGE)) as { transport?: string }).transport).toBe('relay') await adapter.sendEmail(MESSAGE) expect(logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('SMTP settings in Site integrations are incomplete'))).toHaveLength(1) expect(await mailPanelState({ payload }, options)).toMatchObject({ smtpIncomplete: true, transport: 'relay' }) expect((await mailPanelState(relayPayload(), {})).smtpIncomplete).toBeUndefined() expect(fake.outbox).toHaveLength(2) }) test('R-11: a mail that was not sent stays visible after the next one went out', async () => { const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) await sendThroughRelay(payload, options, MESSAGE) fake.backend = 'recipient-suppressed' await sendThroughRelay(payload, options, withMailKind({ ...MESSAGE, subject: 'Lost' }, 'form-confirmation')) fake.backend = 'ok' expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Fine' })).sent).toBe(true) const status = await getRelayStatus(payload, options) expect(status.lastFailure).toMatchObject({ code: 'relay-recipient-suppressed', kind: 'form-confirmation' }) expect(Date.parse(status.lastFailure!.at)).toBeGreaterThan(Date.now() - 5000) }) test('the token never follows a redirect, and the service\'s words are one clean line', async () => { const seen: RequestInit[] = [] const fetchImpl = (async (_input: unknown, init?: RequestInit) => { seen.push(init ?? {}) return Response.json({ code: 'quota-exceeded', message: 'Line one\u202E\u0007 of it\nsecond line', ok: false, retryable: false }, { status: 429 }) }) as typeof fetch const answer = await relayRequest({ fetchImpl, method: 'POST', path: '/v1/send', token: `ims_${'t'.repeat(43)}`, url: 'https://relay.example.net/mail' }) expect(seen[0].redirect).toBe('manual') expect(answer).toMatchObject({ message: 'Line one of it', ok: false }) const headers = new Headers(seen[0].headers) expect(headers.has('origin')).toBe(false) expect(headers.has('sec-fetch-site')).toBe(false) }) test('an enrolment is not taken for done when the token that arrived belongs to another nonce', async () => { const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) // a token delivered for some OTHER enrolment is in the store; the service answers 200 to this one without calling back const other = `oth${'e'.repeat(40)}` await holdNonce(payload, other, 60_000) await callConfirmRoute(payload)(`https://${HOST}/api/iapl/mail-relay/confirm`, { body: JSON.stringify({ nonce: other, state: 'active', token: `ims_${'o'.repeat(43)}` }), headers: {} }) fake.intercept = (request) => (request.url.endsWith('/v1/enrol') ? Response.json({ ok: true, state: 'active' }) : undefined) expect(await enrolRelay(payload, options)).toMatchObject({ code: 'callback-failed', ok: false }) expect((await readRelayStore(payload)).token).toBeUndefined() }) test('what an operation said about its mail is for one recipient and is taken back when it sent none', () => { expectMailTo('Anna@Example.org', 'account', { visitor: '198.51.100.9' }) expect(takeExpectedMail(['anna@example.org', 'jan@example.org'])).toBeUndefined() // a mail to several is not that mail expect(takeExpectedMail(['anna@example.org'])).toEqual({ kind: 'account', visitor: '198.51.100.9' }) expect(takeExpectedMail(['anna@example.org'])).toBeUndefined() // used up expectMailTo('jan@example.org', 'account') dropExpectedMail(' JAN@example.org ') expect(takeExpectedMail(['jan@example.org'])).toBeUndefined() // the hook pair on an auth collection does exactly that around an operation const marked = withAccountMailMark({ slug: 'users', auth: true, fields: [] }) const before = marked.hooks!.beforeOperation!.at(-1) as (args: object) => unknown const after = marked.hooks!.afterOperation!.at(-1) as (args: object) => unknown const args = { args: { data: { email: 'ola@example.org' } }, operation: 'forgotPassword', req: { headers: new Headers() } } before(args) after({ ...args, result: null }) expect(takeExpectedMail(['ola@example.org'])).toBeUndefined() before(args) expect(takeExpectedMail(['ola@example.org'])?.kind).toBe('account') expect(withAccountMailMark(marked)).toBe(marked) // not added twice }) }) describe('what the panel is told', () => { test('the panel calls the service by its short name, IWSN, in both languages — one constant, never another name', () => { expect(RELAY_SHORT_NAME).toBe('IWSN') for (const lang of ['en', 'pl'] as const) { const texts = Object.entries(adminTexts[lang] as Record).filter(([key]) => /^(?:mailRelay|statusEmailRelay|testEmailSentRelay|testEmailNotConfirmed)/.test(key)) expect(texts.length).toBeGreaterThan(40) const named = texts.filter(([, text]) => text.includes(RELAY_SHORT_NAME)) expect(named.length).toBeGreaterThan(20) for (const [key, text] of texts) {expect(text, key).not.toMatch(/mail service|usług|Intecion|Webservice/i)} } const tab = JSON.stringify(buildSmtpFields()) expect(tab).toContain('IWSN') expect(tab).not.toMatch(/mail service|usług/) expect(JSON.stringify(buildSmtpFields({ relay: false }))).not.toContain('IWSN') }) test('a site that runs locally is shown as refused before any e-mail; a public one as "not connected yet"; SMTP and "off" say so', async () => { const local = relayPayload({ serverURL: 'http://localhost:3000' }) expect(await mailPanelState(local, {})).toMatchObject({ relay: { connected: false, refusal: { code: 'host-not-allowed' } }, replyAddress: null, transport: 'relay' }) const nowhere = relayPayload({ serverURL: '' }) expect((await mailPanelState(nowhere, {})).relay?.refusal?.code).toBe('client-no-host') const fresh = relayPayload({ integrations: { smtpFromAddress: ' biuro@example.com ' } }) const state = await mailPanelState(fresh, {}) expect(state).toMatchObject({ confirmUrl: 'https://example.com/api/iapl/mail-relay/confirm', relay: { connected: false, host: HOST, senderAddress: 'notification@webservices.intecion.net' }, replyAddress: 'biuro@example.com', transport: 'relay' }) expect(state.relay?.refusal).toBeUndefined() const smtp = relayPayload({ integrations: { smtpHost: 'smtp.example.com', smtpPassword: 'x', smtpUser: 'u' } }) expect((await mailPanelState(smtp, {})).transport).toBe('smtp') expect(await mailPanelState(fresh, false)).toMatchObject({ relay: null, transport: 'none' }) expect(JSON.stringify([state])).not.toContain('ims_') }) }) 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: 'notification@webservices.intecion.net' }) 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: 'biuro@example.com' } }) 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([]) }) })