From a7af7193b60ae904ac58e4f8e7b35346427a796b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:48:44 +0000 Subject: [PATCH 1/5] test(runtime): platformSystemApi on the api ObjectRepository.execute hands the dispatched action keeps the 'action' mark (failing first) Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- ...tform-system-api-35434.integration.test.ts | 221 ++++++++++++++++++ 1 file changed, 221 insertions(+) create mode 100644 packages/runtime/src/execute-dispatched-action-platform-system-api-35434.integration.test.ts diff --git a/packages/runtime/src/execute-dispatched-action-platform-system-api-35434.integration.test.ts b/packages/runtime/src/execute-dispatched-action-platform-system-api-35434.integration.test.ts new file mode 100644 index 00000000000..ccdb36f0edc --- /dev/null +++ b/packages/runtime/src/execute-dispatched-action-platform-system-api-35434.integration.test.ts @@ -0,0 +1,221 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The platform's own system api (`platformSystemApi`, objectql) over the api + * `ObjectRepository.execute` hands the action it dispatches + * (`ctx.api.object(o).execute(name)`). + * + * - It keeps the `'action'` app-automation mark `execute` sets: that api, and + * every api derived from it, carries the dispatched action's origin flag, + * and on a flagged api `platformSystemApi` answers what `sudo()` answers. + * So the dispatched handler's writes to the identity-assignment objects + * through it are refused as `content/docs/permissions/system-context.mdx` + * says (the identity-assignment refusal), whichever api dispatched it: the + * action door's (an action handler chaining another) or a bare engine api. + * - CONTROL: the api the audit writer holds (a hook registered in code, fired + * by the dispatched handler's write) is not the dispatched action's: there + * it still takes the mark off, and the platform's write lands. + * - CONTROL: the origin flag is not the app-authored flag, so the dispatched + * handler's permanent delete (ADR-0148 D3) still runs. + * + * Real `ObjectQL`, a real SQL driver and the real `SecurityPlugin` middleware; + * the store is read back past the middleware. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +// Paid at collection: the action path reaches a dynamic import of this package inside a clocked case. +import '@objectstack/metadata'; +import { ObjectQL, platformSystemApi } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { buildActionApi } from './action-execution.js'; + +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[], extra: Record = {}) => ({ + name, + label: name, + fields: { id: pk, ...Object.fromEntries(fields.map((f) => [f, text(f)])) }, + ...extra, +}); + +const MEMBER = PermissionSetSchema.parse({ + name: 'qa_member', + objects: { qa_note: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, +}); + +/** The invoking user's envelope, as an action door receives it. */ +const CALLER = { userId: 'usr_plain', tenantId: 'org_default', positions: [], permissions: ['qa_member'], isSystem: false }; + +/** A row of each of the four identity-assignment objects. */ +const ROWS: Record Record> = { + sys_user_position: (id) => ({ id, user_id: 'usr_target', position: 'qa_rep', business_unit_id: 'bu_east' }), + sys_user_permission_set: (id) => ({ id, user_id: 'usr_target', permission_set: 'qa_plain' }), + sys_invitation: (id) => ({ id, email: `${id}@example.test`, role: 'member', status: 'pending', inviter_id: 'usr_plain' }), + sys_member: (id) => ({ id, user_id: 'usr_target', organization_id: 'org_default', role: 'member' }), +}; +const OBJECTS = Object.keys(ROWS); + +const engines: ObjectQL[] = []; +afterEach(async () => { + while (engines.length) { + try { await engines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +async function boot(): Promise { + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const engine = new ObjectQL({ logger } as never); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never, + true, + ); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.execute-dispatched-action-platform-system-api', + name: 'execute dispatched action platform system api', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [ + inline('sys_user', ['name'], { managedBy: 'better-auth' }), + inline('sys_organization', ['name'], { managedBy: 'better-auth' }), + inline('sys_member', ['user_id', 'organization_id', 'role'], { managedBy: 'better-auth' }), + inline('sys_invitation', ['email', 'role', 'status', 'inviter_id', 'organization_id'], { managedBy: 'better-auth' }), + inline('sys_user_position', ['user_id', 'position', 'business_unit_id', 'granted_by']), + inline('sys_user_permission_set', ['user_id', 'permission_set', 'granted_by']), + inline('qa_note', ['title', 'organization_id', 'owner_id']), + inline('sys_audit_log', ['action', 'object_name'], { managedBy: 'append-only', systemFields: { tenant: false } }), + ], + } as never); + await engine.syncSchemas(); + engines.push(engine); + + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? [MEMBER].find((s: any) => s?.name === name) : engine.getSchema(name)) ?? null, + list: async () => [MEMBER], + }, + }; + const ctx = { + logger, + registerService: vi.fn(), + 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; +} + +/** The two apis a dispatch can start from: the action door's, and a bare engine api. */ +const CALLERS: ReadonlyArray any]> = [ + ["the action door's api (an action handler chaining another action)", (engine) => buildActionApi({} as never, engine, { ...CALLER })], + ['a bare engine api', (engine) => engine.createContext({ ...CALLER })], +]; + +/** The stored row, read past the middleware; `null` when there is none. */ +async function stored(engine: ObjectQL, object: string, id: string): Promise | null> { + return ((await engine.findOne(object, { where: { id }, context: { isSystem: true } } as never)) as any) ?? null; +} + +/** The refusal a write met, or `null` when it landed. */ +async function refusal(write: () => Promise): Promise { + try { + await write(); + return null; + } catch (e) { + return e; + } +} + +function expectIdentityRefused(err: any, object: string, route: string): void { + expect(err, `insert on ${object} through ${route} was not refused`).not.toBe(null); + expect(err.code).toBe('PERMISSION_DENIED'); + expect(err.statusCode ?? err.status).toBe(403); + expect(String(err.message)).toMatch(/an action body \(an action body runs as system\)/); +} + +describe("platformSystemApi on the api ObjectRepository.execute hands the dispatched action keeps the 'action' mark", () => { + for (const [caller, apiOf] of CALLERS) { + for (const object of OBJECTS) { + it(`dispatched from ${caller}: an insert into ${object} through it, through its sudo() and inside its transaction is refused, and nothing lands`, async () => { + const engine = await boot(); + const seen: Record = {}; + engine.registerAction('qa_note', 'grant', async (actx: any) => { + seen.direct = await refusal(() => platformSystemApi(actx.api)!.object(object).insert(ROWS[object]('direct'))); + seen.sudo = await refusal(() => platformSystemApi(actx.api.sudo())!.object(object).insert(ROWS[object]('sudo'))); + seen.trx = await refusal(() => + actx.api.transaction(async (trx: any) => platformSystemApi(trx)!.object(object).insert(ROWS[object]('trx'))), + ); + // CONTROL: the handler's own sudo(), refused before this card too. + seen.ownSudo = await refusal(() => actx.api.sudo().object(object).insert(ROWS[object]('own_sudo'))); + }); + + await apiOf(engine).object('qa_note').execute('grant'); + + for (const route of ['direct', 'sudo', 'trx', 'ownSudo']) expectIdentityRefused(seen[route], object, route); + for (const id of ['direct', 'sudo', 'trx', 'own_sudo']) expect(await stored(engine, object, id)).toBe(null); + }, 30000); + } + } + + it("its insert into an ordinary object is owner-stamped with the caller, as the action body's insert is", async () => { + const engine = await boot(); + engine.registerAction('qa_note', 'note', async (actx: any) => + platformSystemApi(actx.api)!.object('qa_note').insert({ id: 'note_1', title: 'by dispatched handler' }), + ); + await CALLERS[0][1](engine).object('qa_note').execute('note'); + expect(await stored(engine, 'qa_note', 'note_1')).toMatchObject({ owner_id: CALLER.userId }); + }, 30000); +}); + +describe("CONTROL: the api the audit writer holds is not the dispatched action's", () => { + it("a hook registered in code, fired by the dispatched handler's write, takes the mark off and its platform write lands; its sudo() does not", async () => { + const engine = await boot(); + const seen: Record = {}; + engine.registerHook('afterInsert', async (hctx: any) => { + if ((hctx.result?.id ?? hctx.input?.data?.id) !== 'note_1') return; + await platformSystemApi(hctx.api)!.object('sys_member').insert(ROWS.sys_member('by_platform')); + await platformSystemApi(hctx.api)!.object('sys_audit_log').insert({ id: 'audit_1', action: 'create', object_name: 'qa_note' }); + seen.sudo = await refusal(() => hctx.api.sudo().object('sys_member').insert(ROWS.sys_member('by_sudo'))); + }, { object: 'qa_note', packageId: 'sys:qa' }); + engine.registerAction('qa_note', 'note', async (actx: any) => + actx.api.object('qa_note').insert({ id: 'note_1', title: 'by dispatched handler' }), + ); + + await CALLERS[0][1](engine).object('qa_note').execute('note'); + + expect(await stored(engine, 'qa_note', 'note_1')).toMatchObject({ id: 'note_1' }); + expect(await stored(engine, 'sys_member', 'by_platform')).toMatchObject({ id: 'by_platform' }); + expect(await stored(engine, 'sys_audit_log', 'audit_1')).toMatchObject({ id: 'audit_1' }); + expectIdentityRefused(seen.sudo, 'sys_member', "the hook api's sudo()"); + expect(await stored(engine, 'sys_member', 'by_sudo')).toBe(null); + }, 30000); +}); + +describe("CONTROL: the dispatched action's origin flag is not the app-authored flag", () => { + it("the dispatched handler's permanent delete still runs, through its api and through platformSystemApi on it", async () => { + const engine = await boot(); + const api = CALLERS[0][1](engine); + await api.object('qa_note').insert({ id: 'note_1', title: 'one' }); + await api.object('qa_note').insert({ id: 'note_2', title: 'two' }); + engine.registerAction('qa_note', 'purge', async (actx: any) => { + await actx.api.object('qa_note').delete({ where: { id: 'note_1' }, permanent: true }); + await platformSystemApi(actx.api)!.object('qa_note').delete({ where: { id: 'note_2' }, permanent: true }); + }); + + await api.object('qa_note').execute('purge'); + + expect(await stored(engine, 'qa_note', 'note_1')).toBe(null); + expect(await stored(engine, 'qa_note', 'note_2')).toBe(null); + }, 30000); +}); From 800d7edf89b885d5d6bd697f86190afc0da55576 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:56:31 +0000 Subject: [PATCH 2/5] fix(objectql): platformSystemApi on the api ObjectRepository.execute hands the dispatched action keeps the 'action' mark Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- content/docs/permissions/system-context.mdx | 2 +- .../objectql/src/engine-object-repository.ts | 34 ++++++++++++++++++- .../objectql/src/engine-scoped-context.ts | 19 +++++++---- packages/objectql/src/platform-system-api.ts | 6 +--- 4 files changed, 47 insertions(+), 14 deletions(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 1729479dfe1..ab1ab3859f1 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -100,7 +100,7 @@ bugs — it is the protection or the side effect that silently does not happen. | # | Behaviour when `isSystem` | Package | What you get / what you lose | Symbol | |:--|:---|:---|:---|:---| | 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. The platform's own system api (`platformSystemApi`, objectql) takes the mark and `flowRunId` off a platform hook's api, for the audit writer's own ledger rows. On an app-authored hook's api and on the api an action door hands its handler (a host code action handler's included), and on every api derived from either, it answers what that api's `sudo()` answers, mark kept, so this refusal, and the action body's owner stamp in the next row, hold through it too. Not covered: the api `ObjectRepository.execute` hands the action it dispatches (`ctx.api.object(o).execute(name)`) is a bare engine api carrying the `'action'` mark and no action-door flag, so on it `platformSystemApi` still takes the mark off. 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` | +| 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. The platform's own system api (`platformSystemApi`, objectql) takes the mark and `flowRunId` off a platform hook's api, for the audit writer's own ledger rows. On an app-authored hook's api and on the api an action door hands its handler (a host code action handler's included), and on every api derived from either, it answers what that api's `sudo()` answers, mark kept, so this refusal, and the action body's owner stamp in the next row, hold through it too. 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). 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`), and every field a disabled package withholds named to it (`getMetadataReadableWithheldFields`, so the served object's `_withheldFields` keeps every entry). Lose: field masking | `resolveProjectionFieldMask`, `computeMetadataReadableWithheldFields` | diff --git a/packages/objectql/src/engine-object-repository.ts b/packages/objectql/src/engine-object-repository.ts index 97a79f3d07d..cdce79d71f4 100644 --- a/packages/objectql/src/engine-object-repository.ts +++ b/packages/objectql/src/engine-object-repository.ts @@ -35,6 +35,35 @@ import { markAppAutomationElevation } from '@objectstack/core'; import { ScopedContext } from './engine.js'; import type { ObjectRepository } from './engine.js'; +/** + * The dispatched action's origin flag: the api {@link ObjectRepositoryFacet.execute} + * hands the action it dispatches, and every api `ScopedContext`'s `derive` + * builds from one (`engine-scoped-context.ts`). On a flagged api the platform's + * own system api (`platformSystemApi`, `platform-system-api.ts`) is the api's + * `sudo()`: the `'action'` mark `execute` sets, and any `flowRunId`, stay, so the + * dispatched handler's writes to the identity-assignment objects through it are + * judged as an action body's (plugin-security). + * + * A flag of its own, and ⛔ not the engine's app-authored one: that one also + * refuses a permanent delete (ADR-0148 D3), which a dispatched host handler + * keeps. Keyed by instance and held here, beside the one place that sets it, so + * the facade (`engine.ts`) carries no field for it. Every reader reaches it + * through the instance's own members, so the flag and its reader are always the + * same copy of this package. + */ +const DISPATCHED_ACTION_APIS = new WeakSet(); + +/** Flag `api` as the api a dispatched action is handed, or as one derived from it (see {@link DISPATCHED_ACTION_APIS}). */ +export function markDispatchedActionApi(api: ScopedContext): ScopedContext { + DISPATCHED_ACTION_APIS.add(api); + return api; +} + +/** Is `api` the api a dispatched action is handed, or one derived from it (see {@link DISPATCHED_ACTION_APIS})? */ +export function isDispatchedActionApi(api: ScopedContext): boolean { + return DISPATCHED_ACTION_APIS.has(api); +} + /** * The `ObjectRepository` members the bodies of {@link ObjectRepositoryFacet} * read — every one of them, and no other. Each is typed AS the class member (an @@ -134,6 +163,9 @@ export class ObjectRepositoryFacet { // (runtime) gives the REST and MCP doors' action bodies: the action this // reaches is app-authored automation running elevated, so its writes to // the four identity-assignment objects are refused (plugin-security). + // The api carries the dispatched action's origin flag, so + // `platformSystemApi` on it, and on every api derived from it, keeps + // the mark ({@link DISPATCHED_ACTION_APIS}). const executionContext: ExecutionContext = markAppAutomationElevation( { ...this.context, isSystem: true }, 'action', @@ -144,7 +176,7 @@ export class ObjectRepositoryFacet { tenantId: this.context.tenantId, roles: this.context.positions, executionContext, - api: new ScopedContext(executionContext, this.engine), + api: markDispatchedActionApi(new ScopedContext(executionContext, this.engine)), }); } throw new Error(`Actions not supported by engine`); diff --git a/packages/objectql/src/engine-scoped-context.ts b/packages/objectql/src/engine-scoped-context.ts index 68808d82a76..e68fc14850f 100644 --- a/packages/objectql/src/engine-scoped-context.ts +++ b/packages/objectql/src/engine-scoped-context.ts @@ -53,6 +53,7 @@ import type { HookRunAs, HookRunAsRef } from './hook-run-as.js'; import { scopedContextHost } from './engine-scoped-hosts.js'; import { ObjectRepository, ScopedContext } from './engine.js'; import type { ObjectQL } from './engine.js'; +import { isDispatchedActionApi, markDispatchedActionApi } from './engine-object-repository.js'; /** * The `ScopedContext` members the bodies of {@link ScopedContextFacet} read — @@ -76,16 +77,18 @@ export interface ScopedContextHost { /** The bodies of `ScopedContext`'s methods: a stateless facet, called by the class's stubs. */ export class ScopedContextFacet { /** - * A child over `executionContext` that keeps this api's provenance. + * A child over `executionContext` that keeps this api's provenance: the + * app-authored flag, and the dispatched action's origin flag + * (`engine-object-repository.ts`, `markDispatchedActionApi`). * * The child's private `appAuthored` is written through the child's own host * (`scopedContextHost.of(child)`), the port its class's static block fills: * a module function cannot write another instance's private field directly. */ - static derive(this: Pick, executionContext: ExecutionContext): ScopedContext { + static derive(this: Pick, executionContext: ExecutionContext): ScopedContext { const child = new ScopedContext(executionContext, this.engine); scopedContextHost.of(child).appAuthored = this.appAuthored; - return child; + return isDispatchedActionApi(this.facade) ? markDispatchedActionApi(child) : child; } /** @@ -124,11 +127,13 @@ export class ScopedContextFacet { /** * The body of `ScopedContext#[PLATFORM_SYSTEM_API]`; its contract, and * where its guard stops, is `platform-system-api.ts`'s module header. - * An app-authored hook's api is never the platform's: there it is that - * api's own {@link ScopedContextFacet.sudo}, provenance kept. + * An app-authored hook's api, and the api `ObjectRepository.execute` hands + * the action it dispatches (`isDispatchedActionApi`), are never the + * platform's: there it is that api's own {@link ScopedContextFacet.sudo}, + * provenance kept. */ - static platformSystemApi(this: Pick): ScopedContext { - if (this.appAuthored) return ScopedContextFacet.sudo.call(this); + static platformSystemApi(this: Pick): ScopedContext { + if (this.appAuthored || isDispatchedActionApi(this.facade)) return ScopedContextFacet.sudo.call(this); const { flowRunId: _run, ...context } = withoutAppAutomationElevation({ ...this.executionContext, isSystem: true }); return this.derive(context as ExecutionContext); } diff --git a/packages/objectql/src/platform-system-api.ts b/packages/objectql/src/platform-system-api.ts index 76004a927b6..78bbc05b7d8 100644 --- a/packages/objectql/src/platform-system-api.ts +++ b/packages/objectql/src/platform-system-api.ts @@ -50,11 +50,7 @@ * (ADR-0148 D3) that a host handler keeps. * * So a handler handing its own api here gains nothing, and its writes to the - * identity-assignment objects are judged as its own. ⚠️ Not covered: the api - * `ObjectRepository.execute` hands the action it dispatches - * (`ctx.api.object(o).execute(name)`, `engine-object-repository.ts`) is a bare - * `ScopedContext` carrying the `'action'` mark and neither line's flag, so on - * it this takes the mark off, as on the audit writer's hook api. The api the audit writer + * identity-assignment objects are judged as its own. The api the audit writer * holds is neither: `buildHookApi` builds a fresh `ScopedContext` over the * write's context, carrying the `'action'` mark when an action's write fired * the hook, and this takes it off there. Neither line is a security boundary: From 2b62b2c21fb02f9ca2579c4a1d3cbb24e8abff58 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 16:07:05 +0000 Subject: [PATCH 3/5] chore(changeset): objectql patch for the dispatched action's origin flag Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- .../35434-execute-dispatched-action-keeps-mark.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .changeset/35434-execute-dispatched-action-keeps-mark.md diff --git a/.changeset/35434-execute-dispatched-action-keeps-mark.md b/.changeset/35434-execute-dispatched-action-keeps-mark.md new file mode 100644 index 00000000000..dfaffa70ae8 --- /dev/null +++ b/.changeset/35434-execute-dispatched-action-keeps-mark.md @@ -0,0 +1,15 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): `platformSystemApi` on the api `ObjectRepository.execute` hands the action it dispatches keeps the `'action'` mark + +Clause-②: no +Metadata-protocol: none + +`ctx.api.object(o).execute(name)` dispatches the named action with an api over a context it marks `'action'`. That api carried neither the app-authored flag nor the action door's origin flag, so `platformSystemApi(ctx.api)` in the dispatched handler took the mark off, and its writes to `sys_member`, `sys_user_position`, `sys_user_permission_set` and `sys_invitation` passed as a platform writer's, against the documented refusal for action handlers. + +- The api `execute` hands the dispatched action now carries its own origin flag, kept by every api derived from it (`sudo()`, `withRunAs(...)`, a transaction's context, the api `platformSystemApi` and the user-grants seeds return). On it, `platformSystemApi(api)` returns what `api.sudo()` returns: the `'action'` mark and any `flowRunId` kept. Writes to the four identity-assignment objects through it are refused `PERMISSION_DENIED` (403), whichever api dispatched the action, and its inserts are owner-stamped with the invoking user. +- The flag is not the app-authored flag: the dispatched handler's `delete(…, { permanent: true })` still runs. +- The api the audit writer holds (a hook registered in code) is unchanged: `platformSystemApi` still takes the mark off there. +- This closes the path the previous note on `platformSystemApi` named as not covered. No new export, and no published signature changes. From 186bbc489c00f71d513eac6e3550aa13fa820ffb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 04:08:09 +0000 Subject: [PATCH 4/5] docs(changeset): the pending platformSystemApi note no longer names the execute path as not covered Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- .changeset/35174-action-api-platform-system-api-mark.md | 1 - 1 file changed, 1 deletion(-) diff --git a/.changeset/35174-action-api-platform-system-api-mark.md b/.changeset/35174-action-api-platform-system-api-mark.md index a61cd6ccc00..e15c3c56ed9 100644 --- a/.changeset/35174-action-api-platform-system-api-mark.md +++ b/.changeset/35174-action-api-platform-system-api-mark.md @@ -13,5 +13,4 @@ Metadata-protocol: none - The flag is not the app-authored flag: a host handler's `delete(…, { permanent: true })` still runs. - The api the audit writer holds (a hook registered in code) is unchanged: `platformSystemApi` still takes the mark off there. - Runtime's derivation walk now wraps the api any symbol-keyed member derives (`platformSystemApi`'s, the user-grants seeds'), awaited when it is a promise, so it is served through the stored-metadata read seam and the landed-write answer like `ctx.api.sudo()`. -- Not covered: the api `ctx.api.object(o).execute(name)` hands the action it dispatches is built by the engine, not the action door, so `platformSystemApi` still takes the mark off there. - No new export, and `@objectstack/objectql` is unchanged but for its module header: the member's key is the `Symbol.for` key objectql already uses, which neither package entry exports. From 0a28c2810934861aaadc66e469e2af4295c216dd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 04:47:18 +0000 Subject: [PATCH 5/5] docs(objectql): name the dispatched action's api in the platformSystemApi enumerations; the changeset bullet stands alone Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- .../35434-execute-dispatched-action-keeps-mark.md | 2 +- content/docs/permissions/system-context.mdx | 2 +- packages/objectql/src/platform-system-api.ts | 12 +++++++++--- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/.changeset/35434-execute-dispatched-action-keeps-mark.md b/.changeset/35434-execute-dispatched-action-keeps-mark.md index dfaffa70ae8..0981c1eec47 100644 --- a/.changeset/35434-execute-dispatched-action-keeps-mark.md +++ b/.changeset/35434-execute-dispatched-action-keeps-mark.md @@ -12,4 +12,4 @@ Metadata-protocol: none - The api `execute` hands the dispatched action now carries its own origin flag, kept by every api derived from it (`sudo()`, `withRunAs(...)`, a transaction's context, the api `platformSystemApi` and the user-grants seeds return). On it, `platformSystemApi(api)` returns what `api.sudo()` returns: the `'action'` mark and any `flowRunId` kept. Writes to the four identity-assignment objects through it are refused `PERMISSION_DENIED` (403), whichever api dispatched the action, and its inserts are owner-stamped with the invoking user. - The flag is not the app-authored flag: the dispatched handler's `delete(…, { permanent: true })` still runs. - The api the audit writer holds (a hook registered in code) is unchanged: `platformSystemApi` still takes the mark off there. -- This closes the path the previous note on `platformSystemApi` named as not covered. No new export, and no published signature changes. +- This is the path the action-door fix in this release did not reach. No new export, and no published signature changes. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index ab1ab3859f1..111f4c645c9 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -100,7 +100,7 @@ bugs — it is the protection or the side effect that silently does not happen. | # | Behaviour when `isSystem` | Package | What you get / what you lose | Symbol | |:--|:---|:---|:---|:---| | 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. The platform's own system api (`platformSystemApi`, objectql) takes the mark and `flowRunId` off a platform hook's api, for the audit writer's own ledger rows. On an app-authored hook's api and on the api an action door hands its handler (a host code action handler's included), and on every api derived from either, it answers what that api's `sudo()` answers, mark kept, so this refusal, and the action body's owner stamp in the next row, hold through it too. 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` | +| 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. The platform's own system api (`platformSystemApi`, objectql) takes the mark and `flowRunId` off a platform hook's api, for the audit writer's own ledger rows. On an app-authored hook's api, on the api an action door hands its handler (a host code action handler's included) and on the api `ObjectRepository.execute` hands the action it dispatches (`ctx.api.object(o).execute(name)`), and on every api derived from any of them, it answers what that api's `sudo()` answers, mark kept, so this refusal, and the action body's owner stamp in the next row, hold through it too. 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). 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`), and every field a disabled package withholds named to it (`getMetadataReadableWithheldFields`, so the served object's `_withheldFields` keeps every entry). Lose: field masking | `resolveProjectionFieldMask`, `computeMetadataReadableWithheldFields` | diff --git a/packages/objectql/src/platform-system-api.ts b/packages/objectql/src/platform-system-api.ts index 78bbc05b7d8..47ae98d0713 100644 --- a/packages/objectql/src/platform-system-api.ts +++ b/packages/objectql/src/platform-system-api.ts @@ -35,8 +35,8 @@ * ⛔ For the platform's own rows only, never for a write the automation itself * asked for: an action body's or a hook's insert into those objects, through * its `ctx.api` or its `ctx.api.sudo()`, keeps the provenance and is judged. - * That line holds on two of the apis the automation is handed, and on every - * api derived from either: + * That line holds on three of the apis the automation is handed, and on every + * api derived from any of them: * * - an app-authored hook's api (its handler's `ctx.api`, * `APP_AUTHORED_HOOK_API`): the engine enforces it, and this answers @@ -47,7 +47,13 @@ * the action door's own origin flag and answers this symbol member with * the api's `sudo()`, so the `'action'` mark and any `flowRunId` stay. Not * the engine's app-authored flag, which also refuses a permanent delete - * (ADR-0148 D3) that a host handler keeps. + * (ADR-0148 D3) that a host handler keeps; + * - the api `ObjectRepository.execute` hands the action it dispatches + * (`ctx.api.object(o).execute(name)`, `engine-object-repository.ts`): it + * carries the dispatched action's origin flag, which `derive` copies to + * every api built from it, and this answers it with the api's `sudo()`, so + * the `'action'` mark `execute` sets stays. Not the app-authored flag + * either, for the same reason. * * So a handler handing its own api here gains nothing, and its writes to the * identity-assignment objects are judged as its own. The api the audit writer