Skip to content

Commit fdfcc7a

Browse files
feat(spec, plugin-sharing): ownership-queue reads take the caller package, so a declared rule's queue recipient resolves by ADR-0150 D3 (#31789)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9TtV9zn69iQ2y6yezQxLz2i)_ Fixes #31734 Clause-②: yes (widening); narrowing per ADR-0150 D3 declared below Metadata-protocol: none Narrowing (ADR-0150 D3): a declared sharing rule whose package P depends on a disabled package D, where an unrelated package U declares a queue of the same name. Before (main `43fb4822`): the rule granted to U's queue members, silently. After: the recipient is refused, `outside-closure`, naming U, logged once at `warn` (D3 never reaches U, and a disabled package holds nothing for this read); U's members gain no grant, grants the rule already holds are kept, as for any refused recipient. Pin: `refuses when the holder the caller reaches is disabled, naming the unrelated holder as outside the closure — never serving it, never silent` (ablations A4–A6). First-party: 0 (no first-party package declares a queue). Seat 3 ruled it the D3 answer. ## 维护者速读 - 改了什么:所有权队列服务契约(`IOwnershipQueueService`)的三个按队列名读取的方法(`resolveQueue`、`expandMembers`、`isMember`)加了一个可选的「调用方软件包」参数。共享插件在读「声明的共享规则」的队列接收方时,把规则所在的包传进去,队列就从这个包出发解析:本包的队列,否则它声明依赖的包里唯一持有者,否则拒绝并列出全部候选。不传参数时与今天完全一样。 - 为什么改:E4(#31728)落地时契约里没有调用方,只能整环境解析,所以「规则的依赖包和一个无关包都有同名队列」会被拒绝。这比 ADR-0150 D3 更严。本卡把这半补上(专题 #31527)。 - 风险与回滚:只影响「两个已安装的包声明了同名队列,且某个包里的共享规则把它当接收方」的部署。第一方实测 0 个包声明队列。另有一个边角情形(规则依赖的那个包被禁用、无关包有同名队列):以前悄悄发给了无关包的成员,现在拒绝,日志 warn 一次,点名那个无关包。回滚即 revert 本 PR。 - 先看:`packages/plugins/plugin-sharing/src/package-scoped-declarations.ts` 的 `resolveDeclaredName`(调用方分支);`sharing-rule-service.ts` 的 `queueRecipientCaller`;`packages/spec/src/contracts/ownership-queue-service.ts` 的新可选键。 - 两分钟验证:`pnpm --filter @objectstack/plugin-sharing exec vitest run src/package-scoped-declarations.test.ts`,预期 23 个用例全绿(新增 6 个)。 - 需要你做的:无,席位落地。 ## What changes - **Contract (`@objectstack/spec/contracts`).** `resolveQueue`, `expandMembers` and `isMember` take an optional `callerPackageId` (new exported type `OwnershipQueueCallerPackage` = `string | null`). With a package id the name resolves from that package (ADR-0150 D3). Omitted, `null` or `''`, the read is environment-wide, as before. `queuesOf` and `hasAnyQueue` name no queue and take none. `declaredQueueNamed` (the activation door's lookup) is unchanged: the door belongs to no package. An implementation written before the key still satisfies the contract (pinned). - **Resolution (`package-scoped-declarations.ts`).** `resolveDeclaredName` takes an optional caller package. With one and a registry that carries the package-scoped slice, the answer is objectql's `resolvePackageScopedName` from that package, final: no one-listed-item shortcut (the one listed item may be outside the package's reach), and no first-registered fallback. The listing still bounds it: the resolver is asked over `listedHoldersView(registry)`, which leaves out a holder whose package is disabled (the filter `listItems` applies) and changes nothing else. So a package whose one reachable holder is disabled gets the resolver's own `outside-closure` refusal naming every holder still served, never the disabled holder's item and never silence. Without a caller package nothing changes. - **Queue service (`ownership-queue-service.ts`).** The three reads pass `callerPackageId` to that resolution. Refusals answer as E4's do: `null` / `[]` / `false`, or under `onFailedRead: 'refuse'` a `PackageScopedNameRefusedError` (`409 RESOURCE_CONFLICT`, every candidate named), reported once per name and caller. - **Rule service (`sharing-rule-service.ts`).** `assertQueueRecipientReachable` becomes `queueRecipientCaller`: the same P-side check (now over the same `listedHoldersView`), which still throws and reports its refusal first, and then it hands the rule's package to `isMember` / `expandMembers`. The check stays ahead of the read on purpose, so a queue service written before the key (environment-wide) can never serve a holder outside P's reach. New `queueRecipientPackageOf(rule)` answers the rule's package for a look-through that grants nothing. - **BU look-through (`sharing-plugin.ts`).** "Does this queue recipient read the BU tree?" now resolves the rule's queue from the rule's package, so it reads the queue the grants are read from. - **Position look-through (`queuesNaming`).** It reads every declared holder's specifications, not only the names an environment-wide read serves. Without this, a rule served by D's `q` (a name U also declares) would not be re-evaluated when a position moves in D's queue, and its grants would go stale. Including a name more often only re-evaluates a rule, which then answers as before. - Changeset: patch for `@objectstack/spec` and `@objectstack/plugin-sharing`, with both declaration lines. ## Step 0: every implementer and caller of the contract Measured at `43fb4822` (main with E4). | Site | Method | Caller package after this PR | |:--|:--|:--| | plugin-sharing `OwnershipQueueService` (the one registered implementation) | implements all | reads it | | spec `ownership-queue-failed-read.pin.test.ts` `legacy` double | implements, no key | compiles unchanged (pinned) | | plugin-sharing `sharing-rule-service.ts` (rule recompute, per-user pass) | `expandMembers`, `isMember` | **the declared rule's package** | | plugin-sharing `sharing-plugin.ts` (BU-tree look-through) | `resolveQueue` | **the declared rule's package** | | plugin-sharing `sharing-service.ts` (sitting-record access path) | `queuesOf`, `isMember` | none (no package asks) | | plugin-security `authz-middleware`, `explain-access` | `isMember` | none | | plugin-security `ownership-queue-gate.ts`, `kernel-queue-membership.ts` | `resolveQueue`, `queuesOf` | none | | plugin-hono-server `current-user-endpoints.ts` | `hasAnyQueue` | none (takes no name) | | runtime `catalog-activation.ts` (activation door) | `declaredQueueNamed` | none (unchanged method) | | objectql `assignment-rules.ts` (assignment pool) | `resolveQueue`, `expandMembers` | none: see Acceptance notes | | plugin-approvals `approval-service.ts` (approver slate) | `expandMembers` | none: see Acceptance notes | Every caller that passes no key compiles and answers as before. Test doubles in objectql, plugin-approvals and plugin-security are untouched. ## Tests New top-level `describe` in the E4 harness `src/package-scoped-declarations.test.ts` (6 cases, real `SchemaRegistry`): - P = ALPHA depends on D = BETA; U = GAMMA is unrelated; BETA and GAMMA each declare queue `support`. From ALPHA, `resolveQueue` answers BETA's queue, `expandMembers` answers `['u_beta']` (also under `refuse`), `isMember` is `true` for `u_beta` and `false` for `u_gamma`. **Red on main.** - The declared rule in ALPHA naming `support`: the standing grant to `u_beta` is still desired (`revokeRuleGrantsForRetiredRecipients` returns `0`). **Red on main** (main throws the two-holder refusal). - ALPHA depends on BETA and GAMMA, both declare `support`: refused, `ambiguous-in-closure`, candidates BETA and GAMMA, `409 RESOURCE_CONFLICT` under `refuse`, nothing under `nobody`. - No caller package (`undefined`, `null`, `''`), same fixture as the first case: refused environment-wide naming BETA and GAMMA, exactly as main. - BETA disabled: from ALPHA `resolveQueue` is `null` and `expandMembers` `[]`; under `refuse` a `409` `outside-closure` refusal naming GAMMA; the queue service warns once naming GAMMA; the declared rule's recompute throws the same refusal and the rule service warns naming GAMMA. **Red on main** (main serves GAMMA's members, silently). - `queuesNaming('position', …)` finds `support` from either holder's position. **Red on main.** Forced test change: `packages/spec/src/contracts/ownership-queue-failed-read.pin.test.ts` pinned the exact option keys (`_ExpandOptionKeys`, `_IsMemberOptionKeys`); both now include `callerPackageId`. The file gains a second `describe` with the new key's type pins. No other existing test was edited. ## Acceptance notes - **Claim's "only the D-and-U case moves".** Measured by running the new block against main's plugin source (`git restore --source=43fb4822` on the four source files, then restored, `git diff HEAD` empty): 5 of the 6 new cases are red on main, 18 of 23 in the file green. The D-and-U case moves from refused to resolved, as the card asks. Two other cases also move, and both are declared here for the seat: - **A disabled dependency.** P depends on D, D is disabled, U holds the same queue name. Main serves U's queue to P's rule, silently (the P-side check passes through D, then the environment-wide listing sees only U). This PR refuses it, naming U as outside P's closure, and reports it. That is a narrowing of a wrong answer, first-party count 0 (no first-party package declares a queue). Seat 3 accepted it as the D3 answer; the epic seat asked that it be reported, naming U; declared on the `Narrowing` line above and in the changeset. - **The position look-through.** It now includes names two packages declare. A rule naming such a name re-evaluates on a position write; for a rule with no package that re-evaluation answers the refusal it already answers on every other recompute (its grants are kept and it warns), so the visible difference is that warning on one more path. - The two-holders-in-closure case refuses on both trees; only the refusal's vocabulary moves (`ambiguous-in-environment` with no caller on main, `ambiguous-in-closure` naming ALPHA here). Same candidates, same `409`. - **Other package-written queue references.** A declared assignment rule's queue (objectql `assignment-rules.ts`) and an approval step's queue (plugin-approvals) are also written inside a package and still read environment-wide. That is stricter than D3, never looser, the same interim E4 accepted for this card. Outside this card's file surface; carrier: epic #31527 seat. - **New public name** `OwnershipQueueCallerPackage` and the option key `callerPackageId` (the resolver's own `PackageScopedQuery` key). The seat's call. ## Verification Head `f9c4e48b`. Source last changed at `d1d77686` (the listed-holders view and the disabled-dependency refusal); `f9c4e48b` only rewords the changeset, and `check-adr-0087-registration`, `check-changeset-no-major`, `check-empty-changeset`, `check:issue-citations`, `check:nul-bytes` and `check:doc-authoring` re-ran exit 0 on it. - On `d1d77686`: `pnpm --filter @objectstack/plugin-sharing test` (under the lock): Test Files 72 passed (72), Tests 1493 passed (1493). New block 6/6; harness file 23/23. `typecheck` exit 0. Root `eslint --no-inline-config packages/plugins/plugin-sharing/src` exit 0; `packages/spec/src/contracts` exit 0 (on `20a19d69`, unchanged since). - `@objectstack/spec`: `typecheck` exit 0; `check:test-typecheck` OK (52 files / 240 errors / 131 signatures held, unchanged); contract pin file 2/2; `check:generated` after `--fix`: `api-surface` and `export-origins` regenerated (`+OwnershipQueueCallerPackage`, 1 added, 0 breaking). - Contract consumers (a spec contract changed): `typecheck` exit 0 for `@objectstack/objectql`, `plugin-approvals`, `plugin-security`, `plugin-hono-server` and `runtime`; their queue suites green: objectql `ownership-queue.test.ts` 41/41, plugin-security `kernel-queue-membership` + `ownership-queue-gate` 46/46, plugin-approvals `approval-service.test.ts` 463/463. - `dispatch-gates --ran` on `d1d77686` (re-derived; a full `turbo run build --filter=./packages/**` ran first on `20a19d69`, lock VERDICT exit 0): 94 derived, 94 run, 0 NOT-MEASURED, 0 UNRUN, every one exit 0. Also 94/94 exit 0 on `20a19d69`. - Dogfood, full battery on `20a19d69` under the lock (not owed: no `!` and no narrowing arm): Test Files 440 passed, 3 skipped (443); Tests 3652 passed, 41 skipped (3693); VERDICT command-exit 0. Not re-run on `d1d77686`: the only behaviour that moved since is the disabled-dependency refusal, which no first-party package can reach (0 queues declared). <details><summary>Ablations: five legs, each red, each restored (scripts/ablation-replace.mjs)</summary> plugin-sharing tests import its source directly; no dist leg. Each leg: anchor 1 to 0, blob changed, run red, restored with blob == HEAD and `git diff HEAD` empty. - A1, the caller-package refusal answered as the first listed holder (`resolveDeclaredName`): 1 red, `refuses when the caller's closure reaches two holders, naming both`. - (A2, run on `20a19d69` against the earlier silent not-found, is superseded: that code is gone.) - A3, the no-caller refusal answered as the first listed holder: 9 red, the 8 E4 `two holders` pins and `reads environment-wide without a caller package …`. - On `d1d77686`, for the epic seat's condition (the disabled-dependency refusal is reported, naming U): - A4, the caller-package refusal silenced (answered `not-found`): 2 red, `refuses when the caller's closure reaches two holders …` and `refuses when the holder the caller reaches is disabled, naming the unrelated holder …`. - A5, `listedHoldersView` unfiltered (a disabled holder counted): 1 red, the disabled-dependency pin (the disabled holder's queue served). - A6, the rule service's own check over the raw registry instead of the view: 1 red, the same pin (its warning naming GAMMA missing). That is the guard that holds for a queue service written before the key. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: domain:server#3 · os-steve · session_01ADHkmQs1r4citFGcqUhPZE --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6be71ab commit fdfcc7a

10 files changed

Lines changed: 479 additions & 44 deletions
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/plugin-sharing': patch
4+
---
5+
6+
feat(spec, plugin-sharing): the ownership-queue reads take an optional caller package, so a declared sharing rule's queue recipient resolves from the rule's package
7+
8+
Clause-②: yes (widening); narrowing per ADR-0150 D3 declared below
9+
Metadata-protocol: none
10+
11+
`IOwnershipQueueService.resolveQueue`, `expandMembers` and `isMember` (`@objectstack/spec/contracts`) take an optional `callerPackageId` (new type `OwnershipQueueCallerPackage`, `string | null`). With it, a queue name resolves from that package (ADR-0150 D3): the package's own declared queue, else the unique holder in its declared dependency closure plus `sys`, else a refusal naming every candidate. Without it, the read is environment-wide, exactly as before. An implementation written before the key still satisfies the contract.
12+
13+
`@objectstack/plugin-sharing` implements it and passes it where a package wrote the queue name: a declared sharing rule's queue recipient is now read from the rule's package. A queue name the rule's package reaches through one declared dependency is served even when an unrelated package also declares a queue of that name; before, that name was refused because two packages declared it. Every other answer is unchanged: no caller package, one holder, two holders in the package's reach (refused, naming both), a holder only outside the reach (refused), and an organization's own `sys_queue` row.
14+
15+
Narrowing, per ADR-0150 D3: take a declared rule whose package depends on a package D that is disabled, where an unrelated package U declares a queue of the same name. That rule used to grant to U's queue members. Its queue recipient is now refused. The refusal is logged once at `warn` and names U as outside the rule package's dependency closure. U's members gain no grant from it; grants the rule already holds are kept, as for any refused recipient. A disabled package holds no queue for this read, the same population the listing serves. To resolve it, enable D or declare a dependency on the package whose queue you mean. Measured first-party: 0 (no first-party package declares a queue).

‎packages/plugins/plugin-sharing/src/ownership-queue-service.ts‎

Lines changed: 63 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,14 @@
3030
* never answered as the first (or, as `queuesOf` once did, the last) holder
3131
* listed. It stays a declared name: no `sys_queue` row may take it.
3232
*
33+
* A read that names the queue from inside a package — a declared sharing
34+
* rule's queue recipient — passes that package as `callerPackageId` (the
35+
* contract's `OwnershipQueueCallerPackage`), and the name resolves from it
36+
* (ADR-0150 D3): the package's own queue, else the unique holder in its
37+
* declared closure plus `sys`, else a refusal naming every candidate. So a
38+
* name two packages declare resolves for a caller whose closure reaches one of
39+
* them, and is refused for a caller with no package.
40+
*
3341
* ## One expander
3442
*
3543
* {@link OwnershipQueueService.expandMembers} is the function the access path,
@@ -85,6 +93,7 @@
8593

8694
import type {
8795
IOwnershipQueueService,
96+
OwnershipQueueCallerPackage,
8897
OwnershipQueueFailedReadAnswer,
8998
QueueExpansionPurpose,
9099
QueueMemberSpec,
@@ -239,25 +248,36 @@ export class OwnershipQueueService implements IOwnershipQueueService {
239248

240249
// ── The contract ───────────────────────────────────────────────────────────
241250

242-
async resolveQueue(name: string, organizationId: string | null): Promise<ResolvedQueue | null> {
243-
return this.resolve(name, organizationId, false);
251+
async resolveQueue(
252+
name: string,
253+
organizationId: string | null,
254+
options?: { callerPackageId?: OwnershipQueueCallerPackage },
255+
): Promise<ResolvedQueue | null> {
256+
return this.resolve(name, organizationId, false, options?.callerPackageId);
244257
}
245258

246259
/**
247260
* {@link resolveQueue}, with the caller's failed-read answer: under `refuse`
248261
* a failed `sys_queue` or `sys_queue_member` read rejects (a failure naming
249262
* the read, which the public caller wraps in {@link queueReadRefusal})
250-
* instead of resolving nowhere or to no authored members.
263+
* instead of resolving nowhere or to no authored members. `callerPackageId`
264+
* is the package the name is read from, or none (the module header).
251265
*/
252-
private async resolve(name: string, organizationId: string | null, refuse: boolean): Promise<ResolvedQueue | null> {
266+
private async resolve(
267+
name: string,
268+
organizationId: string | null,
269+
refuse: boolean,
270+
callerPackageId?: OwnershipQueueCallerPackage,
271+
): Promise<ResolvedQueue | null> {
253272
const engine = this.engine();
254273
if (!engine || !name) return null;
255-
const answer = this.declaredQueueAnswer(name);
274+
const answer = this.declaredQueueAnswer(name, callerPackageId);
256275
if (answer.status === 'refused') {
257-
// [ADR-0150 D3, child E4] Two packages declare this name: it is neither
258-
// of them, and — a declared name — never an authored row either. Under
259-
// 'refuse' the caller is told so, naming every holder; otherwise it
260-
// resolves nowhere, which for every 'nobody' consumer denies.
276+
// [ADR-0150 D3, child E4] The name names no one queue for this caller
277+
// (two packages declare it, or — read from a package — none in its reach
278+
// does): it is none of them, and — a declared name — never an authored
279+
// row either. Under 'refuse' the caller is told so, naming every holder;
280+
// otherwise it resolves nowhere, which for every 'nobody' consumer denies.
261281
if (refuse) throw new PackageScopedNameRefusedError(answer.refusal);
262282
return null;
263283
}
@@ -293,11 +313,15 @@ export class OwnershipQueueService implements IOwnershipQueueService {
293313
async expandMembers(
294314
name: string,
295315
organizationId: string | null,
296-
options?: { purpose?: QueueExpansionPurpose; onFailedRead?: OwnershipQueueFailedReadAnswer },
316+
options?: {
317+
purpose?: QueueExpansionPurpose;
318+
onFailedRead?: OwnershipQueueFailedReadAnswer;
319+
callerPackageId?: OwnershipQueueCallerPackage;
320+
},
297321
): Promise<string[]> {
298322
const pass = newPass(options?.purpose, options?.onFailedRead);
299323
try {
300-
const queue = await this.resolve(name, organizationId, pass.refuse);
324+
const queue = await this.resolve(name, organizationId, pass.refuse, options?.callerPackageId);
301325
if (!queue) return [];
302326
return await this.expandSpecs(queue.members, organizationId, pass);
303327
} catch (err) {
@@ -312,12 +336,12 @@ export class OwnershipQueueService implements IOwnershipQueueService {
312336
userId: string,
313337
name: string,
314338
organizationId: string | null,
315-
options?: { onFailedRead?: OwnershipQueueFailedReadAnswer },
339+
options?: { onFailedRead?: OwnershipQueueFailedReadAnswer; callerPackageId?: OwnershipQueueCallerPackage },
316340
): Promise<boolean> {
317341
if (!userId) return false;
318342
const pass = newPass('access', options?.onFailedRead);
319343
try {
320-
const queue = await this.resolve(name, organizationId, pass.refuse);
344+
const queue = await this.resolve(name, organizationId, pass.refuse, options?.callerPackageId);
321345
if (!queue) return false;
322346
return await this.specsReachUser(queue.members, userId, organizationId, pass);
323347
} catch (err) {
@@ -390,11 +414,13 @@ export class OwnershipQueueService implements IOwnershipQueueService {
390414
/**
391415
* [ADR-0150 D3/D4, child E4] The declared queue a bare `name` addresses —
392416
* one holder's, `not-found`, or the shared resolver's refusal naming every
393-
* package that declares it (`package-scoped-declarations.ts`). Switched on
394-
* or off: the ledger is read by the caller. A refusal is reported once.
417+
* package that declares it (`package-scoped-declarations.ts`). Read from
418+
* `callerPackageId` when one is given (ADR-0150 D3), else environment-wide.
419+
* Switched on or off: the ledger is read by the caller. A refusal is
420+
* reported once per name and caller.
395421
*/
396-
private declaredQueueAnswer(name: string): DeclaredNameAnswer<DeclaredQueueItem> {
397-
const answer = resolveDeclaredName(this.engine()?.registry, 'queue', name, this.declaredItems());
422+
private declaredQueueAnswer(name: string, callerPackageId?: OwnershipQueueCallerPackage): DeclaredNameAnswer<DeclaredQueueItem> {
423+
const answer = resolveDeclaredName(this.engine()?.registry, 'queue', name, this.declaredItems(), callerPackageId);
398424
if (answer.status === 'refused') reportRefusedDeclaration(this.logger, this.refusedReported, answer.refusal);
399425
return answer;
400426
}
@@ -414,13 +440,20 @@ export class OwnershipQueueService implements IOwnershipQueueService {
414440
* The queues in `organizationId` whose member specifications name one of
415441
* `values` under `kind` — the recompute's look-through from a position, team
416442
* or business-unit write to the queue-recipient sharing rules it moves.
443+
*
444+
* [ADR-0150 D3] Every declared holder's specifications count, not only the
445+
* names an environment-wide read serves: a name two packages declare is
446+
* refused for a caller with no package but resolves for a rule whose
447+
* package reaches one of them, so a position moving in either holder's
448+
* queue re-evaluates the rules naming it. A rule it does not move answers
449+
* as before when re-evaluated.
417450
*/
418451
async queuesNaming(kind: string, values: ReadonlySet<string>, organizationId: string | null): Promise<string[]> {
419452
const engine = this.engine();
420453
if (!engine || values.size === 0) return [];
421454
const out = new Set<string>();
422455
if (kind === 'position') {
423-
for (const q of await this.activeDeclaredQueues()) {
456+
for (const q of await this.switchedOnDeclaredHolders()) {
424457
if (declaredMemberSpecs(q).some((s) => values.has(s.value))) out.add(q.name);
425458
}
426459
}
@@ -605,6 +638,18 @@ export class OwnershipQueueService implements IOwnershipQueueService {
605638
return items.filter((q) => !off.has(q.name));
606639
}
607640

641+
/**
642+
* Every declared queue item switched on, EVERY holder of a name — the
643+
* look-through's population ({@link queuesNaming}). ⛔ Never a resolution:
644+
* nothing is served from it, it only says which names a write may move.
645+
*/
646+
private async switchedOnDeclaredHolders(): Promise<DeclaredQueueItem[]> {
647+
const items = this.declaredItems();
648+
if (items.length === 0) return [];
649+
const off = await this.switchedOff(QUEUE_ACTIVATION_TYPE, [...new Set(items.map((q) => q.name))]);
650+
return items.filter((q) => !off.has(q.name));
651+
}
652+
608653
/**
609654
* The organization's `sys_queue` row named `name`. A failed read resolves
610655
* the name nowhere, logged once — or, under `refuse` (#29604), rejects with

‎packages/plugins/plugin-sharing/src/package-scoped-declarations.test.ts‎

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,3 +357,184 @@ describe('a declared rule’s queue recipient resolves from the rule’s package
357357
expect(await serviceWithGrant('u_alpha').revokeRuleGrantsForRetiredRecipients(rule)).toBe(0);
358358
});
359359
});
360+
361+
describe('a queue read from a caller package resolves by D3 (ADR-0150, the queue contract’s callerPackageId)', () => {
362+
const GAMMA = 'com.acme.gamma';
363+
364+
/** Holders of the two packages' positions, plus GAMMA's, in org_a. */
365+
const tables = (): Record<string, Row[]> => ({
366+
sys_user_position: [
367+
...TABLES().sys_user_position,
368+
{ id: 'up_3', position: 'gamma_agent', user_id: 'u_gamma', organization_id: 'org_a' },
369+
],
370+
});
371+
372+
/** ALPHA's declared rule `share_support`, granting to queue `support`, and its org_a projection. */
373+
const declaredQueueRule = () => {
374+
declare('sharing_rule', ALPHA, {
375+
...sharingRule('share_support', 'unused'),
376+
sharedWith: { type: 'queue', value: 'support' },
377+
});
378+
return {
379+
id: 'share_support',
380+
name: 'share_support',
381+
label: 'share_support',
382+
object_name: 'account',
383+
organization_id: 'org_a',
384+
criteria: { region: 'emea' },
385+
recipient_type: 'queue' as const,
386+
recipient_id: 'support',
387+
access_level: 'read' as const,
388+
active: true,
389+
managed_by: 'package' as const,
390+
};
391+
};
392+
393+
const queueService = () => {
394+
const engine = makeEngine(tables());
395+
return { engine, queues: new OwnershipQueueService({ engine: () => engine as any }) };
396+
};
397+
398+
/**
399+
* ALPHA (the rule's package P) declares a dependency on BETA (D); GAMMA (U)
400+
* is unrelated. BETA and GAMMA each declare queue `support`.
401+
*/
402+
const dependencyAndUnrelated = () => {
403+
registry = new SchemaRegistry();
404+
install(BETA);
405+
install(GAMMA);
406+
install(ALPHA, [BETA]);
407+
declare('queue', BETA, queue('support', 'beta_agent'));
408+
declare('queue', GAMMA, queue('support', 'gamma_agent'));
409+
};
410+
411+
it('resolves to the dependency’s queue, not the unrelated package’s, for every read that takes a name', async () => {
412+
dependencyAndUnrelated();
413+
const { queues } = queueService();
414+
const fromAlpha = { callerPackageId: ALPHA };
415+
expect(await queues.resolveQueue('support', 'org_a', fromAlpha)).toMatchObject({ name: 'support', source: 'declared', packageId: BETA });
416+
expect(await queues.expandMembers('support', 'org_a', fromAlpha)).toEqual(['u_beta']);
417+
expect(await queues.expandMembers('support', 'org_a', { ...fromAlpha, onFailedRead: 'refuse' })).toEqual(['u_beta']);
418+
expect(await queues.isMember('u_beta', 'support', 'org_a', fromAlpha)).toBe(true);
419+
expect(await queues.isMember('u_gamma', 'support', 'org_a', { ...fromAlpha, onFailedRead: 'refuse' })).toBe(false);
420+
});
421+
422+
it('serves the declared rule’s queue recipient from the dependency: its member’s standing grant is still desired', async () => {
423+
dependencyAndUnrelated();
424+
const rule = declaredQueueRule();
425+
const engine = makeEngine({
426+
...tables(),
427+
sys_record_share: [{ id: 'rs_1', source: 'rule', source_id: 'share_support', organization_id: 'org_a', recipient_id: 'u_beta' }],
428+
});
429+
const queues = new OwnershipQueueService({ engine: () => engine as any });
430+
const service = new SharingRuleService({
431+
engine: engine as any,
432+
sharing: {} as any,
433+
declaredRules: createDeclaredSharingRuleSource({ engine: { registry } }),
434+
ownershipQueues: () => queues,
435+
logger: { warn: () => {}, error: () => {} },
436+
});
437+
expect(await service.revokeRuleGrantsForRetiredRecipients(rule)).toBe(0);
438+
expect(await service.queueRecipientPackageOf(rule)).toBe(ALPHA);
439+
});
440+
441+
it('refuses when the caller’s closure reaches two holders, naming both', async () => {
442+
registry = new SchemaRegistry();
443+
install(BETA);
444+
install(GAMMA);
445+
install(ALPHA, [BETA, GAMMA]);
446+
declare('queue', BETA, queue('support', 'beta_agent'));
447+
declare('queue', GAMMA, queue('support', 'gamma_agent'));
448+
const { queues } = queueService();
449+
const fromAlpha = { callerPackageId: ALPHA };
450+
expect(await queues.resolveQueue('support', 'org_a', fromAlpha)).toBeNull();
451+
expect(await queues.expandMembers('support', 'org_a', fromAlpha)).toEqual([]);
452+
expect(await queues.isMember('u_beta', 'support', 'org_a', fromAlpha)).toBe(false);
453+
for (const read of [
454+
() => queues.expandMembers('support', 'org_a', { ...fromAlpha, onFailedRead: 'refuse' }),
455+
() => queues.isMember('u_beta', 'support', 'org_a', { ...fromAlpha, onFailedRead: 'refuse' }),
456+
]) {
457+
const refused = await read().catch((e: unknown) => e);
458+
expect(refused).toBeInstanceOf(PackageScopedNameRefusedError);
459+
expect(refused).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 });
460+
expect((refused as PackageScopedNameRefusedError).refusal).toMatchObject({
461+
reason: 'ambiguous-in-closure',
462+
callerPackageId: ALPHA,
463+
candidates: [
464+
{ kind: 'package', packageId: BETA },
465+
{ kind: 'package', packageId: GAMMA },
466+
],
467+
});
468+
}
469+
});
470+
471+
it('reads environment-wide without a caller package, as before the key: the same two holders are refused', async () => {
472+
dependencyAndUnrelated();
473+
const { queues } = queueService();
474+
for (const options of [undefined, { callerPackageId: null }, { callerPackageId: '' }]) {
475+
expect(await queues.resolveQueue('support', 'org_a', options)).toBeNull();
476+
expect(await queues.expandMembers('support', 'org_a', options ?? undefined)).toEqual([]);
477+
expect(await queues.isMember('u_beta', 'support', 'org_a', options ?? undefined)).toBe(false);
478+
const refused = await queues.expandMembers('support', 'org_a', { ...options, onFailedRead: 'refuse' }).catch((e: unknown) => e);
479+
expect(refused).toBeInstanceOf(PackageScopedNameRefusedError);
480+
expect((refused as PackageScopedNameRefusedError).refusal).toMatchObject({
481+
reason: 'ambiguous-in-environment',
482+
callerPackageId: null,
483+
candidates: [
484+
{ kind: 'package', packageId: BETA },
485+
{ kind: 'package', packageId: GAMMA },
486+
],
487+
});
488+
}
489+
});
490+
491+
it('refuses when the holder the caller reaches is disabled, naming the unrelated holder as outside the closure — never serving it, never silent', async () => {
492+
dependencyAndUnrelated();
493+
registry.disablePackage(BETA);
494+
const { warnings, logger } = logs();
495+
const engine = makeEngine(tables());
496+
const queues = new OwnershipQueueService({ engine: () => engine as any, logger });
497+
const outsideClosure = {
498+
reason: 'outside-closure',
499+
callerPackageId: ALPHA,
500+
candidates: [{ kind: 'package', packageId: GAMMA }],
501+
};
502+
expect(await queues.resolveQueue('support', 'org_a', { callerPackageId: ALPHA })).toBeNull();
503+
expect(await queues.expandMembers('support', 'org_a', { callerPackageId: ALPHA })).toEqual([]);
504+
const refused = await queues.expandMembers('support', 'org_a', { callerPackageId: ALPHA, onFailedRead: 'refuse' }).catch((e: unknown) => e);
505+
expect(refused).toBeInstanceOf(PackageScopedNameRefusedError);
506+
expect(refused).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 });
507+
expect((refused as PackageScopedNameRefusedError).refusal).toMatchObject(outsideClosure);
508+
// Reported, not silent: once, naming the unrelated holder.
509+
expect(warnings).toHaveLength(1);
510+
expect(warnings[0].meta).toMatchObject({ type: 'queue', name: 'support', reason: 'outside-closure', candidates: [GAMMA] });
511+
512+
// The declared rule's recipient: the rule service's own check refuses first
513+
// (it guards a queue service written before the key), naming the same holder.
514+
const rule = declaredQueueRule();
515+
const ruleLogs = logs();
516+
const service = new SharingRuleService({
517+
engine: makeEngine({
518+
...tables(),
519+
sys_record_share: [{ id: 'rs_1', source: 'rule', source_id: 'share_support', organization_id: 'org_a', recipient_id: 'u_gamma' }],
520+
}) as any,
521+
sharing: {} as any,
522+
declaredRules: createDeclaredSharingRuleSource({ engine: { registry } }),
523+
ownershipQueues: () => queues,
524+
logger: { warn: ruleLogs.logger.warn, error: () => {} },
525+
});
526+
const ruleRefused = await service.revokeRuleGrantsForRetiredRecipients(rule).catch((e: unknown) => e);
527+
expect(ruleRefused).toBeInstanceOf(PackageScopedNameRefusedError);
528+
expect((ruleRefused as PackageScopedNameRefusedError).refusal).toMatchObject(outsideClosure);
529+
expect(ruleLogs.warnings.map((w) => w.meta)).toContainEqual(
530+
expect.objectContaining({ type: 'queue', name: 'support', reason: 'outside-closure', candidates: [GAMMA] }),
531+
);
532+
});
533+
534+
it('looks through every holder’s positions, so a position move in the dependency’s queue reaches the rule', async () => {
535+
dependencyAndUnrelated();
536+
const { queues } = queueService();
537+
expect(await queues.queuesNaming('position', new Set(['beta_agent']), 'org_a')).toEqual(['support']);
538+
expect(await queues.queuesNaming('position', new Set(['gamma_agent']), 'org_a')).toEqual(['support']);
539+
});
540+
});

0 commit comments

Comments
 (0)