Files
ipal-kit/test/mailMethodHttp.test.ts
T

308 lines
18 KiB
TypeScript

/**
* "Sending method" on a running Payload (SQLite by default; MongoDB and Postgres through
* IPAL_TEST_MONGO_URI / IPAL_TEST_POSTGRES_URI — test/http/db.ts): the explicit choice of 1.17.1.
* - upgrade: a site of 1.17.0 or 1.16.x, with nothing chosen, shows the method it sends through today and
* keeps sending; nothing is written by reading;
* - the first save of the panel's form stores the choice; from then on what is chosen is what is used —
* an unusable choice fails loudly and nothing leaves another way;
* - no stored field was added: the panel's field is virtual, the choice is in the key-value store.
*/
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, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest'
import { mailAdapter, resolveMailMethod, resolveMailTransport } from '../src/modules/email/mailAdapter.js'
import { getMailMethod, MAIL_METHOD_KV_KEY, setMailMethod } from '../src/modules/email/method.js'
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
import { mailPanelState } from '../src/modules/email/relay/panel.js'
import { SECRET_CLEAR } from '../src/modules/secrets/writeOnly.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 GRAPH_ENV = ['GRAPH_TENANT_ID', 'GRAPH_CLIENT_ID', 'GRAPH_CLIENT_SECRET', 'GRAPH_SENDER']
// a mail server nobody listens on: an SMTP attempt fails at once, and is told apart from "not attempted"
const SMTP = { smtpHost: '127.0.0.1', smtpPassword: 'smtp-test-password', smtpPort: 9, smtpUser: 'mailer' }
const NO_SMTP = { smtpHost: null, smtpPassword: SECRET_CLEAR, smtpPort: 587, smtpUser: null }
const MESSAGE = { html: '<p>Hello.</p>', subject: 'New enquiry', to: '[email protected]' }
let server: TestServer
let payload: Payload
let admin: Record<string, string>
const fake = createFakeRelay({
allow: [HOST],
callSite: async (url, init) => fetch(`${server.url}${new URL(url).pathname}`, { ...init, redirect: 'manual' }),
})
const makeConfig = (mail?: Parameters<typeof iapl>[0]['mail'], name = 'mailmethod') =>
buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-mail-method-media') } }],
db: testDatabase(name),
editor: lexicalEditor(),
email: mailAdapter({ smtp: { connectionTimeout: 2000 } as never }),
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
serverURL: `https://${HOST}`,
telemetry: false,
})
const api = (pathname: string, init: RequestInit = {}) =>
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...admin, ...(init.headers as Record<string, string>) } })
/** The global as the panel reads it. */
const read = async () => (await (await api('/globals/site-integrations?depth=0')).json()) as Record<string, unknown>
/** A save the way the panel's form makes it: the whole document, with what the form shows. */
const saveForm = async (change: Record<string, unknown> = {}) => {
const { id: _i, createdAt: _c, emailStatus: _s, globalType: _g, smtpPassword: _p, turnstileStatus: _t, updatedAt: _u, ...form } = await read()
return api('/globals/site-integrations', { body: JSON.stringify({ ...form, ...change }), method: 'POST' })
}
/** A site as an older version left it: the stored fields only, nothing chosen. */
const asStored = async (data: Record<string, unknown>) => {
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailTransport: 'smtp', ...NO_SMTP, ...data } as never })
await payload.kv.delete(MAIL_METHOD_KV_KEY)
}
const state = () => mailPanelState({ payload }, undefined)
const send = () => payload.sendEmail(MESSAGE) as Promise<{ code?: string; sent?: boolean; transport?: string }>
const relayCalls = () => fake.requests.filter((r) => r.path === '/v1/send').length
const status = async () => ((await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as unknown as { emailStatus?: { code?: string; state?: string } }).emailStatus
beforeAll(async () => {
const config = makeConfig({ relay: { fetchImpl: fake.fetch, url: fake.url } })
payload = await getPayload({ config })
server = await startPayloadServer(config)
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
const res = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
admin = { authorization: `JWT ${((await res.json()) as { token: string }).token}` }
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
beforeEach(() => {
for (const name of GRAPH_ENV) {vi.stubEnv(name, '')}
})
afterEach(() => vi.unstubAllEnvs())
describe('upgrade, with no edit: the site shows the method it sends through today, and keeps sending', () => {
test('a 1.17.0 site that sends through the service because SMTP is empty: "IWSN" is selected, mail leaves through it, reading writes nothing', async () => {
await asStored({ smtpFromAddress: '[email protected]', smtpFromName: 'Kancelaria Example' })
expect((await read()).emailMethod).toBe('relay')
expect(await state()).toMatchObject({ methodChosen: false, transport: 'relay' })
const before = relayCalls()
expect(await send()).toMatchObject({ transport: 'relay' })
expect(relayCalls()).toBe(before + 1)
expect(fake.outbox.at(-1)).toMatchObject({ subject: 'New enquiry' })
// the stored field is what it was, and nothing was chosen on the site's behalf
expect((await read()).emailTransport).toBe('smtp')
expect(await getMailMethod(payload)).toBeNull()
expect(await payload.kv.get(MAIL_METHOD_KV_KEY)).toBeNull()
})
test('a site with its SMTP server filled in: "Own SMTP server" is selected, the service is not contacted', async () => {
await asStored(SMTP)
expect((await read()).emailMethod).toBe('smtp')
expect(await state()).toMatchObject({ methodChosen: false, transport: 'smtp' })
const before = fake.requests.length
const sent = await send().catch((e: Error) => ({ code: 'threw', error: e.message, sent: false }))
expect(sent.sent).not.toBe(true) // nobody listens on the port: SMTP was tried, and only SMTP
expect(fake.requests).toHaveLength(before)
expect((await status())?.code).toBe('smtp-error')
})
test('a Graph site: "Microsoft Graph (deprecated)" is selected — with the choice stored as `graph`, or with only the GRAPH_* variables', async () => {
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
await asStored({ emailTransport: 'graph' })
expect((await read()).emailMethod).toBe('graph')
expect(await state()).toMatchObject({ methodChosen: false, transport: 'graph' })
await asStored({})
expect((await read()).emailMethod).toBe('graph')
// and with SMTP filled in beside the variables: SMTP, as in 1.17.0 and 1.16
await asStored(SMTP)
expect((await read()).emailMethod).toBe('smtp')
})
test('1.16.x straight to 1.17.1: "Graph" stored without the variables and SMTP filled in → SMTP; half an SMTP set-up → the service, with the hint', async () => {
await asStored({ emailTransport: 'graph', ...SMTP })
expect((await read()).emailMethod).toBe('smtp')
expect(await state()).toMatchObject({ methodChosen: false, transport: 'smtp' })
await asStored({ smtpHost: 'smtp.example.com', smtpUser: 'mailer' })
expect((await read()).emailMethod).toBe('relay')
expect(await state()).toMatchObject({ methodChosen: false, smtpIncomplete: true, transport: 'relay' })
const before = relayCalls()
expect(await send()).toMatchObject({ transport: 'relay' })
expect(relayCalls()).toBe(before + 1)
})
test('a new site (nothing ever saved): "IWSN" is selected', async () => {
await payload.kv.delete(MAIL_METHOD_KV_KEY)
await asStored({})
expect((await read()).emailMethod).toBe('relay')
})
})
describe('the choice: what is chosen is what is used', () => {
test('the first save of the panel\'s form stores what the form shows; the answer shows it; the stored field of 1.17.0 follows', async () => {
await asStored({})
const saved = await saveForm({ smtpFromName: 'Kancelaria Example' })
expect(saved.status).toBe(200)
expect(((await saved.json()) as { result: { emailMethod: string } }).result.emailMethod).toBe('relay')
expect(await getMailMethod(payload)).toBe('relay')
expect(await state()).toMatchObject({ methodChosen: true, transport: 'relay' })
// a choice changed in the form
const changed = await saveForm({ emailMethod: 'graph' })
expect(((await changed.json()) as { result: { emailMethod: string; emailTransport: string } }).result).toMatchObject({ emailMethod: 'graph', emailTransport: 'graph' })
expect(await getMailMethod(payload)).toBe('graph')
expect((await read()).emailMethod).toBe('graph')
await saveForm({ emailMethod: 'smtp' })
expect(await read()).toMatchObject({ emailMethod: 'smtp', emailTransport: 'smtp' })
})
test('"IWSN" chosen: the service carries the mail although an SMTP server is filled in and the GRAPH_* variables are set', async () => {
await asStored(SMTP)
await saveForm({ emailMethod: 'relay' })
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
expect(await state()).toMatchObject({ methodChosen: true, transport: 'relay' })
const before = relayCalls()
expect(await send()).toMatchObject({ transport: 'relay' })
expect(relayCalls()).toBe(before + 1)
expect((await read()).emailMethod).toBe('relay')
})
test('"Own SMTP server" chosen with nothing filled in: the mail fails and says so — nothing goes through the service', async () => {
await asStored({})
expect((await saveForm({ emailMethod: 'smtp' })).status).toBe(200)
expect(await state()).toMatchObject({ methodChosen: true, methodProblem: 'smtp-incomplete', transport: 'smtp' })
const before = fake.requests.length
expect(await send()).toMatchObject({ code: 'not-configured', sent: false })
expect(fake.requests).toHaveLength(before)
expect(await status()).toMatchObject({ code: 'smtp-incomplete', state: 'degraded' })
// the test e-mail says the same to the admin, and still nothing leaves another way
const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
expect(tested.status).toBe(502)
expect(fake.requests).toHaveLength(before)
// the form still shows what was chosen, not what would work
expect((await read()).emailMethod).toBe('smtp')
})
test('"Microsoft Graph" chosen on a server without GRAPH_*: fails loudly; neither SMTP (filled in) nor the service is tried', async () => {
await asStored(SMTP)
await saveForm({ emailMethod: 'graph' })
expect(await state()).toMatchObject({ methodChosen: true, methodProblem: 'graph-not-set-up', transport: 'graph' })
const before = fake.requests.length
expect(await send()).toMatchObject({ code: 'graph-not-set-up', sent: false })
expect(fake.requests).toHaveLength(before)
expect(await status()).toMatchObject({ code: 'graph-not-set-up', state: 'degraded' }) // not `smtp-error`: SMTP was not tried
const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
expect(tested.status).toBe(502)
expect(((await tested.json()) as { code: string; error: string })).toMatchObject({ code: 'graph-not-set-up' })
// with the variables the problem is gone (no send here: that would call Microsoft)
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
expect((await state()).methodProblem).toBeUndefined()
})
test('the test e-mail names the method that carried it', async () => {
await asStored({ smtpFromName: 'Kancelaria Example' })
await saveForm({ emailMethod: 'relay' })
const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
expect(tested.status).toBe(200)
expect(await tested.json()).toMatchObject({ ok: true, transport: 'relay' })
})
test('a save that names nothing about e-mail leaves the choice alone; the old field written alone means what it meant', async () => {
await asStored({})
await setMailMethod(payload, 'smtp')
expect((await api('/globals/site-integrations', { body: JSON.stringify({ ga4MeasurementId: 'G-TEST123' }), method: 'POST' })).status).toBe(200)
expect(await getMailMethod(payload)).toBe('smtp')
// a script from before 1.17.1 writes `emailTransport`: the order of 1.17.0 applies again
expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailTransport: 'graph' }), method: 'POST' })).status).toBe(200)
expect(await getMailMethod(payload)).toBeNull()
expect((await read()).emailMethod).toBe('relay') // Graph stored, no variables, no SMTP: the service, as in 1.17.0
// the Local API, and the building blocks
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailMethod: 'smtp' } as never })
expect(await getMailMethod(payload)).toBe('smtp')
await setMailMethod(payload, null)
expect(await getMailMethod(payload)).toBeNull()
await expect(setMailMethod(payload, 'sendmail' as never)).rejects.toThrow('not a sending method')
// a value that is not a method is refused by the field
expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: 'sendmail' }), method: 'POST' })).status).toBe(400)
expect(await getMailMethod(payload)).toBeNull()
})
test('only an admin reaches the choice; it is not in the key-value store\'s REST', async () => {
expect((await fetch(`${server.url}/api/globals/site-integrations`, { body: JSON.stringify({ emailMethod: 'smtp' }), headers: { 'content-type': 'application/json' }, method: 'POST' })).status).toBeGreaterThanOrEqual(401)
expect((await api('/payload-kv')).status).toBeGreaterThanOrEqual(400)
})
})
describe('resolveMailMethod', () => {
const full = { smtpHost: 'smtp.example.com', smtpPassword: 'x', smtpUser: 'u' }
const half = { smtpHost: 'smtp.example.com' }
const on = { graphEnv: true, relay: true }
const off = { graphEnv: false, relay: true }
test.each([
// chosen, settings, env → method, problem
['relay', full, on, 'relay', undefined],
['relay', {}, off, 'relay', undefined],
['smtp', full, on, 'smtp', undefined],
['smtp', half, on, 'smtp', 'smtp-incomplete'],
['smtp', {}, off, 'smtp', 'smtp-incomplete'],
['graph', full, on, 'graph', undefined],
['graph', full, off, 'graph', 'graph-not-set-up'],
['graph', {}, off, 'graph', 'graph-not-set-up'],
] as const)('chosen %s, %j, %j → %s (%s)', (chosen, settings, state, method, problem) => {
expect(resolveMailMethod(settings, { ...state, chosen })).toEqual({ explicit: true, method, ...(problem ? { problem } : {}) })
})
test('nothing chosen: the order of 1.17.0, never a problem; "IWSN" chosen with the service switched off counts as nothing chosen', () => {
for (const settings of [{}, half, full, { emailTransport: 'graph' as const }, { emailTransport: 'graph' as const, ...full }]) {
for (const state of [on, off, { graphEnv: true, relay: false }, { graphEnv: false, relay: false }]) {
expect(resolveMailMethod(settings, { ...state, chosen: null })).toEqual({ explicit: false, method: resolveMailTransport(settings, state) })
expect(resolveMailMethod(settings, { ...state, chosen: 'relay', relay: false })).toEqual({ explicit: false, method: resolveMailTransport(settings, { ...state, relay: false }) })
}
}
})
})
describe('no stored field was added', () => {
test('`emailMethod` is virtual: the SQL table has no column for it; the document in the database does not hold it', async () => {
await asStored({})
await saveForm({ emailMethod: 'smtp' })
const db = payload.db as unknown as { collections?: unknown; connection?: { collection: (n: string) => { findOne: (q: object) => Promise<null | Record<string, unknown>> } }; name?: string; tables?: Record<string, Record<string, unknown>> }
if (db.tables) {
const table = db.tables.site_integrations
expect(table).toBeTruthy()
const columns = Object.keys(table).map((c) => c.toLowerCase())
expect(columns).toContain('emailtransport')
expect(columns.filter((c) => c.includes('method'))).toEqual([])
} else {
const raw = await db.connection!.collection('globals').findOne({ globalType: 'site-integrations' })
expect(raw).toMatchObject({ emailTransport: 'smtp' })
expect(raw).not.toHaveProperty('emailMethod')
}
await setMailMethod(payload, null)
})
test('`mail: { relay: false }`: the option "IWSN" is not offered, and a stored choice of it counts as none', async () => {
const methods = (config: Awaited<ReturnType<typeof makeConfig>>) => {
const field = JSON.stringify(config.globals?.find((g) => g.slug === 'site-integrations')?.fields).match(/"name":"emailMethod".*?"options":\[(.*?)\]/)?.[1] ?? ''
return [...field.matchAll(/"value":"(\w+)"/g)].map((m) => m[1])
}
expect(methods(await makeConfig(undefined, 'methodson'))).toEqual(['relay', 'smtp', 'graph'])
expect(methods(await makeConfig({ relay: false }, 'methodsoff'))).toEqual(['smtp', 'graph'])
})
})