Security: staff checks only for staff collections; 2FA covers what the plugin adds
Staff check (userMeetsRole): the 'no roles field = every account passes' rule applied to the account's own collection, so an account of a second auth collection (customers) passed every staff check. It now applies only to staff collections: the panel's login collection plus the new access.staffCollections. The injected auth collection uses the new adminOrSelfIn(slug), so an account of another collection with the same numeric id is not 'self'. 2FA: @clocklimited/payload-2fa wraps the collections and globals present when it runs; ipalKit's own globals and collections were added later and stayed unwrapped, so a password without the TOTP code opened them over REST and GraphQL. ipal-kit now has its own second-factor check (secondFactorPassed / requireSecondFactor): applied to every collection and global at the end of ipalKit, again in onInit for entities added by plugins listed after it, and inside userMeetsRole and the endpoints that take a project access function. It fails closed: an unrecognised user shape is refused, and startup stops when the injected 2FA plugin lacks the parts the check reads (twoFactor.guard: false opts out). Tests through real HTTP requests (REST and GraphQL) against Payload's route handlers, plus the reference smoke test. Docs, agent guide, skills and the reference skills copy updated; changelog entry without a version. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
bc1045a5b7
commit
0c61ac231b
@@ -20,13 +20,34 @@ export const requireRole =
|
||||
({ req: { user } }) =>
|
||||
hasMinimumRole(user, minimum)
|
||||
|
||||
/** Admins see all; others are constrained to their own document. */
|
||||
/**
|
||||
* Admins see all; others are constrained to their own document.
|
||||
*
|
||||
* It cannot know which collection it guards, so "own document" means "the
|
||||
* document with my id". In a project with a second auth collection use
|
||||
* `adminOrSelfIn(slug)` instead: with numeric ids (Postgres, SQLite) customer
|
||||
* no. 5 would otherwise match staff account no. 5.
|
||||
*/
|
||||
export const adminOrSelf: Access = ({ req: { user } }) => {
|
||||
if (isAdmin(user)) {return true}
|
||||
if (!user) {return false}
|
||||
return { id: { equals: user.id } }
|
||||
}
|
||||
|
||||
/**
|
||||
* `adminOrSelf` for the auth collection `slug`: only an account OF THAT
|
||||
* collection is "self". An account of another auth collection gets nothing.
|
||||
*
|
||||
* { slug: 'users', auth: true, access: { read: adminOrSelfIn('users'), update: adminOrSelfIn('users') } }
|
||||
*/
|
||||
export const adminOrSelfIn =
|
||||
(slug: string): Access =>
|
||||
({ req: { user } }) => {
|
||||
if (isAdmin(user)) {return true}
|
||||
if (!user || (user as { collection?: unknown }).collection !== slug) {return false}
|
||||
return { id: { equals: user.id } }
|
||||
}
|
||||
|
||||
/**
|
||||
* Field-level access (returns boolean only — no Where support).
|
||||
* Use in field `access.read/update`.
|
||||
|
||||
@@ -4,12 +4,13 @@ export {
|
||||
adminOrEditor,
|
||||
adminOrEditorField,
|
||||
adminOrSelf,
|
||||
adminOrSelfIn,
|
||||
authenticated,
|
||||
requireRole,
|
||||
requireRoleField,
|
||||
} from './access.js'
|
||||
export { injectRoles } from './injectRoles.js'
|
||||
export { hasMinimumRole, isAdmin, isEditor, userMeetsRole } from './predicates.js'
|
||||
export { hasMinimumRole, isAdmin, isEditor, staffCollectionSlugs, userMeetsRole } from './predicates.js'
|
||||
export { buildRolesField } from './rolesField.js'
|
||||
export type { AccessOption, Role } from './types.js'
|
||||
export { ROLE_HIERARCHY } from './types.js'
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
|
||||
|
||||
import type { Role } from './types.js'
|
||||
|
||||
import { secondFactorPassed } from '../security/totp/secondFactor.js'
|
||||
import { ROLE_HIERARCHY } from './types.js'
|
||||
|
||||
/**
|
||||
@@ -45,23 +46,45 @@ export function isEditor(user: MaybeUser): boolean {
|
||||
return hasMinimumRole(user, 'editor')
|
||||
}
|
||||
|
||||
/**
|
||||
* The auth collections whose accounts are staff: the one the admin panel logs
|
||||
* in with (`admin.user`) plus `access.staffCollections`. Accounts of any other
|
||||
* auth collection — customers, members — are visitors to the plugin.
|
||||
*/
|
||||
export function staffCollectionSlugs(payload?: Pick<BasePayload, 'config'>): string[] {
|
||||
const config = payload?.config
|
||||
if (!config) {return []}
|
||||
const extra = (config.custom as { ipal?: { staffCollections?: string[] } } | undefined)?.ipal?.staffCollections ?? []
|
||||
return [...new Set([config.admin?.user, ...extra].filter((s): s is string => typeof s === 'string' && s !== ''))]
|
||||
}
|
||||
|
||||
/**
|
||||
* Role check for the plugin's own staff features (Site Integrations, the
|
||||
* e-mail test, stats, consent records, form submissions, the settings
|
||||
* globals): true when the user holds at least `minimum` — or, when the
|
||||
* user's auth collection has no `roles` field (the project omitted `access`),
|
||||
* for every logged-in user. Without roles all accounts are equal, as in
|
||||
* Payload's own default; nobody being "admin" would lock those features away.
|
||||
* globals). True when the user holds at least `minimum`.
|
||||
*
|
||||
* Pass `req` (it has `payload` and `user`). An unknown collection counts as
|
||||
* having roles — the strict side. A project with its own role scheme in
|
||||
* another field narrows access through globalOverrides / collection overrides.
|
||||
* Without roles: when the user belongs to a STAFF collection (the panel's
|
||||
* login collection, or one named in `access.staffCollections`) and that
|
||||
* collection has no `roles` field (the project omitted `access`), every
|
||||
* account of it passes — without roles all staff accounts are equal, as in
|
||||
* Payload's own default. An account of any other auth collection (a
|
||||
* `customers` collection has no `roles` field either) never passes this way.
|
||||
*
|
||||
* With 2FA on, an account that has TOTP set up and has not entered the code in
|
||||
* this session never passes (secondFactorPassed).
|
||||
*
|
||||
* Pass `req` (it has `payload` and `user`). Without `payload` only a held role
|
||||
* counts — the strict side. A project with its own role scheme in another
|
||||
* field narrows access through globalOverrides / collection overrides.
|
||||
*/
|
||||
export function userMeetsRole({ payload, user }: { payload?: BasePayload; user?: unknown }, minimum: Role): boolean {
|
||||
if (!user || typeof user !== 'object') {return false}
|
||||
if (!secondFactorPassed({ payload, user })) {return false}
|
||||
if (hasMinimumRole(user as MaybeUser, minimum)) {return true}
|
||||
const slug = (user as { collection?: unknown }).collection
|
||||
const fields = typeof slug === 'string' ? payload?.collections?.[slug as never]?.config.fields : undefined
|
||||
if (typeof slug !== 'string' || !staffCollectionSlugs(payload).includes(slug)) {return false}
|
||||
const collection = payload?.collections?.[slug as never]?.config
|
||||
const fields = (collection?.flattenedFields ?? collection?.fields) as Array<{ name?: string }> | undefined
|
||||
if (!fields) {return false}
|
||||
return !fields.some((f) => 'name' in f && f.name === 'roles')
|
||||
return !fields.some((f) => f.name === 'roles')
|
||||
}
|
||||
|
||||
@@ -34,4 +34,14 @@ export type AccessOption = {
|
||||
* `false` = that account gets what was submitted (`defaultRole` by default).
|
||||
*/
|
||||
firstUserAdmin?: boolean
|
||||
/**
|
||||
* More auth collections whose accounts are staff, besides the one the admin
|
||||
* panel logs in with (`admin.user`). Only accounts of a staff collection can
|
||||
* pass the plugin's staff checks (`userMeetsRole`): the settings globals,
|
||||
* Site integrations, form submissions, consent records, stats, the cookie
|
||||
* scanner. A staff collection WITHOUT a `roles` field passes them all (every
|
||||
* account is admin to the plugin); add `buildRolesField()` to it to tell
|
||||
* admins, editors and users apart. Default: none.
|
||||
*/
|
||||
staffCollections?: string[]
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { CookieChange } from './scan.js'
|
||||
import type { CookieScannerOptions, CookieStorage } from './types.js'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
|
||||
import { CONSENT_CATEGORIES } from '../categories.js'
|
||||
import { COOKIE_REVIEW_SLUG } from './collection.js'
|
||||
import { textFor } from './merge.js'
|
||||
@@ -155,7 +156,7 @@ export async function approveCookies({
|
||||
export function buildCookieApprovalEndpoints(options: CookieScannerOptions): Endpoint[] {
|
||||
const approval = typeof options.approval === 'object' ? options.approval : {}
|
||||
const allowed = async (req: PayloadRequest) =>
|
||||
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
return [
|
||||
{
|
||||
handler: async (req) => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { CookieScanLabels } from '../labels.js'
|
||||
import type { CookieCrawlOptions, CookieScanContext, CookieScannerOptions } from '../types.js'
|
||||
|
||||
import { userMeetsRole } from '../../../access/predicates.js'
|
||||
import { secondFactorPassed } from '../../../security/totp/secondFactor.js'
|
||||
import {
|
||||
COOKIE_CRAWL_PATH,
|
||||
COOKIE_CRAWL_RESULTS_PATH,
|
||||
@@ -59,7 +60,7 @@ export function buildCookieCrawlEndpoints({
|
||||
}): Endpoint[] {
|
||||
const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {}
|
||||
const isStaff = async (req: PayloadRequest) =>
|
||||
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
const read = async (req: PayloadRequest) =>
|
||||
(await req.payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0, overrideAccess: true, req })) as CrawlDoc
|
||||
const write = (req: PayloadRequest, data: Partial<CrawlDoc>) =>
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
|
||||
import type { CookieIntegration, CookieScanContext, CookieScannerOptions } from './types.js'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
|
||||
import { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from './integrations.js'
|
||||
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
|
||||
|
||||
@@ -16,7 +17,7 @@ export const COOKIE_SCAN_PATH = '/ipal/cookie-scan'
|
||||
*/
|
||||
export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: CookieScanContext['plugin']): Endpoint[] {
|
||||
const allowed = async (req: PayloadRequest) =>
|
||||
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
|
||||
// Names in the admin language of the editor who asks.
|
||||
const list = (items: CookieIntegration[], req: PayloadRequest) =>
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { DoctorStatus } from './types.js'
|
||||
|
||||
import { countPendingCookies } from '../consent/scanner/approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
|
||||
import { secondFactorPassed } from '../security/totp/secondFactor.js'
|
||||
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
|
||||
|
||||
/** The plugin's own version (package.json next to dist/ and src/). */
|
||||
@@ -67,7 +68,7 @@ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoi
|
||||
const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'ipal-doctor', windowMs: 60_000 })
|
||||
if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })}
|
||||
const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim()
|
||||
const allowed = (given && sameToken(given, token)) || (options.access ? await options.access({ req }) : false)
|
||||
const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && (await options.access({ req })) : false)
|
||||
if (!allowed) {return Response.json({ error: 'Unauthorized' }, { status: 401 })}
|
||||
const status = await collectDoctorStatus(req.payload)
|
||||
return Response.json(status, { headers: { 'cache-control': 'no-store' } })
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payload'
|
||||
|
||||
/**
|
||||
* ipal-kit's own second-factor check, next to the access wrapper of
|
||||
* @clocklimited/payload-2fa.
|
||||
*
|
||||
* Why it exists: the package wraps the `access` functions of the collections
|
||||
* and globals that are in the config at the moment it runs. Whatever is added
|
||||
* afterwards — ipal-kit's globals and collections, a plugin listed after
|
||||
* ipalKit — was left unwrapped, so a staff password without the TOTP code
|
||||
* opened it over the API. This check does not depend on that order: ipalKit
|
||||
* applies it to everything in the config when it finishes, and again in onInit
|
||||
* to whatever other plugins added later; `userMeetsRole` asks it too.
|
||||
*
|
||||
* It fails closed. An account of the 2FA collection passes only when
|
||||
* - it came through the package's `totp` strategy (password AND code), or
|
||||
* - it authenticated with an API key (the package's own rule), or
|
||||
* - TOTP is not set up on it yet (`hasTotp === false`) — the setup screen
|
||||
* needs that, and the package lets such an account through as well.
|
||||
* Anything else — code not entered, or a user object this check does not
|
||||
* understand (a renamed strategy, no `hasTotp`) — is refused.
|
||||
*/
|
||||
|
||||
/** What ipalKit records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */
|
||||
export type TwoFactorGuardConfig = { collection: string }
|
||||
|
||||
type MaybeReq = { payload?: Pick<BasePayload, 'config'>; user?: unknown }
|
||||
|
||||
const guardConfig = (payload: MaybeReq['payload']): TwoFactorGuardConfig | undefined =>
|
||||
(payload?.config?.custom as { ipal?: { twoFactor?: TwoFactorGuardConfig } } | undefined)?.ipal?.twoFactor
|
||||
|
||||
/**
|
||||
* False only for an account that still owes the second factor: it belongs to
|
||||
* the 2FA collection, has TOTP set up and has not entered the code in this
|
||||
* session. True for everyone else — no user (the access function decides),
|
||||
* accounts of other auth collections, 2FA off (`twoFactor: false`).
|
||||
*
|
||||
* Pass `req`. Use it in your own endpoints and access functions:
|
||||
* if (!secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 })
|
||||
*/
|
||||
export function secondFactorPassed({ payload, user }: MaybeReq): boolean {
|
||||
if (!user || typeof user !== 'object') {return true}
|
||||
const guard = guardConfig(payload)
|
||||
if (!guard) {return true}
|
||||
const u = user as { _strategy?: unknown; collection?: unknown; hasTotp?: unknown }
|
||||
if (u.collection !== guard.collection) {return true}
|
||||
if (u._strategy === 'totp' || u._strategy === 'api-key') {return true}
|
||||
return u.hasTotp === false
|
||||
}
|
||||
|
||||
const GUARDED = Symbol.for('ipal.secondFactorGuard')
|
||||
type AnyAccess = (args: never) => unknown
|
||||
type Guarded = { [GUARDED]?: true } & AnyAccess
|
||||
|
||||
/**
|
||||
* Wraps one access function: refused while the second factor is owed,
|
||||
* otherwise the function itself (or Payload's default, "logged in", when there
|
||||
* is none). Wrapping twice is harmless — an already wrapped function is returned as is.
|
||||
*
|
||||
* access: { read: requireSecondFactor(({ req }) => isAdmin(req.user)) }
|
||||
*/
|
||||
export function requireSecondFactor<T extends AnyAccess>(access?: T): T {
|
||||
if (access && (access as Guarded)[GUARDED]) {return access}
|
||||
const wrapped = ((args: { req: MaybeReq }) => {
|
||||
if (!secondFactorPassed(args.req)) {return false}
|
||||
return access ? access(args as never) : Boolean(args.req?.user)
|
||||
}) as unknown as Guarded
|
||||
wrapped[GUARDED] = true
|
||||
return wrapped as unknown as T
|
||||
}
|
||||
|
||||
/** `admin` (may this account open the panel) stays unwrapped: the code is entered inside the panel. */
|
||||
const COLLECTION_OPERATIONS = ['create', 'delete', 'read', 'readVersions', 'unlock', 'update'] as const
|
||||
const GLOBAL_OPERATIONS = ['read', 'readDrafts', 'readVersions', 'update'] as const
|
||||
|
||||
type AccessMap = Record<string, AnyAccess | undefined>
|
||||
|
||||
function guardAccessMap(access: AccessMap | undefined, operations: readonly string[]): AccessMap {
|
||||
const out: AccessMap = { ...access }
|
||||
for (const op of operations) {out[op] = requireSecondFactor(out[op])}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Every collection and global of a (not yet sanitized) config, guarded. Returns a new config. */
|
||||
export function guardConfigAccess(config: Config): Config {
|
||||
return {
|
||||
...config,
|
||||
collections: (config.collections ?? []).map(
|
||||
(c) => ({ ...c, access: guardAccessMap(c.access as AccessMap | undefined, COLLECTION_OPERATIONS) }) as CollectionConfig,
|
||||
),
|
||||
globals: (config.globals ?? []).map(
|
||||
(g) => ({ ...g, access: guardAccessMap(g.access as AccessMap | undefined, GLOBAL_OPERATIONS) }) as GlobalConfig,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The same for a running Payload, in place: what plugins listed after ipalKit
|
||||
* added. Called from ipalKit's onInit; returns the slugs it had to guard.
|
||||
*/
|
||||
export function guardPayloadAccess(payload: BasePayload): string[] {
|
||||
const late: string[] = []
|
||||
const sweep = (entity: { access?: unknown; slug: string }, operations: readonly string[]) => {
|
||||
const access = (entity.access ?? {}) as AccessMap
|
||||
if (operations.every((op) => (access[op] as Guarded | undefined)?.[GUARDED])) {return}
|
||||
late.push(entity.slug)
|
||||
entity.access = guardAccessMap(access, operations)
|
||||
}
|
||||
// Payload's own collections (payload-preferences, payload-locked-documents, …) keep their rules:
|
||||
// the panel uses them before the code is entered, and the package leaves them alone too.
|
||||
for (const c of payload.config.collections ?? []) {
|
||||
if (!c.slug.startsWith('payload-')) {sweep(c, COLLECTION_OPERATIONS)}
|
||||
}
|
||||
for (const g of payload.config.globals ?? []) {sweep(g, GLOBAL_OPERATIONS)}
|
||||
return late
|
||||
}
|
||||
|
||||
/**
|
||||
* The parts of @clocklimited/payload-2fa the guard relies on, checked right
|
||||
* after the injected factory ran. A missing part means a version this guard
|
||||
* was not written for: it would refuse every staff request, or — worse — the
|
||||
* package itself may no longer protect what it used to. Returns what is
|
||||
* missing; ipalKit refuses to start with it.
|
||||
*/
|
||||
export function missingTotpParts(config: Config, collection: string): string[] {
|
||||
const target = (config.collections ?? []).find((c) => c.slug === collection)
|
||||
const fields = (target?.fields ?? []) as Array<{ name?: string }>
|
||||
const strategies = typeof target?.auth === 'object' ? (target.auth.strategies ?? []) : []
|
||||
const missing: string[] = []
|
||||
if (!fields.some((f) => f.name === 'totpSecret')) {missing.push('the `totpSecret` field')}
|
||||
if (!fields.some((f) => f.name === 'hasTotp')) {missing.push('the `hasTotp` field')}
|
||||
if (!strategies.some((s) => s.name === 'totp')) {missing.push('the `totp` auth strategy')}
|
||||
return missing
|
||||
}
|
||||
Reference in New Issue
Block a user