diff --git a/.changeset/activity-reference-title-reader-scope.md b/.changeset/activity-reference-title-reader-scope.md new file mode 100644 index 00000000000..b35893837c6 --- /dev/null +++ b/.changeset/activity-reference-title-reader-scope.md @@ -0,0 +1,19 @@ +--- +'@objectstack/plugin-audit': patch +--- + +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 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; 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 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 541496d66f5..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 @@ -195,6 +195,18 @@ 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: 'executes', + read: + "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': { kind: 'decided', 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..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 { 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,334 @@ 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'; +/** Referenced by the exposure case; titled by `title`; its declaration serves no API operation. */ +const REF_UNEXPOSED = 'afr_ref_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. */ +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', unexposed: 'AFRREFUNEXPOSED74' }; + +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 }), + }, + }, + { + name: REF_UNEXPOSED, label: 'Reference Unexposed', nameField: 'title', enable: { apiEnabled: false }, + fields: { title: { name: 'title', label: 'Title', type: 'text' as const } }, + }, + { + name: REF_TRACKED_MIXED, label: 'Reference Tracked Mixed', nameField: 'name', + fields: { + name: { name: 'name', label: 'Name', type: 'text' as const }, + 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 }, + }, + }, +]; + + +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 = {}; + + 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 }); + + // [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 () => { + 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('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 () => { + 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 served its title field and admitted to its object', () => { + 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' }, + 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' }; + const answer = (served: string[] | undefined) => async () => served; + const security = (admits: boolean | Error | undefined) => ({ + getReadableFields: async (): Promise => [], + getQueryableFields: async (): Promise => [], + ...(admits === undefined + ? {} + : { + 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 () => { + 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('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 () => { + 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('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 0b9146cf5b2..7441f1d1c3a 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.ts @@ -63,6 +63,39 @@ * 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 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 + * `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 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 }`, @@ -154,6 +187,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 +265,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 +380,111 @@ 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 the declared `sources` of `parent` names?" — `true` when no + * source is a reference field. + */ +export type ReferenceTitlesServedFor = (parent: string, sources: readonly string[]) => 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) => { + for (const field of sources) 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 +674,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 +753,10 @@ 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 sources = provenance[col]; + const served = (await servedWhole(sources)) + && (!referenceTitles || sources === 'unknown' || (await referenceTitles(object, sources))); + if (!served) delete row[col]; } } } @@ -657,7 +809,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( 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..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 @@ -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 served that title field', () => { + 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, + ); +});