diff --git a/.changeset/35874-fixed-read-leaf-census-rest.md b/.changeset/35874-fixed-read-leaf-census-rest.md new file mode 100644 index 00000000000..49d8875bae6 --- /dev/null +++ b/.changeset/35874-fixed-read-leaf-census-rest.md @@ -0,0 +1,22 @@ +--- +'@objectstack/spec': patch +'@objectstack/objectql': patch +'@objectstack/service-analytics': patch +'@objectstack/plugin-security': patch +'@objectstack/driver-odata': patch +--- + +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) + +Clause-②: yes +Metadata-protocol: none + +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. + +- **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. +- **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. +- **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. +- **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. +- **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. +- **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. +- **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. diff --git a/packages/drivers/driver-odata/src/odata-driver.test.ts b/packages/drivers/driver-odata/src/odata-driver.test.ts index dcc7846266d..e2e6781b024 100644 --- a/packages/drivers/driver-odata/src/odata-driver.test.ts +++ b/packages/drivers/driver-odata/src/odata-driver.test.ts @@ -6,6 +6,7 @@ */ import { describe, expect, it } from 'vitest'; +import { READABLE_IDS_REFUSAL, SHARED_RECORD_IDS_CASE_SET, SharedRecordIds } from '@objectstack/spec/data'; import { parseODataDriverConfig } from './config.js'; import { ODataDriver } from './odata-driver.js'; import { ODataRequestError } from './transport.js'; @@ -272,3 +273,29 @@ describe('credentials', () => { expect(requests).toHaveLength(0); }); }); + +describe('[ADR-0155 D4, Q2 storage rows as ruled: R2, with R1 behind it] the share-grant leaf', () => { + // The step-1 case-set's "refuses" reading: D4's envelope on every case that + // holds a leaf, before any request reaches the service (the translator would + // otherwise leave the leaf to the engine, as no restriction). + for (const c of SHARED_RECORD_IDS_CASE_SET.cases.filter((x) => x.holdsLeaf)) { + it(`refuses, sends nothing: ${c.name}`, async () => { + for (const read of ['find', 'count'] as const) { + const { driver, requests } = driverFor([{ url: 'People', body: page(PEOPLE) }]); + const err = await driver[read]('trip_person', { where: c.where() } as never).then(() => null, (e: any) => e); + expect({ code: err?.code, status: err?.status }, read).toEqual(READABLE_IDS_REFUSAL); + expect(urls(requests), read).toEqual([]); + } + }); + } + + it('names the driver and the leaf by name and table, never the recipient', async () => { + const { driver } = driverFor([]); + const err = await driver + .find('trip_person', { where: { $or: [{ first_name: 'Russell' }, { id: { $in: SharedRecordIds.read('trip_person', 'u-secret') } }] } } as never) + .then(() => null, (e: any) => e); + expect(err?.message).toContain('[driver-odata]'); + expect(err?.message).toContain("where.$or[1].id.$in holds a SharedRecordIds leaf, a fixed read of 'sys_record_share'"); + expect(err?.message).not.toContain('u-secret'); + }); +}); diff --git a/packages/drivers/driver-odata/src/odata-driver.ts b/packages/drivers/driver-odata/src/odata-driver.ts index a3832d2f452..d5cb1fece2b 100644 --- a/packages/drivers/driver-odata/src/odata-driver.ts +++ b/packages/drivers/driver-odata/src/odata-driver.ts @@ -50,7 +50,8 @@ * read from `$metadata`, which the driver reads once, at the first request. */ -import { findMisplacedReadableIds, readableIdsDriverRefusal } from '@objectstack/core'; +import { describeFixedReadLeaf, findMisplacedReadableIds, fixedReadLeafRefusal, readableIdsDriverRefusal } from '@objectstack/core'; +import { isComposedReadableIds, isFixedReadLeaf } from '@objectstack/spec/data'; import type { DriverQuery, IDataDriver, IntrospectedSchema, IntrospectedTable } from '@objectstack/spec/contracts'; import type { DriverOptions } from '@objectstack/spec/data'; import type { EdmEntitySet, EdmEntityType, EdmProperty, ODataDialect, ODataServiceModel } from './dialect.js'; @@ -288,6 +289,7 @@ export class ODataDriver implements IDataDriver { async find(object: string, query: DriverQuery = {}, _options?: DriverOptions): Promise { refuseReadableIds(query.where); + refuseFixedReadLeaf(query.where); const binding = await this.bind(object); const limit = typeof query.limit === 'number' ? query.limit : undefined; const offset = typeof query.offset === 'number' ? query.offset : undefined; @@ -327,6 +329,7 @@ export class ODataDriver implements IDataDriver { async count(object: string, query: DriverQuery = {}, _options?: DriverOptions): Promise { refuseReadableIds(query.where); + refuseFixedReadLeaf(query.where); const binding = await this.bind(object); const { filter, complete } = translateWhere(query.where, binding, this.dialect); if (!complete) { @@ -624,6 +627,50 @@ function refuseReadableIds(where: unknown): void { if (site) throw readableIdsDriverRefusal('driver-odata', site, 'an OData $filter has no form of the tenant-walled semi-join'); } +/** + * [ADR-0155 D4, D5; Q2's storage rows as ruled: R2, with R1 behind it] A + * FIXED-READ LEAF (`SharedRecordIds`: "the records of X shared with this + * user") is a semi-join over a platform table this service does not hold, and + * `$filter` has no form of it. The translator leaves what it cannot spell to + * the engine, which would read the leaf as no restriction, so it is refused, + * loudly and before anything is sent, wherever it sits: D4's envelope, + * `INTERNAL_ERROR` / 500, ⛔ never a 400 and never read as an ordinary + * comparand. This driver declares no `fixedReadLeaves`, so the engine's seam + * refuses the leaf before calling it; this is the driver's own refusal for a + * call that reached it another way. Unlogged, as {@link refuseReadableIds} is: + * the driver holds no logger, and the seam logs its own refusal once. + */ +function refuseFixedReadLeaf(where: unknown): void { + const onPath = new Set(); + const find = (value: unknown, at: string): { at: string; leaf: unknown } | null => { + if (isFixedReadLeaf(value)) return { at, leaf: value }; + if (isComposedReadableIds(value)) return find(value.scope, `${at}.scope`); + if (value === null || typeof value !== 'object' || onPath.has(value)) return null; + onPath.add(value); + try { + const entries: [string, unknown][] = Array.isArray(value) + ? value.map((item, i) => [`${at}[${i}]`, item]) + : Object.keys(value).map((key) => [`${at}.${key}`, (value as Record)[key]]); + for (const [path, item] of entries) { + const found = find(item, path); + if (found) return found; + } + return null; + } finally { + onPath.delete(value); + } + }; + const found = find(where, 'where'); + if (found === null) return; + throw fixedReadLeafRefusal( + 'driver-odata', + `${describeFixedReadLeaf(found.at, found.leaf)}: an OData $filter has no form of the fixed inner read's ` + + 'subquery, and this driver declares no fixedReadLeaves (ADR-0155 D4). The request was NOT sent, rather than ' + + 'read the leaf as no restriction. Read this object through the engine, whose seam answers the leaf for a ' + + 'driver that evaluates it.', + ); +} + const etagKey = (object: string, id: string | number) => `${object}\u0000${String(id)}`; /** A verb this driver does not offer, refused by name (a request-shaped refusal, never an outage). */ diff --git a/packages/objectql/src/engine-fixed-read-leaf-seam.test.ts b/packages/objectql/src/engine-fixed-read-leaf-seam.test.ts index 60cb67251f8..4ab892bdb8e 100644 --- a/packages/objectql/src/engine-fixed-read-leaf-seam.test.ts +++ b/packages/objectql/src/engine-fixed-read-leaf-seam.test.ts @@ -31,6 +31,7 @@ import { type FixedReadLeafSeamCase, } from '@objectstack/spec/data'; import { ObjectQL, SECURITY_SERVICE_SOURCE_SLOT } from './engine.js'; +import { driverEvaluatesFixedReadLeaf, fixedReadLeafClassOfEngine } from './index.js'; interface SeenCall { verb: string; object: string; ast: any } @@ -426,3 +427,61 @@ describe('[ADR-0155 D4] a refusal at the door is logged on the boundary\'s flag, expect(errorsIn(logger)).toEqual(['error']); }); }); + +describe('[ADR-0155 plan step 5] the seam\'s public face: the recognition an evaluator asks before it compiles', () => { + it('answers the seam\'s own class, or undefined, reading the engine and calling no driver', async () => { + const { engine, calls, farCalls } = await bootEngine(); + expect(fixedReadLeafClassOfEngine(engine, SharedRecordIds.read('srid_doc', 'u1'))).toBeUndefined(); + expect(fixedReadLeafClassOfEngine(engine, SharedRecordIds.read('srid_far', 'u1'))).toMatchObject({ + class: 'other-datasource', object: 'srid_far', table: 'sys_record_share', + }); + engine.registerHook('afterFind', () => {}, { object: 'sys_record_share' }); + expect(fixedReadLeafClassOfEngine(engine, SharedRecordIds.read('srid_doc', 'u1'))).toMatchObject({ + class: 'registration-by-name', table: 'sys_record_share', + }); + expect(calls).toEqual([]); + expect(farCalls).toEqual([]); + }); + + it('driverEvaluatesFixedReadLeaf reads the declaration and nothing else', () => { + expect(driverEvaluatesFixedReadLeaf({ supports: DECLARES }, 'SharedRecordIds')).toBe(true); + expect(driverEvaluatesFixedReadLeaf({ supports: { readableIdsLeaf: true } }, 'SharedRecordIds')).toBe(false); + expect(driverEvaluatesFixedReadLeaf(undefined, 'SharedRecordIds')).toBe(false); + }); +}); + +describe('[ADR-0155 plan step 5, the array-form in / nin decision] D4\'s envelope, never INVALID_FILTER', () => { + for (const op of ['in', 'nin']) { + it(`an array-form ${op} carrying the leaf is refused INTERNAL_ERROR / 500, naming no recipient`, async () => { + const { engine, calls } = await bootEngine(); + const where = [['id', op, SharedRecordIds.read('srid_doc', 'u-secret')]] as unknown as FilterCondition; + const err = await refusalOf(engine.find('srid_doc', { where }, { context: ASKER as any })); + expect(envelopeOf(err)).toEqual(REFUSED); + expect(err?.message).toContain("holds a SharedRecordIds leaf, a fixed read of 'sys_record_share'"); + expect(err?.message).not.toContain('u-secret'); + expect(calls).toEqual([]); + expect(engine.judgeFilter('srid_doc', where)).toMatchObject({ ok: false, ...REFUSED }); + }); + } + + // The type door's refusals: the shape door passes a list and a scalar + // operator, so these answered INVALID_FILTER / 400, printing the leaf's head, + // while the object spelling `{ id: { $in: [leaf] } }` answered 500. + const typeDoor: Array<[string, (leaf: unknown) => unknown]> = [ + ['the leaf as an array-form in list member', (leaf) => ['id', 'in', [leaf]]], + ['the leaf as an array-form != comparand', (leaf) => ['id', '!=', leaf]], + ]; + for (const [what, condition] of typeDoor) { + it(`${what} is refused INTERNAL_ERROR / 500, naming no recipient, as its object spelling is`, async () => { + const { engine, calls } = await bootEngine(); + const where = [condition(SharedRecordIds.read('srid_doc', 'u-secret'))] as unknown as FilterCondition; + const err = await refusalOf(engine.find('srid_doc', { where }, { context: ASKER as any })); + expect(envelopeOf(err)).toEqual(REFUSED); + expect(err?.message).toContain("holds a SharedRecordIds leaf, a fixed read of 'sys_record_share'"); + expect(err?.message).not.toContain('u-secret'); + expect(calls).toEqual([]); + const objectSpelling = { id: { $in: [SharedRecordIds.read('srid_doc', 'u-secret')] } } as unknown as FilterCondition; + expect(envelopeOf(await refusalOf(engine.find('srid_doc', { where: objectSpelling }, { context: ASKER as any })))).toEqual(REFUSED); + }); + } +}); diff --git a/packages/objectql/src/fixed-read-leaf-seam.ts b/packages/objectql/src/fixed-read-leaf-seam.ts index 24ffa64865d..3bb40e642a6 100644 --- a/packages/objectql/src/fixed-read-leaf-seam.ts +++ b/packages/objectql/src/fixed-read-leaf-seam.ts @@ -56,8 +56,9 @@ * * ⛔ 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. + * then nothing on main writes the leaf. `index.ts` re-exports two readers + * from this module and nothing else (plan step 5): {@link fixedReadLeafClassOfEngine} + * and {@link driverEvaluatesFixedReadLeaf}. */ import { fixedInnerReadOf, fixedReadLeafNameOf, type FixedReadLeaf, type FixedReadLeafName } from '@objectstack/spec/data'; @@ -72,6 +73,8 @@ import { isFixedReadLeafSeamRefusal, } from './fixed-read-leaf-position.js'; import { driverNameOf } from './relation-semi-join.js'; +import { securityResolversHost } from './engine-facet-hosts.js'; +import type { ObjectQL } from './engine.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); @@ -139,6 +142,21 @@ export function fixedReadLeafClassOf(host: FixedReadLeafSeamHost, leaf: FixedRea return undefined; } +/** + * [ADR-0155 D4, plan step 5] The public face of {@link fixedReadLeafClassOf} + * for one engine: which of D4's two classes `leaf` falls in on `engine`, or + * `undefined` when neither. The recognition is the seam's own, run over the + * host the executor boundary reads (`securityResolversHost`), so a caller that + * must decline before it compiles (the analytics native compiler, ADR-0155 Q2 + * as ruled) asks it here and ⛔ restates neither class. + * + * Read-only: it reads the engine's datasource bindings, its object-scoped + * middlewares and its find hooks, and calls no driver and logs nothing. + */ +export function fixedReadLeafClassOfEngine(engine: ObjectQL, leaf: FixedReadLeaf): FixedReadLeafClass | undefined { + return fixedReadLeafClassOf(securityResolversHost.of(engine), leaf); +} + /** 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(); diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index f194125d712..679ff7296e6 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -269,6 +269,12 @@ export type { DatasourceDef } from './engine.js'; // refuses the filter rather than truncate it, and its words name this number. // Exported so a caller running the two-step route itself can page by it. export { RELATION_FILTER_ID_CAP } from './relation-filter-lowering.js'; +// [ADR-0155 D4, plan step 5] The seam's recognition of D4's two classes and +// its reader of a driver's `fixedReadLeaves` declaration, so an evaluator that +// declines before it compiles (the analytics native compiler) asks the seam +// and restates neither. +export { driverEvaluatesFixedReadLeaf, fixedReadLeafClassOfEngine } from './fixed-read-leaf-seam.js'; +export type { FixedReadLeafClass } from './fixed-read-leaf-seam.js'; // Groups ordered by an aggregated column, cut and counted in the driver's own // statement: the engine-internal read option a door carries to `aggregate`, // and the request it carries. Carriers that do not import this package spell diff --git a/packages/plugins/plugin-security/src/explain-engine.ts b/packages/plugins/plugin-security/src/explain-engine.ts index 44f19a75e2a..8001b415448 100644 --- a/packages/plugins/plugin-security/src/explain-engine.ts +++ b/packages/plugins/plugin-security/src/explain-engine.ts @@ -84,7 +84,12 @@ import { } from './unresolved-posture.js'; import { grantSetNameOf } from './grant-permission-set-name.js'; import { holdsExternalPosition, humanBaselineFor } from './external-baseline.js'; -import { isExternalAudienceContext } from '@objectstack/core'; +import { isExternalAudienceContext, type ReadableIdsRefusalLog } from '@objectstack/core'; +import { + batchedFixedReadLeafResolver, + resolveFixedReadLeavesAtRecord, + type FixedReadLeafRecordResolver, +} from './explain-fixed-read-leaf.js'; const SYSTEM_CTX = { isSystem: true } as const; @@ -463,6 +468,19 @@ export interface ExplainEngineDeps { fetchRecord?: (object: string, recordId: string, engineOperation: string) => Promise | null>; /** The sharing service's own read-filter contribution for the object (owner-match OR granted-ids), same as enforcement AND-s in. */ sharingReadFilter?: (object: string, context: any) => Promise; + /** + * [ADR-0155 D4, Q2 as ruled] Of the record ids the record pass judges, the + * ones a fixed-read leaf (`SharedRecordIds`) in {@link sharingReadFilter} + * holds: one indexed read under the leaf's own fixed predicate, keyed by the + * ids, the read `checkEdit` makes for one. The pass resolves the leaf at the + * record with it (`explain-fixed-read-leaf.ts`), so the matcher and the + * published `rowFilter` see the record's id or no share arm, ⛔ never the + * leaf. Absent, a filter that carries a leaf is refused in ADR-0139 D3's + * envelope; a rejection is the read filter failing. + */ + resolveFixedReadLeaf?: FixedReadLeafRecordResolver; + /** [ADR-0155 D4] Where the record pass logs its refusal of a fixed-read leaf, once per log. */ + fixedReadLeafRefusalLog?: ReadableIdsRefusalLog; /** * [#26188 · ADR-0057] Is a hierarchy resolver mounted (the * `hierarchy-scope-resolver` service the enterprise `hierarchy-security` @@ -2127,9 +2145,18 @@ async function applyRecordAttribution( } // A rejected read filter is not a `null` one: the matcher reads `null` as // "no filter" and admits the row, while the find it explains fails. - const sharingFilterOrFault = deps.sharingReadFilter && recordExists + const sharingFilterRead = deps.sharingReadFilter && recordExists ? await settle(deps.sharingReadFilter(object, context)) : undefined; + // [ADR-0155 D4, Q2 as ruled] A share-grant leaf in the filter is resolved at + // this record before anything matches or publishes it: the record's id when + // a grant admits it, no share arm otherwise. A leaf the pass does not + // resolve throws D4's refusal here; the read's rejection is the filter's. + const sharingFilterOrFault = sharingFilterRead === undefined || sharingFilterRead === DEPENDENCY_FAULT + ? sharingFilterRead + : await settle(resolveFixedReadLeavesAtRecord( + sharingFilterRead, object, recordId, deps.resolveFixedReadLeaf, deps.fixedReadLeafRefusalLog, + )); const readFilterFault = sharingFilterOrFault === DEPENDENCY_FAULT; const sharingFilter = sharingFilterOrFault === DEPENDENCY_FAULT ? undefined : sharingFilterOrFault; const sharingMatches = sharingFilter === undefined ? undefined : matches(sharingFilter); @@ -2760,6 +2787,9 @@ export async function explainRecordsForAsker( return answer; }; const verdictById = new Map>(); + // [ADR-0155 D4] …and so a share-grant leaf in it is the same leaf for every + // record of the batch: it is read once, keyed by every id the batch judges. + const batchedLeafRead = batchedFixedReadLeafResolver(recordIds); for (const recordId of new Set(recordIds)) { const recordDeps = depsForRecord(recordId); const askerOnce = askedOncePerRecord(asker); @@ -2768,6 +2798,7 @@ export async function explainRecordsForAsker( ...recordDeps, recordAbsentToCaller: askedOnce(recordDeps.recordAbsentToCaller), ...(recordDeps.sharingReadFilter ? { sharingReadFilter: sharedReadFilter(recordDeps.sharingReadFilter) } : {}), + ...(recordDeps.resolveFixedReadLeaf ? { resolveFixedReadLeaf: batchedLeafRead(recordDeps.resolveFixedReadLeaf) } : {}), }, { ...pass, layers: structuredClone(pass.layers) }, recordId, diff --git a/packages/plugins/plugin-security/src/explain-fixed-read-leaf.test.ts b/packages/plugins/plugin-security/src/explain-fixed-read-leaf.test.ts new file mode 100644 index 00000000000..df9900eab37 --- /dev/null +++ b/packages/plugins/plugin-security/src/explain-fixed-read-leaf.test.ts @@ -0,0 +1,231 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0155 plan step 5, Q2 as ruled] The explainer's record pass resolves the +// share-grant leaf (`SharedRecordIds`) AT THE RECORD: one read of +// `sys_record_share` under the leaf's own fixed predicate, keyed by the record +// ids it judges. The sharing layer's published `rowFilter` then has the two +// shapes today's filter has for a caller with one grant on the record (`[id]`) +// and with none (the share arm left out), and ⛔ never carries the leaf. +// +// The sharing service's read filter is replaced here by the shape the step-6 +// producer writes, `{ $or: [owner match, { id: { $in: leaf } }] }`: no producer +// on main writes the leaf yet (plugin-sharing is untouched on this card). The +// rest is the real SecurityPlugin and the real SharingService, over an engine +// double that records its reads. +import { describe, it, expect, vi } from 'vitest'; +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +import { SharingService } from '@objectstack/plugin-sharing'; +import { ReadableIds, SharedRecordIds } from '@objectstack/spec/data'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import type { PermissionSet } from '@objectstack/spec/security'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; + +const OBJECT = 'srl_doc'; +const U_OWNER = 'u_owner'; +const U_READER = 'u_reader'; +const fieldsOf = (...names: string[]) => Object.fromEntries(names.map((n) => [n, { name: n }])); +const SCHEMA = { name: OBJECT, fields: fieldsOf('id', 'name', 'owner_id', 'created_by', 'organization_id') }; + +const READER_SET: PermissionSet = PermissionSetSchema.parse({ + name: 'srl_reader', + objects: { [OBJECT]: { allowRead: true, allowEdit: true, readScope: 'own', writeScope: 'own' } }, +}); +const PERMISSION_SETS = [defaultPermissionSets.find((p) => p.name === 'member_default')!, READER_SET]; +const READER_CTX = { userId: U_READER, tenantId: 'org1', positions: ['org_member'], permissions: ['srl_reader'] }; + +const row = (id: string) => ({ id, name: id, owner_id: U_OWNER, created_by: U_OWNER, organization_id: 'org1' }); +const SHARED = 'doc_shared'; +const UNSHARED = 'doc_unshared'; +const SHARE_ROWS = [ + { id: 's1', object_name: OBJECT, record_id: SHARED, recipient_type: 'user', recipient_id: U_READER, access_level: 'read' }, + // Two grant rows on one record are one member. + { id: 's2', object_name: OBJECT, record_id: SHARED, recipient_type: 'user', recipient_id: U_READER, access_level: 'edit' }, + // Another recipient's grant is theirs alone. + { id: 's3', object_name: OBJECT, record_id: UNSHARED, recipient_type: 'user', recipient_id: 'u_other', access_level: 'read' }, +]; + +function makeEngine() { + const tables: Record = { + [OBJECT]: [row(SHARED), row(UNSHARED)], + sys_record_share: SHARE_ROWS.map((r) => ({ ...r })), + }; + const reads: Array<{ object: string; where: unknown }> = []; + const matches = (r: any, filter: any): boolean => { + if (!filter || typeof filter !== 'object') return true; + for (const [k, v] of Object.entries(filter)) { + if (k.startsWith('$')) throw new Error(`engine double: unsupported operator '${k}'`); + if (v != null && typeof v === 'object') { + if (Object.keys(v as object).join() !== '$in' || !Array.isArray((v as any).$in)) { + throw new Error(`engine double: unsupported predicate on '${k}': ${JSON.stringify(v)}`); + } + if (!(v as any).$in.includes(r[k])) return false; + continue; + } + if (r[k] !== v) return false; + } + return true; + }; + return { + reads, + _middlewares: [] as any[], + registerMiddleware(mw: any) { this._middlewares.push(mw); }, + getSchema: (name: string) => (name === OBJECT ? SCHEMA : undefined), + async find(object: string, options: any = {}) { + reads.push({ object, where: options.where }); + const hits = (tables[object] ?? []).filter((r) => matches(r, options.filter ?? options.where)); + return typeof options.limit === 'number' ? hits.slice(0, options.limit) : hits; + }, + async findOne(object: string, options: any = {}) { + assertEngineFindOnePredicate(object, options); + return (await this.find(object, { ...options, limit: 1 }))[0] ?? null; + }, + }; +} + +async function makeStack() { + const engine = makeEngine(); + let security: any; + let sharing: SharingService; + const errors: string[] = []; + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { get: async (_t: string, name: string) => (name === OBJECT ? SCHEMA : null), list: async () => PERMISSION_SETS }, + get sharing() { return sharing; }, + }; + const ctx: any = { + logger: { info: vi.fn(), warn: vi.fn(), error: (m: string) => void errors.push(String(m)), debug: vi.fn() }, + registerService: (name: string, impl: any) => { if (name === 'security') security = impl; }, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await plugin.init(ctx); + await plugin.start(ctx); + sharing = new SharingService({ engine: engine as any, securityService: () => security }); + // The step-6 producer's shape (see the header): the owner match OR the leaf. + (sharing as any).buildReadFilter = async (object: string, context: any) => + ({ $or: [{ owner_id: context.userId }, { id: { $in: SharedRecordIds.read(object, context.userId) } }] }); + const explain = (operation: 'read' | 'update', target: { recordId?: string; recordIds?: string[] }) => + security.explain({ object: OBJECT, operation, ...target }, { ...READER_CTX }); + return { engine, explain, errors, sharing }; +} + +const sharingLayer = (decision: any) => decision.layers.find((l: any) => l.layer === 'sharing'); +const shareReads = (engine: ReturnType) => engine.reads.filter((r) => r.object === 'sys_record_share'); +/** No trace of the leaf in what crosses the wire: its fields, its recipient, its brand. */ +function expectNoLeafOnTheWire(decision: any): void { + const wire = JSON.stringify(decision); + expect(wire).not.toContain('"recipient"'); + expect(wire).not.toContain('sharedRecordIds'); + expect(JSON.stringify(sharingLayer(decision).record.rowFilter)).not.toContain(`"object":"${OBJECT}"`); +} + +describe('[ADR-0155 Q2] the explainer resolves the share-grant leaf at the record', () => { + for (const operation of ['read', 'update'] as const) { + it(`${operation}: one grant admits the record, so the share arm is [id], and the record is visible`, async () => { + const { engine, explain } = await makeStack(); + const decision = await explain(operation, { recordId: SHARED }); + const record = sharingLayer(decision).record; + expect(record.rowFilter).toEqual({ $or: [{ owner_id: U_READER }, { id: { $in: [SHARED] } }] }); + expect(record.matchesRecord).toBe(true); + expectNoLeafOnTheWire(decision); + // One indexed read under the leaf's own fixed predicate, keyed by the judged id. + expect(shareReads(engine).map((r) => r.where)).toContainEqual({ + object_name: OBJECT, recipient_type: 'user', recipient_id: U_READER, record_id: { $in: [SHARED] }, + }); + if (operation === 'read') expect(decision.record).toMatchObject({ recordId: SHARED, visible: true }); + }); + + it(`${operation}: no grant admits the record, so the share arm is left out, and the record is excluded`, async () => { + const { explain } = await makeStack(); + const decision = await explain(operation, { recordId: UNSHARED }); + const record = sharingLayer(decision).record; + expect(record.rowFilter).toEqual({ owner_id: U_READER }); + expect(record.matchesRecord).toBe(false); + expectNoLeafOnTheWire(decision); + if (operation === 'read') expect(decision.record).toMatchObject({ recordId: UNSHARED, visible: false }); + }); + } + + it('nothing of the leaf crosses the wire, granted or not, single or batch: a pin of its own', async () => { + const { explain } = await makeStack(); + for (const operation of ['read', 'update'] as const) { + for (const recordId of [SHARED, UNSHARED]) expectNoLeafOnTheWire(await explain(operation, { recordId })); + } + const batch = JSON.stringify(await explain('read', { recordIds: [SHARED, UNSHARED] })); + expect(batch).not.toContain('"recipient"'); + expect(batch).not.toContain('sharedRecordIds'); + }); + + it('the batch form reads the leaf once, keyed by every id it judges, and answers each record its own shape', async () => { + const { engine, explain } = await makeStack(); + const decision = await explain('read', { recordIds: [SHARED, UNSHARED, SHARED] }); + expect(decision.records.map((r: any) => r.visible)).toEqual([true, false, true]); + const keyed = shareReads(engine).filter((r) => (r.where as any)?.record_id?.$in); + expect(keyed).toHaveLength(1); + expect((keyed[0]!.where as any).record_id.$in).toEqual([SHARED, UNSHARED]); + }); + + it('a leaf out of position is refused in D4\'s envelope, logged once, never matched or published', async () => { + const { explain, sharing, errors } = await makeStack(); + (sharing as any).buildReadFilter = async (object: string, context: any) => + ({ $or: [{ owner_id: context.userId }, { id: { $nin: SharedRecordIds.read(object, context.userId) } }] }); + for (let i = 0; i < 2; i++) { + const err = await explain('read', { recordId: SHARED }).then(() => null, (e: any) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INTERNAL_ERROR', status: 500 }); + expect(err?.message).toContain('[plugin-security explain]'); + expect(err?.message).not.toContain(U_READER); + } + expect(errors.filter((m) => m.includes('fixed read of'))).toHaveLength(1); + }); + + // A leaf is admitted by its role, as the engine's seam and the analytics + // compiler admit it, never by the key it sits under: these sit under `id` + // as $in's comparand and name the explained object, but not in its where. + const MISPLACED: Array<[string, string, (object: string, userId: string) => unknown]> = [ + [ + 'inside a relation condition (a self-relation)', 'rowFilter.$or[1].manager.id.$in', + (object, userId) => ({ $or: [{ owner_id: userId }, { manager: { id: { $in: SharedRecordIds.read(object, userId) } } }] }), + ], + [ + 'inside a composed ReadableIds scope', 'rowFilter.$or[1].id.$in.scope.id.$in', + (object, userId) => ({ + $or: [ + { owner_id: userId }, + { id: { $in: ReadableIds.compose(ReadableIds.of(object), { id: { $in: SharedRecordIds.read(object, userId) } }) } }, + ], + }), + ], + ]; + for (const [where, at, readFilter] of MISPLACED) { + it(`a leaf ${where} is refused in D4's envelope, logged once, never resolved or published`, async () => { + const { explain, sharing, errors, engine } = await makeStack(); + (sharing as any).buildReadFilter = async (object: string, context: any) => readFilter(object, context.userId); + for (let i = 0; i < 2; i++) { + const err = await explain('read', { recordId: SHARED }).then(() => null, (e: any) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INTERNAL_ERROR', status: 500 }); + expect(err?.message).toContain(`[plugin-security explain] the sharing read filter of '${OBJECT}': ${at} holds a SharedRecordIds leaf`); + expect(err?.message).not.toContain(U_READER); + } + expect(errors.filter((m) => m.includes('fixed read of'))).toHaveLength(1); + // Refused before the leaf's own read: nothing resolved it at the record. + expect(shareReads(engine).filter((r) => (r.where as any)?.recipient_id !== undefined)).toEqual([]); + }); + } + + it('the share read failing is the read filter failing: the record is not visible, and no filter is published', async () => { + const { explain, engine } = await makeStack(); + const find = engine.find.bind(engine); + engine.find = async (object: string, options: any) => { + if (object === 'sys_record_share') throw new Error('share store down'); + return find(object, options); + }; + const decision = await explain('read', { recordId: SHARED }); + expect(decision.record).toMatchObject({ recordId: SHARED, visible: false, decidedBy: 'sharing' }); + expect(sharingLayer(decision).record.rowFilter).toBeUndefined(); + }); +}); diff --git a/packages/plugins/plugin-security/src/explain-fixed-read-leaf.ts b/packages/plugins/plugin-security/src/explain-fixed-read-leaf.ts new file mode 100644 index 00000000000..3ca8ca272d2 --- /dev/null +++ b/packages/plugins/plugin-security/src/explain-fixed-read-leaf.ts @@ -0,0 +1,264 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 D4, Q2 as ruled] The explainer's record pass over a FIXED-READ + * LEAF (`@objectstack/spec/data`'s `isFixedReadLeaf`: `SharedRecordIds`) in the + * sharing service's read filter: **the leaf is resolved at the record.** + * + * The record pass matches the read filter against the judged record in + * process and publishes it as the sharing layer's `rowFilter`. A leaf is a + * set the database holds ("the records of X shared with this user"), so the + * pass asks it ONE question per explanation: which of the record ids it + * judges does the leaf's fixed inner read hold? That is one indexed read + * under the leaf's own fixed predicate (`fixedInnerReadOf`), keyed by those + * ids, the read `checkEdit` makes for one (`{@link FixedReadLeafRecordResolver}`, + * wired by the plugin). ⛔ No predicate restated by hand. + * + * Each leaf is then replaced, in a copy of the filter, by what it holds of the + * judged record: `[recordId]` when a grant admits it, and nothing otherwise. + * "Nothing" leaves the share arm out of the `$or` it sits in, and an `$or` + * left with one arm is that arm, so the published filter has the two shapes + * today's filter has for a caller with one grant on the record and with none + * (ADR-0155 Q2 costs). Anywhere an arm cannot be left out (under `$and` or + * `$not`) the empty list stays, which matches no record, as the leaf would. + * ⛔ The published `rowFilter` never carries the leaf: its brand is a symbol + * no JSON keeps, so it would cross the wire as an ordinary-looking object. + * + * What it does not resolve is refused, in ADR-0139 D3's envelope + * (`INTERNAL_ERROR` / 500, logged at `error` once per evaluator), ⛔ never read + * as an ordinary comparand: a leaf anywhere but the `$in` comparand of `id` on + * the explained object, a leaf in its write form (a read filter carries the + * read form, ③ ruled A), and any leaf where the host wired no resolver. + */ + +import { describeFixedReadLeaf, refuseFixedReadLeafOnce, type ReadableIdsRefusalLog } from '@objectstack/core'; +import { isComposedReadableIds, isFixedReadLeaf, type FixedReadLeaf } from '@objectstack/spec/data'; + +/** The evaluator the explainer's refusals name. */ +export const EXPLAIN_FIXED_READ_LEAF_EVALUATOR = 'plugin-security explain'; + +/** + * Of `recordIds`, the ids `leaf`'s fixed inner read holds: one read under the + * leaf's own description, keyed by the ids. A rejection is the read failing. + */ +export type FixedReadLeafRecordResolver = (leaf: FixedReadLeaf, recordIds: readonly string[]) => Promise>; + +/** Where the explainer's refusal is logged, once per log. */ +const LOGGED = new WeakMap(); + +function flagOf(log: ReadableIdsRefusalLog | undefined): { logged: boolean } { + if (log === undefined) return { logged: true }; + let flag = LOGGED.get(log); + if (flag === undefined) LOGGED.set(log, (flag = { logged: false })); + return flag; +} + +/** A plain object or a list: what a filter is built from. */ +function isPlainContainer(value: unknown): value is Record | unknown[] { + 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; +} + +/** Does `filter` carry a fixed-read leaf anywhere (a composed `ReadableIds` scope included)? */ +export function carriesFixedReadLeaf(filter: unknown): boolean { + const onPath = new Set(); + const visit = (value: unknown): boolean => { + if (isFixedReadLeaf(value)) return true; + if (isComposedReadableIds(value)) return visit(value.scope); + if (!isPlainContainer(value) || onPath.has(value)) return false; + onPath.add(value); + try { + return (Array.isArray(value) ? value : Object.values(value)).some(visit); + } finally { + onPath.delete(value); + } + }; + return visit(filter); +} + +/** The explainer's refusal of `leaf` at `at`, thrown by the caller. */ +function refusal(at: string, leaf: unknown, object: string, why: string, log: ReadableIdsRefusalLog | undefined): Error { + return refuseFixedReadLeafOnce( + EXPLAIN_FIXED_READ_LEAF_EVALUATOR, + `the sharing read filter of '${object}': ${describeFixedReadLeaf(at, leaf)}${why} The explanation was NOT ` + + 'produced, rather than match the leaf as an ordinary comparand or publish it.', + log, + flagOf(log), + object, + ); +} + +/** + * Every leaf `filter` carries where the record pass resolves one, `{ id: { $in: leaf } }` + * on `object`, in its read form; any other leaf is refused. + * + * The walk reads roles, as the engine's seam and the analytics compiler do: a + * NODE's keys are combinators (`$and`, `$or`, `$not`) and fields; a field's + * plain-object value is an OPERATOR MAP, whose keys are operators; and only an + * operator map's `$in` holds a leaf. Everything else is walked as a value, where + * any leaf is misplaced: a list member, a bare field value, a relation + * condition's inner `{ id: { $in: leaf } }` (a field's value read as a map, so + * its `id` is an operator there), a leaf in a composed `ReadableIds` scope (the + * ids of another read, which the judged record's id does not answer), or a + * node of its own. Cycles are cut on the current path. + */ +function resolvableLeavesOf(filter: unknown, object: string, log: ReadableIdsRefusalLog | undefined): Set { + const leaves = new Set(); + const onPath = new Set(); + const misplaced = (at: string, leaf: unknown): Error => + refusal( + at, leaf, object, + ', where the record pass resolves none: a fixed-read leaf sits only as the $in comparand of id on the ' + + 'object it names (ADR-0155 D1). Place it as { id: { $in: leaf } }.', + log, + ); + const descend = (value: object, walk: () => void): void => { + if (onPath.has(value)) return; + onPath.add(value); + try { + walk(); + } finally { + onPath.delete(value); + } + }; + const visitValue = (value: unknown, at: string): void => { + if (isFixedReadLeaf(value)) throw misplaced(at, value); + if (isComposedReadableIds(value)) { + visitValue(value.scope, `${at}.scope`); + return; + } + if (!isPlainContainer(value)) return; + descend(value, () => { + if (Array.isArray(value)) value.forEach((item, i) => visitValue(item, `${at}[${i}]`)); + else for (const key of Object.keys(value)) visitValue(value[key], `${at}.${key}`); + }); + }; + const visitOperatorMap = (map: Record, at: string, field: string): void => + descend(map, () => { + for (const op of Object.keys(map)) { + const comparand = map[op]; + if (op !== '$in' || !isFixedReadLeaf(comparand)) { + visitValue(comparand, `${at}.${op}`); + continue; + } + if (field !== 'id' || comparand.object !== object) throw misplaced(`${at}.${op}`, comparand); + if (comparand.accessLevels !== undefined) { + throw refusal( + `${at}.${op}`, comparand, object, + ' in its WRITE form, which only a predicate update carries (ADR-0155 ③ ruled A). A read filter carries ' + + 'SharedRecordIds.read(object, recipient).', + log, + ); + } + leaves.add(comparand); + } + }); + const visitNode = (node: unknown, at: string): void => { + if (isFixedReadLeaf(node) || !isPlainContainer(node) || Array.isArray(node)) { + visitValue(node, at); + return; + } + descend(node, () => { + for (const key of Object.keys(node)) { + const value = node[key]; + const here = `${at}.${key}`; + if ((key === '$and' || key === '$or') && Array.isArray(value)) value.forEach((arm, i) => visitNode(arm, `${here}[${i}]`)); + else if (key === '$not') visitNode(value, here); + else if (!key.startsWith('$') && !isFixedReadLeaf(value) && isPlainContainer(value) && !Array.isArray(value)) { + visitOperatorMap(value, here, key); + } else visitValue(value, here); + } + }); + }; + visitNode(filter, 'rowFilter'); + return leaves; +} + +/** `{ : { $in: [] } }` with nothing else: the arm a leaf that holds nothing leaves behind. */ +function isEmptiedArm(arm: unknown): boolean { + if (!isPlainContainer(arm) || Array.isArray(arm)) return false; + const keys = Object.keys(arm); + if (keys.length !== 1 || keys[0]!.startsWith('$')) return false; + const spec = arm[keys[0]!]; + if (!isPlainContainer(spec) || Array.isArray(spec)) return false; + const ops = Object.keys(spec); + return ops.length === 1 && ops[0] === '$in' && Array.isArray(spec.$in) && spec.$in.length === 0; +} + +/** + * A copy of `value` with each resolved leaf replaced by its members, and each + * emptied `$or` arm left out. Copy-on-write: a subtree that carries no leaf + * (another branded leaf among them) is kept by reference. + */ +function substitute(value: unknown, held: ReadonlyMap): unknown { + if (isFixedReadLeaf(value)) return [...(held.get(value) ?? [])]; + if (!isPlainContainer(value) || !carriesFixedReadLeaf(value)) return value; + if (Array.isArray(value)) return value.map((item) => substitute(item, held)); + const out: Record = {}; + for (const key of Object.keys(value)) out[key] = substitute(value[key], held); + if (Array.isArray(out.$or)) { + const arms = out.$or.filter((arm, i) => !(isEmptiedArm(arm) && carriesFixedReadLeaf((value.$or as unknown[])[i]))); + // Every arm emptied is the empty set, which `$in: []` keeps saying. + if (arms.length > 0) out.$or = arms; + if (arms.length === 1 && Object.keys(out).length === 1) return arms[0]; + } + return out; +} + +/** + * [ADR-0155 D4, Q2 as ruled] `filter` with every fixed-read leaf resolved at + * `recordId` (see the module note), or `filter` itself, by reference, when it + * carries none. + * + * Two failures, kept apart on purpose: the refusal for a leaf it does not + * resolve is THROWN, synchronously, before any read, so it propagates as the + * fault it is; the resolver's rejection REJECTS the returned promise, which + * the record pass reads as the read filter failing, as it reads the sharing + * service's own rejection. + */ +export function resolveFixedReadLeavesAtRecord( + filter: unknown, + object: string, + recordId: string, + resolve: FixedReadLeafRecordResolver | undefined, + log: ReadableIdsRefusalLog | undefined, +): Promise { + if (!carriesFixedReadLeaf(filter)) return Promise.resolve(filter); + const leaves = resolvableLeavesOf(filter, object, log); + if (resolve === undefined) { + const [first] = leaves; + throw refusal( + 'rowFilter', first, object, + ' with no reader of its fixed inner read wired for the record pass (resolveFixedReadLeaf).', + log, + ); + } + return (async () => { + const held = new Map(); + for (const leaf of leaves) { + const ids = await resolve(leaf, [recordId]); + held.set(leaf, ids.has(recordId) ? [recordId] : []); + } + return substitute(filter, held); + })(); +} + +/** + * [#29112] A resolver for a batch of `recordIds`: the first question about a + * leaf reads it once, keyed by every id of the batch, and every later question + * about that leaf is answered from that read. The batch shares one read filter + * per (object, context), so its leaves are the same objects for every record. + */ +export function batchedFixedReadLeafResolver(recordIds: readonly string[]): ( + resolve: FixedReadLeafRecordResolver, +) => FixedReadLeafRecordResolver { + const reads = new Map>>(); + const batch = [...new Set(recordIds)]; + return (resolve) => (leaf, ids) => { + let read = reads.get(leaf); + if (read === undefined) reads.set(leaf, (read = resolve(leaf, [...new Set([...batch, ...ids])]))); + return read; + }; +} diff --git a/packages/plugins/plugin-security/src/security-plugin-explain-access.ts b/packages/plugins/plugin-security/src/security-plugin-explain-access.ts index 5de09ad83b7..c9e12d81d36 100644 --- a/packages/plugins/plugin-security/src/security-plugin-explain-access.ts +++ b/packages/plugins/plugin-security/src/security-plugin-explain-access.ts @@ -68,6 +68,7 @@ * Nothing re-exports this module, so the published surface does not move. */ import { resolveUserAuthzGrants, vetOrganizationClaim } from '@objectstack/core'; +import { fixedInnerReadOf } from '@objectstack/spec/data'; import { OWNERSHIP_QUEUE_SERVICE, type AuthoredRowWriteOperation, type IOwnershipQueueService } from '@objectstack/spec/contracts'; import type { ExplainDecision, ExplainOperation, PermissionSet } from '@objectstack/spec/security'; import type { SecurityPlugin } from './security-plugin.js'; @@ -97,6 +98,7 @@ import { */ export interface ExplainAccessHost { readonly baselinePermissionSets: SecurityPlugin['baselinePermissionSets']; + readonly logger: SecurityPlugin['logger']; readonly delegatedAdminGate: SecurityPlugin['delegatedAdminGate']; readonly permissionEvaluator: SecurityPlugin['permissionEvaluator']; readonly ql: SecurityPlugin['ql']; @@ -167,7 +169,7 @@ export async function mayDescribeAnotherUser( /** The body of `SecurityPlugin#explainAccessForCaller`; the method's docblock there is its contract. */ export async function explainAccessForCaller( - this: Pick, + this: Pick, request: { object: string; operation: string; userId?: string; recordId?: string; recordIds?: readonly string[] }, callerContext?: any, ): Promise { @@ -484,6 +486,20 @@ export async function explainAccessForCaller( actsOnBehalfOf(c) ? sharing.buildReadFilter(o, c) : readFilterWithReadScope(o, c), } : {}), + // [ADR-0155 D4, Q2 as ruled] A share-grant leaf in that filter, resolved + // at the record: one indexed read under the leaf's own fixed predicate + // (`fixedInnerReadOf`), keyed by the record ids the pass judges, under + // system authority: the read `checkEdit` makes for one. ⛔ No predicate + // restated here, and no tenant scope on it (ADR-0155 ① ruled A). + resolveFixedReadLeaf: async (leaf, ids) => { + const read = fixedInnerReadOf(leaf); + const where: Record = { ...read.equals }; + for (const [column, values] of Object.entries(read.memberOf)) where[column] = { $in: [...values] }; + where[read.column] = { $in: [...ids] }; + const rows = await this.ql.find(read.table, { where, fields: [read.column], context: { isSystem: true } }); + return new Set((Array.isArray(rows) ? rows : []).map((row: Record) => String(row[read.column]))); + }, + fixedReadLeafRefusalLog: this.logger, // [#26188 · ADR-0057] Asked by the depth layer's record cell: with no // resolver mounted a hierarchy read depth is evaluated as 'own', and the // cell names that instead of the depth. The kernel's own answer, read diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index 34f99f645f6..0546f3d342a 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -2615,7 +2615,8 @@ export class SecurityPlugin implements Plugin { const readQl = () => this.ql; const readResolveKernelService = () => this.resolveKernelService; const readTenancyPosture = () => this.tenancyPosture; - const host: Pick = { + const readLogger = () => this.logger; + const host: Pick = { baselinePermissionSets: this.baselinePermissionSets, checkControlledByParentWrite: (...a) => this.checkControlledByParentWrite(...a), collectRLSPolicies: (...a) => this.collectRLSPolicies(...a), @@ -2625,6 +2626,7 @@ export class SecurityPlugin implements Plugin { get delegatedAdminGate() { return readDelegatedAdminGate(); }, foldFieldRequiredPermissions: (...a) => this.foldFieldRequiredPermissions(...a), getObjectSecurityMeta: (...a) => this.getObjectSecurityMeta(...a), + get logger() { return readLogger(); }, get permissionEvaluator() { return readPermissionEvaluator(); }, get ql() { return readQl(); }, readRowById: (...a) => this.readRowById(...a), diff --git a/packages/services/service-analytics/src/__tests__/fixed-read-leaf-native-compile.test.ts b/packages/services/service-analytics/src/__tests__/fixed-read-leaf-native-compile.test.ts new file mode 100644 index 00000000000..d8802db2e80 --- /dev/null +++ b/packages/services/service-analytics/src/__tests__/fixed-read-leaf-native-compile.test.ts @@ -0,0 +1,300 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 plan step 5, Q2 as ruled] The share-grant leaf (`SharedRecordIds`) + * on the analytics faces: + * + * - **the native compiler compiles it** (`compileScopedFilterToSql`): the + * step-1 conformance cases (`SHARED_RECORD_IDS_CASE_SET`), live on SQLite, + * answer exactly their rows; the write form is refused in D4's envelope; + * - **it declines D4's two classes** (`NativeSQLStrategy.canHandle`), asking + * the engine seam's own recognition (`fixedReadLeafClassOfEngine`), and + * declines too when it cannot ask; + * - **the engine strategy's merge admits the brand**, and the engine answers + * the same rows the native statement does; + * - **the echo prints the subquery** (`/analytics/sql`). + * + * The invariant (D-0): the native face answers the engine path's rows, or the + * query goes to the engine path, or the answer is D4's refusal, + * `INTERNAL_ERROR` / 500. ⛔ No third, quieter answer. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { ObjectQL, fixedReadLeafClassOfEngine } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import { + SHARED_RECORD_IDS_CASE_SET, + SharedRecordIds, + isComposedReadableIds, + isFixedReadLeaf, +} from '@objectstack/spec/data'; +import type { Cube, FilterCondition } from '@objectstack/spec/data'; +import type { AnalyticsQuery } from '@objectstack/spec/contracts'; + +import { AnalyticsService } from '../analytics-service.js'; +import { + READ_SCOPE_FIXED_READ_LEAF_BRANDS, + assertReadScopeComparandsRunnable, + compileScopedFilterToSql, +} from '../read-scope-sql.js'; + +const S = SHARED_RECORD_IDS_CASE_SET; +const REFUSED = { code: 'INTERNAL_ERROR', status: 500 }; + +const quiet = { debug() {}, info() {}, warn() {}, error() {}, child() { return quiet; } }; + +/** Every column a case-set table's rows carry, declared text. */ +function fieldsOf(table: (typeof S.tables)[number]): Record> { + const columns = new Set(); + for (const row of table.rows) for (const column of Object.keys(row)) columns.add(column); + return Object.fromEntries([...columns].map((name) => [name, { type: 'text', name }])); +} + +/** What a case's `where` holds that this read-only compiler never compiles. */ +function shapeOf(where: unknown): 'composed' | 'write-form' | 'plain' { + let found: 'composed' | 'write-form' | 'plain' = 'plain'; + const visit = (value: unknown): void => { + if (isComposedReadableIds(value)) found = 'composed'; + else if (isFixedReadLeaf(value)) { if (value.accessLevels !== undefined && found === 'plain') found = 'write-form'; } + else if (value !== null && typeof value === 'object') for (const v of Object.values(value)) visit(v); + }; + visit(where); + return found; +} + +type Thrown = (Error & { code?: string; status?: number }) | null; +const thrownBy = (fn: () => unknown): Thrown => { + try { + fn(); + return null; + } catch (e) { + return e as Thrown; + } +}; +const envelopeOf = (err: Thrown) => ({ code: err?.code, status: err?.status }); + +describe('[ADR-0155 Q2] the share-grant leaf on the analytics faces, live on SQLite', () => { + let driver: SqliteWasmDriver; + let engine: ObjectQL; + let readScope: unknown = null; + + const runRawSql = async (sql: string, params: unknown[]): Promise[]> => { + const result = await driver.execute(sql.replace(/\$\d+/g, '?'), params as unknown[]); + if (Array.isArray(result)) return result as Record[]; + if (result && typeof result === 'object' && 'rows' in (result as Record)) { + return (result as { rows: Record[] }).rows; + } + return []; + }; + + beforeAll(async () => { + driver = new SqliteWasmDriver({ filename: ':memory:' }); + (driver as unknown as { logger: unknown }).logger = quiet; + await driver.initObjects(S.tables.map((t) => ({ name: t.object, fields: fieldsOf(t) })) as never); + for (const table of S.tables) for (const row of table.rows) await driver.create(table.object, { ...row }); + engine = new ObjectQL({ logger: quiet }); + engine.registerDriver(driver as never, true); + await engine.init(); + for (const table of S.tables) engine.registerObject({ name: table.object, label: table.object, fields: fieldsOf(table) } as never); + }); + + afterAll(async () => { + await driver?.disconnect?.(); + }); + + describe('the native compiler against the step-1 conformance cases', () => { + for (const c of S.cases) { + const shape = shapeOf(c.where()); + if (shape === 'composed') { + // A composed ReadableIds scope is the engine's own artifact (it composes + // at its executor boundary); a read scope reaches this compiler + // uncomposed, and `canHandle` declines it (ADR-0139 D6). Handed one + // anyway, the compiler runs no composition and refuses, 500, rather + // than answer rows. + it(`refuses, runs no composition: ${c.name}`, () => { + const err = thrownBy(() => compileScopedFilterToSql(c.where(), c.object, { object: c.object, dialect: 'sqlite' })); + expect(err?.status).toBe(500); + }); + continue; + } + it(`${shape === 'write-form' ? 'refuses' : 'matches'}: ${c.name}`, async () => { + const compile = () => compileScopedFilterToSql(c.where(), c.object, { object: c.object, dialect: 'sqlite' }); + if (shape === 'write-form') { + // A read-only evaluator: the write form is a predicate update's alone (③ ruled A). + expect(envelopeOf(thrownBy(compile))).toEqual(REFUSED); + return; + } + const { sql, params } = compile(); + // The outer statement's tenant wall is the caller's, untouched; the + // subquery carries none (① ruled A). + const wall = c.options ? ` AND "${c.object}"."${S.tenantField}" = ?` : ''; + const rows = await runRawSql( + `SELECT "id" FROM "${c.object}" WHERE (${sql})${wall} ORDER BY "id"`, + c.options ? [...params, c.options.tenantId] : params, + ); + expect(rows.map((r) => String(r.id))).toEqual([...c.expected]); + if (c.holdsLeaf) expect(sql).toContain('IN (SELECT "record_id" FROM "sys_record_share" WHERE'); + }); + } + }); + + it('binds every value and splices none: the recipient never reaches the statement text', () => { + const { sql, params } = compileScopedFilterToSql({ id: { $in: SharedRecordIds.read('srid_doc', "u1' OR 1=1 --") } } as FilterCondition, 't', { object: 'srid_doc' }); + expect(sql).toBe( + '"t"."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" <> \'\')', + ); + expect(params).toEqual(['srid_doc', 'user', "u1' OR 1=1 --"]); + }); + + describe('a leaf the compiler does not compile is refused in D4\'s envelope, logged once', () => { + const leaf = () => SharedRecordIds.read('srid_doc', 'u1'); + const MISPLACED: Array<[string, () => unknown]> = [ + ['under $nin', () => ({ id: { $nin: leaf() } })], + ['as a list member', () => ({ id: { $in: [leaf()] } })], + ['as a bare field value', () => ({ id: leaf() })], + ['as a $not operand', () => ({ $not: leaf() })], + ['on another field', () => ({ owner: { $in: leaf() } })], + ['in another object\'s scope', () => ({ id: { $in: SharedRecordIds.read('srid_note', 'u1') } })], + ]; + for (const [where, scope] of MISPLACED) { + it(`${where}: compiler and engine-bound merge alike`, () => { + const lines: string[] = []; + const sink = { logger: { warn() {}, error: (m: string) => void lines.push(m) }, state: { logged: false } }; + for (let i = 0; i < 2; i++) { + const compiled = thrownBy(() => compileScopedFilterToSql(scope() as FilterCondition, 'srid_doc', { object: 'srid_doc', fixedReadLeafRefusal: sink })); + expect(envelopeOf(compiled)).toEqual(REFUSED); + expect(compiled?.message).toContain('[service-analytics]'); + expect(compiled?.message).not.toContain('u1'); + const merged = thrownBy(() => assertReadScopeComparandsRunnable(scope(), 'srid_doc', { + admitReadableIds: true, admitFixedReadLeaves: READ_SCOPE_FIXED_READ_LEAF_BRANDS, fixedReadLeafRefusal: sink, object: 'srid_doc', + })); + expect(envelopeOf(merged)).toEqual(REFUSED); + } + expect(lines).toHaveLength(1); + }); + } + + it('the merge admits a placed read-form leaf; without the brand named, the merge refuses it as before', () => { + const scope = { $or: [{ owner: 'u1' }, { id: { $in: leaf() } }] }; + expect(thrownBy(() => assertReadScopeComparandsRunnable(scope, 'srid_doc', { + admitReadableIds: true, admitFixedReadLeaves: READ_SCOPE_FIXED_READ_LEAF_BRANDS, object: 'srid_doc', + }))).toBeNull(); + expect(envelopeOf(thrownBy(() => assertReadScopeComparandsRunnable(scope, 'srid_doc', { admitReadableIds: true })))) + .toEqual({ code: 'READ_SCOPE_COMPILE_FAILED', status: 500 }); + }); + }); + + describe('the strategies: the native statement, its declines, and the engine path agree', () => { + const CUBE: Cube = { + name: 'docs', + sql: 'srid_doc', + measures: { n: { sql: '*', type: 'count', title: 'n' } }, + dimensions: { id: { label: 'id', type: 'string', sql: 'id' } }, + public: true, + } as unknown as Cube; + const QUERY = { cube: 'docs', dimensions: ['id'], measures: ['n'] } as AnalyticsQuery; + const CONTEXT = { userId: 'u1' } as never; + const READ_SCOPE = S.cases.find((c) => c.name.startsWith("the read scope's shape"))!; + + const executeAggregate = async (objectName: string, options: any) => + (await engine.aggregate(objectName, { + where: options.filter, + groupBy: options.groupBy, + aggregations: options.aggregations?.map((a: any) => ({ function: a.method, field: a.field, alias: a.alias })), + context: options.context, + } as never)) as Record[]; + + const service = (opts: { native: boolean; classOf?: 'seam' | 'absent' }) => { + const rawSql = vi.fn(runRawSql); + const svc = new AnalyticsService({ + cubes: [CUBE], + logger: quiet, + queryCapabilities: () => ({ nativeSql: opts.native, objectqlAggregate: true, inMemory: false }), + getReadScope: () => (readScope ?? undefined) as FilterCondition | undefined, + executeAggregate, + ...(opts.native + ? { + executeRawSql: (_object: string, sql: string, params: unknown[]) => rawSql(sql, params), + hasObjectMiddleware: () => false, + sqlDialect: () => 'sqlite' as const, + } + : {}), + // The seam's recognition, as a host that holds the engine wires it. + ...(opts.classOf === 'seam' ? { fixedReadLeafClassOf: (leaf: any) => fixedReadLeafClassOfEngine(engine, leaf) ?? null } : {}), + judgeFilter: (o: string, w: any, j: any) => engine.judgeFilter(o, w, j), + }); + return { svc, rawSql }; + }; + const idsOf = (rows: Array>) => rows.map((r) => String(r.id)).sort(); + + it('neither class applies: the native face compiles the subquery and answers the engine path\'s rows', async () => { + readScope = READ_SCOPE.where(); + const native = service({ native: true, classOf: 'seam' }); + const nativeRows = idsOf((await native.svc.query(QUERY, CONTEXT)).rows); + expect(native.rawSql).toHaveBeenCalledTimes(1); + expect(native.rawSql.mock.calls[0]![0]).toContain('IN (SELECT "record_id" FROM "sys_record_share"'); + readScope = READ_SCOPE.where(); + const engineRows = idsOf((await service({ native: false }).svc.query(QUERY, CONTEXT)).rows); + expect(nativeRows).toEqual([...READ_SCOPE.expected]); + expect(engineRows).toEqual(nativeRows); + }); + + it('a host that cannot ask the seam declines to the engine path, with the same rows', async () => { + readScope = READ_SCOPE.where(); + const native = service({ native: true, classOf: 'absent' }); + expect(idsOf((await native.svc.query(QUERY, CONTEXT)).rows)).toEqual([...READ_SCOPE.expected]); + expect(native.rawSql).not.toHaveBeenCalled(); + }); + + it('a find hook registered for sys_record_share by name: the native face declines, and the engine\'s seam refuses (D4)', async () => { + const hookEngine = engine; + hookEngine.registerHook('beforeFind', () => {}, { object: 'sys_record_share' }); + try { + readScope = READ_SCOPE.where(); + const native = service({ native: true, classOf: 'seam' }); + const err = await native.svc.query(QUERY, CONTEXT).then(() => null, (e: any) => e); + expect(native.rawSql).not.toHaveBeenCalled(); + expect({ code: err?.code, status: err?.status }).toEqual(REFUSED); + } finally { + (hookEngine as any).hooks.get('beforeFind').pop(); + } + }); + + // Compile surface 2. The read scope is the only door a leaf enters analytics + // by. Before plan step 5 the where face answered 400 printing the recipient + // for `$in`, and read a bare value or an array-form `=` as a relation + // condition on `id`. Each spelling is its own pin, and each names the where + // face's evaluator: the array-form `in` is refused by `parseFilterAST` too, + // so only the evaluator tells the two refusals apart. + const secret = SharedRecordIds.read('srid_doc', 'u-secret-42'); + const WHERES: ReadonlyArray = [ + ['{ id: { $in: leaf } }', { id: { $in: secret } }], + ['a bare { id: leaf }', { id: secret }], + ['$eq under $or', { $or: [{ owner: 'u1' }, { id: { $eq: secret } }] }], + ['the array form in', [['id', 'in', secret]]], + ['the array form =', [['id', '=', secret]]], + ]; + for (const [spelling, where] of WHERES) { + it(`a leaf in the caller's where, ${spelling}, is refused by the where face before either strategy runs`, async () => { + for (const native of [true, false]) { + readScope = null; + const { svc, rawSql } = service({ native, classOf: 'seam' }); + const err = await svc.query({ ...QUERY, where } as AnalyticsQuery, CONTEXT).then(() => null, (e: any) => e); + expect({ code: err?.code, status: err?.status }, JSON.stringify({ native, spelling })).toEqual(REFUSED); + expect(err?.message).toContain('[service-analytics where]'); + expect(err?.message).toContain('holds a SharedRecordIds leaf, a fixed read of \'sys_record_share\''); + expect(err?.message).not.toContain('u-secret-42'); + expect(rawSql).not.toHaveBeenCalled(); + } + }); + } + + it('the /analytics/sql echo prints the subquery the statement runs', async () => { + readScope = READ_SCOPE.where(); + const { sql, params } = await service({ native: false }).svc.generateSql(QUERY, CONTEXT); + expect(sql).toContain('"srid_doc"."id" IN (SELECT "record_id" FROM "sys_record_share" WHERE "object_name" = $'); + expect(params).toEqual(expect.arrayContaining(['srid_doc', 'user', 'u1'])); + }); + }); +}); diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index 040278e1fc4..f688da94d38 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -7,7 +7,7 @@ import type { CubeMeta, DatasetSelection, } from '@objectstack/spec/contracts'; -import { percentScaleOf, AggregationFunction, type Cube, type FilterCondition } from '@objectstack/spec/data'; +import { percentScaleOf, AggregationFunction, type Cube, type FilterCondition, type FixedReadLeaf } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { Dataset } from '@objectstack/spec/ui'; // [#6761] The ONE shared `I18nLabel → string` resolver (#6765, maintainer @@ -90,7 +90,8 @@ import { measureResultType } from './measure-result-type.js'; // compile. import { assertCubeMeasureFieldTypesAccepted, type MeasureColumn } from './cube-measure-field-type-door.js'; import { AMOUNT_AGGREGATES, assertRecordCurrencyAggregatesGrouped } from './cube-record-currency-door.js'; -import type { AnalyticsStrategy, AnalyticsDriverCapabilities, StrategyContext, DatasetScopedStrategyContext, DatasetScope, DurationMeasureSpec, ReadScopeFilterJudge } from './strategies/types.js'; +import type { AnalyticsStrategy, AnalyticsDriverCapabilities, StrategyContext, DatasetScopedStrategyContext, DatasetScope, DurationMeasureSpec, FixedReadLeafClassAnswer, ReadScopeFilterJudge } from './strategies/types.js'; +import { fixedReadLeafRefusalSinkOf } from './read-scope-sql.js'; import { NativeSQLStrategy } from './strategies/native-sql-strategy.js'; import { ObjectQLStrategy, aggregateGroupKeys, aggregateObjectOf, resolveCubeFieldName } from './strategies/objectql-strategy.js'; import { declaredCubeMemberKey } from './cube-member-key.js'; @@ -1354,6 +1355,20 @@ export interface AnalyticsServiceConfig { * told once, at construction, when it also wires `executeRawSql`. */ hasObjectMiddleware?: (objectName: string) => boolean | undefined; + /** + * [ADR-0155 D4, plan step 5] The engine seam's recognition of D4's two + * classes for a fixed-read leaf a read scope carries: the class, `null` for + * neither, `undefined` when this host cannot say. See + * `DatasetScopedStrategyContext.fixedReadLeafClassOf`. + * + * `NativeSQLStrategy` compiles the leaf (ADR-0155 Q2 as ruled) only where + * this answers `null`, and declines the query to the ObjectQL strategy on + * every other answer, so a host that wires nothing keeps the right rows and + * loses only the native path for scopes that carry the leaf. A host that + * holds the engine fills it from `@objectstack/objectql`'s + * `fixedReadLeafClassOfEngine(engine, leaf) ?? null`. + */ + fixedReadLeafClassOf?: (leaf: FixedReadLeaf) => FixedReadLeafClassAnswer; /** * The data engine's aggregate grouped also by related records' attributes, * which a SQL driver answers as one `LEFT JOIN … GROUP BY`. See @@ -1781,6 +1796,12 @@ export class AnalyticsService implements IAnalyticsService { // `NativeSQLStrategy` declines on `true` and on `undefined`, so the // engine path serves the object and its middlewares run. hasObjectMiddleware: config.hasObjectMiddleware, + // [ADR-0155 D4] The engine seam's recognition of D4's two classes, + // passed through untouched: `NativeSQLStrategy` compiles a fixed-read + // leaf only on a `null` answer and declines on every other one. + fixedReadLeafClassOf: config.fixedReadLeafClassOf, + // [ADR-0155 D4] This service's half of "logged once per evaluator". + fixedReadLeafRefusal: fixedReadLeafRefusalSinkOf(this.logger), // The engine's relation group join, passed through untouched; absent, // `ObjectQLStrategy` serves a cross-object dimension by its FK-expand. executeRelationGroupAggregate: config.executeRelationGroupAggregate, diff --git a/packages/services/service-analytics/src/plugin.ts b/packages/services/service-analytics/src/plugin.ts index 9c1d3969dc6..3f4f67ca44c 100644 --- a/packages/services/service-analytics/src/plugin.ts +++ b/packages/services/service-analytics/src/plugin.ts @@ -15,6 +15,8 @@ import { assertReadScopeAdmittedByEngine, assertReadScopeCannotVacate, assertReadScopeComparandsRunnable, + READ_SCOPE_FIXED_READ_LEAF_BRANDS, + fixedReadLeafRefusalSinkOf, assertReadScopePlaceholdersResolvable, } from './read-scope-sql.js'; import { readScopeUnresolvedError } from './read-scope-refusal.js'; @@ -1217,7 +1219,15 @@ export class AnalyticsServicePlugin implements Plugin { // [ADR-0139 D6] The engine's `ReadableIds` leaf admitted, as at the // two merges this door mirrors: the `$and` below hands the scope to // `executeAggregate` — the engine — whose boundary composes it. - if (scope) assertReadScopeComparandsRunnable(scope, targetObject, { admitReadableIds: true }); + // [ADR-0155 D4] …and the fixed-read leaf brands, as at those merges. + if (scope) { + assertReadScopeComparandsRunnable(scope, targetObject, { + admitReadableIds: true, + admitFixedReadLeaves: READ_SCOPE_FIXED_READ_LEAF_BRANDS, + fixedReadLeafRefusal: fixedReadLeafRefusalSinkOf(ctx.logger), + object: targetObject, + }); + } if (scope) assertReadScopePlaceholdersResolvable(scope, targetObject, context); if (scope) assertReadScopeAdmittedByEngine(scope, targetObject, context, { judgeFilter }); // #3680 — the sort-key pass hands over the PRE-window id set (every diff --git a/packages/services/service-analytics/src/read-scope-sql.ts b/packages/services/service-analytics/src/read-scope-sql.ts index bdd73e304da..5f30359088a 100644 --- a/packages/services/service-analytics/src/read-scope-sql.ts +++ b/packages/services/service-analytics/src/read-scope-sql.ts @@ -10,6 +10,22 @@ import { assertListComparandShapes, normalizeFilterComparandTypes } from '@objec // the engine-bound merges ({@link assertReadScopeComparandsRunnable} with // `admitReadableIds`), refused at the entry of {@link compileScopedFilterToSql}. import { isReadableIds } from '@objectstack/spec/data'; +// [ADR-0155 D2, D4, plan step 5] The fixed-read leaf (`SharedRecordIds`): its +// brand, its guard and its own description of the fixed inner read, which +// {@link compileScopedFilterToSql} compiles to a subquery and the engine-bound +// merges admit; and ADR-0139 D3's envelope, logged once per evaluator, for a +// leaf this compiler does not compile. +import { + SHARED_RECORD_IDS_BRAND, + fixedInnerReadOf, + fixedReadLeafNameOf, + isComposedReadableIds, + isFixedReadLeaf, + type FixedReadLeaf, + type FixedReadLeafBrand, + type FixedReadLeafName, +} from '@objectstack/spec/data'; +import { describeFixedReadLeaf, refuseFixedReadLeafOnce, type ReadableIdsRefusalLog } from '@objectstack/core'; // [ADR-0053 D-D1, amended 2026-09-30 — #5930 step 3] The shared lowering, run // at the entry of {@link compileScopedFilterToSql}, after the placeholders // resolve and before any clause is compiled. @@ -671,6 +687,40 @@ import { * tests, `$empty` and the text arms read the column as stored, as the native * `where` face does. An absent member is identity, the contract's own reading * for a driver whose storage form is the wire form. + * + * ## The share-grant leaf compiles to its subquery (ADR-0155 D2, D4, Q2 as ruled) + * + * A read scope may carry the engine-internal fixed-read leaf + * (`SharedRecordIds`, `@objectstack/spec/data`'s `isFixedReadLeaf`) as the + * `$in` comparand of `id`: "the records of this object shared with this user". + * Q2 ruled what this compiler does with it: **it compiles the leaf**, as the + * `$in` arm's subquery, from the leaf's own description (`fixedInnerReadOf`), + * every value bound, ⛔ never spliced: + * + * ```sql + * "t"."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" <> '') + * ``` + * + * the statement `driver-sql` compiles for the same leaf (ADR-0155 plan step + * 3), with ⛔ no tenant scope on the inner read (① ruled A: the outer + * statement's wall is untouched). So the NativeSQL face runs it and the + * `/analytics/sql` echo prints it. + * + * Anything else is ADR-0139 D3's envelope, `INTERNAL_ERROR` / 500, logged at + * `error` once per evaluator ({@link ReadScopeCompileOptions.fixedReadLeafRefusal}), + * ⛔ never this module's `READ_SCOPE_COMPILE_FAILED` and never `INVALID_FILTER`: + * a leaf is never an author's, so the fault is the code that composed it. The + * one exception to "the only way this module refuses" below, by ADR-0155 D4's + * "wherever it occurs". Two shapes reach it ({@link findUnservedFixedReadLeaf}): + * a leaf anywhere but a field's `$in` comparand, where reading it would bind or + * walk it as an ordinary value; and the leaf's WRITE form, which a predicate + * update alone carries (③ ruled A) and the engine refuses on every read. + * + * Which objects the native path compiles it for is not this compiler's + * question: `NativeSQLStrategy.canHandle` asks the engine seam's recognition of + * D4's two classes first and declines those to the ObjectQL strategy. */ const IDENT = /^[a-z_][a-z0-9_]*$/i; @@ -798,6 +848,210 @@ export interface ReadScopeCompileOptions { * compiler's output. Absent is identity: the column reads as written. */ coerceTemporalFilterColumn?: (field: string, columnSql: string) => string; + /** + * [ADR-0155 D4] Where a fixed-read leaf this compiler does not compile is + * logged: the evaluator's log and its once-flag. Absent, the refusal is + * thrown unlogged. See {@link FixedReadLeafRefusalSink}. + */ + fixedReadLeafRefusal?: FixedReadLeafRefusalSink; + /** + * [ADR-0155 D1] The object this scope reads, which the alias stands for: a + * fixed-read leaf compiles only in the scope of the object it names. Absent + * (a caller that cannot name it), that half of the leaf's position is not + * judged here; the field half still is. + */ + object?: string; +} + +/** + * [ADR-0155 D4] One evaluator's half of ADR-0139 D3's "logged at `error` once + * per evaluator": the logger a refusal of a fixed-read leaf is written to, and the + * flag that keeps it to one line (`@objectstack/core`'s `refuseFixedReadLeafOnce`). + * `AnalyticsService` holds one per instance and hands it to both strategies. + */ +export interface FixedReadLeafRefusalSink { + readonly logger: ReadableIdsRefusalLog | undefined; + readonly state: { logged: boolean }; +} + +const REFUSAL_SINKS = new WeakMap(); + +/** + * [ADR-0155 D4] The refusal sink for `logger`, one per logger object: the service's + * strategies and the plugin's record-label read hand the same logger and so + * share one flag, one line for this evaluator between them. + */ +export function fixedReadLeafRefusalSinkOf(logger: ReadableIdsRefusalLog): FixedReadLeafRefusalSink { + let sink = REFUSAL_SINKS.get(logger); + if (sink === undefined) REFUSAL_SINKS.set(logger, (sink = { logger, state: { logged: false } })); + return sink; +} + +/** [ADR-0155 D4] The evaluator this module's fixed-read-leaf refusals name. */ +export const READ_SCOPE_FIXED_READ_LEAF_EVALUATOR = 'service-analytics'; + +/** + * [ADR-0155 D4, Q2 as ruled] The brands this module compiles and its + * engine-bound merges admit: ONE list that names its brands, as the engine's + * door does (`ENGINE_FIXED_READ_LEAF_BRANDS`), never a flag per brand. ADR-0147's + * leaf joins it on the card that teaches this compiler that leaf, with its row + * in {@link LEAF_RULES}. + */ +export const READ_SCOPE_FIXED_READ_LEAF_BRANDS: readonly FixedReadLeafBrand[] = Object.freeze([SHARED_RECORD_IDS_BRAND]); + +/** + * What this compiler reads per leaf, one row per leaf name (ADR-0155 D4: an + * evaluator's answer to a leaf is the leaf's own). For `SharedRecordIds`, the + * readings the engine seam's own row gives (ADR-0155 D1, ③ ruled A): + * + * - `position`: the leaf sits as the `$in` comparand of `id` on the object it + * names. The native path runs no engine seam, so this compiler is the one + * that holds a leaf to its position there. + * - `readForm`: it is the read form exactly when it carries no `accessLevels`. + */ +const LEAF_RULES: Readonly { readonly field: string; readonly object: string }; + readonly readForm: (leaf: FixedReadLeaf) => boolean; +}>> = Object.freeze({ + SharedRecordIds: Object.freeze({ + position: (leaf: FixedReadLeaf) => ({ field: 'id', object: leaf.object }), + readForm: (leaf: FixedReadLeaf) => leaf.accessLevels === undefined, + }), +}); + +/** A fixed-read leaf this compiler does not compile, where it sits, and why. */ +interface UnservedFixedReadLeaf { + readonly at: string; + readonly leaf: unknown; + readonly reason: 'misplaced' | 'write-form'; +} + +/** A plain object or a list: something a filter is built from and the walk below descends into. */ +function isPlainContainer(value: unknown): value is Record | unknown[] { + 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, D4] The first fixed-read leaf in `scope` this compiler does not + * compile, or `null`: one anywhere but as the `$in` comparand of the field its + * row names, on the object it names (`misplaced`), or one there in its write + * form (`write-form`). `object` is the object the scope reads; absent, the + * object half is not judged (a caller that compiles for an alias it cannot + * name), and the field half still is. + * + * The walk reads roles, as `driver-sql`'s floor does: a NODE's keys are + * combinators and fields, an OPERATOR MAP's keys are operators, and only an + * operator map's `$in` holds a leaf. Everything else is walked as a value, where + * any leaf is misplaced (a list member, a bare field value, a `$not` operand, a + * node of its own). A composed `ReadableIds` scope is a node. Cycles are cut on + * the current path. A leaf of a brand {@link READ_SCOPE_FIXED_READ_LEAF_BRANDS} + * does not name is found as misplaced wherever it sits. + */ +function findUnservedFixedReadLeaf(scope: unknown, path: string, scopeObject: string | undefined): UnservedFixedReadLeaf | null { + const onPath = new Set(); + const descend = (value: object, walk: () => UnservedFixedReadLeaf | null): UnservedFixedReadLeaf | null => { + if (onPath.has(value)) return null; + onPath.add(value); + try { + return walk(); + } finally { + onPath.delete(value); + } + }; + const visitValue = (value: unknown, at: string, object: string | undefined): UnservedFixedReadLeaf | null => { + if (isFixedReadLeaf(value)) return { at, leaf: value, reason: 'misplaced' }; + if (isComposedReadableIds(value)) { + return value.scope === undefined ? null : visitNode(value.scope, `${at}.scope`, value.object); + } + if (!isPlainContainer(value)) return null; + return descend(value, () => { + const entries: [string, unknown][] = Array.isArray(value) + ? value.map((item, i) => [`[${i}]`, item]) + : Object.keys(value).map((key) => [`.${key}`, value[key]]); + for (const [step, item] of entries) { + const found = visitValue(item, `${at}${step}`, object); + if (found) return found; + } + return null; + }); + }; + const visitNode = (node: unknown, at: string, object: string | undefined): UnservedFixedReadLeaf | null => { + if (isFixedReadLeaf(node) || !isPlainContainer(node) || Array.isArray(node)) return visitValue(node, at, object); + return descend(node, () => { + for (const key of Object.keys(node)) { + const value = node[key]; + const here = `${at}.${key}`; + let found: UnservedFixedReadLeaf | null = null; + if ((key === '$and' || key === '$or') && Array.isArray(value)) { + for (let i = 0; i < value.length && found === null; i++) found = visitNode(value[i], `${here}[${i}]`, object); + } else if (key === '$not') { + found = visitNode(value, here, object); + } else if (!key.startsWith('$') && !isFixedReadLeaf(value) && isPlainContainer(value) && !Array.isArray(value)) { + found = visitOperatorMap(value, here, key, object); + } else { + found = visitValue(value, here, object); + } + if (found) return found; + } + return null; + }); + }; + const visitOperatorMap = ( + map: Record, + at: string, + field: string, + object: string | undefined, + ): UnservedFixedReadLeaf | null => + descend(map, () => { + for (const op of Object.keys(map)) { + const comparand = map[op]; + if (op === '$in' && isFixedReadLeaf(comparand, READ_SCOPE_FIXED_READ_LEAF_BRANDS)) { + const rules = LEAF_RULES[fixedReadLeafNameOf(comparand)!]; + const position = rules.position(comparand); + if (field !== position.field || (object !== undefined && object !== position.object)) { + return { at: `${at}.${op}`, leaf: comparand, reason: 'misplaced' }; + } + if (!rules.readForm(comparand)) return { at: `${at}.${op}`, leaf: comparand, reason: 'write-form' }; + continue; + } + const found = visitValue(comparand, `${at}.${op}`, object); + if (found) return found; + } + return null; + }); + return visitNode(scope, path, scopeObject); +} + +/** + * [ADR-0155 D4] Refuse, in ADR-0139 D3's envelope (`INTERNAL_ERROR` / 500, + * logged at `error` once per evaluator), the first fixed-read leaf `scope` + * carries that this module does not compile ({@link findUnservedFixedReadLeaf}). + * The message names the evaluator, the leaf (by name and table, never its + * inputs: a recipient is a principal's id, and the line reaches logs) and the + * remedy. Run at the entry of {@link compileScopedFilterToSql} and by + * {@link assertReadScopeComparandsRunnable} for a merge that admits the brand. + */ +function refuseUnservedFixedReadLeaf( + scope: unknown, + objectName: string, + scopeObject: string | undefined, + sink: FixedReadLeafRefusalSink | undefined, +): void { + const found = findUnservedFixedReadLeaf(scope, 'readScope', scopeObject); + if (found === null) return; + const what = describeFixedReadLeaf(found.at, found.leaf); + const message = found.reason === 'write-form' + ? `read scope for "${objectName}": ${what} in its WRITE form, which only a predicate update carries ` + + '(ADR-0155 ③ ruled A) and every read refuses. The statement was NOT run. A read scope carries the read ' + + 'form, SharedRecordIds.read(object, recipient).' + : `read scope for "${objectName}": ${what}, where no read-scope compiler compiles one: a fixed-read leaf ` + + 'compiles only as the $in comparand of id on the object it names (ADR-0155 D1). The statement was NOT run, ' + + 'rather than read the leaf as an ordinary comparand. Place it as { id: { $in: leaf } } in the scope of that object.'; + const state = sink?.state ?? { logged: true }; + throw refuseFixedReadLeafOnce(READ_SCOPE_FIXED_READ_LEAF_EVALUATOR, message, sink?.logger, state, objectName); } /** A node the compiler can walk: a plain object, not `null` and not an array. */ @@ -851,6 +1105,11 @@ export function compileScopedFilterToSql( 'strategy; the dry-run echo cannot show a statement it would not run.', ); } + // [ADR-0155 D4] A fixed-read leaf this compiler does not compile (out of + // position, or in its write form) is refused next, by name, in ADR-0139 D3's + // envelope, before a single clause reads it as a value. Every other leaf + // compiles at the `$in` arm (see the module header). + refuseUnservedFixedReadLeaf(filter, alias, options.object, options.fixedReadLeafRefusal); // [#20075] Resolve the scope's placeholders with the engine's own resolver // BEFORE the lowering, because the lowering binds values: what is bound, and // what the echo prints, is the value the ObjectQL face's engine resolves. A @@ -893,7 +1152,14 @@ export function compileScopedFilterToSql( // lowering on purpose: a shape this compiler already refuses keeps its own // sentence, and the faces add exactly the shapes it would otherwise have // lowered. See the module header's #20018 section. - assertReadScopeComparandsRunnable(filter, alias); + // + // [ADR-0155 D4, plan step 5] It names the fixed-read leaf brands it compiles + // (`READ_SCOPE_FIXED_READ_LEAF_BRANDS`): what it admits, it compiled above. + assertReadScopeComparandsRunnable(filter, alias, { + admitFixedReadLeaves: READ_SCOPE_FIXED_READ_LEAF_BRANDS, + fixedReadLeafRefusal: options.fixedReadLeafRefusal, + object: options.object, + }); if (unresolvable) throw unresolvable; return { sql, params }; } @@ -1034,6 +1300,19 @@ export interface ReadScopeComparandOptions { * by the engine-bound merges only; `compileScopedFilterToSql` never passes it. */ readonly admitReadableIds?: boolean; + /** + * [ADR-0155 D4, Q2 as ruled] The fixed-read leaf brands to admit as a `$in` + * comparand ({@link READ_SCOPE_FIXED_READ_LEAF_BRANDS}): passed by the + * engine-bound merges, whose engine passes the leaf through its seam, and by + * {@link compileScopedFilterToSql}, which compiles it. A leaf of these brands + * out of position or in its write form is refused first, in ADR-0139 D3's + * envelope (`INTERNAL_ERROR` / 500), not this module's. + */ + readonly admitFixedReadLeaves?: readonly FixedReadLeafBrand[]; + /** [ADR-0155 D4] Where that refusal is logged, once per evaluator. */ + readonly fixedReadLeafRefusal?: FixedReadLeafRefusalSink; + /** [ADR-0155 D1] The object the scope reads, when the caller can name it (see {@link ReadScopeCompileOptions.object}). */ + readonly object?: string; } /** @@ -1070,6 +1349,36 @@ export function findReadableIdsLeaf(scope: unknown): { object: string; path: str return visit(scope, ''); } +/** + * [ADR-0155 D4] Every fixed-read leaf `scope` carries, in walk order, wherever + * it sits (a composed `ReadableIds` scope included). Exported for + * `NativeSQLStrategy.canHandle`, which asks the engine seam's recognition of + * D4's two classes about each before anything compiles. + */ +export function fixedReadLeavesIn(scope: unknown): FixedReadLeaf[] { + const leaves: FixedReadLeaf[] = []; + const onPath = new Set(); + const visit = (value: unknown): void => { + if (isFixedReadLeaf(value)) { + leaves.push(value); + return; + } + if (isComposedReadableIds(value)) { + visit(value.scope); + return; + } + if (!isPlainContainer(value) || onPath.has(value)) return; + onPath.add(value); + try { + for (const item of Array.isArray(value) ? value : Object.values(value)) visit(item); + } finally { + onPath.delete(value); + } + }; + visit(scope); + return leaves; +} + /** * [#19995] Refuse, in this module's envelope, a read scope the ENGINE would * refuse for one of its comparands — judged on the scope ALONE, before it is @@ -1156,6 +1465,20 @@ export function findReadableIdsLeaf(scope: unknown): { object: string; path: str * (the brand is a symbol key no JSON carries), and the engine's door keeps * refusing it there as the non-list comparand it always was. * + * ## …and the fixed-read leaf (ADR-0155 D4, Q2 as ruled) + * + * The share-grant leaf (`SharedRecordIds`) is admitted under + * `options.admitFixedReadLeaves`, the brands its callers name + * ({@link READ_SCOPE_FIXED_READ_LEAF_BRANDS}). D4 names the callers of the + * spec face that may name a brand: the engine's door, and the analytics + * merges, which Q2 ruled admit it. In this package those are this function's + * callers: the two engine-bound merges and the record-label read, which hand + * the leaf to the engine's seam, and {@link compileScopedFilterToSql}, which + * Q2 ruled compiles the leaf and which reaches the spec face only through + * here. Every leaf this function admits is either handed to the engine or + * compiled. A leaf of those brands out of position or in its write form is + * refused before the faces, in ADR-0139 D3's envelope. + * * @param scope the `StrategyContext.getReadScope` output, exactly as returned * @param objectName the object the scope was requested for — for the operator's * log only; withheld from the response by the `READ_SCOPE_COMPILE_FAILED` / @@ -1167,8 +1490,22 @@ export function assertReadScopeComparandsRunnable( objectName: string, options?: ReadScopeComparandOptions, ): void { + // [ADR-0155 D4] A merge that admits the fixed-read leaf brands refuses, first + // and in ADR-0139 D3's own envelope, a leaf of them it would not hand on: + // the engine would refuse it too, and this module's envelope would dress a + // composition fault as a scope this module could not compile. + const admitFixedReadLeaves = options?.admitFixedReadLeaves; + if (admitFixedReadLeaves !== undefined && admitFixedReadLeaves.length > 0) { + refuseUnservedFixedReadLeaf(scope, objectName, options?.object, options?.fixedReadLeafRefusal); + } + const shapeOptions = options?.admitReadableIds === true || admitFixedReadLeaves !== undefined + ? { + ...(options?.admitReadableIds === true ? { admitReadableIds: true } : {}), + ...(admitFixedReadLeaves !== undefined ? { admitFixedReadLeaves } : {}), + } + : undefined; try { - assertListComparandShapes(scope, undefined, 'readScope', options?.admitReadableIds === true ? { admitReadableIds: true } : undefined); + assertListComparandShapes(scope, undefined, 'readScope', shapeOptions); normalizeFilterComparandTypes(scope, undefined, 'readScope'); } catch (e) { throw readScopeCompileError( @@ -2159,6 +2496,37 @@ function assertNoFieldReferenceComparand(field: string, spec: unknown): void { * #19886's ruling A, carried on that card. The other scalar operators carrying a * list are not this ruling's either. */ +/** + * [ADR-0155 D2, D4] The subquery a fixed-read leaf compiles to, from the leaf's + * own description (`fixedInnerReadOf`): ⛔ no predicate restated by hand, every + * value bound into `params`, the identifiers through {@link quoteIdent}. + * + * - each `equals` entry as `"column" = ?`, each `memberOf` entry as + * `"column" IN (?, …)`, ANDed, in the description's order; + * - the blank-id guard, `"column" IS NOT NULL AND "column" <> ''`, so a + * negation answers every row the set does not hold. (The one dialect that + * stores `''` as NULL, Oracle, is not one this compiler names: + * `NativeSQLStrategy` declines a leaf on a dialect it cannot name.) + * - **no tenant scope** (`tenantScope: 'none'`, ADR-0155 ① ruled A). The + * outer statement's wall is untouched. + * + * One statement, no `EXISTS`, no correlation, no join (ADR-0155 D1). + */ +function fixedReadLeafSubquerySql(leaf: FixedReadLeaf, params: unknown[]): string { + const read = fixedInnerReadOf(leaf); + // ADR-0155 ① ruled A: no tenant scope on the inner read. A widened type fails here. + const tenantScope: 'none' = read.tenantScope; + void tenantScope; + const column = quoteIdent(read.column, 'column'); + const predicates: string[] = []; + for (const [name, value] of Object.entries(read.equals)) predicates.push(`${quoteIdent(name, 'column')} = ${bind(params, value)}`); + for (const [name, values] of Object.entries(read.memberOf)) { + predicates.push(`${quoteIdent(name, 'column')} IN (${values.map((value) => bind(params, value)).join(', ')})`); + } + predicates.push(`${column} IS NOT NULL`, `${column} <> ''`); + return `SELECT ${column} FROM ${quoteIdent(read.table, 'table')} WHERE ${predicates.join(' AND ')}`; +} + function assertNoListInEqualitySlot(field: string, spec: unknown): void { if (!isFilterNode(spec) || !Array.isArray(spec.$eq)) return; throw readScopeCompileError( @@ -2195,6 +2563,9 @@ function compileOperator( case '$lt': return `${vcol()} < ${vbind(val)}`; case '$lte': return `${vcol()} <= ${vbind(val)}`; case '$in': { + // [ADR-0155 D2] The fixed-read leaf: its subquery. The entry's walk + // already refused every leaf this arm does not compile. + if (isFixedReadLeaf(val, READ_SCOPE_FIXED_READ_LEAF_BRANDS)) return `${col} IN (${fixedReadLeafSubquerySql(val, params)})`; if (!Array.isArray(val)) throw readScopeCompileError(`[read-scope-sql] $in for "${field}" needs an array (fail-closed).`); if (val.length === 0) return FALSE_CLAUSE; // IN () matches nothing — safe assertCompilableMembers(op, field, val); diff --git a/packages/services/service-analytics/src/strategies/filter-normalizer.ts b/packages/services/service-analytics/src/strategies/filter-normalizer.ts index 3d92b215574..d19a7585b14 100644 --- a/packages/services/service-analytics/src/strategies/filter-normalizer.ts +++ b/packages/services/service-analytics/src/strategies/filter-normalizer.ts @@ -439,7 +439,9 @@ import { assertListComparandShapes, + isComposedReadableIds, isFilterAST, + isFixedReadLeaf, isRefusedTextComparand, normalizeFilterComparandTypes, parseFilterAST, @@ -447,6 +449,7 @@ import { textComparandRefusalReason, VALID_AST_OPERATORS, } from '@objectstack/spec/data'; +import { describeFixedReadLeaf, fixedReadLeafRefusal } from '@objectstack/core'; // [ADR-0053 D-D1, amended 2026-09-30 — #5930 step 3] The shared lowering, run // on what this door admitted, before any face reads the condition — see // {@link normalizeAnalyticsFilterTree} (F10) and the draft preview (F11). @@ -2128,6 +2131,8 @@ function assertNoRetiredOperators(node: unknown, path = 'where'): void { * evaluates the narrowed condition the published one lowers. */ export function normalizeWhereComparands(node: T, path = 'where'): T { + // [ADR-0155 D4, plan step 5] A fixed-read leaf first, in its own envelope. + refuseFixedReadLeafInWhere(node, path); assertWhereComparandShapes(node, path); const narrowed = normalizeWhereComparandTypes(node, path); // [#20040] Then the null flags' boolean domain, before any node is built — @@ -2139,6 +2144,61 @@ export function normalizeWhereComparands(node: T, path = 'where'): T { return narrowed; } +/** The evaluator this module's fixed-read-leaf refusal names. */ +const WHERE_FIXED_READ_LEAF_EVALUATOR = 'service-analytics where'; + +/** + * [ADR-0155 D4, plan step 5: compile surface 2] Refuse a fixed-read leaf + * (`SharedRecordIds`) anywhere in an analytics query's `where`, either + * spelling, in ADR-0139 D3's envelope (`INTERNAL_ERROR` / 500), before any + * other gate reads the condition. + * + * A leaf reaches analytics only in the read scope (`ctx.getReadScope`), which + * its own door judges (`read-scope-sql.ts#assertReadScopeComparandsRunnable`). + * A `where` names no brand, and no request can spell the leaf (its brand is a + * symbol no JSON keeps), so a leaf here is the in-process code that put it + * there. Without this pass the face answered it three ways, none of them the + * leaf's own: `{ id: { $in: leaf } }` the shape door's `INVALID_FILTER` / 400, + * whose message printed the leaf's inputs; a bare `{ id: leaf }`, and the + * array form's `=`, a relation condition on `id` built from the leaf's fields. + * The message names the leaf by its name and table only. Unlogged: the face + * holds no logger, as `parseFilterAST` holds none. + */ +function refuseFixedReadLeafInWhere(node: unknown, path: string): void { + const onPath = new Set(); + const find = (value: unknown, at: string): { at: string; leaf: unknown } | null => { + if (isFixedReadLeaf(value)) return { at, leaf: value }; + if (isComposedReadableIds(value)) return find(value.scope, `${at}.scope`); + // Plain objects and lists only: a filter is built from those, and a leaf + // inside anything else (a Date, a Buffer) is no position at all. + if (value === null || typeof value !== 'object' || onPath.has(value)) return null; + const proto = Object.getPrototypeOf(value); + if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) return null; + onPath.add(value); + try { + const entries: [string, unknown][] = Array.isArray(value) + ? value.map((item, i) => [`${at}[${i}]`, item]) + : Object.keys(value).map((key) => [`${at}.${key}`, (value as Record)[key]]); + for (const [step, item] of entries) { + const found = find(item, step); + if (found) return found; + } + return null; + } finally { + onPath.delete(value); + } + }; + const found = find(node, path); + if (found === null) return; + throw fixedReadLeafRefusal( + WHERE_FIXED_READ_LEAF_EVALUATOR, + `${describeFixedReadLeaf(found.at, found.leaf)}, which an analytics query's where admits in no position: ` + + 'a fixed-read leaf reaches analytics only in the read scope, as { id: { $in: leaf } } (ADR-0155 D1, D4). ' + + 'The query was NOT run, rather than read the leaf as a comparand or a relation condition. Remove the leaf ' + + 'from the where and let the read scope carry it.', + ); +} + /** * Lower an analytics query's `where` to the CANONICAL `FilterCondition` object, * before any node is built. `null` when the query carries no `where`. @@ -2166,6 +2226,9 @@ export function lowerAnalyticsWhere( if (Array.isArray(where)) { // (1) `[]` is "no filter", not a failed filter. if (where.length === 0) return null; + // [ADR-0155 D4, plan step 5] A fixed-read leaf in either spelling, before + // `parseFilterAST` lowers an `=` comparand by reference. + refuseFixedReadLeafInWhere(where, 'where'); // (3) Not a shape `parseFilterAST` can express. if (!isFilterAST(where)) throw filterArrayNotLowerableError(where); // (2) The declared path. diff --git a/packages/services/service-analytics/src/strategies/native-sql-strategy.ts b/packages/services/service-analytics/src/strategies/native-sql-strategy.ts index 4f5b33fe51d..cbd87fa7639 100644 --- a/packages/services/service-analytics/src/strategies/native-sql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/native-sql-strategy.ts @@ -37,7 +37,7 @@ import { numberComparandRefusalMessage, } from '@objectstack/spec/data'; import { findCrossFieldComparand, findUninterpretableTemporalMember } from '../comparand-shape.js'; -import { assertReadScopeCannotVacate, compileScopedFilterToSql, findReadableIdsLeaf } from '../read-scope-sql.js'; +import { assertReadScopeCannotVacate, compileScopedFilterToSql, findReadableIdsLeaf, fixedReadLeavesIn } from '../read-scope-sql.js'; import { nonTextColumnResolver, textOperatorPolarity } from '../non-text-column.js'; import { declaredValueShapeResolver, whereEmptyLeafSql } from '../empty-operator-sql.js'; // [#20986] The one resolver of the object a relationship-path hop reads. @@ -912,6 +912,22 @@ export class NativeSQLStrategy implements AnalyticsStrategy { // reason: one owner of the composition, no second copy here. Every object // the statement scopes is read, as the cross-field decline reads them. if (this.readScopeCarriesReadableIds(query, ctx)) return false; + // ── [ADR-0155 D4, Q2 as ruled] DECLINE a share-grant leaf of D4's classes ─ + // + // A read scope may carry the engine-internal fixed-read leaf + // (`SharedRecordIds`) as the `$in` comparand of `id`, and Q2 ruled that + // this strategy compiles it (`compileScopedFilterToSql` emits its + // subquery). Where either of D4's two classes applies (the object bound to + // another datasource than the leaf's inner table, or a middleware or find + // hook registered for that table by name), the subquery would read the + // wrong database or read around the registration, so the query declines + // to the ObjectQL strategy before anything compiles, and the engine's seam + // gives the class its answer. The class is the seam's recognition, asked + // through the host (`fixedReadLeafClassOf`); ⛔ no second copy here. It + // FAILS CLOSED like the middleware decline: no hook, an `undefined` + // answer, a throw, and a dialect this compiler cannot name decline too. + // See {@link readScopeCarriesUncompilableFixedReadLeaf}. + if (this.readScopeCarriesUncompilableFixedReadLeaf(query, ctx)) return false; // ── [#25778] DECLINE a duration measure on a dialect nobody named ────── // // A dataset duration measure is the time between two `datetime` columns of @@ -959,6 +975,40 @@ export class NativeSQLStrategy implements AnalyticsStrategy { return objects.some((object) => findReadableIdsLeaf(ctx.getReadScope!(object)) !== null); } + /** + * [ADR-0155 D4] Does the read scope of any object this statement scopes carry + * a fixed-read leaf this strategy may not compile? See the decline at + * {@link canHandle}. The objects are the ones {@link readScopeCarriesReadableIds} + * reads. Every leaf in a scope is asked about, wherever it sits: one out of + * position is not declined here, and `compileScopedFilterToSql` refuses it in + * ADR-0139 D3's envelope, as the engine would. + */ + private readScopeCarriesUncompilableFixedReadLeaf(query: AnalyticsQuery, ctx: StrategyContext): boolean { + if (typeof ctx.getReadScope !== 'function') return false; + const cube = query.cube ? ctx.getCube(query.cube) : undefined; + if (!cube) return false; + const scoped = (ctx as DatasetScopedStrategyContext).readScopedObjects; + const objects = scoped + ? [...scoped] + : [this.extractObjectName(cube), ...Object.keys(cube.joins ?? {}).map((alias) => cube.joins?.[alias]?.name ?? alias)]; + const classOf = (ctx as DatasetScopedStrategyContext).fixedReadLeafClassOf; + return objects.some((object) => { + const leaves = fixedReadLeavesIn(ctx.getReadScope!(object)); + if (leaves.length === 0) return false; + // The subquery's blank-id guard is spelled per dialect (Oracle stores + // `''` as NULL); a dialect this compiler cannot name is declined. + if (sqlDialectFor(ctx, object) === 'unknown') return true; + if (typeof classOf !== 'function') return true; + return leaves.some((leaf) => { + try { + return classOf.call(ctx, leaf) !== null; + } catch { + return true; + } + }); + }); + } + /** * [#29304] Does a `dimensions` entry of this query resolve to a column the * host declares VIRTUAL (the spec's `isVirtualSearchField`: `formula`)? See @@ -1750,7 +1800,13 @@ export class NativeSQLStrategy implements AnalyticsStrategy { // D-A1 / D-A2), bound to the OBJECT (never the alias), so a temporal // comparand binds in the column's storage form and the scope admits the // rows the engine admits. + // [ADR-0155 D2, D4] …and the object and this service's refusal sink, so a + // share-grant leaf compiles to its subquery in the scope of the object it + // names, and a leaf out of position is refused in D4's envelope, logged + // once. `canHandle` declined D4's two classes before this point. const { sql, params: scopeParams } = compileScopedFilterToSql(filter, alias, { + object: objectName, + fixedReadLeafRefusal: (ctx as DatasetScopedStrategyContext).fixedReadLeafRefusal, nonTextColumn: nonTextColumnResolver(ctx, objectName), dialect: sqlDialectFor(ctx, objectName), context: ctx.context, diff --git a/packages/services/service-analytics/src/strategies/objectql-strategy.ts b/packages/services/service-analytics/src/strategies/objectql-strategy.ts index c581598c72a..a74d192112d 100644 --- a/packages/services/service-analytics/src/strategies/objectql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/objectql-strategy.ts @@ -27,6 +27,7 @@ import { assertReadScopeAdmittedByEngine, assertReadScopeCannotVacate, assertReadScopeComparandsRunnable, + READ_SCOPE_FIXED_READ_LEAF_BRANDS, assertReadScopePlaceholdersResolvable, compileScopedFilterToSql, } from '../read-scope-sql.js'; @@ -1237,7 +1238,13 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // prints the `$empty` arm the executed native statement runs. // [#21505] …and the same temporal coercion pair, so the echo prints // the storage-form comparand and column the executed statement binds. + // [ADR-0155 D2, Q2 as ruled] …and the object and the refusal sink, so a + // scope carrying the share-grant leaf prints the subquery the executed + // statement runs (the native statement compiles it; the engine's driver + // compiles the same subquery), and refuses a leaf neither runs. const { sql: scopeSql, params: scopeParams } = compileScopedFilterToSql(scope, tableName, { + object: tableName, + fixedReadLeafRefusal: (ctx as DatasetScopedStrategyContext).fixedReadLeafRefusal, nonTextColumn: nonTextColumnResolver(ctx, tableName), dialect: sqlDialectFor(ctx, tableName), context: ctx.context, @@ -1365,7 +1372,16 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // the leaf from the security service exactly as a find does. The option // is this merge's and the engine's; `compileScopedFilterToSql` keeps // refusing the leaf, and the caller's own `where` never carries one. - assertReadScopeComparandsRunnable(scope, objectName, { admitReadableIds: true }); + // [ADR-0155 D4, Q2 as ruled] …and the fixed-read leaf brands admitted + // too: the engine's seam passes such a leaf through to a driver that + // declares it, or refuses it in D4's envelope. A leaf out of position or + // in its write form is refused here, in that envelope, before the engine. + assertReadScopeComparandsRunnable(scope, objectName, { + admitReadableIds: true, + admitFixedReadLeaves: READ_SCOPE_FIXED_READ_LEAF_BRANDS, + fixedReadLeafRefusal: (ctx as DatasetScopedStrategyContext).fixedReadLeafRefusal, + object: objectName, + }); // [#19995] …and the placeholder half. The engine resolves `{…}` values on // the COMPOSED `where`, so a placeholder in the scope it cannot resolve // came back as its `FILTER_TOKEN_*` / 400 with the token relayed. Judged @@ -2115,7 +2131,15 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // [ADR-0139 D6] The engine's `ReadableIds` leaf admitted, as at // `withReadScope`: this is an engine-bound merge, and the engine composes // the leaf at its boundary. - if (scope != null) assertReadScopeComparandsRunnable(scope, refObject, { admitReadableIds: true }); + // [ADR-0155 D4] …and the fixed-read leaf brands, as at `withReadScope`. + if (scope != null) { + assertReadScopeComparandsRunnable(scope, refObject, { + admitReadableIds: true, + admitFixedReadLeaves: READ_SCOPE_FIXED_READ_LEAF_BRANDS, + fixedReadLeafRefusal: (ctx as DatasetScopedStrategyContext).fixedReadLeafRefusal, + object: refObject, + }); + } // [#19995] …and the placeholder half, as at `withReadScope`, with the // context forwarded to `executeAggregate` below. if (scope != null) assertReadScopePlaceholdersResolvable(scope, refObject, ctx.context); diff --git a/packages/services/service-analytics/src/strategies/types.ts b/packages/services/service-analytics/src/strategies/types.ts index 4ac6878070b..01dc2a5497a 100644 --- a/packages/services/service-analytics/src/strategies/types.ts +++ b/packages/services/service-analytics/src/strategies/types.ts @@ -15,7 +15,7 @@ export type { AnalyticsDriverCapabilities, } from '@objectstack/spec/contracts'; -import type { FilterCondition, ValueShapeFieldDef } from '@objectstack/spec/data'; +import type { FilterCondition, FixedReadLeaf, ValueShapeFieldDef } from '@objectstack/spec/data'; import type { IObjectQLEngine, StrategyContext } from '@objectstack/spec/contracts'; import type { DATASET_DURATION_AGGREGATES, DatasetDurationUnit } from '@objectstack/spec/ui'; @@ -27,6 +27,17 @@ import type { DATASET_DURATION_AGGREGATES, DatasetDurationUnit } from '@objectst */ type EngineJudgeFilter = NonNullable; +/** + * [ADR-0155 D4] The answer {@link DatasetScopedStrategyContext.fixedReadLeafClassOf} + * gives: the class a leaf falls in (`'other-datasource'` or + * `'registration-by-name'`, with what names it), `null` for neither, or + * `undefined` when the host cannot say. + */ +export type FixedReadLeafClassAnswer = + | { readonly class: 'other-datasource' | 'registration-by-name' } + | null + | undefined; + /** * [#19995] A host's answer to "would the ENGINE admit this `where`?": the * engine's own verdict, or `undefined` when the host cannot answer. The @@ -269,6 +280,32 @@ export interface DatasetScopedStrategyContext extends StrategyContext { * it had. */ hasObjectMiddleware?(objectName: string): boolean | undefined; + /** + * [ADR-0155 D4, plan step 5] The engine seam's recognition of D4's two + * classes for a fixed-read leaf (`SharedRecordIds`) a read scope carries + * (`@objectstack/objectql`'s `fixedReadLeafClassOfEngine`): an object naming + * the class when the leaf's object is bound to another datasource than its + * inner table, or a middleware or find hook is registered for that table by + * name; `null` when neither applies; `undefined` when the host cannot say. + * + * `NativeSQLStrategy` compiles the leaf itself (Q2 as ruled), so it asks this + * before it compiles and declines a query to the ObjectQL strategy on a + * class, and on `undefined` too: a class it cannot see is not one it may + * read around. The engine's seam then gives the class its answer. ⛔ No + * second copy of either class in this package. + * + * `AnalyticsService` passes through `AnalyticsServiceConfig.fixedReadLeafClassOf`. + * Declared HERE for the reason `getDatasetScope` is: nothing about it is an + * authorable surface. A context built without the hook declines every scope + * that carries the leaf. + */ + fixedReadLeafClassOf?(leaf: FixedReadLeaf): FixedReadLeafClassAnswer; + /** + * [ADR-0155 D4] Where this service logs a fixed-read leaf its read-scope + * compiler or merges refuse, once per evaluator (`read-scope-sql.ts`'s + * `FixedReadLeafRefusalSink`). Absent, the refusal is thrown unlogged. + */ + fixedReadLeafRefusal?: { readonly logger: { error?(message: string): void; warn(message: string): void } | undefined; readonly state: { logged: boolean } }; /** * The data engine's aggregate of `objectName`, grouped ALSO by attributes of * related records (one {@link RelationGroupAggregateRelation} per relation), diff --git a/packages/spec/src/data/filter.zod.ts b/packages/spec/src/data/filter.zod.ts index dd5bbd9d9b4..511abdb4ec2 100644 --- a/packages/spec/src/data/filter.zod.ts +++ b/packages/spec/src/data/filter.zod.ts @@ -3,6 +3,8 @@ import { z } from 'zod'; import { closedObject } from '../shared/strict-object'; import { assertListComparandShapes } from './filter-comparand-shape'; +import { fixedInnerReadOf, fixedReadLeafNameOf, isFixedReadLeaf } from './fixed-read-leaf'; +import { isComposedReadableIds } from './readable-ids'; // [#19889] The equality-slot refusal's words, shared with the comparand-shape // face so the save door and the query door print one sentence (ruling A, // record 5805248669: "one constant, two doors"). @@ -3021,7 +3023,8 @@ function convertComparison(node: [string, string, unknown]): FilterCondition { * [#9228] Whatever this function returns has first passed * {@link assertListComparandShapes}: `$in` / `$nin` carry an ARRAY and * `$between` a `[min, max]` pair, or the call is refused with the - * `INVALID_FILTER` / 400 envelope. That gate used to run only at the engine's + * `INVALID_FILTER` / 400 envelope (for a condition carrying a fixed-read leaf, + * `INTERNAL_ERROR` / 500 instead: the exception at the end of this section). That gate used to run only at the engine's * lowering seam, so a caller that lowered a filter here and handed it straight * to a driver (`InMemoryDriver.find()` — an embedder, and this repo's own * driver conformance suites) met nothing: the shape was carried by mingo's @@ -3041,6 +3044,10 @@ function convertComparison(node: [string, string, unknown]): FilterCondition { * five drivers came to answer an unsupported comparand type five ways * (#7956's divergence matrix); the door module's header carries the ruling. * + * [ADR-0155 D4] The one exception to both doors' envelope: when either refuses + * a condition that carries a fixed-read leaf, the refusal is `INTERNAL_ERROR` / + * 500, naming the leaf and not its inputs ({@link refuseFixedReadLeafAtParse}). + * * @example * // Simple condition * parseFilterAST(["status", "=", "active"]) @@ -3064,8 +3071,69 @@ export function parseFilterAST(filter: unknown, context?: string): FilterConditi // through rather than minted here so the engine's array branch keeps the // exact message it has pinned since #6209, now that the shape gate refuses // one step earlier than the engine's own call to it. - assertListComparandShapes(lowered, context); - return normalizeFilterComparandTypes(lowered, context); + try { + assertListComparandShapes(lowered, context); + return normalizeFilterComparandTypes(lowered, context); + } catch (refused) { + // [ADR-0155 D4, plan step 5] A condition carrying a fixed-read leaf is + // refused in D4's envelope instead, whichever door refused it; see + // {@link refuseFixedReadLeafAtParse}. + refuseFixedReadLeafAtParse(lowered, context); + throw refused; + } +} + +/** + * [ADR-0155 D4, plan step 5: the array-form `in` / `nin` decision] When either + * door of {@link parseFilterAST} refuses what it lowered and the condition + * carries a fixed-read leaf (`SharedRecordIds`), the refusal is ADR-0139 D3's + * envelope, `INTERNAL_ERROR` / 500, naming the first leaf, ⛔ not the door's + * `INVALID_FILTER` / 400. The shape door refuses the leaf as an array-form + * `in` / `nin` comparand (a non-list); the type door refuses it as a list + * member, or as a scalar operator's comparand (`!=`, `>` and the rest), where + * it reads as a plain object. + * + * No request can spell the leaf (its brand is a symbol no JSON carries) and its + * one producer places it in the object form at the engine's seam, never in the + * array form this function lowers, so a leaf here is the in-process code that + * wrote it: D4's reason for the envelope. The 400 was also the wrong answer to + * relay: a 4xx message reaches the caller, and both doors' messages printed + * the leaf's inputs, a principal's id among them. This message names the leaf + * by its name and table only. A leaf neither door refuses (an array-form `=`) + * is lowered by reference and refused at the engine's seam, as before. + */ +function refuseFixedReadLeafAtParse(condition: unknown, context: string | undefined): void { + const onPath = new Set(); + const find = (value: unknown, at: string): { at: string; leaf: unknown } | null => { + if (isFixedReadLeaf(value)) return { at, leaf: value }; + if (isComposedReadableIds(value)) return find(value.scope, `${at}.scope`); + if (value === null || typeof value !== 'object' || onPath.has(value)) return null; + onPath.add(value); + try { + const entries: [string, unknown][] = Array.isArray(value) + ? value.map((item, i) => [`${at}[${i}]`, item]) + : Object.keys(value).map((key) => [`${at}.${key}`, (value as Record)[key]]); + for (const [path, item] of entries) { + const found = find(item, path); + if (found) return found; + } + return null; + } finally { + onPath.delete(value); + } + }; + const found = find(condition, 'where'); + if (found === null || !isFixedReadLeaf(found.leaf)) return; + const err = new Error( + `${context ? `${context}: ` : ''}${found.at} holds a ${fixedReadLeafNameOf(found.leaf)} leaf, a fixed read of ` + + `'${fixedInnerReadOf(found.leaf).table}', in a condition parseFilterAST refuses: only the engine's seam places ` + + 'such a leaf, in the object form { id: { $in: leaf } } (ADR-0155 D1, D4). Refused rather than read as a ' + + 'comparand; write the leaf into the object-form where the engine is handed.', + ) as Error & { code: 'INTERNAL_ERROR'; status: 500; httpStatus: 500 }; + err.code = 'INTERNAL_ERROR'; + err.status = 500; + err.httpStatus = 500; + throw err; } /** diff --git a/packages/spec/src/data/shared-record-ids.test.ts b/packages/spec/src/data/shared-record-ids.test.ts index 5fe83684c4d..20a2cb14a2e 100644 --- a/packages/spec/src/data/shared-record-ids.test.ts +++ b/packages/spec/src/data/shared-record-ids.test.ts @@ -346,10 +346,52 @@ describe('the comparand-shape door admits the leaf only for a caller that names expect(err.message).toMatch(/^Operator "\$nin" on field "id" requires an ARRAY of values/); }); - it('the authoring lowering refuses the leaf: parseFilterAST is a door that names no brand', () => { - const err = refusalOf(() => parseFilterAST([['id', 'in', read]])); - expect(envelopeOf(err)).toEqual(ENVELOPE); - expect(err.message).toMatch(/Operator "\$in" on field "id" requires an ARRAY of values/); + it('the authoring lowering refuses the leaf in D4\'s envelope: parseFilterAST names no brand (plan step 5, the array-form decision)', () => { + // Was the shape door's INVALID_FILTER / 400 until plan step 5, and that + // message printed the leaf's inputs. A leaf here is the code that wrote it. + const secret = SharedRecordIds.read('account', 'u-secret-42'); + const shapes = [ + [['id', 'in', secret], 'where.id.$in'], + [['id', 'nin', secret], 'where.id.$nin'], + [['and', ['owner_id', '=', 'u1'], ['id', 'in', SharedRecordIds.write('account', 'u-secret-42', ['edit'])]], 'where.$and[1].id.$in'], + ] as const; + for (const [filter, at] of shapes) { + const err = refusalOf(() => parseFilterAST(filter, "find('account')")); + expect(envelopeOf(err), at).toEqual({ code: StandardErrorCode.enum.INTERNAL_ERROR, status: 500 }); + expect(err.message, at).toContain(`find('account'): ${at} holds a SharedRecordIds leaf, a fixed read of 'sys_record_share'`); + expect(err.message, at).not.toContain('u-secret-42'); + } + }); + + it('a leaf the type door refuses is D4\'s envelope too: a list member and a scalar operator\'s comparand', () => { + // The shape door passes both (a list, and an operator with no shape), so + // the type door's 400 answered them, printing the head of the leaf's JSON. + const secret = SharedRecordIds.read('account', 'u-secret-42'); + const shapes = [ + [['id', 'in', [secret]], 'where.id.$in[0]'], + [['id', '!=', secret], 'where.id.$ne'], + [['and', ['owner_id', '=', 'u1'], ['id', '>', secret]], 'where.$and[1].id.$gt'], + ] as const; + for (const [filter, at] of shapes) { + const err = refusalOf(() => parseFilterAST(filter, "find('account')")); + expect(envelopeOf(err), at).toEqual({ code: StandardErrorCode.enum.INTERNAL_ERROR, status: 500 }); + expect(err.message, at).toContain(`find('account'): ${at} holds a SharedRecordIds leaf, a fixed read of 'sys_record_share'`); + expect(err.message, at).not.toContain('u-secret'); + } + }); + + it('an unbranded copy of the array form keeps the author\'s INVALID_FILTER / 400: plan step 5 moved only the branded leaf', () => { + // That refusal is a request's: a copy that crossed JSON is no leaf. + const wire = refusalOf(() => parseFilterAST(JSON.parse(JSON.stringify([['id', 'in', read]])))); + expect(envelopeOf(wire)).toEqual(ENVELOPE); + expect(wire.message).toMatch(/Operator "\$in" on field "id" requires an ARRAY of values/); + // The type door's refusals of an unbranded copy, as a list member and as + // a scalar operator's comparand, stay the author's too. + for (const filter of [[['id', 'in', [read]]], [['id', '!=', read]]]) { + const copy = refusalOf(() => parseFilterAST(JSON.parse(JSON.stringify(filter)))); + expect(envelopeOf(copy), JSON.stringify(filter)).toEqual(ENVELOPE); + expect(copy.message, JSON.stringify(filter)).toMatch(/^Filter comparand at where\.id\.\$(in\[0\]|ne) is a plain object/); + } }); it('the schema doors never admit it, and no operator spells it', () => { diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 18f2547797f..ed848a5ac82 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -4451,6 +4451,11 @@ "verb": "findOne", "pinned": 1 }, + { + "file": "packages/plugins/plugin-security/src/explain-fixed-read-leaf.test.ts", + "verb": "findOne", + "pinned": 1 + }, { "file": "packages/plugins/plugin-security/src/explain-read-verdict-inputs.test.ts", "verb": "findOne",