contracts/mail-relay refreshed from IWDL 6cd99f7 (64 files). A token the service knows as another site's is forgotten without revoking and the site enrols as itself; a hand-issued one is refused. The fake requires the header and answers host-mismatch. Co-Authored-By: Claude Fable 5.2 <[email protected]>
194 lines
11 KiB
TypeScript
194 lines
11 KiB
TypeScript
/**
|
||
* The plugin's client against the REAL service code of the Intecion Notifications Webservice, run on
|
||
* this machine (the IWDL repository's local stand-in: the same Worker under the local Workers runtime,
|
||
* with mail recorded instead of sent and the call-back allowed to reach `localhost`).
|
||
*
|
||
* Skipped unless the stand-in is named — nothing here can reach the deployed service:
|
||
* cd <IWDL>/services/mail-relay
|
||
* npm run dev:migrate && npm run ims -- allow localhost:3987 && npm run dev
|
||
* npm run ims -- limits localhost:3987 --hour 2000 --day 20000 # after the first run: a run sends about ten messages,
|
||
* # and the default hour (24 for mail that is not account mail) lasts three runs
|
||
* IAPL_TEST_RELAY_URL=http://127.0.0.1:8787/mail pnpm vitest run test/mailRelayService.test.ts
|
||
*/
|
||
import type { Payload } from 'payload'
|
||
|
||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||
import os from 'os'
|
||
import path from 'path'
|
||
import { getPayload } from 'payload'
|
||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||
|
||
import type { ResolvedRelayOptions } from '../src/modules/email/relay/options.js'
|
||
|
||
import { mailAttachmentLimit } from '../src/modules/email/attachmentLimit.js'
|
||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||
import { relayRequest } from '../src/modules/email/relay/client.js'
|
||
import { RELAY_CONTRACT_VERSION } from '../src/modules/email/relay/constants.js'
|
||
import { withMailKind } from '../src/modules/email/relay/kinds.js'
|
||
import { resolveRelayOptions } from '../src/modules/email/relay/options.js'
|
||
import { sendThroughRelay } from '../src/modules/email/relay/send.js'
|
||
import { disconnectRelay, enrolRelay, getRelayStatus, rotateRelayToken } from '../src/modules/email/relay/session.js'
|
||
import { readRelayStore } from '../src/modules/email/relay/store.js'
|
||
import { iapl } from '../src/plugin.js'
|
||
import { buildTestConfig } from './helpers.js'
|
||
import { testDatabase } from './http/db.js'
|
||
import { startPayloadServer, type TestServer } from './http/server.js'
|
||
|
||
vi.mock('server-only', () => ({}))
|
||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||
|
||
const SERVICE = (process.env.IAPL_TEST_RELAY_URL ?? '').replace(/\/+$/, '')
|
||
const PORT = Number(process.env.IAPL_TEST_SITE_PORT ?? 3987)
|
||
const HOST = `localhost:${PORT}`
|
||
const local = /^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?\//.test(`${SERVICE}/`)
|
||
|
||
type Recorded = { from?: { email?: string; name?: string }; headers?: Record<string, string>; replyTo?: string; subject?: string; to?: string[] }
|
||
|
||
describe.skipIf(!SERVICE || !local)('against the real service code, run locally', () => {
|
||
let server: TestServer
|
||
let payload: Payload
|
||
let options: ResolvedRelayOptions
|
||
const origin = SERVICE.replace(/\/mail$/, '')
|
||
const outbox = async () => ((await (await fetch(`${origin}/__dev/outbox`)).json()) as { mails: Recorded[] }).mails
|
||
const MESSAGE = { html: '<p>Hello.</p>', subject: 'New enquiry', to: '[email protected]' }
|
||
|
||
beforeAll(async () => {
|
||
const config = buildTestConfig({
|
||
admin: { user: 'users' },
|
||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-relay-service-media') } }],
|
||
db: testDatabase('relayservice'),
|
||
editor: lexicalEditor(),
|
||
email: mailAdapter(),
|
||
plugins: [iapl({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail: { relay: { retryBackoffMs: 50, url: SERVICE } }, twoFactor: false })],
|
||
secret: 'integration-test-secret-0123456789',
|
||
serverURL: `http://${HOST}`,
|
||
telemetry: false,
|
||
})
|
||
payload = await getPayload({ config })
|
||
server = await startPayloadServer(config, PORT)
|
||
options = resolveRelayOptions(payload, undefined)!
|
||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromAddress: '[email protected]', smtpFromName: 'Kancelaria Example' } as never })
|
||
await fetch(`${origin}/__dev/outbox`, { method: 'DELETE' })
|
||
}, 120_000)
|
||
|
||
afterAll(async () => {
|
||
await server?.close()
|
||
await payload?.destroy?.()
|
||
})
|
||
|
||
test('the service is up and speaks the contract this client was written for', async () => {
|
||
expect(await (await fetch(`${SERVICE}/health`)).json()).toEqual({ ok: true })
|
||
})
|
||
|
||
test('the first e-mail: the service calls the site\'s confirm route over HTTP, then takes the message', async () => {
|
||
const result = (await payload.sendEmail(withMailKind(MESSAGE, 'form-notification'))) as Record<string, unknown>
|
||
expect(result, JSON.stringify(result)).toMatchObject({ replayed: false, senderName: 'Kancelaria Example', sent: true, transport: 'relay', warnings: [] })
|
||
const stored = await readRelayStore(payload)
|
||
expect(stored).toMatchObject({ host: HOST, source: 'enrolment', state: 'active' })
|
||
expect(stored.token).toMatch(/^ims_[\w-]{43}$/)
|
||
const mails = await outbox()
|
||
expect(mails).toHaveLength(1)
|
||
expect(JSON.stringify(mails[0])).toContain('Kancelaria Example')
|
||
expect(JSON.stringify(mails[0])).toContain('[email protected]')
|
||
expect(JSON.stringify(mails[0])).toContain(HOST)
|
||
})
|
||
|
||
test('/v1/status: the state, the limits and the contract version', async () => {
|
||
const status = await getRelayStatus(payload, options, { refresh: true })
|
||
expect(status, JSON.stringify(status)).toMatchObject({ connected: true, host: HOST, state: 'active', tokenSource: 'enrolment' })
|
||
expect(status.error).toBeUndefined()
|
||
expect(status.senderAddress).toMatch(/^[^@\s]+@[^@\s]+$/)
|
||
expect(status.limits?.maxAttachmentBytes).toBeGreaterThan(0)
|
||
expect(status.quota?.hour?.remaining).toBeLessThan(status.quota?.hour?.limit ?? 0)
|
||
const stored = await readRelayStore(payload)
|
||
expect(stored.service?.contract).toBe(RELAY_CONTRACT_VERSION)
|
||
expect(await mailAttachmentLimit(payload)).toBe(status.limits?.maxAttachmentBytes)
|
||
})
|
||
|
||
test('a visitor\'s words in the subject, display names in the recipients, an international domain: accepted as the client cleans them', async () => {
|
||
const before = (await outbox()).length
|
||
const result = await sendThroughRelay(payload, options, {
|
||
cc: '"Kowalski, Jan" <[email protected]>',
|
||
html: '<p>x</p>',
|
||
subject: 'Pytanie\r\nBcc: [email protected] \u{1F469}\u{1F4BB}',
|
||
text: 'x',
|
||
to: ['Biuro <[email protected]>', 'info@żółw.pl'],
|
||
})
|
||
expect(result, JSON.stringify(result)).toMatchObject({ sent: true })
|
||
const mail = (await outbox())[before]
|
||
expect(mail.subject).toBe('Pytanie Bcc: [email protected] \u{1F469}\u{1F4BB}')
|
||
expect(JSON.stringify(mail)).toContain('[email protected]')
|
||
})
|
||
|
||
test('a sender name the service does not accept: sent under the host, with the warning', async () => {
|
||
const result = await sendThroughRelay(payload, options, MESSAGE, { senderName: 'PayPal <[email protected]>' })
|
||
expect(result, JSON.stringify(result)).toMatchObject({ senderName: HOST, sent: true, warnings: ['sender-name-replaced'] })
|
||
expect((await getRelayStatus(payload, options)).nameReplaced).toMatchObject({ used: HOST })
|
||
})
|
||
|
||
test('refusals map to the site statuses: a program as attachment, too many recipients, a file over the limit', async () => {
|
||
const exe = await sendThroughRelay(payload, options, { ...MESSAGE, attachments: [{ content: Buffer.from('MZ'), filename: 'invoice.pdf.exe' }] })
|
||
expect(exe).toMatchObject({ cause: 'attachment-refused', code: 'relay-attachment-refused', sent: false })
|
||
const many = await sendThroughRelay(payload, options, { ...MESSAGE, to: Array.from({ length: 60 }, (_, i) => `a${i}@example.org`) })
|
||
expect(many).toMatchObject({ code: 'relay-quota', sent: false })
|
||
const limit = (await getRelayStatus(payload, options)).limits?.maxAttachmentBytes ?? 0
|
||
const big = await sendThroughRelay(payload, options, { ...MESSAGE, attachments: [{ content: Buffer.alloc(limit + 1), filename: 'big.bin' }] })
|
||
expect(big).toMatchObject({ code: 'relay-too-large', sent: false })
|
||
})
|
||
|
||
test('the answer to a send is lost: the retry carries the same key and bytes, and no second mail goes out', async () => {
|
||
let lost = 0
|
||
const keys: (null | string)[] = []
|
||
const lossy = (async (input: string, init?: RequestInit) => {
|
||
const response = await fetch(input, init)
|
||
if (String(input).endsWith('/v1/send')) {
|
||
keys.push(new Headers(init?.headers).get('idempotency-key'))
|
||
if (lost++ === 0) {throw new TypeError('fetch failed')} // the service did its part; the answer never arrives
|
||
}
|
||
return response
|
||
}) as typeof fetch
|
||
const result = await sendThroughRelay(payload, { ...options, fetchImpl: lossy }, { ...MESSAGE, subject: 'Once only' })
|
||
expect(result, JSON.stringify(result)).toMatchObject({ replayed: true, sent: true })
|
||
expect(keys).toHaveLength(2)
|
||
expect(keys[0]).toBe(keys[1])
|
||
// (the outbox also records the service's own notices to Intecion, so this message is counted by its subject)
|
||
expect((await outbox()).filter((m) => m.subject === 'Once only')).toHaveLength(1)
|
||
})
|
||
|
||
test('requests from a new server address: 401 reverify, one enrolment, the message goes out', async () => {
|
||
const paths: string[] = []
|
||
// an address this site has not used in an earlier run against the same local database
|
||
const elsewhere = `198.51.100.${1 + Math.floor(Math.random() * 250)}`
|
||
const moved = (async (input: string, init?: RequestInit) => {
|
||
paths.push(String(input).slice(SERVICE.length))
|
||
return fetch(input, { ...init, headers: { ...(init?.headers as Record<string, string>), 'x-dev-client-address': elsewhere } })
|
||
}) as typeof fetch
|
||
const result = await sendThroughRelay(payload, { ...options, fetchImpl: moved }, { ...MESSAGE, subject: 'Moved' })
|
||
expect(result, JSON.stringify(result)).toMatchObject({ sent: true })
|
||
expect(paths).toEqual(['/v1/send', '/v1/enrol', '/v1/send'])
|
||
})
|
||
|
||
test('rotation: the new token is stored at once and works; the previous one cannot rotate again', async () => {
|
||
const old = (await readRelayStore(payload)).token!
|
||
expect(await rotateRelayToken(payload, options, { force: true })).toBe('rotated')
|
||
const fresh = (await readRelayStore(payload)).token!
|
||
expect(fresh).not.toBe(old)
|
||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'After rotation' })).sent).toBe(true)
|
||
const again = await relayRequest({ method: 'POST', path: '/v1/rotate', site: HOST, token: old, url: SERVICE })
|
||
expect(again).toMatchObject({ code: 'already-rotated', ok: false, retryable: false })
|
||
})
|
||
|
||
test('"Disconnect" revokes: the token stops working at once; "Connect again" enrols anew', async () => {
|
||
const token = (await readRelayStore(payload)).token!
|
||
await disconnectRelay(payload, options)
|
||
expect(await relayRequest({ method: 'GET', path: '/v1/status', site: HOST, token, url: SERVICE })).toMatchObject({ code: 'invalid-token', ok: false })
|
||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-disconnected', sent: false })
|
||
expect(await enrolRelay(payload, options, { force: true })).toEqual({ ok: true, state: 'active' })
|
||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Back' })).sent).toBe(true)
|
||
})
|
||
|
||
test('nothing in the service\'s outbox carries a token, and the site never logged one', async () => {
|
||
expect(JSON.stringify(await outbox())).not.toContain('ims_')
|
||
})
|
||
})
|