diff --git a/.changeset/35786-fixed-read-leaf-seam.md b/.changeset/35786-fixed-read-leaf-seam.md new file mode 100644 index 00000000000..32172260edf --- /dev/null +++ b/.changeset/35786-fixed-read-leaf-seam.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': minor +'@objectstack/core': patch +'@objectstack/objectql': patch +--- + +feat: the engine's seam for the fixed-read leaf, and the driver declaration for it (ADR-0155, step 2 of 6) + +Clause-②: yes +Metadata-protocol: added + +No visible change on its own: nothing on main writes a fixed-read leaf yet (the sharing plugin starts writing `SharedRecordIds` at ADR-0155's last step), and no driver declares one (the SQL drivers and the memory driver declare it on the steps that compile it). + +- **The driver declaration** (`@objectstack/spec`). `DriverCapabilities.fixedReadLeaves` lists the fixed-read leaves a driver's filter compiler evaluates exactly, by name, e.g. `['SharedRecordIds']`; absence means none. The names are `FIXED_READ_LEAF_NAMES`, and `fixedReadLeafNameOf(leaf)` maps a leaf to its name. It stays separate from `readableIdsLeaf`: a `ReadableIds` leaf is not a fixed-read leaf, and a driver that evaluates both declares both. Both descriptions now say so. +- **The seam** (`@objectstack/objectql`). The engine's comparand door admits a branded `SharedRecordIds` leaf as a `$in` comparand, and the engine hands it to the driver by reference only when it sits on `id` of the object it names (directly, or inside a composed `ReadableIds` scope over that object), on a read verb in its read form or in a predicate update's `where` in its write form, for the context's user or its delegator (a system context is exempt), outside both classes ADR-0155 D4 recognises (the object on another datasource than `sys_record_share`; a middleware or a `beforeFind` / `afterFind` hook registered for `sys_record_share` by name), and to a driver whose `fixedReadLeaves` names it. Anything else is refused before any driver is asked, `INTERNAL_ERROR` / 500, logged at `error` once per evaluator. An unbranded copy is still refused at the door as a non-list comparand, `INVALID_FILTER` / 400. +- **The refusal** (`@objectstack/core`). `fixedReadLeafRefusal`, `refuseFixedReadLeafOnce` and `describeFixedReadLeaf` are the one envelope every evaluator answers a fixed-read leaf it will not run with; `logRefusalOnce` is the once-per-instance log it shares with the `ReadableIds` refusal. +- **Filter tokens** (`@objectstack/core`). `resolveFilterTokens` returns a fixed-read leaf by reference, as it does a `ReadableIds` leaf, so a read scope that carries a placeholder beside the leaf keeps the leaf's brand. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index ca1d7e590f8..9d256652777 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -125,6 +125,7 @@ bugs — it is the protection or the side effect that silently does not happen. | 18c | **Credential-column filter / sort refusal not applied** — a `where`, `orderBy`, per-aggregation `filter` or `expand` entry naming a `password` / `secret` column is evaluated | objectql | Get: the server's own match on a stored credential value, a lookup that never returns it. Every other caller, administrators included, is refused `400 INVALID_FIELD` for anything but a has-a-value check (ADR-0100). Lose: nothing a wire caller reaches — `isSystem` is never set on an inbound request | `rejectCredentialEvaluation` | | 18d | **Stored-metadata type read gate not applied** — a read of `sys_metadata` / `sys_metadata_history` is not narrowed by the capability its row's type requires | objectql | Get: every row of the family on `find` / `findOne` / `count` / `aggregate` — the metadata loader, the `/meta` doors' own store reads, boot (a read with no execution context is not narrowed either). Lose: the narrowing that serves a stored row of a capability-gated type (`datasource`, `external_catalog`) only to holders of the capability the `/meta` type gate names for it | `storedMetadataTypeReadFilter` | | 18e | **`internal: true` evaluate refusal not applied on the engine's read path** — a filter, sort, group key, aggregation operand, per-aggregation `filter`, nested-relation condition or `expand` entry naming a field declared `internal: true` is evaluated | objectql | Get: the server's own match on a flagged column (the API-key, share-link, SCIM-credential and approval-token lookups, the better-auth adapter), which still never returns the value. Every other caller of `find` / `findOne` / `count` / `aggregate`, administrators included, is refused `400 INVALID_FIELD`; the data door asks the same judgement for every caller, a system context included. Lose: nothing a wire caller reaches — `isSystem` is never set on an inbound request | `rejectInternalFieldEvaluation` | +| 18f | **Fixed-read leaf recipient check not applied** — a `SharedRecordIds` leaf (ADR-0155) that names another principal is handed on to the driver | objectql | Get: server code may hand the engine a share-table read for any recipient. Nothing on main writes the leaf yet; the sharing plugin starts at ADR-0155's last step. Every other caller's leaf must name its own user or its delegator, or the operation is refused `500 INTERNAL_ERROR` before any driver is asked (ADR-0155 D4). The position, verb, class and driver-declaration checks apply to every caller, a system context included. Lose: nothing a wire caller reaches — no request can spell the leaf, and `isSystem` is never set on an inbound request | `passFixedReadLeaves` | ### 2. Write pipeline and data integrity @@ -561,6 +562,7 @@ and CI refuses one that differs from what the tree produces. | `packages/objectql/src/engine-update.ts#update` | 4 | 19, 20 | | `packages/objectql/src/engine-validate.ts#validate` | 1 | 21b | | `packages/objectql/src/engine.ts#isSystem` | 1 | 64 | +| `packages/objectql/src/fixed-read-leaf-seam.ts#passFixedReadLeaves` | 1 | 18f | | `packages/objectql/src/internal-field-evaluation-guard.ts#rejectInternalFieldEvaluation` | 1 | 18e | | `packages/objectql/src/recycle-bin/list.ts#assertCallerManagesRecycleBin` | 1 | 29f | | `packages/objectql/src/recycle-bin/purge.ts#recycleBinWallDenies` | 1 | 29d | diff --git a/content/docs/references/data/driver-nosql.mdx b/content/docs/references/data/driver-nosql.mdx index dc0459eac77..fbd54ce7ffe 100644 --- a/content/docs/references/data/driver-nosql.mdx +++ b/content/docs/references/data/driver-nosql.mdx @@ -168,7 +168,8 @@ const result = AggregationPipelineSchema.parse(data); | **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | | **lockRows** | `boolean` | optional | `find()` honours `DriverOptions.lockRows` inside a transaction: no other writer changes a returned row behind the transaction (it waits, or one side fails) (absence = false: the engine sends no lock request) | | **zonedDateBucketing** | `boolean` | optional | `aggregate()` buckets a date groupBy on the calendar of the resolved IANA zone the engine sends (DriverAggregateQuery.timezone), DST-correct, equal to the in-memory buckets (absence = false: the engine buckets a non-UTC zone in memory) | -| **readableIdsLeaf** | `boolean` | optional | The filter compiler compiles (or, in process, evaluates) a composed `ReadableIds` semi-join leaf (absence = false: the engine refuses a nested-relation condition on a read verb up front, INVALID_FILTER / 400) | +| **readableIdsLeaf** | `boolean` | optional | The filter compiler compiles (or, in process, evaluates) a composed `ReadableIds` semi-join leaf (absence = false: the engine refuses a nested-relation condition on a read verb up front, INVALID_FILTER / 400). A `ReadableIds` leaf is not a fixed-read leaf, so `fixedReadLeaves` neither implies nor is implied by this bit | +| **fixedReadLeaves** | `Enum<'SharedRecordIds'>[]` | optional | The fixed-read leaves (ADR-0155 D4) the filter compiler evaluates exactly, by name, e.g. ["SharedRecordIds"] (absence = none: the engine refuses an operation carrying such a leaf before calling the driver, INTERNAL_ERROR / 500). Separate from `readableIdsLeaf`: a `ReadableIds` leaf is not a fixed-read leaf | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | diff --git a/content/docs/references/data/driver-sql.mdx b/content/docs/references/data/driver-sql.mdx index d8b8bcfb1cd..d2f2f9b5cb7 100644 --- a/content/docs/references/data/driver-sql.mdx +++ b/content/docs/references/data/driver-sql.mdx @@ -81,7 +81,8 @@ const result = DataTypeMappingSchema.parse(data); | **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | | **lockRows** | `boolean` | optional | `find()` honours `DriverOptions.lockRows` inside a transaction: no other writer changes a returned row behind the transaction (it waits, or one side fails) (absence = false: the engine sends no lock request) | | **zonedDateBucketing** | `boolean` | optional | `aggregate()` buckets a date groupBy on the calendar of the resolved IANA zone the engine sends (DriverAggregateQuery.timezone), DST-correct, equal to the in-memory buckets (absence = false: the engine buckets a non-UTC zone in memory) | -| **readableIdsLeaf** | `boolean` | optional | The filter compiler compiles (or, in process, evaluates) a composed `ReadableIds` semi-join leaf (absence = false: the engine refuses a nested-relation condition on a read verb up front, INVALID_FILTER / 400) | +| **readableIdsLeaf** | `boolean` | optional | The filter compiler compiles (or, in process, evaluates) a composed `ReadableIds` semi-join leaf (absence = false: the engine refuses a nested-relation condition on a read verb up front, INVALID_FILTER / 400). A `ReadableIds` leaf is not a fixed-read leaf, so `fixedReadLeaves` neither implies nor is implied by this bit | +| **fixedReadLeaves** | `Enum<'SharedRecordIds'>[]` | optional | The fixed-read leaves (ADR-0155 D4) the filter compiler evaluates exactly, by name, e.g. ["SharedRecordIds"] (absence = none: the engine refuses an operation carrying such a leaf before calling the driver, INTERNAL_ERROR / 500). Separate from `readableIdsLeaf`: a `ReadableIds` leaf is not a fixed-read leaf | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | diff --git a/content/docs/references/data/driver.mdx b/content/docs/references/data/driver.mdx index a5d64e49983..2a1f5138b7c 100644 --- a/content/docs/references/data/driver.mdx +++ b/content/docs/references/data/driver.mdx @@ -35,7 +35,8 @@ const result = DriverCapabilitiesSchema.parse(data); | **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | | **lockRows** | `boolean` | optional | `find()` honours `DriverOptions.lockRows` inside a transaction: no other writer changes a returned row behind the transaction (it waits, or one side fails) (absence = false: the engine sends no lock request) | | **zonedDateBucketing** | `boolean` | optional | `aggregate()` buckets a date groupBy on the calendar of the resolved IANA zone the engine sends (DriverAggregateQuery.timezone), DST-correct, equal to the in-memory buckets (absence = false: the engine buckets a non-UTC zone in memory) | -| **readableIdsLeaf** | `boolean` | optional | The filter compiler compiles (or, in process, evaluates) a composed `ReadableIds` semi-join leaf (absence = false: the engine refuses a nested-relation condition on a read verb up front, INVALID_FILTER / 400) | +| **readableIdsLeaf** | `boolean` | optional | The filter compiler compiles (or, in process, evaluates) a composed `ReadableIds` semi-join leaf (absence = false: the engine refuses a nested-relation condition on a read verb up front, INVALID_FILTER / 400). A `ReadableIds` leaf is not a fixed-read leaf, so `fixedReadLeaves` neither implies nor is implied by this bit | +| **fixedReadLeaves** | `Enum<'SharedRecordIds'>[]` | optional | The fixed-read leaves (ADR-0155 D4) the filter compiler evaluates exactly, by name, e.g. ["SharedRecordIds"] (absence = none: the engine refuses an operation carrying such a leaf before calling the driver, INTERNAL_ERROR / 500). Separate from `readableIdsLeaf`: a `ReadableIds` leaf is not a fixed-read leaf | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | @@ -94,7 +95,8 @@ const result = DriverCapabilitiesSchema.parse(data); | **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | | **lockRows** | `boolean` | optional | `find()` honours `DriverOptions.lockRows` inside a transaction: no other writer changes a returned row behind the transaction (it waits, or one side fails) (absence = false: the engine sends no lock request) | | **zonedDateBucketing** | `boolean` | optional | `aggregate()` buckets a date groupBy on the calendar of the resolved IANA zone the engine sends (DriverAggregateQuery.timezone), DST-correct, equal to the in-memory buckets (absence = false: the engine buckets a non-UTC zone in memory) | -| **readableIdsLeaf** | `boolean` | optional | The filter compiler compiles (or, in process, evaluates) a composed `ReadableIds` semi-join leaf (absence = false: the engine refuses a nested-relation condition on a read verb up front, INVALID_FILTER / 400) | +| **readableIdsLeaf** | `boolean` | optional | The filter compiler compiles (or, in process, evaluates) a composed `ReadableIds` semi-join leaf (absence = false: the engine refuses a nested-relation condition on a read verb up front, INVALID_FILTER / 400). A `ReadableIds` leaf is not a fixed-read leaf, so `fixedReadLeaves` neither implies nor is implied by this bit | +| **fixedReadLeaves** | `Enum<'SharedRecordIds'>[]` | optional | The fixed-read leaves (ADR-0155 D4) the filter compiler evaluates exactly, by name, e.g. ["SharedRecordIds"] (absence = none: the engine refuses an operation carrying such a leaf before calling the driver, INTERNAL_ERROR / 500). Separate from `readableIdsLeaf`: a `ReadableIds` leaf is not a fixed-read leaf | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 11d9bbb4a05..b827cfc72b5 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -209,6 +209,9 @@ export * from './utils/blank-storage-form.js'; // above gives. export * from './utils/json-column-operator-refusal.js'; export * from './utils/readable-ids-driver-refusal.js'; +// [ADR-0155 D4] …and the fixed-read leaves' refusal, on the same floor for the +// same reason: the engine's seam answers it now, each evaluator on its own card. +export * from './utils/fixed-read-leaf-refusal.js'; // [#12350 / ADR-0126 §4] THE activation-ledger row contract, parameterized by // `metadata_type`. Same reason as the two entries above: its consumers — diff --git a/packages/core/src/utils/filter-tokens.test.ts b/packages/core/src/utils/filter-tokens.test.ts index 615b564d342..a43cea2b8d5 100644 --- a/packages/core/src/utils/filter-tokens.test.ts +++ b/packages/core/src/utils/filter-tokens.test.ts @@ -1,7 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect } from 'vitest'; -import { PERIOD_KEY_TOKENS, ReadableIds, isReadableIds } from '@objectstack/spec/data'; +import { PERIOD_KEY_TOKENS, ReadableIds, SharedRecordIds, isFixedReadLeaf, isReadableIds } from '@objectstack/spec/data'; import { bucketDateKey } from './datetime.js'; import { resolveFilterToken, @@ -456,6 +456,32 @@ describe('resolveFilterTokens — tree walk', () => { expect(out.$or[0].record_id!.$in).toBe(leaf); expect(isReadableIds(out.$or[0].record_id!.$in)).toBe(true); }); + + // [ADR-0155 D1] The same for a fixed-read leaf: a read scope is an `$or` of + // the owner match and the leaf, and an owner match spelled with a + // placeholder rebuilds the tree around the leaf. + it('returns a fixed-read leaf beside a resolved placeholder by reference, brand intact', () => { + const read = SharedRecordIds.read('cpz_doc', 'usr_1'); + const write = SharedRecordIds.write('cpz_doc', 'usr_1', ['edit']); + const where = { $or: [{ owner: '{current_user_id}' }, { id: { $in: read } }], $and: [{ id: { $in: write } }] }; + const out = resolveFilterTokens(where, ctx) as { + $or: Array<{ owner?: string; id?: { $in: unknown } }>; + $and: Array<{ id: { $in: unknown } }>; + }; + // Control: the tree around the placeholder was rebuilt, so the leaf's identity is the walk's answer. + expect(out).not.toBe(where); + expect(out.$or[1]).not.toBe(where.$or[1]); + expect(out.$or[0].owner).toBe('usr_1'); + expect(out.$or[1].id!.$in).toBe(read); + expect(out.$and[0].id.$in).toBe(write); + expect(isFixedReadLeaf(out.$or[1].id!.$in)).toBe(true); + }); + + it('reads no placeholder inside a fixed-read leaf: its inputs are data', () => { + const leaf = SharedRecordIds.read('cpz_doc', '{current_user_id}'); + const where = { id: { $in: leaf } }; + expect(resolveFilterTokens(where, ctx)).toBe(where); + }); }); /** diff --git a/packages/core/src/utils/filter-tokens.ts b/packages/core/src/utils/filter-tokens.ts index bae919928ef..19b24472795 100644 --- a/packages/core/src/utils/filter-tokens.ts +++ b/packages/core/src/utils/filter-tokens.ts @@ -133,6 +133,7 @@ import { classifyFilterToken, + isFixedReadLeaf, isPeriodKeyToken, isReadableIds, isRecordContextToken, @@ -556,9 +557,9 @@ export function resolveFilterToken( function hasFilterToken(node: unknown): boolean { if (typeof node === 'string') return classifyFilterToken(node) !== null; if (Array.isArray(node)) return node.some(hasFilterToken); - // A `ReadableIds` leaf is a comparand value: its `object` names a table and - // is never a placeholder (see `resolveFilterTokens`). - if (isReadableIds(node)) return false; + // An engine-internal leaf is a comparand value: its inputs name a table and + // a principal and are never a placeholder (see `resolveFilterTokens`). + if (isEngineInternalLeaf(node)) return false; if (node && typeof node === 'object' && !(node instanceof Date)) { // [#25808] An unresolved `$now` anchor is a placeholder by construction. if (isUnresolvedNowAnchor(node)) return true; @@ -628,10 +629,20 @@ function isRecordReference(node: unknown): node is Record { && Object.prototype.hasOwnProperty.call(node, '$record'); } -/** A plain filter object (not a `Date`, not a branded `ReadableIds` leaf). */ +/** + * [ADR-0139 D1, ADR-0155 D1] A branded engine-internal comparand: a + * `ReadableIds` leaf or a fixed-read leaf (`SharedRecordIds`). Each is frozen, + * holds no placeholder, and keeps its meaning only while it keeps its + * non-enumerable brand, so every walk here hands it back by reference. + */ +function isEngineInternalLeaf(node: unknown): boolean { + return isReadableIds(node) || isFixedReadLeaf(node); +} + +/** A plain filter object (not a `Date`, not a branded engine-internal leaf). */ function isFilterObject(node: unknown): node is Record { return !!node && typeof node === 'object' && !Array.isArray(node) - && !(node instanceof Date) && !isReadableIds(node); + && !(node instanceof Date) && !isEngineInternalLeaf(node); } /** An operator object: a field's value carrying at least one `$` key. */ @@ -798,6 +809,12 @@ function resolveNowAnchor(node: { $now: true; addDays?: unknown }, now: Date): R * placeholder would then reach the engine's executor boundary as a plain * object in a `$in` comparand, which the engine cannot compose. The leaf holds * no placeholder and is frozen, so returning it unchanged is exact. + * + * [ADR-0155 D1] A fixed-read leaf (`isFixedReadLeaf`, `SharedRecordIds` + * today) is returned by reference for the same reason: rebuilt, it would + * arrive unbranded and be refused at the comparand door as a non-list + * (`INVALID_FILTER` / 400), so a read scope carrying a placeholder beside the + * leaf would fail every read it scopes. */ export function resolveFilterTokens( filter: T, @@ -826,8 +843,8 @@ export function resolveFilterTokens( return resolved; } if (Array.isArray(node)) return node.map(walk); - // [ADR-0139 D1] The leaf by reference, brand intact (see above). - if (isReadableIds(node)) return node; + // [ADR-0139 D1, ADR-0155 D1] The leaf by reference, brand intact (see above). + if (isEngineInternalLeaf(node)) return node; if (node && typeof node === 'object') { // Dates and other class instances are comparands, not filter structure. if (node instanceof Date) return node; diff --git a/packages/core/src/utils/fixed-read-leaf-refusal.test.ts b/packages/core/src/utils/fixed-read-leaf-refusal.test.ts new file mode 100644 index 00000000000..5dcf46498b2 --- /dev/null +++ b/packages/core/src/utils/fixed-read-leaf-refusal.test.ts @@ -0,0 +1,41 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it, vi } from 'vitest'; +import { SharedRecordIds } from '@objectstack/spec/data'; +import { describeFixedReadLeaf, fixedReadLeafRefusal, refuseFixedReadLeafOnce } from './fixed-read-leaf-refusal.js'; + +// [ADR-0155 D4] The fixed-read leaves' refusal: ADR-0139 D3's envelope, logged once per evaluator. +describe('the fixed-read leaf refusal', () => { + it('is INTERNAL_ERROR / 500, never INVALID_FILTER, and names the evaluator and the leaf', () => { + const leaf = SharedRecordIds.read('doc', 'u1'); + const err = fixedReadLeafRefusal('driver-x', `${describeFixedReadLeaf('where.id.$in', leaf)}, and so on.`, 'doc'); + expect(err).toMatchObject({ code: 'INTERNAL_ERROR', status: 500, httpStatus: 500, object: 'doc' }); + // The subjects it names, not its wording: the evaluator, the position, the leaf and its table. + expect(err.message.startsWith('[driver-x] where.id.$in ')).toBe(true); + expect(err.message).toContain('SharedRecordIds'); + expect(err.message).toContain("'sys_record_share'"); + }); + + it('names no input of the leaf: the recipient is a principal\'s id', () => { + const leaf = SharedRecordIds.write('doc', 'usr_secret_7', ['edit']); + expect(describeFixedReadLeaf('where.id.$in', leaf)).not.toContain('usr_secret_7'); + }); + + it('is logged at error once per state, and returned every time', () => { + const log = { error: vi.fn(), warn: vi.fn() }; + const state = { logged: false }; + const a = refuseFixedReadLeafOnce('objectql', 'm.', log, state); + const b = refuseFixedReadLeafOnce('objectql', 'm.', log, state); + expect([a.code, b.code]).toEqual(['INTERNAL_ERROR', 'INTERNAL_ERROR']); + expect(a).not.toBe(b); + expect(log.error).toHaveBeenCalledTimes(1); + expect(log.error).toHaveBeenCalledWith(expect.stringMatching(/^\[objectql\] m\. /)); + expect(log.warn).not.toHaveBeenCalled(); + }); + + it('falls back to warn on a sink without error', () => { + const log = { warn: vi.fn() }; + refuseFixedReadLeafOnce('objectql', 'm.', log, { logged: false }); + expect(log.warn).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/core/src/utils/fixed-read-leaf-refusal.ts b/packages/core/src/utils/fixed-read-leaf-refusal.ts new file mode 100644 index 00000000000..018af75c19c --- /dev/null +++ b/packages/core/src/utils/fixed-read-leaf-refusal.ts @@ -0,0 +1,89 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 D4] The one refusal every evaluator answers for a fixed-read leaf + * (`@objectstack/spec/data`'s `isFixedReadLeaf`: `SharedRecordIds` today, + * ADR-0147's leaf on the card that adds it) it will not evaluate, and its + * once-per-evaluator log. + * + * It is ADR-0139 D3's envelope (ADR-0112): `INTERNAL_ERROR` / 500, a message + * naming the evaluator, the leaf and the remedy, logged at `error` once per + * evaluator. ⛔ Not `INVALID_FILTER`: no request can spell the leaf, so the + * fault is a composition's, never an author's. An UNBRANDED copy is a + * different fault and keeps its own answer at the comparand door + * (`INVALID_FILTER` / 400, a non-list comparand). + * + * Who answers it: + * + * - **the engine's executor seam** (`@objectstack/objectql`, + * `fixed-read-leaf-seam.ts`), for a leaf out of position, on the wrong + * verb, for another principal, in one of the two classes it recognises, + * or bound for a driver whose `DriverCapabilities.fixedReadLeaves` does not + * name it; + * - **every evaluator that cannot run the leaf**, on its own card (ADR-0155 + * plan steps 3 to 5). + * + * Built once for every fixed-read leaf (ADR-0155 D4, "Built once"), on the + * floor every evaluator already stands on, beside + * `readable-ids-driver-refusal.ts`, whose once-per-instance log it shares + * ({@link logRefusalOnce}). + */ + +import { fixedInnerReadOf, fixedReadLeafNameOf, isFixedReadLeaf } from '@objectstack/spec/data'; +import { logRefusalOnce, type ReadableIdsRefusalLog } from './readable-ids-driver-refusal.js'; + +/** The ADR-0112 envelope of the refusal: a composition fault, never `INVALID_FILTER`. */ +export type FixedReadLeafRefusalError = Error & { + code: 'INTERNAL_ERROR'; + status: 500; + httpStatus: 500; + /** The object the refused operation runs on, when the refusing evaluator knows it. */ + object?: string; +}; + +/** + * How every refusal names the leaf at `at`: its name and the one table its + * fixed inner read reads, never its inputs (a recipient is a principal's id, + * and the message reaches logs). + * + * `leaf` is `unknown` on purpose: the brand is a `unique symbol`, and a caller + * in another package can hold the leaf's type from the other module format's + * declarations of `@objectstack/spec`, which TypeScript reads as a second, + * unrelated symbol. The guard decides at run time instead. + */ +export function describeFixedReadLeaf(at: string, leaf: unknown): string { + if (!isFixedReadLeaf(leaf)) return `${at} holds a value that is not a fixed-read leaf`; + return `${at} holds a ${fixedReadLeafNameOf(leaf)} leaf, a fixed read of '${fixedInnerReadOf(leaf).table}'`; +} + +/** + * The refusal `evaluator` (a driver's or the engine seam's name, e.g. + * `driver-sql`) answers, with `message` naming the leaf, why and the remedy. + */ +export function fixedReadLeafRefusal(evaluator: string, message: string, object?: string): FixedReadLeafRefusalError { + const err = new Error(`[${evaluator}] ${message}`) as FixedReadLeafRefusalError; + err.code = 'INTERNAL_ERROR'; + err.status = 500; + err.httpStatus = 500; + if (object !== undefined) err.object = object; + return err; +} + +/** + * {@link fixedReadLeafRefusal}, logged at `error` the FIRST time this + * evaluator refuses (`state.logged` is that evaluator's own flag), and + * returned for the caller to throw. A composition fault means every such + * operation on this evaluator fails, so one line names it; the caller sees + * every refusal. + */ +export function refuseFixedReadLeafOnce( + evaluator: string, + message: string, + log: ReadableIdsRefusalLog | undefined, + state: { logged: boolean }, + object?: string, +): FixedReadLeafRefusalError { + const err = fixedReadLeafRefusal(evaluator, message, object); + logRefusalOnce(err, log, state, 'evaluator'); + return err; +} diff --git a/packages/core/src/utils/readable-ids-driver-refusal.ts b/packages/core/src/utils/readable-ids-driver-refusal.ts index 4a3828cc3e0..11f8279d543 100644 --- a/packages/core/src/utils/readable-ids-driver-refusal.ts +++ b/packages/core/src/utils/readable-ids-driver-refusal.ts @@ -239,11 +239,27 @@ export function refuseReadableIdsOnce( unsupportedReason?: string, ): ReadableIdsDriverRefusalError { const err = readableIdsDriverRefusal(driver, site, unsupportedReason); - if (!state.logged) { - state.logged = true; - const line = `${err.message} Logged once for this driver; later refusals answer the caller the same way.`; - if (typeof log?.error === 'function') log.error(line); - else log?.warn(line); - } + logRefusalOnce(err, log, state); return err; } + +/** + * The once-per-instance log every composition-fault refusal shares: `err`'s + * message at `error` (at `warn` on a sink without `error`), the first time + * `state` is asked, and never again for that instance. `who` names the + * instance the flag belongs to in the line. [ADR-0155 D4] The fixed-read + * leaves' refusal (`fixed-read-leaf-refusal.ts`) logs through it too, so one + * device logs both leaves' refusals. + */ +export function logRefusalOnce( + err: Error, + log: ReadableIdsRefusalLog | undefined, + state: { logged: boolean }, + who = 'driver', +): void { + if (state.logged) return; + state.logged = true; + const line = `${err.message} Logged once for this ${who}; later refusals answer the caller the same way.`; + if (typeof log?.error === 'function') log.error(line); + else log?.warn(line); +} diff --git a/packages/objectql/src/engine-count-aggregate.ts b/packages/objectql/src/engine-count-aggregate.ts index bcdbeef26ea..b61b92746a5 100644 --- a/packages/objectql/src/engine-count-aggregate.ts +++ b/packages/objectql/src/engine-count-aggregate.ts @@ -75,6 +75,7 @@ import { rejectUnknownEngineOptions, } from './engine.js'; import type { EngineReadOptions, ObjectQL, OperationContext } from './engine.js'; +import { atFixedReadLeafDoor } from './fixed-read-leaf-seam.js'; /** * The `ObjectQL` members the functions below read — every one of them, and no @@ -95,11 +96,14 @@ export interface CountAggregateHost { buildDriverOptions: ObjectQL['buildDriverOptions']; composeReadableIdsAtBoundary: ObjectQL['composeReadableIdsAtBoundary']; find: ObjectQL['find']; + /** [ADR-0155 D4] The engine and its logger, for the door's once-per-engine log of a fixed-read leaf refusal. */ + readonly facade: ObjectQL; + readonly logger: ObjectQL['logger']; } /** The body of `ObjectQL#count`; the method's docblock there is its contract. */ export async function count( - this: Pick, + this: Pick, object: string, query?: EngineCountOptions, options?: EngineReadOptions, @@ -109,7 +113,7 @@ export async function count( // `query.where` only, so an unfolded `{ filter }` counted the whole table. query = foldEngineOptionAliases(object, 'count', query, ENGINE_WHERE_SLOTS); rejectUnknownEngineOptions(object, 'count', query, ENGINE_COUNT_OPTION_KEYS); - query = lowerWhereFilterArray(object, 'count', query, this._registry.getObject(object), this.relatedSchemaOf); + query = atFixedReadLeafDoor(this, () => lowerWhereFilterArray(object, 'count', query, this._registry.getObject(object), this.relatedSchemaOf)); // [ADR-0100] Same internal-field and credential-column refusals as `find`, same position. rejectInternalFieldEvaluation(object, query, mergeReadContext(query?.context, options?.context), this.relatedSchemaOf); rejectCredentialEvaluation(object, 'count', query, mergeReadContext(query?.context, options?.context), this.relatedSchemaOf); diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 03cd568986d..b742f894200 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -39,6 +39,10 @@ import { normalizeFilterComparandTypes } from '@objectstack/spec/data'; import type { EngineAggregateOptions, EngineDeleteOptions, FilterCondition, HookContext, QueryAST } from '@objectstack/spec/data'; import type { InternalFieldEvaluationOptions, InternalFieldEvaluationQuery } from '@objectstack/spec/contracts'; import { assertFilterIsMaterializable, assertListComparandShapes, collectComposableReadableIds, invalidFilterError } from './filter-comparand-shape.js'; +// [ADR-0155 D4] The fixed-read leaf seam reads the engine through the security +// resolvers' host, built once per engine, which carries every member it reads. +import { securityResolversHost } from './engine-facet-hosts.js'; +import { atFixedReadLeafDoor, passFixedReadLeaves } from './fixed-read-leaf-seam.js'; import { assertHavingTemporalComparandsInterpretable, assertTemporalComparandsInterpretable } from './temporal-comparand-door.js'; import { assertTextOperatorTargetsAreStringCapable } from './text-operator-declared-type-door.js'; import { narrowHavingNumberComparands, narrowNumberComparands } from './number-comparand-declared-type-door.js'; @@ -181,7 +185,7 @@ export class DeleteAndAggregateFacet { rejectUnknownEngineOptions(object, 'delete', options, ENGINE_DELETE_OPTION_KEYS); // [#5158] Same ordering reason as update(): the dispatch decision below // reads `where.id`, which an unlowered array never carries. - options = lowerWhereFilterArray(object, 'delete', options, this._registry.getObject(object), this.relatedSchemaOf); + options = atFixedReadLeafDoor(this, () => lowerWhereFilterArray(object, 'delete', options, this._registry.getObject(object), this.relatedSchemaOf)); // [ADR-0100] Same credential-column refusal as update(). rejectCredentialEvaluation(object, 'delete', options, options?.context, this.relatedSchemaOf); @@ -237,6 +241,8 @@ export class DeleteAndAggregateFacet { // delete's predicate is refused at the executor's entry, before the // pre-image reads reach the driver. collectComposableReadableIds(object, 'delete', opCtx.ast?.where, 'where'); + // [ADR-0155 D1] …and no fixed-read leaf at all: a share widens edit, never delete. + passFixedReadLeaves(securityResolversHost.of(this.facade), object, 'delete', opCtx.ast?.where, opCtx.context); const hookContext: HookContext = { object, event: 'beforeDelete', @@ -1031,7 +1037,7 @@ export class DeleteAndAggregateFacet { // `query.where` only, so an unfolded `{ filter }` aggregated every row. query = foldEngineOptionAliases(object, 'aggregate', query, ENGINE_WHERE_SLOTS); rejectUnknownEngineOptions(object, 'aggregate', query, ENGINE_AGGREGATE_OPTION_KEYS); - query = lowerWhereFilterArray(object, 'aggregate', query, this._registry.getObject(object), this.relatedSchemaOf); + query = atFixedReadLeafDoor(this, () => lowerWhereFilterArray(object, 'aggregate', query, this._registry.getObject(object), this.relatedSchemaOf)); // [ADR-0100] The filter half of the credential-column guard — `where` // and every `aggregations[i].filter` — before the search term joins // `where`; the aggregate half (`rejectCredentialAggregation`) follows. @@ -1155,7 +1161,7 @@ export class DeleteAndAggregateFacet { // `null` / string element as no constraint (every row counted). // First among the doors below, which step around a non-node. assertFilterNodeShapes(aggFilter, `aggregations[${i}].filter`); - assertListComparandShapes(object, 'aggregate', aggFilter, `aggregations[${i}].filter`); + atFixedReadLeafDoor(this, () => assertListComparandShapes(object, 'aggregate', aggFilter, `aggregations[${i}].filter`)); assertFilterIsMaterializable(object, 'aggregate', this._registry.getObject(object), aggFilter); // [#15661] …and the declared-type door for the text operators: a // `$contains` over a numeric column in ONE aggregation's filter is @@ -1298,7 +1304,7 @@ export class DeleteAndAggregateFacet { // string element kept every group's rows unconstrained; a condition // array was refused as a key naming no column ('0'). assertFilterNodeShapes(query.having, 'having'); - assertListComparandShapes(object, 'aggregate', query.having, 'having'); + atFixedReadLeafDoor(this, () => assertListComparandShapes(object, 'aggregate', query.having, 'having')); // [#20176] The object's declaration, read once: the per-aggregation // `filter` reads a temporal comparand by its column's storage rule // (`applyInMemoryAggregation` below), and `having` by its aggregated diff --git a/packages/objectql/src/engine-find.ts b/packages/objectql/src/engine-find.ts index 0122b4b25ed..3434ca103d5 100644 --- a/packages/objectql/src/engine-find.ts +++ b/packages/objectql/src/engine-find.ts @@ -45,6 +45,7 @@ import { FindHookResultNotArrayError } from './find-hook-result-shape.js'; import { FindOneHookResultNotRecordError, isFindOneResultShape } from './verb-hook-result-shape.js'; import { rejectCredentialEvaluation } from './credential-evaluation-guard.js'; import { rejectInternalFieldEvaluation } from './internal-field-evaluation-guard.js'; +import { atFixedReadLeafDoor } from './fixed-read-leaf-seam.js'; import { assertProjectionNamesAField, refuseProjectionOfUnknownColumns } from './empty-projection-door.js'; import { PLATFORM_PROVISIONED_COLUMNS, declaredColumnSet, rowsWithDeclaredColumnsOnly, rowsWithSelectedColumnsAnswered, selectedStoredColumns, withDeclaredColumnsOnly, withSelectedColumnsAnswered } from './declared-read-columns.js'; import { @@ -436,7 +437,7 @@ export class FindFacet { rejectUnknownEngineOptions(object, 'find', query, ENGINE_FIND_OPTION_KEYS); // [#27008] An empty projection is refused, never read as every column. assertProjectionNamesAField(object, 'find', query); - query = lowerWhereFilterArray(object, 'find', query, this._registry.getObject(object), this.relatedSchemaOf); + query = atFixedReadLeafDoor(this, () => lowerWhereFilterArray(object, 'find', query, this._registry.getObject(object), this.relatedSchemaOf)); this.logger.debug('Find operation starting', { object, query }); const driver = this.getDriver(object); // [latest per group] The engine-internal request for one row per group @@ -805,7 +806,7 @@ export class FindFacet { rejectUnknownEngineOptions(objectName, 'findOne', query, ENGINE_FIND_OPTION_KEYS); // [#27008] Same refusal as find(). assertProjectionNamesAField(objectName, 'findOne', query); - query = lowerWhereFilterArray(objectName, 'findOne', query, this._registry.getObject(objectName), this.relatedSchemaOf); + query = atFixedReadLeafDoor(this, () => lowerWhereFilterArray(objectName, 'findOne', query, this._registry.getObject(objectName), this.relatedSchemaOf)); this.logger.debug('FindOne operation', { objectName }); const driver = this.getDriver(objectName); // `object` after the spread for the same reason as find(); `limit: 1` diff --git a/packages/objectql/src/engine-fixed-read-leaf-seam.test.ts b/packages/objectql/src/engine-fixed-read-leaf-seam.test.ts new file mode 100644 index 00000000000..60cb67251f8 --- /dev/null +++ b/packages/objectql/src/engine-fixed-read-leaf-seam.test.ts @@ -0,0 +1,428 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 D1, D4] The engine's executor seam for the fixed-read leaves + * (`fixed-read-leaf-position.ts`, `fixed-read-leaf-seam.ts`), on a real + * `ObjectQL`: the door admits the brand, and the seam checks position, verb, + * recipient, the two classes and the driver's declaration, then hands the leaf + * to the driver by reference, or refuses before any driver is asked with + * `INTERNAL_ERROR` / 500. + * + * The step-1 conformance cases (`SHARED_RECORD_IDS_CASE_SET.seam`) run here + * against the seam itself. A case whose filter holds a composed `ReadableIds` + * scope is driven the only way such a scope reaches a driver: the caller + * writes `ReadableIds.of(P)` and the security service answers `P`'s read + * filter with the scope, which the engine composes at its boundary. + * + * No driver in this repository declares `fixedReadLeaves` yet (the compile + * lands per driver, ADR-0155 plan steps 3 and 4), so the pass-through is + * witnessed on a recording driver that declares the brand. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { + ReadableIds, + SHARED_RECORD_IDS_CASE_SET, + SharedRecordIds, + isComposedReadableIds, + isFixedReadLeaf, + type EngineAggregateOptions, + type FilterCondition, + type FixedReadLeafSeamCase, +} from '@objectstack/spec/data'; +import { ObjectQL, SECURITY_SERVICE_SOURCE_SLOT } from './engine.js'; + +interface SeenCall { verb: string; object: string; ast: any } + +const DECLARES = { readableIdsLeaf: true, fixedReadLeaves: ['SharedRecordIds'] }; + +function makeRecordingDriver(name: string, supports: Record) { + const calls: SeenCall[] = []; + const driver: any = { + name, version: '0.0.0', supports, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(object: string, ast: any) { calls.push({ verb: 'find', object, ast }); return []; }, + async findOne(object: string, ast: any) { calls.push({ verb: 'findOne', object, ast }); return null; }, + async count(object: string, ast: any) { calls.push({ verb: 'count', object, ast }); return 0; }, + async aggregate(object: string, ast: any) { calls.push({ verb: 'aggregate', object, ast }); return []; }, + async create(object: string, data: Record) { calls.push({ verb: 'create', object, ast: data }); return data; }, + async update(object: string, _id: string, data: Record) { calls.push({ verb: 'update', object, ast: data }); return data; }, + async updateMany(object: string, ast: any) { calls.push({ verb: 'updateMany', object, ast }); return 0; }, + async delete(object: string) { calls.push({ verb: 'delete', object, ast: null }); return true; }, + async deleteMany(object: string, ast: any) { calls.push({ verb: 'deleteMany', object, ast }); return 0; }, + }; + return { driver, calls }; +} + +function capturingLogger() { + const lines: Array<{ level: string; msg: string }> = []; + const push = (level: string) => (msg: string) => void lines.push({ level, msg: String(msg) }); + const logger: any = { + lines, + trace() {}, fatal() {}, + debug: push('debug'), info: push('info'), warn: push('warn'), error: push('error'), + child() { return logger; }, + }; + return logger; +} + +const text = (name: string) => ({ name, type: 'text' }); +const OBJECTS = [ + { name: 'srid_doc', fields: { owner: text('owner'), label: text('label') } }, + { name: 'srid_note', fields: { record_id: text('record_id') } }, + { name: 'srid_other', fields: { title: text('title') } }, + { name: 'srid_far', datasource: 'far', fields: { owner: text('owner') } }, + { + name: 'sys_record_share', + fields: { + object_name: text('object_name'), recipient_type: text('recipient_type'), + recipient_id: text('recipient_id'), record_id: text('record_id'), access_level: text('access_level'), + }, + }, +]; + +type Thrown = (Error & { code?: string; status?: number; httpStatus?: number }) | null; +const refusalOf = async (p: Promise): Promise => p.then(() => null, (e: any) => e); +const envelopeOf = (err: Thrown) => ({ code: err?.code, status: err?.status }); +const REFUSED = { code: 'INTERNAL_ERROR', status: 500 }; +const ASKER = { userId: 'u1' }; + +/** Every fixed-read leaf in `node`, composed scopes included, by identity. */ +function leavesIn(node: unknown, out: unknown[] = []): unknown[] { + if (isFixedReadLeaf(node)) out.push(node); + else if (isComposedReadableIds(node)) leavesIn(node.scope, out); + else if (node !== null && typeof node === 'object') for (const v of Object.values(node)) leavesIn(v, out); + return out; +} + +/** + * The filter a caller writes for a case "as the seam sees it": each composed + * scope becomes `ReadableIds.of(P)`, and `scopes` holds the read filter the + * security service answers for `P`. Every fixed-read leaf is kept by reference. + */ +function asCallerWrites(node: unknown, scopes: Map): unknown { + if (isFixedReadLeaf(node)) return node; + if (isComposedReadableIds(node)) { + scopes.set(node.object, asCallerWrites(node.scope, scopes)); + return ReadableIds.of(node.object); + } + if (Array.isArray(node)) return node.map((v) => asCallerWrites(v, scopes)); + if (node !== null && typeof node === 'object') { + return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, asCallerWrites(v, scopes)])); + } + return node; +} + +async function bootEngine(opts: { supports?: Record } = {}) { + const logger = capturingLogger(); + const engine = new ObjectQL({ logger }); + const rec = makeRecordingDriver('recording', opts.supports ?? DECLARES); + const far = makeRecordingDriver('far', DECLARES); + engine.registerDriver(rec.driver, true); + engine.registerDriver(far.driver); + await engine.init(); + for (const def of OBJECTS) engine.registry.registerObject(def as any, 'test'); + return { engine, logger, calls: rec.calls, farCalls: far.calls, driver: rec.driver }; +} + +/** Put a security service in the engine's slot, answering `scopes` as each parent's read filter. */ +function wireSecurity(engine: ObjectQL, scopes: Map): void { + const svc = { + async canReadObject() { return true; }, + async getReadFilter(object: string) { return scopes.get(object); }, + async explain() { return { allowed: false }; }, + }; + (engine as unknown as Record)[SECURITY_SERVICE_SOURCE_SLOT] = () => svc; +} + +/** Run one operation the way a case names it. */ +function run(engine: ObjectQL, c: Pick, filter: unknown) { + const context = c.context as any; + const where = c.clause === 'where' ? (filter as FilterCondition) : undefined; + switch (c.operation) { + case 'find': return engine.find(c.object, { where }, { context }); + case 'findOne': return engine.findOne(c.object, { where }, { context }); + case 'count': return engine.count(c.object, { where }, { context }); + case 'aggregate': { + const query: EngineAggregateOptions = { + ...(where !== undefined ? { where } : {}), + ...(c.clause === 'having' ? { having: filter as FilterCondition, groupBy: ['owner'] } : {}), + aggregations: [{ function: 'count', alias: 'n' }], + }; + return engine.aggregate(c.object, query, { context }); + } + case 'update': return engine.update(c.object, { label: 'z' }, { where, multi: true, context } as any); + case 'delete': return engine.delete(c.object, { where, multi: true, context } as any); + } +} + +describe('[ADR-0155 D1, D4] the step-1 seam cases, against the engine\'s seam', () => { + let booted: Awaited>; + beforeEach(async () => { booted = await bootEngine(); }); + + for (const c of SHARED_RECORD_IDS_CASE_SET.seam) { + it(`${c.verdict}: ${c.name}`, async () => { + const scopes = new Map(); + const built = c.filter(); + const filter = asCallerWrites(built, scopes); + wireSecurity(booted.engine, scopes); + const err = await refusalOf(Promise.resolve(run(booted.engine, c, filter))); + if (c.verdict === 'refuses') { + expect(envelopeOf(err), err?.message).toEqual(REFUSED); + expect(booted.calls, 'no driver was asked').toEqual([]); + return; + } + expect(err).toBeNull(); + expect(booted.calls.length).toBeGreaterThan(0); + // Every leaf the case wrote reached the driver, the same object: by reference, brand intact. + const wrote = leavesIn(built); + for (const call of booted.calls) { + const reached = leavesIn(call.ast?.where); + expect(reached.length, call.verb).toBe(wrote.length); + for (const leaf of reached) expect(wrote.includes(leaf), call.verb).toBe(true); + } + }); + } +}); + +describe('[ADR-0155 D4] the recipient rule compares, never replaces', () => { + it('a context with no user and no system flag is refused: absence is never system', async () => { + const { engine, calls } = await bootEngine(); + const err = await refusalOf(engine.find('srid_doc', { where: { id: { $in: SharedRecordIds.read('srid_doc', 'u1') } } })); + expect(envelopeOf(err)).toEqual(REFUSED); + expect(calls).toEqual([]); + }); + + it('an admitted leaf keeps its recipient: the delegator\'s leaf reaches the driver as the delegator\'s', async () => { + const { engine, calls } = await bootEngine(); + const leaf = SharedRecordIds.read('srid_doc', 'u1'); + await engine.find('srid_doc', { where: { id: { $in: leaf } } }, { context: { userId: 'agent_1', onBehalfOf: { userId: 'u1' } } as any }); + expect(calls[0].ast.where.id.$in).toBe(leaf); + expect((calls[0].ast.where.id.$in as SharedRecordIds).recipient).toBe('u1'); + }); +}); + +describe('[ADR-0155 D4, Q2 as ruled] the driver declaration', () => { + const where = () => ({ id: { $in: SharedRecordIds.read('srid_doc', 'u1') } }); + + it('a driver that declares nothing is never handed the leaf: INTERNAL_ERROR / 500, naming the driver and the leaf', async () => { + const { engine, calls } = await bootEngine({ supports: {} }); + const err = await refusalOf(engine.find('srid_doc', { where: where() }, { context: ASKER as any })); + expect(envelopeOf(err)).toEqual(REFUSED); + expect(err?.httpStatus).toBe(500); + expect(err?.message).toContain("'recording'"); + expect(err?.message).toContain('SharedRecordIds'); + expect(calls).toEqual([]); + }); + + it('an empty list and the readableIdsLeaf bit alone declare no fixed-read leaf', async () => { + for (const supports of [{ fixedReadLeaves: [] }, { readableIdsLeaf: true }]) { + const { engine, calls } = await bootEngine({ supports }); + expect(envelopeOf(await refusalOf(engine.count('srid_doc', { where: where() }, { context: ASKER as any })))).toEqual(REFUSED); + expect(calls).toEqual([]); + } + }); + + it('the refusal is logged at error once per driver, and answered every time', async () => { + const { engine, logger } = await bootEngine({ supports: {} }); + for (let i = 0; i < 3; i++) { + expect(envelopeOf(await refusalOf(engine.find('srid_doc', { where: where() }, { context: ASKER as any })))).toEqual(REFUSED); + } + const lines = logger.lines.filter((l: { msg: string }) => l.msg.includes('fixed read of')); + expect(lines.map((l: { level: string }) => l.level)).toEqual(['error']); + }); +}); + +describe('[ADR-0155 D4, ② as ruled] the two classes the seam recognises', () => { + const where = (object = 'srid_doc') => ({ id: { $in: SharedRecordIds.read(object, 'u1') } }); + + it('an object bound to another datasource than sys_record_share is refused, its driver\'s declaration notwithstanding', async () => { + const { engine, farCalls } = await bootEngine(); + const err = await refusalOf(engine.find('srid_far', { where: where('srid_far') }, { context: ASKER as any })); + expect(envelopeOf(err)).toEqual(REFUSED); + expect(err?.message).toContain("'far'"); + expect(farCalls).toEqual([]); + }); + + it('an object-scoped middleware registered for sys_record_share by name is refused', async () => { + const { engine, calls } = await bootEngine(); + engine.registerMiddleware(async (_ctx, next) => next(), { object: 'sys_record_share' }); + expect(envelopeOf(await refusalOf(engine.find('srid_doc', { where: where() }, { context: ASKER as any })))).toEqual(REFUSED); + expect(calls).toEqual([]); + }); + + for (const event of ['beforeFind', 'afterFind']) { + for (const object of ['sys_record_share', ['srid_other', 'sys_record_share']]) { + it(`a ${event} hook naming sys_record_share (${JSON.stringify(object)}) is refused`, async () => { + const { engine, calls } = await bootEngine(); + engine.registerHook(event, () => {}, { object }); + expect(envelopeOf(await refusalOf(engine.find('srid_doc', { where: where() }, { context: ASKER as any })))).toEqual(REFUSED); + expect(calls).toEqual([]); + }); + } + } + + it('a registration that names no object, or \'*\', is outside the class: the leaf passes through', async () => { + const { engine, calls } = await bootEngine(); + engine.registerMiddleware(async (_ctx, next) => next()); + engine.registerMiddleware(async (_ctx, next) => next(), { object: '*' }); + engine.registerHook('beforeFind', () => {}); + engine.registerHook('afterFind', () => {}, { object: '*' }); + engine.registerHook('beforeFind', () => {}, { object: 'srid_other' }); + const leaf = SharedRecordIds.read('srid_doc', 'u1'); + await engine.find('srid_doc', { where: { id: { $in: leaf } } }, { context: ASKER as any }); + expect(calls.map((c) => c.verb)).toEqual(['find']); + expect(calls[0].ast.where.id.$in).toBe(leaf); + }); + + it('a hook that names sys_record_share and excludes it is not dispatched for it, so it is outside the class', async () => { + const { engine, calls } = await bootEngine(); + engine.registerHook('beforeFind', () => {}, { object: ['sys_record_share', 'srid_other'], excludeObjects: 'sys_record_share' }); + await engine.find('srid_doc', { where: where() }, { context: ASKER as any }); + expect(calls.map((c) => c.verb)).toEqual(['find']); + }); +}); + +describe('[ADR-0155 D4] a leaf the pipeline wrote meets the same seam at the boundary', () => { + it('a middleware-written read form passes through on each read verb; the door never saw it', async () => { + const { engine, calls } = await bootEngine(); + const leaf = SharedRecordIds.read('srid_doc', 'u1'); + engine.registerMiddleware(async (ctx, next) => { + if (ctx.ast && ['find', 'findOne', 'count', 'aggregate'].includes(ctx.operation)) { + ctx.ast.where = { $and: [ctx.ast.where ?? {}, { $or: [{ owner: 'u1' }, { id: { $in: leaf } }] }] }; + } + await next(); + }, { object: 'srid_doc' }); + const where = { label: 'keep' }; + await engine.find('srid_doc', { where }, { context: ASKER as any }); + await engine.findOne('srid_doc', { where }, { context: ASKER as any }); + await engine.count('srid_doc', { where }, { context: ASKER as any }); + await engine.aggregate('srid_doc', { where, aggregations: [{ function: 'count', alias: 'n' }] }, { context: ASKER as any }); + expect(calls.map((c) => c.verb)).toEqual(['find', 'findOne', 'count', 'aggregate']); + for (const call of calls) expect(leavesIn(call.ast.where), call.verb).toEqual([leaf]); + }); + + it('a middleware-written write form passes through a predicate update, to its write', async () => { + const { engine, calls } = await bootEngine(); + const leaf = SharedRecordIds.write('srid_doc', 'u1', ['edit']); + engine.registerMiddleware(async (ctx, next) => { + if (ctx.ast && ctx.operation === 'update') ctx.ast.where = { $and: [ctx.ast.where ?? {}, { id: { $in: leaf } }] }; + await next(); + }, { object: 'srid_doc' }); + await engine.update('srid_doc', { label: 'z' }, { where: { label: 'keep' }, multi: true, context: ASKER } as any); + const writes = calls.filter((c) => c.verb === 'updateMany'); + expect(writes).toHaveLength(1); + expect(leavesIn(writes[0].ast.where)).toEqual([leaf]); + }); + + it('a beforeFind hook that writes the leaf out of position is refused at the boundary, logged once for the engine', async () => { + const { engine, calls, logger } = await bootEngine(); + engine.registerHook('beforeFind', (ctx: any) => { + ctx.input.ast.where = { id: SharedRecordIds.read('srid_doc', 'u1') }; + }, { object: 'srid_doc' }); + for (let i = 0; i < 2; i++) { + expect(envelopeOf(await refusalOf(engine.find('srid_doc', { where: { label: 'keep' } }, { context: ASKER as any })))).toEqual(REFUSED); + } + expect(calls).toEqual([]); + expect(logger.lines.filter((l: { msg: string }) => l.msg.includes('fixed read of')).map((l: { level: string }) => l.level)).toEqual(['error']); + }); + + it('a middleware-written leaf on delete is refused before the pre-image read', async () => { + const { engine, calls } = await bootEngine(); + engine.registerMiddleware(async (ctx, next) => { + if (ctx.ast && ctx.operation === 'delete') ctx.ast.where = { id: { $in: SharedRecordIds.write('srid_doc', 'u1', ['edit']) } }; + await next(); + }, { object: 'srid_doc' }); + const err = await refusalOf(engine.delete('srid_doc', { where: { label: 'keep' }, multi: true, context: ASKER } as any)); + expect(envelopeOf(err)).toEqual(REFUSED); + expect(calls).toEqual([]); + }); +}); + +describe('[ADR-0155 D1] the comparand door', () => { + it('an unbranded copy stays a non-list comparand: INVALID_FILTER / 400, as before', async () => { + const { engine, calls } = await bootEngine(); + const copy = JSON.parse(JSON.stringify(SharedRecordIds.read('srid_doc', 'u1'))); + const err = await refusalOf(engine.find('srid_doc', { where: { id: { $in: copy } } }, { context: ASKER as any })); + expect(envelopeOf(err)).toEqual({ code: 'INVALID_FILTER', status: 400 }); + expect(calls).toEqual([]); + }); + + it('a leaf an array-form where lowers by reference into another position is refused by name, not as a value', async () => { + const { engine, calls } = await bootEngine(); + const where = [['id', '=', SharedRecordIds.read('srid_doc', 'u1')]] as unknown as FilterCondition; + const err = await refusalOf(engine.find('srid_doc', { where }, { context: ASKER as any })); + expect(envelopeOf(err)).toEqual(REFUSED); + expect(calls).toEqual([]); + }); + + it('a leaf in an aggregation\'s own filter is refused', async () => { + const { engine, calls } = await bootEngine(); + const filter = { id: { $in: SharedRecordIds.read('srid_doc', 'u1') } } as unknown as FilterCondition; + const err = await refusalOf(engine.aggregate('srid_doc', { + aggregations: [{ function: 'count', alias: 'n', filter }], + }, { context: ASKER as any })); + expect(envelopeOf(err)).toEqual(REFUSED); + expect(calls).toEqual([]); + }); +}); + +describe('[ADR-0155 D4] a refusal at the door is logged on the boundary\'s flag, once per engine', () => { + const misplaced = () => ({ id: { $nin: SharedRecordIds.read('srid_doc', 'u1') } }); + const errorsIn = (logger: { lines: Array<{ level: string; msg: string }> }) => + logger.lines.filter((l) => l.msg.includes('fixed read of')).map((l) => l.level); + + it('a misplaced leaf in a caller\'s where is refused at the door, 500, and two refusals log once at error', async () => { + const { engine, calls, logger } = await bootEngine(); + for (let i = 0; i < 2; i++) { + expect(envelopeOf(await refusalOf(engine.find('srid_doc', { where: misplaced() as unknown as FilterCondition }, { context: ASKER as any })))).toEqual(REFUSED); + } + expect(calls).toEqual([]); + expect(errorsIn(logger)).toEqual(['error']); + }); + + it('a refusal at the door and one at the boundary share one log, in either order', async () => { + const otherRecipient = () => ({ id: { $in: SharedRecordIds.read('srid_doc', 'someone_else') } }); + const door = (engine: ObjectQL) => engine.find('srid_doc', { where: misplaced() as unknown as FilterCondition }, { context: ASKER as any }); + const boundary = (engine: ObjectQL) => engine.find('srid_doc', { where: otherRecipient() as unknown as FilterCondition }, { context: ASKER as any }); + for (const order of [[door, boundary], [boundary, door]]) { + const { engine, logger } = await bootEngine(); + for (const call of order) expect(envelopeOf(await refusalOf(call(engine)))).toEqual(REFUSED); + expect(errorsIn(logger)).toEqual(['error']); + } + }); + + // Every verb's door calls: the lowering of `where` (both branches), and the + // aggregate's `having` and per-aggregation `filter` doors. + const DOOR_SITES: Array<[string, (engine: ObjectQL) => Promise]> = [ + ['find', (e) => e.find('srid_doc', { where: misplaced() as unknown as FilterCondition }, { context: ASKER as any })], + ['find, array form', (e) => e.find('srid_doc', { where: [['id', '=', SharedRecordIds.read('srid_doc', 'u1')]] as unknown as FilterCondition }, { context: ASKER as any })], + ['findOne', (e) => e.findOne('srid_doc', { where: misplaced() as unknown as FilterCondition }, { context: ASKER as any })], + ['count', (e) => e.count('srid_doc', { where: misplaced() as unknown as FilterCondition }, { context: ASKER as any })], + ['aggregate where', (e) => e.aggregate('srid_doc', { where: misplaced() as unknown as FilterCondition, aggregations: [{ function: 'count', alias: 'n' }] }, { context: ASKER as any })], + ['aggregate having', (e) => e.aggregate('srid_doc', { groupBy: ['owner'], having: misplaced() as unknown as FilterCondition, aggregations: [{ function: 'count', alias: 'n' }] }, { context: ASKER as any })], + ['aggregate filter', (e) => e.aggregate('srid_doc', { aggregations: [{ function: 'count', alias: 'n', filter: misplaced() as unknown as FilterCondition }] }, { context: ASKER as any })], + ['update', (e) => e.update('srid_doc', { label: 'z' }, { where: misplaced(), multi: true, context: ASKER } as any)], + ['delete', (e) => e.delete('srid_doc', { where: misplaced(), multi: true, context: ASKER } as any)], + ]; + for (const [site, call] of DOOR_SITES) { + it(`the door refusal on ${site} is logged at error once`, async () => { + const { engine, calls, logger } = await bootEngine(); + for (let i = 0; i < 2; i++) expect(envelopeOf(await refusalOf(call(engine))), site).toEqual(REFUSED); + expect(calls).toEqual([]); + expect(errorsIn(logger)).toEqual(['error']); + }); + } + + it('an unbranded copy stays INVALID_FILTER / 400 and is not logged by this device, nor spends its flag', async () => { + const { engine, logger } = await bootEngine(); + const copy = JSON.parse(JSON.stringify(SharedRecordIds.read('srid_doc', 'u1'))); + for (let i = 0; i < 2; i++) { + expect(envelopeOf(await refusalOf(engine.find('srid_doc', { where: { id: { $in: copy } } }, { context: ASKER as any })))).toEqual({ code: 'INVALID_FILTER', status: 400 }); + } + expect(errorsIn(logger)).toEqual([]); + expect(logger.lines.filter((l: { level: string }) => l.level === 'error')).toEqual([]); + expect(envelopeOf(await refusalOf(engine.find('srid_doc', { where: misplaced() as unknown as FilterCondition }, { context: ASKER as any })))).toEqual(REFUSED); + expect(errorsIn(logger)).toEqual(['error']); + }); +}); diff --git a/packages/objectql/src/engine-security-resolvers.ts b/packages/objectql/src/engine-security-resolvers.ts index 5b6eff5d0e9..3eb5431cf7d 100644 --- a/packages/objectql/src/engine-security-resolvers.ts +++ b/packages/objectql/src/engine-security-resolvers.ts @@ -39,6 +39,7 @@ import { isPlannedRelationLeaf } from './relation-semi-join.js'; import { referenceTargetOf } from '@objectstack/spec/data'; import type { EngineQueryOptions, QueryAST } from '@objectstack/spec/data'; import { collectComposableReadableIds, describeReadableIdsLeaf, readableIdsRefusalError } from './filter-comparand-shape.js'; +import { passFixedReadLeaves } from './fixed-read-leaf-seam.js'; import type { ComposableReadableIdsSite } from './filter-comparand-shape.js'; import { isStoredMetadataBodyObject } from '@objectstack/spec/kernel'; import type { ExecutionContext } from '@objectstack/spec/kernel'; @@ -72,6 +73,7 @@ export interface SecurityResolversHost { readonly formulaHopReads: ObjectQL['formulaHopReads']; formulaOptionLabels: ObjectQL['formulaOptionLabels']; hasObjectMiddleware: ObjectQL['hasObjectMiddleware']; + readonly hooks: ObjectQL['hooks']; readonly i18nService: ObjectQL['i18nService']; readonly insertRecomputeListeners: ObjectQL['insertRecomputeListeners']; readonly logger: ObjectQL['logger']; @@ -221,16 +223,23 @@ export class SecurityResolversFacet { * aggregations' own filters are judged here too, so a leaf a middleware * wrote there is refused rather than evaluated in memory. */ - static async composeReadableIdsAtBoundary(this: Pick, object: string, operation: 'find' | 'findOne' | 'count' | 'aggregate', ast: A, context: ExecutionContext | undefined, driverOptions?: unknown): Promise { + static async composeReadableIdsAtBoundary(this: Pick, object: string, operation: 'find' | 'findOne' | 'count' | 'aggregate', ast: A, context: ExecutionContext | undefined, driverOptions?: unknown): Promise { if (operation === 'aggregate') { collectComposableReadableIds(object, operation, ast.having, 'having'); + passFixedReadLeaves(this, object, operation, ast.having, context, 'having'); const aggregations = Array.isArray(ast.aggregations) ? ast.aggregations : []; aggregations.forEach((agg, i) => { collectComposableReadableIds(object, operation, (agg as { filter?: unknown } | undefined)?.filter, `aggregations[${i}].filter`); + passFixedReadLeaves(this, object, operation, (agg as { filter?: unknown } | undefined)?.filter, context, `aggregations[${i}].filter`); }); } const sites = collectComposableReadableIds(object, operation, ast.where, 'where'); - if (sites.length === 0) return ast; + // [ADR-0155 D4] The fixed-read leaves pass through: nothing to compose, every + // check on the final where, the composed scopes included (below). + if (sites.length === 0) { + passFixedReadLeaves(this, object, operation, ast.where, context); + return ast; + } const security = this.resolveReadableIdsSecurity(); // A planned relation leaf asks the security service nothing @@ -248,6 +257,7 @@ export class SecurityResolversFacet { } const chain: ReadableIdsChain = { object, operation, security, context, answers: new Map(), driverOptions }; const where = await this.composeReadableIdsChain(chain, ast.where, sites, []); + passFixedReadLeaves(this, object, operation, where, context); return { ...ast, where }; } diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index c98d4cadfb4..fc3f7bb78a5 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -15,6 +15,7 @@ import { AUDIT_PROVENANCE_FIELDS, ENGINE_UPDATE_UPSERT_REMOVED, FILE_REFERENCE_T import type { DroppedFieldsEvent, FilterCondition, FilterLoweringOptions, HookContext, QueryAST, QueryAliasSlot, RecycleBinClearedReference, ServiceObject } from '@objectstack/spec/data'; import type { EngineFilterJudgement, ISecurityService } from '@objectstack/spec/contracts'; import { assertFilterIsMaterializable, assertListComparandShapes, collectComposableReadableIds, invalidFilterError } from './filter-comparand-shape.js'; +import { collectFixedReadLeaves } from './fixed-read-leaf-position.js'; import { assertResolvedTemporalTokensInRange, assertTemporalComparandsInterpretable } from './temporal-comparand-door.js'; import type { ResolvedTokenJudge } from './temporal-comparand-door.js'; import { assertTextOperatorTargetsAreStringCapable } from './text-operator-declared-type-door.js'; @@ -1054,6 +1055,10 @@ export function lowerWhereFilterArray( // reference into any other position is refused here by name, as the object // branch refuses it — first, before the doors below read it as a value. collectComposableReadableIds(object, operation, condition, 'where'); + // [ADR-0155 D1] The same for a fixed-read leaf the lowering carried by + // reference: `parseFilterAST` refuses one as a `$in` comparand (400), and + // any other position is refused here by name, before the doors below. + collectFixedReadLeaves(object, operation, condition, 'where'); // [#8296] Same door as the object branch above, on the LOWERED condition — // the array sugar (`[['is_open','=',true]]`) names fields too, and a gate on // one branch would answer one mistake two ways depending on the spelling. @@ -3737,6 +3742,23 @@ export function hookMatchesObject( return true; } +/** + * [ADR-0155 D4] Is `entry` a registration made for `objectName` BY NAME: one + * that {@link hookMatchesObject} dispatches for it AND whose `object` names it + * literally? A global registration (no `object`) or a `'*'` one covers the + * object without naming it, and is outside: the engine reads a registration + * by the object it names, and counts no global one, on the line + * `hasObjectMiddleware` draws for middleware. The dispatch half is + * {@link hookMatchesObject}'s alone, so an `excludeObjects` that subtracts the + * object takes it out here too. + */ +export function hookNamesObject( + entry: Pick, + objectName: string, +): boolean { + return hookTargetList(entry.object).includes(objectName) && hookMatchesObject(entry, objectName); +} + /** * [#5928] Registration-time refusal for the `excludeObjects` face, following * the sister ruling on empty hook targets (#4281 / #4001, ADR-0078 "no silently diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 215cfc4ea66..9507b0df593 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -35,6 +35,10 @@ import type { DroppedFieldsEvent, EngineUpdateOptions, HookContext, QueryAST } from '@objectstack/spec/data'; import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; import { collectComposableReadableIds } from './filter-comparand-shape.js'; +// [ADR-0155 D4] The fixed-read leaf seam reads the engine through the security +// resolvers' host, built once per engine, which carries every member it reads. +import { securityResolversHost } from './engine-facet-hosts.js'; +import { atFixedReadLeafDoor, passFixedReadLeaves } from './fixed-read-leaf-seam.js'; import { retiredSecretSlots, secretFieldsWritten } from './engine-secret-internal-fields.js'; import type { PendingSecretRow, SecretHandleSlot } from './engine-secret-internal-fields.js'; import { sealedSecretsNamedBy, secretKeysHoldingCallerValues, suppliedOverSealedSecrets } from './engine-update-sealed-secrets.js'; @@ -200,7 +204,7 @@ export class UpdateFacet { // [#5158] Lower before the by-id extraction below reads `where.id`: on an // array that read is `undefined` whatever the caller wrote, so an // `update({ where: [['id','=',x]] })` used to route to the multi-row path. - options = lowerWhereFilterArray(object, 'update', options, this._registry.getObject(object), this.relatedSchemaOf); + options = atFixedReadLeafDoor(this, () => lowerWhereFilterArray(object, 'update', options, this._registry.getObject(object), this.relatedSchemaOf)); // [ADR-0100] A predicate write is judged like a read: a non-system // caller's `where` evaluates no `secret` / `password` column. rejectCredentialEvaluation(object, 'update', options, options?.context, this.relatedSchemaOf); @@ -519,6 +523,11 @@ export class UpdateFacet { // wrote — here, at the executor's entry, because the prior-row reads // below reach the driver before `updateMany` does. collectComposableReadableIds(object, 'update', opCtx.ast?.where, 'where'); + // [ADR-0155 D4, ③ ruled A] The fixed-read leaves on the same AST, at the + // same point: the write form passes through in a predicate update's + // where, judged once, as the update, for its prior-row read and its + // write alike; every other leaf is refused before either runs. + passFixedReadLeaves(securityResolversHost.of(this.facade), object, 'update', opCtx.ast?.where, opCtx.context); // [#20082] The write's ONE permission resolution, shared by its option // gates and the formula fields on its response — asked at most once, and // only by the first of them that needs the map. diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index df822b86d9f..aa42cfe1d51 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -5322,6 +5322,7 @@ export class ObjectQL implements IObjectQLEngine { buildDriverOptions: (...a) => this.buildDriverOptions(...a), composeReadableIdsAtBoundary: (...a) => this.composeReadableIdsAtBoundary(...a), find: (...a) => this.find(...a), + facade: this, logger: this.logger, }; return count.call(host, object, query, options); } @@ -6145,6 +6146,7 @@ export class ObjectQL implements IObjectQLEngine { get formulaHopReads() { return engine.formulaHopReads; }, formulaOptionLabels: (...a) => engine.formulaOptionLabels(...a), hasObjectMiddleware: (...a) => engine.hasObjectMiddleware(...a), + get hooks() { return engine.hooks; }, get i18nService() { return engine.i18nService; }, get insertRecomputeListeners() { return engine.insertRecomputeListeners; }, get logger() { return engine.logger; }, diff --git a/packages/objectql/src/filter-comparand-shape.ts b/packages/objectql/src/filter-comparand-shape.ts index 218819faa03..2aaba5daa91 100644 --- a/packages/objectql/src/filter-comparand-shape.ts +++ b/packages/objectql/src/filter-comparand-shape.ts @@ -50,6 +50,7 @@ import { type ReadableIds, type ComposedReadableIds, } from '@objectstack/spec/data'; +import { ENGINE_FIXED_READ_LEAF_BRANDS, collectFixedReadLeaves } from './fixed-read-leaf-position.js'; /** * A plain object — filter STRUCTURE rather than a comparand. @@ -113,6 +114,17 @@ export function invalidFilterError(message: string): Error { * the engine will never compose — see {@link collectComposableReadableIds} for * the positions. An UNBRANDED copy never gets that far: the door refuses it as * a non-list comparand (`INVALID_FILTER` / 400). + * + * [ADR-0155 D4] It is also the one engine caller that names the fixed-read + * leaf brands (`admitFixedReadLeaves`, {@link ENGINE_FIXED_READ_LEAF_BRANDS}): + * such a leaf arrives composed and the engine's seam passes it through. It + * then refuses, by name, every one out of position or on the wrong verb + * (`fixed-read-leaf-position.ts#collectFixedReadLeaves`), a refusal the verb + * calling this door logs once per engine + * (`fixed-read-leaf-seam.ts#atFixedReadLeafDoor`); the recipient, the + * two classes and the driver's declaration are the executor boundary's + * (`fixed-read-leaf-seam.ts`). An unbranded copy is refused as a non-list, + * here, as before. */ export function assertListComparandShapes( object: string, @@ -120,7 +132,15 @@ export function assertListComparandShapes( node: unknown, path = 'where', ): void { - assertListComparandShapesAt(node, `${operation}('${object}')`, path, { admitReadableIds: true }); + // [ADR-0155 D1] A fixed-read leaf out of position is refused by name FIRST: + // it is branded, so the fault is the code that wrote it, and the door below + // would read one in a `$nin` or a list as a caller's non-list (400). The + // sites it returns are judged in full at the executor boundary. + collectFixedReadLeaves(object, operation, node, path); + assertListComparandShapesAt(node, `${operation}('${object}')`, path, { + admitReadableIds: true, + admitFixedReadLeaves: ENGINE_FIXED_READ_LEAF_BRANDS, + }); // The sites it returns are composed at the executor boundary, on the final // AST; here only its refusals are wanted. collectComposableReadableIds(object, operation, node, path); diff --git a/packages/objectql/src/fixed-read-leaf-position.ts b/packages/objectql/src/fixed-read-leaf-position.ts new file mode 100644 index 00000000000..8caf15107ba --- /dev/null +++ b/packages/objectql/src/fixed-read-leaf-position.ts @@ -0,0 +1,238 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 D1, D4] Where a FIXED-READ LEAF may sit, and on which verb: the + * half of the engine's executor seam for these leaves that needs nothing but + * the filter. The other half, the recipient, the two classes and the driver's + * declaration, is `fixed-read-leaf-seam.ts`, which asks this walk first; the + * module note there carries the whole seam. + * + * A module of its own because the comparand door + * (`filter-comparand-shape.ts#assertListComparandShapes`) asks it too, before + * the middleware chain, and the door sits below `engine-top-level.ts`, which + * the other half reads: one walk, at the door and at the boundary, with no + * import cycle. + * + * - **Position (D1).** Legal only as the `$in` comparand of `id` on the + * object it names: directly in that object's `where`, or inside the + * composed scope of a `ReadableIds` leaf whose parent is that object (the + * walk descends into every composed scope). It composes under `$and`, `$or` + * and `$not`. Every other position is refused: another field or object, an + * implicit-equality value, a `$eq` / `$nin` comparand, a list member, a node + * of its own, a nested-relation condition, a `having`, an aggregation's + * filter. + * - **Verb (D1, ③ ruled A).** The read form on `find`, `findOne`, `count` and + * `aggregate`, and inside every composed scope (the `where` of a read of its + * parent). The write form only in the `where` of a predicate `update`, where + * the read form is refused. `delete` admits neither. + * + * Every refusal is ADR-0139 D3's envelope, `INTERNAL_ERROR` / 500, ⛔ never + * `INVALID_FILTER`: no request can spell the leaf, so the fault is the + * in-process code that wrote it. `index.ts` re-exports nothing from this + * module. + */ + +import { + SHARED_RECORD_IDS_BRAND, + fixedReadLeafNameOf, + isComposedReadableIds, + isFixedReadLeaf, + type FixedReadLeaf, + type FixedReadLeafBrand, + type FixedReadLeafName, +} from '@objectstack/spec/data'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { describeFixedReadLeaf, fixedReadLeafRefusal, type FixedReadLeafRefusalError } from '@objectstack/core'; + +/** + * [ADR-0155 D4] The brands the engine's comparand door admits as a `$in` + * comparand (`admitFixedReadLeaves`): ONE list that names its brands, never a + * flag per brand. ADR-0147's leaf joins it on the card that adds that leaf to + * the seam, with its row in {@link LEAF_RULES}. + */ +export const ENGINE_FIXED_READ_LEAF_BRANDS: readonly FixedReadLeafBrand[] = Object.freeze([SHARED_RECORD_IDS_BRAND]); + +/** The evaluator the seam names in its own refusals. */ +export const FIXED_READ_LEAF_SEAM = 'objectql'; + +/** The verbs whose `where` may carry the read form. */ +const READ_VERBS: ReadonlySet = new Set(['find', 'findOne', 'count', 'aggregate']); + +/** + * What the seam reads per leaf, one row per leaf name: the meaning of each is + * the leaf's own (ADR-0155 D4: per leaf, never shared), and the seam applies + * one rule over all of them. + */ +export interface FixedReadLeafRules { + /** The field and object the leaf's `$in` must sit on. */ + readonly position: (leaf: FixedReadLeaf) => { readonly field: string; readonly object: string }; + /** `write` for the form a predicate update carries, `read` for every other. */ + readonly form: (leaf: FixedReadLeaf) => 'read' | 'write'; + /** Does the context the operation runs under admit every identity the leaf names (a system context aside)? */ + readonly principalAdmitted: (leaf: FixedReadLeaf, context: ExecutionContext | undefined) => boolean; +} + +const LEAF_RULES: Readonly> = Object.freeze({ + SharedRecordIds: Object.freeze({ + position: (leaf: FixedReadLeaf) => ({ field: 'id', object: leaf.object }), + form: (leaf: FixedReadLeaf) => (leaf.accessLevels === undefined ? 'read' : 'write'), + // Its one identity, the recipient: the context's user, or its delegator. + principalAdmitted: (leaf: FixedReadLeaf, context: ExecutionContext | undefined) => + leaf.recipient === context?.userId || leaf.recipient === context?.onBehalfOf?.userId, + }), +}); + +/** The rules of the leaf `leaf` is. */ +export function fixedReadLeafRulesOf(leaf: FixedReadLeaf): FixedReadLeafRules { + // `isFixedReadLeaf` vouched for the brand, so the name is one of the table's keys. + return LEAF_RULES[fixedReadLeafNameOf(leaf) as FixedReadLeafName]; +} + +/** One fixed-read leaf the seam may hand to a driver: the comparand of the `$in` at `at`. */ +export interface FixedReadLeafSite { + readonly leaf: FixedReadLeaf; + readonly at: string; +} + +const NO_SITES: readonly FixedReadLeafSite[] = Object.freeze([]); + +/** Every refusal the seam built, so the boundary logs the seam's refusals and nothing else. */ +const SEAM_REFUSALS = new WeakSet(); + +/** Did the seam build `err` ({@link fixedReadLeafSeamRefusal})? */ +export function isFixedReadLeafSeamRefusal(err: unknown): boolean { + return err instanceof Error && SEAM_REFUSALS.has(err); +} + +/** + * The seam's refusal of the leaf at `at` in an operation on `object`: the + * composition-fault envelope (`@objectstack/core`'s `fixedReadLeafRefusal`), + * naming the seam, the operation, the leaf, `why` and the remedy. + */ +export function fixedReadLeafSeamRefusal(object: string, operation: string, at: string, leaf: FixedReadLeaf, why: string): FixedReadLeafRefusalError { + const err = fixedReadLeafRefusal( + FIXED_READ_LEAF_SEAM, + `${operation}('${object}'): ${describeFixedReadLeaf(at, leaf)}, and ${why} The operation was NOT run and no driver was asked.`, + object, + ); + SEAM_REFUSALS.add(err); + return err; +} + +/** A plain filter object or a list: what the walk descends into. A `Date` or class instance holds no filter. */ +function isWalkable(value: unknown): value is object { + if (value === null || typeof value !== 'object') return false; + if (Array.isArray(value)) return true; + const proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +/** + * [ADR-0155 D1] Every fixed-read leaf in `node` the seam may hand to a + * driver, in walk order, and a loud refusal (`INTERNAL_ERROR` / 500) for the + * first leaf out of position or on the wrong verb. `path` is the clause + * (`where`, `having`, `aggregations[i].filter`); `at` labels the root and + * defaults to it. Read-only and cycle-safe; a filter with no leaf answers a + * shared empty list. + * + * It judges the leaf's position, its verb and its form only: the recipient, + * the classes and the declaration are `fixed-read-leaf-seam.ts`'s + * `passFixedReadLeaves`, which asks this walk first. + */ +export function collectFixedReadLeaves( + object: string, + operation: string, + node: unknown, + path = 'where', + at: string = path, +): readonly FixedReadLeafSite[] { + let sites: FixedReadLeafSite[] | undefined; + const onPath = new Set(); + + const misplaced = (leaf: FixedReadLeaf, here: string): Error => { + const { field, object: named } = fixedReadLeafRulesOf(leaf).position(leaf); + return fixedReadLeafSeamRefusal(object, operation, here, leaf, path === 'where' + ? `the leaf is legal only as the $in comparand of ${field} on '${named}', the object it names, in that ` + + `object's where or inside the composed scope of a ReadableIds leaf over it, under $and, $or and $not; ` + + `its producer wrote it elsewhere. Write it there as { ${field}: { $in: leaf } }.` + : `the leaf is legal only in the where of a read, never in ${path}: ` + + `${path === 'having' ? 'having filters the aggregated rows' : "an aggregation's filter is evaluated in memory"}. ` + + 'Narrow the rows in where instead.'); + }; + + // Any leaf anywhere inside `value` is out of position. + const scan = (value: unknown, here: string): void => { + if (isFixedReadLeaf(value)) throw misplaced(value, here); + if (isComposedReadableIds(value)) return scan(value.scope, `${here}.scope`); + if (!isWalkable(value) || onPath.has(value)) return; + onPath.add(value); + try { + if (Array.isArray(value)) value.forEach((item, i) => scan(item, `${here}[${i}]`)); + else for (const key of Object.keys(value)) scan((value as Record)[key], `${here}.${key}`); + } finally { + onPath.delete(value); + } + }; + + const judge = (leaf: FixedReadLeaf, field: string, scopeObject: string, nested: boolean, here: string): void => { + if (path !== 'where') throw misplaced(leaf, here); + if (!READ_VERBS.has(operation) && operation !== 'update') { + throw fixedReadLeafSeamRefusal(object, operation, here, leaf, + `no fixed-read leaf is admitted on ${operation}: a read's where carries the read form and a predicate update's ` + + `where the write form, and ${operation} is neither. Write the predicate without the leaf.`); + } + const position = fixedReadLeafRulesOf(leaf).position(leaf); + if (field !== position.field || scopeObject !== position.object) throw misplaced(leaf, here); + const wanted = nested || READ_VERBS.has(operation) ? 'read' : 'write'; + const form = fixedReadLeafRulesOf(leaf).form(leaf); + if (form !== wanted) { + throw fixedReadLeafSeamRefusal(object, operation, here, leaf, + `it is the ${form} form, where ${nested ? 'a composed scope, the where of a read of its parent,' : `the where of ${operation}`} ` + + `admits only the ${wanted} form: the write form belongs in a predicate update's where alone, the read form ` + + 'everywhere else a leaf may sit. Build the form for this verb.'); + } + (sites ??= []).push({ leaf, at: here }); + }; + + // A filter node: logical operators over field conditions. + const visitNode = (value: unknown, scopeObject: string, nested: boolean, here: string): void => { + if (isFixedReadLeaf(value)) throw misplaced(value, here); + if (!isWalkable(value) || Array.isArray(value)) return scan(value, here); + if (onPath.has(value)) return; + onPath.add(value); + try { + for (const key of Object.keys(value)) { + const child = (value as Record)[key]; + const there = `${here}.${key}`; + if ((key === '$and' || key === '$or') && Array.isArray(child)) { + child.forEach((item, i) => visitNode(item, scopeObject, nested, `${there}[${i}]`)); + } else if (key === '$not') { + visitNode(child, scopeObject, nested, there); + } else if (key.startsWith('$')) { + scan(child, there); + } else { + visitField(key, child, scopeObject, nested, there); + } + } + } finally { + onPath.delete(value); + } + }; + + // One field's condition: a `$in` holding a leaf or a composed scope, or anything else. + const visitField = (field: string, value: unknown, scopeObject: string, nested: boolean, here: string): void => { + if (isFixedReadLeaf(value)) throw misplaced(value, here); + if (!isWalkable(value) || Array.isArray(value) || isComposedReadableIds(value)) return scan(value, here); + for (const op of Object.keys(value)) { + const comparand = (value as Record)[op]; + const there = `${here}.${op}`; + if (op === '$in' && isFixedReadLeaf(comparand)) judge(comparand, field, scopeObject, nested, there); + else if (op === '$in' && isComposedReadableIds(comparand)) { + visitNode(comparand.scope, comparand.object, true, `${there}.scope`); + } else scan(comparand, there); + } + }; + + visitNode(node, object, false, at); + return sites ?? NO_SITES; +} diff --git a/packages/objectql/src/fixed-read-leaf-seam.ts b/packages/objectql/src/fixed-read-leaf-seam.ts new file mode 100644 index 00000000000..24ffa64865d --- /dev/null +++ b/packages/objectql/src/fixed-read-leaf-seam.ts @@ -0,0 +1,242 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 D1, D4] The engine's executor seam for the FIXED-READ LEAVES + * (`@objectstack/spec/data`'s `isFixedReadLeaf`: `SharedRecordIds` today, + * ADR-0147's leaf on the card that adds it), built once in the two-leaf shape. + * + * A fixed-read leaf arrives composed: the engine composes nothing for it. The + * seam checks where it sits, on which verb and for whom, recognises the two + * classes it is never handed to a driver in, consults the driver's + * declaration, and hands the leaf to the driver as it stands, by reference. + * Every refusal is ADR-0139 D3's envelope, `INTERNAL_ERROR` / 500 + * (`@objectstack/core`'s `fixedReadLeafRefusal`), ⛔ never `INVALID_FILTER`: + * no request can spell the leaf, so the fault is a composition's. + * + * ## Where it runs + * + * - **The comparand door** (`filter-comparand-shape.ts#assertListComparandShapes`: + * both branches of `lowerWhereFilterArray`, an aggregate's `having` and its + * aggregations' filters). The door admits a leaf of a brand in + * `ENGINE_FIXED_READ_LEAF_BRANDS` as a `$in` comparand, then + * `collectFixedReadLeaves` (`fixed-read-leaf-position.ts`) refuses, by + * name, every leaf out of position or on the wrong verb, before a later + * door reads it as a value. + * - **The executor boundary** of a read verb + * (`engine-security-resolvers.ts#composeReadableIdsAtBoundary`), on the + * FINAL AST after the middleware chain, the before-hooks and the + * `ReadableIds` composition, immediately before the driver call; and the + * **executor's entry** of an `update` and a `delete`, before their prior-row + * reads reach the driver. There {@link passFixedReadLeaves} runs every + * check, so a leaf a middleware or a hook wrote meets the same rules as one + * a caller wrote, and a leaf inside a composed scope meets them too. + * + * ## The rules + * + * - **Position and verb (D1, ③ ruled A)** — `fixed-read-leaf-position.ts`. + * - **Recipient (D4).** The leaf is admitted only when the identity it names + * is the user of the context the operation runs under, or that context's + * delegator (ADR-0090 D10, `onBehalfOf.userId`); a system context + * (`isSystem: true`) is the one exemption. Absence is never system. ⛔ The + * check compares and never replaces: the recipient stays the producer's. + * - **The two classes (D4, ② as ruled)** — {@link fixedReadLeafClassOf}. + * - **The declaration (D4, Q2 as ruled).** The leaf reaches the driver only + * when its `DriverCapabilities.fixedReadLeaves` names it + * ({@link driverEvaluatesFixedReadLeaf}); otherwise the operation is + * refused before the driver is called. ⛔ No list fallback, ever. + * + * ## The log + * + * The refusal is logged at `error` once per evaluator wherever it occurs + * (`@objectstack/core`'s `logRefusalOnce`): once per driver for a declaration + * it lacks, once per engine for every other fault. The door holds no logger, + * so each verb runs its door calls through {@link atFixedReadLeafDoor}, which + * logs a door refusal on the SAME per-engine flag the boundary's refusals use: + * a refusal at the door and one at the boundary log one line between them. + * + * ⛔ No boot refusal and no producer here: the class-② boot check and R2's + * share-arm answer land with the producer (ADR-0155 plan step 6), and until + * then nothing on main writes the leaf. `index.ts` re-exports nothing from + * this module. + */ + +import { fixedInnerReadOf, fixedReadLeafNameOf, type FixedReadLeaf, type FixedReadLeafName } from '@objectstack/spec/data'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { describeFixedReadLeaf, fixedReadLeafRefusal, logRefusalOnce, type ReadableIdsRefusalLog } from '@objectstack/core'; +import { hookNamesObject, type HookEntry } from './engine-top-level.js'; +import { + FIXED_READ_LEAF_SEAM, + collectFixedReadLeaves, + fixedReadLeafRulesOf, + fixedReadLeafSeamRefusal, + isFixedReadLeafSeamRefusal, +} from './fixed-read-leaf-position.js'; +import { driverNameOf } from './relation-semi-join.js'; + +/** The hook events whose registration for the inner table BY NAME is D4's second class. */ +const FIND_HOOK_EVENTS = Object.freeze(['beforeFind', 'afterFind'] as const); + +/** + * [ADR-0155 D4, ② as ruled] Does `driver` evaluate the fixed-read leaf + * `name`? Its `DriverCapabilities.fixedReadLeaves` lists the name; absence is + * none. The one reader of the declaration: the seam's consult now, and the + * producer's up-front answer (R2) when it lands (ADR-0155 plan step 6), which + * reaches the driver through `IDataEngine.getDriverForObject`. + */ +export function driverEvaluatesFixedReadLeaf(driver: { readonly supports?: unknown } | undefined, name: FixedReadLeafName): boolean { + const supports = driver?.supports; + if (supports === null || typeof supports !== 'object') return false; + const names = (supports as { fixedReadLeaves?: unknown }).fixedReadLeaves; + return Array.isArray(names) && names.includes(name); +} + +/** What the seam reads off the engine: `SecurityResolversHost` carries every member. */ +export interface FixedReadLeafSeamHost { + /** The engine itself: the driver an operation dispatches to, and the key of its once-per-engine log. */ + readonly facade: { getDriverForObject(object: string): { readonly name?: unknown; readonly supports?: unknown } | undefined }; + readonly logger: ReadableIdsRefusalLog; + readonly hooks: ReadonlyMap[]>; + hasObjectMiddleware(object: string): boolean; + resolveDatasourceBinding(object: string): { readonly datasource: string } | undefined; +} + +/** Which of D4's two classes a leaf falls in, and what names it. */ +export type FixedReadLeafClass = + | { readonly class: 'other-datasource'; readonly object: string; readonly table: string; readonly objectDatasource: string | undefined; readonly tableDatasource: string | undefined } + | { readonly class: 'registration-by-name'; readonly table: string; readonly registration: string }; + +/** + * [ADR-0155 D4, ② as ruled] Which of the two classes the seam recognises + * `leaf` falls in, or `undefined` when neither; the ONE recognition, which the + * analytics native compiler asks before it compiles (ADR-0155 plan step 5). + * + * 1. **Another datasource**: the object the leaf names is bound to another + * datasource than the table its fixed inner read reads + * (`resolveDatasourceBinding`), so no driver evaluates the subquery. + * 2. **A registration for the table BY NAME**: an object-scoped middleware + * (`hasObjectMiddleware`) or a `beforeFind` / `afterFind` hook that names + * it (`hookNamesObject`), which today's read of the table runs and the + * subquery would read around. A registration that names no object, or + * `'*'`, is outside the class (D4's boundary). + * + * At this step both answer with the refusal (R1). ⛔ The seam never reads + * around either. + */ +export function fixedReadLeafClassOf(host: FixedReadLeafSeamHost, leaf: FixedReadLeaf): FixedReadLeafClass | undefined { + const { table } = fixedInnerReadOf(leaf); + const object = fixedReadLeafRulesOf(leaf).position(leaf).object; + const objectDatasource = host.resolveDatasourceBinding(object)?.datasource; + const tableDatasource = host.resolveDatasourceBinding(table)?.datasource; + if (objectDatasource !== tableDatasource) return { class: 'other-datasource', object, table, objectDatasource, tableDatasource }; + if (host.hasObjectMiddleware(table)) { + return { class: 'registration-by-name', table, registration: `an object-scoped middleware registered for '${table}'` }; + } + for (const event of FIND_HOOK_EVENTS) { + if ((host.hooks.get(event) ?? []).some((entry) => hookNamesObject(entry, table))) { + return { class: 'registration-by-name', table, registration: `a ${event} hook registered for '${table}' by name` }; + } + } + return undefined; +} + +/** The once-per-evaluator log's flags: one per engine for the seam's faults, one per driver for a declaration it lacks. */ +const LOGGED = new WeakMap(); + +function flagOf(evaluator: object): { logged: boolean } { + let flag = LOGGED.get(evaluator); + if (flag === undefined) LOGGED.set(evaluator, (flag = { logged: false })); + return flag; +} + +/** What the door's half of the log reads: the engine its flag is keyed on, and the engine's logger. */ +export interface FixedReadLeafDoorHost { + readonly facade: object; + readonly logger: ReadableIdsRefusalLog | undefined; +} + +/** Log `err` once for the engine `host.facade` names when it is the seam's refusal; any other error is not this log's. */ +function logSeamRefusalOnce(host: FixedReadLeafDoorHost, err: unknown): void { + if (isFixedReadLeafSeamRefusal(err)) logRefusalOnce(err as Error, host.logger, flagOf(host.facade), 'evaluator'); +} + +/** + * [ADR-0155 D4] Run `door`, one of a verb's door calls (`lowerWhereFilterArray`, + * or `assertListComparandShapes` on `having` or an aggregation's filter), and + * when it throws the seam's refusal for a fixed-read leaf out of position or on + * the wrong verb, log it at `error` on the engine's flag, the one + * {@link passFixedReadLeaves} logs on, then re-throw it unchanged. Any other + * error, an unbranded copy's `INVALID_FILTER` / 400 among them, passes through + * unlogged here. + */ +export function atFixedReadLeafDoor(host: FixedReadLeafDoorHost, door: () => T): T { + try { + return door(); + } catch (err) { + logSeamRefusalOnce(host, err); + throw err; + } +} + +/** + * [ADR-0155 D4] The executor seam's pass-through: judge every fixed-read leaf + * in `node` (an operation's `where`, or the `path` clause) for an operation on + * `object` under `context`, and return when each may be handed to the driver + * as it stands; otherwise throw the refusal, logged once per evaluator. + * + * It edits nothing: an admitted leaf reaches the driver by reference. + */ +export function passFixedReadLeaves( + host: FixedReadLeafSeamHost, + object: string, + operation: string, + node: unknown, + context: ExecutionContext | undefined, + path = 'where', +): void { + let sites: ReturnType; + try { + sites = collectFixedReadLeaves(object, operation, node, path); + for (const { leaf, at } of sites) { + if (context?.isSystem !== true && !fixedReadLeafRulesOf(leaf).principalAdmitted(leaf, context)) { + throw fixedReadLeafSeamRefusal(object, operation, at, leaf, + 'the identity it names is neither the user of the context this operation runs under nor that context\'s ' + + 'delegator, and the context is not a system context: a scope that arrives composed is trusted only for ' + + 'the principal it was composed for, and the engine never replaces it. Build the scope under this context.'); + } + const recognised = fixedReadLeafClassOf(host, leaf); + if (recognised?.class === 'other-datasource') { + throw fixedReadLeafSeamRefusal(object, operation, at, leaf, + `'${recognised.object}' is bound to datasource '${String(recognised.objectDatasource)}' while ` + + `'${recognised.table}' is bound to '${String(recognised.tableDatasource)}': no driver evaluates the fixed ` + + `inner read across two datasources. Bind '${recognised.object}' to the datasource of '${recognised.table}', ` + + 'or have the producer write no leaf for it.'); + } + if (recognised?.class === 'registration-by-name') { + throw fixedReadLeafSeamRefusal(object, operation, at, leaf, + `the host carries ${recognised.registration}, which a read of '${recognised.table}' runs and the fixed inner ` + + `read would read around: the engine never reads around it. Remove that registration for ` + + `'${recognised.table}', or have the producer write no leaf on this host.`); + } + } + } catch (err) { + logSeamRefusalOnce(host, err); + throw err; + } + if (sites.length === 0) return; + const driver = host.facade.getDriverForObject(object); + for (const { leaf, at } of sites) { + const name = fixedReadLeafNameOf(leaf) as FixedReadLeafName; + if (driverEvaluatesFixedReadLeaf(driver, name)) continue; + const err = fixedReadLeafRefusal( + FIXED_READ_LEAF_SEAM, + `${operation}('${object}'): ${describeFixedReadLeaf(at, leaf)}, and driver '${driverNameOf(driver)}' does not ` + + `evaluate it: its supports.fixedReadLeaves does not list ${name}. The operation was NOT run and no driver ` + + `was asked, rather than answer a short or an unscoped set. Bind '${object}' to a driver that evaluates ` + + `${name}, or have the producer write no leaf for it; a driver lists the name only once its filter compiler ` + + 'evaluates the leaf exactly.', + object, + ); + logRefusalOnce(err, host.logger, flagOf((driver as object | undefined) ?? host.facade), 'evaluator'); + throw err; + } +} diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index c997f9b4f02..3e01b23b4e8 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -315,6 +315,7 @@ "FILTER_TEXT_ROWS (const)", "FILTER_TOKEN_WRAPPED_RE (const)", "FIXED_READ_LEAF_CASE_SETS (const)", + "FIXED_READ_LEAF_NAMES (const)", "FORMER_CREDENTIAL_ALIASES (const)", "FORMULA_RETURN_TYPE_AS_FIELD_TYPE (const)", "FederationOnlyDriverId (type)", @@ -386,6 +387,7 @@ "FixedReadLeafBrand (type)", "FixedReadLeafCaseSet (interface)", "FixedReadLeafMatchesCase (interface)", + "FixedReadLeafName (type)", "FixedReadLeafRow (type)", "FixedReadLeafSeamCase (interface)", "FixedReadLeafSeamContext (interface)", @@ -1018,6 +1020,7 @@ "filterSubtreeProvenanceOf (function)", "fixedInnerReadOf (function)", "fixedReadLeafBrandOf (function)", + "fixedReadLeafNameOf (function)", "foldAsciiCase (function)", "foldQueryAliasSlots (function)", "formatUnknownAuthoringKey (function)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index b26e8b55698..cfa1f92021e 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -193,6 +193,7 @@ "data/DriverCapabilities:connectionPooling [RETIRED]", "data/DriverCapabilities:create [RETIRED]", "data/DriverCapabilities:delete [RETIRED]", + "data/DriverCapabilities:fixedReadLeaves", "data/DriverCapabilities:fullTextSearch [RETIRED]", "data/DriverCapabilities:geospatialQuery [RETIRED]", "data/DriverCapabilities:indexes [RETIRED]", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 1ea9ebaf021..4ce918d354a 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -310,6 +310,7 @@ "FILTER_TEXT_ROWS": "src/data/filter-text-conformance.ts#FILTER_TEXT_ROWS (const)", "FILTER_TOKEN_WRAPPED_RE": "src/data/context-tokens.zod.ts#FILTER_TOKEN_WRAPPED_RE (const)", "FIXED_READ_LEAF_CASE_SETS": "src/data/fixed-read-leaf-conformance.ts#FIXED_READ_LEAF_CASE_SETS (const)", + "FIXED_READ_LEAF_NAMES": "src/data/fixed-read-leaf.ts#FIXED_READ_LEAF_NAMES (const)", "FORMER_CREDENTIAL_ALIASES": "src/data/driver/common.zod.ts#FORMER_CREDENTIAL_ALIASES (const)", "FORMULA_RETURN_TYPE_AS_FIELD_TYPE": "src/data/filter-text-operator-declared-type.ts#FORMULA_RETURN_TYPE_AS_FIELD_TYPE (const)", "FederationOnlyDriverId": "src/data/driver/config-registry.zod.ts#FederationOnlyDriverId (type)", @@ -377,6 +378,7 @@ "FixedReadLeafBrand": "src/data/fixed-read-leaf.ts#FixedReadLeafBrand (type)", "FixedReadLeafCaseSet": "src/data/fixed-read-leaf-conformance.ts#FixedReadLeafCaseSet (interface)", "FixedReadLeafMatchesCase": "src/data/fixed-read-leaf-conformance.ts#FixedReadLeafMatchesCase (interface)", + "FixedReadLeafName": "src/data/fixed-read-leaf.ts#FixedReadLeafName (type)", "FixedReadLeafRow": "src/data/fixed-read-leaf-conformance.ts#FixedReadLeafRow (type)", "FixedReadLeafSeamCase": "src/data/fixed-read-leaf-conformance.ts#FixedReadLeafSeamCase (interface)", "FixedReadLeafSeamContext": "src/data/fixed-read-leaf-conformance.ts#FixedReadLeafSeamContext (interface)", @@ -1003,6 +1005,7 @@ "filterSubtreeProvenanceOf": "src/data/filter-subtree-provenance.ts#filterSubtreeProvenanceOf (function)", "fixedInnerReadOf": "src/data/fixed-read-leaf.ts#fixedInnerReadOf (function)", "fixedReadLeafBrandOf": "src/data/fixed-read-leaf.ts#fixedReadLeafBrandOf (function)", + "fixedReadLeafNameOf": "src/data/fixed-read-leaf.ts#fixedReadLeafNameOf (function)", "foldAsciiCase": "src/data/filter.zod.ts#foldAsciiCase (function)", "foldQueryAliasSlots": "src/data/data-engine.zod.ts#foldQueryAliasSlots (function)", "formatUnknownAuthoringKey": "src/data/authoring-key-lint.ts#formatUnknownAuthoringKey (function)", diff --git a/packages/spec/src/data/driver.test.ts b/packages/spec/src/data/driver.test.ts index ef2200de112..7275e4c6d79 100644 --- a/packages/spec/src/data/driver.test.ts +++ b/packages/spec/src/data/driver.test.ts @@ -8,6 +8,7 @@ import { type DriverOptions, driverSupportsTransactions, } from './driver.zod'; +import { FIXED_READ_LEAF_NAMES } from './fixed-read-leaf'; /** * The 31 capability bits retired in 17.0.0 (#4634, ADR-0049 enforce-or-remove). @@ -72,6 +73,11 @@ const RETIRED_BITS = [ * says whether a driver's filter compiler understands a composed `ReadableIds` * leaf (every driver has `find()`), and the engine's nested-relation lowering * reads it to plan the semi-join or refuse the condition up front. + * + * [ADR-0155 D4] `fixedReadLeaves` is the ninth, and a list rather than a bit: + * the names of the fixed-read leaves the filter compiler evaluates. No method + * says that either, and the engine's executor seam reads it to hand such a + * leaf to the driver or refuse the operation before calling it. */ const LIVE_BITS = [ 'queryDateGranularity', @@ -82,6 +88,7 @@ const LIVE_BITS = [ 'lockRows', 'zonedDateBucketing', 'readableIdsLeaf', + 'fixedReadLeaves', ] as const; describe('DriverCapabilitiesSchema', () => { @@ -95,6 +102,7 @@ describe('DriverCapabilitiesSchema', () => { lockRows: true, zonedDateBucketing: true, readableIdsLeaf: true, + fixedReadLeaves: ['SharedRecordIds'], }; expect(() => DriverCapabilitiesSchema.parse(capabilities)).not.toThrow(); @@ -119,6 +127,9 @@ describe('DriverCapabilitiesSchema', () => { // [#33876] Absent = no semi-join leaf: the engine refuses a nested-relation // condition on a read verb up front. expect(parsed).not.toHaveProperty('readableIdsLeaf'); + // [ADR-0155 D4] Absent = no fixed-read leaf: the engine's seam refuses an + // operation carrying one before calling the driver. + expect(parsed).not.toHaveProperty('fixedReadLeaves'); }); it('refuses a non-boolean aggregationFilter', () => { @@ -137,7 +148,21 @@ describe('DriverCapabilitiesSchema', () => { expect(DriverCapabilitiesSchema.safeParse({ readableIdsLeaf: 'yes' }).success).toBe(false); }); - it('declares exactly the audited shape: 8 live bits + 31 tombstones', () => { + it('accepts every fixed-read leaf name and an empty list, and keeps the names it was given', () => { + expect(DriverCapabilitiesSchema.parse({ fixedReadLeaves: [...FIXED_READ_LEAF_NAMES] }).fixedReadLeaves) + .toEqual([...FIXED_READ_LEAF_NAMES]); + expect(DriverCapabilitiesSchema.parse({ fixedReadLeaves: [] }).fixedReadLeaves).toEqual([]); + }); + + it('refuses a fixedReadLeaves that is not a list of fixed-read leaf names', () => { + // A bit is not the declaration: the key names the leaves it covers. + expect(DriverCapabilitiesSchema.safeParse({ fixedReadLeaves: true }).success).toBe(false); + // `ReadableIds` is not a fixed-read leaf, and a brand's symbol key is not its name. + expect(DriverCapabilitiesSchema.safeParse({ fixedReadLeaves: ['ReadableIds'] }).success).toBe(false); + expect(DriverCapabilitiesSchema.safeParse({ fixedReadLeaves: ['objectstack.filter.sharedRecordIds'] }).success).toBe(false); + }); + + it('declares exactly the audited shape: 9 live bits + 31 tombstones', () => { const shape = (DriverCapabilitiesSchema as unknown as { shape: Record }).shape; const keys = Object.keys(shape).sort(); expect(keys).toEqual([...RETIRED_BITS, ...LIVE_BITS].slice().sort()); @@ -238,7 +263,7 @@ describe('tsc channel: the retired bits are unwritable in DriverCapabilities', ( const props = new Map(capsType.getProperties().map((p) => [p.getName(), p])); // Anti-vacuity: the walked shape is the audited key set — 31 tombstones - // plus the live bits (8 since `readableIdsLeaf`). + // plus the live bits (9 since `fixedReadLeaves`). expect([...props.keys()].sort()).toEqual([...RETIRED_BITS, ...LIVE_BITS].slice().sort()); const decl = capsAlias!.declarations?.[0]; diff --git a/packages/spec/src/data/driver.zod.ts b/packages/spec/src/data/driver.zod.ts index 44419122ef0..3cc22e1e517 100644 --- a/packages/spec/src/data/driver.zod.ts +++ b/packages/spec/src/data/driver.zod.ts @@ -4,6 +4,7 @@ import { z } from 'zod'; import { QuerySchema, DateGranularity } from '../data/query.zod'; import { IsolationLevelEnum } from '../shared/enums.zod'; import { retiredKey } from '../shared/retired-key'; +import { FIXED_READ_LEAF_NAMES } from './fixed-read-leaf'; /** * Common Driver Options @@ -196,6 +197,12 @@ const capRemoved = (key: string, mechanism: string) => * 400) on one that does not, before any related read runs. The analytics * relation group join reads the same bit for a dimension through a lookup * (`INVALID_QUERY` / 400 without it). + * - `fixedReadLeaves` — the fixed-read leaves (ADR-0155 D4) the filter + * compiler evaluates, by name: the engine's executor seam hands such a leaf + * to a driver that lists its name and refuses it (`INTERNAL_ERROR` / 500) + * before calling one that does not. A list, not a bit, because one key + * covers every fixed-read leaf; separate from `readableIdsLeaf`, because a + * `ReadableIds` leaf is not one. * * Everything else IS the method: aggregate pushdown gates on * `typeof driver.aggregate === 'function'`, schema sync on @@ -474,7 +481,47 @@ export const DriverCapabilitiesSchema = lazySchema(() => z.object({ * * Optional; absence means `false`, like `batchSchemaSync`. */ - readableIdsLeaf: z.boolean().optional().describe('The filter compiler compiles (or, in process, evaluates) a composed `ReadableIds` semi-join leaf (absence = false: the engine refuses a nested-relation condition on a read verb up front, INVALID_FILTER / 400)'), + readableIdsLeaf: z.boolean().optional().describe('The filter compiler compiles (or, in process, evaluates) a composed `ReadableIds` semi-join leaf (absence = false: the engine refuses a nested-relation condition on a read verb up front, INVALID_FILTER / 400). A `ReadableIds` leaf is not a fixed-read leaf, so `fixedReadLeaves` neither implies nor is implied by this bit'), + + /** + * [ADR-0155 D4, O1 as ruled] The fixed-read leaves this driver's filter + * compiler evaluates exactly, by name (`FIXED_READ_LEAF_NAMES`, + * `./fixed-read-leaf.ts`): `SharedRecordIds` today, and ADR-0147's leaf on + * the card that adds it. A fixed-read leaf is a branded `$in` comparand that + * arrives composed and denotes `field IN (SELECT column FROM table WHERE + * AND column IS NOT NULL AND column <> '')` under system + * authority (`fixedInnerReadOf`). + * + * What the engine does with it: its executor seam, after the position, + * verb and recipient checks, hands a fixed-read leaf to the driver as it + * stands only when this list holds the leaf's name; when it does not, the + * engine REFUSES the operation before any driver is called, `INTERNAL_ERROR` + * / 500, naming the driver, the leaf and the remedy (ADR-0155 Q2: R1, and + * the declaration R2 reads up front). ⛔ No list fallback: the engine never + * substitutes an id list for a leaf a driver does not name. + * + * Why a list and not a bit: one key covers every fixed-read leaf, as the + * comparand door admits them through one option that names its brands + * (`admitFixedReadLeaves`), so ADR-0147's leaf joins by adding a name, never + * a second key. Why a name and not the brand: a capability is declared data, + * and a `unique symbol` cannot be one. + * + * How it relates to `readableIdsLeaf`: the two stay separate. A + * `ReadableIds` leaf is composed by the engine from the caller's read scope + * and compiles to a subquery over that scope; a fixed-read leaf arrives + * composed and compiles to a fixed inner read of one platform table, and + * `isFixedReadLeaf` does not admit a `ReadableIds` leaf. A driver that + * evaluates both declares both: a fixed-read leaf inside a composed + * `ReadableIds` scope needs both, because a driver without + * `readableIdsLeaf` refuses the composed leaf that carries it (ADR-0139 D3). + * + * ⛔ Not a way to say "this leaf, today": it describes the driver's filter + * compiler, is read at dispatch time, and a driver whose transport + * evaluates a leaf only sometimes does not list it. + * + * Optional; absence means none, like `readableIdsLeaf`'s `false`. + */ + fixedReadLeaves: z.array(z.enum(FIXED_READ_LEAF_NAMES)).optional().describe('The fixed-read leaves (ADR-0155 D4) the filter compiler evaluates exactly, by name, e.g. ["SharedRecordIds"] (absence = none: the engine refuses an operation carrying such a leaf before calling the driver, INTERNAL_ERROR / 500). Separate from `readableIdsLeaf`: a `ReadableIds` leaf is not a fixed-read leaf'), // ============================================================================ // Retired capability bits (#4634, ADR-0049 enforce-or-remove) — 17.0.0 diff --git a/packages/spec/src/data/fixed-read-leaf-conformance.test.ts b/packages/spec/src/data/fixed-read-leaf-conformance.test.ts index fc02500f6e8..bb38d67c783 100644 --- a/packages/spec/src/data/fixed-read-leaf-conformance.test.ts +++ b/packages/spec/src/data/fixed-read-leaf-conformance.test.ts @@ -196,15 +196,23 @@ function seamVerdict(c: FixedReadLeafSeamCase, reading: SeamReading): 'admits' | || (reading !== 'no-verb-rule' && !verbOk) || (reading !== 'no-recipient-rule' && !recipientOk)) refused = true; }; + // A leaf anywhere but a `$in` comparand of a field of the where is out of position. + const misplaced = () => { + if (reading !== 'no-position-rule') refused = true; + }; const walk = (node: unknown, object: string, nested: boolean): void => { if (node === null || typeof node !== 'object') return; + if (isSharedRecordIds(node)) return misplaced(); for (const [key, value] of Object.entries(node)) { if (key === '$and' || key === '$or') (value as unknown[]).forEach((child) => walk(child, object, nested)); else if (key === '$not') walk(value, object, nested); + else if (isSharedRecordIds(value)) misplaced(); else if (value !== null && typeof value === 'object' && !Array.isArray(value)) { for (const [op, comparand] of Object.entries(value)) { - if (isSharedRecordIds(comparand)) judge(comparand, op, key, object, nested); - else if (isComposedReadableIds(comparand) && reading !== 'no-descent') walk(comparand.scope, comparand.object, true); + if (op === '$in' && isSharedRecordIds(comparand)) judge(comparand, op, key, object, nested); + else if (op === '$in' && isComposedReadableIds(comparand)) { + if (reading !== 'no-descent') walk(comparand.scope, comparand.object, true); + } else if (holdsLeaf(comparand)) misplaced(); } } } diff --git a/packages/spec/src/data/fixed-read-leaf-conformance.ts b/packages/spec/src/data/fixed-read-leaf-conformance.ts index eb18046f308..4e4789b9cbc 100644 --- a/packages/spec/src/data/fixed-read-leaf-conformance.ts +++ b/packages/spec/src/data/fixed-read-leaf-conformance.ts @@ -58,10 +58,11 @@ * {@link FixedReadLeafCaseSet.seam} holds, as data, what ADR-0155 D1 and D4 * say the engine's executor seam admits and refuses: the leaf's position, its * verbs and its recipient. Nothing in this package runs them against an - * engine; the seam's card (ADR-0155 plan step 2) does. One question D1 leaves - * to that card is deliberately not a case: whether the write form may appear - * on a read verb, as it does in the prior-row read a predicate update makes - * with its own `where` (`packages/objectql/src/engine-update.ts`). + * engine; `@objectstack/objectql` runs them against its seam + * (`fixed-read-leaf-seam.ts`). The write form on a read verb is refused like + * any misplaced leaf (ADR-0155 ③ ruled A); the prior-row read a predicate + * update makes with its own `where` is that update's, and the seam judges it + * once, as the update. * * # What belongs here * @@ -75,7 +76,7 @@ */ import type { FilterCondition } from './filter.zod'; -import type { FixedReadLeafBrand } from './fixed-read-leaf'; +import type { FixedReadLeafBrand, FixedReadLeafName } from './fixed-read-leaf'; import { ReadableIds } from './readable-ids'; import { SHARED_RECORD_IDS_BRAND, SharedRecordIds } from './shared-record-ids'; @@ -157,8 +158,8 @@ export interface FixedReadLeafSeamCase extends FixedReadLeafCaseBase { /** One leaf's cases. */ export interface FixedReadLeafCaseSet { - /** The leaf the set is for, by its factory's name. ADR-0147's leaf widens this. */ - readonly leaf: 'SharedRecordIds'; + /** The leaf the set is for, by its factory's name (`FIXED_READ_LEAF_NAMES`). */ + readonly leaf: FixedReadLeafName; /** Its brand: what a door caller names, and what an evaluator recognises. */ readonly brand: FixedReadLeafBrand; /** The tenant field every fixture table declares. */ @@ -440,6 +441,43 @@ const SHARED_RECORD_IDS_SEAM: readonly FixedReadLeafSeamCase[] = Object.freeze([ note: 'ADR-0111 D3: a share widens edit, never delete, so no producer writes the leaf on delete.', }, { name: 'the read form on delete', operation: 'delete', object: DOC, clause: 'where', filter: () => ({ id: { $in: read('u1') } }), context: ASKER, verdict: 'refuses' }, + // The write form on a read verb (ADR-0155 ③ ruled A): refused like any misplaced leaf. + { name: 'the write form in a find\'s where', operation: 'find', object: DOC, clause: 'where', filter: () => ({ id: { $in: write('u1') } }), context: ASKER, verdict: 'refuses' }, + { name: 'the write form in a findOne\'s where', operation: 'findOne', object: DOC, clause: 'where', filter: () => ({ id: { $in: write('u1') } }), context: ASKER, verdict: 'refuses' }, + { name: 'the write form in a count\'s where', operation: 'count', object: DOC, clause: 'where', filter: () => ({ id: { $in: write('u1') } }), context: ASKER, verdict: 'refuses' }, + { name: 'the write form in an aggregate\'s where', operation: 'aggregate', object: DOC, clause: 'where', filter: () => ({ id: { $in: write('u1') } }), context: ASKER, verdict: 'refuses' }, + { + name: 'the write form inside a composed ReadableIds scope', + operation: 'find', object: NOTE, clause: 'where', + filter: () => ({ record_id: { $in: ReadableIds.compose(ReadableIds.of(DOC), { id: { $in: write('u1') } }) } }), + context: ASKER, verdict: 'refuses', + note: 'ADR-0155 D1: a composed scope is the where of a read of its parent, so it holds the read form only.', + }, + // The leaf outside the $in comparand (ADR-0155 D1): refused at every other position. + { name: 'as an implicit-equality value', operation: 'find', object: DOC, clause: 'where', filter: () => ({ id: read('u1') }), context: ASKER, verdict: 'refuses' }, + { name: 'as the comparand of $eq', operation: 'find', object: DOC, clause: 'where', filter: () => ({ id: { $eq: read('u1') } }), context: ASKER, verdict: 'refuses' }, + { + name: 'as the comparand of $nin', + operation: 'find', object: DOC, clause: 'where', + filter: () => ({ id: { $nin: read('u1') } }), + context: ASKER, verdict: 'refuses', + note: 'ADR-0155 D1: the negation is $not over the $in, which needs the blank-id guard; $nin is not a position.', + }, + { name: 'as a member of a $in list', operation: 'find', object: DOC, clause: 'where', filter: () => ({ id: { $in: [read('u1')] } }), context: ASKER, verdict: 'refuses' }, + { + name: 'as a filter node of its own', + operation: 'find', object: DOC, clause: 'where', + filter: () => ({ $and: [{ label: 'keep' }, read('u1') as unknown as FilterCondition] }), + context: ASKER, verdict: 'refuses', + note: 'Its enumerable inputs would read as an equality filter on fields named object and recipient.', + }, + { + name: 'inside a nested-relation condition', + operation: 'find', object: NOTE, clause: 'where', + filter: () => ({ record_id: { id: { $in: read('u1') } } } as unknown as FilterCondition), + context: ASKER, verdict: 'refuses', + note: 'ADR-0155 D1: legal in the object\'s own where or a composed scope, and a nested-relation condition is neither.', + }, // Recipient (ADR-0155 D4): the context's user, its delegator, a system context; any other is refused. { name: 'the recipient is the reading context\'s delegator', diff --git a/packages/spec/src/data/fixed-read-leaf.ts b/packages/spec/src/data/fixed-read-leaf.ts index 87f589353f1..1989ad879bc 100644 --- a/packages/spec/src/data/fixed-read-leaf.ts +++ b/packages/spec/src/data/fixed-read-leaf.ts @@ -88,11 +88,26 @@ export interface FixedInnerRead { /** The brand of every fixed-read leaf declared in this package. ADR-0147's leaf adds its own. */ export type FixedReadLeafBrand = typeof SHARED_RECORD_IDS_BRAND; +/** + * [ADR-0155 D4, O1 as ruled] The name of every fixed-read leaf declared in + * this package, by its factory's name: what a driver lists in + * `DriverCapabilities.fixedReadLeaves` (`./driver.zod.ts`) to say that it + * evaluates the leaf. ADR-0147's leaf adds its own. + * + * A name and not the brand, because a capability is declared data and a + * `unique symbol` cannot be a value of a schema; {@link fixedReadLeafNameOf} + * is the one mapping from a leaf, and so from its brand, to its name. + */ +export const FIXED_READ_LEAF_NAMES = Object.freeze(['SharedRecordIds'] as const); + +/** One of {@link FIXED_READ_LEAF_NAMES}. */ +export type FixedReadLeafName = (typeof FIXED_READ_LEAF_NAMES)[number]; + /** Every fixed-read leaf declared in this package. ADR-0147's leaf adds its own. */ export type FixedReadLeaf = SharedRecordIds; /** - * One row per fixed-read leaf: its brand, its guard and its description. + * One row per fixed-read leaf: its brand, its name, its guard and its description. * * Each guard refuses a value that carries any symbol-keyed property besides its * own brand, so the guards are disjoint and at most one row answers for any @@ -101,10 +116,16 @@ export type FixedReadLeaf = SharedRecordIds; */ const FIXED_READ_LEAVES: readonly { readonly brand: FixedReadLeafBrand; + readonly name: FixedReadLeafName; readonly is: (value: unknown) => boolean; readonly innerRead: (leaf: FixedReadLeaf) => FixedInnerRead; }[] = Object.freeze([ - Object.freeze({ brand: SHARED_RECORD_IDS_BRAND, is: isSharedRecordIds, innerRead: SharedRecordIds.innerRead }), + Object.freeze({ + brand: SHARED_RECORD_IDS_BRAND, + name: 'SharedRecordIds', + is: isSharedRecordIds, + innerRead: SharedRecordIds.innerRead, + }), ]); /** @@ -115,6 +136,15 @@ export function fixedReadLeafBrandOf(value: unknown): FixedReadLeafBrand | undef return FIXED_READ_LEAVES.find((row) => row.is(value))?.brand; } +/** + * The name of the fixed-read leaf `value` is ({@link FIXED_READ_LEAF_NAMES}), + * or `undefined` when it is none, exactly where {@link fixedReadLeafBrandOf} + * answers `undefined`. What an evaluator's declaration is matched against. + */ +export function fixedReadLeafNameOf(value: unknown): FixedReadLeafName | undefined { + return FIXED_READ_LEAVES.find((row) => row.is(value))?.name; +} + /** * Is `value` a fixed-read leaf — and, when `brands` is given, one of those * brands? An evaluator asks it without `brands` to recognise every leaf it owes diff --git a/scripts/adr-anchors/packages__objectql__src__fixed-read-leaf-position.ts.json b/scripts/adr-anchors/packages__objectql__src__fixed-read-leaf-position.ts.json new file mode 100644 index 00000000000..b3c449a7a19 --- /dev/null +++ b/scripts/adr-anchors/packages__objectql__src__fixed-read-leaf-position.ts.json @@ -0,0 +1,7 @@ +{ + "file": "packages/objectql/src/fixed-read-leaf-position.ts", + "adrs": [ + "ADR-0155" + ], + "invariant": "collectFixedReadLeaves is the one rule for where a fixed-read leaf may sit and on which verb, asked by the comparand door before the middleware chain and by the executor seam after it (ADR-0155 D1): only as the $in comparand of id on the object it names, in that object's where or inside the composed scope of a ReadableIds leaf over it, under $and, $or and $not; the read form on find, findOne, count and aggregate and inside every composed scope, the write form only in a predicate update's where (ruling 3 A), and no leaf on delete. Every other position, a having and an aggregation's filter are refused INTERNAL_ERROR / 500 by name, before a later door reads the leaf as a value. ENGINE_FIXED_READ_LEAF_BRANDS is the one list of brands the engine's door admits (admitFixedReadLeaves). Do not admit the write form on a read verb, do not add a flag per brand, and do not admit a leaf the seam does not judge." +} diff --git a/scripts/adr-anchors/packages__objectql__src__fixed-read-leaf-seam.ts.json b/scripts/adr-anchors/packages__objectql__src__fixed-read-leaf-seam.ts.json new file mode 100644 index 00000000000..e180000c68f --- /dev/null +++ b/scripts/adr-anchors/packages__objectql__src__fixed-read-leaf-seam.ts.json @@ -0,0 +1,8 @@ +{ + "file": "packages/objectql/src/fixed-read-leaf-seam.ts", + "adrs": [ + "ADR-0139", + "ADR-0155" + ], + "invariant": "The engine's executor seam passes a fixed-read leaf (isFixedReadLeaf: SharedRecordIds) through to the driver by reference, composing nothing, at a read verb's executor boundary on the final AST (after the ReadableIds composition, into every composed scope) and at an update's and a delete's executor entry (ADR-0155 D4). It admits a leaf only after the position and verb walk (fixed-read-leaf-position.ts), when the identity the leaf names is the context's user or its delegator or the context is a system one (compared, never replaced), when neither class D4 recognises applies (the object on another datasource than the inner read's table; a middleware or a beforeFind or afterFind hook registered for that table by name, a registration naming no object or '*' being outside), and when the driver's DriverCapabilities.fixedReadLeaves names the leaf. Every refusal is INTERNAL_ERROR / 500 before any driver is asked, logged at error once per evaluator, never INVALID_FILTER. Do not substitute an id list for a leaf a driver does not name, do not read around either class, do not re-derive or replace the recipient, and do not refuse a boot here." +}