/** * 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, relayAttachmentLimit } from '../src/modules/email/relay/adapter.js' import { relayRequest } from '../src/modules/email/relay/client.js' import { RELAY_DEFAULTS, RELAY_SHORT_NAME } from '../src/modules/email/relay/constants.js' import { createFakeRelay } from '../src/modules/email/relay/fake.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, pluginDevelopmentHosts, 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, siteIsNonPublic, siteNonPublicSignal } from '../src/modules/email/relay/session.js' import { holdNonce, otherRelayHosts, readRelayCandidate, readRelayStore, updateRelayStore } from '../src/modules/email/relay/store.js' import { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../src/modules/notifications/defaults.js' import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js' import { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from '../src/modules/shared/developmentHosts.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, '')} // every site is public unless a test says otherwise for (const name of ['IAPL_NOINDEX', 'IPAL_NOINDEX']) {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) }) describe('one database, several hosts (review round 2, Q-1; the store is keyed by host)', () => { /** One service and any number of sites on ONE key-value store; the service calls each back at its own host. */ const shared = (fakeOptions: Parameters[0] = {}) => { const sites: Record> = {} const first = relaySite({ ...fakeOptions, fake: { allow: ['*'], callSite: (url, init) => sites[new URL(url).host](url, init), ...fakeOptions.fake } }) sites[new URL(fakeOptions.serverURL ?? `https://${HOST}`).host] = callConfirmRoute(first.payload) const another = (serverURL: string, own: Parameters[1] = {}) => { const site = relayPayload({ serverURL }) ;(site.payload as unknown as { kv: unknown }).kv = (first.payload as unknown as { kv: unknown }).kv sites[new URL(serverURL).host] = callConfirmRoute(site.payload) return { ...site, options: resolveRelayOptions(site.payload, { fetchImpl: first.fake.fetch, retryBackoffMs: 1, url: first.fake.url, ...(own || {}) })! } } return { ...first, another } } const everything = (store: Map) => JSON.stringify([...store.entries()].sort()) test.each([ ['enrolled by the call-back', false], ['with a token issued by hand', true], ])('a developer\'s process on the live database (%s): reading the state, the limit, the doctor\'s view and a send change NOTHING', async (_name, byHand) => { const production = shared() if (byHand) {await setRelayToken(production.payload, production.fake.issueToken(HOST))} expect((await sendThroughRelay(production.payload, production.options, MESSAGE)).sent).toBe(true) const before = everything(production.store) const requests = production.fake.requests.length const dev = production.another('http://localhost:3000', { url: undefined }) expect(await mailPanelState({ payload: dev.payload }, dev.options)).toMatchObject({ relay: { connected: false, host: 'localhost:3000', refusal: { code: 'host-not-allowed' } } }) expect(await getRelayStatus(dev.payload, dev.options)).toMatchObject({ connected: false }) expect(await relayAttachmentLimit(dev.payload, dev.options)).toBeNull() expect(await sendThroughRelay(dev.payload, dev.options, MESSAGE)).toMatchObject({ code: 'relay-refused', sent: false }) expect(await rotateRelayToken(dev.payload, dev.options)).toBe('not-due') await refreshRelayStatus(dev.payload, dev.options) expect(everything(production.store)).toBe(before) expect(production.fake.requests).toHaveLength(requests) expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'Still here' })).sent).toBe(true) expect(production.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(byHand ? 0 : 1) }) test('`client.pl` and `www.client.pl` on one database, mail in turn: one enrolment each, not one a mail', async () => { const apex = shared({ serverURL: 'https://client.pl' }) const www = apex.another('https://www.client.pl') const apexOptions = resolveRelayOptions(apex.payload, { fetchImpl: apex.fake.fetch, retryBackoffMs: 1, url: apex.fake.url })! for (let i = 0; i < 4; i++) { expect((await sendThroughRelay(apex.payload, apexOptions, { ...MESSAGE, subject: `apex ${i}` })).sent).toBe(true) expect((await sendThroughRelay(www.payload, www.options, { ...MESSAGE, subject: `www ${i}` })).sent).toBe(true) } expect(apex.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(2) expect(apex.fake.outbox.map((m) => m.host)).toEqual(['client.pl', 'www.client.pl', 'client.pl', 'www.client.pl', 'client.pl', 'www.client.pl', 'client.pl', 'www.client.pl']) expect([...apex.store.keys()].filter((k) => k.includes(':site:')).sort()).toEqual(['iapl:mail-relay:site:client.pl', 'iapl:mail-relay:site:www.client.pl']) }) // The owner's sites: built and enrolled on a development address, then launched on the real domain. A // development address is known by its host: the built-in pattern `*.dev.netscale.pl`, with NO environment // variable and no option (every test here runs with IAPL_NOINDEX empty unless it says otherwise). const DEV = 'acme.dev.netscale.pl' const DEV_HOSTS = {} const AGENCY = { developmentHosts: ['*.dev.agency-example.com'] } test('before launch: the site on its development address, with an empty store, enrols and sends by itself', async () => { const dev = shared({ options: DEV_HOSTS, serverURL: `https://${DEV}` }) expect(process.env.IAPL_NOINDEX).toBe('') expect(siteIsNonPublic(dev.payload, dev.options)).toBe(true) expect(siteNonPublicSignal(dev.payload, dev.options)).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) expect(await mailPanelState({ payload: dev.payload }, dev.options)).toMatchObject({ nonPublic: true, nonPublicBy: 'development-host', nonPublicPattern: '*.dev.netscale.pl' }) expect((await sendThroughRelay(dev.payload, dev.options, MESSAGE)).sent).toBe(true) expect(dev.fake.outbox[0].host).toBe(DEV) // the same with the switch such a site already has, and no option at all vi.stubEnv('IAPL_NOINDEX', '1') const noindex = relaySite({ fake: { allow: [HOST] } }) expect(siteNonPublicSignal(noindex.payload, noindex.options)).toEqual({ by: 'noindex' }) expect(await mailPanelState({ payload: noindex.payload }, noindex.options)).toMatchObject({ nonPublic: true, nonPublicBy: 'noindex' }) expect((await sendThroughRelay(noindex.payload, noindex.options, MESSAGE)).sent).toBe(true) }) test('launch day: the real domain finds the development address\'s entry and enrols by itself — no click; the development site on its own database sends on', async () => { const dev = shared({ options: DEV_HOSTS, serverURL: `https://${DEV}` }) await sendThroughRelay(dev.payload, dev.options, MESSAGE) // the test mail before launch // launch: the same data, now served at the real domain (public: no noindex, not a development host) const live = dev.another('https://client.pl', DEV_HOSTS) expect(siteIsNonPublic(live.payload, live.options)).toBe(false) const first = await sendThroughRelay(live.payload, live.options, { ...MESSAGE, subject: 'First mail after launch' }) expect(first).toMatchObject({ sent: true }) expect(dev.fake.outbox.at(-1)).toMatchObject({ host: 'client.pl', subject: 'First mail after launch' }) expect(dev.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(2) expect((await mailPanelState({ payload: live.payload }, live.options)).relay?.refusal).toBeUndefined() // the doctor can still say that the database knows another host (information, for the case that this is a copy) expect(await mailPanelState({ payload: live.payload }, live.options)).toMatchObject({ otherHostEntries: true }) expect((await mailPanelState({ payload: live.payload }, { ...live.options, otherHosts: [DEV] })).otherHostEntries).toBeUndefined() // the development site keeps running beside it on its OWN database: nothing changes for it const apart = relaySite({ fake: { allow: ['*'] }, options: DEV_HOSTS, serverURL: `https://${DEV}` }) await sendThroughRelay(apart.payload, apart.options, MESSAGE) expect((await sendThroughRelay(apart.payload, apart.options, { ...MESSAGE, subject: 'Dev, later' })).sent).toBe(true) // …but a development site that still runs ON the launched database now holds the live site's data: it stops by itself const before = dev.fake.requests.length expect(await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: 'a-real-customer@example.org' })).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', sent: false }) expect(dev.fake.requests).toHaveLength(before) }) test('production\'s database copied BACK to the development address: the copy has a token of its own, and still mails nobody by itself', async () => { // one service, two sites, each with a database of its own const sites: Record> = {} const service = createFakeRelay({ allow: ['*'], callSite: (url, init) => sites[new URL(url).host](url, init) }) const site = (serverURL: string) => { const made = relayPayload({ serverURL }) sites[new URL(serverURL).host] = callConfirmRoute(made.payload) return { ...made, options: resolveRelayOptions(made.payload, { ...DEV_HOSTS, fetchImpl: service.fetch, retryBackoffMs: 1, url: service.url })! } } const copy = (from: Map, to: Map) => { to.clear() for (const [key, value] of from) {to.set(key, structuredClone(value))} } const dev = site(`https://${DEV}`) expect((await sendThroughRelay(dev.payload, dev.options, MESSAGE)).sent).toBe(true) // launch: the live site starts from the development site's data, and enrols by itself const live = site('https://client.pl') const liveOptions = live.options copy(dev.store, live.store) expect((await sendThroughRelay(live.payload, liveOptions, { ...MESSAGE, subject: 'Live' })).sent).toBe(true) const liveToken = (await readRelayStore(live.payload)).token! // months later: production's data is copied back onto the development address, to work on a bug copy(live.store, dev.store) expect((await readRelayStore(dev.payload)).token).toMatch(/^ims_/) // its own old entry came back with the copy const requests = service.requests.length const held = await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: 'a-real-customer@example.org' }) expect(held).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', confirmed: true, sent: false }) expect(service.requests).toHaveLength(requests) expect(await mailPanelState({ payload: dev.payload }, dev.options)).toMatchObject({ nonPublic: true, relay: { connected: true, refusal: { code: 'client-other-host', reason: 'client.pl' } } }) // a developer decides that this copy sends: "Connect again", once expect((await enrolRelay(dev.payload, dev.options, { force: true })).ok).toBe(true) expect((await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, subject: 'On purpose' })).sent).toBe(true) expect(service.outbox.at(-1)).toMatchObject({ host: DEV, subject: 'On purpose' }) expect((await mailPanelState({ payload: dev.payload }, dev.options)).relay?.refusal).toBeUndefined() // the next fresh copy is held again: the consent was this database's, and the copy replaced it copy(live.store, dev.store) expect(await sendThroughRelay(dev.payload, dev.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) // production never noticed any of it expect((await readRelayStore(live.payload)).token).toBe(liveToken) expect(service.requests.map((r) => r.path)).not.toContain('/v1/revoke') expect((await sendThroughRelay(live.payload, liveOptions, { ...MESSAGE, subject: 'Live, still' })).sent).toBe(true) }) test('a staging copy of production\'s data that says it is not public (IAPL_NOINDEX) does not enrol — and uses, changes and revokes nothing of production\'s', async () => { const production = shared({ integrations: { smtpFromName: 'Example' } }) await sendThroughRelay(production.payload, production.options, MESSAGE) const token = (await readRelayStore(production.payload)).token! const entry = JSON.stringify(production.store.get(`iapl:mail-relay:site:${HOST}`)) const staging = production.another('https://staging.example.com') const seen: string[] = [] // what the copy's requests carry (production's own later request is not the copy's) production.fake.intercept = (request) => void (request.headers.get('x-intecion-site') !== HOST && seen.push(request.headers.get('authorization') ?? '')) vi.stubEnv('IAPL_NOINDEX', '1') // the staging process const requests = production.fake.requests.length const held = await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, to: 'a-real-customer@example.org' }) expect(held).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', confirmed: true, sent: false }) expect(held.sent === false && held.detail).toContain('example.com') expect(production.fake.requests).toHaveLength(requests) expect(production.fake.outbox).toHaveLength(1) expect(await mailPanelState({ payload: staging.payload }, staging.options)).toMatchObject({ nonPublic: true, relay: { connected: false, host: 'staging.example.com', refusal: { code: 'client-other-host', reason: HOST } } }) // "Disconnect" on the copy revokes nothing of production's await disconnectRelay(staging.payload, staging.options) expect(production.fake.requests.filter((r) => r.path === '/v1/revoke')).toEqual([]) expect(JSON.stringify(production.store.get(`iapl:mail-relay:site:${HOST}`))).toBe(entry) // an admin decides that the copy sends: "Connect again", once — then it is a site of its own and heals by itself expect(await enrolRelay(staging.payload, staging.options, { force: true })).toEqual({ ok: true, state: 'active' }) expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'From staging' })).sent).toBe(true) expect(production.fake.outbox.at(-1)).toMatchObject({ host: 'staging.example.com', subject: 'From staging' }) const own = (await readRelayStore(staging.payload)).token! expect(own).not.toBe(token) await production.fake.handle(new Request(`${production.fake.url}/v1/revoke`, { headers: { authorization: `Bearer ${own}`, 'x-intecion-site': 'staging.example.com' }, method: 'POST' })) expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'Healed' })).sent).toBe(true) // also when its token is gone altogether (another container rotated it away) await updateRelayStore(staging.payload, (c) => ({ ...c, token: undefined })) expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'Healed again' })).sent).toBe(true) // a token the service delivers for ONE host waits beside that host's token only: the other host never tries it const nonce = `stg${'n'.repeat(40)}` await holdNonce(staging.payload, nonce, 60_000) await callConfirmRoute(staging.payload)('https://staging.example.com/api/iapl/mail-relay/confirm', { body: JSON.stringify({ nonce, state: 'active', token: `ims_${'s'.repeat(43)}` }), headers: {} }) expect((await readRelayCandidate(staging.payload))?.token).toBe(`ims_${'s'.repeat(43)}`) expect(await readRelayCandidate(production.payload)).toBeNull() vi.stubEnv('IAPL_NOINDEX', '') // production's process const sends = production.fake.requests.length expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'Its own token' })).sent).toBe(true) expect(production.fake.requests.slice(sends).map((r) => r.path)).toEqual(['/v1/send']) expect(seen.every((header) => !header.includes(token))).toBe(true) expect(JSON.stringify([staging.logger.warn.mock.calls, staging.logger.error.mock.calls])).not.toContain('ims_') expect((await readRelayStore(production.payload)).token).toBe(token) }) test('the development pattern is a default a project can replace or empty — the plugin option, the mail option, the matcher', async () => { const at = (serverURL: string, custom?: object, own: Parameters[1] = {}) => { const site = relayPayload({ custom, serverURL }) return siteNonPublicSignal(site.payload, resolveRelayOptions(site.payload, own)!) } // built in: Intecion's development domain, any depth, any case, with a port; nothing that merely looks like it expect(DEFAULT_DEVELOPMENT_HOSTS).toEqual(['*.dev.netscale.pl']) expect(at('https://acme.dev.netscale.pl')).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) expect(at('https://WWW.Acme.dev.netscale.pl:8443/pl')).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) for (const url of ['https://client.pl', 'https://dev.netscale.pl', 'https://acme.dev.netscale.pl.evil.example', 'https://acme-dev.netscale.pl', 'https://netscale.pl', 'http://localhost:3000']) {expect(at(url)).toBeNull()} // iapl({ developmentHosts }) replaces the list… const own = { iapl: { developmentHosts: ['*.preview.agency-example.com', 'staging.client.pl'] } } expect(at('https://x.preview.agency-example.com', own)).toEqual({ by: 'development-host', pattern: '*.preview.agency-example.com' }) expect(at('https://staging.client.pl', own)).toEqual({ by: 'development-host', pattern: 'staging.client.pl' }) expect(at('https://acme.dev.netscale.pl', own)).toBeNull() expect(pluginDevelopmentHosts(relayPayload({ custom: own }).payload)).toEqual(own.iapl.developmentHosts) // …`[]` empties it (the project's choice: then only IAPL_NOINDEX marks a copy)… expect(at('https://acme.dev.netscale.pl', { iapl: { developmentHosts: [] } })).toBeNull() // …and mail.relay.developmentHosts wins for the mail service expect(at('https://acme.dev.netscale.pl', own, { developmentHosts: ['acme.*'] })).toEqual({ by: 'development-host', pattern: 'acme.*' }) expect(at('https://acme.dev.netscale.pl', undefined, { developmentHosts: [] })).toBeNull() // either signal is enough; the host is named first vi.stubEnv('IAPL_NOINDEX', '1') expect(at('https://client.pl')).toEqual({ by: 'noindex' }) expect(at('https://acme.dev.netscale.pl')).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) vi.stubEnv('IAPL_NOINDEX', '') // the matcher alone expect(matchDevelopmentHost('https://a.dev.netscale.pl/x')).toBe('*.dev.netscale.pl') expect(isDevelopmentHost('a.b.dev.netscale.pl')).toBe(true) expect(isDevelopmentHost('a.dev.netscale.pl', [])).toBe(false) expect(isDevelopmentHost('', ['*'])).toBe(false) expect(matchDevelopmentHost('x.example.com', [' ', '*.Example.com '])).toBe('*.Example.com ') // what emptying the list means: production's data on the development address is then a "launch", and sends const live = shared({ serverURL: 'https://client.pl' }) await sendThroughRelay(live.payload, live.options, MESSAGE) const copy = live.another(`https://${DEV}`) expect(await sendThroughRelay(copy.payload, copy.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) expect((await sendThroughRelay(copy.payload, { ...copy.options, developmentHosts: [] }, MESSAGE)).sent).toBe(true) }) test('V-3: production\'s dump restored into the RUNNING development site right after it sent a mail — the very next mail is refused', async () => { const live = shared({ serverURL: 'https://client.pl' }) await sendThroughRelay(live.payload, live.options, MESSAGE) const dev = shared({ serverURL: `https://${DEV}` }) const on = { ...dev.options, fetchImpl: live.fake.fetch, url: live.fake.url } // the development site is connected and has just sent (its own database, its own data) await setRelayToken(dev.payload, live.fake.issueToken(DEV), on) expect((await sendThroughRelay(dev.payload, on, MESSAGE)).sent).toBe(true) // the restore: production's entries land in the database of the running process for (const [key, value] of live.store) {dev.store.set(key, structuredClone(value))} const requests = live.fake.requests.length expect(await sendThroughRelay(dev.payload, on, { ...MESSAGE, to: 'a-real-customer@example.org' })).toMatchObject({ cause: 'client-other-host', sent: false }) expect(live.fake.requests).toHaveLength(requests) expect((await mailPanelState({ payload: dev.payload }, on)).relay?.refusal).toMatchObject({ code: 'client-other-host', reason: 'client.pl' }) }) test('V-1, V-2: a malformed list stops the start; a trailing dot and a Unicode pattern still match', async () => { // what is refused — by the checker, by the options in effect, by a value left in the config by hand for (const bad of ['*.dev.netscale.pl', null, {}, [1, 2], [''], [' '], ['*.dev.netscale.pl', 7], ['*'], ['*.*'], [' * '], ['https://x.dev.example.com'], ['x.example.com/path'], ['a b.example.com'], ['*ż.example.com']]) { expect(() => assertDevelopmentHosts(bad), JSON.stringify(bad)).toThrow(/must be an array of host patterns/) const site = relayPayload({ custom: { iapl: { developmentHosts: bad } } }) expect(() => resolveRelayOptions(site.payload, {}), JSON.stringify(bad)).toThrow(/developmentHosts/) expect(() => resolveRelayOptions(relayPayload().payload, { developmentHosts: bad as never }), JSON.stringify(bad)).toThrow(/mail\.relay\.developmentHosts/) } expect(() => assertDevelopmentHosts(['*'])).toThrow(/matches every host/) expect(() => assertDevelopmentHosts('*.dev.netscale.pl', 'iapl({ developmentHosts })')).toThrow('[iapl] iapl({ developmentHosts }) must be an array') // what is taken for (const good of [[], ['*.dev.netscale.pl'], ['staging.client.pl', '*.Preview.Agency-Example.com ', 'acme.*', '*.dev.zażółć.pl', '*.dev.netscale.pl.']]) {expect(assertDevelopmentHosts(good)).toBe(good)} // a fully qualified name with the dot, in the address and in the pattern expect(matchDevelopmentHost('https://acme.dev.netscale.pl.')).toBe('*.dev.netscale.pl') expect(matchDevelopmentHost('https://acme.dev.netscale.pl.:8443/pl')).toBe('*.dev.netscale.pl') expect(matchDevelopmentHost('acme.dev.netscale.pl', ['*.dev.netscale.pl.'])).toBe('*.dev.netscale.pl.') const dotted = relayPayload({ serverURL: 'https://acme.dev.netscale.pl.' }) expect(siteNonPublicSignal(dotted.payload, resolveRelayOptions(dotted.payload, {})!)).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) // a pattern written in Unicode matches the punycode host, and the other way round expect(matchDevelopmentHost('https://acme.dev.zażółć.pl', ['*.dev.zażółć.pl'])).toBe('*.dev.zażółć.pl') expect(new URL('https://zażółć.pl').hostname).toMatch(/^xn--/) expect(matchDevelopmentHost(`acme.dev.${new URL('https://zażółć.pl').hostname}`, ['*.dev.ZAŻÓŁĆ.pl'])).toBe('*.dev.ZAŻÓŁĆ.pl') expect(matchDevelopmentHost('https://acme.dev.zażółć.pl', [`*.dev.${new URL('https://zażółć.pl').hostname}`])).not.toBeNull() expect(matchDevelopmentHost('acme.dev.zazolc.pl', ['*.dev.zażółć.pl'])).toBeNull() }) test('a developer\'s `localhost` on the production database, no env: refused before any call, nothing written', async () => { const production = shared({ serverURL: 'https://client.pl' }) await sendThroughRelay(production.payload, production.options, MESSAGE) const before = everything(production.store) const requests = production.fake.requests.length const local = production.another('http://localhost:3000') const real = { ...local.options, ownUrl: false } expect(siteNonPublicSignal(local.payload, real)).toBeNull() expect(await sendThroughRelay(local.payload, real, { ...MESSAGE, to: 'a-real-customer@example.org' })).toMatchObject({ cause: 'host-not-allowed', code: 'relay-refused', sent: false }) expect(production.fake.requests).toHaveLength(requests) expect(everything(production.store)).toBe(before) }) test('`www` and the bare domain are one site, also for a non-public one: neither holds the other', async () => { const apex = shared({ options: DEV_HOSTS, serverURL: `https://${DEV}` }) const www = apex.another(`https://www.${DEV}`, DEV_HOSTS) expect(siteIsNonPublic(www.payload, www.options)).toBe(true) for (const site of [apex, www, apex, www]) {expect((await sendThroughRelay(site.payload, site.options, MESSAGE)).sent).toBe(true)} expect(apex.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(2) expect((await mailPanelState({ payload: www.payload }, www.options)).otherHostEntries).toBeUndefined() // the launched site names the development address once, with or without `www.`: both forms count const live = apex.another('https://www.client.pl', { otherHosts: [`www.${DEV}`] }) expect((await sendThroughRelay(live.payload, live.options, MESSAGE)).sent).toBe(true) expect((await mailPanelState({ payload: live.payload }, live.options)).otherHostEntries).toBeUndefined() }) test('what remains possible: a staging copy that forgot to say it is not public enrols and sends like a launch — the panel state and the doctor name it', async () => { const production = shared() await sendThroughRelay(production.payload, production.options, MESSAGE) const staging = production.another('https://staging.example.com') // no IAPL_NOINDEX, no development host const sent = await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, to: 'a-real-customer@example.org' }) expect(sent).toMatchObject({ sent: true }) // the plugin cannot tell this from launch day expect(await mailPanelState({ payload: staging.payload }, staging.options)).toMatchObject({ otherHostEntries: true, relay: { connected: true } }) expect((await mailPanelState({ payload: staging.payload }, staging.options)).nonPublic).toBeUndefined() // the same site once it says so: held from the next e-mail on, although it has a token by now vi.stubEnv('IAPL_NOINDEX', '1') expect(await sendThroughRelay(staging.payload, staging.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) }) test('a domain move needs nobody; `otherHosts` — \'wait\', \'enrol\', the site\'s own hosts; the rule ends when its reason does', async () => { const old = shared() await sendThroughRelay(old.payload, old.options, MESSAGE) // the same data under a new, public host: enrols by itself const moved = old.another('https://example.org') expect((await sendThroughRelay(moved.payload, moved.options, MESSAGE)).sent).toBe(true) expect(old.fake.outbox.at(-1)?.host).toBe('example.org') // 'wait': the rule of the first cut — a public site without a connection of its own waits too const waiting = old.another('https://example.net', { otherHosts: 'wait' }) expect(await sendThroughRelay(waiting.payload, waiting.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) // ('wait' holds a site WITHOUT a connection: the old domain, connected long ago, sends on beside the new hosts) expect((await sendThroughRelay(old.payload, { ...old.options, otherHosts: 'wait' }, MESSAGE)).sent).toBe(true) // …and the wait ends at once when the project names the other hosts as the site's own (no cool-down in the way) const named = { ...waiting.options, otherHosts: ['example.com', 'www.example.org'] } expect((await sendThroughRelay(waiting.payload, named, MESSAGE)).sent).toBe(true) expect((await readRelayStore(waiting.payload, 'example.net')).refusal).toBeFalsy() // a non-public copy with 'enrol': the project took the rule away const any = old.another('https://copy.dev.agency-example.com', { ...AGENCY, otherHosts: 'enrol' }) expect((await sendThroughRelay(any.payload, any.options, MESSAGE)).sent).toBe(true) // a non-public copy that names SOME hosts as its own still stops for the others const partly = old.another('https://two.dev.agency-example.com', { ...AGENCY, otherHosts: ['example.com'] }) expect(await sendThroughRelay(partly.payload, partly.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) // …the panel shows that refusal from the store, and drops it the moment its reason is gone (no send needed) expect((await mailPanelState({ payload: partly.payload }, partly.options)).relay?.refusal).toMatchObject({ code: 'client-other-host' }) expect((await readRelayStore(partly.payload, 'two.dev.agency-example.com')).refusal).toMatchObject({ code: 'client-other-host' }) expect((await mailPanelState({ payload: partly.payload }, { ...partly.options, otherHosts: 'enrol' })).relay?.refusal).toBeUndefined() // …and one that names ALL of them (with or without `www.`) sends by itself const others = (await otherRelayHosts(partly.payload, 'two.dev.agency-example.com')).map((h) => (h === 'example.com' ? 'www.example.com' : h)) expect(others.length).toBeGreaterThan(2) expect((await sendThroughRelay(partly.payload, { ...partly.options, otherHosts: others }, MESSAGE)).sent).toBe(true) expect(siteIsNonPublic(partly.payload, { developmentHosts: ['*.dev.other.example', 'two.dev.agency-exam*'], host: undefined })).toBe(true) expect(siteIsNonPublic(partly.payload, { developmentHosts: ['dev.agency-example.com', '*.agency-example'], host: undefined })).toBe(false) }) }) test('Q-2: the file limit is answered from what is stored and never waits for the service', async () => { const { fake, options, payload } = relaySite({ fake: { allow: [HOST], limits: { maxAttachmentBytes: 4242 } } }) await sendThroughRelay(payload, options, MESSAGE) // the status is read after the first send // an hour and more later, with the service hanging: the stored answer, at once, and no request await updateRelayStore(payload, (c) => ({ ...c, service: { ...c.service!, fetchedAt: new Date(Date.now() - 3 * 60 * 60_000).toISOString() } })) const hanging = (async (_input: unknown, init?: RequestInit) => new Promise((_resolve, reject) => init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError'))))) as typeof fetch const requests = fake.requests.length const started = Date.now() for (let i = 0; i < 3; i++) {expect(await relayAttachmentLimit(payload, { ...options, fetchImpl: hanging })).toBe(4242)} expect(Date.now() - started).toBeLessThan(200) expect(fake.requests).toHaveLength(requests) // renewed by the next send, not by a read fake.limits.maxAttachmentBytes = 1000 await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Renews it' }) expect(await relayAttachmentLimit(payload, options)).toBe(1000) }) test('Q-3: a file whose mail was not confirmed is not reported as a wrong file', () => { const texts = NOTIFICATION_FALLBACK.form const failed = { field: 'cv', file: 'cv.pdf', reason: 'delivery', success: false } as const expect(resolveFormMessage(failed, texts)).toContain('Choose a smaller file') const unconfirmed = resolveFormMessage({ ...failed, unconfirmed: true }, texts) expect(unconfirmed).toContain('cv.pdf') expect(unconfirmed).toMatch(/could not confirm/) expect(unconfirmed).not.toMatch(/try again|smaller file/) expect(resolveFormMessage({ ...failed, unconfirmed: true }, NOTIFICATION_FALLBACK_PL.form)).toMatch(/Nie wysyłaj go ponownie/) }) test('a token issued by hand is stored the same way; enrol: "manual" and enrol: false never enrol by themselves', async () => { 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) // (a status read follows: what was known about the service was forgotten with the token) expect(fake.requests.slice(before).map((r) => r.path).slice(0, 3)).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' }) // the access-key field is the project's switch, off by default expect(state.accessKeyField).toBeUndefined() expect((await mailPanelState(fresh, { accessKeyField: true })).accessKeyField).toBe(true) 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([]) }) })