From 8620e5c1e5885e4e3fc98eb1c85a294689b9e2d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 01:52:50 +0000 Subject: [PATCH 1/9] wip(plugin-audit): an activity text naming a referenced record by title is served only to a reader who may read that title Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../src/activity-field-redaction.test.ts | 276 +++++++++++++++++- .../src/activity-field-redaction.ts | 158 +++++++++- 2 files changed, 429 insertions(+), 5 deletions(-) diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts index ea9c893f57f..602494a25bc 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts @@ -39,7 +39,7 @@ import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; import type { EngineQueryOptions } from '@objectstack/spec/data'; import { AuditPlugin } from './audit-plugin.js'; -import { resolveServedFields } from './activity-field-redaction.js'; +import { referenceTitlesPerRead, resolveServedFields } from './activity-field-redaction.js'; import { singlePostureTenancy } from './__tests__/single-posture-tenancy.js'; import { installDefaultOrganization } from './default-organization.testkit.js'; @@ -387,3 +387,277 @@ describe('[#21081] resolveServedFields — the security service answer, as the r }, 'o', ctx)).toEqual([]); }); }); + +// ── a text composed from a reference names the referenced record's title ── + +/** Referenced by every reference below; titled by `secret_name`. */ +const REF_TARGET = 'afr_ref_target'; +/** Referenced by the object-level cases; titled by `title`. */ +const REF_CLOSED = 'afr_ref_closed'; +/** Titled by a lookup into {@link REF_TARGET}. */ +const REF_TITLED = 'afr_ref_titled'; +/** Titled by a lookup into {@link REF_CLOSED}. */ +const REF_TITLED_CLOSED = 'afr_ref_titled_closed'; +/** Titled by a lookup into {@link REF_CLOSED} that declares `referenceNameVisible`. */ +const REF_TITLED_VISIBLE = 'afr_ref_titled_visible'; +/** Titled by `name`; tracks a lookup into {@link REF_TARGET}. */ +const REF_TRACKED = 'afr_ref_tracked'; +const REF_PACKAGE = 'com.objectstack.audit.test.activity-reference-title'; + +/** Served neither target's title field; admitted to every object. */ +const TITLE_WITHHELD = { userId: 'u_title_withheld', tenantId: 'org_1', positions: ['org_member'] }; +/** Served every field; refused the closed target object. */ +const OBJECT_REFUSED = { userId: 'u_object_refused', tenantId: 'org_1', positions: ['org_member'] }; +/** Served every field, admitted to every object. */ +const REF_CONTROL = { userId: 'u_ref_control', tenantId: 'org_1', positions: ['org_member'] }; + +/** Synthetic titles. */ +const T = { one: 'AFRREFTITLEONE71', two: 'AFRREFTITLETWO72', closed: 'AFRREFCLOSED73' }; + +const refLookup = (reference: string, extra: Record = {}) => + ({ name: 'target', label: 'Target', type: 'lookup' as const, reference, ...extra }); +const refObjects = [ + { + name: REF_TARGET, label: 'Reference Target', nameField: 'secret_name', + fields: { + name: { name: 'name', label: 'Name', type: 'text' as const }, + secret_name: { name: 'secret_name', label: 'Secret Name', type: 'text' as const }, + }, + }, + { + name: REF_CLOSED, label: 'Reference Closed', nameField: 'title', + fields: { title: { name: 'title', label: 'Title', type: 'text' as const } }, + }, + { + name: REF_TITLED, label: 'Reference Titled', nameField: 'target', + fields: { name: { name: 'name', label: 'Name', type: 'text' as const }, target: refLookup(REF_TARGET) }, + }, + { + name: REF_TITLED_CLOSED, label: 'Reference Titled Closed', nameField: 'target', + fields: { name: { name: 'name', label: 'Name', type: 'text' as const }, target: refLookup(REF_CLOSED) }, + }, + { + name: REF_TITLED_VISIBLE, label: 'Reference Titled Visible', nameField: 'target', + fields: { + name: { name: 'name', label: 'Name', type: 'text' as const }, + target: refLookup(REF_CLOSED, { referenceNameVisible: true }), + }, + }, + { + name: REF_TRACKED, label: 'Reference Tracked', nameField: 'name', + fields: { + name: { name: 'name', label: 'Name', type: 'text' as const }, + target: refLookup(REF_TARGET, { trackHistory: true }), + }, + }, +]; + +describe('an activity text naming a referenced record by its title is served only to a reader who may read that title', () => { + let kernel: ObjectKernel; + let engine: ObjectQL; + const ids: Record = {}; + + const allFields = (object: string): string[] => + Object.keys(((engine as any).getSchema(object)?.fields ?? {}) as Record); + + /** The double: the field answers and the object-level read admission, per reader. */ + const security = { + async getReadableFields(object: string, context?: any): Promise { + const all = allFields(object); + if (context?.userId === TITLE_WITHHELD.userId) { + if (object === REF_TARGET) return all.filter((f) => f !== 'secret_name'); + if (object === REF_CLOSED) return all.filter((f) => f !== 'title'); + } + return all; + }, + async getQueryableFields(object: string, context?: any): Promise { + return security.getReadableFields(object, context); + }, + async canReadObject(object: string, context?: any): Promise { + return !(context?.userId === OBJECT_REFUSED.userId && object === REF_CLOSED); + }, + async getReadFilter(): Promise | undefined> { + return undefined; + }, + async explain(_request: { object: string }, context?: any): Promise<{ allowed: boolean }> { + return { allowed: !context?.isSystem }; + }, + }; + + const rowsAbout = (object: string, context: EngineQueryOptions['context']) => + engine.find(ACTIVITY, { + where: { object_name: object, record_id: ids[object] }, + orderBy: [{ field: 'timestamp', order: 'asc' }], + context, + }) as Promise; + + beforeAll(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } }); + await kernel.use(new ObjectQLPlugin()); + await kernel.use({ + name: 'test.security-double', + version: '0.0.0', + init: async (ctx: any) => ctx.registerService('security', security), + start: async () => {}, + } as any); + await kernel.use(singlePostureTenancy()); + await kernel.use(new AuditPlugin()); + await kernel.bootstrap(); + + engine = kernel.getService('objectql'); + const driver = new SqliteWasmDriver({ filename: ':memory:' }); + await driver.connect(); + engine.registerDriver(driver, true); + for (const object of refObjects) engine.registry.registerObject(object as any, REF_PACKAGE); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + + const insert = async (object: string, data: Row) => String((await engine.insert(object, data, { context: SYS })).id); + const one = await insert(REF_TARGET, { name: 'one', secret_name: T.one }); + const two = await insert(REF_TARGET, { name: 'two', secret_name: T.two }); + const closed = await insert(REF_CLOSED, { title: T.closed }); + ids[REF_TITLED] = await insert(REF_TITLED, { name: 'titled', target: one }); + await engine.update(REF_TITLED, { name: 'titled again' }, { where: { id: ids[REF_TITLED] }, context: SYS }); + ids[REF_TITLED_CLOSED] = await insert(REF_TITLED_CLOSED, { name: 'closed', target: closed }); + ids[REF_TITLED_VISIBLE] = await insert(REF_TITLED_VISIBLE, { name: 'visible', target: closed }); + ids[REF_TRACKED] = await insert(REF_TRACKED, { name: 'tracked', target: one }); + await engine.update(REF_TRACKED, { target: two }, { where: { id: ids[REF_TRACKED] }, context: SYS }); + }, 120_000); + + afterAll(async () => { + if (kernel) { + await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + } + }, 30_000); + + it('control: at rest, the mirror names each referenced record by its title', async () => { + const titled = await rowsAbout(REF_TITLED, SYS); + expect(titled.map((r) => r.type)).toEqual(['created', 'updated']); + for (const row of titled) expect(row.record_label).toBe(T.one); + expect((await rowsAbout(REF_TITLED_CLOSED, SYS))[0]?.record_label).toBe(T.closed); + expect(JSON.stringify(await rowsAbout(REF_TRACKED, SYS))).toContain(T.two); + }); + + it('a reader not served the referenced title field is served the rows without the label or a summary naming it, and keeps the record id', async () => { + const rows = await rowsAbout(REF_TITLED, TITLE_WITHHELD); + expect(rows.map((r) => r.type)).toEqual(['created', 'updated']); + for (const row of rows) { + expect(row).not.toHaveProperty('record_label'); + expect(row).not.toHaveProperty('summary'); + expect(row.record_id).toBe(ids[REF_TITLED]); + } + expect(JSON.stringify(rows)).not.toContain(T.one); + }); + + it('a reader refused the referenced object is served no text naming its records by title', async () => { + const rows = await rowsAbout(REF_TITLED_CLOSED, OBJECT_REFUSED); + expect(rows).toHaveLength(1); + expect(rows[0]).not.toHaveProperty('record_label'); + expect(rows[0]).not.toHaveProperty('summary'); + expect(JSON.stringify(rows)).not.toContain(T.closed); + }); + + it('referenceNameVisible lifts the object-level refusal and never the field-level rule', async () => { + const refused = await rowsAbout(REF_TITLED_VISIBLE, OBJECT_REFUSED); + expect(refused[0]?.record_label).toBe(T.closed); + const withheld = await rowsAbout(REF_TITLED_VISIBLE, TITLE_WITHHELD); + expect(withheld).toHaveLength(1); + expect(withheld[0]).not.toHaveProperty('record_label'); + expect(JSON.stringify(withheld)).not.toContain(T.closed); + }); + + it('a tracked reference change names the referenced records by title only to a reader served that title', async () => { + const withheld = (await rowsAbout(REF_TRACKED, TITLE_WITHHELD)).find((r) => r.type === 'updated'); + expect(withheld).toBeTruthy(); + expect(withheld).not.toHaveProperty('summary'); + expect(JSON.stringify(withheld)).not.toContain(T.one); + expect(JSON.stringify(withheld)).not.toContain(T.two); + // The record's own label is not composed from the reference: it stays. + expect(withheld?.record_label).toBe('tracked'); + }); + + it('control: a reader who may read every referenced title reads every row whole', async () => { + for (const row of await rowsAbout(REF_TITLED, REF_CONTROL)) { + expect(row.record_label).toBe(T.one); + expect(String(row.summary)).toContain(T.one); + } + expect((await rowsAbout(REF_TITLED_CLOSED, REF_CONTROL))[0]?.record_label).toBe(T.closed); + const tracked = (await rowsAbout(REF_TRACKED, REF_CONTROL)).find((r) => r.type === 'updated'); + expect(String(tracked?.summary)).toContain(T.one); + expect(String(tracked?.summary)).toContain(T.two); + }); + + it('findOne: the by-id read is judged like the list', async () => { + const [created] = await rowsAbout(REF_TITLED, SYS); + const row = await engine.findOne(ACTIVITY, { where: { id: created.id }, context: TITLE_WITHHELD }) as Row; + expect(row?.id).toBe(created.id); + expect(row).not.toHaveProperty('record_label'); + expect(JSON.stringify(row)).not.toContain(T.one); + }); +}); + +describe('referenceTitlesPerRead — a referenced title is served only to a reader who may read it', () => { + const schemas: Record = { + parent: { + name: 'parent', + fields: { + name: { type: 'text' }, + target: { type: 'lookup', reference: 'target' }, + visible: { type: 'lookup', reference: 'target', referenceNameVisible: true }, + untitled: { type: 'lookup', reference: 'untitled' }, + gone: { type: 'lookup', reference: 'not_registered' }, + }, + }, + target: { name: 'target', nameField: 'title', fields: { title: { type: 'text' } } }, + untitled: { name: 'untitled', nameField: 'id', fields: {} }, + }; + const schemaOf = (object: string) => schemas[object]; + const reader = { userId: 'u' }; + const answer = (served: string[] | undefined) => async () => served; + const security = (admits: boolean | Error | undefined) => ({ + getReadableFields: async () => [], + getQueryableFields: async () => [], + ...(admits === undefined + ? {} + : { canReadObject: async () => { if (admits instanceof Error) throw admits; return admits; } }), + }); + + it('a source that is not a reference is judged by the parent alone', async () => { + const judge = referenceTitlesPerRead(schemaOf, security(false), reader, answer([])); + expect(await judge('parent', ['name'])).toBe(true); + }); + + it('a reference is served only when the reader is served the target title field and admitted to the target', async () => { + expect(await referenceTitlesPerRead(schemaOf, security(true), reader, answer(['title']))('parent', ['target'])).toBe(true); + expect(await referenceTitlesPerRead(schemaOf, security(true), reader, answer([]))('parent', ['target'])).toBe(false); + expect(await referenceTitlesPerRead(schemaOf, security(false), reader, answer(['title']))('parent', ['target'])).toBe(false); + }); + + it('referenceNameVisible lifts the admission and never the field-level answer', async () => { + expect(await referenceTitlesPerRead(schemaOf, security(false), reader, answer(['title']))('parent', ['visible'])).toBe(true); + expect(await referenceTitlesPerRead(schemaOf, security(false), reader, answer([]))('parent', ['visible'])).toBe(false); + }); + + it('fail closed: a throwing admission, or a target that is not registered, serves no title', async () => { + const warnings: string[] = []; + const logger = { warn: (m: string) => warnings.push(m) }; + expect(await referenceTitlesPerRead(schemaOf, security(new Error('boom')), reader, answer(['title']), logger)('parent', ['target'])).toBe(false); + expect(warnings).toHaveLength(1); + expect(await referenceTitlesPerRead(schemaOf, security(true), reader, answer(['title']))('parent', ['gone'])).toBe(false); + }); + + it('a target with no title field is named by its id, which is no title to withhold', async () => { + expect(await referenceTitlesPerRead(schemaOf, security(false), reader, answer([]))('parent', ['untitled'])).toBe(true); + }); + + it('no admission member: the field-level answer alone decides; no answer for the target narrows nothing', async () => { + expect(await referenceTitlesPerRead(schemaOf, security(undefined), reader, answer(['title']))('parent', ['target'])).toBe(true); + expect(await referenceTitlesPerRead(schemaOf, security(true), reader, answer(undefined))('parent', ['target'])).toBe(true); + }); + + it('unknown provenance is judged against every reference field of the parent', async () => { + expect(await referenceTitlesPerRead(schemaOf, security(true), reader, answer(['title']))('parent', 'unknown')).toBe(false); + const known = { ...schemas, parent: { name: 'parent', fields: { name: { type: 'text' }, target: { type: 'lookup', reference: 'target' } } } }; + expect(await referenceTitlesPerRead((o) => known[o], security(true), reader, answer(['title']))('parent', 'unknown')).toBe(true); + }); +}); diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.ts index 0b9146cf5b2..3fb97736e66 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.ts @@ -63,6 +63,30 @@ * names fields, and which field names a reader may see is the metadata * plane's question, not this one's. * + * ## A text composed from a reference carries the referenced record's title + * + * The mirror names a referenced record by its TITLE: the record label of an + * object titled by a reference field, a tracked reference's change, a fired + * milestone's reference token. That title is a field of ANOTHER object, so the + * parent's served fields do not answer for it. A text whose declared sources + * name a reference field is served only to a reader who may read the title of + * the object it points at, the reader `$expand` gives that title to + * ({@link referenceTitlesPerRead}): + * + * - the reader is served the target's title field unmasked — its ADR-0079 + * `resolveDisplayField` answer, the field the mirror reads a title from — + * by the same {@link resolveServedFields} answer, which also withholds a + * formula title computed from a field the reader may not read; + * - and the security service admits the reader to the target object + * (`canReadObject`), unless the reference field declares + * `referenceNameVisible`: that key lifts the object-level refusal and never + * the field-level rule, as on `$expand`. + * + * Otherwise the text is dropped whole, like any text this reader is not served, + * and the row's `record_id` is the bare id it is named by. A text of unknown + * provenance is judged against every reference field of the parent. No row is + * read: the answers are asked once per target object per read. + * * ## Rows without a declaration * * - A row in the mirror's EARLIER shape — `metadata` exactly `{ old, new }`, @@ -154,6 +178,8 @@ * context-less programmatic calls are not redacted, as for the read gate. */ +import type { ISecurityService, SecurityContext } from '@objectstack/spec/contracts'; +import { referenceTargetOf, resolveDisplayField } from '@objectstack/spec/data'; import { ACTIVITY_CHANGED_FIELDS_COLUMN, ACTIVITY_KIND_KEY, @@ -230,8 +256,12 @@ const VALUE_BEARING_COLUMNS = [ ACTIVITY_MILESTONE_KEY_COLUMN, ] as const; -/** The slice of the security contract this seam asks — the REAL interface. */ -export type ActivityFieldVisibilitySource = FieldVisibilitySource; +/** + * The slice of the security contract this seam asks — the REAL interface: the + * two field answers, and the optional object-level read admission a text + * composed from a reference is judged by ({@link referenceTitlesPerRead}). + */ +export type ActivityFieldVisibilitySource = FieldVisibilitySource & Partial>; export type ActivityRedactionLogger = FieldRedactionLogger; @@ -341,6 +371,112 @@ async function sourcesServed( return sources === 'unknown' ? !(await restricted()) : sources.every((f) => served.has(f)); } +/** + * One read's answer to "may this reader read every referenced title a text + * composed from `sources` of `parent` names?" — `true` when no source is a + * reference field. `'unknown'` provenance names every field of the parent. + */ +export type ReferenceTitlesServedFor = (parent: string, sources: string[] | 'unknown') => Promise; + +/** + * {@link ReferenceTitlesServedFor} for ONE read, asked of the reader `context` + * (see "A text composed from a reference carries the referenced record's + * title" in this module's header). A source of `parent` that is a reference + * field (`referenceTargetOf`, the spec's one arbiter of a reference's target) + * names its target's title, and that title is served when: + * + * - the target declares no title field, or names the primary key: the mirror + * names such a record by its id, which is no title; + * - otherwise the reader is served the target's title field + * (`resolveDisplayField`) by `servedFor` — a target the service gives no + * answer for is not narrowed, as for the parent — AND the security service + * admits the reader to the target object (`canReadObject`, `=== true`; a + * throw refuses). A reference field declaring `referenceNameVisible` lifts + * only that admission, as it does on `$expand`. A service that answers no + * `canReadObject` leaves the title to the field-level answer, as the + * parent-record gate leaves its own objects to the caller-scoped read. + * + * A reference whose target is not registered, or a field declaration that + * cannot be read, refuses (fail closed). One answer per reference field and one + * admission per target object, per read; no row is read. + */ +export function referenceTitlesPerRead( + schemaOf: ((object: string) => unknown) | undefined, + security: ActivityFieldVisibilitySource | undefined, + context: unknown, + servedFor: ServedFor, + logger?: ActivityRedactionLogger, +): ReferenceTitlesServedFor { + const schema = (object: string): Record | undefined => { + try { + const s = schemaOf?.(object); + return isRecord(s) ? s : undefined; + } catch { + return undefined; + } + }; + const fieldsOf = (object: string): Record => { + const fields = schema(object)?.fields; + return isRecord(fields) ? fields : {}; + }; + + const admitted = new Map>(); + const admits = (target: string): Promise => { + let p = admitted.get(target); + if (!p) { + p = (async () => { + const canReadObject = security?.canReadObject; + if (typeof canReadObject !== 'function') return true; + try { + return (await canReadObject.call(security, target, { ...(context as object) } as SecurityContext)) === true; + } catch (err) { + logger?.warn( + `[audit] ${REDACTION_SEAM}: the object-level read admission for '${target}' failed — a text naming ` + + `its records by title is not served on this read (fail closed) (${(err as Error)?.message ?? err})`, + ); + return false; + } + })(); + admitted.set(target, p); + } + return p; + }; + + const perField = new Map>(); + const titleServed = (parent: string, field: string): Promise => { + const key = JSON.stringify([parent, field]); + let p = perField.get(key); + if (!p) { + p = (async () => { + const def = fieldsOf(parent)[field]; + let target: string | undefined; + try { + target = referenceTargetOf(def); + } catch { + return false; + } + if (!target) return true; + const targetSchema = schema(target); + if (!targetSchema) return false; + const titleField = resolveDisplayField(targetSchema as Parameters[0]); + if (!titleField || titleField === 'id') return true; + const served = await servedFor(target); + if (served !== undefined && !served.some((f) => String(f) === titleField)) return false; + if (isRecord(def) && def.referenceNameVisible === true) return true; + return admits(target); + })(); + perField.set(key, p); + } + return p; + }; + + return async (parent, sources) => { + const fields = sources === 'unknown' ? Object.keys(fieldsOf(parent)) : sources; + for (const field of fields) if (!(await titleServed(parent, field))) return false; + return true; + }; +} + /** * The engine slice the withheld-row rule needs: the registry its parent objects * are enumerated from, and each object's registered definition (its CURRENT @@ -530,6 +666,11 @@ export async function redactActivityRows( served?: ServedFor, /** [#22786] Likewise the read's answer for unknown provenance. */ restricted?: RestrictedFor, + /** The read's answer for a text composed from a reference + * ({@link referenceTitlesPerRead}). It needs the registry's definitions, so + * the middleware always hands it in; without it no source is judged as a + * reference. */ + referenceTitles?: ReferenceTitlesServedFor, ): Promise { const list = (Array.isArray(rows) ? rows : rows ? [rows] : []) as unknown[]; if (list.length === 0) return; @@ -604,7 +745,9 @@ export async function redactActivityRows( if (!provenance) continue; for (const col of TEXT_COLUMNS) { if (!(col in row)) continue; - if (!(await servedWhole(provenance[col]))) delete row[col]; + const served = (await servedWhole(provenance[col])) + && (!referenceTitles || (await referenceTitles(object, provenance[col]))); + if (!served) delete row[col]; } } } @@ -657,7 +800,14 @@ export function installActivityFieldRedaction( await next(); const list = (Array.isArray(ctx.result) ? ctx.result : ctx.result ? [ctx.result] : []) as unknown[]; try { - await redactActivityRows(list, security, ctx.context, logger, servedFor, restrictedFor); + const referenceTitles = referenceTitlesPerRead( + (object) => (typeof engine.getSchema === 'function' ? engine.getSchema(object) : undefined), + security, + ctx.context, + servedFor, + logger, + ); + await redactActivityRows(list, security, ctx.context, logger, servedFor, restrictedFor, referenceTitles); } catch (err) { // A redaction failure must never fall open into a leak. logger.warn( From ff61a848fe47e4b356497e406d6183daec489efa Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:11:35 +0000 Subject: [PATCH 2/9] wip: door-level pins and changeset for the reader-scoped referenced title Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../activity-reference-title-reader-scope.md | 17 ++ ...tivity-label-display-field.dogfood.test.ts | 174 ++++++++++++++++++ ...approval-notification-body.dogfood.test.ts | 148 +++++++++++++++ 3 files changed, 339 insertions(+) create mode 100644 .changeset/activity-reference-title-reader-scope.md diff --git a/.changeset/activity-reference-title-reader-scope.md b/.changeset/activity-reference-title-reader-scope.md new file mode 100644 index 00000000000..c503992c285 --- /dev/null +++ b/.changeset/activity-reference-title-reader-scope.md @@ -0,0 +1,17 @@ +--- +'@objectstack/plugin-audit': patch +--- + +fix(plugin-audit): an activity text that names a referenced record by its title is served only to a reader who may read that title + +Clause-②: no +Metadata-protocol: none + +**The rule.** An activity row names a referenced record by its title in three places: the record label of an object whose `nameField` is a lookup or `user` field, a tracked reference field's change, and a fired milestone's reference token. Each such text is served to a reader only when that reader may read the title of the object the reference points at, the reader `$expand` would serve the title to: + +- the reader is served the target object's title field (its ADR-0079 `nameField`) unmasked, by the security service's field answer, which also withholds a formula title computed from a field the reader may not read; and +- the security service admits the reader to the target object. A reference field that declares `referenceNameVisible` lifts this object-level admission and never the field-level rule, as it does on `$expand`. + +Otherwise the text is served the way any activity text composed from a field the reader is not served already is: the row keeps its `record_id`, and the label or summary is left out of the row. A row whose provenance is unknown is judged against every reference field of its object. A reader who may read the title, and every system read, are served the row as before. + +The judgement is made at read time from the security service's answers, once per referenced object per read; no row is read for it, and rows already written are judged the same way. diff --git a/packages/qa/dogfood/test/activity-label-display-field.dogfood.test.ts b/packages/qa/dogfood/test/activity-label-display-field.dogfood.test.ts index 89f1f76a088..9a3cc2f627d 100644 --- a/packages/qa/dogfood/test/activity-label-display-field.dogfood.test.ts +++ b/packages/qa/dogfood/test/activity-label-display-field.dogfood.test.ts @@ -225,3 +225,177 @@ describe('[#21878] an activity row names its record by the ADR-0079 title, with expect(blob).not.toContain(V.companyRenamed); }); }); + +// ── a label naming a referenced record by its title ───────────────────────── +// +// An object titled by a lookup is labelled by the referenced record's title. +// On a real boot, through the list door and the by-id door: a reader whose +// permission set withholds the target's title field is served the rows without +// the label and without a summary naming it, and keeps the record id; the +// control reader is served the title. Armed first: the data plane serves the +// withheld reader the target without its title field and the control with it, +// and the rows at rest carry the title. + +const REF_TARGET = 'ald_ref_target'; +const REF_TITLED = 'ald_ref_titled'; +const REF_TITLE = 'ALDREFTITLE65'; + +const RefTarget = ObjectSchema.create({ + name: REF_TARGET, + label: 'ALD Ref Target', + pluralLabel: 'ALD Ref Targets', + sharingModel: 'public_read_write', + nameField: 'code_name', + fields: { + name: Field.text({ label: 'Name' }), + code_name: Field.text({ label: 'Code Name' }), + }, +}); +const RefTitled = ObjectSchema.create({ + name: REF_TITLED, + label: 'ALD Ref Titled', + pluralLabel: 'ALD Ref Titled', + sharingModel: 'public_read_write', + nameField: 'target', + fields: { + name: Field.text({ label: 'Name' }), + target: Field.lookup(REF_TARGET, { label: 'Target' }), + }, +}); + +const refFixtureStack = defineStack({ + manifest: { + id: 'com.dogfood.activity-label-reference-title', + namespace: 'ald', + version: '0.0.0', + type: 'app', + name: 'Activity Label Reference Title Fixture', + description: 'An object titled by a lookup, mirrored on the activity timeline.', + }, + objects: [RefTarget, RefTitled], +}); + +const refGrants = { + ...Object.fromEntries( + [REF_TARGET, REF_TITLED].map((o) => [o, { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }]), + ), + sys_activity: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, +}; +const refBaselineSet = PermissionSetSchema.parse({ name: 'ald_ref_baseline', label: 'ALD ref baseline', objects: refGrants }); +const refWithholdSet = PermissionSetSchema.parse({ + name: 'ald_ref_withhold_set', + label: 'ALD ref withhold', + objects: refGrants, + fields: { [`${REF_TARGET}.code_name`]: { readable: false, editable: false } }, +}); +const REF_PRINCIPALS: Record<'writer' | 'withheld' | 'control', string[]> = { + writer: [refBaselineSet.name], + withheld: [refWithholdSet.name], + control: [refBaselineSet.name], +}; + +describe('an activity label naming a referenced record by its title is served only to a reader who may read that title', () => { + let stack: VerifyStack; + let ql: any; + const token: Record = {}; + let targetId = ''; + let recordId = ''; + + const listed = async (who: keyof typeof REF_PRINCIPALS): Promise => { + const filter = encodeURIComponent(JSON.stringify({ object_name: REF_TITLED, record_id: recordId })); + const res = await stack.apiAs(token[who], 'GET', `/data/sys_activity?$filter=${filter}`); + expect(res.status).toBe(200); + return rowsOf(await res.json()); + }; + const byId = async (who: keyof typeof REF_PRINCIPALS, id: string): Promise => { + const res = await stack.apiAs(token[who], 'GET', `/data/sys_activity/${id}`); + expect(res.status).toBe(200); + return recordOf(await res.json()); + }; + + beforeAll(async () => { + stack = await bootStack(refFixtureStack as unknown as Parameters[0], { + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, refBaselineSet, refWithholdSet], + fallbackPermissionSet: refBaselineSet.name, + }), + extraPlugins: [new AuditPlugin()], + }); + ql = await stack.kernel.getServiceAsync('objectql'); + const idOf = async (object: string, where: Record) => + String((await ql.findOne(object, { where, context: { isSystem: true } }))?.id ?? ''); + + for (const who of Object.keys(REF_PRINCIPALS) as Array) { + const email = `ald-ref-${who}@verify.test`; + token[who] = await stack.signUp(email); + const userId = await idOf('sys_user', { email }); + for (const name of REF_PRINCIPALS[who]) { + expect(await catalogPermissionSet(ql, name), `fixture permission set ${name} served by the security catalog`).toBeTruthy(); + await ql.insert('sys_user_permission_set', { user_id: userId, permission_set: name }, SYS); + } + } + + const post = async (object: string, body: Row) => { + const res = await stack.apiAs(token.writer, 'POST', `/data/${object}`, body); + expect(res.status).toBe(201); + return idOfBody(await res.json()); + }; + targetId = await post(REF_TARGET, { name: 'target', code_name: REF_TITLE }); + recordId = await post(REF_TITLED, { name: 'titled', target: targetId }); + const update = await stack.apiAs(token.writer, 'PATCH', `/data/${REF_TITLED}/${recordId}`, { name: 'titled again' }); + expect(update.status).toBe(200); + + const targetAs = async (who: keyof typeof REF_PRINCIPALS) => { + const res = await stack.apiAs(token[who], 'GET', `/data/${REF_TARGET}/${targetId}`); + const rec = recordOf(await res.json()); + return { status: res.status, title: !('code_name' in rec) ? 'absent' : rec.code_name === REF_TITLE ? 'stored' : 'replaced' }; + }; + + await assertArmed([ + armedWhen({ + control: 'the mirror wrote a created and an updated row, each labelled by the referenced record\'s title', + disarmedBy: 'a row labelled by an id would let every case below pass without a title to withhold', + observe: async () => + ((await ql.find('sys_activity', { where: { object_name: REF_TITLED, record_id: recordId }, context: { isSystem: true } })) as Row[]) + .map((r) => `${r.type}:${r.record_label === REF_TITLE}`).sort().join(','), + armed: (o) => o === 'created:true,updated:true', + describe: (o) => o, + }), + armedWhen({ + control: 'the data plane serves the withheld reader the target without its title field, and the control with it', + disarmedBy: 'a withholding set that did not resolve would make the withheld case measure an unrestricted reader', + observe: async () => ({ withheld: await targetAs('withheld'), control: await targetAs('control') }), + armed: (o) => + o.withheld.status === 200 && o.withheld.title === 'absent' && + o.control.status === 200 && o.control.title === 'stored', + describe: (o) => JSON.stringify(o), + }), + ]); + }, 180_000); + + afterAll(async () => { + if (stack) await stack.stop(); + }); + + it('a reader withheld the referenced title field is served the rows without the label or a summary naming it, list and by id', async () => { + const rows = await listed('withheld'); + expect(rows.map((r) => r.type).sort()).toEqual(['created', 'updated']); + for (const row of rows) { + expect(row).not.toHaveProperty('record_label'); + expect(row).not.toHaveProperty('summary'); + expect(row.record_id).toBe(recordId); + expect(JSON.stringify(await byId('withheld', row.id))).not.toContain(REF_TITLE); + } + expect(JSON.stringify(rows)).not.toContain(REF_TITLE); + }); + + it('control: a reader served the referenced title reads the label and the summary naming it', async () => { + const rows = await listed('control'); + expect(rows).toHaveLength(2); + for (const row of rows) { + expect(row.record_label).toBe(REF_TITLE); + expect(String(row.summary)).toContain(REF_TITLE); + expect((await byId('control', row.id)).record_label).toBe(REF_TITLE); + } + }); +}); diff --git a/packages/qa/dogfood/test/approval-notification-body.dogfood.test.ts b/packages/qa/dogfood/test/approval-notification-body.dogfood.test.ts index fdd18e49945..9aee612e0cb 100644 --- a/packages/qa/dogfood/test/approval-notification-body.dogfood.test.ts +++ b/packages/qa/dogfood/test/approval-notification-body.dogfood.test.ts @@ -188,3 +188,151 @@ describe('an approval notification reaches its recipient with its text in the bo 120_000, ); }); + +// ── the record a notification names, as each recipient may read it ───────── +// +// An approval notification names its record by a title the recipient may read, +// else by its id: here a FORMULA title over a field one approver's permission +// set withholds, which the security plugin withholds with it. On a booted app +// with the real security, approvals and messaging chain, read back from each +// approver's `GET /api/v1/notifications`: the withheld approver's notification +// carries no part of the withheld field, and the control approver's carries +// the title whole. Armed first: the data plane serves the withheld approver the +// record without the title, and the control with it. + +const TITLED = 'anb_titled'; +const TITLED_WITHHELD = 'anb-titled-withheld@example.com'; +const TITLED_CONTROL = 'anb-titled-control@example.com'; +const TITLED_SUBMITTER = 'anb-titled-submitter@example.com'; +const WITHHELD_CODE = 'ANBTITLECODE57'; + +const AnbTitled = ObjectSchema.create({ + name: TITLED, + label: 'Titled Request', + pluralLabel: 'Titled Requests', + sharingModel: 'public_read_write', + nameField: 'display_title', + fields: { + name: Field.text({ label: 'Name', required: true }), + code: Field.text({ label: 'Code' }), + display_title: Field.formula({ label: 'Display Title', expression: "record.name + ' ' + record.code", returnType: 'text' } as never), + }, +}); + +const AnbTitledFlow = defineFlow({ + name: 'anb_titled_flow', + label: 'Titled Request Flow', + description: 'Fires on insert and routes to two user approvers, authored as emails.', + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'On Create', config: { objectName: TITLED, triggerType: 'record-after-create' } }, + { + id: 'review', + type: 'approval', + label: 'Review', + config: { + approvers: [{ type: 'user', value: TITLED_WITHHELD }, { type: 'user', value: TITLED_CONTROL }], + behavior: 'first_response', + }, + }, + { id: 'approved', type: 'end', label: 'Approved' }, + { id: 'rejected', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'review' }, + { id: 'e2', source: 'review', target: 'approved', label: 'approve' }, + { id: 'e3', source: 'review', target: 'rejected', label: 'reject' }, + ], +}); + +const anbTitledStack = defineStack({ + manifest: { + id: 'com.dogfood.approval-notification-title', + namespace: 'anb', + version: '0.0.0', + type: 'app', + name: 'Approval Notification Title Fixture', + description: 'One object titled by a formula, one flow routed to two email-authored user approvers.', + }, + requires: ['automation', 'triggers'], + objects: [AnbTitled], + flows: [AnbTitledFlow], +}); + +const titledGrants = { [TITLED]: { allowRead: true, allowCreate: true, allowEdit: false, allowDelete: false } }; +const anbTitledMemberSet = PermissionSetSchema.parse({ + name: 'anb_titled_member', + label: 'Titled member — create + read on anb_titled only', + objects: titledGrants, +}); +const anbTitledWithholdSet = PermissionSetSchema.parse({ + name: 'anb_titled_withhold', + label: 'Titled withhold — the code field is not readable', + objects: titledGrants, + fields: { [`${TITLED}.code`]: { readable: false, editable: false } }, +}); + +describe('an approval notification names its record by a title the recipient may read, else not at all', () => { + it( + 'a recipient withheld a field of a formula title reads no part of it; the control reads the title', + async () => { + const stack = await bootStack(anbTitledStack as unknown as Parameters[0], { + automation: true, + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, anbTitledMemberSet, anbTitledWithholdSet], + fallbackPermissionSet: anbTitledMemberSet.name, + }), + extraPlugins: [ + new MessagingServicePlugin({ reliableDelivery: false }), + new RecordChangeTriggerPlugin(), + new ApprovalsServicePlugin(), + ], + }); + try { + const ql = (await stack.kernel.getServiceAsync('objectql')) as any; + const submitterToken = await stack.signUp(TITLED_SUBMITTER); + const withheldToken = await stack.signUp(TITLED_WITHHELD); + const controlToken = await stack.signUp(TITLED_CONTROL); + const withheldUser = await ql.findOne('sys_user', { where: { email: TITLED_WITHHELD }, context: { isSystem: true } }); + await ql.insert( + 'sys_user_permission_set', + { user_id: withheldUser.id, permission_set: anbTitledWithholdSet.name }, + { context: { isSystem: true } }, + ); + + const created = await stack.apiAs(submitterToken, 'POST', `/data/${TITLED}`, { name: 'contract', code: WITHHELD_CODE }); + expect(created.status).toBe(201); + const createdBody = (await created.json()) as { id?: string; record?: { id?: string } }; + const recordId = String(createdBody.id ?? createdBody.record?.id ?? ''); + + // Armed: the data plane serves the withheld approver the record without + // its title, and the control with it — else the case below measures an + // unrestricted recipient. + const titleAs = async (token: string) => { + const res = await stack.apiAs(token, 'GET', `/data/${TITLED}/${recordId}`); + expect(res.status).toBe(200); + const body = (await res.json()) as Record; + return (body.record ?? body).display_title ?? null; + }; + expect(await titleAs(withheldToken)).toBeNull(); + expect(await titleAs(controlToken)).toBe(`contract ${WITHHELD_CODE}`); + + const requested = async (token: string): Promise => { + const res = await stack.apiAs(token, 'GET', `/notifications?${new URLSearchParams({ type: 'approval.requested' })}`); + expect(res.status).toBe(200); + return ((await res.json()) as { data: { notifications: InboxRow[] } }).data.notifications; + }; + const toWithheld = await requested(withheldToken); + const toControl = await requested(controlToken); + expect(toWithheld, "the withheld approver's inbox holds the one request notification").toHaveLength(1); + expect(toControl, "the control approver's inbox holds the one request notification").toHaveLength(1); + expect(JSON.stringify(toWithheld)).not.toContain(WITHHELD_CODE); + expect(`${toControl[0].title} ${toControl[0].body}`).toContain(`contract ${WITHHELD_CODE}`); + } finally { + await stack.stop(); + } + }, + 120_000, + ); +}); From 793ff787f1ecb17b2a3a30c3a0c3aaf7d1cbd286 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:26:48 +0000 Subject: [PATCH 3/9] wip(plugin-audit): type the admission double Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../plugin-audit/src/activity-field-redaction.test.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts index 602494a25bc..c25ddec566d 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts @@ -615,11 +615,16 @@ describe('referenceTitlesPerRead — a referenced title is served only to a read const reader = { userId: 'u' }; const answer = (served: string[] | undefined) => async () => served; const security = (admits: boolean | Error | undefined) => ({ - getReadableFields: async () => [], - getQueryableFields: async () => [], + getReadableFields: async (): Promise => [], + getQueryableFields: async (): Promise => [], ...(admits === undefined ? {} - : { canReadObject: async () => { if (admits instanceof Error) throw admits; return admits; } }), + : { + canReadObject: async (): Promise => { + if (admits instanceof Error) throw admits; + return admits === true; + }, + }), }); it('a source that is not a reference is judged by the parent alone', async () => { From 06bbce6bca4cd0312a15f8374091daeafa7939ec Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:27:52 +0000 Subject: [PATCH 4/9] wip(plugin-audit): state the rule as the two answers it is judged by Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .changeset/activity-reference-title-reader-scope.md | 4 ++-- .../plugin-audit/src/activity-field-redaction.test.ts | 4 ++-- .../plugins/plugin-audit/src/activity-field-redaction.ts | 5 +++-- .../test/activity-label-display-field.dogfood.test.ts | 2 +- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/.changeset/activity-reference-title-reader-scope.md b/.changeset/activity-reference-title-reader-scope.md index c503992c285..1ac2d180317 100644 --- a/.changeset/activity-reference-title-reader-scope.md +++ b/.changeset/activity-reference-title-reader-scope.md @@ -2,12 +2,12 @@ '@objectstack/plugin-audit': patch --- -fix(plugin-audit): an activity text that names a referenced record by its title is served only to a reader who may read that title +fix(plugin-audit): an activity text that names a referenced record by its title is served only to a reader served that title field and admitted to its object Clause-②: no Metadata-protocol: none -**The rule.** An activity row names a referenced record by its title in three places: the record label of an object whose `nameField` is a lookup or `user` field, a tracked reference field's change, and a fired milestone's reference token. Each such text is served to a reader only when that reader may read the title of the object the reference points at, the reader `$expand` would serve the title to: +**The rule.** An activity row names a referenced record by its title in three places: the record label of an object whose `nameField` is a lookup or `user` field, a tracked reference field's change, and a fired milestone's reference token. Each such text is served to a reader only when both of these hold for the object the reference points at, the two answers `$expand` judges a target's title by at that level: - the reader is served the target object's title field (its ADR-0079 `nameField`) unmasked, by the security service's field answer, which also withholds a formula title computed from a field the reader may not read; and - the security service admits the reader to the target object. A reference field that declares `referenceNameVisible` lifts this object-level admission and never the field-level rule, as it does on `$expand`. diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts index c25ddec566d..0c5dbdefc81 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts @@ -452,7 +452,7 @@ const refObjects = [ }, ]; -describe('an activity text naming a referenced record by its title is served only to a reader who may read that title', () => { +describe('an activity text naming a referenced record by its title is served only to a reader served that title field and admitted to its object', () => { let kernel: ObjectKernel; let engine: ObjectQL; const ids: Record = {}; @@ -596,7 +596,7 @@ describe('an activity text naming a referenced record by its title is served onl }); }); -describe('referenceTitlesPerRead — a referenced title is served only to a reader who may read it', () => { +describe('referenceTitlesPerRead — a referenced title is served only to a reader served its title field and admitted to its object', () => { const schemas: Record = { parent: { name: 'parent', diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.ts index 3fb97736e66..11c0a9787d2 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.ts @@ -69,8 +69,9 @@ * object titled by a reference field, a tracked reference's change, a fired * milestone's reference token. That title is a field of ANOTHER object, so the * parent's served fields do not answer for it. A text whose declared sources - * name a reference field is served only to a reader who may read the title of - * the object it points at, the reader `$expand` gives that title to + * name a reference field is served only to a reader served the title field of + * the object it points at and admitted to that object, the two answers + * `$expand` judges a target's title by at that level * ({@link referenceTitlesPerRead}): * * - the reader is served the target's title field unmasked — its ADR-0079 diff --git a/packages/qa/dogfood/test/activity-label-display-field.dogfood.test.ts b/packages/qa/dogfood/test/activity-label-display-field.dogfood.test.ts index 9a3cc2f627d..5f2c5bcea00 100644 --- a/packages/qa/dogfood/test/activity-label-display-field.dogfood.test.ts +++ b/packages/qa/dogfood/test/activity-label-display-field.dogfood.test.ts @@ -294,7 +294,7 @@ const REF_PRINCIPALS: Record<'writer' | 'withheld' | 'control', string[]> = { control: [refBaselineSet.name], }; -describe('an activity label naming a referenced record by its title is served only to a reader who may read that title', () => { +describe('an activity label naming a referenced record by its title is served only to a reader served that title field', () => { let stack: VerifyStack; let ql: any; const token: Record = {}; From 64ae5387e09df731e2a4336b0fb07a6c6f4b199a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:42:34 +0000 Subject: [PATCH 5/9] wip(plugin-audit): a text of unknown provenance keeps its own rule Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../activity-reference-title-reader-scope.md | 2 +- .../src/activity-field-redaction.test.ts | 8 ++++---- .../src/activity-field-redaction.ts | 20 +++++++++---------- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/.changeset/activity-reference-title-reader-scope.md b/.changeset/activity-reference-title-reader-scope.md index 1ac2d180317..4e32ca6b66f 100644 --- a/.changeset/activity-reference-title-reader-scope.md +++ b/.changeset/activity-reference-title-reader-scope.md @@ -12,6 +12,6 @@ Metadata-protocol: none - the reader is served the target object's title field (its ADR-0079 `nameField`) unmasked, by the security service's field answer, which also withholds a formula title computed from a field the reader may not read; and - the security service admits the reader to the target object. A reference field that declares `referenceNameVisible` lifts this object-level admission and never the field-level rule, as it does on `$expand`. -Otherwise the text is served the way any activity text composed from a field the reader is not served already is: the row keeps its `record_id`, and the label or summary is left out of the row. A row whose provenance is unknown is judged against every reference field of its object. A reader who may read the title, and every system read, are served the row as before. +Otherwise the text is served the way any activity text composed from a field the reader is not served already is: the row keeps its `record_id`, and the label or summary is left out of the row. A reader who may read the title, and every system read, are served the row as before. The judgement is made at read time from the security service's answers, once per referenced object per read; no row is read for it, and rows already written are judged the same way. diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts index 0c5dbdefc81..ffff3826e2c 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts @@ -660,9 +660,9 @@ describe('referenceTitlesPerRead — a referenced title is served only to a read expect(await referenceTitlesPerRead(schemaOf, security(true), reader, answer(undefined))('parent', ['target'])).toBe(true); }); - it('unknown provenance is judged against every reference field of the parent', async () => { - expect(await referenceTitlesPerRead(schemaOf, security(true), reader, answer(['title']))('parent', 'unknown')).toBe(false); - const known = { ...schemas, parent: { name: 'parent', fields: { name: { type: 'text' }, target: { type: 'lookup', reference: 'target' } } } }; - expect(await referenceTitlesPerRead((o) => known[o], security(true), reader, answer(['title']))('parent', 'unknown')).toBe(true); + it('every declared reference source is judged: one the reader may not read refuses the text', async () => { + const judge = referenceTitlesPerRead(schemaOf, security(true), reader, async (o: string) => (o === 'target' ? ['title'] : [])); + expect(await judge('parent', ['name', 'target'])).toBe(true); + expect(await judge('parent', ['target', 'gone'])).toBe(false); }); }); diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.ts index 11c0a9787d2..d0865f5024b 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.ts @@ -84,9 +84,9 @@ * the field-level rule, as on `$expand`. * * Otherwise the text is dropped whole, like any text this reader is not served, - * and the row's `record_id` is the bare id it is named by. A text of unknown - * provenance is judged against every reference field of the parent. No row is - * read: the answers are asked once per target object per read. + * and the row's `record_id` is the bare id it is named by. A text whose + * provenance is unknown keeps the rule of rows without a declaration, below. No + * row is read: the answers are asked once per target object per read. * * ## Rows without a declaration * @@ -374,10 +374,10 @@ async function sourcesServed( /** * One read's answer to "may this reader read every referenced title a text - * composed from `sources` of `parent` names?" — `true` when no source is a - * reference field. `'unknown'` provenance names every field of the parent. + * composed from the declared `sources` of `parent` names?" — `true` when no + * source is a reference field. */ -export type ReferenceTitlesServedFor = (parent: string, sources: string[] | 'unknown') => Promise; +export type ReferenceTitlesServedFor = (parent: string, sources: readonly string[]) => Promise; /** * {@link ReferenceTitlesServedFor} for ONE read, asked of the reader `context` @@ -472,8 +472,7 @@ export function referenceTitlesPerRead( }; return async (parent, sources) => { - const fields = sources === 'unknown' ? Object.keys(fieldsOf(parent)) : sources; - for (const field of fields) if (!(await titleServed(parent, field))) return false; + for (const field of sources) if (!(await titleServed(parent, field))) return false; return true; }; } @@ -746,8 +745,9 @@ export async function redactActivityRows( if (!provenance) continue; for (const col of TEXT_COLUMNS) { if (!(col in row)) continue; - const served = (await servedWhole(provenance[col])) - && (!referenceTitles || (await referenceTitles(object, provenance[col]))); + const sources = provenance[col]; + const served = (await servedWhole(sources)) + && (!referenceTitles || sources === 'unknown' || (await referenceTitles(object, sources))); if (!served) delete row[col]; } } From ec536fa835158b9aeea3ba641564f021e6d0e4ff Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:11:51 +0000 Subject: [PATCH 6/9] wip(plugin-audit): a referenced title is served only from a target whose API exposure serves get Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../src/activity-field-redaction.test.ts | 90 ++++++++++++++++++- .../src/activity-field-redaction.ts | 35 ++++++-- 2 files changed, 116 insertions(+), 9 deletions(-) diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts index ffff3826e2c..df0b344c276 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts @@ -39,7 +39,7 @@ import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; import type { EngineQueryOptions } from '@objectstack/spec/data'; import { AuditPlugin } from './audit-plugin.js'; -import { referenceTitlesPerRead, resolveServedFields } from './activity-field-redaction.js'; +import { referenceTitlesPerRead, resolveServedFields, servesReferencedTitleTarget } from './activity-field-redaction.js'; import { singlePostureTenancy } from './__tests__/single-posture-tenancy.js'; import { installDefaultOrganization } from './default-organization.testkit.js'; @@ -402,6 +402,10 @@ const REF_TITLED_CLOSED = 'afr_ref_titled_closed'; const REF_TITLED_VISIBLE = 'afr_ref_titled_visible'; /** Titled by `name`; tracks a lookup into {@link REF_TARGET}. */ const REF_TRACKED = 'afr_ref_tracked'; +/** Referenced by the exposure case; titled by `title`; its declaration serves no API operation. */ +const REF_UNEXPOSED = 'afr_ref_unexposed'; +/** Titled by a lookup into {@link REF_UNEXPOSED} that declares `referenceNameVisible`. */ +const REF_TITLED_UNEXPOSED = 'afr_ref_titled_unexposed'; const REF_PACKAGE = 'com.objectstack.audit.test.activity-reference-title'; /** Served neither target's title field; admitted to every object. */ @@ -412,7 +416,7 @@ const OBJECT_REFUSED = { userId: 'u_object_refused', tenantId: 'org_1', position const REF_CONTROL = { userId: 'u_ref_control', tenantId: 'org_1', positions: ['org_member'] }; /** Synthetic titles. */ -const T = { one: 'AFRREFTITLEONE71', two: 'AFRREFTITLETWO72', closed: 'AFRREFCLOSED73' }; +const T = { one: 'AFRREFTITLEONE71', two: 'AFRREFTITLETWO72', closed: 'AFRREFCLOSED73', unexposed: 'AFRREFUNEXPOSED74' }; const refLookup = (reference: string, extra: Record = {}) => ({ name: 'target', label: 'Target', type: 'lookup' as const, reference, ...extra }); @@ -450,8 +454,39 @@ const refObjects = [ target: refLookup(REF_TARGET, { trackHistory: true }), }, }, + { + name: REF_UNEXPOSED, label: 'Reference Unexposed', nameField: 'title', enable: { apiEnabled: false }, + fields: { title: { name: 'title', label: 'Title', type: 'text' as const } }, + }, + { + name: REF_TITLED_UNEXPOSED, label: 'Reference Titled Unexposed', nameField: 'target', + fields: { + name: { name: 'name', label: 'Name', type: 'text' as const }, + target: refLookup(REF_UNEXPOSED, { referenceNameVisible: true }), + }, + }, ]; +/** + * A row in the mirror's declared shape, naming the record's referenced record + * by `title` in its label and its summary: the shape the mirror writes for an + * object titled by a lookup, inserted as written so the target's declaration + * can be judged at read time whatever it was when the row was written. + */ +const declaredReferenceRow = (object: string, recordId: string, target: string, title: string): Row => ({ + type: 'created', + timestamp: new Date().toISOString(), + object_name: object, + record_id: recordId, + record_label: title, + summary: `Created ${object} "${title}"`, + metadata: JSON.stringify({ + old: null, + new: { target }, + text_sources: { summary: ['target'], record_label: ['target'] }, + }), +}); + describe('an activity text naming a referenced record by its title is served only to a reader served that title field and admitted to its object', () => { let kernel: ObjectKernel; let engine: ObjectQL; @@ -522,6 +557,18 @@ describe('an activity text naming a referenced record by its title is served onl ids[REF_TITLED_VISIBLE] = await insert(REF_TITLED_VISIBLE, { name: 'visible', target: closed }); ids[REF_TRACKED] = await insert(REF_TRACKED, { name: 'tracked', target: one }); await engine.update(REF_TRACKED, { target: two }, { where: { id: ids[REF_TRACKED] }, context: SYS }); + + // [ADR-0049] The exposure case and its control: one row each in the + // mirror's declared shape, naming the referenced record by its title. + const unexposed = await insert(REF_UNEXPOSED, { title: T.unexposed }); + ids.unexposedRecord = await insert(REF_TITLED_UNEXPOSED, { name: 'unexposed', target: unexposed }); + ids.exposedRecord = await insert(REF_TITLED, { name: 'exposed', target: one }); + for (const row of [ + declaredReferenceRow(REF_TITLED_UNEXPOSED, ids.unexposedRecord, unexposed, T.unexposed), + declaredReferenceRow(REF_TITLED, ids.exposedRecord, one, T.one), + ]) { + await engine.insert(ACTIVITY, row, { context: SYS }); + } }, 120_000); afterAll(async () => { @@ -587,6 +634,30 @@ describe('an activity text naming a referenced record by its title is served onl expect(String(tracked?.summary)).toContain(T.two); }); + it('a referenced object whose API exposure does not serve get serves its title to no reader, referenceNameVisible included', async () => { + const atRest = (await engine.find(ACTIVITY, { + where: { object_name: REF_TITLED_UNEXPOSED, record_id: ids.unexposedRecord }, + context: SYS, + })) as Row[]; + expect(atRest.some((r) => r.record_label === T.unexposed)).toBe(true); + const refused = (await engine.find(ACTIVITY, { + where: { object_name: REF_TITLED_UNEXPOSED, record_id: ids.unexposedRecord }, + context: REF_CONTROL, + })) as Row[]; + expect(refused.length).toBeGreaterThanOrEqual(1); + expect(JSON.stringify(refused)).not.toContain(T.unexposed); + for (const row of refused) { + expect(row.record_id).toBe(ids.unexposedRecord); + if (row.record_label !== undefined) expect(row.record_label).not.toBe(T.unexposed); + } + // Control: the same row shape about an exposed target is served whole. + const exposed = (await engine.find(ACTIVITY, { + where: { object_name: REF_TITLED, record_id: ids.exposedRecord }, + context: REF_CONTROL, + })) as Row[]; + expect(exposed.filter((r) => r.record_label === T.one && String(r.summary).includes(T.one)).length).toBeGreaterThanOrEqual(1); + }); + it('findOne: the by-id read is judged like the list', async () => { const [created] = await rowsAbout(REF_TITLED, SYS); const row = await engine.findOne(ACTIVITY, { where: { id: created.id }, context: TITLE_WITHHELD }) as Row; @@ -606,10 +677,14 @@ describe('referenceTitlesPerRead — a referenced title is served only to a read visible: { type: 'lookup', reference: 'target', referenceNameVisible: true }, untitled: { type: 'lookup', reference: 'untitled' }, gone: { type: 'lookup', reference: 'not_registered' }, + hidden: { type: 'lookup', reference: 'hidden', referenceNameVisible: true }, + listonly: { type: 'lookup', reference: 'listonly' }, }, }, target: { name: 'target', nameField: 'title', fields: { title: { type: 'text' } } }, untitled: { name: 'untitled', nameField: 'id', fields: {} }, + hidden: { name: 'hidden', nameField: 'title', enable: { apiEnabled: false }, fields: { title: { type: 'text' } } }, + listonly: { name: 'listonly', nameField: 'title', enable: { apiMethods: ['list'] }, fields: { title: { type: 'text' } } }, }; const schemaOf = (object: string) => schemas[object]; const reader = { userId: 'u' }; @@ -655,6 +730,17 @@ describe('referenceTitlesPerRead — a referenced title is served only to a read expect(await referenceTitlesPerRead(schemaOf, security(false), reader, answer([]))('parent', ['untitled'])).toBe(true); }); + it('a target whose API exposure does not serve get is refused for every reader; an exposed target is the control', async () => { + const judge = referenceTitlesPerRead(schemaOf, security(true), reader, answer(['title'])); + expect(await judge('parent', ['hidden'])).toBe(false); + expect(await judge('parent', ['listonly'])).toBe(false); + expect(await judge('parent', ['target'])).toBe(true); + expect(servesReferencedTitleTarget(schemas.hidden)).toBe(false); + expect(servesReferencedTitleTarget(schemas.listonly)).toBe(false); + expect(servesReferencedTitleTarget(schemas.target)).toBe(true); + expect(servesReferencedTitleTarget({ name: 'x', enable: { apiMethods: ['get'] } })).toBe(true); + }); + it('no admission member: the field-level answer alone decides; no answer for the target narrows nothing', async () => { expect(await referenceTitlesPerRead(schemaOf, security(undefined), reader, answer(['title']))('parent', ['target'])).toBe(true); expect(await referenceTitlesPerRead(schemaOf, security(true), reader, answer(undefined))('parent', ['target'])).toBe(true); diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.ts index d0865f5024b..752734bc741 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.ts @@ -81,7 +81,11 @@ * - and the security service admits the reader to the target object * (`canReadObject`), unless the reference field declares * `referenceNameVisible`: that key lifts the object-level refusal and never - * the field-level rule, as on `$expand`. + * the field-level rule, as on `$expand`; + * - and the target's declared API exposure serves `get` + * ({@link servesReferencedTitleTarget}, ADR-0049), for every reader: + * `$expand` withholds a target that exposure refuses whatever the field + * declares. * * Otherwise the text is dropped whole, like any text this reader is not served, * and the row's `record_id` is the bare id it is named by. A text whose @@ -180,7 +184,7 @@ */ import type { ISecurityService, SecurityContext } from '@objectstack/spec/contracts'; -import { referenceTargetOf, resolveDisplayField } from '@objectstack/spec/data'; +import { canServeApiOperation, referenceTargetOf, resolveDisplayField, type EnableLike } from '@objectstack/spec/data'; import { ACTIVITY_CHANGED_FIELDS_COLUMN, ACTIVITY_KIND_KEY, @@ -372,6 +376,21 @@ async function sourcesServed( return sources === 'unknown' ? !(await restricted()) : sources.every((f) => served.has(f)); } +/** + * [ADR-0049] May a text this redaction serves carry a title read from the + * object `targetSchema` declares? Asked of the spec's one exposure decision for + * `get`: the operation the data door's `$expand` asks of a target before it + * serves anything of it, and the one the mirror asks before it reads a title + * at write time (`servesSummaryTitleTarget`, `audit-writers.ts`). It takes no + * reader: a target whose declaration does not serve `get` serves its title to + * nobody, a reference declaring `referenceNameVisible` included. A declaration + * that is not an object declares no `enable` block, which refuses nothing. + */ +export function servesReferencedTitleTarget(targetSchema: unknown): boolean { + const enable = isRecord(targetSchema) ? (targetSchema.enable as EnableLike | null | undefined) : undefined; + return canServeApiOperation(enable, 'get'); +} + /** * One read's answer to "may this reader read every referenced title a text * composed from the declared `sources` of `parent` names?" — `true` when no @@ -388,11 +407,12 @@ export type ReferenceTitlesServedFor = (parent: string, sources: readonly string * * - the target declares no title field, or names the primary key: the mirror * names such a record by its id, which is no title; - * - otherwise the reader is served the target's title field - * (`resolveDisplayField`) by `servedFor` — a target the service gives no - * answer for is not narrowed, as for the parent — AND the security service - * admits the reader to the target object (`canReadObject`, `=== true`; a - * throw refuses). A reference field declaring `referenceNameVisible` lifts + * - otherwise the target's declared exposure serves `get` + * ({@link servesReferencedTitleTarget}), AND the reader is served the + * target's title field (`resolveDisplayField`) by `servedFor` — a target + * the service gives no answer for is not narrowed, as for the parent — AND + * the security service admits the reader to the target object + * (`canReadObject`, `=== true`; a throw refuses). A reference field declaring `referenceNameVisible` lifts * only that admission, as it does on `$expand`. A service that answers no * `canReadObject` leaves the title to the field-level answer, as the * parent-record gate leaves its own objects to the caller-scoped read. @@ -461,6 +481,7 @@ export function referenceTitlesPerRead( if (!targetSchema) return false; const titleField = resolveDisplayField(targetSchema as Parameters[0]); if (!titleField || titleField === 'id') return true; + if (!servesReferencedTitleTarget(targetSchema)) return false; const served = await servedFor(target); if (served !== undefined && !served.some((f) => String(f) === titleField)) return false; if (isRecord(def) && def.referenceNameVisible === true) return true; From 080970572b19d84128a51566fc3ed118e5c89823 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:12:14 +0000 Subject: [PATCH 7/9] test(core): classify the activity redaction's referenced-title read in the second-object exposure census Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../security/second-object-read-exposure.pin.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index 541496d66f5..be71d589718 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -195,6 +195,16 @@ const CALLERS: Record = { wiring: { file: 'packages/plugins/plugin-audit/src/audit-writers.ts', call: 'servesSummaryTitleTarget(objectName' }, pin: 'packages/plugins/plugin-audit/src/audit-lookup-summary.test.ts', }, + 'packages/plugins/plugin-audit/src/activity-field-redaction.ts': { + kind: 'decided', + read: + "the activity timeline's read redaction (`referenceTitlesPerRead` serves a row's label or summary naming a " + + "referenced record by title only when the target's declaration, field answer and object admission serve it)", + operation: 'get', + decision: { file: 'packages/plugins/plugin-audit/src/activity-field-redaction.ts', fn: 'servesReferencedTitleTarget' }, + wiring: { file: 'packages/plugins/plugin-audit/src/activity-field-redaction.ts', call: 'servesReferencedTitleTarget(targetSchema' }, + pin: 'packages/plugins/plugin-audit/src/activity-field-redaction.test.ts', + }, // The engine's relation group join: an analytics cross-object dimension as one `LEFT JOIN … GROUP BY`. 'packages/objectql/src/relation-group-join.ts': { kind: 'decided', @@ -514,6 +524,7 @@ describe('[#22661] every read that reaches a second object asks that object its 'servesLabelTarget', 'servesPayloadDisplayTarget', 'servesReferenceTarget', + 'servesReferencedTitleTarget', 'servesSummaryTitleTarget', ]); From 86880c83965748872e179e1ea5ff0da6891159e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:19:19 +0000 Subject: [PATCH 8/9] wip: the changeset states the exposure half of the rule Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .changeset/activity-reference-title-reader-scope.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.changeset/activity-reference-title-reader-scope.md b/.changeset/activity-reference-title-reader-scope.md index 4e32ca6b66f..e1e851fbd3e 100644 --- a/.changeset/activity-reference-title-reader-scope.md +++ b/.changeset/activity-reference-title-reader-scope.md @@ -7,11 +7,12 @@ fix(plugin-audit): an activity text that names a referenced record by its title Clause-②: no Metadata-protocol: none -**The rule.** An activity row names a referenced record by its title in three places: the record label of an object whose `nameField` is a lookup or `user` field, a tracked reference field's change, and a fired milestone's reference token. Each such text is served to a reader only when both of these hold for the object the reference points at, the two answers `$expand` judges a target's title by at that level: +**The rule.** An activity row names a referenced record by its title in three places: the record label of an object whose `nameField` is a lookup or `user` field, a tracked reference field's change, and a fired milestone's reference token. Each such text is served to a reader only when all three of these hold for the object the reference points at, the answers `$expand` judges a target's title by at the declaration, object and field level: -- the reader is served the target object's title field (its ADR-0079 `nameField`) unmasked, by the security service's field answer, which also withholds a formula title computed from a field the reader may not read; and -- the security service admits the reader to the target object. A reference field that declares `referenceNameVisible` lifts this object-level admission and never the field-level rule, as it does on `$expand`. +- the reader is served the target object's title field (its ADR-0079 `nameField`) unmasked, by the security service's field answer, which also withholds a formula title computed from a field the reader may not read; +- the security service admits the reader to the target object. A reference field that declares `referenceNameVisible` lifts this object-level admission and never the field-level rule, as it does on `$expand`; and +- the target object's declared API exposure serves `get` (ADR-0049). This holds for every reader, a reference declaring `referenceNameVisible` included, as `$expand` withholds a target its exposure refuses. -Otherwise the text is served the way any activity text composed from a field the reader is not served already is: the row keeps its `record_id`, and the label or summary is left out of the row. A reader who may read the title, and every system read, are served the row as before. +Otherwise the text is served the way any activity text composed from a field the reader is not served already is: the row keeps its `record_id`, and the label or summary is left out of the row. A reader served the title field and admitted to its object, of a target whose exposure serves `get`, and every system read, are served the row as before. The judgement is made at read time from the security service's answers, once per referenced object per read; no row is read for it, and rows already written are judged the same way. From 37b748d8d06e31ac9ad4d454d36b079c8225fdb1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:26:09 +0000 Subject: [PATCH 9/9] fix(plugin-audit): judge a referenced title by its reader, and leave its exposure to the write that read it Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../activity-reference-title-reader-scope.md | 11 ++- .../second-object-read-exposure.pin.test.ts | 17 ++-- .../src/activity-field-redaction.test.ts | 98 ++++++------------- .../src/activity-field-redaction.ts | 43 +++----- 4 files changed, 62 insertions(+), 107 deletions(-) diff --git a/.changeset/activity-reference-title-reader-scope.md b/.changeset/activity-reference-title-reader-scope.md index e1e851fbd3e..b35893837c6 100644 --- a/.changeset/activity-reference-title-reader-scope.md +++ b/.changeset/activity-reference-title-reader-scope.md @@ -7,12 +7,13 @@ fix(plugin-audit): an activity text that names a referenced record by its title Clause-②: no Metadata-protocol: none -**The rule.** An activity row names a referenced record by its title in three places: the record label of an object whose `nameField` is a lookup or `user` field, a tracked reference field's change, and a fired milestone's reference token. Each such text is served to a reader only when all three of these hold for the object the reference points at, the answers `$expand` judges a target's title by at the declaration, object and field level: +**The rule.** An activity row names a referenced record by its title in three places: the record label of an object whose `nameField` is a lookup or `user` field, a tracked reference field's change, and a fired milestone's reference token. Each such text is served to a reader only when both of these hold for the object every such reference points at, the two answers `$expand` judges a target's title by at that level: -- the reader is served the target object's title field (its ADR-0079 `nameField`) unmasked, by the security service's field answer, which also withholds a formula title computed from a field the reader may not read; -- the security service admits the reader to the target object. A reference field that declares `referenceNameVisible` lifts this object-level admission and never the field-level rule, as it does on `$expand`; and -- the target object's declared API exposure serves `get` (ADR-0049). This holds for every reader, a reference declaring `referenceNameVisible` included, as `$expand` withholds a target its exposure refuses. +- the reader is served the target object's title field (its ADR-0079 `nameField`) unmasked, by the security service's field answer, which also withholds a formula title computed from a field the reader may not read; and +- the security service admits the reader to the target object. A reference field that declares `referenceNameVisible` lifts this object-level admission and never the field-level rule, as it does on `$expand`. -Otherwise the text is served the way any activity text composed from a field the reader is not served already is: the row keeps its `record_id`, and the label or summary is left out of the row. A reader served the title field and admitted to its object, of a target whose exposure serves `get`, and every system read, are served the row as before. +Otherwise the text is served the way any activity text composed from a field the reader is not served already is: the row keeps its `record_id`, and the label or summary is left out of the row. A reader served each referenced title field and admitted to each referenced object, and every system read, are served the row as before. + +A target's declared API exposure (ADR-0049) is decided where its title is read: the mirror titles a reference only when the target's exposure serves `get`, and names every other referenced record by its stored id, so one sentence can title one reference and name another by its id. Such a sentence is judged by the two answers above for every reference it names, whatever the target's exposure. The judgement is made at read time from the security service's answers, once per referenced object per read; no row is read for it, and rows already written are judged the same way. diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index be71d589718..352a8741e6c 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -196,14 +196,16 @@ const CALLERS: Record = { pin: 'packages/plugins/plugin-audit/src/audit-lookup-summary.test.ts', }, 'packages/plugins/plugin-audit/src/activity-field-redaction.ts': { - kind: 'decided', + kind: 'executes', read: - "the activity timeline's read redaction (`referenceTitlesPerRead` serves a row's label or summary naming a " + - "referenced record by title only when the target's declaration, field answer and object admission serve it)", - operation: 'get', - decision: { file: 'packages/plugins/plugin-audit/src/activity-field-redaction.ts', fn: 'servesReferencedTitleTarget' }, - wiring: { file: 'packages/plugins/plugin-audit/src/activity-field-redaction.ts', call: 'servesReferencedTitleTarget(targetSchema' }, - pin: 'packages/plugins/plugin-audit/src/activity-field-redaction.test.ts', + "the activity timeline's read redaction, serving per reader the referenced records' titles the mirror's " + + '`resolveLookupTitles` wrote (`referenceTitlesPerRead` judges each reader against the title field and the object ' + + 'of every reference a text names)', + decidedIn: 'packages/plugins/plugin-audit/src/audit-writers.ts', + also: + 'reads no record of the target and no title: `referenceTargetOf` names the object whose title field and read ' + + 'admission a reader is judged against; the title was read at write time, only from a target whose exposure ' + + 'serves `get` (`servesSummaryTitleTarget`). Pinned in `activity-field-redaction.test.ts`', }, // The engine's relation group join: an analytics cross-object dimension as one `LEFT JOIN … GROUP BY`. 'packages/objectql/src/relation-group-join.ts': { @@ -524,7 +526,6 @@ describe('[#22661] every read that reaches a second object asks that object its 'servesLabelTarget', 'servesPayloadDisplayTarget', 'servesReferenceTarget', - 'servesReferencedTitleTarget', 'servesSummaryTitleTarget', ]); diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts index df0b344c276..d3bf84e5b9f 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts @@ -39,7 +39,7 @@ import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; import type { EngineQueryOptions } from '@objectstack/spec/data'; import { AuditPlugin } from './audit-plugin.js'; -import { referenceTitlesPerRead, resolveServedFields, servesReferencedTitleTarget } from './activity-field-redaction.js'; +import { referenceTitlesPerRead, resolveServedFields } from './activity-field-redaction.js'; import { singlePostureTenancy } from './__tests__/single-posture-tenancy.js'; import { installDefaultOrganization } from './default-organization.testkit.js'; @@ -404,8 +404,8 @@ const REF_TITLED_VISIBLE = 'afr_ref_titled_visible'; const REF_TRACKED = 'afr_ref_tracked'; /** Referenced by the exposure case; titled by `title`; its declaration serves no API operation. */ const REF_UNEXPOSED = 'afr_ref_unexposed'; -/** Titled by a lookup into {@link REF_UNEXPOSED} that declares `referenceNameVisible`. */ -const REF_TITLED_UNEXPOSED = 'afr_ref_titled_unexposed'; +/** Titled by `name`; tracks a lookup into {@link REF_UNEXPOSED} and one into {@link REF_TARGET}. */ +const REF_TRACKED_MIXED = 'afr_ref_tracked_mixed'; const REF_PACKAGE = 'com.objectstack.audit.test.activity-reference-title'; /** Served neither target's title field; admitted to every object. */ @@ -459,33 +459,15 @@ const refObjects = [ fields: { title: { name: 'title', label: 'Title', type: 'text' as const } }, }, { - name: REF_TITLED_UNEXPOSED, label: 'Reference Titled Unexposed', nameField: 'target', + name: REF_TRACKED_MIXED, label: 'Reference Tracked Mixed', nameField: 'name', fields: { name: { name: 'name', label: 'Name', type: 'text' as const }, - target: refLookup(REF_UNEXPOSED, { referenceNameVisible: true }), + hidden: { name: 'hidden', label: 'Hidden', type: 'lookup' as const, reference: REF_UNEXPOSED, trackHistory: true }, + open: { name: 'open', label: 'Open', type: 'lookup' as const, reference: REF_TARGET, trackHistory: true }, }, }, ]; -/** - * A row in the mirror's declared shape, naming the record's referenced record - * by `title` in its label and its summary: the shape the mirror writes for an - * object titled by a lookup, inserted as written so the target's declaration - * can be judged at read time whatever it was when the row was written. - */ -const declaredReferenceRow = (object: string, recordId: string, target: string, title: string): Row => ({ - type: 'created', - timestamp: new Date().toISOString(), - object_name: object, - record_id: recordId, - record_label: title, - summary: `Created ${object} "${title}"`, - metadata: JSON.stringify({ - old: null, - new: { target }, - text_sources: { summary: ['target'], record_label: ['target'] }, - }), -}); describe('an activity text naming a referenced record by its title is served only to a reader served that title field and admitted to its object', () => { let kernel: ObjectKernel; @@ -558,17 +540,12 @@ describe('an activity text naming a referenced record by its title is served onl ids[REF_TRACKED] = await insert(REF_TRACKED, { name: 'tracked', target: one }); await engine.update(REF_TRACKED, { target: two }, { where: { id: ids[REF_TRACKED] }, context: SYS }); - // [ADR-0049] The exposure case and its control: one row each in the - // mirror's declared shape, naming the referenced record by its title. - const unexposed = await insert(REF_UNEXPOSED, { title: T.unexposed }); - ids.unexposedRecord = await insert(REF_TITLED_UNEXPOSED, { name: 'unexposed', target: unexposed }); - ids.exposedRecord = await insert(REF_TITLED, { name: 'exposed', target: one }); - for (const row of [ - declaredReferenceRow(REF_TITLED_UNEXPOSED, ids.unexposedRecord, unexposed, T.unexposed), - declaredReferenceRow(REF_TITLED, ids.exposedRecord, one, T.one), - ]) { - await engine.insert(ACTIVITY, row, { context: SYS }); - } + // [ADR-0049] One change moving a reference into a target whose exposure + // serves no `get` (the mirror names it by its id) and one into an exposed + // target (named by its title). + ids.unexposed = await insert(REF_UNEXPOSED, { title: T.unexposed }); + ids[REF_TRACKED_MIXED] = await insert(REF_TRACKED_MIXED, { name: 'mixed' }); + await engine.update(REF_TRACKED_MIXED, { hidden: ids.unexposed, open: one }, { where: { id: ids[REF_TRACKED_MIXED] }, context: SYS }); }, 120_000); afterAll(async () => { @@ -634,28 +611,20 @@ describe('an activity text naming a referenced record by its title is served onl expect(String(tracked?.summary)).toContain(T.two); }); - it('a referenced object whose API exposure does not serve get serves its title to no reader, referenceNameVisible included', async () => { - const atRest = (await engine.find(ACTIVITY, { - where: { object_name: REF_TITLED_UNEXPOSED, record_id: ids.unexposedRecord }, - context: SYS, - })) as Row[]; - expect(atRest.some((r) => r.record_label === T.unexposed)).toBe(true); - const refused = (await engine.find(ACTIVITY, { - where: { object_name: REF_TITLED_UNEXPOSED, record_id: ids.unexposedRecord }, - context: REF_CONTROL, - })) as Row[]; - expect(refused.length).toBeGreaterThanOrEqual(1); - expect(JSON.stringify(refused)).not.toContain(T.unexposed); - for (const row of refused) { - expect(row.record_id).toBe(ids.unexposedRecord); - if (row.record_label !== undefined) expect(row.record_label).not.toBe(T.unexposed); - } - // Control: the same row shape about an exposed target is served whole. - const exposed = (await engine.find(ACTIVITY, { - where: { object_name: REF_TITLED, record_id: ids.exposedRecord }, - context: REF_CONTROL, - })) as Row[]; - expect(exposed.filter((r) => r.record_label === T.one && String(r.summary).includes(T.one)).length).toBeGreaterThanOrEqual(1); + it('a change naming an unexposed target by its id and an exposed one by its title is served to a reader who may read that title, and to no reader withheld it', async () => { + const updatedAs = async (context: EngineQueryOptions['context']) => + (await rowsAbout(REF_TRACKED_MIXED, context)).find((r) => r.type === 'updated'); + const atRest = await updatedAs(SYS); + expect(String(atRest?.summary)).toContain(T.one); + expect(String(atRest?.summary)).toContain(ids.unexposed); + expect(String(atRest?.summary)).not.toContain(T.unexposed); + const control = await updatedAs(REF_CONTROL); + expect(String(control?.summary)).toContain(T.one); + expect(String(control?.summary)).toContain(ids.unexposed); + const withheld = await updatedAs(TITLE_WITHHELD); + expect(withheld).toBeTruthy(); + expect(withheld).not.toHaveProperty('summary'); + expect(JSON.stringify(withheld)).not.toContain(T.one); }); it('findOne: the by-id read is judged like the list', async () => { @@ -730,15 +699,12 @@ describe('referenceTitlesPerRead — a referenced title is served only to a read expect(await referenceTitlesPerRead(schemaOf, security(false), reader, answer([]))('parent', ['untitled'])).toBe(true); }); - it('a target whose API exposure does not serve get is refused for every reader; an exposed target is the control', async () => { - const judge = referenceTitlesPerRead(schemaOf, security(true), reader, answer(['title'])); - expect(await judge('parent', ['hidden'])).toBe(false); - expect(await judge('parent', ['listonly'])).toBe(false); - expect(await judge('parent', ['target'])).toBe(true); - expect(servesReferencedTitleTarget(schemas.hidden)).toBe(false); - expect(servesReferencedTitleTarget(schemas.listonly)).toBe(false); - expect(servesReferencedTitleTarget(schemas.target)).toBe(true); - expect(servesReferencedTitleTarget({ name: 'x', enable: { apiMethods: ['get'] } })).toBe(true); + it('a target whose API exposure serves no get is judged by the reader like any other: its exposure was decided where the title was read', async () => { + for (const field of ['hidden', 'listonly']) { + expect(await referenceTitlesPerRead(schemaOf, security(true), reader, answer(['title']))('parent', [field])).toBe(true); + expect(await referenceTitlesPerRead(schemaOf, security(true), reader, answer([]))('parent', [field])).toBe(false); + } + expect(await referenceTitlesPerRead(schemaOf, security(false), reader, answer(['title']))('parent', ['listonly'])).toBe(false); }); it('no admission member: the field-level answer alone decides; no answer for the target narrows nothing', async () => { diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.ts index 752734bc741..7441f1d1c3a 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.ts @@ -81,17 +81,21 @@ * - and the security service admits the reader to the target object * (`canReadObject`), unless the reference field declares * `referenceNameVisible`: that key lifts the object-level refusal and never - * the field-level rule, as on `$expand`; - * - and the target's declared API exposure serves `get` - * ({@link servesReferencedTitleTarget}, ADR-0049), for every reader: - * `$expand` withholds a target that exposure refuses whatever the field - * declares. + * the field-level rule, as on `$expand`. * * Otherwise the text is dropped whole, like any text this reader is not served, * and the row's `record_id` is the bare id it is named by. A text whose * provenance is unknown keeps the rule of rows without a declaration, below. No * row is read: the answers are asked once per target object per read. * + * The target's declared API exposure (ADR-0049) is decided where the title is + * READ: the mirror reads a title only from a target whose exposure serves + * `get` (`servesSummaryTitleTarget`, `audit-writers.ts`) and names every other + * referenced record by its stored id, per id, so one text can title one + * reference and name another by its id. A row is a snapshot of that write, and + * this redaction judges its reader against every reference a text names by + * the two answers above, whatever the target's exposure. + * * ## Rows without a declaration * * - A row in the mirror's EARLIER shape — `metadata` exactly `{ old, new }`, @@ -184,7 +188,7 @@ */ import type { ISecurityService, SecurityContext } from '@objectstack/spec/contracts'; -import { canServeApiOperation, referenceTargetOf, resolveDisplayField, type EnableLike } from '@objectstack/spec/data'; +import { referenceTargetOf, resolveDisplayField } from '@objectstack/spec/data'; import { ACTIVITY_CHANGED_FIELDS_COLUMN, ACTIVITY_KIND_KEY, @@ -376,21 +380,6 @@ async function sourcesServed( return sources === 'unknown' ? !(await restricted()) : sources.every((f) => served.has(f)); } -/** - * [ADR-0049] May a text this redaction serves carry a title read from the - * object `targetSchema` declares? Asked of the spec's one exposure decision for - * `get`: the operation the data door's `$expand` asks of a target before it - * serves anything of it, and the one the mirror asks before it reads a title - * at write time (`servesSummaryTitleTarget`, `audit-writers.ts`). It takes no - * reader: a target whose declaration does not serve `get` serves its title to - * nobody, a reference declaring `referenceNameVisible` included. A declaration - * that is not an object declares no `enable` block, which refuses nothing. - */ -export function servesReferencedTitleTarget(targetSchema: unknown): boolean { - const enable = isRecord(targetSchema) ? (targetSchema.enable as EnableLike | null | undefined) : undefined; - return canServeApiOperation(enable, 'get'); -} - /** * One read's answer to "may this reader read every referenced title a text * composed from the declared `sources` of `parent` names?" — `true` when no @@ -407,12 +396,11 @@ export type ReferenceTitlesServedFor = (parent: string, sources: readonly string * * - the target declares no title field, or names the primary key: the mirror * names such a record by its id, which is no title; - * - otherwise the target's declared exposure serves `get` - * ({@link servesReferencedTitleTarget}), AND the reader is served the - * target's title field (`resolveDisplayField`) by `servedFor` — a target - * the service gives no answer for is not narrowed, as for the parent — AND - * the security service admits the reader to the target object - * (`canReadObject`, `=== true`; a throw refuses). A reference field declaring `referenceNameVisible` lifts + * - otherwise the reader is served the target's title field + * (`resolveDisplayField`) by `servedFor` — a target the service gives no + * answer for is not narrowed, as for the parent — AND the security service + * admits the reader to the target object (`canReadObject`, `=== true`; a + * throw refuses). A reference field declaring `referenceNameVisible` lifts * only that admission, as it does on `$expand`. A service that answers no * `canReadObject` leaves the title to the field-level answer, as the * parent-record gate leaves its own objects to the caller-scoped read. @@ -481,7 +469,6 @@ export function referenceTitlesPerRead( if (!targetSchema) return false; const titleField = resolveDisplayField(targetSchema as Parameters[0]); if (!titleField || titleField === 'id') return true; - if (!servesReferencedTitleTarget(targetSchema)) return false; const served = await servedFor(target); if (served !== undefined && !served.some((f) => String(f) === titleField)) return false; if (isRecord(def) && def.referenceNameVisible === true) return true;