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..a61cd6ccc00 --- /dev/null +++ b/.changeset/35174-action-api-platform-system-api-mark.md @@ -0,0 +1,17 @@ +--- +'@objectstack/runtime': patch +--- + +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, 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 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 5da5efe131d..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. 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 5e3fcb1dd4c..76004a927b6 100644 --- a/packages/objectql/src/platform-system-api.ts +++ b/packages/objectql/src/platform-system-api.ts @@ -29,33 +29,41 @@ * 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, 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. + * That line holds on two of the apis the automation is handed, 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 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`): 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. + * + * 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 + * 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 @@ -64,7 +72,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'; 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..5405f880a67 --- /dev/null +++ b/packages/runtime/src/action-door-platform-system-api.integration.test.ts @@ -0,0 +1,244 @@ +// 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 (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. + * - 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'; +// Paid at collection: the action path reaches a dynamic import of this package inside a clocked case. +import '@objectstack/metadata'; +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'; +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'); +/** 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 () => { + 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(), and it keeps the origin flag', async () => { + const engine = await boot(); + const api = actionApi(engine); + 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); +}); + +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)); + + 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); + } +}); + +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); +}); diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index d138e683b75..3fc874ada96 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 { 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` @@ -3926,11 +3926,18 @@ 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. + * + * 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: unknown) => - serveStoredMetadataReadsThrough(answerLandedWritesDespiteStaleSummary(scoped, ACTION_API_SURFACE), ql); + serveStoredMetadataReadsThrough( + answerLandedWritesDespiteStaleSummary(keepActionDoorProvenance(scoped), ACTION_API_SURFACE), + ql, + ); try { return served(ql.createContext(buildActionExecutionContext(ec))); } catch { @@ -3945,6 +3952,37 @@ 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`: `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 + * `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 bd13aa08549..da23f6d7571 100644 --- a/packages/runtime/src/stored-metadata-reader-seam.ts +++ b/packages/runtime/src/stored-metadata-reader-seam.ts @@ -399,26 +399,41 @@ export function refuseStoredMetadataBodyReads(api: T): T { return deriveThroughSeam(api, BODY_READS_REFUSED, refuseBodyRepositoryReads); } +/** + * 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: 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 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 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 + * 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': @@ -440,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;