Copied staff collections: the plugin's rule goes in front, nothing is replaced (a rule that cannot widen)
A plugin listed after ipalKit that copies a staff collection under a new slug, or reuses its access object, brings
rules the plugin wrote for the ORIGINAL. On 1.16.7 the copy also carried the boolean 'seen' marker and was left
alone: 'the account itself' then meant an account of the original — with numeric ids the original's account with
the same id changed the copy's account (17 of 40 measured shapes).
Design: the plugin never replaces and never rewrites a rule on such a collection. It puts its rule for the copy's
own slug in front, and both must allow: on a copy named as staff in front of every rule; on a copy that is not
staff or keeps its own rules (custom.ipal.accountRules: false) in front of the rules marked as the plugin's for
another collection. The roles field of every copy is guarded. The mark on the plugin's functions says only
{ slug, self }; custom.ipalAccounts says { slug, staff } (a collection named as staff during next dev is handled
on the reload). The plugin's rules are marked before its 2FA guard, which carries the mark.
Accepted cost: a copy's own account cannot edit itself through a copied rule (as on 1.16.7); the copy writes
access.update — one documented line.
Proof: test/accountCopyTableSuite.ts — 40 shapes x accounts x operations, each row not wider than the measurement
taken on 1.16.7 (test/fixtures/copyRulesBaseline.json) and not wider than the plugin's rule; 2FA off and on.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
4c7b722aed
commit
8dcc123b99
+114
-10
@@ -17,9 +17,12 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { adminOrSelfIn } from '../src/modules/access/index.js'
|
||||
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
|
||||
import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
|
||||
import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesAreAList, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
|
||||
import { buildPasswordRuleHook, checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
|
||||
import { isPasswordRuleHook, markedStaffRule, staffRuleOf } from '../src/modules/access/ruleMark.js'
|
||||
import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesAreAList, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
|
||||
import { requireSecondFactor } from '../src/modules/security/totp/secondFactor.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig, withTotpParts } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
@@ -555,8 +558,11 @@ export function accountRulesSuite(twoFactor: boolean): void {
|
||||
expect([of(own, 'users').access?.create, of(own, 'users').access?.update, of(own, 'users').access?.delete]).toEqual([mine, mine, mine])
|
||||
// the collection that carries the plugin's roles: the admin rule, although the field is injected later
|
||||
const ownNoRule = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
|
||||
expect(of(ownNoRule, 'users').access?.create).toBe(staffCreateAccess)
|
||||
expect(of(ownNoRule, 'users').access?.delete).toBe(staffCreateAccess)
|
||||
// (the plugin's rules carry its mark for the slug, on the function: that is how a copy of the collection is told later)
|
||||
expect(['create', 'delete', 'update', 'unlock', 'read', 'readVersions'].map((op) => staffRuleOf((of(ownNoRule, 'users').access as Record<string, unknown>)[op])?.slug)).toEqual(Array(6).fill('users'))
|
||||
expect(await (of(ownNoRule, 'users').access!.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users', roles: ['editor'] } } })).toBe(false)
|
||||
expect(staffRuleOf(mine)).toBeUndefined() // a rule the project wrote is not marked
|
||||
expect(staffRuleOf(staffCreateAccess)).toBeUndefined() // nor the exported rule itself: the mark is on a function of its own
|
||||
})
|
||||
|
||||
test('whose roles: the plugin\'s rule only where the roles are the plugin\'s', () => {
|
||||
@@ -622,7 +628,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, readVersions: staffReadAccess })
|
||||
expect(Object.keys(of(payloadWay, 'staff2').access ?? {}).sort()).toEqual(['read', 'readVersions'])
|
||||
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
|
||||
@@ -642,7 +648,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
|
||||
// without the plugin's roles nobody is an admin to it
|
||||
const noAccess = await ipalKit({ i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config)
|
||||
expect(of(noAccess, 'users').access?.create).toBeTypeOf('function')
|
||||
expect(of(noAccess, 'users').access?.create).not.toBe(staffCreateAccess)
|
||||
expect(await (of(noAccess, 'users').access!.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users' } } })).toBe(true)
|
||||
})
|
||||
|
||||
test('the roles field: protected where the plugin\'s update rule is in force and the field has no access of its own', async () => {
|
||||
@@ -651,7 +657,10 @@ export function accountRulesSuite(twoFactor: boolean): void {
|
||||
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)
|
||||
const fieldRule0 = inRow(await build({}, collections())).access?.update as (a: unknown) => boolean
|
||||
expect(staffRuleOf(fieldRule0)?.slug).toBe('staff2')
|
||||
expect(fieldRule0({ req: { payload: { staffCollections: ['staff2'] }, user: { id: 1, collection: 'staff2', roles: ['editor'] } } })).toBe(false)
|
||||
expect(fieldRule0({ req: { payload: { staffCollections: ['staff2'] }, user: { id: 1, collection: 'staff2', roles: ['admin'] } } })).toBe(true)
|
||||
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
|
||||
@@ -676,9 +685,9 @@ export function accountRulesSuite(twoFactor: boolean): void {
|
||||
const bw = ({ req }: { req: { user: unknown } }) => Boolean(req.user)
|
||||
const narrow = () => false
|
||||
const where = () => ({ team: { equals: 'a' } })
|
||||
const hook = () => undefined
|
||||
const hook = buildPasswordRuleHook() // a real one: the plugin knows its own hook by a mark on the function
|
||||
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: {}, hasMany: true, options: ['user', 'admin'] }] }
|
||||
const seen = { slug: 'users', access: { create: g }, auth: true, custom: { ipalAccounts: true }, endpoints: [], fields: [] }
|
||||
const seen = { slug: 'users', access: { create: g }, auth: true, custom: { ipalAccounts: { slug: 'users', staff: 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: [] }
|
||||
@@ -708,7 +717,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
|
||||
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(staffRuleOf((late.fields[0] as { access?: { update?: unknown } }).access?.update)?.slug).toBe('late')
|
||||
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
|
||||
// a late auth collection that is not staff: the first-user endpoint only
|
||||
@@ -727,6 +736,101 @@ export function accountRulesSuite(twoFactor: boolean): void {
|
||||
expect(await bothAllow(() => false, () => { throw new Error('not asked') })({} as never)).toBe(false)
|
||||
})
|
||||
|
||||
// The copy rules ("a rule that cannot widen"): the HTTP proof is the table in accountCopyTableSuite.ts; here the parts.
|
||||
test('the plugin\'s mark: on the function itself, never on a shared rule or through somebody\'s wrapper', async () => {
|
||||
const marked = markedStaffRule(staffCreateAccess, 'agents')
|
||||
expect(marked).not.toBe(staffCreateAccess)
|
||||
expect(staffRuleOf(marked)).toEqual({ slug: 'agents', self: marked })
|
||||
expect(staffRuleOf(staffCreateAccess)).toBeUndefined() // the exported rule is shared: a project may use it anywhere
|
||||
expect(staffRuleOf(() => true)).toBeUndefined()
|
||||
expect(staffRuleOf(undefined)).toBeUndefined()
|
||||
expect(await marked({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users', roles: ['admin'] } } } as never)).toBe(true)
|
||||
// the plugin's own wrapper (its 2FA guard) gets a mark made for IT
|
||||
const guarded = requireSecondFactor(marked)
|
||||
expect(staffRuleOf(guarded)).toEqual({ slug: 'agents', self: guarded })
|
||||
expect(staffRuleOf(requireSecondFactor(() => true))).toBeUndefined()
|
||||
// wrappers that are not the plugin's answer with the same property — and are not the rule
|
||||
const symbol = Symbol.for('ipal.staffRule')
|
||||
for (const [name, fn] of [['a Proxy', new Proxy(marked, { apply: () => false })], ['the rule as prototype', Object.setPrototypeOf(() => false, marked)], ['copied descriptors', Object.defineProperties(() => false, Object.getOwnPropertyDescriptors(marked))]] as [string, unknown][]) {
|
||||
expect([name, (fn as Record<symbol, unknown>)[symbol] !== undefined, staffRuleOf(fn)]).toEqual([name, true, undefined])
|
||||
}
|
||||
expect(staffRuleOf(marked.bind(null))).toBeUndefined()
|
||||
// the password hook: marked the same way, so a copy has it once — also across module instances (a registered symbol)
|
||||
const hook = buildPasswordRuleHook()
|
||||
expect(isPasswordRuleHook(hook)).toBe(true)
|
||||
expect((hook as unknown as Record<symbol, unknown>)[Symbol.for('ipal.passwordRule')]).toEqual({ self: hook })
|
||||
expect([isPasswordRuleHook(() => undefined), isPasswordRuleHook(new Proxy(hook, {}))]).toEqual([false, false])
|
||||
// with 2FA wiring that wraps every access function: the function that ENDS UP on the collection carries the mark…
|
||||
const wrapping = ((o: { collection: string }) => (c: Config) => withTotpParts({ ...c, collections: (c.collections ?? []).map((col) => ({ ...col, access: Object.fromEntries(Object.entries(col.access ?? {}).map(([k, v]) => [k, (x: never) => (v as (x: never) => unknown)(x)])) })) } as Config, o.collection)) as never
|
||||
const withFactory = await build({ twoFactor: { issuer: 'A', plugin: wrapping } })
|
||||
expect(['create', 'update', 'delete', 'unlock', 'read', 'readVersions'].map((op) => staffRuleOf((of(withFactory, 'staff2').access as Record<string, unknown>)[op])?.slug)).toEqual(Array(6).fill('staff2'))
|
||||
expect(staffRuleOf(of(withFactory, 'customers').access?.create)).toBeUndefined() // the project's own rule
|
||||
// …and marking does not undo ipal-kit's 2FA guard: a plain 2FA config has nothing left to guard at start
|
||||
const { ensurePayloadGuarded } = await import('../src/modules/security/totp/secondFactor.js')
|
||||
const plain = await build({ twoFactor: { issuer: 'A', plugin: ((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection)) as never } })
|
||||
expect([ensurePayloadGuarded({ config: plain } as never), ensurePayloadGuarded({ config: withFactory } as never)]).toEqual([[], []])
|
||||
})
|
||||
|
||||
test('a copied collection: the plugin\'s rule for ITS slug goes in front of every rule it brought; nothing is replaced', async () => {
|
||||
const mk = (slug: string, rule: unknown) => markedStaffRule(rule as () => unknown, slug)
|
||||
const access = { create: mk('agents', staffCreateAccess), delete: mk('agents', staffCreateAccess), read: mk('agents', staffReadAccess), update: mk('agents', staffUpdateAccess('agents')) }
|
||||
const pluginRoles = () => ({ name: 'roles', type: 'select', options: ['user', 'editor', 'admin'] }) as { access?: { update?: (a: unknown) => unknown }; name: string; options: string[]; type: string }
|
||||
const agents = { slug: 'agents', access, auth: true, custom: { ipalAccountRules: { slug: 'agents', applied: Object.keys(access), ownRoles: false }, ipalAccounts: { slug: 'agents', staff: true } }, endpoints: [], fields: [pluginRoles()], hooks: { beforeOperation: [buildPasswordRuleHook()] } }
|
||||
const nobody = () => false
|
||||
const copy = { ...agents, slug: 'copy', endpoints: [], fields: [pluginRoles()] }
|
||||
const ownRule = { ...agents, slug: 'own-rule', access: { ...access, update: nobody }, endpoints: [], fields: [pluginRoles()] }
|
||||
const optOut = { ...agents, slug: 'opt-out', custom: { ...agents.custom, ipal: { accountRules: false } }, endpoints: [], fields: [pluginRoles()] }
|
||||
const notStaff = { ...agents, slug: 'not-staff', endpoints: [], fields: [pluginRoles()] }
|
||||
const claims = { slug: 'claims', access: { create: mk('claims', () => true) }, auth: true, endpoints: [], fields: [] } // a mark that claims this very collection
|
||||
const hook = buildPasswordRuleHook()
|
||||
const adopted = adoptLateAuthCollections({ collections: [agents, copy, ownRule, optOut, notStaff, claims] } as never, ['agents', 'copy', 'own-rule', 'opt-out', 'claims'], { beforeOperation: hook })
|
||||
expect(adopted.map((x) => [x.slug, x.applied, x.password])).toEqual([
|
||||
['copy', ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], false], // the hook came along: not put twice
|
||||
['own-rule', ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], false],
|
||||
['opt-out', ['create', 'update', 'delete', 'read', 'roles'], false], // only in front of the rules the plugin wrote for `agents`, and the roles field
|
||||
['not-staff', ['create', 'update', 'delete', 'read', 'roles'], false],
|
||||
['claims', ['create', 'update', 'delete', 'unlock', 'read', 'readVersions'], true],
|
||||
])
|
||||
const staff = { staffCollections: ['users', 'agents', 'copy', 'own-rule', 'opt-out', 'claims'] }
|
||||
const ask = (c: { access: Record<string, unknown> }, operation: string, user: unknown) => (c.access[operation] as (a: unknown) => unknown)({ req: { payload: staff, user } })
|
||||
const admin = { id: 1, collection: 'users', roles: ['admin'] }
|
||||
const namesake = { id: 7, collection: 'agents', roles: ['user'] }
|
||||
for (const c of [copy, ownRule, optOut, notStaff]) {
|
||||
const own = { id: 7, collection: c.slug, roles: ['user'] }
|
||||
// the original's account with the same id is not "the account itself" here; nor does the copy's own account pass
|
||||
// the rule that still says "an account of `agents`" — both rules must allow (the accepted cost: the copy writes its own update rule)
|
||||
expect([c.slug, await ask(c, 'update', namesake), await ask(c, 'update', own), await ask(c, 'create', own), await ask(c, 'delete', own)]).toEqual([c.slug, false, false, false, false])
|
||||
// the functions that came along are still inside: nothing was replaced
|
||||
expect([c.slug, staffRuleOf(c.access.update)?.slug]).toEqual([c.slug, c.slug])
|
||||
expect([c.slug, await ask(c, 'create', admin)]).toEqual([c.slug, true])
|
||||
// the roles field of every copy is guarded, whatever the mode
|
||||
const field = (c.fields[0]).access?.update
|
||||
expect([c.slug, staffRuleOf(field)?.slug, await field?.({ id: 7, req: { payload: staff, user: own } })]).toEqual([c.slug, c.slug, false])
|
||||
expect(c.fields[0]).not.toBe(agents.fields[0])
|
||||
expect(c.access).not.toBe(agents.access)
|
||||
}
|
||||
expect(await ask(ownRule, 'update', admin)).toBe(false) // its own "nobody" still has to allow
|
||||
expect(await ask(copy, 'update', admin)).toBe(true)
|
||||
// the one line a copying plugin writes so that the copy's own accounts edit themselves (docs/access.md)
|
||||
const fixed = { ...agents, slug: 'fixed', access: { ...access, update: adminOrSelfIn('fixed') }, endpoints: [], fields: [pluginRoles()] }
|
||||
adoptLateAuthCollections({ collections: [fixed] } as never, ['agents', 'fixed'], { beforeOperation: hook })
|
||||
const all = { staffCollections: ['users', 'agents', 'fixed'] }
|
||||
const askFixed = (user: unknown) => (fixed.access.update as (a: unknown) => unknown)({ req: { payload: all, user } })
|
||||
expect(await askFixed({ id: 7, collection: 'fixed', roles: ['user'] })).toEqual({ and: [{ id: { equals: 7 } }, { id: { equals: 7 } }] })
|
||||
expect([await askFixed(namesake), await askFixed(admin)]).toEqual([false, true])
|
||||
// a mark that claims the collection does not leave the function alone
|
||||
expect([await ask(claims, 'create', { id: 9, collection: 'customers' }), await ask(claims, 'create', null), await ask(claims, 'create', admin)]).toEqual([false, false, true])
|
||||
// the original is untouched
|
||||
expect(await ask(agents, 'update', namesake)).toEqual({ id: { equals: 7 } })
|
||||
expect(staffRuleOf(agents.access.update)?.slug).toBe('agents')
|
||||
// R4-2: an object seen as NOT staff (a `next dev` edit names it as staff afterwards) is handled again; a second call changes nothing
|
||||
const visitors = { slug: 'visitors', access: { create: () => true }, auth: true, endpoints: [], fields: [] }
|
||||
expect(adoptLateAuthCollections({ collections: [visitors] } as never, [], { beforeOperation: hook }).map((x) => [x.slug, x.applied, x.firstUser])).toEqual([['visitors', [], true]])
|
||||
expect(adoptLateAuthCollections({ collections: [visitors] } as never, ['visitors'], { beforeOperation: hook }).map((x) => [x.slug, x.applied.length > 0, x.password, x.firstUser])).toEqual([['visitors', true, true, false]])
|
||||
expect(adoptLateAuthCollections({ collections: [visitors] } as never, ['visitors'], { beforeOperation: hook })).toEqual([])
|
||||
expect(await (visitors.access.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['visitors'] }, user: { id: 9, collection: 'customers' } } })).toBe(false)
|
||||
})
|
||||
|
||||
test('the rules are on the collections BEFORE the 2FA package wraps them', async () => {
|
||||
// the package gives every collection a create / update / delete of its own; afterwards "no rule" cannot be seen
|
||||
const seen: Record<string, unknown> = {}
|
||||
|
||||
Reference in New Issue
Block a user