Security review round 2: no exception by name, staff list fails closed, verify limit
R2-1: the sweep skipped every collection whose slug starts with payload-,
so a plugin's payload-... collection added after ipalKit was never guarded.
There is no exception by name or prefix now: every collection and global
is guarded, Payload's own included, and the job queue's run / queue /
cancel rules too.
R2-2: role predicates called without a source fail closed where the staff
collections are not known (browser bundle, middleware, edge): nobody is
staff. They accept req.payload, a config (also the client config) or
{ staffCollections } as the source.
R2-3: the staff list is filed per config / Payload instance; a call without
a source gets only what every config in the process calls staff.
R2-4: payload.config is watched on the instance, so a config swapped in by
a dev reload is guarded before any request or Local API call.
R2-5: verify attempts are limited per account (default 5 in 10 minutes,
twoFactor.verifyLimit), counted in memory, never skipped.
R2-6: a user object without collection owes the second factor; endpoints
the 2FA package may add on collections or globals are guarded too; a
warning names staff collections that 2FA does not cover; docs state what
is not covered, fix the one-argument examples and the doctor example.
HTTP tests for each on payload-2fa beta.7, run on SQLite, Postgres and
MongoDB (test adapter added).
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
32faaa5e30
commit
c56f0d41b8
+36
-6
@@ -3,7 +3,7 @@ import type { FieldAccess, PayloadRequest } from 'payload'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, adminOrSelfIn, requireRole, requireRoleField } from '../src/modules/access/access.js'
|
||||
import { hasMinimumRole, isAdmin, isEditor } from '../src/modules/access/predicates.js'
|
||||
import { hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffRegistrySize } from '../src/modules/access/predicates.js'
|
||||
import { buildRolesField } from '../src/modules/access/rolesField.js'
|
||||
import { testEmailEndpoint } from '../src/modules/email/test/testEmailEndpoint.js'
|
||||
|
||||
@@ -17,11 +17,11 @@ const payload = { config: { admin: { user: 'users' } } } as never
|
||||
|
||||
describe('role predicates', () => {
|
||||
test('hierarchy admin > editor > user', () => {
|
||||
expect(isAdmin(admin)).toBe(true)
|
||||
expect(isAdmin(editor)).toBe(false)
|
||||
expect(isEditor(admin)).toBe(true)
|
||||
expect(isEditor(user)).toBe(false)
|
||||
expect(hasMinimumRole(user, 'user')).toBe(true)
|
||||
expect(isAdmin(admin, payload)).toBe(true)
|
||||
expect(isAdmin(editor, payload)).toBe(false)
|
||||
expect(isEditor(admin, payload)).toBe(true)
|
||||
expect(isEditor(user, payload)).toBe(false)
|
||||
expect(hasMinimumRole(user, 'user', payload)).toBe(true)
|
||||
})
|
||||
|
||||
test('unknown roles and odd shapes grant nothing', () => {
|
||||
@@ -42,6 +42,36 @@ describe('role predicates', () => {
|
||||
expect(isAdmin(member, withMembers)).toBe(true)
|
||||
})
|
||||
|
||||
test('where the staff collections are not known, nobody is staff (browser bundle, middleware)', () => {
|
||||
// no ipalKit config in this process (test/setup.ts clears the registry) and no source given
|
||||
expect(isAdmin(admin)).toBe(false)
|
||||
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false)
|
||||
expect(hasMinimumRole(user, 'user')).toBe(false)
|
||||
// …until the caller says where staff come from: the config (also the client config), or the list itself
|
||||
expect(isAdmin(admin, { admin: { user: 'users' } })).toBe(true)
|
||||
expect(isAdmin(admin, { staffCollections: ['users'] })).toBe(true)
|
||||
expect(isAdmin({ collection: 'customers', roles: ['admin'] }, { staffCollections: ['users'] })).toBe(false)
|
||||
})
|
||||
|
||||
test('two configs in one process: a call without a source gets only what both call staff', () => {
|
||||
const a = {}
|
||||
const b = {}
|
||||
registerStaffCollections(a, ['users'])
|
||||
expect(isAdmin(admin)).toBe(true)
|
||||
registerStaffCollections(b, ['staff', 'customers'])
|
||||
expect(isAdmin(admin)).toBe(false) // not staff in B
|
||||
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) // not staff in A
|
||||
registerStaffCollections(b, ['users', 'customers'])
|
||||
expect(isAdmin(admin)).toBe(true)
|
||||
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false)
|
||||
// with the source, each config gets its own answer
|
||||
expect(isAdmin({ collection: 'customers', roles: ['admin'] }, { staffCollections: ['users', 'customers'] })).toBe(true)
|
||||
// an instance taking over its config's token replaces the entry instead of adding one
|
||||
const instance = {}
|
||||
registerStaffCollections(instance, ['users'], a)
|
||||
expect(staffRegistrySize()).toBe(2)
|
||||
})
|
||||
|
||||
test('every ready access function refuses that account', () => {
|
||||
const member = { id: 1, collection: 'members', roles: ['admin'] }
|
||||
const req = { payload, user: member }
|
||||
|
||||
+10
-1
@@ -1,3 +1,4 @@
|
||||
import { mongooseAdapter } from '@payloadcms/db-mongodb'
|
||||
import { postgresAdapter } from '@payloadcms/db-postgres'
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
|
||||
@@ -7,9 +8,17 @@ import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
* another):
|
||||
* docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:17
|
||||
* IPAL_TEST_POSTGRES_URI=postgres://postgres:[email protected]:55432/postgres pnpm vitest run test/securityHttp.test.ts
|
||||
* Each test file gets its own schema (`name`), so the files can run one after another against one server.
|
||||
* `IPAL_TEST_MONGO_URI` points them at MongoDB (what the client sites run):
|
||||
* docker run -d --rm -p 127.0.0.1:27217:27017 mongo:7
|
||||
* IPAL_TEST_MONGO_URI=mongodb://127.0.0.1:27217 pnpm vitest run test/securityHttp.test.ts
|
||||
* Each test file gets its own schema / database (`name`), so the files can run one after another against one server.
|
||||
*/
|
||||
/** True on the adapters where ids are numbers counted per collection (an id can repeat across collections). */
|
||||
export const numericIds = () => !process.env.IPAL_TEST_MONGO_URI
|
||||
|
||||
export function testDatabase(name: string) {
|
||||
const mongo = process.env.IPAL_TEST_MONGO_URI
|
||||
if (mongo) {return mongooseAdapter({ url: `${mongo.replace(/\/$/, '')}/${name}_${Date.now()}` })}
|
||||
const uri = process.env.IPAL_TEST_POSTGRES_URI
|
||||
if (uri) {return postgresAdapter({ pool: { connectionString: uri }, push: true, schemaName: `${name}_${Date.now()}` })}
|
||||
return sqliteAdapter({ client: { url: 'file::memory:' }, push: true })
|
||||
|
||||
+1
-1
@@ -137,7 +137,7 @@ describe('options that keep features reachable and overridable', () => {
|
||||
test('with `access` the roles still decide', async () => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, stats: true, twoFactor: false })(base())
|
||||
const users = config.collections!.find((c) => c.slug === 'users')!
|
||||
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } } }, user }) as never
|
||||
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } }, config: { admin: { user: 'users' } } }, user }) as never
|
||||
const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: { req: unknown }) => unknown
|
||||
expect(read({ req: req({ id: 1, collection: 'users', roles: ['editor'] }) })).toBe(false)
|
||||
expect(read({ req: req({ id: 1, collection: 'users', roles: ['admin'] }) })).toBe(true)
|
||||
|
||||
@@ -10,7 +10,8 @@ import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { adminOrSelfIn } from '../src/modules/access/access.js'
|
||||
import { isAdmin, staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
|
||||
import { guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed } from '../src/modules/security/totp/secondFactor.js'
|
||||
import { ensurePayloadGuarded, guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed, watchPayloadConfig } from '../src/modules/security/totp/secondFactor.js'
|
||||
import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { withTotpParts } from './helpers.js'
|
||||
|
||||
@@ -76,7 +77,7 @@ describe('userMeetsRole: who is staff', () => {
|
||||
})
|
||||
|
||||
describe('adminOrSelfIn', () => {
|
||||
const run = (fn: Access, user: unknown) => fn({ req: { user } } as never)
|
||||
const run = (fn: Access, user: unknown) => fn({ req: { payload: { config: { admin: { user: 'users' } } }, user } } as never)
|
||||
test('"self" is an account of that collection only', () => {
|
||||
const access = adminOrSelfIn('users')
|
||||
expect(run(access, { id: 5, collection: 'users', roles: ['user'] })).toEqual({ id: { equals: 5 } })
|
||||
@@ -97,6 +98,7 @@ describe('secondFactorPassed', () => {
|
||||
['a user object without the fields the check knows (fail closed)', { collection: 'users' }, false],
|
||||
['an unknown strategy name (fail closed)', { _strategy: 'two-factor', collection: 'users', hasTotp: true }, false],
|
||||
['an account of another auth collection', { _strategy: 'local-jwt', collection: 'customers' }, true],
|
||||
['a user object that does not say its collection (fail closed)', { _strategy: 'totp', hasTotp: true }, false],
|
||||
]
|
||||
test.each(cases)('%s', (_, user, expected) => {
|
||||
expect(secondFactorPassed({ payload, user })).toBe(expected)
|
||||
@@ -142,14 +144,35 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
expect((integrations.access!.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
|
||||
})
|
||||
|
||||
test('onInit guards what a later plugin added; Payload\'s own collections are left alone', () => {
|
||||
test('the sweep guards everything a later plugin or Payload itself added — no exception by name or prefix', () => {
|
||||
const late = { slug: 'late', access: {} as Record<string, unknown> }
|
||||
const prefixed = { slug: 'payload-vault', access: {} as Record<string, unknown> } // a plugin's collection, e.g. payload-mcp-api-keys
|
||||
const internal = { slug: 'payload-preferences', access: {} as Record<string, unknown> }
|
||||
const payload = { config: { collections: [late, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [] } } as never
|
||||
expect(guardPayloadAccess(payload)).toEqual(['late'])
|
||||
expect((late.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false)
|
||||
expect(internal.access.read).toBeUndefined()
|
||||
const jobs = { access: {} as Record<string, unknown> }
|
||||
const payload = { config: { collections: [late, prefixed, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [{ slug: 'payload-jobs-stats' }], jobs } } as never
|
||||
expect(guardPayloadAccess(payload)).toEqual(['late', 'payload-vault', 'payload-preferences', 'payload-jobs-stats', 'jobs'])
|
||||
for (const entity of [late, prefixed, internal]) {
|
||||
expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false)
|
||||
expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
|
||||
}
|
||||
// the job queue's own rules (run / queue / cancel)
|
||||
for (const op of ['run', 'queue', 'cancel']) {
|
||||
expect((jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false)
|
||||
expect((jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
|
||||
}
|
||||
expect(guardPayloadAccess(payload)).toEqual([]) // nothing left to do the second time
|
||||
expect(ensurePayloadGuarded(payload)).toEqual([])
|
||||
expect(ensurePayloadGuarded(payload)).toBeNull() // this config object was done
|
||||
})
|
||||
|
||||
test('a config swapped onto the instance (dev reload) is adopted at once, before any request', () => {
|
||||
const adopted: unknown[] = []
|
||||
const instance = { config: { name: 'first' } } as never as { config: { name: string } }
|
||||
watchPayloadConfig(instance as never, (p) => adopted.push((p as never as { config: { name: string } }).config.name))
|
||||
instance.config = { name: 'second' }
|
||||
expect(adopted).toEqual(['second'])
|
||||
expect(instance.config.name).toBe('second')
|
||||
expect({ ...instance }.config.name).toBe('second') // still an ordinary enumerable property to readers
|
||||
})
|
||||
|
||||
test('a 2FA plugin without the parts the guard relies on stops the start', async () => {
|
||||
@@ -210,6 +233,55 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
expect(await call('/admin/reset-user-totp', verified)).toBe(200)
|
||||
})
|
||||
|
||||
test('verify attempts are limited per account, and the limit can be changed or switched off', async () => {
|
||||
clearVerifyLimits()
|
||||
const req = (id: unknown) => ({ i18n: undefined, payload: { logger: { warn: () => {} } }, user: { id, collection: 'users' } }) as never
|
||||
const limit = buildVerifyLimit('users') // 5 in 10 minutes
|
||||
for (let i = 0; i < 5; i++) {expect(limit(req(1))).toBeNull()}
|
||||
const refused = limit(req(1))!
|
||||
expect(refused.status).toBe(429)
|
||||
expect(Number(refused.headers.get('retry-after'))).toBeGreaterThan(0)
|
||||
expect(((await refused.json()) as { message: string }).message).toMatch(/Too many codes/)
|
||||
expect(limit(req(2))).toBeNull() // another account is not affected
|
||||
expect(limit({ ...(req(1) as object), user: null } as never)).toBeNull() // no session: the package refuses by itself
|
||||
const two = buildVerifyLimit('admins', { max: 2, windowMinutes: 1 })
|
||||
expect([two(req(1)), two(req(1))]).toEqual([null, null])
|
||||
expect(two(req(1))!.status).toBe(429)
|
||||
|
||||
// wired by default; twoFactor.verifyLimit: false leaves the package's endpoint as it is
|
||||
const base = () => ({ collections: [], endpoints: [], secret: 'x' }) as unknown as Config
|
||||
const withEndpoint = (o: { collection: string }) => (c: Config) => ({ ...withTotpParts(c, o.collection), endpoints: [...(c.endpoints ?? []), { handler: () => Response.json({ ok: false }), method: 'post' as const, path: '/verify-totp' }] })
|
||||
const call = async (config: Config, n: number) => {
|
||||
const endpoint = config.endpoints!.find((e) => e.path === '/verify-totp')!
|
||||
let last = 0
|
||||
for (let i = 0; i < n; i++) {last = (await endpoint.handler(req(77))).status}
|
||||
return last
|
||||
}
|
||||
clearVerifyLimits()
|
||||
expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never } })(base()), 6)).toBe(429)
|
||||
clearVerifyLimits()
|
||||
expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never, verifyLimit: false } })(base()), 8)).toBe(200)
|
||||
})
|
||||
|
||||
test('staff collections outside the 2FA collection are named in a warning at start', async () => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
|
||||
...twoAuth(),
|
||||
admin: { user: 'users' },
|
||||
} as Config)
|
||||
const warnings: string[] = []
|
||||
const payload = {
|
||||
collections: {},
|
||||
config: { admin: { user: 'users' }, collections: [], custom: config.custom, globals: [] },
|
||||
count: () => ({ totalDocs: 0 }),
|
||||
find: () => ({ docs: [] }),
|
||||
findGlobal: () => ({}),
|
||||
logger: { info: () => {}, warn: (m: string) => warnings.push(m) },
|
||||
updateGlobal: () => ({}),
|
||||
}
|
||||
await Promise.resolve(config.onInit!(payload as never)).catch(() => {}) // later onInit steps need a real database
|
||||
expect(warnings.join('\n')).toMatch(/2FA covers "users" only\. Staff accounts of "partners"/)
|
||||
})
|
||||
|
||||
test('twoFactor: false — no guard, a password is enough (as documented)', async () => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
|
||||
const payload = payloadOf(config)
|
||||
|
||||
@@ -15,7 +15,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { numericIds, testDatabase } from './http/db.js'
|
||||
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
|
||||
import { totp } from './http/totp.js'
|
||||
|
||||
@@ -28,7 +28,13 @@ const PASSWORD = 'a-long-test-password-1'
|
||||
/** A plugin the project lists AFTER ipalKit: its collection did not exist when ipalKit ran. */
|
||||
const latePlugin: Plugin = (config: Config) => ({
|
||||
...config,
|
||||
collections: [...(config.collections ?? []), { slug: 'late-notes', fields: [{ name: 'note', type: 'text' }] }],
|
||||
collections: [
|
||||
...(config.collections ?? []),
|
||||
{ slug: 'late-notes', fields: [{ name: 'note', type: 'text' }] },
|
||||
// A plugin may well call its collection `payload-…` (@payloadcms/plugin-mcp: `payload-mcp-api-keys`).
|
||||
{ slug: 'payload-vault', access: { read: ({ req }) => Boolean(req.user) }, fields: [{ name: 'secret', type: 'text' }] },
|
||||
],
|
||||
globals: [...(config.globals ?? []), { slug: 'late-settings', fields: [{ name: 'note', type: 'text' }] }],
|
||||
})
|
||||
|
||||
const projectCollections: CollectionConfig[] = [
|
||||
@@ -114,10 +120,14 @@ beforeAll(async () => {
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config)
|
||||
|
||||
// The plugin's own and `late-notes`. Payload's built-in collections and the late plugin's `payload-vault` /
|
||||
// `late-settings` have a describe of their own below (their rule is "any logged-in account", so the comparisons
|
||||
// with an anonymous visitor do not apply to them).
|
||||
pluginCollections = payload.config.collections.map((c) => c.slug).filter((s) => !PROJECT_SLUGS.has(s) && !s.startsWith('payload-'))
|
||||
pluginGlobals = payload.config.globals.map((g) => g.slug)
|
||||
pluginGlobals = payload.config.globals.map((g) => g.slug).filter((slug) => slug !== 'late-settings')
|
||||
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: 'S3CRET' } as never })
|
||||
await payload.create({ collection: 'payload-vault' as never, data: { secret: 'VAULT' } as never })
|
||||
const user = (email: string, extra: object) =>
|
||||
payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['admin'], ...extra } as never })
|
||||
await user('[email protected]', { totpSecret: TOTP_SECRET })
|
||||
@@ -346,7 +356,7 @@ describe("the 2FA package's endpoints accept accounts of the 2FA collection only
|
||||
const after = await secretOf('[email protected]')
|
||||
expect(after.totpSecret).toBe(TOTP_SECRET)
|
||||
// the case this test is about: the two accounts really share an id (SQL adapters; on MongoDB ids never repeat)
|
||||
expect(String(customer.user.id)).toBe(String(admin.id))
|
||||
if (numericIds()) {expect(String(customer.user.id)).toBe(String(admin.id))}
|
||||
// an account of yet another auth collection is refused the same way
|
||||
const member = await api('/setup-totp', sessions.member, { body: JSON.stringify({ secret: ATTACKER, token: totp(ATTACKER) }), method: 'POST' })
|
||||
expect(member.status).toBe(403)
|
||||
@@ -382,16 +392,86 @@ describe('per-entity opt-out from the second factor', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('no exception by name: a later plugin\'s `payload-…` collection is guarded like any other', () => {
|
||||
test('REST (list, count, by id) and GraphQL refuse a password-only session; a verified one reads it', async () => {
|
||||
for (const p of ['/payload-vault', '/payload-vault/count', '/globals/late-settings']) {
|
||||
const res = await api(p, sessions.passwordOnly)
|
||||
expect([p, res.status]).toEqual([p, 403])
|
||||
expect(await res.text()).not.toContain('VAULT')
|
||||
}
|
||||
const out = await gql(sessions.passwordOnly, '{ PayloadVaults { docs { secret } } }')
|
||||
expect(out.errors?.length, JSON.stringify(out)).toBeGreaterThan(0)
|
||||
expect(JSON.stringify(out)).not.toContain('VAULT')
|
||||
const ok = await api('/payload-vault', sessions.verified)
|
||||
expect(ok.status).toBe(200)
|
||||
expect(await ok.text()).toContain('VAULT')
|
||||
})
|
||||
|
||||
test("Payload's own collections answer a password-only session nothing either", async () => {
|
||||
const own = payload.config.collections.map((c) => c.slug).filter((slug) => slug.startsWith('payload-') && slug !== 'payload-vault')
|
||||
expect(own).toEqual(expect.arrayContaining(['payload-preferences', 'payload-locked-documents', 'payload-migrations']))
|
||||
const open: string[] = []
|
||||
for (const slug of own) {
|
||||
const status = (await api(`/${slug}`, sessions.passwordOnly)).status
|
||||
if (status === 200) {open.push(`${slug}: ${status}`)}
|
||||
}
|
||||
expect(open).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('the code cannot be guessed: verify attempts are limited per account', () => {
|
||||
const GUESS_SECRET = 'ONSWG4TFORRW6ZDF'
|
||||
let cookie: string
|
||||
beforeAll(async () => {
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: GUESS_SECRET } as never })
|
||||
cookie = (await login('users', '[email protected]')).cookies.join('; ')
|
||||
})
|
||||
const verify = (token: string, headers: Record<string, string> = { cookie }) =>
|
||||
fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token }), headers: { 'content-type': 'application/json', ...headers }, method: 'POST' })
|
||||
|
||||
test('five wrong codes are answered, the sixth attempt is refused — also with the right code', async () => {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const res = await verify('000000')
|
||||
expect(res.status).toBe(200)
|
||||
expect(((await res.json()) as { ok: boolean }).ok).toBe(false)
|
||||
}
|
||||
const sixth = await verify('000000')
|
||||
expect(sixth.status).toBe(429)
|
||||
expect(Number(sixth.headers.get('retry-after'))).toBeGreaterThan(0)
|
||||
const right = await verify(totp(GUESS_SECRET))
|
||||
expect(right.status).toBe(429)
|
||||
expect(right.headers.getSetCookie().join(';')).not.toContain('payload-totp')
|
||||
expect((await fetch(`${server.url}/api/pages`, { headers: { cookie } })).status).toBe(403)
|
||||
})
|
||||
|
||||
test('the limit is the account\'s alone: nobody without its password can use it, other accounts are not affected', async () => {
|
||||
// someone without the password cannot count against the account: no session, or a session of another collection
|
||||
for (let i = 0; i < 8; i++) {
|
||||
await verify('000000', {})
|
||||
await verify('000000', sessions.customer.headers)
|
||||
}
|
||||
// another staff account still verifies
|
||||
const other = await login('users', '[email protected]')
|
||||
const ok = await verify(totp(TOTP_SECRET), { cookie: other.cookies.join('; ') })
|
||||
expect(((await ok.json()) as { ok: boolean }).ok).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
// Last: it replaces the running config.
|
||||
describe('dev hot reload', () => {
|
||||
test('a freshly built config is guarded again, also what a later plugin added', async () => {
|
||||
// What Payload's reload() does to the instance: a newly built and sanitized config, no onInit.
|
||||
const fresh = await makeConfig()
|
||||
payload.config = fresh
|
||||
// Before any HTTP request: the Local API meets the new config guarded already.
|
||||
const passwordOnlyUser = { ...(await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0], _strategy: 'local-jwt', collection: 'users' }
|
||||
payload.collections = Object.fromEntries(
|
||||
fresh.collections.map((c) => [c.slug, { config: c, customIDType: payload.collections[c.slug as never]?.customIDType }]),
|
||||
) as never
|
||||
payload.globals = { config: fresh.globals }
|
||||
await expect(payload.find({ collection: 'late-notes' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
|
||||
await expect(payload.find({ collection: 'payload-vault' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
|
||||
await expect(payload.findGlobal({ slug: 'late-settings' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
|
||||
|
||||
expect((await api('/late-notes', sessions.passwordOnly)).status).toBe(403)
|
||||
expect((await api('/late-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { beforeEach } from 'vitest'
|
||||
|
||||
import { clearStaffRegistry } from '../src/modules/access/predicates.js'
|
||||
|
||||
/**
|
||||
* Role predicates called without `req.payload` use the staff collections of the configs built in this process —
|
||||
* what every one of them agrees on. A test file builds many unrelated configs, so each test starts with none:
|
||||
* a test that builds a config and then calls an access function with a bare `{ req: { user } }` sees that config.
|
||||
*/
|
||||
beforeEach(() => {
|
||||
clearStaffRegistry()
|
||||
})
|
||||
Reference in New Issue
Block a user