Skip to content

Commit 2fa6977

Browse files
committed
wip(audit): pins for the package_uninstall row, changeset, durability callee
Claude-Session: https://claude.ai/code/session_017ihL2bwU56eMCkj69h7Gd8 Co-Authored-By: Claude <noreply@anthropic.com>
1 parent f12b3c9 commit 2fa6977

7 files changed

Lines changed: 412 additions & 6 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/plugin-audit': patch
3+
'@objectstack/metadata-protocol': patch
4+
---
5+
6+
feat(audit): a package uninstall writes one `package_uninstall` row about the package itself
7+
8+
Clause-②: yes
9+
Metadata-protocol: none
10+
11+
Uninstalling a package left a `sys_audit_log` row for each metadata item it removed, and nothing about the package: its `sys_packages` row is deleted with raw SQL, so no hook ever saw it. A package that shipped no stored metadata left no trace at all. The uninstall verb (`deletePackage`, the path `DELETE /api/v1/packages/:id`, the import rollback, the paired-customization undo and any in-process caller take) now writes one row per package it uninstalled, after the package's stored row is gone: `action: "package_uninstall"`, the actor the verb was called for (`user_id` and `actor`; a `svc:` principal is the `actor` only), no record and no organization (an uninstall is environment-wide, so the row is deployment-level and served to the platform administrator alone), and in `metadata` the package id, its installed version, the environment, whether the object tables were kept, the items removed and left behind, and `outcome` (`complete` or `partial`).
12+
13+
An uninstall the verb refuses writes no row, and neither does an id that is not installed. The writer lives on the `audit` service slot as `recordPackageLifecycleEvent`, beside `recordAuthEvent`; a kernel without the audit plugin uninstalls exactly as before, and a ledger write that fails is logged at `error` once per cause without changing the uninstall's answer.

‎packages/metadata-protocol/src/protocol.package-delete-refusal.test.ts‎

Lines changed: 142 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,11 @@ const thrownDatabaseError: StoreDelete = async () => {
107107
};
108108

109109
/** One process over `world`. A second call over the same world is a restart. */
110-
function boot(world: World, storeDelete: StoreDelete = landed, opts: { uninstallRefusal?: Error } = {}) {
110+
function boot(
111+
world: World,
112+
storeDelete: StoreDelete = landed,
113+
opts: { uninstallRefusal?: Error; audit?: unknown; environmentId?: string } = {},
114+
) {
111115
const rows = new Map<string, { manifest: Record<string, unknown>; status: string; enabled: boolean }>();
112116
const registry = {
113117
installPackage(manifest: Record<string, unknown>, source: string) {
@@ -150,6 +154,8 @@ function boot(world: World, storeDelete: StoreDelete = landed, opts: { uninstall
150154
},
151155
};
152156
const services = new Map<string, unknown>([
157+
// [#31186] The `audit` slot, when the case composes one.
158+
...(opts.audit !== undefined ? [['audit', opts.audit] as [string, unknown]] : []),
153159
['package', {
154160
publish: async () => ({ success: true }),
155161
delete: async (id: string) => {
@@ -158,7 +164,7 @@ function boot(world: World, storeDelete: StoreDelete = landed, opts: { uninstall
158164
},
159165
}],
160166
]);
161-
const impl = new ObjectStackProtocolImplementation(engine as never, () => services as never) as any;
167+
const impl = new ObjectStackProtocolImplementation(engine as never, () => services as never, opts.environmentId) as any;
162168
vi.spyOn(impl, 'deleteMetaItem').mockImplementation(async (req: any) => {
163169
world.steps.push(`sys_metadata.delete ${req.type}/${req.name}/${req.state}`);
164170
world.sysMetadata = world.sysMetadata.filter(
@@ -323,3 +329,137 @@ describe('#21276 the restart — a fresh process over the same store holds the p
323329
expect(snapshot(world)).toEqual({ sysPackages: [], sysMetadata: [], grants: [] });
324330
});
325331
});
332+
333+
/**
334+
* [#31186] The uninstall verb hands the `audit` slot ONE `package_uninstall`
335+
* event per package it uninstalled, after the package's stored row is gone and
336+
* its cleanups ran — and none for an uninstall it refused. plugin-audit owns
337+
* the row that event becomes (`package-lifecycle-audit.test.ts` there); this
338+
* pins the verb's half: when it calls, how often, and with what.
339+
*/
340+
describe('#31186 deletePackage — the package\'s own ledger event on the `audit` slot', () => {
341+
/** An `audit` slot that records each event and the step it ran at. */
342+
function recordingAudit(world: World) {
343+
const events: unknown[] = [];
344+
return {
345+
events,
346+
slot: {
347+
async recordPackageLifecycleEvent(event: unknown) {
348+
world.steps.push('audit.package_uninstall');
349+
events.push(event);
350+
},
351+
},
352+
};
353+
}
354+
355+
it('an uninstall hands the slot one event naming the package, its version, the environment and the actor — last', async () => {
356+
const world = makeWorld();
357+
const audit = recordingAudit(world);
358+
const { impl } = boot(world, landed, { audit: audit.slot, environmentId: 'env_31186' });
359+
360+
const res = await impl.deletePackage({ packageId: PKG, actor: 'u_admin', keepData: true });
361+
362+
expect(res).toMatchObject({ success: true, deletedCount: 2, failedCount: 0 });
363+
expect(audit.events).toEqual([{
364+
action: 'package_uninstall',
365+
packageId: PKG,
366+
version: '1.0.0',
367+
environmentId: 'env_31186',
368+
actor: 'u_admin',
369+
keepData: true,
370+
itemsRemoved: 2,
371+
itemsFailed: 0,
372+
}]);
373+
// After the store delete, the item deletes, the withdrawal and the cleanups.
374+
expect(world.steps[world.steps.length - 1]).toBe('audit.package_uninstall');
375+
expect(world.steps.indexOf('sys_packages.delete')).toBeLessThan(world.steps.indexOf('audit.package_uninstall'));
376+
});
377+
378+
it('a caller with no actor and a host bound to no environment: the event says neither, and still names the package', async () => {
379+
const world = makeWorld();
380+
const audit = recordingAudit(world);
381+
const { impl } = boot(world, landed, { audit: audit.slot });
382+
383+
await impl.deletePackage({ packageId: PKG });
384+
385+
expect(audit.events).toEqual([{
386+
action: 'package_uninstall', packageId: PKG, version: '1.0.0', itemsRemoved: 2, itemsFailed: 0,
387+
}]);
388+
});
389+
390+
it('a partial uninstall still records the package, with the item it left behind', async () => {
391+
const world = makeWorld();
392+
const audit = recordingAudit(world);
393+
const { impl } = boot(world, landed, { audit: audit.slot });
394+
vi.spyOn(impl, 'deleteMetaItem').mockImplementation(async (req: any) => {
395+
if (req.type === 'view') throw Object.assign(new Error('locked'), { code: 'METADATA_LOCKED', status: 423 });
396+
world.sysMetadata = world.sysMetadata.filter((r) => !(r.type === req.type && r.name === req.name));
397+
return { success: true };
398+
});
399+
400+
const res = await impl.deletePackage({ packageId: PKG, actor: 'u_admin' });
401+
402+
expect(res).toMatchObject({ success: false, deletedCount: 1, failedCount: 1 });
403+
expect(audit.events).toEqual([expect.objectContaining({ packageId: PKG, itemsRemoved: 1, itemsFailed: 1 })]);
404+
});
405+
406+
it.each(REFUSALS)('CONTROL: a %s store refusal hands the slot nothing', async (_label, _code, refusal) => {
407+
const world = makeWorld();
408+
const audit = recordingAudit(world);
409+
const { impl } = boot(world, refusal, { audit: audit.slot });
410+
411+
await rejectionOf(impl.deletePackage({ packageId: PKG, actor: 'u_admin' }));
412+
413+
expect(audit.events).toEqual([]);
414+
});
415+
416+
it('CONTROL: the registry\'s uninstall refusal and a retired request key hand the slot nothing', async () => {
417+
const world = makeWorld();
418+
const audit = recordingAudit(world);
419+
const refused = boot(world, landed, { audit: audit.slot, uninstallRefusal: new Error('extended by com.example.addon') });
420+
await rejectionOf(refused.impl.deletePackage({ packageId: PKG }));
421+
const retired = boot(world, landed, { audit: audit.slot });
422+
await rejectionOf(retired.impl.deletePackage({ packageId: PKG, organizationId: 'org_a' } as any));
423+
424+
expect(audit.events).toEqual([]);
425+
});
426+
427+
it('CONTROL: an id that is not installed and binds no metadata is not a package — no event', async () => {
428+
const world = makeWorld();
429+
const audit = recordingAudit(world);
430+
const { impl } = boot(world, landed, { audit: audit.slot });
431+
432+
const res = await impl.deletePackage({ packageId: 'com.example.absent' });
433+
434+
expect(res).toMatchObject({ deletedCount: 0, failedCount: 0 });
435+
expect(audit.events).toEqual([]);
436+
});
437+
438+
it('CONTROL: with no `audit` slot the uninstall completes exactly as before', async () => {
439+
const world = makeWorld();
440+
const { impl, registry } = boot(world);
441+
442+
const res = await impl.deletePackage({ packageId: PKG, actor: 'u_admin' });
443+
444+
expect(res).toMatchObject({ success: true, deletedCount: 2, failedCount: 0 });
445+
expect(registry.getPackage(PKG)).toBeUndefined();
446+
});
447+
448+
it('a slot that throws does not change the answer: the uninstall completes and the lost row is logged at error', async () => {
449+
const world = makeWorld();
450+
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
451+
try {
452+
const { impl } = boot(world, landed, {
453+
audit: { recordPackageLifecycleEvent: async () => { throw new Error('ledger offline'); } },
454+
});
455+
456+
const res = await impl.deletePackage({ packageId: PKG });
457+
458+
expect(res).toMatchObject({ success: true, deletedCount: 2 });
459+
expect(errorSpy).toHaveBeenCalledTimes(1);
460+
expect(String(errorSpy.mock.calls[0]?.[0])).toContain(PKG);
461+
} finally {
462+
errorSpy.mockRestore();
463+
}
464+
});
465+
});

‎packages/plugins/plugin-audit/src/audit-log-deployment-level-rows.integration.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
* exactly like a rule that was never written. The rows about an organization
1616
* are written by the real CRUD mirror; the deployment-level rows as their
1717
* writers write them: as the system, about no organization (service-settings'
18-
* GLOBAL `config_change`, plugin-security's platform-admin standing roster).
18+
* GLOBAL `config_change`, plugin-security's platform-admin standing roster,
19+
* plugin-audit's `package_uninstall`).
1920
*
2021
* ⛔ No security plugin, on purpose. WHICH organization's rows an organization
2122
* reader is served under a wall is the platform row policy's answer
@@ -55,6 +56,9 @@ type Row = Record<string, any>;
5556
const DEPLOYMENT_LEVEL = [
5657
{ action: 'config_change', object_name: 'sys_platform_setting', record_id: null },
5758
{ action: 'platform_admin_standing_change', object_name: 'sys_user', record_id: null },
59+
// [#31186] A package uninstall is environment-wide: its row names no record and no organization
60+
// (`package-lifecycle-audit.ts`), so it is served to the platform administrator alone.
61+
{ action: 'package_uninstall', object_name: null, record_id: null },
5862
];
5963

6064
const noteObject = {
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#31186] The package lifecycle writer stores a REAL, READ-BACK ledger row for
5+
* each package uninstall.
6+
*
7+
* The slot cases boot the real composition this package ships in
8+
* (`ObjectQLPlugin` + `AuditPlugin` on a sqlite driver) and reach the writer
9+
* the way the uninstall verb does: through the `audit` service slot's
10+
* `recordPackageLifecycleEvent`. Every assertion reads the row back through the
11+
* engine, for the reason `auth-event-audit.test.ts` records: every
12+
* `sys_audit_log` field is `readonly` and `validateRecord` skips readonly
13+
* fields, so "the call did not throw" is equally true when the row landed
14+
* right, landed wrong, or was never attempted. The verb's half — one event per
15+
* package it uninstalled, none for a refused uninstall — is pinned in
16+
* `@objectstack/metadata-protocol`'s `protocol.package-delete-refusal.test.ts`.
17+
*/
18+
19+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
20+
import { ObjectKernel } from '@objectstack/core';
21+
import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql';
22+
import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm';
23+
24+
import { AuditPlugin } from './audit-plugin.js';
25+
import {
26+
PACKAGE_UNINSTALL_AUDIT_ACTION,
27+
buildPackageLifecycleAuditRow,
28+
createPackageLifecycleAuditWriter,
29+
type PackageLifecycleAuditEvent,
30+
type PackageLifecycleAuditWriter,
31+
} from './package-lifecycle-audit.js';
32+
33+
const LEDGER = 'sys_audit_log';
34+
const SYS = { isSystem: true } as const;
35+
36+
/** An uninstall as the verb hands it; each case overrides what it is about. */
37+
function uninstallEvent(overrides: Partial<PackageLifecycleAuditEvent> = {}): PackageLifecycleAuditEvent {
38+
return {
39+
action: 'package_uninstall',
40+
packageId: 'com.acme.leave',
41+
version: '1.2.0',
42+
environmentId: 'env_31186',
43+
actor: 'u_admin',
44+
itemsRemoved: 3,
45+
itemsFailed: 0,
46+
...overrides,
47+
};
48+
}
49+
50+
const metadataOf = (row: Record<string, unknown>): Record<string, any> => JSON.parse(String(row.metadata));
51+
52+
describe('[#31186] the package lifecycle writer on the real `audit` slot', () => {
53+
let kernel: ObjectKernel;
54+
let engine: ObjectQL;
55+
let audit: PackageLifecycleAuditWriter;
56+
57+
/** The uninstall rows at rest, oldest first. */
58+
const uninstallRows = async (): Promise<Array<Record<string, any>>> =>
59+
(await engine.find(LEDGER, {
60+
where: { action: PACKAGE_UNINSTALL_AUDIT_ACTION },
61+
orderBy: [{ field: 'created_at', order: 'asc' }],
62+
context: SYS,
63+
})) as Array<Record<string, any>>;
64+
65+
beforeAll(async () => {
66+
kernel = new ObjectKernel({ logger: { level: 'silent' } });
67+
await kernel.use(new ObjectQLPlugin());
68+
await kernel.use(new AuditPlugin());
69+
await kernel.bootstrap();
70+
engine = kernel.getService<ObjectQL>('objectql');
71+
const driver = new SqliteWasmDriver({ filename: ':memory:' });
72+
await driver.connect();
73+
engine.registerDriver(driver, true);
74+
await engine.syncSchemas();
75+
audit = kernel.getService<PackageLifecycleAuditWriter>('audit');
76+
}, 120_000);
77+
78+
afterAll(async () => {
79+
if (kernel) await Promise.race([kernel.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]);
80+
}, 30_000);
81+
82+
it('the slot carries the writer beside the other ledger ingresses', () => {
83+
expect(typeof audit.recordPackageLifecycleEvent).toBe('function');
84+
expect(typeof (audit as any).recordAuthEvent).toBe('function');
85+
expect(typeof (audit as any).recordDataExport).toBe('function');
86+
});
87+
88+
it('an uninstall writes ONE row naming the actor, the package, its version and the environment', async () => {
89+
const before = (await uninstallRows()).length;
90+
await audit.recordPackageLifecycleEvent(uninstallEvent({ keepData: true }));
91+
const rows = await uninstallRows();
92+
expect(rows).toHaveLength(before + 1);
93+
const row = rows[rows.length - 1];
94+
expect(row).toMatchObject({
95+
action: 'package_uninstall',
96+
user_id: 'u_admin',
97+
actor: 'u_admin',
98+
object_name: null,
99+
record_id: null,
100+
tenant_id: null,
101+
});
102+
expect(row.old_value ?? null).toBeNull();
103+
expect(row.new_value ?? null).toBeNull();
104+
expect(metadataOf(row)).toEqual({
105+
package_id: 'com.acme.leave',
106+
version: '1.2.0',
107+
environment_id: 'env_31186',
108+
keep_data: true,
109+
items_removed: 3,
110+
items_failed: 0,
111+
outcome: 'complete',
112+
});
113+
});
114+
115+
it('a partial uninstall records the items it left behind', async () => {
116+
await audit.recordPackageLifecycleEvent(uninstallEvent({ itemsRemoved: 2, itemsFailed: 1 }));
117+
const rows = await uninstallRows();
118+
expect(metadataOf(rows[rows.length - 1])).toMatchObject({ items_removed: 2, items_failed: 1, outcome: 'partial' });
119+
});
120+
121+
it('no actor, no version, no environment: the row still names the package, and records the absences as null', async () => {
122+
await audit.recordPackageLifecycleEvent(uninstallEvent({ actor: undefined, version: undefined, environmentId: undefined }));
123+
const rows = await uninstallRows();
124+
const row = rows[rows.length - 1];
125+
expect(row).toMatchObject({ user_id: null, actor: null });
126+
expect(metadataOf(row)).toMatchObject({ package_id: 'com.acme.leave', version: null, environment_id: null, keep_data: false });
127+
});
128+
129+
it('an event that names no package, or another action, writes nothing', async () => {
130+
const before = (await uninstallRows()).length;
131+
await audit.recordPackageLifecycleEvent(uninstallEvent({ packageId: ' ' }));
132+
await audit.recordPackageLifecycleEvent({ ...uninstallEvent(), action: 'package_install' as any });
133+
expect(await uninstallRows()).toHaveLength(before);
134+
});
135+
});
136+
137+
describe('[#31186] the package_uninstall row shape', () => {
138+
it('a service principal is the actor and never the `sys_user` lookup', () => {
139+
const row = buildPackageLifecycleAuditRow(uninstallEvent({ actor: 'svc:cloud-uninstall' }));
140+
expect(row).toMatchObject({ user_id: null, actor: 'svc:cloud-uninstall' });
141+
});
142+
143+
it('a ledger deployed without the `actor` column gets no `actor` key', () => {
144+
const row = buildPackageLifecycleAuditRow(uninstallEvent(), (_o, field) => field !== 'actor');
145+
expect(row).not.toHaveProperty('actor');
146+
expect(row.user_id).toBe('u_admin');
147+
});
148+
});
149+
150+
describe('[#31186] the writer never changes the uninstall\'s answer', () => {
151+
it('with no engine it writes nothing and does not throw', async () => {
152+
const writer = createPackageLifecycleAuditWriter({ getEngine: () => undefined });
153+
await expect(writer.recordPackageLifecycleEvent(uninstallEvent())).resolves.toBeUndefined();
154+
});
155+
156+
it('a refused insert is reported at error once per cause, and never thrown', async () => {
157+
const error = vi.fn();
158+
const debug = vi.fn();
159+
const failing = {
160+
insert: async () => {
161+
throw Object.assign(new Error('disk full'), { code: 'SQLITE_FULL' });
162+
},
163+
getSchema: () => undefined,
164+
} as any;
165+
const writer = createPackageLifecycleAuditWriter({ getEngine: () => failing, logger: { error, debug, warn: vi.fn() } });
166+
167+
await expect(writer.recordPackageLifecycleEvent(uninstallEvent())).resolves.toBeUndefined();
168+
await expect(writer.recordPackageLifecycleEvent(uninstallEvent())).resolves.toBeUndefined();
169+
170+
expect(error).toHaveBeenCalledTimes(1);
171+
expect(String(error.mock.calls[0]?.[0])).toContain('com.acme.leave');
172+
expect(debug).toHaveBeenCalledTimes(1);
173+
});
174+
});

0 commit comments

Comments
 (0)