diff --git a/.changeset/35802-cbp-predicate-write-master-gate.md b/.changeset/35802-cbp-predicate-write-master-gate.md new file mode 100644 index 00000000000..c807459da29 --- /dev/null +++ b/.changeset/35802-cbp-predicate-write-master-gate.md @@ -0,0 +1,35 @@ +--- +'@objectstack/plugin-security': patch +--- + +fix(plugin-security)!: a predicate update or delete of a `controlled_by_parent` detail now writes every row its caller may write by id, the rows other users created included, instead of stopping at the platform's creator-only floor + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING: an existing flow now changes or deletes detail rows its caller did not create.** A flow's bulk update or bulk delete node, a server-side script or a hook that runs a predicate write (`update(object, data, { where, multi: true })`, `delete(object, { where, multi: true })`) on a `controlled_by_parent` detail, as an organization member who may edit the master record (or read it, where the detail declares `sharing.controlledByParent.writeRequiresMasterRead`), used to change or delete only the detail rows that member had created and answer success. It now changes or deletes every row its predicate matches that the member can read, within any row-level `update` or `delete` policy the app authored on the detail. Review any such flow that deletes by predicate before upgrading: it will delete more rows than it did. + +It ships `patch` because it is a non-protocol breaking change (AGENTS.md Post-Task Checklist step 3): no schema, key or stored value moves, so `Metadata-protocol` is `none`. + +- FROM: on a `controlled_by_parent` detail the predicate write kept the platform ownership floor (`owner_only_writes` / `owner_only_deletes` in `member_default`, `created_by == current_user.id`) after its master check had passed. It matched only the rows the caller created, answered success, and never judged the other rows. Measured on a 4-row detail under one master: the master's owner changed 2 rows by predicate and all 4 by id; a member holding an `edit` share on the master, and a manager holding `modifyAllRecords`, changed 0 by predicate and all 4 by id. +- TO: once the master check has passed for every master the write reaches, the write is no longer held to that floor. It changes the rows a write of each row by id would change for the same caller, and it applies to all of its matched rows or to none: a newly matched row refused by a row-level `check`, a validation rule, a hook or a `restrict` relation refuses the whole write with that refusal, and nothing is written. + +**A detail that carries its own row-level write policy now writes fewer of the caller's own rows by predicate.** Where an app authors an `update` or `delete` policy with a `using` on a `controlled_by_parent` detail, a predicate write used to compose the platform floor beside that policy as one more OR term, so it also wrote the rows the caller created that the policy does not admit. The floor is no longer a term of that write, so the authored policy alone bounds it: those rows are left unwritten and the write answers success for the rows the policy admits. A by-id write of such a row was already refused, so the two now agree. A write made on another user's behalf keeps the floor and is not changed. + +The fix for a caller that must keep the old outcome: narrow the predicate to the rows it means to write (add `created_by` to the `where` to keep writing only the caller's own rows), or write the rows by id to get an outcome per row. To forbid a caller from writing rows other users created on a detail, author a row-level policy on the detail; it binds every row, by id and by predicate. + +This is the `controlled_by_parent` half of the predicate-write change shipped beside it: see the note "a predicate update or delete now writes the rows a Modify All holder, a non-creator owner or an edit-share target can write by id" for every other object. It follows the maintainer's ruling that a predicate write and a by-id write of such a detail agree (ADR-0055 §3 as amended 2026-11-22). + +What does not change: + +- A predicate write reaches only the rows its predicate matches that the caller can read, and a predicate matching more than 10,000 of them is refused before anything is written. +- It is refused whole, with `PERMISSION_DENIED` / 403 and nothing written, when it reaches a detail row under a master the caller may not edit (or may not read, where the detail declares `writeRequiresMasterRead`). +- A detail row that names no master (an optional master) is written by its owner or a Modify All holder; a predicate write that reaches such a row the caller can read and may not write is refused whole. +- A write made on another user's behalf keeps the floor for both principals, as its by-id write does. +- `sharing.controlledByParent.ownerMayEdit` widens a by-id update only: a predicate update still needs edit on the master. +- A by-id write is unchanged, and so is every predicate write on an object that is not a `controlled_by_parent` detail. +- No key, option or response member is added. + +A predicate write on such a detail also asks the read door for its rows once where it asked twice: the write is scoped to the rows its master check judged, so a row that starts matching the predicate while the write is being authorized is not written. diff --git a/.changeset/35802-predicate-write-floor-deferral.md b/.changeset/35802-predicate-write-floor-deferral.md index bf514492f17..f9a31383976 100644 --- a/.changeset/35802-predicate-write-floor-deferral.md +++ b/.changeset/35802-predicate-write-floor-deferral.md @@ -18,7 +18,7 @@ The fix for a caller: write those rows by id to get an outcome per row, or narro A predicate write (`update(object, data, { where, multi: true })`, `delete(object, { where, multi: true })`) by an organization member held the platform's own ownership floor (`owner_only_writes` / `owner_only_deletes` in `member_default`, `created_by == current_user.id`) as an unconditional condition, where record sharing enforces writes. Unless an app-authored write policy admitted a row, the write matched only the rows that member had created, even when the same user could update or delete the other matching rows one at a time by id. This affected a manager holding `modifyAllRecords` on the object, a row's owner who did not create it, and, for an update, the target of an `edit`-level record share or a member of the queue a row sits in. The write answered success and changed fewer rows than its predicate matched. A write by id lets the record-sharing service's `allow` verdict replace the floor. -The predicate write now makes the by-id decision for each matched row the floor would refuse. Such a row is written when a write of that row by id would be, because the sharing service answers `allow` for it: ownership at the caller's write depth, Modify All, or, for an update only, an `edit` share or the row's queue. A row the service abstains on keeps the floor: on an object with no `owner_id`, on a delete under `public_read_write` (an update there has no floor to keep, because that OWD opens row updates), and on a `controlled_by_parent` detail unless an update's row sits in a queue the caller belongs to. A row it denies keeps the floor too. The row-level `check` on each updated row follows the same decision. +The predicate write now makes the by-id decision for each matched row the floor would refuse. Such a row is written when a write of that row by id would be, because the sharing service answers `allow` for it: ownership at the caller's write depth, Modify All, or, for an update only, an `edit` share or the row's queue. A row the service abstains on keeps the floor: on an object with no `owner_id`, and on a delete under `public_read_write` (an update there has no floor to keep, because that OWD opens row updates). A row it denies keeps the floor too. The row-level `check` on each updated row follows the same decision. The by-id decision costs one sharing verdict, a few store reads, for each matched row the floor does not already admit. Measured on SQLite in memory: @@ -35,6 +35,6 @@ What does not change: - An `edit` share still widens update and never delete. - The tenant wall is unchanged. - A write made on another user's behalf keeps the floor for both principals, as its by-id write does. -- A `controlled_by_parent` detail keeps the floor on a predicate write, except on an update of a row that sits in a queue the caller belongs to, which the sharing service answers `allow` for under any OWD. The master gate still judges the predicate write. Its by-id write is decided by the master gate instead of the floor, and that half is not changed here. +- A `controlled_by_parent` detail is not decided by this composition. Its predicate write, like its by-id write, is decided by its master gate instead of the floor: see the note "a predicate update or delete of a `controlled_by_parent` detail now writes every row its caller may write by id". A flow, script or server-side bulk update or delete that relied on a predicate write skipping the rows its caller did not create now changes those rows too, when the caller may write them by id, and is refused whole when one of them is refused. The fix is the one above. diff --git a/content/docs/permissions/permissions-matrix.mdx b/content/docs/permissions/permissions-matrix.mdx index cbc138305a7..55337203528 100644 --- a/content/docs/permissions/permissions-matrix.mdx +++ b/content/docs/permissions/permissions-matrix.mdx @@ -63,8 +63,12 @@ by-id write and a predicate write both take that replacement unless an app-authored `using` policy for the write applies to the caller; then the write keeps the floor beside that policy, so a row the caller created stays writable and the policy bounds every other row. A write made on another user's behalf -keeps the floor. A `controlled_by_parent` detail's by-id write is -judged by its master gate instead of the floor. An app-authored policy is never +keeps the floor. A `controlled_by_parent` detail's write, by id or by +predicate, is judged by its master gate instead of the floor: a caller who may +edit the master (or read it, where the detail declares +`writeRequiresMasterRead`) writes the detail rows under it whoever created +them, and a predicate write that reaches a master the caller may not write +under is refused whole. An app-authored policy is never replaced. The Layer 0 tenant wall always ANDs on top. See [Sharing & OWD](/docs/permissions/sharing-rules#how-viewallrecords--modifyallrecords-interact-with-the-owd) and `plugin-security/src/security-plugin.ts` (`computeLayeredRlsFilter`). diff --git a/content/docs/permissions/rls.mdx b/content/docs/permissions/rls.mdx index c0dedc8621f..7be5870fbae 100644 --- a/content/docs/permissions/rls.mdx +++ b/content/docs/permissions/rls.mdx @@ -84,9 +84,10 @@ does not take away a row the floor admits (one the caller created), whether or not record sharing replaces the floor for that row. Two exceptions: on an object whose org-wide default is `public_read_write`, an `update` has no floor, so an authored `update` policy is the whole scope and does refuse the caller's -own non-matching row; and on a `controlled_by_parent` detail, a by-id write is +own non-matching row; and on a `controlled_by_parent` detail, a write is judged by its master gate instead of the floor, so a detail policy bounds every -detail row written by id (a predicate write on a detail keeps the floor). To cap what a caller +detail row written, by id or by predicate (a write made on another user's +behalf keeps the floor). To cap what a caller may do to rows they created, use a `check` (it judges the stored image) or a `beforeUpdate` / `beforeDelete` lifecycle hook (it sees the prior row as `ctx.previous`). Nothing is derived for `insert` diff --git a/content/docs/permissions/sharing-rules.mdx b/content/docs/permissions/sharing-rules.mdx index 29536e28fc1..31be14a4c87 100644 --- a/content/docs/permissions/sharing-rules.mdx +++ b/content/docs/permissions/sharing-rules.mdx @@ -61,8 +61,13 @@ Two things the bits do **not** override, regardless of the OWD: `org_member`). Under `public_read_write` the update policy does not apply (that OWD opens row updates) and the delete policy does; under every other OWD both apply, and record sharing can replace them row by row, as below. - A `controlled_by_parent` detail's by-id write is judged by its master gate - instead. The super-user bits short-circuit RLS **only + A `controlled_by_parent` detail's write is judged by its master gate + instead, by id and by predicate alike: a caller who may edit the master (or + read it, where the detail declares `writeRequiresMasterRead`) updates and + deletes the detail rows under it whoever created them. A predicate + (`multi: true`) update or delete writes the rows a by-id write of each + would, and is refused whole, with nothing written, when it reaches a master + the caller may not write under. The super-user bits short-circuit RLS **only where the object's access posture permits it** — `access: { default: 'private' }`, `tenancy.enabled: false` (deployment-level: no organization column), or better-auth managed objects (ADR-0066 D2 ①). On an ordinary tenant business object, diff --git a/docs/adr/0055-master-detail-controlled-by-parent.md b/docs/adr/0055-master-detail-controlled-by-parent.md index 0ed8d4c4ad4..e08406f9ed4 100644 --- a/docs/adr/0055-master-detail-controlled-by-parent.md +++ b/docs/adr/0055-master-detail-controlled-by-parent.md @@ -10,6 +10,7 @@ · **Amended** (2026-11-07, #30906 / PR #31082, the same ruling 「A」) — **§3 judges the null-master row by an owner rule**: a row of an optional master whose reference is empty is written by its owner (`owner_id`) and by Modify All on the detail, everyone else `403`; an insert naming no master is admitted; setting a master asks edit on it, emptying one asks edit on the stored master (the 2026-10-26 opt-in does not cover it); a chain hop with no master of its own ends the chain under the same rule. A required master is unchanged. See **"Amendment (2026-11-07, #30906): the null-master row its owner writes"** at the end. ⚠️ **Amended 2026-11-14 (#33250 / PR #33369)** — that "setting a master asks edit on it, emptying one asks edit on the stored master" no longer holds on a detail that declares `writeRequiresMasterRead`: there the new master and the stored master are each asked **read**. The owner rule of the null-master row is unchanged. See the 2026-11-14 line below. · **Amended** (2026-11-14, #33250 / PR #33369, ruling A+ `6880588685`) — **§3 gains a second per-object opt-in, and for the objects that declare it the 2026-10-26 amendment's "Option 2 … was not chosen" line is lifted**: `sharing.controlledByParent.writeRequiresMasterRead: true` makes **read** on the master the master question for every write of the detail (insert, update and delete, by id or by predicate, and the lifecycle verbs); the detail's own object permissions, row-level security, field-level security and the platform ownership floors decide the rest. The default is unchanged: a write's answer moves only if its own object, or a `controlled_by_parent` master on its chain, declares the key. See **"Amendment (2026-11-14, #33250): read on the master is enough to write, by opt-in"** at the end. · **Amended** (2026-11-15, #33696, ruling 「只对管理员去掉」 `6893666857`) — **for one reader class the parent chain over a REQUIRED master is dropped, and that class alone reads that master's detail rows whose reference is empty or dangling**: a reader who holds View All on the detail AND whose every master hop answers unrestricted (the engine's per-hop scope, not `hasSuperuserReadBypass`) sees those rows — naming no master, or a master that does not exist — inside its own tenant wall. That is consistent with the 2026-11-06 ruling 「A」, whose reader of a row with no master, beside its owner, is View All on the detail. Every other reader, members included, keeps the chain unchanged. An optional master's two arms are outside the ruling, and §3 (the write gate) is not amended by this note. The ruling lifts ADR-0139 D6's ⛔ ("interim removal of the predicate for an unrestricted master scope") for that class only, and [ADR-0139](./0139-engine-internal-semi-join-leaf-readable-parent-ids.md) D6 as amended 2026-11-15 carries the ruling's binding bullets verbatim. This is the "ADR-0055's 10-22 note in step" the ruling orders, and it precedes the code: #33696's change lands only after it. See the note under **"The rules the read keeps"** in the 2026-11-06 amendment. +· **Amended** (2026-11-22, #35802, ruling 「A 批量与逐条一致」 `7073030861`) — **§3: an addressed predicate update or delete hands the platform ownership floor to the master gate, as the by-id write does**: once the gate has passed every master a non-delegated predicate (`multi: true`) write reaches, the write is no longer held to `owner_only_writes` / `owner_only_deletes` (`created_by == current_user.id`), and the rows it writes are the rows a by-id write of each would write for the same caller. This supersedes one sentence of the 2026-11-14 amendment ("A **predicate** update or delete keeps the floor, as before"). The gate's refusals, the read narrowing, the null-master owner rule, app-authored row-level policies, the 10,000-row cap, the delegated write's two floors and `ownerMayEdit` are unchanged. See **"Amendment (2026-11-22, #35802): a predicate write hands the ownership floor to the master gate"** at the end. **Deciders**: ObjectStack Protocol Architects **Builds on**: [ADR-0049](./0049-no-unenforced-security-properties.md) (enforce-or-remove), [ADR-0054](./0054-runtime-proof-for-authorable-surface.md) (prove-it-runs) **Surfaced by**: an audit of master-detail permission semantics — `OWDModel.controlled_by_parent` is **declared but unenforced** (zero runtime consumers; not reachable through the object's `sharingModel` enum; the RLS compiler is relationship-blind). This is *false compliance* (ADR-0049) and *unproven liveness* (ADR-0054). @@ -282,6 +283,7 @@ Every `controlled_by_parent` object with a required master, byte for byte: its e - **What decides after the master question.** Unchanged: the detail's own object-level grant for the verb, its own row-level policies (step 2.7 of `packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts`), field-level security, and the platform ownership floors. In plain words, "admitted when the caller can read the master" is always subject to those floors: - A **by-id** update or delete hands the floor (`owner_only_writes` / `owner_only_deletes`, `created_by == current_user.id`, `packages/plugins/plugin-security/src/platform-ownership-policies.ts`) to the master gate, as it has for every `controlled_by_parent` detail through the coverage vouch (`masterGateCoversThisWrite`, step 2.7). So a master reader can update or delete a row they did not create. - A **predicate** update or delete keeps the floor, as before: among the rows it selects it touches only those the caller created. + ⚠️ **Amended 2026-11-22 (#35802, ruling `7073030861`) — superseded.** A non-delegated addressed predicate update or delete now hands the floor to the master gate once the gate has passed every master the write reaches, on every `controlled_by_parent` detail, this opt-in included. See the 2026-11-22 amendment at the end. - A **delegated** (on-behalf-of) by-id update or delete keeps **both** principals' floors, the ADR-0090 D10 exclusion, unchanged. - **On behalf of.** Step 2.8 runs the gate once per principal, the agent and then the delegator, each asked the read under its own context: either one unable to read the master refuses the write, and both able admit it, subject to the floors above. - **What a refusal answers.** A by-id update or delete by a caller who cannot read the master answers `404 RECORD_NOT_FOUND`, not `403`: the detail row's own read derives from its master (§2), so the read door (`callerCannotReadAddressedRow`, step 2.7) hides the row before the gate runs. That is the hidden-row rule (#7505), the same answer a detail that does not opt in gives. An insert or a re-point answers `403 PERMISSION_DENIED`, named for the caller's object and verb, "requires read access to its master record". `ISecurityService.checkControlledByParentWrite` answers `deny` for all of them, on `object_permission` (the master read is refused) or `row_level_security` (the master row is not returned); the closed leg union is not widened. `os explain` (`packages/plugins/plugin-security/src/explain-engine.ts#chainAsksMasterRead`) chooses prose that names the read question; its verdict still comes from the served member. A predicate (`multi: true`) update or delete by a caller who cannot read the master selects none of that master's rows, so it judges no master for them, writes none of them and answers no refusal, as on a detail that does not opt in: its matched set is narrowed to the rows the caller can read (`packages/plugins/plugin-security/src/security-plugin-addressed-writes.ts#readableRowsScopeForPredicateWrite`), a detail row's own read deriving from its master (§2), and the gate judges the masters of those rows only (`packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts#controlledByParentPredicateWriteMasters`). @@ -310,3 +312,36 @@ The `[#33250]` describes in `packages/plugins/plugin-security/src/controlled-by- ### What is unchanged §1, §2, the cycle guard and the depth bound; the 2026-11-07 owner rule for a null-master row; the 2026-10-26 owner leg on a detail that does not declare the new key; and every detail whose chain declares no `writeRequiresMasterRead`. + +## Amendment (2026-11-22, #35802): a predicate write hands the ownership floor to the master gate + +**Ruling.** objectstack-ai/objectstack#35802, ruling record `7073030861` (maintainer Leehom, answered by tap at 2026-11-22T02:37Z). The option he chose, label and consequence as shown, verbatim: 「A 批量与逐条一致」 — 「有权编辑主记录的人批量改删明细时,改到逐条能改的全部行;其中一行被规则拦下就整次拒绝。升级后现有流程会多改到别人创建的行。一个PR。」 (A, predicate and by-id agree: someone who may edit the master record, changing or deleting details by predicate, reaches every row they could change one at a time; one row stopped by a rule refuses the whole write. After the upgrade existing flows change more rows that others created. One PR.) It supersedes one sentence of the 2026-11-14 amendment, "A **predicate** update or delete keeps the floor, as before: among the rows it selects it touches only those the caller created", and the bullet of the `RlsFilterOptions.masterGateCoversThisWrite` docblock that called dropping the floor on that path "a separate decision". Neither older amendment is rewritten; the superseded sentence carries a pointer here. + +### The gap this closes + +The ruling that made the master gate the sole row-write authority for a `controlled_by_parent` detail (commit `6feac910b6`) set one condition: "the floor comes off only where the master gate demonstrably covers the same operation; otherwise the change is a bare widening". When it was made, the gate returned early on a write that addressed no single row, so a predicate write kept the floor. The gate has judged a predicate write since #25012: every master of the rows the write selects, refusing the write whole on the first the caller may not write under. The condition therefore held on the predicate path, and the floor stayed there all the same. Measured on `origin/main` `a5a5312ff4` (real engine, SQL driver, sharing service): the owner of the master changed 2 of 4 detail rows by predicate, the two they had created, where their by-id writes changed all 4; a Modify All holder and a member holding an `edit` share on the master changed 0 of 4 against 4; on a detail declaring `writeRequiresMasterRead`, a master reader changed 2 against 4. Each write answered success. + +### What changes, exactly + +- **The floor.** On a `controlled_by_parent` detail, an addressed predicate update or delete (`multi: true`) by a caller who is not acting on another user's behalf composes its row scope with `masterGateCoversThisWrite`, once step 2.8's gate has judged the write for that caller and refused nothing (`packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts`, steps 2.8 and 3). The platform ownership floor is then absent from that scope exactly as it is from a by-id write's (step 2.7); every app-authored policy, and the write-visibility derivation of a detail that authors none, stand as they do there. A predicate update's per-row stored-image check (step 3.6) is composed on the same decision. +- **The rows.** The write is scoped to the rows the gate judged: the gate records the ids of the rows whose master reference it read (`packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts#predicateWriteRowIdsJudgedByMasterGate`), and that list replaces the second asking of the read question the predicate door otherwise makes. So a row that comes to match the predicate after the gate read it is not written: no row is written under the handed-over floor without its master having been judged, or, for a row naming no master, without the owner rule having been asked. +- **The vouch is a fact about the pass, not about the object.** The middleware takes the record straight after the caller's own pass of the gate returns. A write the gate did not judge has none and keeps the floor: a shape the engine does not route down its predicate path, a nested or referential write, a principal for whom step 2.8 does not run. +- **Equal to the by-id answer.** The rows such a write changes are the rows a by-id write of each selected row changes for the same caller, with two stated differences, both older than this amendment and both in the refusing direction: the predicate write is refused whole on the first master the caller may not write under, where the by-id writes of the rows under the other masters succeed; and `ownerMayEdit`'s owner leg is a by-id update only (ruling `6398566164`), so a predicate update still asks edit on the master. + +### The declared narrowing + +A predicate write applies to all of its matched rows or to none (the outcome rule PR #35914 declared for the sharing half of the same card). Rows this amendment adds to the match are subject to it: one that a row-level `check`, a validation rule, a hook or a `restrict` relation refuses now refuses the whole write, where before it was not matched and the write answered success on the rows the caller had created. The change is therefore shipped on the narrowing arm, with the upgrade note leading on the other visible effect: an existing flow now changes or deletes detail rows its caller did not create. + +### What is unchanged + +- A predicate write reaches only rows the caller can read, and above 10,000 readable rows it is refused. +- It is refused whole on the first master the caller may not edit, or may not read on a detail declaring `writeRequiresMasterRead`. +- A row naming no (optional) master is judged by the 2026-11-07 owner rule; one the caller may not write refuses the write. +- An app-authored row-level policy binds every row. +- A delegated (on-behalf-of) predicate write keeps both principals' floors, as its by-id write does (ADR-0090 D10). +- `ownerMayEdit` (2026-10-26): its owner leg is a by-id update only. +- No key, switch or response member is added; the spec does not move. + +### Proof + +`packages/plugins/plugin-security/src/predicate-write-floor-deferral.test.ts`, the describe "a predicate write of a controlled_by_parent detail writes the rows its by-id writes do": each caller's predicate update and delete compared row for row with by-id writes of the same rows on a second copy (the master's owner; a member with an `edit` share on the master who created no row; a Modify All holder; `writeRequiresMasterRead`; `ownerMayEdit`; null-master rows; a delegated write), the whole-write refusals, the all-or-none outcome, and a row inserted after the gate's read. `packages/plugins/plugin-security/src/controlled-by-parent-detail-write-authority.test.ts` §3 holds the composed predicate: no floor where the gate admitted the write, the floor where the gate judged nothing. diff --git a/packages/plugins/plugin-security/src/controlled-by-parent-detail-write-authority.test.ts b/packages/plugins/plugin-security/src/controlled-by-parent-detail-write-authority.test.ts index 7fc6e10b977..81869015b84 100644 --- a/packages/plugins/plugin-security/src/controlled-by-parent-detail-write-authority.test.ts +++ b/packages/plugins/plugin-security/src/controlled-by-parent-detail-write-authority.test.ts @@ -44,10 +44,14 @@ // master gate is what decides". // // Section 3 is the other half of the same precondition, and the reason the floor -// is dropped from a CALL SITE rather than from the object's posture alone: on a -// BULK (AST) write `assertControlledByParentWrite` returns early -// (`extractSingleId == null`), so nothing there replaces the floor and the floor -// therefore STAYS. That is a residual, pinned, not an oversight. +// is dropped from a CALL SITE rather than from the object's posture alone. When +// this file was written the gate returned early on a write that addressed no +// single id, so nothing replaced the floor there and it stayed. The gate has +// since judged every master an addressed predicate write reaches, and ruling +// record 7073030861 (ADR-0055 §3 as amended 2026-11-22) applies the same +// precondition to that path: the floor is handed over where the gate judged the +// write and admitted it, for the rows it judged, and stays on every write the +// gate did not judge. import { describe, it, expect, vi } from 'vitest'; import { SecurityPlugin } from './security-plugin.js'; @@ -401,9 +405,12 @@ function makeStore(rows: Record) { } if (!seam || opCtx.operation !== 'update') return; const dispatch = assertEngineUpdateDispatch(opCtx.data, opCtx.options); - if (dispatch.kind !== 'by-id') return; seam.honoured = true; - const targets = (rows[opCtx.object] ?? []).filter((r) => r.id === dispatch.id); + // The predicate path judges every row the composed AST selects, each + // merged with the payload, as `ObjectQL.update` does. + const targets = (rows[opCtx.object] ?? []).filter((r) => + dispatch.kind === 'by-id' ? r.id === dispatch.id : matchesFilterCondition(r, opCtx.ast?.where ?? null), + ); await seam.evaluate(targets.map((r) => ({ ...r, ...opCtx.data }))); }, }; @@ -536,12 +543,14 @@ async function boot(seed: { shares?: Row[] } = {}) { * so the injected tree is the only place the scope is observable (the * engine double is never called with it). */ - bulkDetailWrite: async (operation: string, where: Record, context: any) => { + bulkDetailWrite: async (operation: string, where: Record, context: any, multi = false) => { const opCtx: any = { object: 'crm_campaign_member', operation, ...(operation === 'delete' ? {} : { data: { status: 'responded' } }), - options: { where }, + // `multi: true` is what the engine routes down its predicate path; a + // write that carries neither it nor an id is one the engine refuses. + options: { where, ...(multi ? { multi: true } : {}) }, ast: { where }, context, }; @@ -705,16 +714,48 @@ describe('[#8757] §2 the card\'s three measured refusals become the master gate }); }); -describe('[#8757] §3 RESIDUAL — the floor STAYS where the master gate does not run', () => { - it('a BULK write on the detail keeps the ownership floor', async () => { +describe('[#8757] §3 THE PREDICATE PATH — the floor goes where the master gate judged the write, and stays where it did not', () => { + // Ruling record 7073030861 (ADR-0055 §3 as amended 2026-11-22). This section + // used to pin a RESIDUAL: "a BULK write on the detail keeps the ownership + // floor", on the reasoning that the gate returned early with no single id. + // The gate has judged a predicate write since: every master of the rows the + // write selects, refusing the write whole on the first the caller may not + // edit. So the precondition the floor's removal hangs on holds there too, and + // the residual is now the write the gate does NOT judge. + for (const operation of ['update', 'delete'] as const) { + it(`an addressed predicate ${operation.toUpperCase()} the gate admitted carries no ownership floor, and is scoped to the rows it judged`, async () => { + const h = await boot(); + const mkt = h.ctxFor(MKT, 'marketing'); + // Both rows under the campaign `usr_marketing` owns, one of them created + // by the admin: the row the floor used to leave out of the match. + const { outcome, injected } = await h.bulkDetailWrite(operation, { crm_campaign: 'camp_mkt' }, mkt, true); + expect(outcome).toMatchObject({ ok: true }); + expect(injected).not.toContain('created_by'); + // The scope is the gate's own row list: the rows whose master it judged. + expect(injected).toContain('mem_mkt_byadmin'); + expect(injected).toContain('"mem_mkt"'); + expect(injected).not.toContain('mem_admin'); + }); + + it(`a predicate ${operation.toUpperCase()} that reaches a master the caller may not edit is refused whole by the gate`, async () => { + const h = await boot(); + const mkt = h.ctxFor(MKT, 'marketing'); + // `status: 'sent'` selects rows under both campaigns; `camp_admin` is not + // `usr_marketing`'s to edit. The widening is bounded by this refusal. + const { outcome } = await h.bulkDetailWrite(operation, { status: 'sent' }, mkt, true); + expect(outcome).toMatchObject({ ok: false, code: 'PERMISSION_DENIED', status: 403 }); + expect(outcome.message).toMatch(MASTER_GATE_SENTENCE); + }); + } + + it('a write the gate does not judge keeps the ownership floor', async () => { const h = await boot(); const mkt = h.ctxFor(MKT, 'marketing'); - // `assertControlledByParentWrite` returns early on a bulk write - // (`extractSingleId == null` — "scoped by the read filter on the AST"), so - // no master gate covers this path and the precondition is NOT satisfied - // here. The floor is therefore dropped from the by-id CALL SITE, never from - // the object's posture alone, and this case is what holds that shape: the - // AST-injected filter must still carry `created_by == current_user.id`. + // No id and no `multi: true`: the engine refuses this shape itself, the + // gate judges nothing for it, and so nothing vouches for the floor's + // removal. The floor is dropped from a CALL SITE the gate covers, never + // from the object's posture alone, and this case is what holds that shape: + // the AST-injected filter must still carry `created_by == current_user.id`. const { injected } = await h.bulkDetailWrite('update', { status: 'sent' }, mkt); expect(injected).toContain('created_by'); expect(injected).toContain(MKT); diff --git a/packages/plugins/plugin-security/src/controlled-by-parent-every-master-edit.test.ts b/packages/plugins/plugin-security/src/controlled-by-parent-every-master-edit.test.ts index 1324e38dee3..4df133e52f2 100644 --- a/packages/plugins/plugin-security/src/controlled-by-parent-every-master-edit.test.ts +++ b/packages/plugins/plugin-security/src/controlled-by-parent-every-master-edit.test.ts @@ -340,9 +340,14 @@ const LEGS: ReadonlyArray<{ leg: Leg; name: string; callers: readonly Caller[] } { leg: 'chain', name: "the master's own master", callers: ['a member', 'an org admin'] }, ]; -/** The rows a write reaches: a selecting write by a floor-bound caller reaches only the rows it created. */ +/** + * The rows a write reaches. A selecting write the master gate admits reaches + * every row it selects, the rows another user created included (ADR-0055 §3 as + * amended 2026-11-22, ruling record 7073030861); a delegated one keeps both + * principals' ownership floors and reaches only the rows the member created. + */ const reached = (caller: Caller, shape: ShapeName, rows: { own: string[]; all: string[] }) => - shape !== 'selecting' ? [rows.own[0]] : caller === 'an org admin' ? rows.all : rows.own; + shape !== 'selecting' ? [rows.own[0]] : caller === 'an agent acting for a member' ? rows.own : rows.all; describe('ADR-0055 §3 — a write to a controlled_by_parent detail asks for edit access on every master it involves', () => { let rig: Rig; diff --git a/packages/plugins/plugin-security/src/controlled-by-parent-write-shape-master-edit.test.ts b/packages/plugins/plugin-security/src/controlled-by-parent-write-shape-master-edit.test.ts index af3a21f7c2a..cda42032179 100644 --- a/packages/plugins/plugin-security/src/controlled-by-parent-write-shape-master-edit.test.ts +++ b/packages/plugins/plugin-security/src/controlled-by-parent-write-shape-master-edit.test.ts @@ -394,8 +394,11 @@ describe("ADR-0055 §3 — a controlled_by_parent detail is written only under m describe('a write whose rows all sit under masters the caller may edit lands as it did', () => { const WRITES: Record = { - // The platform ownership floor binds a member, on its own write and an agent's alike. - 'a member': 'own', + // The master gate judged every master the write reaches, so the member's + // own write hands the platform ownership floor to it (ADR-0055 §3 as + // amended 2026-11-22, ruling record 7073030861). A delegated write keeps + // both principals' floors. + 'a member': 'all', 'an agent acting for a member': 'own', 'an org admin': 'all', }; diff --git a/packages/plugins/plugin-security/src/platform-ownership-policies.ts b/packages/plugins/plugin-security/src/platform-ownership-policies.ts index 651bcc7e8a9..e5a4d24c10b 100644 --- a/packages/plugins/plugin-security/src/platform-ownership-policies.ts +++ b/packages/plugins/plugin-security/src/platform-ownership-policies.ts @@ -317,10 +317,14 @@ export function owdOpenWritesCoversOperation(operation: string): boolean { * * So the caller must vouch for coverage separately * (`RlsFilterOptions.masterGateCoversThisWrite`), and the floor comes off only - * where BOTH hold. The path that makes the distinction load-bearing rather than - * ceremonial is the BULK write: `assertControlledByParentWrite` returns early - * when the operation addresses no single id, so nothing replaces the floor - * there and the floor stays — on an object this predicate answers `true` for. + * where BOTH hold. The paths that make the distinction load-bearing rather than + * ceremonial are the writes the gate does not judge: a delegated write keeps + * both principals' floors, and a write the engine does not route to the gate's + * by-id or predicate leg has nothing replacing the floor, so the floor stays — + * on an object this predicate answers `true` for. An addressed predicate write + * used to be among them; the gate judges every master it reaches, and since + * ruling record 7073030861 (ADR-0055 §3 as amended 2026-11-22) the caller + * vouches for it there too, for the rows the gate judged. * * An unresolvable schema yields `false` and the floor stays (fail closed). */ diff --git a/packages/plugins/plugin-security/src/predicate-write-floor-deferral.test.ts b/packages/plugins/plugin-security/src/predicate-write-floor-deferral.test.ts index cd93d39d468..64d6cd7e940 100644 --- a/packages/plugins/plugin-security/src/predicate-write-floor-deferral.test.ts +++ b/packages/plugins/plugin-security/src/predicate-write-floor-deferral.test.ts @@ -75,6 +75,18 @@ const MEMBER_DEFAULT = defaultPermissionSets.find((p) => p.name === 'member_defa const DEAL = 'pwf_deal'; const MEMO = 'pwf_memo'; +/** The master of the `controlled_by_parent` details below: `private`, so its owner, a share or Modify All decides who edits it. */ +const ORDER = 'pwf_order'; +/** A `controlled_by_parent` detail of {@link ORDER}, its master required. */ +const LINE = 'pwf_line'; +/** The same detail declaring `writeRequiresMasterRead`: READ on the master is the master question. */ +const LINE_MASTER_READ = 'pwf_line_master_read'; +/** The same detail declaring `ownerMayEdit`: a by-id update by the row's owner asks READ on the master. */ +const LINE_OWNER_MAY_EDIT = 'pwf_line_owner_may_edit'; +/** The same detail with an OPTIONAL master: a row that names none is its owner's. */ +const LINE_OPTIONAL = 'pwf_line_optional'; +const LINES = [LINE, LINE_MASTER_READ, LINE_OWNER_MAY_EDIT, LINE_OPTIONAL] as const; +type LineObject = (typeof LINES)[number]; const ORG = 'org_pwf'; /** Owns r1 and r2, created r1 and r3: the owner who created some of what they own. */ @@ -101,8 +113,12 @@ const WIDE_MANAGER = 'usr_wide_manager'; const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; const MODIFY_ALL = { ...CRUD, viewAllRecords: true, modifyAllRecords: true }; -const REP_SET = PermissionSetSchema.parse({ name: 'pwf_rep', objects: { [DEAL]: CRUD, [MEMO]: CRUD } }); -const MANAGER_SET = PermissionSetSchema.parse({ name: 'pwf_manager', objects: { [DEAL]: MODIFY_ALL, [MEMO]: MODIFY_ALL } }); +const onOrderAndLines = (grant: T) => Object.fromEntries([ORDER, ...LINES].map((object) => [object, grant])); +const REP_SET = PermissionSetSchema.parse({ name: 'pwf_rep', objects: { [DEAL]: CRUD, [MEMO]: CRUD, ...onOrderAndLines(CRUD) } }); +const MANAGER_SET = PermissionSetSchema.parse({ + name: 'pwf_manager', + objects: { [DEAL]: MODIFY_ALL, [MEMO]: MODIFY_ALL, ...onOrderAndLines(MODIFY_ALL) }, +}); /** * Modify All, and an APP-AUTHORED update policy beside it. On an ordinary * business object Modify All does not bypass write-side row-level security @@ -180,6 +196,23 @@ const MATRIX: Record = { /** The rows DAVE's `edit` shares name. */ const SHARED_WITH_DAVE: readonly Role[] = ['r2', 'r3']; +/** A `controlled_by_parent` detail of {@link ORDER}: an ordinary tenant object carrying the owner x creator pair. */ +const lineObject = (name: string, label: string, extra: Record = {}, masterRequired = true) => ({ + name, + label, + sharingModel: 'controlled_by_parent', + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, + batch: { name: 'batch', type: 'text' }, + order: { name: 'order', type: 'master_detail', reference: ORDER, required: masterRequired }, + owner_id: { name: 'owner_id', type: 'text' }, + created_by: { name: 'created_by', type: 'text' }, + organization_id: { name: 'organization_id', type: 'text' }, + }, + ...extra, +}); + let engine: ObjectQL; let securityPlugin: SecurityPlugin; let sharing: SharingService | undefined; @@ -239,6 +272,26 @@ beforeAll(async () => { organization_id: { name: 'organization_id', type: 'text' }, }, }, + { + name: ORDER, + label: 'Order', + sharingModel: 'private', + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, + owner_id: { name: 'owner_id', type: 'text' }, + created_by: { name: 'created_by', type: 'text' }, + organization_id: { name: 'organization_id', type: 'text' }, + }, + }, + lineObject(LINE, 'Order line'), + lineObject(LINE_MASTER_READ, 'Order line, written with read on the order', { + sharing: { controlledByParent: { writeRequiresMasterRead: true } }, + }), + lineObject(LINE_OWNER_MAY_EDIT, 'Order line, edited by its owner', { + sharing: { controlledByParent: { ownerMayEdit: true } }, + }), + lineObject(LINE_OPTIONAL, 'Order line, order optional', {}, false), ], } as never); await engine.syncSchemas(); @@ -892,3 +945,224 @@ describe('[#35802] predicateWriteFloorDropIds: the by-id floor decision, asked p expect(peak).toBe(25); }); }); + +// [#35802 · ruling record 7073030861] The other half of the card: its own +// repro object, a `controlled_by_parent` detail. +// +// Record sharing abstains on such a detail (its access derives from the +// master), so the composition above never replaces its floor. The by-id write +// hands the floor to ADR-0055's master gate instead (step 2.8): a caller who +// may edit the master writes every detail row under it, whoever created the +// row. The gate judges a predicate write too, every master of the rows it +// selects, and refuses the write whole on the first the caller may not write +// under; yet the floor stayed on that path, so the master's owner changed only +// the rows they had created and a Modify All holder changed none. +// +// Ruled: once the gate has passed every master a non-delegated addressed +// predicate write reaches, the floor is handed to it there as well. The pins +// are the same comparison as above, row for row against the by-id write, on +// +// pwf_order the master: `private`, owned by ALICE. DAVE holds +// an `edit` share on it; BOB and CAROL a `read` share. +// pwf_line the detail, master required. +// pwf_line_master_read … declaring `writeRequiresMasterRead`. +// pwf_line_owner_may_edit … declaring `ownerMayEdit`. +// pwf_line_optional … its master optional. +// +// Each copy of the matrix hangs under a fresh order; a second order of BOB's, +// which ALICE reads through a share and may not edit, is there for the rows a +// case moves under it. +describe('[#35802] a predicate write of a controlled_by_parent detail writes the rows its by-id writes do', () => { + type LineSeed = { + /** Rows that hang under BOB's order, which ALICE can read and may not edit. */ + underOtherOrder?: readonly Role[]; + /** Rows that name no order (the optional-master detail only). */ + noOrder?: readonly Role[]; + }; + + async function seedLines(object: LineObject, seed: LineSeed = {}): Promise<{ batch: string; ids: Ids }> { + const batch = `line_batch_${++seq}`; + const order = `${batch}_order`; + const otherOrder = `${batch}_other_order`; + await engine.insert(ORDER, [ + { id: order, name: 'order', owner_id: ALICE, created_by: ALICE, organization_id: ORG }, + { id: otherOrder, name: 'other order', owner_id: BOB, created_by: BOB, organization_id: ORG }, + ], SYS); + const shares: Array<[record: string, recipient: string, level: 'read' | 'edit']> = [ + [order, DAVE, 'edit'], + [order, BOB, 'read'], + [order, CAROL, 'read'], + [otherOrder, ALICE, 'read'], + ]; + for (const [recordId, recipient, level] of shares) { + await engine.insert('sys_record_share', { + object_name: ORDER, record_id: recordId, recipient_type: 'user', recipient_id: recipient, + access_level: level, source: 'manual', organization_id: ORG, + }, SYS); + } + const ids = Object.fromEntries(ROLES.map((role) => [role, `${batch}_${role}`])) as Ids; + await engine.insert(object, ROLES.map((role) => ({ + id: ids[role], + name: 'as seeded', + batch, + order: seed.noOrder?.includes(role) ? null : seed.underOtherOrder?.includes(role) ? otherOrder : order, + organization_id: ORG, + ...MATRIX[role], + })), SYS); + return { batch, ids }; + } + + /** Predicate write on one copy, by-id writes on another; both must name `expected`. */ + async function expectLinesMatchById( + object: LineObject, + verb: 'update' | 'delete', + caller: object, + expected: readonly Role[], + seed: LineSeed = {}, + ): Promise { + const predicateCopy = await seedLines(object, seed); + await predicateWrite(object, verb, predicateCopy.batch, caller); + const byPredicate = await changedRows(object, predicateCopy.ids, verb); + + const byIdCopy = await seedLines(object, seed); + const byId = await byIdAdmits(object, verb, byIdCopy.ids, caller); + + expect(byPredicate, 'the predicate write changes exactly the rows the by-id path admits').toEqual(byId); + expect(byId, 'the by-id oracle answers the set this case expects').toEqual([...expected]); + } + + type Refusal = { code?: unknown; statusCode?: unknown; status?: unknown } | null; + const refusalOf = (p: Promise) => p.then(() => null, (e: unknown) => e) as Promise; + + /** The predicate write is refused by the master gate and changes no row; the by-id writes admit `byIdExpected`. */ + async function expectRefusedWhole( + object: LineObject, + verb: 'update' | 'delete', + caller: object, + byIdExpected: readonly Role[], + seed: LineSeed = {}, + ): Promise { + const copy = await seedLines(object, seed); + const refusal = await refusalOf(predicateWrite(object, verb, copy.batch, caller)); + expect(refusal, 'the predicate write is refused').not.toBeNull(); + expect(refusal?.code).toBe('PERMISSION_DENIED'); + expect(refusal?.statusCode ?? refusal?.status).toBe(403); + expect(await changedRows(object, copy.ids, verb), 'nothing was written').toEqual([]); + + const byIdCopy = await seedLines(object, seed); + expect(await byIdAdmits(object, verb, byIdCopy.ids, caller)).toEqual([...byIdExpected]); + } + + const ALL: readonly Role[] = ['r1', 'r2', 'r3', 'r4']; + + for (const verb of ['update', 'delete'] as const) { + describe(`predicate ${verb}`, () => { + it("the master's owner (ALICE): every row under her order, the two CAROL created included", async () => { + await expectLinesMatchById(LINE, verb, memberOf(ALICE, REP_SET.name), ALL); + }); + + it('a member who may edit the master and created none of the rows (DAVE, an edit share on the order): every row', async () => { + await expectLinesMatchById(LINE, verb, memberOf(DAVE, REP_SET.name), ALL); + }); + + it('the Modify All manager, who owns and created nothing: every row', async () => { + await expectLinesMatchById(LINE, verb, memberOf(MANAGER, MANAGER_SET.name), ALL); + }); + + it('a member who may not edit ONE of the masters (r4 under an order ALICE only reads): refused whole, nothing written', async () => { + await expectRefusedWhole(LINE, verb, memberOf(ALICE, REP_SET.name), ['r1', 'r2', 'r3'], { underOtherOrder: ['r4'] }); + }); + + it('a member who only reads the master (CAROL): refused whole, the rows she created included', async () => { + await expectRefusedWhole(LINE, verb, memberOf(CAROL, REP_SET.name), []); + }); + + it('a detail declaring writeRequiresMasterRead: a member who only reads the master (CAROL) writes every row', async () => { + await expectLinesMatchById(LINE_MASTER_READ, verb, memberOf(CAROL, REP_SET.name), ALL); + }); + + it("a detail declaring ownerMayEdit: the master's owner writes every row", async () => { + await expectLinesMatchById(LINE_OWNER_MAY_EDIT, verb, memberOf(ALICE, REP_SET.name), ALL); + }); + + it('a detail declaring ownerMayEdit, unchanged: its owner leg is a by-id update only, so BOB, who reads the master, is refused whole', async () => { + // Ruling 6398566164: by id BOB updates the two rows he owns and + // deletes none; a predicate write still asks EDIT on the master. + await expectRefusedWhole(LINE_OWNER_MAY_EDIT, verb, memberOf(BOB, REP_SET.name), verb === 'update' ? ['r3', 'r4'] : []); + }); + + it('rows that name no master are their owner\'s: ALICE writes the two she owns, created by her or not', async () => { + await expectLinesMatchById(LINE_OPTIONAL, verb, memberOf(ALICE, REP_SET.name), ['r1', 'r2'], { noOrder: ALL }); + }); + + it('rows that name no master, the Modify All manager: every row', async () => { + await expectLinesMatchById(LINE_OPTIONAL, verb, memberOf(MANAGER, MANAGER_SET.name), ALL, { noOrder: ALL }); + }); + + it("a write on another user's behalf keeps both floors (ADR-0090 D10): ALICE for ERIN writes only the rows ALICE created", async () => { + await expectLinesMatchById(LINE, verb, onBehalfOf(memberOf(ALICE, REP_SET.name), ERIN), ['r1', 'r3']); + }); + }); + } + + it('all matched rows or none: a newly matched row a beforeDelete hook refuses refuses the whole delete', async () => { + // Before the ruling ALICE's predicate delete matched r1 and r3 alone (the + // floor) and answered success. r2, which CAROL created, is now matched as + // its by-id delete is admitted, and the hook's refusal of it is the answer + // for the whole write. + const refuseDeleteOf = new Set(); + engine.registerHook( + 'beforeDelete', + async (ctx: any) => { + if (refuseDeleteOf.has(String(ctx.input?.id))) { + throw Object.assign(new Error('refused by the beforeDelete hook'), { status: 409 }); + } + }, + { object: LINE }, + ); + const copy = await seedLines(LINE); + refuseDeleteOf.add(copy.ids.r2); + try { + const refusal = await refusalOf(predicateWrite(LINE, 'delete', copy.batch, memberOf(ALICE, REP_SET.name))); + expect(refusal, 'the predicate delete is refused').not.toBeNull(); + expect(refusal?.statusCode ?? refusal?.status).toBe(409); + expect(await changedRows(LINE, copy.ids, 'delete')).toEqual([]); + } finally { + refuseDeleteOf.clear(); + } + }); + + it('a row that appears after the master gate judged the write is not written: the write is scoped to the rows the gate judged', async () => { + // The gate reads the rows the predicate selects and judges their masters. + // A row inserted after that read, under an order ALICE reads and may not + // edit, matches her predicate and has had no master judged; with the floor + // handed to the gate nothing else would refuse it. The write's scope is + // the gate's own id list, so the row is not matched. + const { batch, ids } = await seedLines(LINE); + const late = `${batch}_late`; + const realFind = engine.find.bind(engine); + let armed = true; + (engine as any).find = async (object: string, query: any, ...rest: unknown[]) => { + const answer = await realFind(object, query, ...(rest as [])); + const callerRead = object === LINE && query?.context?.userId === ALICE && query?.context?.isSystem !== true; + if (armed && callerRead) { + armed = false; + await engine.insert(LINE, { + id: late, name: 'as seeded', batch, order: `${batch}_other_order`, organization_id: ORG, owner_id: BOB, created_by: ALICE, + }, SYS); + } + return answer; + }; + try { + await predicateWrite(LINE, 'update', batch, memberOf(ALICE, REP_SET.name)); + } finally { + (engine as any).find = realFind; + } + expect(armed, 'the row was inserted during the write').toBe(false); + expect(await changedRows(LINE, ids, 'update')).toEqual(ALL); + const lateRow = (await engine.findOne(LINE, { where: { id: late }, context: { isSystem: true } } as never)) as + | Record + | null; + expect(lateRow?.name, 'the unjudged row keeps its value').toBe('as seeded'); + }); +}); 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 a056eada89f..0f41242093e 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -134,7 +134,11 @@ import { } from './unresolved-posture.js'; import { assertReadableQueryFields } from './predicate-guard.js'; import { DelegationScopeViolationError, PermissionDeniedError, MaskedValueWriteError } from './errors.js'; -import { masterGateRefusalUserCopyOf, type MasterQuestion } from './security-plugin-cbp-write-gate.js'; +import { + masterGateRefusalUserCopyOf, + predicateWriteRowIdsJudgedByMasterGate, + type MasterQuestion, +} from './security-plugin-cbp-write-gate.js'; import { QUEUE_FIELD, CLAIM_REFUSAL, @@ -919,7 +923,9 @@ export function registerAuthzMiddleware( // never reaches 2.7, so its per-row check (step 3.6, [#19950]) keeps the // floor on exactly the terms its `where` scope does: step 3 decides the // floor per matched row ({@link predicateFloorDropIds}), and the check - // reads that decision for each row it judges. + // reads that decision for each row it judges; on a `controlled_by_parent` + // detail the master gate vouched for, both carry no floor + // ({@link predicateMasterGateRowIds}). let preImageFloorOpts: RlsFilterOptions | null = null; // [#35802] The predicate write's per-row floor decision: the matched rows // whose platform ownership floor step 3 replaced, because a by-id write of @@ -928,6 +934,18 @@ export function registerAuthzMiddleware( // 3.6's per-row check reads it when the engine hands the rows over, which // is after step 3 has run. let predicateFloorDropIds: ReadonlySet | null = null; + // [ADR-0055 §3 as amended 2026-11-22 · ruling record 7073030861] The + // COVERAGE VOUCH on the predicate path: the rows ADR-0055's master gate + // (step 2.8) judged for this addressed predicate update or delete of a + // `controlled_by_parent` detail, on the caller's own pass, having refused + // none. Null until that pass returns, and on every other write: a by-id + // write (step 2.7 vouches there), a delegated one (both floors stay, + // ADR-0090 D10), a nested or referential one, an object that derives + // nothing from a master. Step 3 hands the platform ownership floor to the + // gate for exactly these rows and scopes the write to them; step 3.6 + // holds a predicate update's rows to the check composed on the same + // decision. + let predicateMasterGateRowIds: readonly unknown[] | null = null; // [ADR-0090 D10] Its twin for the DELEGATOR of an on-behalf-of write: the // floor decision and coverage vouch the delegator's OWN direct by-id write // of this row would get ({@link delegatorOwnWriteFloorOptions}). Null on @@ -1445,7 +1463,8 @@ export function registerAuthzMiddleware( // pass, and 2.8's condition is a strict SUPERSET of this one: the same // `permissionSets.length > 0 && userId && this.ql` triple, the same // single target id (`extractSingleId`; with none, 2.8 judges every - // master the write reaches instead), and one + // master the write reaches instead, and vouches for that write + // itself: `predicateMasterGateRowIds`), and one // additional operation (`insert`, which has no pre-image and so no // floor to drop). Reaching this line therefore PROVES the master gate // will answer the same write — the maintainer's precondition, held @@ -1639,6 +1658,16 @@ export function registerAuthzMiddleware( opCtx, opCtx.context, ); + // [ADR-0055 §3 as amended 2026-11-22 · ruling record 7073030861] The + // gate has just judged this write for the caller and refused nothing. + // On an addressed predicate write that is not delegated, the rows it + // judged are the vouch that it covers this write, as step 2.7's + // position above this block is for a by-id write. Read here, before + // the delegator's pass, so the record is the caller's; a delegated + // write takes none and keeps both floors, as its by-id write does. + if (!delegatorSets && this.addressedPredicateWrite(opCtx, nestedInOperation, referentialFieldClearWrite)) { + predicateMasterGateRowIds = predicateWriteRowIdsJudgedByMasterGate(opCtx); + } // [ADR-0090 D10] The delegator must ALSO have edit access to the master // — a detail write on behalf of a user requires that user's master-edit. if (delegatorSets) { @@ -2237,7 +2266,11 @@ export function registerAuthzMiddleware( opCtx.object, opCtx.operation, opCtx.context, - preImageFloorOpts ?? undefined, + // A by-id update is held to step 2.7's floor decision. A predicate + // update of a `controlled_by_parent` detail the master gate vouched + // for is held to the check its rows' by-id writes get, the floor + // handed to that gate (ruling record 7073030861). + preImageFloorOpts ?? (predicateMasterGateRowIds ? { masterGateCoversThisWrite: true } : undefined), ); // [ADR-0090 D10] The post-image must satisfy the delegator's CHECK too — // an on-behalf-of write may not produce a row the delegator itself @@ -2490,10 +2523,13 @@ export function registerAuthzMiddleware( // old one. Every other row keeps `checkParts`. Not on a delegated // write, whose floors step 3 keeps, nor where step 2.7 already // decided this write's floor (`preImageFloorOpts`), whose - // `checkParts` already carry that decision. + // `checkParts` already carry that decision; nor where the master + // gate vouched for a predicate write (`predicateMasterGateRowIds`), + // for the same reason. let floorDropJudge: ((image: Record) => boolean) | undefined; if ( !preImageFloorOpts && + !predicateMasterGateRowIds && !delegatorSets && this.addressedPredicateWrite(opCtx, nestedInOperation, referentialFieldClearWrite) ) { @@ -2784,11 +2820,18 @@ export function registerAuthzMiddleware( // here with the SAME `andComposeLayers` that wrapper uses — so the // injected predicate is byte-identical to before, and the Layer 0 // verdict that produced it is in hand to be RECORDED below. + // + // [ADR-0055 §3 as amended 2026-11-22 · ruling record 7073030861] A + // predicate write the master gate vouched for (step 2.8, + // `predicateMasterGateRowIds`) composes the Layer 1 its rows' by-id + // writes do: the platform ownership floor handed to that gate, every + // app-authored policy and the write-visibility derivation as they stand. const layered = await this.computeLayeredRlsFilter( permissionSets, opCtx.object, opCtx.operation, opCtx.context, + predicateMasterGateRowIds ? { masterGateCoversThisWrite: true } : undefined, ); const rlsFilter = andComposeLayers(layered.layer0, layered.layer1); // [#35802] Where the caller's scope sits in `extra`: a predicate write @@ -2840,7 +2883,17 @@ export function registerAuthzMiddleware( // writes none of the object's records, whatever its predicate addresses. // The by-id leg (step 2.7) refuses the same caller too. if (this.addressedPredicateWrite(opCtx, nestedInOperation, referentialFieldClearWrite)) { - const readableScope = await this.readableRowsScopeForPredicateWrite(opCtx); + // [ruling record 7073030861] Where the master gate vouched for this + // write, the scope is the gate's own row list, never a second asking + // of the same read question: the rows the floor is handed over for + // are then the rows whose masters were judged, and a row that came to + // match the predicate after the gate read it is not written. The list + // is the read door's answer for the caller's predicate, under the cap + // and the refusals the narrowing itself applies + // (`controlledByParentPredicateWriteMasters`). + const readableScope = predicateMasterGateRowIds + ? { id: { $in: [...predicateMasterGateRowIds] } } + : await this.readableRowsScopeForPredicateWrite(opCtx); extra.push(readableScope); // [#35802] The #5492 floor composition, per matched row. Step 2.7 // lets the declared write authority's `allow` replace the platform @@ -2856,8 +2909,10 @@ export function registerAuthzMiddleware( // and only where no authored write-class policy remains once it is // (where one does, replacing the floor admits no row and no verdict is // asked). Layer 0 is recomposed as it stood. Not for a delegated - // write, which keeps both floors on the by-id path too. - if (rlsFilter && layered.layer1 && !delegatorSets) { + // write, which keeps both floors on the by-id path too, nor for a + // write the master gate vouched for, whose Layer 1 carries no floor + // to replace. + if (rlsFilter && layered.layer1 && !delegatorSets && !predicateMasterGateRowIds) { const relief = await predicateWriteFloorRelief.call( this, opCtx, diff --git a/packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts b/packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts index e2178931bbe..b730dbc0375 100644 --- a/packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts +++ b/packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts @@ -254,11 +254,44 @@ type CbpRelation = NonNullable> * none — only where the master is OPTIONAL ({@link CbpRelation.optional}); a * required master's empty reference is refused there, as before. Each such row * carries its `id`, its master reference and, where the object has one, its - * `owner_id`, read as system. + * `owner_id`, read as system. `rowIds` are the ids of the selected rows whose + * master reference was read: the rows `masterIds` and `nullMasterRows` were + * derived from, and so the rows the gate judges. */ export interface CbpPredicateWriteSelection { masterIds: unknown[]; nullMasterRows: Array>; + rowIds: unknown[]; +} + +/** + * [ADR-0055 §3 as amended 2026-11-22 · ruling record 7073030861] The rows a + * predicate write's master gate judged, keyed by the operation it judged. + * + * Written by {@link judgeControlledByParentWrite} once, at the end of a pass + * that refused nothing: every master those rows name passed the walk, every + * row naming none passed the owner rule, and a master the body names was + * asked. A pass that refuses writes nothing here, and neither does a by-id + * write, an insert, or a shape the engine does not route down its predicate + * path. + * + * Read by the engine middleware, straight after the CALLER's own pass, as the + * coverage vouch for the predicate path (`RlsFilterOptions.masterGateCoversThisWrite`) + * and as that write's row scope, so the rows the floor is handed over for are + * the rows the gate judged and no others + * ({@link predicateWriteRowIdsJudgedByMasterGate}). + */ +const PREDICATE_WRITE_JUDGED_ROW_IDS = new WeakMap(); + +/** + * The ids {@link PREDICATE_WRITE_JUDGED_ROW_IDS} holds for `opCtx`: the rows + * the last pass of the master gate judged for this predicate write and + * admitted, or `null` when no pass did (the gate refused, did not run, or the + * write is not a predicate write of a `controlled_by_parent` detail). + */ +export function predicateWriteRowIdsJudgedByMasterGate(opCtx: unknown): readonly unknown[] | null { + if (opCtx === null || typeof opCtx !== 'object') return null; + return PREDICATE_WRITE_JUDGED_ROW_IDS.get(opCtx) ?? null; } /** @@ -631,7 +664,7 @@ async function judgeControlledByParentWrite( : rlsOperationForVerb(operation) === 'delete' && resolveEngineDeleteDispatch(opCtx.options as EngineDeleteDispatchInput | undefined).kind === 'multi'; if (!predicatePath) return; - const { masterIds: predicateMasters, nullMasterRows } = + const { masterIds: predicateMasters, nullMasterRows, rowIds } = await this.controlledByParentPredicateWriteMasters(object, operation, rel, opCtx); for (const predicateMasterId of predicateMasters) { await this.assertControlledByParentChainEditable( @@ -655,6 +688,10 @@ async function judgeControlledByParentWrite( // body names is asked (re-pointing a row under a master is that master's // question, whoever owns the row). if (predicateMasters.length > 0 || nullMasterRows.length > 0) await askBodyNamedMaster(predicateMasters); + // [ruling record 7073030861] Nothing above refused: these are the rows + // this pass judged, recorded for the middleware's coverage vouch + // ({@link PREDICATE_WRITE_JUDGED_ROW_IDS}). + if (opCtx !== null && typeof opCtx === 'object') PREDICATE_WRITE_JUDGED_ROW_IDS.set(opCtx, rowIds); return; } detailRecordId = targetId; @@ -1077,7 +1114,7 @@ export async function controlledByParentPredicateWriteMasters( const ids = rows .map((r) => (r && typeof r === 'object' ? (r as { id?: unknown }).id : undefined)) .filter((id) => id !== undefined && id !== null); - if (ids.length === 0) return { masterIds: [], nullMasterRows: [] }; + if (ids.length === 0) return { masterIds: [], nullMasterRows: [], rowIds: [] }; // [ADR-0055 §3 as amended · #30905 ruling A] An OPTIONAL master's row may // name none, and is then judged by its owner, so the owner column is read // beside the reference where the object carries one. @@ -1090,19 +1127,25 @@ export async function controlledByParentPredicateWriteMasters( }); const masterIds = new Set(); const nullMasterRows: Array> = []; + // The rows whose master reference was read here, which is what the gate + // judges: a selected row no longer stored by this second read names no + // master to judge, and is not among them. + const rowIds: unknown[] = []; for (const row of Array.isArray(stored) ? stored : []) { if (!row || typeof row !== 'object') continue; const masterId = (row as Record)[rel.fk]; if (masterId == null) { if (rel.optional) { nullMasterRows.push(row as Record); + rowIds.push((row as { id?: unknown }).id); continue; } throw new MasterReferenceMissingError(object, operation, rel.fk, (row as { id?: unknown }).id); } masterIds.add(masterId); + rowIds.push((row as { id?: unknown }).id); } - return { masterIds: [...masterIds], nullMasterRows }; + return { masterIds: [...masterIds], nullMasterRows, rowIds }; } /** The body of `SecurityPlugin#assertMasterRowEditable`; the method's docblock there is its contract. */ diff --git a/packages/plugins/plugin-security/src/security-plugin-rls-filter.ts b/packages/plugins/plugin-security/src/security-plugin-rls-filter.ts index 4fde7736d89..a989cbd32a9 100644 --- a/packages/plugins/plugin-security/src/security-plugin-rls-filter.ts +++ b/packages/plugins/plugin-security/src/security-plugin-rls-filter.ts @@ -289,9 +289,11 @@ export async function computeLayeredRlsFilter( // the floor comes off only where the master gate DEMONSTRABLY covers the // same operation, which is a fact about the call site. The by-id write // pre-image gate vouches for it (step 2.8 runs immediately below it on - // the same pass, under a superset of its own guard); the bulk-write path - // does not and must not, because `assertControlledByParentWrite` returns - // early with no single id and nothing would replace the floor there. + // the same pass, under a superset of its own guard); the addressed + // predicate write vouches for it once step 2.8 has judged every master + // the write reaches, for the rows it judged (ADR-0055 §3 as amended + // 2026-11-22, ruling record 7073030861); a write that gate did not judge + // carries no vouch and keeps the floor. // Both directions are pinned in // `controlled-by-parent-detail-write-authority.test.ts`. // diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index bc7f66c01e5..cd665596fa6 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -679,14 +679,22 @@ interface RlsFilterOptions { * master is itself `controlled_by_parent`, on a non-delegated write. Why * the walk covers that master's write is stated once, at that call site's * `masterGateCoversThisWrite` bullet — not restated here; - * • the BULK write path does NOT, and must not: with no single id, - * `assertControlledByParentWrite` judges every master the write reaches - * and refuses on the first the caller may not edit, but that is a - * verdict, not a row scope, so the floor stays — dropping it here would - * widen the rows a member writes, a separate decision. Reading the - * posture alone here would have widened bulk writes on - * every `controlled_by_parent` detail to "any row under a READABLE - * master", which no gate had authorized; + * • [ADR-0055 §3 as amended 2026-11-22 · ruling record 7073030861] the + * addressed PREDICATE write (`multi: true` update or delete) sets it, + * for a caller not acting on another user's behalf, once step 2.8 has + * judged the write on that caller's pass and refused nothing: with no + * single id, `assertControlledByParentWrite` judges every master of the + * rows the write selects, and each selected row that names none by the + * owner rule, and refuses the write whole on the first it may not write + * under. The vouch is the gate's own record of the rows it judged + * (`predicateWriteRowIdsJudgedByMasterGate`), and the write is scoped to + * those rows, so the floor is handed over for no row whose master went + * unjudged. The ruling applies the precondition quoted above to this + * path; it replaces an earlier bullet here that kept the floor on it + * as "a separate decision". A write the gate did not judge (a shape the + * engine does not route down its predicate path, a nested or + * referential write, a delegated one) carries no record and keeps the + * floor: the posture alone still drops nothing; * • `getReadFilter` and `checkAuthoredRowWrite` do not, and need not: the * floor is `update`/`delete`-only so the read path never carries it, and * the authored-write probe already removes it by provenance; @@ -5201,7 +5209,8 @@ export class SecurityPlugin implements Plugin { * predicate write of a detail is narrowed to the rows the read door returns * for the caller's own predicate ({@link readableRowsScopeForPredicateWrite}, * where this leaf composes) and judged per master by the 2.8 gate - * ({@link assertControlledByParentWrite}, a verdict, never a scope). + * ({@link assertControlledByParentWrite}, a verdict; the rows it judged are + * the scope of a write it vouches for, ruling record 7073030861). * * [ADR-0139 D5.2 / D5.3] The two master shapes the engine composes no leaf * over — a master on another datasource, a master an object-scoped read @@ -5726,7 +5735,8 @@ export class SecurityPlugin implements Plugin { * the read question the write doors narrow a predicate write's matched set to * ({@link readableRowsScopeForPredicateWrite}), so every row that write can * reach is among them. They can be MORE than it writes: the write-class - * scopes (the platform ownership floor, the detail's own write policy) still + * scopes (the detail's own write policy, and the platform ownership floor + * on a write this gate does not vouch for, a delegated one) still * leave some of them unwritten, and a row among them under a master the * caller may not edit refuses the write all the same. The caller named that * row and can read it, and its master too (the detail's read scope is the