diff --git a/.changeset/33696-drop-unrestricted-cbp-chain.md b/.changeset/33696-drop-unrestricted-cbp-chain.md new file mode 100644 index 00000000000..eaacd91121d --- /dev/null +++ b/.changeset/33696-drop-unrestricted-cbp-chain.md @@ -0,0 +1,27 @@ +--- +'@objectstack/objectql': patch +--- + +Clause-②: no +Metadata-protocol: none + +perf(objectql): a `controlled_by_parent` read no longer carries the parent-chain subquery for a +reader who holds View All on the detail and whose scope is unrestricted at every master hop, when the +detail's `master_detail` is required. + +For that reader (an admin with View All on the detail and on every object of the chain, under a +posture whose read scope adds no row condition), the engine's `ReadableIds` composition drops the +required master's leaf (`fk IN (SELECT id FROM master …)`) instead of compiling it. Admin lists, +counts and aggregates on detail objects run one subquery fewer per hop. + +Behaviour change, by maintainer ruling: totals, counts and aggregates for that reader may include +orphan rows, which are detail rows whose required master is missing or empty (rows that a +system-context write or a schema change left behind), inside the reader's own tenant wall. Every +other reader keeps the whole chain and sees exactly what it saw before. That includes a reader with +any restricted hop, a reader with View All on the detail only, and a plain member. An optional master +keeps its leaf. Under walled tenancy a tenant admin's master scope is the tenant wall, so nothing is +dropped there. + +Writes are unchanged. Every read a write makes while it runs keeps the chain: the security checks on a +predicate or by-id update or delete, and a hook's reads. An orphan therefore stays outside every +write, exactly as before. diff --git a/packages/objectql/src/engine-middleware-and-context.ts b/packages/objectql/src/engine-middleware-and-context.ts index 4229f070195..9659a4b9886 100644 --- a/packages/objectql/src/engine-middleware-and-context.ts +++ b/packages/objectql/src/engine-middleware-and-context.ts @@ -38,6 +38,7 @@ import type { IPubSub } from '@objectstack/spec/contracts'; import { redactPropagatedDriverFault } from '@objectstack/types'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { isWriteEpochOperation } from './write-epoch.js'; +import { READABLE_IDS_WRITE_IN_FLIGHT } from './engine-readable-ids-permission-formula.js'; import { bridgeAuthzInvalidation } from './authz-invalidation-bridge.js'; import { isMissingTableError } from '@objectstack/metadata/errors'; import { ORGANIZATION_OBJECT, SystemWriteOrganizationRequiredError, carriesOrganization, resolveSystemWriteOrganization, resolveTenantFieldName, type SystemWriteOrganizationDecision } from './tenancy/system-write-organization.js'; @@ -160,7 +161,9 @@ export class MiddlewareAndContextFacet { } }; - await next(); + // [#33696] A write's chain runs inside the write scope: its reads keep the chain. + if (isWriteEpochOperation(ctx.operation)) await READABLE_IDS_WRITE_IN_FLIGHT.run(true, next); + else await next(); return ctx.result; } diff --git a/packages/objectql/src/engine-readable-ids-nested-composition.test.ts b/packages/objectql/src/engine-readable-ids-nested-composition.test.ts index 4b1413bdc4c..b7ba69fb66f 100644 --- a/packages/objectql/src/engine-readable-ids-nested-composition.test.ts +++ b/packages/objectql/src/engine-readable-ids-nested-composition.test.ts @@ -409,3 +409,132 @@ describe('[ADR-0139 D6 as amended] a leaf inside a composed scope is composed to expect(outer.scope).toBe(scope); }); }); + +// ── [#33696 · ruling record 6893666857] step 5: the required master's leaf over an unrestricted master ── +// +// A leaf over the REQUIRED master of a `controlled_by_parent` object, the whole +// comparand of a `$in` on that master field in an AND position, is dropped when +// the master's answered scope is unrestricted AND the caller holds View All on +// that object (the security service's effective object-permission map); a +// scope left empty by the drop is unrestricted itself, so a chain drops whole +// only when every hop is. Every other position, an optional master, a +// restricted hop, a caller without View All, a delegated caller, a service +// without the map or one whose map throws, and a leaf on an object that is not +// `controlled_by_parent` compose exactly as before. The rows this +// serves are measured on the real stack in `@objectstack/plugin-security` +// (`security-plugin-cbp-read-filter.test.ts`). +describe('[#33696 ruling 6893666857] the required master\'s leaf over an unrestricted master is dropped, nowhere else', () => { + let engine: ObjectQL; + let calls: SeenCall[]; + + const cbp = (name: string, fk: string, master: string, required: boolean) => ({ + name, + label: name, + sharingModel: 'controlled_by_parent', + fields: { + name: { name: 'name', type: 'text' }, + [fk]: { name: fk, type: 'master_detail', reference: master, required }, + }, + }); + const ACCOUNT = { name: 'rid_r4_account', label: 'Account', fields: { owner: { name: 'owner', type: 'text' } } }; + const OPP = cbp('rid_r4_opp', 'account', 'rid_r4_account', true); + const LINE = cbp('rid_r4_line', 'opp', 'rid_r4_opp', true); + const NOTE = cbp('rid_r4_note', 'opp', 'rid_r4_opp', false); + /** The leaf the controlled-by-parent derivation answers for a detail over `master` on `fk`. */ + const leafOn = (fk: string, master: string) => ({ [fk]: { $in: ReadableIds.of(master) } }); + /** View All on every detail: the effective map a security service answers for an administrator. */ + const VIEW_ALL_DETAILS = { rid_r4_opp: { viewAllRecords: true }, rid_r4_line: { viewAllRecords: true }, rid_r4_note: { modifyAllRecords: true } }; + /** + * The service of the chain: the opportunity's scope is its leaf over the + * account; the account's is `accountScope`; the caller's effective map is + * `effective` (`null`: the service has no such member; a function: its answer). + */ + const chain = (accountScope: unknown, effective: unknown = VIEW_ALL_DETAILS) => { + const security = makeSecurity({ + scope: (object) => (object === 'rid_r4_opp' ? leafOn('account', 'rid_r4_account') : object === 'rid_r4_account' ? accountScope : undefined), + }); + if (effective !== null) { + security.svc.getEffectiveObjectPermissions = async (context?: unknown) => { + security.asked.push('getEffectiveObjectPermissions'); + return typeof effective === 'function' ? (effective as (c: unknown) => unknown)(context) : effective; + }; + } + return security; + }; + const whereOf = async (object: string, where: Record, context: unknown = { userId: 'u1' }) => { + calls.length = 0; + await engine.find(object, { where, context: context as any }); + expect(calls.map((c) => c.verb)).toEqual(['find']); + return calls[0].ast.where; + }; + + beforeEach(async () => { + const rec = makeRecordingDriver(); + calls = rec.calls; + engine = new ObjectQL(); + engine.registerDriver(rec.driver, true); + await engine.init(); + for (const def of [ACCOUNT, OPP, LINE, NOTE, CHILD, PARENT]) engine.registry.registerObject(def as any, 'test'); + calls.length = 0; + }); + + it('every hop unrestricted: the leaf at the root, and as an `$and` member, is dropped; the masters are still asked', async () => { + const { svc, asked } = chain(undefined); + wire(engine, () => svc); + expect(await whereOf('rid_r4_line', leafOn('opp', 'rid_r4_opp'))).toEqual({}); + // The effective map is asked once per read, and only once a leaf could be dropped. + expect(asked).toEqual([ + 'canReadObject:rid_r4_opp', 'getReadFilter:rid_r4_opp', 'canReadObject:rid_r4_account', 'getReadFilter:rid_r4_account', + 'getEffectiveObjectPermissions', + ]); + expect(await whereOf('rid_r4_line', { $and: [{ name: 'x' }, leafOn('opp', 'rid_r4_opp')] })).toEqual({ $and: [{ name: 'x' }] }); + expect(await whereOf('rid_r4_line', { name: 'x', ...leafOn('opp', 'rid_r4_opp') })).toEqual({ name: 'x' }); + }); + + it('a restricted hop keeps the whole chain: the outer leaf composed, the inner one too', async () => { + const accountScope = { owner: 'u1' }; + const { svc } = chain(accountScope); + wire(engine, () => svc); + const outer = (await whereOf('rid_r4_line', leafOn('opp', 'rid_r4_opp'))).opp.$in; + expect(isComposedReadableIds(outer)).toBe(true); + expect(outer.object).toBe('rid_r4_opp'); + expect(isComposedReadableIds(outer.scope.account.$in)).toBe(true); + expect(outer.scope.account.$in.scope).toBe(accountScope); + }); + + it('an `$or` position, an OPTIONAL master and an object that is not controlled_by_parent compose as before', async () => { + const { svc } = chain(undefined); + wire(engine, () => svc); + const or = await whereOf('rid_r4_line', { $or: [leafOn('opp', 'rid_r4_opp'), { name: 'x' }] }); + expect(isComposedReadableIds(or.$or[0].opp.$in)).toBe(true); + const optional = await whereOf('rid_r4_note', leafOn('opp', 'rid_r4_opp')); + expect(isComposedReadableIds(optional.opp.$in)).toBe(true); + // The master's own leaf was dropped, so its composed scope is unrestricted. + expect(optional.opp.$in.scope).toBeUndefined(); + const plain = await whereOf('rid_child', branch('rid_parent')); + expect(isComposedReadableIds(plain.record_id.$in)).toBe(true); + }); + + it('a caller without View All on the detail keeps the whole chain, whatever the hops answer', async () => { + for (const [label, effective, context] of [ + ['no View All on any detail', { rid_r4_line: { allowRead: true }, rid_r4_opp: { allowRead: true } }, { userId: 'u1' }], + ['View All on the read detail only', { rid_r4_line: { viewAllRecords: true } }, { userId: 'u1' }], + ['a service without the effective map', null, { userId: 'u1' }], + ['an effective map that throws', () => { throw new Error('resolution is down'); }, { userId: 'u1' }], + ['a delegated caller', VIEW_ALL_DETAILS, { userId: 'agent', onBehalfOf: { userId: 'u1' } }], + ] as const) { + const { svc } = chain(undefined, effective); + wire(engine, () => svc); + const outer = (await whereOf('rid_r4_line', leafOn('opp', 'rid_r4_opp'), context)).opp.$in; + expect(isComposedReadableIds(outer), label).toBe(true); + expect(isComposedReadableIds(outer.scope.account.$in), label).toBe(true); + expect(outer.scope.account.$in.scope, label).toBeUndefined(); + } + }); + + it('a master the caller may not read keeps the leaf, answered `$in: []`', async () => { + const { svc } = makeSecurity({ canRead: (object) => object !== 'rid_r4_opp' }); + wire(engine, () => svc); + expect(await whereOf('rid_r4_line', leafOn('opp', 'rid_r4_opp'))).toEqual({ opp: { $in: [] } }); + }); +}); diff --git a/packages/objectql/src/engine-readable-ids-permission-formula.ts b/packages/objectql/src/engine-readable-ids-permission-formula.ts index 34d88be6d08..5b11fe55225 100644 --- a/packages/objectql/src/engine-readable-ids-permission-formula.ts +++ b/packages/objectql/src/engine-readable-ids-permission-formula.ts @@ -62,11 +62,19 @@ * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. + * + * [#33696 · ruling record 6893666857] `composeReadableIdsChain` reads the + * registry too (`_registry`, a getter like the others): a leaf over the + * REQUIRED master of a `controlled_by_parent` object is dropped when its + * master's scope is unrestricted and the caller holds View All on the object + * ({@link unrestrictedRequiredMasterLeavesDropped}). */ -import { ReadableIds, RLS_DENY_FILTER, controlledByParentMasterOf, markFilterSubtreeProvenance } from '@objectstack/spec/data'; +import { AsyncLocalStorage } from 'node:async_hooks'; +import { ReadableIds, RLS_DENY_FILTER, controlledByParentMasterOf, filterSubtreeProvenanceOf, isReadableIds, markFilterSubtreeProvenance } from '@objectstack/spec/data'; import type { FilterCondition } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { ISecurityService } from '@objectstack/spec/contracts'; import { toEvalPermissions, type EvalError, type EvalPermissions } from '@objectstack/formula'; import { collectComposableReadableIds, composeReadableIdsLeaves, describeReadableIdsLeaf, readableIdsRefusalError } from './filter-comparand-shape.js'; import type { ComposableReadableIdsSite } from './filter-comparand-shape.js'; @@ -152,9 +160,27 @@ export const READABLE_IDS_MAX_CHAIN_DEPTH = 8; * not compose, inside an answered scope is refused by the same walk that * refuses it in a caller's `where` ({@link collectComposableReadableIds}): * the scope is the `where` of a read of its parent and is judged as one. + * + * [#33696 · ruling record 6893666857] 5. A leaf over the REQUIRED master of + * the object whose `where` or scope `node` is — that object + * `controlled_by_parent`, the leaf the whole comparand of a `$in` on its + * required `master_detail` field, in an AND position — is DROPPED, not + * composed, when the master's answered scope is `undefined` (admitted, no + * row restriction) AND the caller holds View All on that object + * ({@link readerViewsAllOf}): `fk IN (SELECT id FROM master)` then removes + * only the rows whose master is missing or empty, and the ruling has that + * reader see those, as #30905 ruling A has a View All holder see the + * null-master rows of an optional master. Every other reader, a delegated + * one included, keeps the chain. A scope that is left with no condition once its own leaves + * are dropped is itself `undefined`, so a chain drops whole only when every + * hop is unrestricted; a restricted hop keeps its leaf and every leaf below + * it. An optional master, a leaf in an `$or`/`$not`, and every other + * consumer's leaf compose exactly as before. The tenant wall is not part of + * the scope (D2 step 3): the outer read's own wall still bounds the detail + * rows. See {@link unrestrictedRequiredMasterLeavesDropped}. */ export async function composeReadableIdsChain( - this: Pick, + this: Pick, chain: ReadableIdsChain, node: N, sites: readonly ComposableReadableIdsSite[], @@ -196,18 +222,160 @@ export async function composeReadableIdsChain( // The scope is the `where` of a read of `parent`: judged as one, and // the leaves it carries are composed before this parent's leaf is. const nested = collectComposableReadableIds(object, operation, answer.scope, 'where', `${site.at}.scope`); - chain.answers.set(parent, nested.length === 0 - ? answer - : { scope: await this.composeReadableIdsChain(chain, answer.scope, nested, [...ancestors, parent]) }); + if (nested.length === 0) { + chain.answers.set(parent, answer); + continue; + } + const composed = await this.composeReadableIdsChain(chain, answer.scope, nested, [...ancestors, parent]); + // [#33696] Every condition of the scope was a dropped leaf: unrestricted. + chain.answers.set(parent, { scope: isEmptyCondition(composed) ? undefined : composed }); } + // [#33696] Step 5: the required master's leaf over an unrestricted master, + // for a reader who holds View All on the object this node scopes. + const scoped = ancestors.length === 0 ? object : ancestors[ancestors.length - 1]!; + const master = requiredControlledByParentMasterOf(this._registry.getObject(scoped)); + const vacuous = (leaf: ReadableIds): boolean => { + const answer = chain.answers.get(leaf.object); + return leaf.object === master?.master && answer != null && answer.scope === undefined; + }; + const pruned = master && sites.some((site) => vacuous(site.leaf)) && await readerViewsAllOf(chain, scoped) + ? unrestrictedRequiredMasterLeavesDropped(node, master, vacuous) + : node; // A parent with no answer (`null`, or never asked: not registered) is // `$in: []`. - return composeReadableIdsLeaves(node, (leaf) => { + return composeReadableIdsLeaves(pruned, (leaf) => { const answer = chain.answers.get(leaf.object); return answer ? ReadableIds.compose(leaf, answer.scope) : []; }); } +/** + * [#33696 · ruling record 6893666857] The effective object-permission map of + * the read's caller, asked of the security service once per read + * (`ISecurityService.getEffectiveObjectPermissions`, the map + * `/auth/me/permissions` serves, folded through the same super-user predicate + * as the plugin's View All bypass). `null` — and so no leaf dropped — for a + * delegated (on-behalf-of) caller, a service without the member, and a + * resolution that threw: each keeps the chain, the answer every reader had + * before, so a failure here costs the subquery and never a row. + */ +/** + * [#33696 · review 6895328067, route (a)] Set while a write's middleware + * chain runs (`executeWithMiddleware`, for every write-epoch operation), so a + * read issued on a write's behalf under the caller's context — the security + * plugin's predicate-write narrowing, its 2.8 gate's predicate leg, its + * step-2.7 by-id read, a hook's read — keeps the chain: ruling 6893666857 is a + * read ruling, and every write path answers byte-identically to before it. An + * async scope, not a context stamp, for the reason the security plugin's + * `engineOperationScope` gives: a context is shared and spread across the very + * reads and sub-writes it would have to mark, and a scope cannot outlive the + * write it wraps. + */ +export const READABLE_IDS_WRITE_IN_FLIGHT = new AsyncLocalStorage(); + +const EFFECTIVE_PERMISSIONS = new WeakMap> | null>>(); + +/** Does the read's caller hold View All (`viewAllRecords`, or `modifyAllRecords`) on `object`? */ +async function readerViewsAllOf(chain: ReadableIdsChain, object: string): Promise { + // Inside a write: the chain stays, whoever reads (route (a) above). + if (READABLE_IDS_WRITE_IN_FLIGHT.getStore() === true) return false; + let pending = EFFECTIVE_PERMISSIONS.get(chain); + if (pending === undefined) { + const svc = chain.security.kind === 'usable' + ? (chain.security.svc as Partial>) + : undefined; + const delegated = (chain.context as { onBehalfOf?: { userId?: unknown } } | undefined)?.onBehalfOf?.userId != null; + pending = svc && !delegated && typeof svc.getEffectiveObjectPermissions === 'function' + ? Promise.resolve() + .then(() => svc.getEffectiveObjectPermissions!(chain.context as never)) + // Fails toward the chain: the read keeps its subquery, never a row. + .catch(() => null) + : Promise.resolve(null); + EFFECTIVE_PERMISSIONS.set(chain, pending); + } + const entry = (await pending)?.[object] as { viewAllRecords?: unknown; modifyAllRecords?: unknown } | undefined; + return entry?.viewAllRecords === true || entry?.modifyAllRecords === true; +} + +/** A plain object with no key: a condition that matches every row. */ +function isEmptyCondition(node: unknown): boolean { + if (node === null || typeof node !== 'object' || Array.isArray(node)) return false; + const proto = Object.getPrototypeOf(node); + return (proto === Object.prototype || proto === null) && Object.keys(node).length === 0; +} + +/** + * [ADR-0055 §1 · #33696] The REQUIRED master of a `controlled_by_parent` + * object, as its field map declares it — the field and the object it + * references — or `undefined`: another sharing model, an optional master + * (`required: false`, whose leaf is one arm of an `$or` and always composes), + * no resolvable master, or a reference that is not a plain object name. + */ +function requiredControlledByParentMasterOf(schema: unknown): { field: string; master: string } | undefined { + const s = schema as { sharingModel?: unknown; security?: { sharingModel?: unknown }; fields?: Record } | null | undefined; + if ((s?.sharingModel ?? s?.security?.sharingModel) !== 'controlled_by_parent') return undefined; + const relation = controlledByParentMasterOf(s?.fields); + if (!relation || relation.optional) return undefined; + const master = s?.fields?.[relation.field]?.reference; + return typeof master === 'string' && master.length > 0 ? { field: relation.field, master } : undefined; +} + +/** + * [#33696 · ruling record 6893666857] `node` — the `where` or + * scope of a `controlled_by_parent` object — with every leaf over its REQUIRED + * master removed whose master `unrestricted` answers as unrestricted. Only a + * leaf that is the whole comparand of `{ [master.field]: { $in: leaf } }` is + * removed, and only in an AND position: the node itself or a member of an + * `$and` reached through AND positions. A `$and` member left empty goes, and + * an `$and` left empty goes with it. Copy-on-write, provenance marks kept. + * + * Why only there: in an AND position the leaf is one conjunct, so removing it + * widens exactly by the rows the leaf alone removed — with the master + * unrestricted, the rows whose required master is missing or empty, which the + * ruling has an unrestricted reader see. Under an `$or` or a `$not` removing a + * conjunct is no such widening, and the optional master's leaf sits in an + * `$or` by construction ({@link requiredControlledByParentMasterOf} does not + * name it either), so neither is touched. + */ +function unrestrictedRequiredMasterLeavesDropped( + node: N, + master: { field: string; master: string } | undefined, + unrestricted: (leaf: ReadableIds) => boolean, +): N { + if (!master) return node; + const prune = (value: unknown): unknown => { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return value; + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) return value; + let out: Record | undefined; + for (const key of Object.keys(value)) { + const item = (value as Record)[key]; + if (key === master.field && item !== null && typeof item === 'object' && !Array.isArray(item) + && Object.keys(item).length === 1) { + const leaf = (item as { $in?: unknown }).$in; + if (isReadableIds(leaf) && leaf.object === master.master && unrestricted(leaf)) { + out ??= { ...(value as Record) }; + delete out[key]; + continue; + } + } + if (key === '$and' && Array.isArray(item)) { + const members = item.map(prune); + if (members.some((m, i) => m !== item[i])) { + const kept = members.filter((m) => !isEmptyCondition(m)); + out ??= { ...(value as Record) }; + if (kept.length === 0) delete out[key]; + else out[key] = kept; + } + } + } + if (out === undefined) return value; + const mark = filterSubtreeProvenanceOf(value); + return mark === null ? out : markFilterSubtreeProvenance(out, mark); + }; + return prune(node) as N; +} + /** The body of `ObjectQL#findUnservableControlledByParentMasters`; the method's docblock there is its contract. */ export function findUnservableControlledByParentMasters( this: Pick, diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index a5809caab3f..8a136744cb0 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -1555,7 +1555,9 @@ export class ObjectQL implements IObjectQLEngine { ancestors: readonly string[], ): Promise { // [#25522 cut 15] The body moved to `engine-readable-ids-permission-formula.ts`, its docblock with it (see `ReadableIdsPermissionFormulaHost`). + const readRegistry = () => this._registry; const host: ThisParameterType = { + get _registry() { return readRegistry(); }, refuseUncomposableReadableIdsClasses: (...a) => this.refuseUncomposableReadableIdsClasses(...a), readableIdsScopeOf: (...a) => this.readableIdsScopeOf(...a), composeReadableIdsChain: (...a) => this.composeReadableIdsChain(...a), diff --git a/packages/plugins/plugin-security/src/controlled-by-parent-leaf-switch.test.ts b/packages/plugins/plugin-security/src/controlled-by-parent-leaf-switch.test.ts index dc600244428..590a0731ebd 100644 --- a/packages/plugins/plugin-security/src/controlled-by-parent-leaf-switch.test.ts +++ b/packages/plugins/plugin-security/src/controlled-by-parent-leaf-switch.test.ts @@ -29,8 +29,9 @@ * - every caller shape keeps its row set: plain (restricted by ownership and a * share), unrestricted (`viewAllRecords`), delegated (the ADR-0090 D10 * intersection), two-level chain, null and dangling master pointers - * (excluded — ruling B item 4), and a caller the master object does not - * admit (the deny door, `$in: []`); + * (excluded — ruling B item 4 — for every caller but View All on the detail + * over unrestricted hops, which reads them: ruling record 6893666857), and a + * caller the master object does not admit (the deny door, `$in: []`); * - statements per request: find = 1, find + count = 2, no scan of the master * on its own, the master inside the child's subquery; * - past the variable limit: 200 with exactly the right rows; @@ -101,6 +102,8 @@ const DEEP_LINKS = 10; const HUMAN = 'u_cbp_leaf_human'; const OTHER = 'u_cbp_leaf_other'; const VIEW_ALL = 'u_cbp_leaf_view_all'; +/** View All on the account AND on every detail: the reader ruling record 6893666857 drops the chain for. */ +const ADMIN_ALL = 'u_cbp_leaf_admin_all'; const NO_ACCOUNT_READ = 'u_cbp_leaf_no_account_read'; const SET = { @@ -108,6 +111,8 @@ const SET = { member: 'qa_cbp_leaf_member', /** The same, with `viewAllRecords` on the account: an unrestricted master scope. */ viewAll: 'qa_cbp_leaf_view_all', + /** View All on the account and on every detail. */ + adminAll: 'qa_cbp_leaf_admin_all', /** Read on the details, not on the account. */ noAccount: 'qa_cbp_leaf_no_account', /** The agent's ceiling: read everywhere, a content rule on the account's rows. */ @@ -229,7 +234,7 @@ async function boot(cell: Cell) { logger: { warn: () => void }; }; await e.insert('sys_organization', { id: ORG, name: ORG, slug: ORG }, SYS); - for (const id of [HUMAN, OTHER, VIEW_ALL, NO_ACCOUNT_READ]) { + for (const id of [HUMAN, OTHER, VIEW_ALL, ADMIN_ALL, NO_ACCOUNT_READ]) { await e.insert('sys_user', { id, name: id, email: `${id}@example.test` }, SYS); await e.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, SYS); } @@ -241,6 +246,7 @@ async function boot(cell: Cell) { ...defaultPermissionSets, PermissionSetSchema.parse({ name: SET.member, objects: { ...readAll, [ACCOUNT]: READ_EDIT, [CONTACT]: READ_EDIT } }), PermissionSetSchema.parse({ name: SET.viewAll, objects: { ...readAll, [ACCOUNT]: { ...READ, viewAllRecords: true } } }), + PermissionSetSchema.parse({ name: SET.adminAll, objects: Object.fromEntries([ACCOUNT, CONTACT, QUOTE, LINE].map((o) => [o, { ...READ, viewAllRecords: true }])) }), PermissionSetSchema.parse({ name: SET.noAccount, objects: Object.fromEntries(detailObjects.map((o) => [o, READ])) }), PermissionSetSchema.parse({ name: SET.ceiling, @@ -444,6 +450,10 @@ for (const cell of CELLS) describe(`on ${cell.label}`, () => { const context = member(VIEW_ALL, SET.viewAll); expect(await rig.read(CONTACT, context)).toEqual(['c_open', 'c_other', 'c_secret', 'c_shared']); expect(await rig.count(CONTACT, context)).toBe(4); + // [ruling record 6893666857] View All on the detail too: no chain, so the null and dangling pointers as well. + const admin = member(ADMIN_ALL, SET.adminAll); + expect(await rig.read(CONTACT, admin)).toEqual(['c_dangling', 'c_null', 'c_open', 'c_other', 'c_secret', 'c_shared']); + expect(await rig.count(CONTACT, admin)).toBe(6); }); it('a caller the master object does not admit reads no contact: canReadObject(ACCOUNT) is false, the leaf is $in: []', async () => { @@ -468,6 +478,8 @@ for (const cell of CELLS) describe(`on ${cell.label}`, () => { expect(await rig.read(LINE, member(VIEW_ALL, SET.viewAll))).toEqual(['l_open', 'l_other']); expect(await rig.read(LINE, await rig.onBehalfOf(HUMAN))).toEqual(['l_open']); expect(await rig.count(LINE, member(VIEW_ALL, SET.viewAll))).toBe(2); + // [ruling record 6893666857] View All on every detail over unrestricted hops: the orphans at either hop too. + expect(await rig.read(LINE, member(ADMIN_ALL, SET.adminAll))).toEqual(['l_dangling', 'l_null', 'l_open', 'l_other', 'l_via_dangling', 'l_via_null']); }); it('CONTROL — a system context reads every detail whose master pointer is set, the chain composed with no restriction', async () => { @@ -506,6 +518,13 @@ for (const cell of CELLS) describe(`on ${cell.label}`, () => { for (const sql of reading(both)) expect(sql, bothAll).toMatch(/in \(select/i); }); + it('View All on the detail over unrestricted hops: the find is one statement with no master subquery (ruling record 6893666857)', async () => { + const find = await rig.statementsDuring(() => rig.engine.find(CONTACT, { context: member(ADMIN_ALL, SET.adminAll) } as never)); + const reads = find.filter((sql) => readsTable(CONTACT)(sql) || readsTable(ACCOUNT)(sql)); + expect(reads, find.join('\n')).toHaveLength(1); + expect(reads[0], find.join('\n')).not.toMatch(/in \(select/i); + }); + it('a delegated find is one statement too: both halves write the leaf, the engine composes the master once, the subquery is carried twice', async () => { const context = await rig.onBehalfOf(HUMAN); const find = await rig.statementsDuring(() => rig.engine.find(CONTACT, { context: { ...context } } as never)); diff --git a/packages/plugins/plugin-security/src/security-plugin-cbp-read-filter.test.ts b/packages/plugins/plugin-security/src/security-plugin-cbp-read-filter.test.ts new file mode 100644 index 00000000000..461ad8145f5 --- /dev/null +++ b/packages/plugins/plugin-security/src/security-plugin-cbp-read-filter.test.ts @@ -0,0 +1,463 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#33696 · ruling record 6893666857] The controlled-by-parent read leaf over a +// REQUIRED master is dropped by the engine's composition for a reader who holds +// View All on the detail AND whose every master hop answers an unrestricted +// scope: the read carries no parent-chain subquery, and that reader also sees +// the orphan detail rows (a master that no longer exists, or a required master +// left empty) inside its own tenant wall, as View All on the detail reads an +// optional master's null-master rows (#30905 ruling A). Every other reader keeps +// the chain unchanged: a restricted master hop, View All on the detail alone, a +// plain member over an unrestricted master. An OPTIONAL master keeps its `$or` +// leaf whoever reads. +// +// The leaf this module writes (`computeControlledByParentFilter`) is unchanged: +// the drop is the engine's (`composeReadableIdsChain`, step 5), because only the +// engine holds the per-hop answer — the master's scope after `canReadObject` and +// `getReadFilter` — and the ruling keys the drop on that answer, never on View +// All on the detail alone (`hasSuperuserReadBypass`, which does not open the +// master arm). +// +// The real stack: `ObjectQL` over better-sqlite3, the real `SecurityPlugin` +// and the real `SharingService` with its middleware, objects in two +// organizations. The orphans are written the two ways measured on the card: a +// system-context insert naming a master that does not exist (the reference +// check's documented `isSystem` residual), and a row stored through the driver +// with its required master empty (what a promotion of an optional master to +// required leaves behind). +// +// r4_account (private) <-account- r4_opp (cbp, required) <-opp- r4_line (cbp, required) +// r4_opp <-opp?- r4_note (cbp, OPTIONAL master) +// r4_pub_account (public_read_write) <-account- r4_pub_line (cbp, required) + +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SharingService, buildSharingMiddleware, SysRecordShare } from '@objectstack/plugin-sharing'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { isComposedReadableIds, isReadableIds } from '@objectstack/spec/data'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; +import { SysUserPosition } from './objects/sys-user-position.object.js'; +import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; +import { wireEngineSecuritySource } from './engine-security-source.testkit.js'; + +const SYS = { context: { isSystem: true } } as never; +const ORG_A = 'org_r4_a'; +const ORG_B = 'org_r4_b'; + +const ACCOUNT = 'r4_account'; +const OPP = 'r4_opp'; +const LINE = 'r4_line'; +const NOTE = 'r4_note'; +const PUB_ACCOUNT = 'r4_pub_account'; +const PUB_LINE = 'r4_pub_line'; +const OBJECTS = [ACCOUNT, OPP, LINE, NOTE, PUB_ACCOUNT, PUB_LINE]; + +/** View All on every object of the chain: every hop answers an unrestricted scope. */ +const ADMIN_USER = 'usr_r4_admin'; +/** Read on every object, View All on none: the private account hop is owner-scoped. */ +const MEMBER_USER = 'usr_r4_member'; +/** View All on every DETAIL, not on the account: a restricted master hop. */ +const DETAIL_ADMIN_USER = 'usr_r4_detail_admin'; +/** View All on the read detail (`r4_line`) only. */ +const LINE_ADMIN_USER = 'usr_r4_line_admin'; + +const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; +const ADMIN_SET = PermissionSetSchema.parse({ + name: 'r4_admin', + objects: Object.fromEntries(OBJECTS.map((o) => [o, { ...CRUD, viewAllRecords: true, modifyAllRecords: true }])), +}); +const MEMBER_SET = PermissionSetSchema.parse({ + name: 'r4_member', + objects: Object.fromEntries(OBJECTS.map((o) => [o, CRUD])), +}); +const DETAIL_ADMIN_SET = PermissionSetSchema.parse({ + name: 'r4_detail_admin', + objects: Object.fromEntries(OBJECTS.map((o) => [o, o === ACCOUNT ? CRUD : { ...CRUD, viewAllRecords: true }])), +}); +const LINE_ADMIN_SET = PermissionSetSchema.parse({ + name: 'r4_line_admin', + objects: Object.fromEntries(OBJECTS.map((o) => [o, o === LINE ? { ...CRUD, viewAllRecords: true } : CRUD])), +}); +const MEMBER_DEFAULT = defaultPermissionSets.find((p) => p.name === 'member_default')!; +const SETS = [MEMBER_DEFAULT, ADMIN_SET, MEMBER_SET, DETAIL_ADMIN_SET, LINE_ADMIN_SET]; + +/** The execution context `resolveAuthzContext` hands the middleware for an organization member holding `set`. */ +const memberOf = (userId: string, set: string, tenantId: string) => ({ + userId, + tenantId, + positions: ['org_member'], + permissions: [set, 'member_default'], + posture: 'MEMBER', +}); +const ADMIN = memberOf(ADMIN_USER, ADMIN_SET.name, ORG_A); +const ADMIN_B = memberOf(ADMIN_USER, ADMIN_SET.name, ORG_B); +const MEMBER = memberOf(MEMBER_USER, MEMBER_SET.name, ORG_A); +const DETAIL_ADMIN = memberOf(DETAIL_ADMIN_USER, DETAIL_ADMIN_SET.name, ORG_A); +const LINE_ADMIN = memberOf(LINE_ADMIN_USER, LINE_ADMIN_SET.name, ORG_A); + +const detail = (name: string, fk: string, reference: string, required: boolean) => ({ + name, + label: name, + sharingModel: 'controlled_by_parent', + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, + [fk]: { name: fk, type: 'master_detail', reference, required }, + }, +}); + +const ids = (rows: unknown): string[] => + (Array.isArray(rows) ? rows : [rows]).filter(Boolean).map((r) => String((r as { id: unknown }).id)).sort(); + +/** Every `ReadableIds` leaf, composed or not, anywhere in `node`. */ +function leavesIn(node: unknown, out: unknown[] = []): unknown[] { + if (node === null || typeof node !== 'object') return out; + if (isReadableIds(node) || isComposedReadableIds(node)) { + out.push(node); + if (isComposedReadableIds(node)) leavesIn((node as { scope?: unknown }).scope, out); + return out; + } + for (const value of Array.isArray(node) ? node : Object.values(node)) leavesIn(value, out); + return out; +} + +type Posture = 'single' | 'isolated'; + +/** One rig per tenancy posture: the seeded rows are the same in both. */ +async function boot(posture: Posture) { + /** The `where` the driver received for each read of a detail, in order. */ + const received: Array<{ object: string; where: unknown }> = []; + /** Every SQL statement the driver ran, while `capturing`. */ + const statements: string[] = []; + let capturing = false; + + const engine = new ObjectQL(); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.cbp-unrestricted-chain', + name: 'A controlled_by_parent chain read over unrestricted hops', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [ + SysRecordShare, SysUser, SysOrganization, SysMember, SysUserPosition, SysUserPermissionSet, + { + name: ACCOUNT, + label: 'Account', + sharingModel: 'private', + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, + }, + }, + detail(OPP, 'account', ACCOUNT, true), + detail(LINE, 'opp', OPP, true), + detail(NOTE, 'opp', OPP, false), + { + name: PUB_ACCOUNT, + label: 'Public account', + sharingModel: 'public_read_write', + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, + }, + }, + detail(PUB_LINE, 'account', PUB_ACCOUNT, true), + ], + } as never); + await engine.syncSchemas(); + + await engine.insert('sys_organization', [ORG_A, ORG_B].map((id) => ({ id, name: id, slug: id })), SYS); + await engine.insert('sys_user', [ADMIN_USER, MEMBER_USER, DETAIL_ADMIN_USER, LINE_ADMIN_USER].map((id) => ({ + id, name: id, email: `${id}@r4.test`, + })), SYS); + + let securityService: unknown; + let sharing: SharingService | undefined; + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + type === 'permission' ? SETS.find((s) => s.name === name) ?? null : engine.getSchema(name) ?? null, + list: async () => SETS, + }, + get sharing() { return sharing; }, + tenancy: { posture, isolationActive: posture !== 'single' }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: (name: string, svc: unknown) => { if (name === 'security') securityService = svc; }, + hook: () => undefined, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + wireEngineSecuritySource(engine, () => plugin); + sharing = new SharingService({ engine: engine as never, securityService: () => securityService as never }); + engine.registerMiddleware(buildSharingMiddleware(sharing, ctx.logger) as never, { object: '*' }); + + // Seeded as system, in each organization; the member owns acc_a1, the detail admin acc_a2. + const inOrg = (org: string) => ({ context: { isSystem: true, tenantId: org } }) as never; + await engine.insert(ACCOUNT, [ + { id: 'acc_a1', name: 'a1', owner_id: MEMBER_USER }, + { id: 'acc_a2', name: 'a2', owner_id: DETAIL_ADMIN_USER }, + ], inOrg(ORG_A)); + await engine.insert(ACCOUNT, [{ id: 'acc_b1', name: 'b1', owner_id: ADMIN_USER }], inOrg(ORG_B)); + await engine.insert(OPP, [ + { id: 'opp_a1', name: 'a1', account: 'acc_a1' }, + { id: 'opp_a2', name: 'a2', account: 'acc_a2' }, + // Orphan one hop up: its required master does not exist. + { id: 'opp_a_ghost_account', name: 'ghost account', account: 'acc_ghost' }, + ], inOrg(ORG_A)); + await engine.insert(OPP, [{ id: 'opp_b1', name: 'b1', account: 'acc_b1' }], inOrg(ORG_B)); + await engine.insert(LINE, [ + { id: 'line_a1', name: 'a1', opp: 'opp_a1' }, + { id: 'line_a2', name: 'a2', opp: 'opp_a2' }, + // Orphan: a system write naming a master that does not exist (stored, measured). + { id: 'line_a_ghost', name: 'ghost', opp: 'opp_ghost' }, + // Orphan through its master: the opportunity exists, its account does not. + { id: 'line_a_ghost_account', name: 'ghost account', opp: 'opp_a_ghost_account' }, + ], inOrg(ORG_A)); + // Organization B: one line on a real chain, one orphan. + await engine.insert(LINE, [ + { id: 'line_b1', name: 'b1', opp: 'opp_b1' }, + { id: 'line_b_ghost', name: 'ghost', opp: 'opp_ghost_b' }, + ], inOrg(ORG_B)); + // Orphan: the required master left empty — a row stored before the master + // was declared required. The engine refuses the write, so the driver writes it. + await (engine as any).getDriver(LINE).create(LINE, { id: 'line_a_null', name: 'null', opp: null, organization_id: ORG_A }); + await engine.insert(NOTE, [ + { id: 'note_a1', name: 'a1', opp: 'opp_a1' }, + // An OPTIONAL master naming one that does not exist: the leaf keeps it hidden. + { id: 'note_a_ghost', name: 'ghost', opp: 'opp_ghost' }, + ], inOrg(ORG_A)); + + // An unrestricted master for a plain member: the public account. + await engine.insert(PUB_ACCOUNT, [{ id: 'pub_a1', name: 'p1' }], inOrg(ORG_A)); + await engine.insert(PUB_LINE, [ + { id: 'pub_line_1', name: 'p1', account: 'pub_a1' }, + { id: 'pub_line_ghost', name: 'ghost', account: 'pub_ghost' }, + ], inOrg(ORG_A)); + + const origFind = (driver as any).find.bind(driver); + (driver as any).find = async (object: string, query: any, opts: any) => { + if (object === LINE || object === NOTE || object === PUB_LINE) received.push({ object, where: query?.where }); + return origFind(object, query, opts); + }; + const origCount = (driver as any).count.bind(driver); + (driver as any).count = async (object: string, query: any, opts: any) => { + if (object === LINE || object === NOTE || object === PUB_LINE) received.push({ object, where: query?.where }); + return origCount(object, query, opts); + }; + (driver as any).knex.on('query', (q: { sql?: unknown }) => { + if (capturing && typeof q?.sql === 'string') statements.push(q.sql); + }); + + const read = async (object: string, context: object, where?: unknown) => { + received.length = 0; + statements.length = 0; + capturing = true; + try { + const rows = await engine.find(object, { ...(where === undefined ? {} : { where }), context: { ...context } } as never); + return { ids: ids(rows), where: received[0]?.where, sql: statements.filter((q) => /^select/i.test(q.trim())) }; + } finally { + capturing = false; + } + }; + const count = async (object: string, context: object) => { + statements.length = 0; + capturing = true; + try { + return { n: await engine.count(object, { context: { ...context } } as never), sql: statements.filter((q) => /^select/i.test(q.trim())) }; + } finally { + capturing = false; + } + }; + const stored = async (object: string) => ids(await engine.find(object, { context: { isSystem: true } } as never)); + return { engine, security: securityService as { getReadFilter: (o: string, c: unknown) => Promise }, read, count, stored }; +} + +/** A statement that carries a parent-chain subquery. */ +const SUBQUERY = /\bin \(select `id` from/i; + +/** The rows whose whole master chain resolves: every reader's answer before the ruling. */ +const CHAINED_LINES = ['line_a1', 'line_a2', 'line_b1']; +/** The orphans: a missing master, a master whose own master is missing, an empty required master. */ +const ORPHAN_LINES = ['line_a_ghost', 'line_a_ghost_account', 'line_a_null', 'line_b_ghost']; + +describe('[#33696 ruling 6893666857] the parent chain of a REQUIRED master over unrestricted hops — the real engine', () => { + let rig: Awaited>; + beforeAll(async () => { rig = await boot('single'); }); + afterAll(async () => { try { await rig?.engine.destroy(); } catch { /* noop */ } }); + + it('(a) View All on the detail over unrestricted hops runs no parent-chain subquery and sees every stored row, orphans included', async () => { + const r = await rig.read(LINE, ADMIN); + expect(leavesIn(r.where)).toEqual([]); + expect(r.sql.filter((q) => /`r4_line`/.test(q))).toHaveLength(1); + expect(r.sql.some((q) => SUBQUERY.test(q))).toBe(false); + expect(r.ids).toEqual(await rig.stored(LINE)); + expect(r.ids).toEqual([...CHAINED_LINES, ...ORPHAN_LINES].sort()); + + const c = await rig.count(LINE, ADMIN); + expect(c.n).toBe(CHAINED_LINES.length + ORPHAN_LINES.length); + expect(c.sql.some((q) => SUBQUERY.test(q))).toBe(false); + const ghost = await rig.engine.findOne(LINE, { where: { id: 'line_a_ghost' }, context: { ...ADMIN } } as never); + expect(ids(ghost)).toEqual(['line_a_ghost']); + }); + + it('(1) parity: on the rows whose master chain resolves, the read without the chain answers what the chain answered', async () => { + const admin = await rig.read(LINE, ADMIN); + // Every chained row is still served, and nothing beyond the chained rows but the orphans. + expect(admin.ids.filter((id) => !ORPHAN_LINES.includes(id))).toEqual(CHAINED_LINES); + // The intermediate hop: the unrestricted reader's direct read of the master drops its own leaf too. + const opps = await rig.read(OPP, ADMIN); + expect(opps.sql.some((q) => SUBQUERY.test(q))).toBe(false); + expect(opps.ids).toEqual(await rig.stored(OPP)); + }); + + it('the scope the security service hands a bypassing door (analytics) composes the same way: no subquery, the same rows', async () => { + const scope = await rig.security.getReadFilter(LINE, { ...ADMIN }); + expect(leavesIn(scope).length).toBeGreaterThan(0); + const r = await rig.read(LINE, ADMIN, scope); + expect(r.sql.some((q) => SUBQUERY.test(q))).toBe(false); + expect(r.ids).toEqual([...CHAINED_LINES, ...ORPHAN_LINES].sort()); + }); + + it('(b) a reader with a restricted master hop keeps the whole chain and never sees an orphan', async () => { + // View All on every detail; the private account stays owner-scoped (the detail admin owns acc_a2). + const r = await rig.read(LINE, DETAIL_ADMIN); + expect(r.sql.some((q) => SUBQUERY.test(q))).toBe(true); + expect(r.ids).toEqual(['line_a2']); + for (const orphan of ORPHAN_LINES) expect(r.ids).not.toContain(orphan); + }); + + it('(c) a reader with View All on the detail only keeps the whole chain and never sees an orphan', async () => { + const r = await rig.read(LINE, LINE_ADMIN); + expect(r.sql.some((q) => SUBQUERY.test(q))).toBe(true); + expect(r.ids).toEqual([]); + for (const orphan of ORPHAN_LINES) expect(r.ids).not.toContain(orphan); + }); + + it('(d) a plain member keeps the chain, over a restricted master and over an unrestricted one alike', async () => { + const restricted = await rig.read(LINE, MEMBER); + expect(restricted.sql.some((q) => SUBQUERY.test(q))).toBe(true); + expect(restricted.ids).toEqual(['line_a1']); + // The public account answers an unrestricted scope for the member: the chain stays, and so does its answer. + const unrestricted = await rig.read(PUB_LINE, MEMBER); + expect(unrestricted.sql.some((q) => SUBQUERY.test(q))).toBe(true); + expect(unrestricted.ids).toEqual(['pub_line_1']); + // The control: View All on the detail over the same unrestricted master drops it. + const admin = await rig.read(PUB_LINE, ADMIN); + expect(admin.sql.some((q) => SUBQUERY.test(q))).toBe(false); + expect(admin.ids).toEqual(['pub_line_1', 'pub_line_ghost']); + }); + + it('(2) an OPTIONAL master keeps its leaf for an unrestricted reader: a note naming a missing master stays hidden', async () => { + const r = await rig.read(NOTE, ADMIN); + expect(r.sql.some((q) => SUBQUERY.test(q))).toBe(true); + expect(r.ids).toEqual(['note_a1']); + expect(await rig.stored(NOTE)).toContain('note_a_ghost'); + }); +}); + +describe('[#33696 ruling 6893666857] the tenant wall still bounds the detail rows — walled posture', () => { + let rig: Awaited>; + beforeAll(async () => { rig = await boot('isolated'); }); + afterAll(async () => { try { await rig?.engine.destroy(); } catch { /* noop */ } }); + + it('(e) a View All reader of one organization never sees a row, orphan or not, of another', async () => { + const a = await rig.read(LINE, ADMIN); + const b = await rig.read(LINE, ADMIN_B); + for (const id of ['line_b1', 'line_b_ghost']) expect(a.ids).not.toContain(id); + for (const id of ['line_a1', 'line_a2', 'line_a_ghost', 'line_a_ghost_account', 'line_a_null']) expect(b.ids).not.toContain(id); + expect(a.ids).toEqual(expect.arrayContaining(['line_a1', 'line_a2'])); + expect(b.ids).toEqual(expect.arrayContaining(['line_b1'])); + }); +}); + +/** A write's answer: landed, or the refusal's code and status (the ADR-0112 envelope). */ +const outcomeOf = (p: Promise) => + p.then( + () => ({ kind: 'landed' as const }), + (e: { code?: unknown; status?: unknown; statusCode?: unknown } | null) => ({ + kind: 'refused' as const, + code: e?.code == null ? undefined : String(e.code), + status: Number(e?.statusCode ?? e?.status), + }), + ); + +describe('[#33696 · review 6895328067 route (a)] the write doors keep the chain: a View All reader over unrestricted hops writes as before', () => { + // Ruling 6893666857 is a READ ruling. The reads the security plugin asks on a + // write's behalf under the caller's context — the predicate-write narrowing, + // the 2.8 gate's predicate leg and the step-2.7 by-id read — keep the chain, + // so an orphan stays outside every write exactly as before the ruling. + let rig: Awaited>; + // Two rows the admin created: a predicate write here composes the + // own-records write predicate (`created_by` = the caller), so these are the + // rows the admin's predicate writes land on. The rig stamps no `created_by`, + // so the driver stores it. + const MINE = ['line_mine_1', 'line_mine_2']; + beforeAll(async () => { + rig = await boot('single'); + const driver = (rig.engine as any).getDriver(LINE); + await driver.create(LINE, { id: 'line_mine_1', name: 'mine1', opp: 'opp_a1', organization_id: ORG_A, created_by: ADMIN_USER }); + await driver.create(LINE, { id: 'line_mine_2', name: 'mine2', opp: 'opp_a2', organization_id: ORG_A, created_by: ADMIN_USER }); + }); + afterAll(async () => { try { await rig?.engine.destroy(); } catch { /* noop */ } }); + + it('a hook\'s read inside a write, under the caller\'s context, keeps the chain and sees no orphan', async () => { + let seen: string[] | undefined; + rig.engine.registerHook( + 'afterUpdate', + async (hookCtx: any) => { + seen ??= ids(await hookCtx.api.object(LINE).find({})); + }, + { object: PUB_LINE, packageId: 'com.objectstack.qa.cbp-unrestricted-chain-write' }, + ); + const outcome = await outcomeOf(rig.engine.update(PUB_LINE, { name: 'edited' }, { where: { id: 'pub_line_1' }, context: { ...ADMIN } } as never)); + expect(outcome).toEqual({ kind: 'landed' }); + expect(seen).toEqual([...CHAINED_LINES, ...MINE].sort()); + // The control: the same reader's plain read, outside any write, drops the chain. + expect((await rig.read(LINE, ADMIN)).ids).toEqual([...CHAINED_LINES, ...MINE, ...ORPHAN_LINES].sort()); + }); + + it('a predicate delete over a set holding an empty-required-master orphan deletes the other rows and leaves the orphan', async () => { + const outcome = await outcomeOf(rig.engine.delete(LINE, { + where: { name: { $in: ['mine1', 'null'] } }, multi: true, context: { ...ADMIN }, + } as never)); + expect(outcome).toEqual({ kind: 'landed' }); + const left = await rig.stored(LINE); + expect(left).not.toContain('line_mine_1'); + expect(left).toContain('line_a_null'); + }); + + it('a predicate update over a set holding an empty-master and a dangling-master orphan edits the other rows and leaves both orphans', async () => { + const outcome = await outcomeOf(rig.engine.update(LINE, { name: 'edited' }, { + where: { name: { $in: ['mine2', 'null', 'ghost'] } }, multi: true, context: { ...ADMIN }, + } as never)); + expect(outcome).toEqual({ kind: 'landed' }); + const rows = (await rig.engine.find(LINE, { context: { isSystem: true } } as never)) as Array<{ id: string; name: string }>; + const nameOf = (id: string) => rows.find((r) => r.id === id)?.name; + expect(nameOf('line_mine_2')).toBe('edited'); + expect(nameOf('line_a_null')).toBe('null'); + expect(nameOf('line_a_ghost')).toBe('ghost'); + }); + + it('a by-id update or delete of an orphan is still not found', async () => { + expect(await outcomeOf(rig.engine.update(LINE, { name: 'edited' }, { where: { id: 'line_a_ghost' }, context: { ...ADMIN } } as never))) + .toMatchObject({ kind: 'refused', code: 'RECORD_NOT_FOUND', status: 404 }); + expect(await outcomeOf(rig.engine.delete(LINE, { where: { id: 'line_a_null' }, context: { ...ADMIN } } as never))) + .toMatchObject({ kind: 'refused', code: 'RECORD_NOT_FOUND', status: 404 }); + expect(await rig.stored(LINE)).toEqual(expect.arrayContaining(['line_a_ghost', 'line_a_null'])); + }); +}); diff --git a/packages/plugins/plugin-security/src/security-plugin-cbp-read-filter.ts b/packages/plugins/plugin-security/src/security-plugin-cbp-read-filter.ts index 2ba0466291d..09d8049bdc6 100644 --- a/packages/plugins/plugin-security/src/security-plugin-cbp-read-filter.ts +++ b/packages/plugins/plugin-security/src/security-plugin-cbp-read-filter.ts @@ -53,6 +53,17 @@ * composes: `computeControlledByParentFilter` takes the caller's resolved * permission sets (for View All on the detail) and the host hands it * `permissionEvaluator`. A required master's leaf is unchanged. + * + * [#33696 · ruling record 6893666857] The leaf of a REQUIRED master is still + * written for every caller; the ENGINE drops it when it composes the read for a + * caller who holds View All on the detail and finds the master's scope + * unrestricted at every hop (`composeReadableIdsChain` step 5, + * `@objectstack/objectql`), so that reader runs no parent-chain subquery and + * also sees the detail rows whose master is missing or empty — as View All on + * the detail reads an optional master's null-master rows below. The per-hop + * half is the engine's because only it holds the per-hop answer; ⛔ View All + * on the detail alone never drops it (it does not open the master arm). Every + * other reader keeps the chain. Pinned in `security-plugin-cbp-read-filter.test.ts`. */ import type { SecurityPlugin } from './security-plugin.js'; diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index ee13615f8f4..e73b5ed77c5 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -5078,6 +5078,18 @@ export class SecurityPlugin implements Plugin { * `DATABASE_ERROR` / 500 past ~32,800 masters (the dialect's bind limit), and * its CPU grew with the master table. * + * [#33696 · ruling record 6893666857] One reader class reads without it: + * a caller holding View All on the detail whose every master hop answers + * unrestricted, over a REQUIRED master. For that caller the engine drops the + * leaf instead of compiling it (`composeReadableIdsChain` step 5), and the + * read also returns detail rows whose master is missing or empty. The drop + * applies to reads only. While a write's middleware chain runs, every read + * made on its behalf keeps the chain, so write paths answer exactly as + * before: the predicate-write narrowing + * ({@link readableRowsScopeForPredicateWrite}), the 2.8 gate's predicate + * leg, the step-2.7 by-id read, and a hook's read. This method still writes + * the leaf for every caller. + * * [#5386] The master's scope is the SAME scope a direct find of the master * runs under, point for point: both halves above are the ones the engine * middleware chain ANDs into a direct read of the master, asked of the same