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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/39339-owner-beside-delete-policy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@objectstack/plugin-security': patch
---

fix(security): the owner of a record deletes it beside an app's own delete rule, whoever created it

Clause-②: no
Metadata-protocol: none

Who sees it: an app that authors a row-level `delete` policy (for example "anyone may delete a closed deal") on an object with an owner column (`owner_id`), on `private`, `public_read` and `public_read_write` objects alike.

- **The record's owner deletes it again.** Before, beside such a policy the platform's own row gate admitted only the person who created the record, so the owner of a record they did not type in (assigned to them, imported, handed over) was refused with 403 on every record the policy does not admit: a rule written to let more people delete took the delete away from owners. Now the owner, someone above the owner by write depth (`writeScope`), and a holder of write depth `org` delete it, as they do on an object with no authored delete policy. A by-id delete and a predicate (bulk) delete reach the same records, and `security/explain` agrees.
- **Unchanged:** Modify All (`modifyAllRecords`) still does not lift an authored delete policy on a business object, so its holder deletes the records the policy admits and the ones they created, and no others. A creator who no longer owns a record is still refused unless the policy admits it. An object with no owner column keeps the creator rule. Edit (update) is not changed by this release.
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,16 @@ async function boot(posture: TenancyPosture) {
row('held_1', 'held', BOUNDED, OTHER),
row('held_2', 'held', OTHER, OTHER),
row('free_1', 'free', BOUNDED, BOUNDED),
row('held_del_direct', 'held', BOUNDED, OTHER),
row('held_del_agent', 'held', BOUNDED, OTHER),
// [ruling of record 7288570890 (C)] Owner-less: the delegator's write depth
// `org` reaches every OWNED row for delete, so the row its own delete
// refuses is one no owner holds.
{ ...row('held_del_direct', 'held', OTHER, OTHER), owner_id: null },
{ ...row('held_del_agent', 'held', OTHER, OTHER), owner_id: null },
// [ruling of record 7288570890 (C)] A held row the delegator OWNS and did
// not create: ownership admits the delegator's own delete beside the
// authored policy; the delegated delete keeps both floors and is refused.
row('held_owned_del_direct', 'held', BOUNDED, OTHER),
row('held_owned_del_agent', 'held', BOUNDED, OTHER),
row('free_del_direct', 'free', BOUNDED, BOUNDED),
row('free_del_agent', 'free', BOUNDED, BOUNDED),
row('store_direct', 'free', BOUNDED, OTHER),
Expand Down Expand Up @@ -429,6 +437,10 @@ const CELLS: Cell[] = [
},
// The bound only narrows: rows the delegator's own write admits and the
// delegated write has always refused stay refused.
{
delegator: BOUNDED, verb: 'delete', object: 'OBJ', rows: { direct: 'held_owned_del_direct', agent: 'held_owned_del_agent' },
shape: 'unchanged on its behalf: a held row the delegator owns and did not create (ownership admits its own delete)', direct: ADMITTED, agent: DENIED,
},
{
delegator: PLAIN, verb: 'update', object: 'OBJ', rows: { direct: 'plain_1', agent: 'plain_1' },
shape: 'unchanged: a row the delegator\'s own update admits and the delegated update refuses', direct: ADMITTED, agent: DENIED,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,324 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* An app-authored DELETE row policy on an object that has an owner column,
* read beside the two rulings that govern it:
*
* - ruling of record 7063130499 (A): under a sharing `allow`, the
* creator/owner floor stays an OR term beside an authored update/delete
* `using` policy, and the by-id and predicate writes give one answer;
* - ruling of record 7288570890 (C): delete on an owned object follows the
* record's owner, someone above the owner by write depth, or a Modify All
* holder; a creator who no longer owns the row cannot delete.
*
* Before this file the OR term beside the authored policy was only the
* creator half (`created_by == current_user.id`, `owner_only_deletes`), so the
* owner of a row they did not create (assigned, imported, handed over) was
* refused on every row the authored policy does not admit: the policy, meant
* to widen delete, took it away from the owner. Here ownership admits the row
* beside the authored policy as it does where no authored policy stands, and
* Modify All stays out of that OR (ADR-0066 ①: it does not lift an authored
* write policy on a business object).
*
* One real stack, as `public-read-write-owner-delete.test.ts` builds it: an
* `ObjectKernel` with `ObjectQLPlugin` over better-sqlite3, the real
* `SecurityPlugin` (the real `member_default` floor) and the real
* `SharingServicePlugin`. Every caller holds the `org_member` position, the
* floor's domain. The authored policy admits a `closed` row to every member;
* every row the owner cases probe is `open`, so the policy never admits them.
*/

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_obadp';
/** Owns rows it did not create. */
const OWNER = 'usr_obadp_owner';
/** Created rows it no longer owns. */
const CREATOR = 'usr_obadp_creator';
/** Neither owns nor created the probed rows. */
const STRANGER = 'usr_obadp_stranger';
/** Above {@link OWNER} by write depth (`own_and_reports`). */
const MANAGER = 'usr_obadp_manager';
/** Write depth `org`, declared, without Modify All. */
const ORG_DEPTH = 'usr_obadp_org_depth';
/** Holds Modify All on the probed objects. */
const MODIFY_ALL = 'usr_obadp_modify_all';
const USERS = [OWNER, CREATOR, STRANGER, MANAGER, ORG_DEPTH, MODIFY_ALL];

/** `public_read_write`, owner column. */
const DEAL = 'qa_obadp_deal';
/** `private`, otherwise identical. */
const SECRET = 'qa_obadp_secret';
/** `public_read_write` with NO owner column: the creator floor stays its row-level delete gate. */
const MEMO = 'qa_obadp_memo';

const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } as const;
/** The authored widener: any member deletes a `closed` row, on each probed object. */
const CLOSED_DELETABLE = [DEAL, SECRET, MEMO].map((object) => ({
name: `${object}_closed_deletable`,
object,
operation: 'delete' as const,
using: "stage == 'closed'",
}));
const setWith = (name: string, extra: Record<string, unknown> = {}) =>
PermissionSetSchema.parse({
name,
objects: { [DEAL]: { ...CRUD, ...extra }, [SECRET]: { ...CRUD, ...extra }, [MEMO]: { ...CRUD, ...extra } },
rowLevelSecurity: CLOSED_DELETABLE,
});
/** Ordinary CRUD: every refusal below is row-level, never the object bit. */
const REP = setWith('qa_obadp_rep');
/** Depth `own_and_reports`, read too, so the `private` row is visible to the manager. */
const LEAD = setWith('qa_obadp_lead', { readScope: 'own_and_reports', writeScope: 'own_and_reports' });
/** Depth `org`, read too, and no Modify All. */
const WIDE = setWith('qa_obadp_wide', { readScope: 'org', writeScope: 'org' });
/** Modify All Data on the probed objects. */
const ADMIN = setWith('qa_obadp_admin', { viewAllRecords: true, modifyAllRecords: true });

/** 403 where the caller reads the row, 404 where it cannot (the `private` row of another owner). */
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] });

type Outcome = { kind: 'landed' } | { kind: 'refused'; code?: string; status?: number };
const outcomeOf = (p: Promise<unknown>): Promise<Outcome> =>
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.obadp.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.owner-beside-authored-delete-policy',
namespace: 'qa_obadp',
version: '1.0.0',
type: 'plugin',
name: 'owner beside an authored delete policy',
objects: [
SysUser, SysMember, SysOrganization,
{ name: DEAL, label: 'Deal', sharingModel: 'public_read_write', fields: fields() },
{ name: SECRET, label: 'Secret', sharingModel: 'private', fields: fields() },
{
name: MEMO,
label: 'Memo',
sharingModel: 'public_read_write',
ownership: 'none',
fields: { name: { type: 'text', label: 'Name' }, stage: { type: 'text', label: 'Stage' } },
},
],
});
// [ADR-0057] 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('an authored delete policy on an owned object: ownership admits the row beside it, Modify All does not', () => {
let kernel: ObjectKernel;
let ql: ObjectQL;
let security: Required<Pick<ISecurityService, 'explain'>>;
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, WIDE, ADMIN],
fallbackPermissionSet: 'member_default',
}));
await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false }));
await kernel.bootstrap();
ql = kernel.getService<ObjectQL>('objectql');
security = kernel.getService<Required<Pick<ISecurityService, 'explain'>>>('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: 'member' }, SYS);
}
}, 120_000);

afterAll(async () => {
if (kernel) await Promise.race([kernel.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]);
}, 30_000);

/** One fresh row, `owner_id` and `created_by` set apart. */
const seed = async (object: string, owner: string | null, creator: string | null, stage = 'open') => {
const id = `obadp_${++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));
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 authored policy is in play: a stranger deletes a closed row and is refused an open one', async () => {
const closed = await seed(DEAL, OWNER, CREATOR, 'closed');
expect(await deleteById(DEAL, closed, member(STRANGER, REP.name))).toEqual({ kind: 'landed' });
const open = await seed(DEAL, OWNER, CREATOR);
expect(await deleteById(DEAL, open, member(STRANGER, REP.name))).toMatchObject({ kind: 'refused', status: 403 });
expect(await exists(DEAL, open)).toBe(true);
});

describe('by id, on a row the authored policy does not admit: ownership deletes it', () => {
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 holder of write depth org, without Modify All', member(ORG_DEPTH, WIDE.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, on a row the authored policy does not admit: everyone else is refused', () => {
for (const [what, context] of [
['the creator who no longer owns it', member(CREATOR, REP.name)],
['a member who neither owns nor created it', member(STRANGER, REP.name)],
['a Modify All holder who neither owns nor created it (ADR-0066 ①)', member(MODIFY_ALL, ADMIN.name)],
] as const) {
for (const object of [DEAL, SECRET]) {
it(`${object}: ${what} is refused, the row stays, 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(false);
const out = await deleteById(object, id, context);
// The Modify All holder reads every row of the private object, so it
// meets the 403 there too.
expect(out).toMatchObject(context.userId === MODIFY_ALL ? { kind: 'refused', status: 403 } : REFUSED(object));
expect(await exists(object, id), 'the row stays').toBe(true);
});
}
}
});

it('unchanged: a Modify All holder who created a row it no longer owns deletes it through the creator term', async () => {
const id = await seed(DEAL, OWNER, MODIFY_ALL);
expect(await explainDelete(DEAL, id, member(MODIFY_ALL, ADMIN.name))).toBe(true);
expect(await deleteById(DEAL, id, member(MODIFY_ALL, ADMIN.name))).toEqual({ kind: 'landed' });
});

it('an object with no owner column keeps the creator floor beside the authored policy', async () => {
const open = await seed(MEMO, null, CREATOR);
expect(await deleteById(MEMO, open, member(STRANGER, REP.name))).toMatchObject({ kind: 'refused', status: 403 });
expect(await exists(MEMO, open)).toBe(true);
expect(await deleteById(MEMO, open, member(CREATOR, REP.name))).toEqual({ kind: 'landed' });
const closed = await seed(MEMO, null, CREATOR, 'closed');
expect(await deleteById(MEMO, closed, member(STRANGER, REP.name))).toEqual({ kind: 'landed' });
});

describe('a predicate delete matches exactly the rows the by-id delete admits (ruling A)', () => {
for (const object of [DEAL, SECRET]) {
it(`${object}: the owner's predicate delete removes the row it owns and leaves the one it only created`, 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(`${DEAL}: the manager's predicate delete removes the owner's row and the closed row the policy admits`, async () => {
const owners = await seed(DEAL, OWNER, CREATOR, 'bulk');
const closed = await seed(DEAL, STRANGER, STRANGER, 'closed');
const other = await seed(DEAL, STRANGER, STRANGER, 'bulk');
const out = await outcomeOf(ql.delete(DEAL, {
where: { id: { $in: [owners, closed, other] } }, multi: true, context: member(MANAGER, LEAD.name),
} as never));
expect(out).toEqual({ kind: 'landed' });
expect(await exists(DEAL, owners)).toBe(false);
expect(await exists(DEAL, closed)).toBe(false);
expect(await exists(DEAL, other)).toBe(true);
});

it(`${DEAL}: a Modify All holder's predicate delete removes the closed row and the one it created, and no other`, async () => {
const closed = await seed(DEAL, OWNER, CREATOR, 'closed');
const created = await seed(DEAL, OWNER, MODIFY_ALL, 'bulk');
const other = await seed(DEAL, OWNER, CREATOR, 'bulk');
const out = await outcomeOf(ql.delete(DEAL, {
where: { id: { $in: [closed, created, other] } }, multi: true, context: member(MODIFY_ALL, ADMIN.name),
} as never));
expect(out).toEqual({ kind: 'landed' });
expect(await exists(DEAL, closed)).toBe(false);
expect(await exists(DEAL, created)).toBe(false);
expect(await exists(DEAL, other), 'Modify All does not lift the authored policy').toBe(true);
});
});

it('edit is untouched by this composition: the authored policy is delete-only, and every member edits the deal', 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' });
}
});
});
Loading
Loading