M1 review: account rules before 2FA, the SMTP password stays with its server, the rest of the findings
M1-1 the first-user route is the plugin's own endpoint in front of Payload's; nothing is read from the path.
M1-2 the account rules are put on the collections before the 2FA package wraps them.
M1-6 the admin rule only where the roles are the plugin's; other staff collections: an account of that collection.
update / delete get the matching defaults (accounts.adminOnlyWrite); doctor rule staff-accounts-open.
M1-5 access.firstUserAdmin: false with a role below the panel role: the default panel role steps aside, an explicit one is refused.
M1-3 a save that changes the SMTP server, port, user or encryption must send the password again (secrets.reenterOnChange);
new panel field smtpRequireTls.
M1-4 a restore of a version masks the secrets (maskSecretsOnRestore).
M1-7 a refused origin is logged once with the ways to allow it; default ports are normalised.
Minors: m1 day boundary, m3 e-mail check on reset and bulk update, m4 text of 'all', m5 the mask is never kept.
The account suite runs with 2FA off and on.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
81cee02e78
commit
1141c749de
@@ -6,7 +6,7 @@ import { FieldDescription, FieldLabel, useField, useTranslation } from '@payload
|
||||
import { useState } from 'react'
|
||||
|
||||
import { ipalT } from '../../../modules/admin-i18n/t.js'
|
||||
import { SECRET_CLEAR, SECRET_MASK } from '../../../modules/secrets/writeOnly.js'
|
||||
import { SECRET_CLEAR, SECRET_MASK } from '../../../modules/secrets/constants.js'
|
||||
|
||||
/**
|
||||
* Text input for a secret (SMTP password, Turnstile secret key, …).
|
||||
@@ -26,7 +26,7 @@ import { SECRET_CLEAR, SECRET_MASK } from '../../../modules/secrets/writeOnly.js
|
||||
*/
|
||||
export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
|
||||
const { t } = useTranslation()
|
||||
const { setValue, value } = useField<string>({ path })
|
||||
const { errorMessage, setValue, showError, value } = useField<string>({ path })
|
||||
const [revealed, setRevealed] = useState(false)
|
||||
|
||||
// A string or one string per language — FieldLabel / FieldDescription translate it.
|
||||
@@ -68,6 +68,12 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showError && errorMessage ? (
|
||||
<p className="field-description" role="alert" style={{ color: 'var(--theme-error-500)', margin: '.25rem 0 0' }}>
|
||||
{errorMessage}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{stored || removing ? (
|
||||
<p className="field-description" role="status" style={{ margin: '.25rem 0 0' }}>
|
||||
{ipalT(t as never, stored ? 'maskedSet' : 'maskedRemoved')}
|
||||
|
||||
@@ -93,6 +93,19 @@ export const smtpFields: Field[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'smtpRequireTls',
|
||||
type: 'checkbox',
|
||||
admin: {
|
||||
condition: usesSmtp,
|
||||
description: {
|
||||
en: 'The password is sent only over an encrypted connection; without one, no e-mail is sent.',
|
||||
pl: 'Hasło jest wysyłane tylko szyfrowanym połączeniem; bez niego e-mail nie zostanie wysłany.',
|
||||
},
|
||||
},
|
||||
defaultValue: false,
|
||||
label: { en: 'Require encryption', pl: 'Wymagaj szyfrowania' },
|
||||
},
|
||||
{
|
||||
name: 'smtpUser',
|
||||
type: 'text',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Field, GlobalConfig } from 'payload'
|
||||
|
||||
import { userMeetsRole } from '../../modules/access/index.js'
|
||||
import { INTEGRATION_SECRET_FIELDS, writeOnlySecrets } from '../../modules/secrets/writeOnly.js'
|
||||
import { INTEGRATION_SECRET_FIELDS, maskSecretsOnRestore, SMTP_PASSWORD_BOUND_TO, writeOnlySecrets } from '../../modules/secrets/writeOnly.js'
|
||||
import { indexNowFields } from '../../modules/seo/indexNow.js'
|
||||
import { analyticsFields } from './fields/analytics.js'
|
||||
import { smtpFields } from './fields/smtp.js'
|
||||
@@ -10,6 +10,12 @@ import { turnstileFields } from './fields/turnstile.js'
|
||||
type BuildSiteIntegrationsArgs = {
|
||||
/** Extra fields injected by the client project */
|
||||
additionalFields?: Field[]
|
||||
/**
|
||||
* A save in the panel that changes the SMTP server, port, user name, transport or "require
|
||||
* encryption" must send the password again (or remove it). Default true; needs write-only
|
||||
* secrets. `false` = the stored password follows the new server, as before.
|
||||
*/
|
||||
reenterSecretOnChange?: boolean
|
||||
/**
|
||||
* The stored secrets (`smtpPassword`, `turnstileSecretKey`) are write-only: reads through
|
||||
* access control get `SECRET_MASK`, never the value (modules/secrets/writeOnly.ts). Default
|
||||
@@ -32,9 +38,16 @@ type BuildSiteIntegrationsArgs = {
|
||||
*/
|
||||
export function buildSiteIntegrations({
|
||||
additionalFields,
|
||||
reenterSecretOnChange = true,
|
||||
writeOnlySecrets: writeOnly = true,
|
||||
}: BuildSiteIntegrationsArgs = {}): GlobalConfig {
|
||||
const secret = (fields: Field[]) => (writeOnly ? writeOnlySecrets(fields, INTEGRATION_SECRET_FIELDS) : fields)
|
||||
const secret = (fields: Field[]) =>
|
||||
writeOnly ? writeOnlySecrets(fields, INTEGRATION_SECRET_FIELDS, reenterSecretOnChange
|
||||
? {
|
||||
// not when the save switches to Microsoft Graph: the password is not used there, and its field is hidden
|
||||
smtpPassword: { appliesWhen: (data) => data.emailTransport !== 'graph', boundTo: SMTP_PASSWORD_BOUND_TO },
|
||||
}
|
||||
: {}) : fields
|
||||
return {
|
||||
slug: 'site-integrations',
|
||||
access: {
|
||||
@@ -69,6 +82,8 @@ export function buildSiteIntegrations({
|
||||
},
|
||||
],
|
||||
hooks: {
|
||||
// a restore answers with the version document: the secrets are masked there too
|
||||
...(writeOnly ? { afterRead: [maskSecretsOnRestore] } : {}),
|
||||
beforeChange: [
|
||||
// Keys edited in the panel → clear that integration's old status, so a stale
|
||||
// "not working" banner doesn't linger until the next form submission.
|
||||
|
||||
+17
-2
@@ -24,7 +24,17 @@ export {
|
||||
export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js'
|
||||
export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWORD_MIN_LENGTH, resolvePasswordRule } from './modules/access/passwordRule.js'
|
||||
export type { PasswordRuleOptions } from './modules/access/passwordRule.js'
|
||||
export { applyAdminOnlyCreate, applyFirstUserRoute, buildFirstUserGuard, openSignUpCollections, staffCreateAccess } from './modules/access/selfRegistration.js'
|
||||
export {
|
||||
applyFirstUserRoute,
|
||||
applyStaffAccountAccess,
|
||||
buildFirstUserEndpoint,
|
||||
hasPluginRoles,
|
||||
openSignUpCollections,
|
||||
sameStaffCollectionAccess,
|
||||
staffCollectionsOpenToOthers,
|
||||
staffCreateAccess,
|
||||
staffUpdateAccess,
|
||||
} from './modules/access/selfRegistration.js'
|
||||
export type { FirstUserRouteOption } from './modules/access/selfRegistration.js'
|
||||
export type { AccountsOptions } from './modules/access/types.js'
|
||||
// Concrete files, not module barrels: a barrel that also re-exports 'use client'
|
||||
@@ -304,15 +314,20 @@ export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './module
|
||||
// Lexical → Markdown (pure, no React) — for AI-readable output.
|
||||
export { lexicalToMarkdown } from './modules/richtext/lexicalToMarkdown.js'
|
||||
export {
|
||||
buildKeepSecret,
|
||||
INTEGRATION_SECRET_FIELDS,
|
||||
isSecretMask,
|
||||
keepSecretBeforeValidate,
|
||||
maskSecretAfterRead,
|
||||
maskSecretsOnRestore,
|
||||
maskWriteOnlySecrets,
|
||||
SECRET_CLEAR,
|
||||
SECRET_MASK,
|
||||
SMTP_PASSWORD_BOUND_TO,
|
||||
writeOnlySecret,
|
||||
writeOnlySecrets,
|
||||
} from './modules/secrets/writeOnly.js'
|
||||
export type { WriteOnlySecretOptions } from './modules/secrets/writeOnly.js'
|
||||
export {
|
||||
buildAdminCsp,
|
||||
buildAdminCspHeaders,
|
||||
@@ -348,7 +363,7 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit
|
||||
export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
|
||||
export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js'
|
||||
export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js'
|
||||
export { ownOrigins, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
|
||||
export { ownOrigins, reportRefusedOrigin, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
|
||||
export { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js'
|
||||
export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js'
|
||||
export { SETUP_FROM_FIELD } from './modules/security/totp/secondFactor.js'
|
||||
|
||||
@@ -51,23 +51,41 @@ export function buildPasswordRuleHook({ minLength = DEFAULT_PASSWORD_MIN_LENGTH
|
||||
if (operation !== 'create' && operation !== 'update' && operation !== 'resetPassword') {return args}
|
||||
const data = (args as { data?: { email?: unknown; password?: unknown } }).data
|
||||
const password = data?.password
|
||||
if (typeof password !== 'string' || password === '') {return args} // no password in this request: nothing is being set
|
||||
let email = typeof data?.email === 'string' ? data.email : null
|
||||
const id = (args as { id?: number | string }).id
|
||||
if (!email && operation === 'update' && id !== undefined && req?.payload) {
|
||||
try {
|
||||
const doc = (await req.payload.findByID({ id, collection: collection.slug as never, depth: 0, overrideAccess: true, req })) as { email?: unknown }
|
||||
email = typeof doc?.email === 'string' ? doc.email : null
|
||||
} catch {
|
||||
email = null
|
||||
}
|
||||
}
|
||||
const problem = checkPassword(password, { email, minLength })
|
||||
if (problem) {
|
||||
if (password === undefined || password === null || password === '') {return args} // no password in this request: nothing is being set
|
||||
const refuse = (problem: 'email' | 'short'): never => {
|
||||
const i18n = req?.i18n as Parameters<typeof serverText>[0]
|
||||
const message = problem === 'short' ? serverText(i18n, 'passwordTooShort', { min: minLength }) : serverText(i18n, 'passwordIsEmail')
|
||||
throw new ValidationError({ collection: collection.slug, errors: [{ message, path: 'password' }] }, req?.t)
|
||||
}
|
||||
// a number, a list, an object: not a password (it used to end in a server error further on)
|
||||
if (typeof password !== 'string') {return refuse('short')}
|
||||
// The address(es) the password must differ from: the one in the request, else the account(s)
|
||||
// the request is about — by id, by the reset token, or every account a bulk update matches.
|
||||
const emails: string[] = typeof data?.email === 'string' ? [data.email] : []
|
||||
if (!emails.length && req?.payload) {
|
||||
const { id, where } = args as { id?: number | string; where?: unknown }
|
||||
const token = (data as { token?: unknown }).token
|
||||
const query =
|
||||
operation === 'update' && id !== undefined
|
||||
? { id: { equals: id } }
|
||||
: operation === 'update' && where && typeof where === 'object'
|
||||
? where
|
||||
: operation === 'resetPassword' && typeof token === 'string' && token
|
||||
? { resetPasswordToken: { equals: token } }
|
||||
: null
|
||||
if (query) {
|
||||
try {
|
||||
const found = await req.payload.find({ collection: collection.slug as never, depth: 0, limit: 0, overrideAccess: true, pagination: false, req, where: query as never })
|
||||
for (const doc of found.docs as { email?: unknown }[]) {
|
||||
if (typeof doc?.email === 'string') {emails.push(doc.email)}
|
||||
}
|
||||
} catch {
|
||||
/* the account cannot be looked up: the length is still checked */
|
||||
}
|
||||
}
|
||||
}
|
||||
const problem = checkPassword(password, { minLength }) ?? (emails.some((email) => checkPassword(password, { email, minLength }) === 'email') ? 'email' : null)
|
||||
if (problem) {return refuse(problem)}
|
||||
return args
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,10 @@ export function buildRolesField(defaultRole: Role = 'user', { firstUserAdmin = t
|
||||
hooks: {
|
||||
beforeChange: [
|
||||
async ({ collection, operation, req, value }) => {
|
||||
if (operation !== 'create' || !collection || !req.pathname?.endsWith('/first-register')) {return value}
|
||||
// The first-user route: marked by the plugin's own endpoint (selfRegistration.ts); where that is off
|
||||
// (accounts.firstUserRoute: 'all'), by Payload's path, in any letter case — as Payload's router matches it.
|
||||
const first = req.context?.ipalFirstRegister === true || /\/first-register\/?$/i.test(req.pathname ?? '')
|
||||
if (operation !== 'create' || !collection || !first) {return value}
|
||||
const { totalDocs } = await req.payload.count({ collection: collection.slug, overrideAccess: true, req })
|
||||
return totalDocs === 0 ? ['admin'] : value
|
||||
},
|
||||
|
||||
@@ -1,91 +1,161 @@
|
||||
import type { Access, CollectionBeforeOperationHook, Config } from 'payload'
|
||||
import type { Access, CollectionConfig, Config, Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import { Forbidden } from 'payload'
|
||||
|
||||
import { userMeetsRole } from './predicates.js'
|
||||
import { secondFactorPassed } from '../security/totp/secondFactor.js'
|
||||
import { staffCollectionSlugs, userMeetsRole } from './predicates.js'
|
||||
import { ROLE_HIERARCHY } from './types.js'
|
||||
|
||||
/**
|
||||
* Nobody creates an account for themselves.
|
||||
* Nobody creates an account for themselves, and nobody takes one over.
|
||||
*
|
||||
* Two doors, both closed by default (`accounts.adminOnlyCreate`, `accounts.firstUserRoute`):
|
||||
* Payload's defaults for a collection without access rules are "any logged-in user" for
|
||||
* `create`, `update` and `delete` — an account of ANY auth collection. On a project's own
|
||||
* staff collection that let a visitor account (`customers`) create a staff account, or change
|
||||
* a staff account's password and roles. And Payload's first-user route
|
||||
* (`POST /api/<slug>/first-register`) answers for EVERY auth collection while it is empty —
|
||||
* on an empty second staff collection the first visitor became a staff account.
|
||||
*
|
||||
* 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.
|
||||
* Defaults now, for the staff collections (`accounts.adminOnlyCreate`, `accounts.adminOnlyWrite`,
|
||||
* `accounts.firstUserRoute`) — a rule the project wrote always 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 collection whose roles are the plugin's (`roles` with user / editor / admin):
|
||||
* create — an admin; update — an admin, or the account itself; delete — an admin;
|
||||
* - a staff collection with other roles, or none (the plugin cannot tell who its admins
|
||||
* are): an account of that same collection, or a plugin admin of another staff
|
||||
* collection. A visitor account, and an editor of another staff collection, are refused;
|
||||
* - the first-user route answers only for the collection the panel logs in with, unless a
|
||||
* collection's own `create` rule lets an anonymous request through.
|
||||
*
|
||||
* A visitor collection that allows sign-up (`customers` with `create: () => true`) is not
|
||||
* touched by either.
|
||||
* Always "fully signed in": the second factor is part of every one of these rules. They are
|
||||
* put on the collections BEFORE the 2FA package runs, because that package gives every
|
||||
* collection a `create` / `update` / `delete` function of its own (Payload's default, wrapped)
|
||||
* — afterwards a missing rule can no longer be told from one the project wrote.
|
||||
*/
|
||||
|
||||
/** `create` for a staff collection: an admin, fully signed in. */
|
||||
type Staffish = Pick<CollectionConfig, 'fields' | 'slug'>
|
||||
|
||||
/** True when the collection carries the plugin's roles: a top-level `roles` select whose values are all the plugin's. */
|
||||
export function hasPluginRoles(collection: Staffish): boolean {
|
||||
const field = (collection.fields ?? []).find((f) => 'name' in f && f.name === 'roles') as { options?: unknown[]; type?: string } | undefined
|
||||
if (!field || field.type !== 'select' || !Array.isArray(field.options) || !field.options.length) {return false}
|
||||
return field.options.every((option) => ROLE_HIERARCHY.includes((typeof option === 'string' ? option : (option as { value?: unknown })?.value) as never))
|
||||
}
|
||||
|
||||
const collectionOf = (req: PayloadRequest): string | undefined => (req.user as { collection?: string } | null | undefined)?.collection
|
||||
|
||||
/** `create` / `delete` where the roles are the plugin's: 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 {
|
||||
/** `update` where the roles are the plugin's: an admin, or the account itself (fully signed in). */
|
||||
export const staffUpdateAccess =
|
||||
(slug: string): Access =>
|
||||
({ req }) => {
|
||||
if (userMeetsRole(req, 'admin')) {return true}
|
||||
if (!req.user || collectionOf(req) !== slug || !secondFactorPassed(req)) {return false}
|
||||
return { id: { equals: req.user.id } }
|
||||
}
|
||||
|
||||
/**
|
||||
* Any operation on a staff collection whose roles are NOT the plugin's: an account of that same
|
||||
* collection (the project's own roles decide the rest), or a plugin admin of another staff
|
||||
* collection. Never an account of a collection that is not staff.
|
||||
*/
|
||||
export const sameStaffCollectionAccess =
|
||||
(slug: string): Access =>
|
||||
({ req }) => {
|
||||
if (!req.user || !secondFactorPassed(req)) {return false}
|
||||
const from = collectionOf(req)
|
||||
if (from === slug) {return staffCollectionSlugs(req.payload).includes(slug)}
|
||||
return userMeetsRole(req, 'admin')
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the defaults on the named staff collections where the project wrote no rule.
|
||||
* `pluginRoles`: slugs that will carry the plugin's roles although the field is not there yet
|
||||
* (`access.authCollection`, whose field is injected later).
|
||||
*/
|
||||
export function applyStaffAccountAccess(config: Config, staffSlugs: string[], { create = true, pluginRoles = [], write = true }: { create?: boolean; pluginRoles?: string[]; write?: boolean } = {}): Config {
|
||||
if (!create && !write) {return config}
|
||||
return {
|
||||
...config,
|
||||
collections: (config.collections ?? []).map((collection) =>
|
||||
collection.auth && staffSlugs.includes(collection.slug) && !collection.access?.create ? { ...collection, access: { ...collection.access, create: staffCreateAccess } } : collection,
|
||||
),
|
||||
collections: (config.collections ?? []).map((collection) => {
|
||||
if (!collection.auth || !staffSlugs.includes(collection.slug)) {return collection}
|
||||
const ours = pluginRoles.includes(collection.slug) || hasPluginRoles(collection)
|
||||
const other = sameStaffCollectionAccess(collection.slug)
|
||||
const access = { ...collection.access }
|
||||
if (create && !access.create) {access.create = ours ? staffCreateAccess : other}
|
||||
if (write && !access.update) {access.update = ours ? staffUpdateAccess(collection.slug) : other}
|
||||
if (write && !access.delete) {access.delete = ours ? staffCreateAccess : other}
|
||||
return { ...collection, access }
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/** `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\/?$/
|
||||
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.
|
||||
* The plugin's own `POST /first-register` for a collection. It is put in front of Payload's
|
||||
* (a collection's own endpoints are matched before the built-in ones, with the same matcher —
|
||||
* so whatever spelling reaches Payload's route reaches this one first): refuses unless the
|
||||
* collection is allowed, then hands the request to Payload's handler. Nothing is decided
|
||||
* from the request's path.
|
||||
*/
|
||||
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
|
||||
export function buildFirstUserEndpoint(option: FirstUserRouteOption = 'panel'): Endpoint {
|
||||
const endpoint: Endpoint = {
|
||||
custom: { ipalFirstUser: true },
|
||||
handler: async (req) => {
|
||||
const slug = (req.routeParams as { collection?: string } | undefined)?.collection
|
||||
const collection = slug ? req.payload.collections[slug as never] : undefined
|
||||
const refused = () => Response.json({ errors: [{ message: req.t('error:notAllowedToPerformAction' as never) }] }, { status: 403 })
|
||||
if (!slug || !collection) {return refused()}
|
||||
let allowed = Array.isArray(option) ? option.includes(slug) : slug === req.payload.config.admin?.user
|
||||
if (!allowed) {
|
||||
// a collection that lets a visitor sign up anyway may keep its first-user route
|
||||
try {
|
||||
allowed = Boolean(await collection.config.access?.create?.({ data: req.data, req: { ...req, user: null } } as never))
|
||||
} catch {
|
||||
allowed = false
|
||||
}
|
||||
}
|
||||
if (!allowed) {return refused()}
|
||||
// Payload's own handler: the built-in endpoint of this collection with the same path and method.
|
||||
const builtIn = (collection.config.endpoints || []).find((e) => e !== endpoint && e.method === 'post' && e.path === FIRST_REGISTER && !(e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)
|
||||
if (!builtIn) {return refused()}
|
||||
// for hooks that need to know (the roles field makes the first account an admin)
|
||||
req.context = { ...req.context, ipalFirstRegister: true }
|
||||
return builtIn.handler(req)
|
||||
},
|
||||
method: 'post',
|
||||
path: FIRST_REGISTER,
|
||||
}
|
||||
return endpoint
|
||||
}
|
||||
|
||||
/** Adds the guard to every auth collection (it lets the allowed ones through itself). `'all'` adds nothing. */
|
||||
/** Puts the first-user endpoint in front of Payload's on every auth collection. `'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,
|
||||
),
|
||||
collections: (config.collections ?? []).map((collection) => {
|
||||
if (!collection.auth || collection.endpoints === false) {return collection}
|
||||
const own = (collection.endpoints ?? []).filter((e) => !(e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)
|
||||
return { ...collection, endpoints: [buildFirstUserEndpoint(option), ...own] }
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
type LivePayload = { collections: Record<string, { config: { access?: { create?: Access; delete?: Access; update?: Access }; auth?: unknown; slug: string } }>; config?: unknown }
|
||||
|
||||
/**
|
||||
* 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[]> {
|
||||
export async function openSignUpCollections(payload: LivePayload): Promise<string[]> {
|
||||
const open: string[] = []
|
||||
for (const { config } of Object.values(payload.collections ?? {})) {
|
||||
if (!config.auth) {continue}
|
||||
@@ -97,3 +167,27 @@ export async function openSignUpCollections(payload: { collections: Record<strin
|
||||
}
|
||||
return open.sort()
|
||||
}
|
||||
|
||||
/**
|
||||
* Staff collections that an account of ANOTHER, non-staff auth collection may create in,
|
||||
* update or delete from — `'users:update'`. For the doctor. Asked with a made-up account of a
|
||||
* collection that is not staff; a rule that throws counts as closed.
|
||||
*/
|
||||
export async function staffCollectionsOpenToOthers(payload: LivePayload): Promise<string[]> {
|
||||
const staff = staffCollectionSlugs(payload as never)
|
||||
const outsider = { id: '__ipal-outsider__', collection: '__ipal-outsider__' }
|
||||
const open: string[] = []
|
||||
for (const { config } of Object.values(payload.collections ?? {})) {
|
||||
if (!config.auth || !staff.includes(config.slug)) {continue}
|
||||
for (const operation of ['create', 'update', 'delete'] as const) {
|
||||
try {
|
||||
const rule = config.access?.[operation]
|
||||
// no rule = Payload's default: any logged-in user
|
||||
if (!rule || (await rule({ id: '__ipal-other__', req: { payload, user: outsider } } as never))) {open.push(`${config.slug}:${operation}`)}
|
||||
} catch {
|
||||
/* closed */
|
||||
}
|
||||
}
|
||||
}
|
||||
return open.sort()
|
||||
}
|
||||
|
||||
@@ -19,10 +19,23 @@ 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.
|
||||
* logged-in account do it. Where the collection's roles are not the
|
||||
* plugin's (role values of its own, or no `roles` field) the plugin cannot
|
||||
* tell who is an admin there: an account of that same collection, or a
|
||||
* plugin admin of another staff collection. A `create` rule the project
|
||||
* wrote stays. `false` = Payload's default on collections without a rule.
|
||||
*/
|
||||
adminOnlyCreate?: false
|
||||
/**
|
||||
* The same for `update` and `delete` on a staff collection without those
|
||||
* rules: an admin, or — `update` only — the account itself. Payload's
|
||||
* default ("any logged-in user") let an account of ANOTHER auth collection
|
||||
* (a `customers` visitor) change a staff account's password. On a staff
|
||||
* collection whose roles are not the plugin's: an account of that same
|
||||
* collection, or a plugin admin. A rule the project wrote stays.
|
||||
* `false` = Payload's default on collections without a rule, as before.
|
||||
*/
|
||||
adminOnlyWrite?: false
|
||||
/**
|
||||
* Which auth collections Payload's first-user route
|
||||
* (`POST /api/<slug>/first-register`) answers for while they are empty.
|
||||
|
||||
@@ -16,6 +16,7 @@ export const integrationsTexts = defineTexts({
|
||||
maskedRemoved: 'The stored value will be removed when you save.',
|
||||
maskedSet: 'A value is set. It is not shown; type a new one to replace it.',
|
||||
maskedShow: 'Show',
|
||||
secretReenter: 'Enter the password again: the server, port, user name or encryption setting changed. To use the server without a password, remove the stored value.',
|
||||
|
||||
// Status banner on an integration's tab (IntegrationStatusBanner)
|
||||
statusCode: 'Code: {{code}}.',
|
||||
@@ -74,6 +75,7 @@ export const integrationsTexts = defineTexts({
|
||||
maskedRemoved: 'Zapisana wartość zostanie usunięta po zapisaniu.',
|
||||
maskedSet: 'Wartość jest ustawiona. Nie jest wyświetlana; wpisz nową, aby ją zastąpić.',
|
||||
maskedShow: 'Pokaż',
|
||||
secretReenter: 'Wpisz hasło ponownie: zmienił się serwer, port, nazwa użytkownika lub szyfrowanie. Aby używać serwera bez hasła, usuń zapisaną wartość.',
|
||||
|
||||
statusCode: 'Kod: {{code}}.',
|
||||
statusEmailFailing: 'Wysyłka e-mail nie działa. Powiadomienia z formularzy mogą nie docierać.',
|
||||
|
||||
@@ -183,13 +183,34 @@ export const securityRules: DoctorRule[] = [
|
||||
group: 'security',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// A staff collection that an account of another auth collection (a customer, a member) may write to:
|
||||
// it can create a staff account, or change a staff account's password. The plugin's default rules close
|
||||
// it (accounts.adminOnlyCreate / adminOnlyWrite); this fires when they are off or a project's own rule is wider.
|
||||
id: 'staff-accounts-open',
|
||||
check: (ctx) =>
|
||||
(ctx.deep?.staffOpenToOthers ?? []).map((entry) => {
|
||||
const [slug, operation] = entry.split(':')
|
||||
return {
|
||||
fix: `give "${slug}" an access.${operation} rule that asks for a staff account (staffCreateAccess, staffUpdateAccess('${slug}'), adminOrSelfIn('${slug}')), or drop accounts: false / accounts.adminOnly${operation === 'create' ? 'Create' : 'Write'}: false`,
|
||||
message: `an account of another auth collection may ${operation} in the staff collection "${slug}"${operation === 'create' ? ': it can make itself a staff account' : operation === 'update' ? ": it can change a staff account's password" : ''}`,
|
||||
severity: 'error' 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',
|
||||
check: (ctx) => {
|
||||
const status = ctx.deep?.turnstile
|
||||
if (!status || status.state !== 'degraded') {return []}
|
||||
const hours = status.since ? Math.floor((Date.parse(`${ctx.today}T23:59:59Z`) - Date.parse(status.since)) / 3_600_000) : null
|
||||
// "Now": the clock when the run is for today; for another date (a test, a replay) the middle of that day.
|
||||
// Not the END of the day: a state that began at 23:59 would be "a day old" a minute later.
|
||||
const now = ctx.today === new Date().toISOString().slice(0, 10) ? Date.now() : Date.parse(`${ctx.today}T12:00:00Z`)
|
||||
const hours = status.since ? Math.floor((now - Date.parse(status.since)) / 3_600_000) : null
|
||||
const long = hours !== null && hours >= 24
|
||||
return [{
|
||||
fix: 'Site integrations → Spam protection: both keys from the same Cloudflare widget; then send a test form',
|
||||
|
||||
@@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs'
|
||||
|
||||
import type { DoctorStatus } from './types.js'
|
||||
|
||||
import { openSignUpCollections } from '../access/selfRegistration.js'
|
||||
import { openSignUpCollections, staffCollectionsOpenToOthers } 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'
|
||||
@@ -68,7 +68,13 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
} catch {
|
||||
openSignUp = null
|
||||
}
|
||||
return { node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
|
||||
let staffOpenToOthers: null | string[] = null
|
||||
try {
|
||||
staffOpenToOthers = await staffCollectionsOpenToOthers(payload as never)
|
||||
} catch {
|
||||
staffOpenToOthers = null
|
||||
}
|
||||
return { node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
|
||||
}
|
||||
|
||||
export type DoctorEndpointOptions = {
|
||||
|
||||
@@ -65,6 +65,11 @@ export type DoctorStatus = {
|
||||
openSignUp?: null | string[]
|
||||
pendingCookies?: null | number
|
||||
plugin?: string
|
||||
/**
|
||||
* Staff collections an account of ANOTHER, non-staff auth collection may create in, update or
|
||||
* delete from: `'users:update'`. Slugs and operations only.
|
||||
*/
|
||||
staffOpenToOthers?: null | string[]
|
||||
/** The Turnstile integration's recorded state (Site integrations): never a key, only the state. null = not known. */
|
||||
turnstile?: { code?: null | string; since?: null | string; state?: null | string } | null
|
||||
/** The Turnstile secret key in use comes from the environment (the panel field is empty). Deprecated. */
|
||||
|
||||
@@ -9,6 +9,7 @@ type SmtpIntegrations = {
|
||||
smtpHost?: null | string
|
||||
smtpPassword?: null | string
|
||||
smtpPort?: null | number
|
||||
smtpRequireTls?: boolean | null
|
||||
smtpUser?: null | string
|
||||
}
|
||||
|
||||
@@ -87,7 +88,9 @@ export const panelSmtpAdapter =
|
||||
auth: { pass, user },
|
||||
host,
|
||||
port,
|
||||
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
|
||||
// "Require an encrypted connection" in the panel: no STARTTLS offered = no login, nothing sent
|
||||
requireTLS: smtp.smtpRequireTls === true && port !== 465,
|
||||
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
|
||||
})
|
||||
|
||||
try {
|
||||
|
||||
@@ -13,6 +13,7 @@ type SmtpIntegrations = {
|
||||
smtpHost?: null | string
|
||||
smtpPassword?: null | string
|
||||
smtpPort?: null | number
|
||||
smtpRequireTls?: boolean | null
|
||||
smtpUser?: null | string
|
||||
}
|
||||
|
||||
@@ -75,6 +76,8 @@ export async function sendEmail({
|
||||
auth: { pass, user },
|
||||
host,
|
||||
port,
|
||||
// "Require an encrypted connection" in the panel: no STARTTLS offered = no login, nothing sent
|
||||
requireTLS: smtp.smtpRequireTls === true && port !== 465,
|
||||
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
|
||||
})
|
||||
|
||||
|
||||
@@ -36,8 +36,9 @@ const DEFAULT_CHECKS: Record<string, IntegrationLabel> = {
|
||||
* everything is fine — and never throws (DB not ready → nothing).
|
||||
*
|
||||
* The texts come from the Site integrations global, which only admins may read: the widget
|
||||
* reads it with access control off, so it decides itself who gets them (`details`). A
|
||||
* session that still owes its second factor gets nothing (`userMeetsRole` includes it).
|
||||
* reads it with access control off, so it decides itself who gets them (`details`). With a
|
||||
* role, a session that still owes its second factor gets nothing (`userMeetsRole` includes
|
||||
* it); `details: 'all'` checks nothing at all — no role, no second factor.
|
||||
*/
|
||||
export async function IntegrationAlerts({ adminRoute = '/admin', checks = DEFAULT_CHECKS, details = 'admin', i18n, payload, user }: Props) {
|
||||
if (!payload) {return null}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* The two values of a write-only secret that travel between the server and the panel.
|
||||
* On their own, without any server code: the panel's field component imports them.
|
||||
*/
|
||||
|
||||
/** What a read gets instead of a stored secret: "a value is set". */
|
||||
export const SECRET_MASK = '********'
|
||||
/** Send this as the value to remove a stored secret (an empty value keeps it). */
|
||||
export const SECRET_CLEAR = '[[clear]]'
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { Field, FieldHook } from 'payload'
|
||||
import type { CollectionAfterReadHook, Field, FieldHook, GlobalAfterReadHook } from 'payload'
|
||||
|
||||
import { ValidationError } from 'payload'
|
||||
|
||||
import { ipalT } from '../admin-i18n/t.js'
|
||||
import { SECRET_CLEAR, SECRET_MASK } from './constants.js'
|
||||
|
||||
/**
|
||||
* Write-only secrets: a field whose stored value never leaves the server.
|
||||
@@ -14,16 +19,22 @@ import type { Field, FieldHook } from 'payload'
|
||||
* - **returned in full** only to a Local API read with access control off (the default of
|
||||
* `payload.findGlobal` / `payload.find` on the server) — how the plugin's own code reads it;
|
||||
* - **kept** when a save sends nothing, an empty value or the mask back;
|
||||
* - **replaced** when a save sends a new value, and **removed** when it sends `SECRET_CLEAR`.
|
||||
* - **replaced** when a save sends a new value, and **removed** when it sends `SECRET_CLEAR`;
|
||||
* - **asked for again** when a save through access control changes a field the secret is
|
||||
* bound to (`boundTo`) and sends no new secret. The SMTP password is bound to the server,
|
||||
* the port, the user name, the transport and "require encryption": otherwise a stolen admin
|
||||
* session points the server at its own machine, sends a test e-mail and reads the password
|
||||
* off the wire. `secrets: { reenterOnChange: false }` turns that off.
|
||||
*
|
||||
* Restoring a version (a project that turns versions on) answers with the version document —
|
||||
* the fields sit under `version`, where field hooks do not run. `maskSecretsOnRestore` is the
|
||||
* global / collection `afterRead` hook that masks them there too.
|
||||
*
|
||||
* Off for the two built-in fields: `secrets: { writeOnly: false }`. For a field of your own:
|
||||
* `writeOnlySecret({ name: 'apiToken', type: 'text', admin: { components: { Field: '@intecion/ipal-kit/admin#MaskedField' } } })`.
|
||||
*/
|
||||
|
||||
/** What a read gets instead of a stored secret: "a value is set". */
|
||||
export const SECRET_MASK = '********'
|
||||
/** Send this as the value to remove a stored secret (an empty value keeps it). */
|
||||
export const SECRET_CLEAR = '[[clear]]'
|
||||
export { SECRET_CLEAR, SECRET_MASK }
|
||||
|
||||
/** True when a value read from the API means "a secret is stored" rather than being one. */
|
||||
export const isSecretMask = (value: unknown): boolean => value === SECRET_MASK
|
||||
@@ -41,19 +52,64 @@ export const maskSecretAfterRead: FieldHook = ({ overrideAccess, value }) => {
|
||||
* anything else is the new secret. Runs in `beforeValidate`, so every later hook (the global's
|
||||
* own `beforeChange` included) already sees the real value.
|
||||
*/
|
||||
export const keepSecretBeforeValidate: FieldHook = ({ originalDoc, path, value }) => {
|
||||
if (value === SECRET_CLEAR) {return null}
|
||||
if (value === undefined || value === null || value === '' || value === SECRET_MASK) {
|
||||
const stored = dig(originalDoc, path)
|
||||
// The original document is read by Payload with access control off, so this is the real value;
|
||||
// a mask here would mean it was not — never store the mask.
|
||||
return typeof stored === 'string' && stored !== SECRET_MASK ? stored : (stored ?? null)
|
||||
}
|
||||
return value
|
||||
export type WriteOnlySecretOptions = {
|
||||
/** With `boundTo`: the rule applies only to a save for which this returns true (the sibling data of the save). */
|
||||
appliesWhen?: (siblingData: Record<string, unknown>) => boolean
|
||||
/**
|
||||
* Sibling fields the secret belongs to (the server it is sent to, the user it is for). A save
|
||||
* through access control that changes one of them must send the secret again — or remove it.
|
||||
*/
|
||||
boundTo?: string[]
|
||||
}
|
||||
|
||||
/** Two values of a bound field are the same setting: compared as trimmed, lower-case text. */
|
||||
const asText = (value: unknown): string => (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : value === undefined || value === null ? '' : JSON.stringify(value)).trim().toLowerCase()
|
||||
const sameSetting = (a: unknown, b: unknown): boolean => asText(a) === asText(b)
|
||||
|
||||
/** The stored value of the secret — never the mask (the original document is read with access control off; a mask there is not a secret). */
|
||||
const storedSecret = (originalDoc: unknown, path: (number | string)[]): null | string => {
|
||||
const stored = dig(originalDoc, path)
|
||||
return typeof stored === 'string' && stored !== '' && stored !== SECRET_MASK ? stored : null
|
||||
}
|
||||
|
||||
/** The `beforeValidate` hook of a write-only secret. `keepSecretBeforeValidate` is the one without options. */
|
||||
export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOptions = {}): FieldHook {
|
||||
return ({ collection, field, global, originalDoc, overrideAccess, path, req, siblingData, siblingFields, value: given }) => {
|
||||
// What the save SENT. For a field that was not sent Payload passes a fallback as `value` — the
|
||||
// stored secret itself — which must not pass for a secret typed again.
|
||||
const name = (field as { name?: string } | undefined)?.name
|
||||
const value = siblingData && name ? (siblingData as Record<string, unknown>)[name] : given
|
||||
if (value === SECRET_CLEAR) {return null}
|
||||
if (!(value === undefined || value === null || value === '' || value === SECRET_MASK)) {return value}
|
||||
const stored = storedSecret(originalDoc, path)
|
||||
if (stored && boundTo.length && overrideAccess !== true && (!appliesWhen || appliesWhen((siblingData ?? {}) as Record<string, unknown>))) {
|
||||
const before = dig(originalDoc, path.slice(0, -1)) as Record<string, unknown> | undefined
|
||||
const changed = boundTo.filter((name) => {
|
||||
const next = (siblingData as Record<string, unknown> | undefined)?.[name]
|
||||
if (next === undefined) {return false} // not part of this save
|
||||
// a value never saved counts as the field's default (an older document, a field added since)
|
||||
const fallback = (siblingFields as { defaultValue?: unknown; name?: string }[] | undefined)?.find((f) => f.name === name)?.defaultValue
|
||||
const was = before?.[name] ?? (typeof fallback === 'function' ? undefined : fallback)
|
||||
return !sameSetting(next, was)
|
||||
})
|
||||
if (changed.length) {
|
||||
const message = req?.t ? ipalT(req.t as never, 'secretReenter') : 'Enter the password again: the settings it belongs to have changed.'
|
||||
throw new ValidationError({ collection: collection?.slug, errors: [{ message, path: path.join('.') }], global: global?.slug }, req?.t)
|
||||
}
|
||||
}
|
||||
return stored
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes: nothing, an empty value or the mask keep what is stored; `SECRET_CLEAR` removes it;
|
||||
* anything else is the new secret. Runs in `beforeValidate`, so every later hook (the global's
|
||||
* own `beforeChange` included) already sees the real value.
|
||||
*/
|
||||
export const keepSecretBeforeValidate: FieldHook = buildKeepSecret()
|
||||
|
||||
/** Adds the two hooks to a field (a text field as a rule). The field's own hooks stay, and run around them. */
|
||||
export function writeOnlySecret<F extends Field>(field: F): F {
|
||||
export function writeOnlySecret<F extends Field>(field: F, options: WriteOnlySecretOptions = {}): F {
|
||||
const own = (field as { hooks?: { afterRead?: FieldHook[]; beforeValidate?: FieldHook[] } }).hooks ?? {}
|
||||
return {
|
||||
...field,
|
||||
@@ -61,21 +117,65 @@ export function writeOnlySecret<F extends Field>(field: F): F {
|
||||
hooks: {
|
||||
...own,
|
||||
afterRead: [...(own.afterRead ?? []), maskSecretAfterRead],
|
||||
beforeValidate: [keepSecretBeforeValidate, ...(own.beforeValidate ?? [])],
|
||||
beforeValidate: [options.boundTo?.length ? buildKeepSecret(options) : keepSecretBeforeValidate, ...(own.beforeValidate ?? [])],
|
||||
},
|
||||
} as F
|
||||
}
|
||||
|
||||
/** `writeOnlySecret` for the named fields, wherever they are in the tree (tabs, rows, groups, collapsibles). */
|
||||
export function writeOnlySecrets(fields: Field[], names: string[]): Field[] {
|
||||
/**
|
||||
* `writeOnlySecret` for the named fields, wherever they are in the tree (tabs, rows, groups, collapsibles).
|
||||
* `options`: per field name (`{ smtpPassword: { boundTo: [...] } }`).
|
||||
*/
|
||||
export function writeOnlySecrets(fields: Field[], names: string[], options: Record<string, WriteOnlySecretOptions> = {}): Field[] {
|
||||
return fields.map((field) => {
|
||||
const f = field as { fields?: Field[]; name?: string; tabs?: { fields: Field[] }[] } & Field
|
||||
if (f.name && names.includes(f.name) && !('fields' in f && Array.isArray(f.fields))) {return writeOnlySecret(field)}
|
||||
if (Array.isArray(f.tabs)) {return { ...f, tabs: f.tabs.map((tab) => ({ ...tab, fields: writeOnlySecrets(tab.fields, names) })) } as Field}
|
||||
if (Array.isArray(f.fields)) {return { ...f, fields: writeOnlySecrets(f.fields, names) } as Field}
|
||||
if (f.name && names.includes(f.name) && !('fields' in f && Array.isArray(f.fields))) {return writeOnlySecret(field, options[f.name])}
|
||||
if (Array.isArray(f.tabs)) {return { ...f, tabs: f.tabs.map((tab) => ({ ...tab, fields: writeOnlySecrets(tab.fields, names, options) })) } as Field}
|
||||
if (Array.isArray(f.fields)) {return { ...f, fields: writeOnlySecrets(f.fields, names, options) } as Field}
|
||||
return field
|
||||
})
|
||||
}
|
||||
|
||||
type Tree = { blocks?: { fields: Field[]; slug: string }[]; custom?: { ipalWriteOnly?: boolean }; fields?: Field[]; name?: string; tabs?: { fields: Field[]; name?: string }[]; type?: string }
|
||||
|
||||
/** Masks every write-only secret in `data`, following the field tree (tabs, rows, groups, arrays, blocks). In place. */
|
||||
export function maskWriteOnlySecrets(data: unknown, fields: Field[]): void {
|
||||
if (!data || typeof data !== 'object') {return}
|
||||
const doc = data as Record<string, unknown>
|
||||
for (const field of fields as Tree[]) {
|
||||
if (Array.isArray(field.tabs)) {
|
||||
for (const tab of field.tabs) {maskWriteOnlySecrets(tab.name ? doc[tab.name] : doc, tab.fields)}
|
||||
} else if (!field.name) {
|
||||
if (Array.isArray(field.fields)) {maskWriteOnlySecrets(doc, field.fields)}
|
||||
} else if (field.custom?.ipalWriteOnly) {
|
||||
if (typeof doc[field.name] === 'string' && doc[field.name] !== '') {doc[field.name] = SECRET_MASK}
|
||||
} else if (Array.isArray(field.fields)) {
|
||||
const value = doc[field.name]
|
||||
for (const row of Array.isArray(value) ? value : [value]) {maskWriteOnlySecrets(row, field.fields)}
|
||||
} else if (Array.isArray(field.blocks) && Array.isArray(doc[field.name])) {
|
||||
for (const row of doc[field.name] as { blockType?: string }[]) {
|
||||
const block = field.blocks.find((b) => b.slug === row?.blockType)
|
||||
if (block) {maskWriteOnlySecrets(row, block.fields)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `afterRead` hook for a global or a collection with write-only secrets AND versions: a restore
|
||||
* answers with the version document, the fields under `version`, where the field hooks do not
|
||||
* reach. Masks them there for every read through access control. Put on Site integrations by
|
||||
* the plugin; add it to your own entity next to `writeOnlySecret`.
|
||||
*/
|
||||
export const maskSecretsOnRestore: CollectionAfterReadHook & GlobalAfterReadHook = (args: { collection?: { fields: Field[] }; context?: { isRestoringVersion?: unknown }; doc: unknown; global?: { fields: Field[] }; overrideAccess?: boolean }) => {
|
||||
const { context, doc, overrideAccess } = args
|
||||
const fields = (args.global ?? args.collection)?.fields
|
||||
const version = (doc as { version?: unknown } | null)?.version
|
||||
if (overrideAccess !== true && context?.isRestoringVersion && fields && version && typeof version === 'object') {maskWriteOnlySecrets(version, fields)}
|
||||
return doc
|
||||
}
|
||||
|
||||
/** The plugin's own stored secrets (Site integrations). */
|
||||
export const INTEGRATION_SECRET_FIELDS = ['smtpPassword', 'turnstileSecretKey']
|
||||
/** What the SMTP password belongs to: changing one of these in the panel asks for the password again. */
|
||||
export const SMTP_PASSWORD_BOUND_TO = ['emailTransport', 'smtpHost', 'smtpPort', 'smtpUser', 'smtpRequireTls']
|
||||
|
||||
@@ -13,8 +13,25 @@
|
||||
* `twoFactor.sameOrigin.origins`. A request with neither `Origin` nor `Sec-Fetch-Site` is not
|
||||
* a browser's cross-site request (a script, `curl`, a server) and passes: it cannot ride on
|
||||
* somebody's cookie.
|
||||
*
|
||||
* A reverse proxy that rewrites `Host` and sends no `X-Forwarded-Host` (nginx's plain
|
||||
* `proxy_pass`) hides the site's address from the server: without `serverURL` the site's own
|
||||
* pages are then refused. That must not happen in silence — the first refusal of every origin
|
||||
* is written to the log with the ways to allow it (`reportRefusedOrigin`).
|
||||
*/
|
||||
type RequestLike = { headers?: { get(name: string): null | string }; payload?: { config?: { cors?: unknown; csrf?: unknown; serverURL?: unknown } }; url?: null | string }
|
||||
type RequestLike = {
|
||||
headers?: { get(name: string): null | string }
|
||||
payload?: { config?: { cors?: unknown; csrf?: unknown; serverURL?: unknown }; logger?: { warn(message: string): void } }
|
||||
url?: null | string
|
||||
}
|
||||
|
||||
/** `site.example:443` is `site.example` for https, `:80` for http — a proxy may write the port out. */
|
||||
const withoutDefaultPort = (host: string, protocol: string): string => {
|
||||
const lower = host.toLowerCase()
|
||||
if (protocol === 'https:' && lower.endsWith(':443')) {return lower.slice(0, -4)}
|
||||
if (protocol === 'http:' && lower.endsWith(':80')) {return lower.slice(0, -3)}
|
||||
return lower
|
||||
}
|
||||
|
||||
const originOf = (value: unknown): null | string => {
|
||||
if (typeof value !== 'string' || !value) {return null}
|
||||
@@ -54,9 +71,42 @@ export function requestFromOwnOrigin(req: RequestLike, extra: string[] = []): bo
|
||||
const parsed = originOf(origin)
|
||||
if (!parsed) {return false} // "null" (a sandboxed page, a redirect chain) or garbage
|
||||
const { hosts, origins } = ownOrigins(req, extra)
|
||||
return origins.has(parsed) || hosts.has(new URL(parsed).host.toLowerCase())
|
||||
if (origins.has(parsed)) {return true}
|
||||
// `URL.origin` has already dropped the default port; a `Host` / `X-Forwarded-Host` may carry it
|
||||
const { host, protocol } = new URL(parsed)
|
||||
return [...hosts].some((own) => withoutDefaultPort(own, protocol) === host.toLowerCase())
|
||||
}
|
||||
const site = req.headers?.get('sec-fetch-site')
|
||||
if (site) {return site === 'same-origin' || site === 'none'}
|
||||
return true
|
||||
}
|
||||
|
||||
const reported = new Set<string>()
|
||||
const MAX_REPORTED = 50
|
||||
|
||||
/**
|
||||
* Says in the log, once per origin and process, that a 2FA attempt was refused and how to allow
|
||||
* that origin. Without it a site behind a proxy that hides its address has a panel nobody can
|
||||
* enter and a silent log. Returns true when a line was written.
|
||||
*/
|
||||
export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boolean {
|
||||
const origin = req.headers?.get('origin')
|
||||
const key = origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`
|
||||
if (reported.has(key) || reported.size >= MAX_REPORTED) {return false}
|
||||
reported.add(key)
|
||||
const { hosts, origins } = ownOrigins(req, extra)
|
||||
const known = [...origins, ...[...hosts].map((h) => `host ${h}`)].join(', ') || 'none'
|
||||
const how = originOf(origin)
|
||||
? `If "${originOf(origin)}" is this site's own address (a reverse proxy that rewrites Host and sends no X-Forwarded-Host), set serverURL to it in the Payload config, ` +
|
||||
`or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
|
||||
: 'The browser did not name an origin this site knows. '
|
||||
req.payload?.logger?.warn(
|
||||
`[ipal] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` +
|
||||
how +
|
||||
'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.',
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
/** For tests: forget which origins were reported. */
|
||||
export const clearReportedOrigins = (): void => reported.clear()
|
||||
|
||||
+52
-6
@@ -15,7 +15,8 @@ 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 { applyPasswordRule, resolvePasswordRule } from './modules/access/passwordRule.js'
|
||||
import { applyAdminOnlyCreate, applyFirstUserRoute } from './modules/access/selfRegistration.js'
|
||||
import { applyFirstUserRoute, applyStaffAccountAccess } from './modules/access/selfRegistration.js'
|
||||
import { ROLE_HIERARCHY } from './modules/access/types.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'
|
||||
@@ -40,7 +41,7 @@ import { serverText } from './modules/integrations/texts.js'
|
||||
import { buildSystemPagesFields } from './modules/pages/index.js'
|
||||
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
|
||||
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
|
||||
import { requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
|
||||
import { reportRefusedOrigin, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
|
||||
import {
|
||||
buildGuardStrategy,
|
||||
ensurePayloadGuarded,
|
||||
@@ -201,11 +202,25 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
let setupWindowHours = 0
|
||||
/** accounts.panelRole in force: the collection and the role, for the start-up line. */
|
||||
let panelRoleFor: { role: Role; slug: string } | null = null
|
||||
/** Why the default panel role was not applied (said once at start). */
|
||||
let panelRoleSkipped: null | string = null
|
||||
/** `accounts: false` turns every account rule off. */
|
||||
const accounts: AccountsOptions | null = options.accounts === false ? null : (options.accounts ?? {})
|
||||
/** requireSetup.setupNotice / statusField (on unless switched off). */
|
||||
let setupNotice = true
|
||||
let statusField = false
|
||||
// Account rules (accounts.*): nobody creates an account for themselves, or takes one over.
|
||||
// BEFORE the 2FA package: it gives every collection a create / update / delete function of
|
||||
// its own, and afterwards a missing rule cannot be told from one the project wrote.
|
||||
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)))]
|
||||
config = applyStaffAccountAccess(config, staffSlugs, {
|
||||
create: accounts.adminOnlyCreate !== false,
|
||||
pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [],
|
||||
write: accounts.adminOnlyWrite !== false,
|
||||
})
|
||||
}
|
||||
if (options.twoFactor !== false) {
|
||||
const tf = options.twoFactor
|
||||
if (!tf?.issuer) {
|
||||
@@ -277,7 +292,15 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
const extraOrigins = typeof tf.sameOrigin === 'object' ? (tf.sameOrigin.origins ?? []) : []
|
||||
const guards = {
|
||||
...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}),
|
||||
...(tf.sameOrigin === false ? {} : { ownOrigin: (req: PayloadRequest) => requestFromOwnOrigin(req as never, extraOrigins) }),
|
||||
...(tf.sameOrigin === false
|
||||
? {}
|
||||
: {
|
||||
ownOrigin: (req: PayloadRequest) => {
|
||||
if (requestFromOwnOrigin(req as never, extraOrigins)) {return true}
|
||||
reportRefusedOrigin(req as never, extraOrigins) // never in silence: once per origin, with the ways to allow it
|
||||
return false
|
||||
},
|
||||
}),
|
||||
onSetupClosed: (req: PayloadRequest) =>
|
||||
Response.json({ message: serverText(req.i18n as never, 'twoFactorSetupClosed'), ok: false }, { status: 403 }),
|
||||
}
|
||||
@@ -562,8 +585,22 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
const staff = [...new Set([options.access.authCollection, ...(options.access.staffCollections ?? [])])]
|
||||
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffCollections: staff } }
|
||||
// Account rules (accounts.*): the lowest role stays out of the panel.
|
||||
const panelRole = accounts ? resolvePanelRole(accounts.panelRole) : null
|
||||
let panelRole = accounts ? resolvePanelRole(accounts.panelRole) : null
|
||||
const rolesSlug = options.access.authCollection
|
||||
// With firstUserAdmin: false the first account gets the default role. Below the panel
|
||||
// role, a fresh site would have nobody who can open the panel — and nobody to raise a role.
|
||||
const firstRole = options.access.defaultRole ?? 'user'
|
||||
if (panelRole && options.access.firstUserAdmin === false && ROLE_HIERARCHY.indexOf(firstRole) < ROLE_HIERARCHY.indexOf(panelRole)) {
|
||||
if (accounts?.panelRole !== undefined) {
|
||||
throw new Error(
|
||||
`[ipal] access.firstUserAdmin: false with accounts.panelRole: '${panelRole}' leaves a fresh site with nobody who can open the panel: ` +
|
||||
`the first account gets the role '${firstRole}', which is below the panel role. Set access.defaultRole to '${panelRole}' or higher, ` +
|
||||
"or accounts: { panelRole: false }, or drop access.firstUserAdmin: false (docs/access.md \"Account rules\").",
|
||||
)
|
||||
}
|
||||
panelRoleSkipped = `access.firstUserAdmin is false and the first account gets the role '${firstRole}'`
|
||||
panelRole = null
|
||||
}
|
||||
// the project's own access.admin (or access.authAccess.admin) wins
|
||||
if (panelRole && !(config.collections ?? []).find((c) => c.slug === rolesSlug)?.access?.admin) {
|
||||
config = applyPanelRole(config, rolesSlug, panelRole)
|
||||
@@ -574,7 +611,6 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
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)
|
||||
const passwordRule = resolvePasswordRule(accounts.password)
|
||||
if (passwordRule) {config = applyPasswordRule(config, staffSlugs, passwordRule)}
|
||||
@@ -645,7 +681,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
: { searchFields: typeof searchSettings === 'function' ? searchSettings(searchSettingsFields) : searchSettingsFields }),
|
||||
systemPageFields,
|
||||
}),
|
||||
buildSiteIntegrations({ additionalFields: options.integrationsFields, writeOnlySecrets: options.secrets?.writeOnly !== false }),
|
||||
buildSiteIntegrations({
|
||||
additionalFields: options.integrationsFields,
|
||||
reenterSecretOnChange: options.secrets?.reenterOnChange !== false,
|
||||
writeOnlySecrets: options.secrets?.writeOnly !== false,
|
||||
}),
|
||||
withFillLocales('global', buildCookieSettings(), fillLocales['cookie-settings']),
|
||||
buildNotifications({ lightbox: options.lightbox === true }),
|
||||
]
|
||||
@@ -864,6 +904,12 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
)
|
||||
}
|
||||
}
|
||||
if (panelRoleSkipped) {
|
||||
payload.logger.warn(
|
||||
`[ipal] The panel role (accounts.panelRole, 'editor' by default) is NOT applied: ${panelRoleSkipped}, so nobody could open the panel on a fresh site. ` +
|
||||
'Every account of the login collection can open the panel. To keep the lowest role out, set access.defaultRole to \'editor\' or drop access.firstUserAdmin: false (docs/access.md "Account rules").',
|
||||
)
|
||||
}
|
||||
// The panel role: tell a site how many of its accounts the rule keeps out of the panel.
|
||||
if (panelRoleFor) {
|
||||
try {
|
||||
|
||||
+13
-4
@@ -112,8 +112,10 @@ export type IpalOptions = {
|
||||
* and link): `'admin'` (default), `'editor'`, `'all'`; an editor below that
|
||||
* sees a neutral "an integration needs attention — ask an administrator",
|
||||
* anyone else nothing. `cookies` — who sees the cookie crawl / approval
|
||||
* alert: `'editor'` (default) or `'all'`. `'all'` = as before. A session
|
||||
* that still owes its second factor sees none of them.
|
||||
* alert: `'editor'` (default) or `'all'`. With a role (`'admin'`,
|
||||
* `'editor'`) a session that still owes its second factor sees nothing.
|
||||
* `'all'` = as before, and it checks NOTHING — no role and no second
|
||||
* factor: whoever the dashboard is drawn for sees the full text.
|
||||
*/
|
||||
dashboardAlerts?: { cookies?: 'all' | 'editor'; integrations?: 'admin' | 'all' | 'editor' }
|
||||
|
||||
@@ -209,9 +211,16 @@ export type IpalOptions = {
|
||||
* value or the mask keeps what is stored, `'[[clear]]'` removes it. Server
|
||||
* code reads the real value through the Local API (access control off, the
|
||||
* default). `{ writeOnly: false }` = the value is returned to whoever may
|
||||
* read the global, as before 1.16.7. docs/security.md "Stored secrets".
|
||||
* read the global, as before 1.16.7.
|
||||
*
|
||||
* The SMTP password is bound to its server: a save in the panel that changes
|
||||
* the server, the port, the user name, the transport or "require an encrypted
|
||||
* connection" must send the password again, or remove it — otherwise a stolen
|
||||
* admin session points the server at its own machine and a test e-mail hands
|
||||
* the password over. `{ reenterOnChange: false }` = the stored password
|
||||
* follows the new server. docs/security.md "Stored secrets".
|
||||
*/
|
||||
secrets?: { writeOnly?: false }
|
||||
secrets?: { reenterOnChange?: false; writeOnly?: false }
|
||||
seo?: SeoOption
|
||||
|
||||
/** Additional fields injected into SiteSettings global */
|
||||
|
||||
+4
-338
@@ -1,342 +1,8 @@
|
||||
/**
|
||||
* M1 account rules over real HTTP (SQLite by default; Postgres / MongoDB with IPAL_TEST_POSTGRES_URI /
|
||||
* IPAL_TEST_MONGO_URI): who may open the panel, who may create an account, what a password must be.
|
||||
*/
|
||||
import type { Config, Payload } from 'payload'
|
||||
/** The account rules with 2FA off — see accountRulesSuite.ts. */
|
||||
import { vi } from 'vitest'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { pbkdf2Sync, randomBytes } from 'node:crypto'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
|
||||
import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.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'
|
||||
import { startPayloadServer, type TestServer } from './http/server.js'
|
||||
import { accountRulesSuite } from './accountRulesSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
|
||||
type Session = Record<string, string>
|
||||
const call = (pathname: string, session: Session = {}, init: RequestInit = {}) =>
|
||||
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...session, ...(init.headers as Record<string, string> | undefined) } })
|
||||
const post = (pathname: string, body: unknown, session: Session = {}) => call(pathname, session, { body: JSON.stringify(body), method: 'POST' })
|
||||
const login = async (collection: string, email: string, password = PASSWORD): Promise<Session> => {
|
||||
const body = (await (await post(`/${collection}/login`, { email, password })).json()) as { token?: string }
|
||||
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
|
||||
return { authorization: `JWT ${body.token}` }
|
||||
}
|
||||
const make = (collection: string, data: Record<string, unknown>) => payload.create({ collection: collection as never, data: { password: PASSWORD, ...data } as never })
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
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', staffCollections: ['staff2'] }, i18n, 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?.()
|
||||
})
|
||||
|
||||
// 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)
|
||||
|
||||
beforeAll(async () => {
|
||||
await make('users', { email: '[email protected]', roles: ['admin'] })
|
||||
await make('users', { email: '[email protected]', roles: ['editor'] })
|
||||
await make('users', { email: '[email protected]', roles: ['user'] })
|
||||
await make('customers', { email: '[email protected]' })
|
||||
})
|
||||
|
||||
test('Payload reports panel access for an admin and an editor, not for a plain user or a visitor account', async () => {
|
||||
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(true)
|
||||
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(true)
|
||||
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(false)
|
||||
expect(await canAccessAdmin(await login('customers', '[email protected]'))).toBe(false)
|
||||
expect(await canAccessAdmin({})).toBe(false)
|
||||
})
|
||||
|
||||
test('the API is not touched: the plain user still logs in and reads its own account', async () => {
|
||||
const session = await login('users', '[email protected]')
|
||||
const me = (await (await call('/users/me', session)).json()) as { user?: { email?: string } }
|
||||
expect(me.user?.email).toBe('[email protected]')
|
||||
})
|
||||
|
||||
test('the start-up count: how many accounts are below the panel role', async () => {
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the password rule (accounts.password): twelve characters when a password is set', () => {
|
||||
let admin: Session
|
||||
const messageOf = async (res: Response) => JSON.stringify(await res.json())
|
||||
|
||||
beforeAll(async () => {
|
||||
admin = await login('users', '[email protected]')
|
||||
})
|
||||
|
||||
test('a new account: 11 characters refused with a clear message, 12 accepted', async () => {
|
||||
const short = await post('/users', { email: '[email protected]', password: 'abcdefghijk', roles: ['editor'] }, admin)
|
||||
expect(short.status).toBe(400)
|
||||
expect(await messageOf(short)).toMatch(/at least 12 characters/)
|
||||
expect((await post('/users', { email: '[email protected]', password: 'abcdefghijkl', roles: ['editor'] }, admin)).status).toBe(201)
|
||||
// counted in characters, not bytes
|
||||
expect((await post('/users', { email: '[email protected]', password: 'zażółć gęślą', roles: ['editor'] }, admin)).status).toBe(201)
|
||||
})
|
||||
|
||||
test('in Polish for a Polish panel', async () => {
|
||||
const res = await post('/users', { email: '[email protected]', password: 'krotkie', roles: ['editor'] }, { ...admin, 'accept-language': 'pl' })
|
||||
expect(res.status).toBe(400)
|
||||
expect(await messageOf(res)).toMatch(/co najmniej 12 znaków/)
|
||||
})
|
||||
|
||||
test('not the account\'s own e-mail address', async () => {
|
||||
const same = await post('/users', { email: '[email protected]', password: '[email protected]', roles: ['editor'] }, admin)
|
||||
expect(same.status).toBe(400)
|
||||
expect(await messageOf(same)).toMatch(/same as the e-mail/)
|
||||
})
|
||||
|
||||
test('changing a password: checked; changing anything else: not', async () => {
|
||||
const doc = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0]
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'tooshort' }), method: 'PATCH' })).status).toBe(400)
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: '[email protected]' }), method: 'PATCH' })).status).toBe(400) // its own address, looked up
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })).status).toBe(200)
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'a-new-long-password' }), method: 'PATCH' })).status).toBe(200)
|
||||
await login('users', '[email protected]', 'a-new-long-password')
|
||||
})
|
||||
|
||||
test('an EXISTING shorter password keeps logging in — nothing is checked at login', async () => {
|
||||
// an account as an earlier version left it: a 6-character password, stored the way Payload stored it then
|
||||
const old = await make('users', { email: '[email protected]', roles: ['editor'] })
|
||||
const salt = randomBytes(32).toString('hex')
|
||||
const hash = pbkdf2Sync('short1', salt, 25000, 512, 'sha256').toString('hex')
|
||||
await payload.db.updateOne({ id: old.id, collection: 'users' as never, data: { hash, salt } as never })
|
||||
const session = await login('users', '[email protected]', 'short1')
|
||||
expect(((await (await call('/users/me', session)).json()) as { user?: { email?: string } }).user?.email).toBe('[email protected]')
|
||||
// the rule meets it the next time the password is changed
|
||||
expect((await call(`/users/${old.id}`, session, { body: JSON.stringify({ password: 'short2' }), method: 'PATCH' })).status).toBe(400)
|
||||
})
|
||||
|
||||
test('a reset by e-mail is held to the rule too', async () => {
|
||||
const token = await payload.forgotPassword({ collection: 'users' as never, data: { email: '[email protected]' }, disableEmail: true })
|
||||
const short = await post('/users/reset-password', { password: 'tooshort', token })
|
||||
expect(short.status).toBe(400)
|
||||
expect(await messageOf(short)).toMatch(/at least 12 characters/)
|
||||
expect((await post('/users/reset-password', { password: 'reset-to-a-long-one', token })).status).toBe(200)
|
||||
})
|
||||
|
||||
test('visitor collections are not touched', async () => {
|
||||
expect((await post('/customers', { email: '[email protected]', password: 'abc123' })).status).toBe(201)
|
||||
})
|
||||
|
||||
test('the option, the checker and the switch', async () => {
|
||||
expect(resolvePasswordRule(undefined)).toEqual({ minLength: 12 })
|
||||
expect(resolvePasswordRule({ minLength: 16 })).toEqual({ minLength: 16 })
|
||||
expect(resolvePasswordRule(false)).toBeNull()
|
||||
for (const bad of ['12', 0, -1, 1.5, Number.NaN]) {expect(() => resolvePasswordRule({ minLength: bad as never })).toThrow(/minLength must be/)}
|
||||
expect(checkPassword('abcdefghijk')).toBe('short')
|
||||
expect(checkPassword('abcdefghijkl')).toBeNull()
|
||||
expect(checkPassword('abcd', { minLength: 4 })).toBeNull()
|
||||
expect(checkPassword('[email protected] ', { email: '[email protected]', minLength: 4 })).toBe('email')
|
||||
const hooks = async (options: Record<string, unknown>) =>
|
||||
(await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0])
|
||||
expect(await hooks({})).toEqual([['customers', 1], ['users', 2]]) // customers: the first-user guard only
|
||||
expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 1], ['users', 1]])
|
||||
expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]])
|
||||
})
|
||||
})
|
||||
|
||||
describe('accounts.panelRole: the config', () => {
|
||||
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
|
||||
ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config)
|
||||
const adminRule = (config: Config) => config.collections!.find((c) => c.slug === 'users')!.access?.admin
|
||||
|
||||
test('on by default at editor; a role, false and accounts: false change it', async () => {
|
||||
expect(resolvePanelRole(undefined)).toBe('editor')
|
||||
expect(resolvePanelRole('admin')).toBe('admin')
|
||||
expect(resolvePanelRole('user')).toBeNull() // the lowest role = everyone, as before
|
||||
expect(resolvePanelRole(false)).toBeNull()
|
||||
expect(() => resolvePanelRole('boss' as never)).toThrow(/panelRole must be one of/)
|
||||
expect(adminRule(await build({}))).toBeTypeOf('function')
|
||||
expect(adminRule(await build({ accounts: { panelRole: 'user' } }))).toBeUndefined()
|
||||
expect(adminRule(await build({ accounts: { panelRole: false } }))).toBeUndefined()
|
||||
expect(adminRule(await build({ accounts: false }))).toBeUndefined()
|
||||
// without `access` there are no roles to ask about
|
||||
expect(adminRule(await ipalKit({ i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config))).toBeUndefined()
|
||||
})
|
||||
|
||||
test("the project's own rule wins: on its own collection, and through access.authAccess", async () => {
|
||||
const mine = () => true
|
||||
const own = await build({}, { collections: [{ slug: 'users', access: { admin: mine }, auth: true, fields: [] }] } as never)
|
||||
expect(adminRule(own)).toBe(mine)
|
||||
const injected = await build({ access: { authAccess: { admin: mine }, authCollection: 'users' } })
|
||||
expect(adminRule(injected)).toBe(mine)
|
||||
// the project's own collection without a rule gets the plugin's
|
||||
const plain = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
|
||||
expect(adminRule(plain)).toBeTypeOf('function')
|
||||
})
|
||||
|
||||
test('the rule looks at the role, not at the second factor, and only at staff accounts', () => {
|
||||
const source = { staffCollections: ['users'] }
|
||||
const ask = (user: unknown, minimum?: 'admin' | 'editor') => panelAccess(minimum)({ req: { payload: source, user } } as never)
|
||||
expect(ask({ collection: 'users', roles: ['editor'] })).toBe(true)
|
||||
expect(ask({ _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] })).toBe(true) // still owes its code: the 2FA screens are part of the panel
|
||||
expect(ask({ collection: 'users', roles: ['user'] })).toBe(false)
|
||||
expect(ask({ collection: 'users', roles: [] })).toBe(false)
|
||||
expect(ask({ collection: 'users' })).toBe(false)
|
||||
expect(ask({ collection: 'customers', roles: ['admin'] })).toBe(false)
|
||||
expect(ask(null)).toBe(false)
|
||||
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({})
|
||||
// staff collections: the first-user guard and the password rule; a visitor collection: the guard only
|
||||
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([2, 2, 1, 0])
|
||||
const payloadWay = await build({ accounts: { adminOnlyCreate: false, firstUserRoute: 'all', password: false } })
|
||||
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'])
|
||||
})
|
||||
})
|
||||
accountRulesSuite(false)
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/** The account rules with 2FA ON (the default on a site) — see accountRulesSuite.ts. */
|
||||
import { vi } from 'vitest'
|
||||
|
||||
import { accountRulesSuite } from './accountRulesSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
accountRulesSuite(true)
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* A project with role values of its OWN and no `access` option (review of M1, M1-6): the account rules must not
|
||||
* lock it out of its own accounts after an upgrade — and must still keep accounts of other collections away.
|
||||
* 2FA on, as on a real site. Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI /
|
||||
* IPAL_TEST_MONGO_URI.
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
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 { staffCollectionsOpenToOthers } from '../src/modules/access/selfRegistration.js'
|
||||
import { ipalKit } 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'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
|
||||
type Session = Record<string, string>
|
||||
const call = (pathname: string, session: Session, method: string, body?: unknown) =>
|
||||
fetch(`${server.url}/api${pathname}`, { body: body === undefined ? undefined : JSON.stringify(body), headers: { 'content-type': 'application/json', ...session }, method })
|
||||
const idOf = async (collection: string, email: string) => (await payload.find({ collection: collection as never, where: { email: { equals: email } } })).docs[0]?.id
|
||||
/** A full login: password, and for the 2FA collection the code. */
|
||||
const login = async (collection: string, email: string): Promise<Session> => {
|
||||
const res = await call(`/${collection}/login`, {}, 'POST', { email, password: PASSWORD })
|
||||
const body = (await res.json()) as { token?: string }
|
||||
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
|
||||
if (collection !== 'users') {return { authorization: `JWT ${body.token}` }}
|
||||
await payload.update({ collection: 'users' as never, data: { totpSecret: TOTP_SECRET } as never, where: { email: { equals: email } } })
|
||||
const cookies = cookiesOf(res)
|
||||
const verify = await fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(TOTP_SECRET) }), headers: { 'content-type': 'application/json', cookie: cookies.join('; ') }, method: 'POST' })
|
||||
expect(((await verify.json()) as { ok?: boolean }).ok).toBe(true)
|
||||
return { cookie: [...cookies, ...cookiesOf(verify)].join('; ') }
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [
|
||||
// the project's own staff collection: its own role values, no access rules, no `access` option below
|
||||
{ slug: 'users', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['superadmin', 'writer'] }] },
|
||||
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
|
||||
],
|
||||
db: testDatabase('accounts_own_roles'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp, verifyLimit: 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('the first account registers; accounts of the collection create, change and delete accounts as before the upgrade', async () => {
|
||||
expect((await call('/users/first-register', {}, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['superadmin'] })).status).toBe(200)
|
||||
const boss = await login('users', '[email protected]')
|
||||
// the first M1 cut: 403 — the plugin looked for one of ITS roles and found none
|
||||
expect((await call('/users', boss, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['writer'] })).status).toBe(201)
|
||||
const writer = await login('users', '[email protected]')
|
||||
// the project's roles are the project's to enforce: inside the collection nothing changed
|
||||
expect((await call('/users', writer, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['writer'] })).status).toBe(201)
|
||||
const third = await idOf('users', '[email protected]')
|
||||
expect((await call(`/users/${third}`, boss, 'PATCH', { roles: ['superadmin'] })).status).toBe(200)
|
||||
expect((await call(`/users/${third}`, boss, 'DELETE')).status).toBe(200)
|
||||
})
|
||||
|
||||
test('an account of another collection, a half-signed-in one and nobody stay out', async () => {
|
||||
expect((await call('/customers', {}, 'POST', { email: '[email protected]', password: PASSWORD })).status).toBe(201)
|
||||
const visitor = await login('customers', '[email protected]')
|
||||
const halfRes = await call('/users/login', {}, 'POST', { email: '[email protected]', password: PASSWORD })
|
||||
const half: Session = { authorization: `JWT ${((await halfRes.json()) as { token: string }).token}` } // the password only
|
||||
const victim = await idOf('users', '[email protected]')
|
||||
for (const [who, session] of [['visitor', visitor], ['password only', half], ['anonymous', {}]] as [string, Session][]) {
|
||||
expect([who, (await call('/users', session, 'POST', { email: `by-${who.replace(' ', '-')}@example.com`, password: PASSWORD, roles: ['superadmin'] })).status]).toEqual([who, 403])
|
||||
expect([who, (await call(`/users/${victim}`, session, 'PATCH', { password: 'taken-over-password-1' })).status]).toEqual([who, 403])
|
||||
expect([who, (await call(`/users/${victim}`, session, 'DELETE')).status]).toEqual([who, 403])
|
||||
}
|
||||
expect((await call('/users/login', {}, 'POST', { email: '[email protected]', password: 'taken-over-password-1' })).status).not.toBe(200)
|
||||
expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([])
|
||||
})
|
||||
@@ -0,0 +1,580 @@
|
||||
/**
|
||||
* M1 account rules over real HTTP (SQLite by default; Postgres / MongoDB with IPAL_TEST_POSTGRES_URI /
|
||||
* IPAL_TEST_MONGO_URI): who may open the panel, who may create, change or delete an account, what a
|
||||
* password must be. One suite, run twice: with 2FA off (accountRules.test.ts) and with 2FA on
|
||||
* (accountRules2fa.test.ts) — the 2FA package rewrites every collection's access, and a rule that
|
||||
* holds without it may not hold with it.
|
||||
*/
|
||||
import type { Config, Payload } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { pbkdf2Sync, randomBytes } from 'node:crypto'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
|
||||
import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
|
||||
import { hasPluginRoles, openSignUpCollections, sameStaffCollectionAccess, staffCollectionsOpenToOthers, staffCreateAccess, staffUpdateAccess } from '../src/modules/access/selfRegistration.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig, withTotpParts } 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 TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
|
||||
|
||||
/** The whole suite; `twoFactor` = run it with the 2FA package on. */
|
||||
export function accountRulesSuite(twoFactor: boolean): void {
|
||||
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
|
||||
type Session = Record<string, string>
|
||||
const call = (pathname: string, session: Session = {}, init: RequestInit = {}) =>
|
||||
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...session, ...(init.headers as Record<string, string> | undefined) } })
|
||||
const post = (pathname: string, body: unknown, session: Session = {}) => call(pathname, session, { body: JSON.stringify(body), method: 'POST' })
|
||||
const sessions = new Map<string, Session>()
|
||||
/** A full login. With 2FA on, an account of the 2FA collection (`users`) also types its code. */
|
||||
const login = async (collection: string, email: string, password = PASSWORD): Promise<Session> => {
|
||||
const key = `${collection}|${email}|${password}`
|
||||
const known = sessions.get(key)
|
||||
if (known) {return known}
|
||||
const res = await post(`/${collection}/login`, { email, password })
|
||||
const body = (await res.json()) as { token?: string }
|
||||
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
|
||||
let session: Session = { authorization: `JWT ${body.token}` }
|
||||
if (twoFactor && collection === 'users') {
|
||||
// accounts made over HTTP in a test have no secret yet: give them one, as their owner would on the setup screen
|
||||
await payload.update({ collection: 'users' as never, data: { totpSecret: TOTP_SECRET } as never, where: { email: { equals: email } } })
|
||||
const cookies = cookiesOf(res)
|
||||
const verify = await fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(TOTP_SECRET) }), headers: { 'content-type': 'application/json', cookie: cookies.join('; ') }, method: 'POST' })
|
||||
const verified = (await verify.json()) as { ok?: boolean }
|
||||
if (!verified.ok) {throw new Error(`2FA failed for ${email}: ${JSON.stringify(verified)}`)}
|
||||
session = { cookie: [...cookies, ...cookiesOf(verify)].join('; ') }
|
||||
}
|
||||
sessions.set(key, session)
|
||||
return session
|
||||
}
|
||||
/** Password only: with 2FA on, a `users` session that still owes its code. */
|
||||
const passwordOnly = async (email: string): Promise<Session> => ({ authorization: `JWT ${((await (await post('/users/login', { email, password: PASSWORD })).json()) as { token: string }).token}` })
|
||||
const make = (collection: string, data: Record<string, unknown>) =>
|
||||
payload.create({ collection: collection as never, data: { password: PASSWORD, ...(twoFactor && collection === 'users' ? { totpSecret: TOTP_SECRET } : {}), ...data } as never })
|
||||
const patch = (pathname: string, body: unknown, session: Session = {}) => call(pathname, session, { body: JSON.stringify(body), method: 'PATCH' })
|
||||
const remove = (pathname: string, session: Session = {}) => call(pathname, session, { method: 'DELETE' })
|
||||
const idOf = async (collection: string, email: string) => (await payload.find({ collection: collection as never, where: { email: { equals: email } } })).docs[0]?.id
|
||||
const canLogIn = async (collection: string, email: string, password = PASSWORD) => (await post(`/${collection}/login`, { email, password })).status === 200
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
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
|
||||
// a staff collection with the project's OWN role values and no rules: the plugin cannot tell who its admins are
|
||||
{ slug: 'crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['boss', 'worker'] }] },
|
||||
// a staff collection with the plugin's role values, written by the project, no rules
|
||||
{ slug: 'agents', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
|
||||
],
|
||||
db: testDatabase(twoFactor ? 'accounts_2fa' : 'accounts'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2', 'crew', 'agents'] }, i18n, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : 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?.()
|
||||
})
|
||||
|
||||
// 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('…in every spelling Payload\'s router accepts or might: letter case, slashes, encoding, query', async () => {
|
||||
// the first cut read the path and missed /First-Register: an anonymous visitor became a staff admin
|
||||
const spellings = ['/first-register', '/first-register/', '/First-Register', '/FIRST-REGISTER', '/fIrSt-ReGiStEr', '/first-registe%72', '//first-register', '/first-register?x=1', '/first-register;x', '/First-Register/?x=1']
|
||||
for (const collection of ['staff2', 'crew', 'agents', 'members']) {
|
||||
for (const spelling of spellings) {
|
||||
const res = await post(`/${collection}${spelling}`, { email: `sp-${Math.random().toString(36).slice(2)}@example.com`, password: PASSWORD, roles: ['admin'] })
|
||||
expect([collection, spelling, res.status === 200 || res.status === 201]).toEqual([collection, spelling, false])
|
||||
}
|
||||
expect([collection, await count(collection)]).toEqual([collection, 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 () => {
|
||||
// in a spelling of its own: the account is still the first one, and still an admin
|
||||
const first = await post('/users/First-Register', { email: '[email protected]', password: PASSWORD, roles: ['user'] })
|
||||
expect(first.status).toBe(200)
|
||||
expect(((await first.json()) as { token?: string }).token).toBeTypeOf('string')
|
||||
expect(first.headers.getSetCookie().join(';')).toMatch(/payload-token=/)
|
||||
expect(await rolesOf('[email protected]')).toEqual(['admin'])
|
||||
for (const spelling of ['/first-register', '/First-Register', '/FIRST-REGISTER/']) {
|
||||
expect((await post(`/users${spelling}`, { 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)
|
||||
// GraphQL is the same rule
|
||||
const gql = (await (await post('/graphql', { query: `mutation { createUser(data: { email: "[email protected]", password: "${PASSWORD}", roles: [admin] }) { id } }` }, visitor)).json()) as { errors?: unknown[] }
|
||||
expect(gql.errors?.length).toBeGreaterThan(0)
|
||||
expect(await idOf('users', '[email protected]')).toBeUndefined()
|
||||
})
|
||||
|
||||
test('a session that still owes its second factor creates nothing', async () => {
|
||||
if (!twoFactor) {return}
|
||||
const half = await passwordOnly('[email protected]')
|
||||
expect((await post('/users', { email: '[email protected]', password: PASSWORD }, half)).status).toBe(403)
|
||||
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, half)).status).toBe(403)
|
||||
expect((await post('/crew', { email: '[email protected]', password: PASSWORD }, half)).status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
// Closing `create` alone is little help while Payload's default for `update` and `delete` is "any logged-in user".
|
||||
describe('nobody takes an account over (accounts.adminOnlyWrite)', () => {
|
||||
const NEW = 'taken-over-password-1'
|
||||
let admin: Session
|
||||
let visitor: Session
|
||||
let editor: Session
|
||||
let plain: Session
|
||||
|
||||
beforeAll(async () => {
|
||||
admin = await login('users', '[email protected]')
|
||||
visitor = await login('customers', '[email protected]')
|
||||
await make('users', { email: '[email protected]', roles: ['editor'] })
|
||||
await make('users', { email: '[email protected]', roles: ['user'] })
|
||||
editor = await login('users', '[email protected]')
|
||||
plain = await login('users', '[email protected]')
|
||||
await make('agents', { email: '[email protected]', roles: ['admin'] })
|
||||
await make('agents', { email: '[email protected]', roles: ['editor'] })
|
||||
await make('staff2', { email: '[email protected]' })
|
||||
await make('crew', { email: '[email protected]', roles: ['boss'] })
|
||||
await make('crew', { email: '[email protected]', roles: ['worker'] })
|
||||
})
|
||||
|
||||
test.each(['agents', 'staff2', 'crew'])('%s (the project\'s own staff collection, no rules): a visitor account and an anonymous request change and delete nothing', async (collection) => {
|
||||
const email = { agents: '[email protected]', crew: '[email protected]', staff2: '[email protected]' }[collection]!
|
||||
const id = await idOf(collection, email)
|
||||
for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
|
||||
// before: 200 for the visitor — a staff account's password and roles
|
||||
expect([who, (await patch(`/${collection}/${id}`, { password: NEW, roles: ['admin'] }, session)).status]).toEqual([who, 403])
|
||||
await patch(`/${collection}?where[email][equals]=${email}`, { password: NEW }, session) // bulk: whatever it answers…
|
||||
expect([who, (await remove(`/${collection}/${id}`, session)).status]).toEqual([who, 403])
|
||||
await remove(`/${collection}?where[email][equals]=${email}`, session)
|
||||
}
|
||||
// …nothing happened
|
||||
expect(await idOf(collection, email)).toBe(id)
|
||||
expect(await canLogIn(collection, email, NEW)).toBe(false)
|
||||
expect(await canLogIn(collection, email)).toBe(true)
|
||||
})
|
||||
|
||||
test('where the roles are the plugin\'s: an admin changes and deletes; anyone else only its own account, and not its roles', async () => {
|
||||
const victim = await idOf('agents', '[email protected]')
|
||||
const own = await idOf('agents', '[email protected]')
|
||||
const agentEditor = await login('agents', '[email protected]')
|
||||
// an editor of the same collection, and an editor / plain user of the panel's collection
|
||||
for (const [who, session] of [['agent editor', agentEditor], ['editor', editor], ['plain', plain]] as [string, Session][]) {
|
||||
expect([who, (await patch(`/agents/${victim}`, { password: NEW }, session)).status]).toEqual([who, 403])
|
||||
expect([who, (await remove(`/agents/${victim}`, session)).status]).toEqual([who, 403])
|
||||
}
|
||||
expect(await canLogIn('agents', '[email protected]', NEW)).toBe(false)
|
||||
// its own account: yes — and never a delete
|
||||
expect((await patch(`/agents/${own}`, { password: 'my-own-new-password-1' }, agentEditor)).status).toBe(200)
|
||||
expect(await canLogIn('agents', '[email protected]', 'my-own-new-password-1')).toBe(true)
|
||||
expect((await remove(`/agents/${own}`, agentEditor)).status).toBe(403)
|
||||
// the injected collection: the same, and the roles field is the admin's
|
||||
const me = await idOf('users', '[email protected]')
|
||||
await patch(`/users/${me}`, { roles: ['admin'] }, editor)
|
||||
expect(((await payload.findByID({ id: me as never, collection: 'users' as never })) as { roles?: string[] }).roles).toEqual(['editor'])
|
||||
expect((await patch(`/users/${await idOf('users', '[email protected]')}`, { password: NEW }, editor)).status).toBe(403)
|
||||
// an admin: everything
|
||||
const spare = await make('agents', { email: '[email protected]', roles: ['user'] })
|
||||
expect((await patch(`/agents/${spare.id}`, { roles: ['editor'] }, admin)).status).toBe(200)
|
||||
expect((await remove(`/agents/${spare.id}`, admin)).status).toBe(200)
|
||||
})
|
||||
|
||||
test('where the roles are the project\'s own: accounts of that collection keep working as before; a plugin admin too; nobody else', async () => {
|
||||
// the plugin cannot tell a `boss` from a `worker`: the project's own rules decide inside the collection
|
||||
const boss = await login('crew', '[email protected]')
|
||||
expect((await post('/crew', { email: '[email protected]', password: PASSWORD, roles: ['worker'] }, boss)).status).toBe(201)
|
||||
const id = await idOf('crew', '[email protected]')
|
||||
expect((await patch(`/crew/${id}`, { roles: ['boss'] }, boss)).status).toBe(200)
|
||||
expect((await remove(`/crew/${id}`, boss)).status).toBe(200)
|
||||
// an admin of the panel's collection
|
||||
expect((await post('/crew', { email: '[email protected]', password: PASSWORD, roles: ['worker'] }, admin)).status).toBe(201)
|
||||
// an editor of another staff collection, a visitor, nobody
|
||||
for (const [who, session] of [['editor', editor], ['plain', plain], ['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
|
||||
expect([who, (await post('/crew', { email: `by-${who}@crew.example.com`, password: PASSWORD, roles: ['boss'] }, session)).status]).toEqual([who, 403])
|
||||
}
|
||||
})
|
||||
|
||||
test('the doctor\'s check: no staff collection is open to an account of another collection', async () => {
|
||||
expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([])
|
||||
expect(await openSignUpCollections(payload as never)).toEqual(['customers'])
|
||||
})
|
||||
})
|
||||
|
||||
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)
|
||||
|
||||
beforeAll(async () => {
|
||||
await make('users', { email: '[email protected]', roles: ['admin'] })
|
||||
await make('users', { email: '[email protected]', roles: ['editor'] })
|
||||
await make('users', { email: '[email protected]', roles: ['user'] })
|
||||
await make('customers', { email: '[email protected]' })
|
||||
})
|
||||
|
||||
test('Payload reports panel access for an admin and an editor, not for a plain user or a visitor account', async () => {
|
||||
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(true)
|
||||
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(true)
|
||||
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(false)
|
||||
expect(await canAccessAdmin(await login('customers', '[email protected]'))).toBe(false)
|
||||
expect(await canAccessAdmin({})).toBe(false)
|
||||
})
|
||||
|
||||
test('the API is not touched: the plain user still logs in and reads its own account', async () => {
|
||||
const session = await login('users', '[email protected]')
|
||||
const me = (await (await call('/users/me', session)).json()) as { user?: { email?: string } }
|
||||
expect(me.user?.email).toBe('[email protected]')
|
||||
})
|
||||
|
||||
test('the start-up count: how many accounts are below the panel role', async () => {
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the password rule (accounts.password): twelve characters when a password is set', () => {
|
||||
let admin: Session
|
||||
const messageOf = async (res: Response) => JSON.stringify(await res.json())
|
||||
|
||||
beforeAll(async () => {
|
||||
admin = await login('users', '[email protected]')
|
||||
})
|
||||
|
||||
test('a new account: 11 characters refused with a clear message, 12 accepted', async () => {
|
||||
const short = await post('/users', { email: '[email protected]', password: 'abcdefghijk', roles: ['editor'] }, admin)
|
||||
expect(short.status).toBe(400)
|
||||
expect(await messageOf(short)).toMatch(/at least 12 characters/)
|
||||
expect((await post('/users', { email: '[email protected]', password: 'abcdefghijkl', roles: ['editor'] }, admin)).status).toBe(201)
|
||||
// counted in characters, not bytes
|
||||
expect((await post('/users', { email: '[email protected]', password: 'zażółć gęślą', roles: ['editor'] }, admin)).status).toBe(201)
|
||||
})
|
||||
|
||||
test('in Polish for a Polish panel', async () => {
|
||||
const res = await post('/users', { email: '[email protected]', password: 'krotkie', roles: ['editor'] }, { ...admin, 'accept-language': 'pl' })
|
||||
expect(res.status).toBe(400)
|
||||
expect(await messageOf(res)).toMatch(/co najmniej 12 znaków/)
|
||||
})
|
||||
|
||||
test('not the account\'s own e-mail address', async () => {
|
||||
const same = await post('/users', { email: '[email protected]', password: '[email protected]', roles: ['editor'] }, admin)
|
||||
expect(same.status).toBe(400)
|
||||
expect(await messageOf(same)).toMatch(/same as the e-mail/)
|
||||
})
|
||||
|
||||
test('changing a password: checked; changing anything else: not', async () => {
|
||||
const doc = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0]
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'tooshort' }), method: 'PATCH' })).status).toBe(400)
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: '[email protected]' }), method: 'PATCH' })).status).toBe(400) // its own address, looked up
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })).status).toBe(200)
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'a-new-long-password' }), method: 'PATCH' })).status).toBe(200)
|
||||
await login('users', '[email protected]', 'a-new-long-password')
|
||||
})
|
||||
|
||||
test('an EXISTING shorter password keeps logging in — nothing is checked at login', async () => {
|
||||
// an account as an earlier version left it: a 6-character password, stored the way Payload stored it then
|
||||
const old = await make('users', { email: '[email protected]', roles: ['editor'] })
|
||||
const salt = randomBytes(32).toString('hex')
|
||||
const hash = pbkdf2Sync('short1', salt, 25000, 512, 'sha256').toString('hex')
|
||||
await payload.db.updateOne({ id: old.id, collection: 'users' as never, data: { hash, salt } as never })
|
||||
const session = await login('users', '[email protected]', 'short1')
|
||||
expect(((await (await call('/users/me', session)).json()) as { user?: { email?: string } }).user?.email).toBe('[email protected]')
|
||||
// the rule meets it the next time the password is changed
|
||||
expect((await call(`/users/${old.id}`, session, { body: JSON.stringify({ password: 'short2' }), method: 'PATCH' })).status).toBe(400)
|
||||
})
|
||||
|
||||
test('a reset by e-mail is held to the rule too', async () => {
|
||||
const token = await payload.forgotPassword({ collection: 'users' as never, data: { email: '[email protected]' }, disableEmail: true })
|
||||
const short = await post('/users/reset-password', { password: 'tooshort', token })
|
||||
expect(short.status).toBe(400)
|
||||
expect(await messageOf(short)).toMatch(/at least 12 characters/)
|
||||
// not the account's own address either: there is no e-mail in a reset request, the account is found by its token
|
||||
const own = await post('/users/reset-password', { password: '[email protected]', token })
|
||||
expect(own.status).toBe(400)
|
||||
expect(await messageOf(own)).toMatch(/same as the e-mail/)
|
||||
expect((await post('/users/reset-password', { password: 'reset-to-a-long-one', token })).status).toBe(200)
|
||||
})
|
||||
|
||||
test('a bulk update is checked against every account it matches; a password that is not text is refused, not a server error', async () => {
|
||||
await make('users', { email: '[email protected]', roles: ['editor'] })
|
||||
const bulk = await patch('/users?where[email][equals][email protected]', { password: '[email protected]' }, admin)
|
||||
expect(JSON.stringify(await bulk.json())).toMatch(/same as the e-mail/)
|
||||
expect(await canLogIn('users', '[email protected]', '[email protected]')).toBe(false)
|
||||
for (const notText of [123456789012, ['a-long-enough-one'], { length: 20 }]) {
|
||||
const res = await post('/users', { email: `nt-${Math.random().toString(36).slice(2)}@example.com`, password: notText, roles: ['editor'] }, admin)
|
||||
expect([JSON.stringify(notText), res.status]).toEqual([JSON.stringify(notText), 400])
|
||||
}
|
||||
})
|
||||
|
||||
test('visitor collections are not touched', async () => {
|
||||
expect((await post('/customers', { email: '[email protected]', password: 'abc123' })).status).toBe(201)
|
||||
})
|
||||
|
||||
test('the option, the checker and the switch', async () => {
|
||||
expect(resolvePasswordRule(undefined)).toEqual({ minLength: 12 })
|
||||
expect(resolvePasswordRule({ minLength: 16 })).toEqual({ minLength: 16 })
|
||||
expect(resolvePasswordRule(false)).toBeNull()
|
||||
for (const bad of ['12', 0, -1, 1.5, Number.NaN]) {expect(() => resolvePasswordRule({ minLength: bad as never })).toThrow(/minLength must be/)}
|
||||
expect(checkPassword('abcdefghijk')).toBe('short')
|
||||
expect(checkPassword('abcdefghijkl')).toBeNull()
|
||||
expect(checkPassword('abcd', { minLength: 4 })).toBeNull()
|
||||
expect(checkPassword('[email protected] ', { email: '[email protected]', minLength: 4 })).toBe('email')
|
||||
const hooks = async (options: Record<string, unknown>) =>
|
||||
(await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0])
|
||||
expect(await hooks({})).toEqual([['customers', 0], ['users', 1]])
|
||||
expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 0], ['users', 0]])
|
||||
expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]])
|
||||
})
|
||||
})
|
||||
|
||||
describe('accounts.panelRole: the config', () => {
|
||||
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
|
||||
ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config)
|
||||
const adminRule = (config: Config) => config.collections!.find((c) => c.slug === 'users')!.access?.admin
|
||||
|
||||
test('on by default at editor; a role, false and accounts: false change it', async () => {
|
||||
expect(resolvePanelRole(undefined)).toBe('editor')
|
||||
expect(resolvePanelRole('admin')).toBe('admin')
|
||||
expect(resolvePanelRole('user')).toBeNull() // the lowest role = everyone, as before
|
||||
expect(resolvePanelRole(false)).toBeNull()
|
||||
expect(() => resolvePanelRole('boss' as never)).toThrow(/panelRole must be one of/)
|
||||
expect(adminRule(await build({}))).toBeTypeOf('function')
|
||||
expect(adminRule(await build({ accounts: { panelRole: 'user' } }))).toBeUndefined()
|
||||
expect(adminRule(await build({ accounts: { panelRole: false } }))).toBeUndefined()
|
||||
expect(adminRule(await build({ accounts: false }))).toBeUndefined()
|
||||
// without `access` there are no roles to ask about
|
||||
expect(adminRule(await ipalKit({ i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config))).toBeUndefined()
|
||||
})
|
||||
|
||||
test("the project's own rule wins: on its own collection, and through access.authAccess", async () => {
|
||||
const mine = () => true
|
||||
const own = await build({}, { collections: [{ slug: 'users', access: { admin: mine }, auth: true, fields: [] }] } as never)
|
||||
expect(adminRule(own)).toBe(mine)
|
||||
const injected = await build({ access: { authAccess: { admin: mine }, authCollection: 'users' } })
|
||||
expect(adminRule(injected)).toBe(mine)
|
||||
// the project's own collection without a rule gets the plugin's
|
||||
const plain = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
|
||||
expect(adminRule(plain)).toBeTypeOf('function')
|
||||
})
|
||||
|
||||
test('the rule looks at the role, not at the second factor, and only at staff accounts', () => {
|
||||
const source = { staffCollections: ['users'] }
|
||||
const ask = (user: unknown, minimum?: 'admin' | 'editor') => panelAccess(minimum)({ req: { payload: source, user } } as never)
|
||||
expect(ask({ collection: 'users', roles: ['editor'] })).toBe(true)
|
||||
expect(ask({ _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] })).toBe(true) // still owes its code: the 2FA screens are part of the panel
|
||||
expect(ask({ collection: 'users', roles: ['user'] })).toBe(false)
|
||||
expect(ask({ collection: 'users', roles: [] })).toBe(false)
|
||||
expect(ask({ collection: 'users' })).toBe(false)
|
||||
expect(ask({ collection: 'customers', roles: ['admin'] })).toBe(false)
|
||||
expect(ask(null)).toBe(false)
|
||||
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 rules get them; a rule the project wrote stays; other collections are not touched', async () => {
|
||||
const config = await build({})
|
||||
expect(of(config, 'staff2').access?.create).toBeTypeOf('function')
|
||||
expect(of(config, 'staff2').access?.update).toBeTypeOf('function')
|
||||
expect(of(config, 'staff2').access?.delete).toBeTypeOf('function')
|
||||
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, 'customers').access?.update).toBeUndefined() // not a staff collection
|
||||
expect(of(config, 'pages').access?.create).toBeUndefined()
|
||||
const mine = () => true
|
||||
const own = await build({}, { collections: [{ slug: 'users', access: { create: mine, delete: mine, update: mine }, auth: true, fields: [] }, { slug: 'staff2', auth: true, fields: [] }] } as never)
|
||||
expect([of(own, 'users').access?.create, of(own, 'users').access?.update, of(own, 'users').access?.delete]).toEqual([mine, mine, mine])
|
||||
// the collection that carries the plugin's roles: the admin rule, although the field is injected later
|
||||
const ownNoRule = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
|
||||
expect(of(ownNoRule, 'users').access?.create).toBe(staffCreateAccess)
|
||||
expect(of(ownNoRule, 'users').access?.delete).toBe(staffCreateAccess)
|
||||
})
|
||||
|
||||
test('whose roles: the plugin\'s rule only where the roles are the plugin\'s', () => {
|
||||
const roles = (options: unknown[]) => ({ slug: 'x', fields: [{ name: 'roles', type: 'select', hasMany: true, options }] }) as never
|
||||
expect(hasPluginRoles(roles(['user', 'editor', 'admin']))).toBe(true)
|
||||
expect(hasPluginRoles(roles([{ label: 'Admin', value: 'admin' }, { label: 'Editor', value: 'editor' }]))).toBe(true)
|
||||
expect(hasPluginRoles(roles(['superadmin', 'writer']))).toBe(false)
|
||||
expect(hasPluginRoles(roles(['admin', 'writer']))).toBe(false) // one foreign value: the project's own roles
|
||||
expect(hasPluginRoles(roles([]))).toBe(false)
|
||||
expect(hasPluginRoles({ slug: 'x', fields: [] })).toBe(false)
|
||||
expect(hasPluginRoles({ slug: 'x', fields: [{ name: 'roles', type: 'text' }] } as never)).toBe(false)
|
||||
|
||||
const staff = { staffCollections: ['users', 'agents', 'crew'] }
|
||||
const ask = (rule: ReturnType<typeof staffUpdateAccess>, user: unknown) => rule({ req: { payload: staff, user } } as never)
|
||||
const admin = { id: 1, collection: 'users', roles: ['admin'] }
|
||||
const editor = { id: 2, collection: 'users', roles: ['editor'] }
|
||||
const customer = { id: 2, collection: 'customers', roles: ['admin'] }
|
||||
// the plugin's roles
|
||||
expect(ask(staffCreateAccess, admin)).toBe(true)
|
||||
expect(ask(staffCreateAccess, editor)).toBe(false)
|
||||
expect(ask(staffUpdateAccess('users'), admin)).toBe(true)
|
||||
expect(ask(staffUpdateAccess('users'), editor)).toEqual({ id: { equals: 2 } })
|
||||
expect(ask(staffUpdateAccess('agents'), editor)).toBe(false) // "self" is an account of THAT collection: id 2 of another one is somebody else
|
||||
expect(ask(staffUpdateAccess('users'), customer)).toBe(false)
|
||||
expect(ask(staffUpdateAccess('users'), null)).toBe(false)
|
||||
// the project's own roles
|
||||
const crew = sameStaffCollectionAccess('crew')
|
||||
expect(ask(crew, { id: 5, collection: 'crew', roles: ['worker'] })).toBe(true)
|
||||
expect(ask(crew, admin)).toBe(true)
|
||||
expect(ask(crew, editor)).toBe(false)
|
||||
expect(ask(crew, customer)).toBe(false)
|
||||
expect(ask(crew, null)).toBe(false)
|
||||
expect(ask(sameStaffCollectionAccess('shop'), { id: 5, collection: 'shop' })).toBe(false) // not a staff collection: never by this rule
|
||||
})
|
||||
|
||||
test('the switches', async () => {
|
||||
const guards = (config: Config, slug: string) => of(config, slug).hooks?.beforeOperation?.length ?? 0
|
||||
const firstUser = (config: Config, slug: string) => (of(config, slug).endpoints || []).filter((e) => e.path === '/first-register').length
|
||||
const on = await build({})
|
||||
// staff collections: the password rule; every auth collection: the first-user endpoint
|
||||
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([1, 1, 0, 0])
|
||||
expect([firstUser(on, 'users'), firstUser(on, 'staff2'), firstUser(on, 'customers'), firstUser(on, 'pages')]).toEqual([1, 1, 1, 0])
|
||||
const payloadWay = await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false } })
|
||||
expect(of(payloadWay, 'staff2').access).toBeUndefined()
|
||||
expect([guards(payloadWay, 'staff2'), firstUser(payloadWay, 'staff2')]).toEqual([0, 0])
|
||||
// each switch on its own
|
||||
const createOnly = await build({ accounts: { adminOnlyWrite: false } })
|
||||
expect([typeof of(createOnly, 'staff2').access?.create, of(createOnly, 'staff2').access?.update, of(createOnly, 'staff2').access?.delete]).toEqual(['function', undefined, undefined])
|
||||
const writeOnly = await build({ accounts: { adminOnlyCreate: false } })
|
||||
expect([of(writeOnly, 'staff2').access?.create, typeof of(writeOnly, 'staff2').access?.update, typeof of(writeOnly, 'staff2').access?.delete]).toEqual([undefined, 'function', 'function'])
|
||||
const off = await build({ accounts: false })
|
||||
expect(of(off, 'staff2').access?.create).toBeUndefined()
|
||||
expect(of(off, 'staff2').access?.update).toBeUndefined()
|
||||
expect([guards(off, 'users'), firstUser(off, 'users')]).toEqual([0, 0])
|
||||
await expect(build({ accounts: { firstUserRoute: 'everyone' } })).rejects.toThrow(/firstUserRoute must be/)
|
||||
// a collection that turned its endpoints off keeps them off
|
||||
const noEndpoints = await build({}, { collections: [{ slug: 'staff2', auth: true, endpoints: false, fields: [] }] } as never)
|
||||
expect(of(noEndpoints, 'staff2').endpoints).toBe(false)
|
||||
// without `access` the rules still apply to the panel's login collection — as "an account of this collection":
|
||||
// without the plugin's roles nobody is an admin to it
|
||||
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).toBeTypeOf('function')
|
||||
expect(of(noAccess, 'users').access?.create).not.toBe(staffCreateAccess)
|
||||
})
|
||||
|
||||
test('the rules are on the collections BEFORE the 2FA package wraps them', async () => {
|
||||
// the package gives every collection a create / update / delete of its own; afterwards "no rule" cannot be seen
|
||||
const seen: Record<string, unknown> = {}
|
||||
const factory = (o: { collection: string }) => (c: Config) => {
|
||||
for (const col of c.collections ?? []) {seen[col.slug] = { ...col.access }}
|
||||
return withTotpParts({ ...c, collections: (c.collections ?? []).map((col) => ({ ...col, access: { create: () => true, delete: () => true, update: () => true, ...col.access } })) }, o.collection)
|
||||
}
|
||||
await build({ twoFactor: { issuer: 'A', plugin: factory as never } })
|
||||
expect(Object.keys(seen.staff2 as object).sort()).toEqual(['create', 'delete', 'update'])
|
||||
expect(seen.customers).toEqual({ create: expect.any(Function) })
|
||||
})
|
||||
|
||||
test('access.firstUserAdmin: false and the panel role: the first account must be able to get in', async () => {
|
||||
const adminRule = (config: Config) => of(config, 'users').access?.admin
|
||||
// the default panel role steps aside (a line at start says so)…
|
||||
expect(adminRule(await build({ access: { authCollection: 'users', firstUserAdmin: false } }))).toBeUndefined()
|
||||
// …a role the project asked for is refused at start, with the ways out
|
||||
await expect(build({ access: { authCollection: 'users', firstUserAdmin: false }, accounts: { panelRole: 'editor' } })).rejects.toThrow(/nobody who can open the panel[\s\S]*defaultRole/)
|
||||
await expect(build({ access: { authCollection: 'users', defaultRole: 'editor', firstUserAdmin: false }, accounts: { panelRole: 'admin' } })).rejects.toThrow(/nobody who can open the panel/)
|
||||
// a default role that reaches the panel is fine
|
||||
expect(adminRule(await build({ access: { authCollection: 'users', defaultRole: 'editor', firstUserAdmin: false } }))).toBeTypeOf('function')
|
||||
expect(adminRule(await build({ access: { authCollection: 'users', defaultRole: 'editor', firstUserAdmin: false }, accounts: { panelRole: 'editor' } }))).toBeTypeOf('function')
|
||||
// and nothing to decide when the rule is off
|
||||
expect(adminRule(await build({ access: { authCollection: 'users', firstUserAdmin: false }, accounts: { panelRole: false } }))).toBeUndefined()
|
||||
})
|
||||
|
||||
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'])
|
||||
})
|
||||
|
||||
test('staffCollectionsOpenToOthers: staff collections an account of a non-staff collection may write to', async () => {
|
||||
const anyone = ({ req }: { req: { user: unknown } }) => Boolean(req.user) // Payload's default
|
||||
const collections = {
|
||||
agents: { config: { slug: 'agents', access: { create: staffCreateAccess, delete: anyone, update: anyone }, auth: true } },
|
||||
customers: { config: { slug: 'customers', access: { create: () => true, update: anyone }, auth: true } }, // not staff: not its business
|
||||
users: { config: { slug: 'users', access: { create: staffCreateAccess, delete: staffCreateAccess, update: staffUpdateAccess('users') }, auth: true } },
|
||||
weird: { config: { slug: 'weird', access: { update: () => { throw new Error('x') } }, auth: true } },
|
||||
}
|
||||
expect(await staffCollectionsOpenToOthers({ collections, config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['agents', 'weird'] } } } } as never)).toEqual(['agents:delete', 'agents:update', 'weird:create', 'weird:delete']) // no rule = Payload's default, open; a rule that throws = closed
|
||||
})
|
||||
})
|
||||
}
|
||||
+14
-1
@@ -169,6 +169,11 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
|
||||
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(2), state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
|
||||
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(48), state: 'degraded' } })).toEqual(['turnstile-degraded:error'])
|
||||
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
|
||||
// the day is counted in hours from the middle of the run's date (the clock itself when the run is for today), not to its end:
|
||||
// a state that began late the evening before is not "a day old" in the morning
|
||||
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(13), state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
|
||||
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(23), state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
|
||||
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(24), state: 'degraded' } })).toEqual(['turnstile-degraded:error'])
|
||||
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(48), state: 'ok' } })).toEqual([])
|
||||
expect(await run(cfg, ['turnstile-degraded'], { turnstile: null })).toEqual([])
|
||||
expect(await run(cfg, ['turnstile-degraded'])).toEqual([]) // no deep status: nothing to say
|
||||
@@ -198,6 +203,14 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
|
||||
expect(await run(cfg, ['open-signup'])).toEqual([])
|
||||
})
|
||||
|
||||
test('staff-accounts-open: a staff collection an account of another collection may write to is an error', async () => {
|
||||
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
|
||||
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:delete', 'agents:update', 'users:create'] })).toEqual(['staff-accounts-open:error', 'staff-accounts-open:error', 'staff-accounts-open:error'])
|
||||
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: [] })).toEqual([])
|
||||
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: null })).toEqual([])
|
||||
expect(await run(cfg, ['staff-accounts-open'])).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) => ({
|
||||
@@ -498,7 +511,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', 'openSignUp', 'pendingCookies', 'plugin', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
|
||||
expect(Object.keys(status).sort()).toEqual(['node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOpenToOthers', '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 () => {
|
||||
|
||||
@@ -10,7 +10,7 @@ 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 { requestFromOwnOrigin } from '../src/modules/security/totp/sameOrigin.js'
|
||||
import { clearReportedOrigins, reportRefusedOrigin, requestFromOwnOrigin } from '../src/modules/security/totp/sameOrigin.js'
|
||||
import {
|
||||
ensurePayloadGuarded,
|
||||
guardPayloadAccess,
|
||||
@@ -422,6 +422,14 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
['a sibling subdomain', { host: 'site.example', origin: 'https://blog.site.example' }, { serverURL: 'https://site.example' }, false],
|
||||
['another site', { host: 'site.example', origin: 'https://evil.example' }, {}, false],
|
||||
['the same host on another port', { host: 'site.example', origin: 'https://site.example:8443' }, {}, false],
|
||||
// a proxy that writes the default port out
|
||||
['the forwarded host with :443 for an https origin', { host: 'internal:3000', origin: 'https://site.example', 'x-forwarded-host': 'site.example:443' }, {}, true],
|
||||
['the host with :80 for an http origin', { host: 'site.example:80', origin: 'http://site.example' }, {}, true],
|
||||
['Origin with the default port written out', { host: 'site.example', origin: 'https://site.example:443' }, {}, true],
|
||||
[':443 is not the default of http', { host: 'site.example:443', origin: 'http://site.example' }, {}, false],
|
||||
[':80 is not the default of https', { host: 'site.example:80', origin: 'https://site.example' }, {}, false],
|
||||
// nginx's plain proxy_pass: Host rewritten, no X-Forwarded-Host, no serverURL — the site's own page is refused (and reported, below)
|
||||
['a proxy that hides the address, nothing configured', { host: 'upstream:3000', origin: 'https://site.example' }, {}, false],
|
||||
['Origin: null (a sandboxed page)', { host: 'site.example', origin: 'null' }, {}, false],
|
||||
['Sec-Fetch-Site: same-origin without Origin', { 'sec-fetch-site': 'same-origin' }, {}, true],
|
||||
['Sec-Fetch-Site: same-site (a sibling subdomain) without Origin', { 'sec-fetch-site': 'same-site' }, {}, false],
|
||||
@@ -430,6 +438,29 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
expect(requestFromOwnOrigin(req(headers as Record<string, string>, config))).toBe(expected)
|
||||
})
|
||||
|
||||
test('a refusal is never silent: one line per origin, with the ways to allow it', () => {
|
||||
clearReportedOrigins()
|
||||
const warn = vi.fn()
|
||||
const hidden = { headers: new Headers({ host: 'upstream:3000', origin: 'https://site.example' }), payload: { config: {}, logger: { warn } }, url: 'http://upstream:3000/api/verify-totp' }
|
||||
expect(reportRefusedOrigin(hidden)).toBe(true)
|
||||
expect(reportRefusedOrigin(hidden)).toBe(false) // once per origin
|
||||
expect(warn).toHaveBeenCalledTimes(1)
|
||||
const line = warn.mock.calls[0][0] as string
|
||||
expect(line).toContain('origin "https://site.example"')
|
||||
expect(line).toContain('host upstream:3000')
|
||||
expect(line).toMatch(/serverURL/)
|
||||
expect(line).toMatch(/sameOrigin: \{ origins: \['https:\/\/site\.example'\] \}/)
|
||||
expect(line).toMatch(/X-Forwarded-Host/)
|
||||
// another origin gets its own line; a request without Origin is named by what the browser said
|
||||
expect(reportRefusedOrigin({ ...hidden, headers: new Headers({ origin: 'https://evil.example' }) })).toBe(true)
|
||||
expect(reportRefusedOrigin({ ...hidden, headers: new Headers({ 'sec-fetch-site': 'cross-site' }) })).toBe(true)
|
||||
expect(warn.mock.calls[2][0]).toContain('sec-fetch-site: cross-site')
|
||||
// the log cannot be flooded with made-up origins
|
||||
for (let i = 0; i < 200; i++) {reportRefusedOrigin({ ...hidden, headers: new Headers({ origin: `https://n${i}.example` }) })}
|
||||
expect(warn.mock.calls.length).toBeLessThanOrEqual(50)
|
||||
clearReportedOrigins()
|
||||
})
|
||||
|
||||
test('twoFactor.sameOrigin.origins adds an origin', () => {
|
||||
const other = req({ host: 'site.example', origin: 'https://panel.example.org' })
|
||||
expect(requestFromOwnOrigin(other)).toBe(false)
|
||||
@@ -438,13 +469,15 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
|
||||
test('wired by default on verify and setup, before the limit; not on other endpoints; sameOrigin: false turns it off', async () => {
|
||||
const handler = vi.fn(() => Response.json({ ok: true }))
|
||||
const warn = vi.fn()
|
||||
clearReportedOrigins()
|
||||
const withEndpoints = (o: { collection: string }) => (c: Config) => ({
|
||||
...withTotpParts(c, o.collection),
|
||||
endpoints: [...(c.endpoints ?? []), ...['/verify-totp', '/setup-totp', '/remove-totp'].map((path) => ({ handler, method: 'post' as const, path }))],
|
||||
})
|
||||
const build = (twoFactor: Record<string, unknown> = {}) => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config)
|
||||
const call = async (config: Config, path: string, headers: Record<string, string>, user: Record<string, unknown>) =>
|
||||
(await config.endpoints!.find((e) => e.path === path)!.handler({ headers: new Headers(headers), i18n: undefined, payload: { config, logger: { warn: () => {} } }, url: 'https://site.example/api' + path, user: { id: 5, collection: 'users', ...user } } as never)).status
|
||||
(await config.endpoints!.find((e) => e.path === path)!.handler({ headers: new Headers(headers), i18n: undefined, payload: { config, logger: { warn } }, url: 'https://site.example/api' + path, user: { id: 5, collection: 'users', ...user } } as never)).status
|
||||
const elsewhere = { host: 'site.example', origin: 'https://blog.site.example' }
|
||||
const own = { host: 'site.example', origin: 'https://site.example' }
|
||||
const owes = { _strategy: 'local-jwt', hasTotp: true }
|
||||
@@ -455,6 +488,8 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
// twenty attempts from elsewhere: all refused, none counted
|
||||
for (let i = 0; i < 20; i++) {expect(await call(config, '/verify-totp', elsewhere, owes)).toBe(403)}
|
||||
expect(handler).not.toHaveBeenCalled()
|
||||
// …and said in the log, once, with the origin and how to allow it
|
||||
expect(warn.mock.calls.filter(([line]) => String(line).includes('blog.site.example'))).toHaveLength(1)
|
||||
for (let i = 0; i < 5; i++) {expect(await call(config, '/verify-totp', own, owes)).toBe(200)} // the owner still has all five
|
||||
expect(await call(config, '/verify-totp', own, owes)).toBe(429)
|
||||
expect(await call(config, '/setup-totp', elsewhere, fresh)).toBe(403)
|
||||
|
||||
@@ -91,10 +91,11 @@ describe('reading', () => {
|
||||
|
||||
describe('saving', () => {
|
||||
test('another field alone: the secrets stay, and the answer does not carry them', async () => {
|
||||
const res = await save({ smtpHost: 'smtp2.example.com' })
|
||||
// (a field the SMTP password belongs to — server, port, user — asks for it again: writeOnlySecretsBound.test.ts)
|
||||
const res = await save({ smtpFromName: 'The site' })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).not.toContain('S3CRET')
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'smtp2.example.com', smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
|
||||
expect(await stored()).toMatchObject({ smtpFromName: 'The site', smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
|
||||
})
|
||||
|
||||
test('what the panel sends back when nothing was typed (the mask), an empty value, null: kept', async () => {
|
||||
@@ -132,9 +133,13 @@ describe('saving', () => {
|
||||
|
||||
test('GraphQL mutation: the mask keeps, a value replaces', async () => {
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: SMTP } as never })
|
||||
let out = await gql(`mutation { updateSiteIntegration(data: { smtpPassword: "${SECRET_MASK}", smtpUser: "mailer2" }) { smtpPassword smtpUser } }`)
|
||||
let out = await gql(`mutation { updateSiteIntegration(data: { smtpPassword: "${SECRET_MASK}", smtpFromName: "By GraphQL" }) { smtpPassword smtpFromName } }`)
|
||||
expect(out.errors).toBeUndefined()
|
||||
expect(out.data?.updateSiteIntegration).toMatchObject({ smtpPassword: SECRET_MASK, smtpUser: 'mailer2' })
|
||||
expect(out.data?.updateSiteIntegration).toMatchObject({ smtpFromName: 'By GraphQL', smtpPassword: SECRET_MASK })
|
||||
// a field the password belongs to, without the password: refused here as over REST
|
||||
const moved = await gql(`mutation { updateSiteIntegration(data: { smtpPassword: "${SECRET_MASK}", smtpHost: "other.example.com" }) { smtpHost } }`)
|
||||
expect(moved.errors?.length).toBeGreaterThan(0)
|
||||
expect((await stored()).smtpHost).not.toBe('other.example.com')
|
||||
expect((await stored()).smtpPassword).toBe(SMTP)
|
||||
out = await gql('mutation { updateSiteIntegration(data: { smtpPassword: "S3CRET-by-graphql" }) { smtpPassword } }')
|
||||
expect(JSON.stringify(out)).not.toContain('S3CRET')
|
||||
@@ -155,7 +160,7 @@ describe('the building blocks', () => {
|
||||
for (const nothing of [undefined, null, '', SECRET_MASK]) {expect(write(nothing, { token: 'old' })).toBe('old')}
|
||||
expect(write(SECRET_CLEAR, { token: 'old' })).toBeNull()
|
||||
expect(write(SECRET_MASK, undefined)).toBeNull() // nothing stored: never the mask itself
|
||||
expect(write(SECRET_MASK, { token: SECRET_MASK })).toBe(SECRET_MASK) // (a stored mask is left; it cannot get there through these hooks)
|
||||
expect(write(SECRET_MASK, { token: SECRET_MASK })).toBeNull() // a stored mask is not a secret: never written back
|
||||
expect(write('', { group: { items: [{ token: 'deep' }] } }, ['group', 'items', 0, 'token'])).toBe('deep')
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* Write-only secrets, the two ways a stored value still got out (review of M1):
|
||||
* - the SMTP password went to whatever server an admin session pointed the settings at;
|
||||
* - with versions on for the global, a restore answered with the stored value.
|
||||
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import net from 'node:net'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { buildSiteIntegrations } from '../src/globals/SiteIntegrations/index.js'
|
||||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||||
import { buildKeepSecret, keepSecretBeforeValidate, maskSecretsOnRestore, maskWriteOnlySecrets, SECRET_CLEAR, SECRET_MASK, writeOnlySecret } from '../src/modules/secrets/writeOnly.js'
|
||||
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 = 'a-long-test-password-1'
|
||||
const SMTP = 'S3CRET-smtp-value'
|
||||
const G = '/globals/site-integrations'
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
let auth: Record<string, string>
|
||||
|
||||
const stored = async () => (await payload.findGlobal({ slug: 'site-integrations' as never })) as unknown as Record<string, unknown>
|
||||
const api = (pathname: string, init: RequestInit = {}, headers: Record<string, string> = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...auth, ...headers } })
|
||||
const save = (data: Record<string, unknown>, headers: Record<string, string> = {}) => api(G, { body: JSON.stringify(data), method: 'POST' }, headers)
|
||||
const reset = () => payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpRequireTls: false, smtpUser: 'mailer' } as never })
|
||||
|
||||
/** An SMTP server that offers no STARTTLS and writes down what a client logs in with. */
|
||||
const fakeSmtp = async () => {
|
||||
const seen = { auth: '', mails: 0 }
|
||||
const srv = net.createServer((c) => {
|
||||
c.on('error', () => {})
|
||||
let body = false
|
||||
c.write('220 fake ESMTP\r\n')
|
||||
c.on('data', (d) => {
|
||||
for (const line of d.toString().split('\r\n').filter(Boolean)) {
|
||||
if (body) {
|
||||
if (line === '.') {
|
||||
body = false
|
||||
seen.mails += 1
|
||||
c.write('250 ok\r\n')
|
||||
}
|
||||
} else if (/^EHLO/i.test(line)) {c.write('250-fake\r\n250 AUTH PLAIN LOGIN\r\n')}
|
||||
else if (/^AUTH PLAIN/i.test(line)) {
|
||||
seen.auth = Buffer.from(line.split(' ')[2] ?? '', 'base64').toString().replace(/\0/g, '|')
|
||||
c.write('235 ok\r\n')
|
||||
} else if (/^(?:MAIL|RCPT|RSET)/i.test(line)) {c.write('250 ok\r\n')}
|
||||
else if (/^DATA/i.test(line)) {
|
||||
body = true
|
||||
c.write('354 go\r\n')
|
||||
} else if (/^QUIT/i.test(line)) {c.end('221 bye\r\n')}
|
||||
else {c.write('502 not implemented\r\n')} // STARTTLS among them
|
||||
}
|
||||
})
|
||||
})
|
||||
await new Promise<void>((resolve) => srv.listen(0, '127.0.0.1', resolve))
|
||||
return { close: () => new Promise<void>((resolve) => srv.close(() => resolve())), port: (srv.address() as net.AddressInfo).port, seen }
|
||||
}
|
||||
const testEmail = () => api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
|
||||
db: testDatabase('secrets_bound'),
|
||||
editor: lexicalEditor(),
|
||||
email: mailAdapter(),
|
||||
plugins: [
|
||||
ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
forms: {},
|
||||
// a project that turns versions on for the global
|
||||
globalOverrides: { 'site-integrations': { versions: { drafts: true } } as never },
|
||||
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)
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
|
||||
const login = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }
|
||||
auth = { authorization: `JWT ${login.token}` }
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
beforeEach(async () => {
|
||||
await reset()
|
||||
})
|
||||
|
||||
describe('the SMTP password stays with the server it was saved for (secrets.reenterOnChange)', () => {
|
||||
test('an admin session cannot send the stored password to a server of its own', async () => {
|
||||
const mine = await fakeSmtp()
|
||||
try {
|
||||
// before: 200, then the test e-mail logged in to the new server with the stored password
|
||||
const moved = await save({ smtpHost: '127.0.0.1', smtpPort: mine.port })
|
||||
expect(moved.status).toBe(400)
|
||||
const body = JSON.stringify(await moved.json())
|
||||
expect(body).toMatch(/Enter the password again/)
|
||||
expect(body).toContain('smtpPassword')
|
||||
expect(body).not.toContain(SMTP)
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587 })
|
||||
await testEmail()
|
||||
expect(mine.seen).toEqual({ auth: '', mails: 0 })
|
||||
} finally {
|
||||
await mine.close()
|
||||
}
|
||||
})
|
||||
|
||||
test.each([
|
||||
['the server', { smtpHost: 'other.example.com' }],
|
||||
['the port', { smtpPort: 2525 }],
|
||||
['the user name', { smtpUser: 'someone-else' }],
|
||||
['"require an encrypted connection"', { smtpRequireTls: true }],
|
||||
['the server, sending the mask back as the panel does', { smtpHost: 'other.example.com', smtpPassword: SECRET_MASK }],
|
||||
['the server, with an empty password', { smtpHost: 'other.example.com', smtpPassword: '' }],
|
||||
['the server, in a draft', { _status: 'draft', smtpHost: 'other.example.com' }],
|
||||
])('changing %s without the password is refused, and nothing is stored', async (_what, data) => {
|
||||
const draft = '_status' in data
|
||||
const res = await api(`${G}${draft ? '?draft=true' : ''}`, { body: JSON.stringify(data), method: 'POST' })
|
||||
expect(res.status).toBe(400)
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpUser: 'mailer' })
|
||||
})
|
||||
|
||||
test('in Polish for a Polish panel', async () => {
|
||||
const res = await save({ smtpHost: 'other.example.com' }, { 'accept-language': 'pl' })
|
||||
expect(res.status).toBe(400)
|
||||
expect(JSON.stringify(await res.json())).toMatch(/Wpisz hasło ponownie/)
|
||||
})
|
||||
|
||||
test('with the password typed again the new server is saved; removing the stored value works too', async () => {
|
||||
expect((await save({ smtpHost: 'other.example.com', smtpPassword: 'typed-again' })).status).toBe(200)
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'other.example.com', smtpPassword: 'typed-again' })
|
||||
expect((await save({ smtpHost: 'third.example.com', smtpPassword: SECRET_CLEAR })).status).toBe(200)
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'third.example.com' })
|
||||
expect((await stored()).smtpPassword ?? null).toBeNull()
|
||||
// nothing stored = nothing to protect: the server can be changed freely
|
||||
expect((await save({ smtpHost: 'fourth.example.com' })).status).toBe(200)
|
||||
})
|
||||
|
||||
test('a save that changes nothing the password belongs to keeps it: the same values sent back, other fields, another letter case', async () => {
|
||||
const doc = (await (await api(G)).json()) as Record<string, unknown>
|
||||
for (const key of ['id', 'createdAt', 'updatedAt', 'globalType']) {delete doc[key]}
|
||||
expect((await save(doc)).status).toBe(200) // the whole form, as the panel sends it
|
||||
expect((await save({ smtpFromName: 'The site', smtpHost: ' SMTP.example.com ', smtpPort: '587', smtpUser: 'mailer' })).status).toBe(200)
|
||||
expect((await save({ turnstileSiteKey: 'site-key' })).status).toBe(200)
|
||||
expect(await stored()).toMatchObject({ smtpFromName: 'The site', smtpPassword: SMTP })
|
||||
})
|
||||
|
||||
test('a document saved before the port and the checkbox had a value: their defaults are not a change', async () => {
|
||||
await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), smtpPort: null, smtpRequireTls: null } as never })
|
||||
expect((await save({ smtpFromName: 'Again', smtpPort: 587, smtpRequireTls: false })).status).toBe(200)
|
||||
expect((await stored()).smtpPassword).toBe(SMTP)
|
||||
})
|
||||
|
||||
test('switching to Microsoft Graph asks for nothing (the password is not used there); switching back to another server does', async () => {
|
||||
expect((await save({ emailTransport: 'graph' })).status).toBe(200)
|
||||
expect((await stored()).smtpPassword).toBe(SMTP)
|
||||
expect((await save({ emailTransport: 'smtp', smtpHost: 'other.example.com' })).status).toBe(400)
|
||||
expect((await save({ emailTransport: 'smtp' })).status).toBe(400) // the transport itself is one of the settings
|
||||
expect((await save({ emailTransport: 'smtp', smtpPassword: 'typed-again' })).status).toBe(200)
|
||||
})
|
||||
|
||||
test('server code (a seed, the Local API with access control off) moves the server and keeps the password', async () => {
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'seeded.example.com' } as never })
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'seeded.example.com', smtpPassword: SMTP })
|
||||
})
|
||||
|
||||
test('the option and the building block', () => {
|
||||
const hooksOf = (global: ReturnType<typeof buildSiteIntegrations>) => {
|
||||
const found: unknown[] = []
|
||||
JSON.stringify(global.fields, (_k, v) => {
|
||||
if (v && typeof v === 'object' && (v as { name?: string }).name === 'smtpPassword') {found.push((v as { hooks: { beforeValidate: unknown[] } }).hooks?.beforeValidate?.[0])}
|
||||
return v as unknown
|
||||
})
|
||||
return found[0]
|
||||
}
|
||||
expect(hooksOf(buildSiteIntegrations())).not.toBe(keepSecretBeforeValidate)
|
||||
expect(hooksOf(buildSiteIntegrations({ reenterSecretOnChange: false }))).toBe(keepSecretBeforeValidate)
|
||||
// a field of a project's own
|
||||
const field = writeOnlySecret({ name: 'apiToken', type: 'text' }, { boundTo: ['apiUrl'] })
|
||||
const hook = (field as unknown as { hooks: { beforeValidate: ((args: never) => unknown)[] } }).hooks.beforeValidate[0]
|
||||
const run = (siblingData: unknown, overrideAccess?: boolean) => hook({ originalDoc: { apiToken: 'old', apiUrl: 'https://a.example' }, overrideAccess, path: ['apiToken'], siblingData, value: undefined } as never)
|
||||
expect(run({ apiUrl: 'https://a.example' })).toBe('old')
|
||||
expect(run({})).toBe('old')
|
||||
expect(() => run({ apiUrl: 'https://b.example' })).toThrow()
|
||||
expect(run({ apiUrl: 'https://b.example' }, true)).toBe('old')
|
||||
expect(buildKeepSecret({ appliesWhen: () => false, boundTo: ['apiUrl'] })({ originalDoc: { apiToken: 'old', apiUrl: 'a' }, path: ['apiToken'], siblingData: { apiUrl: 'b' }, value: '' } as never)).toBe('old')
|
||||
})
|
||||
})
|
||||
|
||||
describe('"Require an encrypted connection" (smtpRequireTls)', () => {
|
||||
test('a server that offers no encryption never sees the password; without the option it does, as before', async () => {
|
||||
const plain = await fakeSmtp()
|
||||
try {
|
||||
expect((await save({ smtpHost: '127.0.0.1', smtpPassword: SMTP, smtpPort: plain.port, smtpRequireTls: true })).status).toBe(200)
|
||||
await testEmail()
|
||||
expect(plain.seen).toEqual({ auth: '', mails: 0 })
|
||||
expect((await save({ smtpPassword: SMTP, smtpRequireTls: false })).status).toBe(200)
|
||||
await testEmail()
|
||||
expect(plain.seen.auth).toContain(SMTP)
|
||||
expect(plain.seen.mails).toBe(1)
|
||||
} finally {
|
||||
await plain.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('versions on the global: a restore does not hand the value back', () => {
|
||||
test('REST restore answers with the mask; the stored value is the restored one', async () => {
|
||||
await save({ smtpFromName: 'One' })
|
||||
await save({ smtpFromName: 'Two' })
|
||||
const versions = (await (await api(`${G}/versions?limit=50`)).json()) as { docs: { id: number | string; version: Record<string, unknown> }[] }
|
||||
expect(versions.docs.length).toBeGreaterThan(1)
|
||||
expect(JSON.stringify(versions)).not.toContain(SMTP)
|
||||
const target = versions.docs.find((d) => d.version.smtpFromName === 'One')!
|
||||
const restored = await api(`${G}/versions/${target.id}`, { method: 'POST' })
|
||||
expect(restored.status).toBe(200)
|
||||
const text = await restored.text()
|
||||
// before: the stored password, under `version`
|
||||
expect(text).not.toContain(SMTP)
|
||||
expect(text).toContain(SECRET_MASK)
|
||||
expect(await stored()).toMatchObject({ smtpFromName: 'One', smtpPassword: SMTP })
|
||||
// server code that restores with access control off still gets the document as it is
|
||||
const local = (await payload.restoreGlobalVersion({ id: target.id as never, slug: 'site-integrations' as never })) as unknown as { version?: Record<string, unknown> }
|
||||
expect(JSON.stringify(local)).toContain(SMTP)
|
||||
})
|
||||
|
||||
test('the hook and the walker', () => {
|
||||
const fields = [
|
||||
{ type: 'tabs', tabs: [{ fields: [writeOnlySecret({ name: 'a', type: 'text' }), { name: 'plain', type: 'text' }], label: 'T' }, { name: 'named', fields: [writeOnlySecret({ name: 'b', type: 'text' })] }] },
|
||||
{ name: 'g', type: 'group', fields: [{ type: 'row', fields: [writeOnlySecret({ name: 'c', type: 'text' })] }] },
|
||||
{ name: 'rows', type: 'array', fields: [writeOnlySecret({ name: 'd', type: 'text' })] },
|
||||
{ name: 'layout', type: 'blocks', blocks: [{ slug: 'x', fields: [writeOnlySecret({ name: 'e', type: 'text' })] }] },
|
||||
] as never
|
||||
const doc = () => ({ a: 's', g: { c: 's' }, layout: [{ blockType: 'x', e: 's' }, { blockType: 'other', e: 'kept' }], named: { b: 's' }, plain: 'p', rows: [{ d: 's' }, { d: '' }] })
|
||||
const masked = doc()
|
||||
maskWriteOnlySecrets(masked, fields)
|
||||
expect(masked).toEqual({ a: SECRET_MASK, g: { c: SECRET_MASK }, layout: [{ blockType: 'x', e: SECRET_MASK }, { blockType: 'other', e: 'kept' }], named: { b: SECRET_MASK }, plain: 'p', rows: [{ d: SECRET_MASK }, { d: '' }] })
|
||||
const hook = (extra: Record<string, unknown>) => JSON.stringify(maskSecretsOnRestore({ context: { isRestoringVersion: true }, doc: { version: doc() }, global: { fields }, ...extra } as never))
|
||||
expect(hook({})).not.toContain('"s"')
|
||||
expect(hook({ overrideAccess: true })).toContain('"s"')
|
||||
expect(hook({ context: {} })).toContain('"s"') // an ordinary read: the field hooks did the work already
|
||||
expect(hook({ collection: { fields }, global: undefined })).not.toContain('"s"')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user