Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .changeset/write-tenant-options-wall.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: not-required (no-migration-prescription) no metadata an author writes changes; a write is refused only where its option bag asks for an organization outside the caller's own wall, so there is nothing stored for an upgrader to migrate -->

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.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
48 changes: 38 additions & 10 deletions packages/objectql/src/engine-driver-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>,
tenantScope: { tenantId: string; tenantIds?: string[] } | undefined,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading