Skip to content

Commit 0a3dd40

Browse files
feat(service-analytics, plugin-security, driver-odata): compile, resolve at the record, and refuse the SharedRecordIds leaf (ADR-0155 step 5) (#35945)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6Jao8mXHQniWvfYM2uHoosm2Da)_ Fixes #35874 Refs #33787 Clause-②: yes The explainer's published sharing-layer `rowFilter` changes content (ADR-0155 Q2 costs: the share arm is the judged record's id when a grant admits it and is left out otherwise, and never the leaf), and the analytics merges admit the `SharedRecordIds` brand at a second door. `packages/spec` changes too (B6): `parseFilterAST` answers a leaf it refuses in the array form (an `in` / `nin` comparand, an `in` / `nin` list member, a scalar operator's comparand) with `INTERNAL_ERROR` / 500 instead of `INVALID_FILTER` / 400. Metadata-protocol: none ## 维护者速读 - 问题:共享记录权限改造(把共享授权从限量名单改成数据库子查询)的第 5 步,用户无感。 - 这一步做什么:分析报表能直接编译这种子查询,权限解释器逐条记录判断共享,OData 数据源遇到它明确拒绝。 - 不做会怎样:切换上线后,仪表盘、分析查询和“为什么我能看到这条记录”的解释会报错或给出不一致的结果;本步改动可整体撤回。 - 要你做的:无。接线问题(分析服务怎样问引擎“这个对象能否用子查询”)已拆到 #35946,要在第 6 步之前裁定;在那之前,所有环境的分析查询照旧走引擎路径。 ## Read first (by risk) 1. `packages/plugins/plugin-security/src/explain-fixed-read-leaf.ts`: the leaf resolved at the record and the copy-on-write substitution that drops an emptied `$or` arm. This is the Clause-② content change. 2. `packages/services/service-analytics/src/read-scope-sql.ts`: `findUnservedFixedReadLeaf` (the role-aware walk) and `fixedReadLeafSubquerySql` (every value bound, the `tenantScope: 'none'` check). 3. `packages/services/service-analytics/src/strategies/native-sql-strategy.ts`: `readScopeCarriesUncompilableFixedReadLeaf`, the fail-closed decline. ## Two-minute check `pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2 src/__tests__/fixed-read-leaf-native-compile.test.ts`. Expect 31 passed: 11 conformance rows matched live on SQLite, 4 refused, and the native statement agreeing with the engine path. ## What changes - **service-analytics, the native compiler** (`compileScopedFilterToSql`). A read-form leaf placed as `{ id: { $in: leaf } }` on the scope's own object compiles to `"id" IN (SELECT "record_id" FROM "sys_record_share" WHERE "object_name" = ? AND "recipient_type" = ? AND "recipient_id" = ? AND ...)`, closed by the blank-id guard on `record_id` (not null, not the empty string). It is built from the leaf's own `fixedInnerReadOf` description, binds every value, and puts no tenant scope on the subquery (① ruled A). Any other leaf is refused in D4's envelope (`INTERNAL_ERROR` / 500, logged at `error` once per service logger): one placed elsewhere, under `$nin`, on another object, or in its write form. - **service-analytics, the decline.** `NativeSQLStrategy.canHandle` declines a scope carrying a leaf unless the host's `AnalyticsServiceConfig.fixedReadLeafClassOf` answers `null` (neither of D4's two classes) for every leaf and the dialect is known. A missing hook, a throwing hook, or any other answer also declines. The engine path then answers. This change ships the hook unwired: `AnalyticsServicePlugin` passes no answer, so the native path declines a scope carrying the leaf and the engine path answers, until #35946 wires it. - **service-analytics, the merges and the echo.** `withReadScope`, the related-object scope and the plugin's label read pass `admitFixedReadLeaves` to `assertReadScopeComparandsRunnable`, which refuses an unplaced leaf first and then admits the placed one. `ObjectQLStrategy.generateSql` prints the subquery. - **service-analytics, the query's `where`** (compile surface 2). A leaf anywhere in a query's `where`, in either spelling, is refused in the envelope before either strategy runs. - **plugin-security, the explainer.** `resolveFixedReadLeavesAtRecord` replaces each leaf in a copy of the sharing read filter with `[recordId]` or `[]`, from one `sys_record_share` read under `fixedInnerReadOf(leaf)`, keyed by the judged ids. A batch makes one read per leaf, keyed by every id. An emptied `$or` arm is dropped, and an `$or` left with one arm is that arm. A leaf it cannot resolve is refused, logged once, and so is a leaf anywhere but `{ id: { $in: leaf } }` in the object's own filter: the walk reads roles, as the engine's seam and the analytics compiler do, so a leaf inside a relation condition or a composed `ReadableIds` scope is refused. A failing share read is the read filter failing: the record is not visible, and no `rowFilter` is published. - **driver-odata.** `find` and `count` refuse the leaf before any request, `INTERNAL_ERROR` / 500. - **spec** (B6). `parseFilterAST` refuses a leaf that either of its doors refuses with `INTERNAL_ERROR` / 500: the shape door (an array-form `in` / `nin` comparand) or the type door (an `in` / `nin` list member, a scalar operator's comparand such as `!=` or `>`). The message names the leaf and its table, not the recipient. An unbranded copy keeps `INVALID_FILTER` / 400. - **objectql.** `index.ts` exports `fixedReadLeafClassOfEngine` and `driverEvaluatesFixedReadLeaf` from `fixed-read-leaf-seam.ts`. `engine.ts` is untouched. ## Compile surfaces (one conclusion each) 1. `compileScopedFilterToSql`: **changed here.** Compiles the placed read form and refuses the rest. Pinned against `SHARED_RECORD_IDS_CASE_SET` live on SQLite: 11 cases answer exactly their rows, the 2 write-form cases are refused 500, and the 2 composed cases are refused 500 with no composition run. 2. `lowerAnalyticsWhere`: **changed here.** At 17ed9e7, before this change: `{ id: { $in: leaf } }` answered `INVALID_FILTER` / 400 and printed the recipient; a bare `{ id: leaf }` and an array-form `=` were lowered to `{ kind: 'relation', member: 'id', condition: { object, recipient } }`. Now every spelling answers 500 with no recipient. No producer writes a leaf into a `where`: the leaf enters analytics only as the read scope. 3. `assertReadScopeComparandsRunnable`: **changed here.** Admits the brand only for a caller that passes `admitFixedReadLeaves`. Without it the answer is `READ_SCOPE_COMPILE_FAILED` / 500, as before (pinned). 4. The native decline: **changed here** (above). Pinned three ways: with the seam's answer, the native statement runs and agrees with the engine path; with no hook, it declines with the same rows; with a `beforeFind` hook on `sys_record_share`, it declines and the engine's seam refuses 500. 5. The dry-run echo, `ObjectQLStrategy.generateSql` through `compileScopedFilterToSql`: **changed here.** Prints the subquery (pinned). It does not consult the class recognition: it describes the statement and runs nothing. 6. The explainer, `matchUnderDeclaredColumns`: **changed here.** Leaves are resolved before the match, in `applyRecordAttribution`. 7. `driver-odata`: **changed here.** The refusal sits beside `refuseReadableIds`. 8. `driver-mongodb` `translateFilter`: **out of scope** (frozen under #5499). Its R1 is the step-2 seam: `fixed-read-leaf-seam.ts#passFixedReadLeaves` refuses any leaf bound for a driver whose `supports.fixedReadLeaves` does not list it, before the driver is asked. 9. `driver-memory`: **out of scope** (#35873 on hold). The same seam refusal applies. 10. `formula` `matchesFilterCondition` and objectql `applyHaving` / `matchesHaving`: **already compliant.** The engine's having door refuses a leaf before `applyHaving` runs (`engine-delete-and-aggregate.ts`: `atFixedReadLeafDoor(this, () => assertListComparandShapes(object, 'aggregate', query.having, 'having'))`). `matchesFilterCondition` sees a sharing read filter only through the explainer, which now resolves the leaf first. The write tenant wall's call matches tenant checks only. 11. `driver-sql` / Turso: **already compliant** (step 3, 643fe3b). ## Acceptance notes - **B1, split to #35946.** `service-analytics` has no runtime dependency on `@objectstack/objectql`, and no route that adds no package edge lets the plugin ask the seam. So this PR ships the hook (`AnalyticsServiceConfig.fixedReadLeafClassOf`) and the fail-closed decline, and leaves the hook unwired in `AnalyticsServicePlugin`. Until #35946 wires it, the native path declines a scope carrying a leaf on every host and the engine path answers, with the right rows. Nothing writes the leaf before step 6, so nothing changes today. #35946 carries the wiring fork, and it lands before step 6. - **D4's admission, reconciled.** In analytics, D4's "brand-naming callers" are the callers that pass `admitFixedReadLeaves` to `assertReadScopeComparandsRunnable`: the two merges, the label read, and `compileScopedFilterToSql`. The last is the native compiler's own door. It admits only what it compiles, and Q2 ruled that the native compiler compiles the leaf. This reads as Q2's ruled consequence, so no ADR amendment is needed. The seat may file a pointer note. - **B6, decided: moved to the envelope.** No producer can emit the array form: step 6 writes the object form at the engine's seam, and JSON cannot carry the brand. The 400 also printed the recipient's id. This replaces step 2's pin `the authoring lowering refuses the leaf` in `shared-record-ids.test.ts`, which pinned exactly that branch. The new pin asserts 500, the message, no recipient, and that the unbranded copy keeps 400. Neither the spec refusal nor the where-face refusal is logged: neither function holds a logger (the same precedent as `driver-odata`'s `refuseReadableIds`). - **PostgreSQL non-`text` `id`** (#35906, open): mirrors step 3's `driver-sql`. No cast on the subquery. - **A residual:** the spec door still answers a branded leaf for every other caller that names no brand with `INVALID_FILTER` / 400, and its message prints the leaf's inputs. Step 2 pinned that as the refusal those callers had before the leaf. No caller here can reach it with a branded leaf. ## Tests The five new or changed test files ran at 65d8e8f, the rebased head. The service-analytics file and its typecheck ran again at 646a10e, after the sink field was renamed. Other runs are marked. <details><summary>New and changed test files</summary> - `service-analytics src/__tests__/fixed-read-leaf-native-compile.test.ts`: Test Files 1 passed, Tests 27 passed - `plugin-security src/explain-fixed-read-leaf.test.ts`: Tests 7 passed - `driver-odata src/odata-driver.test.ts`: Tests 34 passed - `objectql src/engine-fixed-read-leaf-seam.test.ts`: Tests 68 passed - `spec src/data/shared-record-ids.test.ts`: Tests 30 passed </details> <details><summary>Package suites and typecheck</summary> - Suites at the pre-rebase tree: spec 865 files passed, 1 skipped (27797 tests); objectql 624 files, 14169 tests; service-analytics 221 files, 5643 tests (after the surface-2 change); plugin-security 285 files, 7075 tests; driver-odata 9 files, 1455 tests. - `typecheck`: spec, objectql, service-analytics, plugin-security and driver-odata all exit 0. - After the rebase, at 65d8e8f: rebuilt the platform-objects and objectql dists and reran the five files above. plugin-security `typecheck` passed, objectql `typecheck` passed, and the plugin-security suite passed: 285 files, 7079 tests (45 skipped). </details> <details><summary>Ablation (committed first, restored to the HEAD blob)</summary> - Mutation: `scripts/ablation-replace.mjs` replaced `find`'s `refuseFixedReadLeaf(query.where);` in `odata-driver.ts` with a marker. The anchor went from 1 to 0 and the blob from d5cb1fe to a4af98f3458f. On-disk marker count 1; the refusal call count fell from 2 to 1. - Predicted: every `find` case red, every `count` case green. - Observed: 12 failed, 22 passed. `find` returned rows (`{ code: undefined, status: undefined }`) instead of refusing, which is B5's pre-change behaviour: the predicate was left out of the `$filter` sent. - Restore: blob back to d5cb1fe, equal to HEAD; `git diff HEAD` empty. - A first attempt was refused by the tool before it ran any command: its replacement text was a substring of the anchor, so the replacement count could not rise. </details> ## Verification - `node scripts/pm/dispatch-gates.mjs --commands` over the diff at 646a10e: 112 derived families. 110 exit 0. 2 exit 3, PREREQUISITE NOT MET, read as NOT MEASURED: `check:dual-build-cjs-loads` needs every workspace package's `dist/`, and `check:i18n` needs the workspace CLI built. `--ran` reconciliation: 112 derived, 110 run, 2 NOT-MEASURED, 0 UNRUN. - At 65d8e8f two gates went red, both from this diff, and both are fixed in 646a10e. `check:logger-receiver-detach` read the refusal sink's `log` field as a log channel passed as a callback, so the field is now `logger`. `check:engine-double-contract` needed `--write` to record the new explainer test's `findOne` double in `scripts/engine-double-contract.pinned.json`. - Line budget: 1632 changed lines (+1611 / −21) in 22 files, under 3,000. - `node scripts/pm/overlap-check.mjs`: clean against origin/main 17ed9e7 and #34817, which shares `objectql/src/index.ts`. --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz)_ <!-- signed: repo:objectstack#7 · os-tesla · session_01L9qibyXo4gSy8DJPNz4ANz --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9972432 commit 0a3dd40

22 files changed

Lines changed: 1743 additions & 23 deletions
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/objectql': patch
4+
'@objectstack/service-analytics': patch
5+
'@objectstack/plugin-security': patch
6+
'@objectstack/driver-odata': patch
7+
---
8+
9+
feat: analytics compiles the `SharedRecordIds` fixed-read leaf, the access explainer resolves it at the record, and OData refuses it (ADR-0155, step 5 of 6)
10+
11+
Clause-②: yes
12+
Metadata-protocol: none
13+
14+
No visible change on its own: nothing on main writes a `SharedRecordIds` leaf yet. The sharing plugin starts writing it at ADR-0155's last step.
15+
16+
- **Analytics, the native SQL path** (`@objectstack/service-analytics`). A read scope carrying `{ id: { $in: SharedRecordIds.read(object, user) } }` compiles to one subquery in the list's own position, `id IN (SELECT "record_id" FROM "sys_record_share" WHERE "object_name" = ? AND "recipient_type" = ? AND "recipient_id" = ? AND "record_id" IS NOT NULL AND "record_id" <> '')`, with every value bound and no tenant scope on the subquery (ADR-0155 ① ruled A). The native strategy takes such a scope only when the host answers `AnalyticsServiceConfig.fixedReadLeafClassOf` with `null` for each leaf (outside both classes ADR-0155 D4 recognises: the object on another datasource than `sys_record_share`, or a middleware or `beforeFind` / `afterFind` hook registered for `sys_record_share` by name) and the dialect is SQLite, PostgreSQL, MySQL or SQL Server. Otherwise it declines, and the ObjectQL engine path answers. A host that wires no answer keeps today's behaviour: the native path declines every scope that carries the leaf. This change ships the hook unwired: `AnalyticsServicePlugin` passes no answer, so the native path declines a scope carrying the leaf and the engine path answers, until #35946 wires it.
17+
- **Analytics, the ObjectQL path.** The read-scope merges (`withReadScope`, the related-object scope, the label read) admit a placed read-form leaf and hand it to the engine by reference. The dry-run SQL echo prints the subquery. A leaf in any other position, under `$nin`, on another object or in its write form is refused, `INTERNAL_ERROR` / 500, logged at `error` once per service logger.
18+
- **Analytics, the query's `where`.** A leaf reaches analytics only in the read scope. A leaf anywhere in a query's `where`, in either spelling, is now refused before either strategy runs, with `INTERNAL_ERROR` / 500. The message names the leaf and its table, not the recipient. Before this release `{ id: { $in: leaf } }` there answered `INVALID_FILTER` / 400, with a message that printed the recipient. A bare `{ id: leaf }`, or an array-form `=`, was read as a relation condition on `id`. No request can spell the leaf, so only in-process code could reach this.
19+
- **The access explainer** (`@objectstack/plugin-security`). `ISecurityService.explain` resolves each leaf in the sharing read filter at the record it judges, with one read of `sys_record_share` under the leaf's own predicate, keyed by the record ids (one read for a whole batch). The sharing layer's `rowFilter` then has the two shapes it has today: `{ id: { $in: [recordId] } }` in the share arm for a caller with a grant on the record, and the share arm left out for a caller without one. The published `rowFilter` never carries the leaf. A leaf it cannot resolve is refused, `INTERNAL_ERROR` / 500, logged at `error` once. That includes a leaf anywhere but `{ id: { $in: leaf } }` in the object's own filter, such as one inside a relation condition or a composed `ReadableIds` scope, as the engine and the analytics compiler refuse it.
20+
- **OData** (`@objectstack/driver-odata`). `find` and `count` refuse a `where` carrying the leaf before any request is sent, `INTERNAL_ERROR` / 500. An OData `$filter` has no form of the subquery, and the driver declares no `fixedReadLeaves`. Before this release a direct `find` left the leaf's predicate out of the `$filter` it sent. The engine already refused the leaf before calling this driver.
21+
- **The array form** (`@objectstack/spec`). `parseFilterAST` now refuses a leaf in the array form with `INTERNAL_ERROR` / 500 wherever it answered `INVALID_FILTER` / 400: as an `in` / `nin` comparand, as a member of an `in` / `nin` list, or as the comparand of a scalar operator (`!=`, `>` and the rest). The old messages printed the leaf's inputs, the recipient among them. The new message names the leaf and its table only. An unbranded copy that crossed JSON is still `INVALID_FILTER` / 400. An array-form `=` is passed on by reference and refused by the engine, as before.
22+
- **New exports** (`@objectstack/objectql`). `fixedReadLeafClassOfEngine(engine, leaf)` answers which ADR-0155 D4 class, if any, keeps the engine from handing a leaf to a driver. `driverEvaluatesFixedReadLeaf` answers whether a driver declares the leaf. Neither reads or writes anything.

‎packages/drivers/driver-odata/src/odata-driver.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*/
77

88
import { describe, expect, it } from 'vitest';
9+
import { READABLE_IDS_REFUSAL, SHARED_RECORD_IDS_CASE_SET, SharedRecordIds } from '@objectstack/spec/data';
910
import { parseODataDriverConfig } from './config.js';
1011
import { ODataDriver } from './odata-driver.js';
1112
import { ODataRequestError } from './transport.js';
@@ -272,3 +273,29 @@ describe('credentials', () => {
272273
expect(requests).toHaveLength(0);
273274
});
274275
});
276+
277+
describe('[ADR-0155 D4, Q2 storage rows as ruled: R2, with R1 behind it] the share-grant leaf', () => {
278+
// The step-1 case-set's "refuses" reading: D4's envelope on every case that
279+
// holds a leaf, before any request reaches the service (the translator would
280+
// otherwise leave the leaf to the engine, as no restriction).
281+
for (const c of SHARED_RECORD_IDS_CASE_SET.cases.filter((x) => x.holdsLeaf)) {
282+
it(`refuses, sends nothing: ${c.name}`, async () => {
283+
for (const read of ['find', 'count'] as const) {
284+
const { driver, requests } = driverFor([{ url: 'People', body: page(PEOPLE) }]);
285+
const err = await driver[read]('trip_person', { where: c.where() } as never).then(() => null, (e: any) => e);
286+
expect({ code: err?.code, status: err?.status }, read).toEqual(READABLE_IDS_REFUSAL);
287+
expect(urls(requests), read).toEqual([]);
288+
}
289+
});
290+
}
291+
292+
it('names the driver and the leaf by name and table, never the recipient', async () => {
293+
const { driver } = driverFor([]);
294+
const err = await driver
295+
.find('trip_person', { where: { $or: [{ first_name: 'Russell' }, { id: { $in: SharedRecordIds.read('trip_person', 'u-secret') } }] } } as never)
296+
.then(() => null, (e: any) => e);
297+
expect(err?.message).toContain('[driver-odata]');
298+
expect(err?.message).toContain("where.$or[1].id.$in holds a SharedRecordIds leaf, a fixed read of 'sys_record_share'");
299+
expect(err?.message).not.toContain('u-secret');
300+
});
301+
});

‎packages/drivers/driver-odata/src/odata-driver.ts‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@
5050
* read from `$metadata`, which the driver reads once, at the first request.
5151
*/
5252

53-
import { findMisplacedReadableIds, readableIdsDriverRefusal } from '@objectstack/core';
53+
import { describeFixedReadLeaf, findMisplacedReadableIds, fixedReadLeafRefusal, readableIdsDriverRefusal } from '@objectstack/core';
54+
import { isComposedReadableIds, isFixedReadLeaf } from '@objectstack/spec/data';
5455
import type { DriverQuery, IDataDriver, IntrospectedSchema, IntrospectedTable } from '@objectstack/spec/contracts';
5556
import type { DriverOptions } from '@objectstack/spec/data';
5657
import type { EdmEntitySet, EdmEntityType, EdmProperty, ODataDialect, ODataServiceModel } from './dialect.js';
@@ -288,6 +289,7 @@ export class ODataDriver implements IDataDriver {
288289

289290
async find(object: string, query: DriverQuery = {}, _options?: DriverOptions): Promise<Row[]> {
290291
refuseReadableIds(query.where);
292+
refuseFixedReadLeaf(query.where);
291293
const binding = await this.bind(object);
292294
const limit = typeof query.limit === 'number' ? query.limit : undefined;
293295
const offset = typeof query.offset === 'number' ? query.offset : undefined;
@@ -327,6 +329,7 @@ export class ODataDriver implements IDataDriver {
327329

328330
async count(object: string, query: DriverQuery = {}, _options?: DriverOptions): Promise<number> {
329331
refuseReadableIds(query.where);
332+
refuseFixedReadLeaf(query.where);
330333
const binding = await this.bind(object);
331334
const { filter, complete } = translateWhere(query.where, binding, this.dialect);
332335
if (!complete) {
@@ -624,6 +627,50 @@ function refuseReadableIds(where: unknown): void {
624627
if (site) throw readableIdsDriverRefusal('driver-odata', site, 'an OData $filter has no form of the tenant-walled semi-join');
625628
}
626629

630+
/**
631+
* [ADR-0155 D4, D5; Q2's storage rows as ruled: R2, with R1 behind it] A
632+
* FIXED-READ LEAF (`SharedRecordIds`: "the records of X shared with this
633+
* user") is a semi-join over a platform table this service does not hold, and
634+
* `$filter` has no form of it. The translator leaves what it cannot spell to
635+
* the engine, which would read the leaf as no restriction, so it is refused,
636+
* loudly and before anything is sent, wherever it sits: D4's envelope,
637+
* `INTERNAL_ERROR` / 500, ⛔ never a 400 and never read as an ordinary
638+
* comparand. This driver declares no `fixedReadLeaves`, so the engine's seam
639+
* refuses the leaf before calling it; this is the driver's own refusal for a
640+
* call that reached it another way. Unlogged, as {@link refuseReadableIds} is:
641+
* the driver holds no logger, and the seam logs its own refusal once.
642+
*/
643+
function refuseFixedReadLeaf(where: unknown): void {
644+
const onPath = new Set<object>();
645+
const find = (value: unknown, at: string): { at: string; leaf: unknown } | null => {
646+
if (isFixedReadLeaf(value)) return { at, leaf: value };
647+
if (isComposedReadableIds(value)) return find(value.scope, `${at}.scope`);
648+
if (value === null || typeof value !== 'object' || onPath.has(value)) return null;
649+
onPath.add(value);
650+
try {
651+
const entries: [string, unknown][] = Array.isArray(value)
652+
? value.map((item, i) => [`${at}[${i}]`, item])
653+
: Object.keys(value).map((key) => [`${at}.${key}`, (value as Record<string, unknown>)[key]]);
654+
for (const [path, item] of entries) {
655+
const found = find(item, path);
656+
if (found) return found;
657+
}
658+
return null;
659+
} finally {
660+
onPath.delete(value);
661+
}
662+
};
663+
const found = find(where, 'where');
664+
if (found === null) return;
665+
throw fixedReadLeafRefusal(
666+
'driver-odata',
667+
`${describeFixedReadLeaf(found.at, found.leaf)}: an OData $filter has no form of the fixed inner read's ` +
668+
'subquery, and this driver declares no fixedReadLeaves (ADR-0155 D4). The request was NOT sent, rather than ' +
669+
'read the leaf as no restriction. Read this object through the engine, whose seam answers the leaf for a ' +
670+
'driver that evaluates it.',
671+
);
672+
}
673+
627674
const etagKey = (object: string, id: string | number) => `${object}\u0000${String(id)}`;
628675

629676
/** A verb this driver does not offer, refused by name (a request-shaped refusal, never an outage). */

‎packages/objectql/src/engine-fixed-read-leaf-seam.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
type FixedReadLeafSeamCase,
3232
} from '@objectstack/spec/data';
3333
import { ObjectQL, SECURITY_SERVICE_SOURCE_SLOT } from './engine.js';
34+
import { driverEvaluatesFixedReadLeaf, fixedReadLeafClassOfEngine } from './index.js';
3435

3536
interface SeenCall { verb: string; object: string; ast: any }
3637

@@ -426,3 +427,61 @@ describe('[ADR-0155 D4] a refusal at the door is logged on the boundary\'s flag,
426427
expect(errorsIn(logger)).toEqual(['error']);
427428
});
428429
});
430+
431+
describe('[ADR-0155 plan step 5] the seam\'s public face: the recognition an evaluator asks before it compiles', () => {
432+
it('answers the seam\'s own class, or undefined, reading the engine and calling no driver', async () => {
433+
const { engine, calls, farCalls } = await bootEngine();
434+
expect(fixedReadLeafClassOfEngine(engine, SharedRecordIds.read('srid_doc', 'u1'))).toBeUndefined();
435+
expect(fixedReadLeafClassOfEngine(engine, SharedRecordIds.read('srid_far', 'u1'))).toMatchObject({
436+
class: 'other-datasource', object: 'srid_far', table: 'sys_record_share',
437+
});
438+
engine.registerHook('afterFind', () => {}, { object: 'sys_record_share' });
439+
expect(fixedReadLeafClassOfEngine(engine, SharedRecordIds.read('srid_doc', 'u1'))).toMatchObject({
440+
class: 'registration-by-name', table: 'sys_record_share',
441+
});
442+
expect(calls).toEqual([]);
443+
expect(farCalls).toEqual([]);
444+
});
445+
446+
it('driverEvaluatesFixedReadLeaf reads the declaration and nothing else', () => {
447+
expect(driverEvaluatesFixedReadLeaf({ supports: DECLARES }, 'SharedRecordIds')).toBe(true);
448+
expect(driverEvaluatesFixedReadLeaf({ supports: { readableIdsLeaf: true } }, 'SharedRecordIds')).toBe(false);
449+
expect(driverEvaluatesFixedReadLeaf(undefined, 'SharedRecordIds')).toBe(false);
450+
});
451+
});
452+
453+
describe('[ADR-0155 plan step 5, the array-form in / nin decision] D4\'s envelope, never INVALID_FILTER', () => {
454+
for (const op of ['in', 'nin']) {
455+
it(`an array-form ${op} carrying the leaf is refused INTERNAL_ERROR / 500, naming no recipient`, async () => {
456+
const { engine, calls } = await bootEngine();
457+
const where = [['id', op, SharedRecordIds.read('srid_doc', 'u-secret')]] as unknown as FilterCondition;
458+
const err = await refusalOf(engine.find('srid_doc', { where }, { context: ASKER as any }));
459+
expect(envelopeOf(err)).toEqual(REFUSED);
460+
expect(err?.message).toContain("holds a SharedRecordIds leaf, a fixed read of 'sys_record_share'");
461+
expect(err?.message).not.toContain('u-secret');
462+
expect(calls).toEqual([]);
463+
expect(engine.judgeFilter('srid_doc', where)).toMatchObject({ ok: false, ...REFUSED });
464+
});
465+
}
466+
467+
// The type door's refusals: the shape door passes a list and a scalar
468+
// operator, so these answered INVALID_FILTER / 400, printing the leaf's head,
469+
// while the object spelling `{ id: { $in: [leaf] } }` answered 500.
470+
const typeDoor: Array<[string, (leaf: unknown) => unknown]> = [
471+
['the leaf as an array-form in list member', (leaf) => ['id', 'in', [leaf]]],
472+
['the leaf as an array-form != comparand', (leaf) => ['id', '!=', leaf]],
473+
];
474+
for (const [what, condition] of typeDoor) {
475+
it(`${what} is refused INTERNAL_ERROR / 500, naming no recipient, as its object spelling is`, async () => {
476+
const { engine, calls } = await bootEngine();
477+
const where = [condition(SharedRecordIds.read('srid_doc', 'u-secret'))] as unknown as FilterCondition;
478+
const err = await refusalOf(engine.find('srid_doc', { where }, { context: ASKER as any }));
479+
expect(envelopeOf(err)).toEqual(REFUSED);
480+
expect(err?.message).toContain("holds a SharedRecordIds leaf, a fixed read of 'sys_record_share'");
481+
expect(err?.message).not.toContain('u-secret');
482+
expect(calls).toEqual([]);
483+
const objectSpelling = { id: { $in: [SharedRecordIds.read('srid_doc', 'u-secret')] } } as unknown as FilterCondition;
484+
expect(envelopeOf(await refusalOf(engine.find('srid_doc', { where: objectSpelling }, { context: ASKER as any })))).toEqual(REFUSED);
485+
});
486+
}
487+
});

‎packages/objectql/src/fixed-read-leaf-seam.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,9 @@
5656
*
5757
* ⛔ No boot refusal and no producer here: the class-② boot check and R2's
5858
* share-arm answer land with the producer (ADR-0155 plan step 6), and until
59-
* then nothing on main writes the leaf. `index.ts` re-exports nothing from
60-
* this module.
59+
* then nothing on main writes the leaf. `index.ts` re-exports two readers
60+
* from this module and nothing else (plan step 5): {@link fixedReadLeafClassOfEngine}
61+
* and {@link driverEvaluatesFixedReadLeaf}.
6162
*/
6263

6364
import { fixedInnerReadOf, fixedReadLeafNameOf, type FixedReadLeaf, type FixedReadLeafName } from '@objectstack/spec/data';
@@ -72,6 +73,8 @@ import {
7273
isFixedReadLeafSeamRefusal,
7374
} from './fixed-read-leaf-position.js';
7475
import { driverNameOf } from './relation-semi-join.js';
76+
import { securityResolversHost } from './engine-facet-hosts.js';
77+
import type { ObjectQL } from './engine.js';
7578

7679
/** The hook events whose registration for the inner table BY NAME is D4's second class. */
7780
const FIND_HOOK_EVENTS = Object.freeze(['beforeFind', 'afterFind'] as const);
@@ -139,6 +142,21 @@ export function fixedReadLeafClassOf(host: FixedReadLeafSeamHost, leaf: FixedRea
139142
return undefined;
140143
}
141144

145+
/**
146+
* [ADR-0155 D4, plan step 5] The public face of {@link fixedReadLeafClassOf}
147+
* for one engine: which of D4's two classes `leaf` falls in on `engine`, or
148+
* `undefined` when neither. The recognition is the seam's own, run over the
149+
* host the executor boundary reads (`securityResolversHost`), so a caller that
150+
* must decline before it compiles (the analytics native compiler, ADR-0155 Q2
151+
* as ruled) asks it here and ⛔ restates neither class.
152+
*
153+
* Read-only: it reads the engine's datasource bindings, its object-scoped
154+
* middlewares and its find hooks, and calls no driver and logs nothing.
155+
*/
156+
export function fixedReadLeafClassOfEngine(engine: ObjectQL, leaf: FixedReadLeaf): FixedReadLeafClass | undefined {
157+
return fixedReadLeafClassOf(securityResolversHost.of(engine), leaf);
158+
}
159+
142160
/** The once-per-evaluator log's flags: one per engine for the seam's faults, one per driver for a declaration it lacks. */
143161
const LOGGED = new WeakMap<object, { logged: boolean }>();
144162

‎packages/objectql/src/index.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,12 @@ export type { DatasourceDef } from './engine.js';
269269
// refuses the filter rather than truncate it, and its words name this number.
270270
// Exported so a caller running the two-step route itself can page by it.
271271
export { RELATION_FILTER_ID_CAP } from './relation-filter-lowering.js';
272+
// [ADR-0155 D4, plan step 5] The seam's recognition of D4's two classes and
273+
// its reader of a driver's `fixedReadLeaves` declaration, so an evaluator that
274+
// declines before it compiles (the analytics native compiler) asks the seam
275+
// and restates neither.
276+
export { driverEvaluatesFixedReadLeaf, fixedReadLeafClassOfEngine } from './fixed-read-leaf-seam.js';
277+
export type { FixedReadLeafClass } from './fixed-read-leaf-seam.js';
272278
// Groups ordered by an aggregated column, cut and counted in the driver's own
273279
// statement: the engine-internal read option a door carries to `aggregate`,
274280
// and the request it carries. Carriers that do not import this package spell

0 commit comments

Comments
 (0)