Skip to content

Commit 2ecf6a7

Browse files
fix(plugin-audit)!: serve the ledger’s deployment-level rows to the platform administrator alone, in every posture (#28047)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DUkDtugva69s3nUwLDmAzKf)_ Fixes #26750 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: updated here ## 维护者速读 - **改了什么**:合规审计账本里不属于任何组织的部署级记录(`tenant_id` 为空:全局设置变更、用户导入、平台管理员身份变更、管理员建号与重置密码),在所有租户姿态下(含 `single`)只给平台管理员看;其他读者,包括 `view_all_audit_log` 的持有者,只看属于某个组织的记录。 - **为什么改**:落实 #26750 的裁决 A。`single` 姿态下组织行策略被剥离,任何拿到账本读权的人都能读到部署级记录。 - **风险与回滚**:读范围收窄(BREAKING)。`single` 部署里自建的审计角色和组织管理员将看不到部署配置历史;记录仍在库,系统上下文的导出不受影响。回滚即 revert 本 PR,无数据迁移。 - **先看**:`packages/plugins/plugin-audit/src/audit-log-read-visibility.ts`(中间件末尾新增的一行规则与 `readsDeploymentLevelLedgerRows`)、`packages/plugins/plugin-audit/src/audit-log-deployment-level-rows.integration.test.ts`、`packages/qa/dogfood/test/admin-ledger-decision-metadata.dogfood.test.ts`(按裁决翻转的钉子)。 - **两分钟验证**:`pnpm --filter @objectstack/plugin-audit exec vitest run src/audit-log-deployment-level-rows.integration.test.ts`,预期 `single` / `group` / `isolated` 三个姿态共 18 条全绿。 - **需要你做的**:无,席位落地。 ## What changes - **The read rule** (`packages/plugins/plugin-audit/src/audit-log-read-visibility.ts`). On every non-system engine read of `sys_audit_log` (find, findOne, count, aggregate), a reader that is not the platform administrator gets one more clause ANDed into its `where`: `tenant_id` is neither null nor empty. It is added after the parent-record gate, which plans its parents off the read's own `where`, and it reaches the holder of `view_all_audit_log` too, whom that gate exempts. The platform administrator is the carried `PLATFORM_ADMIN` posture rung (`PLATFORM_OPERATOR_POSTURE`, ADR-0095 D2/D3), which the unscoped `admin_full_access` grant derives. Positions, set names and capabilities are not read, and a context with no rung gets the clause. Writes, system-context reads and context-less programmatic reads are untouched. Which organization's rows an organization reader is served stays the row policy's answer (ADR-0131 D8). The module is not re-exported, so the package's public surface is unchanged. - **The capability text** (`packages/spec/src/security/capabilities.ts`). The `view_all_audit_log` description gains one sentence for `single`. Nothing else in `packages/spec` changes. - **Docs.** One sentence in `content/docs/permissions/record-view-auditing.mdx`. - **Changeset** `.changeset/26750-ledger-deployment-level-rows.md`: patch for both packages, the two declaration lines, a BREAKING banner, and an upgrade note for `single` operators who granted the ledger to someone who is not the platform administrator. ## Why Ruling A on #26750 (comment 6457448424): deployment-level ledger rows (no `tenant_id`, ADR-0131 D7) are served only to the platform administrator in every tenancy posture, `single` included, and an organization-scoped holder of `view_all_audit_log` reads only the rows about its organization(s). Under `single` the shipped row policy `sys_audit_log_org` is stripped (a platform tenant policy by provenance, ADR-0105 D3), so every reader with a ledger grant was served those rows. On the ruling's "its superuser read bypass": the bypass (`viewAllRecords`) skips plugin-security's Layer 1 only and never reaches this plugin's read middleware. So the rule reads the carried rung that names the platform administrator, and no new capability is introduced. ## Tests - `audit-log-read-visibility.test.ts` (unit): - the clause's shape, and a fresh tree per call; - the rung-only predicate: `TENANT_ADMIN`, `MEMBER`, `EXTERNAL`, a mis-cased rung, no rung, `platform_admin` as a position, and `admin_full_access` as a permission or a capability all answer false; - a non-holder gets the gate, then the clause; - a holder on every non-admin rung gets the clause alone, on find, findOne, count and aggregate; - the platform administrator, with or without the capability, gets no clause; - writes, system reads and context-less reads get none. - `audit-log-read-visibility.integration.test.ts`: the fixture rows now carry the tenant each real writer stamps. A new case serves the deployment-level rows to the platform administrator alone; the member, the other member, the organization admin and the holder are served none. - `audit-log-deployment-level-rows.integration.test.ts` (new): one boot per posture (`single`, `group`, `isolated`) with the real CRUD mirror. The organization holder and the organization admin are served their organization's rows and no deployment-level row, through find, count, a `tenant_id: null` filter, findOne by id and a grouped aggregate. The platform administrator is served both. - The dogfood pin sweep. Both files were named to the seat and added to the claim's file surface before they were edited. - `audit-log-audit-capability.dogfood.test.ts`: the broad read's bulk rows were system inserts with no `tenant_id`, which made them deployment-level rows. They now carry the holder's organization, as the CRUD mirror stamps a row about a record of it. The test's subject is unchanged. - `admin-ledger-decision-metadata.dogfood.test.ts`: **a pin flip caused by ruling 6457448424, not a fix-to-green.** Every row about the subject (plugin-auth's explicit rows and the mirror's rows, written by the platform administrator's endpoints with no organization) is deployment-level, so no class reader can be served one in any posture. The decisions-only guarantee is now asserted at the producer, on the rows at rest. The read side pins the ruling: every reader is served only a control row about the same subject that carries the readers' organization, and the platform administrator is served every row. The armed checks keep their shape: the rows exist and the mirror carries every class; every reader opens the subject; no row about the subject carries an organization, and every reader is served the control row. - Two plugin-audit fixtures the full package suite found (inside the claim's surface, "its tests under `packages/plugins/plugin-audit/src/`"): - `audit-log-field-redaction.test.ts`: the rows from other writers were system inserts with no `tenant_id`, so the organization readers there were no longer served them. They carry the Default Organization, as a tenant-scope writer stamps them. The redaction cases are unchanged. - `parent-record-read-leaf.integration.test.ts`: the rows about no record carry the Default Organization the same way. The observer that records each ledger read's WHERE "as the gates left it" takes the deployment-level clause, ANDed after the gate, off what it records, so the gate's own WHERE is still what is measured. The holder's case now also pins that the clause is there. ## Acceptance notes - **Measurement (the card's first step).** Under `group` and `isolated`, a custom set that grants the ledger read and `view_all_audit_log` and omits `sys_audit_log_org` was measured on a real boot before the change. Its holder was served only its own organization's rows, so that set has no NULL-tenant leak to fix. - **The cross-organization half is outside this card.** The same measurement found that under a wall, a custom set that authors its own ledger row policy, or that grants the read bypass on the ledger, is served rows beyond its holder's organization. This change closes the deployment-level half of that: those rows are now the platform administrator's alone, in every posture. Rows about other organizations stay reachable through such a set. No reproduction detail is given here; the withheld detail stays on #26640. - The ledger rows stay stored, and nothing is re-attributed (the ruling: not B). ## Verification Final head `af925f22`. It differs from `173abc30` only in the two plugin-audit fixtures above, which no dogfood file runs. <details><summary>Ablation 1: the rule line replaced by a marker, three plugin-audit files: 20 red, restored</summary> ```text node scripts/ablation-replace.mjs --file packages/plugins/plugin-audit/src/audit-log-read-visibility.ts \ --anchor 'if (!readsDeploymentLevelLedgerRows(ctx.context)) andIntoWhere(ctx, ledgerRowAboutAnOrganizationWhere());' \ --replacement '// ABLATION: the deployment-level rule removed' -- pnpm --filter @objectstack/plugin-audit exec vitest run \ src/audit-log-read-visibility.test.ts src/audit-log-read-visibility.integration.test.ts src/audit-log-deployment-level-rows.integration.test.ts ablation-replace: ok mutation landed: anchor 1 -> 0, blob c49da4b -> f05a69cb34ea Test Files 3 failed (3) Tests 20 failed | 44 passed (64) red (count × title): 3 × the organization holder of the audit capability is served its organization's rows, and no deployment-level row (single, group, isolated) 3 × the organization admin is served its organization's rows, and no deployment-level row (single, group, isolated) 3 × a read that asks for the deployment-level rows by name or by id is served none of them (single, group, isolated) 3 × a grouped count sees no deployment-level row (single, group, isolated) 1 × a caller without the audit capability gets the gate, then the clause ANDed after it 1 × an organization holder of the audit capability, on every rung but the platform administrator's, gets the clause alone 1 × its holder is not narrowed by the parent-record gate, on any read operation, and nothing is scanned for it 1 × [#26750] the deployment-level rows are served to the platform administrator alone 1 × [#21260] a holder of the ledger audit capability is served every row about the organization, deleted and unreadable records included 1 × find: a member reads the rows about records it can read and the organization's rows about no record, and nothing else 1 × aggregate: a grouped count sees only the readable rows 1 × an admin, who reads every record, keeps every row about a record that exists and the organization's rows about none ablation-replace: ok restored: blob == HEAD (c49da4b) and `git diff HEAD` is empty ``` </details> <details><summary>Ablation 2: the predicate also reads a <code>platform_admin</code> position: the rung-only pin red, restored</summary> ```text --anchor 'return context?.posture === PLATFORM_OPERATOR_POSTURE;' --replacement 'return context?.posture === PLATFORM_OPERATOR_POSTURE || ((context as any)?.positions ?? []).includes("platform_admin"); // ABLATION: positions read beside the rung' Test Files 1 failed | 2 passed (3) Tests 1 failed | 63 passed (64) × the platform administrator is the carried PLATFORM_ADMIN rung, and nothing else AssertionError: {"userId":"u1","positions":["platform_admin"]}: expected true to be false ablation-replace: ok restored: blob == HEAD (c49da4b) and `git diff HEAD` is empty ``` </details> <details><summary>Ablation 3: the rule removed, against the re-armed leaf fixture: the holder's clause pin red, restored</summary> ```text Test Files 1 failed | 1 passed (2) Tests 1 failed | 32 passed (33) × ledger: the audit capability's holder is not narrowed — the gate writes nothing for it AssertionError: expected false to be true ablation-replace: ok restored: blob == HEAD (c49da4b) and `git diff HEAD` is empty ``` </details> <details><summary>Package suites (green), each under the verify lock</summary> ```text pnpm --filter @objectstack/plugin-audit test Test Files 66 passed (66) · Tests 1077 passed (1077) pnpm --filter @objectstack/spec exec vitest run src/security src/identity Test Files 26 passed (26) · Tests 601 passed (601) pnpm --filter @objectstack/plugin-security test Test Files 237 passed (237) · Tests 5119 passed | 45 skipped (5164) plugin-auth: durability-swallow-repair + admin-user-endpoints Test Files 2 passed (2) · Tests 115 passed (115) service-settings: config-change-audit Test Files 1 passed (1) · Tests 17 passed (17) service-automation: resume-decider-identity + runas-attribution-contract Test Files 2 passed (2) · Tests 23 passed (23) ``` The neighbouring suites are the ones outside plugin-audit that boot the audit plugin and read the ledger. </details> <details><summary>Full dogfood battery: red on the first head (the two fixtures, named above), green after</summary> ```text 46f5ab6 · os-verify-lock: VERDICT command-exit 1 · held the lock 1175s Test Files 2 failed | 355 passed | 3 skipped (360) Tests 1 failed | 2866 passed | 28 skipped (2895) audit-log-audit-capability.dogfood.test.ts:352 expected 2055, received 5 (the bulk rows carried no tenant_id) admin-ledger-decision-metadata.dogfood.test.ts assertArmed disarmed (no reader served any row about the subject) 173abc3 · pnpm --filter @objectstack/dogfood test os-verify-lock: VERDICT command-exit 0 · held the lock 1118s (18m38s) · waited 0s Test Files 357 passed | 3 skipped (360) Tests 2877 passed | 20 skipped (2897) ``` </details> <details><summary>dispatch-gates: 106 derived families, run and reconciled</summary> ```text 173abc3: node scripts/pm/dispatch-gates.mjs --ran gates-ran.txt Run reconciliation — 106 derived, 106 run, 0 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 106 derived famil(ies) accounted for — 106 run, 0 NOT-MEASURED (a DERIVED zero — all 106 recorded an exit code and none of them is 3). every family exit 0 af925f2: the same 106 families (re-derived, identical list) are re-running; the reconciliation goes in the card's report comment. ``` Three families needed a prerequisite in this shallow cloud clone before they measured: `check-plugin-teardown-shape --self-test` (the pinned fixture commit fetched), `spec check:skill-examples` (client SDK declarations built), `check:dual-build-cjs-loads` (six package builds). </details> <details><summary>Lint and generated artifacts</summary> ```text pnpm lint exit 0 pnpm --filter @objectstack/spec run check:generated exit 0 · All 14 generated artifacts are up to date node scripts/pm/check-governed-merges.mjs --branch … NOT governed · 0 of 9 paths hit the register ``` </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (The only spec change is one sentence in a capability description.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (`check:generated`: all 14 up to date; no artifact carries the description.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (The `维护者速读` block is the fleet's one sanctioned Chinese section.) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. Contract review is owed: the seat runs it on the final head. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cwC9jjzyBACUnk1V9V --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cwC9jjzyBACUnk1V9V)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5448585 commit 2ecf6a7

11 files changed

Lines changed: 567 additions & 119 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/plugin-audit': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
fix(plugin-audit)!: the compliance ledger's deployment-level rows (no `tenant_id`) are served to the platform administrator alone, in every tenancy posture, `single` included (#26750)
7+
8+
Clause-②: no (narrowing) — under `single`, a non-system reader of `sys_audit_log` that is not the platform administrator (an organization administrator, the holder of a set that grants the ledger read, a holder of `view_all_audit_log`) is no longer served the ledger rows that carry no `tenant_id`; under a wall, the shipped sets' row scope already excluded them. Nothing is widened.
9+
Metadata-protocol: none
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export is added, removed or renamed: one runtime read rule on sys_audit_log changes which stored rows a reader who is not the platform administrator is served, and the view_all_audit_log description gains one sentence. There is nothing for a migration to rewrite and no tombstone. -->
12+
13+
**BREAKING** read narrowing on `sys_audit_log` (`@objectstack/plugin-audit`), on every engine read of the ledger: the data API's list, by-id, count and aggregate, and the Setup views and record history built on them.
14+
15+
- **Before.** The ledger has no organization column (ADR-0131 D7); the organization a row is about is the attribution field `tenant_id`, and a row about a deployment-level action carries none: a GLOBAL settings change, a user-import run, a platform-admin standing change, a user account the platform administrator creates or resets through the admin endpoints, a system write about an object with no organization column. Under a wall the shipped row policy `sys_audit_log_org` kept those rows from every organization reader. Under `single` no wall is enforced and that policy is stripped, so every reader whose sets grant the ledger read was served them, and a holder of `view_all_audit_log` was served them past the parent-record gate too.
16+
- **Now.** In every posture, a ledger row with no `tenant_id` is served only to the platform administrator: the carried `PLATFORM_ADMIN` posture rung, which the unscoped `admin_full_access` grant derives. Every other non-system reader is served only the rows about an organization. Which organization's rows stays the row policy's answer, unchanged. The same holds under a wall for a set that authors its own ledger row policy or grants the superuser read bypass on the ledger: its holder is not the platform administrator.
17+
- **Unchanged.** The rows stay stored. A system-context read and a context-less programmatic read still return every row. The platform administrator reads every row as before, on a request that carries the `PLATFORM_ADMIN` rung, which the request's authorization context resolves for the administrator. A context built outside that resolution carries no rung and is served the rows about an organization only (fail-closed, never wider): for example, an automation run with `runAs: 'user'` whose run context seeds no posture. The parent-record gate and the field-level redaction of the snapshots are unchanged. A walled deployment on the shipped sets serves every reader the same rows as before.
18+
- **The capability text.** The `view_all_audit_log` description (`PLATFORM_CAPABILITIES`, `@objectstack/spec`) gains one sentence saying the same for `single`.
19+
20+
**Upgrade note for `single` operators who granted the ledger to someone who is not the platform administrator.** An auditor role (a set granting `sys_audit_log` read, with or without `view_all_audit_log`), an organization administrator, or a `viewer_readonly` holder no longer sees deployment configuration history: global settings changes, user-import runs, platform-admin standing changes, and the user accounts the platform administrator creates or resets through the admin endpoints. The organization's own record history and tenant-scope settings changes are still served. A person who must read deployment configuration history needs the platform administrator's grant (`admin_full_access`); no narrower grant serves those rows. A job that exports the full ledger reads it in system context and is unaffected.

‎content/docs/permissions/record-view-auditing.mdx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,11 @@ posture, its own organization's rows), with each snapshot still narrowed by
220220
field-level security. Platform administrators hold it by default;
221221
anyone else holds it only through a permission set whose `systemPermissions`
222222
grant it. Those rows stay stored, and a system-context read still returns them.
223+
A row about no organization (its `tenant_id` empty: a global settings change, a
224+
user-import run, a platform-admin standing change, a user account created or
225+
reset through the admin endpoints) is served to the platform
226+
administrator alone, in every tenancy posture, `single` included; no other
227+
reader is served one, this capability's holders included.
223228
Rows carry the
224229
ADR-0057 `audit` lifecycle class: retained hot for
225230
90 days, then archived for seven years where an `archive` datasource is
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#26750, ruling A] The compliance ledger's deployment-level rows — rows that
5+
* carry no organization in `tenant_id` (ADR-0131 D7) — are served to the
6+
* platform administrator alone, in every tenancy posture, `single` included.
7+
* Pinned on the plugin's READ PATH, one boot per posture.
8+
*
9+
* ## Each boot
10+
*
11+
* `ObjectQLPlugin`, the `tenancy` service as AuthPlugin registers it for the
12+
* posture (its posture, whether the wall is up, and the Default Organization
13+
* under `single` alone), and `AuditPlugin`, which mounts the ledger's read
14+
* gate at `kernel:ready` — so a rule that stops being mounted fails here
15+
* exactly like a rule that was never written. The rows about an organization
16+
* are written by the real CRUD mirror; the deployment-level rows as their
17+
* writers write them: as the system, about no organization (service-settings'
18+
* GLOBAL `config_change`, plugin-security's platform-admin standing roster).
19+
*
20+
* ⛔ No security plugin, on purpose. WHICH organization's rows an organization
21+
* reader is served under a wall is the platform row policy's answer
22+
* (`sys_audit_log_org`, pinned in plugin-security's
23+
* `sys-audit-log-row-scope.test.ts`); the rule this package adds reads no
24+
* posture and no organization, so the boots below differ only in what the
25+
* posture changes about the WRITES, and the readers' answers must not.
26+
*
27+
* ## The readers
28+
*
29+
* - an organization HOLDER of the ledger audit capability (the `MEMBER`
30+
* rung), the reader the ruling is about;
31+
* - an organization ADMIN (the `TENANT_ADMIN` rung, no capability);
32+
* - the PLATFORM administrator: the `PLATFORM_ADMIN` rung, holding the
33+
* capability as `admin_full_access` grants it.
34+
*/
35+
36+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
37+
import { ObjectKernel, type Plugin } from '@objectstack/core';
38+
import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql';
39+
import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm';
40+
41+
import { AuditPlugin } from './audit-plugin.js';
42+
import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js';
43+
44+
const LEDGER = 'sys_audit_log';
45+
/** A parent object every caller reads, so the parent-record gate keeps every row about one of its records. */
46+
const NOTE = 'dlr_note';
47+
const HARNESS_PACKAGE = 'com.objectstack.audit.test.deployment-level-rows';
48+
const CAP = 'view_all_audit_log';
49+
const SYS = { isSystem: true } as const;
50+
51+
type Posture = 'single' | 'group' | 'isolated';
52+
type Row = Record<string, any>;
53+
54+
/** The deployment-level rows, as their writers insert them: as the system, with no organization. */
55+
const DEPLOYMENT_LEVEL = [
56+
{ action: 'config_change', object_name: 'sys_platform_setting', record_id: null },
57+
{ action: 'platform_admin_standing_change', object_name: 'sys_user', record_id: null },
58+
];
59+
60+
const noteObject = {
61+
name: NOTE,
62+
label: 'Note',
63+
fields: { name: { name: 'name', label: 'Name', type: 'text' as const } },
64+
};
65+
66+
/** The `tenancy` service AuthPlugin registers for `posture`, reduced to what the audit writer asks. */
67+
function tenancyFor(posture: Posture): Plugin {
68+
return {
69+
name: `test.tenancy-${posture}`,
70+
async init(ctx) {
71+
ctx.registerService('tenancy', {
72+
posture,
73+
isolationActive: posture !== 'single',
74+
defaultOrgId: async () => (posture === 'single' ? DEFAULT_ORGANIZATION_ID : null),
75+
});
76+
},
77+
} as Plugin;
78+
}
79+
80+
const key = (r: Row) => `${r.action}:${r.object_name ?? 'NULL'}@${r.tenant_id ?? 'NULL'}`;
81+
const keys = (rows: Row[]) => rows.map(key).sort();
82+
83+
describe.each(['single', 'group', 'isolated'] as const)('[#26750] deployment-level ledger rows under `%s`', (posture) => {
84+
/** The organization the readers and the note belong to: the Default Organization under `single`. */
85+
const ORG = posture === 'single' ? DEFAULT_ORGANIZATION_ID : 'org_a';
86+
const HOLDER = { userId: 'u_holder', tenantId: ORG, positions: ['org_member'], systemPermissions: [CAP], posture: 'MEMBER' as const };
87+
const ORG_ADMIN = { userId: 'u_org_admin', tenantId: ORG, positions: ['org_admin'], posture: 'TENANT_ADMIN' as const };
88+
const PLATFORM_ADMIN = { userId: 'u_platform', tenantId: ORG, positions: ['platform_admin'], systemPermissions: [CAP], posture: 'PLATFORM_ADMIN' as const };
89+
90+
let kernel: ObjectKernel;
91+
let engine: ObjectQL;
92+
let atRest: Row[] = [];
93+
let aboutTheOrganization: string[] = [];
94+
let deploymentLevel: string[] = [];
95+
96+
beforeAll(async () => {
97+
kernel = new ObjectKernel({ logger: { level: 'silent' } });
98+
await kernel.use(new ObjectQLPlugin());
99+
await kernel.use(tenancyFor(posture));
100+
await kernel.use(new AuditPlugin());
101+
await kernel.bootstrap();
102+
103+
engine = kernel.getService<ObjectQL>('objectql');
104+
const driver = new SqliteWasmDriver({ filename: ':memory:' });
105+
await driver.connect();
106+
engine.registerDriver(driver, true);
107+
engine.registry.registerObject(noteObject as any, HARNESS_PACKAGE);
108+
await engine.syncSchemas();
109+
await installDefaultOrganization(engine);
110+
111+
// The rows about the organization: the real CRUD mirror's, about a note of it.
112+
const noteId = (await engine.insert(NOTE, { name: 'note', organization_id: ORG }, { context: { ...SYS, tenantId: ORG } })).id;
113+
await engine.update(NOTE, { name: 'note, renamed' }, { where: { id: noteId }, context: { ...SYS, tenantId: ORG } });
114+
for (const row of DEPLOYMENT_LEVEL) {
115+
await engine.insert(LEDGER, { ...row, user_id: null, actor: 'svc:fixture', tenant_id: null }, { context: SYS });
116+
}
117+
118+
atRest = await engine.find(LEDGER, { context: SYS });
119+
aboutTheOrganization = atRest.filter((r) => r.object_name === NOTE).map(key).sort();
120+
deploymentLevel = atRest.filter((r) => r.tenant_id == null).map(key).sort();
121+
}, 120_000);
122+
123+
afterAll(async () => {
124+
if (kernel) await Promise.race([kernel.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]);
125+
}, 30_000);
126+
127+
it('control: the mirror stamped the organization on its rows, and the deployment-level rows carry none', () => {
128+
expect(aboutTheOrganization).toEqual([`create:${NOTE}@${ORG}`, `update:${NOTE}@${ORG}`]);
129+
expect(deploymentLevel).toEqual(DEPLOYMENT_LEVEL.map((r) => key({ ...r, tenant_id: null })).sort());
130+
expect(keys(atRest)).toEqual([...aboutTheOrganization, ...deploymentLevel].sort());
131+
});
132+
133+
it('the organization holder of the audit capability is served its organization’s rows, and no deployment-level row', async () => {
134+
const rows = await engine.find(LEDGER, { context: HOLDER });
135+
expect(keys(rows)).toEqual(aboutTheOrganization);
136+
expect(await engine.count(LEDGER, {}, { context: HOLDER })).toBe(aboutTheOrganization.length);
137+
});
138+
139+
it('the organization admin is served its organization’s rows, and no deployment-level row', async () => {
140+
expect(keys(await engine.find(LEDGER, { context: ORG_ADMIN }))).toEqual(aboutTheOrganization);
141+
});
142+
143+
it('a read that asks for the deployment-level rows by name or by id is served none of them', async () => {
144+
for (const reader of [HOLDER, ORG_ADMIN]) {
145+
expect(await engine.find(LEDGER, { where: { tenant_id: null }, context: reader })).toEqual([]);
146+
expect(await engine.count(LEDGER, { where: { action: 'platform_admin_standing_change' } }, { context: reader })).toBe(0);
147+
for (const row of atRest.filter((r) => r.tenant_id == null)) {
148+
expect(await engine.findOne(LEDGER, { where: { id: row.id }, context: reader })).toBeNull();
149+
}
150+
}
151+
});
152+
153+
it('a grouped count sees no deployment-level row', async () => {
154+
const groups = await engine.aggregate(
155+
LEDGER,
156+
{ groupBy: ['action'], aggregations: [{ function: 'count', alias: 'n' }], context: HOLDER },
157+
);
158+
expect(Object.fromEntries(groups.map((g: Row) => [g.action, Number(g.n)]))).toEqual({ create: 1, update: 1 });
159+
});
160+
161+
it('the platform administrator is served both: the organization’s rows and every deployment-level row', async () => {
162+
const rows = await engine.find(LEDGER, { context: PLATFORM_ADMIN });
163+
expect(keys(rows)).toEqual([...aboutTheOrganization, ...deploymentLevel].sort());
164+
expect(await engine.count(LEDGER, {}, { context: PLATFORM_ADMIN })).toBe(atRest.length);
165+
for (const row of atRest.filter((r) => r.tenant_id == null)) {
166+
expect((await engine.findOne(LEDGER, { where: { id: row.id }, context: PLATFORM_ADMIN }))?.id).toBe(row.id);
167+
}
168+
});
169+
});

‎packages/plugins/plugin-audit/src/audit-log-field-redaction.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import type { EngineQueryOptions } from '@objectstack/spec/data';
4848

4949
import { AuditPlugin } from './audit-plugin.js';
5050
import { redactAuditLogRows } from './audit-log-field-redaction.js';
51-
import { installDefaultOrganization } from './default-organization.testkit.js';
51+
import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js';
5252

5353
const LEDGER = 'sys_audit_log';
5454
const ITEM = 'alr_item';
@@ -186,7 +186,10 @@ describe('[#21155] sys_audit_log before/after snapshots are served through the s
186186

187187
// Rows other writers put on the ledger, in their writers' shapes: a
188188
// settings digest and an administrator roster (not a parent's field map),
189-
// and three record-write rows the mirror's own shape cannot judge.
189+
// and three record-write rows the mirror's own shape cannot judge. Each
190+
// carries the Default Organization: a row with no `tenant_id` is a
191+
// deployment-level row, served to the platform administrator alone
192+
// (#26750), and every reader here is an organization reader.
190193
const stamp = new Date().toISOString();
191194
const extra: Array<[keyof typeof rowIds, Row]> = [
192195
['config', { action: 'config_change', object_name: ITEM, new_value: JSON.stringify({ namespace: 'n', key: 'k', scope: 's', digest: 'd' }) }],
@@ -196,7 +199,11 @@ describe('[#21155] sys_audit_log before/after snapshots are served through the s
196199
['foreign', { action: 'create', object_name: 'alr_not_registered', record_id: 'x1', new_value: JSON.stringify({ any: V.foreign }) }],
197200
];
198201
for (const [key, row] of extra) {
199-
rowIds[key] = String((await engine.insert(LEDGER, { ...row, created_at: stamp }, { context: SYS })).id);
202+
rowIds[key] = String((await engine.insert(
203+
LEDGER,
204+
{ ...row, tenant_id: DEFAULT_ORGANIZATION_ID, created_at: stamp },
205+
{ context: SYS },
206+
)).id);
200207
}
201208
}, 120_000);
202209

0 commit comments

Comments
 (0)