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
16 changes: 16 additions & 0 deletions .changeset/direct-share-grant-is-manual.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/plugin-sharing': patch
---

fix(plugin-sharing)!: a share granted directly by a non-system caller is always a manual share

Clause-②: no (narrowing)
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export changes shape. The moved answer is a refusal of two input fields on one service method and the door that calls it: no stored row changes, so there is nothing for a migration to rewrite and no tombstone. -->

**BREAKING** for a client that sends a non-manual `source` or a `sourceId` on the direct-grant door. `SharingService.grant` called by a non-system caller, and so `POST /api/v1/data/:object/:id/shares`, now refuses an input whose `source` is present and is not `'manual'`, and an input that carries any `sourceId`, with `VALIDATION_FAILED` (400), and writes nothing. The refusal comes before any other check reads anything. Only the platform's own sharing-rule, team and system paths, which run under a system context, write a share of another source.

**Who moves:** a client that sent a non-manual `source` (`'rule'`, `'team'`, `'inherited'` or any other string) or a `sourceId` on the direct-grant door. FROM 201 with the row written TO 400 `VALIDATION_FAILED`, nothing written. The fix is one line: drop `source` and `sourceId` from the request (or send `source: 'manual'` with no `sourceId`); a share that should follow a rule is declared as a sharing rule.

**Not moved.** A grant with no `source`, or with `source: 'manual'` and no `sourceId`, answers as before. The system path (the sharing-rule evaluator and other platform callers under a system context) writes its shares as before, and the revoke door answers as before.
4 changes: 4 additions & 0 deletions content/docs/kernel/runtime-services/sharing-service.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ manager** whose effective write DEPTH (`unit` / `unit_and_below` /
`@objectstack/plugin-security` fails closed to owner-only; without the
enterprise resolver the DEPTH path is inert and authority stays owner +
Modify-All. Pass `{ isSystem: true }` only from platform-internal machinery.
A share a non-system caller grants is always a **manual** share: `grant` refuses
a `source` other than `'manual'`, and any `sourceId`, with `VALIDATION_FAILED`
(400), because only the platform's own sharing-rule, team and system paths write
a share of another source.

## The verb boundary (ADR-0111 D3)

Expand Down
102 changes: 81 additions & 21 deletions packages/plugins/plugin-sharing/src/sharing-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1382,29 +1382,89 @@ describe('[ADR-0111 D7] no inert grants', () => {
.toEqual(['srule_1:edit', 'srule_2:edit']);
});

it('a manual grant keeps one row per recipient whatever `sourceId` the caller sends', async () => {
const a = await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob', sourceId: 'x' } as any, { userId: 'alice' });
const b = await svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit', sourceId: 'y' } as any,
{ userId: 'alice' },
);
expect(engine._tables.sys_record_share.length).toBe(1);
expect(b.id).toBe(a.id);
expect(b.access_level).toBe('edit');
// A direct (non-system) grant that carries a `source` other than 'manual',
// or any `sourceId`, is refused before the upsert is reached, so it has no
// key to keep — pinned in "a direct grant is always a manual share" below.
});

describe('[ADR-0111 D7] a direct grant is always a manual share', () => {
let engine: ReturnType<typeof makeFakeEngine>;
let svc: SharingService;
let reads: number;
const OWNER = { userId: 'alice' };
const SYSTEM = { isSystem: true } as any;
const base = { object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'read' as const };
beforeEach(() => {
engine = makeFakeEngine({ account: ACCOUNT_SCHEMA, sys_record_share: {} });
svc = new SharingService({ engine });
engine._tables.account = [{ id: 'a1', owner_id: 'alice' }];
reads = 0;
const find = engine.find.bind(engine);
engine.find = async (object: string, options?: any) => { reads += 1; return find(object, options); };
});

const refused: Array<[string, Record<string, unknown>]> = [
["source 'rule' with a sourceId", { source: 'rule', sourceId: 'srule_1' }],
["source 'rule' alone", { source: 'rule' }],
["source 'team'", { source: 'team', sourceId: 'team_1' }],
["source 'inherited'", { source: 'inherited' }],
['an unknown source string', { source: 'bogus' }],
['an empty source string', { source: '' }],
['a sourceId with no source', { sourceId: 'srule_1' }],
["a sourceId with source 'manual'", { source: 'manual', sourceId: 'srule_1' }],
];

for (const [label, extra] of refused) {
it(`refuses a non-system caller's grant with ${label}: VALIDATION_FAILED, nothing read, no row`, async () => {
await expect(svc.grant({ ...base, ...extra } as any, OWNER)).rejects.toThrow(/^VALIDATION_FAILED: /);
expect(engine._tables.sys_record_share ?? []).toHaveLength(0);
// Refused ahead of the authorization pre-flight's record read and the
// upsert's lookup: a refused caller pays nothing.
expect(reads).toBe(0);
});
}

it('refuses a caller without manage-shares rights the same way, before authorization reads anything', async () => {
await expect(
svc.grant({ ...base, source: 'rule', sourceId: 'srule_1' } as any, { userId: 'mallory' }),
).rejects.toThrow(/^VALIDATION_FAILED: /);
expect(reads).toBe(0);
expect(engine._tables.sys_record_share ?? []).toHaveLength(0);
});

it('a direct (non-system) grant keeps one row per recipient whatever non-manual `source` and `sourceId` it sends', async () => {
const a = await svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', source: 'rule', sourceId: 'srule_x' } as any,
{ userId: 'alice' },
);
const b = await svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit', source: 'rule', sourceId: 'srule_y' } as any,
{ userId: 'alice' },
);
expect(engine._tables.sys_record_share.length).toBe(1);
expect(b.id).toBe(a.id);
expect(b.access_level).toBe('edit');
it('CONTROL: no source grants a manual share', async () => {
const r = await svc.grant(base, OWNER);
expect(r.source).toBe('manual');
expect(engine._tables.sys_record_share).toHaveLength(1);
expect(engine._tables.sys_record_share[0]).toMatchObject({ source: 'manual', source_id: null });
});

it('CONTROL: a null source and a null sourceId read as absent and grant a manual share', async () => {
const r = await svc.grant({ ...base, source: null, sourceId: null } as any, OWNER);
expect(r.source).toBe('manual');
expect(engine._tables.sys_record_share[0]).toMatchObject({ source: 'manual', source_id: null });
});

it("CONTROL: an explicit 'manual' source grants a manual share, and its revoke still works", async () => {
const r = await svc.grant({ ...base, source: 'manual' }, OWNER);
expect(engine._tables.sys_record_share[0]).toMatchObject({ source: 'manual', source_id: null });
await svc.revoke(r.id, OWNER, { object: 'account', recordId: 'a1' });
expect(engine._tables.sys_record_share).toHaveLength(0);
});

it('CONTROL: the system context still writes a rule share with its sourceId', async () => {
const r = await svc.grant({ ...base, source: 'rule', sourceId: 'srule_1' }, SYSTEM);
expect(r).toMatchObject({ source: 'rule', source_id: 'srule_1' });
expect(engine._tables.sys_record_share).toHaveLength(1);
expect(engine._tables.sys_record_share[0]).toMatchObject({ source: 'rule', source_id: 'srule_1' });
});

it('CONTROL: a non-system revoke of a system-written rule share is still CONFLICT', async () => {
const r = await svc.grant({ ...base, source: 'rule', sourceId: 'srule_1' }, SYSTEM);
await expect(
svc.revoke(r.id, OWNER, { object: 'account', recordId: 'a1' }),
).rejects.toThrow(/^CONFLICT: /);
expect(engine._tables.sys_record_share).toHaveLength(1);
});
});

Expand Down
36 changes: 36 additions & 0 deletions packages/plugins/plugin-sharing/src/sharing-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,39 @@ function nonUserRecipientTypeRemedy(value: unknown): string {
+ ' (ADR-0111 D7)';
}

/**
* [ADR-0111 D7] A share a non-system caller grants is always a MANUAL share.
* Only the platform's own paths — the sharing-rule evaluator, team and system
* machinery, each running under a system context — write a share with another
* `source` or with a `sourceId`.
*
* So the non-system path refuses, rather than rewrites, an input whose
* `source` is present and is not `'manual'`, and an input that carries any
* `sourceId`: a caller that sent a source learns it was not honoured. An
* absent `source` (`undefined` or `null`, which `grant` reads as `'manual'`)
* and an explicit `'manual'` with no `sourceId` pass unchanged.
*
* Called before any read or write, so a refused caller pays nothing.
*/
function assertDirectGrantIsManual(input: GrantShareInput): void {
const source: unknown = input.source;
if (source != null && source !== 'manual') {
throw new Error(
`VALIDATION_FAILED: a share granted directly is a manual share — send no source, or source 'manual' `
+ `(received ${JSON.stringify(source)}); a share with any other source is written only by the `
+ `platform's own sharing-rule, team and system paths (ADR-0111 D7)`,
);
}
const sourceId: unknown = input.sourceId;
if (sourceId != null) {
throw new Error(
`VALIDATION_FAILED: a share granted directly is a manual share and carries no sourceId `
+ `(received ${JSON.stringify(sourceId)}); a share with a sourceId is written only by the `
+ `platform's own sharing-rule, team and system paths (ADR-0111 D7)`,
);
}
}

/**
* Owner field convention. Hard-coded to `owner_id` for MVP — the
* sharing model in Salesforce / ServiceNow / Dynamics all assume a
Expand Down Expand Up @@ -1992,6 +2025,9 @@ export class SharingService implements ISharingService {
this.assertNotInertGrant(input.object);
organizationId = await this.resolveSystemGrantOrganization(input, context);
} else {
// [ADR-0111 D7] A direct grant is a manual share — refused here, ahead
// of every read, so a refused caller pays nothing.
assertDirectGrantIsManual(input);
this.assertSharingEnforced(input.object);
await this.assertCanManageShares(input.object, input.recordId, context);
organizationId = await this.resolveDirectGrantOrganization(input, context);
Expand Down
137 changes: 137 additions & 0 deletions packages/qa/dogfood/test/direct-share-grant-is-manual.dogfood.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
//
// [ADR-0111 D7] A share a non-system caller grants is always a MANUAL share,
// pinned at the direct-grant door of the booted showcase:
// `POST /api/v1/data/:object/:id/shares`.
//
// The door forwards the caller's `source` / `sourceId` to `SharingService.grant`,
// and the service refuses, on its non-system path, an input whose `source` is
// present and is not `'manual'` and an input that carries any `sourceId`: 400
// `VALIDATION_FAILED`, nothing written. The service-level pins (every refused
// shape, nothing read, the system-path controls) live beside the service in
// `plugin-sharing/src/sharing-service.test.ts`; this file holds the composed
// door — the real REST route, the real service, the real engine — because only
// the booted runtime has all three.
//
// Controls: no source and an explicit 'manual' are granted (and the manual
// share revokes); the system context still writes a rule share with its
// sourceId, and that share's revoke through the door is still CONFLICT. The
// generic data door on `sys_record_share` itself is pinned as refused too.

import { describe, it, expect, beforeAll } from 'vitest';
import { type VerifyStack } from '@objectstack/verify';
import type { ISharingService } from '@objectstack/spec/contracts';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { getSharedShowcase } from './shared-showcase.js';

const OBJECT = 'showcase_private_note';
const SYS = { isSystem: true } as const;
const idOf = (b: any) => b?.id ?? b?.record?.id;

describe('[ADR-0111 D7] a share granted directly by a non-system caller is always a manual share', () => {
let stack: VerifyStack;
let ql: any;
let sharing: ISharingService;
let ownerToken: string;
let recipientId: string;
let organizationId: string | undefined;

const sharesOn = async (recordId: string) =>
ql.find('sys_record_share', { where: { object_name: OBJECT, record_id: recordId }, context: SYS });

const newNote = async (title: string): Promise<string> => {
const res = await stack.apiAs(ownerToken, 'POST', `/data/${OBJECT}`, { title });
expect(res.status, await res.clone().text()).toBe(201);
return String(idOf(await res.json()));
};

const grant = (recordId: string, extra: Record<string, unknown>) =>
stack.apiAs(ownerToken, 'POST', `/data/${OBJECT}/${recordId}/shares`, {
recipientId, accessLevel: 'read', ...extra,
});

beforeAll(async () => {
stack = await getSharedShowcase();
ql = await stack.kernel.getServiceAsync('objectql');
sharing = stack.kernel.getService<ISharingService>('sharing');
ownerToken = await stack.signUp('dsm-owner@verify.test');
await stack.signUp('dsm-recipient@verify.test');
const user = await ql.findOne('sys_user', { where: { email: 'dsm-recipient@verify.test' }, context: SYS });
recipientId = String(user?.id);
}, 120_000);

const refused: Array<[string, Record<string, unknown>]> = [
["source 'rule' with a sourceId", { source: 'rule', sourceId: 'srule_dsm' }],
["source 'team'", { source: 'team' }],
['an unknown source string', { source: 'bogus' }],
['a sourceId with no source', { sourceId: 'srule_dsm' }],
['a snake_case source_id with no source', { source_id: 'srule_dsm' }],
["a sourceId with source 'manual'", { source: 'manual', sourceId: 'srule_dsm' }],
];

for (const [label, extra] of refused) {
it(`refuses ${label}: 400 VALIDATION_FAILED, no share written`, async () => {
const recordId = await newNote(`dsm refused ${label}`);
const res = await grant(recordId, extra);
const body = await res.json() as { error?: { code?: string } };
expect(res.status, JSON.stringify(body)).toBe(400);
expect(body.error?.code).toBe('VALIDATION_FAILED');
expect(await sharesOn(recordId)).toHaveLength(0);
});
}

it('CONTROL: no source is granted as a manual share, and the owner revokes it', async () => {
const recordId = await newNote('dsm control no source');
const res = await grant(recordId, {});
expect(res.status, await res.clone().text()).toBe(201);
const share = await res.json() as { id: string; source: string };
expect(share.source).toBe('manual');
const rows = await sharesOn(recordId);
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ source: 'manual', recipient_id: recipientId });
organizationId = rows[0].organization_id ?? undefined;

const revoke = await stack.apiAs(ownerToken, 'DELETE', `/data/${OBJECT}/${recordId}/shares/${share.id}`);
expect(revoke.status, await revoke.clone().text()).toBe(204);
expect(await sharesOn(recordId)).toHaveLength(0);
});

it("CONTROL: an explicit 'manual' source is granted as a manual share", async () => {
const recordId = await newNote('dsm control manual');
const res = await grant(recordId, { source: 'manual' });
expect(res.status, await res.clone().text()).toBe(201);
const rows = await sharesOn(recordId);
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ source: 'manual', source_id: null });
});

it('CONTROL: the system context still writes a rule share, and its revoke through the door is still CONFLICT', async () => {
const recordId = await newNote('dsm control system rule share');
const share = await sharing.grant(
{ object: OBJECT, recordId, recipientId, accessLevel: 'read', source: 'rule', sourceId: 'srule_dsm' },
{ ...SYS, ...(organizationId ? { tenantId: organizationId } : {}) } as ExecutionContext,
);
const rows = await sharesOn(recordId);
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ source: 'rule', source_id: 'srule_dsm' });

const revoke = await stack.apiAs(ownerToken, 'DELETE', `/data/${OBJECT}/${recordId}/shares/${share.id}`);
const body = await revoke.json() as { error?: { code?: string } };
expect(revoke.status, JSON.stringify(body)).toBe(409);
expect(body.error?.code).toBe('CONFLICT');
expect(await sharesOn(recordId)).toHaveLength(1);
});

it('the generic data door on sys_record_share refuses the caller\'s create and writes no share row', async () => {
const recordId = await newNote('dsm generic door');
const res = await stack.apiAs(ownerToken, 'POST', '/data/sys_record_share', {
object_name: OBJECT, record_id: recordId, recipient_type: 'user', recipient_id: recipientId,
access_level: 'read', source: 'rule', source_id: 'srule_dsm',
});
const text = await res.text();
// `enable.apiMethods` on `sys_record_share` grants no create (ADR-0103).
expect(res.status, text).toBe(405);
expect(text).toContain('OBJECT_API_METHOD_NOT_ALLOWED');
expect(await sharesOn(recordId)).toHaveLength(0);
});
});
1 change: 1 addition & 0 deletions packages/qa/dogfood/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ import {
// Files proven eligible for the worker-shared plain showcase stack.
const SHARED_SHOWCASE = [
'test/create-caller-id-collision.dogfood.test.ts',
'test/direct-share-grant-is-manual.dogfood.test.ts',
'test/form-self-auth.dogfood.test.ts',
'test/showcase-agent-intersection.dogfood.test.ts',
'test/showcase-agent-scope-ceiling.dogfood.test.ts',
Expand Down
Loading