-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathaudit-writers.test.ts
More file actions
296 lines (263 loc) · 10.9 KB
/
Copy pathaudit-writers.test.ts
File metadata and controls
296 lines (263 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect } from 'vitest';
import { installAuditWriters } from './audit-writers.js';
/**
* Regression coverage for #1532 — on single-tenant stacks the
* SchemaRegistry does NOT auto-inject `organization_id` into
* `sys_audit_log` / `sys_activity`, so the audit writer must not emit that
* column. Previously it stamped `organization_id` unconditionally, making
* every audit INSERT fail with "table sys_audit_log has no column named
* organization_id" (swallowed → audit logging silently non-functional).
*/
interface CapturedRow {
object: string;
row: Record<string, any>;
}
/**
* Build a fake ObjectQL engine that records hook registrations and the rows
* written through `api.sudo().object(name).create(row)`.
*
* @param schemas Map of object short-name → declared field set. Mirrors what
* `engine.getSchema(name)` returns after `applySystemFields` has (or has
* not) injected `organization_id`.
*/
function makeEngine(
schemas: Record<string, string[] | Record<string, any>>,
objectDefs: Record<string, any> = {},
) {
const hooks = new Map<string, Array<(ctx: any) => any>>();
const created: CapturedRow[] = [];
const sudoApi = {
object(name: string) {
return {
async create(row: Record<string, any>) {
created.push({ object: name, row });
return { id: 'generated-id', ...row };
},
};
},
};
// `writeAudit` calls `ctx.api.sudo()` to get the object accessor above.
const api = { sudo: () => sudoApi };
const engine = {
getSchema(name: string) {
const fields = schemas[name];
if (!fields) return undefined;
const fieldMap = Array.isArray(fields)
? Object.fromEntries(fields.map((f) => [f, { type: 'text' }]))
: fields;
return { name, fields: fieldMap, ...(objectDefs[name] || {}) };
},
registerHook(event: string, fn: (ctx: any) => any) {
const list = hooks.get(event) ?? [];
list.push(fn);
hooks.set(event, list);
},
unregisterHooksByPackage() {
/* no-op */
},
logger: { warn() {} },
};
async function fire(event: string, ctx: any) {
for (const fn of hooks.get(event) ?? []) {
await fn({ ...ctx, event, api });
}
}
return { engine, fire, created };
}
const SINGLE_TENANT = {
// No `organization_id` — single-tenant stacks skip the auto-injection.
sys_audit_log: ['id', 'action', 'user_id', 'actor', 'object_name', 'record_id', 'old_value', 'new_value', 'tenant_id'],
sys_activity: ['id', 'type', 'timestamp', 'summary', 'actor_id', 'object_name', 'record_id', 'record_label', 'metadata'],
};
const MULTI_TENANT = {
sys_audit_log: [...SINGLE_TENANT.sys_audit_log, 'organization_id'],
sys_activity: [...SINGLE_TENANT.sys_activity, 'organization_id'],
};
describe('audit writers — organization_id stamping (#1532)', () => {
it('omits organization_id on single-tenant tables that lack the column', async () => {
const { engine, fire, created } = makeEngine(SINGLE_TENANT);
installAuditWriters(engine as any, 'test.audit');
await fire('afterInsert', {
object: 'crm_lead',
input: { id: 'lead-1' },
result: { id: 'lead-1', name: 'Acme' },
session: {},
});
const audit = created.find((c) => c.object === 'sys_audit_log');
const activity = created.find((c) => c.object === 'sys_activity');
expect(audit).toBeDefined();
expect(activity).toBeDefined();
// The fix: no undeclared column is emitted, so the INSERT would succeed.
expect('organization_id' in audit!.row).toBe(false);
expect('organization_id' in activity!.row).toBe(false);
// tenant_id is schema-declared and still written.
expect('tenant_id' in audit!.row).toBe(true);
});
it('stamps organization_id on multi-tenant tables when the column exists', async () => {
const { engine, fire, created } = makeEngine(MULTI_TENANT);
installAuditWriters(engine as any, 'test.audit');
await fire('afterInsert', {
object: 'crm_lead',
input: { id: 'lead-1' },
result: { id: 'lead-1', name: 'Acme', organization_id: 'org-9' },
session: { tenantId: 'org-9', userId: 'user-1' },
});
const audit = created.find((c) => c.object === 'sys_audit_log');
const activity = created.find((c) => c.object === 'sys_activity');
expect(audit?.row.organization_id).toBe('org-9');
expect(activity?.row.organization_id).toBe('org-9');
});
});
describe('audit writers — actor attribution (ADR-0014 D2, cloud#340)', () => {
it('records a real user id on actor + user_id', async () => {
const { engine, fire, created } = makeEngine(SINGLE_TENANT);
installAuditWriters(engine as any, 'test.audit');
await fire('afterInsert', {
object: 'crm_lead',
input: { id: 'lead-1' },
result: { id: 'lead-1', name: 'Acme' },
session: { userId: 'user-7' },
});
const audit = created.find((c) => c.object === 'sys_audit_log');
expect(audit?.row.user_id).toBe('user-7');
expect(audit?.row.actor).toBe('user-7');
});
it('attributes a service-token write (no userId) via session.actor → actor, user_id stays null', async () => {
const { engine, fire, created } = makeEngine(SINGLE_TENANT);
installAuditWriters(engine as any, 'test.audit');
// The os-790m7q class: a service-token delete with no real user.
await fire('afterDelete', {
object: 'sys_environment',
input: { id: 'os-790m7q' },
__previous: { id: 'os-790m7q', name: 'test' },
result: { id: 'os-790m7q' },
session: { actor: 'svc:cloud-control' },
});
const audit = created.find((c) => c.object === 'sys_audit_log');
expect(audit?.row.action).toBe('delete');
// user_id (sys_user lookup) stays null — a service principal isn't a user…
expect(audit?.row.user_id).toBeNull();
// …but the action is now ATTRIBUTABLE on actor.
expect(audit?.row.actor).toBe('svc:cloud-control');
});
it('leaves actor null when neither a user nor a service principal is present', async () => {
const { engine, fire, created } = makeEngine(SINGLE_TENANT);
installAuditWriters(engine as any, 'test.audit');
await fire('afterInsert', {
object: 'crm_lead',
input: { id: 'lead-2' },
result: { id: 'lead-2', name: 'Beta' },
session: {},
});
const audit = created.find((c) => c.object === 'sys_audit_log');
expect(audit?.row.actor).toBeNull();
expect(audit?.row.user_id).toBeNull();
});
});
describe('audit writers — declarative trackHistory activity (ADR-0052 §5b)', () => {
// crm_opportunity with a tracked select field (Stage) carrying option labels.
const SCHEMA = {
sys_audit_log: SINGLE_TENANT.sys_audit_log,
sys_activity: SINGLE_TENANT.sys_activity,
crm_opportunity: {
id: { type: 'text' },
name: { type: 'text', label: 'Name' },
amount: { type: 'currency', label: 'Amount' },
stage: {
type: 'select',
label: 'Stage',
trackHistory: true,
options: [
{ value: 'proposal', label: 'Proposal' },
{ value: 'closed_won', label: 'Closed Won' },
],
},
},
};
it('renders a tracked field change as "<label>: <old> → <new>" with option labels', async () => {
const { engine, fire, created } = makeEngine(SCHEMA);
installAuditWriters(engine as any, 'test.audit');
await fire('afterUpdate', {
object: 'crm_opportunity',
input: { id: 'opp-1', stage: 'closed_won' },
result: { id: 'opp-1', name: 'Acme Renewal', stage: 'closed_won' },
__previous: { id: 'opp-1', name: 'Acme Renewal', stage: 'proposal' },
session: {},
});
const activity = created.find((c) => c.object === 'sys_activity');
// Platform-generated, human-readable — no app code wrote this.
expect(activity?.row.summary).toBe('Stage: Proposal → Closed Won');
});
it('falls back to the generic summary when only untracked fields change', async () => {
const { engine, fire, created } = makeEngine(SCHEMA);
installAuditWriters(engine as any, 'test.audit');
await fire('afterUpdate', {
object: 'crm_opportunity',
input: { id: 'opp-1', amount: 200 },
result: { id: 'opp-1', name: 'Acme Renewal', amount: 200, stage: 'proposal' },
__previous: { id: 'opp-1', name: 'Acme Renewal', amount: 100, stage: 'proposal' },
session: {},
});
const activity = created.find((c) => c.object === 'sys_activity');
expect(activity?.row.summary).toBe('Updated crm_opportunity "Acme Renewal"');
});
});
describe('audit writers — declarative milestones (ADR-0052 §5b.2)', () => {
const FIELDS = {
id: { type: 'text' },
name: { type: 'text', label: 'Name' },
stage: {
type: 'select',
label: 'Stage',
trackHistory: true,
options: [
{ value: 'negotiation', label: 'Negotiation' },
{ value: 'closed_won', label: 'Closed Won' },
],
},
};
const SCHEMA = {
sys_audit_log: SINGLE_TENANT.sys_audit_log,
sys_activity: SINGLE_TENANT.sys_activity,
crm_opportunity: FIELDS,
};
// Object-level milestone: when stage enters closed_won → "Deal won: {name}".
const OBJECT_DEFS = {
crm_opportunity: {
activityMilestones: [
{ field: 'stage', value: 'closed_won', summary: 'Deal won: {name}', type: 'completed' },
],
},
};
it('emits the interpolated milestone summary (precedence over field-change) on transition', async () => {
const { engine, fire, created } = makeEngine(SCHEMA, OBJECT_DEFS);
installAuditWriters(engine as any, 'test.audit');
await fire('afterUpdate', {
object: 'crm_opportunity',
input: { id: 'opp-1', stage: 'closed_won' },
result: { id: 'opp-1', name: 'Acme Renewal', stage: 'closed_won' },
__previous: { id: 'opp-1', name: 'Acme Renewal', stage: 'negotiation' },
session: {},
});
const activity = created.find((c) => c.object === 'sys_activity');
// Milestone summary wins over the "Stage: Negotiation → Closed Won" diff.
expect(activity?.row.summary).toBe('Deal won: Acme Renewal');
expect(activity?.row.type).toBe('completed');
});
it('does not fire the milestone when the field does not transition into the value', async () => {
const { engine, fire, created } = makeEngine(SCHEMA, OBJECT_DEFS);
installAuditWriters(engine as any, 'test.audit');
await fire('afterUpdate', {
object: 'crm_opportunity',
input: { id: 'opp-1', stage: 'negotiation' },
result: { id: 'opp-1', name: 'Acme Renewal', stage: 'negotiation' },
__previous: { id: 'opp-1', name: 'Acme Renewal', stage: 'proposal' },
session: {},
});
const activity = created.find((c) => c.object === 'sys_activity');
// Falls back to the field-change render (trackHistory), not the milestone.
// `proposal` has no option entry here → raw value; `negotiation` → its label.
expect(activity?.row.summary).toBe('Stage: proposal → Negotiation');
});
});