From fa0c6ad689bbf42bbd05aec49dfbf81a30c107b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:28:17 +0000 Subject: [PATCH 1/5] fix(plugin-security): stamp an action body's insert with its invoker as owner Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- .../action-body-insert-owner-stamp.test.ts | 363 ++++++++++++++++++ .../plugin-security/src/owner-anchor-stamp.ts | 122 ++++++ .../src/security-plugin-authz-middleware.ts | 48 ++- 3 files changed, 517 insertions(+), 16 deletions(-) create mode 100644 packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts create mode 100644 packages/plugins/plugin-security/src/owner-anchor-stamp.ts diff --git a/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts b/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts new file mode 100644 index 00000000000..b3bc812f2b5 --- /dev/null +++ b/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts @@ -0,0 +1,363 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An action body's insert is owner-stamped the way a direct create is. + * + * ## The defect this pins + * + * An action body's `ctx.api` runs the invoker's envelope elevated — + * `{ ...envelope, isSystem: true }` with the `'action'` app-automation + * elevation mark (`buildActionExecutionContext`, `@objectstack/runtime`) — and + * the authorization middleware's `isSystem` bypass returned before step 3.5, + * the empty-owner stamp. So a row the body inserted landed with `owner_id` + * null, and on a private object its invoker could neither read it nor update + * it: the read door answered not-found for the id the action had just + * returned. A direct create by the same user was stamped. + * + * ## What is pinned + * + * 1. The repro: a non-admin invoker's body inserts into a private object; the + * row is owned by the invoker, who reads it by id and updates it. A direct + * create under the same envelope is the control. + * 2. An `owner_id` the body sets itself is kept — another user's included: the + * body is trusted, elevated code, and no forge guard runs on it. + * 3. The guest invoker: nothing is stamped (ADR-0138 D1). + * 4. Delegation (ADR-0090 D10): the stamp names the principal a direct create + * under the same envelope is stamped with. + * 5. Forge: nothing in the payload or in a client-spelt context steers the + * stamp. A context that SPELLS the mark as a string is not marked, and the + * elevations the stamp does not key on — a flow run, a hook's + * `runAs: 'system'`, a bare `isSystem` — land owner null exactly as before. + * 6. A batch insert from a body: every row with an empty owner. + * 7. A queue the body names parks the row as step 3.5 parks a trusted + * writer's (ADR-0142 D3): `owner_id` supplied empty beside the queue stays + * unset; an absent owner is stamped and the queue is the row's home queue. + * + * ## The rig + * + * The real `SecurityPlugin` over a real `ObjectQL` and SQL driver + * (better-sqlite3, in memory), the real `SharingService` as the kernel's + * `sharing` service with its middleware after this plugin's, and the + * platform's `member_default` set — the `controlled-by-parent-owner-may-edit` + * rig. The private object declares no owner column: the registry injects + * `owner_id` (and the ownership-queue column) as it does for every user-owned + * object. The body's `ctx.api` is `engine.createContext(context)`, the call + * `buildActionApi` makes, over the context `buildActionExecutionContext` + * builds: the envelope spread, `isSystem: true`, and the `'action'` mark. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SharingService, buildSharingMiddleware, SysRecordShare } from '@objectstack/plugin-sharing'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { markAppAutomationElevation } from '@objectstack/core'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; +import { SysUserPosition } from './objects/sys-user-position.object.js'; +import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; +import { wireEngineSecuritySource } from './engine-security-source.testkit.js'; + +const SYS = { context: { isSystem: true } } as never; +const MEMBER_DEFAULT = defaultPermissionSets.find((p) => p.name === 'member_default')!; + +const NOTE = 'abo_note'; +const ORG = 'org_abo'; +/** The invoker: a non-admin member who creates, reads and edits the rows it owns. */ +const ME = 'usr_abo_invoker'; +/** Someone else: owns nothing the invoker can see. */ +const OTHER = 'usr_abo_other'; +/** The agent principal acting for {@link DELEGATOR} (ADR-0090 D10). */ +const AGENT = 'usr_abo_agent'; +const DELEGATOR = 'usr_abo_delegator'; + +const WRITER_SET = PermissionSetSchema.parse({ + name: 'abo_writer', + objects: { [NOTE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, +}); +const SETS = [MEMBER_DEFAULT, WRITER_SET]; + +/** The envelope `resolveAuthzContext` hands the middleware for an organization member holding the writer set. */ +const memberOf = (userId: string) => ({ + userId, + tenantId: ORG, + positions: ['org_member'], + permissions: [WRITER_SET.name, 'member_default'], + posture: 'MEMBER', +}); +const INVOKER = memberOf(ME); +const GUEST = { principalKind: 'guest', tenantId: ORG, positions: [], permissions: ['member_default'] }; +const DELEGATED = { ...memberOf(AGENT), onBehalfOf: { userId: DELEGATOR } }; + +/** What `buildActionExecutionContext` (runtime) builds from an envelope. */ +const actionBody = (envelope: object) => markAppAutomationElevation({ ...envelope, isSystem: true }, 'action'); + +type Row = Record; + +let engine: ObjectQL; +let seq = 0; +const nextId = (tag: string) => `abo_${tag}_${++seq}`; + +beforeAll(async () => { + 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.action-body-insert-owner-stamp', + name: 'An action body insert is owner-stamped like a direct create', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [ + SysRecordShare, + SysUser, + SysOrganization, + SysMember, + SysUserPosition, + SysUserPermissionSet, + { + name: NOTE, + label: 'Note', + sharingModel: 'private', + tenancy: { enabled: false }, + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, + }, + }, + ], + } as never); + await engine.syncSchemas(); + await engine.insert('sys_user', [ME, OTHER, AGENT, DELEGATOR].map((id) => ({ id, name: id, email: `${id}@abo.test` })), SYS); + await engine.insert('sys_organization', [{ id: ORG, name: 'ABO', slug: 'abo' }], SYS); + + let securityService: unknown; + let sharing: SharingService | undefined; + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + type === 'permission' ? SETS.find((s) => s.name === name) ?? null : engine.getSchema(name) ?? null, + list: async () => SETS, + }, + get sharing() { return sharing; }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: (name: string, svc: unknown) => { if (name === 'security') securityService = 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: 'member_default' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + wireEngineSecuritySource(engine, () => plugin); + sharing = new SharingService({ engine: engine as never, securityService: () => securityService as never }); + engine.registerMiddleware(buildSharingMiddleware(sharing, ctx.logger) as never, { object: '*' }); +}); + +afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } +}); + +/** The body's `ctx.api` insert under `context`, as `buildActionApi` builds it. */ +const bodyInsert = (context: object, data: Row | Row[]) => + (engine as any).createContext(context).object(NOTE).insert(data); +/** The stored row, read past every gate. */ +const stored = async (id: string): Promise => + ((await engine.findOne(NOTE, { where: { id }, context: { isSystem: true } } as never)) ?? null) as Row | null; +/** The caller's own by-id read, as the data door issues it. */ +const readAs = async (context: object, id: string): Promise => + ((await engine.findOne(NOTE, { where: { id }, context } as never)) ?? null) as Row | null; + +describe('the schema the suite runs on', () => { + it('the private object carries the injected owner and queue columns', () => { + const fields = Object.keys((engine.getSchema(NOTE) as { fields: Record }).fields); + expect(fields).toContain('owner_id'); + expect(fields).toContain('queue'); + }); +}); + +describe('an action body insert on a private object (the repro)', () => { + it('is owned by the invoker, who reads it by id and updates it', async () => { + const id = nextId('repro'); + await bodyInsert(actionBody(INVOKER), { id, name: 'filed by the action' }); + + expect((await stored(id))?.owner_id).toBe(ME); + expect((await readAs(INVOKER, id))?.id).toBe(id); + await engine.update(NOTE, { name: 'edited by the invoker' }, { where: { id }, context: { ...INVOKER } } as never); + expect((await stored(id))?.name).toBe('edited by the invoker'); + }); + + it('is owned exactly as the same envelope’s direct create is (the control)', async () => { + const direct = nextId('direct'); + const body = nextId('body'); + await engine.insert(NOTE, { id: direct, name: 'direct' }, { context: { ...INVOKER } } as never); + await bodyInsert(actionBody(INVOKER), { id: body, name: 'body' }); + + expect((await stored(direct))?.owner_id).toBe(ME); + expect((await stored(body))?.owner_id).toBe((await stored(direct))?.owner_id); + }); + + it('stamps an owner the body supplies EMPTY (null and the empty string)', async () => { + const asNull = nextId('null'); + const asEmpty = nextId('empty'); + await bodyInsert(actionBody(INVOKER), { id: asNull, name: 'n', owner_id: null }); + await bodyInsert(actionBody(INVOKER), { id: asEmpty, name: 'e', owner_id: '' }); + + expect((await stored(asNull))?.owner_id).toBe(ME); + expect((await stored(asEmpty))?.owner_id).toBe(ME); + }); +}); + +describe('an owner the body sets itself is kept', () => { + it('another user’s id lands as written, with no forge refusal', async () => { + const id = nextId('theirs'); + await bodyInsert(actionBody(INVOKER), { id, name: 'for someone else', owner_id: OTHER }); + + expect((await stored(id))?.owner_id).toBe(OTHER); + // The invoker does not own it, so the private object hides it from them. + expect(await readAs(INVOKER, id)).toBeNull(); + }); + + it('the invoker’s own id lands as written', async () => { + const id = nextId('mine'); + await bodyInsert(actionBody(INVOKER), { id, name: 'for me', owner_id: ME }); + + expect((await stored(id))?.owner_id).toBe(ME); + }); +}); + +describe('the guest invoker (ADR-0138 D1)', () => { + it('is stamped with nothing: an absent or empty owner stays unset', async () => { + const absent = nextId('guest_absent'); + const empty = nextId('guest_empty'); + await bodyInsert(actionBody(GUEST), { id: absent, name: 'a' }); + await bodyInsert(actionBody(GUEST), { id: empty, name: 'e', owner_id: '' }); + + expect((await stored(absent))?.owner_id ?? null).toBeNull(); + expect((await stored(empty))?.owner_id ?? null).toBeNull(); + }); +}); + +describe('delegation (ADR-0090 D10)', () => { + it('stamps the principal a direct create under the same envelope is stamped with', async () => { + const id = nextId('delegated'); + await bodyInsert(actionBody(DELEGATED), { id, name: 'by the agent' }); + + // Step 3.5's own reading for the same envelope, through the middleware + // that stamps a direct create: the envelope's `userId`, the agent. + const direct = { name: 'direct, delegated' } as Row; + await stampedByDirectCreate(DELEGATED, direct); + + expect(direct.owner_id).toBe(AGENT); + expect((await stored(id))?.owner_id).toBe(direct.owner_id); + }); +}); + +describe('forge: nothing a client sends steers the stamp', () => { + it('a client-spelt context is not the body’s elevation: no stamp, and no other user', async () => { + // Everything a request body can carry, the mark's own name included as a + // string key: JSON has no symbols, so this context is not marked. + const spelt = JSON.parse(JSON.stringify({ + ...INVOKER, + userId: OTHER, + isSystem: true, + 'objectstack.core.appAutomationElevation': 'action', + appAutomationElevation: 'action', + })); + const id = nextId('spelt'); + await bodyInsert(spelt, { id, name: 'spelt' }); + + expect((await stored(id))?.owner_id ?? null).toBeNull(); + }); + + it('a payload naming another creator does not change who is stamped', async () => { + const id = nextId('payload'); + await bodyInsert(actionBody(INVOKER), { id, name: 'payload', created_by: OTHER }); + + expect((await stored(id))?.owner_id).toBe(ME); + }); + + it.each([ + ['a flow run (isSystem with a flowRunId)', { ...INVOKER, isSystem: true, flowRunId: 'run_abo_1' }], + ['a flow run reaching an action (the flow wins over the mark)', { ...actionBody(INVOKER), flowRunId: 'run_abo_2' }], + ["a hook's runAs: 'system'", markAppAutomationElevation({ ...INVOKER, isSystem: true }, 'hook')], + ['a bare isSystem carrying a user', { ...INVOKER, isSystem: true }], + ['a bare isSystem', { isSystem: true }], + ])('%s still lands owner null (unchanged)', async (_name, context) => { + const id = nextId('control'); + await bodyInsert(context, { id, name: 'control' }); + + expect((await stored(id))?.owner_id ?? null).toBeNull(); + }); +}); + +describe('a batch insert from a body', () => { + it('stamps every row whose owner is empty and keeps the one the body set', async () => { + const ids = [nextId('b1'), nextId('b2'), nextId('b3'), nextId('b4')]; + await bodyInsert(actionBody(INVOKER), [ + { id: ids[0], name: 'one' }, + { id: ids[1], name: 'two', owner_id: OTHER }, + { id: ids[2], name: 'three', owner_id: null }, + { id: ids[3], name: 'four' }, + ]); + + const owners = await Promise.all(ids.map(async (id) => (await stored(id))?.owner_id)); + expect(owners).toEqual([ME, OTHER, ME, ME]); + }); +}); + +describe('a queue the body names (ADR-0142 D3)', () => { + it('parks the row when the body supplies the owner empty beside the queue', async () => { + const id = nextId('parked'); + await bodyInsert(actionBody(INVOKER), { id, name: 'parked', queue: 'abo_intake', owner_id: null }); + + const row = await stored(id); + expect(row?.queue).toBe('abo_intake'); + expect(row?.owner_id ?? null).toBeNull(); + }); + + it('stamps the invoker when the owner is absent: the queue is the home queue', async () => { + const id = nextId('homed'); + await bodyInsert(actionBody(INVOKER), { id, name: 'homed', queue: 'abo_intake' }); + + const row = await stored(id); + expect(row?.queue).toBe('abo_intake'); + expect(row?.owner_id).toBe(ME); + }); +}); + +/** + * The owner a DIRECT create under `envelope` is stamped with, read off the + * row the middleware chain hands the driver: the engine's own insert under + * the envelope, its stored row's owner copied back onto `row`. Under + * delegation the direct create is refused further down the chain on this + * rig (the delegator holds no membership), so the stamp is read where step + * 3.5 writes it — on the payload — through a middleware registered after + * the security plugin's. + */ +async function stampedByDirectCreate(envelope: object, row: Row): Promise { + const tag = `abo_probe_${++seq}`; + let seen: unknown; + let armed = true; + engine.registerMiddleware((async (opCtx: any, next: () => Promise) => { + if (armed && opCtx.operation === 'insert' && opCtx.object === NOTE && opCtx.data?.name === tag) { + seen = opCtx.data.owner_id; + armed = false; + throw new Error('probe: stop before the write'); + } + return next(); + }) as never, { object: NOTE }); + await engine.insert(NOTE, { name: tag }, { context: { ...envelope } } as never).catch(() => undefined); + armed = false; + row.owner_id = seen; +} diff --git a/packages/plugins/plugin-security/src/owner-anchor-stamp.ts b/packages/plugins/plugin-security/src/owner-anchor-stamp.ts new file mode 100644 index 00000000000..02233ccc6dd --- /dev/null +++ b/packages/plugins/plugin-security/src/owner-anchor-stamp.ts @@ -0,0 +1,122 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The owner-anchor INSERT stamp: who an inserted row's empty `owner_id` names. + * + * One rule, read at two places in the authorization middleware: + * + * 1. Step 3.5 (the ownership gate), for every write the middleware judges: an + * empty owner is stamped to the acting user, the grant holder's park + * (`owner_id` supplied empty beside a supplied queue, ADR-0142 D3) leaves + * it unset, and the guest (ADR-0138 D1) is stamped with nothing. + * 2. An action body's insert ({@link stampActionBodyInsertOwners}), read + * ahead of the `isSystem` bypass that skips step 3.5. An action body's + * `ctx.api` / `ctx.engine` run the invoker's envelope elevated with + * `isSystem: true` and the `'action'` app-automation elevation mark + * (`buildActionExecutionContext`, runtime). Without this, the body's insert + * landed with `owner_id` null while `created_by` named the invoker, so on a + * private object the invoker could neither read nor update the row its own + * action had just created. + * + * ## What the action-body stamp is, and what it is not + * + * - It keys on the `'action'` mark ONLY. A flow run (`isSystem` with a + * `flowRunId`, which wins over a mark the way the identity-write refusal reads + * it), a hook's `runAs: 'system'` (the `'hook'` mark), seed / boot / import + * system writes and a bare `{ isSystem: true }` are unchanged: they still land + * the owner they wrote, or none. + * - It stamps the SAME principal step 3.5 stamps for a direct create under the + * same envelope: the envelope's own `userId` (under ADR-0090 D10 delegation, + * the acting principal, exactly as step 3.5 reads it), never a value from + * the payload. The envelope is the caller's server-built one, spread into + * the elevated context by the action door; the mark is a symbol key + * (`APP_AUTOMATION_ELEVATION`, `@objectstack/core`), which no request body, + * query string or stored row can spell, so no client can claim it. + * - It fills only an EMPTY owner. An `owner_id` the body sets itself is left + * alone: the body is trusted, elevated code, and the forge / transfer guard + * step 3.5 runs for a user's write is not run on it. + * - A queue the body names parks the row exactly as step 3.5 parks it for a + * trusted writer (the grant holder): an `owner_id` supplied empty beside the + * queue leaves the owner unset; an absent owner is stamped, and the queue is + * the row's home queue. + * - Batch inserts: every row with an empty owner. + */ + +import { appAutomationElevationOf } from '@objectstack/core'; +import { QUEUE_FIELD, writesQueue } from './ownership-queue-gate.js'; + +/** The row-ownership anchor column (`applySystemFields`, objectql). */ +export const OWNER_FIELD = 'owner_id'; + +/** + * Does `row` carry `owner_id` as an own property — the change-set SUPPLIES the + * anchor? Own-property only: a polluted `Object.prototype.owner_id` must not + * make an ordinary row look like it names an owner. + */ +export function writesOwner(row: unknown): row is Record { + return !!row && typeof row === 'object' && !Array.isArray(row) && + Object.prototype.hasOwnProperty.call(row, OWNER_FIELD); +} + +/** Is the row's owner EMPTY — absent, `null`, `undefined` or `''`? */ +export function hasEmptyOwner(row: Record): boolean { + return !writesOwner(row) || row.owner_id == null || row.owner_id === ''; +} + +/** Who the stamp names, and the two cases in which it names nobody. */ +export interface EmptyOwnerStamp { + /** The acting principal's id, from the operation's own envelope. */ + userId: unknown; + /** The anonymous principal (`isGuestEnvelope`): stamped with nothing (ADR-0138 D1). */ + guest: boolean; + /** The trusted writer's park: `owner_id` supplied empty beside a supplied queue (ADR-0142 D3). */ + park: boolean; +} + +/** + * Stamp `row`'s EMPTY owner (the caller checks {@link hasEmptyOwner} first): + * unset for a park, the acting user when there is one, and for a guest nothing + * at all, its empty string normalised to unset (an empty string would land in + * the anchor as a value that is neither an owner nor none). + */ +export function stampEmptyOwner(row: Record, stamp: EmptyOwnerStamp): void { + if (stamp.park) row.owner_id = null; + // Batch rows included: the single-record-only stamp left bulk-inserted rows + // NULL-owned and invisible to their creator. + else if (stamp.userId) row.owner_id = stamp.userId; + // [ADR-0138 D1 item 5] + else if (stamp.guest && row.owner_id === '') row.owner_id = null; +} + +/** + * Is `context` an action body's elevation — `isSystem` with the `'action'` + * mark and no flow run? The flow run wins over a mark, as the identity-write + * refusal's source reading has it (`flow-system-identity-write-refusal.ts`). + */ +export function isActionBodyElevation(context: { isSystem?: unknown; flowRunId?: unknown } | null | undefined): boolean { + return !!context?.isSystem && !context.flowRunId && appAutomationElevationOf(context) === 'action'; +} + +/** + * The action-body half of the stamp (see the module header): every row of the + * insert whose owner is empty is stamped as step 3.5 stamps a trusted writer's + * row under the same envelope. The caller has established that the operation + * is an insert under an action body's elevation, onto an object that carries + * `owner_id`; `hasQueue` says whether it carries the queue column too. + */ +export function stampActionBodyInsertOwners( + data: unknown, + context: { userId?: unknown } | null | undefined, + guest: boolean, + hasQueue: boolean, +): void { + if (!data || typeof data !== 'object') return; + const rows = (Array.isArray(data) ? data : [data]) as unknown[]; + for (const row of rows) { + if (!row || typeof row !== 'object' || Array.isArray(row)) continue; + const r = row as Record; + if (!hasEmptyOwner(r)) continue; + const park = hasQueue && writesQueue(r) && r[QUEUE_FIELD] != null && r[QUEUE_FIELD] !== '' && writesOwner(r); + stampEmptyOwner(r, { userId: context?.userId, guest, park }); + } +} diff --git a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts index 509b1570f1b..e083bd07bac 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -144,6 +144,13 @@ import { writesQueue, } from './ownership-queue-gate.js'; import { assertEngineOwnedWriteAllowed } from './system-write-guard.js'; +import { + hasEmptyOwner, + isActionBodyElevation, + stampActionBodyInsertOwners, + stampEmptyOwner, + writesOwner, +} from './owner-anchor-stamp.js'; import { externalGrantPatch } from './external-owd-grant-stamp.js'; import { computedFieldsReadingThroughReferences } from './field-masker.js'; @@ -666,6 +673,21 @@ export function registerAuthzMiddleware( (line) => ctx.logger.warn(line), ); + // [#34885] An action body's insert is owner-stamped as a direct create + // is: the body's `ctx.api` / `ctx.engine` run the invoker's envelope + // elevated with the `'action'` mark, and the bypass below skips step 3.5, + // so without this the row landed with `owner_id` null and its invoker, + // on a private object, could neither read nor update it. An EMPTY owner + // only, the envelope's own principal only (nothing for the guest), keyed + // on the `'action'` mark only — flows, hooks and every other system write + // are unchanged. See `owner-anchor-stamp.ts`. + if (opCtx.operation === 'insert' && opCtx.data && typeof opCtx.data === 'object' && isActionBodyElevation(opCtx.context)) { + const fields = await this.getObjectFieldNames(metadata, opCtx.object, ql); + if (fields?.has('owner_id')) { + stampActionBodyInsertOwners(opCtx.data, opCtx.context, isGuestEnvelope(opCtx.context), fields.has(QUEUE_FIELD)); + } + } + // System operations bypass security if (opCtx.context?.isSystem) { return next(); @@ -1795,12 +1817,11 @@ export function registerAuthzMiddleware( ) { const isInsert = opCtx.operation === 'insert'; const rows = (Array.isArray(opCtx.data) ? opCtx.data : [opCtx.data]) as Record[]; - // Own-property test only — never read `owner_id` through the prototype - // chain (a polluted `Object.prototype.owner_id` must not make ordinary - // field-only updates look like ownership writes). - const writesOwner = (r: unknown): r is Record => - !!r && typeof r === 'object' && !Array.isArray(r) && - Object.prototype.hasOwnProperty.call(r, 'owner_id'); + // `writesOwner` is an own-property test only — never read `owner_id` + // through the prototype chain (a polluted `Object.prototype.owner_id` + // must not make ordinary field-only updates look like ownership + // writes). It and the insert stamp below are `owner-anchor-stamp.ts`, + // shared with the action-body stamp ahead of the `isSystem` bypass. // A valid owner id is a NON-EMPTY SCALAR. Anything else (array / object / // boolean / '' ) is neither a stampable self-owner nor a tolerable echo — // String()-coercing it would let `owner_id: [selfId]` pass as "self" and @@ -1924,16 +1945,11 @@ export function registerAuthzMiddleware( denyQueueWrite(INSERT_QUEUE_REFUSAL, 'record_queue_assign_denied'); } } - if (!writesOwner(row) || row.owner_id == null || row.owner_id === '') { - if (park) row.owner_id = null; - // Auto-stamp the acting user (batch rows included — the - // single-record-only stamp left bulk-inserted rows NULL-owned - // and invisible to their creator). - else if (userId) row.owner_id = userId; - // [ADR-0138 D1 item 5] A guest is stamped with nothing, and - // its empty owner is left UNSET: an empty string would land - // in the anchor as a value that is neither an owner nor none. - else if (guest && row.owner_id === '') row.owner_id = null; + if (hasEmptyOwner(row)) { + // Auto-stamp the acting user, batch rows included; the park + // leaves it unset, and [ADR-0138 D1 item 5] a guest is + // stamped with nothing. + stampEmptyOwner(row, { userId, guest, park }); } else if (guest) { denyGuestOwnerWrite(); } else if ( From 330df045834bdd2f85f6da2b34d7f59e889a931c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:29:42 +0000 Subject: [PATCH 2/5] test(plugin-security): pin the action-body owner stamp against a real engine Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- .../action-body-insert-owner-stamp.test.ts | 46 ++++++------------- 1 file changed, 13 insertions(+), 33 deletions(-) diff --git a/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts b/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts index b3bc812f2b5..8042c583c6a 100644 --- a/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts +++ b/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts @@ -134,6 +134,13 @@ beforeAll(async () => { await engine.syncSchemas(); await engine.insert('sys_user', [ME, OTHER, AGENT, DELEGATOR].map((id) => ({ id, name: id, email: `${id}@abo.test` })), SYS); await engine.insert('sys_organization', [{ id: ORG, name: 'ABO', slug: 'abo' }], SYS); + // The delegator's current membership (ADR-0093 D8.1: a delegation needs it) + // and its stored grant of the writer set, so a direct create on its behalf + // lands — the control the delegated body insert is compared with. + await engine.insert('sys_member', [{ id: 'mem_abo_delegator', user_id: DELEGATOR, organization_id: ORG, role: 'member' }], SYS); + await (engine as any).getDriver('sys_user_permission_set').create('sys_user_permission_set', { + id: 'ups_abo_delegator', user_id: DELEGATOR, permission_set: WRITER_SET.name, organization_id: ORG, + }); let securityService: unknown; let sharing: SharingService | undefined; @@ -251,15 +258,14 @@ describe('the guest invoker (ADR-0138 D1)', () => { describe('delegation (ADR-0090 D10)', () => { it('stamps the principal a direct create under the same envelope is stamped with', async () => { const id = nextId('delegated'); + const direct = nextId('delegated_direct'); + await engine.insert(NOTE, { id: direct, name: 'direct, delegated' }, { context: { ...DELEGATED } } as never); await bodyInsert(actionBody(DELEGATED), { id, name: 'by the agent' }); - // Step 3.5's own reading for the same envelope, through the middleware - // that stamps a direct create: the envelope's `userId`, the agent. - const direct = { name: 'direct, delegated' } as Row; - await stampedByDirectCreate(DELEGATED, direct); - - expect(direct.owner_id).toBe(AGENT); - expect((await stored(id))?.owner_id).toBe(direct.owner_id); + // Step 3.5 stamps a direct create under this envelope with its `userId`: + // the acting principal, the agent. + expect((await stored(direct))?.owner_id).toBe(AGENT); + expect((await stored(id))?.owner_id).toBe((await stored(direct))?.owner_id); }); }); @@ -335,29 +341,3 @@ describe('a queue the body names (ADR-0142 D3)', () => { expect(row?.owner_id).toBe(ME); }); }); - -/** - * The owner a DIRECT create under `envelope` is stamped with, read off the - * row the middleware chain hands the driver: the engine's own insert under - * the envelope, its stored row's owner copied back onto `row`. Under - * delegation the direct create is refused further down the chain on this - * rig (the delegator holds no membership), so the stamp is read where step - * 3.5 writes it — on the payload — through a middleware registered after - * the security plugin's. - */ -async function stampedByDirectCreate(envelope: object, row: Row): Promise { - const tag = `abo_probe_${++seq}`; - let seen: unknown; - let armed = true; - engine.registerMiddleware((async (opCtx: any, next: () => Promise) => { - if (armed && opCtx.operation === 'insert' && opCtx.object === NOTE && opCtx.data?.name === tag) { - seen = opCtx.data.owner_id; - armed = false; - throw new Error('probe: stop before the write'); - } - return next(); - }) as never, { object: NOTE }); - await engine.insert(NOTE, { name: tag }, { context: { ...envelope } } as never).catch(() => undefined); - armed = false; - row.owner_id = seen; -} From d8b390f60748dd0713ec6b73f5684140118801db Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:42:38 +0000 Subject: [PATCH 3/5] chore(changeset): plugin-security patch for the action-body owner stamp Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- .../34885-action-body-insert-owner-stamp.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .changeset/34885-action-body-insert-owner-stamp.md diff --git a/.changeset/34885-action-body-insert-owner-stamp.md b/.changeset/34885-action-body-insert-owner-stamp.md new file mode 100644 index 00000000000..c2677e0d3d5 --- /dev/null +++ b/.changeset/34885-action-body-insert-owner-stamp.md @@ -0,0 +1,20 @@ +--- +'@objectstack/plugin-security': patch +--- + +fix(plugin-security): a record an action body inserts is owned by the user who ran the action + +Clause-②: yes +Metadata-protocol: none + +An action body's `ctx.api` (and `ctx.engine`) runs the invoking user's context elevated to system. The security middleware's system bypass skipped the owner stamp a direct create gets, so a row the body inserted with `ctx.api.object(X).insert({...})` was stored with `owner_id` null, while `created_by` named the invoker. On an object with `sharingModel: 'private'` a non-admin invoker then could not read or update the record their own action had just created: `get` by the returned id answered not-found. + +An action body's insert now fills an EMPTY `owner_id` with the invoker, as a direct create by that user does: + +- every row of a batch insert whose owner is empty is stamped; +- an `owner_id` the body sets itself is kept, another user's included (the body is trusted code, as before); +- a guest invoker is stamped with nothing (ADR-0138 D1); +- under delegation the stamp names the same principal a direct create under that context names (ADR-0090 D10); +- a body that names an ownership queue and supplies `owner_id` empty beside it parks the row unowned in the queue; a body that names a queue and leaves `owner_id` out gets an owned row with that home queue (ADR-0142 D3). + +Unchanged: flows (`runAs: 'system'` or not), hooks with `runAs: 'system'`, seed, boot and import writes, and any other system context. They still store the owner they write, or none. Rows stored before this release keep `owner_id` null; an administrator can assign their owners. From 2fb169f60bf42587312a77cf08c787d988b0b7bd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 18:20:26 +0000 Subject: [PATCH 4/5] docs(permissions): the system-context page names the action-body owner stamp Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- content/docs/permissions/system-context.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 0ce67742164..cf7d0a74c98 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -101,7 +101,7 @@ bugs — it is the protection or the side effect that silently does not happen. |:--|:---|:---|:---|:---| | 1 | **The whole security middleware short-circuits** before any gate runs | plugin-security | Get: every CRUD/FLS/tenant/owner gate below skipped in one branch. Lose: every gate under it in this lane at once, down to and including the write-bypass row that widens the effective write scope to `org` (row 7) — this is the single largest behaviour on the page | `registerAuthzMiddleware` | | 1b | **App-authored automation's system context is REFUSED governed writes to the identity-assignment objects** — a flow run's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and an action body's; checked ahead of the middleware's short-circuit, beside the append-only refusal (`assertAppAutomationAppendOnlyWriteAllowed`) | plugin-security | Get: nothing — an insert, update, delete, transfer, restore or purge of `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` from a context carrying `isSystem` and either a `flowRunId` (a `runAs: 'system'` flow's data nodes) or the app-automation elevation mark (`@objectstack/core`; set only by a hook's `runAs: 'system'` derivation, by the action body's execution-context builder and `ObjectRepository.execute`, and on the api of a hook bound through the hook binder, whose inherited system context and `sudo()` it marks), at any depth of their writes, is refused `PERMISSION_DENIED` before the short-circuit skips the ADR-0090 D12 gate and the identity write guard. Lose: nothing a platform writer held — a system context with neither (the seeders, better-auth and its reconciliation, invitation placement, platform code's `sudo()`, which never sets the mark, and a hook registered in code) passes on to the short-circuit unchanged, reads are not judged, and a `runAs: 'user'` flow or hook carries no `isSystem`, so the D12 gate judges it as the user it acts for | `elevationSource`, `appAuthoredHookApi` | -| 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware` | +| 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) — except an action body's insert | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability. Except an action body's: an insert from a context carrying `isSystem` and the `'action'` app-automation elevation mark, with no `flowRunId`, has every EMPTY `owner_id` stamped with the envelope's own `userId` ahead of the short-circuit, by the same stamp step 3.5 applies (nothing for the guest; an owner the body sets is kept; an `owner_id` supplied empty beside a supplied queue parks the row). A flow run, a hook's `runAs: 'system'`, the seeders and every other system context still land the owner they write, or none | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware`; the action-body exception is `isActionBodyElevation` | | 3 | Row-level read filter resolves to "no filter" | plugin-security | Get: unscoped reads. Lose: row-level scoping entirely | `getReadFilter` | | 4 | Field-level security returns **all** fields | plugin-security | Get: every column readable (`getReadableFields`) and writable (`getWritableFields`). Lose: field masking | `resolveProjectionFieldMask` | | 5 | Export permission granted unconditionally | plugin-security | Get: `canExport` is `true` | `canExport` | @@ -605,6 +605,7 @@ and CI refuses one that differs from what the tree produces. | `packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts#onUpdate` | 1 | 23d | | `packages/plugins/plugin-security/src/grant-permission-set-name.ts#onInsert` | 1 | 23c | | `packages/plugins/plugin-security/src/grant-permission-set-name.ts#onUpdate` | 1 | 23c | +| `packages/plugins/plugin-security/src/owner-anchor-stamp.ts#isActionBodyElevation` | 1 | 2 | | `packages/plugins/plugin-security/src/position-catalog-refusal.ts#assertPositionNamesCatalogRow` | 1 | 23b | | `packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts#registerAuthzMiddleware` | 1 | 1, 2, 30 | | `packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts#checkControlledByParentWrite` | 1 | 9b | From 6cacf68c50645caa3d6d48817d03b877468e8d4a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:56:06 +0000 Subject: [PATCH 5/5] fix(plugin-security): pin and disclose that assignment rules route neither an action-body insert nor a direct create Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- .../34885-action-body-insert-owner-stamp.md | 9 ++- content/docs/permissions/system-context.mdx | 2 +- .../src/security/app-automation-elevation.ts | 7 +- .../action-body-insert-owner-stamp.test.ts | 80 ++++++++++++++++++- 4 files changed, 93 insertions(+), 5 deletions(-) diff --git a/.changeset/34885-action-body-insert-owner-stamp.md b/.changeset/34885-action-body-insert-owner-stamp.md index c2677e0d3d5..99c2cf1d3b9 100644 --- a/.changeset/34885-action-body-insert-owner-stamp.md +++ b/.changeset/34885-action-body-insert-owner-stamp.md @@ -1,5 +1,6 @@ --- '@objectstack/plugin-security': patch +'@objectstack/core': patch --- fix(plugin-security): a record an action body inserts is owned by the user who ran the action @@ -17,4 +18,10 @@ An action body's insert now fills an EMPTY `owner_id` with the invoker, as a dir - under delegation the stamp names the same principal a direct create under that context names (ADR-0090 D10); - a body that names an ownership queue and supplies `owner_id` empty beside it parks the row unowned in the queue; a body that names a queue and leaves `owner_id` out gets an owned row with that home queue (ADR-0142 D3). -Unchanged: flows (`runAs: 'system'` or not), hooks with `runAs: 'system'`, seed, boot and import writes, and any other system context. They still store the owner they write, or none. Rows stored before this release keep `owner_id` null; an administrator can assign their owners. +This covers every handler an action door dispatches, not only a script body's `ctx.api`. A host code action handler and an action reached through `ObjectRepository.execute` run under the same action context, and their inserts are stamped the same way. + +Assignment rules (ADR-0142 D5) route only a row whose `owner_id` and `queue` are both still empty. An action-body insert is now the invoker's own record, as a direct create by that user already was, so assignment rules route neither. Before this release, an action body's unowned, queue-less insert on an object a rule reaches was routed by the rule. It now goes to the invoker. A body has no spelling today that asks a rule to route its row. + +`@objectstack/core`: the header of the app-automation elevation mark (shipped in its type declarations) now names the owner stamp as a second reader beside the refusals. + +Unchanged: flows (`runAs: 'system'` or not), hooks with `runAs: 'system'`, seed, boot and import writes, and any other system context. They still store the owner they write, or none, and an unowned, queue-less insert from one of them is still routed by assignment rules. Rows stored before this release keep `owner_id` null; an administrator can assign their owners. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index cf7d0a74c98..c434d7b58e9 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -101,7 +101,7 @@ bugs — it is the protection or the side effect that silently does not happen. |:--|:---|:---|:---|:---| | 1 | **The whole security middleware short-circuits** before any gate runs | plugin-security | Get: every CRUD/FLS/tenant/owner gate below skipped in one branch. Lose: every gate under it in this lane at once, down to and including the write-bypass row that widens the effective write scope to `org` (row 7) — this is the single largest behaviour on the page | `registerAuthzMiddleware` | | 1b | **App-authored automation's system context is REFUSED governed writes to the identity-assignment objects** — a flow run's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and an action body's; checked ahead of the middleware's short-circuit, beside the append-only refusal (`assertAppAutomationAppendOnlyWriteAllowed`) | plugin-security | Get: nothing — an insert, update, delete, transfer, restore or purge of `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` from a context carrying `isSystem` and either a `flowRunId` (a `runAs: 'system'` flow's data nodes) or the app-automation elevation mark (`@objectstack/core`; set only by a hook's `runAs: 'system'` derivation, by the action body's execution-context builder and `ObjectRepository.execute`, and on the api of a hook bound through the hook binder, whose inherited system context and `sudo()` it marks), at any depth of their writes, is refused `PERMISSION_DENIED` before the short-circuit skips the ADR-0090 D12 gate and the identity write guard. Lose: nothing a platform writer held — a system context with neither (the seeders, better-auth and its reconciliation, invitation placement, platform code's `sudo()`, which never sets the mark, and a hook registered in code) passes on to the short-circuit unchanged, reads are not judged, and a `runAs: 'user'` flow or hook carries no `isSystem`, so the D12 gate judges it as the user it acts for | `elevationSource`, `appAuthoredHookApi` | -| 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) — except an action body's insert | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability. Except an action body's: an insert from a context carrying `isSystem` and the `'action'` app-automation elevation mark, with no `flowRunId`, has every EMPTY `owner_id` stamped with the envelope's own `userId` ahead of the short-circuit, by the same stamp step 3.5 applies (nothing for the guest; an owner the body sets is kept; an `owner_id` supplied empty beside a supplied queue parks the row). A flow run, a hook's `runAs: 'system'`, the seeders and every other system context still land the owner they write, or none | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware`; the action-body exception is `isActionBodyElevation` | +| 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) — except an action body's insert | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability. Except an action body's: an insert from a context carrying `isSystem` and the `'action'` app-automation elevation mark, with no `flowRunId`, has every EMPTY `owner_id` stamped with the envelope's own `userId` ahead of the short-circuit, by the same stamp step 3.5 applies (nothing for the guest; an owner the body sets is kept; an `owner_id` supplied empty beside a supplied queue parks the row). Like a direct create, such an insert is the invoker's own record, so assignment rules (ADR-0142 D5), which route only a row whose owner and queue are both still empty, route neither; a body has no spelling today that asks a rule to route its row. The mark is set on every handler an action door dispatches (a host code action handler included) and by `ObjectRepository.execute`. A flow run, a hook's `runAs: 'system'`, the seeders and every other system context still land the owner they write, or none, and an unowned, queue-less one is still routed | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware`; the action-body exception is `isActionBodyElevation` | | 3 | Row-level read filter resolves to "no filter" | plugin-security | Get: unscoped reads. Lose: row-level scoping entirely | `getReadFilter` | | 4 | Field-level security returns **all** fields | plugin-security | Get: every column readable (`getReadableFields`) and writable (`getWritableFields`). Lose: field masking | `resolveProjectionFieldMask` | | 5 | Export permission granted unconditionally | plugin-security | Get: `canExport` is `true` | `canExport` | diff --git a/packages/core/src/security/app-automation-elevation.ts b/packages/core/src/security/app-automation-elevation.ts index 269da59c1a9..ac751686dec 100644 --- a/packages/core/src/security/app-automation-elevation.ts +++ b/packages/core/src/security/app-automation-elevation.ts @@ -37,7 +37,12 @@ * It is server-constructed by construction: no request body, query string or * stored row can spell a symbol, so no caller can claim or shed it. It is an * in-process provenance fact, never a principal and never an authorization - * grant — its only reader narrows (it refuses; it admits nothing). `Symbol.for` + * grant. It has two readers, both in plugin-security, and neither admits an + * operation. The identity-write and append-only refusals narrow: they refuse. + * The owner stamp (`owner-anchor-stamp.ts`) reads the `'action'` mark to give + * ownership on an insert: an EMPTY `owner_id` is filled with the context's own + * `userId`, the principal a direct create under the same envelope is stamped + * with, and never a different one. `Symbol.for` * rather than a module-local `Symbol()`, because this package ships an ESM and * a CJS build and a process may load both: the mark must be the same key in * each. diff --git a/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts b/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts index 8042c583c6a..ffb1f8a107d 100644 --- a/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts +++ b/packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts @@ -32,6 +32,12 @@ * 7. A queue the body names parks the row as step 3.5 parks a trusted * writer's (ADR-0142 D3): `owner_id` supplied empty beside the queue stays * unset; an absent owner is stamped and the queue is the row's home queue. + * 8. An object a declared assignment rule routes (ADR-0142 D5): the rule + * routes on this rig (a system insert and a flow run's insert go to the + * rule's user), the invoker's direct create is stamped and not routed, and + * an action body's insert is owned exactly as that direct create is. The + * seam routes only a row whose owner and queue are both still empty, and a + * body has no spelling that asks it to route. * * ## The rig * @@ -63,6 +69,8 @@ const SYS = { context: { isSystem: true } } as never; const MEMBER_DEFAULT = defaultPermissionSets.find((p) => p.name === 'member_default')!; const NOTE = 'abo_note'; +/** A private object a declared assignment rule routes (ADR-0142 D5): every unowned, queue-less insert to {@link LEAD}. */ +const TICKET = 'abo_ticket'; const ORG = 'org_abo'; /** The invoker: a non-admin member who creates, reads and edits the rows it owns. */ const ME = 'usr_abo_invoker'; @@ -71,10 +79,15 @@ const OTHER = 'usr_abo_other'; /** The agent principal acting for {@link DELEGATOR} (ADR-0090 D10). */ const AGENT = 'usr_abo_agent'; const DELEGATOR = 'usr_abo_delegator'; +/** The user the declared assignment rule hands every routed ticket to: an active member of {@link ORG}. */ +const LEAD = 'usr_abo_lead'; const WRITER_SET = PermissionSetSchema.parse({ name: 'abo_writer', - objects: { [NOTE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, + objects: { + [NOTE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, + [TICKET]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, + }, }); const SETS = [MEMBER_DEFAULT, WRITER_SET]; @@ -129,14 +142,29 @@ beforeAll(async () => { name: { name: 'name', type: 'text' }, }, }, + { + name: TICKET, + label: 'Ticket', + sharingModel: 'private', + tenancy: { enabled: false }, + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, + }, + }, + ], + assignmentRules: [ + { name: 'abo_ticket_intake', object: TICKET, active: true, entries: [{ name: 'all', assignTo: { type: 'user', value: LEAD } }] }, ], } as never); await engine.syncSchemas(); - await engine.insert('sys_user', [ME, OTHER, AGENT, DELEGATOR].map((id) => ({ id, name: id, email: `${id}@abo.test` })), SYS); + await engine.insert('sys_user', [ME, OTHER, AGENT, DELEGATOR, LEAD].map((id) => ({ id, name: id, email: `${id}@abo.test` })), SYS); await engine.insert('sys_organization', [{ id: ORG, name: 'ABO', slug: 'abo' }], SYS); // The delegator's current membership (ADR-0093 D8.1: a delegation needs it) // and its stored grant of the writer set, so a direct create on its behalf // lands — the control the delegated body insert is compared with. + // The rule's target is a member of the organization the rows land in. + await engine.insert('sys_member', [{ id: 'mem_abo_lead', user_id: LEAD, organization_id: ORG, role: 'member' }], SYS); await engine.insert('sys_member', [{ id: 'mem_abo_delegator', user_id: DELEGATOR, organization_id: ORG, role: 'member' }], SYS); await (engine as any).getDriver('sys_user_permission_set').create('sys_user_permission_set', { id: 'ups_abo_delegator', user_id: DELEGATOR, permission_set: WRITER_SET.name, organization_id: ORG, @@ -341,3 +369,51 @@ describe('a queue the body names (ADR-0142 D3)', () => { expect(row?.owner_id).toBe(ME); }); }); + +describe('an object an assignment rule routes (ADR-0142 D5): owned like a direct create, so the rule routes neither', () => { + const bodyInsertTicket = (context: object, data: Row) => + (engine as any).createContext(context).object(TICKET).insert(data); + const storedTicket = async (id: string): Promise => + ((await engine.findOne(TICKET, { where: { id }, context: { isSystem: true } } as never)) ?? null) as Row | null; + + it('the rule does route on this rig: an unowned, queue-less system insert goes to the rule’s user (the control)', async () => { + const id = nextId('routed_system'); + await engine.insert(TICKET, { id, name: 'system intake' }, { context: { isSystem: true, tenantId: ORG } } as never); + + expect((await storedTicket(id))?.owner_id).toBe(LEAD); + }); + + it('a flow run’s unowned insert is still routed (unchanged) — the route an action body’s insert took before', async () => { + const id = nextId('routed_flow'); + await bodyInsertTicket({ ...INVOKER, isSystem: true, flowRunId: 'run_abo_routed' }, { id, name: 'flow intake' }); + + expect((await storedTicket(id))?.owner_id).toBe(LEAD); + }); + + it('the invoker’s direct create is stamped with the invoker and not routed', async () => { + const id = nextId('direct_ticket'); + await engine.insert(TICKET, { id, name: 'direct' }, { context: { ...INVOKER } } as never); + + const row = await storedTicket(id); + expect(row?.owner_id).toBe(ME); + expect(row?.queue ?? null).toBeNull(); + }); + + it('an action body’s insert is owned exactly as that direct create is: the invoker’s, not routed', async () => { + const id = nextId('body_ticket'); + await bodyInsertTicket(actionBody(INVOKER), { id, name: 'filed by the action' }); + + const row = await storedTicket(id); + expect(row?.owner_id).toBe(ME); + expect(row?.queue ?? null).toBeNull(); + const seen = (await engine.findOne(TICKET, { where: { id }, context: { ...INVOKER } } as never)) as Row | null; + expect(seen?.id).toBe(id); + }); + + it('an owner the body supplies empty is stamped too: a body has no spelling that asks the rule to route', async () => { + const id = nextId('body_ticket_null'); + await bodyInsertTicket(actionBody(INVOKER), { id, name: 'null owner', owner_id: null }); + + expect((await storedTicket(id))?.owner_id).toBe(ME); + }); +});