Skip to content

Commit 047f37b

Browse files
fix(plugin-audit): an activity summary names a referenced record by a title the writer may read, else by its id (#34493)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9CEjuTu4HVEtNH1742UngyH)_ Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:活动动态摘要里提到被引用的记录时(跟踪的查找字段变更、里程碑句子里的 `{token}`),记录名称按写入者自己的读取范围取得;写入者读不到该记录或其名称字段时,摘要写记录 id。 - 为什么改:加固规则——活动摘要只用写入者本人可读的名称来指称被引用记录,否则用 id;与同一活动行的记录标签用同一读取范围。 - 风险与回滚:只影响此后写入的活动行,已写入的行不变;有权读取的写入者和系统写入的摘要与之前相同;读取次数不变。回滚即 revert 本 PR,无数据迁移。 - 先看:`packages/plugins/plugin-audit/src/audit-writers.ts`(两个摘要分支调用 `resolveLookupTitles` 的两处,以及该函数 "Whose read it is" 一节);`packages/plugins/plugin-audit/src/activity-summary-title-writer-scope.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/plugin-audit exec vitest run src/activity-summary-title-writer-scope.test.ts`,预期 1 个文件、11 个用例全部通过。 - 需要你做的:无,席位落地。 ## What changes Hardening rule: **an activity summary names a referenced record by a title the writer may read, else by its id.** `sys_activity.summary` names a referenced record in two branches: the tracked-change diff (`Vault: A → B`) and a fired milestone's `{token}` (`Escalated to {vault}`). Both take the title from `resolveLookupTitles` in `audit-writers.ts`. Both now hand it the hook's own `api`, the writer's scope. The row's record label already reads there, so every title an activity row writes follows one rule. - A record the writer may not read keeps its stored id: the object refuses the writer, or the writer's row scope leaves the record out. - A record the writer may read without its title column keeps its stored id. - The rule holds per id. 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 target, and every system write, gets the same summary as before. - No read is added. It is still one `id: { $in }` read per distinct target object, and only when a tracked reference moved or a fired milestone names one. The resolver's docblock now states the rule for every caller. Rows already written keep the summary they were written with. ## Tests New file `src/activity-summary-title-writer-scope.test.ts` (11 cases) runs a bare engine with the real `installAuditWriters`. The restrictions are engine middleware on the target object: a refused read, a row left out by row scope, and a row served without its title column. For each branch it pins the three restricted writers, a writer who may read and a system write. The tracked branch also pins the per-id case. The cases assert the stored sentence and the stored summary code that the read side composes from. <details><summary>Red first: the new file against the base source</summary> At `origin/main` `bf76922925`, before the fix: ``` Test Files 1 failed (1) Tests 7 failed | 4 passed (11) ``` The 4 that pass are the controls (a writer who may read, and a system write, in each branch). </details> <details><summary>Ablations via scripts/ablation-replace.mjs, each restored to the HEAD blob with an empty git diff HEAD</summary> | Mutation | Red | |---|---| | M1: the tracked-change branch's call takes its base-source argument again | 4 (the three restricted writers and the per-id case) | | M2: the milestone branch's call takes its base-source argument again | 3 (the three restricted writers) | Each logged `ok mutation landed: anchor 1 -> 0` and `ok restored: blob == HEAD (b8e96db) and git diff HEAD is empty`. </details> <details><summary>Package suite and typecheck at 7c093c0 (after merging origin/main)</summary> Closure rebuilt after the merge (`turbo run build --filter=@objectstack/plugin-audit...`, 16/16 tasks), `@objectstack/spec check:generated` reports all 14 generated artifacts up to date. Under `scripts/pm/os-verify-lock.sh`: ``` pnpm --filter @objectstack/plugin-audit test && pnpm --filter @objectstack/plugin-audit typecheck Test Files 100 passed (100) Tests 1665 passed (1665) check:test-typecheck: OK — @objectstack/plugin-audit's test layer compiles os-verify-lock: VERDICT command-exit 0 ``` </details> ## Acceptance notes - **Scope.** Only the two summary branches change. The record label already read its title in the writer's scope. - **`referenceNameVisible`.** A lookup that declares it follows the same rule in the summary as in the record label. Whether that key should widen what activity rows name is a question raised with the owning seat. This PR does not decide it. - **Already-written rows** keep the summary they were written with. Snapshots are not rewritten. - **Test placement.** The summary branches have no shared harness file (each audit suite carries its own), so the pins are a new file named for the rule. ## Verification Local gate subset: the `scripts/pm/dispatch-gates.mjs --commands` list derived at `7c093c01` (72 commands). 70 answered exit 0, one of them after its pinned fixture commit was fetched into this shallow clone. `check:dual-build-cjs-loads` refused locally (PREREQUISITE NOT MET: it reads every package's build output), and so did `check:i18n` (it needs the CLI build closure). Both are NOT MEASURED here. CI runs both in `Lint & Repo Gates`, and CI runs the full farm. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmRiaNzHVY81pCjZrpv)_ <!-- signed: security#1 · os-steve · session_01ADHkmRiaNzHVY81pCjZrpv --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1efe7a2 commit 047f37b

3 files changed

Lines changed: 394 additions & 17 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/plugin-audit': patch
3+
---
4+
5+
fix(plugin-audit): an activity summary names a referenced record by a title the writer may read, else by its id
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
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.
Lines changed: 356 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* An activity summary names a referenced record by a title the writer may
5+
* read, else by its id.
6+
*
7+
* Two summary branches name a referenced record: the tracked-change diff
8+
* (`Vault: A → B`) and a fired milestone's `{token}` (`Escalated to {vault}`).
9+
* Both take the title from one resolver, `resolveLookupTitles` in
10+
* `audit-writers.ts`, which reads in the WRITER's scope (the hook's own
11+
* `api`), the scope the record's own label is read in. The rule holds per id:
12+
* one read answers every id of a target, and an id the writer may read is
13+
* titled while an id beside it the writer may not read keeps its id.
14+
*
15+
* What is pinned, for each branch:
16+
* - a writer the security layer refuses the target ROW (its row scope) names
17+
* the record by its id;
18+
* - a writer refused the target OBJECT names the record by its id, and the
19+
* write and its activity row still land;
20+
* - a writer served the target row without its title column names the record
21+
* by its id;
22+
* - a writer who may read the target names it by its title, and so does a
23+
* system write (no regression);
24+
* - the stored summary CODE (the message the read side composes per reader)
25+
* carries the same value as the stored sentence.
26+
*
27+
* A bare engine, the real `installAuditWriters`, and a copy-returning store.
28+
* The three refusals are engine middleware on the target object, the layer
29+
* the security service enforces on: a row filtered out of the result, a
30+
* refused read, and a result served without the column.
31+
*
32+
* ⚠️ No test title states a value.
33+
*/
34+
35+
import { describe, it, expect } from 'vitest';
36+
import { ObjectQL } from '@objectstack/objectql';
37+
import { installAuditWriters } from './audit-writers.js';
38+
import { singlePostureDefaultOrganization } from './__tests__/single-posture-tenancy.js';
39+
40+
const f = (name: string, type: string, extra: Record<string, unknown> = {}) =>
41+
({ name, label: name, type, ...extra }) as any;
42+
43+
const sysAuditLog = {
44+
name: 'sys_audit_log', label: 'Audit Log',
45+
fields: {
46+
id: f('id', 'text', { primaryKey: true }), action: f('action', 'text'),
47+
user_id: f('user_id', 'text'), object_name: f('object_name', 'text'),
48+
record_id: f('record_id', 'text'), old_value: f('old_value', 'textarea'),
49+
new_value: f('new_value', 'textarea'), tenant_id: f('tenant_id', 'text'),
50+
actor: f('actor', 'text'), metadata: f('metadata', 'textarea'),
51+
},
52+
};
53+
54+
const sysActivity = {
55+
name: 'sys_activity', label: 'Activity',
56+
fields: {
57+
id: f('id', 'text', { primaryKey: true }), type: f('type', 'text'),
58+
timestamp: f('timestamp', 'datetime'), summary: f('summary', 'text'),
59+
actor_id: f('actor_id', 'text'), object_name: f('object_name', 'text'),
60+
record_id: f('record_id', 'text'), record_label: f('record_label', 'text'),
61+
metadata: f('metadata', 'textarea'),
62+
},
63+
};
64+
65+
/** The referenced object, titled by `name`. */
66+
const vault = {
67+
name: 'wst_vault', label: 'Vault', nameField: 'name',
68+
fields: { id: f('id', 'text', { primaryKey: true }), name: f('name', 'text') },
69+
};
70+
71+
/**
72+
* The audited object: one tracked lookup, and a milestone whose sentence names
73+
* that lookup. `stage` is untracked, so a stage-only update fires the
74+
* milestone and nothing else.
75+
*/
76+
const caseObject = {
77+
name: 'wst_case', label: 'Case', nameField: 'subject',
78+
fields: {
79+
id: f('id', 'text', { primaryKey: true }),
80+
subject: f('subject', 'text'),
81+
stage: f('stage', 'text', { label: 'Stage' }),
82+
vault: f('vault', 'lookup', { label: 'Vault', reference: 'wst_vault', trackHistory: true }),
83+
},
84+
activityMilestones: [{ field: 'stage', value: 'escalated', summary: 'Escalated to {vault}' }],
85+
};
86+
87+
function makeStore() {
88+
const stores = new Map<string, Map<string, Record<string, unknown>>>();
89+
const storeFor = (o: string) => {
90+
let s = stores.get(o);
91+
if (!s) { s = new Map(); stores.set(o, s); }
92+
return s;
93+
};
94+
let nextId = 0;
95+
const copy = <T,>(r: T): T => (r == null ? r : JSON.parse(JSON.stringify(r)));
96+
const matches = (row: Record<string, unknown>, where: any): boolean => {
97+
if (!where || typeof where !== 'object') return true;
98+
for (const [k, v] of Object.entries<any>(where)) {
99+
if (k === '$and' && Array.isArray(v)) {
100+
if (!v.every((sub) => matches(row, sub))) return false;
101+
continue;
102+
}
103+
if (k.startsWith('$')) continue;
104+
if (v && typeof v === 'object' && '$in' in v) {
105+
if (!(v.$in as unknown[]).includes(row[k])) return false;
106+
continue;
107+
}
108+
const expected = (v && typeof v === 'object' && '$eq' in v) ? v.$eq : v;
109+
if ((row[k] ?? null) !== (expected ?? null)) return false;
110+
}
111+
return true;
112+
};
113+
const select = (object: string, where: any, limit?: number) => {
114+
const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, where));
115+
const page = typeof limit === 'number' ? rows.slice(0, limit) : rows;
116+
return page.map(copy);
117+
};
118+
const driver: any = {
119+
name: 'memory', version: '0.0.0', supports: {} as any,
120+
async connect() {}, async disconnect() {}, async checkHealth() { return true; },
121+
async execute() { return null; },
122+
async find(object: string, ast: any) { return select(object, ast?.where, ast?.limit); },
123+
async findOne(object: string, ast: any) { return select(object, ast?.where, 1)[0] ?? null; },
124+
async create(object: string, data: Record<string, unknown>) {
125+
nextId += 1;
126+
const id = (data.id as string) ?? `r_${nextId}`;
127+
const row = { ...data, id };
128+
storeFor(object).set(id, row);
129+
return copy(row);
130+
},
131+
async update(object: string, id: string, data: Record<string, unknown>) {
132+
const s = storeFor(object);
133+
const cur = s.get(id);
134+
if (!cur) return null;
135+
const updated = { ...cur, ...data, id };
136+
s.set(id, updated);
137+
return copy(updated);
138+
},
139+
async upsert(object: string, data: Record<string, unknown>) {
140+
const id = data.id as string | undefined;
141+
return id && storeFor(object).has(id) ? this.update(object, id, data) : this.create(object, data);
142+
},
143+
async delete(object: string, id: string) { return storeFor(object).delete(id); },
144+
async count(object: string, ast: any) { return (await this.find(object, ast)).length; },
145+
async bulkCreate(object: string, rows: Record<string, unknown>[]) {
146+
return Promise.all(rows.map((r) => this.create(object, r)));
147+
},
148+
async bulkUpdate() { return []; },
149+
async bulkDelete() {},
150+
async updateMany(object: string, ast: any, data: Record<string, unknown>) {
151+
const rows = await this.find(object, ast);
152+
const s = storeFor(object);
153+
for (const r of rows) s.set(r.id as string, { ...s.get(r.id as string), ...data, id: r.id });
154+
return rows.length;
155+
},
156+
async deleteMany(object: string, ast: any) {
157+
const rows = await this.find(object, ast);
158+
for (const r of rows) storeFor(object).delete(r.id as string);
159+
return rows.length;
160+
},
161+
async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; },
162+
async commit() {}, async rollback() {},
163+
};
164+
return { driver, storeFor };
165+
}
166+
167+
const OWNER_PACKAGE = 'com.objectstack.test.activity-summary-title-writer-scope';
168+
/** The record the restricted writers may not read (or whose title they may not read). */
169+
const SEALED = 'vlt_sealed_000000000000000000000';
170+
const SEALED_TITLE = 'Sealed Vault Title';
171+
/** A record every writer may read. */
172+
const OPEN = 'vlt_open_00000000000000000000000';
173+
const OPEN_TITLE = 'Open Vault Title';
174+
175+
const ALLOWED_WRITER = 'usr_allowed_writer';
176+
/** Its row scope leaves the sealed vault out of every result. */
177+
const ROW_REFUSED_WRITER = 'usr_row_refused_writer';
178+
/** Refused every read of the vault object. */
179+
const OBJECT_REFUSED_WRITER = 'usr_object_refused_writer';
180+
/** Served vault rows without their `name` column. */
181+
const NAMELESS_WRITER = 'usr_nameless_writer';
182+
183+
async function boot() {
184+
const engine = new ObjectQL();
185+
const store = makeStore();
186+
engine.registerDriver(store.driver, true);
187+
await engine.init();
188+
for (const o of [sysAuditLog, sysActivity, vault, caseObject]) {
189+
engine.registry.registerObject(o as any, OWNER_PACKAGE);
190+
}
191+
installAuditWriters(engine as any, 'test.audit', { getDefaultOrganizationId: singlePostureDefaultOrganization });
192+
// The security layer's three answers on the referenced object, at the layer
193+
// it enforces on. A system read is never restricted.
194+
engine.registerMiddleware(async (op: any, next: () => Promise<void>) => {
195+
const userId = op.context && !op.context.isSystem ? op.context.userId : undefined;
196+
if (op.operation === 'find' && userId === OBJECT_REFUSED_WRITER) {
197+
throw Object.assign(new Error('PERMISSION_DENIED: no read on wst_vault'), { code: 'PERMISSION_DENIED', status: 403 });
198+
}
199+
await next();
200+
if (op.operation !== 'find' || !Array.isArray(op.result)) return;
201+
if (userId === ROW_REFUSED_WRITER) {
202+
op.result = op.result.filter((row: Record<string, unknown>) => row?.id !== SEALED);
203+
}
204+
if (userId === NAMELESS_WRITER) {
205+
op.result = op.result.map(({ name: _hidden, ...rest }: Record<string, unknown>) => rest);
206+
}
207+
}, { object: 'wst_vault' });
208+
const system = { context: { isSystem: true } } as any;
209+
await engine.insert('wst_vault', { id: SEALED, name: SEALED_TITLE }, system);
210+
await engine.insert('wst_vault', { id: OPEN, name: OPEN_TITLE }, system);
211+
await engine.insert('wst_case', { id: 'case_1', subject: 'Case One', stage: 'new', vault: SEALED }, system);
212+
return { engine, ...store };
213+
}
214+
215+
const as = (userId: string) => ({ context: { userId } });
216+
const asSystem = { context: { isSystem: true } };
217+
218+
/**
219+
* The activity row the write under test produced: the record's rows are its
220+
* seeding create and then exactly one update.
221+
*/
222+
const lastUpdateRow = (storeFor: (o: string) => Map<string, Record<string, unknown>>): Record<string, unknown> => {
223+
const rows = Array.from(storeFor('sys_activity').values()).filter((r) => r.record_id === 'case_1');
224+
expect(rows.map((r) => r.type)).toEqual(['created', 'updated']);
225+
return rows[1];
226+
};
227+
228+
/** The stored summary code, serialized: the message the read side composes each reader's summary from. */
229+
const storedCode = (row: Record<string, unknown>): string => {
230+
const code = JSON.parse(String(row.metadata)).summary_message;
231+
expect(code, 'the row stores a summary code').toBeDefined();
232+
return JSON.stringify(code);
233+
};
234+
235+
/** A tracked change of the lookup: sealed → cleared, by `ctx`. */
236+
const clearVault = (engine: ObjectQL, ctx: object) =>
237+
engine.update('wst_case', { vault: null }, { where: { id: 'case_1' }, ...ctx } as any);
238+
239+
/** A stage-only update that fires the milestone naming the lookup, by `ctx`. */
240+
const escalate = (engine: ObjectQL, ctx: object) =>
241+
engine.update('wst_case', { stage: 'escalated' }, { where: { id: 'case_1' }, ...ctx } as any);
242+
243+
describe('a tracked-change summary names a referenced record by a title the writer may read, else by its id', () => {
244+
it('control: a writer who may read the referenced record names it by its title', async () => {
245+
const { engine, storeFor } = await boot();
246+
247+
await clearVault(engine, as(ALLOWED_WRITER));
248+
249+
const row = lastUpdateRow(storeFor);
250+
expect(String(row.summary)).toContain(SEALED_TITLE);
251+
expect(String(row.summary)).not.toContain(SEALED);
252+
});
253+
254+
it('control: a system write names the referenced record by its title', async () => {
255+
const { engine, storeFor } = await boot();
256+
257+
await clearVault(engine, asSystem);
258+
259+
expect(String(lastUpdateRow(storeFor).summary)).toContain(SEALED_TITLE);
260+
});
261+
262+
it('a writer whose row scope excludes the referenced record names it by its id', async () => {
263+
const { engine, storeFor } = await boot();
264+
265+
await clearVault(engine, as(ROW_REFUSED_WRITER));
266+
267+
const row = lastUpdateRow(storeFor);
268+
expect(String(row.summary)).toContain(SEALED);
269+
expect(String(row.summary)).not.toContain(SEALED_TITLE);
270+
expect(storedCode(row)).not.toContain(SEALED_TITLE);
271+
});
272+
273+
it('a writer refused the referenced object names the record by its id, and the write still lands', async () => {
274+
const { engine, storeFor } = await boot();
275+
276+
await clearVault(engine, as(OBJECT_REFUSED_WRITER));
277+
278+
const row = lastUpdateRow(storeFor);
279+
expect(String(row.summary)).toContain(SEALED);
280+
expect(String(row.summary)).not.toContain(SEALED_TITLE);
281+
expect(storedCode(row)).not.toContain(SEALED_TITLE);
282+
expect(storeFor('wst_case').get('case_1')?.vault ?? null).toBeNull();
283+
});
284+
285+
it('a writer served the referenced record without its title column names it by its id', async () => {
286+
const { engine, storeFor } = await boot();
287+
288+
await clearVault(engine, as(NAMELESS_WRITER));
289+
290+
const row = lastUpdateRow(storeFor);
291+
expect(String(row.summary)).toContain(SEALED);
292+
expect(String(row.summary)).not.toContain(SEALED_TITLE);
293+
expect(storedCode(row)).not.toContain(SEALED_TITLE);
294+
});
295+
296+
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 () => {
297+
const { engine, storeFor } = await boot();
298+
299+
await engine.update('wst_case', { vault: OPEN }, { where: { id: 'case_1' }, ...as(ROW_REFUSED_WRITER) } as any);
300+
301+
const row = lastUpdateRow(storeFor);
302+
expect(String(row.summary)).toContain(SEALED);
303+
expect(String(row.summary)).not.toContain(SEALED_TITLE);
304+
expect(String(row.summary)).toContain(OPEN_TITLE);
305+
expect(String(row.summary)).not.toContain(OPEN);
306+
});
307+
});
308+
309+
describe('a fired milestone summary names a referenced record by a title the writer may read, else by its id', () => {
310+
it('control: a writer who may read the referenced record names it by its title', async () => {
311+
const { engine, storeFor } = await boot();
312+
313+
await escalate(engine, as(ALLOWED_WRITER));
314+
315+
expect(lastUpdateRow(storeFor).summary).toBe(`Escalated to ${SEALED_TITLE}`);
316+
});
317+
318+
it('control: a system write names the referenced record by its title', async () => {
319+
const { engine, storeFor } = await boot();
320+
321+
await escalate(engine, asSystem);
322+
323+
expect(lastUpdateRow(storeFor).summary).toBe(`Escalated to ${SEALED_TITLE}`);
324+
});
325+
326+
it('a writer whose row scope excludes the referenced record names it by its id', async () => {
327+
const { engine, storeFor } = await boot();
328+
329+
await escalate(engine, as(ROW_REFUSED_WRITER));
330+
331+
const row = lastUpdateRow(storeFor);
332+
expect(row.summary).toBe(`Escalated to ${SEALED}`);
333+
expect(String(row.metadata)).not.toContain(SEALED_TITLE);
334+
});
335+
336+
it('a writer refused the referenced object names the record by its id, and the write still lands', async () => {
337+
const { engine, storeFor } = await boot();
338+
339+
await escalate(engine, as(OBJECT_REFUSED_WRITER));
340+
341+
const row = lastUpdateRow(storeFor);
342+
expect(row.summary).toBe(`Escalated to ${SEALED}`);
343+
expect(String(row.metadata)).not.toContain(SEALED_TITLE);
344+
expect(storeFor('wst_case').get('case_1')?.stage).toBe('escalated');
345+
});
346+
347+
it('a writer served the referenced record without its title column names it by its id', async () => {
348+
const { engine, storeFor } = await boot();
349+
350+
await escalate(engine, as(NAMELESS_WRITER));
351+
352+
const row = lastUpdateRow(storeFor);
353+
expect(row.summary).toBe(`Escalated to ${SEALED}`);
354+
expect(String(row.metadata)).not.toContain(SEALED_TITLE);
355+
});
356+
});

0 commit comments

Comments
 (0)