Files
ipal-kit/test/mailRelayContract.test.ts
Radosław SmolińskiandClaude Fable 5.2 fef2c51bae Mail relay: contract 1.7.0 — X-Intecion-Site on every request with a token, host-mismatch
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]>
2026-11-25 22:13:58 +01:00

274 lines
16 KiB
TypeScript

/**
* The plugin's copy of the wire contract of the Intecion Notifications Webservice (contracts/mail-relay,
* copied from the IWDL repository), and both sides of it as the plugin has them:
* - the copy is unedited (checksums) and is the version the client says it speaks;
* - the fake service (createFakeRelay) passes every example, through the contract's own runner;
* - the client does with each canned answer what the example's `client` block says: retry or not,
* enrol again or not, and the site status it reports;
* - the site's confirm route answers the call-back examples.
*/
import { execFileSync } from 'node:child_process'
import { randomBytes } from 'node:crypto'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { describe, expect, test, vi } from 'vitest'
import { RELAY_BASE_URL, RELAY_CONFIRM_PATH, RELAY_CONTRACT_VERSION, RELAY_STATUS_CODES } from '../src/modules/email/relay/constants.js'
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
import { sendThroughRelay } from '../src/modules/email/relay/send.js'
import { enrolRelay, refreshRelayStatus } from '../src/modules/email/relay/session.js'
import { holdNonce, readRelayCandidate, updateRelayStore } from '../src/modules/email/relay/store.js'
// the contract's runner is plain JavaScript, copied as it is
import { CONTRACT_VERSION, expand, runCallbackExample, runExample } from '../contracts/mail-relay/runner.mjs'
import { callConfirmRoute, CONTRACT_DIR, contractExamples, relayPayload, relaySite } from './mailRelay/helpers.js'
vi.mock('server-only', () => ({}))
const schema = JSON.parse(readFileSync(path.join(CONTRACT_DIR, 'schema.json'), 'utf8')) as { $defs: Record<string, Schema> }
type Schema = { [key: string]: unknown }
/** The part of JSON Schema 2020-12 the contract uses. Returns the problems found. */
function validate(node: Schema, value: unknown, at = 'value'): string[] {
const out: string[] = []
if (typeof node.$ref === 'string') {return validate(schema.$defs[node.$ref.replace('#/$defs/', '')], value, at)}
if ('const' in node && value !== node.const) {out.push(`${at}: not ${JSON.stringify(node.const)}`)}
if (Array.isArray(node.enum) && !node.enum.includes(value)) {out.push(`${at}: not one of ${node.enum.join(', ')}`)}
const type = node.type as string | undefined
const actual = Array.isArray(value) ? 'array' : value === null ? 'null' : Number.isInteger(value) ? 'integer' : typeof value
if (type && type !== actual && !(type === 'number' && actual === 'integer')) {return [...out, `${at}: ${actual}, expected ${type}`]}
if (typeof value === 'string') {
if (typeof node.minLength === 'number' && [...value].length < node.minLength) {out.push(`${at}: too short`)}
if (typeof node.maxLength === 'number' && [...value].length > node.maxLength) {out.push(`${at}: too long`)}
if (typeof node.pattern === 'string' && !new RegExp(node.pattern, 'u').test(value)) {out.push(`${at}: does not match ${node.pattern}`)}
}
if (typeof value === 'number' && typeof node.minimum === 'number' && value < node.minimum) {out.push(`${at}: below ${node.minimum}`)}
if (Array.isArray(value)) {
if (typeof node.minItems === 'number' && value.length < node.minItems) {out.push(`${at}: too few items`)}
if (typeof node.maxItems === 'number' && value.length > node.maxItems) {out.push(`${at}: too many items`)}
if (node.items) {value.forEach((item, i) => out.push(...validate(node.items as Schema, item, `${at}[${i}]`)))}
}
if (value && typeof value === 'object' && !Array.isArray(value)) {
const object = value as Record<string, unknown>
const properties = (node.properties ?? {}) as Record<string, Schema>
for (const name of (node.required ?? []) as string[]) {
if (!(name in object)) {out.push(`${at}: ${name} is missing`)}
}
for (const [name, child] of Object.entries(properties)) {
if (name in object) {out.push(...validate(child, object[name], `${at}.${name}`))}
}
if (node.additionalProperties === false) {
for (const name of Object.keys(object)) {
if (!(name in properties)) {out.push(`${at}: unknown field ${name}`)}
}
}
}
for (const part of (node.allOf ?? []) as Schema[]) {out.push(...validate(part, value, at))}
if (Array.isArray(node.anyOf) && !(node.anyOf as Schema[]).some((part) => validate(part, value, at).length === 0)) {out.push(`${at}: matches none of anyOf`)}
if (node.not && validate(node.not as Schema, value, at).length === 0) {out.push(`${at}: matches what it must not`)}
if (node.if) {
const branch = validate(node.if as Schema, value, at).length === 0 ? node.then : node.else
if (branch) {out.push(...validate(branch as Schema, value, at))}
}
return out
}
const examples = contractExamples()
const toService = examples.filter((e) => e.direction !== 'service-to-site')
const HOST = 'example.com'
const RECIPIENT = '[email protected]'
const ALERTS = '[email protected]'
const sha = async (text: string) => Buffer.from(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).toString('hex')
describe('the copied contract', () => {
test('is unedited: every file matches CHECKSUMS', () => {
const out = execFileSync('node', [path.join(CONTRACT_DIR, 'checksums.mjs'), '--check'], { encoding: 'utf8' })
expect(out).toMatch(/files match CHECKSUMS/)
})
test('is the version the client says it speaks, with the client\'s constants', () => {
const version = readFileSync(path.join(CONTRACT_DIR, 'VERSION'), 'utf8').trim()
expect(RELAY_CONTRACT_VERSION).toBe(version)
expect(CONTRACT_VERSION).toBe(version)
const readme = readFileSync(path.join(CONTRACT_DIR, 'README.md'), 'utf8')
expect(readme).toContain(`**Base address: \`${RELAY_BASE_URL}\`**`)
// the confirm path the service calls for this product, under Payload's default API route
expect(readme).toContain(`| \`iapl\` | \`POST https://<host>/api${RELAY_CONFIRM_PATH}\` |`)
expect(examples.find((e) => e.id === 'callback-confirm')?.request.path).toBe(`/api${RELAY_CONFIRM_PATH}`)
})
test('has the examples this file expects', () => {
expect(examples.length).toBeGreaterThanOrEqual(55)
expect(toService.length).toBeGreaterThanOrEqual(52)
})
})
describe('the fake service speaks the contract (the contract\'s runner, every example)', () => {
for (const example of toService) {
test(example.id, async () => {
const given = example.given ?? {}
const calls = { confirm: 0 }
const fake = createFakeRelay({
alertRecipient: ALERTS,
callSite: async (_url, init) => {
calls.confirm += 1
const { nonce, token } = JSON.parse(init.body) as { nonce: string; token: string }
switch (given.callback) {
case 'no-content':
return new Response(null, { status: 204 })
case 'not-found':
return new Response(null, { status: 404 })
case 'redirect':
return new Response(null, { headers: { location: 'https://www.example.com/' }, status: 301 })
case 'wrong-confirmation':
return Response.json({ confirmation: await sha(`${token}.${nonce}`) })
default:
return Response.json({ confirmation: await sha(`${nonce}.${token}`) })
}
},
})
let outboxStart = 0
const driver = {
arrange: async () => {
let token = `ims_${'x'.repeat(43)}`
if (given.listed === true) {fake.allow(HOST)}
if (given.site && given.site !== 'none') {
token = fake.setSite(HOST, given.site as 'active')
if (given.token === 'previous') {
// the token in {{token}} was replaced a moment ago
const rotated = await fake.handle(new Request(`${fake.url}/v1/rotate`, { headers: { authorization: `Bearer ${token}`, 'x-intecion-site': HOST }, method: 'POST' }))
expect(rotated.status).toBe(200)
}
if (given.token === 'unknown') {token = `ims_${'u'.repeat(43)}`}
}
const site = fake.site(HOST)
if (site && given.quota === 'hour-exhausted') {site.hourOther = fake.limits.messagesPerHour}
if (site && given.quota === 'day-exhausted') {site.dayOther = fake.limits.messagesPerDay}
if (site && given.quota === 'hour-share-used') {site.hourOther = Math.floor((fake.limits.messagesPerHour * 4) / 5)}
if (site && given.quota === 'recipient-exhausted') {site.confirmations.set(RECIPIENT, fake.limits.perRecipientPerDay)}
if (given.backend) {fake.backend = given.backend as 'failure'}
const vars = { alertRecipient: ALERTS, host: HOST, idempotencyKey: randomBytes(18).toString('base64url'), nonce: randomBytes(32).toString('base64url'), recipient: RECIPIENT, senderAddress: '[email protected]', token }
if (given.idempotency === 'sent-same' || given.idempotency === 'sent-other') {
const body = expand(example.request.body, vars, example.id) as Record<string, unknown>
const first = await fake.handle(new Request(`${fake.url}/v1/send`, {
body: JSON.stringify(given.idempotency === 'sent-same' ? body : { ...body, subject: 'Another message' }),
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'idempotency-key': vars.idempotencyKey, 'x-intecion-site': HOST },
method: 'POST',
}))
expect(first.status).toBe(200)
}
outboxStart = fake.outbox.length
return vars
},
mails: async () => fake.outbox.slice(outboxStart),
request: async ({ body, headers, method, path: route }: { body?: unknown; headers: Record<string, string>; method: string; path: string }) => {
const response = await fake.handle(new Request(`${fake.url}${route}`, {
body: body === undefined ? undefined : JSON.stringify(body),
headers: { ...headers, ...(given.address === 'unknown' ? { 'x-fake-client-address': '198.51.100.99' } : {}) },
method,
}))
return { body: (await response.json().catch(() => null)) as unknown, headers: Object.fromEntries(response.headers), status: response.status }
},
validate: (name: string, value: unknown) => validate(schema.$defs[name], value),
}
await runExample(example, driver)
// a suspended site is not called back; a refused request never reaches the site either
if (example.response.status === 403 || example.response.status === 400) {expect(calls.confirm).toBe(0)}
})
}
})
describe('the client acts on each answer as the example says (canned answers)', () => {
const KNOWN = new Set<string>(RELAY_STATUS_CODES)
for (const example of toService.filter((e) => e.client)) {
test(example.id, async () => {
const client = example.client!
const route = example.request.path
const canned: Record<string, unknown> = { message: 'canned', retryable: client.retry === true, ...example.response.body }
// /v1/send answers `ok: true` in full when the example only states part of it
const full: Record<string, unknown> = canned.ok === true && route === '/v1/send' ? { id: 'm1', quota: {}, replayed: false, senderName: HOST, warnings: [], ...canned } : canned
const seen: string[] = []
const { options, payload } = relaySite({
options: {
fetchImpl: (async (input: Request | string | URL) => {
const target = String(input instanceof Request ? input.url : input)
const called = target.slice(target.indexOf('/mail') + 5)
seen.push(called)
// the answer under test comes from the example's own route; an enrolment on the way is refused, so it shows
if (called === route) {return Response.json(full, { status: example.response.status })}
return Response.json({ code: 'enrolment-closed', message: 'closed', ok: false, retryable: false }, { status: 403 })
}) as typeof fetch,
},
})
if (route !== '/v1/enrol') {await updateRelayStore(payload, (c) => ({ ...c, host: HOST, state: 'active', token: `ims_${'t'.repeat(43)}` }))}
let status: null | string = null
if (route === '/v1/send') {
const result = await sendThroughRelay(payload, options, { html: '<p>Hello.</p>', subject: 'New enquiry', to: RECIPIENT })
status = result.sent ? (result.warnings.includes('sender-name-replaced') ? 'relay-name-replaced' : null) : result.code
expect(result.sent).toBe(full.ok === true)
// retried with the same request exactly when the example says so — three attempts in all, never more
expect(seen.filter((p) => p === '/v1/send').length).toBe(client.retry ? 3 : 1)
} else if (route === '/v1/enrol') {
const result = await enrolRelay(payload, options)
// the canned `200` carries no call-back, so no token arrived: only the refusals say something here
status = full.ok === true ? (full.state === 'pending' ? 'relay-pending' : null) : result.ok ? null : result.status
expect(seen.filter((p) => p === '/v1/enrol').length).toBe(1)
} else if (route === '/v1/status') {
const { error, stored } = await refreshRelayStatus(payload, options)
status = error ? null : stored.state === 'pending' ? 'relay-pending' : null
} else {
return // rotate, revoke: nothing a site reports
}
// enrols again exactly when the example says so
if (route !== '/v1/enrol') {expect(seen.includes('/v1/enrol')).toBe(client.reEnrol === true)}
if (client.status) {
expect(status).toBe(client.status)
// every status the contract suggests has a text of its own in the panel, or is the name warning
expect(KNOWN.has(client.status)).toBe(true)
} else if (full.ok !== true && !client.reEnrol && route === '/v1/send') {
// "report a bug" answers: not sent, and said so
expect(status).toBe('relay-error')
}
})
}
})
describe('the site\'s confirm route answers the call-back examples', () => {
const ours = examples.filter((e) => e.direction === 'service-to-site' && e.request.path === `/api${RELAY_CONFIRM_PATH}`)
test('both IAPL examples are here', () => {
expect(ours.map((e) => e.id).sort()).toEqual(['callback-confirm', 'callback-unknown-nonce'])
})
for (const example of ours) {
test(example.id, async () => {
const { payload } = relayPayload()
const confirm = callConfirmRoute(payload)
let raw = ''
const response = await runCallbackExample(example, {
confirm: async (request: { body: unknown; headers: Record<string, string>; path: string }) => {
const answer = await confirm(`https://${HOST}${request.path}`, { body: JSON.stringify(request.body), headers: request.headers })
raw = await answer.text()
return { body: raw ? (JSON.parse(raw) as unknown) : null, status: answer.status }
},
prepare: async (body: { held: boolean; nonce: string }) => {
if (body.held) {await holdNonce(payload, body.nonce, 60_000)}
},
})
const sent = example.request.body as { nonce: string; token: string }
if (response.status === 200) {
// exactly this object and nothing else
expect(raw).toBe(JSON.stringify(example.response.body))
expect(validate(schema.$defs.CallbackResponse, JSON.parse(raw))).toEqual([])
expect((await readRelayCandidate(payload))?.token).toBe(sent.token)
// single use: the same call again is a 404 and changes nothing
expect((await confirm(`https://${HOST}/api${RELAY_CONFIRM_PATH}`, { body: JSON.stringify(sent), headers: {} })).status).toBe(404)
} else {
expect(raw).toBe('')
expect(await readRelayCandidate(payload)).toBeNull()
}
})
}
})