Skip to content

Commit e2657fe

Browse files
committed
feat(runtime): the permission-set clone door lands "new similar" in a writable target package
A copy of a packaged set with no target lands in the source package's paired <X>.custom, ensured through the ensure door; a given target must be installed, writable and reach the set's objects (the shared new-similar target check); an environment-authored source copies environment-wide. Claude-Session: https://claude.ai/code/session_01FEkQ5khiLzZmecWFfjSZLc Co-authored-by: Claude <noreply@anthropic.com>
1 parent cd065d3 commit e2657fe

5 files changed

Lines changed: 425 additions & 32 deletions

File tree

‎packages/qa/dogfood/test/permission-set-clone-door.dogfood.test.ts‎

Lines changed: 109 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,15 @@
1616
// - the copy GRANTS: a holder of it resolves its object grants;
1717
// - the source is read from the catalog, not from a `sys_permission_set` row:
1818
// the source's rows are removed first, and the clone still lands;
19-
// - a caller without `manage_metadata` is refused 403 and nothing is saved.
19+
// - a caller without `manage_metadata` is refused 403 and nothing is saved;
20+
// - [ADR-0146 D3/D6] "new similar": a copy of a PACKAGED set with no target
21+
// lands in the source package's paired `<X>.custom`, created by N-13's
22+
// ensure door on the first copy and reused on the next — the stored row
23+
// bound to the pair, the item itself naming no package — and is granted
24+
// through a position AND a direct assignment by its bare name; a given
25+
// target is judged (writable and in closure lands, read-only / unknown /
26+
// out-of-closure are refused with no row); an environment-authored source
27+
// still copies environment-wide.
2028

2129
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
2230
import { resolveUserAuthzGrants, securityCatalogReaderOf } from '@objectstack/core';
@@ -34,6 +42,12 @@ const DEFAULT_COPY = 'my_member_default';
3442
const MEMBER_EMAIL = 'clone.member@example.com';
3543
const HOLDER_EMAIL = 'clone.holder@example.com';
3644
const COPY_POSITION = 'clone_door_position';
45+
/** The showcase's manifest id, and its paired customization package (ADR-0146 D3). */
46+
const SHOWCASE = 'com.example.showcase';
47+
const SHOWCASE_PAIR = `${SHOWCASE}.custom`;
48+
/** A Studio-created writable package that declares the showcase, and one that declares nothing. */
49+
const IN_CLOSURE = 'com.acme.clone-in-closure';
50+
const OUT_OF_CLOSURE = 'com.acme.clone-out-of-closure';
3751

3852
interface Engine {
3953
find(object: string, options?: unknown): Promise<Array<Record<string, unknown>>>;
@@ -82,17 +96,35 @@ describe('the permission-set clone door, on a booted showcase', () => {
8296
// stage 8 retired the `sys_permission_set` row object.
8397
expect(ql.getObject?.('sys_permission_set')).toBeFalsy();
8498

99+
// Anti-vacuity for the landing: the source is the showcase's, and no
100+
// pair exists before the first copy.
101+
expect(source?.packageId).toBe(SHOWCASE);
102+
expect((await stack.apiAs(token, 'GET', `/packages/${SHOWCASE_PAIR}`)).status).toBe(404);
103+
85104
const res = await clone(token, DELEGATE_SET, { name: DELEGATE_COPY, label: 'My Field Ops Delegate' });
86105
const text = await res.clone().text();
87106
expect(res.status, text).toBe(200);
88-
const data = JSON.parse(text).data as { permissionSet: Record<string, unknown>; notice: string };
107+
const data = JSON.parse(text).data as { permissionSet: Record<string, unknown>; package: string | null; notice: string };
89108
expect(data.permissionSet.name).toBe(DELEGATE_COPY);
90109
expect(data.permissionSet).not.toHaveProperty('adminScope');
110+
expect(data.permissionSet).not.toHaveProperty('packageId');
91111
expect(data.notice).toContain('adminScope');
112+
// [ADR-0146 D3/D6] The copy landed in the showcase's pair, which the
113+
// ensure door created for it.
114+
expect(data.package).toBe(SHOWCASE_PAIR);
115+
expect(data.notice).toContain(`'${SHOWCASE_PAIR}'`);
116+
const pair = await stack.apiAs(token, 'GET', `/packages/${SHOWCASE_PAIR}`);
117+
expect(pair.status, await pair.clone().text()).toBe(200);
118+
119+
// The stored row is bound to the pair (its `package_id`), and the item
120+
// names no package of its own.
121+
const rows = await ql.find('sys_metadata', { where: { type: 'permission', name: DELEGATE_COPY }, context: SYSTEM_CTX });
122+
expect(rows.map((r) => r.package_id)).toEqual([SHOWCASE_PAIR]);
123+
expect(JSON.parse(String(rows[0].metadata))).not.toHaveProperty('packageId');
92124

93125
const copy = await reader!.resolve('permission', DELEGATE_COPY);
94126
expect(copy?.name, 'the copy does not resolve through the catalog').toBe(DELEGATE_COPY);
95-
expect(copy?.packageId).toBeUndefined();
127+
expect(copy?.packageId).toBe(SHOWCASE_PAIR);
96128
expect(copy?.definition).not.toHaveProperty('adminScope');
97129
expect(copy?.definition.label).toBe('My Field Ops Delegate');
98130
// The facets came across whole.
@@ -106,9 +138,16 @@ describe('the permission-set clone door, on a booted showcase', () => {
106138

107139
const res = await clone(token, DEFAULT_SET, { name: DEFAULT_COPY, label: 'My Member Default' });
108140
expect(res.status, await res.clone().text()).toBe(200);
141+
// The second copy REUSES the pair the first created: one pair, the same id.
142+
expect(((await res.json()) as any).data.package).toBe(SHOWCASE_PAIR);
143+
const listed = ((await (await stack.apiAs(token, 'GET', '/packages')).json()) as any).data;
144+
const pairs = (Array.isArray(listed) ? listed : listed?.packages ?? [])
145+
.filter((p: any) => (p?.manifest?.id ?? p?.id) === SHOWCASE_PAIR);
146+
expect(pairs).toHaveLength(1);
109147

110148
const copy = await reader.resolve('permission', DEFAULT_COPY);
111149
expect(copy?.name).toBe(DEFAULT_COPY);
150+
expect(copy?.packageId).toBe(SHOWCASE_PAIR);
112151
expect(copy?.definition.isDefault === undefined || copy?.definition.isDefault === false).toBe(true);
113152
expect(copy?.definition.objects).toEqual(source!.definition.objects);
114153

@@ -131,6 +170,73 @@ describe('the permission-set clone door, on a booted showcase', () => {
131170
expect(grants.permissions).toContain(DEFAULT_COPY);
132171
});
133172

173+
it('a copy in the pair is granted through a direct assignment too, by its bare name', async () => {
174+
const email = 'clone.direct@example.com';
175+
await stack.signUp(email);
176+
const [user] = await ql.find('sys_user', { where: { email }, limit: 1, context: SYSTEM_CTX });
177+
expect(user?.id, `no sys_user row for ${email}`).toBeTruthy();
178+
const tenantId = await sessionOrgOf(stack);
179+
// Anti-vacuity: the user holds no copy before the assignment.
180+
const before = await resolveUserAuthzGrants(ql as never, String(user.id), { tenantId });
181+
expect(before.permissions).not.toContain(DELEGATE_COPY);
182+
await ql.insert(
183+
'sys_user_permission_set',
184+
{ id: 'ups_clone_door_direct', user_id: String(user.id), permission_set: DELEGATE_COPY },
185+
{ context: SYSTEM_CTX },
186+
);
187+
const after = await resolveUserAuthzGrants(ql as never, String(user.id), { tenantId });
188+
expect(after.permissions).toContain(DELEGATE_COPY);
189+
});
190+
191+
it('a given writable target inside the closure lands there; read-only, unknown and out-of-closure targets are refused with no row', async () => {
192+
const reader = securityCatalogReaderOf(ql)!;
193+
for (const [id, namespace, dependencies] of [
194+
[IN_CLOSURE, 'clone_in', { [SHOWCASE]: '*' }],
195+
[OUT_OF_CLOSURE, 'clone_out', {}],
196+
] as const) {
197+
const created = await stack.apiAs(token, 'POST', '/packages', {
198+
manifest: { id, name: id, version: '0.1.0', type: 'app', namespace, dependencies },
199+
});
200+
expect(created.status, await created.clone().text()).toBe(201);
201+
}
202+
203+
const landed = await clone(token, DEFAULT_SET, { name: 'in_closure_copy', label: 'In Closure', package: IN_CLOSURE });
204+
expect(landed.status, await landed.clone().text()).toBe(200);
205+
expect(((await landed.json()) as any).data.package).toBe(IN_CLOSURE);
206+
expect((await reader.resolve('permission', 'in_closure_copy'))?.packageId).toBe(IN_CLOSURE);
207+
208+
const refused: Array<[string, string, number, string]> = [
209+
['read_only_copy', SHOWCASE, 422, 'WRITABLE_PACKAGE_REQUIRED'],
210+
['unknown_copy', 'com.acme.no_such_package', 422, 'WRITABLE_PACKAGE_REQUIRED'],
211+
['out_closure_copy', OUT_OF_CLOSURE, 409, 'RESOURCE_CONFLICT'],
212+
];
213+
for (const [name, target, status, code] of refused) {
214+
const res = await clone(token, DEFAULT_SET, { name, label: 'X', package: target });
215+
const text = await res.clone().text();
216+
expect(res.status, `${target}: ${text}`).toBe(status);
217+
expect(((await res.json()) as any).error?.code, target).toBe(code);
218+
expect(await reader.resolve('permission', name), target).toBeUndefined();
219+
const rows = await ql.find('sys_metadata', { where: { type: 'permission', name }, context: SYSTEM_CTX });
220+
expect(rows, target).toEqual([]);
221+
}
222+
});
223+
224+
it('CONTROL — an environment-authored source still copies environment-wide, with no package', async () => {
225+
const saved = await stack.apiAs(token, 'PUT', '/meta/permission/env_authored_source', {
226+
name: 'env_authored_source', label: 'Env Authored', objects: { showcase_task: { allowRead: true } },
227+
});
228+
expect(saved.status, await saved.clone().text()).toBe(200);
229+
const source = await securityCatalogReaderOf(ql)!.resolve('permission', 'env_authored_source');
230+
expect(source?.packageId, 'the control source is packaged').toBeUndefined();
231+
232+
const res = await clone(token, 'env_authored_source', { name: 'env_authored_copy', label: 'Env Authored Copy' });
233+
expect(res.status, await res.clone().text()).toBe(200);
234+
expect(((await res.json()) as any).data.package).toBeNull();
235+
expect((await securityCatalogReaderOf(ql)!.resolve('permission', 'env_authored_copy'))?.packageId).toBeUndefined();
236+
const rows = await ql.find('sys_metadata', { where: { type: 'permission', name: 'env_authored_copy' }, context: SYSTEM_CTX });
237+
expect(rows.map((r) => r.package_id ?? null)).toEqual([null]);
238+
});
239+
134240
it('a taken name is 409, an unknown source 404, a bad name 400', async () => {
135241
const taken = await clone(token, DEFAULT_SET, { name: DELEGATE_SET, label: 'X' });
136242
expect(taken.status, await taken.clone().text()).toBe(409);

‎packages/runtime/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
"@objectstack/driver-sql": "workspace:*",
4545
"@objectstack/driver-sqlite-wasm": "workspace:*",
4646
"@objectstack/formula": "workspace:*",
47+
"@objectstack/lint": "workspace:*",
4748
"@objectstack/metadata": "workspace:*",
4849
"@objectstack/objectql": "workspace:*",
4950
"@objectstack/metadata-protocol": "workspace:*",
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0146 D3/D6] THE ONE CHECK OF A "NEW SIMILAR" DOOR'S GIVEN TARGET
5+
* PACKAGE — the permission-set clone door (`./permission-set-clone.ts`) and
6+
* the flow clone door ask it; ⛔ no door spells its own.
7+
*
8+
* A "new similar" copy is a new item of a package the customer can author
9+
* into. When the caller names that package (`package` in the door's body),
10+
* the target must be:
11+
*
12+
* 1. **installed and writable** — an id the package registry holds, and
13+
* writable by ADR-0070 D2's one predicate (`isWritablePackage`,
14+
* `@objectstack/metadata-protocol`). Unknown and read-only are one
15+
* refusal, `422 WRITABLE_PACKAGE_REQUIRED`, the save door's own code for
16+
* both: `isWritablePackage` alone answers "writable" for a bare id no
17+
* registry holds (an ADR-0048 authoring workspace), and a copy must land
18+
* in a package that exists, so installation is asked first;
19+
* 2. **able to reach what the copy references** — its dependency closure
20+
* (`resolvePackageClosure`, `@objectstack/lint/runtime`: the one walk the
21+
* save gate and Studio's pickers use) holds the source's package, and,
22+
* when the door names the objects the copy grants on, every one of them
23+
* survives the save gate's own closure predicate
24+
* (`narrowObjectsToPackageClosure`: a platform/system object, an
25+
* unpackaged one, or one owned inside the closure). Otherwise
26+
* `409 RESOURCE_CONFLICT`, naming what is out of reach and the remedy (a
27+
* declared dependency).
28+
*
29+
* Pure over the engine's registry: it writes nothing and resolves no default
30+
* target — each door decides its own default (the paired `<X>.custom`
31+
* through N-13's ensure door) and asks this only of a target its caller gave.
32+
*/
33+
34+
import { narrowObjectsToPackageClosure, resolvePackageClosure } from '@objectstack/lint/runtime';
35+
import { isWritablePackage } from '@objectstack/metadata-protocol';
36+
37+
/** The ADR-0146 record the refusals point at. */
38+
const NEW_SIMILAR_TARGET_DOCS = 'docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md';
39+
40+
/** What a door asks about its caller's target. */
41+
export interface NewSimilarTargetRequest {
42+
/** The package the caller named. */
43+
readonly target: string;
44+
/** The package that ships the source, when it has one (an environment-authored source has none). */
45+
readonly sourcePackageId?: string;
46+
/** The source, in words, for the sentences: `permission set 'crm_sales_rep'`, `flow 'x'`. */
47+
readonly subject: string;
48+
/**
49+
* The objects the copy grants on or reads, when the door can name them
50+
* from the item's own declaration; each must be reachable from the target.
51+
*/
52+
readonly objects?: readonly string[];
53+
}
54+
55+
/** The engine surface this check reads — the ObjectQL engine satisfies it as it stands. */
56+
interface TargetEngine {
57+
manifests?: { has?(id: string): boolean };
58+
registry?: {
59+
getPackage?(id: string): { manifest?: unknown } | undefined;
60+
getObject?(name: string): unknown;
61+
getObjectOwner?(name: string): { packageId?: string } | undefined;
62+
};
63+
}
64+
65+
function refusal(status: number, code: string, message: string, packageId: string): Error {
66+
return Object.assign(new Error(message), {
67+
status,
68+
statusCode: status,
69+
code,
70+
details: { code, packageId, docs: NEW_SIMILAR_TARGET_DOCS },
71+
});
72+
}
73+
74+
/**
75+
* Why `request.target` cannot take the copy, as an ADR-0112 error (status +
76+
* code + `packageId` + `docs`), or `undefined` when it can.
77+
*/
78+
export function newSimilarTargetRefusal(engine: unknown, request: NewSimilarTargetRequest): Error | undefined {
79+
const { target, sourcePackageId, subject } = request;
80+
const e = engine as TargetEngine | null | undefined;
81+
const registry = e?.registry;
82+
const getPackage = (id: string) => registry?.getPackage?.call(registry, id);
83+
84+
if (!getPackage(target) || !isWritablePackage(engine, target)) {
85+
const installed = getPackage(target) !== undefined;
86+
return refusal(
87+
422,
88+
'WRITABLE_PACKAGE_REQUIRED',
89+
`Cannot save the copy of ${subject} in package '${target}': `
90+
+ (installed
91+
? 'it is read-only (provided by code or an installed app), and a copy is a new item of a package you can author into. '
92+
: 'no package with that id is installed. ')
93+
+ 'Name an installed, writable package, or leave `package` out to save the copy in the paired customization '
94+
+ 'package of the package the original came from (ADR-0146 D3).',
95+
target,
96+
);
97+
}
98+
99+
const closure = resolvePackageClosure(target, (id) => getPackage(id));
100+
const reachable = new Set<string>(closure ? [closure.packageId, ...closure.dependencies] : [target]);
101+
const outOfReach: string[] = [];
102+
if (sourcePackageId !== undefined && !reachable.has(sourcePackageId)) {
103+
outOfReach.push(`the package '${sourcePackageId}' the original comes from`);
104+
}
105+
if (request.objects && request.objects.length > 0) {
106+
const entries: Array<Record<string, unknown>> = [];
107+
for (const name of request.objects) {
108+
const object = registry?.getObject?.call(registry, name) as Record<string, unknown> | undefined;
109+
// An object no registry holds is the save's to judge, not this check's.
110+
if (!object) continue;
111+
entries.push({ name, isSystem: object.isSystem, _packageId: registry?.getObjectOwner?.call(registry, name)?.packageId });
112+
}
113+
const kept = new Set(narrowObjectsToPackageClosure(entries, closure));
114+
const dropped = entries.filter((entry) => !kept.has(entry));
115+
if (dropped.length > 0) {
116+
outOfReach.push(dropped.length === 1
117+
? `object '${String(dropped[0].name)}' (package '${String(dropped[0]._packageId)}')`
118+
: `objects ${dropped.map((d) => `'${String(d.name)}' (package '${String(d._packageId)}')`).join(', ')}`);
119+
}
120+
}
121+
if (outOfReach.length === 0) return undefined;
122+
return refusal(
123+
409,
124+
'RESOURCE_CONFLICT',
125+
`Cannot save the copy of ${subject} in package '${target}': it cannot reach ${outOfReach.join(', and ')}. `
126+
+ `A package references only itself, the packages its manifest declares in \`dependencies\` (and theirs), and `
127+
+ `platform objects. Declare the dependency on '${target}', name a package that already declares it, or leave `
128+
+ '`package` out to save the copy in the paired customization package of the package the original came from '
129+
+ '(ADR-0146 D3).',
130+
target,
131+
);
132+
}

0 commit comments

Comments
 (0)