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..9f98446d1cf --- /dev/null +++ b/.changeset/34247-exact-read-own-item-or-none.md @@ -0,0 +1,40 @@ +--- +'@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, 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 +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 + + + +**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. 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/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/...`) 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). +- 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). 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. + +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-discovery-and-bases.ts b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts index 3f952ea487d..7bd9118eef1 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-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 7454a58608f..8fe46e89f53 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 type { FlowRegistration } from '@objectstack/spec/api'; import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared'; @@ -54,6 +54,7 @@ import { declinesPackageLessRowAt, exactQualifierItem, isPackageLessRow, + notHeldByQualifierRefusal, refuseUnjudgeableByNameRead, } from './protocol-exact-qualifier.js'; import { readThroughMetaCompileCache } from './meta-compile-cache.js'; @@ -327,21 +328,47 @@ 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, 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 { - 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): 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 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 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; } /** @@ -436,6 +463,58 @@ 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. 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, 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, + request: { type: string; name: string; packageId?: string }, + 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; + packageScopedHoldersOf?(type: string, name: string): string[] | undefined; + } | undefined; + const own = typeof scoped?.getPackageScopedItem === 'function' + ? scoped.getPackageScopedItem(request.type, request.name, request.packageId, member) + : 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. */ function sameStoredItem(left: unknown, right: unknown): boolean { if (left === right) return true; @@ -712,8 +791,11 @@ 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 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: C }))).toBe('alpha view'); + expect(labelOf(await protocol.getMetaItem({ type: 'view', name: 'all', packageId: A }))).toBe('alpha view'); + 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 () => { @@ -394,10 +396,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 (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: 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 +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', 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: C }))).toBe('alpha view'); + expect(labelOf(await protocol.getMetaItem({ type: 'view', name: 'all', packageId: A }))).toBe('alpha view'); + 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 }]]); }); }); }); @@ -830,6 +835,157 @@ 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: 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. + * + * 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 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. */ + 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 (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']) { + 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 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); + 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 + * another package's address has no slot of its own. `registryAnswerAtAddress` + * leaves its answer to the code layers, on the plain read and `/layers`. + */ + it.each(['position', 'capability'])('CONTROL — %s (one holder, security catalog): `?package=` of another package keeps the code layers\' answer, the holder\'s item, on the plain read and /layers', async (type) => { + 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); + 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']); + }); +}); + /** * [#34041, ADR-0150 D3] A disabled package holds no name, of any type: beside * one enabled holder, the read naming no package serves that holder's item, and diff --git a/packages/rest/src/index.ts b/packages/rest/src/index.ts index 383f4f90def..b7359ede047 100644 --- a/packages/rest/src/index.ts +++ b/packages/rest/src/index.ts @@ -167,6 +167,7 @@ export { createMetaLayeredAnswer, createMetaListReadGate, createMetaListAnswer, + gateHolderNamingRefusal, isPublicAudienceRead, META_TYPE_READ_CAPABILITIES, META_TYPE_WRITE_CAPABILITIES, @@ -202,6 +203,8 @@ export type { MetaBookTreeSources, MetaItemAnswer, MetaItemAnswerSources, + MetaHolderCandidate, + MetaHolderItemReader, MetaItemReadGateSources, MetaItemReadRefusal, MetaItemReadVerdict, diff --git a/packages/rest/src/meta-item-history-routes.ts b/packages/rest/src/meta-item-history-routes.ts index 6a1bba7f109..b8d17c6aaaa 100644 --- a/packages/rest/src/meta-item-history-routes.ts +++ b/packages/rest/src/meta-item-history-routes.ts @@ -1488,6 +1488,15 @@ export function registerMetaItemPublishedRoute(this: MetaItemPublishedRouteHost, if (mixedOwner !== undefined && typeof stamp === 'string' && stamp !== mixedOwner && mixedHolders.includes(stamp)) { data = 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; + if (canonicalMetaUrlType(type) === 'doc' && publishedCode != null && (typeof codeStamp !== 'string' || codeStamp === '' || codeStamp === 'sys_metadata') + && typeof stamp === 'string' && stamp !== '' && stamp !== 'sys_metadata') { + data = publishedCode; + } // The 404 this route could never produce before. An // item that exists but was never published still // answers 200 with its current definition — that is diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index 20ea92f45e0..f81db4d6087 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -4755,6 +4755,93 @@ 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 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 = (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 holder holds it, is refused by + * the protocol `409 RESOURCE_CONFLICT` `not-held-by-qualifier` with the + * holders as its candidates. For a `doc` and a `view`, 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 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, 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. + */ +export async function gateHolderNamingRefusal( + sources: MetaItemReadGateSources, + metaType: string, + name: string, + policy: MetaReadGatePolicy, + thrown: unknown, + 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 candidates = Array.isArray(refusal.candidates) ? refusal.candidates as unknown[] : []; + const items: unknown[] = []; + 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); + if (verdict.kind === 'refuse' && verdict.refusal.reason === 'audience-permission') return verdict.refusal; + } + 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 356116bd6b7..12a0b8b3c84 100644 --- a/packages/rest/src/meta-item-read-routes.ts +++ b/packages/rest/src/meta-item-read-routes.ts @@ -1086,7 +1086,33 @@ 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 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' }; + 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, + // A holder's item, read at its own address. + async (holder) => (await p.getMetaItem({ + type: req.params.type, name: req.params.name, + ...(holder.kind === 'package' ? { packageId: holder.packageId } : {}), + ...memberSelector, + }) as { item?: unknown } | undefined)?.item, + ); + 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 +1147,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..c755bc0ff14 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -4452,7 +4452,30 @@ 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 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, + ...(holder.kind === 'package' ? { packageId: holder.packageId } : {}), + ...metaReadGate.metaMemberSelector(req.query), + ...(environmentId ? { environmentId } : {}), + } as any) as { item?: unknown } | undefined)?.item, + ); + 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 f02d2d3aa29..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 @@ -249,23 +249,142 @@ 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 }); + }); + + // [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]); + } + } + }); + + it.runIf(ships.length === 1)('CONTROL [#34248]: one holder\'s doc is what the bare plain read, /layers and /published serve, both transports', async () => { + 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]); + } + }); + + // [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`; + 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: -// 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). // -// Measured on this rig (origin/main 86350e12, PR #34036 merged): with either -// entry the bare doors do not answer the environment's item; they answer the -// holder the metadata service registered last (a registration-order pick), -// and `/layers` reports the row as the overlay over that holder's effective -// item. Pinned as measured, unresolved: a follow-up decides that answer. +// [#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' }), }, { 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] }, @@ -275,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); @@ -305,31 +433,89 @@ 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 () => { + /** 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 { - 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]); - } + 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('(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 () => { - 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); - 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]); - } + // [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 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(); // The row alone, its registry copy gone: no exemption, refused again. docRegistryOf(booted!).delete('shared_doc'); 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 + // 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 () => { + 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; + 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/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..bb22c43cca3 --- /dev/null +++ b/packages/runtime/src/domains/meta-holder-refusal-audience-gate.test.ts @@ -0,0 +1,377 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [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 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. + */ + +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'; +type Candidate = { kind: 'package'; packageId: string } | { kind: 'environment' }; +const THROW: { type?: string; name?: string; candidates?: Candidate[]; holderReadFails?: boolean } = {}; + +// ── 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 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$/, ''); +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' | 'view-holder' | 'both-view-holder', 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: [] }, + 'view-holder': { + ctx: { userId: 'u_view_holder', isSystem: false, systemPermissions: ['crm_pipeline_audit'] }, + 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; + +/** + * 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 (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 !== '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: THROW.candidates ?? [{ kind: 'package' as const, packageId: 'crm' }], + }; + 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. */ +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, 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; + 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) => { + 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() }; + }), + }; +} + +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, packageId = 'sales') { + 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: packageId }, { 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, packageId = 'sales') { + 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: 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 }; + }; + return { read }; +} + +const DOORS = ['', '/layers'] as const; +const PATH = (type: string, name: string, suffix: string) => `/meta/${type}/${name}${suffix}`; + +/** + * 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', 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) { + 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; + THROW.candidates = undefined; + THROW.holderReadFails = 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]); + } + }); +}); + +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([403, 'PERMISSION_DENIED', false, answer.door]); + } + }); + + 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'); + } + }); + + 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]); + } + 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]); + } + }); +}); + +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'); + } + }); +}); + +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 7054c60488a..126f0815037 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, @@ -104,6 +105,7 @@ import { translateMetaEnvelope, translateMetaList, wantsMetaItemLayers, + type MetaHolderItemReader, type MetaItemAnswer, type MetaItemAnswerSources, type MetaItemReadGateSources, @@ -947,6 +949,30 @@ type LayeredReadWithDraft = ( opts: { withDraft?: boolean }, ) => ReturnType; +/** + * [#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. + */ +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 a holder of the ${type} "${name}" cannot be read to judge its read gate.`); + } + const envelope = await protocol.getMetaItem({ + type, name, ...(holder.kind === 'package' ? { packageId: holder.packageId } : {}), ...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 @@ -1018,6 +1044,20 @@ async function answerMetaLayered( { metaType: pluralToSingular(type), name, ...(packageId ? { packageId } : {}), ...memberSelector, maskPosture }, )(layered); } catch (e: any) { + // [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, + holderItemReader(protocol, type, name, memberSelector), + ); + } 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) { @@ -1676,7 +1716,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; }; @@ -2407,7 +2454,27 @@ 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 read gate admits the caller: the read gate + // answers before the `not-held-by-qualifier` refusal + // names any holder (`gateHolderNamingRefusal`, + // `RestServer`'s question). + 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; + } // [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 217c8533173..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). * @@ -109,7 +92,24 @@ 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): 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 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) { + if (!appName || !readsByNameAfter(localErr, appName)) 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/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 a0413e7774f..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,31 @@ 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 + // `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)) { + 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 (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`, { @@ -100,7 +119,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: { @@ -117,7 +136,7 @@ const { ADAPTER, WORLD } = vi.hoisted(() => { }, }), }; - return { ADAPTER, WORLD }; + return { ADAPTER, WORLD, GATED_REASON }; }); vi.mock('@object-ui/app-shell', async (importOriginal) => ({ @@ -559,4 +578,81 @@ 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']); + }); + + // 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(); + expect(screen.queryByTestId('doc-content')).toBeNull(); + }); + }); });