From 7002ebbfa6ec45c599250a839dc976724484cfcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 24 Nov 2026 23:57:40 +0100 Subject: [PATCH] M1 review round 2: the transport is no way round, nobody raises its own role, late staff collections R2-1 the SMTP password is bound to server, port and user whatever the transport says; the transport alone is not bound. R2-2 where the plugin's update rule is in force the roles field is closed for the account itself (the plugin's roles: only an admin; roles of the project's own: never one's own). R2-3 auth collections a later plugin adds get the account rules, the password rule and the first-user endpoint when the config goes live; a staff slug that is not an auth collection stops the start. R2-4 smtpRequireTls is taken out: the branch adds no field, column or collection. Also: read (a staff account) and unlock (an admin) defaults on staff collections (accounts.staffOnlyRead); doctor staff-own-roles and read / unlock in staff-accounts-open; r1 NULL against the default, also inside a row; r2 bound values compared exactly. Co-Authored-By: Claude Fable 5.2 --- reference/src/payload-types.ts | 5 - src/globals/SiteIntegrations/fields/smtp.ts | 13 -- src/globals/SiteIntegrations/index.ts | 11 +- src/index.ts | 7 + src/modules/access/selfRegistration.ts | 199 ++++++++++++++++--- src/modules/access/types.ts | 11 + src/modules/admin-i18n/texts/integrations.ts | 4 +- src/modules/doctor/rules/security.ts | 27 ++- src/modules/doctor/status.ts | 10 +- src/modules/doctor/types.ts | 9 +- src/modules/email/panelSmtpAdapter.ts | 3 - src/modules/email/sendEmail.ts | 3 - src/modules/secrets/writeOnly.ts | 38 +++- src/plugin.ts | 35 +++- src/types.ts | 4 +- test/accountRulesOwnRoles.test.ts | 27 +++ test/accountRulesSuite.ts | 152 +++++++++++++- test/doctor.test.ts | 6 +- test/secondFactorGuard.test.ts | 3 +- test/writeOnlySecretsBound.test.ts | 74 ++++--- 20 files changed, 519 insertions(+), 122 deletions(-) diff --git a/reference/src/payload-types.ts b/reference/src/payload-types.ts index 14664dd..9abab69 100644 --- a/reference/src/payload-types.ts +++ b/reference/src/payload-types.ts @@ -2799,10 +2799,6 @@ export interface SiteIntegration { * Usually 587, or 465. */ smtpPort?: number | null; - /** - * The password is sent only over an encrypted connection; without one, no e-mail is sent. - */ - smtpRequireTls?: boolean | null; smtpUser?: string | null; smtpPassword?: string | null; emailStatus?: { @@ -3224,7 +3220,6 @@ export interface SiteIntegrationsSelect { smtpFromName?: T; smtpHost?: T; smtpPort?: T; - smtpRequireTls?: T; smtpUser?: T; smtpPassword?: T; emailStatus?: diff --git a/src/globals/SiteIntegrations/fields/smtp.ts b/src/globals/SiteIntegrations/fields/smtp.ts index c171579..b8b5a57 100644 --- a/src/globals/SiteIntegrations/fields/smtp.ts +++ b/src/globals/SiteIntegrations/fields/smtp.ts @@ -93,19 +93,6 @@ 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', diff --git a/src/globals/SiteIntegrations/index.ts b/src/globals/SiteIntegrations/index.ts index b83692c..48714f1 100644 --- a/src/globals/SiteIntegrations/index.ts +++ b/src/globals/SiteIntegrations/index.ts @@ -11,8 +11,8 @@ 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 + * A save through access control that changes the SMTP server, port or user name must send the + * password again (or remove it), whatever the transport. Default true; needs write-only * secrets. `false` = the stored password follows the new server, as before. */ reenterSecretOnChange?: boolean @@ -42,12 +42,7 @@ export function buildSiteIntegrations({ writeOnlySecrets: writeOnly = true, }: BuildSiteIntegrationsArgs = {}): GlobalConfig { 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 + writeOnly ? writeOnlySecrets(fields, INTEGRATION_SECRET_FIELDS, reenterSecretOnChange ? { smtpPassword: { boundTo: SMTP_PASSWORD_BOUND_TO } } : {}) : fields return { slug: 'site-integrations', access: { diff --git a/src/index.ts b/src/index.ts index 36e9582..7ca618c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,16 +25,23 @@ export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, r export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWORD_MIN_LENGTH, resolvePasswordRule } from './modules/access/passwordRule.js' export type { PasswordRuleOptions } from './modules/access/passwordRule.js' export { + adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, buildFirstUserEndpoint, hasPluginRoles, openSignUpCollections, + rolesByAdminOnly, + rolesNotOwn, sameStaffCollectionAccess, + staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, + staffReadAccess, staffUpdateAccess, + unknownStaffCollections, } from './modules/access/selfRegistration.js' +export type { StaffAccountAccessOptions, StaffAccountRules } 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' diff --git a/src/modules/access/selfRegistration.ts b/src/modules/access/selfRegistration.ts index 935d9f1..8baf704 100644 --- a/src/modules/access/selfRegistration.ts +++ b/src/modules/access/selfRegistration.ts @@ -33,13 +33,6 @@ import { ROLE_HIERARCHY } from './types.js' type Staffish = Pick -/** 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. */ @@ -68,28 +61,173 @@ export const sameStaffCollectionAccess = return userMeetsRole(req, 'admin') } +/** `read` on a staff collection: a fully signed-in account of a staff collection. Never a visitor account. */ +export const staffReadAccess: Access = ({ req }) => { + const from = collectionOf(req) + return Boolean(req.user && from && staffCollectionSlugs(req.payload).includes(from) && secondFactorPassed(req)) +} + +type FieldAccessArgs = { id?: number | string; req: PayloadRequest } +/** `roles` where the roles are the plugin's: only an admin changes them — nobody raises itself. */ +export const rolesByAdminOnly = ({ req }: FieldAccessArgs): boolean => 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). + * `roles` where the role values are the project's own (the plugin cannot rank them): an account + * never changes its OWN roles. Another account of the collection, or a plugin admin, may. */ -export function applyStaffAccountAccess(config: Config, staffSlugs: string[], { create = true, pluginRoles = [], write = true }: { create?: boolean; pluginRoles?: string[]; write?: boolean } = {}): Config { - if (!create && !write) {return config} +export const rolesNotOwn = + (slug: string) => + ({ id, req }: FieldAccessArgs): boolean => + !(req.user && collectionOf(req) === slug && id !== undefined && String(req.user.id) === String(id)) + +type FieldLike = { access?: { update?: unknown }; fields?: FieldLike[]; name?: string; tabs?: { fields: FieldLike[]; name?: string }[] } +/** The `roles` field of a collection: at the top level of the data (also inside a row, a collapsible or an unnamed tab). */ +function findRolesField(fields: FieldLike[] | undefined): FieldLike | undefined { + for (const field of fields ?? []) { + if (field.name === 'roles') {return field} + if (!field.name && field.fields) { + const found = findRolesField(field.fields) + if (found) {return found} + } + for (const tab of field.tabs ?? []) { + const found = tab.name ? undefined : findRolesField(tab.fields) + if (found) {return found} + } + } + return undefined +} + +/** True when the collection carries the plugin's roles: a `roles` select at the top level of the data (also inside a row or an unnamed tab) whose values are all the plugin's. */ +export function hasPluginRoles(collection: Staffish): boolean { + const field = findRolesField(collection.fields as FieldLike[]) 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)) +} + +/** What the plugin put on a staff collection (`custom.ipalAccountRules`) — for the doctor and for late collections. */ +export type StaffAccountRules = { applied: string[]; ownRoles: boolean } + +/** Payload's own default ("any logged-in user"), as a sanitized config holds it where the project wrote no rule. */ +const isPayloadDefault = (rule: unknown): boolean => !rule || (typeof rule === 'function' && rule.name === 'defaultAccess') + +export type StaffAccountAccessOptions = { + /** `create` (accounts.adminOnlyCreate). */ + create?: boolean + /** Slugs that will carry the plugin's roles although the field is not there yet (`access.authCollection`). */ + pluginRoles?: string[] + /** `read` (accounts.staffOnlyRead). */ + read?: boolean + /** `update`, `delete`, `unlock`, and the `roles` field (accounts.adminOnlyWrite). */ + write?: boolean +} + +/** + * Puts the defaults on ONE staff collection, in place: the operations without a rule, and the + * `roles` field when the plugin's `update` rule is the one in force. Returns what it applied. + */ +function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions): StaffAccountRules { + const slug = collection.slug + const ours = pluginRoles.includes(slug) || hasPluginRoles(collection) + const other = sameStaffCollectionAccess(slug) + const access = (collection.access ?? {}) as Record + const applied: string[] = [] + const put = (operation: string, rule: unknown) => { + if (!isPayloadDefault(access[operation])) {return} + access[operation] = rule + applied.push(operation) + } + if (create) {put('create', ours ? staffCreateAccess : other)} + if (write) { + put('update', ours ? staffUpdateAccess(slug) : other) + put('delete', ours ? staffCreateAccess : other) + put('unlock', ours ? staffCreateAccess : other) + } + if (read) {put('read', staffReadAccess)} + collection.access = access as CollectionConfig['access'] + // The plugin's `update` rule lets an account change itself (or, with roles of its own, every account of + // the collection change every other): a `roles` field without access of its own would let it raise itself. + const roles = findRolesField(collection.fields as FieldLike[]) + if (applied.includes('update')) { + if (roles && !roles.access?.update) { + roles.access = { ...roles.access, update: ours ? rolesByAdminOnly : rolesNotOwn(slug) } + applied.push('roles') + } + } + // "roles of its own": a roles field whose values are not the plugin's (a collection without the field has no roles to rank) + const rules: StaffAccountRules = { applied, ownRoles: !ours && Boolean(roles) } + collection.custom = { ...collection.custom, ipalAccountRules: rules } + return rules +} + +/** A copy of the field tree down to the `roles` field, so the project's own objects are not changed. */ +const copyToRoles = (fields: FieldLike[] | undefined): FieldLike[] | undefined => + fields?.map((field) => { + if (field.name === 'roles') {return { ...field }} + if (!field.name && field.fields) {return { ...field, fields: copyToRoles(field.fields) }} + if (field.tabs) {return { ...field, tabs: field.tabs.map((tab) => (tab.name ? tab : { ...tab, fields: copyToRoles(tab.fields)! })) }} + return field + }) + +/** + * Puts the defaults on the named staff collections where the project wrote no rule: `create`, + * `update`, `delete`, `unlock`, `read`, and `roles` cannot be raised by its own account. + */ +export function applyStaffAccountAccess(config: Config, staffSlugs: string[], options: StaffAccountAccessOptions = {}): Config { + const { create = true, read = true, write = true } = options + if (!create && !write && !read) {return config} return { ...config, 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 } + const copy = { ...collection, access: { ...collection.access }, fields: copyToRoles(collection.fields as FieldLike[]) as CollectionConfig['fields'] } + ruleStaffCollection(copy, options) + return copy }), } } +type LiveCollections = Record + +/** + * Collections that were not in the config when ipalKit ran — a plugin listed after it added them. + * Called when a config goes live (start, dev reload): a late STAFF collection gets the same + * defaults, and every late auth collection the first-user endpoint. Changes the live config in + * place; returns the slugs it adopted. `beforeOperation`: the password rule's hook for staff. + */ +export function adoptLateAuthCollections( + payload: { collections: LiveCollections }, + staffSlugs: string[], + { access, beforeOperation, firstUserRoute = 'panel' }: { access?: false | StaffAccountAccessOptions; beforeOperation?: unknown; firstUserRoute?: FirstUserRouteOption } = {}, +): string[] { + const adopted: string[] = [] + for (const { config } of Object.values(payload.collections ?? {})) { + if (!config.auth || (config.custom as { ipalAccounts?: boolean } | undefined)?.ipalAccounts) {continue} + config.custom = { ...config.custom, ipalAccounts: true } + adopted.push(config.slug) + if (staffSlugs.includes(config.slug)) { + if (access !== false) {ruleStaffCollection(config, access ?? {})} + if (beforeOperation) { + const hooks = (config.hooks ?? {}) as { beforeOperation?: unknown[] } + hooks.beforeOperation = [...(hooks.beforeOperation ?? []), beforeOperation] + config.hooks = hooks as CollectionConfig['hooks'] + } + } + if (firstUserRoute !== 'all' && Array.isArray(config.endpoints) && !config.endpoints.some((e) => (e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)) { + config.endpoints.unshift(buildFirstUserEndpoint(firstUserRoute)) + } + } + return adopted +} + +/** Marks the auth collections ipalKit has seen at config time, so `adoptLateAuthCollections` leaves them alone. */ +export function markSeenAuthCollections(config: Config): Config { + return { ...config, collections: (config.collections ?? []).map((c) => (c.auth ? { ...c, custom: { ...c.custom, ipalAccounts: true } } : c)) } +} + +/** Slugs named as staff that are not auth collections of the live config. */ +export function unknownStaffCollections(payload: { collections: LiveCollections }, staffSlugs: string[]): string[] { + return staffSlugs.filter((slug) => !payload.collections?.[slug]?.config?.auth) +} + /** `accounts.firstUserRoute`: `'panel'` (default) = the panel's login collection only; slugs = those; `'all'` = Payload's behaviour. */ export type FirstUserRouteOption = 'all' | 'panel' | string[] @@ -149,7 +287,7 @@ export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption } } -type LivePayload = { collections: Record; config?: unknown } +type LivePayload = { collections: Record; config?: unknown } /** * Auth collections whose `create` rule lets an anonymous request through — open sign-up. @@ -169,9 +307,9 @@ export async function openSignUpCollections(payload: LivePayload): Promise { const staff = staffCollectionSlugs(payload as never) @@ -179,7 +317,7 @@ export async function staffCollectionsOpenToOthers(payload: LivePayload): Promis 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) { + for (const operation of ['create', 'read', 'update', 'delete', 'unlock'] as const) { try { const rule = config.access?.[operation] // no rule = Payload's default: any logged-in user @@ -191,3 +329,16 @@ export async function staffCollectionsOpenToOthers(payload: LivePayload): Promis } return open.sort() } + +/** + * Staff collections with role values of their OWN that run on the plugin's defaults: inside such a + * collection every account may create, change and delete accounts — the plugin cannot rank the + * project's roles. For the doctor: the project should write its own rules. Slugs only. + */ +export function staffCollectionsOnOwnRoles(payload: LivePayload): string[] { + return Object.values(payload.collections ?? {}) + .map(({ config }) => ({ slug: config.slug, rules: (config as { custom?: { ipalAccountRules?: StaffAccountRules } }).custom?.ipalAccountRules })) + .filter(({ rules }) => rules?.ownRoles && rules.applied.some((operation) => operation === 'create' || operation === 'update' || operation === 'delete')) + .map(({ slug }) => slug) + .sort() +} diff --git a/src/modules/access/types.ts b/src/modules/access/types.ts index 1813adb..ea55503 100644 --- a/src/modules/access/types.ts +++ b/src/modules/access/types.ts @@ -33,6 +33,10 @@ export type AccountsOptions = { * (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. + * With it: `unlock` gets the admin rule, and the collection's `roles` + * field (when it has no `access.update` of its own) cannot be raised by + * its own account — with the plugin's roles only an admin changes roles; + * with role values of the project's own, never the account itself. * `false` = Payload's default on collections without a rule, as before. */ adminOnlyWrite?: false @@ -63,6 +67,13 @@ export type AccountsOptions = { * logging in. `false` = Payload's own rule (3 characters). */ password?: false | PasswordRuleOptions + /** + * `read` on a staff collection without a `read` rule: a fully signed-in + * account of a staff collection. Payload's default let any logged-in + * account — a `customers` visitor — list the staff accounts. A rule the + * project wrote stays. `false` = Payload's default, as before. + */ + staffOnlyRead?: false } /** diff --git a/src/modules/admin-i18n/texts/integrations.ts b/src/modules/admin-i18n/texts/integrations.ts index afbd411..240fc4e 100644 --- a/src/modules/admin-i18n/texts/integrations.ts +++ b/src/modules/admin-i18n/texts/integrations.ts @@ -16,7 +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.', + secretReenter: 'Enter the password again: the server, port or user name changed. To use the server without a password, remove the stored value.', // Status banner on an integration's tab (IntegrationStatusBanner) statusCode: 'Code: {{code}}.', @@ -75,7 +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ść.', + secretReenter: 'Wpisz hasło ponownie: zmienił się serwer, port lub nazwa użytkownika. 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ć.', diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index dc656ad..2c9226b 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -191,16 +191,37 @@ export const securityRules: DoctorRule[] = [ check: (ctx) => (ctx.deep?.staffOpenToOthers ?? []).map((entry) => { const [slug, operation] = entry.split(':') + const what: Record = { + create: ': it can make itself a staff account', + read: ': it can list the staff accounts (addresses, roles)', + unlock: ': it can lift the lock after failed logins, which helps guessing a password', + update: ": it can change a staff account's password", + } + const option = operation === 'create' ? 'adminOnlyCreate' : operation === 'read' ? 'staffOnlyRead' : 'adminOnlyWrite' 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, + fix: `give "${slug}" an access.${operation} rule that asks for a staff account (staffCreateAccess, staffUpdateAccess('${slug}'), staffReadAccess, adminOrSelfIn('${slug}')), or drop accounts: false / accounts.${option}: false`, + message: `an account of another auth collection may ${operation} in the staff collection "${slug}"${what[operation] ?? ''}`, + severity: operation === 'read' ? ('warning' as const) : ('error' as const), } }), docs: 'docs/access.md', group: 'security', source: 'deep', }, + { + // A staff collection with role values of its own on the plugin's default rules: the plugin cannot rank + // those roles, so inside the collection every account may create an account with any role. + id: 'staff-own-roles', + check: (ctx) => + (ctx.deep?.staffOnOwnRoles ?? []).map((slug) => ({ + fix: `write "${slug}"'s own access.create / update / delete rules (and field access on its roles field) from its own roles`, + message: `the staff collection "${slug}" has role values of its own and no access rules: accounts of other collections are kept out, but inside it every account may create, change and delete accounts, with any role`, + severity: 'warning' 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', diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index 2fd30c9..b971e0b 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs' import type { DoctorStatus } from './types.js' -import { openSignUpCollections, staffCollectionsOpenToOthers } from '../access/selfRegistration.js' +import { openSignUpCollections, staffCollectionsOnOwnRoles, 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' @@ -74,7 +74,13 @@ export async function collectDoctorStatus(payload: BasePayload): Promise (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : value === undefined || value === null ? '' : JSON.stringify(value)).trim().toLowerCase() +/** Two values of a bound field are the same setting: the same text, exactly (`587` and `'587'` are the same; another letter case or a space is a change). */ +const asText = (value: unknown): string => (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : value === undefined || value === null ? '' : JSON.stringify(value)) const sameSetting = (a: unknown, b: unknown): boolean => asText(a) === asText(b) +/** A field by name among the siblings — also inside a row or a collapsible, which add no level to the data. */ +const siblingField = (fields: unknown, name: string): { defaultValue?: unknown } | undefined => { + for (const field of (Array.isArray(fields) ? fields : []) as { defaultValue?: unknown; fields?: unknown; name?: string; tabs?: { fields?: unknown; name?: string }[] }[]) { + if (field.name === name) {return field} + if (!field.name && field.fields) { + const found = siblingField(field.fields, name) + if (found) {return found} + } + for (const tab of field.tabs ?? []) { + if (tab.name) {continue} + const found = siblingField(tab.fields, name) + if (found) {return found} + } + } + return undefined +} + /** 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) @@ -88,9 +105,10 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp const next = (siblingData as Record | 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) + // (a SQL row can hold NULL where MongoDB holds nothing; the field may sit inside a row) + const fallback = siblingField(siblingFields, name)?.defaultValue + const byDefault = typeof fallback === 'function' ? undefined : fallback + return !sameSetting(next ?? byDefault, before?.[name] ?? byDefault) }) if (changed.length) { const message = req?.t ? ipalT(req.t as never, 'secretReenter') : 'Enter the password again: the settings it belongs to have changed.' @@ -177,5 +195,9 @@ export const maskSecretsOnRestore: CollectionAfterReadHook & GlobalAfterReadHook /** 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'] +/** + * What the SMTP password belongs to: changing one of these through access control asks for the password again — + * whatever the transport says. `emailTransport` is not in the list: the mail adapter falls back to SMTP when Graph + * is not configured, so the transport decides nothing about where the password goes; the server, port and user do. + */ +export const SMTP_PASSWORD_BOUND_TO = ['smtpHost', 'smtpPort', 'smtpUser'] diff --git a/src/plugin.ts b/src/plugin.ts index 161e879..24a8731 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -14,8 +14,8 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js' import { buildSiteSettings } from './globals/SiteSettings/index.js' import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js' import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js' -import { applyPasswordRule, resolvePasswordRule } from './modules/access/passwordRule.js' -import { applyFirstUserRoute, applyStaffAccountAccess } from './modules/access/selfRegistration.js' +import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js' +import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, unknownStaffCollections } 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' @@ -193,6 +193,17 @@ export const ipalKit = (options: IpalOptions): Plugin => { const adoptConfig = (payload: BasePayload) => { const token = (payload.config.custom as { ipal?: { staffToken?: object } } | undefined)?.ipal?.staffToken registerStaffCollections(payload, staffCollectionSlugs(payload), token) + // Auth collections a plugin listed after ipalKit added: the account rules for them too — BEFORE the + // 2FA guard below wraps their access (it needs the rule inside its wrapper). + if (accounts) { + const rule = resolvePasswordRule(accounts.password) + const lateAccounts = adoptLateAuthCollections(payload as never, staffCollectionSlugs(payload), { + access: { ...accountAccess, pluginRoles: [] }, + beforeOperation: rule ? buildPasswordRuleHook(rule) : undefined, + firstUserRoute: accounts.firstUserRoute, + }) + if (lateAccounts.length) {payload.logger.info(`[ipal] Account rules also put on auth collections added after ipalKit: ${lateAccounts.join(', ')}.`)} + } if (!secondFactorGuard) {return} const late = ensurePayloadGuarded(payload) if (late?.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)} @@ -206,6 +217,8 @@ export const ipalKit = (options: IpalOptions): Plugin => { let panelRoleSkipped: null | string = null /** `accounts: false` turns every account rule off. */ const accounts: AccountsOptions | null = options.accounts === false ? null : (options.accounts ?? {}) + /** Which of the staff defaults are on (accounts.adminOnlyCreate / adminOnlyWrite / staffOnlyRead). */ + const accountAccess = { create: accounts?.adminOnlyCreate !== false, read: accounts?.staffOnlyRead !== false, write: accounts?.adminOnlyWrite !== false } /** requireSetup.setupNotice / statusField (on unless switched off). */ let setupNotice = true let statusField = false @@ -215,11 +228,7 @@ 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)))] - config = applyStaffAccountAccess(config, staffSlugs, { - create: accounts.adminOnlyCreate !== false, - pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [], - write: accounts.adminOnlyWrite !== false, - }) + config = applyStaffAccountAccess(config, staffSlugs, { ...accountAccess, pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [] }) } if (options.twoFactor !== false) { const tf = options.twoFactor @@ -883,6 +892,16 @@ export const ipalKit = (options: IpalOptions): Plugin => { const incomingOnInit = config.onInit config.onInit = async (payload) => { if (incomingOnInit) {await incomingOnInit(payload)} + // A staff collection that does not exist protects nothing and hides a typo: its accounts would not be staff, + // or — worse — a collection of that name added later would be, without anyone having decided it. + const unknownStaff = unknownStaffCollections(payload as never, [...new Set([options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]) + if (unknownStaff.length) { + throw new Error( + `[ipal] access names ${unknownStaff.map((s) => `"${s}"`).join(', ')} as a staff collection, but this config has no auth collection with that slug ` + + `(auth collections: ${Object.values(payload.collections).filter((c) => c.config.auth).map((c) => c.config.slug).join(', ') || 'none'}). ` + + 'Fix the slug in access.authCollection / access.staffCollections, or add the collection (docs/access.md "Who is staff").', + ) + } adoptConfig(payload) // Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once. watchPayloadConfig(payload, adoptConfig) @@ -945,6 +964,8 @@ export const ipalKit = (options: IpalOptions): Plugin => { payload.logger.info('[ipal] Plugin initialized.') } + // Every auth collection of this config has been seen: what appears later is a late one (adoptConfig). + if (accounts) {config = markSeenAuthCollections(config)} return config } } diff --git a/src/types.ts b/src/types.ts index 81d4d18..f6e8680 100644 --- a/src/types.ts +++ b/src/types.ts @@ -214,8 +214,8 @@ export type IpalOptions = { * 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 + * the server, the port or the user name must send the password again, or + * remove it (whatever the transport says) — 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". diff --git a/test/accountRulesOwnRoles.test.ts b/test/accountRulesOwnRoles.test.ts index ef6099e..e0c9e59 100644 --- a/test/accountRulesOwnRoles.test.ts +++ b/test/accountRulesOwnRoles.test.ts @@ -82,6 +82,20 @@ test('the first account registers; accounts of the collection create, change and expect((await call(`/users/${third}`, boss, 'DELETE')).status).toBe(200) }) +// Review round 2 (R2-2): the plugin cannot rank the project's roles, but one thing it can hold: nobody changes its OWN. +test('an account does not change its own roles; another account of the collection does (the project\'s rules narrow that)', async () => { + const writer = await login('users', 'writer@example.com') + const id = await idOf('users', 'writer@example.com') + const roles = async () => ((await payload.findByID({ id: id as never, collection: 'users' as never })) as { roles?: string[] }).roles + await call(`/users/${id}`, writer, 'PATCH', { roles: ['superadmin'] }) + await call('/users?where[email][equals]=writer@example.com', writer, 'PATCH', { roles: ['superadmin'] }) + expect(await roles()).toEqual(['writer']) + const boss = await login('users', 'boss@example.com') + expect((await call(`/users/${id}`, boss, 'PATCH', { roles: ['superadmin'] })).status).toBe(200) + expect(await roles()).toEqual(['superadmin']) + await payload.update({ id: id as never, collection: 'users' as never, data: { roles: ['writer'] } as never }) +}) + test('an account of another collection, a half-signed-in one and nobody stay out', async () => { expect((await call('/customers', {}, 'POST', { email: 'visitor@example.com', password: PASSWORD })).status).toBe(201) const visitor = await login('customers', 'visitor@example.com') @@ -96,3 +110,16 @@ test('an account of another collection, a half-signed-in one and nobody stay out expect((await call('/users/login', {}, 'POST', { email: 'boss@example.com', password: 'taken-over-password-1' })).status).not.toBe(200) expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([]) }) + +test('a staff collection that does not exist stops the start, with the slug and the fix', async () => { + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }], + db: testDatabase('accounts_ghost'), + editor: lexicalEditor(), + plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['ghost-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })], + secret: 'integration-test-secret-0123456789', + telemetry: false, + }) + await expect(getPayload({ config, key: 'ghost' })).rejects.toThrow(/"ghost-staff"[\s\S]*no auth collection with that slug[\s\S]*staffCollections/) +}) diff --git a/test/accountRulesSuite.ts b/test/accountRulesSuite.ts index 6b08764..8ccde09 100644 --- a/test/accountRulesSuite.ts +++ b/test/accountRulesSuite.ts @@ -5,7 +5,7 @@ * (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 type { Config, Payload, Plugin } from 'payload' import { payloadTotp } from '@clocklimited/payload-2fa' import { lexicalEditor } from '@payloadcms/richtext-lexical' @@ -19,7 +19,7 @@ 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 { adoptLateAuthCollections, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js' import { ipalKit } from '../src/plugin.js' import { buildTestConfig, withTotpParts } from './helpers.js' import { testDatabase } from './http/db.js' @@ -28,6 +28,16 @@ import { totp } from './http/totp.js' const TOTP_SECRET = 'JBSWY3DPEHPK3PXP' +/** A plugin the project lists AFTER ipalKit: its auth collections did not exist when ipalKit ran (review round 2, R2-3). */ +const latePlugin: Plugin = (config: Config) => ({ + ...config, + collections: [ + ...(config.collections ?? []), + { slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }] }, + { slug: 'late-members', auth: true, fields: [] }, + ], +}) + /** 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' }] } @@ -85,7 +95,7 @@ export function accountRulesSuite(twoFactor: boolean): void { ], 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 })], + plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2', 'crew', 'agents', 'late-staff'] }, i18n, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), latePlugin], secret: 'integration-test-secret-0123456789', telemetry: false, }) @@ -124,7 +134,7 @@ export function accountRulesSuite(twoFactor: boolean): void { 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 collection of ['staff2', 'crew', 'agents', 'members', 'late-staff', 'late-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]) @@ -263,7 +273,76 @@ export function accountRulesSuite(twoFactor: boolean): void { } }) + // Review round 2 (R2-2): the default "the account itself may update" must not reach the roles. + test('nobody raises its own role: a lowest-role account of a second staff collection stays what it is', async () => { + await make('agents', { email: 'low@agents.example.com', roles: ['user'] }) + const low = await login('agents', 'low@agents.example.com') + const id = await idOf('agents', 'low@agents.example.com') + const rolesOf = async (collection: string, of: unknown) => ((await payload.findByID({ id: of as never, collection: collection as never })) as { roles?: string[] }).roles + for (const body of [{ roles: ['admin'] }, { roles: 'admin' }, { password: 'another-long-password-1', roles: ['admin', 'user'] }]) { + await patch(`/agents/${id}`, body, low) + expect(await rolesOf('agents', id)).toEqual(['user']) + } + await patch('/agents?where[email][equals]=low@agents.example.com', { roles: ['admin'] }, low) // bulk + expect(await rolesOf('agents', id)).toEqual(['user']) + const gql = await post('/graphql', { query: `mutation { updateAgent(id: ${typeof id === 'number' ? id : `"${id}"`}, data: { roles: [admin] }) { id } }` }, low) + await gql.text() + expect(await rolesOf('agents', id)).toEqual(['user']) + // the rest of its own account is its own (the password above was changed) + expect(await canLogIn('agents', 'low@agents.example.com', 'another-long-password-1')).toBe(true) + // and it opens nothing an admin opens + expect((await call('/globals/site-integrations', low)).status).toBe(403) + // an admin gives roles + expect((await patch(`/agents/${id}`, { roles: ['editor'] }, admin)).status).toBe(200) + expect(await rolesOf('agents', id)).toEqual(['editor']) + + // role values of the project's own: the plugin cannot rank them, but an account still never changes its own + const worker = await login('crew', 'worker@crew.example.com') + const workerId = await idOf('crew', 'worker@crew.example.com') + await patch(`/crew/${workerId}`, { roles: ['boss'] }, worker) + await patch('/crew?where[email][equals]=worker@crew.example.com', { roles: ['boss'] }, worker) + expect(await rolesOf('crew', workerId)).toEqual(['worker']) + // somebody else of the collection does (what the project's own rules must narrow — said by the doctor) + const boss = await login('crew', 'boss@crew.example.com') + expect((await patch(`/crew/${workerId}`, { roles: ['boss'] }, boss)).status).toBe(200) + expect(await rolesOf('crew', workerId)).toEqual(['boss']) + await payload.update({ id: workerId as never, collection: 'crew' as never, data: { roles: ['worker'] } as never }) + }) + + // Payload's defaults for `read` and `unlock` are "any logged-in user" too. + test('a visitor account does not list staff accounts or unlock them; staff does (accounts.staffOnlyRead)', async () => { + for (const collection of ['agents', 'staff2', 'crew', 'late-staff']) { + for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) { + expect([collection, who, (await call(`/${collection}`, session)).status]).toEqual([collection, who, 403]) + expect([collection, who, (await post(`/${collection}/unlock`, { email: 'agent@example.com' }, session)).status]).toEqual([collection, who, 403]) + } + expect([collection, (await call(`/${collection}`, editor)).status]).toEqual([collection, 200]) // staff reads staff + } + const gql = (await (await post('/graphql', { query: '{ Agents { docs { email } } }' }, visitor)).json()) as { data?: unknown; errors?: unknown[] } + expect(JSON.stringify(gql)).not.toContain('agent@example.com') + expect((await post('/agents/unlock', { email: 'agent@example.com' }, editor)).status).toBe(403) + expect((await post('/agents/unlock', { email: 'agent@example.com' }, admin)).status).toBe(200) + }) + + // Review round 2 (R2-3): a staff collection a later plugin adds. + test('a staff collection added by a plugin listed after ipalKit has the same rules', async () => { + expect((await payload.count({ collection: 'late-staff' as never })).totalDocs).toBe(0) // the first-user spellings above created nothing + expect((await post('/late-staff', { email: 'x@late.example.com', password: PASSWORD, roles: ['admin'] }, visitor)).status).toBe(403) + expect((await post('/late-staff', { email: 'x@late.example.com', password: PASSWORD, roles: ['admin'] }, editor)).status).toBe(403) + // the password rule is there too + expect((await post('/late-staff', { email: 'short@late.example.com', password: 'tooshort', roles: ['user'] }, admin)).status).toBe(400) + expect((await post('/late-staff', { email: 'one@late.example.com', password: PASSWORD, roles: ['user'] }, admin)).status).toBe(201) + const id = await idOf('late-staff', 'one@late.example.com') + expect((await patch(`/late-staff/${id}`, { password: NEW }, visitor)).status).toBe(403) + expect((await remove(`/late-staff/${id}`, visitor)).status).toBe(403) + const one = await login('late-staff', 'one@late.example.com') + await patch(`/late-staff/${id}`, { roles: ['admin'] }, one) + expect(((await payload.findByID({ id: id as never, collection: 'late-staff' as never })) as { roles?: string[] }).roles).toEqual(['user']) + expect((await patch(`/late-staff/${id}`, { roles: ['editor'] }, admin)).status).toBe(200) + }) + test('the doctor\'s check: no staff collection is open to an account of another collection', async () => { + expect(staffCollectionsOnOwnRoles(payload as never)).toEqual(['crew']) // `staff2` has no roles field: nothing to rank expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([]) expect(await openSignUpCollections(payload as never)).toEqual(['customers']) }) @@ -508,7 +587,8 @@ export function accountRulesSuite(twoFactor: boolean): void { 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(of(payloadWay, 'staff2').access).toEqual({ read: staffReadAccess }) + expect(of(await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false, staffOnlyRead: false } }), '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 } }) @@ -530,6 +610,62 @@ export function accountRulesSuite(twoFactor: boolean): void { expect(of(noAccess, 'users').access?.create).not.toBe(staffCreateAccess) }) + test('the roles field: protected where the plugin\'s update rule is in force and the field has no access of its own', async () => { + const rolesField = (config: Config, slug: string) => of(config, slug).fields.find((f) => 'name' in f && f.name === 'roles') as { access?: { update?: unknown } } + const own = { name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] } + const collections = (extra: object = {}, field: object = own) => ({ collections: [{ slug: 'staff2', auth: true, fields: [{ type: 'row', fields: [field] }], ...extra }] }) as never + const inRow = (config: Config) => (of(config, 'staff2').fields[0] as unknown as { fields: { access?: { update?: unknown } }[] }).fields[0] + // the plugin's roles: only an admin; found inside a row too; the project's own field object is not changed + expect(inRow(await build({}, collections())).access?.update).toBe(rolesByAdminOnly) + expect((own as { access?: unknown }).access).toBeUndefined() + // roles of the project's own: never the account itself + const mine = inRow(await build({}, collections({}, { ...own, options: ['boss', 'worker'] }))).access?.update as (a: unknown) => boolean + expect(mine({ id: 5, req: { user: { id: 5, collection: 'staff2' } } })).toBe(false) + expect(mine({ id: '5', req: { user: { id: 5, collection: 'staff2' } } })).toBe(false) + expect(mine({ id: 6, req: { user: { id: 5, collection: 'staff2' } } })).toBe(true) + expect(mine({ id: 5, req: { user: { id: 5, collection: 'users' } } })).toBe(true) // id 5 of another collection is somebody else + expect(rolesNotOwn('x')({ id: undefined, req: { user: { id: 5, collection: 'x' } } } as never)).toBe(true) // a create + // left alone: a field with its own rule, a collection with its own update rule, the switch + const fieldRule = () => true + expect(inRow(await build({}, collections({}, { ...own, access: { update: fieldRule } }))).access?.update).toBe(fieldRule) + expect(inRow(await build({}, collections({ access: { update: () => true } }))).access).toBeUndefined() + expect(inRow(await build({ accounts: { adminOnlyWrite: false } }, collections())).access).toBeUndefined() + // the injected collection's field has the plugin's own access already + expect(rolesField(await build({}), 'users').access?.update).toBeTypeOf('function') + }) + + test('late collections: adopted once, with the same rules; a project\'s own rule and Payload\'s default told apart', () => { + function defaultAccess({ req }: { req: { user: unknown } }) {return Boolean(req.user)} // what a sanitized config holds where nothing was written + const mine = () => true + const hook = () => undefined + const late = { slug: 'late', access: { create: defaultAccess, delete: mine, read: defaultAccess, unlock: defaultAccess, update: defaultAccess }, auth: true, endpoints: [{ handler: () => undefined, method: 'post', path: '/first-register' }], fields: [{ name: 'roles', type: 'select', options: ['user', 'admin'] }] } + const seen = { slug: 'users', access: { create: defaultAccess }, auth: true, custom: { ipalAccounts: true }, endpoints: [], fields: [] } + const visitors = { slug: 'visitors', access: { create: defaultAccess }, auth: true, endpoints: [], fields: [] } + const pages = { slug: 'pages', access: {}, endpoints: [], fields: [] } + const live = { collections: { late: { config: late }, pages: { config: pages }, users: { config: seen }, visitors: { config: visitors } } } as never + expect(adoptLateAuthCollections(live, ['users', 'late'], { beforeOperation: hook })).toEqual(['late', 'visitors']) + expect(late.access.create).toBe(staffCreateAccess) + expect(late.access.delete).toBe(mine) + expect(late.access.read).toBe(staffReadAccess) + expect(late.access.unlock).toBe(staffCreateAccess) + expect((late.fields[0] as { access?: { update?: unknown } }).access?.update).toBe(rolesByAdminOnly) + expect((late as { hooks?: { beforeOperation?: unknown[] } }).hooks?.beforeOperation).toEqual([hook]) + expect((late.endpoints[0] as { custom?: { ipalFirstUser?: boolean } }).custom?.ipalFirstUser).toBe(true) // in FRONT of Payload's + expect(late.endpoints).toHaveLength(2) + // a late auth collection that is not staff: the first-user endpoint only + expect(visitors.access.create).toBe(defaultAccess) + expect(visitors.endpoints).toHaveLength(1) + // what ipalKit saw at config time, and what is not an auth collection: untouched + expect(seen.access.create).toBe(defaultAccess) + expect(seen.endpoints).toHaveLength(0) + expect(pages.endpoints).toHaveLength(0) + // a second call (a request after the start) changes nothing + expect(adoptLateAuthCollections(live, ['users', 'late'], { beforeOperation: hook })).toEqual([]) + expect(late.endpoints).toHaveLength(2) + // a staff slug without an auth collection + expect(unknownStaffCollections(live, ['users', 'late', 'pages', 'ghost'])).toEqual(['pages', 'ghost']) + }) + 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 = {} @@ -538,7 +674,7 @@ export function accountRulesSuite(twoFactor: boolean): void { 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(Object.keys(seen.staff2 as object).sort()).toEqual(['create', 'delete', 'read', 'unlock', 'update']) expect(seen.customers).toEqual({ create: expect.any(Function) }) }) @@ -571,10 +707,10 @@ export function accountRulesSuite(twoFactor: boolean): void { 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 } }, + users: { config: { slug: 'users', access: { create: staffCreateAccess, delete: staffCreateAccess, read: staffReadAccess, unlock: 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 + expect(await staffCollectionsOpenToOthers({ collections, config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['agents', 'weird'] } } } } as never)).toEqual(['agents:delete', 'agents:read', 'agents:unlock', 'agents:update', 'weird:create', 'weird:delete', 'weird:read', 'weird:unlock']) // no rule = Payload's default, open; a rule that throws = closed }) }) } diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 7eda7ad..855bb73 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -206,6 +206,10 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () = 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: ['agents:read', 'agents:unlock'] })).toEqual(expect.arrayContaining(['staff-accounts-open:warning', 'staff-accounts-open:error'])) + expect(await run(cfg, ['staff-own-roles'], { staffOnOwnRoles: ['crew'] })).toEqual(['staff-own-roles:warning']) + expect(await run(cfg, ['staff-own-roles'], { staffOnOwnRoles: [] })).toEqual([]) + expect(await run(cfg, ['staff-own-roles'])).toEqual([]) 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([]) @@ -511,7 +515,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', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa']) + expect(Object.keys(status).sort()).toEqual(['node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', '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 () => { diff --git a/test/secondFactorGuard.test.ts b/test/secondFactorGuard.test.ts index 02e3cae..9ed2280 100644 --- a/test/secondFactorGuard.test.ts +++ b/test/secondFactorGuard.test.ts @@ -512,8 +512,9 @@ describe('ipalKit and the 2FA plugin', () => { admin: { user: 'users' }, } as Config) const warnings: string[] = [] + const auth = (slug: string) => ({ config: { slug, auth: true, custom: { ipalAccounts: true }, fields: [] } }) const payload = { - collections: {}, + collections: { partners: auth('partners'), users: auth('users') }, config: { admin: { user: 'users' }, collections: [], custom: config.custom, globals: [] }, count: () => ({ totalDocs: 0 }), find: () => ({ docs: [] }), diff --git a/test/writeOnlySecretsBound.test.ts b/test/writeOnlySecretsBound.test.ts index e4a4307..d583a96 100644 --- a/test/writeOnlySecretsBound.test.ts +++ b/test/writeOnlySecretsBound.test.ts @@ -33,7 +33,7 @@ let auth: Record const stored = async () => (await payload.findGlobal({ slug: 'site-integrations' as never })) as unknown as Record const api = (pathname: string, init: RequestInit = {}, headers: Record = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...auth, ...headers } }) const save = (data: Record, headers: Record = {}) => api(G, { body: JSON.stringify(data), method: 'POST' }, headers) -const reset = () => payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailTransport: 'smtp', smtpFromAddress: 'site@example.com', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpRequireTls: false, smtpUser: 'mailer' } as never }) +const reset = () => payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailTransport: 'smtp', smtpFromAddress: 'site@example.com', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpUser: 'mailer' } as never }) /** An SMTP server that offers no STARTTLS and writes down what a client logs in with. */ const fakeSmtp = async () => { @@ -127,7 +127,10 @@ describe('the SMTP password stays with the server it was saved for (secrets.reen ['the server', { smtpHost: 'other.example.com' }], ['the port', { smtpPort: 2525 }], ['the user name', { smtpUser: 'someone-else' }], - ['"require an encrypted connection"', { smtpRequireTls: true }], + ['the server to another letter case', { smtpHost: 'SMTP.example.com' }], + ['the server by a space', { smtpHost: 'smtp.example.com ' }], + ['the server while naming Microsoft Graph as the transport', { emailTransport: 'graph', smtpHost: 'other.example.com' }], + ['the port while naming Microsoft Graph as the transport', { emailTransport: 'graph', smtpPort: 2525 }], ['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' }], @@ -154,27 +157,55 @@ describe('the SMTP password stays with the server it was saved for (secrets.reen 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 () => { + test('a save that changes nothing the password belongs to keeps it: the same values sent back, other fields, the port as text', async () => { const doc = (await (await api(G)).json()) as Record 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({ 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) + test('a stored NULL where the field has a default (a SQL row, an older document) is not a change', async () => { + // the port sits inside a row; its default is 587, the transport's is 'smtp' + await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), emailTransport: null, smtpPort: null } as never }) + expect((await save({ smtpFromName: 'Again' })).status).toBe(200) + expect((await save({ emailTransport: 'smtp', smtpFromName: 'Again', smtpPort: 587 })).status).toBe(200) + await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), emailTransport: null, smtpPort: null } as never }) + expect((await save({ smtpFromName: 'Again', smtpPort: null })).status).toBe(200) + const doc = (await (await api(G)).json()) as Record + for (const key of ['id', 'createdAt', 'updatedAt', 'globalType']) {delete doc[key]} + expect((await save(doc)).status).toBe(200) + expect((await save({ smtpPort: 2525 })).status).toBe(400) 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) + // Review round 2 (R2-1): "Microsoft Graph" in the panel does not mean Graph sends — the mail adapter falls back to + // SMTP when the GRAPH_* variables are missing. The transport decides nothing; the server, port and user do. + test('the transport switch is not a way round: Graph + my server in one save, or Graph first and my server after', async () => { + const mine = await fakeSmtp() + try { + const gql = async (data: string) => (await (await api('/graphql', { body: JSON.stringify({ query: `mutation { updateSiteIntegration(data: { ${data} }) { smtpHost } }` }), method: 'POST' })).json()) as { errors?: unknown[] } + // 1. in one save, over REST and over GraphQL + expect((await save({ emailTransport: 'graph', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400) + expect((await gql(`emailTransport: graph, smtpHost: "127.0.0.1", smtpPort: ${mine.port}`)).errors?.length).toBeGreaterThan(0) + await testEmail() + // 2. the switch alone passes (the password is not asked for, and stays)… + expect((await save({ emailTransport: 'graph' })).status).toBe(200) + // …and the server afterwards does not, with or without naming the transport again + expect((await save({ smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400) + expect((await save({ emailTransport: 'graph', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400) + expect((await save({ emailTransport: 'smtp', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400) + expect((await gql(`smtpHost: "127.0.0.1", smtpPort: ${mine.port}`)).errors?.length).toBeGreaterThan(0) + await testEmail() + await api('/ipal/test-email', { body: JSON.stringify({ attachmentMB: 5, to: 'someone@example.com' }), method: 'POST' }) + expect(mine.seen).toEqual({ auth: '', mails: 0 }) + expect(await stored()).toMatchObject({ emailTransport: 'graph', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587 }) + // back to SMTP alone: the same server as before, nothing to ask + expect((await save({ emailTransport: 'smtp' })).status).toBe(200) + } finally { + await mine.close() + } }) test('server code (a seed, the Local API with access control off) moves the server and keeps the password', async () => { @@ -205,23 +236,6 @@ describe('the SMTP password stays with the server it was saved for (secrets.reen }) }) -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' })