WIP: form attachments tests
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
6003b3d7d7
commit
02b1e96d3d
@@ -91,6 +91,9 @@ function readGraphEnv(): GraphEnv | null {
|
||||
*/
|
||||
const tokenCache = new Map<string, { expiresAt: number; token: string }>()
|
||||
|
||||
/** Forgets cached Graph tokens (after rotating the client secret in a running process; tests). */
|
||||
export const clearGraphTokenCache = (): void => tokenCache.clear()
|
||||
|
||||
async function getAccessToken(env: GraphEnv, fetchImpl: typeof fetch = fetch): Promise<string> {
|
||||
const cacheKey = `${env.tenantId}:${env.clientId}`
|
||||
const cached = tokenCache.get(cacheKey)
|
||||
|
||||
@@ -170,10 +170,11 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
|
||||
if (attemptKey) {
|
||||
const running = inflight.get(attemptKey)
|
||||
if (running) {return stop(await running)}
|
||||
const earlier = await findSubmitAttempt(payload, attemptKey)
|
||||
if (earlier) {return stop(earlier)}
|
||||
// Registered before the next await, so a twin request arriving now waits for this one.
|
||||
registered = attemptKey
|
||||
inflight.set(attemptKey, new Promise<SubmitFormResult>((done) => (settle = done)))
|
||||
const earlier = await findSubmitAttempt(payload, attemptKey)
|
||||
if (earlier) {return stop(earlier)}
|
||||
}
|
||||
|
||||
if (checked.validation.fileFields.length > 0 && !canCarryFiles(checked.validation.form)) {return stop({ reason: 'delivery', success: false })}
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
/**
|
||||
* Attachments through both e-mail paths. SMTP: the real nodemailer against a
|
||||
* small local SMTP server. Microsoft Graph: a mocked Graph (no tenant, no
|
||||
* credentials) that records every call — the inline path, the upload session,
|
||||
* and the clean-up of the mailbox copy.
|
||||
*/
|
||||
import type { BasePayload, PayloadEmailAdapter } from 'payload'
|
||||
|
||||
import { createServer, type Server } from 'node:net'
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { clearGraphTokenCache, graphAdapter, graphLargeAttachmentSupport } from '../src/modules/email/graphAdapter.js'
|
||||
import { GRAPH_INLINE_MAX_BYTES } from '../src/modules/email/graphAttachments.js'
|
||||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||||
import { panelSmtpAdapter } from '../src/modules/email/panelSmtpAdapter.js'
|
||||
import { fakePayload } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const MB = 1024 * 1024
|
||||
const bytes = (size: number) => Buffer.from(Array.from({ length: size }, (_, i) => i % 251))
|
||||
const attachment = (size: number, filename = 'cv.pdf') => ({ content: bytes(size), contentDisposition: 'attachment' as const, contentType: 'application/pdf', filename })
|
||||
|
||||
// ---- SMTP -------------------------------------------------------------------------------------
|
||||
|
||||
type Received = { data: string; to: string[] }
|
||||
|
||||
/** `refuseOver`: answer DATA with 552 when the message is larger (a server with a size limit). */
|
||||
function startSmtp(received: Received[], limits: { refuseOver?: number } = {}): Promise<{ port: number; server: Server }> {
|
||||
const server = createServer((socket) => {
|
||||
const mail: Received = { data: '', to: [] }
|
||||
let inData = false
|
||||
let buffer = ''
|
||||
const reply = (line: string) => socket.write(`${line}\r\n`)
|
||||
reply('220 localhost ESMTP test')
|
||||
socket.on('data', (chunk) => {
|
||||
buffer += chunk.toString('latin1')
|
||||
let index: number
|
||||
while ((index = buffer.indexOf('\r\n')) >= 0) {
|
||||
const line = buffer.slice(0, index)
|
||||
buffer = buffer.slice(index + 2)
|
||||
if (inData) {
|
||||
if (line === '.') {
|
||||
inData = false
|
||||
if (limits.refuseOver && mail.data.length > limits.refuseOver) {
|
||||
reply('552 5.3.4 Message size exceeds fixed limit')
|
||||
} else {
|
||||
received.push(mail)
|
||||
reply('250 2.0.0 Ok: queued')
|
||||
}
|
||||
} else {
|
||||
mail.data += `${line}\n`
|
||||
}
|
||||
continue
|
||||
}
|
||||
const command = line.toUpperCase()
|
||||
if (command.startsWith('EHLO')) {socket.write('250-localhost\r\n250-AUTH PLAIN LOGIN\r\n250 8BITMIME\r\n')}
|
||||
else if (command.startsWith('AUTH PLAIN')) {reply('235 2.7.0 Authentication successful')}
|
||||
else if (command.startsWith('MAIL FROM:')) {reply('250 2.1.0 Ok')}
|
||||
else if (command.startsWith('RCPT TO:')) {
|
||||
mail.to.push(line.slice(8).trim())
|
||||
reply('250 2.1.5 Ok')
|
||||
} else if (command === 'DATA') {
|
||||
inData = true
|
||||
reply('354 End data with <CR><LF>.<CR><LF>')
|
||||
} else if (command === 'QUIT') {
|
||||
reply('221 2.0.0 Bye')
|
||||
socket.end()
|
||||
} else {reply('502 5.5.2 Command not recognized')}
|
||||
}
|
||||
})
|
||||
})
|
||||
return new Promise((resolve) => {
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const address = server.address()
|
||||
resolve({ port: typeof address === 'object' && address ? address.port : 0, server })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const build = (adapter: PayloadEmailAdapter, payload: BasePayload) => adapter({ payload } as Parameters<PayloadEmailAdapter>[0])
|
||||
|
||||
/** The base64 body of the first attachment in a raw message, decoded. */
|
||||
function attachedBytes(raw: string): Buffer {
|
||||
const start = raw.indexOf('Content-Disposition: attachment')
|
||||
const body = raw.slice(raw.indexOf('\n\n', start) + 2)
|
||||
return Buffer.from(body.slice(0, body.indexOf('\n--')).replace(/\s+/g, ''), 'base64')
|
||||
}
|
||||
|
||||
// ---- a mocked Microsoft Graph ------------------------------------------------------------------
|
||||
|
||||
type Call = { body?: unknown; headers: Record<string, string>; method: string; url: string }
|
||||
|
||||
const jwt = (roles: string[]) => `x.${Buffer.from(JSON.stringify({ roles })).toString('base64url')}.y`
|
||||
|
||||
function mockGraph({ fail, roles = ['Mail.Send', 'Mail.ReadWrite'], sentAfterLooks = 1 }: { fail?: (call: Call) => number | undefined; roles?: string[]; sentAfterLooks?: number } = {}) {
|
||||
const calls: Call[] = []
|
||||
const uploaded: Buffer[] = []
|
||||
let looks = 0
|
||||
const fetchImpl = (async (input: string | URL, init: RequestInit = {}) => {
|
||||
const url = String(input)
|
||||
const method = init.method ?? 'GET'
|
||||
const headers = (init.headers ?? {}) as Record<string, string>
|
||||
if (url.includes('login.microsoftonline.com')) {return Response.json({ access_token: jwt(roles), expires_in: 3600 })}
|
||||
const call: Call = { body: typeof init.body === 'string' ? (JSON.parse(init.body) as unknown) : init.body, headers, method, url }
|
||||
calls.push(call)
|
||||
const failure = fail?.(call)
|
||||
if (failure) {return new Response('{"error":{"code":"Failed"}}', { status: failure })}
|
||||
if (url.endsWith('/sendMail')) {return new Response(null, { status: 202 })}
|
||||
if (method === 'POST' && url.endsWith('/messages')) {return Response.json({ id: 'draft-1' }, { status: 201 })}
|
||||
if (url.endsWith('/attachments/createUploadSession')) {return Response.json({ uploadUrl: 'https://outlook.office.com/upload/session-1' }, { status: 201 })}
|
||||
if (url.endsWith('/attachments')) {return Response.json({ id: 'att' }, { status: 201 })}
|
||||
if (method === 'PUT' && url.startsWith('https://outlook.office.com/upload/')) {
|
||||
uploaded.push(Buffer.from(init.body as Uint8Array))
|
||||
const [, end, total] = /bytes \d+-(\d+)\/(\d+)/.exec(headers['Content-Range']) ?? []
|
||||
return Response.json({}, { status: Number(end) + 1 === Number(total) ? 201 : 200 })
|
||||
}
|
||||
if (url.endsWith('/send')) {return new Response(null, { status: 202 })}
|
||||
if (method === 'GET' && url.includes('/messages/draft-1')) {return Response.json({ isDraft: ++looks < sentAfterLooks })}
|
||||
if (url.endsWith('/permanentDelete')) {return new Response(null, { status: 204 })}
|
||||
if (method === 'DELETE') {return new Response(null, { status: 204 })}
|
||||
return new Response('unexpected', { status: 500 })
|
||||
}) as unknown as typeof fetch
|
||||
const names = () => calls.map((c) => `${c.method} ${c.url.replace('https://graph.microsoft.com/v1.0/users/forms%40example.com', '').replace(/\?.*$/, '')}`)
|
||||
return { calls, fetchImpl, names, uploaded }
|
||||
}
|
||||
|
||||
const graphEnv = () => {
|
||||
vi.stubEnv('GRAPH_TENANT_ID', 'tenant')
|
||||
vi.stubEnv('GRAPH_CLIENT_ID', 'client')
|
||||
vi.stubEnv('GRAPH_CLIENT_SECRET', 'secret')
|
||||
vi.stubEnv('GRAPH_SENDER', '[email protected]')
|
||||
}
|
||||
|
||||
describe('attachments', () => {
|
||||
const received: Received[] = []
|
||||
const limited: Received[] = []
|
||||
let port = 0
|
||||
let limitedPort = 0
|
||||
let servers: Server[] = []
|
||||
|
||||
beforeAll(async () => {
|
||||
const open = await startSmtp(received)
|
||||
const small = await startSmtp(limited, { refuseOver: 200_000 })
|
||||
port = open.port
|
||||
limitedPort = small.port
|
||||
servers = [open.server, small.server]
|
||||
})
|
||||
afterAll(async () => {
|
||||
await Promise.all(servers.map((s) => new Promise((resolve) => s.close(resolve))))
|
||||
})
|
||||
afterEach(() => {
|
||||
received.length = 0
|
||||
limited.length = 0
|
||||
clearGraphTokenCache()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
const smtp = (p = port) => ({ smtpFromAddress: '[email protected]', smtpHost: '127.0.0.1', smtpPassword: 'pw', smtpPort: p, smtpUser: 'mailer' })
|
||||
const message = (size: number) => ({ attachments: [attachment(size)], html: '<p>New application</p>', subject: 'Application', to: '[email protected]' })
|
||||
|
||||
describe('SMTP', () => {
|
||||
test('a 10 MB file goes out as an attachment and arrives byte for byte', async () => {
|
||||
const { payload } = fakePayload({ integrations: smtp() })
|
||||
const result = await build(panelSmtpAdapter(), payload).sendEmail(message(10 * MB))
|
||||
expect(result).toMatchObject({ sent: true })
|
||||
expect(received).toHaveLength(1)
|
||||
expect(received[0].data).toContain('filename=cv.pdf')
|
||||
expect(received[0].data.length).toBeGreaterThan(13.3 * MB) // base64: about 13.7 MB on the wire
|
||||
expect(Buffer.compare(attachedBytes(received[0].data), bytes(10 * MB))).toBe(0)
|
||||
expect(await (build(panelSmtpAdapter(), payload) as { attachmentLimit?: unknown }).attachmentLimit).toBeUndefined()
|
||||
}, 60_000)
|
||||
|
||||
test('a server that refuses the size: reported as not sent, with the server\'s reason', async () => {
|
||||
const { payload } = fakePayload({ integrations: smtp(limitedPort) })
|
||||
const result = (await build(panelSmtpAdapter(), payload).sendEmail(message(MB))) as { detail?: string; sent: boolean }
|
||||
expect(result.sent).toBe(false)
|
||||
expect(result.detail).toContain('552')
|
||||
expect(limited).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Microsoft Graph (mocked)', () => {
|
||||
test('under 3 MB: one sendMail call with the file inline, nothing kept in the mailbox', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ roles: ['Mail.Send'] })
|
||||
const { payload } = fakePayload()
|
||||
const result = await build(graphAdapter({ fetchImpl: graph.fetchImpl }), payload).sendEmail(message(2 * MB))
|
||||
expect(result).toEqual({ sent: true })
|
||||
expect(graph.names()).toEqual(['POST /sendMail'])
|
||||
const body = graph.calls[0].body as { message: { attachments: { contentBytes: string; name: string }[] }; saveToSentItems: boolean }
|
||||
expect(body.saveToSentItems).toBe(false)
|
||||
expect(body.message.attachments[0].name).toBe('cv.pdf')
|
||||
expect(Buffer.compare(Buffer.from(body.message.attachments[0].contentBytes, 'base64'), bytes(2 * MB))).toBe(0)
|
||||
})
|
||||
|
||||
test('10 MB: draft → upload session in order → send → the mailbox copy is deleted', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ sentAfterLooks: 2 })
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ cleanupDelaysMs: [0, 0, 0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(10 * MB))) as { cleanup: Promise<string>; sent: boolean }
|
||||
expect(result.sent).toBe(true)
|
||||
expect(await result.cleanup).toBe('deleted')
|
||||
|
||||
expect(graph.names()).toEqual([
|
||||
'POST /messages',
|
||||
'POST /messages/draft-1/attachments/createUploadSession',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'POST /messages/draft-1/send',
|
||||
'GET /messages/draft-1', // still a draft: not deleted yet (deleting now could cancel the send)
|
||||
'GET /messages/draft-1', // sent
|
||||
'POST /messages/draft-1/permanentDelete',
|
||||
])
|
||||
// The draft is addressed and labelled like any message, and asks for an id that survives the move to Sent Items.
|
||||
expect(graph.calls[0].body).toMatchObject({ subject: 'Application', toRecipients: [{ emailAddress: { address: '[email protected]' } }] })
|
||||
expect(graph.calls[0].headers.Prefer).toBe('IdType="ImmutableId"')
|
||||
expect((graph.calls[1].body as { AttachmentItem: unknown }).AttachmentItem).toMatchObject({ name: 'cv.pdf', attachmentType: 'file', size: 10 * MB })
|
||||
// Every byte, in order, in pieces under 4 MB, without the bearer token on the pre-authenticated URL.
|
||||
expect(Buffer.compare(Buffer.concat(graph.uploaded), bytes(10 * MB))).toBe(0)
|
||||
expect(graph.uploaded.every((part) => part.length < 4 * MB)).toBe(true)
|
||||
const puts = graph.calls.filter((c) => c.method === 'PUT')
|
||||
expect(puts.every((c) => !('Authorization' in c.headers))).toBe(true)
|
||||
expect(puts.map((c) => c.headers['Content-Range'])[0]).toBe(`bytes 0-${10 * 320 * 1024 - 1}/${10 * MB}`)
|
||||
})
|
||||
|
||||
test('several files: small ones are added directly, large ones through a session', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph()
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl }), payload).sendEmail({
|
||||
...message(MB),
|
||||
attachments: [attachment(MB, 'letter.pdf'), attachment(4 * MB, 'cv.pdf')],
|
||||
})) as { cleanup: Promise<string>; sent: boolean }
|
||||
expect(result.sent).toBe(true)
|
||||
await result.cleanup
|
||||
expect(graph.names().slice(0, 6)).toEqual([
|
||||
'POST /messages',
|
||||
'POST /messages/draft-1/attachments',
|
||||
'POST /messages/draft-1/attachments/createUploadSession',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'POST /messages/draft-1/send',
|
||||
])
|
||||
})
|
||||
|
||||
test.each([
|
||||
['the upload fails', (c: Call) => (c.method === 'PUT' ? 503 : undefined)],
|
||||
['the send fails', (c: Call) => (c.url.endsWith('/send') ? 500 : undefined)],
|
||||
['the upload session cannot be created', (c: Call) => (c.url.endsWith('createUploadSession') ? 400 : undefined)],
|
||||
])('%s: not sent, and the draft with the file is deleted from the mailbox', async (_name, fail) => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ fail })
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { code?: string; sent: boolean }
|
||||
expect(result).toMatchObject({ code: 'graph-error', sent: false })
|
||||
expect(graph.names().at(-1)).toBe('POST /messages/draft-1/permanentDelete')
|
||||
expect(graph.names()).not.toContain('GET /messages/draft-1')
|
||||
})
|
||||
|
||||
test('permanentDelete unavailable: falls back to a plain delete', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ fail: (c) => (c.url.endsWith('/permanentDelete') ? 404 : undefined) })
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { cleanup: Promise<string> }
|
||||
expect(await result.cleanup).toBe('deleted')
|
||||
expect(graph.names().slice(-2)).toEqual(['POST /messages/draft-1/permanentDelete', 'DELETE /messages/draft-1'])
|
||||
})
|
||||
|
||||
test('the sent copy cannot be removed: the send still counts, and the log says to delete it by hand', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ fail: (c) => (c.url.endsWith('/permanentDelete') || c.method === 'DELETE' ? 500 : undefined) })
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ cleanupDelaysMs: [0, 0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { cleanup: Promise<string>; sent: boolean }
|
||||
expect(result.sent).toBe(true)
|
||||
expect(await result.cleanup).toBe('left')
|
||||
expect(payload.logger.warn).toHaveBeenCalledWith(expect.stringContaining('delete it by hand'))
|
||||
})
|
||||
|
||||
test('without Mail.ReadWrite: a clear refusal that names the permission, and nothing is created', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ roles: ['Mail.Send'] })
|
||||
const { payload } = fakePayload()
|
||||
const adapter = build(graphAdapter({ fetchImpl: graph.fetchImpl }), payload)
|
||||
const result = (await adapter.sendEmail(message(5 * MB))) as { code?: string; detail?: string; sent: boolean }
|
||||
expect(result).toMatchObject({ code: 'graph-permission', sent: false })
|
||||
expect(result.detail).toContain('Mail.ReadWrite')
|
||||
expect(payload.logger.error).toHaveBeenCalledWith(expect.stringContaining('Mail.ReadWrite'))
|
||||
expect(graph.calls).toEqual([])
|
||||
expect(await graphLargeAttachmentSupport({ fetchImpl: graph.fetchImpl })).toBe('no-permission')
|
||||
expect(await (adapter as unknown as { attachmentLimit: () => Promise<null | number> }).attachmentLimit()).toBe(GRAPH_INLINE_MAX_BYTES - 1)
|
||||
})
|
||||
|
||||
test('Graph answers 403 to the draft (a token that hides its roles): the same refusal', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ fail: (c) => (c.method === 'POST' && c.url.endsWith('/messages') ? 403 : undefined) })
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { code?: string; detail?: string }
|
||||
expect(result.code).toBe('graph-permission')
|
||||
expect(result.detail).toContain('Mail.ReadWrite')
|
||||
})
|
||||
|
||||
test('largeAttachments: false — Graph keeps to small attachments', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph()
|
||||
const { payload } = fakePayload()
|
||||
const adapter = build(graphAdapter({ fetchImpl: graph.fetchImpl, largeAttachments: false }), payload)
|
||||
expect(await adapter.sendEmail(message(5 * MB))).toMatchObject({ code: 'graph-large-off', sent: false })
|
||||
expect(graph.calls).toEqual([])
|
||||
expect(await adapter.sendEmail(message(MB))).toEqual({ sent: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('mailAdapter: Graph selected in the panel', () => {
|
||||
const limitOf = (adapter: unknown) => (adapter as { attachmentLimit: () => Promise<null | number> }).attachmentLimit()
|
||||
|
||||
test('permission present: large files go over Graph, no ceiling', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph()
|
||||
const { payload } = fakePayload({ integrations: { ...smtp(), emailTransport: 'graph' } })
|
||||
const adapter = build(mailAdapter({ graph: { cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl } }), payload)
|
||||
expect(await limitOf(adapter)).toBeNull()
|
||||
expect(await adapter.sendEmail(message(5 * MB))).toMatchObject({ sent: true })
|
||||
expect(graph.names()).toContain('POST /messages/draft-1/send')
|
||||
expect(received).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('permission missing, SMTP filled in: the large message goes over SMTP; small ones stay on Graph', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ roles: ['Mail.Send'] })
|
||||
const { payload } = fakePayload({ integrations: { ...smtp(), emailTransport: 'graph' } })
|
||||
const adapter = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl } }), payload)
|
||||
expect(await limitOf(adapter)).toBeNull()
|
||||
expect(await adapter.sendEmail(message(5 * MB))).toMatchObject({ sent: true })
|
||||
expect(received).toHaveLength(1)
|
||||
expect(Buffer.compare(attachedBytes(received[0].data), bytes(5 * MB))).toBe(0)
|
||||
expect(graph.calls).toEqual([])
|
||||
expect(await adapter.sendEmail(message(MB))).toEqual({ sent: true })
|
||||
expect(graph.names()).toEqual(['POST /sendMail'])
|
||||
expect(received).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('permission missing, no SMTP: the ceiling is just under 3 MB, and a larger send fails clearly', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ roles: ['Mail.Send'] })
|
||||
const { payload } = fakePayload({ integrations: { emailTransport: 'graph' } })
|
||||
const adapter = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl } }), payload)
|
||||
expect(await limitOf(adapter)).toBe(GRAPH_INLINE_MAX_BYTES - 1)
|
||||
const result = (await adapter.sendEmail(message(5 * MB))) as { code?: string; detail?: string; sent: boolean }
|
||||
expect(result).toMatchObject({ code: 'graph-permission', sent: false })
|
||||
expect(result.detail).toContain('Mail.ReadWrite')
|
||||
})
|
||||
|
||||
test('switched off by the project (largeAttachments: false): SMTP carries large files when filled in', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph()
|
||||
const withSmtp = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl, largeAttachments: false } }), fakePayload({ integrations: { ...smtp(), emailTransport: 'graph' } }).payload)
|
||||
expect(await limitOf(withSmtp)).toBeNull()
|
||||
expect(await withSmtp.sendEmail(message(5 * MB))).toMatchObject({ sent: true })
|
||||
expect(received).toHaveLength(1)
|
||||
const without = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl, largeAttachments: false } }), fakePayload({ integrations: { emailTransport: 'graph' } }).payload)
|
||||
expect(await limitOf(without)).toBe(GRAPH_INLINE_MAX_BYTES - 1)
|
||||
})
|
||||
|
||||
test('SMTP selected: no ceiling from the plugin', async () => {
|
||||
const adapter = build(mailAdapter(), fakePayload({ integrations: smtp() }).payload)
|
||||
expect(await limitOf(adapter)).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import type { BasePayload, PayloadEmailAdapter } from 'payload'
|
||||
import { createServer, type Server } from 'node:net'
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { clearGraphTokenCache } from '../src/modules/email/graphAdapter.js'
|
||||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||||
import { panelSmtpAdapter } from '../src/modules/email/panelSmtpAdapter.js'
|
||||
import { sendEmail } from '../src/modules/email/sendEmail.js'
|
||||
@@ -90,6 +91,7 @@ describe('e-mail transports (nodemailer 10)', () => {
|
||||
|
||||
afterEach(() => {
|
||||
received.length = 0
|
||||
clearGraphTokenCache()
|
||||
vi.unstubAllEnvs()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
@@ -0,0 +1,645 @@
|
||||
/**
|
||||
* Form files end to end through a REAL Payload (SQLite in memory): the form is
|
||||
* built in the "panel" (Local API), the browser's multipart request goes to the
|
||||
* real endpoint handler as a stream, and the e-mails land in a recording adapter.
|
||||
*
|
||||
* The groups follow the seven acceptance tests of the client request
|
||||
* (vanstevpl-web, 2026-11-13), re-read for "files are e-mailed, never stored".
|
||||
*/
|
||||
import type { Payload, PayloadEmailAdapter, PayloadRequest } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { readdirSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import zlib from 'node:zlib'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { FormFileScanInput } from '../src/modules/forms/attachments/config.js'
|
||||
|
||||
import { getFormAttachments } from '../src/modules/forms/attachments/config.js'
|
||||
import { handleFormSubmit } from '../src/modules/forms/attachments/submitHandler.js'
|
||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const MB = 1024 * 1024
|
||||
const mediaDir = path.join(os.tmpdir(), 'ipal-test-form-files-media')
|
||||
|
||||
// ---- sample files -------------------------------------------------------------------------
|
||||
|
||||
const utf16 = (text: string) => Buffer.from(text, 'utf16le')
|
||||
const pad = (head: Buffer, size: number) => Buffer.concat([head, Buffer.alloc(Math.max(0, size - head.length), 0x20)])
|
||||
|
||||
/** A stored (uncompressed) ZIP with the given entries — enough for the container checks. */
|
||||
function zip(entries: Record<string, string>): Buffer {
|
||||
const locals: Buffer[] = []
|
||||
const central: Buffer[] = []
|
||||
let offset = 0
|
||||
for (const [name, content] of Object.entries(entries)) {
|
||||
const data = Buffer.from(content)
|
||||
const file = Buffer.from(name)
|
||||
const crc = zlib.crc32(data)
|
||||
const local = Buffer.alloc(30)
|
||||
local.writeUInt32LE(0x04034b50, 0)
|
||||
local.writeUInt16LE(20, 4)
|
||||
local.writeUInt32LE(crc, 14)
|
||||
local.writeUInt32LE(data.length, 18)
|
||||
local.writeUInt32LE(data.length, 22)
|
||||
local.writeUInt16LE(file.length, 26)
|
||||
const header = Buffer.alloc(46)
|
||||
header.writeUInt32LE(0x02014b50, 0)
|
||||
header.writeUInt16LE(20, 4)
|
||||
header.writeUInt16LE(20, 6)
|
||||
header.writeUInt32LE(crc, 16)
|
||||
header.writeUInt32LE(data.length, 20)
|
||||
header.writeUInt32LE(data.length, 24)
|
||||
header.writeUInt16LE(file.length, 28)
|
||||
header.writeUInt32LE(offset, 42)
|
||||
locals.push(local, file, data)
|
||||
central.push(header, file)
|
||||
offset += 30 + file.length + data.length
|
||||
}
|
||||
const directory = Buffer.concat(central)
|
||||
const end = Buffer.alloc(22)
|
||||
end.writeUInt32LE(0x06054b50, 0)
|
||||
end.writeUInt16LE(Object.keys(entries).length, 8)
|
||||
end.writeUInt16LE(Object.keys(entries).length, 10)
|
||||
end.writeUInt32LE(directory.length, 12)
|
||||
end.writeUInt32LE(offset, 16)
|
||||
return Buffer.concat([...locals, directory, end])
|
||||
}
|
||||
|
||||
const OLE = Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])
|
||||
const PDF = pad(Buffer.from('%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n'), 4096)
|
||||
const DOC = pad(Buffer.concat([OLE, utf16('WordDocument')]), 2048)
|
||||
const DOC_MACRO = pad(Buffer.concat([OLE, utf16('WordDocument'), utf16('Macros'), utf16('_VBA_PROJECT')]), 2048)
|
||||
const DOCX = zip({ '[Content_Types].xml': '<Types/>', 'word/document.xml': '<w:document/>' })
|
||||
const DOCX_MACRO = zip({ '[Content_Types].xml': '<Types/>', 'word/document.xml': '<w:document/>', 'word/vbaProject.bin': 'x' })
|
||||
const EXE = pad(Buffer.from('MZ\x90\x00\x03'), 1024)
|
||||
const ARCHIVE = zip({ 'readme.txt': 'hello' })
|
||||
|
||||
// ---- the site ------------------------------------------------------------------------------
|
||||
|
||||
type Mail = { attachments?: { content: Buffer; contentType: string; filename: string }[]; html: string; subject: string; to: string }
|
||||
const mails: Mail[] = []
|
||||
let mailMode: 'ok' | 'refuse' | 'throw' = 'ok'
|
||||
const recordingMail: PayloadEmailAdapter = () => ({
|
||||
name: 'test-mail',
|
||||
defaultFromAddress: '[email protected]',
|
||||
defaultFromName: 'Acme',
|
||||
sendEmail: (message) => {
|
||||
const mail = message as unknown as Mail
|
||||
mails.push(mail)
|
||||
// Only the message that carries a file is refused — like a server with a size limit.
|
||||
if (mail.attachments?.length && mailMode === 'refuse') {return Promise.resolve({ detail: '552 5.3.4 Message size exceeds fixed limit', error: 'The e-mail was not sent.', sent: false })}
|
||||
if (mail.attachments?.length && mailMode === 'throw') {return Promise.reject(new Error('connect ECONNREFUSED'))}
|
||||
return Promise.resolve({ messageId: 'ok' })
|
||||
},
|
||||
})
|
||||
|
||||
const scanned: FormFileScanInput[] = []
|
||||
let scanVerdict = true
|
||||
|
||||
const text = (value: string) => ({
|
||||
root: {
|
||||
type: 'root',
|
||||
children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: value, version: 1 }], direction: null, format: '', indent: 0, version: 1 }],
|
||||
direction: null,
|
||||
format: '',
|
||||
indent: 0,
|
||||
version: 1,
|
||||
},
|
||||
})
|
||||
|
||||
let payload: Payload
|
||||
let formId: string
|
||||
let ipCounter = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({
|
||||
config: buildTestConfig({
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: mediaDir } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
email: recordingMail,
|
||||
plugins: [
|
||||
ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
forms: {
|
||||
attachments: {
|
||||
maxConcurrent: 0,
|
||||
maxSizeMB: 1,
|
||||
scan: (file) => {
|
||||
scanned.push(file)
|
||||
return { ok: scanVerdict }
|
||||
},
|
||||
},
|
||||
},
|
||||
i18n: {
|
||||
defaultLocale: 'pl',
|
||||
locales: [
|
||||
{ code: 'pl', label: 'Polski' },
|
||||
{ code: 'en', label: 'English' },
|
||||
{ code: 'de', label: 'Deutsch' },
|
||||
{ code: 'nl', label: 'Nederlands' },
|
||||
],
|
||||
},
|
||||
twoFactor: false,
|
||||
}),
|
||||
],
|
||||
secret: 'form-files-test-secret',
|
||||
telemetry: false,
|
||||
}),
|
||||
})
|
||||
|
||||
// Built in the default language first, then the English texts on the same rows.
|
||||
const base = {
|
||||
confirmationMessage: text('Thank you'),
|
||||
emails: [
|
||||
{ emailFrom: '[email protected]', emailTo: '[email protected]', message: text('New application from {{name}}: {{attachment}}'), subject: 'Application' },
|
||||
{ emailFrom: '[email protected]', emailTo: '{{email}}', message: text('We got your application, {{name}}.'), subject: 'Thank you' },
|
||||
],
|
||||
fields: [
|
||||
{ name: 'name', blockType: 'text', label: 'Name', required: true },
|
||||
{ name: 'email', blockType: 'email', label: 'E-mail', required: true },
|
||||
{ name: 'attachment', allowedTypes: ['pdf', 'doc', 'docx'], blockType: 'file', help: 'PDF, DOC or DOCX, up to 1 MB', label: 'Załącznik (opcjonalnie)', maxFiles: 1, maxSizeMB: 1 },
|
||||
{ name: 'consent', blockType: 'checkbox', label: 'Consent' },
|
||||
],
|
||||
title: 'Careers',
|
||||
}
|
||||
const form = (await payload.create({ collection: 'forms' as never, data: base as never, locale: 'pl' })) as unknown as {
|
||||
emails: Record<string, unknown>[]
|
||||
fields: Record<string, unknown>[]
|
||||
id: number | string
|
||||
}
|
||||
formId = String(form.id)
|
||||
await payload.update({
|
||||
id: formId,
|
||||
collection: 'forms' as never,
|
||||
data: {
|
||||
confirmationMessage: base.confirmationMessage,
|
||||
emails: form.emails.map((email, i) => ({ ...email, message: base.emails[i].message, subject: base.emails[i].subject })),
|
||||
fields: form.fields.map(({ resolved: _resolved, ...f }) => (f.name === 'attachment' ? { ...f, help: 'PDF, DOC or DOCX, up to 1 MB', label: 'Attachment (optional)' } : f)),
|
||||
} as never,
|
||||
locale: 'en',
|
||||
})
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
mails.length = 0
|
||||
scanned.length = 0
|
||||
mailMode = 'ok'
|
||||
scanVerdict = true
|
||||
vi.unstubAllGlobals()
|
||||
delete process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY
|
||||
delete process.env.TURNSTILE_SECRET_KEY
|
||||
})
|
||||
|
||||
type Upload = { data: Buffer; field?: string; name: string }
|
||||
type Post = {
|
||||
attempt?: string
|
||||
files?: Upload[]
|
||||
form?: string
|
||||
headers?: Record<string, string>
|
||||
ip?: string
|
||||
locale?: string
|
||||
token?: string
|
||||
values?: Record<string, unknown>
|
||||
}
|
||||
|
||||
const answers = { name: 'Jan Kowalski', consent: true, email: '[email protected]' }
|
||||
|
||||
/** The browser's request: answers first, files last — to the real handler, body as a stream. */
|
||||
async function post({ attempt, files = [], form = formId, headers = {}, ip, locale = 'en', token, values = answers }: Post = {}) {
|
||||
const body = new FormData()
|
||||
body.append('_form', form)
|
||||
body.append('_locale', locale)
|
||||
if (attempt) {body.append('_attempt', attempt)}
|
||||
if (token) {body.append('_token', token)}
|
||||
body.append('_values', JSON.stringify(values))
|
||||
for (const file of files) {body.append(file.field ?? 'attachment', new File([new Uint8Array(file.data)], file.name))}
|
||||
const request = new Request(`http://localhost/api/ipal/forms/submit?locale=${locale}`, {
|
||||
body,
|
||||
headers: { 'sec-fetch-site': 'same-origin', 'x-real-ip': ip ?? `10.9.${Math.floor(++ipCounter / 250)}.${ipCounter % 250}`, ...headers },
|
||||
method: 'POST',
|
||||
})
|
||||
const response = await handleFormSubmit(Object.assign(request, { payload }) as unknown as PayloadRequest)
|
||||
return { body: (await response.json()) as { field?: string; message: string; reason?: string; success: boolean }, status: response.status }
|
||||
}
|
||||
|
||||
type Submission = {
|
||||
attemptKey?: string
|
||||
filesDelivery?: string
|
||||
filesDeliveryNote?: string
|
||||
id: number | string
|
||||
submissionData: { field: string; value: string }[]
|
||||
submissionFiles?: { field: string; name: string; size: number; type: string }[]
|
||||
}
|
||||
const submissions = async () =>
|
||||
(await payload.find({ collection: 'form-submissions' as never, depth: 0, limit: 200, sort: 'createdAt' })).docs as unknown as Submission[]
|
||||
const count = async () => (await payload.count({ collection: 'form-submissions' as never })).totalDocs
|
||||
const withFile = () => mails.filter((m) => m.attachments?.length)
|
||||
|
||||
describe('1 · a submission without the optional file works as before', () => {
|
||||
test('through the server action path: stored, both e-mails sent, no file data anywhere', async () => {
|
||||
const before = await count()
|
||||
const result = await submitForm({ data: answers, formId, ip: '10.8.0.1', locale: 'en', payload })
|
||||
expect(result.success).toBe(true)
|
||||
expect(await count()).toBe(before + 1)
|
||||
expect(mails.map((m) => m.to).sort()).toEqual(['[email protected]', '[email protected]'])
|
||||
expect(withFile()).toEqual([])
|
||||
const stored = (await submissions()).at(-1)!
|
||||
expect(stored.submissionData.map((d) => d.field)).toEqual(['name', 'email', 'consent'])
|
||||
expect(stored.filesDelivery ?? null).toBeNull()
|
||||
expect(stored.submissionFiles ?? []).toEqual([])
|
||||
})
|
||||
|
||||
test('through the endpoint without a file part: the same outcome', async () => {
|
||||
const before = await count()
|
||||
const { body, status } = await post()
|
||||
expect({ status, success: body.success }).toEqual({ status: 200, success: true })
|
||||
expect(await count()).toBe(before + 1)
|
||||
expect(mails).toHaveLength(2)
|
||||
expect(withFile()).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('2 · each allowed format: one submission, the file in the staff e-mail only', () => {
|
||||
test.each([
|
||||
['CV Jan Kowalski.pdf', PDF, 'pdf', 'application/pdf'],
|
||||
['cv.DOC', DOC, 'doc', 'application/msword'],
|
||||
['Życiorys (2026).docx', DOCX, 'docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
|
||||
])('%s', async (name, data, type, mime) => {
|
||||
const before = await count()
|
||||
const { body, status } = await post({ files: [{ name, data }] })
|
||||
expect({ status, success: body.success }).toEqual({ status: 200, success: true })
|
||||
expect(await count()).toBe(before + 1)
|
||||
|
||||
// The staff e-mail carries the file, byte for byte; the confirmation to the visitor does not.
|
||||
const staff = mails.filter((m) => m.to === '[email protected]')
|
||||
expect(staff).toHaveLength(1)
|
||||
expect(staff[0].attachments).toHaveLength(1)
|
||||
const attachment = staff[0].attachments![0]
|
||||
expect(Buffer.compare(attachment.content, data)).toBe(0)
|
||||
expect(attachment.contentType).toBe(mime)
|
||||
expect(attachment.filename.endsWith(`.${type}`)).toBe(true)
|
||||
expect(staff[0].html).toContain(attachment.filename) // {{attachment}} → the readable name
|
||||
expect(staff[0].html).toContain('not checked for viruses')
|
||||
const customer = mails.filter((m) => m.to === '[email protected]')
|
||||
expect(customer).toHaveLength(1)
|
||||
expect(customer[0].attachments).toBeUndefined()
|
||||
expect(customer[0].html).not.toContain('viruses')
|
||||
|
||||
// The submission keeps metadata only.
|
||||
const stored = (await submissions()).at(-1)!
|
||||
expect(stored.submissionFiles).toMatchObject([{ name: attachment.filename, type, field: 'attachment', size: data.length }])
|
||||
expect(stored.filesDelivery).toBe('sent')
|
||||
expect(stored.submissionData.find((d) => d.field === 'attachment')?.value).toMatch(new RegExp(`\\.${type} \\(\\d+ (?:B|KB)\\)$`))
|
||||
expect(JSON.stringify(stored)).not.toContain(data.toString('base64').slice(0, 40))
|
||||
expect(scanned.map((s) => s.type)).toEqual([type]) // the optional scan hook saw exactly this file
|
||||
})
|
||||
})
|
||||
|
||||
describe('3 · refused files leave no submission and send no e-mail', () => {
|
||||
const refused = async (files: Upload[], expected: RegExp, extra: Post = {}) => {
|
||||
const before = await count()
|
||||
const { body, status } = await post({ files, ...extra })
|
||||
expect(body.success).toBe(false)
|
||||
expect(status).toBe(422)
|
||||
expect(body.message).toMatch(expected)
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
}
|
||||
|
||||
test('oversized: stopped while reading', async () => {
|
||||
await refused([{ name: 'big.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 200_000) }], /"big\.pdf" is too large\. The limit is 1 MB\./)
|
||||
expect(scanned).toEqual([])
|
||||
})
|
||||
|
||||
test('mismatched: a program named .pdf, a PDF named .docx, an empty file', async () => {
|
||||
await refused([{ name: 'cv.pdf', data: EXE }], /"cv\.pdf" is not an accepted file type\. Accepted: PDF, DOC, DOCX\./)
|
||||
await refused([{ name: 'cv.docx', data: PDF }], /not an accepted file type/)
|
||||
await refused([{ name: 'cv.pdf', data: Buffer.alloc(0) }], /not an accepted file type|too large/)
|
||||
})
|
||||
|
||||
test('unsupported and dangerous names: other type, program, double extension, archive, macro-enabled Office', async () => {
|
||||
await refused([{ name: 'photo.png', data: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }], /not an accepted file type/)
|
||||
await refused([{ name: 'cv.exe', data: EXE }], /not an accepted file type/)
|
||||
await refused([{ name: 'cv.pdf.exe', data: EXE }], /not an accepted file type/)
|
||||
await refused([{ name: 'cv.exe.pdf', data: PDF }], /not an accepted file type/)
|
||||
await refused([{ name: 'cv.pdf.docx', data: DOCX }], /not an accepted file type/)
|
||||
await refused([{ name: 'cv.zip', data: ARCHIVE }], /not an accepted file type/)
|
||||
await refused([{ name: 'cv.docm', data: DOCX_MACRO }], /not an accepted file type/)
|
||||
})
|
||||
|
||||
test('the right container with macros inside: DOCX with a macro project, DOC with a macro storage', async () => {
|
||||
await refused([{ name: 'cv.docx', data: DOCX_MACRO }], /not an accepted file type/)
|
||||
await refused([{ name: 'cv.doc', data: DOC_MACRO }], /not an accepted file type/)
|
||||
await refused([{ name: 'cv.docx', data: ARCHIVE }], /not an accepted file type/) // a ZIP that is not a Word file
|
||||
})
|
||||
|
||||
test('extra files: more than the field allows, a file under a key that is no File field', async () => {
|
||||
await refused([{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }], /Attach at most 1 files in "Attachment \(optional\)"\./)
|
||||
const before = await count()
|
||||
const { body } = await post({ files: [{ name: 'a.pdf', data: PDF, field: 'name' }], values: { consent: true, email: '[email protected]' } })
|
||||
expect(body.success).toBe(false)
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
})
|
||||
|
||||
test('direct calls that skip the form: text under the File key, a stringified File, a media id', async () => {
|
||||
const before = await count()
|
||||
for (const attachment of ['[object File]', '65f0c0ffee', { id: 1 }]) {
|
||||
const result = await submitForm({ data: { ...answers, attachment }, formId, ip: '10.8.0.9', maxPerMinute: 0, payload })
|
||||
expect(result).toMatchObject({ field: 'attachment', reason: 'validation', success: false })
|
||||
}
|
||||
expect(await count()).toBe(before)
|
||||
})
|
||||
|
||||
test('the antivirus hook can refuse a file that passed everything else', async () => {
|
||||
scanVerdict = false
|
||||
await refused([{ name: 'cv.pdf', data: PDF }], /not an accepted file type/)
|
||||
expect(scanned).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('a body that declares itself too large is refused unread', async () => {
|
||||
const before = await count()
|
||||
const request = new Request('http://localhost/api/ipal/forms/submit?locale=en', {
|
||||
body: 'x',
|
||||
headers: { 'content-length': String(50 * MB), 'content-type': 'multipart/form-data; boundary=x', 'sec-fetch-site': 'same-origin', 'x-real-ip': '10.8.1.1' },
|
||||
method: 'POST',
|
||||
})
|
||||
const response = await handleFormSubmit(Object.assign(request, { payload }) as unknown as PayloadRequest)
|
||||
expect(response.status).toBe(413)
|
||||
expect(await count()).toBe(before)
|
||||
})
|
||||
})
|
||||
|
||||
describe('4 · no gate can be bypassed by attaching a file', () => {
|
||||
const blocked = async (extra: Post, status: number, reason: string | undefined) => {
|
||||
const before = await count()
|
||||
const result = await post({ files: [{ name: 'cv.pdf', data: PDF }], ...extra })
|
||||
expect(result.status).toBe(status)
|
||||
expect(result.body.reason).toBe(reason)
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
expect(scanned).toEqual([]) // the file was never taken in
|
||||
return result
|
||||
}
|
||||
|
||||
test('missing consent', async () => {
|
||||
const { body } = await blocked({ values: { ...answers, consent: false } }, 422, 'consent')
|
||||
expect(body.message).toMatch(/privacy policy/)
|
||||
})
|
||||
|
||||
test('a required field left empty', async () => {
|
||||
await blocked({ values: { consent: true, email: '[email protected]' } }, 422, 'validation')
|
||||
})
|
||||
|
||||
test('Turnstile configured: no token, and a token Cloudflare rejects', async () => {
|
||||
process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY = 'site-key'
|
||||
process.env.TURNSTILE_SECRET_KEY = 'secret-key'
|
||||
vi.stubGlobal('fetch', vi.fn(async () => Response.json({ 'error-codes': ['invalid-input-response'], success: false })))
|
||||
await blocked({}, 403, 'turnstile')
|
||||
await blocked({ token: 'forged' }, 403, 'turnstile')
|
||||
})
|
||||
|
||||
test('a tripped honeypot: a fake success, nothing stored, nothing sent', async () => {
|
||||
const before = await count()
|
||||
const { body, status } = await post({ files: [{ name: 'cv.pdf', data: PDF }], values: { ...answers, company_url: 'http://spam.example' } })
|
||||
expect({ status, success: body.success }).toEqual({ status: 200, success: true })
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
expect(scanned).toEqual([])
|
||||
})
|
||||
|
||||
test('rate limit: the sixth request in a minute from one address is refused before its body is read', async () => {
|
||||
const ip = '10.8.2.2'
|
||||
for (let i = 0; i < 5; i++) {await post({ ip, values: { ...answers, consent: false } })}
|
||||
await blocked({ ip }, 429, 'rate_limited')
|
||||
})
|
||||
|
||||
test('another site cannot post to the endpoint; REST cannot create a submission', async () => {
|
||||
await blocked({ headers: { origin: 'https://evil.example', 'sec-fetch-site': 'cross-site' } }, 403, 'error')
|
||||
await expect(
|
||||
payload.create({ collection: 'form-submissions' as never, data: { form: formId, submissionData: [] } as never, overrideAccess: false }),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
test('a file sent before the answers is not accepted', async () => {
|
||||
const before = await count()
|
||||
const body = new FormData()
|
||||
body.append('attachment', new File([new Uint8Array(PDF)], 'cv.pdf'))
|
||||
body.append('_form', formId)
|
||||
body.append('_values', JSON.stringify(answers))
|
||||
const request = new Request('http://localhost/api/ipal/forms/submit?locale=en', { body, headers: { 'sec-fetch-site': 'same-origin', 'x-real-ip': '10.8.2.9' }, method: 'POST' })
|
||||
const response = await handleFormSubmit(Object.assign(request, { payload }) as unknown as PayloadRequest)
|
||||
expect(response.status).toBeGreaterThanOrEqual(400)
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('5 · nothing is stored, nothing can be downloaded', () => {
|
||||
test('no upload collection, no file on disk, no route that serves a file', async () => {
|
||||
await post({ files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(withFile()).toHaveLength(1)
|
||||
|
||||
// The only upload collection is the project's own Media, and it is empty.
|
||||
const uploads = payload.config.collections.filter((c) => c.upload).map((c) => c.slug)
|
||||
expect(uploads).toEqual(['media'])
|
||||
expect((await payload.count({ collection: 'media' as never })).totalDocs).toBe(0)
|
||||
let onDisk: string[] = []
|
||||
try {
|
||||
onDisk = readdirSync(mediaDir)
|
||||
} catch {
|
||||
/* the directory was never created */
|
||||
}
|
||||
expect(onDisk).toEqual([])
|
||||
|
||||
// The submission has no upload relation — form-builder's own upload storage stays off.
|
||||
const fields = payload.collections['form-submissions' as never].config.fields.map((f) => ('name' in f ? f.name : ''))
|
||||
expect(fields).not.toContain('submissionUploads')
|
||||
// One endpoint, POST only.
|
||||
const mine = (payload.config.endpoints ?? []).filter((e) => e.path.includes('forms'))
|
||||
expect(mine.map((e) => `${e.method} ${e.path}`)).toEqual(['post /ipal/forms/submit'])
|
||||
})
|
||||
|
||||
test('the option is opt-in: without it the config has no File block, no endpoint, no extra fields', async () => {
|
||||
const plain = await buildTestConfig({
|
||||
collections: [{ slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' } }),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false })],
|
||||
secret: 'x',
|
||||
})
|
||||
const forms = plain.collections.find((c) => c.slug === 'forms')!
|
||||
const blocks = (forms.fields.find((f) => 'name' in f && f.name === 'fields') as { blocks: { slug: string }[] }).blocks.map((b) => b.slug)
|
||||
expect(blocks).not.toContain('file')
|
||||
expect((plain.endpoints ?? []).some((e) => e.path.includes('forms/submit'))).toBe(false)
|
||||
const submissionFields = plain.collections.find((c) => c.slug === 'form-submissions')!.fields.map((f) => ('name' in f ? f.name : ''))
|
||||
expect(submissionFields.filter((name) => /file|attempt/i.test(name))).toEqual([])
|
||||
expect((plain.custom as { ipal?: { formAttachments?: unknown } } | undefined)?.ipal?.formAttachments).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('6 · failed send, retry, repeated request', () => {
|
||||
test('the mail server refuses the message: the visitor is told, staff get a notice, the attempt is marked', async () => {
|
||||
mailMode = 'refuse'
|
||||
const before = await count()
|
||||
const { body, status } = await post({ files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(status).toBe(502)
|
||||
expect(body).toMatchObject({ message: 'We could not send your file. Try again, or send it by e-mail.', reason: 'delivery', success: false })
|
||||
|
||||
const stored = (await submissions()).at(-1)!
|
||||
expect(await count()).toBe(before + 1)
|
||||
expect(stored.filesDelivery).toBe('failed')
|
||||
expect(stored.filesDeliveryNote).toContain('552')
|
||||
expect(stored.submissionFiles).toHaveLength(1)
|
||||
|
||||
// One attempt with the file, then the notice without it. No confirmation to the visitor.
|
||||
expect(mails.map((m) => [m.to, m.attachments?.length ?? 0])).toEqual([['[email protected]', 1], ['[email protected]', 0]])
|
||||
expect(mails[1].html).toContain('could not be sent')
|
||||
expect(mails[1].html).not.toContain('viruses')
|
||||
|
||||
// The retry is a new attempt and goes through once.
|
||||
mails.length = 0
|
||||
mailMode = 'ok'
|
||||
const retry = await post({ files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(retry.body.success).toBe(true)
|
||||
expect(await count()).toBe(before + 2)
|
||||
expect(withFile()).toHaveLength(1)
|
||||
expect(mails.filter((m) => m.to === '[email protected]')).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('an adapter that throws is a failed send too', async () => {
|
||||
mailMode = 'throw'
|
||||
const { body } = await post({ files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(body.reason).toBe('delivery')
|
||||
expect((await submissions()).at(-1)!.filesDelivery).toBe('failed')
|
||||
})
|
||||
|
||||
test('the same attempt key again: the first answer, no second submission, no second e-mail', async () => {
|
||||
const before = await count()
|
||||
const attempt = 'attempt-0123456789abcdef'
|
||||
const first = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(first.body.success).toBe(true)
|
||||
const sent = mails.length
|
||||
const again = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(again.body).toEqual(first.body)
|
||||
expect(await count()).toBe(before + 1)
|
||||
expect(mails).toHaveLength(sent)
|
||||
expect(scanned).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('two identical requests at the same moment: one submission, one e-mail with the file', async () => {
|
||||
const before = await count()
|
||||
const attempt = 'attempt-concurrent-000001'
|
||||
const [a, b] = await Promise.all([
|
||||
post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }),
|
||||
post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }),
|
||||
])
|
||||
expect(a.body.success && b.body.success).toBe(true)
|
||||
expect(await count()).toBe(before + 1)
|
||||
expect(withFile()).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('a failed attempt repeated with its key stays failed and sends nothing more', async () => {
|
||||
mailMode = 'refuse'
|
||||
const attempt = 'attempt-failed-0000000001'
|
||||
await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
const before = await count()
|
||||
mails.length = 0
|
||||
mailMode = 'ok'
|
||||
const again = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(again.body.reason).toBe('delivery')
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('7 · languages, the panel, limits', () => {
|
||||
test('messages follow the page language: Polish and English defaults, German and Dutch from the panel', async () => {
|
||||
await payload.updateGlobal({ slug: 'notifications' as never, data: { form: { fileTooLarge: 'Die Datei „{file}“ ist zu groß. Maximal {max} MB.' } } as never, locale: 'de' })
|
||||
await payload.updateGlobal({ slug: 'notifications' as never, data: { form: { fileTooLarge: 'Het bestand "{file}" is te groot. Maximaal {max} MB.' } } as never, locale: 'nl' })
|
||||
const big = [{ name: 'big.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 10) }]
|
||||
expect((await post({ files: big, locale: 'pl' })).body.message).toBe('Plik „big.pdf” jest za duży. Limit to 1 MB.')
|
||||
expect((await post({ files: big, locale: 'en' })).body.message).toBe('"big.pdf" is too large. The limit is 1 MB.')
|
||||
expect((await post({ files: big, locale: 'de' })).body.message).toBe('Die Datei „big.pdf“ ist zu groß. Maximal 1 MB.')
|
||||
expect((await post({ files: big, locale: 'nl' })).body.message).toBe('Het bestand "big.pdf" is te groot. Maximaal 1 MB.')
|
||||
// The field's label comes from the panel in the page language.
|
||||
const two = [{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }]
|
||||
expect((await post({ files: two, locale: 'pl' })).body.message).toBe('W polu „Załącznik (opcjonalnie)” można dodać najwyżej 1 plików.')
|
||||
})
|
||||
|
||||
test('the form the browser gets carries the limits that really apply, and where to post', async () => {
|
||||
const form = (await payload.findByID({ id: formId, collection: 'forms' as never, depth: 0, locale: 'en' })) as unknown as {
|
||||
fields: { blockType: string; help?: string; resolved?: Record<string, unknown> }[]
|
||||
fileSubmitUrl?: string
|
||||
}
|
||||
const field = form.fields.find((f) => f.blockType === 'file')!
|
||||
expect(field.help).toBe('PDF, DOC or DOCX, up to 1 MB')
|
||||
expect(field.resolved).toMatchObject({ extensions: ['pdf', 'doc', 'docx'], maxFiles: 1, maxSizeMB: 1, typeLabels: 'PDF, DOC, DOCX' })
|
||||
expect(String(field.resolved?.accept)).toContain('.pdf')
|
||||
expect(form.fileSubmitUrl).toBe('/api/ipal/forms/submit')
|
||||
})
|
||||
|
||||
test('the panel: the File block, its caps, and a form with a File field needs a fixed-recipient e-mail', async () => {
|
||||
const options = getFormAttachments(payload)!
|
||||
expect(options).toMatchObject({ maxFiles: 3, maxSizeMB: 1, maxTotalMB: 1 })
|
||||
const block = (payload.collections['forms' as never].config.fields.find((f) => 'name' in f && f.name === 'fields') as { blocks: { fields: unknown[]; slug: string }[] }).blocks.find((b) => b.slug === 'file')!
|
||||
expect(JSON.stringify(block.fields)).toContain('Dozwolone typy plików')
|
||||
|
||||
const fields = [{ name: 'cv', allowedTypes: ['pdf'], blockType: 'file', label: 'CV' }]
|
||||
const confirmationMessage = text('ok')
|
||||
const refusal = await payload
|
||||
.create({ collection: 'forms' as never, data: { confirmationMessage, emails: [{ emailTo: '{{email}}', message: text('x'), subject: 'x' }], fields, title: 'No staff e-mail' } as never })
|
||||
.then(() => null, (err: { data?: { errors?: { message: string; path: string }[] } }) => err.data?.errors?.[0])
|
||||
expect(refusal).toMatchObject({ path: 'emails' })
|
||||
expect(refusal?.message).toMatch(/fixed recipient|stałym adresem/)
|
||||
await expect(payload.create({ collection: 'forms' as never, data: { confirmationMessage, fields, title: 'No e-mail at all' } as never })).rejects.toThrow()
|
||||
// A size over the cap is refused by the field itself.
|
||||
await expect(
|
||||
payload.create({ collection: 'forms' as never, data: { confirmationMessage, emails: [{ emailTo: '[email protected]', message: text('x'), subject: 'x' }], fields: [{ ...fields[0], maxSizeMB: 50 }], title: 'Too big' } as never }),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
test('a required File field: the submission without a file is refused', async () => {
|
||||
const required = await payload.create({
|
||||
collection: 'forms' as never,
|
||||
data: {
|
||||
confirmationMessage: text('ok'),
|
||||
emails: [{ emailFrom: '[email protected]', emailTo: '[email protected]', message: text('x'), subject: 'x' }],
|
||||
fields: [{ name: 'cv', allowedTypes: ['pdf'], blockType: 'file', label: 'CV', required: true }],
|
||||
title: 'Required file',
|
||||
} as never,
|
||||
locale: 'en',
|
||||
})
|
||||
const before = await count()
|
||||
const none = await post({ form: String(required.id), values: {} })
|
||||
expect(none.body).toMatchObject({ field: 'cv', reason: 'validation', success: false })
|
||||
expect(await submitForm({ data: {}, formId: String(required.id), maxPerMinute: 0, payload })).toMatchObject({ field: 'cv', kind: 'required' })
|
||||
expect(await count()).toBe(before)
|
||||
const ok = await post({ files: [{ name: 'cv.pdf', data: PDF, field: 'cv' }], form: String(required.id), values: {} })
|
||||
expect(ok.body.success).toBe(true)
|
||||
})
|
||||
|
||||
test('submitForm({ files }) — a project\'s own transfer path gets the same checks and the same delivery', async () => {
|
||||
const good = await submitForm({ data: answers, files: { attachment: [{ name: 'cv.pdf', data: PDF }] }, formId, locale: 'en', maxPerMinute: 0, payload })
|
||||
expect(good.success).toBe(true)
|
||||
expect(withFile()).toHaveLength(1)
|
||||
expect(await submitForm({ data: answers, files: { attachment: [{ name: 'cv.pdf', data: EXE }] }, formId, maxPerMinute: 0, payload })).toMatchObject({ kind: 'file_type' })
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user