diff --git a/src/index.ts b/src/index.ts index 7ca618c..bfb6cc4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,6 +28,7 @@ export { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, + bothAllow, buildFirstUserEndpoint, hasPluginRoles, openSignUpCollections, @@ -41,7 +42,7 @@ export { staffUpdateAccess, unknownStaffCollections, } from './modules/access/selfRegistration.js' -export type { StaffAccountAccessOptions, StaffAccountRules } from './modules/access/selfRegistration.js' +export type { LateAdoption, 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 8baf704..0ee6662 100644 --- a/src/modules/access/selfRegistration.ts +++ b/src/modules/access/selfRegistration.ts @@ -106,8 +106,27 @@ export function hasPluginRoles(collection: Staffish): boolean { /** 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') +/** + * BOTH rules must allow: the plugin's and the one the collection already has. For a collection + * that arrives after ipalKit ran (a later plugin), whose config is already sanitized: Payload has + * filled every missing rule with its default by then, and that default cannot be told from a + * rule somebody wrote — not by its name (a production build minifies it away) and not safely by + * identity. So nothing is guessed: the plugin's rule is put in FRONT of whatever is there. With + * Payload's default behind it the result is the plugin's rule; with a rule of the collection's + * own the result is the narrower of the two. Never wider than the plugin's rule: fail closed. + */ +export function bothAllow(first: Access, second: unknown): Access { + if (typeof second !== 'function') {return first} + return async (args) => { + const a = await first(args) + if (!a) {return false} + const b = await (second as Access)(args) + if (!b) {return false} + if (a === true) {return b} + if (b === true) {return a} + return { and: [a, b] } + } +} export type StaffAccountAccessOptions = { /** `create` (accounts.adminOnlyCreate). */ @@ -123,16 +142,19 @@ export type StaffAccountAccessOptions = { /** * 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. + * `late`: the collection's config is already sanitized (see `bothAllow`) — the plugin's rule is + * combined with whatever is there instead of only filling gaps. */ -function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions): StaffAccountRules { +function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, late = false): 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 + const put = (operation: string, rule: Access) => { + if (late) {access[operation] = bothAllow(rule, access[operation])} + else if (!access[operation]) {access[operation] = rule} + else {return} // a rule the project wrote applied.push(operation) } if (create) {put('create', ours ? staffCreateAccess : other)} @@ -141,7 +163,11 @@ function ruleStaffCollection(collection: CollectionConfig, { create = true, plug put('delete', ours ? staffCreateAccess : other) put('unlock', ours ? staffCreateAccess : other) } - if (read) {put('read', staffReadAccess)} + if (read) { + put('read', staffReadAccess) + // versions of an account hold what the account holds (e-mail addresses, roles) + put('readVersions', 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. @@ -185,35 +211,42 @@ export function applyStaffAccountAccess(config: Config, staffSlugs: string[], op } } -type LiveCollections = Record +/** What was put on one late auth collection: for the log, which says only what was really done. */ +export type LateAdoption = { applied: string[]; firstUser: boolean; password: boolean; slug: string } /** * 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. + * Called when a config goes live (start, dev reload) with THAT config: a late STAFF collection + * gets the account rules (in front of whatever rules it has — `bothAllow`), the roles-field rule + * and the password hook; every late auth collection gets the first-user endpoint. Changes the + * config in place; returns what it put where. A late collection that wants its own rules exactly + * as they are says so: `custom: { ipal: { accountRules: false } }`. */ export function adoptLateAuthCollections( - payload: { collections: LiveCollections }, + config: { collections?: CollectionConfig[] }, 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 ?? {})} +): LateAdoption[] { + const adopted: LateAdoption[] = [] + for (const collection of config.collections ?? []) { + const custom = collection.custom as { ipal?: { accountRules?: unknown }; ipalAccounts?: boolean } | undefined + if (!collection.auth || custom?.ipalAccounts) {continue} + collection.custom = { ...collection.custom, ipalAccounts: true } + const done: LateAdoption = { slug: collection.slug, applied: [], firstUser: false, password: false } + if (staffSlugs.includes(collection.slug)) { + if (access !== false && custom?.ipal?.accountRules !== false) {done.applied = ruleStaffCollection(collection, access ?? {}, true).applied} if (beforeOperation) { - const hooks = (config.hooks ?? {}) as { beforeOperation?: unknown[] } + const hooks = (collection.hooks ?? {}) as { beforeOperation?: unknown[] } hooks.beforeOperation = [...(hooks.beforeOperation ?? []), beforeOperation] - config.hooks = hooks as CollectionConfig['hooks'] + collection.hooks = hooks as CollectionConfig['hooks'] + done.password = true } } - if (firstUserRoute !== 'all' && Array.isArray(config.endpoints) && !config.endpoints.some((e) => (e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)) { - config.endpoints.unshift(buildFirstUserEndpoint(firstUserRoute)) + if (firstUserRoute !== 'all' && Array.isArray(collection.endpoints) && !collection.endpoints.some((e) => (e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)) { + collection.endpoints.unshift(buildFirstUserEndpoint(firstUserRoute)) + done.firstUser = true } + if (done.applied.length || done.firstUser || done.password) {adopted.push(done)} } return adopted } @@ -224,8 +257,8 @@ export function markSeenAuthCollections(config: Config): Config { } /** 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) +export function unknownStaffCollections(config: { collections?: CollectionConfig[] }, staffSlugs: string[]): string[] { + return staffSlugs.filter((slug) => !(config.collections ?? []).some((c) => c.slug === slug && c.auth)) } /** `accounts.firstUserRoute`: `'panel'` (default) = the panel's login collection only; slugs = those; `'all'` = Payload's behaviour. */ @@ -287,7 +320,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. @@ -317,7 +350,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', 'read', 'update', 'delete', 'unlock'] as const) { + for (const operation of ['create', 'read', 'readVersions', 'update', 'delete', 'unlock'] as const) { try { const rule = config.access?.[operation] // no rule = Payload's default: any logged-in user diff --git a/src/modules/admin-i18n/texts/integrations.ts b/src/modules/admin-i18n/texts/integrations.ts index 240fc4e..103ba5a 100644 --- a/src/modules/admin-i18n/texts/integrations.ts +++ b/src/modules/admin-i18n/texts/integrations.ts @@ -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', + secretNotText: 'Enter the value as text.', 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) @@ -75,6 +76,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ż', + secretNotText: 'Wpisz wartość jako tekst.', 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}}.', diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index 2c9226b..fe52202 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -194,14 +194,16 @@ export const securityRules: DoctorRule[] = [ const what: Record = { create: ': it can make itself a staff account', read: ': it can list the staff accounts (addresses, roles)', + readVersions: ': it can read the versions of 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' + const reads = operation === 'read' || operation === 'readVersions' + const option = operation === 'create' ? 'adminOnlyCreate' : reads ? 'staffOnlyRead' : 'adminOnlyWrite' return { 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), + severity: reads ? ('warning' as const) : ('error' as const), } }), docs: 'docs/access.md', diff --git a/src/modules/secrets/writeOnly.ts b/src/modules/secrets/writeOnly.ts index dc3b28c..e573543 100644 --- a/src/modules/secrets/writeOnly.ts +++ b/src/modules/secrets/writeOnly.ts @@ -97,7 +97,14 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp const name = (field as { name?: string } | undefined)?.name const value = siblingData && name ? (siblingData as Record)[name] : given if (value === SECRET_CLEAR) {return null} - if (!(value === undefined || value === null || value === '' || value === SECRET_MASK)) {return value} + const refuse = (key: 'secretNotText' | 'secretReenter', fallback: string): never => { + const message = req?.t ? ipalT(req.t as never, key) : fallback + throw new ValidationError({ collection: collection?.slug, errors: [{ message, path: path.join('.') }], global: global?.slug }, req?.t) + } + const nothing = value === undefined || value === null || value === '' || value === SECRET_MASK + // a secret is text: `false`, `0`, a list or an object is refused, not stored as typed + if (!nothing && typeof value !== 'string') {return refuse('secretNotText', 'Enter the value as text.')} + if (!nothing) {return value} const stored = storedSecret(originalDoc, path) if (stored && boundTo.length && overrideAccess !== true && (!appliesWhen || appliesWhen((siblingData ?? {}) as Record))) { const before = dig(originalDoc, path.slice(0, -1)) as Record | undefined @@ -110,10 +117,7 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp 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.' - throw new ValidationError({ collection: collection?.slug, errors: [{ message, path: path.join('.') }], global: global?.slug }, req?.t) - } + if (changed.length) {return refuse('secretReenter', 'Enter the password again: the settings it belongs to have changed.')} } return stored } diff --git a/src/modules/security/totp/setupRequired.ts b/src/modules/security/totp/setupRequired.ts index 9e0eaf5..6d6ce53 100644 --- a/src/modules/security/totp/setupRequired.ts +++ b/src/modules/security/totp/setupRequired.ts @@ -73,6 +73,9 @@ export function resolveRequireSetup(option: false | RequireSetupOptions | undefi /** What was already said about a wrong `exempt` answer: each kind is logged once per process. */ const exemptComplaints = new Set() +/** The constructor of async functions (there is no global for it). */ +const ASYNC_FUNCTION: unknown = (async () => {}).constructor + /** * The project's `exempt`, made safe to call from an access check: only an answer of exactly * `true` exempts. An async function is refused at start (its Promise would be truthy for every @@ -83,7 +86,8 @@ export function strictExempt(exempt: unknown): NonNullable boolean.') } - if (exempt.constructor?.name === 'AsyncFunction') { + // by the constructor itself, not by its name + if (exempt.constructor === ASYNC_FUNCTION) { throw new Error( '[ipal] twoFactor.requireSetup.exempt must not be async: it is called in access checks, which cannot wait, and a Promise ' + 'would count as "exempt" for every account. Return true or false at once (decide from the fields on `user`).', diff --git a/src/plugin.ts b/src/plugin.ts index 24a8731..9ac799e 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -197,12 +197,18 @@ export const ipalKit = (options: IpalOptions): Plugin => { // 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), { + // `payload.config`, not `payload.collections`: on a dev reload Payload swaps the config first, and + // `payload.collections` still holds the old one at this moment. + const lateAccounts = adoptLateAuthCollections(payload.config 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(', ')}.`)} + // said exactly: what was put, on which collection + for (const late of lateAccounts) { + const parts = [late.applied.length ? `access rules for ${late.applied.join(', ')}` : '', late.password ? 'the password rule' : '', late.firstUser ? 'the first-user endpoint' : ''].filter(Boolean) + payload.logger.info(`[ipal] "${late.slug}" was added after ipalKit: put on it — ${parts.join('; ')}.`) + } } if (!secondFactorGuard) {return} const late = ensurePayloadGuarded(payload) @@ -894,11 +900,11 @@ export const ipalKit = (options: IpalOptions): Plugin => { 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)))]) + const unknownStaff = unknownStaffCollections(payload.config 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'}). ` + + `(auth collections: ${payload.config.collections.filter((c) => c.auth).map((c) => c.slug).join(', ') || 'none'}). ` + 'Fix the slug in access.authCollection / access.staffCollections, or add the collection (docs/access.md "Who is staff").', ) } diff --git a/test/accountRulesReload.test.ts b/test/accountRulesReload.test.ts new file mode 100644 index 0000000..73f84ed --- /dev/null +++ b/test/accountRulesReload.test.ts @@ -0,0 +1,9 @@ +/** A dev reload and a late staff collection, 2FA off — see accountRulesReloadSuite.ts. */ +import { vi } from 'vitest' + +import { reloadSuite } from './accountRulesReloadSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +reloadSuite(false) diff --git a/test/accountRulesReload2fa.test.ts b/test/accountRulesReload2fa.test.ts new file mode 100644 index 0000000..117bf1b --- /dev/null +++ b/test/accountRulesReload2fa.test.ts @@ -0,0 +1,9 @@ +/** A dev reload and a late staff collection, 2FA ON — see accountRulesReloadSuite.ts. */ +import { vi } from 'vitest' + +import { reloadSuite } from './accountRulesReloadSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +reloadSuite(true) diff --git a/test/accountRulesReloadSuite.ts b/test/accountRulesReloadSuite.ts new file mode 100644 index 0000000..3d84ae0 --- /dev/null +++ b/test/accountRulesReloadSuite.ts @@ -0,0 +1,96 @@ +/** + * A dev reload (review round 3, R3-2): Payload swaps `payload.config` and runs no onInit. A staff collection that a + * plugin listed after ipalKit adds must keep the account rules on the new config — with 2FA off and on. + * Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI. + */ +import type { Config, Payload, Plugin, SanitizedConfig } 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 { expect, test } from 'vitest' + +import { ipalKit } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' +import { startPayloadServer } from './http/server.js' + +const PASSWORD = 'a-long-test-password-1' +const late: Plugin = (config: Config) => ({ + ...config, + collections: [...(config.collections ?? []), { slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] }], versions: true }], +}) +const makeConfig = (twoFactor: boolean) => + buildTestConfig({ + admin: { user: 'users' }, + collections: [ + { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }, + ], + db: testDatabase(twoFactor ? 'reload_2fa' : 'reload'), + editor: lexicalEditor(), + plugins: [ + ipalKit({ access: { authCollection: 'users', staffCollections: ['late-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), + late, + ], + secret: 'integration-test-secret-0123456789', + telemetry: false, + }) + +/** One Payload instance per test file (Payload caches it): run from a file of its own for 2FA off and on. */ +export function reloadSuite(twoFactor: boolean): void { + test(`a late staff collection keeps its rules over a dev reload (2FA on: ${twoFactor})`, async () => { + const config = makeConfig(twoFactor) + const payload: Payload = await getPayload({ config }) + const server = await startPayloadServer(config) + const call = (method: string, pathname: string, body?: unknown, headers: Record = {}) => + fetch(`${server.url}/api${pathname}`, { body: body === undefined ? undefined : JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method }) + const round = async (when: string) => { + const tag = `${when.replace(/\W+/g, "-")}-${Math.random().toString(36).slice(2)}` + // an EMPTY late staff collection: its first-user route, in two spellings + const before = (await payload.count({ collection: 'late-staff' as never })).totalDocs + for (const spelling of ['/first-register', '/First-Register']) { + expect([when, spelling, (await call('POST', `/late-staff${spelling}`, { email: `first-${tag}@example.com`, password: PASSWORD, roles: ['admin'] })).status]).toEqual([when, spelling, 403]) + } + expect([when, (await payload.count({ collection: 'late-staff' as never })).totalDocs]).toEqual([when, before]) + // a visitor account + expect((await call('POST', '/customers', { email: `c-${tag}@example.com`, password: PASSWORD })).status).toBe(201) + const token = ((await (await call('POST', '/customers/login', { email: `c-${tag}@example.com`, password: PASSWORD })).json()) as { token: string }).token + const visitor = { authorization: `JWT ${token}` } + const victim = await payload.create({ collection: 'late-staff' as never, data: { email: `v-${tag}@example.com`, password: PASSWORD, roles: ['user'] } as never }) + const got = { + create: (await call('POST', '/late-staff', { email: `x-${tag}@example.com`, password: PASSWORD, roles: ['admin'] }, visitor)).status, + delete: (await call('DELETE', `/late-staff/${victim.id}`, undefined, visitor)).status, + patch: (await call('PATCH', `/late-staff/${victim.id}`, { password: 'taken-over-password-1' }, visitor)).status, + read: (await call('GET', '/late-staff', undefined, visitor)).status, + unlock: (await call('POST', '/late-staff/unlock', { email: `v-${tag}@example.com` }, visitor)).status, + versions: (await call('GET', '/late-staff/versions', undefined, visitor)).status, + } + expect([when, got]).toEqual([when, { create: 403, delete: 403, patch: 403, read: 403, unlock: 403, versions: 403 }]) + // the password rule is on the collection too + await expect(payload.create({ collection: 'late-staff' as never, data: { email: `s-${tag}@example.com`, password: 'tooshort', roles: ['user'] } as never })).rejects.toThrow() + await payload.delete({ collection: 'late-staff' as never, where: { email: { contains: tag } } }) + } + try { + await round('start') + // what Payload's dev `reload()` does: a NEW sanitized config is assigned first, the collections after it + const next = await makeConfig(twoFactor) + const live = payload as unknown as { collections: Record; config: SanitizedConfig; globals: { config: unknown } } + live.config = next + live.collections = Object.fromEntries(next.collections.map((c) => [c.slug, { config: c, customIDType: live.collections[c.slug]?.customIDType }])) + live.globals = { config: next.globals } + await round('after the reload') + // and once more: a second reload meets a fresh config again + const third = await makeConfig(twoFactor) + live.config = third + live.collections = Object.fromEntries(third.collections.map((c) => [c.slug, { config: c, customIDType: live.collections[c.slug]?.customIDType }])) + live.globals = { config: third.globals } + await round('after a second reload') + } finally { + await server.close() + await payload.destroy?.() + } + }, 120_000) +} diff --git a/test/accountRulesSuite.ts b/test/accountRulesSuite.ts index 8ccde09..d913ecf 100644 --- a/test/accountRulesSuite.ts +++ b/test/accountRulesSuite.ts @@ -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 { adoptLateAuthCollections, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js' +import { adoptLateAuthCollections, bothAllow, 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' @@ -33,7 +33,7 @@ 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-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true }, { slug: 'late-members', auth: true, fields: [] }, ], }) @@ -90,7 +90,7 @@ export function accountRulesSuite(twoFactor: boolean): void { // 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: 'agents', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true }, { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }, ], db: testDatabase(twoFactor ? 'accounts_2fa' : 'accounts'), @@ -318,15 +318,28 @@ export function accountRulesSuite(twoFactor: boolean): void { } expect([collection, (await call(`/${collection}`, editor)).status]).toEqual([collection, 200]) // staff reads staff } + // versions hold what the accounts hold (review round 3, R3-3) + await payload.update({ collection: 'agents' as never, data: { roles: ['admin'] } as never, where: { email: { equals: 'agent@example.com' } } }) + for (const collection of ['agents', 'late-staff']) { + for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) { + const res = await call(`/${collection}/versions`, session) + expect([collection, who, res.status]).toEqual([collection, who, 403]) + expect(await res.text()).not.toContain('agent@example.com') + } + expect([collection, (await call(`/${collection}/versions`, editor)).status]).toEqual([collection, 200]) + } 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) + await make('late-staff', { email: 'locked@late.example.com', roles: ['user'] }) + expect((await post('/late-staff/unlock', { email: 'locked@late.example.com' }, editor)).status).toBe(403) // a late collection: the same table + expect((await post('/late-staff/unlock', { email: 'locked@late.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 + // (the first-user spellings above created nothing: counted there) 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 @@ -587,7 +600,7 @@ 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).toEqual({ read: staffReadAccess }) + expect(of(payloadWay, 'staff2').access).toEqual({ read: staffReadAccess, readVersions: 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 @@ -634,36 +647,62 @@ export function accountRulesSuite(twoFactor: boolean): void { 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 + // Review round 3 (R3-1): nothing may depend on recognising Payload's default — a production build minifies + // its name away. The functions below have the names a bundler gives them: none that means anything. + test('late collections: the plugin\'s rule goes in FRONT of whatever is there, whatever it is called', async () => { + const g = ({ req }: { req: { user: unknown } }) => Boolean(req.user) // Payload's default as a built site holds it: no telling name + const bw = ({ req }: { req: { user: unknown } }) => Boolean(req.user) + const narrow = () => false + const where = () => ({ team: { equals: 'a' } }) 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 late = { slug: 'late', access: { create: g, delete: narrow, read: g, readVersions: g, unlock: bw, update: where }, auth: true, endpoints: [{ handler: () => undefined, method: 'post', path: '/first-register' }], fields: [{ name: 'roles', type: 'select', access: {}, options: ['user', 'admin'] }] } + const seen = { slug: 'users', access: { create: g }, auth: true, custom: { ipalAccounts: true }, endpoints: [], fields: [] } + const visitors = { slug: 'visitors', access: { create: g }, auth: true, endpoints: [], fields: [] } + const asIs = { slug: 'as-is', access: { create: g }, auth: true, custom: { ipal: { accountRules: false } }, 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) + const config = { collections: [late, pages, seen, visitors, asIs] } as never + const staff = { staffCollections: ['users', 'late', 'as-is'] } + expect(adoptLateAuthCollections(config, ['users', 'late', 'as-is'], { beforeOperation: hook })).toEqual([ + { slug: 'late', applied: ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], firstUser: true, password: true }, + { slug: 'visitors', applied: [], firstUser: true, password: false }, + { slug: 'as-is', applied: [], firstUser: true, password: true }, // its own rules as they are: it said so + ]) + const ask = (operation: keyof typeof late.access, user: unknown) => (late.access[operation] as (a: unknown) => unknown)({ req: { payload: staff, user } }) + const admin = { id: 1, collection: 'users', roles: ['admin'] } + const editor = { id: 2, collection: 'users', roles: ['editor'] } + const own = { id: 7, collection: 'late', roles: ['user'] } + const customer = { id: 9, collection: 'customers', roles: ['admin'] } + for (const operation of ['create', 'read', 'readVersions', 'update', 'delete', 'unlock'] as const) { + expect([operation, await ask(operation, customer)]).toEqual([operation, false]) + expect([operation, await ask(operation, null)]).toEqual([operation, false]) + } + expect(await ask('create', editor)).toBe(false) + expect(await ask('create', admin)).toBe(true) + expect(await ask('unlock', editor)).toBe(false) // an admin, as the table in the docs says + expect(await ask('unlock', admin)).toBe(true) + expect(await ask('read', editor)).toBe(true) + expect(await ask('readVersions', editor)).toBe(true) + // a rule of the collection's own is kept, and only ever narrows: both must allow + expect(await ask('delete', admin)).toBe(false) + expect(await ask('update', admin)).toEqual({ team: { equals: 'a' } }) + expect(await ask('update', own)).toEqual({ and: [{ id: { equals: 7 } }, { team: { equals: 'a' } }] }) 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) + expect(visitors.access.create).toBe(g) + expect(asIs.access.create).toBe(g) // 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) + expect(seen.access.create).toBe(g) + expect([seen.endpoints.length, pages.endpoints.length]).toEqual([0, 0]) // a second call (a request after the start) changes nothing - expect(adoptLateAuthCollections(live, ['users', 'late'], { beforeOperation: hook })).toEqual([]) + expect(adoptLateAuthCollections(config, ['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']) + expect(unknownStaffCollections(config, ['users', 'late', 'pages', 'ghost'])).toEqual(['pages', 'ghost']) + // the combiner + expect(await bothAllow(() => true, undefined)({} as never)).toBe(true) + expect(await bothAllow(() => false, () => { throw new Error('not asked') })({} as never)).toBe(false) }) test('the rules are on the collections BEFORE the 2FA package wraps them', async () => { @@ -674,7 +713,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', 'read', 'unlock', 'update']) + expect(Object.keys(seen.staff2 as object).sort()).toEqual(['create', 'delete', 'read', 'readVersions', 'unlock', 'update']) expect(seen.customers).toEqual({ create: expect.any(Function) }) }) @@ -707,10 +746,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, read: staffReadAccess, unlock: staffCreateAccess, update: staffUpdateAccess('users') }, auth: true } }, + users: { config: { slug: 'users', access: { create: staffCreateAccess, delete: staffCreateAccess, read: staffReadAccess, readVersions: 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:read', 'agents:unlock', 'agents:update', 'weird:create', 'weird:delete', 'weird:read', 'weird:unlock']) // 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:readVersions', 'agents:unlock', 'agents:update', 'weird:create', 'weird:delete', 'weird:read', 'weird:readVersions', 'weird:unlock']) // no rule = Payload's default, open; a rule that throws = closed }) }) } diff --git a/test/secondFactorGuard.test.ts b/test/secondFactorGuard.test.ts index 9ed2280..6094d55 100644 --- a/test/secondFactorGuard.test.ts +++ b/test/secondFactorGuard.test.ts @@ -512,10 +512,10 @@ 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 auth = (slug: string) => ({ slug, auth: true, custom: { ipalAccounts: true }, fields: [] }) const payload = { - collections: { partners: auth('partners'), users: auth('users') }, - config: { admin: { user: 'users' }, collections: [], custom: config.custom, globals: [] }, + collections: {}, + config: { admin: { user: 'users' }, collections: [auth('partners'), auth('users')], custom: config.custom, globals: [] }, count: () => ({ totalDocs: 0 }), find: () => ({ docs: [] }), findGlobal: () => ({}), diff --git a/test/writeOnlySecrets.test.ts b/test/writeOnlySecrets.test.ts index d08c3b6..752a67b 100644 --- a/test/writeOnlySecrets.test.ts +++ b/test/writeOnlySecrets.test.ts @@ -131,6 +131,17 @@ describe('saving', () => { expect((await stored()).smtpPassword ?? null).toBeNull() }) + test('a value that is not text is refused, and the stored one stays', async () => { + await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: SMTP, turnstileSecretKey: TURNSTILE } as never }) + for (const notText of [false, 0, 5, {}, { a: 1 }, [SECRET_MASK], ['x']]) { + const res = await save({ smtpPassword: notText }) + expect([JSON.stringify(notText), res.status]).toEqual([JSON.stringify(notText), 400]) + expect(await res.text()).not.toContain('S3CRET') + expect((await save({ turnstileSecretKey: notText })).status).toBe(400) + } + expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE }) + }) + 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}", smtpFromName: "By GraphQL" }) { smtpPassword smtpFromName } }`)