From 4bb5993aca87570b35a5236a0a16d49c95ebbf02 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:53:38 +0000 Subject: [PATCH 1/7] fix(objectql,runtime): the action door's api keeps its mark through platformSystemApi, and the seam walk wraps the symbol members An api an action door builds now carries its own origin flag (not the app-authored flag, so a host handler keeps the permanent delete), and platformSystemApi on it, and on every api derived from it, answers as its sudo(): the 'action' mark and flowRunId kept. The runtime seam walk wraps the platform-system and action-door symbol members, so the derived api stays inside the stored-metadata read seam and the landed-write answer. Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- content/docs/permissions/system-context.mdx | 2 +- .../objectql/src/engine-scoped-context.ts | 30 +++++++--- packages/objectql/src/engine.ts | 24 +++++++- packages/objectql/src/platform-system-api.ts | 60 ++++++++++++------- packages/runtime/src/action-execution.ts | 22 ++++++- .../src/stored-metadata-reader-seam.ts | 24 ++++++-- 6 files changed, 123 insertions(+), 39 deletions(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 5da5efe131d..ea023af6208 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. 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, and nowhere else: 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-scoped-context.ts b/packages/objectql/src/engine-scoped-context.ts index 68808d82a76..c23e622c201 100644 --- a/packages/objectql/src/engine-scoped-context.ts +++ b/packages/objectql/src/engine-scoped-context.ts @@ -12,7 +12,8 @@ * which the codemod refuses to move (`foreign-private`), so each writes it * through that instance's own host setter. * The body of `[DETACHED_HOOK_RUN]` (#33651) was written here, in the same - * stub-and-facet shape, and so was the body of `[PLATFORM_SYSTEM_API]`. + * stub-and-facet shape, and so were the bodies of `[PLATFORM_SYSTEM_API]` and + * `[ACTION_DOOR_API]`. * * A MOVE, not a redesign. {@link ScopedContextFacet} is a stateless facet of * `ScopedContext`: each static method of it is the body of the `ScopedContext` @@ -63,6 +64,7 @@ import type { ObjectQL } from './engine.js'; */ export interface ScopedContextHost { appAuthored: ScopedContext['appAuthored']; + actionDoor: ScopedContext['actionDoor']; derive: ScopedContext['derive']; readonly engine: ScopedContext['engine']; readonly executionContext: ScopedContext['executionContext']; @@ -82,12 +84,25 @@ export class ScopedContextFacet { * (`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; + const host = scopedContextHost.of(child); + host.appAuthored = this.appAuthored; + host.actionDoor = this.actionDoor; return child; } + /** + * The body of `ScopedContext#[ACTION_DOOR_API]`; the method's docblock there + * is its contract. A child over the same context, its private `actionDoor` + * written through its own host, as in {@link ScopedContextFacet.derive}. + */ + static actionDoorApi(this: Pick): ScopedContext { + const api = this.derive(this.executionContext); + scopedContextHost.of(api).actionDoor = true; + return api; + } + /** * The body of `ScopedContext#[APP_AUTHORED_HOOK_API]`; the method's docblock * there is its contract. The new api's private `appAuthored` is written @@ -124,11 +139,12 @@ 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 an action door hands its handler, + * 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 || this.actionDoor) 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/engine.ts b/packages/objectql/src/engine.ts index 870455531f8..8c966025428 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -246,7 +246,7 @@ import { stripReadonlyFields, staticReadonlyInsertSubject } from './validation/r // and points at `ctx.previous` — the module owns the measurement and the // reason the explanation cannot be composed any further downstream. import { UnscopedHookApi, SEED_USER_GRANTS, APP_AUTHORED_HOOK_API, type HookRunAs, type HookRunAsRef, type RunAsDerivableApi } from './hook-run-as.js'; -import { PLATFORM_SYSTEM_API } from './platform-system-api.js'; +import { ACTION_DOOR_API, PLATFORM_SYSTEM_API } from './platform-system-api.js'; import { DETACHED_HOOK_RUN, type UNIT_ROLLED_BACK, type UnitCommitQueue } from './unit-detach.js'; // [#6457] The master-detail header a `parent`-scoped predicate reads is made // total over the MASTER's declared fields before it leaves this engine — the @@ -6466,6 +6466,14 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi { */ private appAuthored = false; + /** + * Set on the api an action door hands its handler ({@link ACTION_DOOR_API}) + * and kept by every api derived from it ({@link derive}); read by + * {@link PLATFORM_SYSTEM_API} alone. Not {@link appAuthored}, which also + * refuses a permanent delete (ADR-0148 D3) that a host code handler keeps. + */ + private actionDoor = false; + private derive(executionContext: ExecutionContext): ScopedContext { // [#30975] The body moved to `engine-scoped-context.ts`, its docblock with it (see `ScopedContextHost`). return ScopedContextFacet.derive.call(scopedContextHost.of(this), executionContext); @@ -6509,6 +6517,18 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi { return ScopedContextFacet.platformSystemApi.call(scopedContextHost.of(this)); } + /** + * The api an action door hands its handler: this api's context, carrying the + * action-door origin flag, which every api derived from it keeps. On it, and + * on each of those, {@link PLATFORM_SYSTEM_API} answers what `sudo()` + * answers, the `'action'` mark kept (`platform-system-api.ts`). Keyed on an + * unexported symbol that runtime's `buildActionApi` names through + * `Symbol.for`. + */ + [ACTION_DOOR_API](): ScopedContext { + return ScopedContextFacet.actionDoorApi.call(scopedContextHost.of(this)); + } + /** * [#25653] The api an app-authored hook runs with — see * {@link APP_AUTHORED_HOOK_API} (`hook-run-as.ts`), where the line between @@ -6840,6 +6860,8 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi { scopedContextHost.install((instance) => ({ get appAuthored() { return instance.appAuthored; }, set appAuthored(v) { instance.appAuthored = v; }, + get actionDoor() { return instance.actionDoor; }, + set actionDoor(v) { instance.actionDoor = v; }, derive: (...a) => instance.derive(...a), get engine() { return instance.engine; }, get executionContext() { return instance.executionContext; }, diff --git a/packages/objectql/src/platform-system-api.ts b/packages/objectql/src/platform-system-api.ts index 5e3fcb1dd4c..6945c20405d 100644 --- a/packages/objectql/src/platform-system-api.ts +++ b/packages/objectql/src/platform-system-api.ts @@ -29,33 +29,39 @@ * The write's context, elevated as `sudo()` elevates it — every other key kept, * so the rows stay in the write's unit of work, its organization and its * attribution — without the app-automation mark and without `flowRunId`. The - * api is derived as every api is (`derive`), and its own `sudo()` marks again. + * api is derived as every api is (`derive`): not app-authored and not the + * action door's, so its own `sudo()` adds no mark. * * ⛔ 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. - * The engine enforces that line for the one api it knows is the automation's: - * on an app-authored hook's api (its handler's `ctx.api`, and every api - * derived from it) this answers exactly what that api's `sudo()` answers — the - * `'hook'` mark when the context carries none, the mark it carries otherwise, - * `flowRunId` kept — so a hook handing its own api here gains nothing. + * The engine enforces that line on the two apis it knows are the + * automation's, and on every api derived from either: * - * The line stops there: it guards app-authored hook apis and every api derived - * from one, and nothing else. An app author's in-process action handler, - * registered with `engine.registerAction` (as `examples/app-todo` does from - * `onEnable(ctx.ql)`), is handed runtime's `buildActionApi` api — an engine - * `createContext` carrying the `'action'` mark, and not app-authored. On that - * api this sheds the mark and any `flowRunId`, and the engine cannot tell it - * from the api the audit writer holds (`buildHookApi`, a fresh `ScopedContext` - * over the write's context: not app-authored either, and carrying the same - * mark when an action's write fired the hook). It adds no reach: the handler's - * package registered through the engine it holds, whose - * `createContext({ isSystem: true })` already builds a system api with - * neither. And what it returns is outside runtime's `deriveThroughSeam` - * wrappers on that `ctx.api` (the stored-metadata read seam and the - * landed-write answer): the walk wraps `object`, `sudo`, `withRunAs`, - * `transaction` and `beginTransaction`, and its default arm binds this symbol - * member to the unwrapped api, so the derived api comes back unwrapped. + * - an app-authored hook's api (its handler's `ctx.api`, + * `APP_AUTHORED_HOOK_API`); + * - the api an action door hands its handler, a host code action handler's + * included: runtime's `buildActionApi` derives it through + * {@link ACTION_DOOR_API}, and that origin flag is a different one from + * the app-authored flag, because the app-authored flag also refuses a + * permanent delete (ADR-0148 D3), which a host handler keeps. + * + * On either, this answers exactly what that api's `sudo()` answers — the + * mark the context carries (`'action'` on an action door's api; `'hook'` on an + * app-authored hook's when it carries none), `flowRunId` kept — so a handler + * handing its own api here gains nothing, and its writes to the + * identity-assignment objects and the append-only ones are judged as its own. + * The api the audit writer holds is neither: `buildHookApi` builds a fresh + * `ScopedContext` over the write's context, with neither flag, even when an + * action's write fired the hook and the context carries the `'action'` mark. + * The flag is not a security boundary: a host handler's package registered + * through the engine it holds, whose `createContext({ isSystem: true })` + * already builds a system api with neither the mark nor the run. It keeps the + * documented answer for the api the handler was handed. + * + * What this returns over runtime's wrapped `ctx.api` stays wrapped: runtime's + * `deriveThroughSeam` (the stored-metadata read seam and the landed-write + * answer) walks this symbol member as it walks `sudo()`. * * A symbol, and ⛔ not re-exported from either package entry, for the reason * `SEED_USER_GRANTS` gives (`hook-run-as.ts`): the method is no nameable member @@ -72,6 +78,16 @@ import type { ScopedContext } from './engine.js'; /** The key the engine's `ScopedContext` derives the platform's own system api under. */ export const PLATFORM_SYSTEM_API: unique symbol = Symbol.for('objectstack.objectql.platformSystemApi'); +/** + * The key the engine's `ScopedContext` derives the action door's api under: + * the same context, carrying the action-door origin flag, which this api and + * every api derived from it keep. Read by {@link platformSystemApi} alone. + * Runtime's `buildActionApi` names it through `Symbol.for`, for the reason the + * header gives for {@link PLATFORM_SYSTEM_API}, and ⛔ it is not re-exported + * from either package entry either. + */ +export const ACTION_DOOR_API: unique symbol = Symbol.for('objectstack.objectql.actionDoorApi'); + interface PlatformSystemDerivableApi { [PLATFORM_SYSTEM_API](): ScopedContext; } diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index d138e683b75..9f2300ea6af 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -95,7 +95,7 @@ import type { FlowFailureDetails } from '@objectstack/spec/api'; import { recordNotFoundError, omitInternalFieldsFromWriteResponse } from '@objectstack/metadata-protocol'; // [#31697] The environment store's rows are the resync's: a legacy organization's rows left out off the physical column. import { isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core'; -import { serveStoredMetadataRead, serveStoredMetadataReadsThrough } from './stored-metadata-reader-seam.js'; +import { ACTION_DOOR_API, serveStoredMetadataRead, serveStoredMetadataReadsThrough } from './stored-metadata-reader-seam.js'; import { actionInvocationBranch, actionInvocationFailure, actionInvocationTarget, recordActionInvocation, withActionSurface } from './action-invocation-audit.js'; import type { HttpProtocolContext } from './http-dispatcher.js'; // The ONE admitted sequence every action door shares; `invokeBusinessAction` @@ -3926,11 +3926,27 @@ export function buildActionExecutionContext(ec: any): Record { * handler (`landed-write-answer.ts`), on this context and every one it * derives. That layer sits beneath the reader seam, so the answer is served * like any write's return. + * + * The context is derived through objectql's action-door member + * (`ACTION_DOOR_API`), so it and every api derived from it carry the action + * door's origin flag: on it, `platformSystemApi(ctx.api)` answers what + * `ctx.api.sudo()` answers, the `'action'` mark kept, and the handler's writes + * to the identity-assignment and append-only objects stay judged as its own + * (`platform-system-api.ts`, objectql). Not the app-authored flag: a host + * handler keeps the engine's permanent delete (ADR-0148 D3). An api with no + * such member (an engine double) has no `platformSystemApi` member either, so + * there is nothing for the flag to guard. */ export function buildActionApi(_deps: ActionExecutionDeps, ql: any, ec: any): any | undefined { if (!ql || typeof ql.createContext !== 'function') return undefined; - const served = (scoped: unknown) => - serveStoredMetadataReadsThrough(answerLandedWritesDespiteStaleSummary(scoped, ACTION_API_SURFACE), ql); + const served = (scoped: any) => + serveStoredMetadataReadsThrough( + answerLandedWritesDespiteStaleSummary( + typeof scoped?.[ACTION_DOOR_API] === 'function' ? scoped[ACTION_DOOR_API]() : scoped, + ACTION_API_SURFACE, + ), + ql, + ); try { return served(ql.createContext(buildActionExecutionContext(ec))); } catch { diff --git a/packages/runtime/src/stored-metadata-reader-seam.ts b/packages/runtime/src/stored-metadata-reader-seam.ts index bd13aa08549..1879c275bad 100644 --- a/packages/runtime/src/stored-metadata-reader-seam.ts +++ b/packages/runtime/src/stored-metadata-reader-seam.ts @@ -399,13 +399,25 @@ export function refuseStoredMetadataBodyReads(api: T): T { return deriveThroughSeam(api, BODY_READS_REFUSED, refuseBodyRepositoryReads); } +/** + * The two symbol-keyed members of objectql's `ScopedContext` that derive an + * api, named through `Symbol.for` because neither package entry exports them + * (`platform-system-api.ts`, objectql): the platform's own system api + * (`platformSystemApi`) and the action door's api (`buildActionApi`'s + * derivation, `action-execution.ts`). + */ +const PLATFORM_SYSTEM_API: unique symbol = Symbol.for('objectstack.objectql.platformSystemApi'); +export const ACTION_DOOR_API: unique symbol = Symbol.for('objectstack.objectql.actionDoorApi'); + /** * The walk both layers share: `api`, and every context it can derive — - * `object(name)`, `sudo()`, `withRunAs(...)`, the context a `transaction(fn)` - * callback receives, and the `ctx` `beginTransaction()` returns — with each - * repository passed through `wrapRepository`. One definition of what a scoped - * API can derive, so neither layer can leave a route around it. [#28861] The - * landed-write layer (`landed-write-answer.ts`) walks it too. + * `object(name)`, `sudo()`, `withRunAs(...)`, the api `platformSystemApi(api)` + * derives and the action door's api (the two symbol-keyed members above), the + * context a `transaction(fn)` callback receives, and the `ctx` + * `beginTransaction()` returns — with each repository passed through + * `wrapRepository`. One definition of what a scoped API can derive, so neither + * layer can leave a route around it. [#28861] The landed-write layer + * (`landed-write-answer.ts`) walks it too. */ export function deriveThroughSeam( api: T, @@ -425,6 +437,8 @@ export function deriveThroughSeam( return (name: string, ...rest: unknown[]) => wrapRepository(name, value.call(target, name, ...rest)); case 'sudo': case 'withRunAs': + case PLATFORM_SYSTEM_API: + case ACTION_DOOR_API: return (...args: unknown[]) => wrap(value.apply(target, args)); case 'transaction': return (callback: unknown, ...rest: unknown[]) => From 7bcc47f6ddd9c81c8788d5bdff49f917f14db4d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:58:17 +0000 Subject: [PATCH 2/7] test(runtime): pin platformSystemApi on the action door's api (mark kept, walk served, audit and permanent-delete controls) Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- ...or-platform-system-api.integration.test.ts | 223 ++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 packages/runtime/src/action-door-platform-system-api.integration.test.ts diff --git a/packages/runtime/src/action-door-platform-system-api.integration.test.ts b/packages/runtime/src/action-door-platform-system-api.integration.test.ts new file mode 100644 index 00000000000..4511da6de13 --- /dev/null +++ b/packages/runtime/src/action-door-platform-system-api.integration.test.ts @@ -0,0 +1,223 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The platform's own system api (`platformSystemApi`, objectql) over the api an + * action door hands its handler (`buildActionApi`), a host code action + * handler's included. + * + * - It keeps the `'action'` app-automation mark: that api, and every api + * derived from it, carries the action door's origin flag, and on a flagged + * api `platformSystemApi` answers what `sudo()` answers. So the handler's + * writes to the identity-assignment objects through it are refused as + * `content/docs/permissions/system-context.mdx` says (the identity-assignment + * refusal), and its insert is owner-stamped as an action body's is. + * - What it returns stays inside runtime's walk (`deriveThroughSeam`): the + * stored-metadata read seam and the landed-write answer, both layers of + * `buildActionApi`, report it served. + * - CONTROL: the api the audit writer holds (a hook registered in code, fired + * by the action api's write) is not the action door'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 host + * 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'; +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); + +/** The idempotence markers of `buildActionApi`'s two layers: each reads `true` on an api its walk serves. */ +const SERVED_BY_READ_SEAM = Symbol.for('objectstack.runtime.storedMetadataReaderSeam'); +const SERVED_BY_LANDED_WRITE_ANSWER = Symbol.for('objectstack.runtime.landedWritesAnswered'); + +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.action-door-platform-system-api', + name: 'action door 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 api an action door hands its handler, from the caller's envelope. */ +function actionApi(engine: ObjectQL): any { + return buildActionApi({} as never, engine, { ...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): void { + expect(err, `insert on ${object} through platformSystemApi 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 action door's api keeps the 'action' mark", () => { + for (const object of OBJECTS) { + it(`an insert into ${object} through it, through its sudo() and inside its transaction is refused, and nothing lands`, async () => { + const engine = await boot(); + const api = actionApi(engine); + + expectIdentityRefused(await refusal(() => platformSystemApi(api)!.object(object).insert(ROWS[object]('direct'))), object); + expectIdentityRefused(await refusal(() => platformSystemApi(api.sudo())!.object(object).insert(ROWS[object]('sudo'))), object); + expectIdentityRefused( + await refusal(() => api.transaction(async (trx: any) => platformSystemApi(trx)!.object(object).insert(ROWS[object]('trx')))), + object, + ); + + for (const id of ['direct', 'sudo', 'trx']) 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(); + await platformSystemApi(actionApi(engine))!.object('qa_note').insert({ id: 'note_1', title: 'by handler' }); + expect(await stored(engine, 'qa_note', 'note_1')).toMatchObject({ owner_id: CALLER.userId }); + }, 30000); +}); + +describe("what platformSystemApi derives from the action door's api stays inside runtime's walk", () => { + it('both layers of buildActionApi serve it, as they serve sudo()', async () => { + const engine = await boot(); + const api = actionApi(engine); + const actionDoor = Symbol.for('objectstack.objectql.actionDoorApi'); + for (const derived of [platformSystemApi(api), platformSystemApi(api.sudo()), api[actionDoor](), api.sudo()]) { + expect(derived[SERVED_BY_READ_SEAM]).toBe(true); + expect(derived[SERVED_BY_LANDED_WRITE_ANSWER]).toBe(true); + } + // CONTROL: the markers are the walk's, not a property every api answers. + const bare = engine.createContext({ isSystem: true }); + expect((bare as any)[SERVED_BY_READ_SEAM]).toBeUndefined(); + expect((platformSystemApi(bare) as any)[SERVED_BY_LANDED_WRITE_ANSWER]).toBeUndefined(); + }, 30000); +}); + +describe("CONTROL: the api the audit writer holds is not the action door's", () => { + it("a hook registered in code, fired by the action api'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' }); + + await actionApi(engine).object('qa_note').insert({ id: 'note_1', title: 'by handler' }); + + 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'); + expect(await stored(engine, 'sys_member', 'by_sudo')).toBe(null); + }, 30000); +}); + +describe("CONTROL: the action door's origin flag is not the app-authored flag", () => { + it("the host handler's permanent delete still runs, through its api and through platformSystemApi on it", async () => { + const engine = await boot(); + const api = actionApi(engine); + await api.object('qa_note').insert({ id: 'note_1', title: 'one' }); + await api.object('qa_note').insert({ id: 'note_2', title: 'two' }); + + await api.object('qa_note').delete({ where: { id: 'note_1' }, permanent: true }); + await platformSystemApi(api)!.object('qa_note').delete({ where: { id: 'note_2' }, permanent: true }); + + expect(await stored(engine, 'qa_note', 'note_1')).toBe(null); + expect(await stored(engine, 'qa_note', 'note_2')).toBe(null); + }, 30000); +}); From 3f0978d621851f33dea30ea51ea9578515151ac2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 06:19:14 +0000 Subject: [PATCH 3/7] test(objectql): the ScopedContext symbol roster counts the action door's member, unexported; changeset Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- ...35174-action-api-platform-system-api-mark.md | 17 +++++++++++++++++ packages/objectql/src/hook-run-as.test.ts | 5 ++++- 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 .changeset/35174-action-api-platform-system-api-mark.md diff --git a/.changeset/35174-action-api-platform-system-api-mark.md b/.changeset/35174-action-api-platform-system-api-mark.md new file mode 100644 index 00000000000..03dbcb3723d --- /dev/null +++ b/.changeset/35174-action-api-platform-system-api-mark.md @@ -0,0 +1,17 @@ +--- +'@objectstack/objectql': patch +'@objectstack/runtime': patch +--- + +fix(objectql, runtime): `platformSystemApi` on an action handler's `ctx.api` keeps the `'action'` mark, and what it returns stays wrapped + +Clause-②: no +Metadata-protocol: none + +`platformSystemApi(api)` (new in this release, from `@objectstack/objectql`) takes the app-automation elevation mark and `flowRunId` off a hook's api, so the audit writer's own ledger rows are not judged as an automation's insert. On the `ctx.api` an action door hands a host code action handler (`engine.registerAction`) it took the `'action'` mark off too, so a handler handing its own api to it could write `sys_member`, `sys_user_position`, `sys_user_permission_set` and `sys_invitation` as a platform writer, against the documented refusal for action handlers. What it returned also bypassed the two layers runtime puts on that api: the stored-metadata read projection and the answer for a write that landed while its parent roll-up could not be recomputed. + +- The api an action door builds now carries its own origin flag, kept by every api derived from it (`sudo()`, `withRunAs(...)`, a transaction's context). 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), and its inserts are owner-stamped with the invoking user, as the handler's own are. +- 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 `platformSystemApi` derives, so it is served through the stored-metadata read seam and the landed-write answer like `ctx.api.sudo()`. +- No new export: the flag's key is a `Symbol.for` key neither package entry exports. diff --git a/packages/objectql/src/hook-run-as.test.ts b/packages/objectql/src/hook-run-as.test.ts index 039f1ff0ebe..f07fa4efc67 100644 --- a/packages/objectql/src/hook-run-as.test.ts +++ b/packages/objectql/src/hook-run-as.test.ts @@ -453,7 +453,10 @@ describe('#14010 Hook.runAs — the identity a hook\'s ctx.api presents', () => // exported, only the reader `platformSystemApi` is. expect('PLATFORM_SYSTEM_API' in entry).toBe(false); expect(typeof (entry as Record).platformSystemApi).toBe('function'); - expect(Object.getOwnPropertySymbols(ScopedContext.prototype)).toHaveLength(4); + // The action door's api (`ACTION_DOOR_API`, `platform-system-api.ts`) is the fifth: runtime names + // its key through `Symbol.for`, and the package entry does not export it. + expect('ACTION_DOOR_API' in entry).toBe(false); + expect(Object.getOwnPropertySymbols(ScopedContext.prototype)).toHaveLength(5); }); it('a resolver failure keeps the UNSEEDED pin — narrower, never elevated — and says so once at warn', async () => { From bb4bdda0b6c708ab4b43869e3612c20d090722be Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 06:40:39 +0000 Subject: [PATCH 4/7] refactor(runtime): carry the action door's origin flag as a runtime layer, not an engine member The engine-side flag grew packages/objectql/src/engine.ts past its facade line ceiling. The action door's api is now built over a provenance layer on the shared walk: it and every api derived from it carry the action door's own origin flag, and on each the platform's own system api is answered by sudo(), the 'action' mark kept. objectql keeps only its module header edits (N1, the guard's two apis); engine.ts, engine-scoped-context.ts and the ScopedContext symbol roster pin are back to main. Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- ...174-action-api-platform-system-api-mark.md | 7 +-- .../objectql/src/engine-scoped-context.ts | 30 +++------ packages/objectql/src/engine.ts | 24 +------- packages/objectql/src/hook-run-as.test.ts | 5 +- packages/objectql/src/platform-system-api.ts | 61 ++++++++----------- ...or-platform-system-api.integration.test.ts | 14 +++-- packages/runtime/src/action-execution.ts | 50 ++++++++++----- .../src/stored-metadata-reader-seam.ts | 32 +++++----- 8 files changed, 97 insertions(+), 126 deletions(-) diff --git a/.changeset/35174-action-api-platform-system-api-mark.md b/.changeset/35174-action-api-platform-system-api-mark.md index 03dbcb3723d..257c06b5dd1 100644 --- a/.changeset/35174-action-api-platform-system-api-mark.md +++ b/.changeset/35174-action-api-platform-system-api-mark.md @@ -1,17 +1,16 @@ --- -'@objectstack/objectql': patch '@objectstack/runtime': patch --- -fix(objectql, runtime): `platformSystemApi` on an action handler's `ctx.api` keeps the `'action'` mark, and what it returns stays wrapped +fix(runtime): `platformSystemApi` on an action handler's `ctx.api` keeps the `'action'` mark, and what it returns stays wrapped Clause-②: no Metadata-protocol: none `platformSystemApi(api)` (new in this release, from `@objectstack/objectql`) takes the app-automation elevation mark and `flowRunId` off a hook's api, so the audit writer's own ledger rows are not judged as an automation's insert. On the `ctx.api` an action door hands a host code action handler (`engine.registerAction`) it took the `'action'` mark off too, so a handler handing its own api to it could write `sys_member`, `sys_user_position`, `sys_user_permission_set` and `sys_invitation` as a platform writer, against the documented refusal for action handlers. What it returned also bypassed the two layers runtime puts on that api: the stored-metadata read projection and the answer for a write that landed while its parent roll-up could not be recomputed. -- The api an action door builds now carries its own origin flag, kept by every api derived from it (`sudo()`, `withRunAs(...)`, a transaction's context). 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), and its inserts are owner-stamped with the invoking user, as the handler's own are. +- The api an action door builds now carries its own origin flag, a runtime layer beneath its other two, kept by every api derived from it (`sudo()`, `withRunAs(...)`, a transaction's context). 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), and its inserts are owner-stamped with the invoking user, as the handler's own are. - 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 `platformSystemApi` derives, so it is served through the stored-metadata read seam and the landed-write answer like `ctx.api.sudo()`. -- No new export: the flag's key is a `Symbol.for` key neither package entry exports. +- 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. diff --git a/packages/objectql/src/engine-scoped-context.ts b/packages/objectql/src/engine-scoped-context.ts index c23e622c201..68808d82a76 100644 --- a/packages/objectql/src/engine-scoped-context.ts +++ b/packages/objectql/src/engine-scoped-context.ts @@ -12,8 +12,7 @@ * which the codemod refuses to move (`foreign-private`), so each writes it * through that instance's own host setter. * The body of `[DETACHED_HOOK_RUN]` (#33651) was written here, in the same - * stub-and-facet shape, and so were the bodies of `[PLATFORM_SYSTEM_API]` and - * `[ACTION_DOOR_API]`. + * stub-and-facet shape, and so was the body of `[PLATFORM_SYSTEM_API]`. * * A MOVE, not a redesign. {@link ScopedContextFacet} is a stateless facet of * `ScopedContext`: each static method of it is the body of the `ScopedContext` @@ -64,7 +63,6 @@ import type { ObjectQL } from './engine.js'; */ export interface ScopedContextHost { appAuthored: ScopedContext['appAuthored']; - actionDoor: ScopedContext['actionDoor']; derive: ScopedContext['derive']; readonly engine: ScopedContext['engine']; readonly executionContext: ScopedContext['executionContext']; @@ -84,25 +82,12 @@ export class ScopedContextFacet { * (`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); - const host = scopedContextHost.of(child); - host.appAuthored = this.appAuthored; - host.actionDoor = this.actionDoor; + scopedContextHost.of(child).appAuthored = this.appAuthored; return child; } - /** - * The body of `ScopedContext#[ACTION_DOOR_API]`; the method's docblock there - * is its contract. A child over the same context, its private `actionDoor` - * written through its own host, as in {@link ScopedContextFacet.derive}. - */ - static actionDoorApi(this: Pick): ScopedContext { - const api = this.derive(this.executionContext); - scopedContextHost.of(api).actionDoor = true; - return api; - } - /** * The body of `ScopedContext#[APP_AUTHORED_HOOK_API]`; the method's docblock * there is its contract. The new api's private `appAuthored` is written @@ -139,12 +124,11 @@ 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, and the api an action door hands its handler, - * are never the platform's: there it is that api's own - * {@link ScopedContextFacet.sudo}, provenance kept. + * An app-authored hook's api is never the platform's: there it is that + * api's own {@link ScopedContextFacet.sudo}, provenance kept. */ - static platformSystemApi(this: Pick): ScopedContext { - if (this.appAuthored || this.actionDoor) return ScopedContextFacet.sudo.call(this); + static platformSystemApi(this: Pick): ScopedContext { + if (this.appAuthored) 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/engine.ts b/packages/objectql/src/engine.ts index 8c966025428..870455531f8 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -246,7 +246,7 @@ import { stripReadonlyFields, staticReadonlyInsertSubject } from './validation/r // and points at `ctx.previous` — the module owns the measurement and the // reason the explanation cannot be composed any further downstream. import { UnscopedHookApi, SEED_USER_GRANTS, APP_AUTHORED_HOOK_API, type HookRunAs, type HookRunAsRef, type RunAsDerivableApi } from './hook-run-as.js'; -import { ACTION_DOOR_API, PLATFORM_SYSTEM_API } from './platform-system-api.js'; +import { PLATFORM_SYSTEM_API } from './platform-system-api.js'; import { DETACHED_HOOK_RUN, type UNIT_ROLLED_BACK, type UnitCommitQueue } from './unit-detach.js'; // [#6457] The master-detail header a `parent`-scoped predicate reads is made // total over the MASTER's declared fields before it leaves this engine — the @@ -6466,14 +6466,6 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi { */ private appAuthored = false; - /** - * Set on the api an action door hands its handler ({@link ACTION_DOOR_API}) - * and kept by every api derived from it ({@link derive}); read by - * {@link PLATFORM_SYSTEM_API} alone. Not {@link appAuthored}, which also - * refuses a permanent delete (ADR-0148 D3) that a host code handler keeps. - */ - private actionDoor = false; - private derive(executionContext: ExecutionContext): ScopedContext { // [#30975] The body moved to `engine-scoped-context.ts`, its docblock with it (see `ScopedContextHost`). return ScopedContextFacet.derive.call(scopedContextHost.of(this), executionContext); @@ -6517,18 +6509,6 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi { return ScopedContextFacet.platformSystemApi.call(scopedContextHost.of(this)); } - /** - * The api an action door hands its handler: this api's context, carrying the - * action-door origin flag, which every api derived from it keeps. On it, and - * on each of those, {@link PLATFORM_SYSTEM_API} answers what `sudo()` - * answers, the `'action'` mark kept (`platform-system-api.ts`). Keyed on an - * unexported symbol that runtime's `buildActionApi` names through - * `Symbol.for`. - */ - [ACTION_DOOR_API](): ScopedContext { - return ScopedContextFacet.actionDoorApi.call(scopedContextHost.of(this)); - } - /** * [#25653] The api an app-authored hook runs with — see * {@link APP_AUTHORED_HOOK_API} (`hook-run-as.ts`), where the line between @@ -6860,8 +6840,6 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi { scopedContextHost.install((instance) => ({ get appAuthored() { return instance.appAuthored; }, set appAuthored(v) { instance.appAuthored = v; }, - get actionDoor() { return instance.actionDoor; }, - set actionDoor(v) { instance.actionDoor = v; }, derive: (...a) => instance.derive(...a), get engine() { return instance.engine; }, get executionContext() { return instance.executionContext; }, diff --git a/packages/objectql/src/hook-run-as.test.ts b/packages/objectql/src/hook-run-as.test.ts index f07fa4efc67..039f1ff0ebe 100644 --- a/packages/objectql/src/hook-run-as.test.ts +++ b/packages/objectql/src/hook-run-as.test.ts @@ -453,10 +453,7 @@ describe('#14010 Hook.runAs — the identity a hook\'s ctx.api presents', () => // exported, only the reader `platformSystemApi` is. expect('PLATFORM_SYSTEM_API' in entry).toBe(false); expect(typeof (entry as Record).platformSystemApi).toBe('function'); - // The action door's api (`ACTION_DOOR_API`, `platform-system-api.ts`) is the fifth: runtime names - // its key through `Symbol.for`, and the package entry does not export it. - expect('ACTION_DOOR_API' in entry).toBe(false); - expect(Object.getOwnPropertySymbols(ScopedContext.prototype)).toHaveLength(5); + expect(Object.getOwnPropertySymbols(ScopedContext.prototype)).toHaveLength(4); }); it('a resolver failure keeps the UNSEEDED pin — narrower, never elevated — and says so once at warn', async () => { diff --git a/packages/objectql/src/platform-system-api.ts b/packages/objectql/src/platform-system-api.ts index 6945c20405d..8c551cd9ed3 100644 --- a/packages/objectql/src/platform-system-api.ts +++ b/packages/objectql/src/platform-system-api.ts @@ -29,39 +29,37 @@ * The write's context, elevated as `sudo()` elevates it — every other key kept, * so the rows stay in the write's unit of work, its organization and its * attribution — without the app-automation mark and without `flowRunId`. The - * api is derived as every api is (`derive`): not app-authored and not the - * action door's, so its own `sudo()` adds no mark. + * api is derived as every api is (`derive`): not app-authored, so its own + * `sudo()` adds no mark. * * ⛔ 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. - * The engine enforces that line on the two apis it knows are the - * automation's, and on every api derived from either: + * That line holds on the two apis the automation is handed, and on every api + * derived from either: * * - an app-authored hook's api (its handler's `ctx.api`, - * `APP_AUTHORED_HOOK_API`); + * `APP_AUTHORED_HOOK_API`): the engine enforces it, and this answers + * exactly what that api's `sudo()` answers — the `'hook'` mark when the + * context carries none, the mark it carries otherwise, `flowRunId` kept; * - the api an action door hands its handler, a host code action handler's - * included: runtime's `buildActionApi` derives it through - * {@link ACTION_DOOR_API}, and that origin flag is a different one from - * the app-authored flag, because the app-authored flag also refuses a - * permanent delete (ADR-0148 D3), which a host handler keeps. + * included (runtime's `buildActionApi`): runtime's layer over it carries + * 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. * - * On either, this answers exactly what that api's `sudo()` answers — the - * mark the context carries (`'action'` on an action door's api; `'hook'` on an - * app-authored hook's when it carries none), `flowRunId` kept — so a handler - * handing its own api here gains nothing, and its writes to the - * identity-assignment objects and the append-only ones are judged as its own. - * The api the audit writer holds is neither: `buildHookApi` builds a fresh - * `ScopedContext` over the write's context, with neither flag, even when an - * action's write fired the hook and the context carries the `'action'` mark. - * The flag is not a security boundary: a host handler's package registered - * through the engine it holds, whose `createContext({ isSystem: true })` - * already builds a system api with neither the mark nor the run. It keeps the - * documented answer for the api the handler was handed. - * - * What this returns over runtime's wrapped `ctx.api` stays wrapped: runtime's - * `deriveThroughSeam` (the stored-metadata read seam and the landed-write - * answer) walks this symbol member as it walks `sudo()`. + * 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 + * 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: + * a host handler's package registered through the engine it holds, whose + * `createContext({ isSystem: true })` already builds a system api with neither + * the mark nor the run. They keep the documented answer for the api a handler + * was handed. And what this returns over runtime's wrapped `ctx.api` stays + * wrapped: runtime's `deriveThroughSeam` (the stored-metadata read seam and + * the landed-write answer) walks this symbol member as it walks `sudo()`. * * A symbol, and ⛔ not re-exported from either package entry, for the reason * `SEED_USER_GRANTS` gives (`hook-run-as.ts`): the method is no nameable member @@ -70,7 +68,8 @@ * `Symbol()`, because the reader and the engine may be different copies of * this package — its ESM and CJS builds, or its two entries (`.` and * `./core`) served from different builds — and the key must be the same in - * each, or the reader would silently fall back to `sudo()`. + * each, or the reader would silently fall back to `sudo()`; and runtime names + * it too (`deriveThroughSeam`), which no export can serve. */ import type { ScopedContext } from './engine.js'; @@ -78,16 +77,6 @@ import type { ScopedContext } from './engine.js'; /** The key the engine's `ScopedContext` derives the platform's own system api under. */ export const PLATFORM_SYSTEM_API: unique symbol = Symbol.for('objectstack.objectql.platformSystemApi'); -/** - * The key the engine's `ScopedContext` derives the action door's api under: - * the same context, carrying the action-door origin flag, which this api and - * every api derived from it keep. Read by {@link platformSystemApi} alone. - * Runtime's `buildActionApi` names it through `Symbol.for`, for the reason the - * header gives for {@link PLATFORM_SYSTEM_API}, and ⛔ it is not re-exported - * from either package entry either. - */ -export const ACTION_DOOR_API: unique symbol = Symbol.for('objectstack.objectql.actionDoorApi'); - interface PlatformSystemDerivableApi { [PLATFORM_SYSTEM_API](): ScopedContext; } diff --git a/packages/runtime/src/action-door-platform-system-api.integration.test.ts b/packages/runtime/src/action-door-platform-system-api.integration.test.ts index 4511da6de13..b6c3e4d306d 100644 --- a/packages/runtime/src/action-door-platform-system-api.integration.test.ts +++ b/packages/runtime/src/action-door-platform-system-api.integration.test.ts @@ -6,8 +6,9 @@ * handler's included. * * - It keeps the `'action'` app-automation mark: that api, and every api - * derived from it, carries the action door's origin flag, and on a flagged - * api `platformSystemApi` answers what `sudo()` answers. So the handler's + * derived from it, carries the action door's origin flag (runtime's + * provenance layer), and on a flagged api `platformSystemApi` answers what + * `sudo()` answers. So the handler's * writes to the identity-assignment objects through it are refused as * `content/docs/permissions/system-context.mdx` says (the identity-assignment * refusal), and its insert is owner-stamped as an action body's is. @@ -60,6 +61,8 @@ const OBJECTS = Object.keys(ROWS); /** The idempotence markers of `buildActionApi`'s two layers: each reads `true` on an api its walk serves. */ const SERVED_BY_READ_SEAM = Symbol.for('objectstack.runtime.storedMetadataReaderSeam'); const SERVED_BY_LANDED_WRITE_ANSWER = Symbol.for('objectstack.runtime.landedWritesAnswered'); +/** The action door's origin flag, `true` on every api its provenance layer serves. */ +const ACTION_DOOR_ORIGIN = Symbol.for('objectstack.runtime.actionDoorOrigin'); const engines: ObjectQL[] = []; afterEach(async () => { @@ -172,17 +175,18 @@ describe("platformSystemApi on the action door's api keeps the 'action' mark", ( }); describe("what platformSystemApi derives from the action door's api stays inside runtime's walk", () => { - it('both layers of buildActionApi serve it, as they serve sudo()', async () => { + it('both layers of buildActionApi serve it, as they serve sudo(), and it keeps the origin flag', async () => { const engine = await boot(); const api = actionApi(engine); - const actionDoor = Symbol.for('objectstack.objectql.actionDoorApi'); - for (const derived of [platformSystemApi(api), platformSystemApi(api.sudo()), api[actionDoor](), api.sudo()]) { + for (const derived of [platformSystemApi(api), platformSystemApi(api.sudo()), api.sudo()]) { expect(derived[SERVED_BY_READ_SEAM]).toBe(true); expect(derived[SERVED_BY_LANDED_WRITE_ANSWER]).toBe(true); + expect(derived[ACTION_DOOR_ORIGIN]).toBe(true); } // CONTROL: the markers are the walk's, not a property every api answers. const bare = engine.createContext({ isSystem: true }); expect((bare as any)[SERVED_BY_READ_SEAM]).toBeUndefined(); + expect((bare as any)[ACTION_DOOR_ORIGIN]).toBeUndefined(); expect((platformSystemApi(bare) as any)[SERVED_BY_LANDED_WRITE_ANSWER]).toBeUndefined(); }, 30000); }); diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 9f2300ea6af..6a0acc9b077 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -95,7 +95,7 @@ import type { FlowFailureDetails } from '@objectstack/spec/api'; import { recordNotFoundError, omitInternalFieldsFromWriteResponse } from '@objectstack/metadata-protocol'; // [#31697] The environment store's rows are the resync's: a legacy organization's rows left out off the physical column. import { isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core'; -import { ACTION_DOOR_API, serveStoredMetadataRead, serveStoredMetadataReadsThrough } from './stored-metadata-reader-seam.js'; +import { PLATFORM_SYSTEM_API, deriveThroughSeam, serveStoredMetadataRead, serveStoredMetadataReadsThrough } from './stored-metadata-reader-seam.js'; import { actionInvocationBranch, actionInvocationFailure, actionInvocationTarget, recordActionInvocation, withActionSurface } from './action-invocation-audit.js'; import type { HttpProtocolContext } from './http-dispatcher.js'; // The ONE admitted sequence every action door shares; `invokeBusinessAction` @@ -3927,24 +3927,15 @@ export function buildActionExecutionContext(ec: any): Record { * derives. That layer sits beneath the reader seam, so the answer is served * like any write's return. * - * The context is derived through objectql's action-door member - * (`ACTION_DOOR_API`), so it and every api derived from it carry the action - * door's origin flag: on it, `platformSystemApi(ctx.api)` answers what - * `ctx.api.sudo()` answers, the `'action'` mark kept, and the handler's writes - * to the identity-assignment and append-only objects stay judged as its own - * (`platform-system-api.ts`, objectql). Not the app-authored flag: a host - * handler keeps the engine's permanent delete (ADR-0148 D3). An api with no - * such member (an engine double) has no `platformSystemApi` member either, so - * there is nothing for the flag to guard. + * It is built over {@link keepActionDoorProvenance}, beneath both layers, so + * it and every api derived from it carry the action door's origin flag: on + * it, `platformSystemApi(ctx.api)` answers what `ctx.api.sudo()` answers. */ export function buildActionApi(_deps: ActionExecutionDeps, ql: any, ec: any): any | undefined { if (!ql || typeof ql.createContext !== 'function') return undefined; - const served = (scoped: any) => + const served = (scoped: unknown) => serveStoredMetadataReadsThrough( - answerLandedWritesDespiteStaleSummary( - typeof scoped?.[ACTION_DOOR_API] === 'function' ? scoped[ACTION_DOOR_API]() : scoped, - ACTION_API_SURFACE, - ), + answerLandedWritesDespiteStaleSummary(keepActionDoorProvenance(scoped), ACTION_API_SURFACE), ql, ); try { @@ -3961,6 +3952,35 @@ export function buildActionApi(_deps: ActionExecutionDeps, ql: any, ec: any): an } } +/** The action door's origin flag: `true` on the api {@link buildActionApi} builds, and on every api derived from it. */ +const ACTION_DOOR_ORIGIN = Symbol.for('objectstack.runtime.actionDoorOrigin'); + +/** On the action door's api, the platform's own system api is answered by `sudo()`. */ +const ACTION_DOOR_ANSWERS: ReadonlyMap = new Map([[PLATFORM_SYSTEM_API, 'sudo']]); + +/** + * The action door's provenance layer: `api`, and every api derived from it + * (the shared walk, `deriveThroughSeam`), carry {@link ACTION_DOOR_ORIGIN}, + * and on each the platform's own system api (`platformSystemApi`, objectql) + * is the api's `sudo()`: the `'action'` mark {@link buildActionExecutionContext} + * sets, and any `flowRunId`, stay. So a handler handing its own `ctx.api` to + * `platformSystemApi` gains nothing, and its writes to the identity-assignment + * objects are refused as an action handler's are + * (`content/docs/permissions/system-context.mdx`). `platformSystemApi` takes + * the mark off only the api the audit writer holds, a hook api the engine + * builds, which this layer never wraps. + * + * A flag of the action door's own, and ⛔ not the engine's app-authored one: + * that one also refuses a permanent delete (ADR-0148 D3), and a host code + * handler keeps the engine's permanent delete. Repositories pass through + * unchanged. Not a security boundary: the handler's package registered + * through the engine it holds, whose `createContext({ isSystem: true })` + * already builds a system api with neither the mark nor the run. + */ +function keepActionDoorProvenance(api: T): T { + return deriveThroughSeam(api, ACTION_DOOR_ORIGIN, (_name, repo) => repo, ACTION_DOOR_ANSWERS); +} + /** [#28861] The surfaces the stale-column line names, for an action handler's two data handles. */ const ACTION_API_SURFACE = 'action ctx.api'; const ACTION_ENGINE_SURFACE = 'action ctx.engine'; diff --git a/packages/runtime/src/stored-metadata-reader-seam.ts b/packages/runtime/src/stored-metadata-reader-seam.ts index 1879c275bad..ed18a3ae509 100644 --- a/packages/runtime/src/stored-metadata-reader-seam.ts +++ b/packages/runtime/src/stored-metadata-reader-seam.ts @@ -400,37 +400,38 @@ export function refuseStoredMetadataBodyReads(api: T): T { } /** - * The two symbol-keyed members of objectql's `ScopedContext` that derive an - * api, named through `Symbol.for` because neither package entry exports them - * (`platform-system-api.ts`, objectql): the platform's own system api - * (`platformSystemApi`) and the action door's api (`buildActionApi`'s - * derivation, `action-execution.ts`). + * The symbol-keyed member of objectql's `ScopedContext` that derives the + * platform's own system api (`platformSystemApi`, `platform-system-api.ts`), + * named through `Symbol.for` because neither package entry exports it. */ -const PLATFORM_SYSTEM_API: unique symbol = Symbol.for('objectstack.objectql.platformSystemApi'); -export const ACTION_DOOR_API: unique symbol = Symbol.for('objectstack.objectql.actionDoorApi'); +export const PLATFORM_SYSTEM_API: unique symbol = Symbol.for('objectstack.objectql.platformSystemApi'); /** * The walk both layers share: `api`, and every context it can derive — * `object(name)`, `sudo()`, `withRunAs(...)`, the api `platformSystemApi(api)` - * derives and the action door's api (the two symbol-keyed members above), the - * context a `transaction(fn)` callback receives, and the `ctx` - * `beginTransaction()` returns — with each repository passed through - * `wrapRepository`. One definition of what a scoped API can derive, so neither - * layer can leave a route around it. [#28861] The landed-write layer - * (`landed-write-answer.ts`) walks it too. + * derives ({@link PLATFORM_SYSTEM_API}), the context a `transaction(fn)` + * callback receives, and the `ctx` `beginTransaction()` returns — with each + * repository passed through `wrapRepository`. One definition of what a scoped + * API can derive, so neither layer can leave a route around it. [#28861] The + * landed-write layer (`landed-write-answer.ts`) walks it too, and so does the + * action door's provenance layer (`action-execution.ts`), which alone passes + * `answeredBy`: a member named there is answered by the member it maps to (on + * the same walk, so what it derives is wrapped as that member's result is). */ export function deriveThroughSeam( api: T, marker: symbol, wrapRepository: (name: string, repo: unknown) => unknown, + answeredBy?: ReadonlyMap, ): T { if (api === null || typeof api !== 'object') return api; if ((api as Record)[marker] === true) return api; - const wrap = (derived: unknown) => deriveThroughSeam(derived, marker, wrapRepository); + const wrap = (derived: unknown) => deriveThroughSeam(derived, marker, wrapRepository, answeredBy); return new Proxy(api as unknown as Record, { get(target, prop) { if (prop === marker) return true; - const value = Reflect.get(target, prop, target); + const answering = answeredBy?.get(prop); + const value = Reflect.get(target, answering === undefined ? prop : answering, target); if (typeof value !== 'function') return value; switch (prop) { case 'object': @@ -438,7 +439,6 @@ export function deriveThroughSeam( case 'sudo': case 'withRunAs': case PLATFORM_SYSTEM_API: - case ACTION_DOOR_API: return (...args: unknown[]) => wrap(value.apply(target, args)); case 'transaction': return (callback: unknown, ...rest: unknown[]) => From 2919fe6ac70a1cfb2a6486f176764260759fe75f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 07:00:15 +0000 Subject: [PATCH 5/7] test(runtime): pay the metadata package's load at collection in the action-door pin Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- .../src/action-door-platform-system-api.integration.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/runtime/src/action-door-platform-system-api.integration.test.ts b/packages/runtime/src/action-door-platform-system-api.integration.test.ts index b6c3e4d306d..d166114e2cc 100644 --- a/packages/runtime/src/action-door-platform-system-api.integration.test.ts +++ b/packages/runtime/src/action-door-platform-system-api.integration.test.ts @@ -26,6 +26,8 @@ */ 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'; From e7f820c3704a53ef013d3fda9c2e4e61fc73a9cc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 08:06:29 +0000 Subject: [PATCH 6/7] fix(runtime): the walk wraps the api a symbol-keyed member derives (the user-grants seeds), and the prose names execute()'s api as not covered Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- ...174-action-api-platform-system-api-mark.md | 5 +-- content/docs/permissions/system-context.mdx | 2 +- packages/objectql/src/platform-system-api.ts | 10 ++++-- ...or-platform-system-api.integration.test.ts | 17 ++++++++- packages/runtime/src/action-execution.ts | 4 ++- .../src/stored-metadata-reader-seam.ts | 36 ++++++++++++++----- 6 files changed, 57 insertions(+), 17 deletions(-) diff --git a/.changeset/35174-action-api-platform-system-api-mark.md b/.changeset/35174-action-api-platform-system-api-mark.md index 257c06b5dd1..a61cd6ccc00 100644 --- a/.changeset/35174-action-api-platform-system-api-mark.md +++ b/.changeset/35174-action-api-platform-system-api-mark.md @@ -9,8 +9,9 @@ Metadata-protocol: none `platformSystemApi(api)` (new in this release, from `@objectstack/objectql`) takes the app-automation elevation mark and `flowRunId` off a hook's api, so the audit writer's own ledger rows are not judged as an automation's insert. On the `ctx.api` an action door hands a host code action handler (`engine.registerAction`) it took the `'action'` mark off too, so a handler handing its own api to it could write `sys_member`, `sys_user_position`, `sys_user_permission_set` and `sys_invitation` as a platform writer, against the documented refusal for action handlers. What it returned also bypassed the two layers runtime puts on that api: the stored-metadata read projection and the answer for a write that landed while its parent roll-up could not be recomputed. -- The api an action door builds now carries its own origin flag, a runtime layer beneath its other two, kept by every api derived from it (`sudo()`, `withRunAs(...)`, a transaction's context). 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), and its inserts are owner-stamped with the invoking user, as the handler's own are. +- The api an action door builds now carries its own origin flag, a runtime layer beneath its other two, kept by every api derived from it (`sudo()`, `withRunAs(...)`, a transaction's context, and the api `seedHookUserGrants` / `seedHookUnreadMembership` 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), and its inserts are owner-stamped with the invoking user, as the handler's own are. - 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 `platformSystemApi` derives, so it is served through the stored-metadata read seam and the landed-write answer like `ctx.api.sudo()`. +- 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. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index ea023af6208..1729479dfe1 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, and nowhere else: 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 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` | | 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 8c551cd9ed3..76004a927b6 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 the two apis the automation is handed, and on every api - * derived from either: + * That line holds on two of the apis the automation is handed, and on every + * api derived from either: * * - an app-authored hook's api (its handler's `ctx.api`, * `APP_AUTHORED_HOOK_API`): the engine enforces it, and this answers @@ -50,7 +50,11 @@ * (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. The api the audit writer + * 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 * 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: diff --git a/packages/runtime/src/action-door-platform-system-api.integration.test.ts b/packages/runtime/src/action-door-platform-system-api.integration.test.ts index d166114e2cc..1937bcdfa91 100644 --- a/packages/runtime/src/action-door-platform-system-api.integration.test.ts +++ b/packages/runtime/src/action-door-platform-system-api.integration.test.ts @@ -28,7 +28,7 @@ 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 { ObjectQL, platformSystemApi, seedHookUserGrants, seedHookUnreadMembership } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { PermissionSetSchema } from '@objectstack/spec/security'; import { SecurityPlugin } from '@objectstack/plugin-security'; @@ -193,6 +193,21 @@ describe("what platformSystemApi derives from the action door's api stays inside }, 30000); }); +describe("what the published user-grants seeds derive from the action door's api keeps the flag and the mark", () => { + for (const [name, seed] of [['seedHookUserGrants', seedHookUserGrants], ['seedHookUnreadMembership', seedHookUnreadMembership]] as const) { + it(`${name}: the seeded api is served by all three layers, and an insert into sys_member through platformSystemApi on it is refused`, async () => { + const engine = await boot(); + const seeded: any = await seed(actionApi(engine)); + expect(seeded[ACTION_DOOR_ORIGIN]).toBe(true); + expect(seeded[SERVED_BY_READ_SEAM]).toBe(true); + expect(seeded[SERVED_BY_LANDED_WRITE_ANSWER]).toBe(true); + + expectIdentityRefused(await refusal(() => platformSystemApi(seeded)!.object('sys_member').insert(ROWS.sys_member('seeded'))), 'sys_member'); + expect(await stored(engine, 'sys_member', 'seeded')).toBe(null); + }, 30000); + } +}); + describe("CONTROL: the api the audit writer holds is not the action door's", () => { it("a hook registered in code, fired by the action api's write, takes the mark off and its platform write lands; its sudo() does not", async () => { const engine = await boot(); diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 6a0acc9b077..3fc874ada96 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -3960,7 +3960,9 @@ const ACTION_DOOR_ANSWERS: ReadonlyMap = new Map([[PLA /** * The action door's provenance layer: `api`, and every api derived from it - * (the shared walk, `deriveThroughSeam`), carry {@link ACTION_DOOR_ORIGIN}, + * (the shared walk, `deriveThroughSeam`: `sudo()`, `withRunAs(...)`, a + * transaction's context, and the api a symbol-keyed member derives, the + * user-grants seed's included), carry {@link ACTION_DOOR_ORIGIN}, * and on each the platform's own system api (`platformSystemApi`, objectql) * is the api's `sudo()`: the `'action'` mark {@link buildActionExecutionContext} * sets, and any `flowRunId`, stay. So a handler handing its own `ctx.api` to diff --git a/packages/runtime/src/stored-metadata-reader-seam.ts b/packages/runtime/src/stored-metadata-reader-seam.ts index ed18a3ae509..da23f6d7571 100644 --- a/packages/runtime/src/stored-metadata-reader-seam.ts +++ b/packages/runtime/src/stored-metadata-reader-seam.ts @@ -402,17 +402,19 @@ export function refuseStoredMetadataBodyReads(api: T): T { /** * The symbol-keyed member of objectql's `ScopedContext` that derives the * platform's own system api (`platformSystemApi`, `platform-system-api.ts`), - * named through `Symbol.for` because neither package entry exports it. + * named through `Symbol.for` because neither package entry exports it: the + * action door's provenance layer answers it with `sudo()` (`answeredBy`). */ export const PLATFORM_SYSTEM_API: unique symbol = Symbol.for('objectstack.objectql.platformSystemApi'); /** * The walk both layers share: `api`, and every context it can derive — - * `object(name)`, `sudo()`, `withRunAs(...)`, the api `platformSystemApi(api)` - * derives ({@link PLATFORM_SYSTEM_API}), the context a `transaction(fn)` - * callback receives, and the `ctx` `beginTransaction()` returns — with each - * repository passed through `wrapRepository`. One definition of what a scoped - * API can derive, so neither layer can leave a route around it. [#28861] The + * `object(name)`, `sudo()`, `withRunAs(...)`, the api a symbol-keyed member + * derives (`platformSystemApi(api)`'s {@link PLATFORM_SYSTEM_API}, the + * user-grants seed), the context a `transaction(fn)` callback receives, and + * the `ctx` `beginTransaction()` returns — with each repository passed + * through `wrapRepository`. One definition of what a scoped API can derive, + * so neither layer can leave a route around it. [#28861] The * landed-write layer (`landed-write-answer.ts`) walks it too, and so does the * action door's provenance layer (`action-execution.ts`), which alone passes * `answeredBy`: a member named there is answered by the member it maps to (on @@ -438,7 +440,6 @@ export function deriveThroughSeam( return (name: string, ...rest: unknown[]) => wrapRepository(name, value.call(target, name, ...rest)); case 'sudo': case 'withRunAs': - case PLATFORM_SYSTEM_API: return (...args: unknown[]) => wrap(value.apply(target, args)); case 'transaction': return (callback: unknown, ...rest: unknown[]) => @@ -454,8 +455,25 @@ export function deriveThroughSeam( const begun = await value.apply(target, args); return isPlainRecord(begun) && 'ctx' in begun ? { ...begun, ctx: wrap(begun.ctx) } : begun; }; - default: - return value.bind(target); + default: { + if (typeof prop !== 'symbol') return value.bind(target); + // A symbol-keyed member: objectql's own, which no package entry + // names, reached through a published reader (`platformSystemApi`, + // `seedHookUserGrants`, `seedHookUnreadMembership`). One that derives + // an api answers one of this api's own kind, now or through a + // promise, and that api is wrapped as `sudo()`'s is; any other + // answer passes through as it is. + const derivedOrAsIs = (answer: unknown) => + answer !== null && typeof answer === 'object' && Object.getPrototypeOf(answer) === Object.getPrototypeOf(target) + ? wrap(answer) + : answer; + return (...args: unknown[]) => { + const answer = value.apply(target, args); + return typeof (answer as PromiseLike | null)?.then === 'function' + ? (answer as PromiseLike).then(derivedOrAsIs) + : derivedOrAsIs(answer); + }; + } } }, }) as unknown as T; From 6bec461ee09b50c47158cb0e88996b2312a811e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 08:22:48 +0000 Subject: [PATCH 7/7] test(runtime): the seed pins assert the refusal before the layer markers Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- .../src/action-door-platform-system-api.integration.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/runtime/src/action-door-platform-system-api.integration.test.ts b/packages/runtime/src/action-door-platform-system-api.integration.test.ts index 1937bcdfa91..5405f880a67 100644 --- a/packages/runtime/src/action-door-platform-system-api.integration.test.ts +++ b/packages/runtime/src/action-door-platform-system-api.integration.test.ts @@ -198,12 +198,12 @@ describe("what the published user-grants seeds derive from the action door's api it(`${name}: the seeded api is served by all three layers, and an insert into sys_member through platformSystemApi on it is refused`, async () => { const engine = await boot(); const seeded: any = await seed(actionApi(engine)); - expect(seeded[ACTION_DOOR_ORIGIN]).toBe(true); - expect(seeded[SERVED_BY_READ_SEAM]).toBe(true); - expect(seeded[SERVED_BY_LANDED_WRITE_ANSWER]).toBe(true); expectIdentityRefused(await refusal(() => platformSystemApi(seeded)!.object('sys_member').insert(ROWS.sys_member('seeded'))), 'sys_member'); expect(await stored(engine, 'sys_member', 'seeded')).toBe(null); + expect(seeded[ACTION_DOOR_ORIGIN]).toBe(true); + expect(seeded[SERVED_BY_READ_SEAM]).toBe(true); + expect(seeded[SERVED_BY_LANDED_WRITE_ANSWER]).toBe(true); }, 30000); } });