M1 review round 2: the transport is no way round, nobody raises its own role, late staff collections

R2-1 the SMTP password is bound to server, port and user whatever the transport says; the transport alone is not bound.
R2-2 where the plugin's update rule is in force the roles field is closed for the account itself
     (the plugin's roles: only an admin; roles of the project's own: never one's own).
R2-3 auth collections a later plugin adds get the account rules, the password rule and the first-user endpoint when
     the config goes live; a staff slug that is not an auth collection stops the start.
R2-4 smtpRequireTls is taken out: the branch adds no field, column or collection.
Also: read (a staff account) and unlock (an admin) defaults on staff collections (accounts.staffOnlyRead);
doctor staff-own-roles and read / unlock in staff-accounts-open; r1 NULL against the default, also inside a row;
r2 bound values compared exactly.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 00:39:24 +01:00
co-authored by Claude Fable 5.2
parent a32329fbb4
commit 7002ebbfa6
20 changed files with 519 additions and 122 deletions
+27
View File
@@ -82,6 +82,20 @@ test('the first account registers; accounts of the collection create, change and
expect((await call(`/users/${third}`, boss, 'DELETE')).status).toBe(200)
})
// Review round 2 (R2-2): the plugin cannot rank the project's roles, but one thing it can hold: nobody changes its OWN.
test('an account does not change its own roles; another account of the collection does (the project\'s rules narrow that)', async () => {
const writer = await login('users', '[email protected]')
const id = await idOf('users', '[email protected]')
const roles = async () => ((await payload.findByID({ id: id as never, collection: 'users' as never })) as { roles?: string[] }).roles
await call(`/users/${id}`, writer, 'PATCH', { roles: ['superadmin'] })
await call('/users?where[email][equals][email protected]', writer, 'PATCH', { roles: ['superadmin'] })
expect(await roles()).toEqual(['writer'])
const boss = await login('users', '[email protected]')
expect((await call(`/users/${id}`, boss, 'PATCH', { roles: ['superadmin'] })).status).toBe(200)
expect(await roles()).toEqual(['superadmin'])
await payload.update({ id: id as never, collection: 'users' as never, data: { roles: ['writer'] } as never })
})
test('an account of another collection, a half-signed-in one and nobody stay out', async () => {
expect((await call('/customers', {}, 'POST', { email: '[email protected]', password: PASSWORD })).status).toBe(201)
const visitor = await login('customers', '[email protected]')
@@ -96,3 +110,16 @@ test('an account of another collection, a half-signed-in one and nobody stay out
expect((await call('/users/login', {}, 'POST', { email: '[email protected]', password: 'taken-over-password-1' })).status).not.toBe(200)
expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([])
})
test('a staff collection that does not exist stops the start, with the slug and the fix', async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('accounts_ghost'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['ghost-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
await expect(getPayload({ config, key: 'ghost' })).rejects.toThrow(/"ghost-staff"[\s\S]*no auth collection with that slug[\s\S]*staffCollections/)
})
+144 -8
View File
@@ -5,7 +5,7 @@
* (accountRules2fa.test.ts) — the 2FA package rewrites every collection's access, and a rule that
* holds without it may not hold with it.
*/
import type { Config, Payload } from 'payload'
import type { Config, Payload, Plugin } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
@@ -19,7 +19,7 @@ import type { I18nConfig } from '../src/modules/i18n/types.js'
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
import { hasPluginRoles, openSignUpCollections, sameStaffCollectionAccess, staffCollectionsOpenToOthers, staffCreateAccess, staffUpdateAccess } from '../src/modules/access/selfRegistration.js'
import { adoptLateAuthCollections, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig, withTotpParts } from './helpers.js'
import { testDatabase } from './http/db.js'
@@ -28,6 +28,16 @@ import { totp } from './http/totp.js'
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
/** A plugin the project lists AFTER ipalKit: its auth collections did not exist when ipalKit ran (review round 2, R2-3). */
const latePlugin: Plugin = (config: Config) => ({
...config,
collections: [
...(config.collections ?? []),
{ slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }] },
{ slug: 'late-members', auth: true, fields: [] },
],
})
/** The whole suite; `twoFactor` = run it with the 2FA package on. */
export function accountRulesSuite(twoFactor: boolean): void {
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
@@ -85,7 +95,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
],
db: testDatabase(twoFactor ? 'accounts_2fa' : 'accounts'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2', 'crew', 'agents'] }, i18n, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false })],
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2', 'crew', 'agents', 'late-staff'] }, i18n, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), latePlugin],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
@@ -124,7 +134,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
test('…in every spelling Payload\'s router accepts or might: letter case, slashes, encoding, query', async () => {
// the first cut read the path and missed /First-Register: an anonymous visitor became a staff admin
const spellings = ['/first-register', '/first-register/', '/First-Register', '/FIRST-REGISTER', '/fIrSt-ReGiStEr', '/first-registe%72', '//first-register', '/first-register?x=1', '/first-register;x', '/First-Register/?x=1']
for (const collection of ['staff2', 'crew', 'agents', 'members']) {
for (const collection of ['staff2', 'crew', 'agents', 'members', 'late-staff', 'late-members']) {
for (const spelling of spellings) {
const res = await post(`/${collection}${spelling}`, { email: `sp-${Math.random().toString(36).slice(2)}@example.com`, password: PASSWORD, roles: ['admin'] })
expect([collection, spelling, res.status === 200 || res.status === 201]).toEqual([collection, spelling, false])
@@ -263,7 +273,76 @@ export function accountRulesSuite(twoFactor: boolean): void {
}
})
// Review round 2 (R2-2): the default "the account itself may update" must not reach the roles.
test('nobody raises its own role: a lowest-role account of a second staff collection stays what it is', async () => {
await make('agents', { email: '[email protected]', roles: ['user'] })
const low = await login('agents', '[email protected]')
const id = await idOf('agents', '[email protected]')
const rolesOf = async (collection: string, of: unknown) => ((await payload.findByID({ id: of as never, collection: collection as never })) as { roles?: string[] }).roles
for (const body of [{ roles: ['admin'] }, { roles: 'admin' }, { password: 'another-long-password-1', roles: ['admin', 'user'] }]) {
await patch(`/agents/${id}`, body, low)
expect(await rolesOf('agents', id)).toEqual(['user'])
}
await patch('/agents?where[email][equals][email protected]', { roles: ['admin'] }, low) // bulk
expect(await rolesOf('agents', id)).toEqual(['user'])
const gql = await post('/graphql', { query: `mutation { updateAgent(id: ${typeof id === 'number' ? id : `"${id}"`}, data: { roles: [admin] }) { id } }` }, low)
await gql.text()
expect(await rolesOf('agents', id)).toEqual(['user'])
// the rest of its own account is its own (the password above was changed)
expect(await canLogIn('agents', '[email protected]', 'another-long-password-1')).toBe(true)
// and it opens nothing an admin opens
expect((await call('/globals/site-integrations', low)).status).toBe(403)
// an admin gives roles
expect((await patch(`/agents/${id}`, { roles: ['editor'] }, admin)).status).toBe(200)
expect(await rolesOf('agents', id)).toEqual(['editor'])
// role values of the project's own: the plugin cannot rank them, but an account still never changes its own
const worker = await login('crew', '[email protected]')
const workerId = await idOf('crew', '[email protected]')
await patch(`/crew/${workerId}`, { roles: ['boss'] }, worker)
await patch('/crew?where[email][equals][email protected]', { roles: ['boss'] }, worker)
expect(await rolesOf('crew', workerId)).toEqual(['worker'])
// somebody else of the collection does (what the project's own rules must narrow — said by the doctor)
const boss = await login('crew', '[email protected]')
expect((await patch(`/crew/${workerId}`, { roles: ['boss'] }, boss)).status).toBe(200)
expect(await rolesOf('crew', workerId)).toEqual(['boss'])
await payload.update({ id: workerId as never, collection: 'crew' as never, data: { roles: ['worker'] } as never })
})
// Payload's defaults for `read` and `unlock` are "any logged-in user" too.
test('a visitor account does not list staff accounts or unlock them; staff does (accounts.staffOnlyRead)', async () => {
for (const collection of ['agents', 'staff2', 'crew', 'late-staff']) {
for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
expect([collection, who, (await call(`/${collection}`, session)).status]).toEqual([collection, who, 403])
expect([collection, who, (await post(`/${collection}/unlock`, { email: '[email protected]' }, session)).status]).toEqual([collection, who, 403])
}
expect([collection, (await call(`/${collection}`, editor)).status]).toEqual([collection, 200]) // staff reads staff
}
const gql = (await (await post('/graphql', { query: '{ Agents { docs { email } } }' }, visitor)).json()) as { data?: unknown; errors?: unknown[] }
expect(JSON.stringify(gql)).not.toContain('[email protected]')
expect((await post('/agents/unlock', { email: '[email protected]' }, editor)).status).toBe(403)
expect((await post('/agents/unlock', { email: '[email protected]' }, admin)).status).toBe(200)
})
// Review round 2 (R2-3): a staff collection a later plugin adds.
test('a staff collection added by a plugin listed after ipalKit has the same rules', async () => {
expect((await payload.count({ collection: 'late-staff' as never })).totalDocs).toBe(0) // the first-user spellings above created nothing
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, visitor)).status).toBe(403)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, editor)).status).toBe(403)
// the password rule is there too
expect((await post('/late-staff', { email: '[email protected]', password: 'tooshort', roles: ['user'] }, admin)).status).toBe(400)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['user'] }, admin)).status).toBe(201)
const id = await idOf('late-staff', '[email protected]')
expect((await patch(`/late-staff/${id}`, { password: NEW }, visitor)).status).toBe(403)
expect((await remove(`/late-staff/${id}`, visitor)).status).toBe(403)
const one = await login('late-staff', '[email protected]')
await patch(`/late-staff/${id}`, { roles: ['admin'] }, one)
expect(((await payload.findByID({ id: id as never, collection: 'late-staff' as never })) as { roles?: string[] }).roles).toEqual(['user'])
expect((await patch(`/late-staff/${id}`, { roles: ['editor'] }, admin)).status).toBe(200)
})
test('the doctor\'s check: no staff collection is open to an account of another collection', async () => {
expect(staffCollectionsOnOwnRoles(payload as never)).toEqual(['crew']) // `staff2` has no roles field: nothing to rank
expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([])
expect(await openSignUpCollections(payload as never)).toEqual(['customers'])
})
@@ -508,7 +587,8 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([1, 1, 0, 0])
expect([firstUser(on, 'users'), firstUser(on, 'staff2'), firstUser(on, 'customers'), firstUser(on, 'pages')]).toEqual([1, 1, 1, 0])
const payloadWay = await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false } })
expect(of(payloadWay, 'staff2').access).toBeUndefined()
expect(of(payloadWay, 'staff2').access).toEqual({ read: staffReadAccess })
expect(of(await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false, staffOnlyRead: false } }), 'staff2').access).toBeUndefined()
expect([guards(payloadWay, 'staff2'), firstUser(payloadWay, 'staff2')]).toEqual([0, 0])
// each switch on its own
const createOnly = await build({ accounts: { adminOnlyWrite: false } })
@@ -530,6 +610,62 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(of(noAccess, 'users').access?.create).not.toBe(staffCreateAccess)
})
test('the roles field: protected where the plugin\'s update rule is in force and the field has no access of its own', async () => {
const rolesField = (config: Config, slug: string) => of(config, slug).fields.find((f) => 'name' in f && f.name === 'roles') as { access?: { update?: unknown } }
const own = { name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] }
const collections = (extra: object = {}, field: object = own) => ({ collections: [{ slug: 'staff2', auth: true, fields: [{ type: 'row', fields: [field] }], ...extra }] }) as never
const inRow = (config: Config) => (of(config, 'staff2').fields[0] as unknown as { fields: { access?: { update?: unknown } }[] }).fields[0]
// the plugin's roles: only an admin; found inside a row too; the project's own field object is not changed
expect(inRow(await build({}, collections())).access?.update).toBe(rolesByAdminOnly)
expect((own as { access?: unknown }).access).toBeUndefined()
// roles of the project's own: never the account itself
const mine = inRow(await build({}, collections({}, { ...own, options: ['boss', 'worker'] }))).access?.update as (a: unknown) => boolean
expect(mine({ id: 5, req: { user: { id: 5, collection: 'staff2' } } })).toBe(false)
expect(mine({ id: '5', req: { user: { id: 5, collection: 'staff2' } } })).toBe(false)
expect(mine({ id: 6, req: { user: { id: 5, collection: 'staff2' } } })).toBe(true)
expect(mine({ id: 5, req: { user: { id: 5, collection: 'users' } } })).toBe(true) // id 5 of another collection is somebody else
expect(rolesNotOwn('x')({ id: undefined, req: { user: { id: 5, collection: 'x' } } } as never)).toBe(true) // a create
// left alone: a field with its own rule, a collection with its own update rule, the switch
const fieldRule = () => true
expect(inRow(await build({}, collections({}, { ...own, access: { update: fieldRule } }))).access?.update).toBe(fieldRule)
expect(inRow(await build({}, collections({ access: { update: () => true } }))).access).toBeUndefined()
expect(inRow(await build({ accounts: { adminOnlyWrite: false } }, collections())).access).toBeUndefined()
// the injected collection's field has the plugin's own access already
expect(rolesField(await build({}), 'users').access?.update).toBeTypeOf('function')
})
test('late collections: adopted once, with the same rules; a project\'s own rule and Payload\'s default told apart', () => {
function defaultAccess({ req }: { req: { user: unknown } }) {return Boolean(req.user)} // what a sanitized config holds where nothing was written
const mine = () => true
const hook = () => undefined
const late = { slug: 'late', access: { create: defaultAccess, delete: mine, read: defaultAccess, unlock: defaultAccess, update: defaultAccess }, auth: true, endpoints: [{ handler: () => undefined, method: 'post', path: '/first-register' }], fields: [{ name: 'roles', type: 'select', options: ['user', 'admin'] }] }
const seen = { slug: 'users', access: { create: defaultAccess }, auth: true, custom: { ipalAccounts: true }, endpoints: [], fields: [] }
const visitors = { slug: 'visitors', access: { create: defaultAccess }, auth: true, endpoints: [], fields: [] }
const pages = { slug: 'pages', access: {}, endpoints: [], fields: [] }
const live = { collections: { late: { config: late }, pages: { config: pages }, users: { config: seen }, visitors: { config: visitors } } } as never
expect(adoptLateAuthCollections(live, ['users', 'late'], { beforeOperation: hook })).toEqual(['late', 'visitors'])
expect(late.access.create).toBe(staffCreateAccess)
expect(late.access.delete).toBe(mine)
expect(late.access.read).toBe(staffReadAccess)
expect(late.access.unlock).toBe(staffCreateAccess)
expect((late.fields[0] as { access?: { update?: unknown } }).access?.update).toBe(rolesByAdminOnly)
expect((late as { hooks?: { beforeOperation?: unknown[] } }).hooks?.beforeOperation).toEqual([hook])
expect((late.endpoints[0] as { custom?: { ipalFirstUser?: boolean } }).custom?.ipalFirstUser).toBe(true) // in FRONT of Payload's
expect(late.endpoints).toHaveLength(2)
// a late auth collection that is not staff: the first-user endpoint only
expect(visitors.access.create).toBe(defaultAccess)
expect(visitors.endpoints).toHaveLength(1)
// what ipalKit saw at config time, and what is not an auth collection: untouched
expect(seen.access.create).toBe(defaultAccess)
expect(seen.endpoints).toHaveLength(0)
expect(pages.endpoints).toHaveLength(0)
// a second call (a request after the start) changes nothing
expect(adoptLateAuthCollections(live, ['users', 'late'], { beforeOperation: hook })).toEqual([])
expect(late.endpoints).toHaveLength(2)
// a staff slug without an auth collection
expect(unknownStaffCollections(live, ['users', 'late', 'pages', 'ghost'])).toEqual(['pages', 'ghost'])
})
test('the rules are on the collections BEFORE the 2FA package wraps them', async () => {
// the package gives every collection a create / update / delete of its own; afterwards "no rule" cannot be seen
const seen: Record<string, unknown> = {}
@@ -538,7 +674,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
return withTotpParts({ ...c, collections: (c.collections ?? []).map((col) => ({ ...col, access: { create: () => true, delete: () => true, update: () => true, ...col.access } })) }, o.collection)
}
await build({ twoFactor: { issuer: 'A', plugin: factory as never } })
expect(Object.keys(seen.staff2 as object).sort()).toEqual(['create', 'delete', 'update'])
expect(Object.keys(seen.staff2 as object).sort()).toEqual(['create', 'delete', 'read', 'unlock', 'update'])
expect(seen.customers).toEqual({ create: expect.any(Function) })
})
@@ -571,10 +707,10 @@ export function accountRulesSuite(twoFactor: boolean): void {
const collections = {
agents: { config: { slug: 'agents', access: { create: staffCreateAccess, delete: anyone, update: anyone }, auth: true } },
customers: { config: { slug: 'customers', access: { create: () => true, update: anyone }, auth: true } }, // not staff: not its business
users: { config: { slug: 'users', access: { create: staffCreateAccess, delete: staffCreateAccess, update: staffUpdateAccess('users') }, auth: true } },
users: { config: { slug: 'users', access: { create: staffCreateAccess, delete: staffCreateAccess, read: staffReadAccess, unlock: staffCreateAccess, update: staffUpdateAccess('users') }, auth: true } },
weird: { config: { slug: 'weird', access: { update: () => { throw new Error('x') } }, auth: true } },
}
expect(await staffCollectionsOpenToOthers({ collections, config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['agents', 'weird'] } } } } as never)).toEqual(['agents:delete', 'agents:update', 'weird:create', 'weird:delete']) // no rule = Payload's default, open; a rule that throws = closed
expect(await staffCollectionsOpenToOthers({ collections, config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['agents', 'weird'] } } } } as never)).toEqual(['agents:delete', 'agents:read', 'agents:unlock', 'agents:update', 'weird:create', 'weird:delete', 'weird:read', 'weird:unlock']) // no rule = Payload's default, open; a rule that throws = closed
})
})
}
+5 -1
View File
@@ -206,6 +206,10 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
test('staff-accounts-open: a staff collection an account of another collection may write to is an error', async () => {
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:delete', 'agents:update', 'users:create'] })).toEqual(['staff-accounts-open:error', 'staff-accounts-open:error', 'staff-accounts-open:error'])
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:read', 'agents:unlock'] })).toEqual(expect.arrayContaining(['staff-accounts-open:warning', 'staff-accounts-open:error']))
expect(await run(cfg, ['staff-own-roles'], { staffOnOwnRoles: ['crew'] })).toEqual(['staff-own-roles:warning'])
expect(await run(cfg, ['staff-own-roles'], { staffOnOwnRoles: [] })).toEqual([])
expect(await run(cfg, ['staff-own-roles'])).toEqual([])
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: [] })).toEqual([])
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: null })).toEqual([])
expect(await run(cfg, ['staff-accounts-open'])).toEqual([])
@@ -511,7 +515,7 @@ describe('security and deep status', () => {
}
const status = await collectDoctorStatus(payload as never)
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
expect(Object.keys(status).sort()).toEqual(['node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(Object.keys(status).sort()).toEqual(['node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
})
test('collectDoctorStatus counts the accounts whose 2FA setup window has passed', async () => {
+2 -1
View File
@@ -512,8 +512,9 @@ describe('ipalKit and the 2FA plugin', () => {
admin: { user: 'users' },
} as Config)
const warnings: string[] = []
const auth = (slug: string) => ({ config: { slug, auth: true, custom: { ipalAccounts: true }, fields: [] } })
const payload = {
collections: {},
collections: { partners: auth('partners'), users: auth('users') },
config: { admin: { user: 'users' }, collections: [], custom: config.custom, globals: [] },
count: () => ({ totalDocs: 0 }),
find: () => ({ docs: [] }),
+44 -30
View File
@@ -33,7 +33,7 @@ let auth: Record<string, string>
const stored = async () => (await payload.findGlobal({ slug: 'site-integrations' as never })) as unknown as Record<string, unknown>
const api = (pathname: string, init: RequestInit = {}, headers: Record<string, string> = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...auth, ...headers } })
const save = (data: Record<string, unknown>, headers: Record<string, string> = {}) => api(G, { body: JSON.stringify(data), method: 'POST' }, headers)
const reset = () => payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpRequireTls: false, smtpUser: 'mailer' } as never })
const reset = () => payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpUser: 'mailer' } as never })
/** An SMTP server that offers no STARTTLS and writes down what a client logs in with. */
const fakeSmtp = async () => {
@@ -127,7 +127,10 @@ describe('the SMTP password stays with the server it was saved for (secrets.reen
['the server', { smtpHost: 'other.example.com' }],
['the port', { smtpPort: 2525 }],
['the user name', { smtpUser: 'someone-else' }],
['"require an encrypted connection"', { smtpRequireTls: true }],
['the server to another letter case', { smtpHost: 'SMTP.example.com' }],
['the server by a space', { smtpHost: 'smtp.example.com ' }],
['the server while naming Microsoft Graph as the transport', { emailTransport: 'graph', smtpHost: 'other.example.com' }],
['the port while naming Microsoft Graph as the transport', { emailTransport: 'graph', smtpPort: 2525 }],
['the server, sending the mask back as the panel does', { smtpHost: 'other.example.com', smtpPassword: SECRET_MASK }],
['the server, with an empty password', { smtpHost: 'other.example.com', smtpPassword: '' }],
['the server, in a draft', { _status: 'draft', smtpHost: 'other.example.com' }],
@@ -154,27 +157,55 @@ describe('the SMTP password stays with the server it was saved for (secrets.reen
expect((await save({ smtpHost: 'fourth.example.com' })).status).toBe(200)
})
test('a save that changes nothing the password belongs to keeps it: the same values sent back, other fields, another letter case', async () => {
test('a save that changes nothing the password belongs to keeps it: the same values sent back, other fields, the port as text', async () => {
const doc = (await (await api(G)).json()) as Record<string, unknown>
for (const key of ['id', 'createdAt', 'updatedAt', 'globalType']) {delete doc[key]}
expect((await save(doc)).status).toBe(200) // the whole form, as the panel sends it
expect((await save({ smtpFromName: 'The site', smtpHost: ' SMTP.example.com ', smtpPort: '587', smtpUser: 'mailer' })).status).toBe(200)
expect((await save({ smtpFromName: 'The site', smtpHost: 'smtp.example.com', smtpPort: '587', smtpUser: 'mailer' })).status).toBe(200)
expect((await save({ turnstileSiteKey: 'site-key' })).status).toBe(200)
expect(await stored()).toMatchObject({ smtpFromName: 'The site', smtpPassword: SMTP })
})
test('a document saved before the port and the checkbox had a value: their defaults are not a change', async () => {
await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), smtpPort: null, smtpRequireTls: null } as never })
expect((await save({ smtpFromName: 'Again', smtpPort: 587, smtpRequireTls: false })).status).toBe(200)
test('a stored NULL where the field has a default (a SQL row, an older document) is not a change', async () => {
// the port sits inside a row; its default is 587, the transport's is 'smtp'
await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), emailTransport: null, smtpPort: null } as never })
expect((await save({ smtpFromName: 'Again' })).status).toBe(200)
expect((await save({ emailTransport: 'smtp', smtpFromName: 'Again', smtpPort: 587 })).status).toBe(200)
await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), emailTransport: null, smtpPort: null } as never })
expect((await save({ smtpFromName: 'Again', smtpPort: null })).status).toBe(200)
const doc = (await (await api(G)).json()) as Record<string, unknown>
for (const key of ['id', 'createdAt', 'updatedAt', 'globalType']) {delete doc[key]}
expect((await save(doc)).status).toBe(200)
expect((await save({ smtpPort: 2525 })).status).toBe(400)
expect((await stored()).smtpPassword).toBe(SMTP)
})
test('switching to Microsoft Graph asks for nothing (the password is not used there); switching back to another server does', async () => {
expect((await save({ emailTransport: 'graph' })).status).toBe(200)
expect((await stored()).smtpPassword).toBe(SMTP)
expect((await save({ emailTransport: 'smtp', smtpHost: 'other.example.com' })).status).toBe(400)
expect((await save({ emailTransport: 'smtp' })).status).toBe(400) // the transport itself is one of the settings
expect((await save({ emailTransport: 'smtp', smtpPassword: 'typed-again' })).status).toBe(200)
// Review round 2 (R2-1): "Microsoft Graph" in the panel does not mean Graph sends — the mail adapter falls back to
// SMTP when the GRAPH_* variables are missing. The transport decides nothing; the server, port and user do.
test('the transport switch is not a way round: Graph + my server in one save, or Graph first and my server after', async () => {
const mine = await fakeSmtp()
try {
const gql = async (data: string) => (await (await api('/graphql', { body: JSON.stringify({ query: `mutation { updateSiteIntegration(data: { ${data} }) { smtpHost } }` }), method: 'POST' })).json()) as { errors?: unknown[] }
// 1. in one save, over REST and over GraphQL
expect((await save({ emailTransport: 'graph', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
expect((await gql(`emailTransport: graph, smtpHost: "127.0.0.1", smtpPort: ${mine.port}`)).errors?.length).toBeGreaterThan(0)
await testEmail()
// 2. the switch alone passes (the password is not asked for, and stays)…
expect((await save({ emailTransport: 'graph' })).status).toBe(200)
// …and the server afterwards does not, with or without naming the transport again
expect((await save({ smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
expect((await save({ emailTransport: 'graph', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
expect((await save({ emailTransport: 'smtp', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
expect((await gql(`smtpHost: "127.0.0.1", smtpPort: ${mine.port}`)).errors?.length).toBeGreaterThan(0)
await testEmail()
await api('/ipal/test-email', { body: JSON.stringify({ attachmentMB: 5, to: '[email protected]' }), method: 'POST' })
expect(mine.seen).toEqual({ auth: '', mails: 0 })
expect(await stored()).toMatchObject({ emailTransport: 'graph', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587 })
// back to SMTP alone: the same server as before, nothing to ask
expect((await save({ emailTransport: 'smtp' })).status).toBe(200)
} finally {
await mine.close()
}
})
test('server code (a seed, the Local API with access control off) moves the server and keeps the password', async () => {
@@ -205,23 +236,6 @@ describe('the SMTP password stays with the server it was saved for (secrets.reen
})
})
describe('"Require an encrypted connection" (smtpRequireTls)', () => {
test('a server that offers no encryption never sees the password; without the option it does, as before', async () => {
const plain = await fakeSmtp()
try {
expect((await save({ smtpHost: '127.0.0.1', smtpPassword: SMTP, smtpPort: plain.port, smtpRequireTls: true })).status).toBe(200)
await testEmail()
expect(plain.seen).toEqual({ auth: '', mails: 0 })
expect((await save({ smtpPassword: SMTP, smtpRequireTls: false })).status).toBe(200)
await testEmail()
expect(plain.seen.auth).toContain(SMTP)
expect(plain.seen.mails).toBe(1)
} finally {
await plain.close()
}
})
})
describe('versions on the global: a restore does not hand the value back', () => {
test('REST restore answers with the mask; the stored value is the restored one', async () => {
await save({ smtpFromName: 'One' })