Merge claude/security-a-1172: a locked staff account answers like a wrong password, IPv6 counted per /64, panel actions only from the site's own origin

plugin.ts import conflict: withVersionReadRules (readPublished fix) and withLockedAnswer both kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 11:06:15 +01:00
co-authored by Claude Opus 5.5
35 changed files with 882 additions and 31 deletions
+38
View File
@@ -0,0 +1,38 @@
/** The plugin's panel actions refuse other origins (adminSameOriginSuite.ts). */
import { describe, expect, test, vi } from 'vitest'
import { guardAdminEndpoints } from '../src/modules/security/adminSameOrigin.js'
import { clearReportedOrigins } from '../src/modules/security/totp/sameOrigin.js'
import { ACTIONS, adminSite, SIBLING } from './adminSameOriginSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const { action, state } = adminSite()
describe('adminSameOrigin (default): panel actions only from the site\'s own origin', () => {
test('a page on a sibling subdomain, or a cross-site page, gets 403 on every panel action, with the admin cookie', async () => {
clearReportedOrigins()
for (const path of ACTIONS) {
expect([path, (await action(path, SIBLING)).status]).toEqual([path, 403])
expect([path, (await action(path, { 'sec-fetch-site': 'cross-site' })).status]).toEqual([path, 403])
}
// said in the log once per origin, naming this option
const lines = state.warn.filter((l) => l.includes('blog.site.example'))
expect(lines).toHaveLength(1)
expect(lines[0]).toMatch(/adminSameOrigin/)
})
test('the site\'s own page and a script without browser headers still reach them', async () => {
const own = await action('/ipal/cookie-approval', { origin: state.server.url, 'sec-fetch-site': 'same-origin' }, '{"ids":[]}')
expect(own.status).toBe(200)
const script = await action('/ipal/cookie-approval', {}, '{"ids":[]}')
expect(script.status).toBe(200)
})
test('a project\'s own endpoint on one of these paths is left as it is', () => {
const own = { handler: () => Response.json({ ok: true }), method: 'post' as const, path: '/ipal/test-email' }
const config = guardAdminEndpoints({ endpoints: [own] } as never, new Set([own]), undefined)
expect(config.endpoints?.[0]).toBe(own)
})
})
+22
View File
@@ -0,0 +1,22 @@
/** adminSameOrigin: false leaves the origin check out (adminSameOriginSuite.ts). */
import { describe, expect, test, vi } from 'vitest'
import { iapl } from '../src/plugin.js'
import { adminSite, SIBLING } from './adminSameOriginSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const { action } = adminSite(false)
describe('adminSameOrigin: false', () => {
test('a request from a sibling subdomain reaches the action, as before 1.17.2', async () => {
expect((await action('/ipal/cookie-approval', SIBLING, '{"ids":[]}')).status).toBe(200)
})
test('a value nobody understands stops the start', async () => {
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
await expect((async () => iapl({ adminSameOrigin: 0 as never, i18n } as never)({ collections: [], secret: 'x' } as never))()).rejects.toThrow(/adminSameOrigin must be/)
await expect((async () => iapl({ adminSameOrigin: { origins: 'https://a.example' as never }, i18n } as never)({ collections: [], secret: 'x' } as never))()).rejects.toThrow(/adminSameOrigin\.origins must be a list/)
})
})
+70
View File
@@ -0,0 +1,70 @@
/**
* The plugin's panel actions only from the site's own origin (adminSameOrigin, 1.17.2). Shared by
* adminSameOrigin.test.ts (default) and adminSameOriginOff.test.ts (`adminSameOrigin: false`): one Payload per file.
* A signed-in administrator's cookie rides on a `text/plain` POST (no CORS preflight) from a page on a sibling
* subdomain. Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
*/
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { getPayload } from 'payload'
import { afterAll, beforeAll } from 'vitest'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
const SECRET = 'JBSWY3DPEHPK3PXP'
const PASSWORD = 'a-long-test-password-1'
export const SIBLING = { origin: 'https://blog.site.example', 'sec-fetch-site': 'same-site' }
/** Every panel action the rule covers (path under /api). */
export const ACTIONS = ['/iapl/mail-relay/connect', '/iapl/mail-relay/disconnect', '/ipal/test-email', '/ipal/cookie-scan', '/ipal/cookie-approval', '/ipal/cookie-crawl']
export function adminSite(adminSameOrigin?: false) {
const state = {} as { cookie: string; payload: Payload; server: TestServer; warn: string[] }
beforeAll(async () => {
process.env.IAPL_COOKIE_SCAN_URL ??= 'http://127.0.0.1:9'
process.env.IAPL_COOKIE_SCAN_TOKEN ??= 'test-token-0123456789abcdef0123456789'
const config = buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-admin-origin-media' } }],
db: testDatabase('adminorigin'),
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users' },
...(adminSameOrigin === false ? { adminSameOrigin } : {}),
cookieScanner: { crawl: true },
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
twoFactor: { issuer: 'Example', plugin: payloadTotp },
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
state.payload = await getPayload({ config })
state.warn = []
const warn = state.payload.logger.warn.bind(state.payload.logger)
state.payload.logger.warn = ((msg: unknown, ...rest: unknown[]) => {
state.warn.push(String(msg))
return (warn as (...a: unknown[]) => void)(msg, ...rest)
}) as never
state.server = await startPayloadServer(config)
await state.payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never })
const login = await fetch(`${state.server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
const first = cookiesOf(login)
const verify = await fetch(`${state.server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(SECRET) }), headers: { 'content-type': 'application/json', cookie: first.join('; ') }, method: 'POST' })
state.cookie = [...first, ...cookiesOf(verify)].join('; ')
}, 120_000)
afterAll(async () => {
await state.server?.close()
await state.payload?.destroy?.()
})
/** A POST as a foreign page can send it: text/plain, the admin's cookie. */
const action = (path: string, headers: Record<string, string>, body = '{"to":"[email protected]"}') =>
fetch(`${state.server.url}/api${path}`, { body, headers: { 'content-type': 'text/plain', cookie: state.cookie, ...headers }, method: 'POST', signal: AbortSignal.timeout(20_000) })
return { action, state }
}
+14 -1
View File
@@ -193,6 +193,9 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
expect(await run(build('{ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, plugins: [] }'), ['csrf-empty'])).toEqual([])
expect(await run(build("{ csrf: ['https://site.example'], plugins: [] }"), ['csrf-empty'])).toEqual([])
expect(await run('// not a Payload config', ['csrf-empty'])).toEqual([])
// deep (the running config, 1.17.2): it wins over the file — serverURL may come from a spread or a helper
expect(await run(build('{ ...base, plugins: [] }'), ['csrf-empty'], { originKnown: false })).toEqual(['csrf-empty:warning'])
expect(await run(build("{ plugins: [iapl({ access: { authCollection: 'users' } })] }"), ['csrf-empty'], { originKnown: true })).toEqual([])
})
test('open-signup: an auth collection anyone can register in is said, as info', async () => {
@@ -230,6 +233,16 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
expect(fromEnv.turnstileSecretFromEnv).toBe(true)
expect(JSON.stringify(fromEnv)).not.toMatch(/secret-value/)
})
test('the deep status says whether the running config knows its own origin (serverURL or csrf), never the value', async () => {
const fake = (extra: object) => ({ config: { admin: { user: 'users' }, collections: [{ slug: 'users', fields: [] }], globals: [], ...extra } })
expect((await collectDoctorStatus(fake({}) as never)).originKnown).toBe(false)
expect((await collectDoctorStatus(fake({ serverURL: '' }) as never)).originKnown).toBe(false)
const known = await collectDoctorStatus(fake({ serverURL: 'https://secret-host.example' }) as never)
expect(known.originKnown).toBe(true)
expect(JSON.stringify(known)).not.toMatch(/secret-host/)
expect((await collectDoctorStatus(fake({ csrf: ['https://site.example'] }) as never)).originKnown).toBe(true)
})
})
describe('helpers', () => {
@@ -529,7 +542,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(['mail', 'node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
expect(status.mail).toBeNull() // no Site integrations global in this config
})
+35
View File
@@ -0,0 +1,35 @@
/** A locked staff account answers like a wrong password, REST and GraphQL (lockedAnswerSuite.ts). 2FA on. */
import { describe, expect, test, vi } from 'vitest'
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const { gqlLogin, lock, restLogin, state } = lockedAnswerSite()
describe('accounts.lockedAnswer (default): a locked staff account looks like a wrong password', () => {
test('REST: the locked owner, with any password, gets exactly what an invented address gets', async () => {
await lock('users', '[email protected]')
const invented = await restLogin('users', '[email protected]', 'a-wrong-password')
expect(invented.status).toBe(401)
expect(await restLogin('users', '[email protected]', 'a-wrong-password')).toEqual(invented)
expect(await restLogin('users', '[email protected]', PASSWORD)).toEqual(invented)
expect(invented.body).not.toMatch(/locked/i)
// the lock itself is still there
const stored = (await state.payload.find({ collection: 'users' as never, overrideAccess: true, showHiddenFields: true, where: { email: { equals: '[email protected]' } } })).docs[0] as { lockUntil?: string }
expect(new Date(String(stored.lockUntil)).getTime()).toBeGreaterThan(Date.now())
})
test('GraphQL: the same message, status and error name', async () => {
const invented = await gqlLogin('loginUser', '[email protected]', 'a-wrong-password')
expect(invented.name).toBe('AuthenticationError')
expect(await gqlLogin('loginUser', '[email protected]', PASSWORD)).toEqual(invented)
})
test('a visitor collection keeps Payload\'s answer (not staff)', async () => {
await lock('customers', '[email protected]', 3)
expect((await restLogin('customers', '[email protected]', PASSWORD)).body).toMatch(/locked/i)
expect((await gqlLogin('loginCustomer', '[email protected]', PASSWORD)).name).toBe('LockedAuth')
})
})
+16
View File
@@ -0,0 +1,16 @@
/** A locked staff account answers like a wrong password with 2FA off too (lockedAnswerSuite.ts). */
import { describe, expect, test, vi } from 'vitest'
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
vi.mock('server-only', () => ({}))
const { gqlLogin, lock, restLogin } = lockedAnswerSite({ twoFactor: false })
describe('accounts.lockedAnswer with twoFactor: false', () => {
test('REST and GraphQL answer the locked owner like an invented address', async () => {
await lock('users', '[email protected]')
expect(await restLogin('users', '[email protected]', PASSWORD)).toEqual(await restLogin('users', '[email protected]', 'x-wrong-password-1'))
expect(await gqlLogin('loginUser', '[email protected]', PASSWORD)).toEqual(await gqlLogin('loginUser', '[email protected]', 'x-wrong-password-1'))
})
})
+23
View File
@@ -0,0 +1,23 @@
/** accounts.lockedAnswer: 'payload' keeps Payload's "locked" answer (lockedAnswerSuite.ts). */
import { describe, expect, test, vi } from 'vitest'
import { iapl } from '../src/plugin.js'
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const { gqlLogin, lock, restLogin } = lockedAnswerSite({ lockedAnswer: 'payload' })
describe("accounts.lockedAnswer: 'payload'", () => {
test('the locked owner is told it is locked, REST and GraphQL', async () => {
await lock('users', '[email protected]')
expect((await restLogin('users', '[email protected]', PASSWORD)).body).toMatch(/locked/i)
expect((await gqlLogin('loginUser', '[email protected]', PASSWORD)).name).toBe('LockedAuth')
})
test('a value nobody understands stops the start', async () => {
const config = { collections: [], secret: 'x' } as never
await expect((async () => iapl({ accounts: { lockedAnswer: 'Payload' as never }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } } as never)(config))()).rejects.toThrow(/accounts\.lockedAnswer must be one of/)
})
})
+79
View File
@@ -0,0 +1,79 @@
/**
* A locked staff account answers its login exactly like a wrong password (accounts.lockedAnswer, 1.17.2; IAWL
* idea 6). Shared by lockedAnswer.test.ts (default, 2FA on), lockedAnswer2fa-off.test.ts (2FA off) and
* lockedAnswerPayload.test.ts (`lockedAnswer: 'payload'`): one Payload per file.
* Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
*/
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { getPayload } from 'payload'
import { afterAll, beforeAll } from 'vitest'
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'
export const PASSWORD = 'a-long-test-password-1'
export type Answer = { body: string; status: number }
export function lockedAnswerSite({ lockedAnswer, twoFactor = true }: { lockedAnswer?: 'payload'; twoFactor?: boolean } = {}) {
const state = {} as { payload: Payload; server: TestServer }
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
// a visitor collection with Payload's own lock: not staff, not changed
{ slug: 'customers', access: { create: () => true }, auth: { maxLoginAttempts: 3 }, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-locked-answer-media' } },
],
db: testDatabase('lockedanswer'),
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users' },
...(lockedAnswer ? { accounts: { lockedAnswer } } : {}),
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp } : false,
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
state.payload = await getPayload({ config })
state.server = await startPayloadServer(config)
await state.payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
await state.payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
}, 120_000)
afterAll(async () => {
await state.server?.close()
await state.payload?.destroy?.()
})
const restLogin = async (collection: string, email: string, password: string): Promise<Answer> => {
const res = await fetch(`${state.server.url}/api/${collection}/login`, {
body: JSON.stringify({ email, password }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
return { body: await res.text(), status: res.status }
}
const gqlLogin = async (mutation: string, email: string, password: string) => {
const res = await fetch(`${state.server.url}/api/graphql`, {
body: JSON.stringify({ query: `mutation { ${mutation}(email: ${JSON.stringify(email)}, password: ${JSON.stringify(password)}) { token } }` }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
const body = (await res.json()) as { errors?: { extensions?: { name?: string; statusCode?: number }; message: string }[] }
const e = body.errors?.[0]
return { name: e?.extensions?.name, message: e?.message, status: res.status, statusCode: e?.extensions?.statusCode }
}
/** Locks `email` with wrong passwords (Payload's default: 5). */
const lock = async (collection: string, email: string, times = 5) => {
for (let i = 0; i < times; i++) {await restLogin(collection, email, 'a-wrong-password')}
}
return { gqlLogin, lock, restLogin, state }
}
+108
View File
@@ -0,0 +1,108 @@
/**
* IPv6 is counted per network (1.17.2, IAWL idea 9): a /64 is one client in every limiter of the plugin; a second
* counter per /48 when a project turns it on (`setIpv6Grouping({ wide: 48 })`).
*/
import { afterEach, describe, expect, test, vi } from 'vitest'
import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
import { passRateLimit } from '../src/modules/forms/submitForm.js'
import { checkRateLimit, clientIp, consumeRateLimit, ipRateKey, setIpv6Grouping } from '../src/modules/shared/rateLimit.js'
vi.mock('server-only', () => ({}))
let scope = 0
const nextScope = () => `ipv6-test-${++scope}`
const hex = (n: number) => n.toString(16)
afterEach(() => setIpv6Grouping())
describe('ipRateKey', () => {
test('one key for every address of a /64, whatever the spelling', () => {
const key = ipRateKey('2001:db8:1:2::1')
expect(key).toBe('2001:db8:1:2:0:0:0:0/64')
for (const a of ['2001:db8:1:2:ffff:ffff:ffff:ffff', '2001:0DB8:0001:0002:0000:0000:0000:0042', '[2001:db8:1:2::9]', '2001:db8:1:2::9%eth0']) {
expect([a, ipRateKey(a)]).toEqual([a, key])
}
expect(ipRateKey('2001:db8:1:3::1')).not.toBe(key)
})
test('IPv4 as it is; an IPv4-mapped IPv6 address is its IPv4; anything else unchanged', () => {
expect(ipRateKey('198.51.100.7')).toBe('198.51.100.7')
expect(ipRateKey('::ffff:198.51.100.7')).toBe('198.51.100.7')
expect(ipRateKey('::ffff:c633:6407')).toBe('198.51.100.7')
expect(ipRateKey('')).toBe('')
expect(ipRateKey('not-an-ip')).toBe('not-an-ip')
for (const bad of ['1::2::3', '2001:db8:1:2:3:4:5:6:7', '12345::1', '::ffff:300.1.1.1', 'to:abcdef', 'a:b']) {expect([bad, ipRateKey(bad)]).toEqual([bad, bad])}
expect(ipRateKey('::')).toBe('0:0:0:0:0:0:0:0/64')
expect(ipRateKey('256.1.1.1')).toBe('256.1.1.1')
})
test('setIpv6Grouping: per address again, another prefix; nonsense is refused', () => {
setIpv6Grouping({ prefix: 128 })
expect(ipRateKey('2001:db8::1')).not.toBe(ipRateKey('2001:db8::2'))
setIpv6Grouping({ prefix: 56 })
expect(ipRateKey('2001:db8:0:ff::1')).toBe(ipRateKey('2001:db8:0:1::1'))
expect(() => setIpv6Grouping({ prefix: 0 })).toThrow(/prefix must be/)
expect(() => setIpv6Grouping({ prefix: '64' as never })).toThrow(/prefix must be/)
expect(() => setIpv6Grouping({ prefix: 48, wide: 56 })).toThrow(/shorter prefix/)
})
})
describe('the limiters count a /64 as one client', () => {
test('consumeRateLimit: fifty addresses of one /64 get five requests, not fifty', async () => {
const s = nextScope()
let allowed = 0
for (let i = 1; i <= 50; i++) {
if ((await consumeRateLimit({ key: clientIp(new Headers({ 'x-real-ip': `2001:db8:1:1::${hex(i)}` })), max: 5, scope: s })).ok) {allowed++}
}
expect(allowed).toBe(5)
// another /64 of the same /48 is another client (the wide counter is off by default)
expect((await consumeRateLimit({ key: '2001:db8:1:2::1', max: 5, scope: s })).ok).toBe(true)
})
test('checkRateLimit (the synchronous one) too', () => {
const s = nextScope()
const results = Array.from({ length: 8 }, (_, i) => checkRateLimit({ key: `2001:db8:9:9::${hex(i + 1)}`, max: 3, scope: s }))
expect(results.filter(Boolean)).toHaveLength(3)
})
test('the forms gate (passRateLimit)', async () => {
const results = []
for (let i = 1; i <= 8; i++) {results.push(await passRateLimit({ ip: `2001:db8:abcd:1::${hex(i)}`, maxPerMinute: 5 }))}
expect(results.filter((r) => r === null)).toHaveLength(5)
expect(results[7]).toMatchObject({ reason: 'rate_limited' })
})
test('a plugin endpoint (the consent log, 20 a minute): the 21st address of one /64 gets 429', async () => {
const { handler } = buildConsentLogEndpoint()
const statuses: number[] = []
for (let i = 1; i <= 21; i++) {
const req = { headers: new Headers({ 'x-real-ip': `2001:db8:feed:1::${hex(i)}` }), text: () => Promise.resolve('{') }
statuses.push((await (handler as (r: never) => Promise<Response>)(req as never)).status)
}
expect(statuses.slice(0, 20)).not.toContain(429)
expect(statuses[20]).toBe(429)
})
})
describe('the wide counter (setIpv6Grouping({ wide: 48 }))', () => {
test('three hundred /64s of one /48: at most wideFactor × max requests', async () => {
setIpv6Grouping({ wide: 48, wideFactor: 10 })
const s = nextScope()
let allowed = 0
for (let i = 1; i <= 300; i++) {
if ((await consumeRateLimit({ key: `2001:db8:7:${hex(i)}::1`, max: 5, scope: s })).ok) {allowed++}
}
expect(allowed).toBe(50)
// another /48 is untouched
expect((await consumeRateLimit({ key: '2001:db8:8:1::1', max: 5, scope: s })).ok).toBe(true)
})
test('IPv4 is not affected by it', async () => {
setIpv6Grouping({ wide: 48 })
const s = nextScope()
const ok = []
for (let i = 1; i <= 6; i++) {ok.push((await consumeRateLimit({ key: `198.51.100.${i}`, max: 1, scope: s })).ok)}
expect(ok).toEqual([true, true, true, true, true, true])
})
})