Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/26750-ledger-deployment-level-rows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@objectstack/plugin-audit': patch
'@objectstack/spec': patch
---

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)

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.
Metadata-protocol: none

<!-- 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. -->

**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.

- **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.
- **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.
- **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.
- **The capability text.** The `view_all_audit_log` description (`PLATFORM_CAPABILITIES`, `@objectstack/spec`) gains one sentence saying the same for `single`.

**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.
5 changes: 5 additions & 0 deletions content/docs/permissions/record-view-auditing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,11 @@ posture, its own organization's rows), with each snapshot still narrowed by
field-level security. Platform administrators hold it by default;
anyone else holds it only through a permission set whose `systemPermissions`
grant it. Those rows stay stored, and a system-context read still returns them.
A row about no organization (its `tenant_id` empty: a global settings change, a
user-import run, a platform-admin standing change, a user account created or
reset through the admin endpoints) is served to the platform
administrator alone, in every tenancy posture, `single` included; no other
reader is served one, this capability's holders included.
Rows carry the
ADR-0057 `audit` lifecycle class: retained hot for
90 days, then archived for seven years where an `archive` datasource is
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#26750, ruling A] The compliance ledger's deployment-level rows — rows that
* carry no organization in `tenant_id` (ADR-0131 D7) — are served to the
* platform administrator alone, in every tenancy posture, `single` included.
* Pinned on the plugin's READ PATH, one boot per posture.
*
* ## Each boot
*
* `ObjectQLPlugin`, the `tenancy` service as AuthPlugin registers it for the
* posture (its posture, whether the wall is up, and the Default Organization
* under `single` alone), and `AuditPlugin`, which mounts the ledger's read
* gate at `kernel:ready` — so a rule that stops being mounted fails here
* exactly like a rule that was never written. The rows about an organization
* are written by the real CRUD mirror; the deployment-level rows as their
* writers write them: as the system, about no organization (service-settings'
* GLOBAL `config_change`, plugin-security's platform-admin standing roster).
*
* ⛔ No security plugin, on purpose. WHICH organization's rows an organization
* reader is served under a wall is the platform row policy's answer
* (`sys_audit_log_org`, pinned in plugin-security's
* `sys-audit-log-row-scope.test.ts`); the rule this package adds reads no
* posture and no organization, so the boots below differ only in what the
* posture changes about the WRITES, and the readers' answers must not.
*
* ## The readers
*
* - an organization HOLDER of the ledger audit capability (the `MEMBER`
* rung), the reader the ruling is about;
* - an organization ADMIN (the `TENANT_ADMIN` rung, no capability);
* - the PLATFORM administrator: the `PLATFORM_ADMIN` rung, holding the
* capability as `admin_full_access` grants it.
*/

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { ObjectKernel, type Plugin } from '@objectstack/core';
import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql';
import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm';

import { AuditPlugin } from './audit-plugin.js';
import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js';

const LEDGER = 'sys_audit_log';
/** A parent object every caller reads, so the parent-record gate keeps every row about one of its records. */
const NOTE = 'dlr_note';
const HARNESS_PACKAGE = 'com.objectstack.audit.test.deployment-level-rows';
const CAP = 'view_all_audit_log';
const SYS = { isSystem: true } as const;

type Posture = 'single' | 'group' | 'isolated';
type Row = Record<string, any>;

/** The deployment-level rows, as their writers insert them: as the system, with no organization. */
const DEPLOYMENT_LEVEL = [
{ action: 'config_change', object_name: 'sys_platform_setting', record_id: null },
{ action: 'platform_admin_standing_change', object_name: 'sys_user', record_id: null },
];

const noteObject = {
name: NOTE,
label: 'Note',
fields: { name: { name: 'name', label: 'Name', type: 'text' as const } },
};

/** The `tenancy` service AuthPlugin registers for `posture`, reduced to what the audit writer asks. */
function tenancyFor(posture: Posture): Plugin {
return {
name: `test.tenancy-${posture}`,
async init(ctx) {
ctx.registerService('tenancy', {
posture,
isolationActive: posture !== 'single',
defaultOrgId: async () => (posture === 'single' ? DEFAULT_ORGANIZATION_ID : null),
});
},
} as Plugin;
}

const key = (r: Row) => `${r.action}:${r.object_name ?? 'NULL'}@${r.tenant_id ?? 'NULL'}`;
const keys = (rows: Row[]) => rows.map(key).sort();

describe.each(['single', 'group', 'isolated'] as const)('[#26750] deployment-level ledger rows under `%s`', (posture) => {
/** The organization the readers and the note belong to: the Default Organization under `single`. */
const ORG = posture === 'single' ? DEFAULT_ORGANIZATION_ID : 'org_a';
const HOLDER = { userId: 'u_holder', tenantId: ORG, positions: ['org_member'], systemPermissions: [CAP], posture: 'MEMBER' as const };
const ORG_ADMIN = { userId: 'u_org_admin', tenantId: ORG, positions: ['org_admin'], posture: 'TENANT_ADMIN' as const };
const PLATFORM_ADMIN = { userId: 'u_platform', tenantId: ORG, positions: ['platform_admin'], systemPermissions: [CAP], posture: 'PLATFORM_ADMIN' as const };

let kernel: ObjectKernel;
let engine: ObjectQL;
let atRest: Row[] = [];
let aboutTheOrganization: string[] = [];
let deploymentLevel: string[] = [];

beforeAll(async () => {
kernel = new ObjectKernel({ logger: { level: 'silent' } });
await kernel.use(new ObjectQLPlugin());
await kernel.use(tenancyFor(posture));
await kernel.use(new AuditPlugin());
await kernel.bootstrap();

engine = kernel.getService<ObjectQL>('objectql');
const driver = new SqliteWasmDriver({ filename: ':memory:' });
await driver.connect();
engine.registerDriver(driver, true);
engine.registry.registerObject(noteObject as any, HARNESS_PACKAGE);
await engine.syncSchemas();
await installDefaultOrganization(engine);

// The rows about the organization: the real CRUD mirror's, about a note of it.
const noteId = (await engine.insert(NOTE, { name: 'note', organization_id: ORG }, { context: { ...SYS, tenantId: ORG } })).id;
await engine.update(NOTE, { name: 'note, renamed' }, { where: { id: noteId }, context: { ...SYS, tenantId: ORG } });
for (const row of DEPLOYMENT_LEVEL) {
await engine.insert(LEDGER, { ...row, user_id: null, actor: 'svc:fixture', tenant_id: null }, { context: SYS });
}

atRest = await engine.find(LEDGER, { context: SYS });
aboutTheOrganization = atRest.filter((r) => r.object_name === NOTE).map(key).sort();
deploymentLevel = atRest.filter((r) => r.tenant_id == null).map(key).sort();
}, 120_000);

afterAll(async () => {
if (kernel) await Promise.race([kernel.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]);
}, 30_000);

it('control: the mirror stamped the organization on its rows, and the deployment-level rows carry none', () => {
expect(aboutTheOrganization).toEqual([`create:${NOTE}@${ORG}`, `update:${NOTE}@${ORG}`]);
expect(deploymentLevel).toEqual(DEPLOYMENT_LEVEL.map((r) => key({ ...r, tenant_id: null })).sort());
expect(keys(atRest)).toEqual([...aboutTheOrganization, ...deploymentLevel].sort());
});

it('the organization holder of the audit capability is served its organization’s rows, and no deployment-level row', async () => {
const rows = await engine.find(LEDGER, { context: HOLDER });
expect(keys(rows)).toEqual(aboutTheOrganization);
expect(await engine.count(LEDGER, {}, { context: HOLDER })).toBe(aboutTheOrganization.length);
});

it('the organization admin is served its organization’s rows, and no deployment-level row', async () => {
expect(keys(await engine.find(LEDGER, { context: ORG_ADMIN }))).toEqual(aboutTheOrganization);
});

it('a read that asks for the deployment-level rows by name or by id is served none of them', async () => {
for (const reader of [HOLDER, ORG_ADMIN]) {
expect(await engine.find(LEDGER, { where: { tenant_id: null }, context: reader })).toEqual([]);
expect(await engine.count(LEDGER, { where: { action: 'platform_admin_standing_change' } }, { context: reader })).toBe(0);
for (const row of atRest.filter((r) => r.tenant_id == null)) {
expect(await engine.findOne(LEDGER, { where: { id: row.id }, context: reader })).toBeNull();
}
}
});

it('a grouped count sees no deployment-level row', async () => {
const groups = await engine.aggregate(
LEDGER,
{ groupBy: ['action'], aggregations: [{ function: 'count', alias: 'n' }], context: HOLDER },
);
expect(Object.fromEntries(groups.map((g: Row) => [g.action, Number(g.n)]))).toEqual({ create: 1, update: 1 });
});

it('the platform administrator is served both: the organization’s rows and every deployment-level row', async () => {
const rows = await engine.find(LEDGER, { context: PLATFORM_ADMIN });
expect(keys(rows)).toEqual([...aboutTheOrganization, ...deploymentLevel].sort());
expect(await engine.count(LEDGER, {}, { context: PLATFORM_ADMIN })).toBe(atRest.length);
for (const row of atRest.filter((r) => r.tenant_id == null)) {
expect((await engine.findOne(LEDGER, { where: { id: row.id }, context: PLATFORM_ADMIN }))?.id).toBe(row.id);
}
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import type { EngineQueryOptions } from '@objectstack/spec/data';

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

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

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

Expand Down
Loading
Loading