Skip to content

Commit b1f3252

Browse files
committed
refactor(objectql): move the write-path reference check and the caller's master-detail header read out of engine.ts into engine-referential-integrity.ts
Move-only. The bodies of ObjectQL#assertReferencesResolve and ObjectQL#masterDetailHeadersCallerReads move unedited into packages/objectql/src/engine-referential-integrity.ts, with the module helper isEmptyReferenceValue that only the first calls. Both methods keep name, modifiers, signature, docblock and position; each body is now a host literal of exactly the members it reads (ReferentialIntegrityHost) and a .call. engine.ts drops the buildFieldError import, whose last reader moved. The two moved isSystem read sites re-key their rows in the system-context census page, and the federated injected-column readers table re-keys the assertReferencesResolve referenceTargetOf() row. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KiAsjPtReu1tmXvCEd8f7R
1 parent 366e4aa commit b1f3252

4 files changed

Lines changed: 221 additions & 119 deletions

File tree

‎content/docs/permissions/system-context.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ that silently does not happen.
128128
| 21 | **`readonly` strip bypassed — INSERT** | objectql | Same, on create — one gate over BOTH create-side passes since the 2026-09-03 ruling moved the static-`readonly` strip in beside the runtime-owned one and deleted the DataProtocol ingress copy. `isSystem` is the **only** exemption on this path: `preserveAudit` is deliberately not read on create, so a non-system historical import is still stripped. A second read in the same symbol gates the pass that withholds those caller values from `beforeInsert` before the strip, the same exemption, so a system caller's hook still sees what it sent | `packages/objectql/src/engine.ts#insert` |
129129
| 21b | **`readonly` strip bypassed — the write PREVIEW (`ObjectQL.validate`)** | objectql | Same as 19–21, in the preview: it runs the write's caller-write strips under the write's own gate, so a system preview reports no `readonly` drop and judges the value a system write would store. The `computed` strip of a `formula` value is NOT gated here or on either write verb — no driver has a column for it, so it runs for every caller | `packages/objectql/src/engine.ts#validate` |
130130
| 22 | Strict-drop refusal never fires | objectql | Lose: a caller that opted into loud refusal gets **silence** — strict refuses exactly what the strip would have taken, and the strip took nothing. Two exceptions, both judged in every context: a `formula` value, which the `computed` strip takes from every caller, and a value for a stored field that declares `expression` when it differs from the value the engine computes in its place (`stored_expression`), so strict still refuses both | `packages/objectql/src/engine.ts#insert`, `packages/objectql/src/readonly-strict-errors.ts#READONLY_CLASS_REASONS` |
131-
| 23 | **Referential-integrity check skipped** | objectql | Get: writes proceed against unreachable/unresolvable targets. Lose: an `isSystem` caller can write a **dangling reference** | `packages/objectql/src/engine.ts#assertReferencesResolve` |
131+
| 23 | **Referential-integrity check skipped** | objectql | Get: writes proceed against unreachable/unresolvable targets. Lose: an `isSystem` caller can write a **dangling reference** | `packages/objectql/src/engine-referential-integrity.ts#assertReferencesResolve` |
132132
| 23b | **Position-catalog check skipped** — a `sys_user_position` write whose `position` names no position in the security catalog is not refused | plugin-security | Get: a system writer can store an assignment naming no position — the seed loader writes `stack.data` from `AppPlugin.start()` under a system context, as invitation acceptance and the platform's own bootstraps do. Lose: such a row grants nothing and nothing says so. A non-system insert, or a non-system update that changes `position`, is refused `400 VALIDATION_FAILED` / `reference_not_found` instead when the security catalog holds no position of that name: the environment registry (ADR-0131 D3), one per deployment, which takes no organization, so a name only a `sys_position` row carries — any organization's — is refused like one nobody carries. It is the same stand-down as the engine's referential-integrity check for a lookup column | `packages/plugins/plugin-security/src/position-catalog-refusal.ts#assertPositionNamesCatalogRow` |
133133
| 23c | **Grant-name catalog check skipped** — a `sys_user_permission_set` write whose `permission_set` names no permission set in the security catalog is not refused | plugin-security | Get: a system writer can store a grant naming a set not yet registered — seed replay and boot provisioning may write the grant before the definition it names is registered. Lose: such a row grants nothing and nothing says so. A non-system insert, or a non-system update that changes `permission_set`, is refused `400 VALIDATION_FAILED` / `reference_not_found` instead when the security catalog holds no set by that name; a grant that names no set at all is refused `required` for every caller. The grant names its set by name alone, and nothing derives the name from `permission_set_id` (ADR-0131 D4, D10) | `packages/plugins/plugin-security/src/grant-permission-set-name.ts#onInsert`, `#onUpdate` |
134134
| 23d | **Grant-holder membership check skipped** — a `sys_user_position` or `sys_user_permission_set` write naming a user with no `sys_member` row in the row's organization is not refused | plugin-security | Get: a system writer can store such a grant — invitation acceptance writes the membership and its placement together, and seed replay, the organization-admin reconcile and the platform bootstraps write grants as the system. Lose: such a row takes effect once its user is admitted to the organization. A non-system insert, or a non-system update that moves `user_id` or `organization_id`, is refused `400 VALIDATION_FAILED` / `reference_not_found` at `user_id` instead, for every caller, a platform administrator included; the membership is read as `{ isSystem: true, tenantId }` with `tenantId` the row's own organization, never another one. A row stored with no organization is not judged. Under `single`, 18.0 stamps a new grant with the Default Organization, so such a row is one an earlier release wrote | `packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts#onInsert`, `#onUpdate` |
@@ -140,7 +140,7 @@ that silently does not happen.
140140
| 28 | Dependent-count disclosure on a blocked delete | objectql | Get: the count of blocking children. Nothing was elevated past the caller, so nothing is withheld | `packages/objectql/src/engine.ts#dependentCountIsDisclosable` |
141141
| 29 | Reference-cleanup log attributes the write to `'system'` | objectql | Get: an honest actor label instead of `anonymous` when the context carries neither `userId` nor `actor` | `packages/objectql/src/engine.ts#recordReferenceCheckElevation` |
142142
| 29b | A traversing validation rule's related read skips the **caller's bounds** | objectql | Get: no row bound from the caller's own read on a related object no organization wall scopes, no read door on a header the rule reads through a `master_detail` field, and a related read even with no organization under a walled posture (a `tenantId` on the context still scopes it). Every caller that is not system is held to all three: a header its read door does not return is unavailable to the rule exactly as a header that exists nowhere is, whatever it holds, and a header it can read is judged on its stored values. A plain `lookup` to an object an organization wall scopes asks no read door, system caller or not | `packages/objectql/src/engine.ts#resolveOneHopRelated` |
143-
| 29c | A detail write's master-detail header read asks **no read door** | objectql | Get: the write binds the header a parent-scoped `requiredWhen` / `readonlyWhen` reads as `parent` from the header's stored row whoever can read it, as before. Every caller that is not system meets its own read door first: a header that read does not return answers as a header that exists nowhere — an unbound `parent`, and `reference_not_found` on the reference check (which a system caller's write skips altogether) | `packages/objectql/src/engine.ts#masterDetailHeadersCallerReads` |
143+
| 29c | A detail write's master-detail header read asks **no read door** | objectql | Get: the write binds the header a parent-scoped `requiredWhen` / `readonlyWhen` reads as `parent` from the header's stored row whoever can read it, as before. Every caller that is not system meets its own read door first: a header that read does not return answers as a header that exists nowhere — an unbound `parent`, and `reference_not_found` on the reference check (which a system caller's write skips altogether) | `packages/objectql/src/engine-referential-integrity.ts#masterDetailHeadersCallerReads` |
144144
| 30 | **Bulk data event `organizationId` OMITTED** — the batch is published "not asserted" | plugin-security | Get: nothing — the `data.records.*` event still publishes. Lose: the per-organization attribution: this exit is taken before the security middleware composes any tenant wall, so it records no Layer 0 verdict on the operation (`OperationContext.tenantLayer0Verdict`, #15813), and the engine's bulk producer — which reads that recorded verdict and nothing else — omits the key rather than filling it from the caller's `tenantId`; a tenant-scoped consumer then does not deliver the event inside an organization wall (#15225) | `packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts#registerAuthzMiddleware` |
145145
| 30b | **The import doors admit a control opt-out** — `runAutomations: false` and `treatAsHistorical: true` on `POST /data/:object/import` and `/import/jobs` | rest | Get: an import whose rows are written with `skipAutomations` (no metadata-bound hook, no record-change trigger: an app's approvals and record freezes among them) or with `skipStateMachine` and `preserveAudit`. Every other caller, every signed-in user and administrator included, is refused `403 PERMISSION_DENIED` before the body is parsed, so nothing is written and no job is created. Inbound HTTP never carries the flag, so this is an in-process caller's door. Note: the flag still suppresses none of those controls by itself (see below); it only admits the opt-outs that do | `packages/rest/src/import-prepare.ts#importControlOptOutRefusal` |
146146
| 30c | **The import undo keeps the control skips** — `POST /data/import/jobs/:jobId/undo` | rest | Get: an undo whose deletes and restores are written with `skipAutomations` and `skipStateMachine`, so no metadata-bound hook, record-change trigger or `state_machine` rule refuses a reversal. Every other caller, every signed-in user and administrator included, undoes under those controls: a reversal one of them refuses is reported per row in the undo answer's `failures` and kept in the job's undo log, and the job is stamped reverted only once every row is. A historical job's `preserveAudit` belongs to the job, not the caller, and rides every undo. Inbound HTTP never carries the flag, so this is an in-process caller's door | `packages/rest/src/data-action-routes.ts#importUndoWriteContext` |
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#25522 cut 10] Two referential-integrity bodies of `ObjectQL`, moved out
5+
* of `engine.ts` whole: `assertReferencesResolve` (the write path's #4441
6+
* reference check: a caller-supplied id in a reference field must name a row
7+
* of its target) and `masterDetailHeadersCallerReads` (#22519: which
8+
* master-detail headers the caller's own read door returns), with
9+
* `isEmptyReferenceValue`, the module helper only the first of them calls.
10+
*
11+
* A MOVE, not a redesign. Each exported function below is the body of the
12+
* `ObjectQL` method of the same name as it stood, re-indented one level and
13+
* otherwise unedited: the same system-caller exit, the same `readonly` and
14+
* caller-supplied skips, the same master-detail branch, the same one-`find`
15+
* read door and the same warning when that read fails. Each method's
16+
* docblock stays on the method in `engine.ts`, which is still the contract.
17+
* `isEmptyReferenceValue` moves with its docblock, byte for byte, and is not
18+
* exported.
19+
*
20+
* What stays in the class: `referenceExists`, `resolveMasterDetailParent` and
21+
* `resolveMasterDetailParents`, which read the private static
22+
* `referenceCheckContext` and hold an erased query-options site; the bodies
23+
* that call a module helper `engine.ts` still needs elsewhere
24+
* (`settleMasterDetailLanding`, `resolvePreviewParents`,
25+
* `resolvePredicateRelated`, `resolveOneHopRelated`); and
26+
* `masterDetailHeaderExists`, `materializeParentHeader` and
27+
* `masterDeclaredFields`, whose bodies are no longer than the host literal
28+
* moving them would cost.
29+
*
30+
* ## How the moved bodies reach the class
31+
*
32+
* The shape #23050 set for `rest-server.ts`, applied per method as
33+
* `engine-compatibility-api.ts` applies it. The class keeps both methods with
34+
* name, modifiers, signature, docblock and position, and each body is one
35+
* literal of exactly the {@link ReferentialIntegrityHost} members that method
36+
* reads, plus a `.call`. The one field a body reads (`logger`) goes as a
37+
* GETTER, so the read happens when the body makes it, as it did. The methods
38+
* they call (`find`, `masterDetailHeaderExists`, `referenceExists`) go as
39+
* late-bound closures over the instance, so a double or spy set on the engine
40+
* is still the one a call reaches.
41+
*
42+
* This module imports the engine only as a TYPE, so there is no module cycle
43+
* at run time, and nothing re-exports it, so the published surface does not
44+
* move.
45+
*/
46+
47+
import { referenceTargetOf, type EngineQueryOptions } from '@objectstack/spec/data';
48+
import type { ExecutionContext } from '@objectstack/spec/kernel';
49+
import { ValidationError, buildFieldError } from './validation/record-validator.js';
50+
import type { ObjectQL } from './engine.js';
51+
52+
/**
53+
* The `ObjectQL` members the functions below read — every one of them, and no
54+
* other; each function's `this` is the `Pick` of the members IT reads. Each is
55+
* typed AS the class member (an indexed access on the class), so a change to a
56+
* member's type on the class is a change here too, and naming a member the
57+
* class does not have is a compile error. See the module header for which
58+
* member is a getter.
59+
*/
60+
export interface ReferentialIntegrityHost {
61+
readonly logger: ObjectQL['logger'];
62+
find: ObjectQL['find'];
63+
masterDetailHeaderExists: ObjectQL['masterDetailHeaderExists'];
64+
referenceExists: ObjectQL['referenceExists'];
65+
}
66+
67+
/**
68+
* [#4441] "The caller did not name a record here."
69+
*
70+
* `null` / `undefined` / `''` mean NO LINK — exactly what
71+
* `deleteBehavior: 'set_null'` writes — and an empty array is the multi-value
72+
* spelling of the same thing. None of them is an id to resolve.
73+
*/
74+
function isEmptyReferenceValue(v: unknown): boolean {
75+
if (v === null || v === undefined || v === '') return true;
76+
if (Array.isArray(v)) return v.length === 0 || v.every((e) => e === null || e === undefined || e === '');
77+
return false;
78+
}
79+
80+
/** The body of `ObjectQL#assertReferencesResolve`; the method's docblock there is its contract. */
81+
export async function assertReferencesResolve(
82+
this: Pick<ReferentialIntegrityHost, 'masterDetailHeaderExists' | 'referenceExists'>,
83+
schema: any,
84+
data: Record<string, unknown> | null | undefined,
85+
supplied: Record<string, unknown> | null | undefined,
86+
context: any,
87+
msgCtx?: { locale?: string; translate?: any; objectName?: string },
88+
): Promise<void> {
89+
if (context?.isSystem) return;
90+
const fields = schema?.fields;
91+
if (!fields || !data) return;
92+
93+
const failures: any[] = [];
94+
for (const name of Object.keys(fields)) {
95+
// [#4441, narrowing kept by #4743] A `readonly` field is never the
96+
// caller's to answer for — BY CONSTRUCTION, not by exemption.
97+
//
98+
// This check answers for exactly one thing: "the reference the CALLER
99+
// named". `stripReadonlyFields` removes a non-system caller's value from
100+
// a readonly field before the write — on BOTH write paths since #14147
101+
// moved the create-side strip into this engine and deleted the boundary
102+
// copy it used to live in. So a value still sitting in one at
103+
// this point was minted by the PLATFORM — outside this check's own stated
104+
// scope, whatever it happens to hold. That argument stands on its own and
105+
// depends on no particular field: deleting the `continue` would start
106+
// rejecting the platform's own writes, which is why it is recorded here
107+
// (AGENTS.md PD #13) rather than left to be re-derived.
108+
//
109+
// Historical note, kept because it is how the narrowing was FOUND (the
110+
// dogfood gate, not reasoning) and because the audit next door re-scoped
111+
// itself on its removal: `sys_metadata_history.recorded_by` is a
112+
// `Field.lookup('sys_user', { readonly: true })` that the metadata
113+
// repository once filled with `actor ?? 'system'` — a SENTINEL STRING,
114+
// not a user id, on a write carrying no `isSystem`; checking it rejected
115+
// ordinary metadata authoring (package create / publish / clone). #4556
116+
// replaced that sentinel with NULL, so no platform write puts a non-id in
117+
// a reference column any more. The narrowing survives it unchanged
118+
// because it never rested on it — but #4551's blanket audit skip did, and
119+
// #4743/#5719 duly re-scoped that one (see `inspectDanglingReferences`).
120+
//
121+
// This does NOT weaken #4441: the fields the issue names —
122+
// `sys_position_permission_set.permission_set_id` and
123+
// `showcase_task.project` — are ordinary author-facing lookups with no
124+
// `readonly`, and both stay enforced (pinned in the unit suite).
125+
if (fields[name]?.readonly === true) continue;
126+
// Only a value the CALLER actually supplied is theirs to answer for.
127+
//
128+
// Key presence is not enough: a form serializes an unpicked control as
129+
// an explicit `null`, and `applyFieldDefaults` then fills it from
130+
// `defaultValue` — including the `current_user` token (#2706). The key is
131+
// in the payload, but the ID that lands is the PLATFORM's, so validating
132+
// it would report a server-derived value as the caller's bad reference
133+
// (and reject a perfectly ordinary insert against a driver that has no
134+
// `sys_user` row for the acting principal).
135+
//
136+
// So the value read for the check comes from the post-normalization
137+
// `data` (multi-value strings are already split by then), while WHETHER
138+
// to check is decided by the caller's own raw value being non-empty.
139+
if (!supplied || isEmptyReferenceValue((supplied as Record<string, unknown>)[name])) continue;
140+
if (!(name in data)) continue;
141+
const def = fields[name];
142+
const target = referenceTargetOf(def);
143+
if (!target) continue;
144+
const raw = (data as Record<string, unknown>)[name];
145+
const values = Array.isArray(raw) ? raw : [raw];
146+
for (const v of values) {
147+
if (v === null || v === undefined || v === '') continue;
148+
if (typeof v === 'object') continue;
149+
// [#22519] A master-detail header must also be one the caller can read.
150+
const resolved = def?.type === 'master_detail'
151+
? await this.masterDetailHeaderExists(target, v, context)
152+
: await this.referenceExists(target, v, context);
153+
if (resolved === false) {
154+
failures.push(buildFieldError(
155+
{
156+
field: name,
157+
code: 'reference_not_found',
158+
def,
159+
value: String(v),
160+
constraint: { target },
161+
},
162+
msgCtx as any,
163+
));
164+
}
165+
}
166+
}
167+
if (failures.length > 0) throw new ValidationError(failures);
168+
}
169+
170+
/** The body of `ObjectQL#masterDetailHeadersCallerReads`; the method's docblock there is its contract. */
171+
export async function masterDetailHeadersCallerReads(
172+
this: Pick<ReferentialIntegrityHost, 'find' | 'logger'>,
173+
master: string,
174+
ids: ReadonlyArray<unknown>,
175+
context: ExecutionContext | undefined,
176+
): Promise<ReadonlySet<string>> {
177+
const asked = new Map<string, unknown>();
178+
for (const id of ids) if (id != null) asked.set(String(id), id);
179+
if (context?.isSystem || asked.size === 0) return new Set(asked.keys());
180+
// One id is asked by equality, the predicate shape the elevated probe
181+
// already sends; a batch by `$in`, as read 2 of the batch reads it.
182+
const values = [...asked.values()];
183+
try {
184+
const rows = await this.find(master, {
185+
where: { id: values.length === 1 ? values[0] : { $in: values } },
186+
fields: ['id'],
187+
context,
188+
} as EngineQueryOptions) as Array<Record<string, unknown>>;
189+
const served = new Set<string>();
190+
for (const row of Array.isArray(rows) ? rows : []) {
191+
if (row?.id != null && asked.has(String(row.id))) served.add(String(row.id));
192+
}
193+
return served;
194+
} catch (err) {
195+
this.logger?.warn?.('the caller\'s read of the master-detail header failed — the header binds as a missing header', {
196+
object: master, error: err,
197+
});
198+
return new Set();
199+
}
200+
}

0 commit comments

Comments
 (0)