From a322087f2c80e30feda51cc61634b3183745ef08 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:06:00 +0000 Subject: [PATCH 01/15] fix(metadata-protocol): an exact package read answers that package's own item or none, for every type the exact qualifier does not judge A read naming package X of a doc, view, translation, field, seed, datasource, external_catalog or object_extension that X ships no item of fell through to the registry's getItem, whose last tier is the first composite across packages, so it answered another package's item. The code layers' answer at such an address is now X's own item (the registry's package slot) or nothing (404). The layered read's code layer takes the same rule: it declines the metadata service's copy of another package and reads X's own item or none. So does the credential carry-forward's code-layer read, so a save naming X never carries another package's datasource credential. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .../34247-exact-read-own-item-or-none.md | 24 ++++ .../src/protocol-discovery-and-bases.ts | 16 ++- .../src/protocol-meta-item-reads.ts | 40 ++++++ .../src/protocol-meta-layered-reads.ts | 14 +- .../package-scoped-exact-qualifier.test.ts | 131 +++++++++++++++++- ...meta-disabled-holder-artifact-door.test.ts | 62 +++++++++ 6 files changed, 277 insertions(+), 10 deletions(-) create mode 100644 .changeset/34247-exact-read-own-item-or-none.md diff --git a/.changeset/34247-exact-read-own-item-or-none.md b/.changeset/34247-exact-read-own-item-or-none.md new file mode 100644 index 00000000000..2a4c24f5480 --- /dev/null +++ b/.changeset/34247-exact-read-own-item-or-none.md @@ -0,0 +1,24 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol)!: an exact `?package=X` read of a doc, view or other type the exact qualifier does not judge answers X's own item or 404, never another package's (ADR-0150 D3/D5, red line 2) + +Clause-②: no (narrowing) +Metadata-protocol: none +Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?package=` reads of a holder or of its pair (objectstack-platform SKILL.md, "Customizing an installed package"), which do not move, and never the read of a package that holds no item of the name + + + +**BREAKING** for a caller that reads `?package=X` of a name X ships no item of, for the types the exact qualifier does not judge (`doc`, `view`, `translation`, `field`, `seed`, `datasource`, `external_catalog`, `object_extension`). Measured on the composed artifact rig (the `MetadataPlugin` artifact door plus `AppPlugin`), on the dispatcher and on `RestServer`, in both registration orders: + +- `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME (installed or not) and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now 404. +- `GET /meta/TYPE/NAME/layers?package=X`, same address: was 200 with another package's `code` and `effective`. It is now 404. +- `GET /meta/TYPE/NAME/layers?package=X`, where X and Y ship NAME and Y registered last: was 200 with Y's `code` and `effective` (the metadata service keeps such a type by name alone). It is now X's, as the plain read answers since #34040. +- A save naming package X of a `datasource` with no stored row at X (the credential carry-forward reads the code layer, `readCodeLayerForCarryForward`): carried forward the credential of the package the metadata service kept, or of the first registered holder. It now carries X's own credential, or none when X ships no datasource of the name (the incoming body is kept as sent). Of this family only `datasource` carries a credential, so no other save moves. Path: a save door naming the package (`PUT /meta/datasource/NAME?package=X`), its draft save, and any carry-forward of a body whose credentials the read redacted. + +**Not moved.** A holder's own address, a customization pair's address of its base's item, an item bound to no package (the environment's entry), any read naming no package, `object`, and the covered types (`action`, `hook`, `job`, `sharing_rule`, `queue`, `assignment_rule`), whose exact qualifier already refuses 409 `not-held-by-qualifier`. + +**No migration.** No schema key, stored row or registry slot changes; nothing is rewritten. + +The fix for a caller: address a package that ships the name (or its pair), or read with no package. diff --git a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts index c9185505738..e130d2a13da 100644 --- a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts +++ b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts @@ -37,7 +37,7 @@ import type { SysMetadataRepository } from './sys-metadata-repository.js'; import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL, unrecognisedMetaTypeRefusal } from '@objectstack/spec/shared'; import type { TranslationBundle } from '@objectstack/spec/system'; -import { engineCanRollBack, readAuthoredTranslationLayer } from '@objectstack/core'; +import { engineCanRollBack, isPackageScopedType, readAuthoredTranslationLayer } from '@objectstack/core'; import { restoreTranslatedEchoes } from './protocol-translated-echo.js'; import type { RestoredTranslatedSlot } from './protocol-translated-echo.js'; import { @@ -49,6 +49,7 @@ import { import { pairsOf } from '@objectstack/metadata-core'; import { installedManifestsOfEngine } from './installed-manifests.js'; import { storedBodyForCarryForward } from './protocol-credential-carry-forward.js'; +import { registryAnswerAtAddress, serviceCopyOfAnotherPackage } from './protocol-meta-item-reads.js'; import type { Equal, MetaTypesListing } from './protocol-meta-types-listing.js'; import { HAND_CRAFTED_SCHEMAS, @@ -1121,13 +1122,24 @@ export class ProtocolDiscoveryAndBasesFacet { name: string, packageId: string | null,): Promise { const pkg = packageId ?? undefined; + // [ADR-0150 D3/D5, red line 2] At a package address of a type the + // exact qualifier does not judge, the code layer is that package's + // own item or none, as the by-name read's code steps answer there + // ({@link serviceCopyOfAnotherPackage}, {@link registryAnswerAtAddress}): + // the service keeps such a type by name alone, and a package holding + // no item of the name read another package's first composite, so the + // save carried that package's credential forward. + const address = { type, name, ...(pkg !== undefined ? { packageId: pkg } : {}) }; + const atAddress = pkg !== undefined && !isPackageScopedType(type); const fromService = await host.readItemFromMetadataService(type, name, pkg); - if (fromService.data !== undefined && fromService.data !== null) return fromService.data; + if (fromService.data !== undefined && fromService.data !== null + && !(atAddress && serviceCopyOfAnotherPackage(host, address, fromService.data))) return fromService.data; let item: unknown = host.lookupArtifactItem(type, name, pkg) ?? host.engine.registry.getItem(type, name, pkg); if (item === undefined) { const alt = PLURAL_TO_SINGULAR[type] ?? SINGULAR_TO_PLURAL[type]; if (alt) item = host.engine.registry.getItem(alt, name, pkg); } + if (atAddress) item = registryAnswerAtAddress(host, address, item, undefined, () => true); if (item !== undefined && item !== null) return item; if (fromService.degraded) host.throwMetadataServiceUnavailable(fromService.errors); return undefined; diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index a0d4fe91d97..263bd0a37e8 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -434,6 +434,36 @@ export function serviceCopyOfAnotherPackage( return !isPairOf(served, packageId, installed) && !isPairOf(packageId, served, installed); } +/** + * [ADR-0150 D3/D5, red line 2] The item the code layers (the artifact lookup + * and the registry) answer at an address naming a package (`?package=X`) of + * a type the exact qualifier does not judge: X's own item, or nothing, so the + * read answers 404. Another package's item ({@link serviceCopyOfAnotherPackage}'s + * test, applied to the code layers' answer) is replaced by the registry's + * package slot for X; when X holds no item of the name, nothing is served. + * + * Before, a package that holds no item of the name answered `getItem`'s last + * tier, the first composite across packages: another package's item, under + * X's envelope. Unchanged: an item bound to no package (the environment's + * entry), an item stamped X, a customization pair's item, a stamp the + * registry does not know, and an `object`. + */ +export function registryAnswerAtAddress( + host: Pick, + request: { type: string; name: string; packageId?: string }, + item: unknown, + member: string | undefined, + isWantedMember: (candidate: unknown) => boolean, +): unknown { + if (!request.packageId || item === undefined || item === null) return item; + if (!serviceCopyOfAnotherPackage(host, request, item)) return item; + const scoped = host.engine?.registry as { getPackageScopedItem?(type: string, name: string, packageId: string, member?: string): unknown } | undefined; + const own = typeof scoped?.getPackageScopedItem === 'function' + ? scoped.getPackageScopedItem(request.type, request.name, request.packageId, member) + : undefined; + return own !== undefined && own !== null && isWantedMember(own) ? own : undefined; +} + /** The same item: one object, or (a loader's fresh copy) the same JSON. */ function sameStoredItem(left: unknown, right: unknown): boolean { if (left === right) return true; @@ -1222,6 +1252,9 @@ export async function readMetaItem(host: Pick { expect((await protocol.getMetaItem({ type: 'page', name: 'nothing', packageId: A }))?.item).toBeUndefined(); }); - it('a type outside the nine (view) keeps the prefer-local read', async () => { + it('a type outside the nine (view) keeps the prefer-local read at its holder; [#34247] a package holding none answers nothing (BASE: alpha\'s)', async () => { registry.registerItem('view', { name: 'all', label: 'alpha view' }, 'name' as never, A); - expect(labelOf(await protocol.getMetaItem({ type: 'view', name: 'all', packageId: C }))).toBe('alpha view'); + expect(labelOf(await protocol.getMetaItem({ type: 'view', name: 'all', packageId: A }))).toBe('alpha view'); + expect((await protocol.getMetaItem({ type: 'view', name: 'all', packageId: C }))?.item).toBeUndefined(); }); it('a read naming no package is E8\'s, unchanged', async () => { @@ -394,10 +395,11 @@ describe('fail closed — a registry with no package-scoped resolver refuses wha expect(declaredRefusalMessage(err)).toBe(err.message); }); - it('CONTROL: a type ADR-0150 does not address by package (view) keeps `getItem`\'s read, both ways', async () => { + it('CONTROL: a type ADR-0150 does not address by package (view) keeps `getItem`\'s read, both ways; [#34247] a package holding none answers nothing', async () => { registry.registerItem('view', { name: 'all', label: 'alpha view' }, 'name' as never, A); - expect(labelOf(await sliceless.getMetaItem({ type: 'view', name: 'all', packageId: C }))).toBe('alpha view'); + expect(labelOf(await sliceless.getMetaItem({ type: 'view', name: 'all', packageId: A }))).toBe('alpha view'); expect(labelOf(await sliceless.getMetaItem({ type: 'view', name: 'all' }))).toBe('alpha view'); + expect((await sliceless.getMetaItem({ type: 'view', name: 'all', packageId: C }))?.item).toBeUndefined(); }); it('CONTROL: the same reads on the registry WITH the slice answer as before', async () => { @@ -579,9 +581,10 @@ describe('a covered type the registry reads through `getItem` (seat rulings (a), expect(() => protocol.admitEnvironmentQualifier({ type: 'flow', name: 'local' })).not.toThrow(); }); - it('CONTROL: a type outside the covered set (view) keeps the prefer-local read', async () => { + it('CONTROL: a type outside the covered set (view) keeps the prefer-local read at its holder; [#34247] a package holding none answers nothing', async () => { registry.registerItem('view', { name: 'all', label: 'alpha view' }, 'name' as never, A); - expect(labelOf(await protocol.getMetaItem({ type: 'view', name: 'all', packageId: C }))).toBe('alpha view'); + expect(labelOf(await protocol.getMetaItem({ type: 'view', name: 'all', packageId: A }))).toBe('alpha view'); + expect((await protocol.getMetaItem({ type: 'view', name: 'all', packageId: C }))?.item).toBeUndefined(); }); }); }); @@ -830,6 +833,120 @@ describe('[#34040] the exact read never serves the service\'s copy of another pa }); }); +/** + * [#34247, ADR-0150 D3/D5, red line 2] The exact read of a name the package it + * names holds no item of, for the same family: X's item or 404, never another + * holder's. The step-2 decline above left such an address to the registry's + * `getItem`, whose last tier is the first composite across packages, so + * `?package=gamma` of a doc only alpha and beta ship served one of theirs. + * + * BASE (measured before the fix, here and on the composed artifact rig): + * `?package=` of a package that ships no item of the name answered the first + * registered holder's body, whichever copy the service kept, and with the + * service holding nothing. + */ +describe('[#34247] the exact read of a name the package holds no item of answers nothing, for every type the registry does not read by package', () => { + const OUTSIDE_PINNED = MetadataTypeSchema.options.filter((type) => !(PACKAGE_SCOPED_READ_TYPES as readonly string[]).includes(type) + && !(PACKAGE_SCOPED_TYPES as readonly string[]).includes(type) && !['position', 'capability', 'object'].includes(type)); + /** Judged by the exact qualifier after the layers: its own refusal, unchanged. */ + const COVERED = MetadataTypeSchema.options.filter((type) => !(PACKAGE_SCOPED_READ_TYPES as readonly string[]).includes(type) + && (PACKAGE_SCOPED_TYPES as readonly string[]).includes(type)); + + const shipParsed = (type: string, name: string, packageId: string) => registry.registerItem( + type, + { name, label: `${packageId.split('.').pop()} ${type}`, ...(type === 'action' ? { type: 'url', target: 'https://example.com' } : {}) }, + 'name' as never, + packageId, + ); + /** A protocol whose MetadataService keeps `body` for the name (`undefined`: holds nothing). */ + const servedWith = (body: Record | undefined) => { + const metadata = { + get: vi.fn(async () => body), + getDiagnosed: vi.fn(async () => ({ data: body, degraded: false, errors: [] })), + }; + return new ObjectStackProtocolImplementation(engine as never, () => new Map([['metadata', metadata]])); + }; + const itemAt = async (served: ObjectStackProtocolImplementation, type: string, packageId: string) => + (await served.getMetaItem({ type, name: 'shared', packageId }))?.item as { label?: string } | undefined; + + it('the family: the eight types the #34040 pin fixes', () => { + expect([...OUTSIDE_PINNED].sort()).toEqual(['datasource', 'doc', 'external_catalog', 'field', 'object_extension', 'seed', 'translation', 'view']); + }); + + it.each(OUTSIDE_PINNED.flatMap((type) => [[type, [A, B]], [type, [B, A]]] as const))( + '%s, registered %j: `?package=` of a third package answers nothing, whichever holder\'s copy the service keeps', + async (type, order) => { + for (const id of order) shipParsed(type, 'shared', id); + for (const kept of [...order, undefined]) { + const served = servedWith(kept ? { name: 'shared', label: `${kept.split('.').pop()} ${type}`, _packageId: kept } : undefined); + for (const packageId of [C, 'com.acme.unknown']) { + expect(await itemAt(served, type, packageId), `${type} at ${packageId}, the service keeping ${kept ?? 'nothing'}`).toBeUndefined(); + } + } + }, + ); + + it.each(OUTSIDE_PINNED)('%s, one holder: `?package=` of another package answers nothing; the holder\'s own address its body', async (type) => { + shipParsed(type, 'shared', A); + for (const kept of [A, undefined]) { + const served = servedWith(kept ? { name: 'shared', label: `alpha ${type}`, _packageId: kept } : undefined); + expect(await itemAt(served, type, B), `${type} at ${B}, the service keeping ${kept ?? 'nothing'}`).toBeUndefined(); + expect((await itemAt(served, type, A))?.label, `${type} at its holder`).toBe(`alpha ${type}`); + } + }); + + it.each(OUTSIDE_PINNED)('CONTROL — %s: the environment\'s package-less entry and the holder\'s pair are served as before', async (type) => { + shipParsed(type, 'shared', A); + const served = servedWith(undefined); + expect((await itemAt(served, type, PAIR_A))?.label, `${type} at the holder's pair`).toBe(`alpha ${type}`); + registry.registerItem(type, { name: 'shared', label: `env ${type}` }, 'name' as never); + expect((await itemAt(served, type, B))?.label, `${type}: the package-less entry at ${B}`).toBe(`env ${type}`); + }); + + /** + * The save's credential carry-forward reads the same code layers when no + * stored row is at the address it saves (`readCodeLayerForCarryForward`, a + * private member read here as the save reads it). `datasource` is in the + * family and carries a credential: its real redactor, unmocked. + */ + it('datasource carry-forward: a save naming a package carries that package\'s own credential, or none, whichever holder\'s copy the service keeps', async () => { + expect(hasMetadataRedactor('datasource'), 'the datasource redactor is registered').toBe(true); + const datasource = (packageId: string) => ({ + name: 'shared', label: `${packageId.split('.').pop()} datasource`, driver: 'postgres', + config: { host: 'db.internal', database: 'shared', username: 'reporting', password: `${packageId.split('.').pop()}-secret` }, + }); + for (const order of [[A, B], [B, A]]) { + registry = new SchemaRegistry({ multiTenant: false }); + engine.registry = registry; + for (const id of [A, B, C]) registry.installPackage(manifest(id), 'code'); + for (const id of order) registry.registerItem('datasource', datasource(id), 'name' as never, id); + for (const kept of [...order, undefined]) { + const served = servedWith(kept ? { ...datasource(kept), _packageId: kept } : undefined) as unknown as { + readCodeLayerForCarryForward(type: string, name: string, packageId: string | null): Promise; + }; + const carried = async (packageId: string) => { + const codeLayer = await served.readCodeLayerForCarryForward('datasource', 'shared', packageId); + const incoming = redactMetadataItem('datasource', datasource(packageId)); + // As the save does: no body to carry from leaves the incoming body as it is. + const out = codeLayer ? carryForwardRedactedValues('datasource', incoming, codeLayer) : incoming; + return (out as { config?: { password?: unknown } }).config?.password; + }; + const at = `registered ${order.join(', ')}, the service keeping ${kept ?? 'nothing'}`; + expect(await carried(A), `at ${A}, ${at}`).toBe('alpha-secret'); + expect(await carried(B), `at ${B}, ${at}`).toBe('beta-secret'); + expect(await carried(C), `at ${C} (holds none), ${at}`).toBeUndefined(); + } + } + }); + + it.each(COVERED)('CONTROL — %s (covered): `?package=` of a third package is still the exact qualifier\'s refusal naming both', async (type) => { + shipParsed(type, 'shared', A); + shipParsed(type, 'shared', B); + const err = await refusalOf(() => servedWith(undefined).getMetaItem({ type, name: 'shared', packageId: C })); + expect([err.code, err.status, err.refusal.reason]).toEqual(['RESOURCE_CONFLICT', 409, 'not-held-by-qualifier']); + }); +}); + /** * [#31699 F2, the epic's ruling on the contract review] Two packages of one * App share the App's customization pair, so a locale Studio added there with diff --git a/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts b/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts index 94c712131c8..ea858f98854 100644 --- a/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts +++ b/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts @@ -249,6 +249,68 @@ describe('[#34040] CONTROL — one body ships the doc: its exact address answers }); }); +// [#34247, ADR-0150 D3/D5, red line 2] The exact address of a doc the package +// it names ships none of, on the same rig: 404 on the plain read and `/layers`, +// never another holder's doc. BASE (origin/main 01598d93, PR #34241 merged): +// `?package=` of a package that ships no doc of the name (installed, or not +// installed at all) answered 200 with a holder's doc on both transports and on +// both doors (the first registered after the step-2 decline, else the service's +// copy); `/layers?package=alpha` answered beta's code and effective layers even +// where alpha ships the doc, whenever beta registered last. +const GAMMA = 'com.qa.gamma'; +const NOT_INSTALLED = 'com.qa.unknown'; + +/** The plain read and `/layers` of the doc at `?package=`, on both transports. */ +async function exactDocAndLayers(booted: Booted, packageId: string) { + const query = { package: packageId }; + return [ + ...(await exactDocDoors(booted, packageId)), + { door: `dispatcher doc/shared_doc/layers?package=${packageId}`, ...(await viaDispatcher(booted.kernel, '/meta/doc/shared_doc/layers', query)) }, + { door: `rest doc/shared_doc/layers?package=${packageId}`, ...(await viaRest(booted, '/meta/:type/:name/layers', { type: 'doc', name: 'shared_doc' }, query)) }, + ]; +} + +describe.each([ + { order: 'alpha registered first, both ship', packages: [ALPHA, BETA, GAMMA], ships: [ALPHA, BETA] }, + { order: 'beta registered first, both ship', packages: [BETA, ALPHA, GAMMA], ships: [ALPHA, BETA] }, + { order: 'alpha registered first, beta alone ships', packages: [ALPHA, BETA, GAMMA], ships: [BETA] }, + { order: 'beta registered first, beta alone ships', packages: [BETA, ALPHA, GAMMA], ships: [BETA] }, +])('[#34247] the artifact door: the exact address of a doc its package ships none of, $order', ({ packages, ships }) => { + let booted: Booted | undefined; + + beforeAll(async () => { + booted = await bootArtifactKernel(packages, docBodyOf(ships)); + }, 120_000); + + afterAll(async () => { + if (!booted) return; + if (booted.kernel.getState() === 'running') await booted.kernel.shutdown(); + rmSync(booted.root, { recursive: true, force: true }); + }); + + it('`?package=` of a package shipping none (installed or not) answers 404 on the plain read and /layers, both transports, never a holder\'s doc', async () => { + const nonHolders = [ALPHA, GAMMA, NOT_INSTALLED].filter((id) => !ships.includes(id)); + for (const packageId of nonHolders) { + for (const answer of await exactDocAndLayers(booted!, packageId)) { + expect([answer.status, errorCodeOf(answer.body), answer.door], JSON.stringify(answer.body)).toEqual([404, 'RESOURCE_NOT_FOUND', answer.door]); + expect(JSON.stringify(answer.body ?? null), answer.door).not.toMatch(/(alpha|beta) doc/); + } + } + }); + + it('CONTROL: each holder\'s address answers its own doc on the plain read and /layers (code and effective), both transports', async () => { + for (const packageId of ships) { + const label = `${packageId.split('.').pop()} doc`; + for (const answer of await exactDocAndLayers(booted!, packageId)) { + const served = answer.door.includes('/layers') + ? [answer.body?.code?.label, answer.body?.effective?.label] + : [(answer.body?.item ?? answer.body)?.label]; + expect([answer.status, ...served, answer.door], JSON.stringify(answer.body)).toEqual([200, ...served.map(() => label), answer.door]); + } + } + }); +}); + // [#34040 acceptance item 4, review-c N2/N6 on PR #34036] The bare doc read's // refusal on the same composed rig, and the two package-less registry entries // beside two enabled holders. A hydrated row is laid as the hydrator lays it: From 1b999d9e55dee3c637477ce88185418d6812108f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:06:10 +0000 Subject: [PATCH 02/15] fix(metadata-protocol): a bare doc read beside a package-less entry the layers decline is refused naming both holders The registry exempts a doc name two enabled packages ship from the bare read's refusal when its bare slot holds a package-less entry (a stamp-less registration, or a hydrated or saved row). A doc a package ships is sealed, so the layers decline that row and never serve the entry: they served the metadata service's copy, the holder registered last, on the plain read, the layered read and the published read. Such an entry is no servable environment item, so the read is refused 409 naming both holders, as without it. An entry the layers would serve keeps the exemption. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .../34247-exact-read-own-item-or-none.md | 9 ++-- .../src/protocol-meta-item-reads.ts | 47 ++++++++++++++----- ...meta-disabled-holder-artifact-door.test.ts | 25 +++++----- 3 files changed, 54 insertions(+), 27 deletions(-) diff --git a/.changeset/34247-exact-read-own-item-or-none.md b/.changeset/34247-exact-read-own-item-or-none.md index 2a4c24f5480..7fbf7062b7b 100644 --- a/.changeset/34247-exact-read-own-item-or-none.md +++ b/.changeset/34247-exact-read-own-item-or-none.md @@ -2,11 +2,11 @@ '@objectstack/metadata-protocol': patch --- -fix(metadata-protocol)!: an exact `?package=X` read of a doc, view or other type the exact qualifier does not judge answers X's own item or 404, never another package's (ADR-0150 D3/D5, red line 2) +fix(metadata-protocol)!: an exact `?package=X` read of a doc, view or other type the exact qualifier does not judge answers X's own item or 404, never another package's; a bare doc read of a name two enabled packages ship, beside a package-less entry the layers decline, is refused 409 naming both (ADR-0150 D3/D5, red line 2) Clause-②: no (narrowing) Metadata-protocol: none -Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?package=` reads of a holder or of its pair (objectstack-platform SKILL.md, "Customizing an installed package"), which do not move, and never the read of a package that holds no item of the name +Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?package=` reads of a holder or of its pair (objectstack-platform SKILL.md, "Customizing an installed package"), which do not move, and never the read of a package that holds no item of the name or the bare doc read beside a package-less entry @@ -15,10 +15,11 @@ Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?pac - `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME (installed or not) and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now 404. - `GET /meta/TYPE/NAME/layers?package=X`, same address: was 200 with another package's `code` and `effective`. It is now 404. - `GET /meta/TYPE/NAME/layers?package=X`, where X and Y ship NAME and Y registered last: was 200 with Y's `code` and `effective` (the metadata service keeps such a type by name alone). It is now X's, as the plain read answers since #34040. +- `GET /meta/doc/NAME` and its `/layers` and `/published`, where two enabled packages ship NAME and the registry's bare slot holds a package-less entry (a stamp-less registration, or a hydrated or saved package-less row): was 200 with the doc of the package the metadata service registered last. It is now 409 `RESOURCE_CONFLICT` naming both, as with no such entry. A doc a package ships is sealed, so the layers decline that row; it is no servable environment item. - A save naming package X of a `datasource` with no stored row at X (the credential carry-forward reads the code layer, `readCodeLayerForCarryForward`): carried forward the credential of the package the metadata service kept, or of the first registered holder. It now carries X's own credential, or none when X ships no datasource of the name (the incoming body is kept as sent). Of this family only `datasource` carries a credential, so no other save moves. Path: a save door naming the package (`PUT /meta/datasource/NAME?package=X`), its draft save, and any carry-forward of a body whose credentials the read redacted. -**Not moved.** A holder's own address, a customization pair's address of its base's item, an item bound to no package (the environment's entry), any read naming no package, `object`, and the covered types (`action`, `hook`, `job`, `sharing_rule`, `queue`, `assignment_rule`), whose exact qualifier already refuses 409 `not-held-by-qualifier`. +**Not moved.** A holder's own address, a customization pair's address of its base's item, an item bound to no package (the environment's entry), any read naming no package other than the bare doc case above, `object`, and the covered types (`action`, `hook`, `job`, `sharing_rule`, `queue`, `assignment_rule`), whose exact qualifier already refuses 409 `not-held-by-qualifier`. **No migration.** No schema key, stored row or registry slot changes; nothing is rewritten. -The fix for a caller: address a package that ships the name (or its pair), or read with no package. +The fix for a caller: address a package that ships the name (or its pair), or read with no package. For the bare doc read, address the holder with `?package=`. diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index 263bd0a37e8..f94545c3139 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -325,21 +325,44 @@ export async function judgeBareActionRead( * the registry's first composite. * * Judge only: any answer the registry gives leaves the read to its layers, - * exactly as before. A package-less entry in the registry's bare slot (a - * hydrated or saved row, or a stamp-less registration) exempts the name from - * the refusal, and the layers then read it as before: ⛔ they do not serve - * that entry where the MetadataService holds a holder's copy, which answers - * first (the holder registered last; the composed artifact rig of - * runtime's `meta-disabled-holder-artifact-door.test.ts` pins it, measured and - * unresolved). A package-less row only the store holds is no + * exactly as before. A package-less row only the store holds is no * exemption, because the layers below do not serve it for a `doc` and would * answer a holder by registration order again. * + * [#34248, ADR-0150 red line 2] Nor is a package-less entry in the registry's + * bare slot (a hydrated or saved row, or a stamp-less registration) that is + * the copy of a row the layers decline ({@link ProtocolHost.isStoredEntryOfDeclinedName}: + * a doc a package ships is sealed, so its package-less row is never served). + * The registry exempts the name for such an entry, but the layers do not + * serve it: they served the MetadataService's copy, the holder registered + * last. So two or more enabled holders beside such an entry are refused here + * as without it, naming each holder. An entry the layers would serve keeps + * the exemption. + * * @throws {PackageScopedNameRefusedError} two or more enabled package holders. */ -export function refuseAmbiguousBareDocRead(host: Pick, name: string, member: string | undefined): void { - const registry = host.engine?.registry as { resolveItem?(type: string, name: string, caller: null, member?: string): unknown } | undefined; - if (typeof registry?.resolveItem === 'function') registry.resolveItem('doc', name, null, member); +export function refuseAmbiguousBareDocRead(host: Pick, name: string, member: string | undefined): void { + const registry = host.engine?.registry as { + resolveItem?(type: string, name: string, caller: null, member?: string): unknown; + packageScopedHoldersOf?(type: string, name: string): string[] | undefined; + } | undefined; + if (typeof registry?.resolveItem !== 'function') return; + const answer = registry.resolveItem('doc', name, null, member); + // The registry's answer naming no package is the exempting entry (or a + // name one package or none holds, which the count below leaves alone). + if (answer === undefined || answer === null || storedItemPackageId(answer) !== undefined) return; + if (!host.isStoredEntryOfDeclinedName('doc', answer)) return; + const holders = registry.packageScopedHoldersOf?.('doc', name) ?? []; + if (holders.length < 2) return; + const refused: Omit = { + status: 'refused', + reason: 'ambiguous-in-environment', + type: 'doc' as PackageScopedRefusal['type'], + name, + callerPackageId: null, + candidates: holders.map((packageId) => ({ kind: 'package' as const, packageId })), + }; + throw new PackageScopedNameRefusedError({ ...refused, message: packageScopedRefusalMessage(refused) }); } /** @@ -699,7 +722,9 @@ export async function readMetaItem(host: Pick engine.insert('sys_metadata', { type: 'doc', name: 'shared_doc', namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', state: 'active', version: 1, metadata: JSON.stringify({ name: 'shared_doc', label: 'environment doc', content: '# env' }), }, { context: { isSystem: true } } as any); const docRegistryOf = (booted: Booted) => (booted.engine.registry as unknown as { metadata: Map> }).metadata.get('doc')!; -const labelAt = (door: string, body: any) => (door.endsWith('/layers') ? [body?.overlay?.label, body?.effective?.label] : [body?.item?.label ?? body?.label]); describe.each([ { order: 'alpha registered first', packages: [ALPHA, BETA] }, @@ -367,12 +368,12 @@ describe.each([ await expectExactReadsOwnDoc(); }); - it('(measured, unresolved) a stamp-less bare entry with the service\'s copy: the bare doors serve the holder registered last; each exact address reads its own doc', async () => { + it('[#34248] a stamp-less bare entry with the service\'s copy: the plain read, /layers and /published refuse 409 naming both, on both transports, never the holder registered last; each exact address reads its own doc', async () => { booted!.engine.registry.registerItem('doc', { name: 'shared_doc', label: 'bare entry', content: '# bare' } as never, 'name' as never); try { + await expectRefusedNamingBoth(); for (const answer of await bareDoors(booted!, 'doc', 'shared_doc')) { - expect([answer.status, ...labelAt(answer.door, answer.body), answer.door], JSON.stringify(answer.body)) - .toEqual([200, ...(answer.door.endsWith('/layers') ? [undefined, lastDoc] : [lastDoc]), answer.door]); + expect(JSON.stringify(answer.body ?? null), answer.door).not.toContain(lastDoc); } await expectExactReadsOwnDoc(); } finally { @@ -380,12 +381,12 @@ describe.each([ } }); - it('(measured, unresolved) a hydrated package-less row: the bare doors serve the holder registered last, /layers that holder under the row; each exact address reads its own doc', async () => { + it('[#34248] a hydrated package-less row: the plain read, /layers and /published refuse 409 naming both, on both transports, never the holder registered last; each exact address reads its own doc', async () => { await layEnvironmentDocRow(booted!.engine); booted!.engine.registry.registerItem('doc', { name: 'shared_doc', label: 'environment doc', content: '# env', _packageId: 'sys_metadata' } as never, 'name' as never); + await expectRefusedNamingBoth(); for (const answer of await bareDoors(booted!, 'doc', 'shared_doc')) { - expect([answer.status, ...labelAt(answer.door, answer.body), answer.door], JSON.stringify(answer.body)) - .toEqual([200, ...(answer.door.endsWith('/layers') ? ['environment doc', lastDoc] : [lastDoc]), answer.door]); + expect(JSON.stringify(answer.body ?? null), answer.door).not.toContain(lastDoc); } await expectExactReadsOwnDoc(); // The row alone, its registry copy gone: no exemption, refused again. From 25a4ffa4bc533795147dbef4cec55e9d6799d6d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:15:40 +0000 Subject: [PATCH 03/15] fix(metadata-protocol): a bare doc read beside two holders serves the environment's own package-less entry, never the holder registered last The previous commit refused such an entry 409, reading it as a row the layers decline. The ruling 6893582352 control in objectql's e8 readers pins the opposite: the environment's own entry answers first, and the registry and the facade serve it. The layers serve it too, once the metadata service's package copy no longer answers first. So the plain read, /layers and both /published doors now serve that entry; without one the read stays refused 409. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .../34247-exact-read-own-item-or-none.md | 8 ++- .../src/protocol-meta-item-reads.ts | 64 +++++++++++-------- .../src/protocol-meta-layered-reads.ts | 29 +++++++-- packages/rest/src/meta-item-history-routes.ts | 9 +++ ...meta-disabled-holder-artifact-door.test.ts | 60 ++++++++++++----- packages/runtime/src/domains/meta.ts | 9 ++- 6 files changed, 126 insertions(+), 53 deletions(-) diff --git a/.changeset/34247-exact-read-own-item-or-none.md b/.changeset/34247-exact-read-own-item-or-none.md index 7fbf7062b7b..045dfca269b 100644 --- a/.changeset/34247-exact-read-own-item-or-none.md +++ b/.changeset/34247-exact-read-own-item-or-none.md @@ -1,8 +1,10 @@ --- '@objectstack/metadata-protocol': patch +'@objectstack/runtime': patch +'@objectstack/rest': patch --- -fix(metadata-protocol)!: an exact `?package=X` read of a doc, view or other type the exact qualifier does not judge answers X's own item or 404, never another package's; a bare doc read of a name two enabled packages ship, beside a package-less entry the layers decline, is refused 409 naming both (ADR-0150 D3/D5, red line 2) +fix(metadata-protocol)!: an exact `?package=X` read of a doc, view or other type the exact qualifier does not judge answers X's own item or 404, never another package's; a bare doc read of a name two enabled packages ship, beside the environment's own package-less entry, serves that entry, never the package registered last (ADR-0150 D3/D5, red line 2, ruling 6893582352) Clause-②: no (narrowing) Metadata-protocol: none @@ -15,11 +17,11 @@ Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?pac - `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME (installed or not) and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now 404. - `GET /meta/TYPE/NAME/layers?package=X`, same address: was 200 with another package's `code` and `effective`. It is now 404. - `GET /meta/TYPE/NAME/layers?package=X`, where X and Y ship NAME and Y registered last: was 200 with Y's `code` and `effective` (the metadata service keeps such a type by name alone). It is now X's, as the plain read answers since #34040. -- `GET /meta/doc/NAME` and its `/layers` and `/published`, where two enabled packages ship NAME and the registry's bare slot holds a package-less entry (a stamp-less registration, or a hydrated or saved package-less row): was 200 with the doc of the package the metadata service registered last. It is now 409 `RESOURCE_CONFLICT` naming both, as with no such entry. A doc a package ships is sealed, so the layers decline that row; it is no servable environment item. +- `GET /meta/doc/NAME` and its `/layers` and `/published`, where two enabled packages ship NAME and the registry's bare slot holds a package-less entry (a stamp-less registration, or a hydrated or saved package-less row): was 200 with the doc of the package the metadata service registered last. It is now 200 with the environment's own entry, as the registry and `MetadataFacade.get` already served it: the plain read and `/published` its body, `/layers` a runtime registration as its `code` layer and a stored row as its `overlay` (with `code: null`). Both `/published` doors (the dispatcher's and `RestServer`'s) serve that entry in place of the metadata service's package copy, which they read when no overlay is stored. Without such an entry the read stays refused 409 naming both (#34036). - A save naming package X of a `datasource` with no stored row at X (the credential carry-forward reads the code layer, `readCodeLayerForCarryForward`): carried forward the credential of the package the metadata service kept, or of the first registered holder. It now carries X's own credential, or none when X ships no datasource of the name (the incoming body is kept as sent). Of this family only `datasource` carries a credential, so no other save moves. Path: a save door naming the package (`PUT /meta/datasource/NAME?package=X`), its draft save, and any carry-forward of a body whose credentials the read redacted. **Not moved.** A holder's own address, a customization pair's address of its base's item, an item bound to no package (the environment's entry), any read naming no package other than the bare doc case above, `object`, and the covered types (`action`, `hook`, `job`, `sharing_rule`, `queue`, `assignment_rule`), whose exact qualifier already refuses 409 `not-held-by-qualifier`. **No migration.** No schema key, stored row or registry slot changes; nothing is rewritten. -The fix for a caller: address a package that ships the name (or its pair), or read with no package. For the bare doc read, address the holder with `?package=`. +The fix for a caller: address a package that ships the name (or its pair), or read with no package. For the bare doc read beside the environment's own entry, address a holder with `?package=` to read that holder's doc. diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index f94545c3139..b0a573b7d75 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -329,40 +329,43 @@ export async function judgeBareActionRead( * exemption, because the layers below do not serve it for a `doc` and would * answer a holder by registration order again. * - * [#34248, ADR-0150 red line 2] Nor is a package-less entry in the registry's - * bare slot (a hydrated or saved row, or a stamp-less registration) that is - * the copy of a row the layers decline ({@link ProtocolHost.isStoredEntryOfDeclinedName}: - * a doc a package ships is sealed, so its package-less row is never served). - * The registry exempts the name for such an entry, but the layers do not - * serve it: they served the MetadataService's copy, the holder registered - * last. So two or more enabled holders beside such an entry are refused here - * as without it, naming each holder. An entry the layers would serve keeps - * the exemption. + * [#34248, ruling 6893582352] A package-less entry in the registry's bare + * slot (a stamp-less registration, or a hydrated or saved row stamped with + * the store's sentinel) exempts the name: it is the environment's own item, + * which answers first, as the registry and `MetadataFacade.get` serve it. + * That entry is returned when two or more enabled packages hold the name, + * because the layers must then serve it: the MetadataService keeps a doc by + * name alone, so its copy is the holder registered last, and it answered + * first ({@link bareDocServiceCopyDisplacesEntry}). * + * @returns the environment's entry beside two or more enabled holders, else + * `undefined` (no such entry, or a name one package or none holds). * @throws {PackageScopedNameRefusedError} two or more enabled package holders. */ -export function refuseAmbiguousBareDocRead(host: Pick, name: string, member: string | undefined): void { +export function refuseAmbiguousBareDocRead(host: Pick, name: string, member: string | undefined): unknown { const registry = host.engine?.registry as { resolveItem?(type: string, name: string, caller: null, member?: string): unknown; packageScopedHoldersOf?(type: string, name: string): string[] | undefined; } | undefined; - if (typeof registry?.resolveItem !== 'function') return; + if (typeof registry?.resolveItem !== 'function') return undefined; const answer = registry.resolveItem('doc', name, null, member); // The registry's answer naming no package is the exempting entry (or a // name one package or none holds, which the count below leaves alone). - if (answer === undefined || answer === null || storedItemPackageId(answer) !== undefined) return; - if (!host.isStoredEntryOfDeclinedName('doc', answer)) return; - const holders = registry.packageScopedHoldersOf?.('doc', name) ?? []; - if (holders.length < 2) return; - const refused: Omit = { - status: 'refused', - reason: 'ambiguous-in-environment', - type: 'doc' as PackageScopedRefusal['type'], - name, - callerPackageId: null, - candidates: holders.map((packageId) => ({ kind: 'package' as const, packageId })), - }; - throw new PackageScopedNameRefusedError({ ...refused, message: packageScopedRefusalMessage(refused) }); + if (answer === undefined || answer === null || storedItemPackageId(answer) !== undefined) return undefined; + return (registry.packageScopedHoldersOf?.('doc', name) ?? []).length >= 2 ? answer : undefined; +} + +/** + * [#34248, ruling 6893582352] Is the MetadataService's answer to a bare doc + * read a package's copy where the environment's own entry answers + * ({@link refuseAmbiguousBareDocRead}'s return)? Such a copy is declined at + * the service step, so the registry's bare slot, read first by `getItem`, + * serves the environment's entry. A package-less service copy is the + * environment's own and is kept. + */ +export function bareDocServiceCopyDisplacesEntry(environmentEntry: unknown, serviceCopy: unknown): boolean { + return environmentEntry !== undefined && serviceCopy !== undefined && serviceCopy !== null + && storedItemPackageId(serviceCopy) !== undefined; } /** @@ -723,9 +726,10 @@ export async function readMetaItem(host: Pick { + const label = `${ships[0]!.split('.').pop()} doc`; + for (const answer of await bareDoors(booted!, 'doc', 'shared_doc')) { + const served = answer.door.endsWith('/layers') ? answer.body?.effective?.label : (answer.body?.item ?? answer.body)?.label; + expect([answer.status, served, answer.door], JSON.stringify(answer.body)).toEqual([200, label, answer.door]); + } + }); + it('CONTROL: each holder\'s address answers its own doc on the plain read and /layers (code and effective), both transports', async () => { for (const packageId of ships) { const label = `${packageId.split('.').pop()} doc`; @@ -317,13 +325,15 @@ describe.each([ // the stored `sys_metadata` row, and its package-less copy in the registry's // bare slot (stamped with the `sys_metadata` sentinel). // -// [#34248, ADR-0150 red line 2] Either entry is the copy of a package-less -// row the layers decline (a doc a package ships is sealed), so it is no -// servable environment item, and the bare doors refuse 409 naming both, as -// without it. BASE (origin/main 01598d93, PR #34241 merged): with either entry -// the bare doors answered the holder the metadata service registered last (a -// registration-order pick), and `/layers` reported the row as the overlay over -// that holder's effective item. +// [#34248, ruling 6893582352] Either entry is the environment's own item, and +// the environment's own item answers first: the bare doors serve it (the plain +// read and `/published` its body, `/layers` the entry as the code layer and +// effective, a stored row also as the overlay), never the holder the +// metadata service registered last. Without such an entry the bare doors +// refuse 409 naming both (PR #34036). BASE (origin/main 01598d93, PR #34241 +// merged): with either entry the bare doors answered the holder the metadata +// service registered last (a registration-order pick), and `/layers` reported +// the row as the overlay over that holder's effective item. const layEnvironmentDocRow = (engine: ObjectQL) => engine.insert('sys_metadata', { type: 'doc', name: 'shared_doc', namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', state: 'active', version: 1, metadata: JSON.stringify({ name: 'shared_doc', label: 'environment doc', content: '# env' }), @@ -368,26 +378,42 @@ describe.each([ await expectExactReadsOwnDoc(); }); - it('[#34248] a stamp-less bare entry with the service\'s copy: the plain read, /layers and /published refuse 409 naming both, on both transports, never the holder registered last; each exact address reads its own doc', async () => { + /** Each bare door's answer: the plain read and `/published` the item, `/layers` its code, overlay and effective layers. */ + const expectBareDoorsServe = async (expected: { item: string; code: string | undefined; overlay: string | undefined }) => { + for (const answer of await bareDoors(booted!, 'doc', 'shared_doc')) { + const served = answer.door.endsWith('/layers') + ? [answer.body?.code?.label, answer.body?.overlay?.label, answer.body?.effective?.label] + : [(answer.body?.item ?? answer.body)?.label]; + const want = answer.door.endsWith('/layers') ? [expected.code, expected.overlay, expected.item] : [expected.item]; + expect([answer.status, ...served, answer.door], JSON.stringify(answer.body)).toEqual([200, ...want, answer.door]); + expect(JSON.stringify(answer.body ?? null), answer.door).not.toContain(lastDoc); + } + }; + + it('CONTROL [#34248]: a package-less doc no package ships is what the bare plain read, /layers and /published serve, both transports', async () => { + await booted!.kernel.getService('metadata').register('doc', 'env_only_doc', { name: 'env_only_doc', label: 'env only doc', content: '# env only' }); + for (const answer of await bareDoors(booted!, 'doc', 'env_only_doc')) { + const served = answer.door.endsWith('/layers') ? answer.body?.effective?.label : (answer.body?.item ?? answer.body)?.label; + expect([answer.status, served, answer.door], JSON.stringify(answer.body)).toEqual([200, 'env only doc', answer.door]); + } + }); + + it('[#34248] a stamp-less bare entry with the service\'s copy: the plain read, /layers (its code layer) and /published serve the entry on both transports, never the holder registered last; each exact address reads its own doc', async () => { booted!.engine.registry.registerItem('doc', { name: 'shared_doc', label: 'bare entry', content: '# bare' } as never, 'name' as never); try { - await expectRefusedNamingBoth(); - for (const answer of await bareDoors(booted!, 'doc', 'shared_doc')) { - expect(JSON.stringify(answer.body ?? null), answer.door).not.toContain(lastDoc); - } + await expectBareDoorsServe({ item: 'bare entry', code: 'bare entry', overlay: undefined }); await expectExactReadsOwnDoc(); } finally { docRegistryOf(booted!).delete('shared_doc'); } + // The entry gone: refused again. + await expectRefusedNamingBoth(); }); - it('[#34248] a hydrated package-less row: the plain read, /layers and /published refuse 409 naming both, on both transports, never the holder registered last; each exact address reads its own doc', async () => { + it('[#34248] a hydrated package-less row: the plain read, /layers (its registry copy as the code layer, the row as the overlay) and /published serve the row on both transports, never the holder registered last; each exact address reads its own doc', async () => { await layEnvironmentDocRow(booted!.engine); booted!.engine.registry.registerItem('doc', { name: 'shared_doc', label: 'environment doc', content: '# env', _packageId: 'sys_metadata' } as never, 'name' as never); - await expectRefusedNamingBoth(); - for (const answer of await bareDoors(booted!, 'doc', 'shared_doc')) { - expect(JSON.stringify(answer.body ?? null), answer.door).not.toContain(lastDoc); - } + await expectBareDoorsServe({ item: 'environment doc', code: 'environment doc', overlay: 'environment doc' }); await expectExactReadsOwnDoc(); // The row alone, its registry copy gone: no exemption, refused again. docRegistryOf(booted!).delete('shared_doc'); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index d7fd0cfbf51..01ac93c6677 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -1625,7 +1625,14 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin let publishedCode: unknown; const notAnotherHoldersCopy = (copy: unknown): unknown => { const stamp = (copy as { _packageId?: unknown } | null | undefined)?._packageId; - return mixedOwner !== undefined && typeof stamp === 'string' && stamp !== mixedOwner && mixedHolders.includes(stamp) + if (mixedOwner !== undefined && typeof stamp === 'string' && stamp !== mixedOwner && mixedHolders.includes(stamp)) return publishedCode; + // [#34248, ruling 6893582352] …and a bare doc's package copy where + // the layered read's code layer is the environment's own + // package-less entry (two enabled holders beside it): that entry + // answers first, never the holder registered last. + const codeStamp = (publishedCode as { _packageId?: unknown } | null | undefined)?._packageId; + return publishedType === 'doc' && publishedCode != null && (typeof codeStamp !== 'string' || codeStamp === '' || codeStamp === 'sys_metadata') + && typeof stamp === 'string' && stamp !== '' && stamp !== 'sys_metadata' ? publishedCode : copy; }; From eaf3e5d13b6999b03008ce06907f466c26a3d428 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:56:08 +0000 Subject: [PATCH 04/15] fix(metadata-protocol): the hydrated package-less doc row answers on /layers and /published beside two holders; the Console reads a doc by name where the app's package ships none - getMetaItemLayered: beside two enabled holders, the package-less stored row behind the bare doc read's environment entry is the effective layer, never declined as a sealed doc's row; the hydrator's entry stays no code layer. - registryAnswerAtAddress leaves the security catalog types (position, capability) to the code layers' answer. - DocPage: a 404 at the route's package falls back to the read by name. - Pins: the hydrator's entry shape and a real loadMetaFromDb hydration on the composed rig, the one-holder stamp-less cell, position/capability, and the Console fallback. Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../34247-exact-read-own-item-or-none.md | 16 ++++- .../src/protocol-meta-item-reads.ts | 9 ++- .../src/protocol-meta-layered-reads.ts | 10 ++- .../package-scoped-exact-qualifier.test.ts | 18 ++++++ ...meta-disabled-holder-artifact-door.test.ts | 64 +++++++++++++++++-- ui/apps/console/src/pages/DocPage.tsx | 17 ++++- .../console/src/pages/docs-portal.test.tsx | 56 +++++++++++++++- 7 files changed, 177 insertions(+), 13 deletions(-) diff --git a/.changeset/34247-exact-read-own-item-or-none.md b/.changeset/34247-exact-read-own-item-or-none.md index 045dfca269b..ab9cbd8b70b 100644 --- a/.changeset/34247-exact-read-own-item-or-none.md +++ b/.changeset/34247-exact-read-own-item-or-none.md @@ -2,6 +2,7 @@ '@objectstack/metadata-protocol': patch '@objectstack/runtime': patch '@objectstack/rest': patch +'@object-ui/console': patch --- fix(metadata-protocol)!: an exact `?package=X` read of a doc, view or other type the exact qualifier does not judge answers X's own item or 404, never another package's; a bare doc read of a name two enabled packages ship, beside the environment's own package-less entry, serves that entry, never the package registered last (ADR-0150 D3/D5, red line 2, ruling 6893582352) @@ -17,10 +18,21 @@ Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?pac - `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME (installed or not) and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now 404. - `GET /meta/TYPE/NAME/layers?package=X`, same address: was 200 with another package's `code` and `effective`. It is now 404. - `GET /meta/TYPE/NAME/layers?package=X`, where X and Y ship NAME and Y registered last: was 200 with Y's `code` and `effective` (the metadata service keeps such a type by name alone). It is now X's, as the plain read answers since #34040. -- `GET /meta/doc/NAME` and its `/layers` and `/published`, where two enabled packages ship NAME and the registry's bare slot holds a package-less entry (a stamp-less registration, or a hydrated or saved package-less row): was 200 with the doc of the package the metadata service registered last. It is now 200 with the environment's own entry, as the registry and `MetadataFacade.get` already served it: the plain read and `/published` its body, `/layers` a runtime registration as its `code` layer and a stored row as its `overlay` (with `code: null`). Both `/published` doors (the dispatcher's and `RestServer`'s) serve that entry in place of the metadata service's package copy, which they read when no overlay is stored. Without such an entry the read stays refused 409 naming both (#34036). +- `GET /meta/doc/NAME` and its `/layers` and `/published`, where two enabled packages ship NAME and the registry's bare slot holds a package-less entry: was 200 with the doc of the package the metadata service registered last. It is now 200 with the environment's own item, as the registry and `MetadataFacade.get` already served it. Without such an entry the read stays refused 409 naming both (#34036). Per entry: + - A stamp-less runtime registration: the plain read and `/published` serve its body; `/layers` reports it as `code` and `effective`. + - A stored package-less row the hydrator registered before any package shipped the name (its entry is tenant-authored, `_provenance: 'org'`, so it is no code layer): the plain read and `/published` serve the row; `/layers` reports `code: null` and the row as `overlay` and `effective`. + - Both `/published` doors (the dispatcher's and `RestServer`'s) serve that item in place of the metadata service's package copy. +- The same stored row hydrated after the packages' artifacts registered wears the first registered holder's envelope (the hydrator grafts it), so no package-less entry exists: the bare doors stay refused 409 naming both, as before. - A save naming package X of a `datasource` with no stored row at X (the credential carry-forward reads the code layer, `readCodeLayerForCarryForward`): carried forward the credential of the package the metadata service kept, or of the first registered holder. It now carries X's own credential, or none when X ships no datasource of the name (the incoming body is kept as sent). Of this family only `datasource` carries a credential, so no other save moves. Path: a save door naming the package (`PUT /meta/datasource/NAME?package=X`), its draft save, and any carry-forward of a body whose credentials the read redacted. -**Not moved.** A holder's own address, a customization pair's address of its base's item, an item bound to no package (the environment's entry), any read naming no package other than the bare doc case above, `object`, and the covered types (`action`, `hook`, `job`, `sharing_rule`, `queue`, `assignment_rule`), whose exact qualifier already refuses 409 `not-held-by-qualifier`. +**Console.** The doc page under an app (`/apps/X/docs/...`) reads with X as ADR-0048 prefer-local context. When that read answers 404, it now reads the doc by name. A cross-reference from X's docs to another package's doc, and the app-name segment of a package that ships several apps (which names no package), keep rendering the doc's one holder; a name two other packages ship lists them (the 409 candidate list), where it showed one of them by registration order. + +**Not moved.** +- A holder's own address, a customization pair's address of its base's item, and an item bound to no package (the environment's entry). +- Any read naming no package other than the bare doc case above. +- `object`, and the covered types (`action`, `hook`, `job`, `sharing_rule`, `queue`, `assignment_rule`), whose exact qualifier already refuses 409 `not-held-by-qualifier`. +- The security catalog types `position` and `capability`: the registry keeps one package holder of such a name, so `?package=` of another package keeps the code layers' answer (that holder's item). +- One enabled holder beside a stamp-less bare entry: the bare doors serve the holder's doc while the registry and `MetadataFacade.get` serve the entry (measured, unresolved here; the entry answers first beside two or more holders only). **No migration.** No schema key, stored row or registry slot changes; nothing is rewritten. diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index b0a573b7d75..d48ee944874 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -25,7 +25,7 @@ import { packageScopedRefusalMessage, type PackageScopedRefusal, } from '@objectstack/core'; -import { isPairOf, itemDiscriminator } from '@objectstack/metadata-core'; +import { isPairOf, isSecurityCatalogType, itemDiscriminator } from '@objectstack/metadata-core'; import { boundObjectOf, storedItemPackageId } from '@objectstack/metadata/stored-item-package'; import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared'; // [#24395] The draft row's per-key provenance, read back for the strict draft read. @@ -473,6 +473,11 @@ export function serviceCopyOfAnotherPackage( * X's envelope. Unchanged: an item bound to no package (the environment's * entry), an item stamped X, a customization pair's item, a stamp the * registry does not know, and an `object`. + * + * ⛔ Not a security catalog type (`position`, `capability`; ADR-0131 D3): + * the registry keeps one package holder of such a name, resolved by name + * for the whole environment, so another package's address has no slot of + * its own to answer with. Its answer there stays the code layers' own. */ export function registryAnswerAtAddress( host: Pick, @@ -481,7 +486,7 @@ export function registryAnswerAtAddress( member: string | undefined, isWantedMember: (candidate: unknown) => boolean, ): unknown { - if (!request.packageId || item === undefined || item === null) return item; + if (!request.packageId || item === undefined || item === null || isSecurityCatalogType(request.type)) return item; if (!serviceCopyOfAnotherPackage(host, request, item)) return item; const scoped = host.engine?.registry as { getPackageScopedItem?(type: string, name: string, packageId: string, member?: string): unknown } | undefined; const own = typeof scoped?.getPackageScopedItem === 'function' diff --git a/packages/metadata-protocol/src/protocol-meta-layered-reads.ts b/packages/metadata-protocol/src/protocol-meta-layered-reads.ts index 002850ac836..7fa81e17cfe 100644 --- a/packages/metadata-protocol/src/protocol-meta-layered-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-layered-reads.ts @@ -800,9 +800,17 @@ export async function getMetaItemLayered(host: Pick { + shipParsed(type, 'shared', A); + for (const kept of [A, undefined]) { + const served = servedWith(kept ? { name: 'shared', label: `alpha ${type}`, _packageId: kept } : undefined); + const at = `${type} at ${B}, the service keeping ${kept ?? 'nothing'}`; + expect((await itemAt(served, type, B))?.label, at).toBe(`alpha ${type}`); + const layered = await served.getMetaItemLayered({ type, name: 'shared', packageId: B }); + expect([(layered?.code as { label?: string } | null)?.label, (layered?.effective as { label?: string } | null)?.label], `${at} (/layers)`) + .toEqual([`alpha ${type}`, `alpha ${type}`]); + } + }); + it.each(OUTSIDE_PINNED)('CONTROL — %s: the environment\'s package-less entry and the holder\'s pair are served as before', async (type) => { shipParsed(type, 'shared', A); const served = servedWith(undefined); diff --git a/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts b/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts index 56b30f73d6e..82993a3ab9a 100644 --- a/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts +++ b/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts @@ -306,6 +306,29 @@ describe.each([ } }); + // [review S1] Measured, unresolved: the environment's entry answers first + // only beside two or more enabled holders (#34248's acceptance). Beside + // one holder, the registry (and so `MetadataFacade.get`) answers a + // stamp-less bare entry while the bare doors keep the holder's doc, as on + // main. Declared in the changeset; a second holder flips the doors to the + // entry (the #34248 pins below). + it.runIf(ships.length === 1)('[measured, unresolved] one holder beside a stamp-less bare entry: the bare doors serve the holder\'s doc on both transports while the registry answers the entry', async () => { + const label = `${ships[0]!.split('.').pop()} doc`; + const bareSlot = (booted!.engine.registry as unknown as { metadata: Map> }).metadata.get('doc')!; + const before = bareSlot.has('shared_doc') ? { held: bareSlot.get('shared_doc') } : undefined; + booted!.engine.registry.registerItem('doc', { name: 'shared_doc', label: 'bare entry', content: '# bare' } as never, 'name' as never); + try { + expect((booted!.engine.registry.resolveItem('doc', 'shared_doc', null) as { label?: string } | undefined)?.label).toBe('bare entry'); + for (const answer of await bareDoors(booted!, 'doc', 'shared_doc')) { + const served = answer.door.endsWith('/layers') ? answer.body?.effective?.label : (answer.body?.item ?? answer.body)?.label; + expect([answer.status, served, answer.door], JSON.stringify(answer.body)).toEqual([200, label, answer.door]); + } + } finally { + if (before) bareSlot.set('shared_doc', before.held); + else bareSlot.delete('shared_doc'); + } + }); + it('CONTROL: each holder\'s address answers its own doc on the plain read and /layers (code and effective), both transports', async () => { for (const packageId of ships) { const label = `${packageId.split('.').pop()} doc`; @@ -321,9 +344,13 @@ describe.each([ // [#34040 acceptance item 4, review-c N2/N6 on PR #34036] The bare doc read's // refusal on the same composed rig, and the two package-less registry entries -// beside two enabled holders. A hydrated row is laid as the hydrator lays it: -// the stored `sys_metadata` row, and its package-less copy in the registry's -// bare slot (stamped with the `sys_metadata` sentinel). +// beside two enabled holders. A hydrated row is laid as the hydrator lays it +// when it reads the row before any package ships the name (a doc saved, then +// two packages that ship it installed): the stored `sys_metadata` row, and in +// the registry's bare slot the body `hydrateOverlayIntoRegistry` registers, +// `stateTenantAuthorship(withRowBinding(body, null))`: no `_packageId`, +// `_provenance: 'org'`. With the artifacts read first, the hydrator grafts the +// first holder's envelope onto the row instead (the last pin below). // // [#34248, ruling 6893582352] Either entry is the environment's own item, and // the environment's own item answers first: the bare doors serve it (the plain @@ -410,15 +437,40 @@ describe.each([ await expectRefusedNamingBoth(); }); - it('[#34248] a hydrated package-less row: the plain read, /layers (its registry copy as the code layer, the row as the overlay) and /published serve the row on both transports, never the holder registered last; each exact address reads its own doc', async () => { + // [review M1] The hydrator's entry is tenant-authored, so it is no code + // layer (#21059): `code` is null, and the row is the overlay and the + // effective layer. Measured at 989f4ad7 before the fix: the plain read + // served the row while `/layers` answered `effective: null` (the sealed + // doc's row declined) and both `/published` doors served an empty body. + it('[#34248] a hydrated package-less row (hydrated before the artifacts): the plain read, /layers (no code layer, the row as overlay and effective) and /published serve the row on both transports, never the holder registered last; each exact address reads its own doc', async () => { await layEnvironmentDocRow(booted!.engine); - booted!.engine.registry.registerItem('doc', { name: 'shared_doc', label: 'environment doc', content: '# env', _packageId: 'sys_metadata' } as never, 'name' as never); - await expectBareDoorsServe({ item: 'environment doc', code: 'environment doc', overlay: 'environment doc' }); + booted!.engine.registry.registerItem('doc', { name: 'shared_doc', label: 'environment doc', content: '# env', _provenance: 'org' } as never, 'name' as never); + await expectBareDoorsServe({ item: 'environment doc', code: undefined, overlay: 'environment doc' }); await expectExactReadsOwnDoc(); // The row alone, its registry copy gone: no exemption, refused again. docRegistryOf(booted!).delete('shared_doc'); await expectRefusedNamingBoth(); }); + + // [review M1] The same stored row hydrated by the production read + // (`loadMetaFromDb`) after the artifacts registered: the hydrator grafts + // the first holder's envelope onto it, so no package-less entry exists + // and every bare door refuses naming both, as on main (measured at + // origin/main c9346317 and at this head). The other holder's address + // reads its own doc. + it('CONTROL [#34248]: the row hydrated after the artifacts (`loadMetaFromDb`) wears the first holder\'s envelope, and the bare doors refuse 409 naming both on both transports', async () => { + const hydrated = await (booted!.kernel.getService('protocol') as { loadMetaFromDb(): Promise<{ loaded: number; errors: number }> }).loadMetaFromDb(); + expect([hydrated.loaded > 0, hydrated.errors]).toEqual([true, 0]); + const entry = docRegistryOf(booted!).get('shared_doc') as { _packageId?: unknown; _provenance?: unknown } | undefined; + expect([entry?._packageId, entry?._provenance]).toEqual([packages[0], 'package']); + await expectRefusedNamingBoth(); + const second = packages[1]!; + for (const answer of await exactDocDoors(booted!, second)) { + expect([answer.status, (answer.body?.item ?? answer.body)?.label, answer.door], JSON.stringify(answer.body)) + .toEqual([200, `${second.split('.').pop()} doc`, answer.door]); + } + docRegistryOf(booted!).delete('shared_doc'); + }); }); // [#34041, ADR-0150 D3] A disabled package holds no name, so beside one diff --git a/ui/apps/console/src/pages/DocPage.tsx b/ui/apps/console/src/pages/DocPage.tsx index 217c8533173..1032407a94f 100644 --- a/ui/apps/console/src/pages/DocPage.tsx +++ b/ui/apps/console/src/pages/DocPage.tsx @@ -109,7 +109,22 @@ export default function DocPage() { // ADR-0048 — pass the route's package so the single-doc fetch is // package-scoped (prefer-local) on the server. With this, doc names // need not be globally namespace-prefixed; the prefix becomes optional. - const raw: any = await adapter.getClient().meta.getItem('doc', name, appName ? { packageId: appName } : undefined); + // + // An exact package address answers only that package's own doc + // (ADR-0150 D3/D5): `404` where the route's package ships none of the + // name. The route's segment is prefer-local context, never an exact + // address, so that answer falls back to the read by name, as the + // portal reads it: a cross-reference to another package's doc, and + // the app-name segment of a package that ships several apps (no + // package id at all), read the one holder, or the holders listed below. + const client = adapter.getClient(); + let raw: any; + try { + raw = await client.meta.getItem('doc', name, appName ? { packageId: appName } : undefined); + } catch (localErr: any) { + if (!appName || localErr?.httpStatus !== 404) throw localErr; + raw = await client.meta.getItem('doc', name); + } const item = raw?.item ?? raw?.data ?? raw; if (cancelled) return; if (item && typeof item.content === 'string') { diff --git a/ui/apps/console/src/pages/docs-portal.test.tsx b/ui/apps/console/src/pages/docs-portal.test.tsx index a0413e7774f..8e393c290c2 100644 --- a/ui/apps/console/src/pages/docs-portal.test.tsx +++ b/ui/apps/console/src/pages/docs-portal.test.tsx @@ -92,6 +92,12 @@ const { ADAPTER, WORLD } = vi.hoisted(() => { const conflictRead = (name: string, packageId: string | undefined) => { if (name === 'broken_doc') throw failure(500, 'INTERNAL_ERROR', 'The metadata service is unavailable'); const holders = Object.keys(CONFLICT_CONTENT).filter((p) => name in CONFLICT_CONTENT[p]); + WORLD.reads.push(packageId); + // objectstack#34247 — the server's exact address answers only that + // package's own doc: 404 where it ships none of the name. + if (packageId && WORLD.exact && !holders.includes(packageId)) { + throw failure(404, 'RESOURCE_NOT_FOUND', `doc "${name}" not found in package "${packageId}"`); + } if (packageId) return { item: { name, content: CONFLICT_CONTENT[packageId]?.[name] } }; if (holders.length > 1) { throw failure(409, 'RESOURCE_CONFLICT', `doc "${name}" is held by ${holders.length} packages`, { @@ -100,7 +106,7 @@ const { ADAPTER, WORLD } = vi.hoisted(() => { } return { item: { name, content: holders.length ? CONFLICT_CONTENT[holders[0]][name] : undefined } }; }; - const WORLD = { authored: false, conflict: false }; + const WORLD = { authored: false, conflict: false, exact: false, reads: [] as Array }; const ADAPTER = { getClient: () => ({ meta: { @@ -559,4 +565,52 @@ describe('objectstack#34070 — a doc name two packages ship lists its candidate expect(screen.getByText('The metadata service is unavailable')).toBeInTheDocument(); expect(screen.queryByRole('list', { name: 'Packages that provide this document' })).toBeNull(); }); + + /** + * objectstack#34247 — the server's `?package=X` read answers X's own doc or + * 404. The route's segment is ADR-0048 prefer-local context, not an exact + * address: the doc the route's package ships none of is read by name. + */ + describe('objectstack#34247 — a doc the route\'s package ships none of is read by name', () => { + beforeEach(() => { + WORLD.exact = true; + WORLD.reads.length = 0; + }); + afterEach(() => { + WORLD.exact = false; + }); + + it('a cross-reference from one package\'s docs to another package\'s doc renders that doc', async () => { + render(); + expect(await screen.findByTestId('doc-content')).toHaveTextContent('BETA BODY'); + expect(WORLD.reads).toEqual(['com.example.alpha', undefined]); + }); + + it('an app-name segment that names no package renders the doc its one holder ships', async () => { + render(); + expect(await screen.findByTestId('doc-content')).toHaveTextContent('ALPHA BODY'); + expect(WORLD.reads).toEqual(['alpha_suite', undefined]); + }); + + it('a name two other packages ship lists both holders', async () => { + render(); + const links = within(await candidateList()).getAllByRole('link'); + expect(links.map((l) => l.getAttribute('href'))).toEqual([ + '/apps/com.example.alpha/docs/shared_guide', + '/apps/com.example.beta/docs/shared_guide', + ]); + }); + + it('CONTROL: the route\'s own package\'s doc is read at its package address only', async () => { + render(); + expect(await screen.findByTestId('doc-content')).toHaveTextContent('BETA SHARED BODY'); + expect(WORLD.reads).toEqual(['com.example.beta']); + }); + + it('CONTROL: a name no package ships is still "not found"', async () => { + render(); + expect(await screen.findByText(/It may belong to a package that is not installed/)).toBeInTheDocument(); + expect(screen.queryByTestId('doc-content')).toBeNull(); + }); + }); }); From de137717ef68cdba7099a2bc52c0d52811b873ae Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:32:24 +0000 Subject: [PATCH 05/15] fix(metadata-protocol)!: an exact read of a name the package holds none of is refused naming the holders (ruling 6917064203 on #34398) - registryAnswerAtAddress refuses 409 not-held-by-qualifier naming each package that holds the name, on the plain read and /layers; a name nothing holds stays 404; the credential carry-forward still carries none. - DocPage falls back to the read by name on that 409 (candidates not naming the route's package) as on a 404. - Pins flipped from 404 to the 409, both transports; nothing-holds controls. Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../34247-exact-read-own-item-or-none.md | 12 ++--- .../src/protocol-exact-qualifier.ts | 17 +++++++ .../src/protocol-meta-item-reads.ts | 36 +++++++++++---- .../src/protocol-meta-layered-reads.ts | 7 +-- .../package-scoped-exact-qualifier.test.ts | 45 ++++++++++++++----- ...meta-disabled-holder-artifact-door.test.ts | 23 +++++++++- ui/apps/console/src/pages/DocPage.tsx | 16 ++++--- .../console/src/pages/docs-portal.test.tsx | 10 ++++- 8 files changed, 126 insertions(+), 40 deletions(-) diff --git a/.changeset/34247-exact-read-own-item-or-none.md b/.changeset/34247-exact-read-own-item-or-none.md index ab9cbd8b70b..1cf21f708e9 100644 --- a/.changeset/34247-exact-read-own-item-or-none.md +++ b/.changeset/34247-exact-read-own-item-or-none.md @@ -5,7 +5,7 @@ '@object-ui/console': patch --- -fix(metadata-protocol)!: an exact `?package=X` read of a doc, view or other type the exact qualifier does not judge answers X's own item or 404, never another package's; a bare doc read of a name two enabled packages ship, beside the environment's own package-less entry, serves that entry, never the package registered last (ADR-0150 D3/D5, red line 2, ruling 6893582352) +fix(metadata-protocol)!: an exact `?package=X` read of a doc, view or other type the exact qualifier does not judge answers X's own item, never another package's: where another package holds the name it is refused 409 `not-held-by-qualifier` naming the holders (ruling 6917064203 on #34398), and a name nothing holds stays 404; a bare doc read of a name two enabled packages ship, beside the environment's own package-less entry, serves that entry, never the package registered last (ADR-0150 D3/D5, red line 2, ruling 6893582352) Clause-②: no (narrowing) Metadata-protocol: none @@ -15,17 +15,17 @@ Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?pac **BREAKING** for a caller that reads `?package=X` of a name X ships no item of, for the types the exact qualifier does not judge (`doc`, `view`, `translation`, `field`, `seed`, `datasource`, `external_catalog`, `object_extension`). Measured on the composed artifact rig (the `MetadataPlugin` artifact door plus `AppPlugin`), on the dispatcher and on `RestServer`, in both registration orders: -- `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME (installed or not) and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now 404. -- `GET /meta/TYPE/NAME/layers?package=X`, same address: was 200 with another package's `code` and `effective`. It is now 404. +- `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now `409 RESOURCE_CONFLICT`, reason `not-held-by-qualifier`, with `details.candidates` naming each package that holds NAME (ruling 6917064203 on #34398), the refusal the covered types already answer. X need not be an installed package: a qualifier that names none (the Console's app-name segment) gets the same answer. A name no package holds stays the read's own 404. +- `GET /meta/TYPE/NAME/layers?package=X`, same address: was 200 with another package's `code` and `effective`. It is now the same 409. - `GET /meta/TYPE/NAME/layers?package=X`, where X and Y ship NAME and Y registered last: was 200 with Y's `code` and `effective` (the metadata service keeps such a type by name alone). It is now X's, as the plain read answers since #34040. - `GET /meta/doc/NAME` and its `/layers` and `/published`, where two enabled packages ship NAME and the registry's bare slot holds a package-less entry: was 200 with the doc of the package the metadata service registered last. It is now 200 with the environment's own item, as the registry and `MetadataFacade.get` already served it. Without such an entry the read stays refused 409 naming both (#34036). Per entry: - A stamp-less runtime registration: the plain read and `/published` serve its body; `/layers` reports it as `code` and `effective`. - A stored package-less row the hydrator registered before any package shipped the name (its entry is tenant-authored, `_provenance: 'org'`, so it is no code layer): the plain read and `/published` serve the row; `/layers` reports `code: null` and the row as `overlay` and `effective`. - Both `/published` doors (the dispatcher's and `RestServer`'s) serve that item in place of the metadata service's package copy. - The same stored row hydrated after the packages' artifacts registered wears the first registered holder's envelope (the hydrator grafts it), so no package-less entry exists: the bare doors stay refused 409 naming both, as before. -- A save naming package X of a `datasource` with no stored row at X (the credential carry-forward reads the code layer, `readCodeLayerForCarryForward`): carried forward the credential of the package the metadata service kept, or of the first registered holder. It now carries X's own credential, or none when X ships no datasource of the name (the incoming body is kept as sent). Of this family only `datasource` carries a credential, so no other save moves. Path: a save door naming the package (`PUT /meta/datasource/NAME?package=X`), its draft save, and any carry-forward of a body whose credentials the read redacted. +- A save naming package X of a `datasource` with no stored row at X (the credential carry-forward reads the code layer, `readCodeLayerForCarryForward`): carried forward the credential of the package the metadata service kept, or of the first registered holder. It now carries X's own credential, or none when X ships no datasource of the name (the incoming body is kept as sent; the carry-forward is no read answer, so it does not refuse). Of this family only `datasource` carries a credential, so no other save moves. Path: a save door naming the package (`PUT /meta/datasource/NAME?package=X`), its draft save, and any carry-forward of a body whose credentials the read redacted. -**Console.** The doc page under an app (`/apps/X/docs/...`) reads with X as ADR-0048 prefer-local context. When that read answers 404, it now reads the doc by name. A cross-reference from X's docs to another package's doc, and the app-name segment of a package that ships several apps (which names no package), keep rendering the doc's one holder; a name two other packages ship lists them (the 409 candidate list), where it showed one of them by registration order. +**Console.** The doc page under an app (`/apps/X/docs/...`) reads with X as ADR-0048 prefer-local context. When that read answers the `not-held-by-qualifier` 409 or a 404, it now reads the doc by name. A cross-reference from X's docs to another package's doc, and the app-name segment of a package that ships several apps (which names no package), keep rendering the doc's one holder; a name two other packages ship lists them (the 409 candidate list), where it showed one of them by registration order. **Not moved.** - A holder's own address, a customization pair's address of its base's item, and an item bound to no package (the environment's entry). @@ -36,4 +36,4 @@ Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?pac **No migration.** No schema key, stored row or registry slot changes; nothing is rewritten. -The fix for a caller: address a package that ships the name (or its pair), or read with no package. For the bare doc read beside the environment's own entry, address a holder with `?package=` to read that holder's doc. +The fix for a caller: address a package the refusal names (or its pair), or read with no package. For the bare doc read beside the environment's own entry, address a holder with `?package=` to read that holder's doc. diff --git a/packages/metadata-protocol/src/protocol-exact-qualifier.ts b/packages/metadata-protocol/src/protocol-exact-qualifier.ts index 6cdec6f37dd..ed233dcf70e 100644 --- a/packages/metadata-protocol/src/protocol-exact-qualifier.ts +++ b/packages/metadata-protocol/src/protocol-exact-qualifier.ts @@ -271,6 +271,23 @@ function refusal( return new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); } +/** + * [ruling 6917064203 on #34398, ADR-0150 D5] The refusal of an address naming + * a package that holds no item of the name, for a type outside the exact + * qualifier ({@link admitExactQualifier} judges the covered set): the same + * `not-held-by-qualifier` refusal, naming each package that holds the name. + * Asked only where another package holds it; a name nothing holds is the + * read's own miss. + */ +export function notHeldByQualifierRefusal( + type: string, + name: string, + packageId: string, + holders: readonly string[], +): PackageScopedNameRefusedError { + return refusal(type, name, packageId, 'not-held-by-qualifier', holders.map((holder) => ({ kind: 'package' as const, packageId: holder }))); +} + /** * Judge a by-name read that names package `packageId` as its exact qualifier. * diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index d48ee944874..f1060a07aa3 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -53,6 +53,7 @@ import { declinesPackageLessRowAt, exactQualifierItem, isPackageLessRow, + notHeldByQualifierRefusal, refuseUnjudgeableByNameRead, } from './protocol-exact-qualifier.js'; import { canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; @@ -463,21 +464,29 @@ export function serviceCopyOfAnotherPackage( /** * [ADR-0150 D3/D5, red line 2] The item the code layers (the artifact lookup * and the registry) answer at an address naming a package (`?package=X`) of - * a type the exact qualifier does not judge: X's own item, or nothing, so the - * read answers 404. Another package's item ({@link serviceCopyOfAnotherPackage}'s - * test, applied to the code layers' answer) is replaced by the registry's - * package slot for X; when X holds no item of the name, nothing is served. + * a type the exact qualifier does not judge: X's own item. Another package's + * item ({@link serviceCopyOfAnotherPackage}'s test, applied to the code + * layers' answer) is replaced by the registry's package slot for X. + * + * When X holds no item of the name, a read (`options.refuse`) is refused + * `409 not-held-by-qualifier` naming each package that holds it (ruling + * 6917064203 on #34398), as the exact qualifier refuses the covered types; X + * need not be an installed package. Any other caller (the save's credential + * carry-forward) gets nothing, so it carries nothing. * * Before, a package that holds no item of the name answered `getItem`'s last * tier, the first composite across packages: another package's item, under * X's envelope. Unchanged: an item bound to no package (the environment's - * entry), an item stamped X, a customization pair's item, a stamp the - * registry does not know, and an `object`. + * entry, which answers first), an item stamped X, a customization pair's + * item, a stamp the registry does not know, and an `object`. * * ⛔ Not a security catalog type (`position`, `capability`; ADR-0131 D3): * the registry keeps one package holder of such a name, resolved by name * for the whole environment, so another package's address has no slot of * its own to answer with. Its answer there stays the code layers' own. + * + * @throws {PackageScopedNameRefusedError} `not-held-by-qualifier` (with + * `options.refuse`), when X holds no item of the name and another package does. */ export function registryAnswerAtAddress( host: Pick, @@ -485,14 +494,23 @@ export function registryAnswerAtAddress( item: unknown, member: string | undefined, isWantedMember: (candidate: unknown) => boolean, + options: { readonly refuse?: boolean } = {}, ): unknown { if (!request.packageId || item === undefined || item === null || isSecurityCatalogType(request.type)) return item; if (!serviceCopyOfAnotherPackage(host, request, item)) return item; - const scoped = host.engine?.registry as { getPackageScopedItem?(type: string, name: string, packageId: string, member?: string): unknown } | undefined; + const scoped = host.engine?.registry as { + getPackageScopedItem?(type: string, name: string, packageId: string, member?: string): unknown; + packageScopedHoldersOf?(type: string, name: string): string[] | undefined; + } | undefined; const own = typeof scoped?.getPackageScopedItem === 'function' ? scoped.getPackageScopedItem(request.type, request.name, request.packageId, member) : undefined; - return own !== undefined && own !== null && isWantedMember(own) ? own : undefined; + if (own !== undefined && own !== null && isWantedMember(own)) return own; + if (options.refuse === true) { + const holders = (scoped?.packageScopedHoldersOf?.(request.type, request.name) ?? []).filter((holder) => holder !== request.packageId); + if (holders.length > 0) throw notHeldByQualifierRefusal(request.type, request.name, request.packageId, holders); + } + return undefined; } /** The same item: one object, or (a loader's fresh copy) the same JSON. */ @@ -1353,7 +1371,7 @@ export async function readMetaItem(host: Pick { expect((await protocol.getMetaItem({ type: 'page', name: 'nothing', packageId: A }))?.item).toBeUndefined(); }); - it('a type outside the nine (view) keeps the prefer-local read at its holder; [#34247] a package holding none answers nothing (BASE: alpha\'s)', async () => { + it('a type outside the nine (view) keeps the prefer-local read at its holder; [#34247] a package holding none is refused naming the holder (BASE: alpha\'s)', async () => { registry.registerItem('view', { name: 'all', label: 'alpha view' }, 'name' as never, A); expect(labelOf(await protocol.getMetaItem({ type: 'view', name: 'all', packageId: A }))).toBe('alpha view'); - expect((await protocol.getMetaItem({ type: 'view', name: 'all', packageId: C }))?.item).toBeUndefined(); + const err = await refusalOf(() => protocol.getMetaItem({ type: 'view', name: 'all', packageId: C })); + expect([err.code, err.status, err.refusal.reason, err.refusal.candidates]).toEqual(['RESOURCE_CONFLICT', 409, 'not-held-by-qualifier', [{ kind: 'package', packageId: A }]]); }); it('a read naming no package is E8\'s, unchanged', async () => { @@ -395,7 +396,7 @@ describe('fail closed — a registry with no package-scoped resolver refuses wha expect(declaredRefusalMessage(err)).toBe(err.message); }); - it('CONTROL: a type ADR-0150 does not address by package (view) keeps `getItem`\'s read, both ways; [#34247] a package holding none answers nothing', async () => { + it('CONTROL: a type ADR-0150 does not address by package (view) keeps `getItem`\'s read, both ways; [#34247] a package holding none answers nothing (no holder can be named without the slice)', async () => { registry.registerItem('view', { name: 'all', label: 'alpha view' }, 'name' as never, A); expect(labelOf(await sliceless.getMetaItem({ type: 'view', name: 'all', packageId: A }))).toBe('alpha view'); expect(labelOf(await sliceless.getMetaItem({ type: 'view', name: 'all' }))).toBe('alpha view'); @@ -581,10 +582,11 @@ describe('a covered type the registry reads through `getItem` (seat rulings (a), expect(() => protocol.admitEnvironmentQualifier({ type: 'flow', name: 'local' })).not.toThrow(); }); - it('CONTROL: a type outside the covered set (view) keeps the prefer-local read at its holder; [#34247] a package holding none answers nothing', async () => { + it('CONTROL: a type outside the covered set (view) keeps the prefer-local read at its holder; [#34247] a package holding none is refused naming the holder', async () => { registry.registerItem('view', { name: 'all', label: 'alpha view' }, 'name' as never, A); expect(labelOf(await protocol.getMetaItem({ type: 'view', name: 'all', packageId: A }))).toBe('alpha view'); - expect((await protocol.getMetaItem({ type: 'view', name: 'all', packageId: C }))?.item).toBeUndefined(); + const err = await refusalOf(() => protocol.getMetaItem({ type: 'view', name: 'all', packageId: C })); + expect([err.code, err.status, err.refusal.reason, err.refusal.candidates]).toEqual(['RESOURCE_CONFLICT', 409, 'not-held-by-qualifier', [{ kind: 'package', packageId: A }]]); }); }); }); @@ -835,8 +837,10 @@ describe('[#34040] the exact read never serves the service\'s copy of another pa /** * [#34247, ADR-0150 D3/D5, red line 2] The exact read of a name the package it - * names holds no item of, for the same family: X's item or 404, never another - * holder's. The step-2 decline above left such an address to the registry's + * names holds no item of, for the same family: never another holder's item. + * Where another package holds the name, the read is refused `409 + * not-held-by-qualifier` naming the holders (ruling 6917064203 on #34398, which + * amends the card's "404"); a name nothing holds is the read's own 404. The step-2 decline above left such an address to the registry's * `getItem`, whose last tier is the first composite across packages, so * `?package=gamma` of a doc only alpha and beta ship served one of theirs. * @@ -845,7 +849,7 @@ describe('[#34040] the exact read never serves the service\'s copy of another pa * registered holder's body, whichever copy the service kept, and with the * service holding nothing. */ -describe('[#34247] the exact read of a name the package holds no item of answers nothing, for every type the registry does not read by package', () => { +describe('[#34247] the exact read of a name the package holds no item of is refused naming the holders, for every type the registry does not read by package', () => { const OUTSIDE_PINNED = MetadataTypeSchema.options.filter((type) => !(PACKAGE_SCOPED_READ_TYPES as readonly string[]).includes(type) && !(PACKAGE_SCOPED_TYPES as readonly string[]).includes(type) && !['position', 'capability', 'object'].includes(type)); /** Judged by the exact qualifier after the layers: its own refusal, unchanged. */ @@ -874,27 +878,44 @@ describe('[#34247] the exact read of a name the package holds no item of answers }); it.each(OUTSIDE_PINNED.flatMap((type) => [[type, [A, B]], [type, [B, A]]] as const))( - '%s, registered %j: `?package=` of a third package answers nothing, whichever holder\'s copy the service keeps', + '%s, registered %j: `?package=` of a third package (installed or not) is refused naming both holders, whichever holder\'s copy the service keeps, on the plain read and /layers', async (type, order) => { for (const id of order) shipParsed(type, 'shared', id); for (const kept of [...order, undefined]) { const served = servedWith(kept ? { name: 'shared', label: `${kept.split('.').pop()} ${type}`, _packageId: kept } : undefined); for (const packageId of [C, 'com.acme.unknown']) { - expect(await itemAt(served, type, packageId), `${type} at ${packageId}, the service keeping ${kept ?? 'nothing'}`).toBeUndefined(); + const at = `${type} at ${packageId}, the service keeping ${kept ?? 'nothing'}`; + for (const read of [ + () => served.getMetaItem({ type, name: 'shared', packageId }), + () => served.getMetaItemLayered({ type, name: 'shared', packageId }), + ]) { + const err = await refusalOf(read); + expect([err.code, err.status, err.refusal.reason, err.refusal.callerPackageId], at).toEqual(['RESOURCE_CONFLICT', 409, 'not-held-by-qualifier', packageId]); + expect(err.refusal.candidates.map((c) => (c as { packageId?: string }).packageId).sort(), at).toEqual([A, B]); + } } } }, ); - it.each(OUTSIDE_PINNED)('%s, one holder: `?package=` of another package answers nothing; the holder\'s own address its body', async (type) => { + it.each(OUTSIDE_PINNED)('%s, one holder: `?package=` of another package is refused naming the holder; the holder\'s own address its body', async (type) => { shipParsed(type, 'shared', A); for (const kept of [A, undefined]) { const served = servedWith(kept ? { name: 'shared', label: `alpha ${type}`, _packageId: kept } : undefined); - expect(await itemAt(served, type, B), `${type} at ${B}, the service keeping ${kept ?? 'nothing'}`).toBeUndefined(); + const err = await refusalOf(() => served.getMetaItem({ type, name: 'shared', packageId: B })); + expect([err.code, err.status, err.refusal.reason, err.refusal.candidates], `${type} at ${B}, the service keeping ${kept ?? 'nothing'}`) + .toEqual(['RESOURCE_CONFLICT', 409, 'not-held-by-qualifier', [{ kind: 'package', packageId: A }]]); expect((await itemAt(served, type, A))?.label, `${type} at its holder`).toBe(`alpha ${type}`); } }); + it.each(OUTSIDE_PINNED)('CONTROL — %s: a name no package holds is the read\'s own miss at any package address, never a refusal', async (type) => { + const served = servedWith(undefined); + for (const packageId of [A, C, 'com.acme.unknown']) { + expect(await itemAt(served, type, packageId), `${type} at ${packageId}`).toBeUndefined(); + } + }); + /** * [review S2] Outside the family: a security catalog type (ADR-0131 D3) * keeps one package holder of a name, resolved by name environment-wide, so diff --git a/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts b/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts index 82993a3ab9a..80c3686fb0a 100644 --- a/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts +++ b/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts @@ -288,12 +288,31 @@ describe.each([ rmSync(booted.root, { recursive: true, force: true }); }); - it('`?package=` of a package shipping none (installed or not) answers 404 on the plain read and /layers, both transports, never a holder\'s doc', async () => { + // [ruling 6917064203 on #34398] Refused naming the holders, as the exact + // qualifier refuses the covered types; a qualifier that names no + // installed package (the Console's app-name segment) is answered the same. + it('`?package=` of a package shipping none (installed or not) is refused 409 `not-held-by-qualifier` naming the holders on the plain read and /layers, both transports, never a holder\'s doc', async () => { const nonHolders = [ALPHA, GAMMA, NOT_INSTALLED].filter((id) => !ships.includes(id)); for (const packageId of nonHolders) { for (const answer of await exactDocAndLayers(booted!, packageId)) { + const body = JSON.stringify(answer.body ?? null); + const details = answer.body?.error && typeof answer.body.error === 'object' ? answer.body.error.details : answer.body?.details; + const named = ((details?.candidates ?? []) as Array<{ kind?: string; packageId?: string }>).map((c) => `${c.kind}:${c.packageId}`).sort(); + expect([answer.status, errorCodeOf(answer.body), named, answer.door], body) + .toEqual([409, 'RESOURCE_CONFLICT', ships.map((holder) => `package:${holder}`).sort(), answer.door]); + expect(body, answer.door).not.toMatch(/(alpha|beta) doc|# (alpha|beta)/); + } + } + }); + + it('CONTROL: a doc name no package ships is the read\'s own 404 at any package address, both transports', async () => { + for (const packageId of [ALPHA, GAMMA, NOT_INSTALLED]) { + const query = { package: packageId }; + for (const answer of [ + { door: `dispatcher doc/no_such_doc?package=${packageId}`, ...(await viaDispatcher(booted!.kernel, '/meta/doc/no_such_doc', query)) }, + { door: `rest doc/no_such_doc?package=${packageId}`, ...(await viaRest(booted!, '/meta/:type/:name', { type: 'doc', name: 'no_such_doc' }, query)) }, + ]) { expect([answer.status, errorCodeOf(answer.body), answer.door], JSON.stringify(answer.body)).toEqual([404, 'RESOURCE_NOT_FOUND', answer.door]); - expect(JSON.stringify(answer.body ?? null), answer.door).not.toMatch(/(alpha|beta) doc/); } } }); diff --git a/ui/apps/console/src/pages/DocPage.tsx b/ui/apps/console/src/pages/DocPage.tsx index 1032407a94f..276c9c4f82f 100644 --- a/ui/apps/console/src/pages/DocPage.tsx +++ b/ui/apps/console/src/pages/DocPage.tsx @@ -111,18 +111,22 @@ export default function DocPage() { // need not be globally namespace-prefixed; the prefix becomes optional. // // An exact package address answers only that package's own doc - // (ADR-0150 D3/D5): `404` where the route's package ships none of the - // name. The route's segment is prefer-local context, never an exact - // address, so that answer falls back to the read by name, as the - // portal reads it: a cross-reference to another package's doc, and + // (ADR-0150 D3/D5): where the route's package ships none of the name, + // a `409` whose candidates name the packages that do, the route's not + // among them (ruling 6917064203 on objectstack#34398), or `404` when + // none does. The route's segment is prefer-local context, never an + // exact address, so either answer falls back to the read by name, as + // the portal reads it: a cross-reference to another package's doc, and // the app-name segment of a package that ships several apps (no - // package id at all), read the one holder, or the holders listed below. + // package id at all), read the one holder, or list the holders below. const client = adapter.getClient(); let raw: any; try { raw = await client.meta.getItem('doc', name, appName ? { packageId: appName } : undefined); } catch (localErr: any) { - if (!appName || localErr?.httpStatus !== 404) throw localErr; + if (!appName) throw localErr; + const holders = conflictCandidates(localErr); + if (localErr?.httpStatus !== 404 && (holders === null || holders.includes(appName))) throw localErr; raw = await client.meta.getItem('doc', name); } const item = raw?.item ?? raw?.data ?? raw; diff --git a/ui/apps/console/src/pages/docs-portal.test.tsx b/ui/apps/console/src/pages/docs-portal.test.tsx index 8e393c290c2..e39abe1cfbe 100644 --- a/ui/apps/console/src/pages/docs-portal.test.tsx +++ b/ui/apps/console/src/pages/docs-portal.test.tsx @@ -94,9 +94,15 @@ const { ADAPTER, WORLD } = vi.hoisted(() => { const holders = Object.keys(CONFLICT_CONTENT).filter((p) => name in CONFLICT_CONTENT[p]); WORLD.reads.push(packageId); // objectstack#34247 — the server's exact address answers only that - // package's own doc: 404 where it ships none of the name. + // package's own doc: where it ships none of the name, 409 + // `not-held-by-qualifier` naming the holders (ruling 6917064203 on + // objectstack#34398), or 404 when no package ships it. if (packageId && WORLD.exact && !holders.includes(packageId)) { - throw failure(404, 'RESOURCE_NOT_FOUND', `doc "${name}" not found in package "${packageId}"`); + if (holders.length === 0) throw failure(404, 'RESOURCE_NOT_FOUND', `doc "${name}" not found`); + // The server's envelope carries the candidates, not the reason. + throw failure(409, 'RESOURCE_CONFLICT', `doc "${name}" is not held by package "${packageId}"`, { + candidates: holders.map((p) => ({ kind: 'package', packageId: p })), + }); } if (packageId) return { item: { name, content: CONFLICT_CONTENT[packageId]?.[name] } }; if (holders.length > 1) { From 8c929a558fa9e9be7902453fb04539ab26d5164e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:15:40 +0000 Subject: [PATCH 06/15] fix(metadata-protocol,rest,runtime,console): the audience gate answers before the not-held refusal; the flat doc permalink reads a name its route's package ships none of by name; the hydrated row's layered rule applies only to its own tenant-authored entry - review M2: `DocsSlug.refusalFor` falls back to the read by name on the not-held 409 (route segment not among the candidates) or a 404, through one rule shared with `DocPage` (`doc-address.ts`); pinned under WORLD.exact for a cross-package link and an app-name segment. - ruling 6917064203 parameter 5: for a doc, the audience gate answers before any refusal that names holders (`gateHolderNamingRefusal`, asked by both transports' plain read and /layers read); pinned for a refused member (403), an anonymous caller (401) and an admitted caller (409). - review S4: `environmentRowAnswers` holds only where the bare entry is the row's tenant-authored copy (code null); the mixed state (stamp-less registration beside a different package-less row) is pinned. Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../34247-exact-read-own-item-or-none.md | 5 +- .../src/protocol-meta-layered-reads.ts | 7 +- packages/rest/src/index.ts | 1 + packages/rest/src/meta-item-read-gate.ts | 33 +++ packages/rest/src/meta-item-read-routes.ts | 25 +- packages/rest/src/rest-server.ts | 18 +- ...meta-disabled-holder-artifact-door.test.ts | 28 +- .../meta-holder-refusal-audience-gate.test.ts | 245 ++++++++++++++++++ packages/runtime/src/domains/meta.ts | 25 +- ui/apps/console/src/pages/DocPage.tsx | 25 +- ui/apps/console/src/pages/DocsSlug.tsx | 15 +- ui/apps/console/src/pages/doc-address.ts | 50 ++++ .../console/src/pages/docs-portal.test.tsx | 42 ++- 13 files changed, 483 insertions(+), 36 deletions(-) create mode 100644 packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts create mode 100644 ui/apps/console/src/pages/doc-address.ts diff --git a/.changeset/34247-exact-read-own-item-or-none.md b/.changeset/34247-exact-read-own-item-or-none.md index 1cf21f708e9..e04b8f4869a 100644 --- a/.changeset/34247-exact-read-own-item-or-none.md +++ b/.changeset/34247-exact-read-own-item-or-none.md @@ -15,17 +15,18 @@ Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?pac **BREAKING** for a caller that reads `?package=X` of a name X ships no item of, for the types the exact qualifier does not judge (`doc`, `view`, `translation`, `field`, `seed`, `datasource`, `external_catalog`, `object_extension`). Measured on the composed artifact rig (the `MetadataPlugin` artifact door plus `AppPlugin`), on the dispatcher and on `RestServer`, in both registration orders: -- `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now `409 RESOURCE_CONFLICT`, reason `not-held-by-qualifier`, with `details.candidates` naming each package that holds NAME (ruling 6917064203 on #34398), the refusal the covered types already answer. X need not be an installed package: a qualifier that names none (the Console's app-name segment) gets the same answer. A name no package holds stays the read's own 404. +- `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now `409 RESOURCE_CONFLICT`, reason `not-held-by-qualifier`, with `details.candidates` naming each package that holds NAME (ruling 6917064203 on #34398), the refusal the covered types already answer. X need not be an installed package: a qualifier that names none (the Console's app-name segment) gets the same answer. A name no package holds stays the read's own 404. For a `doc`, the audience gate answers before any refusal that names holders: a caller the ADR-0046 §6.7 docs audience refuses is answered the gate's `401 UNAUTHENTICATED` or `403 PERMISSION_DENIED`, and a caller it admits the 409. - `GET /meta/TYPE/NAME/layers?package=X`, same address: was 200 with another package's `code` and `effective`. It is now the same 409. - `GET /meta/TYPE/NAME/layers?package=X`, where X and Y ship NAME and Y registered last: was 200 with Y's `code` and `effective` (the metadata service keeps such a type by name alone). It is now X's, as the plain read answers since #34040. - `GET /meta/doc/NAME` and its `/layers` and `/published`, where two enabled packages ship NAME and the registry's bare slot holds a package-less entry: was 200 with the doc of the package the metadata service registered last. It is now 200 with the environment's own item, as the registry and `MetadataFacade.get` already served it. Without such an entry the read stays refused 409 naming both (#34036). Per entry: - A stamp-less runtime registration: the plain read and `/published` serve its body; `/layers` reports it as `code` and `effective`. + - The same registration beside a different package-less stored row: all three doors serve the registration; `/layers` reports it as `code` and `effective` and the row as `overlay`. - A stored package-less row the hydrator registered before any package shipped the name (its entry is tenant-authored, `_provenance: 'org'`, so it is no code layer): the plain read and `/published` serve the row; `/layers` reports `code: null` and the row as `overlay` and `effective`. - Both `/published` doors (the dispatcher's and `RestServer`'s) serve that item in place of the metadata service's package copy. - The same stored row hydrated after the packages' artifacts registered wears the first registered holder's envelope (the hydrator grafts it), so no package-less entry exists: the bare doors stay refused 409 naming both, as before. - A save naming package X of a `datasource` with no stored row at X (the credential carry-forward reads the code layer, `readCodeLayerForCarryForward`): carried forward the credential of the package the metadata service kept, or of the first registered holder. It now carries X's own credential, or none when X ships no datasource of the name (the incoming body is kept as sent; the carry-forward is no read answer, so it does not refuse). Of this family only `datasource` carries a credential, so no other save moves. Path: a save door naming the package (`PUT /meta/datasource/NAME?package=X`), its draft save, and any carry-forward of a body whose credentials the read redacted. -**Console.** The doc page under an app (`/apps/X/docs/...`) reads with X as ADR-0048 prefer-local context. When that read answers the `not-held-by-qualifier` 409 or a 404, it now reads the doc by name. A cross-reference from X's docs to another package's doc, and the app-name segment of a package that ships several apps (which names no package), keep rendering the doc's one holder; a name two other packages ship lists them (the 409 candidate list), where it showed one of them by registration order. +**Console.** The doc page under an app (`/apps/X/docs/...`) and the flat permalink every cross-reference is rewritten to (`/apps/X/docs/NAME`, whose single-item read tells a refused name from an absent one) read with X as ADR-0048 prefer-local context. When that read answers the `not-held-by-qualifier` 409 (X not among the candidates) or a 404, each now reads the name again by name. A cross-reference from X's docs to another package's doc, and the app-name segment of a package that ships several apps (which names no package), keep rendering the doc's one holder, or its holder's audience refusal on the flat permalink; a name two other packages ship lists them (the 409 candidate list), where it showed one of them by registration order. **Not moved.** - A holder's own address, a customization pair's address of its base's item, and an item bound to no package (the environment's entry). diff --git a/packages/metadata-protocol/src/protocol-meta-layered-reads.ts b/packages/metadata-protocol/src/protocol-meta-layered-reads.ts index db47c59df0a..896a844b151 100644 --- a/packages/metadata-protocol/src/protocol-meta-layered-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-layered-reads.ts @@ -806,8 +806,13 @@ export async function getMetaItemLayered(host: Pick | undefined> { + if (metaType !== 'doc') return undefined; + const reason = (thrown as { refusal?: { reason?: unknown } } | null | undefined)?.refusal?.reason; + if (reason !== 'not-held-by-qualifier') return undefined; + const named = { name }; + const verdict = await createMetaItemReadGate(sources, metaType, name, [named], policy)(named); + return verdict.kind === 'refuse' && verdict.refusal.reason === 'docs-audience' ? verdict.refusal : undefined; +} + // ── THE layered answer ──────────────────────────────────────────────────────── /** diff --git a/packages/rest/src/meta-item-read-routes.ts b/packages/rest/src/meta-item-read-routes.ts index 356116bd6b7..54fcf8bde03 100644 --- a/packages/rest/src/meta-item-read-routes.ts +++ b/packages/rest/src/meta-item-read-routes.ts @@ -1086,7 +1086,26 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M // [#22877] The member, read once above. ...memberSelector, }; - const envelope = await measureMetaRead(() => p.getMetaItem(itemRequest)) as Record; + // [ruling 6917064203 on #34398] The audience gate answers + // before any refusal that names holders + // (`gateHolderNamingRefusal`, the one both transports ask). + const readPolicyFor: MetaReadGatePolicy = isDraftRead + ? this.STORED_VERSION_DOOR_POLICY + : { arms: 'all', app: 'gate' }; + let envelope: Record; + try { + envelope = await measureMetaRead(() => p.getMetaItem(itemRequest)) as Record; + } catch (readError) { + const gated = await metaReadGate.gateHolderNamingRefusal( + this.metaItemAnswerSources(environmentId, req, p, readPolicyFor), + metaType, req.params.name, readPolicyFor, readError, + ); + if (gated) { + this.sendMetaReadRefusal(res, gated); + return; + } + throw readError; + } // [#20408] Everything this read does to the envelope // after the store read is ONE chain, @@ -1121,9 +1140,7 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M // other caller" is every other caller who may READ // drafts: one who may not never reaches this branch // (`isDraftRead` is false for them). - const readPolicy: MetaReadGatePolicy = isDraftRead - ? this.STORED_VERSION_DOOR_POLICY - : { arms: 'all', app: 'gate' }; + const readPolicy: MetaReadGatePolicy = readPolicyFor; const answer = await metaReadGate.createMetaItemAnswer( this.metaItemAnswerSources(environmentId, req, p, readPolicy), { metaType, name: req.params.name, policy: readPolicy, maskPosture }, diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 4cfa35f26e2..9696a09c791 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -4452,7 +4452,23 @@ export class RestServer { return; } const layeredOptions = { withDraft: mayReadPendingDrafts(layeredCaller) }; - const layered = await p.getMetaItemLayered(layeredRequest, layeredOptions); + let layered: unknown; + try { + layered = await p.getMetaItemLayered(layeredRequest, layeredOptions); + } catch (readError) { + // [ruling 6917064203 on #34398] The audience gate answers before + // any refusal that names holders — the plain read's own question. + const gated = await metaReadGate.gateHolderNamingRefusal( + this.metaItemReadGateSources(environmentId, req, p, true), + RestServer.metaTypeSingular(req.params.type), req.params.name, + metaReadGate.STORED_VERSION_DOOR_POLICY, readError, + ); + if (gated) { + RestServer.sendMetaReadRefusal(res, gated); + return; + } + throw readError; + } // [#20156 · #20478] THE per-caller gate on every layer, then the mask — // the shared chain. The stored-version doors honour the author // exemption, so the caller carries this transport's save-door diff --git a/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts b/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts index 80c3686fb0a..0dca2b70f3a 100644 --- a/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts +++ b/packages/runtime/src/domains/meta-disabled-holder-artifact-door.test.ts @@ -394,6 +394,15 @@ describe.each([ const last = packages[packages.length - 1]!; const lastDoc = `${last.split('.').pop()} doc`; + // The environment's package-less stored row, laid once per kernel (the + // pins below read it in turn). + let rowLaid = false; + const layRowOnce = async () => { + if (rowLaid) return; + await layEnvironmentDocRow(booted!.engine); + rowLaid = true; + }; + beforeAll(async () => { booted = await bootArtifactKernel(packages, docBodyOf([ALPHA, BETA])); }, 120_000); @@ -462,7 +471,7 @@ describe.each([ // served the row while `/layers` answered `effective: null` (the sealed // doc's row declined) and both `/published` doors served an empty body. it('[#34248] a hydrated package-less row (hydrated before the artifacts): the plain read, /layers (no code layer, the row as overlay and effective) and /published serve the row on both transports, never the holder registered last; each exact address reads its own doc', async () => { - await layEnvironmentDocRow(booted!.engine); + await layRowOnce(); booted!.engine.registry.registerItem('doc', { name: 'shared_doc', label: 'environment doc', content: '# env', _provenance: 'org' } as never, 'name' as never); await expectBareDoorsServe({ item: 'environment doc', code: undefined, overlay: 'environment doc' }); await expectExactReadsOwnDoc(); @@ -471,6 +480,22 @@ describe.each([ await expectRefusedNamingBoth(); }); + // [review S4] A stamp-less runtime registration in the bare slot beside a + // DIFFERENT package-less stored row: the entry is a code layer, not the + // row's tenant-authored copy, so the row is no effective layer here and + // all three doors serve the entry, the row reported as `overlay` (as at + // 989f4ad7, before the hydrated row's rule was added). + it('[#34248] a stamp-less bare entry beside a different package-less stored row: the plain read, /layers (the entry as code and effective, the row as overlay) and /published serve the entry on both transports', async () => { + await layRowOnce(); + booted!.engine.registry.registerItem('doc', { name: 'shared_doc', label: 'bare entry', content: '# bare' } as never, 'name' as never); + try { + await expectBareDoorsServe({ item: 'bare entry', code: 'bare entry', overlay: 'environment doc' }); + await expectExactReadsOwnDoc(); + } finally { + docRegistryOf(booted!).delete('shared_doc'); + } + }); + // [review M1] The same stored row hydrated by the production read // (`loadMetaFromDb`) after the artifacts registered: the hydrator grafts // the first holder's envelope onto it, so no package-less entry exists @@ -478,6 +503,7 @@ describe.each([ // origin/main c9346317 and at this head). The other holder's address // reads its own doc. it('CONTROL [#34248]: the row hydrated after the artifacts (`loadMetaFromDb`) wears the first holder\'s envelope, and the bare doors refuse 409 naming both on both transports', async () => { + await layRowOnce(); const hydrated = await (booted!.kernel.getService('protocol') as { loadMetaFromDb(): Promise<{ loaded: number; errors: number }> }).loadMetaFromDb(); expect([hydrated.loaded > 0, hydrated.errors]).toEqual([true, 0]); const entry = docRegistryOf(booted!).get('shared_doc') as { _packageId?: unknown; _provenance?: unknown } | undefined; diff --git a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts new file mode 100644 index 00000000000..ea4df839e5a --- /dev/null +++ b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts @@ -0,0 +1,245 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ruling 6917064203 on #34398 · #34247] The audience gate answers before any + * refusal that names holders. + * + * An exact `?package=X` read of a doc X holds no item of, while another + * package holds the name, is refused by the protocol `409 RESOURCE_CONFLICT` + * `not-held-by-qualifier`, its candidates naming the holders. That refusal is + * the answer only for a caller the ADR-0046 §6.7 docs audience admits to the + * name: a member the gate refuses is answered the gate's `403 + * PERMISSION_DENIED`, an anonymous caller the gate's `401 UNAUTHENTICATED`, + * and neither answer names a holder. Both transports (the dispatcher and + * `RestServer`) ask the one question, `gateHolderNamingRefusal` in + * `@objectstack/rest`, on the plain read and on `/layers`. + * + * The protocol is a double that throws the protocol's own refusal shape; the + * gate, its audience resolution and both transports are the real ones. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { RestServer } from '@objectstack/rest'; +import { HttpDispatcher } from '../http-dispatcher.js'; +import { PackageScopedNameRefusedError } from '@objectstack/core'; +const THROW: { name?: string } = {}; + +// ── Fixtures (the #20193 parity rig's docs) ─────────────────────────────────── + +const DOC_SECRET = 'Rotate the tenant signing keys before every release.'; +const BOOK_SECRET = 'Restricted spine: the incident playbooks.'; + +const ADMIN_GUIDE = { + name: 'admin_guide', + label: 'Admin Guide', + description: BOOK_SECRET, + audience: { permissionSet: 'crm_admin' }, + _packageId: 'crm', + groups: [{ key: 'admin', label: 'Admin', include: 'crm_admin_*' }], +}; +const HELP_CENTER = { + name: 'help_center', + label: 'Help Centre', + audience: 'org', + _packageId: 'crm', + groups: [{ key: 'start', label: 'Start', include: 'crm_intro' }], +}; +const DOCS = [ + { name: 'crm_intro', label: 'Getting started', content: 'Welcome aboard.', _packageId: 'crm' }, + { name: 'crm_admin_runbook', label: 'Admin runbook', content: DOC_SECRET, _packageId: 'crm' }, +]; +const STORE: Record = { book: [ADMIN_GUIDE, HELP_CENTER], doc: DOCS }; + +const clone = (v: T): T => JSON.parse(JSON.stringify(v)); +const singular = (type: unknown): string => String(type ?? '').replace(/s$/, ''); +const find = (type: unknown, name: unknown): any => + (STORE[singular(type)] ?? []).find((i: any) => i.name === name); + +// ── Callers ─────────────────────────────────────────────────────────────────── + +interface Caller { + ctx: { userId?: string; isSystem: false; systemPermissions: string[] }; + holdings: string[]; + readableFields: string[]; +} +const CALLERS: Record<'holder' | 'non-holder' | 'anonymous', Caller> = { + holder: { + ctx: { userId: 'u_holder', isSystem: false, systemPermissions: [] }, + holdings: ['crm_admin'], + readableFields: [], + }, + 'non-holder': { + ctx: { userId: 'u_member', isSystem: false, systemPermissions: [] }, + holdings: [], + readableFields: [], + }, + anonymous: { ctx: { isSystem: false, systemPermissions: [] }, holdings: [], readableFields: [] }, +}; +type CallerName = keyof typeof CALLERS; + +/** + * The protocol's refusal of `?package=sales` for a doc `sales` ships none of + * while `crm` ships it (`notHeldByQualifierRefusal` in + * `@objectstack/metadata-protocol`): `PackageScopedNameRefusedError`, reason + * `not-held-by-qualifier`, naming the holder. + */ +function refuseIfAsked(type: unknown, name: unknown): void { + if (singular(type) !== 'doc' || name !== THROW.name) return; + const base = { + status: 'refused' as const, reason: 'not-held-by-qualifier' as const, type: 'doc', name: String(name), + callerPackageId: 'sales', candidates: [{ kind: 'package' as const, packageId: 'crm' }], + }; + throw new PackageScopedNameRefusedError({ ...base, message: `doc "${String(name)}" is not held by package "sales"` } as never); +} + +/** One protocol double, the same shape both transports read. */ +function protocolDouble() { + return { + getMetaTypes: vi.fn(async () => ({ types: Object.keys(STORE) })), + getMetaItems: vi.fn(async ({ type }: any) => clone(STORE[singular(type)] ?? [])), + getMetaItem: vi.fn(async ({ type, name }: any) => { + refuseIfAsked(type, name); + const found = find(type, name); + return { type: singular(type), name, item: found ? clone(found) : undefined, lock: 'none', editable: true, deletable: true, resettable: false }; + }), + getMetaItemLayered: vi.fn(async ({ type, name }: any) => { + refuseIfAsked(type, name); + const found = find(type, name); + const layer = () => (found ? clone(found) : null); + return { type: singular(type), name, code: layer(), overlay: layer(), effective: layer() }; + }), + }; +} + +const securityFor = (caller: Caller) => ({ + resolvePermissionSetNames: async () => caller.holdings, + getMetadataReadableFields: async () => caller.readableFields, +}); + +// ── The two transports ──────────────────────────────────────────────────────── + +interface Answer { status: number; code?: string; body: any; served?: any } + +/** The dispatcher, exactly as `createHonoApp` builds it: `new HttpDispatcher(kernel)`. */ +function bootDispatcher(callerName: CallerName) { + const caller = CALLERS[callerName]; + const protocol = protocolDouble(); + const services: Record = { + protocol, + security: securityFor(caller), + metadata: { getPublished: async (type: string, name: string) => clone(find(type, name)) }, + }; + const get = (n: string) => services[n] ?? null; + const kernel: any = { context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) }; + const dispatcher = new HttpDispatcher(kernel); + // The seam `dispatch()` resolves identity through; a context handed in is + // overwritten by it, so the principal is supplied here (as the sibling + // dispatch-level pins do). + (dispatcher as any).timedResolveExecutionContext = async () => clone(caller.ctx); + const read = async (path: string): Promise => { + const res = await dispatcher.dispatch('GET', path, undefined, { package: 'sales' }, { request: { headers: {} } } as any); + const status = res.response?.status ?? 0; + const body = res.response?.body; + const data = body?.data; + const served = status === 200 ? data?.item : undefined; + return { status, code: body?.error?.code, body, served }; + }; + return { read, protocol }; +} + +function createMockServer() { + return { + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), use: vi.fn(), + listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), + }; +} + +function makeRes() { + const res: any = { statusCode: 200, body: undefined, headers: {} as Record }; + res.status = vi.fn((c: number) => { res.statusCode = c; return res; }); + res.json = vi.fn((b: any) => { res.body = b; return res; }); + res.send = vi.fn(() => res); + res.header = vi.fn((k: string, v: string) => { res.headers[k] = v; return res; }); + res.setHeader = vi.fn(); res.write = vi.fn(); res.end = vi.fn(); + return res; +} + +/** `RestServer` over the same protocol double and the same caller — the reference answer. */ +function bootRest(callerName: CallerName) { + const caller = CALLERS[callerName]; + const rest: any = new RestServer(createMockServer() as any, protocolDouble() as any, {} as any); + if (caller.ctx.userId) { + const ctx = caller.ctx; + rest.resolveExecCtx = async () => clone(ctx); + } + rest.securityServiceProvider = async () => securityFor(caller); + // ADR-0057 D10 — `tenancy` is an optional service this deployment lacks. + rest.serviceExistsProvider = (name: string) => name !== 'tenancy'; + rest.metadataServiceProvider = async () => ({ + getPublished: async (type: string, name: string) => clone(find(type, name)), + }); + rest.registerRoutes(); + const META = '/api/v1/meta'; + const read = async (type: string, name: string, suffix = ''): Promise => { + const routePath = `${META}/:type/:name${suffix}`; + const route = rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === routePath); + if (!route) throw new Error(`GET ${routePath} is not registered`); + const res = makeRes(); + await route.handler({ method: 'GET', path: `${META}/${type}/${name}${suffix}`, params: { type, name }, query: { package: 'sales' }, body: {}, headers: {} }, res); + const served = res.statusCode === 200 ? res.body?.item : undefined; + return { status: res.statusCode, code: res.body?.code ?? res.body?.error?.code, body: res.body, served }; + }; + return { read }; +} + +const DOORS = ['', '/layers'] as const; +const PATH = (name: string, suffix: string) => `/meta/doc/${name}${suffix}`; + +/** Each transport's answer to `GET /meta/doc/NAME[SUFFIX]?package=sales`, for one caller. */ +async function answersFor(callerName: CallerName, name: string): Promise> { + const answers: Array = []; + THROW.name = name; + try { + for (const suffix of DOORS) { + answers.push({ door: `dispatcher ${PATH(name, suffix)}`, ...(await bootDispatcher(callerName).read(PATH(name, suffix))) }); + answers.push({ door: `rest ${PATH(name, suffix)}`, ...(await bootRest(callerName).read('doc', name, suffix)) }); + } + } finally { + THROW.name = undefined; + } + return answers; +} + +const namesHolders = (a: Answer): boolean => JSON.stringify(a.body ?? null).includes('candidates'); + +describe('[#34247] the audience gate answers before the not-held-by-qualifier refusal, both transports', () => { + it('a member the docs audience refuses is answered the gate\'s 403 at `?package=` of a package holding none, on the plain read and /layers, never the refusal naming holders', async () => { + for (const answer of await answersFor('non-holder', 'crm_admin_runbook')) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([403, 'PERMISSION_DENIED', false, answer.door]); + expect(JSON.stringify(answer.body ?? null), answer.door).not.toContain(DOC_SECRET); + } + }); + + it('an anonymous caller is answered the gate\'s 401 at the same address, never the refusal naming holders', async () => { + for (const answer of await answersFor('anonymous', 'crm_admin_runbook')) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([401, 'UNAUTHENTICATED', false, answer.door]); + } + }); + + it('CONTROL: a caller the gate admits is answered the 409 naming the holders', async () => { + for (const answer of await answersFor('holder', 'crm_admin_runbook')) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([409, 'RESOURCE_CONFLICT', true, answer.door]); + expect(JSON.stringify(answer.body), answer.door).toContain('crm'); + } + }); + + it('CONTROL: a doc every member may read (the `org` audience) is the 409 naming the holders to a member', async () => { + for (const answer of await answersFor('non-holder', 'crm_intro')) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([409, 'RESOURCE_CONFLICT', true, answer.door]); + } + }); +}); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 675ed652574..6673e15e3a3 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -83,6 +83,7 @@ import { createMetaItemReadGate, createMetaLayeredAnswer, createMetaListAnswer, + gateHolderNamingRefusal, isPublicAudienceRead, metaDraftsQueryRefusal, metaItemLayersDeprecationHeaders, @@ -1018,6 +1019,18 @@ async function answerMetaLayered( { metaType: pluralToSingular(type), name, ...(packageId ? { packageId } : {}), ...memberSelector, maskPosture }, )(layered); } catch (e: any) { + // [ruling 6917064203 on #34398] The audience gate answers before any + // refusal that names holders, as `RestServer`'s layered read asks it. + let gated: Awaited>; + try { + gated = await gateHolderNamingRefusal( + metaItemReadGateSources(deps, context, protocol, mayWriteItem), + pluralToSingular(type), name, STORED_VERSION_DOOR_POLICY, e, + ); + } catch (fault: any) { + return withHeaders(deps.errorFromThrown(fault, 500), headers); + } + if (gated) return withHeaders(deps.error(gated.message, gated.status, { code: gated.code }), headers); return withHeaders(deps.errorFromThrown(e, 500), headers); } switch (answer.kind) { @@ -2414,7 +2427,17 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin // rule's refusal: `409` naming every holder, never a miss // for the by-name service read below to answer with // whichever item it finds first. - if (isPackageScopedRefusal(e)) throw e; + if (isPackageScopedRefusal(e)) { + // [ruling 6917064203 on #34398] …answered only after + // the audience gate admits the caller: the audience + // gate answers before any refusal that names holders + // (`gateHolderNamingRefusal`, `RestServer`'s question). + const gated = await gateHolderNamingRefusal( + metaItemReadGateSources(deps, _context, protocol), singularType, name, RENDERED_DOCUMENT_POLICY, e, + ); + if (gated) return { handled: true, response: deps.error(gated.message, gated.status, { code: gated.code }) }; + throw e; + } // [ADR-0150 D3/D5, epic #31527] …and so is any refusal the // protocol DECLARED (`refusal: true`): the read's answer, // such as a by-name read an engine with no package-scoped diff --git a/ui/apps/console/src/pages/DocPage.tsx b/ui/apps/console/src/pages/DocPage.tsx index 276c9c4f82f..477870c7f3c 100644 --- a/ui/apps/console/src/pages/DocPage.tsx +++ b/ui/apps/console/src/pages/DocPage.tsx @@ -13,6 +13,7 @@ import { useAdapter } from '@object-ui/app-shell'; import { MarkdownRenderer, extractToc } from '@object-ui/plugin-markdown'; import { useObjectTranslation } from '@object-ui/i18n'; import { rewriteDocLinks } from './doc-links'; +import { conflictCandidates, readsByNameAfter } from './doc-address'; import { DocShell } from './DocShell'; import { BookSidebar } from './BookSidebar'; import { DocRefusal } from './BookPage'; @@ -32,24 +33,6 @@ function scrollHeadingIntoView(id: string): boolean { return target !== null; } -/** - * The packages a `409 RESOURCE_CONFLICT` doc read names as holders of the - * name: `@objectstack/client` carries the refusal's `details.candidates` on the - * rejection (`{ kind: 'package', packageId }` per package). Null for any other - * failure, and for a refusal that names no package, so those keep their state. - */ -function conflictCandidates(err: unknown): string[] | null { - const e = err as { httpStatus?: unknown; code?: unknown; details?: { candidates?: unknown } } | null; - if (e?.httpStatus !== 409 || e.code !== 'RESOURCE_CONFLICT') return null; - const candidates = e.details?.candidates; - if (!Array.isArray(candidates)) return null; - const packageIds = candidates - .filter((c): c is { kind: 'package'; packageId: string } => - c?.kind === 'package' && typeof c.packageId === 'string' && c.packageId !== '') - .map((c) => c.packageId); - return packageIds.length > 0 ? packageIds : null; -} - /** * `/docs/:name` — render one package-doc metadata item (ADR-0046). * @@ -123,10 +106,8 @@ export default function DocPage() { let raw: any; try { raw = await client.meta.getItem('doc', name, appName ? { packageId: appName } : undefined); - } catch (localErr: any) { - if (!appName) throw localErr; - const holders = conflictCandidates(localErr); - if (localErr?.httpStatus !== 404 && (holders === null || holders.includes(appName))) throw localErr; + } catch (localErr) { + if (!appName || !readsByNameAfter(localErr, appName)) throw localErr; raw = await client.meta.getItem('doc', name); } const item = raw?.item ?? raw?.data ?? raw; diff --git a/ui/apps/console/src/pages/DocsSlug.tsx b/ui/apps/console/src/pages/DocsSlug.tsx index 6164bc8b01b..27fc3a24779 100644 --- a/ui/apps/console/src/pages/DocsSlug.tsx +++ b/ui/apps/console/src/pages/DocsSlug.tsx @@ -15,6 +15,7 @@ import { DocShell } from './DocShell'; import BookPage, { DocRefusal } from './BookPage'; import { useBookData } from './use-book-data'; import { bookNamedBy, bookSlug, homeBook, pkgOf } from './book-nav'; +import { readsByNameAfter } from './doc-address'; /** What the server says about one segment the member's lists do not answer. */ type SegmentAnswer = { slug: string; refusal: string | null }; @@ -27,6 +28,12 @@ type SegmentAnswer = { slug: string; refusal: string | null }; * the server's reason comes back as the answer; anything else (404, a served * item) leaves the portal's own answer standing. `@objectstack/client` rejects a * non-2xx read with the status in `httpStatus`. + * + * The route's package segment is prefer-local context, not an exact address + * (objectstack#34247, `doc-address.ts`): a name the segment's package ships + * none of is asked about again by name, so a cross-reference to another + * package's doc, and the app-name segment of a package that ships several + * apps, reach the audience verdict of the doc's holder. */ async function refusalFor( client: { meta: { getItem: (type: string, name: string, options?: { packageId?: string }) => Promise } }, @@ -35,7 +42,13 @@ async function refusalFor( ): Promise { for (const type of ['doc', 'book'] as const) { try { - await client.meta.getItem(type, name, options); + try { + await client.meta.getItem(type, name, options); + } catch (localErr) { + const packageId = options?.packageId; + if (!packageId || !readsByNameAfter(localErr, packageId)) throw localErr; + await client.meta.getItem(type, name); + } return null; // served: not a refusal } catch (err) { const status = (err as { httpStatus?: unknown } | null)?.httpStatus; diff --git a/ui/apps/console/src/pages/doc-address.ts b/ui/apps/console/src/pages/doc-address.ts new file mode 100644 index 00000000000..d83ab1012b5 --- /dev/null +++ b/ui/apps/console/src/pages/doc-address.ts @@ -0,0 +1,50 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The route's package segment (`/apps/X/docs/...`) is ADR-0048 prefer-local + * context for a doc read, never an exact address. The server's `?package=X` + * read answers only X's own item (ADR-0150 D3/D5): where X ships none of the + * name, a `409 RESOURCE_CONFLICT` whose `details.candidates` name the packages + * that do, X not among them (ruling 6917064203 on objectstack#34398), or `404` + * when no package does. Both doc doors that read under the segment, the + * reader (`DocPage`) and the flat permalink (`DocsSlug`), read such a name by + * name instead, so a cross-reference to another package's doc and the + * app-name segment of a package that ships several apps (no package id at + * all) reach the doc's holder, as the portal reads it. + */ + +/** + * The packages a `409 RESOURCE_CONFLICT` read names as holders of the name: + * `@objectstack/client` carries the refusal's `details.candidates` on the + * rejection (`{ kind: 'package', packageId }` per package). Null for any other + * failure, and for a refusal that names no package. + */ +export function conflictCandidates(err: unknown): string[] | null { + const e = err as { httpStatus?: unknown; code?: unknown; details?: { candidates?: unknown } } | null; + if (e?.httpStatus !== 409 || e.code !== 'RESOURCE_CONFLICT') return null; + const candidates = e.details?.candidates; + if (!Array.isArray(candidates)) return null; + const packageIds = candidates + .filter((c): c is { kind: 'package'; packageId: string } => + c?.kind === 'package' && typeof c.packageId === 'string' && c.packageId !== '') + .map((c) => c.packageId); + return packageIds.length > 0 ? packageIds : null; +} + +/** + * Whether a read at the route's package `packageId` that rejected with `err` + * is re-read by name: a `404`, or a `409` whose candidates leave `packageId` + * out. Any other failure (a refusal of the reader, a 409 naming the route's own + * package, a server error) is the answer at that address and stands. + */ +export function readsByNameAfter(err: unknown, packageId: string): boolean { + if ((err as { httpStatus?: unknown } | null)?.httpStatus === 404) return true; + const holders = conflictCandidates(err); + return holders !== null && !holders.includes(packageId); +} diff --git a/ui/apps/console/src/pages/docs-portal.test.tsx b/ui/apps/console/src/pages/docs-portal.test.tsx index e39abe1cfbe..2cb3f75bd9b 100644 --- a/ui/apps/console/src/pages/docs-portal.test.tsx +++ b/ui/apps/console/src/pages/docs-portal.test.tsx @@ -25,7 +25,7 @@ import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'; // Defined via vi.hoisted so the hoisted vi.mock factory can close over them, // and so the adapter is a STABLE singleton — the real useAdapter() returns a // memoized instance, so a fresh object per render would loop the fetch effects. -const { ADAPTER, WORLD } = vi.hoisted(() => { +const { ADAPTER, WORLD, GATED_REASON } = vi.hoisted(() => { const DOCS = [ { name: 'crm_intro', label: 'CRM Intro', _packageId: 'crm', order: 1 }, { name: 'crm_guide_lead', label: 'Leads', _packageId: 'crm', order: 2 }, @@ -86,12 +86,18 @@ const { ADAPTER, WORLD } = vi.hoisted(() => { 'com.example.alpha': { shared_guide: 'ALPHA SHARED BODY', alpha_welcome: 'ALPHA BODY' }, 'com.example.beta': { shared_guide: 'BETA SHARED BODY', beta_start: 'BETA BODY' }, }; + // objectstack#34247 — a doc beta ships that the member's audience may not + // read: pruned from the member's list (ADR-0046 §6.7), so only the flat + // permalink's single-item read (objectui#10188) answers it, with the gate's + // 403 wherever the read reaches beta's doc. + const GATED: Record = { gated_runbook: 'com.example.beta' }; + const GATED_REASON = 'Only the runbook audience may read this documentation'; /** A rejection shaped like `@objectstack/client`'s on a non-2xx response. */ const failure = (httpStatus: number, code: string, message: string, details?: unknown) => Object.assign(new Error(message), { httpStatus, code, details }); const conflictRead = (name: string, packageId: string | undefined) => { if (name === 'broken_doc') throw failure(500, 'INTERNAL_ERROR', 'The metadata service is unavailable'); - const holders = Object.keys(CONFLICT_CONTENT).filter((p) => name in CONFLICT_CONTENT[p]); + const holders = Object.keys(CONFLICT_CONTENT).filter((p) => name in CONFLICT_CONTENT[p] || GATED[name] === p); WORLD.reads.push(packageId); // objectstack#34247 — the server's exact address answers only that // package's own doc: where it ships none of the name, 409 @@ -104,6 +110,7 @@ const { ADAPTER, WORLD } = vi.hoisted(() => { candidates: holders.map((p) => ({ kind: 'package', packageId: p })), }); } + if (name in GATED) throw failure(403, 'PERMISSION_DENIED', GATED_REASON); if (packageId) return { item: { name, content: CONFLICT_CONTENT[packageId]?.[name] } }; if (holders.length > 1) { throw failure(409, 'RESOURCE_CONFLICT', `doc "${name}" is held by ${holders.length} packages`, { @@ -129,7 +136,7 @@ const { ADAPTER, WORLD } = vi.hoisted(() => { }, }), }; - return { ADAPTER, WORLD }; + return { ADAPTER, WORLD, GATED_REASON }; }); vi.mock('@object-ui/app-shell', async (importOriginal) => ({ @@ -613,6 +620,35 @@ describe('objectstack#34070 — a doc name two packages ship lists its candidate expect(WORLD.reads).toEqual(['com.example.beta']); }); + // The flat permalink (DocsSlug), which every cross-reference is rewritten + // to (doc-links.ts), asks the server about a name the member's lists do + // not answer (objectui#10188): the route's segment is no exact address + // there either, so the doc's holder's audience verdict is what renders. + const refusal = () => screen.findByRole('heading', { name: 'You do not have access to this documentation' }); + + it('the flat permalink: a cross-reference to another package\'s gated doc renders its holder\'s refusal', async () => { + render(); + expect(await refusal()).toBeInTheDocument(); + expect(screen.getByText(GATED_REASON)).toBeInTheDocument(); + expect(screen.queryByText('Documentation not found')).toBeNull(); + expect(screen.getByTestId('where').textContent).toBe('/apps/com.example.alpha/docs/gated_runbook'); + expect(WORLD.reads).toEqual(['com.example.alpha', undefined]); + }); + + it('the flat permalink: an app-name segment that names no package renders the holder\'s refusal', async () => { + render(); + expect(await refusal()).toBeInTheDocument(); + expect(screen.getByText(GATED_REASON)).toBeInTheDocument(); + expect(screen.queryByText('Documentation not found')).toBeNull(); + expect(WORLD.reads).toEqual(['alpha_suite', undefined]); + }); + + it('CONTROL: the flat permalink under the holder\'s own package reads its address only', async () => { + render(); + expect(await refusal()).toBeInTheDocument(); + expect(WORLD.reads).toEqual(['com.example.beta']); + }); + it('CONTROL: a name no package ships is still "not found"', async () => { render(); expect(await screen.findByText(/It may belong to a package that is not installed/)).toBeInTheDocument(); From c47c71b4c37ee12736acaacabf61dc4031149bf8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 18:01:50 +0000 Subject: [PATCH 07/15] test(runtime): pay the audience-gate pin's @objectstack/metadata load at collection (check:test-source-alias) Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../src/domains/meta-holder-refusal-audience-gate.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts index ea4df839e5a..b92e8fbbebd 100644 --- a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts +++ b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts @@ -19,6 +19,9 @@ */ import { describe, it, expect, vi } from 'vitest'; +// The dispatcher's reach loads `@objectstack/metadata` lazily; paid here, at +// collection, never inside a case's clocked window (check:test-source-alias). +import '@objectstack/metadata'; import { RestServer } from '@objectstack/rest'; import { HttpDispatcher } from '../http-dispatcher.js'; import { PackageScopedNameRefusedError } from '@objectstack/core'; From 2496009bb873c8afcefe1f2b1f2376aece6a66c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 21:04:18 +0000 Subject: [PATCH 08/15] docs(changeset): the one-holder cell under "Not moved" names follow-up card #34452, which needs a ruling first Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .changeset/34247-exact-read-own-item-or-none.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34247-exact-read-own-item-or-none.md b/.changeset/34247-exact-read-own-item-or-none.md index e04b8f4869a..07814de3063 100644 --- a/.changeset/34247-exact-read-own-item-or-none.md +++ b/.changeset/34247-exact-read-own-item-or-none.md @@ -33,7 +33,7 @@ Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?pac - Any read naming no package other than the bare doc case above. - `object`, and the covered types (`action`, `hook`, `job`, `sharing_rule`, `queue`, `assignment_rule`), whose exact qualifier already refuses 409 `not-held-by-qualifier`. - The security catalog types `position` and `capability`: the registry keeps one package holder of such a name, so `?package=` of another package keeps the code layers' answer (that holder's item). -- One enabled holder beside a stamp-less bare entry: the bare doors serve the holder's doc while the registry and `MetadataFacade.get` serve the entry (measured, unresolved here; the entry answers first beside two or more holders only). +- One enabled holder beside a stamp-less bare entry: the bare doors serve the holder's doc while the registry and `MetadataFacade.get` serve the entry (measured, unresolved here; the entry answers first beside two or more holders only). Follow-up card #34452 carries this cell; it needs a ruling first on whether the environment's entry answers first beside one holder, before any reader moves. **No migration.** No schema key, stored row or registry slot changes; nothing is rewritten. From 4b5f2e4b20112216f8115de4b44434b48a698253 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:23:37 +0000 Subject: [PATCH 09/15] fix(rest,runtime): narrow the doc audience-gate sentence to the not-held-by-qualifier refusal; declare and pin the view row S8: the changeset, the helper's JSDoc, the transports' comments and the pin's header now state the rule for the refusal it covers: for a doc, the audience gate answers before the not-held-by-qualifier refusal. S7: the view row's order is declared and pinned; the ordering is carried by the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../34247-exact-read-own-item-or-none.md | 3 +- packages/rest/src/meta-item-read-gate.ts | 18 ++-- packages/rest/src/meta-item-read-routes.ts | 4 +- packages/rest/src/rest-server.ts | 5 +- .../meta-holder-refusal-audience-gate.test.ts | 92 +++++++++++++++---- packages/runtime/src/domains/meta.ts | 12 ++- 6 files changed, 97 insertions(+), 37 deletions(-) diff --git a/.changeset/34247-exact-read-own-item-or-none.md b/.changeset/34247-exact-read-own-item-or-none.md index 07814de3063..5debeb73439 100644 --- a/.changeset/34247-exact-read-own-item-or-none.md +++ b/.changeset/34247-exact-read-own-item-or-none.md @@ -15,8 +15,9 @@ Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?pac **BREAKING** for a caller that reads `?package=X` of a name X ships no item of, for the types the exact qualifier does not judge (`doc`, `view`, `translation`, `field`, `seed`, `datasource`, `external_catalog`, `object_extension`). Measured on the composed artifact rig (the `MetadataPlugin` artifact door plus `AppPlugin`), on the dispatcher and on `RestServer`, in both registration orders: -- `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now `409 RESOURCE_CONFLICT`, reason `not-held-by-qualifier`, with `details.candidates` naming each package that holds NAME (ruling 6917064203 on #34398), the refusal the covered types already answer. X need not be an installed package: a qualifier that names none (the Console's app-name segment) gets the same answer. A name no package holds stays the read's own 404. For a `doc`, the audience gate answers before any refusal that names holders: a caller the ADR-0046 §6.7 docs audience refuses is answered the gate's `401 UNAUTHENTICATED` or `403 PERMISSION_DENIED`, and a caller it admits the 409. +- `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now `409 RESOURCE_CONFLICT`, reason `not-held-by-qualifier`, with `details.candidates` naming each package that holds NAME (ruling 6917064203 on #34398), the refusal the covered types already answer. X need not be an installed package: a qualifier that names none (the Console's app-name segment) gets the same answer. A name no package holds stays the read's own 404. For a `doc`, the audience gate answers before the `not-held-by-qualifier` refusal: a caller the ADR-0046 §6.7 docs audience refuses is answered the gate's `401 UNAUTHENTICATED` or `403 PERMISSION_DENIED`, and a caller it admits the 409. - `GET /meta/TYPE/NAME/layers?package=X`, same address: was 200 with another package's `code` and `effective`. It is now the same 409. +- `GET /meta/view/NAME?package=X` and its `/layers`, same address. S7: the view row's order is declared and pinned; the ordering is carried by the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). - `GET /meta/TYPE/NAME/layers?package=X`, where X and Y ship NAME and Y registered last: was 200 with Y's `code` and `effective` (the metadata service keeps such a type by name alone). It is now X's, as the plain read answers since #34040. - `GET /meta/doc/NAME` and its `/layers` and `/published`, where two enabled packages ship NAME and the registry's bare slot holds a package-less entry: was 200 with the doc of the package the metadata service registered last. It is now 200 with the environment's own item, as the registry and `MetadataFacade.get` already served it. Without such an entry the read stays refused 409 naming both (#34036). Per entry: - A stamp-less runtime registration: the plain read and `/published` serve its body; `/layers` reports it as `code` and `effective`. diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index 3431c168500..bf39be73905 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -4756,13 +4756,14 @@ export function createMetaItemAnswer( } /** - * [ruling 6917064203 on #34398 · #34247] The audience gate answers before any - * refusal that names holders. An exact `?package=X` read of a `doc` X holds no - * item of, while another package holds the name, is refused by the protocol - * `409 RESOURCE_CONFLICT` `not-held-by-qualifier` with the holders as its - * candidates; that refusal is answered only to a caller the ADR-0046 §6.7 - * docs audience admits to the name. A caller the gate refuses is answered the - * gate's own `401 UNAUTHENTICATED` / `403 PERMISSION_DENIED` instead. + * [ruling 6917064203 on #34398 · #34247] For a `doc`, the audience gate + * answers before the `not-held-by-qualifier` refusal. An exact `?package=X` + * read of a `doc` X holds no item of, while another package holds the name, is + * refused by the protocol `409 RESOURCE_CONFLICT` `not-held-by-qualifier` with + * the holders as its candidates; that refusal is answered only to a caller + * the ADR-0046 §6.7 docs audience admits to the name. A caller the gate + * refuses is answered the gate's own `401 UNAUTHENTICATED` / + * `403 PERMISSION_DENIED` instead. * * The doc arm of {@link createMetaItemReadGate} judges a doc by its NAME (its * effective audience over the books that claim the name), so the judgment @@ -4771,6 +4772,9 @@ export function createMetaItemAnswer( * that cannot be read REJECTS, as the gate always does: the transport answers * that fault, never the refusal. * + * S7: the view row's order is declared and pinned; the ordering is carried by + * the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). + * * One function, called by both transports' plain read and `/layers` read. */ export async function gateHolderNamingRefusal( diff --git a/packages/rest/src/meta-item-read-routes.ts b/packages/rest/src/meta-item-read-routes.ts index 54fcf8bde03..083aab54470 100644 --- a/packages/rest/src/meta-item-read-routes.ts +++ b/packages/rest/src/meta-item-read-routes.ts @@ -1086,8 +1086,8 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M // [#22877] The member, read once above. ...memberSelector, }; - // [ruling 6917064203 on #34398] The audience gate answers - // before any refusal that names holders + // [ruling 6917064203 on #34398] For a doc, the audience + // gate answers before the `not-held-by-qualifier` refusal // (`gateHolderNamingRefusal`, the one both transports ask). const readPolicyFor: MetaReadGatePolicy = isDraftRead ? this.STORED_VERSION_DOOR_POLICY diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 9696a09c791..1c65f8d328e 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -4456,8 +4456,9 @@ export class RestServer { try { layered = await p.getMetaItemLayered(layeredRequest, layeredOptions); } catch (readError) { - // [ruling 6917064203 on #34398] The audience gate answers before - // any refusal that names holders — the plain read's own question. + // [ruling 6917064203 on #34398] For a doc, the audience gate answers + // before the `not-held-by-qualifier` refusal — the plain read's own + // question. const gated = await metaReadGate.gateHolderNamingRefusal( this.metaItemReadGateSources(environmentId, req, p, true), RestServer.metaTypeSingular(req.params.type), req.params.name, diff --git a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts index b92e8fbbebd..f2038e13595 100644 --- a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts +++ b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [ruling 6917064203 on #34398 · #34247] The audience gate answers before any - * refusal that names holders. + * [ruling 6917064203 on #34398 · #34247] For a doc, the audience gate answers + * before the `not-held-by-qualifier` refusal. * * An exact `?package=X` read of a doc X holds no item of, while another * package holds the name, is refused by the protocol `409 RESOURCE_CONFLICT` @@ -14,6 +14,9 @@ * `RestServer`) ask the one question, `gateHolderNamingRefusal` in * `@objectstack/rest`, on the plain read and on `/layers`. * + * S7: the view row's order is declared and pinned; the ordering is carried by + * the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). + * * The protocol is a double that throws the protocol's own refusal shape; the * gate, its audience resolution and both transports are the real ones. */ @@ -25,7 +28,7 @@ import '@objectstack/metadata'; import { RestServer } from '@objectstack/rest'; import { HttpDispatcher } from '../http-dispatcher.js'; import { PackageScopedNameRefusedError } from '@objectstack/core'; -const THROW: { name?: string } = {}; +const THROW: { type?: string; name?: string } = {}; // ── Fixtures (the #20193 parity rig's docs) ─────────────────────────────────── @@ -51,7 +54,10 @@ const DOCS = [ { name: 'crm_intro', label: 'Getting started', content: 'Welcome aboard.', _packageId: 'crm' }, { name: 'crm_admin_runbook', label: 'Admin runbook', content: DOC_SECRET, _packageId: 'crm' }, ]; -const STORE: Record = { book: [ADMIN_GUIDE, HELP_CENTER], doc: DOCS }; +const VIEWS = [ + { name: 'crm_pipeline_review', label: 'Pipeline review', type: 'grid', data: { provider: 'object', object: 'crm_deal' }, requiredPermissions: ['crm_pipeline_audit'], _packageId: 'crm' }, +]; +const STORE: Record = { book: [ADMIN_GUIDE, HELP_CENTER], doc: DOCS, view: VIEWS }; const clone = (v: T): T => JSON.parse(JSON.stringify(v)); const singular = (type: unknown): string => String(type ?? '').replace(/s$/, ''); @@ -65,7 +71,7 @@ interface Caller { holdings: string[]; readableFields: string[]; } -const CALLERS: Record<'holder' | 'non-holder' | 'anonymous', Caller> = { +const CALLERS: Record<'holder' | 'non-holder' | 'anonymous' | 'view-holder', Caller> = { holder: { ctx: { userId: 'u_holder', isSystem: false, systemPermissions: [] }, holdings: ['crm_admin'], @@ -77,22 +83,28 @@ const CALLERS: Record<'holder' | 'non-holder' | 'anonymous', Caller> = { readableFields: [], }, anonymous: { ctx: { isSystem: false, systemPermissions: [] }, holdings: [], readableFields: [] }, + 'view-holder': { + ctx: { userId: 'u_view_holder', isSystem: false, systemPermissions: ['crm_pipeline_audit'] }, + holdings: [], + readableFields: [], + }, }; type CallerName = keyof typeof CALLERS; /** - * The protocol's refusal of `?package=sales` for a doc `sales` ships none of - * while `crm` ships it (`notHeldByQualifierRefusal` in + * The protocol's refusal of `?package=sales` for a doc or view `sales` ships + * none of while `crm` ships it (`notHeldByQualifierRefusal` in * `@objectstack/metadata-protocol`): `PackageScopedNameRefusedError`, reason * `not-held-by-qualifier`, naming the holder. */ function refuseIfAsked(type: unknown, name: unknown): void { - if (singular(type) !== 'doc' || name !== THROW.name) return; + const t = singular(type); + if (t !== (THROW.type ?? 'doc') || name !== THROW.name) return; const base = { - status: 'refused' as const, reason: 'not-held-by-qualifier' as const, type: 'doc', name: String(name), + status: 'refused' as const, reason: 'not-held-by-qualifier' as const, type: t, name: String(name), callerPackageId: 'sales', candidates: [{ kind: 'package' as const, packageId: 'crm' }], }; - throw new PackageScopedNameRefusedError({ ...base, message: `doc "${String(name)}" is not held by package "sales"` } as never); + throw new PackageScopedNameRefusedError({ ...base, message: `${t} "${String(name)}" is not held by package "sales"` } as never); } /** One protocol double, the same shape both transports read. */ @@ -124,7 +136,7 @@ const securityFor = (caller: Caller) => ({ interface Answer { status: number; code?: string; body: any; served?: any } /** The dispatcher, exactly as `createHonoApp` builds it: `new HttpDispatcher(kernel)`. */ -function bootDispatcher(callerName: CallerName) { +function bootDispatcher(callerName: CallerName, packageId = 'sales') { const caller = CALLERS[callerName]; const protocol = protocolDouble(); const services: Record = { @@ -140,7 +152,7 @@ function bootDispatcher(callerName: CallerName) { // dispatch-level pins do). (dispatcher as any).timedResolveExecutionContext = async () => clone(caller.ctx); const read = async (path: string): Promise => { - const res = await dispatcher.dispatch('GET', path, undefined, { package: 'sales' }, { request: { headers: {} } } as any); + const res = await dispatcher.dispatch('GET', path, undefined, { package: packageId }, { request: { headers: {} } } as any); const status = res.response?.status ?? 0; const body = res.response?.body; const data = body?.data; @@ -168,7 +180,7 @@ function makeRes() { } /** `RestServer` over the same protocol double and the same caller — the reference answer. */ -function bootRest(callerName: CallerName) { +function bootRest(callerName: CallerName, packageId = 'sales') { const caller = CALLERS[callerName]; const rest: any = new RestServer(createMockServer() as any, protocolDouble() as any, {} as any); if (caller.ctx.userId) { @@ -188,7 +200,7 @@ function bootRest(callerName: CallerName) { const route = rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === routePath); if (!route) throw new Error(`GET ${routePath} is not registered`); const res = makeRes(); - await route.handler({ method: 'GET', path: `${META}/${type}/${name}${suffix}`, params: { type, name }, query: { package: 'sales' }, body: {}, headers: {} }, res); + await route.handler({ method: 'GET', path: `${META}/${type}/${name}${suffix}`, params: { type, name }, query: { package: packageId }, body: {}, headers: {} }, res); const served = res.statusCode === 200 ? res.body?.item : undefined; return { status: res.statusCode, code: res.body?.code ?? res.body?.error?.code, body: res.body, served }; }; @@ -196,18 +208,29 @@ function bootRest(callerName: CallerName) { } const DOORS = ['', '/layers'] as const; -const PATH = (name: string, suffix: string) => `/meta/doc/${name}${suffix}`; +const PATH = (type: string, name: string, suffix: string) => `/meta/${type}/${name}${suffix}`; -/** Each transport's answer to `GET /meta/doc/NAME[SUFFIX]?package=sales`, for one caller. */ -async function answersFor(callerName: CallerName, name: string): Promise> { +/** + * Each transport's answer to `GET /meta/TYPE/NAME[SUFFIX]?package=PKG`, for + * one caller. At `sales` (no holder) the protocol double refuses; at `crm` + * (the holder) it serves the holder's item. + */ +async function answersFor( + callerName: CallerName, name: string, type = 'doc', packageId = 'sales', +): Promise> { const answers: Array = []; - THROW.name = name; + if (packageId === 'sales') { + THROW.type = type; + THROW.name = name; + } try { for (const suffix of DOORS) { - answers.push({ door: `dispatcher ${PATH(name, suffix)}`, ...(await bootDispatcher(callerName).read(PATH(name, suffix))) }); - answers.push({ door: `rest ${PATH(name, suffix)}`, ...(await bootRest(callerName).read('doc', name, suffix)) }); + const door = `${PATH(type, name, suffix)}?package=${packageId}`; + answers.push({ door: `dispatcher ${door}`, ...(await bootDispatcher(callerName, packageId).read(PATH(type, name, suffix))) }); + answers.push({ door: `rest ${door}`, ...(await bootRest(callerName, packageId).read(type, name, suffix)) }); } } finally { + THROW.type = undefined; THROW.name = undefined; } return answers; @@ -246,3 +269,32 @@ describe('[#34247] the audience gate answers before the not-held-by-qualifier re } }); }); + + +describe('[#34247] S7: the view row, both transports', () => { + // S7: the view row's order is declared and pinned; the ordering is carried + // by the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). + it('a member outside the view\'s requiredPermissions, at `?package=` of a package holding none: 409 not-held-by-qualifier, on the plain read and /layers', async () => { + for (const answer of await answersFor('non-holder', 'crm_pipeline_review', 'view')) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([409, 'RESOURCE_CONFLICT', true, answer.door]); + } + }); + + it('a member holding the view\'s requiredPermissions, same address: 409 not-held-by-qualifier, on the plain read and /layers', async () => { + for (const answer of await answersFor('view-holder', 'crm_pipeline_review', 'view')) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([409, 'RESOURCE_CONFLICT', true, answer.door]); + } + }); + + it('CONTROL: at the holder\'s own address the view gate refuses the first member (403) and serves the second (200)', async () => { + for (const answer of await answersFor('non-holder', 'crm_pipeline_review', 'view', 'crm')) { + expect([answer.status, answer.code, answer.door], JSON.stringify(answer.body)) + .toEqual([403, 'PERMISSION_DENIED', answer.door]); + } + for (const answer of await answersFor('view-holder', 'crm_pipeline_review', 'view', 'crm')) { + expect([answer.status, answer.door], JSON.stringify(answer.body)).toEqual([200, answer.door]); + } + }); +}); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 6673e15e3a3..a20fed2c484 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -1019,8 +1019,9 @@ async function answerMetaLayered( { metaType: pluralToSingular(type), name, ...(packageId ? { packageId } : {}), ...memberSelector, maskPosture }, )(layered); } catch (e: any) { - // [ruling 6917064203 on #34398] The audience gate answers before any - // refusal that names holders, as `RestServer`'s layered read asks it. + // [ruling 6917064203 on #34398] For a doc, the audience gate answers + // before the `not-held-by-qualifier` refusal, as `RestServer`'s layered + // read asks it. let gated: Awaited>; try { gated = await gateHolderNamingRefusal( @@ -2429,9 +2430,10 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin // whichever item it finds first. if (isPackageScopedRefusal(e)) { // [ruling 6917064203 on #34398] …answered only after - // the audience gate admits the caller: the audience - // gate answers before any refusal that names holders - // (`gateHolderNamingRefusal`, `RestServer`'s question). + // the audience gate admits the caller: for a doc, the + // audience gate answers before the `not-held-by-qualifier` + // refusal (`gateHolderNamingRefusal`, `RestServer`'s + // question). const gated = await gateHolderNamingRefusal( metaItemReadGateSources(deps, _context, protocol), singularType, name, RENDERED_DOCUMENT_POLICY, e, ); From 0ba6987aec1cd73f9a97fa417355a7930302ceae Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:28:35 +0000 Subject: [PATCH 10/15] test(runtime): neutral titles for the S7 view-row pins S7: the view row's order is declared and pinned; the ordering is carried by the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../src/domains/meta-holder-refusal-audience-gate.test.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts index f2038e13595..6229574ded6 100644 --- a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts +++ b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts @@ -270,25 +270,24 @@ describe('[#34247] the audience gate answers before the not-held-by-qualifier re }); }); - describe('[#34247] S7: the view row, both transports', () => { // S7: the view row's order is declared and pinned; the ordering is carried // by the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). - it('a member outside the view\'s requiredPermissions, at `?package=` of a package holding none: 409 not-held-by-qualifier, on the plain read and /layers', async () => { + it('the view row at `?package=` of a package holding none, the first member (non-holder), plain read and /layers', async () => { for (const answer of await answersFor('non-holder', 'crm_pipeline_review', 'view')) { expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) .toEqual([409, 'RESOURCE_CONFLICT', true, answer.door]); } }); - it('a member holding the view\'s requiredPermissions, same address: 409 not-held-by-qualifier, on the plain read and /layers', async () => { + it('the view row at the same address, the second member (view-holder), plain read and /layers', async () => { for (const answer of await answersFor('view-holder', 'crm_pipeline_review', 'view')) { expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) .toEqual([409, 'RESOURCE_CONFLICT', true, answer.door]); } }); - it('CONTROL: at the holder\'s own address the view gate refuses the first member (403) and serves the second (200)', async () => { + it('CONTROL: the same two members at the holder\'s own address', async () => { for (const answer of await answersFor('non-holder', 'crm_pipeline_review', 'view', 'crm')) { expect([answer.status, answer.code, answer.door], JSON.stringify(answer.body)) .toEqual([403, 'PERMISSION_DENIED', answer.door]); From f45378bb1c9df208ada452394f0f3e4615d1ceb5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:43:41 +0000 Subject: [PATCH 11/15] fix(rest,runtime): the view row passes the view gate before any holder is named At `?package=X` of a view X holds none of, the list view audience gate now answers before the `not-held-by-qualifier` refusal, as the docs audience gate already does for a doc: a member it refuses is answered the gate's 403, a member it admits the 409 naming the holders. Both transports, plain read and /layers. The changeset, JSDoc and pin header state the rule only. Claude-Session: https://claude.ai/code/session_01ADHkmNkZcGApqG4pHHMLeY Co-authored-by: Claude --- .../34247-exact-read-own-item-or-none.md | 3 +- packages/rest/src/index.ts | 1 + packages/rest/src/meta-item-read-gate.ts | 76 +++++++++++++------ packages/rest/src/meta-item-read-routes.ts | 11 ++- packages/rest/src/rest-server.ts | 11 ++- .../meta-holder-refusal-audience-gate.test.ts | 51 ++++++------- packages/runtime/src/domains/meta.ts | 22 ++++-- 7 files changed, 109 insertions(+), 66 deletions(-) diff --git a/.changeset/34247-exact-read-own-item-or-none.md b/.changeset/34247-exact-read-own-item-or-none.md index 5debeb73439..9f98446d1cf 100644 --- a/.changeset/34247-exact-read-own-item-or-none.md +++ b/.changeset/34247-exact-read-own-item-or-none.md @@ -15,9 +15,8 @@ Skills-docs: none — no skill teaches a moved answer: `skills/**` teaches `?pac **BREAKING** for a caller that reads `?package=X` of a name X ships no item of, for the types the exact qualifier does not judge (`doc`, `view`, `translation`, `field`, `seed`, `datasource`, `external_catalog`, `object_extension`). Measured on the composed artifact rig (the `MetadataPlugin` artifact door plus `AppPlugin`), on the dispatcher and on `RestServer`, in both registration orders: -- `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now `409 RESOURCE_CONFLICT`, reason `not-held-by-qualifier`, with `details.candidates` naming each package that holds NAME (ruling 6917064203 on #34398), the refusal the covered types already answer. X need not be an installed package: a qualifier that names none (the Console's app-name segment) gets the same answer. A name no package holds stays the read's own 404. For a `doc`, the audience gate answers before the `not-held-by-qualifier` refusal: a caller the ADR-0046 §6.7 docs audience refuses is answered the gate's `401 UNAUTHENTICATED` or `403 PERMISSION_DENIED`, and a caller it admits the 409. +- `GET /meta/TYPE/NAME?package=X`, where X ships no item of NAME and another package does: was 200 with that package's item (the registry's first composite, or the metadata service's copy). It is now `409 RESOURCE_CONFLICT`, reason `not-held-by-qualifier`, with `details.candidates` naming each package that holds NAME (ruling 6917064203 on #34398), the refusal the covered types already answer. X need not be an installed package: a qualifier that names none (the Console's app-name segment) gets the same answer. A name no package holds stays the read's own 404. The read gate answers before the `not-held-by-qualifier` refusal names any holder: for a `doc`, a caller the ADR-0046 §6.7 docs audience refuses is answered the gate's `401 UNAUTHENTICATED` or `403 PERMISSION_DENIED`; for a `view`, a member the list view audience (`requiredPermissions`) refuses is answered the gate's `403 PERMISSION_DENIED`, as the holder's own address answers them. A caller the gate admits is answered the 409. - `GET /meta/TYPE/NAME/layers?package=X`, same address: was 200 with another package's `code` and `effective`. It is now the same 409. -- `GET /meta/view/NAME?package=X` and its `/layers`, same address. S7: the view row's order is declared and pinned; the ordering is carried by the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). - `GET /meta/TYPE/NAME/layers?package=X`, where X and Y ship NAME and Y registered last: was 200 with Y's `code` and `effective` (the metadata service keeps such a type by name alone). It is now X's, as the plain read answers since #34040. - `GET /meta/doc/NAME` and its `/layers` and `/published`, where two enabled packages ship NAME and the registry's bare slot holds a package-less entry: was 200 with the doc of the package the metadata service registered last. It is now 200 with the environment's own item, as the registry and `MetadataFacade.get` already served it. Without such an entry the read stays refused 409 naming both (#34036). Per entry: - A stamp-less runtime registration: the plain read and `/published` serve its body; `/layers` reports it as `code` and `effective`. diff --git a/packages/rest/src/index.ts b/packages/rest/src/index.ts index 846baf1205d..c115977a42b 100644 --- a/packages/rest/src/index.ts +++ b/packages/rest/src/index.ts @@ -203,6 +203,7 @@ export type { MetaBookTreeSources, MetaItemAnswer, MetaItemAnswerSources, + MetaHolderItemReader, MetaItemReadGateSources, MetaItemReadRefusal, MetaItemReadVerdict, diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index bf39be73905..6a1c8da5412 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -4756,24 +4756,36 @@ export function createMetaItemAnswer( } /** - * [ruling 6917064203 on #34398 · #34247] For a `doc`, the audience gate - * answers before the `not-held-by-qualifier` refusal. An exact `?package=X` - * read of a `doc` X holds no item of, while another package holds the name, is - * refused by the protocol `409 RESOURCE_CONFLICT` `not-held-by-qualifier` with - * the holders as its candidates; that refusal is answered only to a caller - * the ADR-0046 §6.7 docs audience admits to the name. A caller the gate - * refuses is answered the gate's own `401 UNAUTHENTICATED` / - * `403 PERMISSION_DENIED` instead. - * - * The doc arm of {@link createMetaItemReadGate} judges a doc by its NAME (its - * effective audience over the books that claim the name), so the judgment - * needs no holder's item. Any other thrown value, and any other type, is - * `undefined`: the transport answers the thrown value as it did. A gate input - * that cannot be read REJECTS, as the gate always does: the transport answers - * that fault, never the refusal. - * - * S7: the view row's order is declared and pinned; the ordering is carried by - * the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). + * [#34247] How {@link gateHolderNamingRefusal} reads one holder's item: the + * transport's own by-name read of `name` at `?package=`, answering + * the served `item` (or `null`/`undefined` when that package serves none). A + * rejection is a gate input that cannot be read: it propagates, and the + * transport answers that fault, never the refusal. + */ +export type MetaHolderItemReader = (packageId: string) => Promise; + +/** + * [ruling 6917064203 on #34398 · #34247] The read gate answers before the + * `not-held-by-qualifier` refusal names any holder. An exact `?package=X` read + * of a name X holds no item of, while another package holds it, is refused by + * the protocol `409 RESOURCE_CONFLICT` `not-held-by-qualifier` with the + * holders as its candidates; that refusal is answered only to a caller the + * type's own read gate admits. A caller the gate refuses is answered the + * gate's own refusal instead, which names no holder: + * + * - `doc`: the ADR-0046 §6.7 docs audience, `401 UNAUTHENTICATED` / + * `403 PERMISSION_DENIED`. The doc arm of {@link createMetaItemReadGate} + * judges a doc by its NAME (its effective audience over the books that + * claim the name), so the judgment needs no holder's item. + * - `view`: the list view audience ({@link filterViewForUser}), `403 + * PERMISSION_DENIED`. A view is judged by its body, so each package holder's + * item is read through `readHolderItem` and judged by the view arm; the + * gate's refusal of any one of them is the answer. + * + * Any other thrown value, and any other type, is `undefined`: the transport + * answers the thrown value as it did. A gate input that cannot be read + * REJECTS, as the gate always does: the transport answers that fault, never + * the refusal. * * One function, called by both transports' plain read and `/layers` read. */ @@ -4783,13 +4795,27 @@ export async function gateHolderNamingRefusal( name: string, policy: MetaReadGatePolicy, thrown: unknown, -): Promise | undefined> { - if (metaType !== 'doc') return undefined; - const reason = (thrown as { refusal?: { reason?: unknown } } | null | undefined)?.refusal?.reason; - if (reason !== 'not-held-by-qualifier') return undefined; - const named = { name }; - const verdict = await createMetaItemReadGate(sources, metaType, name, [named], policy)(named); - return verdict.kind === 'refuse' && verdict.refusal.reason === 'docs-audience' ? verdict.refusal : undefined; + readHolderItem: MetaHolderItemReader, +): Promise | undefined> { + if (metaType !== 'doc' && metaType !== 'view') return undefined; + const refusal = (thrown as { refusal?: { reason?: unknown; candidates?: unknown } } | null | undefined)?.refusal; + if (refusal?.reason !== 'not-held-by-qualifier') return undefined; + if (metaType === 'doc') { + const named = { name }; + const verdict = await createMetaItemReadGate(sources, metaType, name, [named], policy)(named); + return verdict.kind === 'refuse' && verdict.refusal.reason === 'docs-audience' ? verdict.refusal : undefined; + } + const holders = (Array.isArray(refusal.candidates) ? refusal.candidates : []) + .filter((c: any): c is { kind: 'package'; packageId: string } => c?.kind === 'package' && typeof c.packageId === 'string') + .map((c) => c.packageId); + const items: unknown[] = []; + for (const holder of holders) items.push(await readHolderItem(holder)); + const judge = createMetaItemReadGate(sources, metaType, name, items, policy); + for (const item of items) { + const verdict = await judge(item); + if (verdict.kind === 'refuse' && verdict.refusal.reason === 'audience-permission') return verdict.refusal; + } + return undefined; } // ── THE layered answer ──────────────────────────────────────────────────────── diff --git a/packages/rest/src/meta-item-read-routes.ts b/packages/rest/src/meta-item-read-routes.ts index 083aab54470..dcf660c6434 100644 --- a/packages/rest/src/meta-item-read-routes.ts +++ b/packages/rest/src/meta-item-read-routes.ts @@ -1086,9 +1086,10 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M // [#22877] The member, read once above. ...memberSelector, }; - // [ruling 6917064203 on #34398] For a doc, the audience - // gate answers before the `not-held-by-qualifier` refusal - // (`gateHolderNamingRefusal`, the one both transports ask). + // [ruling 6917064203 on #34398] The read gate answers + // before the `not-held-by-qualifier` refusal names any + // holder (`gateHolderNamingRefusal`, the one both + // transports ask). const readPolicyFor: MetaReadGatePolicy = isDraftRead ? this.STORED_VERSION_DOOR_POLICY : { arms: 'all', app: 'gate' }; @@ -1099,6 +1100,10 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M const gated = await metaReadGate.gateHolderNamingRefusal( this.metaItemAnswerSources(environmentId, req, p, readPolicyFor), metaType, req.params.name, readPolicyFor, readError, + // A holder's item, read at its own address. + async (holder) => (await p.getMetaItem({ + type: req.params.type, name: req.params.name, packageId: holder, ...memberSelector, + }) as { item?: unknown } | undefined)?.item, ); if (gated) { this.sendMetaReadRefusal(res, gated); diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 1c65f8d328e..d973219252f 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -4456,13 +4456,18 @@ export class RestServer { try { layered = await p.getMetaItemLayered(layeredRequest, layeredOptions); } catch (readError) { - // [ruling 6917064203 on #34398] For a doc, the audience gate answers - // before the `not-held-by-qualifier` refusal — the plain read's own - // question. + // [ruling 6917064203 on #34398] The read gate answers before the + // `not-held-by-qualifier` refusal names any holder — the plain + // read's own question; a holder's item is read at its own address. const gated = await metaReadGate.gateHolderNamingRefusal( this.metaItemReadGateSources(environmentId, req, p, true), RestServer.metaTypeSingular(req.params.type), req.params.name, metaReadGate.STORED_VERSION_DOOR_POLICY, readError, + async (holder) => (await p.getMetaItem({ + type: req.params.type, name: req.params.name, packageId: holder, + ...metaReadGate.metaMemberSelector(req.query), + ...(environmentId ? { environmentId } : {}), + } as any) as { item?: unknown } | undefined)?.item, ); if (gated) { RestServer.sendMetaReadRefusal(res, gated); diff --git a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts index 6229574ded6..5ff42414206 100644 --- a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts +++ b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts @@ -1,21 +1,19 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [ruling 6917064203 on #34398 · #34247] For a doc, the audience gate answers - * before the `not-held-by-qualifier` refusal. + * [ruling 6917064203 on #34398 · #34247] The read gate answers before the + * `not-held-by-qualifier` refusal names any holder. * - * An exact `?package=X` read of a doc X holds no item of, while another - * package holds the name, is refused by the protocol `409 RESOURCE_CONFLICT` - * `not-held-by-qualifier`, its candidates naming the holders. That refusal is - * the answer only for a caller the ADR-0046 §6.7 docs audience admits to the - * name: a member the gate refuses is answered the gate's `403 - * PERMISSION_DENIED`, an anonymous caller the gate's `401 UNAUTHENTICATED`, - * and neither answer names a holder. Both transports (the dispatcher and - * `RestServer`) ask the one question, `gateHolderNamingRefusal` in - * `@objectstack/rest`, on the plain read and on `/layers`. - * - * S7: the view row's order is declared and pinned; the ordering is carried by - * the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). + * An exact `?package=X` read of a doc or a view X holds no item of, while + * another package holds the name, is refused by the protocol `409 + * RESOURCE_CONFLICT` `not-held-by-qualifier`, its candidates naming the + * holders. That refusal is the answer only for a caller the type's read gate + * admits: for a doc the ADR-0046 §6.7 docs audience (a refused member is + * answered the gate's `403 PERMISSION_DENIED`, an anonymous caller its `401 + * UNAUTHENTICATED`), for a view the list view audience (`403 + * PERMISSION_DENIED`). No gate answer names a holder. Both transports (the + * dispatcher and `RestServer`) ask the one question, `gateHolderNamingRefusal` + * in `@objectstack/rest`, on the plain read and on `/layers`. * * The protocol is a double that throws the protocol's own refusal shape; the * gate, its audience resolution and both transports are the real ones. @@ -95,10 +93,12 @@ type CallerName = keyof typeof CALLERS; * The protocol's refusal of `?package=sales` for a doc or view `sales` ships * none of while `crm` ships it (`notHeldByQualifierRefusal` in * `@objectstack/metadata-protocol`): `PackageScopedNameRefusedError`, reason - * `not-held-by-qualifier`, naming the holder. + * `not-held-by-qualifier`, naming the holder. The holder's own address + * (`?package=crm`) serves its item. */ -function refuseIfAsked(type: unknown, name: unknown): void { +function refuseIfAsked(type: unknown, name: unknown, packageId: unknown): void { const t = singular(type); + if (packageId === 'crm') return; if (t !== (THROW.type ?? 'doc') || name !== THROW.name) return; const base = { status: 'refused' as const, reason: 'not-held-by-qualifier' as const, type: t, name: String(name), @@ -112,13 +112,13 @@ function protocolDouble() { return { getMetaTypes: vi.fn(async () => ({ types: Object.keys(STORE) })), getMetaItems: vi.fn(async ({ type }: any) => clone(STORE[singular(type)] ?? [])), - getMetaItem: vi.fn(async ({ type, name }: any) => { - refuseIfAsked(type, name); + getMetaItem: vi.fn(async ({ type, name, packageId }: any) => { + refuseIfAsked(type, name, packageId); const found = find(type, name); return { type: singular(type), name, item: found ? clone(found) : undefined, lock: 'none', editable: true, deletable: true, resettable: false }; }), - getMetaItemLayered: vi.fn(async ({ type, name }: any) => { - refuseIfAsked(type, name); + getMetaItemLayered: vi.fn(async ({ type, name, packageId }: any) => { + refuseIfAsked(type, name, packageId); const found = find(type, name); const layer = () => (found ? clone(found) : null); return { type: singular(type), name, code: layer(), overlay: layer(), effective: layer() }; @@ -270,20 +270,19 @@ describe('[#34247] the audience gate answers before the not-held-by-qualifier re }); }); -describe('[#34247] S7: the view row, both transports', () => { - // S7: the view row's order is declared and pinned; the ordering is carried - // by the security channel (GHSA-ggc2-jqph-f74f, acknowledgement 6932974351). - it('the view row at `?package=` of a package holding none, the first member (non-holder), plain read and /layers', async () => { +describe('[#34247] the view gate answers before the not-held-by-qualifier refusal, both transports', () => { + it('a member the view audience refuses is answered the gate\'s 403 at `?package=` of a package holding none, on the plain read and /layers, never the refusal naming holders', async () => { for (const answer of await answersFor('non-holder', 'crm_pipeline_review', 'view')) { expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) - .toEqual([409, 'RESOURCE_CONFLICT', true, answer.door]); + .toEqual([403, 'PERMISSION_DENIED', false, answer.door]); } }); - it('the view row at the same address, the second member (view-holder), plain read and /layers', async () => { + it('CONTROL: a member the view audience admits is answered the 409 naming the holders', async () => { for (const answer of await answersFor('view-holder', 'crm_pipeline_review', 'view')) { expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) .toEqual([409, 'RESOURCE_CONFLICT', true, answer.door]); + expect(JSON.stringify(answer.body), answer.door).toContain('crm'); } }); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index a20fed2c484..5a95a790818 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -1019,14 +1019,18 @@ async function answerMetaLayered( { metaType: pluralToSingular(type), name, ...(packageId ? { packageId } : {}), ...memberSelector, maskPosture }, )(layered); } catch (e: any) { - // [ruling 6917064203 on #34398] For a doc, the audience gate answers - // before the `not-held-by-qualifier` refusal, as `RestServer`'s layered - // read asks it. + // [ruling 6917064203 on #34398] The read gate answers before the + // `not-held-by-qualifier` refusal names any holder, as `RestServer`'s + // layered read asks it. let gated: Awaited>; try { gated = await gateHolderNamingRefusal( metaItemReadGateSources(deps, context, protocol, mayWriteItem), pluralToSingular(type), name, STORED_VERSION_DOOR_POLICY, e, + // A holder's item, read at its own address. + async (holder) => (await protocol.getMetaItem({ + type, name, packageId: holder, ...memberSelector, + }) as { item?: unknown } | undefined)?.item, ); } catch (fault: any) { return withHeaders(deps.errorFromThrown(fault, 500), headers); @@ -2430,12 +2434,16 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin // whichever item it finds first. if (isPackageScopedRefusal(e)) { // [ruling 6917064203 on #34398] …answered only after - // the audience gate admits the caller: for a doc, the - // audience gate answers before the `not-held-by-qualifier` - // refusal (`gateHolderNamingRefusal`, `RestServer`'s - // question). + // the read gate admits the caller: the read gate + // answers before the `not-held-by-qualifier` refusal + // names any holder (`gateHolderNamingRefusal`, + // `RestServer`'s question). const gated = await gateHolderNamingRefusal( metaItemReadGateSources(deps, _context, protocol), singularType, name, RENDERED_DOCUMENT_POLICY, e, + // A holder's item, read at its own address. + async (holder) => (await protocol.getMetaItem({ + type: singularType, name, packageId: holder, ...memberSelector, + }) as { item?: unknown } | undefined)?.item, ); if (gated) return { handled: true, response: deps.error(gated.message, gated.status, { code: gated.code }) }; throw e; From 735dd6a95adef49c1efd468a6f5555fdce66d9d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:22:47 +0000 Subject: [PATCH 12/15] fix(runtime): read a holder's item through one reader that refuses when the protocol has no by-name read The dispatcher's two holder reads now share one reader; a protocol without a by-name read rejects it, so the read gate fails closed rather than calling an absent method (the runtime typecheck lane read it as possibly undefined). Claude-Session: https://claude.ai/code/session_01ADHkmNkZcGApqG4pHHMLeY Co-authored-by: Claude --- packages/runtime/src/domains/meta.ts | 32 +++++++++++++++++++++------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 5a95a790818..ba63ac26174 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -105,6 +105,7 @@ import { translateMetaEnvelope, translateMetaList, wantsMetaItemLayers, + type MetaHolderItemReader, type MetaItemAnswer, type MetaItemAnswerSources, type MetaItemReadGateSources, @@ -948,6 +949,27 @@ type LayeredReadWithDraft = ( opts: { withDraft?: boolean }, ) => ReturnType; +/** + * [#34247] A holder's item, read at its own address (`?package=`), for + * {@link gateHolderNamingRefusal}. A protocol with no by-name read cannot + * answer it, so the read REJECTS: the gate fails closed and the transport + * answers that fault, never the refusal naming holders. + */ +function holderItemReader( + protocol: MetaDomainProtocol, + type: string, + name: string, + memberSelector: { member?: string }, +): MetaHolderItemReader { + return async (holder) => { + if (typeof protocol.getMetaItem !== 'function') { + throw new Error(`The protocol serves no by-name read, so the item "${name}" of type "${type}" cannot be read at package "${holder}" to judge its read gate.`); + } + const envelope = await protocol.getMetaItem({ type, name, packageId: holder, ...memberSelector }); + return (envelope as { item?: unknown } | undefined)?.item; + }; +} + /** * [#20478] Answer the layered view — `GET /meta/:type/:name/layers`, and the * deprecated `?layers=` flag on the item read: read the protocol's @@ -1027,10 +1049,7 @@ async function answerMetaLayered( gated = await gateHolderNamingRefusal( metaItemReadGateSources(deps, context, protocol, mayWriteItem), pluralToSingular(type), name, STORED_VERSION_DOOR_POLICY, e, - // A holder's item, read at its own address. - async (holder) => (await protocol.getMetaItem({ - type, name, packageId: holder, ...memberSelector, - }) as { item?: unknown } | undefined)?.item, + holderItemReader(protocol, type, name, memberSelector), ); } catch (fault: any) { return withHeaders(deps.errorFromThrown(fault, 500), headers); @@ -2440,10 +2459,7 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin // `RestServer`'s question). const gated = await gateHolderNamingRefusal( metaItemReadGateSources(deps, _context, protocol), singularType, name, RENDERED_DOCUMENT_POLICY, e, - // A holder's item, read at its own address. - async (holder) => (await protocol.getMetaItem({ - type: singularType, name, packageId: holder, ...memberSelector, - }) as { item?: unknown } | undefined)?.item, + holderItemReader(protocol, singularType, name, memberSelector), ); if (gated) return { handled: true, response: deps.error(gated.message, gated.status, { code: gated.code }) }; throw e; From b6f7c36fbc9739a64c69458fa4290a27da78fffe Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:37:23 +0000 Subject: [PATCH 13/15] fix(rest,runtime): the view gate judges every holder the refusal names, the environment's own item included The view arm reads each holder at its own address (a package at its `?package=`, the environment at the address naming no package) and answers the gate's refusal of any one of them before the `not-held-by-qualifier` refusal names a holder. A holder that cannot be read fails closed with a fault that names none. Claude-Session: https://claude.ai/code/session_01ADHkmNkZcGApqG4pHHMLeY Co-authored-by: Claude --- packages/rest/src/index.ts | 1 + packages/rest/src/meta-item-read-gate.ts | 54 ++++++++++---- packages/rest/src/meta-item-read-routes.ts | 4 +- packages/rest/src/rest-server.ts | 3 +- .../meta-holder-refusal-audience-gate.test.ts | 71 ++++++++++++++++--- packages/runtime/src/domains/meta.ts | 9 ++- 6 files changed, 114 insertions(+), 28 deletions(-) diff --git a/packages/rest/src/index.ts b/packages/rest/src/index.ts index c115977a42b..b7359ede047 100644 --- a/packages/rest/src/index.ts +++ b/packages/rest/src/index.ts @@ -203,6 +203,7 @@ export type { MetaBookTreeSources, MetaItemAnswer, MetaItemAnswerSources, + MetaHolderCandidate, MetaHolderItemReader, MetaItemReadGateSources, MetaItemReadRefusal, diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index 6a1c8da5412..525302ccd1b 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -4755,19 +4755,24 @@ export function createMetaItemAnswer( }; } +/** [#34247] A holder a `not-held-by-qualifier` refusal names, as {@link MetaHolderItemReader} reads it. */ +export type MetaHolderCandidate = { kind: 'package'; packageId: string } | { kind: 'environment' }; + /** * [#34247] How {@link gateHolderNamingRefusal} reads one holder's item: the - * transport's own by-name read of `name` at `?package=`, answering - * the served `item` (or `null`/`undefined` when that package serves none). A - * rejection is a gate input that cannot be read: it propagates, and the - * transport answers that fault, never the refusal. + * transport's own by-name read of the name at that holder's address — a + * package holder at `?package=`, the environment's own item at the + * address that names no package — answering the served `item` (or + * `null`/`undefined` when that address serves none). A rejection is a gate + * input that cannot be read: the gate fails closed (see + * {@link gateHolderNamingRefusal}). */ -export type MetaHolderItemReader = (packageId: string) => Promise; +export type MetaHolderItemReader = (holder: MetaHolderCandidate) => Promise; /** * [ruling 6917064203 on #34398 · #34247] The read gate answers before the * `not-held-by-qualifier` refusal names any holder. An exact `?package=X` read - * of a name X holds no item of, while another package holds it, is refused by + * of a name X holds no item of, while another holder holds it, is refused by * the protocol `409 RESOURCE_CONFLICT` `not-held-by-qualifier` with the * holders as its candidates; that refusal is answered only to a caller the * type's own read gate admits. A caller the gate refuses is answered the @@ -4778,14 +4783,17 @@ export type MetaHolderItemReader = (packageId: string) => Promise; * judges a doc by its NAME (its effective audience over the books that * claim the name), so the judgment needs no holder's item. * - `view`: the list view audience ({@link filterViewForUser}), `403 - * PERMISSION_DENIED`. A view is judged by its body, so each package holder's - * item is read through `readHolderItem` and judged by the view arm; the - * gate's refusal of any one of them is the answer. + * PERMISSION_DENIED`. A view is judged by its body, so EVERY holder the + * refusal names — each package and the environment — is read through + * `readHolderItem` and judged by the view arm; the gate's refusal of any + * one of them is the answer. A candidate of any other kind cannot be read + * at an address of its own, so it fails closed, as a read that rejects. * * Any other thrown value, and any other type, is `undefined`: the transport * answers the thrown value as it did. A gate input that cannot be read - * REJECTS, as the gate always does: the transport answers that fault, never - * the refusal. + * REJECTS, as the gate always does, and a holder read that rejects is + * rethrown as a fault that names no holder: the transport answers that fault, + * never the refusal. * * One function, called by both transports' plain read and `/layers` read. */ @@ -4805,11 +4813,19 @@ export async function gateHolderNamingRefusal( const verdict = await createMetaItemReadGate(sources, metaType, name, [named], policy)(named); return verdict.kind === 'refuse' && verdict.refusal.reason === 'docs-audience' ? verdict.refusal : undefined; } - const holders = (Array.isArray(refusal.candidates) ? refusal.candidates : []) - .filter((c: any): c is { kind: 'package'; packageId: string } => c?.kind === 'package' && typeof c.packageId === 'string') - .map((c) => c.packageId); + const candidates = Array.isArray(refusal.candidates) ? refusal.candidates as unknown[] : []; const items: unknown[] = []; - for (const holder of holders) items.push(await readHolderItem(holder)); + for (const candidate of candidates) { + const holder = holderCandidateOf(candidate); + if (holder === undefined) { + throw new Error(`A holder of the ${metaType} "${name}" cannot be read at an address of its own, so its read gate cannot be judged.`); + } + try { + items.push(await readHolderItem(holder)); + } catch { + throw new Error(`A holder of the ${metaType} "${name}" could not be read, so its read gate cannot be judged.`); + } + } const judge = createMetaItemReadGate(sources, metaType, name, items, policy); for (const item of items) { const verdict = await judge(item); @@ -4818,6 +4834,14 @@ export async function gateHolderNamingRefusal( return undefined; } +/** A refusal candidate as {@link MetaHolderItemReader} reads it, or `undefined` for a kind with no address of its own. */ +function holderCandidateOf(candidate: unknown): MetaHolderCandidate | undefined { + const c = candidate as { kind?: unknown; packageId?: unknown } | null | undefined; + if (c?.kind === 'package' && typeof c.packageId === 'string' && c.packageId !== '') return { kind: 'package', packageId: c.packageId }; + if (c?.kind === 'environment') return { kind: 'environment' }; + return undefined; +} + // ── THE layered answer ──────────────────────────────────────────────────────── /** diff --git a/packages/rest/src/meta-item-read-routes.ts b/packages/rest/src/meta-item-read-routes.ts index dcf660c6434..12a0b8b3c84 100644 --- a/packages/rest/src/meta-item-read-routes.ts +++ b/packages/rest/src/meta-item-read-routes.ts @@ -1102,7 +1102,9 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M metaType, req.params.name, readPolicyFor, readError, // A holder's item, read at its own address. async (holder) => (await p.getMetaItem({ - type: req.params.type, name: req.params.name, packageId: holder, ...memberSelector, + type: req.params.type, name: req.params.name, + ...(holder.kind === 'package' ? { packageId: holder.packageId } : {}), + ...memberSelector, }) as { item?: unknown } | undefined)?.item, ); if (gated) { diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index d973219252f..c755bc0ff14 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -4464,7 +4464,8 @@ export class RestServer { RestServer.metaTypeSingular(req.params.type), req.params.name, metaReadGate.STORED_VERSION_DOOR_POLICY, readError, async (holder) => (await p.getMetaItem({ - type: req.params.type, name: req.params.name, packageId: holder, + type: req.params.type, name: req.params.name, + ...(holder.kind === 'package' ? { packageId: holder.packageId } : {}), ...metaReadGate.metaMemberSelector(req.query), ...(environmentId ? { environmentId } : {}), } as any) as { item?: unknown } | undefined)?.item, diff --git a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts index 5ff42414206..9edfe13cf6d 100644 --- a/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts +++ b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts @@ -26,7 +26,8 @@ import '@objectstack/metadata'; import { RestServer } from '@objectstack/rest'; import { HttpDispatcher } from '../http-dispatcher.js'; import { PackageScopedNameRefusedError } from '@objectstack/core'; -const THROW: { type?: string; name?: string } = {}; +type Candidate = { kind: 'package'; packageId: string } | { kind: 'environment' }; +const THROW: { type?: string; name?: string; candidates?: Candidate[] } = {}; // ── Fixtures (the #20193 parity rig's docs) ─────────────────────────────────── @@ -56,6 +57,15 @@ const VIEWS = [ { name: 'crm_pipeline_review', label: 'Pipeline review', type: 'grid', data: { provider: 'object', object: 'crm_deal' }, requiredPermissions: ['crm_pipeline_audit'], _packageId: 'crm' }, ]; const STORE: Record = { book: [ADMIN_GUIDE, HELP_CENTER], doc: DOCS, view: VIEWS }; +/** + * The environment's own items (no `_packageId`), served at the address that + * names no package: a view only the environment holds, and the environment's + * item of a name `crm` also holds, each behind its own audience. + */ +const ENVIRONMENT_VIEWS = [ + { name: 'env_pipeline_review', label: 'Pipeline review (environment)', type: 'grid', data: { provider: 'object', object: 'crm_deal' }, requiredPermissions: ['crm_pipeline_audit'] }, + { name: 'crm_pipeline_review', label: 'Pipeline review (environment)', type: 'grid', data: { provider: 'object', object: 'crm_deal' }, requiredPermissions: ['env_pipeline_audit'] }, +]; const clone = (v: T): T => JSON.parse(JSON.stringify(v)); const singular = (type: unknown): string => String(type ?? '').replace(/s$/, ''); @@ -69,7 +79,7 @@ interface Caller { holdings: string[]; readableFields: string[]; } -const CALLERS: Record<'holder' | 'non-holder' | 'anonymous' | 'view-holder', Caller> = { +const CALLERS: Record<'holder' | 'non-holder' | 'anonymous' | 'view-holder' | 'both-view-holder', Caller> = { holder: { ctx: { userId: 'u_holder', isSystem: false, systemPermissions: [] }, holdings: ['crm_admin'], @@ -86,6 +96,11 @@ const CALLERS: Record<'holder' | 'non-holder' | 'anonymous' | 'view-holder', Cal holdings: [], readableFields: [], }, + 'both-view-holder': { + ctx: { userId: 'u_both_view_holder', isSystem: false, systemPermissions: ['crm_pipeline_audit', 'env_pipeline_audit'] }, + holdings: [], + readableFields: [], + }, }; type CallerName = keyof typeof CALLERS; @@ -93,16 +108,17 @@ type CallerName = keyof typeof CALLERS; * The protocol's refusal of `?package=sales` for a doc or view `sales` ships * none of while `crm` ships it (`notHeldByQualifierRefusal` in * `@objectstack/metadata-protocol`): `PackageScopedNameRefusedError`, reason - * `not-held-by-qualifier`, naming the holder. The holder's own address - * (`?package=crm`) serves its item. + * `not-held-by-qualifier`, naming the holder (or the holders `THROW.candidates` + * names). Every other address serves: the holder's own (`?package=crm`) its + * item, the one naming no package the environment's item where it has one. */ function refuseIfAsked(type: unknown, name: unknown, packageId: unknown): void { const t = singular(type); - if (packageId === 'crm') return; + if (packageId !== 'sales') return; if (t !== (THROW.type ?? 'doc') || name !== THROW.name) return; const base = { status: 'refused' as const, reason: 'not-held-by-qualifier' as const, type: t, name: String(name), - callerPackageId: 'sales', candidates: [{ kind: 'package' as const, packageId: 'crm' }], + callerPackageId: 'sales', candidates: THROW.candidates ?? [{ kind: 'package' as const, packageId: 'crm' }], }; throw new PackageScopedNameRefusedError({ ...base, message: `${t} "${String(name)}" is not held by package "sales"` } as never); } @@ -114,7 +130,10 @@ function protocolDouble() { getMetaItems: vi.fn(async ({ type }: any) => clone(STORE[singular(type)] ?? [])), getMetaItem: vi.fn(async ({ type, name, packageId }: any) => { refuseIfAsked(type, name, packageId); - const found = find(type, name); + const environmentItem = packageId === undefined && singular(type) === 'view' + ? ENVIRONMENT_VIEWS.find((i) => i.name === name) + : undefined; + const found = environmentItem ?? find(type, name); return { type: singular(type), name, item: found ? clone(found) : undefined, lock: 'none', editable: true, deletable: true, resettable: false }; }), getMetaItemLayered: vi.fn(async ({ type, name, packageId }: any) => { @@ -216,12 +235,13 @@ const PATH = (type: string, name: string, suffix: string) => `/meta/${type}/${na * (the holder) it serves the holder's item. */ async function answersFor( - callerName: CallerName, name: string, type = 'doc', packageId = 'sales', + callerName: CallerName, name: string, type = 'doc', packageId = 'sales', candidates?: Candidate[], ): Promise> { const answers: Array = []; if (packageId === 'sales') { THROW.type = type; THROW.name = name; + THROW.candidates = candidates; } try { for (const suffix of DOORS) { @@ -232,6 +252,7 @@ async function answersFor( } finally { THROW.type = undefined; THROW.name = undefined; + THROW.candidates = undefined; } return answers; } @@ -296,3 +317,37 @@ describe('[#34247] the view gate answers before the not-held-by-qualifier refusa } }); }); + +describe('[#34247] the view gate judges every holder the refusal names, the environment included, both transports', () => { + const ENVIRONMENT_ONLY: Candidate[] = [{ kind: 'environment' }]; + const PACKAGE_AND_ENVIRONMENT: Candidate[] = [{ kind: 'package', packageId: 'crm' }, { kind: 'environment' }]; + + it('a view only the environment holds: a member its audience refuses is answered the gate\'s 403, never the refusal naming holders', async () => { + for (const answer of await answersFor('non-holder', 'env_pipeline_review', 'view', 'sales', ENVIRONMENT_ONLY)) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([403, 'PERMISSION_DENIED', false, answer.door]); + } + }); + + it('CONTROL: a view only the environment holds, a member its audience admits is answered the 409', async () => { + for (const answer of await answersFor('view-holder', 'env_pipeline_review', 'view', 'sales', ENVIRONMENT_ONLY)) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([409, 'RESOURCE_CONFLICT', true, answer.door]); + } + }); + + it('a view a package and the environment both hold: a member the package\'s view admits and the environment\'s refuses is answered the gate\'s 403, never the refusal naming holders', async () => { + for (const answer of await answersFor('view-holder', 'crm_pipeline_review', 'view', 'sales', PACKAGE_AND_ENVIRONMENT)) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([403, 'PERMISSION_DENIED', false, answer.door]); + } + }); + + it('CONTROL: the same co-held view, a member both audiences admit is answered the 409 naming the holders', async () => { + for (const answer of await answersFor('both-view-holder', 'crm_pipeline_review', 'view', 'sales', PACKAGE_AND_ENVIRONMENT)) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([409, 'RESOURCE_CONFLICT', true, answer.door]); + expect(JSON.stringify(answer.body), answer.door).toContain('crm'); + } + }); +}); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index ba63ac26174..6550119c69d 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -950,7 +950,8 @@ type LayeredReadWithDraft = ( ) => ReturnType; /** - * [#34247] A holder's item, read at its own address (`?package=`), for + * [#34247] A holder's item, read at its own address (`?package=` for a + * package, the address naming no package for the environment's own item), for * {@link gateHolderNamingRefusal}. A protocol with no by-name read cannot * answer it, so the read REJECTS: the gate fails closed and the transport * answers that fault, never the refusal naming holders. @@ -963,9 +964,11 @@ function holderItemReader( ): MetaHolderItemReader { return async (holder) => { if (typeof protocol.getMetaItem !== 'function') { - throw new Error(`The protocol serves no by-name read, so the item "${name}" of type "${type}" cannot be read at package "${holder}" to judge its read gate.`); + throw new Error(`The protocol serves no by-name read, so a holder of the ${type} "${name}" cannot be read to judge its read gate.`); } - const envelope = await protocol.getMetaItem({ type, name, packageId: holder, ...memberSelector }); + const envelope = await protocol.getMetaItem({ + type, name, ...(holder.kind === 'package' ? { packageId: holder.packageId } : {}), ...memberSelector, + }); return (envelope as { item?: unknown } | undefined)?.item; }; } From 0bc781b54587635ecf31e2c9e60558828a281a15 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:01:22 +0000 Subject: [PATCH 14/15] fix(runtime): answer an unreadable gate input as a fault on every read door The plain metadata read now answers the same fault status as the layered read when the read gate's input cannot be read; pinned on both transports' plain read and /layers (status and code). Claude-Session: https://claude.ai/code/session_01ADHkmNkZcGApqG4pHHMLeY Co-authored-by: Claude --- packages/rest/src/meta-item-read-gate.ts | 6 ++--- .../meta-holder-refusal-audience-gate.test.ts | 26 ++++++++++++++++++- packages/runtime/src/domains/meta.ts | 16 +++++++++--- 3 files changed, 40 insertions(+), 8 deletions(-) diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index 525302ccd1b..f81db4d6087 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -4774,9 +4774,9 @@ export type MetaHolderItemReader = (holder: MetaHolderCandidate) => Promise clone(STORE[singular(type)] ?? [])), getMetaItem: vi.fn(async ({ type, name, packageId }: any) => { refuseIfAsked(type, name, packageId); + // A holder read that fails: the store behind the holder's address is down. + if (THROW.holderReadFails && packageId !== 'sales') throw new Error('metadata store unavailable'); const environmentItem = packageId === undefined && singular(type) === 'view' ? ENVIRONMENT_VIEWS.find((i) => i.name === name) : undefined; @@ -236,12 +238,14 @@ const PATH = (type: string, name: string, suffix: string) => `/meta/${type}/${na */ async function answersFor( callerName: CallerName, name: string, type = 'doc', packageId = 'sales', candidates?: Candidate[], + holderReadFails = false, ): Promise> { const answers: Array = []; if (packageId === 'sales') { THROW.type = type; THROW.name = name; THROW.candidates = candidates; + THROW.holderReadFails = holderReadFails; } try { for (const suffix of DOORS) { @@ -253,6 +257,7 @@ async function answersFor( THROW.type = undefined; THROW.name = undefined; THROW.candidates = undefined; + THROW.holderReadFails = undefined; } return answers; } @@ -351,3 +356,22 @@ describe('[#34247] the view gate judges every holder the refusal names, the envi } }); }); + +describe('[#34247] a holder the view gate cannot read fails closed, both transports', () => { + it('a holder read that rejects is answered a fault with no candidates on the plain read and /layers, for a refused and an admitted member alike', async () => { + for (const c of ['non-holder', 'view-holder'] as const) { + for (const answer of await answersFor(c, 'crm_pipeline_review', 'view', 'sales', undefined, true)) { + expect([answer.status, answer.code, namesHolders(answer), answer.door], JSON.stringify(answer.body)) + .toEqual([500, 'INTERNAL_ERROR', false, answer.door]); + expect(JSON.stringify(answer.body ?? null), answer.door).not.toContain('crm"'); + } + } + }); + + it('CONTROL: the same address with a holder that reads is the gate\'s answer, not a fault', async () => { + for (const answer of await answersFor('view-holder', 'crm_pipeline_review', 'view', 'sales', undefined, false)) { + expect([answer.status, answer.code, answer.door], JSON.stringify(answer.body)) + .toEqual([409, 'RESOURCE_CONFLICT', answer.door]); + } + }); +}); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 6550119c69d..126f0815037 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -2460,10 +2460,18 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin // answers before the `not-held-by-qualifier` refusal // names any holder (`gateHolderNamingRefusal`, // `RestServer`'s question). - const gated = await gateHolderNamingRefusal( - metaItemReadGateSources(deps, _context, protocol), singularType, name, RENDERED_DOCUMENT_POLICY, e, - holderItemReader(protocol, singularType, name, memberSelector), - ); + let gated: Awaited>; + try { + gated = await gateHolderNamingRefusal( + metaItemReadGateSources(deps, _context, protocol), singularType, name, RENDERED_DOCUMENT_POLICY, e, + holderItemReader(protocol, singularType, name, memberSelector), + ); + } catch (fault: any) { + // A gate input that cannot be read is a fault, answered + // as the layered read answers it: never this handler's + // outer absence, and never the refusal naming holders. + return { handled: true, response: deps.errorFromThrown(fault, 500) }; + } if (gated) return { handled: true, response: deps.error(gated.message, gated.status, { code: gated.code }) }; throw e; } From 1572520e9f465c673a5d9567cdac1e27a91efcf7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:04:45 +0000 Subject: [PATCH 15/15] fix(metadata-protocol): a bare doc read's environment entry keeps the layered read's code layer empty after the bare-name fallback The bare-name artifact fallback of the layered read now skips a bare doc read that answers the environment's own entry, as it skips the bare action read's judged answer: the artifact lookup's first composite is the holder registered first, which that read never serves. Claude-Session: https://claude.ai/code/session_01ADHkmNkZcGApqG4pHHMLeY Co-authored-by: Claude --- .../metadata-protocol/src/protocol-meta-layered-reads.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/metadata-protocol/src/protocol-meta-layered-reads.ts b/packages/metadata-protocol/src/protocol-meta-layered-reads.ts index 21d9f08d7a0..f038dd88f90 100644 --- a/packages/metadata-protocol/src/protocol-meta-layered-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-layered-reads.ts @@ -456,7 +456,11 @@ export async function getMetaItemLayered(host: Pick