Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .changeset/33696-drop-unrestricted-cbp-chain.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 4 additions & 1 deletion packages/objectql/src/engine-middleware-and-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
}

Expand Down
129 changes: 129 additions & 0 deletions packages/objectql/src/engine-readable-ids-nested-composition.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>, 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: [] } });
});
});
Loading
Loading