M1 (6): nobody creates an account for themselves
accounts.adminOnlyCreate (on): a staff collection without a create rule gets
"an admin, fully signed in" instead of Payload's "any logged-in user" — also the
project's own collection; a rule the project wrote stays.
accounts.firstUserRoute ('panel'): Payload's first-user route answers only for
the collection the panel logs in with. For any other empty auth collection it is
refused, unless that collection's own create rule lets an anonymous request in.
Checked and closed: an empty second staff collection, whose first visitor became
a staff admin (test/accountRulesOff.test.ts records the old behaviour, which
accounts: false / firstUserRoute: 'all' still give).
Doctor: open-signup (deep, info) names auth collections with open sign-up.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
cd60b73685
commit
c6fc0d21fe
@@ -2,6 +2,8 @@ export { lightboxNotificationFields } from './globals/Notifications/fields.js'
|
||||
export { applyGlobalOverrides } from './globals/overrides.js'
|
||||
export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js'
|
||||
export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js'
|
||||
export { applyAdminOnlyCreate, applyFirstUserRoute, buildFirstUserGuard, openSignUpCollections, staffCreateAccess } from './modules/access/selfRegistration.js'
|
||||
export type { FirstUserRouteOption } from './modules/access/selfRegistration.js'
|
||||
export type { AccountsOptions } from './modules/access/types.js'
|
||||
export type { AccessOption, Role } from './modules/access/index.js'
|
||||
export {
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { Access, CollectionBeforeOperationHook, Config } from 'payload'
|
||||
|
||||
import { Forbidden } from 'payload'
|
||||
|
||||
import { userMeetsRole } from './predicates.js'
|
||||
|
||||
/**
|
||||
* Nobody creates an account for themselves.
|
||||
*
|
||||
* Two doors, both closed by default (`accounts.adminOnlyCreate`, `accounts.firstUserRoute`):
|
||||
*
|
||||
* 1. **`create` on a staff collection.** Payload's default for a collection without a `create`
|
||||
* rule is "any logged-in user". On a project's own staff collection that let every signed-in
|
||||
* account — the lowest role included — make accounts. Default now: an admin (a staff account
|
||||
* that passes `userMeetsRole(req, 'admin')`, the second factor included). A `create` rule the
|
||||
* project wrote stays.
|
||||
*
|
||||
* 2. **Payload's first-user route** (`POST /api/<slug>/first-register`) exists for EVERY auth
|
||||
* collection and answers while that collection is empty — also for one that allows no
|
||||
* sign-up, and for a second staff collection, whose first account would be staff. Default
|
||||
* now: only the collection the panel logs in with (the first account of a site, which
|
||||
* becomes admin). Another collection's route answers only when that collection's own
|
||||
* `create` rule lets an anonymous request through (it allows sign-up anyway).
|
||||
*
|
||||
* A visitor collection that allows sign-up (`customers` with `create: () => true`) is not
|
||||
* touched by either.
|
||||
*/
|
||||
|
||||
/** `create` for a staff collection: an admin, fully signed in. */
|
||||
export const staffCreateAccess: Access = ({ req }) => userMeetsRole(req, 'admin')
|
||||
|
||||
/** Adds `staffCreateAccess` to the named collections where the project wrote no `create` rule. */
|
||||
export function applyAdminOnlyCreate(config: Config, staffSlugs: string[]): Config {
|
||||
return {
|
||||
...config,
|
||||
collections: (config.collections ?? []).map((collection) =>
|
||||
collection.auth && staffSlugs.includes(collection.slug) && !collection.access?.create ? { ...collection, access: { ...collection.access, create: staffCreateAccess } } : collection,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/** `accounts.firstUserRoute`: `'panel'` (default) = the panel's login collection only; slugs = those; `'all'` = Payload's behaviour. */
|
||||
export type FirstUserRouteOption = 'all' | 'panel' | string[]
|
||||
|
||||
const FIRST_REGISTER = /\/first-register\/?$/
|
||||
|
||||
/**
|
||||
* `beforeOperation` hook for an auth collection: refuses the first-user route unless the
|
||||
* collection is allowed (see above). Not involved in any other create.
|
||||
*/
|
||||
export function buildFirstUserGuard(option: FirstUserRouteOption = 'panel'): CollectionBeforeOperationHook {
|
||||
return async ({ args, collection, operation, req }) => {
|
||||
if (operation !== 'create' || !req?.pathname || !FIRST_REGISTER.test(req.pathname)) {return args}
|
||||
const slug = collection.slug
|
||||
const allowed = Array.isArray(option) ? option.includes(slug) : slug === req.payload.config.admin?.user
|
||||
if (allowed) {return args}
|
||||
// a collection that lets a visitor sign up anyway may keep its first-user route
|
||||
let open = false
|
||||
try {
|
||||
open = Boolean(await collection.access?.create?.({ data: (args as { data?: unknown }).data, req: { ...req, user: null } } as never))
|
||||
} catch {
|
||||
open = false
|
||||
}
|
||||
if (!open) {throw new Forbidden(req.t)}
|
||||
return args
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds the guard to every auth collection (it lets the allowed ones through itself). `'all'` adds nothing. */
|
||||
export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption = 'panel'): Config {
|
||||
if (option === 'all') {return config}
|
||||
if (option !== 'panel' && !Array.isArray(option)) {
|
||||
throw new Error(`[ipal] accounts.firstUserRoute must be 'panel', 'all' or a list of collection slugs, got ${JSON.stringify(option)}.`)
|
||||
}
|
||||
const guard = buildFirstUserGuard(option)
|
||||
return {
|
||||
...config,
|
||||
collections: (config.collections ?? []).map((collection) =>
|
||||
collection.auth ? { ...collection, hooks: { ...collection.hooks, beforeOperation: [guard, ...(collection.hooks?.beforeOperation ?? [])] } } : collection,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Auth collections whose `create` rule lets an anonymous request through — open sign-up.
|
||||
* For the doctor (slugs only). A rule that throws, or needs more than `{ req }`, counts as closed.
|
||||
*/
|
||||
export async function openSignUpCollections(payload: { collections: Record<string, { config: { access?: { create?: Access }; auth?: unknown; slug: string } }> }): Promise<string[]> {
|
||||
const open: string[] = []
|
||||
for (const { config } of Object.values(payload.collections ?? {})) {
|
||||
if (!config.auth) {continue}
|
||||
try {
|
||||
if (await config.access?.create?.({ req: { payload, user: null } } as never)) {open.push(config.slug)}
|
||||
} catch {
|
||||
/* closed */
|
||||
}
|
||||
}
|
||||
return open.sort()
|
||||
}
|
||||
@@ -13,6 +13,23 @@ export type Role = (typeof ROLE_HIERARCHY)[number]
|
||||
* where they apply; each one has its own switch, `accounts: false` turns them all off.
|
||||
*/
|
||||
export type AccountsOptions = {
|
||||
/**
|
||||
* Only an admin creates accounts in a staff collection (the one the panel
|
||||
* logs in with, `access.authCollection`, `access.staffCollections`) — also
|
||||
* in the project's own collection, where Payload's default would let any
|
||||
* logged-in account do it. A `create` rule the project wrote stays.
|
||||
* `false` = Payload's default on collections without a rule, as before.
|
||||
*/
|
||||
adminOnlyCreate?: false
|
||||
/**
|
||||
* Which auth collections Payload's first-user route
|
||||
* (`POST /api/<slug>/first-register`) answers for while they are empty.
|
||||
* Default `'panel'`: only the collection the panel logs in with — the
|
||||
* first account of a site, which becomes admin. A list of slugs = those.
|
||||
* `'all'` = Payload's behaviour (every empty auth collection). A collection
|
||||
* whose own `create` rule allows an anonymous request keeps its route.
|
||||
*/
|
||||
firstUserRoute?: 'all' | 'panel' | string[]
|
||||
/**
|
||||
* The lowest role that may open the admin panel. Default `'editor'`: an
|
||||
* account that holds only `user` (the default role of a new account) sees
|
||||
|
||||
@@ -157,6 +157,19 @@ export const securityRules: DoctorRule[] = [
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// An auth collection anyone can register in. Often exactly what the project wants (customers) — said, not judged.
|
||||
id: 'open-signup',
|
||||
check: (ctx) =>
|
||||
(ctx.deep?.openSignUp ?? []).map((slug) => ({
|
||||
fix: `intended (a customer zone)? silence it with a reason in ipal-doctor.json; otherwise give "${slug}" a create rule`,
|
||||
message: `sign-up is open on "${slug}": an anonymous request can create an account there`,
|
||||
severity: 'info' as const,
|
||||
})),
|
||||
docs: 'docs/access.md',
|
||||
group: 'security',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// Turnstile lets submissions through while it is misconfigured or Cloudflare fails ("degraded") — visible here.
|
||||
id: 'turnstile-degraded',
|
||||
|
||||
@@ -5,6 +5,7 @@ import { readFileSync } from 'node:fs'
|
||||
|
||||
import type { DoctorStatus } from './types.js'
|
||||
|
||||
import { openSignUpCollections } from '../access/selfRegistration.js'
|
||||
import { countPendingCookies } from '../consent/scanner/approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
|
||||
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
|
||||
@@ -61,7 +62,13 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
/* the global cannot be read: unknown */
|
||||
}
|
||||
}
|
||||
return { node: process.version, pendingCookies, plugin: pluginVersion(), turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
|
||||
let openSignUp: null | string[] = null
|
||||
try {
|
||||
openSignUp = await openSignUpCollections(payload as never)
|
||||
} catch {
|
||||
openSignUp = null
|
||||
}
|
||||
return { node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
|
||||
}
|
||||
|
||||
export type DoctorEndpointOptions = {
|
||||
|
||||
@@ -61,6 +61,8 @@ export type DoctorStatus = {
|
||||
/** null = not compared (the endpoint cannot read files). */
|
||||
importMapCurrent?: boolean | null
|
||||
node?: string
|
||||
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
|
||||
openSignUp?: null | string[]
|
||||
pendingCookies?: null | number
|
||||
plugin?: string
|
||||
/** The Turnstile integration's recorded state (Site integrations): never a key, only the state. null = not known. */
|
||||
|
||||
@@ -14,6 +14,7 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
|
||||
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
||||
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
|
||||
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
|
||||
import { applyAdminOnlyCreate, applyFirstUserRoute } from './modules/access/selfRegistration.js'
|
||||
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
|
||||
import { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
|
||||
import { buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
|
||||
@@ -565,6 +566,13 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
panelRoleFor = { slug: rolesSlug, role: panelRole }
|
||||
}
|
||||
}
|
||||
// Account rules (accounts.*): nobody creates an account for themselves.
|
||||
if (accounts) {
|
||||
const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
|
||||
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
|
||||
if (accounts.adminOnlyCreate !== false) {config = applyAdminOnlyCreate(config, staffSlugs)}
|
||||
config = applyFirstUserRoute(config, accounts.firstUserRoute)
|
||||
}
|
||||
// For predicates called without `req.payload` (isAdmin(req.user) in a hook): what this config
|
||||
// says now, under a token; the Payload instance takes the entry over when the config goes live
|
||||
// (adoptConfig), with `admin.user` as Payload resolved it.
|
||||
|
||||
+129
-3
@@ -11,6 +11,7 @@ import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
|
||||
import { buildFirstUserGuard, openSignUpCollections, staffCreateAccess } from '../src/modules/access/selfRegistration.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
@@ -40,11 +41,12 @@ beforeAll(async () => {
|
||||
collections: [
|
||||
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
|
||||
{ slug: 'members', auth: true, fields: [] },
|
||||
{ slug: 'staff2', auth: true, fields: [] }, // a second staff collection, without roles and without rules
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
|
||||
],
|
||||
db: testDatabase('accounts'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })],
|
||||
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, i18n, twoFactor: false })],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
@@ -57,6 +59,64 @@ afterAll(async () => {
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
// The owner's rule: nobody creates an account for themselves; only the first account of a site, as admin.
|
||||
describe('no self-registration (accounts.adminOnlyCreate, accounts.firstUserRoute)', () => {
|
||||
const rolesOf = async (email: string) => ((await payload.find({ collection: 'users' as never, where: { email: { equals: email } } })).docs[0] as { roles?: string[] } | undefined)?.roles
|
||||
const count = async (collection: string) => (await payload.count({ collection: collection as never })).totalDocs
|
||||
|
||||
test('an empty site: an anonymous request creates no staff account, over REST or GraphQL', async () => {
|
||||
expect((await post('/users', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
|
||||
expect((await post('/users', { email: '[email protected]', password: PASSWORD, roles: ['admin'] })).status).toBe(403)
|
||||
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
|
||||
const gql = (await (await post('/graphql', { query: `mutation { createUser(data: { email: "[email protected]", password: "${PASSWORD}", roles: [admin] }) { id } }` })).json()) as { errors?: unknown[] }
|
||||
expect(gql.errors?.length).toBeGreaterThan(0)
|
||||
expect(await count('users')).toBe(0)
|
||||
expect(await count('staff2')).toBe(0)
|
||||
})
|
||||
|
||||
test("the first-user route of other empty auth collections is closed — a second STAFF collection included", async () => {
|
||||
// before: 200 for each of them while empty; a first account in `staff2` would have been staff
|
||||
expect((await post('/staff2/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
|
||||
expect((await post('/members/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
|
||||
expect(await count('staff2')).toBe(0)
|
||||
expect(await count('members')).toBe(0)
|
||||
})
|
||||
|
||||
test('a collection that allows sign-up keeps its routes', async () => {
|
||||
expect((await post('/customers/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(200)
|
||||
expect((await post('/customers', { email: '[email protected]', password: PASSWORD })).status).toBe(201)
|
||||
expect((await post('/members', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
|
||||
})
|
||||
|
||||
test('the first account of the site registers through the first-user route and is an admin; the route then closes', async () => {
|
||||
const first = await post('/users/first-register', { email: '[email protected]', password: PASSWORD, roles: ['user'] })
|
||||
expect(first.status).toBe(200)
|
||||
expect(await rolesOf('[email protected]')).toEqual(['admin'])
|
||||
expect((await post('/users/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
|
||||
expect(await rolesOf('[email protected]')).toBeUndefined()
|
||||
expect((await post('/users', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
|
||||
})
|
||||
|
||||
test('only an admin creates staff accounts — not an editor, not a plain user, not asking for a role', async () => {
|
||||
await make('users', { email: '[email protected]', roles: ['editor'] })
|
||||
await make('users', { email: '[email protected]', roles: ['user'] })
|
||||
for (const who of ['[email protected]', '[email protected]']) {
|
||||
const session = await login('users', who)
|
||||
expect([who, (await post('/users', { email: `by-${who}`, password: PASSWORD, roles: ['admin'] }, session)).status]).toEqual([who, 403])
|
||||
expect([who, (await post('/staff2', { email: `by-${who}`, password: PASSWORD }, session)).status]).toEqual([who, 403])
|
||||
}
|
||||
const admin = await login('users', '[email protected]')
|
||||
expect((await post('/users', { email: '[email protected]', password: PASSWORD, roles: ['editor'] }, admin)).status).toBe(201)
|
||||
expect(await rolesOf('[email protected]')).toEqual(['editor'])
|
||||
// an admin of the panel's collection makes the first account of the second staff collection
|
||||
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, admin)).status).toBe(201)
|
||||
// a visitor account is nobody here
|
||||
const visitor = await login('customers', '[email protected]')
|
||||
expect((await post('/users', { email: '[email protected]', password: PASSWORD }, visitor)).status).toBe(403)
|
||||
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, visitor)).status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the lowest role stays out of the admin panel (accounts.panelRole)', () => {
|
||||
const canAccessAdmin = async (session: Session) => Boolean(((await (await call('/access', session)).json()) as { canAccessAdmin?: boolean }).canAccessAdmin)
|
||||
|
||||
@@ -82,8 +142,11 @@ describe('the lowest role stays out of the admin panel (accounts.panelRole)', ()
|
||||
})
|
||||
|
||||
test('the start-up count: how many accounts are below the panel role', async () => {
|
||||
expect(await countBelowPanelRole(payload, 'users', 'editor')).toEqual({ all: 3, below: 1 })
|
||||
expect(await countBelowPanelRole(payload, 'users', 'admin')).toEqual({ all: 3, below: 2 })
|
||||
const all = (await payload.find({ collection: 'users' as never, limit: 100 })).docs as unknown as { roles?: string[] }[]
|
||||
const has = (role: string) => all.filter((u) => u.roles?.includes(role)).length
|
||||
expect(await countBelowPanelRole(payload, 'users', 'editor')).toEqual({ all: all.length, below: all.length - has('admin') - has('editor') })
|
||||
expect(await countBelowPanelRole(payload, 'users', 'admin')).toEqual({ all: all.length, below: all.length - has('admin') })
|
||||
expect(has('user')).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -130,3 +193,66 @@ describe('accounts.panelRole: the config', () => {
|
||||
expect(ask({ collection: 'users', roles: ['editor'] }, 'admin')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('accounts.adminOnlyCreate / firstUserRoute: the config', () => {
|
||||
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
|
||||
ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, i18n, twoFactor: false, ...options } as never)({
|
||||
collections: [{ slug: 'staff2', auth: true, fields: [] }, { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, { slug: 'pages', fields: [] }],
|
||||
secret: 'x',
|
||||
...incoming,
|
||||
} as unknown as Config)
|
||||
const of = (config: Config, slug: string) => config.collections!.find((c) => c.slug === slug)!
|
||||
|
||||
test('staff collections without a create rule get the admin rule; a rule the project wrote stays; other collections are not touched', async () => {
|
||||
const config = await build({})
|
||||
expect(of(config, 'staff2').access?.create).toBe(staffCreateAccess)
|
||||
expect(of(config, 'users').access?.create).toBeTypeOf('function') // the injected collection had adminOnly already
|
||||
expect(String(of(config, 'customers').access?.create)).toContain('true')
|
||||
expect(of(config, 'pages').access?.create).toBeUndefined()
|
||||
const mine = () => true
|
||||
const own = await build({}, { collections: [{ slug: 'users', access: { create: mine }, auth: true, fields: [] }, { slug: 'staff2', auth: true, fields: [] }] } as never)
|
||||
expect(of(own, 'users').access?.create).toBe(mine)
|
||||
const ownNoRule = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
|
||||
expect(of(ownNoRule, 'users').access?.create).toBe(staffCreateAccess)
|
||||
})
|
||||
|
||||
test('the switches', async () => {
|
||||
const guards = (config: Config, slug: string) => of(config, slug).hooks?.beforeOperation?.length ?? 0
|
||||
const on = await build({})
|
||||
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([1, 1, 1, 0])
|
||||
const payloadWay = await build({ accounts: { adminOnlyCreate: false, firstUserRoute: 'all' } })
|
||||
expect(of(payloadWay, 'staff2').access?.create).toBeUndefined()
|
||||
expect(guards(payloadWay, 'staff2')).toBe(0)
|
||||
const off = await build({ accounts: false })
|
||||
expect(of(off, 'staff2').access?.create).toBeUndefined()
|
||||
expect(guards(off, 'users')).toBe(0)
|
||||
await expect(build({ accounts: { firstUserRoute: 'everyone' } })).rejects.toThrow(/firstUserRoute must be/)
|
||||
// without `access` the rules still apply to the panel's login collection
|
||||
const noAccess = await ipalKit({ i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config)
|
||||
expect(of(noAccess, 'users').access?.create).toBe(staffCreateAccess)
|
||||
})
|
||||
|
||||
test('the first-user guard: the panel collection, a named list, an open collection; nothing else is touched', async () => {
|
||||
const run = (option: 'panel' | string[], slug: string, create: ((a: { req: { user: unknown } }) => unknown) | undefined, pathname = `/api/${slug}/first-register`, operation = 'create') =>
|
||||
buildFirstUserGuard(option)({ args: { data: {} }, collection: { slug, access: { create } }, operation, req: { pathname, payload: { config: { admin: { user: 'users' } } }, t: (k: string) => k, user: null } } as never)
|
||||
await expect(run('panel', 'users', undefined)).resolves.toBeDefined()
|
||||
await expect(run('panel', 'staff2', ({ req }) => Boolean(req.user))).rejects.toThrow()
|
||||
await expect(run('panel', 'customers', () => true)).resolves.toBeDefined() // sign-up is open there anyway
|
||||
await expect(run('panel', 'members', () => { throw new Error('boom') })).rejects.toThrow() // a rule that fails is closed
|
||||
await expect(run(['staff2'], 'staff2', undefined)).resolves.toBeDefined()
|
||||
await expect(run(['staff2'], 'users', undefined)).rejects.toThrow() // a list replaces the default
|
||||
// any other create, and any other operation, is none of its business
|
||||
await expect(run('panel', 'staff2', undefined, '/api/staff2')).resolves.toBeDefined()
|
||||
await expect(run('panel', 'staff2', undefined, '/api/staff2/first-register', 'update')).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
test('openSignUpCollections: slugs of auth collections an anonymous request may create in', async () => {
|
||||
const collections = {
|
||||
customers: { config: { slug: 'customers', access: { create: () => true }, auth: true } },
|
||||
members: { config: { slug: 'members', access: { create: ({ req }: { req: { user: unknown } }) => Boolean(req.user) }, auth: true } },
|
||||
pages: { config: { slug: 'pages', access: { create: () => true } } },
|
||||
weird: { config: { slug: 'weird', access: { create: () => { throw new Error('x') } }, auth: true } },
|
||||
}
|
||||
expect(await openSignUpCollections({ collections } as never)).toEqual(['customers'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* `accounts: false` — Payload's own behaviour, which the M1 account rules replace by default. Kept as a test
|
||||
* for two reasons: the switch must really give it back, and it records what the rules close, including the
|
||||
* case the first check did not cover (an empty second staff collection).
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
|
||||
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { startPayloadServer, type TestServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const PASSWORD = 'short1' // also: no password rule with accounts: false
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
const post = (pathname: string, body: unknown, headers: Record<string, string> = {}) =>
|
||||
fetch(`${server.url}/api${pathname}`, { body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method: 'POST' })
|
||||
const login = async (collection: string, email: string) => ({ authorization: `JWT ${((await (await post(`/${collection}/login`, { email, password: PASSWORD })).json()) as { token: string }).token}` })
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] }, // the project's own staff collection, no access rules
|
||||
{ slug: 'staff2', auth: true, fields: [] },
|
||||
{ slug: 'members', auth: true, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
|
||||
],
|
||||
db: testDatabase('accounts_off'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, accounts: false, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config)
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
test('an empty second staff collection: its first-user route makes the first visitor a staff admin', async () => {
|
||||
const res = await post('/staff2/first-register', { email: '[email protected]', password: PASSWORD })
|
||||
expect(res.status).toBe(200)
|
||||
// `staff2` has no roles field, so every account of it is an admin to the plugin: the secrets global opens
|
||||
const session = await login('staff2', '[email protected]')
|
||||
const integrations = await fetch(`${server.url}/api/globals/site-integrations`, { headers: session })
|
||||
expect(integrations.status).toBe(200)
|
||||
expect((await post('/globals/site-integrations', { smtpHost: 'changed-by-the-first-visitor.example.com' }, session)).status).toBe(200)
|
||||
})
|
||||
|
||||
test("Payload's first-user route answers for every empty auth collection", async () => {
|
||||
expect((await post('/members/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(200)
|
||||
})
|
||||
|
||||
test("the project's own staff collection without a create rule: any signed-in account makes accounts", async () => {
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['user'] } as never })
|
||||
const plain = await login('users', '[email protected]')
|
||||
const made = await post('/users', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, plain)
|
||||
expect(made.status).toBe(201)
|
||||
const doc = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0] as unknown as { roles: string[] }
|
||||
expect(doc.roles).toEqual(['user']) // the roles field still refuses the requested admin
|
||||
// and the plain user may open the panel
|
||||
const access = (await (await fetch(`${server.url}/api/access`, { headers: plain })).json()) as { canAccessAdmin?: boolean }
|
||||
expect(access.canAccessAdmin).toBe(true)
|
||||
})
|
||||
+9
-1
@@ -181,6 +181,14 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
|
||||
expect(await run(cfg, ['turnstile-env-key'])).toEqual([])
|
||||
})
|
||||
|
||||
test('open-signup: an auth collection anyone can register in is said, as info', async () => {
|
||||
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
|
||||
expect(await run(cfg, ['open-signup'], { openSignUp: ['customers', 'members'] })).toEqual(['open-signup:info', 'open-signup:info'])
|
||||
expect(await run(cfg, ['open-signup'], { openSignUp: [] })).toEqual([])
|
||||
expect(await run(cfg, ['open-signup'], { openSignUp: null })).toEqual([])
|
||||
expect(await run(cfg, ['open-signup'])).toEqual([])
|
||||
})
|
||||
|
||||
test('the deep status reports the state and where the secret comes from, never a key', async () => {
|
||||
vi.stubEnv('TURNSTILE_SECRET_KEY', 'env-secret-value')
|
||||
const fake = (integrations: object) => ({
|
||||
@@ -481,7 +489,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', 'pendingCookies', 'plugin', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
|
||||
expect(Object.keys(status).sort()).toEqual(['node', 'openSignUp', 'pendingCookies', 'plugin', '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 () => {
|
||||
|
||||
Reference in New Issue
Block a user