diff --git a/.changeset/35917-by-id-widener-floor-term.md b/.changeset/35917-by-id-widener-floor-term.md new file mode 100644 index 00000000000..f111bead829 --- /dev/null +++ b/.changeset/35917-by-id-widener-floor-term.md @@ -0,0 +1,36 @@ +--- +'@objectstack/plugin-security': patch +--- + +fix(plugin-security): a record sharing `allow` no longer takes the ownership floor out of an OR an authored write policy stands in, so a creator can still edit or delete their own row by id beside an authored widener + +Clause-②: yes (widening) +Metadata-protocol: none + +On a by-id update or delete, when the sharing service answered `allow` for the row, the platform's own ownership floor (`created_by == current_user.id`, from `member_default` and `external_default`) was removed from the row-level filter. The sharing service answers `allow` when the caller owns the row or holds write depth over its owner, holds Modify All, or, for an update, holds an `edit` share on it or belongs to the queue it sits in. That filter is an OR of permissive policies. Where an app-authored update or delete policy applied to the caller as well, for example "any open deal" (`stage == 'open'`), removing the floor left that policy as the only term. A row the floor alone admitted, such as the caller's own closed deal, was then refused with 403 `PERMISSION_DENIED`. A predicate write (`multi: true` update, delete by `where`) over the same row wrote it. + +The maintainer ruled option A on #35917 (ruling comment 7063130499, 2026-11-21): under a sharing `allow`, the creator and owner floor stays an OR term beside an authored update or delete `using` policy, so a by-id write gives the answer a predicate write already gave for those rows. + +The floor is now dropped only where it is the filter's last term. Beside an authored write policy with a `using` it stays one term of the OR, both in the row gate before the write and in the defaulted check on the new image. What changes: + +- On an object where an authored update or delete policy applies to the caller, a by-id update or delete of a row the caller created, where record sharing answers `allow`, is admitted again, as it was before the sharing service could replace the floor. That covers a creator who owns the row, who holds write depth over its owner, who holds Modify All, and, for an update, who holds an `edit` share or queue membership. A creator with none of these is still refused by record sharing on a row the authored policy does not admit. The lifecycle verbs move with their write class: `transfer` with update, `purge` with delete (`restore` addresses no single row id, so it does not meet this gate). +- By id and by predicate now agree on the rows the floor admits. They do not agree on every row: an open row the caller neither owns nor holds a share on, which an authored policy admits, is written by id (the authored policy lifts the sharing refusal) and left out of a predicate write (the sharing bulk scope stays owner and shares). That divergence is older than this change and is not touched here. +- `security/explain` reports the same record verdict for these rows. +- The master check a `controlled_by_parent` detail write asks about its master row moves the same way: a master's creator, where record sharing allows the master, can now insert, update and delete its details beside the master's authored update policy. +- An authored write policy that cannot enforce (a missing column, an unresolved membership key) used to deny every such by-id write under `allow`. The creator's own rows now pass by the floor, as they already did under `abstain` and by predicate. +- A write on another user's behalf (ADR-0090 D10) follows the delegator: a by-id update or delete, by the delegator or on its behalf, of a row the delegator created beside its authored policy is now admitted. Before, both were refused. The suite pinned those refusals in 22 tests. Those tests now use rows the delegator did not create, so they still refuse with every assertion kept, and new tests pin the admission of a row, and of a master, the delegator created: `delegated-write-never-exceeds-delegator.test.ts` (the five held-row cells and the post-image store test, under both tenancy postures, 12 tests) and `explain-enforce-parity.test.ts` (the five #24746 held rows, under both postures, 10 tests). An agent still never writes a row its delegator's own write refuses; on a `controlled_by_parent` object that rests on the delegator's own composition, which new cells pin at the row gate, the stored row and the master gate. + +Removed capability: a `using` write policy no longer stops a row's own creator once record sharing says `allow`, and a master's authored update policy no longer stops the master's creator from writing its details. Where to put such a limit now: + +- A `check` on the update policy judges the stored image of every row, so it can refuse what a row becomes. It does not see the row as it stood before the write, so it cannot hold a row in a state: a creator can still edit a closed deal into one the check accepts. +- A `beforeUpdate` lifecycle hook sees the row as it stood before the write (`ctx.previous`), so a limit on the prior state goes there, and a delete has no new image, so a limit on deleting one's own rows goes in a `beforeDelete` hook. +- For a master's details, the master gate reads the master's row filter, not its `check`, and a hook on the master does not run for a detail write: the limit goes in a hook on the detail object. + +What does not change: + +- Where no authored write policy with a `using` applies, an `allow` still replaces the floor completely, as before. +- An authored policy still bounds every row the floor does not admit. Modify All does not lift an authored write policy on an ordinary business object (ADR-0066 ①), and an owner or `edit`-share target who did not create the row is still held to the authored policy. +- A `check` an author wrote still refuses the new image, the tenant wall still applies, and an `edit` share still widens update and never delete. +- Where record sharing abstains (no owner field), the floor still applies. +- Reads are not affected: the floor is a write-side policy. +- `ISecurityService.checkAuthoredRowWrite` still judges the authored policies alone, without the floor. diff --git a/content/docs/permissions/permissions-matrix.mdx b/content/docs/permissions/permissions-matrix.mdx index 5a1f61d2414..cbc138305a7 100644 --- a/content/docs/permissions/permissions-matrix.mdx +++ b/content/docs/permissions/permissions-matrix.mdx @@ -59,10 +59,11 @@ record sharing enforces writes (an object with an `owner_id` whose OWD is the floor for that row: ownership at the caller's write depth or `modifyAllRecords`, and, for an update, an `edit` share. On an update, a row sitting in a queue the caller belongs to gets the same `allow` under any OWD. A -by-id write takes that replacement, and so does a predicate write unless an -app-authored `using` policy for the write applies to the caller (then it keeps -the floor beside that policy). A write made on another user's behalf keeps the -floor. A `controlled_by_parent` detail's by-id write is +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 replaced. The Layer 0 tenant wall always ANDs on top. See [Sharing & OWD](/docs/permissions/sharing-rules#how-viewallrecords--modifyallrecords-interact-with-the-owd) diff --git a/content/docs/permissions/rls.mdx b/content/docs/permissions/rls.mdx index ec9bfc2149a..c0dedc8621f 100644 --- a/content/docs/permissions/rls.mdx +++ b/content/docs/permissions/rls.mdx @@ -77,9 +77,19 @@ inside the caller's **readable** set, so when **no** write-class policy applies to a caller on an object, the `update` / `delete` scope is derived from that caller's `select` policies — a record they cannot read is one they cannot modify, by id or in bulk. Authoring a write-class policy switches the -derivation off for that class: an authored `update` predicate then decides -the `update` *filter* alone, widening past the platform's owner-scoped write -floor exactly as written. Nothing is derived for `insert` +derivation off for that class: an authored `update` predicate then joins +the `update` *filter* as one more OR term, widening past the platform's +owner-scoped write floor exactly as written. A write policy adds rows; it +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 +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 +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` (there is no pre-existing row to be visible), and a caller holding the read-side superuser bypass (`viewAllRecords` on a private or deployment-level object) is not narrowed, because their readable set is already unbounded. diff --git a/content/docs/permissions/sharing-rules.mdx b/content/docs/permissions/sharing-rules.mdx index 5d01d243c22..8d35a771566 100644 --- a/content/docs/permissions/sharing-rules.mdx +++ b/content/docs/permissions/sharing-rules.mdx @@ -73,9 +73,19 @@ Two things the bits do **not** override, regardless of the OWD: baseline floor for that row: ownership at the caller's write depth or `modifyAllRecords`, and, for an update, an `edit` share. On an update, a row sitting in a queue the caller belongs to gets the same `allow` under - any OWD. A by-id write takes that replacement, and so does a predicate - write unless an app-authored `using` policy for the write applies to the - caller (then it keeps the floor beside that policy). A write made on + any OWD. A 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: a row the floor admits + (one the caller created) stays writable, and the policy still bounds every + other row. The master check of a `controlled_by_parent` detail write + composes its master row the same way, so a master's creator can write its + details beside the master's authored update policy. To hold the creator's + own rows to a limit as well: a `check` on the update policy judges the + stored image of every row, but not the row as it stood before the write; + a `beforeUpdate` lifecycle hook sees that prior row as `ctx.previous`, and + a limit on deleting goes in a `beforeDelete` hook. For a master's details + the limit goes in a hook on the detail object. + A write made on another user's behalf keeps the floor. Under `public_read_write` the sharing service abstains on a delete, so the delete floor stays; on an object with no `owner_id` it abstains on both, diff --git a/packages/plugins/plugin-security/src/delegated-write-never-exceeds-delegator.test.ts b/packages/plugins/plugin-security/src/delegated-write-never-exceeds-delegator.test.ts index 0ca6725ced9..fe050c9da5c 100644 --- a/packages/plugins/plugin-security/src/delegated-write-never-exceeds-delegator.test.ts +++ b/packages/plugins/plugin-security/src/delegated-write-never-exceeds-delegator.test.ts @@ -13,6 +13,14 @@ * - the row an `update` would store; * - a `controlled_by_parent` detail's write, judged through its master. * + * [#35917, ruled A] On an ordinary object the delegator's own composition now + * keeps the floor beside an authored policy, so it narrows nothing the + * floor-standing delegator filter does not. It still narrows on a + * `controlled_by_parent` object, where the delegator's direct write lets the + * floor yield to the master gate: the `d_note_held`, `g_under_mid_held` and + * detail store cells pin that, one per gate (the by-id pre-image, the master + * gate on a middle master, the stored row). + * * Every refusal stands beside the delegator's own request as its control, and * every row-level verdict beside explain's record verdict for the same caller, * under a walled (`isolated`) and a wall-less (`single`) posture. @@ -88,6 +96,8 @@ async function boot(posture: TenancyPosture) { const OBJ = 'qa_bounded_record'; const MASTER = 'qa_bounded_master'; const DETAIL = 'qa_bounded_detail'; + /** A detail of DETAIL: DETAIL is then a `controlled_by_parent` MIDDLE master. */ + const GRAND = 'qa_bounded_grand_detail'; const engine = new ObjectQL(); engine.registerDriver( new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never, @@ -123,6 +133,17 @@ async function boot(posture: TenancyPosture) { master: { name: 'master', type: 'master_detail', required: true, reference: MASTER }, }, }, + { + name: GRAND, + label: 'Grand detail', + sharingModel: 'controlled_by_parent', + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + note: { name: 'note', type: 'text' }, + created_by: { name: 'created_by', type: 'text' }, + master: { name: 'master', type: 'master_detail', required: true, reference: DETAIL }, + }, + }, ], } as never); await engine.syncSchemas(); @@ -145,11 +166,21 @@ async function boot(posture: TenancyPosture) { ...defaultPermissionSets, PermissionSetSchema.parse({ name: 'qa_bounded_writer', - objects: { [OBJ]: org, [MASTER]: org, [DETAIL]: { allowRead: true, allowEdit: true, allowDelete: true } }, + objects: { + [OBJ]: org, [MASTER]: org, + [DETAIL]: { allowRead: true, allowEdit: true, allowDelete: true }, + [GRAND]: { allowRead: true, allowEdit: true, allowDelete: true }, + }, rowLevelSecurity: [ { name: 'qa_bounded_updates', object: OBJ, operation: 'update', using: "name != 'held'" }, { name: 'qa_bounded_deletes', object: OBJ, operation: 'delete', using: "name != 'held'" }, { name: 'qa_bounded_master_updates', object: MASTER, operation: 'update', using: "name != 'held'" }, + // [#24792] The one region where the delegator's own composition still + // narrows under ruling A: a `controlled_by_parent` object, where the + // delegator's direct write carries the master-gate vouch and the + // floor yields to the master, so this policy decides alone, while the + // delegated path's floor-standing filter keeps the floor beside it. + { name: 'qa_bounded_detail_updates', object: DETAIL, operation: 'update', using: "note != 'held'" }, ], }), PermissionSetSchema.parse({ name: 'qa_plain_writer', objects: { [OBJ]: org } }), @@ -167,26 +198,46 @@ async function boot(posture: TenancyPosture) { } const row = (id: string, name: string, owner: string, creator: string) => ({ id, name, note: '', owner_id: owner, created_by: creator, organization_id: ALPHA }); + // [#35917, ruled A] Every `held` row is one the delegator did NOT create. + // The platform's ownership floor (`created_by == current_user.id`) stays an + // OR term beside an authored write policy, so on a row the delegator + // created the floor admits it whatever the authored policy says: the rows + // whose refusal this file pins are created by someone else, and the + // `held_created*` rows pin the creator's admission, by the delegator and + // on its behalf alike. for (const r of [ - row('held_1', 'held', BOUNDED, BOUNDED), - row('held_2', 'held', OTHER, BOUNDED), + row('held_1', 'held', BOUNDED, OTHER), + row('held_2', 'held', OTHER, OTHER), row('free_1', 'free', BOUNDED, BOUNDED), - row('held_del_direct', 'held', BOUNDED, BOUNDED), - row('held_del_agent', 'held', BOUNDED, BOUNDED), + row('held_del_direct', 'held', BOUNDED, OTHER), + row('held_del_agent', 'held', BOUNDED, OTHER), row('free_del_direct', 'free', BOUNDED, BOUNDED), row('free_del_agent', 'free', BOUNDED, BOUNDED), - row('store_direct', 'free', BOUNDED, BOUNDED), - row('store_agent', 'free', BOUNDED, BOUNDED), + row('store_direct', 'free', BOUNDED, OTHER), + row('store_agent', 'free', BOUNDED, OTHER), + row('held_created', 'held', BOUNDED, BOUNDED), + row('held_created_del_direct', 'held', BOUNDED, BOUNDED), + row('held_created_del_agent', 'held', BOUNDED, BOUNDED), row('plain_1', 'x', OTHER, OTHER), row('plain_2', 'x', PLAIN, OTHER), ]) await e.insert(OBJ, r, SYS); - await e.insert(MASTER, row('m_held', 'held', BOUNDED, BOUNDED), SYS); + await e.insert(MASTER, row('m_held', 'held', BOUNDED, OTHER), SYS); await e.insert(MASTER, row('m_free', 'free', BOUNDED, BOUNDED), SYS); - for (const [id, master] of [ - ['d_held', 'm_held'], ['d_free', 'm_free'], ['d_held_del_direct', 'm_held'], ['d_held_del_agent', 'm_held'], + // [#35917, ruled A] A held master the delegator CREATED: the floor stays + // beside the master's authored policy, so the master gate admits its details. + await e.insert(MASTER, row('m_held_created', 'held', BOUNDED, BOUNDED), SYS); + for (const [id, master, note] of [ + ['d_held', 'm_held', ''], ['d_free', 'm_free', ''], ['d_held_del_direct', 'm_held', ''], ['d_held_del_agent', 'm_held', ''], + ['d_under_held_created', 'm_held_created', ''], + ['d_under_held_created_del_direct', 'm_held_created', ''], ['d_under_held_created_del_agent', 'm_held_created', ''], + // [#24792] Details the delegator created that its own detail policy refuses + // (or, for the store rows, would refuse once written), under a master it may edit. + ['d_note_held', 'm_free', 'held'], ['d_store_direct', 'm_free', ''], ['d_store_agent', 'm_free', ''], + ['d_mid_held', 'm_free', 'held'], ] as const) { - await e.insert(DETAIL, { id, note: '', created_by: BOUNDED, master, organization_id: ALPHA }, SYS); + await e.insert(DETAIL, { id, note, created_by: BOUNDED, master, organization_id: ALPHA }, SYS); } + await e.insert(GRAND, { id: 'g_under_mid_held', note: '', created_by: BOUNDED, master: 'd_mid_held', organization_id: ALPHA }, SYS); let security: { explain: (input: unknown, ctx: unknown) => Promise } | undefined; let sharing: SharingService | undefined; @@ -246,7 +297,7 @@ async function boot(posture: TenancyPosture) { accessToken: undefined, } as never)!; }; - const objects = { OBJ, DETAIL } as const; + const objects = { OBJ, DETAIL, GRAND } as const; type Obj = keyof typeof objects; let n = 0; @@ -264,6 +315,11 @@ async function boot(posture: TenancyPosture) { outcomeOf(engine.update(OBJ, { name: 'held' }, { where: { id }, context: { ...(await contextOf(userId, onBehalf)) }, } as never)), + /** A by-id detail update whose stored row carries a note the delegator's own detail policy may not store. */ + storeHeldDetail: async (userId: string, onBehalf: boolean, id: string) => + outcomeOf(engine.update(DETAIL, { note: 'held' }, { + where: { id }, context: { ...(await contextOf(userId, onBehalf)) }, + } as never)), remove: async (userId: string, onBehalf: boolean, object: Obj, id: string) => outcomeOf(engine.delete(objects[object], { where: { id }, context: { ...(await contextOf(userId, onBehalf)) } } as never)), teardown: async () => { @@ -297,7 +353,7 @@ const word = (o: Outcome): string => (o.kind === 'admitted' ? 'admitted' : `refu interface Cell { delegator: string; verb: 'update' | 'delete'; - object: 'OBJ' | 'DETAIL'; + object: 'OBJ' | 'DETAIL' | 'GRAND'; rows: { direct: string; agent: string }; shape: string; direct: Outcome; @@ -333,10 +389,44 @@ const CELLS: Cell[] = [ delegator: BOUNDED, verb: 'delete', object: 'DETAIL', rows: { direct: 'd_held_del_direct', agent: 'd_held_del_agent' }, shape: 'a detail whose master refuses the delegator\'s own detail delete', direct: DENIED, agent: DENIED, }, + // [#35917, ruled A] A held row the delegator CREATED: the ownership floor + // stays an OR term beside the authored policy, so both are admitted. + { + delegator: BOUNDED, verb: 'update', object: 'OBJ', rows: { direct: 'held_created', agent: 'held_created' }, + shape: 'a held row the delegator created (the floor admits it beside the authored policy)', direct: ADMITTED, agent: ADMITTED, + }, + { + delegator: BOUNDED, verb: 'delete', object: 'OBJ', rows: { direct: 'held_created_del_direct', agent: 'held_created_del_agent' }, + shape: 'a held row the delegator created, delete (the floor admits it beside the authored policy)', direct: ADMITTED, agent: ADMITTED, + }, { delegator: BOUNDED, verb: 'update', object: 'DETAIL', rows: { direct: 'd_free', agent: 'd_free' }, shape: 'the control: a detail whose master admits the delegator\'s own detail update', direct: ADMITTED, agent: ADMITTED, }, + // [#35917, ruled A] The master check: a held master the delegator CREATED + // admits its details, for the delegator and on its behalf. + { + delegator: BOUNDED, verb: 'update', object: 'DETAIL', rows: { direct: 'd_under_held_created', agent: 'd_under_held_created' }, + shape: 'a detail under a held master the delegator created (the floor admits the master beside its authored policy)', direct: ADMITTED, agent: ADMITTED, + }, + { + delegator: BOUNDED, verb: 'delete', object: 'DETAIL', rows: { direct: 'd_under_held_created_del_direct', agent: 'd_under_held_created_del_agent' }, + shape: 'a detail under a held master the delegator created, delete', direct: ADMITTED, agent: ADMITTED, + }, + // [#24792] Where the delegator's own composition still narrows: on a + // `controlled_by_parent` object the delegator's direct write lets the floor + // yield to the master gate, so its authored detail policy decides alone, + // while every floor-standing filter on the delegated path admits a row the + // delegator created. Only the delegator's own composition, ANDed beside + // them, refuses on its behalf. + { + delegator: BOUNDED, verb: 'update', object: 'DETAIL', rows: { direct: 'd_note_held', agent: 'd_note_held' }, + shape: 'a detail the delegator created that its own detail policy refuses (the step 2.7 bound)', direct: DENIED, agent: DENIED, + }, + { + delegator: BOUNDED, verb: 'update', object: 'GRAND', rows: { direct: 'g_under_mid_held', agent: 'g_under_mid_held' }, + shape: 'a detail under a middle master the delegator created that its own middle-master policy refuses (the master-gate bound)', direct: DENIED, agent: DENIED, + }, // The bound only narrows: rows the delegator's own write admits and the // delegated write has always refused stay refused. { @@ -374,5 +464,13 @@ describe('an on-behalf-of by-id write never admits a row its delegator\'s own by expect(await rig.storeHeld(BOUNDED, false, 'store_direct'), 'the delegator\'s own write').toStrictEqual(DENIED); expect(await rig.storeHeld(BOUNDED, true, 'store_agent'), 'the write on its behalf').toStrictEqual(DENIED); }, 60_000); + + // [#24792] The post-image bound on a `controlled_by_parent` detail the + // delegator created: its own detail policy refuses the stored note. + it(`\`${posture}\` · update · a detail the delegator created, whose stored row its own detail policy refuses → refused on its behalf as for the delegator`, async () => { + const rig = await rigFor(posture); + expect(await rig.storeHeldDetail(BOUNDED, false, 'd_store_direct'), 'the delegator\'s own write').toStrictEqual(DENIED); + expect(await rig.storeHeldDetail(BOUNDED, true, 'd_store_agent'), 'the write on its behalf').toStrictEqual(DENIED); + }, 60_000); } }); diff --git a/packages/plugins/plugin-security/src/explain-enforce-parity.test.ts b/packages/plugins/plugin-security/src/explain-enforce-parity.test.ts index b2b1684065b..2368357ad45 100644 --- a/packages/plugins/plugin-security/src/explain-enforce-parity.test.ts +++ b/packages/plugins/plugin-security/src/explain-enforce-parity.test.ts @@ -831,7 +831,9 @@ const D_BOUNDED = 'u_d_bounded'; * - `p_beta`: another organization's row, which only the wall-less posture lets through; * - `p_del_*`: the same two shapes again, for the delete rows (a delete that lands removes its row); * - `p_bounded_*`, `p_del_bounded_*`, `m_bounded_*`: rows `D_BOUNDED`'s own authored - * policies refuse (`held`) or admit (`free`), and a detail under each master (#24746). + * policies refuse (`held`, created by someone else) or admit (`free`), and a detail + * under each master (#24746); `p_bounded_held_created`, a `held` row the writer + * created, which the ownership floor admits beside the authored policy (#35917). * * One rig per posture, shared by its rows: an admitted update writes only * `note`, which no policy reads, and every delete row has its own record. @@ -934,13 +936,17 @@ async function bootDelegated(posture: TenancyPosture) { row('p_beta', D_ORG, D_ORG, BETA), row('p_del_theirs_created_by_org', D_OTHER, D_ORG), row('p_del_org_mine_created_by_other', D_ORG, D_OTHER), - { ...row('p_bounded_held', D_BOUNDED, D_BOUNDED), name: 'held' }, + // [#35917, ruled A] A `held` row is one `D_BOUNDED` did NOT create: the + // ownership floor stays an OR term beside an authored write policy, so a + // row the writer created is admitted (`p_bounded_held_created`). + { ...row('p_bounded_held', D_BOUNDED, D_OTHER), name: 'held' }, { ...row('p_bounded_free', D_BOUNDED, D_BOUNDED), name: 'free' }, - { ...row('p_del_bounded_held', D_BOUNDED, D_BOUNDED), name: 'held' }, + { ...row('p_del_bounded_held', D_BOUNDED, D_OTHER), name: 'held' }, + { ...row('p_bounded_held_created', D_BOUNDED, D_BOUNDED), name: 'held' }, ]) await e.insert(PARENT, r, SYS); await e.insert(MASTER, row('m_org', D_ORG, D_ORG), SYS); await e.insert(MASTER, row('m_theirs', D_OTHER, D_OTHER), SYS); - await e.insert(MASTER, { ...row('m_bounded_held', D_BOUNDED, D_BOUNDED), name: 'held' }, SYS); + await e.insert(MASTER, { ...row('m_bounded_held', D_BOUNDED, D_OTHER), name: 'held' }, SYS); await e.insert(MASTER, { ...row('m_bounded_free', D_BOUNDED, D_BOUNDED), name: 'free' }, SYS); await e.insert(DETAIL, { id: 'd_under_org', note: '', created_by: D_ORG, master: 'm_org', organization_id: ALPHA }, SYS); await e.insert(DETAIL, { id: 'd_under_theirs', note: '', created_by: D_ORG, master: 'm_theirs', organization_id: ALPHA }, SYS); @@ -1302,6 +1308,9 @@ function delegatedRows(posture: TenancyPosture, label: string, walled: boolean): [D_BOUNDED, true, 'update', 'PARENT', 'p_bounded_held', 'a row its own authored update policy refuses', REFUSED_DENIED, '#24746'], [D_BOUNDED, false, 'update', 'PARENT', 'p_bounded_held', 'a row its own authored update policy refuses', REFUSED_DENIED, '#24746'], [D_BOUNDED, true, 'update', 'PARENT', 'p_bounded_free', 'a row its own authored update policy admits', 'admitted', '#24746'], + // [#35917, ruled A] The floor stays an OR term beside the authored policy: a held row the writer created is admitted. + [D_BOUNDED, true, 'update', 'PARENT', 'p_bounded_held_created', 'a held row it created, which the ownership floor admits beside its authored update policy', 'admitted', '#35917'], + [D_BOUNDED, false, 'update', 'PARENT', 'p_bounded_held_created', 'a held row it created, which the ownership floor admits beside its authored update policy', 'admitted', '#35917'], [D_BOUNDED, true, 'delete', 'PARENT', 'p_del_bounded_held', 'a row its own authored delete policy refuses', REFUSED_DENIED, '#24746'], [D_BOUNDED, true, 'update', 'DETAIL', 'd_under_bounded_held', 'a detail under a master its own authored update policy refuses', REFUSED_DENIED, '#24746'], [D_BOUNDED, false, 'update', 'DETAIL', 'd_under_bounded_held', 'a detail under a master its own authored update policy refuses', REFUSED_DENIED, '#24746'], 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 5ac9ff0e99d..cd93d39d468 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 @@ -96,6 +96,8 @@ const NARROW = 'usr_narrow'; * on-behalf-of write. */ const ERIN = 'usr_erin'; +/** Holds Modify All under the two wideners; owns nothing, and created only what a case seeds as theirs. */ +const WIDE_MANAGER = 'usr_wide_manager'; const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; const MODIFY_ALL = { ...CRUD, viewAllRecords: true, modifyAllRecords: true }; @@ -111,11 +113,41 @@ const NARROW_SET = PermissionSetSchema.parse({ objects: { [DEAL]: MODIFY_ALL }, rowLevelSecurity: [{ name: 'pwf_open_deals_only', object: DEAL, operation: 'update', using: "stage == 'open'" }], }); -/** An APP-AUTHORED update widener beside the platform floor: any open deal, whoever created it. */ +/** + * APP-AUTHORED wideners beside the platform floor: any open deal, whoever + * created it, may be updated, and deleted. + */ +const OPEN_DEALS_UPDATE = { name: 'pwf_open_deals_widener', object: DEAL, operation: 'update', using: "stage == 'open'" } as const; +const OPEN_DEALS_DELETE = { name: 'pwf_open_deals_delete_widener', object: DEAL, operation: 'delete', using: "stage == 'open'" } as const; const WIDENER_SET = PermissionSetSchema.parse({ name: 'pwf_widener', objects: { [DEAL]: CRUD }, - rowLevelSecurity: [{ name: 'pwf_open_deals_widener', object: DEAL, operation: 'update', using: "stage == 'open'" }], + rowLevelSecurity: [OPEN_DEALS_UPDATE, OPEN_DEALS_DELETE], +}); +/** Modify All, under the same two wideners. */ +const MODIFY_ALL_WIDENER_SET = PermissionSetSchema.parse({ + name: 'pwf_modify_all_widener', + objects: { [DEAL]: MODIFY_ALL }, + rowLevelSecurity: [OPEN_DEALS_UPDATE, OPEN_DEALS_DELETE], +}); +/** + * The update widener, and a restriction the author wrote beside it: an + * updated deal must stay an EMEA deal (a `check`, which bounds every image + * whatever admitted the row). + */ +const WIDENER_EMEA_CHECK_SET = PermissionSetSchema.parse({ + name: 'pwf_widener_emea_check', + objects: { [DEAL]: CRUD }, + rowLevelSecurity: [OPEN_DEALS_UPDATE, { name: 'pwf_widened_stays_in_emea', object: DEAL, operation: 'update', check: "region == 'emea'" }], +}); +/** Wideners on the owner-less memo, which admit no memo this file seeds (every memo is named 'as seeded'). */ +const MEMO_WIDENER_SET = PermissionSetSchema.parse({ + name: 'pwf_memo_widener', + objects: { [MEMO]: CRUD }, + rowLevelSecurity: [ + { name: 'pwf_open_memos_widener', object: MEMO, operation: 'update', using: "name == 'open'" }, + { name: 'pwf_open_memos_delete_widener', object: MEMO, operation: 'delete', using: "name == 'open'" }, + ], }); /** A CHECK-only update policy: an updated deal must be an EMEA deal. It has no `using`, so it narrows no match. */ const EMEA_CHECK_SET = PermissionSetSchema.parse({ @@ -123,7 +155,10 @@ const EMEA_CHECK_SET = PermissionSetSchema.parse({ objects: { [DEAL]: CRUD }, rowLevelSecurity: [{ name: 'pwf_stays_in_emea', object: DEAL, operation: 'update', check: "region == 'emea'" }], }); -const SETS = [MEMBER_DEFAULT, REP_SET, MANAGER_SET, NARROW_SET, WIDENER_SET, EMEA_CHECK_SET]; +const SETS = [ + MEMBER_DEFAULT, REP_SET, MANAGER_SET, NARROW_SET, WIDENER_SET, EMEA_CHECK_SET, + MODIFY_ALL_WIDENER_SET, WIDENER_EMEA_CHECK_SET, MEMO_WIDENER_SET, +]; /** The execution context `resolveAuthzContext` hands the middleware for an organization member holding the sets. */ const memberOf = (userId: string, set: string) => ({ @@ -146,6 +181,7 @@ const MATRIX: Record = { const SHARED_WITH_DAVE: readonly Role[] = ['r2', 'r3']; let engine: ObjectQL; +let securityPlugin: SecurityPlugin; let sharing: SharingService | undefined; let seq = 0; @@ -206,7 +242,7 @@ beforeAll(async () => { ], } as never); await engine.syncSchemas(); - await engine.insert('sys_user', [ALICE, BOB, CAROL, MANAGER, DAVE, NARROW, ERIN].map((id) => ({ + await engine.insert('sys_user', [ALICE, BOB, CAROL, MANAGER, DAVE, NARROW, ERIN, WIDE_MANAGER].map((id) => ({ id, name: id, email: `${id}@pwf.test`, })), SYS); await engine.insert('sys_organization', [{ id: ORG, name: 'PWF', slug: 'pwf' }], SYS); @@ -251,6 +287,7 @@ beforeAll(async () => { }, }; const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + securityPlugin = plugin; await plugin.init(ctx as never); await plugin.start(ctx as never); wireEngineSecuritySource(engine, () => plugin); @@ -512,13 +549,14 @@ describe('[#35802] a predicate write composes the platform ownership floor per r describe('the relief only ever adds rows', () => { it('an owner-creator under an authored widener still writes the closed row she created and owns, and no verdict is asked', async () => { - // The by-id write of r1 is refused: replacing the floor in `floor OR - // widener` leaves the widener alone, and r1 is closed. That narrowing is - // the by-id composition's, reported out of scope; the predicate path - // keeps writing r1, as it did before this change. (By id, the open r3 - // and r4 are written too: an authored row-write policy that admits a - // row answers the sharing gate there, while the predicate path's bulk - // sharing scope stays the owner set. Also not this change's.) + // [#35917] The by-id write of r1 is admitted as well: replacing the + // floor never takes it out of an OR an authored term stands in, so the + // floor still admits r1, which she created, closed or not. (By id, the + // open r3 and r4 are written too: an authored row-write policy that + // admits a row answers the sharing gate there, while the predicate + // path's bulk sharing scope stays the owner set. Not the floor's + // composition, and not this change's; the #35917 matrix below keeps + // such rows closed.) const caller = memberOf(ALICE, WIDENER_SET.name); const overrides: Overrides = { r1: { stage: 'closed' } }; const copy = await seedDeals(overrides); @@ -528,7 +566,7 @@ describe('[#35802] a predicate write composes the platform ownership floor per r expect(await changedRows(DEAL, copy.ids, 'update')).toEqual(['r1', 'r2']); const byIdCopy = await seedDeals(overrides); - expect(await byIdAdmits(DEAL, 'update', byIdCopy.ids, caller), 'the by-id corner, reported out of scope').not.toContain('r1'); + expect(await byIdAdmits(DEAL, 'update', byIdCopy.ids, caller)).toEqual(['r1', 'r2', 'r3', 'r4']); }); }); @@ -666,6 +704,149 @@ describe('[#35802] a predicate write composes the platform ownership floor per r }); }); +describe('[#35917] beside an authored widener, the by-id write keeps the floor as a term of the OR, as the predicate write does', () => { + // The by-id composition (step 2.7) used to take the platform floor OUT of + // Layer 1 on a sharing `allow`. Layer 1 is an OR of permissive policies, so + // beside an authored widener that left the widener as the only term, and a + // row the floor alone admitted (the caller's own closed deal) was refused by + // id, while the predicate write, which keeps the floor beside an authored + // term ({@link predicateWriteFloorRelief}), wrote it. Replacing the floor now + // drops it only where it is the OR's last term; beside an authored term it + // stays, so the replacement adds rows and never takes one away. + // + // The matrix keeps closed every row the caller neither owns nor holds a + // share on: an OPEN such row is admitted by id through the authored-policy + // lift of the sharing refusal, which the predicate path's bulk sharing + // scope does not take (the corner the test above records). Each case names + // its expected set and compares the two paths row for row, as the #35802 + // cases do. + const ALL_CLOSED: Overrides = { + r1: { stage: 'closed' }, r2: { stage: 'closed' }, r3: { stage: 'closed' }, r4: { stage: 'closed' }, + }; + + describe('the owner-creator, ALICE, under the wideners', () => { + for (const verb of ['update', 'delete'] as const) { + it(`by-id ${verb} of her own closed r1 is admitted, and the predicate ${verb} agrees row for row`, async () => { + await expectPredicateMatchesById(verb, memberOf(ALICE, WIDENER_SET.name), ['r1'], ALL_CLOSED); + }); + it(`${verb}: her own closed r1 by the floor, the open r2 she owns by the widener`, async () => { + await expectPredicateMatchesById(verb, memberOf(ALICE, WIDENER_SET.name), ['r1', 'r2'], { + ...ALL_CLOSED, r2: { stage: 'open' }, + }); + }); + } + }); + + describe('the rest of the #35802 matrix under the wideners, every row closed', () => { + for (const verb of ['update', 'delete'] as const) { + it(`BOB (owner, created none), ${verb}: nothing, as before`, async () => { + await expectPredicateMatchesById(verb, memberOf(BOB, WIDENER_SET.name), [], ALL_CLOSED); + }); + it(`CAROL (created r2 and r4, owns none), ${verb}: nothing — the floor admits them, record sharing does not`, async () => { + await expectPredicateMatchesById(verb, memberOf(CAROL, WIDENER_SET.name), [], ALL_CLOSED); + }); + it(`the Modify All holder under the wideners, ${verb}: nothing, unchanged (ADR-0066 ①)`, async () => { + await expectPredicateMatchesById(verb, memberOf(WIDE_MANAGER, MODIFY_ALL_WIDENER_SET.name), [], ALL_CLOSED); + }); + it(`the edit-share target DAVE under the wideners, ${verb}: nothing — the shared rows are closed`, async () => { + await expectPredicateMatchesById(verb, memberOf(DAVE, WIDENER_SET.name), [], ALL_CLOSED); + }); + } + it('the Modify All holder still writes only the open rows the widener admits (r2, r3), unchanged', async () => { + await expectPredicateMatchesById('update', memberOf(WIDE_MANAGER, MODIFY_ALL_WIDENER_SET.name), ['r2', 'r3'], { + r1: { stage: 'closed' }, r4: { stage: 'closed' }, + }); + }); + it('the Modify All holder writes a closed row they created: the floor admits it, by id as by predicate', async () => { + await expectPredicateMatchesById('update', memberOf(WIDE_MANAGER, MODIFY_ALL_WIDENER_SET.name), ['r1'], { + ...ALL_CLOSED, r1: { stage: 'closed', created_by: WIDE_MANAGER }, + }); + }); + it('the edit-share target updates the open row shared with him (r2), and not the closed one (r3)', async () => { + await expectPredicateMatchesById('update', memberOf(DAVE, WIDENER_SET.name), ['r2'], { + ...ALL_CLOSED, r2: { stage: 'open' }, + }); + }); + // The verb boundary beside the floor term: an `edit` share earns `allow` + // on an update, so the floor stays beside the widener and admits the + // closed row the share holder created; on a delete the share earns no + // `allow`, and the sharing gate refuses it (ADR-0111 D3). + it('the edit-share target who created the closed shared r2: the update is admitted by the floor', async () => { + await expectPredicateMatchesById('update', memberOf(DAVE, WIDENER_SET.name), ['r2'], { + ...ALL_CLOSED, r2: { stage: 'closed', created_by: DAVE }, + }); + }); + it('the edit-share target who created the closed shared r2: the delete is still refused', async () => { + await expectPredicateMatchesById('delete', memberOf(DAVE, WIDENER_SET.name), [], { + ...ALL_CLOSED, r2: { stage: 'closed', created_by: DAVE }, + }); + }); + }); + + describe('CONTROLS', () => { + it('a restriction the author wrote still refuses the owner-creator: her closed r1 moved out of EMEA is refused, in EMEA it is written', async () => { + const caller = memberOf(ALICE, WIDENER_EMEA_CHECK_SET.name); + const apac = await seedDeals({ r1: { stage: 'closed', region: 'apac' } }); + const refusal = (await engine + .update(DEAL, { name: 'written' }, { where: { id: apac.ids.r1 }, context: { ...caller } } as never) + .then(() => null, (e: unknown) => e)) as { code?: unknown; statusCode?: unknown; status?: unknown } | null; + expect(refusal, 'the update is refused').not.toBeNull(); + expect(refusal?.code).toBe('PERMISSION_DENIED'); + expect(refusal?.statusCode ?? refusal?.status).toBe(403); + expect(await changedRows(DEAL, apac.ids, 'update', ['r1'])).toEqual([]); + + const emea = await seedDeals({ r1: { stage: 'closed' } }); + expect(await byIdAdmits(DEAL, 'update', emea.ids, caller, ['r1'])).toEqual(['r1']); + }); + + it('the tenant wall still refuses the owner-creator her own closed row in another organization', async () => { + await expectPredicateMatchesById('update', memberOf(ALICE, WIDENER_SET.name), [], { + ...ALL_CLOSED, r1: { stage: 'closed', organization_id: 'org_other' }, + }); + }); + + describe('where record sharing abstains (no owner field), the floor stays beside the wideners', () => { + async function seedMemos(): Promise<{ batch: string; ids: Ids }> { + const batch = `memo_widener_batch_${++seq}`; + const ids = Object.fromEntries(ROLES.map((role) => [role, `${batch}_${role}`])) as Ids; + await engine.insert(MEMO, ROLES.map((role) => ({ + id: ids[role], name: 'as seeded', batch, created_by: MATRIX[role].created_by, organization_id: ORG, + })), SYS); + return { batch, ids }; + } + for (const verb of ['update', 'delete'] as const) { + it(`ALICE, ${verb}: the rows she created (r1, r3); r2 and r4, which she did not, are refused`, async () => { + const caller = memberOf(ALICE, MEMO_WIDENER_SET.name); + const predicateCopy = await seedMemos(); + await predicateWrite(MEMO, verb, predicateCopy.batch, caller); + const byPredicate = await changedRows(MEMO, predicateCopy.ids, verb); + const byIdCopy = await seedMemos(); + const byId = await byIdAdmits(MEMO, verb, byIdCopy.ids, caller); + expect(byPredicate).toEqual(byId); + expect(byId).toEqual(['r1', 'r3']); + }); + } + }); + }); + + it('security/explain answers the verdict the write gets: the owner-creator may update and delete her closed r1', async () => { + const caller = memberOf(ALICE, WIDENER_SET.name); + const { ids } = await seedDeals(ALL_CLOSED); + for (const operation of ['update', 'delete'] as const) { + const decision = (await securityPlugin.explainAccessForCaller( + { object: DEAL, operation, recordId: ids.r1 } as never, + { ...caller } as never, + )) as { record?: { visible?: boolean } }; + expect(decision.record?.visible, `explain ${operation} of r1`).toBe(true); + const other = (await securityPlugin.explainAccessForCaller( + { object: DEAL, operation, recordId: ids.r4 } as never, + { ...caller } as never, + )) as { record?: { visible?: boolean } }; + expect(other.record?.visible, `explain ${operation} of r4`).toBe(false); + } + }); +}); + describe('[#35802] predicateWriteFloorDropIds: the by-id floor decision, asked per row', () => { // A double of the by-id decision that answers like a write authority with an // `edit` share on every row: the floor is replaced for an update, never for diff --git a/packages/plugins/plugin-security/src/security-plugin-authored-row-write.ts b/packages/plugins/plugin-security/src/security-plugin-authored-row-write.ts index 3d588c9429e..9f340531174 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authored-row-write.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authored-row-write.ts @@ -11,7 +11,9 @@ * A MOVE, not a redesign. The function below is the body of the method of the * same name as it stood, re-indented one level and otherwise unedited: the * same abstentions in the same order, the same provenance pre-check, the same - * layered predicate and the same id-only probe read. The scope constant and + * layered predicate and the same id-only probe read (since #35917 the floor + * leaves that predicate through the sets, not the floor-drop knob; the reason + * is at the call). The scope constant and * its docblock moved with it unedited, still unexported, and the probe still * spreads it at its one call site. * @@ -45,6 +47,7 @@ * Nothing re-exports this module, so the published surface does not move. */ import type { AuthoredRowWriteOperation, AuthoredRowWriteVerdict } from '@objectstack/spec/contracts'; +import type { PermissionSet } from '@objectstack/spec/security'; import type { SecurityPlugin } from './security-plugin.js'; import { isPlatformOwnershipFloorPolicy } from './platform-ownership-policies.js'; import { policyDeclaresClause } from './rls-compiler.js'; @@ -95,6 +98,17 @@ export interface AuthoredRowWriteHost { */ const AUTHORED_ROW_WRITE_PROBE_CONTEXT = { isSystem: true, positions: [], permissions: [] } as const; +/** + * [#35917] A permission set with the platform's own ownership floor policies + * taken out (provenance, {@link isPlatformOwnershipFloorPolicy}); the set + * itself when it carries none. Every other member is the set's own. + */ +function withoutPlatformOwnershipFloor(set: PermissionSet): PermissionSet { + const policies = set.rowLevelSecurity; + if (!policies?.some(isPlatformOwnershipFloorPolicy)) return set; + return { ...set, rowLevelSecurity: policies.filter((p) => !isPlatformOwnershipFloorPolicy(p)) }; +} + /** The body of `SecurityPlugin#checkAuthoredRowWrite`; the method's docblock there is its contract. */ export async function checkAuthoredRowWrite( this: Pick, @@ -147,12 +161,22 @@ export async function checkAuthoredRowWrite( ).filter((p) => !isPlatformOwnershipFloorPolicy(p) && policyDeclaresClause(p, 'using')); if (authored.length === 0) return 'abstain'; + // [#35917] The floor is taken out of the SETS, by provenance, rather than + // by `dropPlatformOwnershipFloor`. That knob is the write authority's + // `allow` replacing the floor, and since #35917 a replacement keeps the + // floor's term beside an authored one (the OR an authored policy stands + // in is never shortened by it), which is exactly the case this probe + // exists for: through the knob, the floor would answer here as if it + // were an authored admission (#5493 / #7281). With the floor gone from + // the sets the collection the compiler sees is the one the knob used to + // leave: the floor's alternates are materialized only beside a floor + // ({@link withOwnershipFloorAlternates}), and the authored `using` + // pre-checked above keeps the derive-from-select branch off. const { layer0, layer1 } = await this.computeLayeredRlsFilter( - permissionSets, + permissionSets.map(withoutPlatformOwnershipFloor), object, operation, context, - { dropPlatformOwnershipFloor: true }, ); // See the doc above: a null Layer 1 means no authored predicate is // gating this write, which is an abstention and not an admission. 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 869cbad82cd..a056eada89f 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -1394,6 +1394,13 @@ export function registerAuthzMiddleware( // The platform's own floor defers to the platform's own ownership // authority; app-authored policies keep refusing exactly as before. // + // [#35917] Replacing is not deleting. Where an authored write policy + // stands beside the floor in Layer 1's OR, the floor stays a term of it, + // so a row the floor alone admits (the caller's own closed row beside an + // authored widener) is still admitted; the floor is dropped only where it + // is the OR's last term (`computeLayeredRlsFilter`), which is the + // predicate write's composition too (`predicateWriteFloorRelief`). + // // The verb boundary is INHERITED, not restated (ADR-0111 D3): the same // `rlsOperation` mapping picks `checkEdit` for the update class and // `checkDelete` for the delete class, so an `edit` share widens update and @@ -3008,10 +3015,10 @@ export function idsOfReadableScope(scope: Record): (string | nu * replaced: `computeLayeredRlsFilter` with `dropPlatformOwnershipFloor`. * If that is not `null`, an authored write-class policy remains, and * `null` is answered with no verdict asked. Policies compose by `$or` only - * (`rls-compiler.ts`), so `floored` is that policy set OR the floor: a - * row `floored` refuses fails every authored policy too, and the by-id - * write of it, held to those policies alone, is refused as well. Replacing - * the floor can add no row there, so nothing is asked. + * (`rls-compiler.ts`), and a replacement keeps the floor's term in an OR + * an authored term stands in ([#35917]), so the by-id write of every + * matched row is held to `floored` itself: replacing the floor adds no + * row there and removes none, so nothing is asked. * 3. The rows `floored` already admits are read once, under the caller's * context, and set aside: they are matched today whatever any verdict says, * so nothing is asked about them and the check they are held to does not 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 6c4dc13257f..4fde7736d89 100644 --- a/packages/plugins/plugin-security/src/security-plugin-rls-filter.ts +++ b/packages/plugins/plugin-security/src/security-plugin-rls-filter.ts @@ -387,9 +387,54 @@ export async function computeLayeredRlsFilter( // app-authored policy — even one spelling the identical predicate under a // different name — reaches the compiler untouched (ADR-0049, and the // ADR-0105 F1 lesson that a token match swallows authored policies). - const allRlsPolicies = opts?.dropPlatformOwnershipFloor + // + // [#35917] REPLACING the floor is not DELETING its term. Layer 1 is an OR + // of permissive policies, so taking the floor out of an OR an authored + // term stands in did not hand the row to the write authority — it handed + // it to the authored term alone, and a row the floor alone admitted (the + // caller's own closed deal, beside an authored `stage == 'open'` widener) + // was refused by id, while the predicate write, which keeps the floor + // beside an authored term (`predicateWriteFloorRelief`), wrote it. So the + // floor comes out only where it is the OR's LAST term: there the + // remaining Layer 1 is null and the authority's `allow` admits the row. + // Where an authored term would remain, the floor stays one term of the + // OR: the replacement adds no row there and removes none, and the + // authored term still bounds every row the floor does not admit — which + // is ADR-0066 ① on this posture: Modify All, the `allow` it earns + // included, does not lift an authored write policy. + // + // "An authored term would remain" is asked exactly as the compile below + // answers it, so the two cannot disagree: a policy that survives pass 1 + // carrying a `using`, or one pass 1 drops for a missing column (a deny + // contribution). That is the test the predicate write asks too — whether + // the Layer 1 composed with the floor dropped is null. + // Pass 1 of the field-existence net (its reasons are on the compile + // below), as a function so the floor decision above asks it too. + const fieldExistencePassOne = ( + policies: RowLevelSecurityPolicy[], + ): { compilable: RowLevelSecurityPolicy[]; dropped: number } => { + if (!objectFields) return { compilable: policies, dropped: 0 }; + let dropped = 0; + const compilable = policies.filter((p) => { + const targetField = this.extractTargetField(p.using); + if (!targetField) return true; + if (objectFields.has(targetField)) return true; + if (tenancyDisabled && targetField === 'organization_id') { + return false; + } + dropped++; + return false; + }); + return { compilable, dropped }; + }; + const withoutFloor = opts?.dropPlatformOwnershipFloor ? collected.filter((p) => !isPlatformOwnershipFloorPolicy(p)) : collected; + let allRlsPolicies = withoutFloor; + if (withoutFloor.length < collected.length) { + const rest = fieldExistencePassOne(withoutFloor); + if (rest.dropped > 0 || rest.compilable.some((p) => !!p.using)) allRlsPolicies = collected; + } if (allRlsPolicies.length > 0) { // Field-existence safety, in TWO passes that answer two different // questions. Schema-lookup failure runs neither: a schema that cannot @@ -417,19 +462,7 @@ export async function computeLayeredRlsFilter( // the compiler judges the compiled tree, where a negation is a `$not` // node and has no spelling left to hide behind. The matcher's // include-direction ruling is untouched — it never sees the phantom. - let dropped = 0; - const compilable = objectFields - ? allRlsPolicies.filter((p) => { - const targetField = this.extractTargetField(p.using); - if (!targetField) return true; - if (objectFields.has(targetField)) return true; - if (tenancyDisabled && targetField === 'organization_id') { - return false; - } - dropped++; - return false; - }) - : allRlsPolicies; + const { compilable, dropped } = fieldExistencePassOne(allRlsPolicies); // [#25234 ruling A] The declared membership keys these policies read, // staged before they compile. The resolver's half ran above. await this.stageRlsMembership(context, compilable, object); @@ -634,19 +667,28 @@ export async function computeWriteCheckFilter( // when the pre-image gate kept it: the same three replacements drop it here // (an `allow` from the declared write authority, a `public_read_write` OWD, // a covering master gate), and nothing else does. - const floorReplaced = - !!preImageOpts?.dropPlatformOwnershipFloor || - this.platformFloorYieldsToObjectWriteModel(meta, object, operation, preImageOpts); - const withCheck = writeCheckPolicies( - this.collectRLSPolicies( - permissionSets, - object, - operation, - (context?.positions ?? []) as string[], - context, - ), - { keepOwnershipFloor: !floorReplaced }, + // + // [#35917] And an `allow` replaces the floor here as it does there: the + // floor leaves a defaulted check only where no authored `using` stands + // beside it, the case where the pre-image dropped it as the OR's last term. + // Beside an authored term it stays a term of the check, so a write the + // pre-image admitted by the floor alone is not refused on its new image + // (the floor's `using` defaulted as the check). The test is read off the + // collection, ahead of the field-existence net, so where the two could part + // — an authored policy pass 1 skips as not applicable — the check keeps the + // floor: a term more in an OR, never one fewer. + const applicable = this.collectRLSPolicies( + permissionSets, + object, + operation, + (context?.positions ?? []) as string[], + context, ); + const floorReplaced = + this.platformFloorYieldsToObjectWriteModel(meta, object, operation, preImageOpts) || + (!!preImageOpts?.dropPlatformOwnershipFloor && + !applicable.some((p) => !isPlatformOwnershipFloorPolicy(p) && policyDeclaresClause(p, 'using'))); + const withCheck = writeCheckPolicies(applicable, { keepOwnershipFloor: !floorReplaced }); if (withCheck.length === 0) return null; // [ADR-0105 D11 / commit 1d73d45c1] Stage the app-resolved membership sets on THIS // context before the `check` clause compiles — the same staging the read diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index 0546f3d342a..bc7f66c01e5 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -632,7 +632,7 @@ interface RlsFilterOptions { /** * Drop the PLATFORM's own row-level write ownership floor * (`owner_only_writes` / `owner_only_deletes` — see - * `platform-ownership-policies.ts`) from Layer 1. + * `platform-ownership-policies.ts`) from Layer 1 where it is the OR's last term; beside an authored `using` term it stays one (#35917). * * Set only when `ISharingService.checkEdit` / `checkDelete` answered `allow` * for the row this filter is about to be enforced against — a positive basis @@ -1249,15 +1249,23 @@ export { describeHighPrivilegeBits } from '@objectstack/spec/security'; * with `clause: 'check'` reads `using` for a policy that declares no * `check`), OR-combined. This is the half that changed: those writes were * unchecked, and a row outside every applicable `using` is now refused. - * 3. **The platform's ownership floor takes part in case 2 exactly when the - * pre-image gate kept it** (`owner_only_writes`, recognised by provenance - * through {@link isPlatformOwnershipFloorPolicy}; `keepOwnershipFloor`). - * The by-id write gate lets a declared write authority replace the floor - * (an `allow` from the sharing service, a `public_read_write` OWD, a - * covering controlled-by-parent master gate). Each of those writes targets - * a row whose `created_by` is someone else, so the floor's `using` on the - * post-image would refuse them again one step later; there it stays out. - * Where the pre-image kept it, it stays in: an app-authored USING-only + * 3. **The platform's ownership floor takes part in case 2 unless a declared + * write authority replaced it** (`owner_only_writes`, recognised by + * provenance through {@link isPlatformOwnershipFloorPolicy}; + * `keepOwnershipFloor`). A `public_read_write` OWD or a covering + * controlled-by-parent master gate replaces it outright. An `allow` from + * the sharing service replaces it only where no applicable app-authored + * policy carries a `using` (#35917): beside one, the floor stays an OR term + * in the check as it does at the pre-image. A replaced floor stays out, + * because each of those writes may target a row whose `created_by` is + * someone else, and the floor's `using` on the post-image would refuse it + * again one step later. The check asks the applicable policies before the + * pre-image's field-existence pass 1, so the two can part where that pass + * sets an authored policy aside without counting it (an `organization_id` + * policy on a tenancy-disabled object): there the pre-image drops the floor + * and the check keeps it, and a non-creator the row gate admits is refused + * by the check, as on main. + * Where the floor stays in: an app-authored USING-only * update policy is a WIDENER OR-ed with the floor at the pre-image * (`stage == 'prospecting'`: anyone may edit an open deal), and leaving * the floor out of the check would turn that widener into a restriction on @@ -2966,9 +2974,10 @@ export class SecurityPlugin implements Plugin { * two, and it is private to this package by design. * * **No second RLS evaluator.** The verdict is read off the SAME - * {@link computeLayeredRlsFilter} the middleware enforces with, driven by the - * SAME `dropPlatformOwnershipFloor` knob #6684 landed for the by-id write - * pre-image gate — the floor is removed by provenance, everything else + * {@link computeLayeredRlsFilter} the middleware enforces with. The floor is + * removed by provenance from the permission SETS before the call (since + * #35917 the `dropPlatformOwnershipFloor` knob keeps the floor beside an + * authored term, which is the case this probe exists for); everything else * compiles exactly as it would on the enforcement path. Two consequences * worth naming, because both are load-bearing: *