/** * The Intecion mail service on a running Payload, through real HTTP requests (REST and GraphQL): * - the confirm route is public, answers 404 unless the site itself just started an enrolment, and is * the route the (fake) service really calls during the first send; * - the token is in Payload's key-value store and cannot be read or changed over REST or GraphQL by * anybody, an admin included, and no route of the plugin answers with it; * - each mail says what it is: the test e-mail, a form's two e-mails, Payload's "forgot password"; * - the state routes are for admins; `relay: false` leaves no route and no block; no stored field changed. */ import type { Field, Payload, SanitizedConfig } 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 { mailAdapter } from '../src/modules/email/mailAdapter.js' import { RELAY_CONFIRM_PATH, RELAY_KV_KEY } from '../src/modules/email/relay/constants.js' import { createFakeRelay } from '../src/modules/email/relay/fake.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 PASSWORD = 'a-long-test-password-1' const HOST = 'example.com' const CONFIRM = `/api${RELAY_CONFIRM_PATH}` /** The site's entry: one per host. */ const SITE_KEY = `${RELAY_KV_KEY}:site:${HOST}` let server: TestServer let payload: Payload let admin: Record let editor: Record const confirmCalls: string[] = [] // The service reaches the site the way it would in production — over HTTP, at the fixed path — only the host is this machine. const fake = createFakeRelay({ allow: [HOST], callSite: async (url, init) => { const target = new URL(url) confirmCalls.push(`${target.host}${target.pathname}`) return fetch(`${server.url}${target.pathname}`, { ...init, redirect: 'manual' }) }, }) // the access-key field is off by default; one test switches it on (the plugin reads the options on every request) const relayOptions: { accessKeyField?: boolean; fetchImpl: typeof fetch; url: string } = { fetchImpl: fake.fetch, url: fake.url } const makeConfig = (mail?: Parameters[0]['mail'], name = 'relayhttp') => buildTestConfig({ admin: { user: 'users' }, collections: [ { slug: 'pages', fields: [{ name: 'title', type: 'text' }] }, { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-relay-test-media') } }, ], db: testDatabase(name), editor: lexicalEditor(), email: mailAdapter(), plugins: [ iapl({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail, twoFactor: false, }), ], secret: 'integration-test-secret-0123456789', serverURL: `https://${HOST}`, telemetry: false, }) async function login(email: string): Promise> { const res = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email, password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' }) const body = (await res.json()) as { token?: string } if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)} return { authorization: `JWT ${body.token}` } } const api = (pathname: string, headers: Record = {}, init: RequestInit = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...headers, ...(init.headers as Record) } }) const post = (pathname: string, headers: Record, body?: unknown) => api(pathname, headers, { body: body === undefined ? undefined : JSON.stringify(body), method: 'POST' }) beforeAll(async () => { const config = makeConfig({ relay: relayOptions }) payload = await getPayload({ config }) server = await startPayloadServer(config) await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromAddress: 'biuro@example.com', smtpFromName: 'Kancelaria Example' } as never }) await payload.create({ collection: 'users' as never, data: { email: 'admin@example.com', password: PASSWORD, roles: ['admin'] } as never }) await payload.create({ collection: 'users' as never, data: { email: 'editor@example.com', password: PASSWORD, roles: ['editor'] } as never }) admin = await login('admin@example.com') editor = await login('editor@example.com') }, 120_000) afterAll(async () => { await server?.close() await payload?.destroy?.() }) describe('the confirm route', () => { test('is public and answers 404 with nothing in it — to a stranger, to an admin, to any shape of body', async () => { const token = `ims_${'a'.repeat(43)}` for (const [headers, body] of [ [{}, { nonce: 'n'.repeat(43), state: 'active', token }], [admin, { nonce: 'n'.repeat(43), state: 'active', token }], [{}, {}], [{}, 'not json'], ] as const) { const res = await api(RELAY_CONFIRM_PATH, headers, { body: typeof body === 'string' ? body : JSON.stringify(body), method: 'POST' }) expect(res.status).toBe(404) expect(await res.text()).toBe('') } expect((await api(RELAY_CONFIRM_PATH)).status).toBe(404) // GET: no such route expect((await readRelayStore(payload)).token).toBeUndefined() }) }) describe('the first e-mail', () => { test('the admin\'s test e-mail enrols the site through the confirm route and leaves through the service', async () => { const res = await post('/ipal/test-email', admin, { to: 'anna@example.org' }) const body = (await res.json()) as { message?: string; ok: boolean; transport?: string } expect(body, JSON.stringify(body)).toMatchObject({ ok: true, transport: 'relay' }) expect(body.message).toContain('Kancelaria Example') expect(confirmCalls).toEqual([`${HOST}${CONFIRM}`]) expect(fake.requests.map((r) => r.path).slice(0, 2)).toEqual(['/v1/enrol', '/v1/send']) expect(fake.outbox).toHaveLength(1) expect(fake.outbox[0]).toMatchObject({ fromName: 'Kancelaria Example', host: HOST, kind: 'test', replyTo: 'biuro@example.com', to: ['anna@example.org'] }) expect(JSON.stringify(body)).not.toContain('ims_') }) }) describe('the token cannot be reached from outside', () => { let token = '' let id: number | string = '' test('it is in the key-value store', async () => { token = (await readRelayStore(payload)).token ?? '' expect(token).toMatch(/^ims_[\w-]{43}$/) const rows = await payload.db.find({ collection: 'payload-kv', limit: 0, pagination: false, where: { key: { equals: SITE_KEY } } }) expect(rows.docs).toHaveLength(1) id = (rows.docs[0] as { id: number | string }).id expect(JSON.stringify(rows.docs[0])).toContain(token) }) test.each([['a stranger', () => ({})], ['an editor', () => editor], ['an admin', () => admin]] as const)('REST refuses %s: list, one document, by key, write and delete', async (_who, session) => { const headers = session() const answers = [ await api('/payload-kv', headers), await api(`/payload-kv/${id}`, headers), await api(`/payload-kv?where[key][equals]=${encodeURIComponent(SITE_KEY)}&depth=0`, headers), await api('/payload-kv', headers, { body: JSON.stringify({ data: { token: 'x' }, key: `${RELAY_KV_KEY}:x` }), method: 'POST' }), await api(`/payload-kv/${id}`, headers, { body: JSON.stringify({ data: {} }), method: 'PATCH' }), await api(`/payload-kv/${id}`, headers, { method: 'DELETE' }), await api('/payload-kv/count', headers), ] for (const res of answers) { const text = await res.text() expect(res.status, text).toBeGreaterThanOrEqual(400) expect(text).not.toContain('ims_') } expect((await readRelayStore(payload)).token).toBe(token) }) test('GraphQL has no way to it either', async () => { const ask = async (query: string, headers: Record) => (await post('/graphql', headers, { query })).text() const schema = await ask('{ __schema { queryType { fields { name } } mutationType { fields { name } } types { name } } }', admin) const names = [...schema.matchAll(/"name":"([^"]+)"/g)].map((m) => m[1]).filter((n) => /kv/i.test(n)) for (const headers of [{}, editor, admin]) { for (const query of [ '{ PayloadKvs { docs { key data } } }', `{ PayloadKv(id: ${JSON.stringify(id)}) { key data } }`, '{ countPayloadKvs { totalDocs } }', ...names.map((n) => `{ ${n} { docs { key data } } }`), ]) { const text = await ask(query, headers) expect(text).not.toContain('ims_') expect(text).not.toContain(RELAY_KV_KEY) const parsed = JSON.parse(text) as { data?: null | Record; errors?: unknown[] } // refused, or no such field at all — never data expect(Object.values(parsed.data ?? {}).every((v) => v === null)).toBe(true) expect(parsed.errors?.length).toBeGreaterThan(0) } } }) test('no route of the plugin answers with it: the state block, the global, the doctor status', async () => { const state = await api('/iapl/mail-relay/status?refresh=1', admin) const body = (await state.json()) as { relay: Record; transport: string } expect(body).toMatchObject({ relay: { connected: true, senderAddress: 'notification@webservices.intecion.net', state: 'active' }, replyAddress: 'biuro@example.com', transport: 'relay' }) expect(body.relay.quota).toMatchObject({ hour: { limit: 30, remaining: 29 } }) for (const res of [state, await api('/globals/site-integrations', admin), await api('/globals/site-integrations?depth=2&draft=true', admin)]) { expect(res === state ? JSON.stringify(body) : await res.text()).not.toContain('ims_') } expect(JSON.stringify(body)).not.toContain('ims_') }) }) describe('the state routes are for admins', () => { test('a stranger gets 401, an editor 403, on all three', async () => { for (const [method, route] of [['GET', '/iapl/mail-relay/status'], ['POST', '/iapl/mail-relay/connect'], ['POST', '/iapl/mail-relay/disconnect']] as const) { expect((await api(route, {}, { method })).status).toBe(401) expect((await api(route, editor, { method })).status).toBe(403) } expect((await readRelayStore(payload)).token).toMatch(/^ims_/) }) test('"Disconnect" and "Connect again" work for an admin, and neither shows a token', async () => { // by default there is no access-key field: the state does not offer it and the route takes no token at all const mine = (await readRelayStore(payload)).token expect(((await (await api('/iapl/mail-relay/status', admin)).json()) as { accessKeyField?: boolean }).accessKeyField).toBeUndefined() const closed = await post('/iapl/mail-relay/connect', admin, { token: fake.issueToken(HOST) }) expect(closed.status).toBe(403) // said as what it is — not "only an administrator can do this" to an administrator expect(((await closed.json()) as { error: string }).error).toMatch(/set by the site's developer/) expect((await readRelayStore(payload)).token).toBe(mine) // a project switches the field on: mail.relay.accessKeyField relayOptions.accessKeyField = true expect(((await (await api('/iapl/mail-relay/status', admin)).json()) as { accessKeyField?: boolean }).accessKeyField).toBe(true) // a token of another site pasted while the site is connected: refused, and the site's own token stays const stranger = fake.issueToken('someone-else.example.org') expect((await post('/iapl/mail-relay/connect', admin, { token: stranger })).status).toBe(400) expect((await readRelayStore(payload)).token).toBe(mine) expect(mine).toMatch(/^ims_/) const off = await post('/iapl/mail-relay/disconnect', admin) const offBody = (await off.json()) as Record expect(offBody).toMatchObject({ ok: true, relay: { connected: false, disconnected: true } }) const failed = (await (await post('/ipal/test-email', admin, { to: 'anna@example.org' })).json()) as { code?: string; ok: boolean } expect(failed).toMatchObject({ code: 'relay-disconnected', ok: false }) const bad = await post('/iapl/mail-relay/connect', admin, { token: 'ims_not-a-token' }) expect(bad.status).toBe(400) // the access-key field: a token the service does not know, and a token of ANOTHER site, are refused before // anything is stored; the other site's token is not revoked expect((await post('/iapl/mail-relay/connect', admin, { token: `ims_${'q'.repeat(43)}` })).status).toBe(400) const foreign = fake.issueToken('other-client.example.org') const refused = await post('/iapl/mail-relay/connect', admin, { token: foreign }) expect(refused.status).toBe(400) expect(await refused.text()).not.toContain('ims_') expect((await readRelayStore(payload)).token).toBeUndefined() expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${foreign}`, 'x-intecion-site': 'other-client.example.org' } }))).status).toBe(200) // a token issued by hand for THIS host is taken, and the state says where it came from const own = await post('/iapl/mail-relay/connect', admin, { token: fake.issueToken(HOST) }) expect(await own.json()).toMatchObject({ ok: true, relay: { connected: true, tokenSource: 'manual' } }) await post('/iapl/mail-relay/disconnect', admin) const on = await post('/iapl/mail-relay/connect', admin) const onBody = (await on.json()) as Record expect(onBody, JSON.stringify(onBody)).toMatchObject({ ok: true, relay: { connected: true, disconnected: false, state: 'active' } }) expect(JSON.stringify([offBody, onBody])).not.toContain('ims_') expect(confirmCalls).toHaveLength(2) }) }) describe('each mail says what it is', () => { test('Payload\'s "forgot password" is account mail, and a visitor cannot make the site send it without end', async () => { const before = fake.outbox.length const ask = (email: string) => post('/users/forgot-password', { 'x-forwarded-for': '198.51.100.44' }, { email }) expect((await ask('editor@example.com')).status).toBe(200) const sent = fake.outbox.slice(before) // Payload composed and sent it; the mark of the operation's hook told the transport what it is expect(sent).toHaveLength(1) expect(sent[0]).toMatchObject({ kind: 'account', to: ['editor@example.com'] }) // the mark is used up by that one message: other mail to the same address is not "account" await payload.sendEmail({ html: '

x

', subject: 'Report', to: 'editor@example.com' }) expect(fake.outbox.at(-1)?.kind).toBe('system') // asked again and again: this Payload answers 200 and sends no second mail within its own interval; the // plugin's limit per address and per visitor (mail.relay.accountMail, test/mailRelay.test.ts) is behind it for (let i = 0; i < 6; i++) {expect((await ask('editor@example.com')).status).toBe(200)} expect(fake.outbox.slice(before).filter((m) => m.kind === 'account').length).toBeLessThanOrEqual(5) // an address without an account sends nothing const count = fake.outbox.length await ask('nobody@example.com') expect(fake.outbox).toHaveLength(count) }) test('a form\'s notification (addresses from the panel) and its confirmation (the visitor\'s address) are told apart', async () => { const message = { root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', text: 'Dziękujemy.', version: 1 }], direction: null, format: '', indent: 0, version: 1 }], direction: null, format: '', indent: 0, version: 1 } } const form = await payload.create({ collection: 'forms' as never, data: { confirmationMessage: message, confirmationType: 'message', emails: [ { emailFrom: 'biuro@example.com', emailTo: 'office@example.org', message, subject: 'Nowe zapytanie od {{name}}' }, { emailFrom: 'biuro@example.com', emailTo: '{{email}}', message, subject: 'Potwierdzenie' }, ], fields: [ { name: 'name', blockType: 'text', label: 'Name' }, { name: 'email', blockType: 'email', label: 'E-mail' }, ], title: 'Contact', } as never, }) const before = fake.outbox.length await payload.create({ collection: 'form-submissions' as never, data: { form: (form as { id: number | string }).id, submissionData: [{ field: 'name', value: 'Jan\r\nBcc: x@example.net' }, { field: 'email', value: 'jan@example.org' }] } as never, }) const sent = fake.outbox.slice(before) expect(sent.map((m) => [m.kind, m.to[0]]).sort()).toEqual([['form-confirmation', 'jan@example.org'], ['form-notification', 'office@example.org']]) // a visitor's words in the subject cannot add a header expect(sent.find((m) => m.kind === 'form-notification')?.subject).toBe('Nowe zapytanie od Jan Bcc: x@example.net') expect(sent.every((m) => m.fromName === 'Kancelaria Example')).toBe(true) }) }) describe('switched off, and what did not change', () => { const endpoints = (config: SanitizedConfig) => (config.endpoints ?? []).map((e) => `${e.method} ${e.path}`) const stored = (fields: Field[]): string[] => fields.flatMap((f) => { if (f.type === 'ui') {return []} if (f.type === 'tabs') {return f.tabs.flatMap((t) => stored(t.fields))} const own = 'name' in f && f.name ? [`${f.name}:${f.type}${f.type === 'select' ? `(${(f.options as { value: string }[]).map((o) => (typeof o === 'string' ? o : o.value)).join('|')})` : ''}`] : [] return 'fields' in f && Array.isArray(f.fields) ? [...own, ...stored(f.fields).map((n) => ('name' in f && f.name ? `${f.name}.${n}` : n))] : own }) const emailTab = (config: SanitizedConfig) => JSON.stringify(config.globals?.find((g) => g.slug === 'site-integrations')?.fields) test('mail: { relay: false } leaves no route, no state block and no mark on the auth collection', async () => { const off = await makeConfig({ relay: false }, 'relayoff') const on = await makeConfig(undefined, 'relayon') expect(endpoints(on)).toEqual(expect.arrayContaining(['post /iapl/mail-relay/confirm', 'get /iapl/mail-relay/status', 'post /iapl/mail-relay/connect', 'post /iapl/mail-relay/disconnect'])) expect(endpoints(off).filter((e) => e.includes('mail-relay'))).toEqual([]) expect(emailTab(on)).toContain('"mailRelay":true') expect(emailTab(off)).not.toContain('mailRelay') // no admin component of its own: a site's committed import map stays as it is expect(emailTab(on)).not.toContain('#MailRelayStatus') expect(emailTab(off)).not.toContain('Intecion') expect((off.custom as { iapl: { mail: { relay: unknown } } }).iapl.mail.relay).toBe(false) const hooks = (config: SanitizedConfig) => config.collections?.find((c) => c.slug === 'users')?.hooks?.beforeOperation?.length ?? 0 expect(hooks(on) - hooks(off)).toBe(1) }) test('no stored field differs: the same names, types and select values with the service on, off, and as in 1.16', async () => { const names = (config: SanitizedConfig) => stored((config.globals?.find((g) => g.slug === 'site-integrations')?.fields ?? [])).filter((n) => /^(?:email|smtp)/.test(n)) const on = names(await makeConfig(undefined, 'fieldson')) expect(on).toEqual(names(await makeConfig({ relay: false }, 'fieldsoff'))) expect(on).toEqual([ // new in 1.17.1 (Postgres / SQLite: one migration); the same three values with the service on and off 'emailMethod:select(relay|smtp|graph)', 'emailTransport:select(smtp|graph)', 'smtpFromAddress:email', 'smtpFromName:text', 'smtpHost:text', 'smtpPort:number', 'smtpUser:text', 'smtpPassword:text', 'emailStatus:group', 'emailStatus.state:select(ok|degraded)', 'emailStatus.code:text', 'emailStatus.message:text', 'emailStatus.since:date', 'emailStatus.checkedAt:date', ]) }) })