Files
ipal-kit/src/modules/security/queryGuard.ts
T

144 lines
7.1 KiB
TypeScript

import type { Access, CollectionBeforeOperationHook, CollectionConfig, Config, PayloadRequest, SanitizedConfig } from 'payload'
import { APIError } from 'payload'
import { staffCollectionSlugs } from '../access/predicates.js'
import { secondFactorPassed } from './totp/secondFactor.js'
/**
* Guards for what a REST / GraphQL caller may ask of a collection list (security audit 2026-12, F4 and F5), and
* Payload's document locks closed to visitor accounts (the "document locks" door). Each is on by default, each can be
* turned off or adapted, and every piece is exported for a project's own use (docs/security.md "Lists and sorting").
*
* Local API calls (`req.payloadAPI === 'local'`: the frontend, seeds, the project's own code) are never touched.
*/
export type ListLimitOptions = {
/** Collections left as Payload has them (their lists take any `limit`). */
exclude?: string[]
/** Largest page a caller that is not staff gets. Default 100. */
max?: number
/** Cap staff accounts too (the panel asks for at most 100 per page itself). Default false. */
staff?: boolean
}
export const DEFAULT_LIST_LIMIT = 100
type HookArgs = Parameters<CollectionBeforeOperationHook>[0]
type ListArgs = { id?: unknown; limit?: number | string; pagination?: boolean | string; sort?: unknown }
const fromOutside = (req: PayloadRequest | undefined): boolean =>
Boolean(req) && (req as { payloadAPI?: string }).payloadAPI !== 'local'
/** True when the request's account belongs to a staff collection (any role). */
export function isStaffRequest(req: Pick<PayloadRequest, 'payload' | 'user'> | undefined): boolean {
const slug = (req?.user as { collection?: unknown } | null | undefined)?.collection
return typeof slug === 'string' && staffCollectionSlugs(req?.payload).includes(slug)
}
/**
* The list arguments with `limit` at most `max` and pagination on — what a caller that is not staff gets. Pure: the
* hook below calls it, a project's own endpoint can too.
*/
export function capListLimit<T extends ListArgs>(args: T, max: number = DEFAULT_LIST_LIMIT): T {
// REST hands the query string over as text: '100000', 'false'
const raw = typeof args.limit === 'string' && (args.limit).trim() !== '' ? Number(args.limit) : args.limit
const limit = typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined
const noPages = args.pagination === false || (args.pagination as unknown) === 'false'
// pagination: false and limit 0 both mean "everything" to Payload
if (noPages || limit === 0 || (limit !== undefined && limit > max)) {
return { ...args, limit: limit && limit > 0 ? Math.min(limit, max) : max, pagination: true }
}
return args
}
/** A sort field that names a database operator (`$where`, `-$natural`, `title.$ne`): never a field of a document. */
export function isOperatorSort(sort: unknown): boolean {
const names = Array.isArray(sort) ? sort : typeof sort === 'string' ? sort.split(',') : []
return names.some((n) => typeof n === 'string' && /(?:^-?|\.)\$/.test(n.trim()))
}
/**
* The 400 for an operator sort name. Its own name so Payload logs it as one `info` line without a stack (the plugin
* sets `loggingLevels.RefusedSortError: 'info'` unless the project set it; `false` logs nothing).
*/
export class RefusedSortError extends APIError {
constructor() {
super('This sort field is not allowed.', 400, null, true)
this.name = 'RefusedSortError'
}
}
/** Marks the hook {@link buildQueryGuardHook} made, like the plugin's other hooks (`Symbol.for('iapl.…')`). */
export const QUERY_GUARD_MARK = Symbol.for('iapl.queryGuard')
const LIST_OPERATIONS = new Set(['findVersions', 'read', 'readDistinct'])
/**
* One `beforeOperation` hook for lists from outside: refuses a database operator as a sort field with 400 (instead of
* a 500 and a logged stack trace, F5) and caps `limit` for callers that are not staff (F4). `listLimit: false` or
* `refuseOperatorSort: false` turns that half off.
*/
export function buildQueryGuardHook(options: {
listLimit?: false | ListLimitOptions
refuseOperatorSort?: boolean
}): CollectionBeforeOperationHook {
const limit = options.listLimit === false ? null : { max: DEFAULT_LIST_LIMIT, staff: false, ...options.listLimit }
const refuseSort = options.refuseOperatorSort !== false
const iaplQueryGuard = (({ args, collection, operation, req }: HookArgs) => {
if (!LIST_OPERATIONS.has(operation) || !fromOutside(req)) {return args}
const list = args as ListArgs
if (refuseSort && isOperatorSort(list.sort)) {
throw new RefusedSortError()
}
if (!limit || list.id != null || limit.exclude?.includes(collection.slug)) {return args}
if (!limit.staff && isStaffRequest(req)) {return args}
return capListLimit(list, limit.max)
}) as CollectionBeforeOperationHook
return Object.assign(iaplQueryGuard, { [QUERY_GUARD_MARK]: true })
}
/** True for a hook {@link buildQueryGuardHook} made: for tests and tools that count a collection's hooks. */
export const isQueryGuardHook = (hook: unknown): boolean => typeof hook === 'function' && Boolean((hook as unknown as Record<symbol, unknown>)[QUERY_GUARD_MARK])
/** The hook added to every collection of the config (the project's, the plugin's, other plugins' before iapl). */
export function applyQueryGuard(
config: Config,
options: { listLimit?: false | ListLimitOptions; refuseOperatorSort?: boolean },
): Config {
if (options.listLimit === false && options.refuseOperatorSort === false) {return config}
const hook = buildQueryGuardHook(options)
return {
...config,
collections: (config.collections ?? []).map((c) => ({
...c,
hooks: { ...c.hooks, beforeOperation: [...(c.hooks?.beforeOperation ?? []), hook] },
})),
// Payload's ErrorName union knows only its own errors; the name is looked up by string at log time
loggingLevels: { ...({ RefusedSortError: 'info' } as NonNullable<Config['loggingLevels']>), ...config.loggingLevels },
}
}
/** Payload's collection of document locks ("who edits what"). */
export const LOCKED_DOCUMENTS_SLUG = 'payload-locked-documents'
/**
* Staff accounts (with their second factor, when 2FA is on) — who edits in the panel. Payload's default for its
* document locks is any signed-in account, so a visitor account (a shop's customers) could read who edits what and
* write or delete locks.
*/
export const staffOnlyLocks: Access = ({ req }) => isStaffRequest(req) && secondFactorPassed({ payload: req.payload, user: req.user })
export type LockedDocumentsAccess = Partial<Pick<NonNullable<CollectionConfig['access']>, 'create' | 'delete' | 'read' | 'update'>>
/**
* Payload adds its document-lock collection after every plugin has run, so its rules are set on the live config
* (onInit and after a dev reload). `access` keys the project gives win; the rest is {@link staffOnlyLocks}.
*/
export function applyLockedDocumentsAccess(config: Pick<SanitizedConfig, 'collections'>, access: LockedDocumentsAccess = {}): boolean {
const locks = config.collections?.find((c) => c.slug === LOCKED_DOCUMENTS_SLUG)
if (!locks) {return false}
locks.access = { ...locks.access, create: staffOnlyLocks, delete: staffOnlyLocks, read: staffOnlyLocks, update: staffOnlyLocks, ...access }
return true
}