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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .changeset/35874-fixed-read-leaf-census-rest.md
Original file line number Diff line number Diff line change
@@ -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.
27 changes: 27 additions & 0 deletions packages/drivers/driver-odata/src/odata-driver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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');
});
});
49 changes: 48 additions & 1 deletion packages/drivers/driver-odata/src/odata-driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -288,6 +289,7 @@ export class ODataDriver implements IDataDriver {

async find(object: string, query: DriverQuery = {}, _options?: DriverOptions): Promise<Row[]> {
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;
Expand Down Expand Up @@ -327,6 +329,7 @@ export class ODataDriver implements IDataDriver {

async count(object: string, query: DriverQuery = {}, _options?: DriverOptions): Promise<number> {
refuseReadableIds(query.where);
refuseFixedReadLeaf(query.where);
const binding = await this.bind(object);
const { filter, complete } = translateWhere(query.where, binding, this.dialect);
if (!complete) {
Expand Down Expand Up @@ -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<object>();
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<string, unknown>)[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). */
Expand Down
59 changes: 59 additions & 0 deletions packages/objectql/src/engine-fixed-read-leaf-seam.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down Expand Up @@ -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);
});
}
});
22 changes: 20 additions & 2 deletions packages/objectql/src/fixed-read-leaf-seam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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);
Expand Down Expand Up @@ -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<object, { logged: boolean }>();

Expand Down
6 changes: 6 additions & 0 deletions packages/objectql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading