From 295745ea6a2229927832b5e8c3354de90422352b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 07:26:14 +0000 Subject: [PATCH 1/4] wip(plugin-security): granted_by writer measurement rig Claude-Session: https://claude.ai/code/session_01WkL6Eijt432S1Y7ekb6ovQ Co-authored-by: Claude --- .../src/granted-by-writer-provenance.test.ts | 222 ++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts diff --git a/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts b/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts new file mode 100644 index 00000000000..9f37aaa14d1 --- /dev/null +++ b/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts @@ -0,0 +1,222 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * MEASUREMENT RIG (temporary shape) — what `granted_by` stores per writer case, + * over a real `ObjectQL` engine and a real SQL driver with the real + * `SecurityPlugin` middleware (and so the real `DelegatedAdminGate`) in front. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { PermissionSetSchema } from '@objectstack/spec/security'; + +import { SecurityPlugin } from './security-plugin.js'; +import { createInvitationPlacementService } from './invitation-placement.js'; +import { reconcileOrgAdminGrant } from './auto-org-admin-grant.js'; +import { + SysPermissionSet, + SysPosition, + SysPositionPermissionSet, + SysUserPermissionSet, + SysUserPosition, +} from './objects/index.js'; + +const SYS = { context: { isSystem: true } } as never; + +const pk = { name: 'id', type: 'text' as const, primaryKey: true }; +const text = (name: string) => ({ name, type: 'text' as const }); +const inline = (name: string, fields: string[]) => ({ + name, + label: name, + fields: { id: pk, ...Object.fromEntries(fields.map((f) => [f, text(f)])) }, +}); + +const TENANT_ADMIN = PermissionSetSchema.parse({ + name: 'qa_tenant_admin', + objects: { + '*': { + allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, + viewAllRecords: true, modifyAllRecords: true, + }, + }, +}); + +const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, viewAllRecords: true }; +const DELEGATE = PermissionSetSchema.parse({ + name: 'qa_delegate', + objects: { + sys_user_permission_set: CRUD, + sys_user_position: CRUD, + sys_permission_set: { allowRead: true, viewAllRecords: true }, + sys_position: { allowRead: true, viewAllRecords: true }, + sys_user: { allowRead: true, viewAllRecords: true }, + sys_business_unit: { allowRead: true, viewAllRecords: true }, + }, + adminScope: { + businessUnit: 'east', + includeSubtree: true, + manageAssignments: true, + manageBindings: false, + authorEnvironmentSets: false, + assignablePermissionSets: ['qa_plain'], + }, +}); + +const ADMIN = 'usr_admin'; +const DELEGATE_USER = 'usr_delegate'; +const TARGET = 'usr_target'; +const FORGED = 'usr_forged'; +const ISSUER = 'usr_issuer'; + +const engines: ObjectQL[] = []; +afterEach(async () => { + while (engines.length) { + try { await engines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +async function boot() { + const engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never, + true, + ); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.granted-by-writer-provenance', + name: 'granted_by writer provenance', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [ + inline('sys_user', ['name', 'primary_business_unit_id']), + inline('sys_organization', ['name']), + inline('sys_business_unit', ['name', 'parent_business_unit_id', 'organization_id']), + inline('sys_business_unit_member', ['user_id', 'business_unit_id', 'organization_id']), + inline('sys_member', ['user_id', 'organization_id', 'role', 'created_at']), + SysPermissionSet, + SysPosition, + SysPositionPermissionSet, + SysUserPermissionSet, + SysUserPosition, + ], + } as never); + await engine.syncSchemas(); + engines.push(engine); + + await engine.insert('sys_user', [ADMIN, DELEGATE_USER, TARGET, FORGED, ISSUER].map((id) => ({ id, name: id })), SYS); + await engine.insert('sys_business_unit', [ + { id: 'bu_hq', name: 'hq', parent_business_unit_id: null }, + { id: 'bu_east', name: 'east', parent_business_unit_id: 'bu_hq' }, + ], SYS); + await engine.insert('sys_business_unit_member', [ + { id: 'bum_target', user_id: TARGET, business_unit_id: 'bu_east' }, + ], SYS); + await engine.insert('sys_permission_set', [ + { id: 'ps_plain', name: 'qa_plain', label: 'Plain', active: true }, + ], SYS); + await engine.insert('sys_position', [{ id: 'pos_rep', name: 'qa_rep', label: 'Rep', active: true }], SYS); + await engine.insert('sys_position_permission_set', [ + { id: 'pps_rep', position_id: 'pos_rep', permission_set_id: 'ps_plain' }, + ], SYS); + + const registered: Record = {}; + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (_type: string, name: string) => engine.getSchema(name) ?? null, + list: async () => [TENANT_ADMIN, DELEGATE], + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn((name: string, svc: unknown) => { registered[name] = svc; }), + hook: () => undefined, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'qa_tenant_admin' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + return { engine, registered, plugin }; +} + +const asAdmin = { userId: ADMIN, positions: [], permissions: ['qa_tenant_admin'] }; +const asDelegate = { userId: DELEGATE_USER, positions: [], permissions: ['qa_delegate'] }; + +const grantRow = (extra: Record = {}) => ({ + user_id: TARGET, permission_set_id: 'ps_plain', ...extra, +}); +const assignmentRow = (extra: Record = {}) => ({ + user_id: TARGET, position: 'qa_rep', business_unit_id: 'bu_east', ...extra, +}); + +async function stored(engine: ObjectQL, object: string, id: unknown) { + return (await engine.findOne(object, { where: { id }, context: { isSystem: true } } as never)) as any; +} + +async function attempt(p: Promise) { + return p.then((r) => ({ ok: true as const, r }), (e) => ({ ok: false as const, code: e?.code, msg: String(e?.message) })); +} + +describe('MEASURE granted_by per writer case', () => { + for (const [object, row] of [ + ['sys_user_permission_set', grantRow], + ['sys_user_position', assignmentRow], + ] as const) { + for (const [who, ctx] of [['tenant-admin', asAdmin], ['delegate', asDelegate]] as const) { + for (const explicit of [true, false]) { + it(`${object} · ${who} · ${explicit ? 'explicit granted_by' : 'no granted_by'}`, async () => { + const { engine } = await boot(); + const out = await attempt(engine.insert(object, row(explicit ? { granted_by: FORGED } : {}), { context: { ...ctx } } as never)); + const s = out.ok ? await stored(engine, object, out.r?.id) : null; + console.log(`MEASURE ${object} ${who} explicit=${explicit} ->`, JSON.stringify(out.ok ? { granted_by: s?.granted_by ?? null } : out)); + }); + } + } + + it(`${object} · system insert with a value`, async () => { + const { engine } = await boot(); + const out = await attempt(engine.insert(object, row({ granted_by: FORGED }), SYS)); + const s = out.ok ? await stored(engine, object, out.r?.id) : null; + console.log(`MEASURE ${object} system explicit=true ->`, JSON.stringify(out.ok ? { granted_by: s?.granted_by ?? null } : out)); + }); + + for (const [who, ctx] of [['tenant-admin', asAdmin], ['delegate', asDelegate]] as const) { + it(`${object} · ${who} · UPDATE granted_by`, async () => { + const { engine } = await boot(); + const created = await engine.insert(object, row({ granted_by: ISSUER }), SYS); + const out = await attempt(engine.update(object, { granted_by: FORGED }, { where: { id: (created as any).id }, context: { ...ctx } } as never)); + const s = await stored(engine, object, (created as any).id); + console.log(`MEASURE ${object} ${who} UPDATE ->`, JSON.stringify({ outcome: out.ok ? 'landed' : out, granted_by: s?.granted_by ?? null })); + }); + } + } + + it('invitation placement (system) apply', async () => { + const { engine, registered } = await boot(); + const svc: any = Object.values(registered).find((s: any) => s && typeof s.apply === 'function'); + const res = await svc.apply({ intent: { businessUnitId: 'bu_east', positions: ['qa_rep'] }, userId: TARGET, grantedBy: ISSUER }); + const rows = await engine.find('sys_user_position', { where: { user_id: TARGET }, context: { isSystem: true } } as never) as any[]; + console.log('MEASURE invitation-placement ->', JSON.stringify({ res, granted_by: rows.map((r) => r.granted_by) })); + }); + + it('auto-org-admin reconcile (system) with attributed human', async () => { + const { engine } = await boot(); + await engine.insert('sys_permission_set', [ + { id: 'ps_oa', name: 'organization_admin', label: 'OA', active: true }, + { id: 'ps_oa_nb', name: 'organization_admin_no_bypass', label: 'OA nb', active: true }, + ], SYS); + await engine.insert('sys_member', { id: 'm1', user_id: TARGET, organization_id: 'o1', role: 'owner', created_at: new Date().toISOString() }, SYS); + const res = await reconcileOrgAdminGrant(engine, TARGET, 'o1', { posture: 'single', attributedUserId: ISSUER }); + const rows = await engine.find('sys_user_permission_set', { where: { user_id: TARGET }, context: { isSystem: true } } as never) as any[]; + console.log('MEASURE auto-org-admin ->', JSON.stringify({ res, granted_by: rows.map((r) => r.granted_by) })); + }); +}); + +void createInvitationPlacementService; +void expect; From 2296ab1c751bd789be86af9d2d20cae37390a4ff Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 07:33:44 +0000 Subject: [PATCH 2/4] =?UTF-8?q?fix(plugin-security):=20granted=5Fby=20is?= =?UTF-8?q?=20provenance=20=E2=80=94=20readonly,=20and=20the=20delegated-a?= =?UTF-8?q?dmin=20gate=20stamps=20the=20writer=20on=20every=20non-system?= =?UTF-8?q?=20insert?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01WkL6Eijt432S1Y7ekb6ovQ Co-authored-by: Claude --- .../src/delegated-admin-gate.ts | 64 ++++++++++++++----- .../src/granted-by-writer-provenance.test.ts | 11 ++-- .../objects/sys-user-permission-set.object.ts | 9 +++ .../src/objects/sys-user-position.object.ts | 8 +++ 4 files changed, 71 insertions(+), 21 deletions(-) diff --git a/packages/plugins/plugin-security/src/delegated-admin-gate.ts b/packages/plugins/plugin-security/src/delegated-admin-gate.ts index 8fb102aff56..8fb5c414ec3 100644 --- a/packages/plugins/plugin-security/src/delegated-admin-gate.ts +++ b/packages/plugins/plugin-security/src/delegated-admin-gate.ts @@ -148,6 +148,40 @@ const GOVERNED_OBJECTS = new Set([ const GOVERNED_OPERATIONS = new Set(['insert', 'update', 'delete', 'transfer', 'restore', 'purge']); const ANCHOR_POSITIONS = new Set(['everyone', 'guest']); +/** + * The governed objects whose rows record their writer in `granted_by` — a + * `readonly` provenance column on both (ADR-0090 D12's dual audit: `granted_by` + * = writer, `delegated_from` = authority source, `reason` = why). + * + * The writer is the value, so a caller does not get to name one: every + * non-system insert that this gate admits is stamped with its own `userId`, + * whatever the payload carried — tenant-level admins, delegates and + * self-delegations alike. The stamp is assigned in place on the payload rows + * BEFORE the engine's insert pipeline snapshots them; the engine's create-side + * `readonly` strip does not judge `sys_` objects, so the stamp is what lands. + * A non-system UPDATE gets no stamp: the column is `readonly`, so the engine's + * update strip drops a caller's value and the row keeps its writer. + * + * System writers never reach this gate (`isSystem` short-circuits the security + * middleware first) and keep the id or null they wrote: invitation placement + * writes its issuer, the organization-admin reconcile the attributed human or + * null, the platform-admin promotion null (ADR-0118 D1 — never a sentinel). + */ +const GRANTED_BY_OBJECTS = new Set(['sys_user_position', 'sys_user_permission_set']); + +/** + * Stamp the writer into `granted_by` on every row of an admitted non-system + * insert into a {@link GRANTED_BY_OBJECTS} table. Unconditional on purpose: + * keeping a supplied value would let a caller name any user as the granter. + */ +function stampWriter(opCtx: any, userId: unknown): void { + if (opCtx?.operation !== 'insert' || !GRANTED_BY_OBJECTS.has(opCtx?.object)) return; + if (userId == null || userId === '') return; + for (const row of rowsOf(opCtx)) { + if (row && typeof row === 'object') row.granted_by = userId; + } +} + export interface DelegatedAdminGateDeps { /** ObjectQL engine handle (system-context reads for pre-images/lookups). */ ql: any; @@ -242,6 +276,14 @@ export class DelegatedAdminGate { if (!GOVERNED_OBJECTS.has(opCtx?.object)) return; if (!GOVERNED_OPERATIONS.has(opCtx?.operation)) return; + // Authority first: a refused write throws here and is never stamped. + await this.authorize(opCtx); + // Then provenance, on every admitted path — see {@link GRANTED_BY_OBJECTS}. + stampWriter(opCtx, opCtx.context?.userId); + } + + /** The authority decision for a governed write: returns when admitted, throws when refused. */ + private async authorize(opCtx: any): Promise { const ctx = opCtx.context ?? {}; // Every business-unit anchor this call resolves is resolved in the // caller's own organization — see {@link callerOrganizationId}. @@ -346,9 +388,9 @@ export class DelegatedAdminGate { switch (opCtx.object) { case 'sys_user_position': - return this.assertAssignmentWrite(opCtx, ctx, held, organizationId); + return this.assertAssignmentWrite(opCtx, held, organizationId); case 'sys_user_permission_set': - return this.assertDirectGrantWrite(opCtx, ctx, held); + return this.assertDirectGrantWrite(opCtx, held); case 'sys_position_permission_set': return this.assertBindingWrite(opCtx, held); case 'sys_permission_set': @@ -536,8 +578,9 @@ export class DelegatedAdminGate { * 7. [cloud#830 follow-up] if the delegation carries a `business_unit_id` * anchor, that anchor falls inside the delegator's OWN effective anchor * for the position — a delegation may NARROW visibility, never widen it. - * The writer is stamped into `granted_by` (dual audit: `granted_by` = writer, - * `delegated_from` = authority source). + * The writer is stamped into `granted_by` by {@link DelegatedAdminGate.assert} + * once this returns (dual audit: `granted_by` = writer, `delegated_from` = + * authority source). */ private async assertSelfDelegation(opCtx: any, ctx: any, organizationId?: string): Promise { const now = this.now(); @@ -640,9 +683,6 @@ export class DelegatedAdminGate { deny(`position '${positionName}' distributes the admin set '${b.name}' — administration cannot be self-delegated (D12 containment)`, { position: positionName, permissionSet: b.name }); } } - - // Dual audit: stamp the writer (never overwrite an explicit value). - if (row.granted_by == null) row.granted_by = ctx.userId; } } @@ -737,7 +777,6 @@ export class DelegatedAdminGate { private async assertAssignmentWrite( opCtx: any, - ctx: any, held: HeldScope[], organizationId?: string, ): Promise { @@ -777,16 +816,12 @@ export class DelegatedAdminGate { { operation: opCtx.operation, object: opCtx.object, position: positionName }, ); } - // Audit stamp: who granted this (insert only; never overwrite an explicit value). - if (opCtx.operation === 'insert' && t.next && t.next.granted_by == null && ctx.userId) { - t.next.granted_by = ctx.userId; - } } } // ── sys_user_permission_set: direct user ↔ set grants ─────────────── - private async assertDirectGrantWrite(opCtx: any, ctx: any, held: HeldScope[]): Promise { + private async assertDirectGrantWrite(opCtx: any, held: HeldScope[]): Promise { const targets = await this.materializeTargets(opCtx, 'sys_user_permission_set'); for (const t of targets) { const row = t.next ?? t.prev ?? {}; @@ -817,9 +852,6 @@ export class DelegatedAdminGate { { operation: opCtx.operation, object: opCtx.object, permissionSet: setName }, ); } - if (opCtx.operation === 'insert' && t.next && t.next.granted_by == null && ctx.userId) { - t.next.granted_by = ctx.userId; - } } } diff --git a/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts b/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts index 9f37aaa14d1..de856499790 100644 --- a/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts +++ b/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts @@ -13,7 +13,6 @@ import { PermissionSetSchema } from '@objectstack/spec/security'; import { SecurityPlugin } from './security-plugin.js'; import { createInvitationPlacementService } from './invitation-placement.js'; -import { reconcileOrgAdminGrant } from './auto-org-admin-grant.js'; import { SysPermissionSet, SysPosition, @@ -42,6 +41,8 @@ const TENANT_ADMIN = PermissionSetSchema.parse({ }, }); +const MEMBER = PermissionSetSchema.parse({ name: 'qa_member', objects: {} }); + const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, viewAllRecords: true }; const DELEGATE = PermissionSetSchema.parse({ name: 'qa_delegate', @@ -127,7 +128,7 @@ async function boot() { objectql: engine, metadata: { get: async (_type: string, name: string) => engine.getSchema(name) ?? null, - list: async () => [TENANT_ADMIN, DELEGATE], + list: async () => [MEMBER, TENANT_ADMIN, DELEGATE], }, }; const ctx = { @@ -139,7 +140,7 @@ async function boot() { return services[name]; }, }; - const plugin = new SecurityPlugin({ fallbackPermissionSet: 'qa_tenant_admin' }); + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'qa_member' }); await plugin.init(ctx as never); await plugin.start(ctx as never); return { engine, registered, plugin }; @@ -211,8 +212,8 @@ describe('MEASURE granted_by per writer case', () => { { id: 'ps_oa', name: 'organization_admin', label: 'OA', active: true }, { id: 'ps_oa_nb', name: 'organization_admin_no_bypass', label: 'OA nb', active: true }, ], SYS); - await engine.insert('sys_member', { id: 'm1', user_id: TARGET, organization_id: 'o1', role: 'owner', created_at: new Date().toISOString() }, SYS); - const res = await reconcileOrgAdminGrant(engine, TARGET, 'o1', { posture: 'single', attributedUserId: ISSUER }); + await engine.insert('sys_member', { id: 'm1', user_id: TARGET, organization_id: 'o1', role: 'owner', created_at: new Date().toISOString() }, { context: { isSystem: true, attributedUserId: ISSUER } } as never); + const res = 'via-middleware'; const rows = await engine.find('sys_user_permission_set', { where: { user_id: TARGET }, context: { isSystem: true } } as never) as any[]; console.log('MEASURE auto-org-admin ->', JSON.stringify({ res, granted_by: rows.map((r) => r.granted_by) })); }); diff --git a/packages/plugins/plugin-security/src/objects/sys-user-permission-set.object.ts b/packages/plugins/plugin-security/src/objects/sys-user-permission-set.object.ts index 77b6c486454..2bed0a5ade9 100644 --- a/packages/plugins/plugin-security/src/objects/sys-user-permission-set.object.ts +++ b/packages/plugins/plugin-security/src/objects/sys-user-permission-set.object.ts @@ -102,9 +102,18 @@ export const SysUserPermissionSet = ObjectSchema.create({ description: 'Optional organization scope. NULL = applies in every org context.', }), + // Provenance, not a business link: the platform writes it, a caller does + // not. A non-system insert is stamped with its writer by the + // DelegatedAdminGate whatever the payload carried, and a system writer + // (the organization-admin reconcile, the platform-admin promotion) keeps + // the id or null it wrote (ADR-0118 D1 — never a sentinel). `readonly` + // makes the update strip drop a non-system caller's value, and it is what + // files a granter that no longer resolves under the integrity audit's + // `provenance` bucket rather than as a broken business reference. granted_by: Field.lookup('sys_user', { label: 'Granted By', required: false, + readonly: true, description: 'User who granted this permission set.', }), diff --git a/packages/plugins/plugin-security/src/objects/sys-user-position.object.ts b/packages/plugins/plugin-security/src/objects/sys-user-position.object.ts index d2332104435..9df5977a917 100644 --- a/packages/plugins/plugin-security/src/objects/sys-user-position.object.ts +++ b/packages/plugins/plugin-security/src/objects/sys-user-position.object.ts @@ -103,9 +103,17 @@ export const SysUserPosition = ObjectSchema.create({ description: 'Tenant that owns this assignment; null = global (cross-tenant).', }), + // Provenance, not a business link — the same contract as + // `sys_user_permission_set.granted_by`: a non-system insert is stamped + // with its writer by the DelegatedAdminGate whatever the payload carried, + // a system writer (invitation placement) keeps the issuer it wrote, and + // `readonly` keeps a non-system update from rewriting it and files a + // granter that no longer resolves under the integrity audit's `provenance` + // bucket. granted_by: Field.lookup('sys_user', { label: 'Granted By', required: false, + readonly: true, description: 'User who granted this position assignment (stamped by the delegated-admin gate for delegate writes).', }), From c52e189600a8add6ce1adc3dc77855192269a3c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 07:39:01 +0000 Subject: [PATCH 3/4] test(plugin-security): pin granted_by as the writer per writer case, and as audit provenance; changeset Claude-Session: https://claude.ai/code/session_01WkL6Eijt432S1Y7ekb6ovQ Co-authored-by: Claude --- .changeset/22201-granted-by-provenance.md | 26 ++ .../src/delegated-admin-gate.test.ts | 71 ++++- .../src/granted-by-writer-provenance.test.ts | 292 ++++++++++++------ 3 files changed, 288 insertions(+), 101 deletions(-) create mode 100644 .changeset/22201-granted-by-provenance.md diff --git a/.changeset/22201-granted-by-provenance.md b/.changeset/22201-granted-by-provenance.md new file mode 100644 index 00000000000..906d2af670e --- /dev/null +++ b/.changeset/22201-granted-by-provenance.md @@ -0,0 +1,26 @@ +--- +'@objectstack/plugin-security': minor +--- + +fix(plugin-security)!: `granted_by` on the grant tables is provenance: the platform stamps the writer, and a non-system caller can no longer name the granter + +Clause-②: no (narrowing) + + + +**BREAKING** accept-set narrowing, shipped as `minor` under the repo's launch-window convention for breaking changes. + +`granted_by` records who wrote a grant. The platform already treated it that way: the delegated-admin gate stamped the writer, and the organization-admin reconcile writes the attributed human or null (ADR-0118 D1, an id or null and never a sentinel). But the column was a plain lookup, so a non-system caller could store any existing user as the granter, and the integrity audit filed a granter that no longer resolves as a broken business reference, which raised its `[integrity] stored references that resolve to nothing` warning on every run. + +**What moves for consumers.** + +- **Non-system inserts store the writer.** The delegated-admin gate now stamps the caller's user id into `granted_by` on every `sys_user_permission_set` and `sys_user_position` insert it admits, whatever the payload carried. A tenant-level admin's insert and a delegate's insert are stamped alike. Before, a supplied value was stored as sent, and a tenant-level admin's insert that supplied none stored `null`. +- **Non-system updates cannot change it.** Both columns are now `readonly: true`, so the engine's update strip drops a caller's `granted_by` and the row keeps its granter. Before, the update landed. A caller that passes `strictReadonlyWrites` is refused instead, as for every read-only column. +- **The integrity audit files it as provenance.** A `granted_by` that names a user who no longer exists is reported under the audit's `provenance` bucket, which does not raise the warning. A business reference that resolves to nothing is reported under `dangling` and warns, as before. + +**Unchanged.** + +- System-context writers keep the value they write: invitation placement stamps the issuer, the organization-admin reconcile stamps the attributed human or `null`, and the platform-admin promotion writes `null`. A server-side writer that must record someone other than its caller writes under a system context, as these do. +- Who may write a grant, and what a grant gives, are unchanged. The gate's authority decision runs first; a refused write is not stamped. +- Stored rows are not rewritten, and no stored row is refused on read. A row whose `granted_by` already names someone else, or holds a value that names no user, keeps it. +- `sys_record_share.granted_by` (plugin-sharing) is unchanged: its only writer is the sharing service, which already stamps the acting user under a system context. diff --git a/packages/plugins/plugin-security/src/delegated-admin-gate.test.ts b/packages/plugins/plugin-security/src/delegated-admin-gate.test.ts index 22151556204..b83e54f1dab 100644 --- a/packages/plugins/plugin-security/src/delegated-admin-gate.test.ts +++ b/packages/plugins/plugin-security/src/delegated-admin-gate.test.ts @@ -112,7 +112,7 @@ const insertAssignment = (ctx: any, row: any) => h.gate.assert({ }); describe('DelegatedAdminGate — tenant admins and outsiders', () => { - it('tenant-level admin (superuser wildcard) passes untouched', async () => { + it('tenant-level admin (superuser wildcard) passes — the ordinary CRUD/RLS checks decide', async () => { await expect(insertAssignment(h.ctxOf('tenant_admin'), { user_id: 'u_west_1', position: 'mixed_pos', business_unit_id: 'bu_west', })).resolves.toBeUndefined(); @@ -979,3 +979,72 @@ describe('DelegatedAdminGate — a position is picked by organization, not by ar })).rejects.toThrow(/position 'closer' distributes permission set 'finance_user', which is not in the scope's allowlist/); }); }); + +// ── granted_by is the writer on every admitted insert ───────────────────── +// +// `granted_by` is provenance (`readonly` on both grant tables): the gate stamps +// the writer on every non-system insert it admits, whatever the payload +// carried — a caller-supplied granter is overwritten, not kept, and a +// tenant-level admin's grant is stamped too. What is stored on the real engine +// is pinned in `granted-by-writer-provenance.test.ts`; this block pins the +// gate's own half, path by path. +describe('DelegatedAdminGate — granted_by is the writer on every admitted insert', () => { + const grantRow = (extra: Record = {}): any => ({ user_id: 'u_east_1', permission_set_id: 'ps_sales', ...extra }); + const assignmentRow = (extra: Record = {}): any => ({ user_id: 'u_east_1', position: 'sales_rep', business_unit_id: 'bu_es', ...extra }); + + for (const [object, row] of [ + ['sys_user_position', assignmentRow], + ['sys_user_permission_set', grantRow], + ] as const) { + for (const principal of ['tenant_admin', 'delegate'] as const) { + it(`${object}: ${principal} naming another user as granter is stamped with the writer`, async () => { + const data = row({ granted_by: 'u_west_1' }); + await expect(h.gate.assert({ object, operation: 'insert', data, context: h.ctxOf(principal) })).resolves.toBeUndefined(); + expect(data.granted_by).toBe(`u_${principal}`); + }); + + it(`${object}: ${principal} naming no granter is stamped with the writer`, async () => { + const data = row(); + await expect(h.gate.assert({ object, operation: 'insert', data, context: h.ctxOf(principal) })).resolves.toBeUndefined(); + expect(data.granted_by).toBe(`u_${principal}`); + }); + } + + it(`${object}: every row of a batch insert is stamped`, async () => { + const data = [row({ granted_by: 'u_west_1' }), row()]; + await expect(h.gate.assert({ object, operation: 'insert', data, context: h.ctxOf('tenant_admin') })).resolves.toBeUndefined(); + expect(data.map((r: any) => r.granted_by)).toEqual(['u_tenant_admin', 'u_tenant_admin']); + }); + + it(`${object}: a refused insert is not stamped`, async () => { + const data = row({ granted_by: 'u_west_1' }); + await expect(h.gate.assert({ object, operation: 'insert', data, context: h.ctxOf('crud_only') })).rejects.toThrow(/delegated adminScope/); + expect(data.granted_by).toBe('u_west_1'); + }); + + it(`${object}: an update is not stamped — the column is readonly, so the engine's update strip owns it`, async () => { + const data = { id: 'a_prev', granted_by: 'u_west_1' }; + await expect(h.gate.assert({ object, operation: 'update', data, context: h.ctxOf('tenant_admin') })).resolves.toBeUndefined(); + expect(data.granted_by).toBe('u_west_1'); + }); + } + + it('a self-delegation naming another user as granter is stamped with the delegator', async () => { + const d = makeDelegationHarness(); + const row: any = { + user_id: 'u_deleg', position: 'approver', delegated_from: 'u_boss', valid_until: iso(T0 + 10 * DAY), + reason: 'vacation stand-in', granted_by: 'u_relay', + }; + await expect(d.delegate('u_boss', row)).resolves.toBeUndefined(); + expect(row.granted_by).toBe('u_boss'); + }); + + it('a governed object with no granted_by column is never given one', async () => { + const member: any = { user_id: 'u_x', organization_id: 'org_1', role: 'admin' }; + await expect(h.gate.assert({ object: 'sys_member', operation: 'insert', data: member, context: h.ctxOf('tenant_admin') })).resolves.toBeUndefined(); + const binding: any = { position_id: 'pos_sales', permission_set_id: 'ps_sales' }; + await expect(h.gate.assert({ object: 'sys_position_permission_set', operation: 'insert', data: binding, context: h.ctxOf('tenant_admin') })).resolves.toBeUndefined(); + expect('granted_by' in member).toBe(false); + expect('granted_by' in binding).toBe(false); + }); +}); diff --git a/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts b/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts index de856499790..6a6185b8c19 100644 --- a/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts +++ b/packages/plugins/plugin-security/src/granted-by-writer-provenance.test.ts @@ -1,9 +1,37 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * MEASUREMENT RIG (temporary shape) — what `granted_by` stores per writer case, - * over a real `ObjectQL` engine and a real SQL driver with the real - * `SecurityPlugin` middleware (and so the real `DelegatedAdminGate`) in front. + * `granted_by` on the two grant tables (`sys_user_permission_set`, + * `sys_user_position`) is PROVENANCE — the user who wrote the grant — and is + * pinned here as what is STORED, over a real `ObjectQL` engine and a real SQL + * driver with the real `SecurityPlugin` middleware (and so the real + * `DelegatedAdminGate`) in front of it. + * + * ## The contract, per writer case + * + * - A NON-SYSTEM insert stores its writer, whatever the payload carried: a + * tenant-level admin and a scoped delegate alike, with a `granted_by` naming + * another existing user or with none. Before this, a supplied value was + * stored as sent on both paths, and a tenant-level admin's grant with none + * stored `null`. + * - A SYSTEM writer keeps the value it wrote: a plain system insert (the path + * the platform-admin promotion takes), invitation placement (the issuer), + * and the organization-admin reconcile (the attributed human). + * - A NON-SYSTEM update cannot rewrite it: the column is `readonly`, so the + * engine's update strip drops the caller's value and the row keeps its + * writer. Before this, the update landed. + * - The integrity audit files a granter that resolves to nothing under + * `provenance`, where it raises no warning. A business lookup that resolves + * to nothing on the same row is the positive control: it still lands in + * `dangling` and still warns. + * + * ## Why the stamp lives in the gate and survives + * + * The gate is engine middleware and assigns `granted_by` in place on the + * payload rows. The engine's create-side static `readonly` strip does not + * judge `sys_` objects, so on insert the stamp is what lands; the update strip + * does judge them, which is what closes the update door. Both are measured + * below rather than assumed. */ import { describe, it, expect, vi, afterEach } from 'vitest'; @@ -12,7 +40,7 @@ import { SqlDriver } from '@objectstack/driver-sql'; import { PermissionSetSchema } from '@objectstack/spec/security'; import { SecurityPlugin } from './security-plugin.js'; -import { createInvitationPlacementService } from './invitation-placement.js'; +import { INVITATION_PLACEMENT_SERVICE, type InvitationPlacementService } from './invitation-placement.js'; import { SysPermissionSet, SysPosition, @@ -25,12 +53,17 @@ const SYS = { context: { isSystem: true } } as never; const pk = { name: 'id', type: 'text' as const, primaryKey: true }; const text = (name: string) => ({ name, type: 'text' as const }); +/** A minimal stand-in for an object this package does not ship. */ const inline = (name: string, fields: string[]) => ({ name, label: name, fields: { id: pk, ...Object.fromEntries(fields.map((f) => [f, text(f)])) }, }); +/** The baseline every caller holds: nothing. */ +const MEMBER = PermissionSetSchema.parse({ name: 'qa_member', objects: {} }); + +/** ADR-0066 tenant-level admin: the superuser wildcard. */ const TENANT_ADMIN = PermissionSetSchema.parse({ name: 'qa_tenant_admin', objects: { @@ -41,18 +74,18 @@ const TENANT_ADMIN = PermissionSetSchema.parse({ }, }); -const MEMBER = PermissionSetSchema.parse({ name: 'qa_member', objects: {} }); - const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, viewAllRecords: true }; +const READ = { allowRead: true, viewAllRecords: true }; +/** ADR-0090 D12 delegate: may assign `qa_plain` inside the `east` subtree. */ const DELEGATE = PermissionSetSchema.parse({ name: 'qa_delegate', objects: { sys_user_permission_set: CRUD, sys_user_position: CRUD, - sys_permission_set: { allowRead: true, viewAllRecords: true }, - sys_position: { allowRead: true, viewAllRecords: true }, - sys_user: { allowRead: true, viewAllRecords: true }, - sys_business_unit: { allowRead: true, viewAllRecords: true }, + sys_permission_set: READ, + sys_position: READ, + sys_user: READ, + sys_business_unit: READ, }, adminScope: { businessUnit: 'east', @@ -67,8 +100,11 @@ const DELEGATE = PermissionSetSchema.parse({ const ADMIN = 'usr_admin'; const DELEGATE_USER = 'usr_delegate'; const TARGET = 'usr_target'; -const FORGED = 'usr_forged'; +/** An existing user a caller names as the granter — not the writer. */ +const OTHER = 'usr_other'; const ISSUER = 'usr_issuer'; +/** A granter id with no `sys_user` row: a deleted user, as the audit sees one. */ +const GONE = 'usr_gone'; const engines: ObjectQL[] = []; afterEach(async () => { @@ -77,8 +113,15 @@ afterEach(async () => { } }); -async function boot() { - const engine = new ObjectQL(); +interface Rig { + engine: ObjectQL; + warn: ReturnType; + placement: InvitationPlacementService | undefined; +} + +async function boot(opts: { security: boolean } = { security: true }): Promise { + const warn = vi.fn(); + const engine = new ObjectQL({ logger: { info: vi.fn(), warn, error: vi.fn(), debug: vi.fn() } } as never); engine.registerDriver( new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never, true, @@ -106,118 +149,167 @@ async function boot() { await engine.syncSchemas(); engines.push(engine); - await engine.insert('sys_user', [ADMIN, DELEGATE_USER, TARGET, FORGED, ISSUER].map((id) => ({ id, name: id })), SYS); + // Fixture rows go in past the middleware: setup is not the subject. + await engine.insert('sys_user', [ADMIN, DELEGATE_USER, TARGET, OTHER, ISSUER].map((id) => ({ id, name: id })), SYS); await engine.insert('sys_business_unit', [ { id: 'bu_hq', name: 'hq', parent_business_unit_id: null }, { id: 'bu_east', name: 'east', parent_business_unit_id: 'bu_hq' }, ], SYS); - await engine.insert('sys_business_unit_member', [ - { id: 'bum_target', user_id: TARGET, business_unit_id: 'bu_east' }, - ], SYS); + await engine.insert('sys_business_unit_member', [{ id: 'bum_target', user_id: TARGET, business_unit_id: 'bu_east' }], SYS); await engine.insert('sys_permission_set', [ { id: 'ps_plain', name: 'qa_plain', label: 'Plain', active: true }, + { id: 'ps_oa', name: 'organization_admin', label: 'Organization admin', active: true }, + { id: 'ps_oa_nb', name: 'organization_admin_no_bypass', label: 'Organization admin (no bypass)', active: true }, ], SYS); await engine.insert('sys_position', [{ id: 'pos_rep', name: 'qa_rep', label: 'Rep', active: true }], SYS); - await engine.insert('sys_position_permission_set', [ - { id: 'pps_rep', position_id: 'pos_rep', permission_set_id: 'ps_plain' }, - ], SYS); + await engine.insert('sys_position_permission_set', [{ id: 'pps_rep', position_id: 'pos_rep', permission_set_id: 'ps_plain' }], SYS); - const registered: Record = {}; - const services: Record = { - manifest: { register: vi.fn() }, - objectql: engine, - metadata: { - get: async (_type: string, name: string) => engine.getSchema(name) ?? null, - list: async () => [MEMBER, TENANT_ADMIN, DELEGATE], - }, - }; - const ctx = { - logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, - registerService: vi.fn((name: string, svc: unknown) => { registered[name] = svc; }), - hook: () => undefined, - getService: (name: string) => { - if (!(name in services)) throw new Error(`service not registered: ${name}`); - return services[name]; - }, - }; - const plugin = new SecurityPlugin({ fallbackPermissionSet: 'qa_member' }); - await plugin.init(ctx as never); - await plugin.start(ctx as never); - return { engine, registered, plugin }; + let placement: InvitationPlacementService | undefined; + if (opts.security) { + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (_type: string, name: string) => engine.getSchema(name) ?? null, + list: async () => [MEMBER, TENANT_ADMIN, DELEGATE], + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn((name: string, svc: unknown) => { + if (name === INVITATION_PLACEMENT_SERVICE) placement = svc as InvitationPlacementService; + }), + hook: () => undefined, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'qa_member' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + } + return { engine, warn, placement }; } -const asAdmin = { userId: ADMIN, positions: [], permissions: ['qa_tenant_admin'] }; -const asDelegate = { userId: DELEGATE_USER, positions: [], permissions: ['qa_delegate'] }; +const CALLERS = { + 'a tenant-level admin': { userId: ADMIN, positions: [], permissions: ['qa_tenant_admin'] }, + 'a scoped delegate': { userId: DELEGATE_USER, positions: [], permissions: ['qa_delegate'] }, +} as const; -const grantRow = (extra: Record = {}) => ({ - user_id: TARGET, permission_set_id: 'ps_plain', ...extra, -}); -const assignmentRow = (extra: Record = {}) => ({ - user_id: TARGET, position: 'qa_rep', business_unit_id: 'bu_east', ...extra, -}); +/** Each grant table, and a row on it every caller above may write. */ +const TABLES = { + sys_user_permission_set: (extra: Record = {}) => ({ + user_id: TARGET, permission_set_id: 'ps_plain', ...extra, + }), + sys_user_position: (extra: Record = {}) => ({ + user_id: TARGET, position: 'qa_rep', business_unit_id: 'bu_east', ...extra, + }), +} as const; -async function stored(engine: ObjectQL, object: string, id: unknown) { - return (await engine.findOne(object, { where: { id }, context: { isSystem: true } } as never)) as any; +async function storedGrantedBy(engine: ObjectQL, object: string, id: unknown): Promise { + const row = (await engine.findOne(object, { where: { id }, context: { isSystem: true } } as never)) as any; + expect(row, `${object}#${String(id)} was not stored`).toBeTruthy(); + return row.granted_by ?? null; } -async function attempt(p: Promise) { - return p.then((r) => ({ ok: true as const, r }), (e) => ({ ok: false as const, code: e?.code, msg: String(e?.message) })); -} +describe('granted_by — a non-system insert stores its writer', () => { + for (const [object, row] of Object.entries(TABLES)) { + for (const [who, caller] of Object.entries(CALLERS)) { + it(`${object}: ${who} naming ANOTHER user as granter stores the writer`, async () => { + const { engine } = await boot(); + const created: any = await engine.insert(object, row({ granted_by: OTHER }), { context: { ...caller } } as never); + expect(await storedGrantedBy(engine, object, created.id)).toBe(caller.userId); + }); -describe('MEASURE granted_by per writer case', () => { - for (const [object, row] of [ - ['sys_user_permission_set', grantRow], - ['sys_user_position', assignmentRow], - ] as const) { - for (const [who, ctx] of [['tenant-admin', asAdmin], ['delegate', asDelegate]] as const) { - for (const explicit of [true, false]) { - it(`${object} · ${who} · ${explicit ? 'explicit granted_by' : 'no granted_by'}`, async () => { - const { engine } = await boot(); - const out = await attempt(engine.insert(object, row(explicit ? { granted_by: FORGED } : {}), { context: { ...ctx } } as never)); - const s = out.ok ? await stored(engine, object, out.r?.id) : null; - console.log(`MEASURE ${object} ${who} explicit=${explicit} ->`, JSON.stringify(out.ok ? { granted_by: s?.granted_by ?? null } : out)); - }); - } + it(`${object}: ${who} naming no granter stores the writer`, async () => { + const { engine } = await boot(); + const created: any = await engine.insert(object, row(), { context: { ...caller } } as never); + expect(await storedGrantedBy(engine, object, created.id)).toBe(caller.userId); + }); } + } +}); - it(`${object} · system insert with a value`, async () => { +describe('granted_by — a system writer keeps the value it wrote', () => { + for (const [object, row] of Object.entries(TABLES)) { + it(`${object}: a system-context insert stores its own value (the platform-admin promotion's path)`, async () => { const { engine } = await boot(); - const out = await attempt(engine.insert(object, row({ granted_by: FORGED }), SYS)); - const s = out.ok ? await stored(engine, object, out.r?.id) : null; - console.log(`MEASURE ${object} system explicit=true ->`, JSON.stringify(out.ok ? { granted_by: s?.granted_by ?? null } : out)); + const created: any = await engine.insert(object, row({ granted_by: OTHER }), SYS); + expect(await storedGrantedBy(engine, object, created.id)).toBe(OTHER); }); - - for (const [who, ctx] of [['tenant-admin', asAdmin], ['delegate', asDelegate]] as const) { - it(`${object} · ${who} · UPDATE granted_by`, async () => { - const { engine } = await boot(); - const created = await engine.insert(object, row({ granted_by: ISSUER }), SYS); - const out = await attempt(engine.update(object, { granted_by: FORGED }, { where: { id: (created as any).id }, context: { ...ctx } } as never)); - const s = await stored(engine, object, (created as any).id); - console.log(`MEASURE ${object} ${who} UPDATE ->`, JSON.stringify({ outcome: out.ok ? 'landed' : out, granted_by: s?.granted_by ?? null })); - }); - } } - it('invitation placement (system) apply', async () => { - const { engine, registered } = await boot(); - const svc: any = Object.values(registered).find((s: any) => s && typeof s.apply === 'function'); - const res = await svc.apply({ intent: { businessUnitId: 'bu_east', positions: ['qa_rep'] }, userId: TARGET, grantedBy: ISSUER }); - const rows = await engine.find('sys_user_position', { where: { user_id: TARGET }, context: { isSystem: true } } as never) as any[]; - console.log('MEASURE invitation-placement ->', JSON.stringify({ res, granted_by: rows.map((r) => r.granted_by) })); + it('invitation placement stores the issuer on the assignment it applies', async () => { + const { engine, placement } = await boot(); + expect(placement, 'the SecurityPlugin registers the invitation placement service').toBeTruthy(); + const res = await placement!.apply({ + intent: { businessUnitId: 'bu_east', positions: ['qa_rep'] }, + userId: TARGET, + grantedBy: ISSUER, + }); + expect(res).toEqual({ created: 1, skipped: 0 }); + const rows = (await engine.find('sys_user_position', { where: { user_id: TARGET }, context: { isSystem: true } } as never)) as any[]; + expect(rows.map((r) => r.granted_by)).toEqual([ISSUER]); }); - it('auto-org-admin reconcile (system) with attributed human', async () => { + it('the organization-admin reconcile stores the human its membership write was attributed to', async () => { const { engine } = await boot(); - await engine.insert('sys_permission_set', [ - { id: 'ps_oa', name: 'organization_admin', label: 'OA', active: true }, - { id: 'ps_oa_nb', name: 'organization_admin_no_bypass', label: 'OA nb', active: true }, - ], SYS); - await engine.insert('sys_member', { id: 'm1', user_id: TARGET, organization_id: 'o1', role: 'owner', created_at: new Date().toISOString() }, { context: { isSystem: true, attributedUserId: ISSUER } } as never); - const res = 'via-middleware'; - const rows = await engine.find('sys_user_permission_set', { where: { user_id: TARGET }, context: { isSystem: true } } as never) as any[]; - console.log('MEASURE auto-org-admin ->', JSON.stringify({ res, granted_by: rows.map((r) => r.granted_by) })); + // better-auth's membership write: system context, attributed to the admin who clicked. + await engine.insert( + 'sys_member', + { id: 'mem_owner', user_id: TARGET, organization_id: 'org_1', role: 'owner', created_at: new Date().toISOString() }, + { context: { isSystem: true, attributedUserId: ISSUER } } as never, + ); + const rows = (await engine.find('sys_user_permission_set', { where: { user_id: TARGET }, context: { isSystem: true } } as never)) as any[]; + expect(rows.map((r) => r.granted_by)).toEqual([ISSUER]); }); }); -void createInvitationPlacementService; -void expect; +describe('granted_by — a non-system update cannot rewrite it', () => { + for (const [object, row] of Object.entries(TABLES)) { + for (const [who, caller] of Object.entries(CALLERS)) { + it(`${object}: ${who} renaming the granter leaves the stored writer`, async () => { + const { engine } = await boot(); + const created: any = await engine.insert(object, row({ granted_by: ISSUER }), SYS); + await engine.update(object, { granted_by: OTHER }, { where: { id: created.id }, context: { ...caller } } as never); + expect(await storedGrantedBy(engine, object, created.id)).toBe(ISSUER); + }); + } + } +}); + +describe('granted_by — the integrity audit files a granter that resolves to nothing under provenance', () => { + const integrityWarnings = (warn: ReturnType) => + warn.mock.calls.filter(([msg]) => typeof msg === 'string' && msg.startsWith('[integrity]')); + + for (const [object, row] of Object.entries(TABLES)) { + it(`${object}: a deleted granter lands in provenance, and no warning fires`, async () => { + const { engine, warn } = await boot({ security: false }); + // A system write is exempt from the write-time reference check — the + // shape a granter deleted after the grant leaves behind. + const created: any = await engine.insert(object, row({ granted_by: GONE }), SYS); + + const report = await engine.inspectDanglingReferences({ objects: [object] }); + + expect(report.dangling).toEqual([]); + expect(report.provenance).toEqual([ + { objectName: object, recordId: String(created.id), field: 'granted_by', target: 'sys_user', value: GONE }, + ]); + expect(integrityWarnings(warn)).toEqual([]); + }); + + it(`${object} (control): a business lookup that resolves to nothing still lands in dangling, and warns`, async () => { + const { engine, warn } = await boot({ security: false }); + const created: any = await engine.insert(object, row({ user_id: GONE, granted_by: ADMIN }), SYS); + + const report = await engine.inspectDanglingReferences({ objects: [object] }); + + expect(report.dangling).toEqual([ + { objectName: object, recordId: String(created.id), field: 'user_id', target: 'sys_user', value: GONE }, + ]); + expect(report.provenance).toEqual([]); + expect(integrityWarnings(warn)).toHaveLength(1); + }); + } +}); From 93d7854aaea71706fb9c812957099ae44a12c39d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 07:51:25 +0000 Subject: [PATCH 4/4] test(plugin-security): declare granted_by on the sys_user_position stand-in the gate now stamps for a tenant-level admin Claude-Session: https://claude.ai/code/session_01WkL6Eijt432S1Y7ekb6ovQ Co-authored-by: Claude --- .../src/write-preview-field-gate-parity.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/plugins/plugin-security/src/write-preview-field-gate-parity.test.ts b/packages/plugins/plugin-security/src/write-preview-field-gate-parity.test.ts index b2290d91fa4..0bc3244267e 100644 --- a/packages/plugins/plugin-security/src/write-preview-field-gate-parity.test.ts +++ b/packages/plugins/plugin-security/src/write-preview-field-gate-parity.test.ts @@ -142,6 +142,11 @@ const USER_POSITION = { fields: { user: { type: 'text' }, position: { type: 'text' }, + // Declared as the shipped object declares it: the DelegatedAdminGate stamps + // the writer into `granted_by` on every insert it admits, a tenant-level + // admin's included, so an object without the column refuses that insert as + // an unknown field before the rule this suite is about is ever reached. + granted_by: { type: 'text' }, amount: { type: 'number' }, account: { type: 'lookup', reference: 'crm_account' }, },