diff --git a/.changeset/38517-public-read-write-owner-delete.md b/.changeset/38517-public-read-write-owner-delete.md new file mode 100644 index 00000000000..ac68fb3f70f --- /dev/null +++ b/.changeset/38517-public-read-write-owner-delete.md @@ -0,0 +1,25 @@ +--- +'@objectstack/plugin-sharing': minor +'@objectstack/plugin-security': minor +'@objectstack/spec': patch +--- + +fix(sharing)!: on an object that declares `sharingModel: 'public_read_write'` and has an owner field, deleting a record follows the record's owner, as it already does on a private object + +Clause-②: yes (narrowing) +Metadata-protocol: semantic +Skills-docs: follow-up #39217 + +Everyone who may edit such a record still may; only delete changes. A record of such an object can now be deleted by its owner, by a manager above the owner in the role hierarchy, and by a user holding Modify All on the object. A record with no owner can be deleted only by a Modify All holder. An app-authored row-level delete policy that admits a caller still lets that caller delete, as on any owned object. Who created the record no longer decides. The same rule answers a delete by id, a delete by filter (each matching row is judged on its own), a cascade delete of child records, and the permanent delete of a record from the recycle bin; restoring or purging a recycle-bin entry is unchanged. `security/explain` reports the same answer for delete. + +**BREAKING** for three groups of users on such an object: + +1. A member who created a record that someone else now owns can no longer delete it (they still can edit it). Reassigning the record back, or asking its owner, a manager above the owner, or a Modify All holder, is how it gets deleted. +2. A user whose organization membership role is not one of the built-in roles (a custom role string, so the platform's "only the creator deletes" floor never applied to them), and a session with no organization at all, could until now delete any record of such an object; they now delete only the records they own, like every member. +3. On a deployment with a single organization, or one whose organizations are walled with unbounded admin rights suppressed, organization owners and admins hold the administrator set without Modify All. They could until now delete any record of such an object; they now delete only the records they own or manage, exactly as on a private object. A deployment that wants its admins to clean up colleagues' records grants Modify All on the object, or the full-access admin set. The first platform administrator is unaffected. + +External users follow the same rule as members. Where an external user's permission grant speaks for the object, the external owner of a record can now delete it and an external creator who no longer owns it cannot; where it does not, nothing changes (the object already behaves as private for them). + +Objects that declare `public_read_write` without an owner field (a federated object whose owner field is only the platform's anchor, with no column behind it, among them), platform objects that declare no sharing model, and detail objects controlled by their parent keep today's behaviour. No metadata key, value or type changes and no stored metadata is refused. + + diff --git a/content/docs/kernel/runtime-services/sharing-service.mdx b/content/docs/kernel/runtime-services/sharing-service.mdx index 83aca765b3f..07fc71498cb 100644 --- a/content/docs/kernel/runtime-services/sharing-service.mdx +++ b/content/docs/kernel/runtime-services/sharing-service.mdx @@ -41,7 +41,10 @@ Each write gate has a primary **tri-state** form, `checkEdit` (update) and - `abstain` — record sharing does not enforce on this row at all: a `public` object, an object with no owner field, a bypass-listed platform internal, or an object with no resolvable schema. The decision belongs to whatever else guards - the row. `checkDelete` abstains on exactly the rows `checkEdit` abstains on. + the row. `checkDelete` abstains on the rows `checkEdit` abstains on except + one class: on an object that declares `public_read_write` and has an owner + field, delete follows the record's owner, so `checkDelete` answers `allow` + or `deny` there as it does under `public_read`. - `deny` — refused: a sharing-enforced row where the caller has none of the bases above, a principal-less context, or a lookup that failed. A failure is always `deny`, never `abstain`. diff --git a/content/docs/permissions/permissions-matrix.mdx b/content/docs/permissions/permissions-matrix.mdx index 53d045935d9..d9c78cd80dc 100644 --- a/content/docs/permissions/permissions-matrix.mdx +++ b/content/docs/permissions/permissions-matrix.mdx @@ -53,9 +53,10 @@ policies are short-circuited only on objects whose posture permits it — object, authored RLS still applies, and so does `member_default`'s creator-only write floor (`created_by == current_user.id`) for `org_member` holders. Under `public_read_write` the update floor does not apply (that OWD opens row updates) -and the delete floor does; on an object with no `owner_id` both apply. Where -record sharing enforces writes (an object with an `owner_id` whose OWD is -`private` or `public_read`), the sharing service's `allow` for a row replaces +and a delete follows the record's owner, as below; on an object with no +`owner_id` both floors apply. Where record sharing enforces writes (an object +with an `owner_id` whose OWD is `private` or `public_read`, or, for a delete +only, a declared `public_read_write`), the sharing service's `allow` for a row replaces 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 diff --git a/content/docs/permissions/sharing-rules.mdx b/content/docs/permissions/sharing-rules.mdx index 31be14a4c87..3b7708dab84 100644 --- a/content/docs/permissions/sharing-rules.mdx +++ b/content/docs/permissions/sharing-rules.mdx @@ -59,8 +59,9 @@ Two things the bits do **not** override, regardless of the OWD: platform baseline `member_default` ships creator-only `update`/`delete` policies (`created_by == current_user.id`, applicability domain `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. + (that OWD opens row updates) and the delete policy does, which record + sharing replaces row by row on an object with an owner column; under every + other OWD both apply, and record sharing can replace them row by row, as below. 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 @@ -74,7 +75,8 @@ Two things the bits do **not** override, regardless of the OWD: `modifyAllRecords` does *not* short-circuit those policies (`plugin-security/src/security-plugin.ts` `computeLayeredRlsFilter`). Where record sharing enforces writes (an `owner_id` and a `private` or - `public_read` OWD), the sharing service's `allow` for a row replaces the + `public_read` OWD, or, for a delete only, an `owner_id` and a declared + `public_read_write` OWD), the sharing service's `allow` for a row replaces the 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 @@ -91,12 +93,22 @@ Two things the bits do **not** override, regardless of the OWD: 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, - so both floors stay. An app-authored policy is never replaced. + another user's behalf keeps the floor. Under a declared + `public_read_write` OWD a delete follows the record's owner: the sharing + service answers it as it does under `public_read` (ownership at the caller's + write depth, or `modifyAllRecords`), so a row's creator who does not own it + may not delete it, and a row with no owner only a `modifyAllRecords` holder + may delete; an update stays + open to everyone who may edit. On an object with no `owner_id` it abstains + on both, so both floors stay. An app-authored policy is never replaced. Org admins (`org_admin` / `org_owner`) are outside the `org_member` - applicability domain and are not narrowed by the baseline. + applicability domain and are not narrowed by the baseline. Record sharing + still answers them: where their admin set carries no `modifyAllRecords` + (`organization_admin_no_bypass`, granted on a deployment with no wall + between organizations), they delete only the rows they own or manage of an + owned `public_read_write` object, exactly as on a `private` one. Grant + `modifyAllRecords` on the object, or `admin_full_access`, to let them + clean up colleagues' rows. - **The Layer 0 tenant wall** (ADR-0095 D1) — always ANDs on top. None of this is an enterprise/open-core split: both bits are enforced by the diff --git a/packages/plugins/plugin-security/src/cascade-delete-security-parity.test.ts b/packages/plugins/plugin-security/src/cascade-delete-security-parity.test.ts index 15a20789a03..ab5e09f4471 100644 --- a/packages/plugins/plugin-security/src/cascade-delete-security-parity.test.ts +++ b/packages/plugins/plugin-security/src/cascade-delete-security-parity.test.ts @@ -56,7 +56,10 @@ const ORG = 'org_ccp'; const ME = 'usr_ccp_me'; const OTHER = 'usr_ccp_other'; -/** The parent: open to every member, so its own delete is never the refusal. */ +/** + * The parent, owned by the caller so its own delete is never the refusal: delete on an owned + * `public_read_write` object follows the record's owner (ruling of record 7288570890). + */ const ORDER = 'qa_ccp_order'; /** A record-shared child, owner-scoped (`private`), reached by two cascading lookups. */ const LINE = 'qa_ccp_line'; @@ -243,7 +246,7 @@ describe('cascade delete: security parity between id-shaped and predicate-shaped * the caller at `edit` (read and update, never delete: ADR-0111 D3). */ const seedOrder = async (prefix: string, refused?: 'unreadable' | 'edit-shared') => { - await ql.insert(ORDER, { id: prefix, name: prefix }, SYS); + await ql.insert(ORDER, { id: prefix, name: prefix, owner_id: ME }, SYS); await ql.insert(LINE, [ { id: `${prefix}_a`, owner_id: ME, order: prefix }, { id: `${prefix}_b`, owner_id: refused ? OTHER : ME, order: prefix }, @@ -309,7 +312,7 @@ describe('cascade delete: security parity between id-shaped and predicate-shaped it('a cascade the caller may complete leaves none of the children its probe found', async () => { const prefix = 'f_all'; - await ql.insert(ORDER, { id: prefix }, SYS); + await ql.insert(ORDER, { id: prefix, owner_id: ME }, SYS); const lines = Array.from({ length: 12 }, (_, i) => ({ id: `${prefix}_l${String(i).padStart(2, '0')}`, owner_id: ME, order: prefix })); await ql.insert(LINE, lines, SYS); await ql.insert(NOTE, [{ id: `${prefix}_n1`, order: prefix }, { id: `${prefix}_n2`, order: prefix }], SYS); @@ -326,7 +329,7 @@ describe('cascade delete: security parity between id-shaped and predicate-shaped describe('3. never more rows: the cascade deletes the children it probed and nothing else', () => { it('rows of the child objects under another order, or under none, stay', async () => { const prefix = 'm1'; - await ql.insert(ORDER, [{ id: prefix }, { id: `${prefix}_other` }], SYS); + await ql.insert(ORDER, [{ id: prefix, owner_id: ME }, { id: `${prefix}_other`, owner_id: ME }], SYS); await ql.insert(LINE, [ { id: `${prefix}_mine`, owner_id: ME, order: prefix }, { id: `${prefix}_other_line`, owner_id: ME, order: `${prefix}_other` }, @@ -345,7 +348,7 @@ describe('cascade delete: security parity between id-shaped and predicate-shaped it('a child written after the probe (by a sibling\'s beforeDelete) is not deleted by this cascade', async () => { const prefix = 'm2'; - await ql.insert(ORDER, { id: prefix }, SYS); + await ql.insert(ORDER, { id: prefix, owner_id: ME }, SYS); await ql.insert(LINE, [{ id: `${prefix}_a`, owner_id: ME, order: prefix }, { id: `${prefix}_b`, owner_id: ME, order: prefix }], SYS); spawnFrom = `${prefix}_a`; @@ -363,7 +366,7 @@ describe('cascade delete: security parity between id-shaped and predicate-shaped describe('4. each child\'s delete-side work runs once per child', () => { it('one audit delete row, every share revoked, and each object-less hook phase once, per child, a child two relations reach included', async () => { const prefix = 'h1'; - await ql.insert(ORDER, { id: prefix }, SYS); + await ql.insert(ORDER, { id: prefix, owner_id: ME }, SYS); await ql.insert(LINE, [ { id: `${prefix}_by_order`, owner_id: ME, order: prefix }, { id: `${prefix}_by_both`, owner_id: ME, order: prefix, alt_order: prefix }, diff --git a/packages/plugins/plugin-security/src/explain-engine.ts b/packages/plugins/plugin-security/src/explain-engine.ts index c34021fc713..b8339161579 100644 --- a/packages/plugins/plugin-security/src/explain-engine.ts +++ b/packages/plugins/plugin-security/src/explain-engine.ts @@ -48,7 +48,7 @@ import type { ControlledByParentWriteUnresolvedReason, } from '@objectstack/spec/contracts'; import type { FieldMaskingRule } from '@objectstack/spec/data'; -import { controlledByParentMasterOf, controlledByParentWriteRequiresMasterRead } from '@objectstack/spec/data'; +import { controlledByParentMasterOf, controlledByParentWriteRequiresMasterRead, isOwnerAnchorUnprovable } from '@objectstack/spec/data'; import type { PermissionSet } from '@objectstack/spec/security'; import type { AuthzPosture, @@ -572,6 +572,14 @@ export interface ExplainEngineDeps { * explanation for a `delete` must consult this rather than the update gate. */ canDeleteRecord?: (object: string, recordId: string, context: any) => Promise; + /** + * [Ruling of record 7288570890, option C] Whether the sharing service is + * installed, record id or not. Delete on an object that declares + * `public_read_write` with an owner column follows the record's owner only + * where it is, so the `owd_baseline` layer reads that delete as + * owner-scoped only then (`describeOwdFor`). Absent reads as not installed. + */ + sharingServiceWired?: boolean; /** * [#5493 / ADR-0105 D3] The by-id write gate's DEFERRAL: whether an * APP-AUTHORED row-level policy admits the row for the refusing gate's verb @@ -1336,6 +1344,30 @@ function describeOwd(schema: any): { model: string; declared: boolean; effect: ' return { model: `${String(m)} (unknown → private, fail-closed)`, declared: true, effect: 'private' }; } +/** + * [Ruling of record 7288570890, option C] The OWD reading for one RLS + * operation: {@link describeOwd}, except that a DELETE on an object that + * DECLARES `public_read_write` and carries the owner column meets the + * owner-writes baseline — plugin-sharing answers that delete by ownership, + * write depth and Modify All, exactly as on `public_read` (its + * `ownershipDecidesDeleteOnOpenWrites`). Edit on the same object stays open. + * + * Only where that answer exists: `sharingDecidesDelete` is whether the + * sharing service is installed. Without plugin-sharing no door reads + * the owner for that delete, so the report keeps the declared baseline and + * cannot claim a refusal the request would not meet. + */ +function describeOwdFor(schema: any, rlsOp: string, sharingDecidesDelete: boolean): ReturnType { + const owd = describeOwd(schema); + if (!sharingDecidesDelete) return owd; + const declared = schema?.sharingModel ?? schema?.security?.sharingModel; + // A federated object whose `owner_id` is only the injected anchor carries no + // owner column: plugin-sharing leaves its delete to the floor, so does this. + const owned = Boolean(schema?.fields && 'owner_id' in schema.fields) && !isOwnerAnchorUnprovable(schema); + if (rlsOp !== 'delete' || declared !== 'public_read_write' || !owned) return owd; + return { model: 'public_read_write (delete follows the record owner)', declared: true, effect: 'read' }; +} + /** [ADR-0055] What each refusing leg of the master-detail write check means, for the report's prose. */ const MASTER_DENIAL_LEG_DETAIL: Record = { object_permission: 'the principal holds no object-level update grant on a master', @@ -3505,7 +3537,7 @@ async function explainObjectPass(deps: ExplainEngineDeps, input: ExplainInput, a // stamps for plugin-sharing, so the report and the query cannot disagree. const owdOpClass: 'read' | 'write' = dataOp === 'find' ? 'read' : 'write'; const owd = owdForPrincipal( - describeOwd(schema), + describeOwdFor(schema, rlsOp, deps.sharingServiceWired === true), context, isExternalAudienceContext(context) && deps.externalGrantSpeaks?.(sets, object, owdOpClass, dataOp, context) === true, ); diff --git a/packages/plugins/plugin-security/src/objects/default-permission-sets.ts b/packages/plugins/plugin-security/src/objects/default-permission-sets.ts index 7431d31c908..4c867b00e78 100644 --- a/packages/plugins/plugin-security/src/objects/default-permission-sets.ts +++ b/packages/plugins/plugin-security/src/objects/default-permission-sets.ts @@ -997,9 +997,13 @@ const baseDefaultPermissionSets: PermissionSet[] = [ // (any member could edit/delete any record — #1985). These policies are // ENFORCED on writes via the security middleware's pre-image check (a // by-id update/delete never builds an RLS `where`, so the predicate is - // verified against the target row before the mutation). Objects that - // model transferable ownership with a dedicated owner field should - // override these with a per-object policy. + // verified against the target row before the mutation). On an object + // with an owner field record sharing answers the write by ownership and + // its `allow` replaces these floors (#5492), on every owned OWD — a + // `public_read_write` object's delete included (ruling of record + // 7288570890); they still decide alone on an object with no owner field + // or an undeclared model on a platform table, and for a write made on + // another user's behalf. // [ADR-0090 P2] Applicability domain made EXPLICIT: with the baseline // resolving additively for every authenticated principal (the // `everyone` anchor — no more fallback cliff), these members-only diff --git a/packages/plugins/plugin-security/src/platform-ownership-policies.ts b/packages/plugins/plugin-security/src/platform-ownership-policies.ts index e5a4d24c10b..188e9f1b9e1 100644 --- a/packages/plugins/plugin-security/src/platform-ownership-policies.ts +++ b/packages/plugins/plugin-security/src/platform-ownership-policies.ts @@ -267,15 +267,22 @@ export function owdDeclaresOpenRowWrites(schema: unknown): boolean { /** * The write class {@link owdDeclaresOpenRowWrites} opens — `update` and nothing - * else, so `owner_only_deletes` survives on a `public_read_write` object. + * else, so `owner_only_deletes` survives on a `public_read_write` object. Who + * deletes there is not this file's answer: on such an object with an owner + * column the record's owner, someone above the owner by depth and a Modify All + * holder delete, because record sharing answers that delete by ownership and + * its `allow` replaces the surviving floor (ruling of record 7288570890); the + * floor still decides it on such an object with no owner column, and for a + * write made on another user's behalf. * * This is the OWD vocabulary's own boundary, not a conservative guess: * `public_read_write` is defined as "everyone can see and edit", and the legacy * `full` alias that ALSO covered transfer/delete was refused a mechanical * conversion precisely because it is "wider than `public_read_write`" - * (`spec/conversions/registry.ts`, ADR-0090 D4). An object that wants - * cross-creator deletes declares it with an app-authored policy or a share, - * both of which reach the compiler untouched. + * (`spec/conversions/registry.ts`, ADR-0090 D4). An object that wants deletes + * wider than ownership declares them with an app-authored policy, which + * reaches the compiler untouched (a share widens rows, never the delete verb, + * ADR-0111 D3). */ export function owdOpenWritesCoversOperation(operation: string): boolean { return operation === 'update'; diff --git a/packages/plugins/plugin-security/src/public-read-write-owner-delete.test.ts b/packages/plugins/plugin-security/src/public-read-write-owner-delete.test.ts new file mode 100644 index 00000000000..c0c1dc91c6d --- /dev/null +++ b/packages/plugins/plugin-security/src/public-read-write-owner-delete.test.ts @@ -0,0 +1,460 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Ruling of record 7288570890, option C (「删除统一跟着负责人走」): on an + * object that DECLARES `sharingModel: 'public_read_write'` and carries an + * owner column, DELETE is answered by the authority that answers it on + * `private` and `public_read` — the record's owner, someone above the owner + * by write depth, a Modify All holder. The platform's `created_by` floor + * (`owner_only_deletes`) stops deciding it there. + * + * Before the ruling the sharing service ABSTAINED on every delete of such an + * object, so the creator floor was its only row-level delete gate: the owner + * of a row it had not typed in (assigned, imported, handed over, written by + * the system) was refused, while the row's former creator kept the delete. + * + * Every case here is read off ONE real stack — an `ObjectKernel` with + * `ObjectQLPlugin` over better-sqlite3, the real `SecurityPlugin` (the real + * `member_default` seed, whose `owner_only_deletes` is the floor in question) + * and the real `SharingServicePlugin` — and the callers hold the `org_member` + * position, the floor's applicability domain, so the floor is in play for + * every one of them (the `[integrity]` case proves it). + * + * `qa_prwd_deal` and `qa_prwd_secret` are byte-identical but for their + * `sharingModel`: whatever separates their answers is the OWD and nothing + * else. After the ruling they answer every delete alike. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import type { ISecurityService } from '@objectstack/spec/contracts'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; + +const ORG = 'org_prwd'; +/** Owns rows it did not create. */ +const OWNER = 'usr_prwd_owner'; +/** Created rows it no longer owns. */ +const CREATOR = 'usr_prwd_creator'; +/** Neither owns nor created anything here. */ +const STRANGER = 'usr_prwd_stranger'; +/** Above {@link OWNER} by write depth (`own_and_reports`). */ +const MANAGER = 'usr_prwd_manager'; +/** Holds Modify All on the probed objects. */ +const MODIFY_ALL = 'usr_prwd_modify_all'; +/** An external principal (`org_external`). */ +const EXTERNAL = 'usr_prwd_external'; +/** An organization admin on a wall-less posture: `organization_admin_no_bypass`, no Modify All. */ +const ORG_ADMIN = 'usr_prwd_org_admin'; +const USERS = [OWNER, CREATOR, STRANGER, MANAGER, MODIFY_ALL, EXTERNAL, ORG_ADMIN]; + +/** `public_read_write`, owner column: the object the ruling governs. */ +const DEAL = 'qa_prwd_deal'; +/** `private`, otherwise identical: the authority the ruling hands delete to. */ +const SECRET = 'qa_prwd_secret'; +/** `public_read_write` with NO owner column: unchanged, the creator floor stays its only delete gate. */ +const MEMO = 'qa_prwd_memo'; +/** `public_read_write`, owner column, a cascade child of {@link SECRET}: the cascade leg of the ruling. */ +const LINE = 'qa_prwd_line'; + +const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } as const; +const objectsWith = (extra: Record = {}) => ({ + [DEAL]: { ...CRUD, ...extra }, + [SECRET]: { ...CRUD, ...extra }, + [MEMO]: { ...CRUD, ...extra }, + [LINE]: { ...CRUD, ...extra }, +}); +/** Ordinary CRUD: every refusal below is row-level, never the object bit. */ +const REP = PermissionSetSchema.parse({ name: 'qa_prwd_rep', objects: objectsWith() }); +/** + * The same, at depth `own_and_reports` — read depth too, so the `private` + * control's row is visible to the manager it is deleted by. + */ +const LEAD = PermissionSetSchema.parse({ + name: 'qa_prwd_lead', + objects: objectsWith({ readScope: 'own_and_reports', writeScope: 'own_and_reports' }), +}); +/** Ordinary CRUD plus the recycle bin's removal bit on the deal: the permanent delete's object gate. */ +const BIN = PermissionSetSchema.parse({ + name: 'qa_prwd_bin', + objects: { ...objectsWith(), [DEAL]: { ...CRUD, manageRecycleBin: true } }, +}); +/** Modify All Data on the probed objects. */ +const ADMIN = PermissionSetSchema.parse({ name: 'qa_prwd_admin', objects: objectsWith({ viewAllRecords: true, modifyAllRecords: true }) }); +/** + * An external's grant whose RLS SPEAKS for the deal (a `select` predicate, + * which speaks for the write class too), so the deal's own OWD stands for it + * instead of the owner_only floor every external meets otherwise (ruling of + * record 6355206139). Every probed row is `open`, so the predicate admits it. + */ +const PORTAL = PermissionSetSchema.parse({ + name: 'qa_prwd_portal', + objects: objectsWith(), + rowLevelSecurity: [{ name: 'qa_prwd_portal_open_deals', object: DEAL, operation: 'select', using: "stage == 'open'" }], +}); + +/** + * The refusal a caller meets on a row it may not delete: 403 where it reads + * the row (the `public_read_write` deal), 404 where it cannot (the `private` + * control hides another owner's row from a member, as it always has). + */ +const REFUSED = (object: string) => ({ kind: 'refused', status: object === SECRET ? 404 : 403 }); + +const SYSTEM = { isSystem: true, tenantId: ORG } as const; +const SYS = { context: SYSTEM } as never; +const member = (userId: string, set: string) => ({ userId, tenantId: ORG, positions: ['org_member'], permissions: [set] }); +/** [Ruling of record 7363759845] A member whose membership role is a custom string: the creator floor never binds it. */ +const customRole = (userId: string, set: string) => ({ userId, tenantId: ORG, positions: ['qa_custom_role'], permissions: [set] }); +/** [ADR-0105 D4] An org admin on a wall-less posture holds the no-bypass admin set, never `org_member`. */ +const orgAdmin = (userId: string) => ({ userId, tenantId: ORG, positions: ['org_admin'], permissions: ['organization_admin_no_bypass'] }); +const external = (userId: string, set: string) => ({ + userId, tenantId: ORG, positions: ['org_external'], audience: 'external', permissions: [set], +}); + +type Outcome = { kind: 'landed' } | { kind: 'refused'; code?: string; status?: number }; +const outcomeOf = (p: Promise): Promise => + p.then( + () => ({ kind: 'landed' as const }), + (e: { code?: unknown; status?: unknown; statusCode?: unknown } | null) => { + const status = e?.statusCode ?? e?.status; + return { + kind: 'refused' as const, + code: e?.code == null ? undefined : String(e.code), + status: status == null ? undefined : Number(status), + }; + }, + ); + +function sqliteDriverPlugin(): Plugin { + return { + name: 'test.driver.sqlite', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + ); + }, + }; +} + +const fields = () => ({ + name: { type: 'text', label: 'Name' }, + stage: { type: 'text', label: 'Stage' }, + owner_id: { type: 'lookup', reference: 'sys_user', label: 'Owner' }, +}); + +function fixturePlugin(): Plugin { + return { + name: 'test.prwd.fixture', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + ctx.getService<{ register(m: unknown): unknown }>('manifest').register({ + id: 'test.public-read-write-owner-delete', + namespace: 'qa_prwd', + version: '1.0.0', + type: 'plugin', + name: 'public_read_write owner delete', + objects: [ + SysUser, SysMember, SysOrganization, + { name: DEAL, label: 'Deal', sharingModel: 'public_read_write', fields: fields() }, + { name: SECRET, label: 'Secret', sharingModel: 'private', fields: fields() }, + { + name: LINE, + label: 'Line', + sharingModel: 'public_read_write', + fields: { ...fields(), account: { type: 'lookup', reference: SECRET, deleteBehavior: 'cascade', label: 'Account' } }, + }, + { + name: MEMO, + label: 'Memo', + sharingModel: 'public_read_write', + ownership: 'none', + fields: { name: { type: 'text', label: 'Name' }, stage: { type: 'text', label: 'Stage' } }, + }, + ], + }); + // [ADR-0057] The hierarchy resolver: the manager's `own_and_reports` + // reaches the owner. Nobody else reports to anyone. + ctx.registerService('hierarchy-scope-resolver', { + async resolveOwnerIds(scope: { userId: string }, depth: string) { + if (scope.userId === MANAGER && depth === 'own_and_reports') return [MANAGER, OWNER]; + return [scope.userId]; + }, + }); + }, + }; +} + +describe('[ruling 7288570890 C] delete on an owned public_read_write object follows the record\'s owner', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let security: Required>; + let seq = 0; + + beforeAll(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as never); + await kernel.use(sqliteDriverPlugin()); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(fixturePlugin()); + await kernel.use(new SecurityPlugin({ + defaultPermissionSets: [...defaultPermissionSets, REP, LEAD, ADMIN, PORTAL, BIN], + fallbackPermissionSet: 'member_default', + })); + await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false })); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + security = kernel.getService>>('security'); + + await ql.insert('sys_organization', { id: ORG, name: 'Acme', slug: 'acme' }, SYS); + for (const userId of USERS) { + await ql.insert('sys_user', { id: userId, name: userId, email: `${userId}@acme.test`, email_verified: true }, SYS); + await ql.insert('sys_member', { + user_id: userId, organization_id: ORG, role: userId === EXTERNAL ? 'external' : userId === ORG_ADMIN ? 'admin' : 'member', + }, SYS); + } + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + /** One fresh row: `owner_id` and `created_by` set apart, as assignment, Change Owner and imports leave them. */ + const seed = async (object: string, owner: string | null, creator: string | null, stage = 'open') => { + const id = `prwd_${++seq}`; + await ql.insert(object, { + id, name: id, stage, + ...(object === MEMO ? {} : { owner_id: owner }), + created_by: creator, + }, SYS); + return id; + }; + const exists = async (object: string, id: string) => + (await ql.findOne(object, { where: { id }, context: SYSTEM } as never)) != null; + const deleteById = (object: string, id: string, context: unknown) => + outcomeOf(ql.delete(object, { where: { id }, context } as never)); + /** `security/explain`'s record-grained delete verdict for `context`'s own user. */ + const explainDelete = async (object: string, id: string, context: unknown) => + (await security.explain({ object, operation: 'delete', recordId: id }, context as never))?.record?.visible; + + it('[integrity] the rows carry the owner and creator they were seeded with, and the floor binds the callers', async () => { + const id = await seed(DEAL, OWNER, CREATOR); + const row = await ql.findOne(DEAL, { where: { id }, context: SYSTEM } as never) as Record; + expect(row?.owner_id, 'owner').toBe(OWNER); + expect(row?.created_by, 'creator — the column the floor keys on').toBe(CREATOR); + // The floor is in play: on the owner-less object, where record sharing + // never answers, a member who did not create the row is refused and the + // creator is not. Without the `org_member` position both would land. + const memo = await seed(MEMO, null, CREATOR); + expect(await deleteById(MEMO, memo, member(STRANGER, REP.name))).toMatchObject({ kind: 'refused', status: 403 }); + expect(await exists(MEMO, memo)).toBe(true); + expect(await deleteById(MEMO, memo, member(CREATOR, REP.name))).toEqual({ kind: 'landed' }); + }); + + describe('by id: the owner, the manager above the owner and a Modify All holder delete', () => { + for (const [what, context] of [ + ['the owner (not the creator)', member(OWNER, REP.name)], + ['the manager above the owner (own_and_reports)', member(MANAGER, LEAD.name)], + ['a Modify All holder', member(MODIFY_ALL, ADMIN.name)], + ] as const) { + for (const object of [DEAL, SECRET]) { + it(`${object}: ${what} deletes the row, and security/explain says so first`, async () => { + const id = await seed(object, OWNER, CREATOR); + expect(await explainDelete(object, id, context), 'explain agrees with the door').toBe(true); + expect(await deleteById(object, id, context)).toEqual({ kind: 'landed' }); + expect(await exists(object, id), 'the row is gone').toBe(false); + }); + } + } + }); + + describe('by id: a creator who no longer owns the row, and a stranger, are refused', () => { + for (const [what, context] of [ + ['the creator who no longer owns it (the narrowing)', member(CREATOR, REP.name)], + ['a member who neither owns nor created it', member(STRANGER, REP.name)], + ['a manager above someone else', member(MANAGER, LEAD.name)], + ] as const) { + for (const object of [DEAL, SECRET]) { + it(`${object}: ${what} is refused 403, the row stays, and security/explain says so first`, async () => { + const id = await seed(object, what.startsWith('a manager') ? STRANGER : OWNER, CREATOR); + expect(await explainDelete(object, id, context), 'explain agrees with the door').toBe(false); + expect(await deleteById(object, id, context)).toMatchObject(REFUSED(object)); + expect(await exists(object, id), 'the row stays').toBe(true); + }); + } + } + }); + + describe('a row with no owner is deleted only by a Modify All holder', () => { + for (const object of [DEAL, SECRET]) { + it(`${object}: its creator and a stranger are refused, the Modify All holder deletes it`, async () => { + const id = await seed(object, null, CREATOR); + for (const context of [member(CREATOR, REP.name), member(STRANGER, REP.name)]) { + expect(await explainDelete(object, id, context)).toBe(false); + expect(await deleteById(object, id, context)).toMatchObject(REFUSED(object)); + } + expect(await exists(object, id)).toBe(true); + const admin = member(MODIFY_ALL, ADMIN.name); + expect(await explainDelete(object, id, admin)).toBe(true); + expect(await deleteById(object, id, admin)).toEqual({ kind: 'landed' }); + }); + } + }); + + it('edit on the same object is unchanged: everyone with edit edits every row', async () => { + const id = await seed(DEAL, OWNER, CREATOR); + for (const userId of [OWNER, CREATOR, STRANGER]) { + const out = await outcomeOf(ql.update(DEAL, { name: `edited by ${userId}` }, { where: { id }, context: member(userId, REP.name) } as never)); + expect(out, `${userId} edits`).toEqual({ kind: 'landed' }); + } + }); + + it('security/explain reads the deal\'s baseline per verb: delete is owner-scoped, update stays org-wide', async () => { + const layer = async (operation: string, object: string) => + ((await security.explain({ object, operation: operation as never }, member(STRANGER, REP.name) as never))?.layers ?? []) + .find((l: { layer: string }) => l.layer === 'owd_baseline')?.verdict; + expect(await layer('delete', DEAL), 'delete meets the owner-writes baseline').toBe('narrows'); + expect(await layer('update', DEAL), 'update stays open').toBe('neutral'); + expect(await layer('delete', MEMO), 'no owner column: unchanged').toBe('neutral'); + }); + + it('an object with no owner column keeps the creator floor', async () => { + const id = await seed(MEMO, null, CREATOR); + expect(await deleteById(MEMO, id, member(OWNER, REP.name))).toMatchObject({ kind: 'refused', status: 403 }); + expect(await exists(MEMO, id)).toBe(true); + expect(await deleteById(MEMO, id, member(CREATOR, REP.name))).toEqual({ kind: 'landed' }); + }); + + describe('a predicate delete matches exactly the rows the by-id delete admits', () => { + for (const object of [DEAL, SECRET]) { + it(`${object}: the owner's predicate delete removes its rows and leaves the creator's and a stranger's`, async () => { + const owned = await seed(object, OWNER, CREATOR, 'bulk'); + const created = await seed(object, STRANGER, OWNER, 'bulk'); + const other = await seed(object, STRANGER, STRANGER, 'bulk'); + const out = await outcomeOf(ql.delete(object, { + where: { id: { $in: [owned, created, other] } }, multi: true, context: member(OWNER, REP.name), + } as never)); + expect(out).toEqual({ kind: 'landed' }); + expect(await exists(object, owned), 'the row it owns is gone').toBe(false); + expect(await exists(object, created), 'the row it created but does not own stays').toBe(true); + expect(await exists(object, other), 'a stranger\'s row stays').toBe(true); + }); + + it(`${object}: a Modify All holder's predicate delete removes every matched row`, async () => { + const a = await seed(object, OWNER, CREATOR, 'bulk'); + const b = await seed(object, null, CREATOR, 'bulk'); + const out = await outcomeOf(ql.delete(object, { + where: { id: { $in: [a, b] } }, multi: true, context: member(MODIFY_ALL, ADMIN.name), + } as never)); + expect(out).toEqual({ kind: 'landed' }); + expect(await exists(object, a)).toBe(false); + expect(await exists(object, b)).toBe(false); + }); + } + }); + + describe('principals the creator floor never binds follow the owner too (ruling of record 7363759845)', () => { + for (const object of [DEAL, SECRET]) { + it(`${object}: a custom-role member deletes the row it owns and is refused another user's`, async () => { + const own = await seed(object, STRANGER, OWNER); + expect(await deleteById(object, own, customRole(STRANGER, REP.name))).toEqual({ kind: 'landed' }); + const others = await seed(object, OWNER, STRANGER); + expect(await explainDelete(object, others, customRole(STRANGER, REP.name)), 'explain agrees').toBe(false); + expect(await deleteById(object, others, customRole(STRANGER, REP.name))).toMatchObject(REFUSED(object)); + expect(await exists(object, others)).toBe(true); + }); + } + + it('control: on the object with no owner column the custom-role member is still unbound and deletes any row', async () => { + const memo = await seed(MEMO, null, CREATOR); + expect(await deleteById(MEMO, memo, customRole(STRANGER, REP.name))).toEqual({ kind: 'landed' }); + }); + }); + + describe('an org admin on a wall-less posture follows the owner, as on private', () => { + for (const object of [DEAL, SECRET]) { + it(`${object}: the no-bypass org admin deletes its own row and is refused a colleague's, and explain agrees`, async () => { + const own = await seed(object, ORG_ADMIN, CREATOR); + expect(await explainDelete(object, own, orgAdmin(ORG_ADMIN))).toBe(true); + expect(await deleteById(object, own, orgAdmin(ORG_ADMIN))).toEqual({ kind: 'landed' }); + const colleagues = await seed(object, OWNER, ORG_ADMIN); + expect(await explainDelete(object, colleagues, orgAdmin(ORG_ADMIN))).toBe(false); + expect(await deleteById(object, colleagues, orgAdmin(ORG_ADMIN))).toMatchObject(REFUSED(object)); + expect(await exists(object, colleagues)).toBe(true); + }); + } + }); + + describe('a cascade into an owned public_read_write child follows the child\'s owner', () => { + const seedLine = async (account: string, owner: string, creator: string) => { + const id = `prwd_${++seq}`; + await ql.insert(LINE, { id, name: id, stage: 'open', owner_id: owner, created_by: creator, account }, SYS); + return id; + }; + + it('the parent\'s owner deleting it is refused whole when a child is another user\'s, even one it created', async () => { + const account = await seed(SECRET, OWNER, OWNER); + const line = await seedLine(account, STRANGER, OWNER); + const out = await deleteById(SECRET, account, member(OWNER, REP.name)); + expect(out.kind, JSON.stringify(out)).toBe('refused'); + expect(await exists(SECRET, account), 'the parent stays').toBe(true); + expect(await exists(LINE, line), 'the child stays').toBe(true); + }); + + it('control: with every child its own, the cascade removes parent and children', async () => { + const account = await seed(SECRET, OWNER, OWNER); + const line = await seedLine(account, OWNER, CREATOR); + expect(await deleteById(SECRET, account, member(OWNER, REP.name))).toEqual({ kind: 'landed' }); + expect(await exists(SECRET, account)).toBe(false); + expect(await exists(LINE, line)).toBe(false); + }); + }); + + describe('the permanent delete (the recycle bin\'s by-id purge) follows the owner', () => { + const purge = (id: string, context: unknown) => + outcomeOf(ql.delete(DEAL, { where: { id }, permanent: true, context } as never)); + + it('the owner with the bin\'s removal bit purges its row; the creator who no longer owns it is refused', async () => { + const id = await seed(DEAL, OWNER, CREATOR); + expect(await purge(id, member(CREATOR, BIN.name))).toMatchObject({ kind: 'refused', status: 403 }); + expect(await exists(DEAL, id)).toBe(true); + expect(await purge(id, member(OWNER, BIN.name))).toEqual({ kind: 'landed' }); + expect(await exists(DEAL, id)).toBe(false); + }); + }); + + describe('externals follow the same rule (ruling of record 6355206139)', () => { + it('with no grant speaking for the deal, the owner_only floor stands: the external owner deletes, its former creator does not', async () => { + const owned = await seed(DEAL, EXTERNAL, CREATOR); + expect(await deleteById(DEAL, owned, external(EXTERNAL, REP.name))).toEqual({ kind: 'landed' }); + const created = await seed(DEAL, OWNER, EXTERNAL); + // Unchanged by the ruling: the floor already hides a row it does not own. + expect(await deleteById(DEAL, created, external(EXTERNAL, REP.name))).toMatchObject({ kind: 'refused', status: 404 }); + expect(await exists(DEAL, created)).toBe(true); + }); + + it('with a grant speaking for the deal, the external meets the members\' rule: the owner deletes, the former creator does not', async () => { + const owned = await seed(DEAL, EXTERNAL, CREATOR); + expect(await deleteById(DEAL, owned, external(EXTERNAL, PORTAL.name))).toEqual({ kind: 'landed' }); + const created = await seed(DEAL, OWNER, EXTERNAL); + expect(await deleteById(DEAL, created, external(EXTERNAL, PORTAL.name))).toMatchObject({ kind: 'refused', status: 403 }); + expect(await exists(DEAL, created)).toBe(true); + }); + + it('the external owner of a row outside its grant\'s predicate is refused, and explain agrees', async () => { + const closed = await seed(DEAL, EXTERNAL, CREATOR, 'closed'); + expect(await explainDelete(DEAL, closed, external(EXTERNAL, PORTAL.name))).toBe(false); + const out = await deleteById(DEAL, closed, external(EXTERNAL, PORTAL.name)); + expect(out.kind, JSON.stringify(out)).toBe('refused'); + expect(await exists(DEAL, closed)).toBe(true); + }); + }); +}); 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 3054d45be77..b8da8d6bb6d 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -1502,7 +1502,9 @@ export function registerAuthzMiddleware( // allow → the declared authority REPLACES the floor (it has a positive // basis: ownership at DEPTH, an `edit` share, or the bypass). // abstain → record sharing does not enforce on this row at all (public - // object, no owner field, platform internal). The floor is the + // object, no owner field, platform internal; for delete an + // owned `public_read_write` object is not public, ruling of + // record 7288570890). The floor is the // ONLY row-level write gate such objects have, so it STAYS — // #5492's E2 experiment measured what collapsing this into // "permitted" costs: a member's cross-creator UPDATE on an diff --git a/packages/plugins/plugin-security/src/security-plugin-explain-access.ts b/packages/plugins/plugin-security/src/security-plugin-explain-access.ts index d95bb64c29e..5ef0ee824a7 100644 --- a/packages/plugins/plugin-security/src/security-plugin-explain-access.ts +++ b/packages/plugins/plugin-security/src/security-plugin-explain-access.ts @@ -419,6 +419,11 @@ export async function explainAccessForCaller( const { sharing, ownershipQueues } = recordServices(rid); return { ql: this.ql, + // [Ruling of record 7288570890, option C] Whether plugin-sharing answers + // delete at all: the owd_baseline layer reads an owned public_read_write + // object's delete as owner-scoped only where it does, with or without a + // record id. + sharingServiceWired: this.resolveKernelService?.('sharing') != null, resolveSets: (c: any) => this.resolvePermissionSetsForContext(c), evaluator: this.permissionEvaluator, getObjectSecurityMeta: (o: string) => this.getObjectSecurityMeta(o), 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 61c351c1da0..4d6728c41d2 100644 --- a/packages/plugins/plugin-security/src/security-plugin-rls-filter.ts +++ b/packages/plugins/plugin-security/src/security-plugin-rls-filter.ts @@ -260,7 +260,13 @@ export async function computeLayeredRlsFilter( // the compiler and still refuses (ADR-0049); // - only `update` (`owdOpenWritesCoversOperation`): `owner_only_deletes` // stays, because `public_read_write` is "see and edit" and the alias - // that also meant delete was removed for being wider than it. + // that also meant delete was removed for being wider than it. It stays + // as the gate the ownership authority REPLACES, not as the decider: on + // such an object with an owner column `ISharingService` answers delete + // by ownership (ruling of record 7288570890), so its `allow` replaces + // the floor at the by-id gate exactly as on `private`, and its `deny` + // refuses. Only an object with no owner column keeps the floor as its + // one row-level delete gate. // Layer 0 (the tenant wall) is untouched — a `public_read_write` object is // org-wide open, never cross-tenant open. // diff --git a/packages/plugins/plugin-sharing/src/federated-phantom-owner-scoping.test.ts b/packages/plugins/plugin-sharing/src/federated-phantom-owner-scoping.test.ts index e411a1158b0..8eb91bfaf8c 100644 --- a/packages/plugins/plugin-sharing/src/federated-phantom-owner-scoping.test.ts +++ b/packages/plugins/plugin-sharing/src/federated-phantom-owner-scoping.test.ts @@ -943,3 +943,49 @@ describe('[#27662] a mapped owner column the driver did not serve is diagnosed, expect(warn).not.toHaveBeenCalled(); }); }); + +/** + * [Ruling of record 7288570890, C] Delete on an object that DECLARES + * `public_read_write` and carries an owner column follows the record's owner. + * The grandfathered showcase shape declares that model over a phantom owner + * anchor: no column, so no row of it has a provable owner. It is outside the + * ruling and keeps today's answer — record sharing abstains on its delete and + * the platform floor decides — instead of refusing every delete below Modify + * All. The local control with a real owner column takes the ruled answer. + */ +describe('[ruling 7288570890] delete on a public_read_write object over a phantom owner anchor keeps the floor', () => { + const FEDERATED_ROW = { id: 'c1', name: 'Aurora Labs', email: 'ap@aurora.example', region: 'NA' }; + const LOCAL_OPEN = { name: 'local_open_deal', sharingModel: 'public_read_write', fields: { owner_id: { ...OWNER_FIELD_DEF }, ...REMOTE_COLUMNS } }; + let svc: SharingService; + const ctx = { userId: MEMBER, __writeScope: 'own' } as never; + + beforeEach(() => { + svc = new SharingService({ + engine: makeEngine( + { + showcase_ext_customer: GRANDFATHERED_SHOWCASE_SHAPE, + local_open_deal: LOCAL_OPEN, + sys_record_share: { name: 'sys_record_share' }, + }, + { + showcase_ext_customer: [FEDERATED_ROW], + local_open_deal: [{ id: 'd1', owner_id: 'usr_someone_else', name: 'Not mine' }], + }, + ), + }); + }); + + it('the phantom-anchor object: checkDelete abstains and the delete write filter is open', async () => { + expect(await svc.checkDelete('showcase_ext_customer', 'c1', ctx)).toBe('abstain'); + expect(await svc.checkDeleteMany!('showcase_ext_customer', ['c1'], ctx)).toEqual(['abstain']); + expect(await svc.canDelete('showcase_ext_customer', 'c1', ctx)).toBe(true); + expect(await svc.buildWriteFilter('showcase_ext_customer', ctx, 'delete')).toBeNull(); + }); + + it('ANTI-VACUITY: the same model over a real owner column follows the owner', async () => { + expect(await svc.checkDelete('local_open_deal', 'd1', ctx)).toBe('deny'); + expect(await svc.buildWriteFilter('local_open_deal', ctx, 'delete')).not.toBeNull(); + // Edit on it stays open, as the ruling keeps it. + expect(await svc.checkEdit('local_open_deal', 'd1', ctx)).toBe('abstain'); + }); +}); diff --git a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts index 6cbc4385321..98aa68af5de 100644 --- a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts +++ b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts @@ -33,7 +33,10 @@ const ORG = 'org_opid'; const ME = 'usr_opid_me'; const OTHER = 'usr_opid_other'; -/** The parent of a cascade: open to every member, so its own delete is never the refusal. */ +/** + * The parent of a cascade, owned by the caller so its own delete is never the refusal: delete on an + * owned `public_read_write` object follows the record's owner (ruling of record 7288570890). + */ const ORDER = 'qa_opid_order'; /** Owner-scoped (`private` OWD with an `owner_id`): record sharing enforces on it. */ const LINE = 'qa_opid_line'; @@ -329,7 +332,7 @@ describe('sharing write gate: a write the engine runs as a predicate meets the b describe('a cascade delete gives the answer the by-id delete of the refused child gives', () => { it('a child the caller reads and may edit but not delete: the same refusal envelope, and nothing is deleted', async () => { - await ql.insert(ORDER, { id: 'c1', name: 'c1' }, SYS); + await ql.insert(ORDER, { id: 'c1', name: 'c1', owner_id: ME }, SYS); const { mine, theirs } = await seedLines('c1', 'c1'); await shareToMe(theirs, 'edit'); // The child is on the caller's read door, so the refusal is the delete gate's. @@ -345,7 +348,7 @@ describe('sharing write gate: a write the engine runs as a predicate meets the b }); it('a cascade over children the caller owns deletes the parent and every child', async () => { - await ql.insert(ORDER, { id: 'c2', name: 'c2' }, SYS); + await ql.insert(ORDER, { id: 'c2', name: 'c2', owner_id: ME }, SYS); await ql.insert(LINE, [ { id: 'c2_a', owner_id: ME, order: 'c2' }, { id: 'c2_b', owner_id: ME, order: 'c2' }, diff --git a/packages/plugins/plugin-sharing/src/sharing-service.test.ts b/packages/plugins/plugin-sharing/src/sharing-service.test.ts index 2b3f086b426..c10909fd192 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.test.ts @@ -573,13 +573,21 @@ describe('[ADR-0111 D3] SharingService.canDelete — the verb boundary', () => { ]; }); - it('system context, public objects, and owner-less objects all allow delete (matches canEdit)', async () => { + it('system context and owner-less objects allow delete (matches canEdit)', async () => { expect(await svc.canDelete('account', 'a1', { isSystem: true })).toBe(true); - expect(await svc.canDelete('task', 'anything', { userId: 'carol' })).toBe(true); engine._tables.note = [{ id: 'n1', body: 'x' }]; expect(await svc.canDelete('note', 'n1', { userId: 'carol' })).toBe(true); }); + it('[ruling of record 7288570890] an owned public_read_write object: everyone edits, the owner deletes', async () => { + engine._tables.task = [{ id: 't1', name: 'Board', owner_id: 'alice' }]; + expect(await svc.canEdit('task', 't1', { userId: 'carol' }), 'the OWD opens edit').toBe(true); + expect(await svc.canDelete('task', 't1', { userId: 'carol' }), 'but not delete').toBe(false); + expect(await svc.canDelete('task', 't1', { userId: 'alice' }), 'the owner deletes').toBe(true); + expect(await svc.checkDelete('task', 't1', { userId: 'carol' })).toBe('deny'); + expect(await svc.checkEdit('task', 't1', { userId: 'carol' })).toBe('abstain'); + }); + it('the record owner may delete', async () => { expect(await svc.canDelete('account', 'a1', { userId: 'alice' })).toBe(true); }); @@ -1939,8 +1947,12 @@ describe('[#6428] SharingService.checkEdit / checkDelete — allow / abstain / d it('abstain — a public object, and an object this engine has no schema for', async () => { expect(await svc.checkEdit('whiteboard', 'w1', { userId: 'bob' })).toBe('abstain'); - expect(await svc.checkDelete('whiteboard', 'w1', { userId: 'bob' })).toBe('abstain'); expect(await svc.checkEdit('ghost', 'g1', { userId: 'bob' })).toBe('abstain'); + expect(await svc.checkDelete('ghost', 'g1', { userId: 'bob' })).toBe('abstain'); + }); + + it('[ruling of record 7288570890] DELETE on an owned public_read_write object does not abstain: ownership answers it', async () => { + expect(await svc.checkDelete('whiteboard', 'w1', { userId: 'bob' })).toBe('deny'); }); it('the two bypass reasons split: a system context ALLOWS, a bypass-listed object ABSTAINS', async () => { @@ -2077,7 +2089,10 @@ describe('[#6428] the boolean projection does not drift (compatibility clause)', { what: 'edit-share holder', object: 'account', id: 'a1', ctx: { userId: 'carol' }, edit: true, del: false }, { what: 'no principal', object: 'account', id: 'a1', ctx: {}, edit: false, del: false }, { what: 'system context', object: 'account', id: 'a1', ctx: { isSystem: true }, edit: true, del: true }, - { what: 'public object', object: 'whiteboard', id: 'w1', ctx: { userId: 'bob' }, edit: true, del: true }, + // [Ruling of record 7288570890] An owned `public_read_write` object opens + // edit, and its delete follows the owner: the one cell that moved. + { what: 'public object, not the owner', object: 'whiteboard', id: 'w1', ctx: { userId: 'bob' }, edit: true, del: false }, + { what: 'public object, the owner', object: 'whiteboard', id: 'w1', ctx: { userId: 'alice' }, edit: true, del: true }, { what: 'no owner column', object: 'note', id: 'n1', ctx: { userId: 'bob' }, edit: true, del: true }, { what: 'unknown object', object: 'ghost', id: 'g1', ctx: { userId: 'bob' }, edit: true, del: true }, { what: 'bypass-listed object', object: 'sys_user', id: 'u1', ctx: { userId: 'bob' }, edit: true, del: true }, @@ -2687,7 +2702,8 @@ describe('[#35934] checkEditMany / checkDeleteMany answer, per id, the verdict c // Open OWD: abstains on every row but the one sitting in the caller's queue. expect(letters(await svc.checkEditMany(V_OPEN, idsOf(V_OPEN), member))).toBe('- - - - - a - - - -'); expect(await svc.checkEditMany(V_OPEN, idsOf(V_OPEN, ['own', 'queued_mine']), member)).toEqual(['abstain', 'allow']); - expect(await svc.checkDeleteMany(V_OPEN, idsOf(V_OPEN, ['queued_mine']), member)).toEqual(['abstain']); + // [Ruling of record 7288570890] Delete on it follows the owner; the queue basis never reaches delete. + expect(await svc.checkDeleteMany(V_OPEN, idsOf(V_OPEN, ['own', 'queued_mine']), member)).toEqual(['allow', 'deny']); // No owner field, no schema, a bypass-listed table: abstain throughout. expect(new Set(await svc.checkEditMany(V_MEMO, idsOf(V_MEMO), member))).toEqual(new Set(['abstain'])); expect(new Set(await svc.checkEditMany(V_UNKNOWN, idsOf(V_UNKNOWN), member))).toEqual(new Set(['abstain'])); diff --git a/packages/plugins/plugin-sharing/src/sharing-service.ts b/packages/plugins/plugin-sharing/src/sharing-service.ts index ac8faa475f0..c7623967af1 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.ts @@ -269,7 +269,10 @@ const QUEUE_FIELD = 'queue'; * three behaviours this service enforces: * - `private` → owner-only read + write * - `public_read` → everyone reads, owner writes - * - `public_read_write` → public (no record-level filter) + * - `public_read_write` → public (no record-level filter); a DELETE + * on such an object with an owner column is + * still answered by ownership + * ({@link ownershipDecidesDeleteOnOpenWrites}) * - `controlled_by_parent` → public here (scoped separately by the * security plugin's master-detail path, ADR-0055) * @@ -327,6 +330,53 @@ function owdForPrincipal( return owdForAudience(model, context, object, opClass); } +/** + * [Ruling of record 7288570890, option C: 「删除统一跟着负责人走」] Does the + * record's OWNERSHIP answer DELETE on this object although its declared model + * opens writes? True for an object that DECLARES `sharingModel: + * 'public_read_write'` and carries the owner column — and for nothing else. + * + * `public_read_write` is "everyone sees and edits": it opens the UPDATE verb + * org-wide and says nothing about delete. Delete on an owned object belongs to + * ownership, write DEPTH and Modify All on every owned model (ADR-0111 D3), so + * on this one too: the owner, someone above the owner by depth and a Modify + * All holder delete, and the platform's `created_by` floor (who typed the row + * in) stops deciding it — {@link checkDelete}'s `allow` replaces that floor + * and its `deny` refuses, exactly as on `private` / `public_read`. + * + * The DECLARATION is read, never the effective bucket: an unset model on a + * platform table (effective `public`) and a `controlled_by_parent` detail + * (effective `public`, written through its master, ADR-0055) keep today's + * answer, and so does every object with no owner column, whose only row-level + * delete gate stays the platform floor. A federated object whose `owner_id` is + * only the platform's injected anchor ({@link hasPhantomOwnerAnchor}: no + * storage, no `columnMap` entry) carries no owner column either: no row of it + * has a provable owner, so it keeps today's answer too. + */ +export function ownershipDecidesDeleteOnOpenWrites(schema: any): boolean { + const declared = schema?.sharingModel ?? schema?.security?.sharingModel; + return declared === 'public_read_write' && hasOwnerField(schema) && !hasPhantomOwnerAnchor(schema); +} + +/** + * The org-wide default a WRITE of `verb` meets on `object` for this principal: + * {@link owdForPrincipal} for the write class, except that a DELETE on an + * object {@link ownershipDecidesDeleteOnOpenWrites} answers for meets the + * owner-writes baseline (`'read'`) instead of the open one. An external + * principal follows the same rule as a member (ruling of record 6355206139): + * one the write floor already narrows to owner_only keeps `'private'`. + */ +function writeOwdForVerb( + schema: any, + context: ExecutionContext, + object: string, + verb: 'update' | 'delete', +): 'private' | 'read' | 'public' { + const owd = owdForPrincipal(schema, context, object, 'write'); + if (owd === 'public' && verb === 'delete' && ownershipDecidesDeleteOnOpenWrites(schema)) return 'read'; + return owd; +} + /** * [ADR-0138 D1/D3] The anonymous principal the guest entry assembles — * `principalKind: 'guest'` with no user id. A system context is never one: the @@ -925,7 +975,9 @@ export class SharingService implements ISharingService { * Editable-set = owner-match (widened by write DEPTH) OR records shared to * the caller at a {@link WRITE_ACCESS_LEVELS} level. Unlike reads, this * applies to BOTH `private` and `read` (public_read) models — public_read is - * read-open but write-owned; only a fully `public` object is write-open. + * read-open but write-owned; only a fully `public` object is write-open, + * and a DELETE on an owned `public_read_write` object is owner-scoped like + * `public_read` ({@link ownershipDecidesDeleteOnOpenWrites}). */ async buildWriteFilter( object: string, @@ -939,7 +991,9 @@ export class SharingService implements ISharingService { // [Ruling of record 6355206139] The write half of the EXTERNAL OWD floor // (see buildReadFilter): a `public_read_write` object is not write-open to // an external unless a held grant's RLS speaks for it. - if (owdForPrincipal(schema, context, object, 'write') === 'public') return null; + // [Ruling of record 7288570890] Per verb: a bulk DELETE on an owned + // `public_read_write` object is scoped to the owner/DEPTH set below. + if (writeOwdForVerb(schema, context, object, verb) === 'public') return null; if (!hasOwnerField(schema)) return null; if (!context.userId) { // Authenticated but principal-less → edit nothing (fail closed), @@ -1299,8 +1353,11 @@ export class SharingService implements ISharingService { * ELSE. An `edit` (or legacy `full`) share opens update but not delete * (sharing widens rows, never verbs), so a share holder gets `deny` here * while `checkEdit` answers `allow` on the same row. The `abstain` set is - * IDENTICAL to `checkEdit`'s: both gates agree about which objects sharing - * enforces on, and differ only about the verb. + * `checkEdit`'s MINUS one class: an object that declares `public_read_write` + * and carries an owner column, where edit is open but delete follows the + * record's owner ({@link ownershipDecidesDeleteOnOpenWrites}, ruling of + * record 7288570890) — so this gate answers `allow` / `deny` there while + * `checkEdit` abstains. * * [#4647] The bypass is asked EXPLICITLY (`hasWriteBypass`) instead of only * riding in as `__writeScope === 'org'`. The scope proxy was silently @@ -1345,8 +1402,9 @@ export class SharingService implements ISharingService { * OWD too the answer is `allow` (which lifts the platform's `created_by` * floor for a member); the basis never reaches delete; * 4. [Ruling of record 6355206139] the EXTERNAL OWD floor: a write-open - * object `abstain`; an object with no owner field `abstain`; a - * principal-less context `deny`; + * object `abstain` (for DELETE an owned `public_read_write` object is not + * write-open, {@link ownershipDecidesDeleteOnOpenWrites}); an object with + * no owner field `abstain`; a principal-less context `deny`; * 5. ownership, widened by write DEPTH, `allow` ({@link matchesOwnerScope}); * 6. UPDATE only — an explicit write-level share (`edit`, plus * not-yet-normalised `full`) `allow`, [ADR-0155 ② ruled R2] on an object @@ -1397,7 +1455,7 @@ export class SharingService implements ISharingService { queues = this.ownershipQueues?.() ?? undefined; } try { - if (owdForPrincipal(schema, context, object, 'write') === 'public') objectLevel = 'abstain'; + if (writeOwdForVerb(schema, context, object, verb) === 'public') objectLevel = 'abstain'; else if (!hasOwnerField(schema)) objectLevel = 'abstain'; else if (!context.userId) objectLevel = 'deny'; } catch (error) { @@ -1570,7 +1628,10 @@ export class SharingService implements ISharingService { * DEPTH) or the `modifyAllRecords` super-user bypass — and NOTHING ELSE. An * `edit` (or legacy `full`) share opens update but not delete: sharing widens * rows, never verbs. Always `true` for system context, public objects, and - * objects without an owner field, matching {@link canEdit}. + * objects without an owner field, as {@link canEdit} is, except on an object + * that declares `public_read_write` and carries an owner column, where delete + * follows the record's owner ({@link ownershipDecidesDeleteOnOpenWrites}, + * ruling of record 7288570890) while {@link canEdit} stays open. * * [#6428] The two-state PROJECTION of {@link checkDelete}, on the same rule * as {@link canEdit}: `true` for everything that is not a `deny`. diff --git a/packages/qa/dogfood/test/predicate-write-unreadable-not-matched.dogfood.test.ts b/packages/qa/dogfood/test/predicate-write-unreadable-not-matched.dogfood.test.ts index 07db79021ce..d7c3b1161f2 100644 --- a/packages/qa/dogfood/test/predicate-write-unreadable-not-matched.dogfood.test.ts +++ b/packages/qa/dogfood/test/predicate-write-unreadable-not-matched.dogfood.test.ts @@ -474,9 +474,13 @@ describe('predicate write door: a row the caller cannot read is not matched', () // refusal (the run fails with the node's inner refusal), for a filter // naming rows and a filter naming none alike, and no row changes; // 2. control: a principal holding the capability keeps its predicate write; -// 3. control: the by-id doors give the writer one refusal for a row and for -// an id naming none (unchanged; inside the ownership floor's domain it is -// the record-level refusal, the answer step 2.7 gives every id there). +// 3. control: the by-id update gives the writer one refusal for its own row +// and for an id naming none; the by-id delete gives an id naming none the +// answer another user's row gets (step 2.7's record-level refusal). Its own +// row's delete is the read door's refusal: delete on an owned +// `public_read_write` object follows the owner (ruling of record +// 7288570890, C), so the owner passes step 2.7 and meets the read door, +// as on a `private` object. One answer for every id across OWDs is #39225. const GATED_READ_CAP = 'pw_gated_read'; @@ -711,19 +715,36 @@ describe('a write from a caller the read door refuses is refused, whatever rows expect((await ql.findOne('pw_gated', { where: { id: ids.kappa[0] }, context: SYS }))?.name).toBe('kappa 0'); }); - it('control: the by-id doors give the writer one refusal for its own row and for an id naming none, and the row is untouched', async () => { + it('control: the by-id update gives the writer one refusal for its own row and for an id naming none; the by-id delete gives an id naming none the answer another user\'s row gets; no row is touched', async () => { // A row of the writer's own that no other case here addresses. const id = ids.epsilon[0]; + // A row another user owns (the reader's); no case here deletes it. + const others = ids.gamma[0]; const missing = 'pwgatedmissing0001'; /** The answer with the caller-supplied id written out, so two ids compare. */ const withoutId = (a: Answer, written: string) => JSON.stringify(a).split(written).join('ID'); - for (const [method, body] of [['PATCH', { name: 'should not land' }], ['DELETE', undefined]] as const) { - const row = await call(writerTok, method, `/data/pw_gated/${id}`, body); - const none = await call(writerTok, method, `/data/pw_gated/${missing}`, body); - expect(row.status, JSON.stringify(row.body)).toBe(403); - expect(refusalOf(row).code, JSON.stringify(row.body)).toBe('PERMISSION_DENIED'); - expect(withoutId(none, missing)).toBe(withoutId(row, id)); + + const row = await call(writerTok, 'PATCH', `/data/pw_gated/${id}`, { name: 'should not land' }); + const none = await call(writerTok, 'PATCH', `/data/pw_gated/${missing}`, { name: 'should not land' }); + expect(row.status, JSON.stringify(row.body)).toBe(403); + expect(refusalOf(row).code, JSON.stringify(row.body)).toBe('PERMISSION_DENIED'); + expect(withoutId(none, missing)).toBe(withoutId(row, id)); + + // [Ruling of record 7288570890, C] Delete on this owned public_read_write + // object follows the owner, as on `private`: the writer's own row passes + // step 2.7 and meets the read door's refusal; another user's row and an id + // naming none get the same record-level refusal, so nothing about another + // user's rows is told. One answer for every id across OWDs is #39225. + const ownDelete = await call(writerTok, 'DELETE', `/data/pw_gated/${id}`); + const othersDelete = await call(writerTok, 'DELETE', `/data/pw_gated/${others}`); + const noneDelete = await call(writerTok, 'DELETE', `/data/pw_gated/${missing}`); + for (const a of [ownDelete, othersDelete]) { + expect(a.status, JSON.stringify(a.body)).toBe(403); + expect(refusalOf(a).code, JSON.stringify(a.body)).toBe('PERMISSION_DENIED'); } + expect(withoutId(noneDelete, missing)).toBe(withoutId(othersDelete, others)); + expect((await ql.findOne('pw_gated', { where: { id }, context: SYS }))?.name).toBe('epsilon 0'); + expect(await ql.findOne('pw_gated', { where: { id: others }, context: SYS })).toBeTruthy(); }); }); diff --git a/packages/spec/src/contracts/sharing-service.ts b/packages/spec/src/contracts/sharing-service.ts index 80c369430b0..fd88c4e0771 100644 --- a/packages/spec/src/contracts/sharing-service.ts +++ b/packages/spec/src/contracts/sharing-service.ts @@ -400,9 +400,12 @@ export interface ISharingService { * (Salesforce Read/Write cannot delete; Dataverse `Delete` is a distinct * privilege; Odoo splits `write`/`unlink`). `allow` is ownership (widened by * write DEPTH), the `modifyAllRecords` super-user bypass, or system context - * ONLY; `abstain` covers exactly the rows {@link checkEdit} abstains on, so - * the two gates agree about which objects sharing enforces on and disagree - * only about the verb. + * ONLY; `abstain` covers the rows {@link checkEdit} abstains on except one + * class: on an object that declares `public_read_write` and carries an owner + * column, edit is open (`checkEdit` abstains) while delete follows the + * record's owner, so this gate answers `allow` / `deny` there (ruling of + * record 7288570890). Everywhere else the two gates agree about which + * objects sharing enforces on and disagree only about the verb. */ checkDelete( object: string, @@ -420,7 +423,10 @@ export interface ISharingService { * share does NOT confer it (Salesforce Read/Write cannot delete; Dataverse * `Delete` is a distinct privilege; Odoo splits `write`/`unlink`). Always * true for system context, `public` objects, and objects with no owner - * field, matching {@link canEdit}. A per-record delete grant, if ever added, + * field, as {@link canEdit} is, with one exception: on an object that + * declares `public_read_write` and carries an owner column, delete follows + * the record's owner (ruling of record 7288570890), so a non-owner below + * Modify All is refused here while {@link canEdit} admits it. A per-record delete grant, if ever added, * is a capability mask AND-ed with object CRUD — not a share level. * * [#6428] The two-state PROJECTION of {@link checkDelete}, on the same rule diff --git a/packages/spec/src/security/permission.zod.ts b/packages/spec/src/security/permission.zod.ts index bab3f5f581c..7c3bc72d527 100644 --- a/packages/spec/src/security/permission.zod.ts +++ b/packages/spec/src/security/permission.zod.ts @@ -709,7 +709,10 @@ const ObjectPermissionBaseSchema = lazySchema(() => strictObject( * Bypasses Sharing Rules and Ownership checks — as RECORD SHARING computes * them, i.e. on every object `ISharingService` enforces on, which is any * object carrying an owner field (the common case, and the one this bit is - * granted for). + * granted for). On a `public_read_write` object sharing enforces nothing on + * EDIT (everyone edits), and its DELETE is answered by ownership like any + * owned object's, so this bit deletes there too (ruling of record + * 7288570890). * Equivalent to Microsoft Dataverse "Organization" level write access. * * [#6698] It is NOT a bypass of every ownership check the platform runs. On