diff --git a/.changeset/write-tenant-options-wall.md b/.changeset/write-tenant-options-wall.md new file mode 100644 index 00000000000..570710c1840 --- /dev/null +++ b/.changeset/write-tenant-options-wall.md @@ -0,0 +1,22 @@ +--- +'@objectstack/plugin-security': patch +'@objectstack/objectql': patch +--- + +fix(plugin-security): a write's tenant options never reach past the caller's organization wall + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +Who sees it: a non-system write (insert, update, delete, purge) on a tenant-scoped object under a walled tenancy posture (`isolated`, `group`), whose option bag carries `tenantId` or `tenantIds`, whether the caller passed them or a before-hook set them. + +- The option bag, as the write's before-hooks leave it, is held to the caller's organization wall (ADR-0095 D1) where the engine builds the driver's options: the caller's own Layer 0 for the operation, intersected with the delegator's for an on-behalf-of write. Keys inside the wall pass as before. +- On an insert, every key the bag carries is held to that wall, the active organization and, under `group`, the caller's memberships included: an on-behalf-of insert lands only in an organization the delegator's membership also backs. On an update, a delete or a purge, a key is held to it where it asks beyond the caller's active organization (under `group`, its memberships). +- A key that names an organization outside the wall, or clears the scope (`null`, `''`, a value that is not an organization id), refuses the whole write with `403 PERMISSION_DENIED` before any driver runs. It is refused, never narrowed. +- Not reached: system contexts (an app-authored elevation keeps its own wall, unchanged), a platform operator on a posture-permitting object, objects outside the tenancy machinery, and the `single` posture. A write that sets no tenant option is unchanged, and a caller the wall denies is answered as it was. +- `@objectstack/objectql`: a check on `OperationContext.driverTenantScopeCheck` may opt in (`judgesEveryExplicitKey: true`) to be asked about every explicit tenant key on an insert's landing; every other build, and every check that does not opt in, is asked as before. The docblock names the ordinary write as a second installer. + +**BREAKING** for a non-system caller whose write's option bag names an organization outside its organization wall, or clears the scope: it answers `403 PERMISSION_DENIED` and writes nothing. That includes an on-behalf-of insert naming an organization the acting caller belongs to and the delegator does not. +The fix for a caller: keep a write's `tenantId` / `tenantIds` inside the caller's organizations, or leave them unset so the write lands in the active organization. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 9c417afe767..646cc60266e 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -101,7 +101,7 @@ bugs — it is the protection or the side effect that silently does not happen. |:--|:---|:---|:---|:---| | 1 | **The whole security middleware short-circuits** before any gate runs | plugin-security | Get: every CRUD/FLS/tenant/owner gate below skipped in one branch. Lose: every gate under it in this lane at once, down to and including the write-bypass row that widens the effective write scope to `org` (row 7) — this is the single largest behaviour on the page | `registerAuthzMiddleware` | | 1b | **App-authored automation's system context is REFUSED governed writes to the identity-assignment objects** — a flow run's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and an action body's; checked ahead of the middleware's short-circuit, beside the append-only refusal (`assertAppAutomationAppendOnlyWriteAllowed`) | plugin-security | Get: nothing — an insert, update, delete, transfer, restore or purge of `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` from a context carrying `isSystem` and either a `flowRunId` (a `runAs: 'system'` flow's data nodes) or the app-automation elevation mark (`@objectstack/core`; set only by a hook's `runAs: 'system'` derivation, by the action body's execution-context builder and `ObjectRepository.execute`, and on the api of a hook bound through the hook binder, whose inherited system context and `sudo()` it marks), at any depth of their writes, is refused `PERMISSION_DENIED` before the short-circuit skips the ADR-0090 D12 gate and the identity write guard. The platform's own system api (`platformSystemApi`, objectql) takes the mark and `flowRunId` off a platform hook's api, for the audit writer's own ledger rows. On an app-authored hook's api, on the api an action door hands its handler (a host code action handler's included) and on the api `ObjectRepository.execute` hands the action it dispatches (`ctx.api.object(o).execute(name)`), and on every api derived from any of them, it answers what that api's `sudo()` answers, mark kept, so this refusal, and the action body's owner stamp in the next row, hold through it too. Lose: nothing a platform writer held — a system context with neither (the seeders, better-auth and its reconciliation, invitation placement, platform code's `sudo()`, which never sets the mark, and a hook registered in code) passes on to the short-circuit unchanged, reads are not judged, and a `runAs: 'user'` flow or hook carries no `isSystem`, so the D12 gate judges it as the user it acts for | `elevationSource`, `appAuthoredHookApi` | -| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); a write is judged again on the rows its before-hooks leave, by the same rule, as the plain door judges it; the option bag's `tenantId` / `tenantIds` never widen it past the caller's wall — a write (an insert included) whose bag names an organization outside it, or clears the key, is refused (`403 PERMISSION_DENIED`), and a read whose bag does is answered by the read rule, the caller's wall composed onto its predicate; the bag its before-hooks leave, set, replaced or handed back, is judged by the same rule where the engine builds the driver's options (`OperationContext.driverTenantScopeCheck`): a bag naming only organizations inside the scope the engine itself projects for the caller (its active organization, or under `group` its memberships) is not judged further, and a bag beyond that scope, or one that clears a key, is judged against the caller's wall where a verdict was worked out for the operation and against its active organization alone where none was; on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | +| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); a write is judged again on the rows its before-hooks leave, by the same rule, as the plain door judges it; the option bag's `tenantId` / `tenantIds` never widen it past the caller's wall — a write (an insert included) whose bag names an organization outside it, or clears the key, is refused (`403 PERMISSION_DENIED`), and a read whose bag does is answered by the read rule, the caller's wall composed onto its predicate; the bag its before-hooks leave, set, replaced or handed back, is judged by the same rule where the engine builds the driver's options (`OperationContext.driverTenantScopeCheck`): a bag naming only organizations inside the scope the engine itself projects for the caller (its active organization, or under `group` its memberships) is not judged further, and a bag beyond that scope, or one that clears a key, is judged against the caller's wall where a verdict was worked out for the operation and against its active organization alone where none was (the elevation keeps that in-projection pass on every verb: it is the plain door's bound, for an ordinary caller's insert, that is asked about every key the bag carries, an on-behalf-of insert's held to the delegator's memberships too); on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | | 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-driver-options.ts b/packages/objectql/src/engine-driver-options.ts index a1ee3a4c93e..f74e1bc461a 100644 --- a/packages/objectql/src/engine-driver-options.ts +++ b/packages/objectql/src/engine-driver-options.ts @@ -340,7 +340,27 @@ export function readScopeContextOf(execCtx: ExecutionContext | undefined): Execu * active organization — any explicit key asks beyond it. `tenantIds` is read * as the caller hands it in {@link copyTenantIds}'s plain copy, never through * the bag's own array methods. + * + * The projection is the engine's facts about the context it was handed (the + * active organization; under `group`, that context's memberships), not the + * caller's wall: an enforcement layer can know of a narrower one (an + * on-behalf-of write is also bounded by the delegator's memberships). So an + * insert's landing build skips this question for a bound that opts in + * ({@link LandingTenantScopeCheck}), and asks the bound about every explicit + * key. + */ +/** + * [ADR-0095 D1] A {@link DriverTenantScopeCheck} as an insert's landing build + * reads it. `judgesEveryExplicitKey: true` is the bound's opt-in: on the + * build that names where an insert's rows land (`scope.writeTarget`), the + * engine asks it about every explicit tenant key the bag carries, those + * inside its own projection for the call included. Every other build — an + * update, a delete, a purge, a read — is unchanged, and asks only about keys + * beyond the projection. A bound that does not opt in (the app-automation + * elevation's, whose fast path relies on that skip) is asked as before. */ +type LandingTenantScopeCheck = DriverTenantScopeCheck & { readonly judgesEveryExplicitKey?: boolean }; + function asksBeyondProjectedScope( declared: Record, tenantScope: { tenantId: string; tenantIds?: string[] } | undefined, @@ -467,7 +487,7 @@ export function buildDriverOptions( object: string, execCtx?: ExecutionContext, base?: any, - scope: { writeTarget?: boolean; recordedVerdict?: unknown; tenantScopeCheck?: DriverTenantScopeCheck } = {}, + scope: { writeTarget?: boolean; recordedVerdict?: unknown; tenantScopeCheck?: LandingTenantScopeCheck } = {}, ): any { // The open transaction may arrive explicitly via the context, or ambiently // via txStore when an internal query runs during a transactional write @@ -535,24 +555,32 @@ export function buildDriverOptions( // [ADR-0095 D1] An explicit tenant key is the caller's intent and wins below, // so where the operation carries a bound on it (an enforcement layer's // {@link OperationContext.driverTenantScopeCheck}), the bound judges the keys - // the bag carries NOW — after every before-hook, whatever bag it left. Keys + // the bag carries NOW — after every before-hook, whatever bag it left. + // + // On an insert's landing build (`scope.writeTarget`) a bound that opts in + // (`judgesEveryExplicitKey`) judges EVERY explicit key: the key is where the + // rows land, and the engine's projection is not the caller's wall (see + // {@link asksBeyondProjectedScope}). That build is the only one of the + // operation, so no key the engine filled into the hooks' view is read back. + // + // Every other build, and a bound that does not opt in, is unchanged: keys // that ask for nothing beyond the scope the engine projects for this very // call (its active organization; under `group`, its memberships) are not - // judged, whoever set them: the engine's own projection already scopes the - // driver to them — which is also what lets a later build of the operation - // read back the keys the engine itself filled into the hooks' view - // (`mergeDriverOptionsIntoHookView`). A key beyond that scope, or one that - // clears it, is judged. `tenantIds` is copied once, so the judged value and - // the driver's are the same array — and, judged or not, the driver's array - // is never one object with the caller's. + // judged, whoever set them — which is also what lets a later build of the + // operation read back the keys the engine itself filled into the hooks' + // view (`mergeDriverOptionsIntoHookView`). A key beyond that scope, or one + // that clears it, is judged. `tenantIds` is copied once, so the judged value + // and the driver's are the same array — and, judged or not, the driver's + // array is never one object with the caller's. if (declared && declared.tenantIds !== undefined) { declared.tenantIds = copyTenantIds(declared.tenantIds); } + const judgesEveryLandingKey = scope.writeTarget === true && scope.tenantScopeCheck?.judgesEveryExplicitKey === true; if ( scope.tenantScopeCheck && declared && (declared.tenantId !== undefined || declared.tenantIds !== undefined) && - asksBeyondProjectedScope(declared, tenantScope) + (judgesEveryLandingKey || asksBeyondProjectedScope(declared, tenantScope)) ) { const judged = scope.tenantScopeCheck.judge({ tenantId: declared.tenantId, tenantIds: declared.tenantIds }); delete declared.tenantId; diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 663889be91b..d350f693707 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -4183,12 +4183,20 @@ export interface OperationContext { * the bag carries at that moment that ask beyond the scope the engine * projects for the call (its active organization; under `group`, its * memberships) or clear it. Keys inside that scope are handed to the - * driver unjudged. + * driver unjudged — except on an insert's landing (the build that names + * where its rows land), where a check that opts in + * (`judgesEveryExplicitKey: true`) is asked about every explicit key. * - * Set by an enforcement layer's middleware, and only by it: the security - * plugin sets it for an app-authored elevation that runs for a caller, so - * the elevation's driver scope never reaches past that caller's - * organization wall. ABSENT is the ordinary state, and the engine never + * Set by an enforcement layer's middleware, and only by it. The security + * plugin sets one for an app-authored elevation that runs for a caller + * (it does not opt in), and one for an ordinary write — insert, update, + * delete, purge — of a non-system caller it admits, whose wall bounds + * anything (it opts in); that one refuses a key the caller's wall does not + * admit, never narrowing it. ABSENT where no enforcement layer judged the + * operation (a system context, a stack with no security layer), where the + * caller's wall bounds nothing (a platform operator crossing on a + * posture-permitting object, an object outside the tenancy machinery, the + * `single` posture), and on every other operation; the engine never * invents one. */ driverTenantScopeCheck?: DriverTenantScopeCheck; @@ -4256,9 +4264,10 @@ export interface OperationContext { * carries. `judge` receives the tenant keys the option bag carries when the * engine builds a driver bag for the operation — called only when one of * them asks beyond the scope the engine projects for the call, or clears - * it — and answers the keys the driver is to be - * handed in their place: the same, narrowed, or `undefined` for a key the - * operation's own scope is to fill. It refuses by throwing. + * it, and on an insert's landing for every explicit key when the check + * carries `judgesEveryExplicitKey: true` — and answers the keys the driver + * is to be handed in their place: the same, narrowed, or `undefined` for a + * key the operation's own scope is to fill. It refuses by throwing. */ export interface DriverTenantScopeCheck { judge(asked: { tenantId?: unknown; tenantIds?: unknown }): { tenantId?: unknown; tenantIds?: unknown }; diff --git a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts index 14b2653ed18..08ad806c554 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -130,6 +130,7 @@ import { import { jsonColumnCheckRefusalCarriedBy, storedFormCheckJudge } from './rls-check-stored-form.js'; import { compiledPolicyNameOf } from './rls-compiler.js'; import { andComposeLayers, intersectTenantLayer0Verdicts } from './tenant-layer.js'; +import { bindsWriteOptionTenantKeys, installWriteOptionTenantKeysWall, writeOptionTenantKeysVerdict } from './write-option-tenant-keys-wall.js'; import { rlsOperationForVerb } from './lifecycle-verb-rls-operation.js'; import { unresolvedPostureDenialMessage, @@ -3111,6 +3112,20 @@ export function registerAuthzMiddleware( // here rather than at 2.6, so the request-wide memos the steps above // staged on the caller's envelope (membership sets, queues) ride along. if (operationStamps && Object.keys(operationStamps).length > 0) opCtx.context = { ...opCtx.context, ...operationStamps }; + // [ADR-0095 D1] A write's tenant options never reach past the caller's + // organization wall: the bag the before-hooks leave is judged where the + // engine builds the driver's options. See `write-option-tenant-keys-wall.ts`. + if (bindsWriteOptionTenantKeys(opCtx.operation)) { + const verdict = await writeOptionTenantKeysVerdict( + opCtx, + async () => (await this.computeTenantLayer0Only(async () => permissionSets, opCtx.object, opCtx.operation, opCtx.context)).tenantLayer0Verdict, + delegatorSets + ? async () => (await this.computeTenantLayer0Only(async () => delegatorSets, opCtx.object, opCtx.operation, delegatorContext)).tenantLayer0Verdict + : null, + intersectTenantLayer0Verdicts, + ); + installWriteOptionTenantKeysWall(opCtx, verdict); + } await next(); // [commit a016f08b8] FAIL CLOSED on a seam that was never run. `honoured` is set by diff --git a/packages/plugins/plugin-security/src/write-option-tenant-keys-wall.test.ts b/packages/plugins/plugin-security/src/write-option-tenant-keys-wall.test.ts new file mode 100644 index 00000000000..62b26bdc857 --- /dev/null +++ b/packages/plugins/plugin-security/src/write-option-tenant-keys-wall.test.ts @@ -0,0 +1,548 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A write's tenant options never reach past the caller's organization wall + * (ADR-0095 D1) — `write-option-tenant-keys-wall.ts`. + * + * Real stack: a real `ObjectQL` engine over two SQL driver families, the real + * `SecurityPlugin` middleware, the `isolated` posture unless a cell says + * otherwise, and two organizations with a row each. The write's option bag is + * set by a `before*` hook — after every middleware has run — so the judgement + * pinned here is the one the engine asks where it builds the driver's options. + * + * Pinned: + * - the refusals, `403 PERMISSION_DENIED` on the ADR-0112 envelope, with the + * tables unchanged: an insert, a by-id update, a predicate update, a by-id + * delete and a predicate delete whose options name an organization the + * caller's wall does not admit, or clear the scope; under `group` against + * the membership set; + * - the controls: options inside the wall are admitted; a write that sets no + * option is unchanged; a platform operator on a posture-permitting object, + * a system context and the `single` posture are unaffected; + * - a `purge` (the permanent delete), a bag a hook REPLACES rather than + * edits, and a caller the wall denies; + * - an insert's landing under `group`, on driver-sql: every explicit key an + * insert's bag carries is held to the caller's wall — for an on-behalf-of + * insert, the wall the delegator's membership bounds — single and array, + * hook-set or passed in-process, and for an exempt platform operator + * acting for a walled delegator. Controls: an on-behalf-of insert into the + * active organization, a plain `group` caller naming a sister membership, + * an on-behalf-of by-id delete with no key, and an app-automation + * elevation's insert are unchanged. + */ + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { markAppAutomationElevation } from '@objectstack/core'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import type { PermissionSet } from '@objectstack/spec/security'; +import { SysOrganization, SysUser, SysMember } from '@objectstack/platform-objects/identity'; +import { SecurityPlugin } from './security-plugin.js'; +import { SysPosition, SysPermissionSet, SysPositionPermissionSet } from './__tests__/legacy-catalog-objects.testkit.js'; +import { SysUserPosition } from './objects/sys-user-position.object.js'; +import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; +import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js'; + +/** The caller's active organization. */ +const OWN_ORG = 'org_a'; +/** An organization the caller holds nothing in. */ +const OTHER_ORG = 'org_b'; +/** A second organization the caller belongs to, read under `group` only. */ +const SISTER_ORG = 'org_c'; + +const FIELDS = { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, +}; + +const OBJECTS = [ + // A public tenant object: Layer 0 walls every non-system caller on it. + { name: 'qa_note', label: 'Note', fields: FIELDS }, + // A private object: its posture permits a platform operator to cross the wall. + { name: 'qa_vault', label: 'Vault', access: { default: 'private' }, fields: FIELDS }, +]; + +const MEMBER: PermissionSet = { + name: 'member_default', + label: 'Member', + objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, manageRecycleBin: true } }, +} as unknown as PermissionSet; + +const PLATFORM_ADMIN: PermissionSet = { + name: 'admin_full_access', + label: 'Platform Administrator', + objects: { + '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + }, + systemPermissions: ['manage_platform_settings', 'manage_metadata'], +} as unknown as PermissionSet; + +/** A private object is outside the `'*'` grant, so a delegator holds it by name. */ +const VAULT_WRITER: PermissionSet = { + name: 'qa_vault_writer', + label: 'Vault writer', + objects: { qa_vault: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, +} as unknown as PermissionSet; + +const SETS = [MEMBER, PLATFORM_ADMIN, VAULT_WRITER]; + +/** A person a caller acts for: a member of the caller's active organization only. */ +const DELEGATOR = 'usr_delegator'; + +const SYS_CTX = { isSystem: true, userId: 'usr_system', tenantId: OWN_ORG }; +const MEMBER_CTX = { userId: 'usr_a', tenantId: OWN_ORG, positions: [], permissions: [], posture: 'MEMBER' }; +const GROUP_CTX = { ...MEMBER_CTX, accessible_org_ids: [OWN_ORG, SISTER_ORG] }; +const ADMIN_CTX = { userId: 'usr_admin', tenantId: OWN_ORG, positions: [], permissions: ['admin_full_access'], posture: 'PLATFORM_ADMIN' }; + +/** A caller under `group`, a member of both organizations, acting for the delegator. */ +const OBO_CTX = { ...GROUP_CTX, onBehalfOf: { userId: DELEGATOR } }; +/** A platform operator holding both organizations, acting for the delegator. */ +const OBO_ADMIN_CTX = { ...ADMIN_CTX, accessible_org_ids: [OWN_ORG, OTHER_ORG], onBehalfOf: { userId: DELEGATOR } }; +/** A caller the `isolated` wall denies: no active organization. */ +const DENIED_CTX = { userId: 'usr_a', positions: [], permissions: [], posture: 'MEMBER', accessible_org_ids: [] }; + +type Posture = 'isolated' | 'group' | 'single'; +type Bag = Record; + +const engines: ObjectQL[] = []; +afterEach(async () => { + while (engines.length) { + try { await engines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +interface Booted { + engine: ObjectQL; + /** + * Set the option bag the `before*` hooks leave; `null` leaves it alone. With + * `replace`, a hook hands back a new bag instead of editing the one it got. + */ + setHookOptions: (keys: Bag | null, how?: { replace?: boolean }) => void; + /** How many times a hook wrote the bag, so "the hook ran" is measured. */ + hookRuns: () => number; + table: (name: string) => Promise>>; +} + +/** + * `identity` stores the people an on-behalf-of context names: the delegator, + * a member of the caller's active organization only, holding the private + * object by name there. + */ +async function boot(makeDriver: () => unknown, posture: Posture = 'isolated', options: { identity?: boolean } = {}): Promise { + const engine = new ObjectQL(); + engine.registerDriver(makeDriver() as never, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.write-option-tenant-keys-wall', + name: 'Write option tenant keys wall', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: options.identity + ? [ + SysPosition, SysPermissionSet, SysPositionPermissionSet, SysUserPosition, SysUserPermissionSet, + SysOrganization, SysUser, SysMember, + ...OBJECTS, + ] + : OBJECTS, + } as never); + await engine.syncSchemas(); + engines.push(engine); + if (options.identity) await seedDelegator(engine); + + let hookKeys: Bag | null = null; + let replaceBag = false; + let runs = 0; + const hook = (async (ctx: { input: { options?: Bag; data?: Bag } }) => { + if (hookKeys === null) return; + runs++; + if (replaceBag) ctx.input.options = { ...(ctx.input.options ?? {}), ...hookKeys }; + else { + ctx.input.options = ctx.input.options ?? {}; + Object.assign(ctx.input.options, hookKeys); + } + // Every cell judges the option alone: the row names no organization. + if (ctx.input.data && typeof ctx.input.data === 'object') delete ctx.input.data.organization_id; + }) as never; + for (const object of ['qa_note', 'qa_vault']) { + engine.on('beforeInsert', object, hook); + engine.on('beforeUpdate', object, hook); + engine.on('beforeDelete', object, hook); + } + + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? SETS.find((s: any) => s?.name === name) : engine.getSchema(name)) ?? null, + list: async () => SETS, + }, + }; + if (posture !== 'single') { + services['org-scoping'] = { name: 'com.objectstack.org-scoping' }; + services.tenancy = { posture }; + } + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + // `kernel:ready` never fires here: the plugin's platform bootstrap is not + // started, so no case destroys the engine under its reads. + hook: () => undefined, + registerService: vi.fn(), + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); + + for (const object of ['qa_note', 'qa_vault']) { + await engine.insert( + object, + [ + { id: 'a1', name: 'own', organization_id: OWN_ORG }, + { id: 'b1', name: 'other', organization_id: OTHER_ORG }, + ], + { context: SYS_CTX } as never, + ); + } + + const table = async (name: string) => { + const driver = (engine as unknown as { getDriver(o: string): { knex: unknown } }).getDriver(name); + const knex = driver.knex as (t: string) => { select: (...c: string[]) => Promise>> }; + const rows = await knex(name).select('id', 'name', 'organization_id'); + return [...rows].sort((a, b) => String(a.id).localeCompare(String(b.id))); + }; + + return { + engine, + setHookOptions: (keys, how) => { hookKeys = keys; replaceBag = how?.replace === true; }, + hookRuns: () => runs, + table, + }; +} + +/** The delegator, stored as the on-behalf-of prologue reads them back. */ +async function seedDelegator(engine: ObjectQL): Promise { + // The organization-less permission-set catalogue row exists only on a store + // built before 18.x: that table is this store's. + await relaxTenantColumns(engine as never, ['sys_permission_set']); + for (const id of [OWN_ORG, OTHER_ORG, SISTER_ORG]) { + await engine.insert('sys_organization', { id, name: id, slug: id }, { context: SYS_CTX } as never); + } + await engine.insert('sys_user', { id: DELEGATOR, name: DELEGATOR, email: 'delegator@example.test' }, { context: SYS_CTX } as never); + await engine.insert('sys_member', { id: 'mem_delegator', user_id: DELEGATOR, organization_id: OWN_ORG, role: 'member' }, { context: SYS_CTX } as never); + const driver = (engine as unknown as { getDriver(x: string): { create(x: string, r: Record): Promise } }).getDriver('sys_permission_set'); + await driver.create('sys_permission_set', { + id: 'ps_qa_vault_writer', name: 'qa_vault_writer', label: 'Vault writer', organization_id: null, managed_by: 'admin', active: true, + object_permissions: JSON.stringify({}), system_permissions: JSON.stringify([]), + }); + await engine.insert( + 'sys_user_permission_set', + { id: 'ups_delegator', user_id: DELEGATOR, permission_set: 'qa_vault_writer', organization_id: OWN_ORG }, + { context: SYS_CTX } as never, + ); +} + +const DRIVERS: Array<[string, () => unknown]> = [ + ['driver-sql (better-sqlite3 :memory:)', () => + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never)], + ['driver-sqlite-wasm (:memory:)', () => new SqliteWasmDriver({ filename: ':memory:' } as never)], +]; + +interface Outcome { ok: boolean; value?: unknown; code?: string; status?: number; message?: string } + +const attempt = async (run: () => Promise): Promise => { + try { + return { ok: true, value: await run() }; + } catch (e) { + const err = e as { code?: string; statusCode?: number; status?: number; message?: string }; + return { ok: false, code: err.code, status: err.statusCode ?? err.status, message: String(err.message ?? e) }; + } +}; + +/** The refusal, on the ADR-0112 envelope: never a narrowed success, never a bare throw. */ +const expectRefused = (outcome: Outcome) => { + expect(outcome.ok, `expected a refusal, got a completed write: ${JSON.stringify(outcome.value)}`).toBe(false); + expect(outcome.code, 'ADR-0112 error code').toBe('PERMISSION_DENIED'); + expect(outcome.status, 'ADR-0112 HTTP status').toBe(403); +}; + +const expectAdmitted = (outcome: Outcome) => + expect(outcome.ok, `expected the write to be admitted: ${outcome.message}`).toBe(true); + +const SEEDED = [ + { id: 'a1', name: 'own', organization_id: OWN_ORG }, + { id: 'b1', name: 'other', organization_id: OTHER_ORG }, +]; + +const insert = (b: Booted, data: Bag, context: object = MEMBER_CTX, object = 'qa_note') => + b.engine.insert(object, data as never, { context } as never); +const updateById = (b: Booted, id: string, context: object = MEMBER_CTX) => + b.engine.update('qa_note', { id, name: 'changed' } as never, { context } as never); +const updateWhere = (b: Booted, context: object = MEMBER_CTX) => + b.engine.update('qa_note', { name: 'changed' } as never, { where: { name: { $ne: 'none' } }, multi: true, context } as never); +const deleteById = (b: Booted, id: string, context: object = MEMBER_CTX) => + b.engine.delete('qa_note', { where: { id }, context } as never); +const deleteWhere = (b: Booted, context: object = MEMBER_CTX) => + b.engine.delete('qa_note', { where: { name: { $ne: 'none' } }, multi: true, context } as never); +/** The permanent delete: a by-id delete authorized as `purge`. */ +const purgeById = (b: Booted, id: string, context: object = MEMBER_CTX) => + b.engine.delete('qa_note', { where: { id }, permanent: true, context } as never); + +for (const [driverName, makeDriver] of DRIVERS) { + describe(`a write's tenant options never reach past the caller's organization wall — ${driverName}`, () => { + it('insert: options naming an organization outside the wall are refused, and no row is stored', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OTHER_ORG }); + + expectRefused(await attempt(() => insert(b, { id: 'n1', name: 'new' }))); + expect(b.hookRuns(), 'the hook ran and set the option').toBe(1); + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('insert: options outside the wall are refused when the payload named the caller’s own organization too', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OTHER_ORG }); + + expectRefused(await attempt(() => insert(b, { id: 'n1', name: 'new', organization_id: OWN_ORG }))); + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('insert: options that clear the scope are refused', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: null }); + + expectRefused(await attempt(() => insert(b, { id: 'n1', name: 'new' }))); + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('by-id update: options naming an organization outside the wall are refused, not answered with an empty success', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OTHER_ORG }); + + expectRefused(await attempt(() => updateById(b, 'a1'))); + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('predicate update: options naming an organization outside the wall, or clearing the scope, are refused', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantIds: [OTHER_ORG] }); + expectRefused(await attempt(() => updateWhere(b))); + b.setHookOptions({ tenantId: null }); + expectRefused(await attempt(() => updateWhere(b))); + + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('by-id delete: options naming an organization outside the wall are refused, and the row stays', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OTHER_ORG }); + + expectRefused(await attempt(() => deleteById(b, 'a1'))); + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('predicate delete: options naming an organization outside the wall, or clearing the scope, are refused', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OTHER_ORG }); + expectRefused(await attempt(() => deleteWhere(b))); + b.setHookOptions({ tenantId: null }); + expectRefused(await attempt(() => deleteWhere(b))); + + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('`group` posture: options naming an organization outside the membership set are refused; a member organization is admitted', async () => { + const b = await boot(makeDriver, 'group'); + b.setHookOptions({ tenantId: OTHER_ORG }); + expectRefused(await attempt(() => insert(b, { id: 'n1', name: 'new' }, GROUP_CTX))); + expect(await b.table('qa_note')).toEqual(SEEDED); + + b.setHookOptions({ tenantId: SISTER_ORG }); + expectAdmitted(await attempt(() => insert(b, { id: 'n2', name: 'sister' }, GROUP_CTX))); + expect((await b.table('qa_note'))[2]).toEqual({ id: 'n2', name: 'sister', organization_id: SISTER_ORG }); + }); + + it('purge: options naming an organization outside the wall are refused, and the row stays', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OTHER_ORG }); + + expectRefused(await attempt(() => purgeById(b, 'a1'))); + expect(b.hookRuns(), 'the hook ran and set the option').toBe(1); + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('a bag the hook replaces, rather than edits, never reaches past the wall', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OTHER_ORG }, { replace: true }); + + expectRefused(await attempt(() => insert(b, { id: 'n1', name: 'new' }))); + expectRefused(await attempt(() => updateById(b, 'a1'))); + expectRefused(await attempt(() => deleteById(b, 'a1'))); + expect(await b.table('qa_note')).toEqual(SEEDED); + // A predicate write's statement stays inside the wall: the other + // organization's row is neither changed nor removed. + await attempt(() => updateWhere(b)); + await attempt(() => deleteWhere(b)); + expect(await b.table('qa_note')).toEqual([{ id: 'b1', name: 'other', organization_id: OTHER_ORG }]); + }); + }); + + describe(`a write's tenant options never reach past the caller's organization wall: controls — ${driverName}`, () => { + it('options inside the wall are admitted on every write', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OWN_ORG }); + + expectAdmitted(await attempt(() => insert(b, { id: 'n1', name: 'new' }))); + expectAdmitted(await attempt(() => updateById(b, 'a1'))); + expectAdmitted(await attempt(() => updateWhere(b))); + expect(await b.table('qa_note')).toEqual([ + { id: 'a1', name: 'changed', organization_id: OWN_ORG }, + { id: 'b1', name: 'other', organization_id: OTHER_ORG }, + { id: 'n1', name: 'changed', organization_id: OWN_ORG }, + ]); + expectAdmitted(await attempt(() => deleteById(b, 'n1'))); + expectAdmitted(await attempt(() => deleteWhere(b))); + expect(await b.table('qa_note')).toEqual([{ id: 'b1', name: 'other', organization_id: OTHER_ORG }]); + }); + + it('a write that sets no tenant option lands in the caller’s organization, as before', async () => { + const b = await boot(makeDriver); + + expectAdmitted(await attempt(() => insert(b, { id: 'n1', name: 'new' }))); + expect((await b.table('qa_note'))[2]).toEqual({ id: 'n1', name: 'new', organization_id: OWN_ORG }); + }); + + it('a platform operator on a posture-permitting object is unaffected', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OTHER_ORG }); + + expectAdmitted(await attempt(() => insert(b, { id: 'n1', name: 'new' }, ADMIN_CTX, 'qa_vault'))); + expect((await b.table('qa_vault'))[2]).toEqual({ id: 'n1', name: 'new', organization_id: OTHER_ORG }); + }); + + it('a system context is unaffected', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OTHER_ORG }); + + expectAdmitted(await attempt(() => insert(b, { id: 'n1', name: 'new' }, SYS_CTX))); + expect((await b.table('qa_note'))[2]).toEqual({ id: 'n1', name: 'new', organization_id: OTHER_ORG }); + }); + + it('the `single` posture is unaffected: no wall between organizations', async () => { + const b = await boot(makeDriver, 'single'); + b.setHookOptions({ tenantId: OTHER_ORG }); + + expectAdmitted(await attempt(() => insert(b, { id: 'n1', name: 'new' }))); + expect((await b.table('qa_note'))[2]).toEqual({ id: 'n1', name: 'new', organization_id: OTHER_ORG }); + }); + + it('purge: options inside the wall are admitted, and the row is gone', async () => { + const b = await boot(makeDriver); + b.setHookOptions({ tenantId: OWN_ORG }); + + expectAdmitted(await attempt(() => purgeById(b, 'a1'))); + expect(await b.table('qa_note')).toEqual([{ id: 'b1', name: 'other', organization_id: OTHER_ORG }]); + }); + + it('a caller the wall denies is answered as it is with no option: its options change no answer, and nothing is written', async () => { + const b = await boot(makeDriver); + const writes = [ + () => insert(b, { id: 'n1', name: 'new' }, DENIED_CTX), + () => updateById(b, 'a1', DENIED_CTX), + () => updateWhere(b, DENIED_CTX), + () => deleteById(b, 'a1', DENIED_CTX), + () => deleteWhere(b, DENIED_CTX), + ]; + const answer = (o: Outcome) => ({ ok: o.ok, code: o.code, status: o.status, value: o.value }); + const unset: unknown[] = []; + for (const write of writes) unset.push(answer(await attempt(write))); + // The removals keep the read rule: a by-id delete answers as a row that is not there. + expect(unset[3]).toMatchObject({ ok: false, code: 'RECORD_NOT_FOUND', status: 404 }); + expect(unset[4]).toMatchObject({ ok: true, value: 0 }); + + for (const keys of [{ tenantId: OWN_ORG }, { tenantId: OTHER_ORG }]) { + b.setHookOptions(keys); + const set: unknown[] = []; + for (const write of writes) set.push(answer(await attempt(write))); + expect(set).toEqual(unset); + } + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + }); +} + +const SQL_DRIVER = DRIVERS[0][1]; + +describe('an insert lands only inside the caller’s organization wall, whoever set its tenant options — `group`, on behalf of a delegator', () => { + it('an on-behalf-of insert whose hook names a membership the delegator does not hold is refused, and no row is stored', async () => { + const b = await boot(SQL_DRIVER, 'group', { identity: true }); + b.setHookOptions({ tenantId: SISTER_ORG }); + + expectRefused(await attempt(() => insert(b, { id: 'n1', name: 'new' }, OBO_CTX))); + expect(b.hookRuns(), 'the hook ran and set the option').toBe(1); + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('the same insert of several rows is refused, and no row is stored', async () => { + const b = await boot(SQL_DRIVER, 'group', { identity: true }); + b.setHookOptions({ tenantId: SISTER_ORG }); + + expectRefused(await attempt(() => b.engine.insert('qa_note', [{ id: 'n1', name: 'one' }, { id: 'n2', name: 'two' }] as never, { context: OBO_CTX } as never))); + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('an in-process on-behalf-of insert passing that membership in its options, with no hook, is refused', async () => { + const b = await boot(SQL_DRIVER, 'group', { identity: true }); + + expectRefused(await attempt(() => b.engine.insert('qa_note', { id: 'n1', name: 'new' } as never, { context: OBO_CTX, tenantId: SISTER_ORG } as never))); + expect(await b.table('qa_note')).toEqual(SEEDED); + }); + + it('a platform operator exempt on a private object, acting for a walled delegator, is held to the delegator’s wall', async () => { + const b = await boot(SQL_DRIVER, 'group', { identity: true }); + b.setHookOptions({ tenantId: OTHER_ORG }); + + expectRefused(await attempt(() => insert(b, { id: 'n1', name: 'new' }, OBO_ADMIN_CTX, 'qa_vault'))); + expect(await b.table('qa_vault')).toEqual(SEEDED); + }); +}); + +describe('an insert lands only inside the caller’s organization wall: controls — `group`, on behalf of a delegator', () => { + it('an on-behalf-of insert whose hook names the active organization is admitted there', async () => { + const b = await boot(SQL_DRIVER, 'group', { identity: true }); + b.setHookOptions({ tenantId: OWN_ORG }); + + expectAdmitted(await attempt(() => insert(b, { id: 'n1', name: 'new' }, OBO_CTX))); + expect((await b.table('qa_note'))[2]).toEqual({ id: 'n1', name: 'new', organization_id: OWN_ORG }); + }); + + it('a `group` caller acting for nobody may still name a sister membership', async () => { + const b = await boot(SQL_DRIVER, 'group', { identity: true }); + b.setHookOptions({ tenantId: SISTER_ORG }); + + expectAdmitted(await attempt(() => insert(b, { id: 'n1', name: 'sister' }, GROUP_CTX))); + expect((await b.table('qa_note'))[2]).toEqual({ id: 'n1', name: 'sister', organization_id: SISTER_ORG }); + }); + + it('an on-behalf-of by-id delete that sets no option is admitted: only an insert’s landing asks about every key', async () => { + const b = await boot(SQL_DRIVER, 'group', { identity: true }); + + expectAdmitted(await attempt(() => deleteById(b, 'a1', OBO_CTX))); + expect(await b.table('qa_note')).toEqual([{ id: 'b1', name: 'other', organization_id: OTHER_ORG }]); + }); + + it('an app-automation elevation’s insert whose hook names its caller’s sister membership is unchanged', async () => { + const b = await boot(SQL_DRIVER, 'group', { identity: true }); + b.setHookOptions({ tenantId: SISTER_ORG }); + const elevation = markAppAutomationElevation({ isSystem: true, ...GROUP_CTX }, 'action'); + + expectAdmitted(await attempt(() => insert(b, { id: 'n1', name: 'sister' }, elevation))); + expect((await b.table('qa_note'))[2]).toEqual({ id: 'n1', name: 'sister', organization_id: SISTER_ORG }); + }); +}); diff --git a/packages/plugins/plugin-security/src/write-option-tenant-keys-wall.ts b/packages/plugins/plugin-security/src/write-option-tenant-keys-wall.ts new file mode 100644 index 00000000000..412ef1a1f1a --- /dev/null +++ b/packages/plugins/plugin-security/src/write-option-tenant-keys-wall.ts @@ -0,0 +1,171 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A write's tenant options never reach past the caller's organization wall + * (ADR-0095 D1) — the plain door's half of the rule the app-automation + * elevation's wall already holds (`app-automation-organization-wall.ts`). + * + * ## The rule + * + * A write's option bag carries two driver pass-through tenant keys, + * `tenantId` and `tenantIds`, and an explicit one wins the driver's scope + * under every verdict (`buildDriverOptions`, `@objectstack/objectql`): for an + * insert it is the organization the new row lands in, for an update or a + * delete the organization the statement is scoped to. The bag a before-hook + * leaves — set, replaced or handed back — is the one the engine builds the + * driver's options from, after every middleware has run. So the plain door + * installs, on every ordinary write it admits, the check the engine asks at + * each driver bag it builds (`OperationContext.driverTenantScopeCheck`): + * + * - keys inside the caller's wall pass as they are; + * - a key naming an organization the wall does not admit, or one that clears + * the scope (`null`, `''`, any value that is not an organization id, a + * `tenantIds` that is not an array of them), REFUSES the write — `403 + * PERMISSION_DENIED` — before any driver runs. It is never narrowed in + * silence: a write that cannot go where it was told to does not go + * somewhere else and report success. + * + * Where the engine asks: + * + * - on an insert's landing (the build that names where its rows land), about + * EVERY explicit key, because this bound opts in + * (`judgesEveryExplicitKey`): the scope the engine projects for the call is + * the live caller's, and the caller's wall can be narrower — an + * on-behalf-of insert is bounded by the delegator's memberships too; + * - on every other write (update, delete, purge), only about keys beyond the + * scope the engine projects for the call itself (the active organization; + * under `group`, the memberships), so the common write is never judged. + * + * ## The wall + * + * The caller's own Layer 0 verdict for the operation — the one the read side + * computes, so every exemption stays where it is decided: a platform operator + * crossing on a posture-permitting object, an object outside the tenancy + * machinery and the `single` posture answer `none`, which bounds nothing. For + * an on-behalf-of write it is the intersection with the delegator's verdict + * (ADR-0090 D10). A predicate write reuses the verdict the middleware + * recorded for its predicate; an insert and a by-id write record none, so + * theirs is worked out here, over the permission sets the door already + * resolved. + */ + +import { TenantLayer0VerdictSchema, type TenantLayer0Verdict } from '@objectstack/spec/security'; +import { PermissionDeniedError } from './errors.js'; + +/** The write verbs whose option bag the engine hands its driver. */ +const WRITE_BAG_VERBS: ReadonlySet = new Set(['insert', 'update', 'delete', 'purge']); + +/** + * The judgement the engine asks (`DriverTenantScopeCheck`, `@objectstack/objectql`), + * with the opt-in its insert landing build reads (`judgesEveryExplicitKey`). + */ +interface DriverTenantScopeCheckLike { + judge(asked: { tenantId?: unknown; tenantIds?: unknown }): { tenantId?: unknown; tenantIds?: unknown }; + readonly judgesEveryExplicitKey?: boolean; +} + +/** The operation members this module reads and writes. */ +export interface WriteOptionTenantKeysOperation { + object?: unknown; + operation?: unknown; + ast?: unknown; + tenantLayer0Verdict?: unknown; + driverTenantScopeCheck?: DriverTenantScopeCheckLike; +} + +/** Does this operation hand its driver an option bag a write's wall must bound? */ +export function bindsWriteOptionTenantKeys(operation: unknown): boolean { + return typeof operation === 'string' && WRITE_BAG_VERBS.has(operation); +} + +/** The organizations a verdict admits, or `undefined` where it walls nothing. */ +function admittedOrganizations(verdict: TenantLayer0Verdict): ReadonlySet | undefined { + if (verdict.kind === 'organization') return new Set([verdict.organizationId]); + if (verdict.kind === 'organizations') return new Set(verdict.organizationIds); + if (verdict.kind === 'deny') return new Set(); + return undefined; +} + +const isOrganization = (id: unknown): id is string => typeof id === 'string' && id !== ''; + +/** + * A bag's `tenantIds`, read once by index into a plain array, so what is + * judged is what is handed on. A value that is not an array is returned as is. + */ +function plainTenantIds(tenantIds: unknown): unknown { + if (!Array.isArray(tenantIds)) return tenantIds; + const length = tenantIds.length; + const copy: unknown[] = []; + for (let i = 0; i < length; i++) copy.push(tenantIds[i]); + return copy; +} + +/** Do the keys reach past `admitted` — name an organization outside it, or clear the scope? */ +function reachesPast(asked: { tenantId?: unknown; tenantIds?: unknown }, admitted: ReadonlySet): boolean { + const { tenantId, tenantIds } = asked; + if (tenantId !== undefined && !(isOrganization(tenantId) && admitted.has(tenantId))) return true; + if (tenantIds !== undefined) { + if (!Array.isArray(tenantIds)) return true; + for (const id of tenantIds) if (!(isOrganization(id) && admitted.has(id))) return true; + } + return false; +} + +/** The refusal of a write whose option bag reaches past the caller's organization wall. */ +function optionTenantKeysRefusal(object: string, operation: string): PermissionDeniedError { + return new PermissionDeniedError( + `[Security] Access denied: this ${operation} on '${object}' names, in its options, an organization scope ` + + 'the caller may not write in.', + { operation, object }, + `[ADR-0095 D1] A write's tenant options (\`tenantId\`, \`tenantIds\`) are held to the caller's organization ` + + `wall where the engine builds the driver's options, after every before-hook: this ${operation} on ` + + `'${object}' asked for an organization the caller's Layer 0 does not admit, or cleared the scope, and is ` + + 'refused rather than narrowed. System contexts, and platform operators on posture-permitting objects, ' + + 'are unaffected.', + ); +} + +/** + * Install the bound on an ordinary write's option bag: `verdict` is the + * caller's wall for the operation (see the module header). Composed after a + * check another layer installed, never in place of it. It opts in to being + * asked about every explicit key on an insert's landing. + */ +export function installWriteOptionTenantKeysWall(opCtx: WriteOptionTenantKeysOperation, verdict: TenantLayer0Verdict): void { + const operation = typeof opCtx.operation === 'string' ? opCtx.operation : ''; + if (!WRITE_BAG_VERBS.has(operation)) return; + const admitted = admittedOrganizations(verdict); + if (admitted === undefined) return; + const object = typeof opCtx.object === 'string' ? opCtx.object : ''; + const prior = opCtx.driverTenantScopeCheck; + opCtx.driverTenantScopeCheck = { + judgesEveryExplicitKey: true, + judge(handed) { + const before = prior ? prior.judge(handed) : handed; + // Judged, and handed on, as one plain copy, each key read once. + const asked = { tenantId: before.tenantId, tenantIds: plainTenantIds(before.tenantIds) }; + if (reachesPast(asked, admitted)) throw optionTenantKeysRefusal(object, operation); + return asked; + }, + }; +} + +/** + * The caller's wall for a write: the verdict the middleware recorded for a + * predicate write's predicate where it parses, else the caller's own Layer 0, + * intersected with the delegator's for an on-behalf-of write (`delegator` is + * `null` for a write made for nobody else). + */ +export async function writeOptionTenantKeysVerdict( + opCtx: WriteOptionTenantKeysOperation, + caller: () => Promise, + delegator: (() => Promise) | null, + intersect: (a: TenantLayer0Verdict, b: TenantLayer0Verdict) => TenantLayer0Verdict, +): Promise { + if (opCtx.ast) { + const recorded = TenantLayer0VerdictSchema.safeParse(opCtx.tenantLayer0Verdict); + if (recorded.success) return recorded.data; + } + const own = await caller(); + return delegator === null ? own : intersect(own, await delegator()); +}