From 526a97c7a03590d9c115a77f5c8df1f0081cbef6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 21:33:48 +0000 Subject: [PATCH 1/2] fix(plugin-audit): an activity summary names a referenced record by a title the writer may read, else by its id Both summary branches that name a referenced record (the tracked-change diff and a fired milestone's tokens) read the title in the writer's scope, the scope the record label already reads in. An id whose record or title column the writer may not read keeps its stored id. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmRiaNzHVY81pCjZrpv --- ...ctivity-summary-title-writer-scope.test.ts | 356 ++++++++++++++++++ .../plugins/plugin-audit/src/audit-writers.ts | 43 ++- 2 files changed, 382 insertions(+), 17 deletions(-) create mode 100644 packages/plugins/plugin-audit/src/activity-summary-title-writer-scope.test.ts diff --git a/packages/plugins/plugin-audit/src/activity-summary-title-writer-scope.test.ts b/packages/plugins/plugin-audit/src/activity-summary-title-writer-scope.test.ts new file mode 100644 index 00000000000..683f6634596 --- /dev/null +++ b/packages/plugins/plugin-audit/src/activity-summary-title-writer-scope.test.ts @@ -0,0 +1,356 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An activity summary names a referenced record by a title the writer may + * read, else by its id. + * + * Two summary branches name a referenced record: the tracked-change diff + * (`Vault: A → B`) and a fired milestone's `{token}` (`Escalated to {vault}`). + * Both take the title from one resolver, `resolveLookupTitles` in + * `audit-writers.ts`, which reads in the WRITER's scope (the hook's own + * `api`), the scope the record's own label is read in. The rule holds per id: + * one read answers every id of a target, and an id the writer may read is + * titled while an id beside it the writer may not read keeps its id. + * + * What is pinned, for each branch: + * - a writer the security layer refuses the target ROW (its row scope) names + * the record by its id; + * - a writer refused the target OBJECT names the record by its id, and the + * write and its activity row still land; + * - a writer served the target row without its title column names the record + * by its id; + * - a writer who may read the target names it by its title, and so does a + * system write (no regression); + * - the stored summary CODE (the message the read side composes per reader) + * carries the same value as the stored sentence. + * + * A bare engine, the real `installAuditWriters`, and a copy-returning store. + * The three refusals are engine middleware on the target object, the layer + * the security service enforces on: a row filtered out of the result, a + * refused read, and a result served without the column. + * + * ⚠️ No test title states a value. + */ + +import { describe, it, expect } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { installAuditWriters } from './audit-writers.js'; +import { singlePostureDefaultOrganization } from './__tests__/single-posture-tenancy.js'; + +const f = (name: string, type: string, extra: Record = {}) => + ({ name, label: name, type, ...extra }) as any; + +const sysAuditLog = { + name: 'sys_audit_log', label: 'Audit Log', + fields: { + id: f('id', 'text', { primaryKey: true }), action: f('action', 'text'), + user_id: f('user_id', 'text'), object_name: f('object_name', 'text'), + record_id: f('record_id', 'text'), old_value: f('old_value', 'textarea'), + new_value: f('new_value', 'textarea'), tenant_id: f('tenant_id', 'text'), + actor: f('actor', 'text'), metadata: f('metadata', 'textarea'), + }, +}; + +const sysActivity = { + name: 'sys_activity', label: 'Activity', + fields: { + id: f('id', 'text', { primaryKey: true }), type: f('type', 'text'), + timestamp: f('timestamp', 'datetime'), summary: f('summary', 'text'), + actor_id: f('actor_id', 'text'), object_name: f('object_name', 'text'), + record_id: f('record_id', 'text'), record_label: f('record_label', 'text'), + metadata: f('metadata', 'textarea'), + }, +}; + +/** The referenced object, titled by `name`. */ +const vault = { + name: 'wst_vault', label: 'Vault', nameField: 'name', + fields: { id: f('id', 'text', { primaryKey: true }), name: f('name', 'text') }, +}; + +/** + * The audited object: one tracked lookup, and a milestone whose sentence names + * that lookup. `stage` is untracked, so a stage-only update fires the + * milestone and nothing else. + */ +const caseObject = { + name: 'wst_case', label: 'Case', nameField: 'subject', + fields: { + id: f('id', 'text', { primaryKey: true }), + subject: f('subject', 'text'), + stage: f('stage', 'text', { label: 'Stage' }), + vault: f('vault', 'lookup', { label: 'Vault', reference: 'wst_vault', trackHistory: true }), + }, + activityMilestones: [{ field: 'stage', value: 'escalated', summary: 'Escalated to {vault}' }], +}; + +function makeStore() { + const stores = new Map>>(); + const storeFor = (o: string) => { + let s = stores.get(o); + if (!s) { s = new Map(); stores.set(o, s); } + return s; + }; + let nextId = 0; + const copy = (r: T): T => (r == null ? r : JSON.parse(JSON.stringify(r))); + const matches = (row: Record, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + for (const [k, v] of Object.entries(where)) { + if (k === '$and' && Array.isArray(v)) { + if (!v.every((sub) => matches(row, sub))) return false; + continue; + } + if (k.startsWith('$')) continue; + if (v && typeof v === 'object' && '$in' in v) { + if (!(v.$in as unknown[]).includes(row[k])) return false; + continue; + } + const expected = (v && typeof v === 'object' && '$eq' in v) ? v.$eq : v; + if ((row[k] ?? null) !== (expected ?? null)) return false; + } + return true; + }; + const select = (object: string, where: any, limit?: number) => { + const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, where)); + const page = typeof limit === 'number' ? rows.slice(0, limit) : rows; + return page.map(copy); + }; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {} as any, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, + async execute() { return null; }, + async find(object: string, ast: any) { return select(object, ast?.where, ast?.limit); }, + async findOne(object: string, ast: any) { return select(object, ast?.where, 1)[0] ?? null; }, + async create(object: string, data: Record) { + nextId += 1; + const id = (data.id as string) ?? `r_${nextId}`; + const row = { ...data, id }; + storeFor(object).set(id, row); + return copy(row); + }, + async update(object: string, id: string, data: Record) { + const s = storeFor(object); + const cur = s.get(id); + if (!cur) return null; + const updated = { ...cur, ...data, id }; + s.set(id, updated); + return copy(updated); + }, + async upsert(object: string, data: Record) { + const id = data.id as string | undefined; + return id && storeFor(object).has(id) ? this.update(object, id, data) : this.create(object, data); + }, + async delete(object: string, id: string) { return storeFor(object).delete(id); }, + async count(object: string, ast: any) { return (await this.find(object, ast)).length; }, + async bulkCreate(object: string, rows: Record[]) { + return Promise.all(rows.map((r) => this.create(object, r))); + }, + async bulkUpdate() { return []; }, + async bulkDelete() {}, + async updateMany(object: string, ast: any, data: Record) { + const rows = await this.find(object, ast); + const s = storeFor(object); + for (const r of rows) s.set(r.id as string, { ...s.get(r.id as string), ...data, id: r.id }); + return rows.length; + }, + async deleteMany(object: string, ast: any) { + const rows = await this.find(object, ast); + for (const r of rows) storeFor(object).delete(r.id as string); + return rows.length; + }, + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, storeFor }; +} + +const OWNER_PACKAGE = 'com.objectstack.test.activity-summary-title-writer-scope'; +/** The record the restricted writers may not read (or whose title they may not read). */ +const SEALED = 'vlt_sealed_000000000000000000000'; +const SEALED_TITLE = 'Sealed Vault Title'; +/** A record every writer may read. */ +const OPEN = 'vlt_open_00000000000000000000000'; +const OPEN_TITLE = 'Open Vault Title'; + +const ALLOWED_WRITER = 'usr_allowed_writer'; +/** Its row scope leaves the sealed vault out of every result. */ +const ROW_REFUSED_WRITER = 'usr_row_refused_writer'; +/** Refused every read of the vault object. */ +const OBJECT_REFUSED_WRITER = 'usr_object_refused_writer'; +/** Served vault rows without their `name` column. */ +const NAMELESS_WRITER = 'usr_nameless_writer'; + +async function boot() { + const engine = new ObjectQL(); + const store = makeStore(); + engine.registerDriver(store.driver, true); + await engine.init(); + for (const o of [sysAuditLog, sysActivity, vault, caseObject]) { + engine.registry.registerObject(o as any, OWNER_PACKAGE); + } + installAuditWriters(engine as any, 'test.audit', { getDefaultOrganizationId: singlePostureDefaultOrganization }); + // The security layer's three answers on the referenced object, at the layer + // it enforces on. A system read is never restricted. + engine.registerMiddleware(async (op: any, next: () => Promise) => { + const userId = op.context && !op.context.isSystem ? op.context.userId : undefined; + if (op.operation === 'find' && userId === OBJECT_REFUSED_WRITER) { + throw Object.assign(new Error('PERMISSION_DENIED: no read on wst_vault'), { code: 'PERMISSION_DENIED', status: 403 }); + } + await next(); + if (op.operation !== 'find' || !Array.isArray(op.result)) return; + if (userId === ROW_REFUSED_WRITER) { + op.result = op.result.filter((row: Record) => row?.id !== SEALED); + } + if (userId === NAMELESS_WRITER) { + op.result = op.result.map(({ name: _hidden, ...rest }: Record) => rest); + } + }, { object: 'wst_vault' }); + const system = { context: { isSystem: true } } as any; + await engine.insert('wst_vault', { id: SEALED, name: SEALED_TITLE }, system); + await engine.insert('wst_vault', { id: OPEN, name: OPEN_TITLE }, system); + await engine.insert('wst_case', { id: 'case_1', subject: 'Case One', stage: 'new', vault: SEALED }, system); + return { engine, ...store }; +} + +const as = (userId: string) => ({ context: { userId } }); +const asSystem = { context: { isSystem: true } }; + +/** + * The activity row the write under test produced: the record's rows are its + * seeding create and then exactly one update. + */ +const lastUpdateRow = (storeFor: (o: string) => Map>): Record => { + const rows = Array.from(storeFor('sys_activity').values()).filter((r) => r.record_id === 'case_1'); + expect(rows.map((r) => r.type)).toEqual(['created', 'updated']); + return rows[1]; +}; + +/** The stored summary code, serialized: the message the read side composes each reader's summary from. */ +const storedCode = (row: Record): string => { + const code = JSON.parse(String(row.metadata)).summary_message; + expect(code, 'the row stores a summary code').toBeDefined(); + return JSON.stringify(code); +}; + +/** A tracked change of the lookup: sealed → cleared, by `ctx`. */ +const clearVault = (engine: ObjectQL, ctx: object) => + engine.update('wst_case', { vault: null }, { where: { id: 'case_1' }, ...ctx } as any); + +/** A stage-only update that fires the milestone naming the lookup, by `ctx`. */ +const escalate = (engine: ObjectQL, ctx: object) => + engine.update('wst_case', { stage: 'escalated' }, { where: { id: 'case_1' }, ...ctx } as any); + +describe('a tracked-change summary names a referenced record by a title the writer may read, else by its id', () => { + it('control: a writer who may read the referenced record names it by its title', async () => { + const { engine, storeFor } = await boot(); + + await clearVault(engine, as(ALLOWED_WRITER)); + + const row = lastUpdateRow(storeFor); + expect(String(row.summary)).toContain(SEALED_TITLE); + expect(String(row.summary)).not.toContain(SEALED); + }); + + it('control: a system write names the referenced record by its title', async () => { + const { engine, storeFor } = await boot(); + + await clearVault(engine, asSystem); + + expect(String(lastUpdateRow(storeFor).summary)).toContain(SEALED_TITLE); + }); + + it('a writer whose row scope excludes the referenced record names it by its id', async () => { + const { engine, storeFor } = await boot(); + + await clearVault(engine, as(ROW_REFUSED_WRITER)); + + const row = lastUpdateRow(storeFor); + expect(String(row.summary)).toContain(SEALED); + expect(String(row.summary)).not.toContain(SEALED_TITLE); + expect(storedCode(row)).not.toContain(SEALED_TITLE); + }); + + it('a writer refused the referenced object names the record by its id, and the write still lands', async () => { + const { engine, storeFor } = await boot(); + + await clearVault(engine, as(OBJECT_REFUSED_WRITER)); + + const row = lastUpdateRow(storeFor); + expect(String(row.summary)).toContain(SEALED); + expect(String(row.summary)).not.toContain(SEALED_TITLE); + expect(storedCode(row)).not.toContain(SEALED_TITLE); + expect(storeFor('wst_case').get('case_1')?.vault ?? null).toBeNull(); + }); + + it('a writer served the referenced record without its title column names it by its id', async () => { + const { engine, storeFor } = await boot(); + + await clearVault(engine, as(NAMELESS_WRITER)); + + const row = lastUpdateRow(storeFor); + expect(String(row.summary)).toContain(SEALED); + expect(String(row.summary)).not.toContain(SEALED_TITLE); + expect(storedCode(row)).not.toContain(SEALED_TITLE); + }); + + it('the rule holds per id: one change titles the side the writer may read and keeps the id of the side it may not', async () => { + const { engine, storeFor } = await boot(); + + await engine.update('wst_case', { vault: OPEN }, { where: { id: 'case_1' }, ...as(ROW_REFUSED_WRITER) } as any); + + const row = lastUpdateRow(storeFor); + expect(String(row.summary)).toContain(SEALED); + expect(String(row.summary)).not.toContain(SEALED_TITLE); + expect(String(row.summary)).toContain(OPEN_TITLE); + expect(String(row.summary)).not.toContain(OPEN); + }); +}); + +describe('a fired milestone summary names a referenced record by a title the writer may read, else by its id', () => { + it('control: a writer who may read the referenced record names it by its title', async () => { + const { engine, storeFor } = await boot(); + + await escalate(engine, as(ALLOWED_WRITER)); + + expect(lastUpdateRow(storeFor).summary).toBe(`Escalated to ${SEALED_TITLE}`); + }); + + it('control: a system write names the referenced record by its title', async () => { + const { engine, storeFor } = await boot(); + + await escalate(engine, asSystem); + + expect(lastUpdateRow(storeFor).summary).toBe(`Escalated to ${SEALED_TITLE}`); + }); + + it('a writer whose row scope excludes the referenced record names it by its id', async () => { + const { engine, storeFor } = await boot(); + + await escalate(engine, as(ROW_REFUSED_WRITER)); + + const row = lastUpdateRow(storeFor); + expect(row.summary).toBe(`Escalated to ${SEALED}`); + expect(String(row.metadata)).not.toContain(SEALED_TITLE); + }); + + it('a writer refused the referenced object names the record by its id, and the write still lands', async () => { + const { engine, storeFor } = await boot(); + + await escalate(engine, as(OBJECT_REFUSED_WRITER)); + + const row = lastUpdateRow(storeFor); + expect(row.summary).toBe(`Escalated to ${SEALED}`); + expect(String(row.metadata)).not.toContain(SEALED_TITLE); + expect(storeFor('wst_case').get('case_1')?.stage).toBe('escalated'); + }); + + it('a writer served the referenced record without its title column names it by its id', async () => { + const { engine, storeFor } = await boot(); + + await escalate(engine, as(NAMELESS_WRITER)); + + const row = lastUpdateRow(storeFor); + expect(row.summary).toBe(`Escalated to ${SEALED}`); + expect(String(row.metadata)).not.toContain(SEALED_TITLE); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-writers.ts b/packages/plugins/plugin-audit/src/audit-writers.ts index fff100f0902..b8e96db505a 100644 --- a/packages/plugins/plugin-audit/src/audit-writers.ts +++ b/packages/plugins/plugin-audit/src/audit-writers.ts @@ -718,8 +718,8 @@ type WarnSink = { warn?: (message: string) => void }; * (ADR-0049) for `get`, the read `GET /data/{target}/{id}` performs and the * operation the data door's `$expand` and the dataset door's labels ask of the * same target. It takes no caller: it judges the target's declaration, and - * the read that follows is scoped by whichever reader `resolveLookupTitles` is - * handed (the system for a summary's titles, the writer for a record label). + * the read that follows is in the WRITER's scope (see `resolveLookupTitles`), + * for a summary's titles and a record label alike. * * A refused target is not read, so the summary names its records by their * stored ids, the answer an unresolvable reference already gets. A declaration @@ -780,7 +780,8 @@ function referenceIdsOf(value: any): string[] { * (`renderMilestoneSummary`), each from its own read plan. * * An id with no entry in the map — record deleted, object unregistered, title - * field unresolvable — falls back to the raw id, which is what this function + * field unresolvable, or a record or title column the writer may not read — + * falls back to the raw id, which is what this function * returned before the branch existed. The change is therefore restore-invariant: * it can only replace an id with a title, never a title with an id. * @@ -1786,18 +1787,22 @@ export function installAuditWriters( * * ## Whose read it is * - * `reader` scopes the read and is the caller's choice. The two summary - * branches hand it `api.sudo()`, as they always have. The record's own label + * The WRITER's: an activity row names a referenced record by a title the + * writer may read, else by its id. Every caller — the record's own label * ({@link planLabelLookupRead}, an object whose `nameField` is a reference) - * hands it the hook's own `api`, the WRITER's scope: the label is the title - * the record header shows a reader who may read the target, and a writer the - * security layer refuses the target, or serves it without its title column, - * gets no title it could not have read itself — the refusal throws into the - * catch below, the stripped column reads as no title, and the label keeps - * the stored value. + * and both summary branches — hands `writerApi` the hook's own `api`, the + * scope the write itself ran in, ⛔ never an elevated one. A title is the + * text the record header shows a reader who may read the target, so a + * writer the security layer refuses the target (its object, or the row by + * its row scope), or serves it without its title column, writes no title it + * could not have read itself: a refusal throws into the catch below, a row + * left out of the result is an id with no title, and a stripped column reads + * as no title. Each of those ids keeps its stored value, per id, so one read + * can title the ids the writer may read and leave the rest as ids. A system + * write reads as the system, which is the scope it wrote in. */ const resolveLookupTitles = async ( - reader: any, + writerApi: any, plan: Map>, ): Promise> | undefined> => { if (plan.size === 0) return undefined; @@ -1808,7 +1813,7 @@ export function installAuditWriters( if (!titleField) continue; const ids = Array.from(idSet); try { - const rows: any[] = await reader.object(objectName).find({ + const rows: any[] = await writerApi.object(objectName).find({ where: { id: { $in: ids } }, fields: ['id', titleField], limit: ids.length, @@ -2426,9 +2431,11 @@ export function installAuditWriters( // // The plan reads the same MASKED after-view the interpolation renders // from, so a credential field can no more become a read key here than - // it can reach the summary text. + // it can reach the summary text. The titles are read as the WRITER + // (see `resolveLookupTitles`): a token names a title the writer may + // read, else the stored id. const lookupTitles = await resolveLookupTitles( - api.sudo(), + api, planMilestoneTokenReads(milestone.template, summaryFields, afterView), ); const rendered = renderMilestoneSummary(milestone.template, summaryFields, afterView, lookupTitles); @@ -2442,9 +2449,11 @@ export function installAuditWriters( } else { // [#7230] The read plan is built from the SAME masked views the summary // renders, and only reached once a milestone has declined — a write - // that changes no tracked reference field issues no read at all. + // that changes no tracked reference field issues no read at all. The + // titles are read as the WRITER (see `resolveLookupTitles`): each side + // of a change names a title the writer may read, else the stored id. const lookupTitles = await resolveLookupTitles( - api.sudo(), + api, planTrackedLookupReads(summaryFields, oldValue, newValue), ); const tracked = renderTrackedChangeSummary( From 94b1d0983aaa2424fee3e8d5a44fb2ce3d237ac8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 21:43:19 +0000 Subject: [PATCH 2/2] chore(changeset): an activity summary names a referenced record by a title the writer may read Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmRiaNzHVY81pCjZrpv --- .changeset/activity-summary-titles-writer-scope.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .changeset/activity-summary-titles-writer-scope.md diff --git a/.changeset/activity-summary-titles-writer-scope.md b/.changeset/activity-summary-titles-writer-scope.md new file mode 100644 index 00000000000..6d5ffca62d4 --- /dev/null +++ b/.changeset/activity-summary-titles-writer-scope.md @@ -0,0 +1,12 @@ +--- +'@objectstack/plugin-audit': patch +--- + +fix(plugin-audit): an activity summary names a referenced record by a title the writer may read, else by its id + +Clause-②: no +Metadata-protocol: none + +An activity row's summary can name a record another field points at: a tracked lookup change (`Account: Acme → Globex`) or a fired milestone's `{token}` (`Deal won by {owner}`). That title is now read in the writer's scope, the scope the row's own record label is already read in. When the writer may not read the referenced record, or may read it without its title column, the summary names it by its stored id, as it does for a record that no longer exists. The rule holds per id, so one change can title the side the writer may read and keep the id of the side it may not. + +A writer who may read the referenced record, and every system write, gets the same summary as before. Rows already written keep the summary they were written with.