diff --git a/.changeset/38659-bare-read-own-envelope.md b/.changeset/38659-bare-read-own-envelope.md new file mode 100644 index 00000000000..bc1c26fcf9b --- /dev/null +++ b/.changeset/38659-bare-read-own-envelope.md @@ -0,0 +1,15 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/spec': patch +--- + +fix(metadata-protocol): the bare doc read of the environment's own entry carries the environment's envelope, never a package holder's + +Clause-②: no +Metadata-protocol: none + +A doc read that names no package (`GET /api/v1/meta/doc/NAME`, and the in-process `getMetaItem` with no `packageId`) answers the environment's own doc entry when one or more enabled packages ship the same name. It served that entry's content under the first registered holder's envelope: `item._packageId` and `item._packageVersion` that holder's, `_provenance: 'package'`, and the read envelope's `packageId`, `packageVersion` and `provenance` likewise. A client trusting the envelope read the environment's item as that package's, and with two holders the package it named followed registration order. + +FROM the entry under the first registered holder's envelope, TO the entry under its own: no `_packageId` or `_packageVersion`, its own `_provenance` (`org` for a stored row the environment saved), and no `packageId` on the envelope. The lock is unchanged: it is still the write doors' answer at that address, and a save naming no package is still refused while a holder ships the name, so the envelope still reports `lock: full`. `?package=PACKAGE` still reads that package's doc under that package's envelope. `/layers` and `/published` carried no package envelope and are unchanged. + +The fix for a caller that read the holder's id from the bare read: name the package (`?package=PACKAGE`, or `packageId` in process). The `os migrate meta --from 18` entry `doc-bare-read-environment-entry-first` no longer lists this as a known deviation. diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index 57846980e37..8109df4c61f 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -68,6 +68,7 @@ import { envelopePackageId, exactAddressArtifact, mergeArtifactProtection, + servesEnvironmentOwnItem, withRowBinding, } from './protocol-package-bindings.js'; import type { ServedOverrideRow } from './served-override.js'; @@ -1574,11 +1575,16 @@ export async function readMetaItem(host: Pick host.lookupArtifactItem( request.type, request.name, packageId, bundleMemberOf(request.type, item), artifactOwner, )) + : servesEnvironmentOwnItem(bareDocEnvironmentEntry, item) + ? undefined : host.lookupArtifactItem( request.type, request.name, envelopePackageId(request.packageId, item), bundleMemberOf(request.type, item), artifactOwner, diff --git a/packages/metadata-protocol/src/protocol-package-bindings.ts b/packages/metadata-protocol/src/protocol-package-bindings.ts index bbe13b7a59f..c457fb72507 100644 --- a/packages/metadata-protocol/src/protocol-package-bindings.ts +++ b/packages/metadata-protocol/src/protocol-package-bindings.ts @@ -17,6 +17,7 @@ import { itemDiscriminator, type InstalledManifestLookup, } from '@objectstack/metadata-core'; +import { storedItemPackageId } from '@objectstack/metadata/stored-item-package'; import { isServedOverrideRowOf } from './served-override.js'; import { canonicalMetaType } from './protocol-meta-type-schema.js'; @@ -238,6 +239,37 @@ function envelopePackageId(requestedPackageId: string | undefined, served: unkno return requestedPackageId ?? (served as { _packageId?: string } | null | undefined)?._packageId; } +/** + * [#38659, ruling 6942962369] Does a read that names no package serve the + * environment's own item where packages hold the same name? Then the answer + * wears NO artifact envelope: it keeps the item's own `_packageId` (none) and + * `_provenance`. Its lock is not chosen here and does not move: it is the + * write doors' answer at the read's address (the one item-lock resolution, + * {@link resolveItemLock}, and the sealed-base refusal, through the read's + * `servedLockState`), which refuse a save and a delete there while a holder + * ships the name, so the envelope still reports both refused. + * + * `environmentEntry` is the read's own verdict that the environment's entry + * answers first beside one or more enabled holders (the bare doc read's + * `refuseAmbiguousBareDocRead`), and `served` is the item the read's layers + * reached. Both must hold: the verdict, and a served item bound to no package + * ({@link storedItemPackageId}, the store's own reading, sentinel included). + * + * {@link envelopePackageId} names no package for such an item, so the + * package-less artifact lookup fell back to the first registered holder's + * artifact, and the environment's entry was served under that holder's + * `_packageId`, `_packageVersion` and `_provenance: 'package'`: a client + * trusting the envelope read the environment's item as that package's, and + * which package it named followed registration order. A package-less item + * the read did NOT judge to be the environment's own entry (a package-less + * row standing in for a base) keeps the base's envelope, as before. + */ +function servesEnvironmentOwnItem(environmentEntry: unknown, served: unknown): boolean { + return environmentEntry !== undefined && environmentEntry !== null + && served !== undefined && served !== null + && storedItemPackageId(served) === undefined; +} + /** * [#32501, ADR-0150 D5, epic red line 2] The artifact envelope a read at an * admitted exact address wears: the artifact of the ONE package that address @@ -540,6 +572,7 @@ export { isShippedViewItem, mergeArtifactProtection, perPackageLayerEnvelope, + servesEnvironmentOwnItem, servesSealedOverrideRow, stateTenantAuthorship, stripDerivedProvenance, diff --git a/packages/runtime/src/domains/meta-bare-read-own-envelope-38659.test.ts b/packages/runtime/src/domains/meta-bare-read-own-envelope-38659.test.ts new file mode 100644 index 00000000000..27099a7aa69 --- /dev/null +++ b/packages/runtime/src/domains/meta-bare-read-own-envelope-38659.test.ts @@ -0,0 +1,277 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#38659, ruling 6942962369] A bare read (`GET /meta/doc/NAME`, no +// `?package=`) that answers the environment's own doc entry beside one or more +// enabled holders of the name carries the ENVIRONMENT's envelope: no +// `_packageId` or `_packageVersion` on the item, the entry's own +// `_provenance`, no `packageId` and the entry's own `provenance` on the +// envelope. Its lock is the write doors' answer at that address, which refuse +// a save and a delete there while a holder ships the name, so the envelope +// keeps reporting both refused. Pinned in every cell: one holder and two +// holders, each in both registration orders, on the runtime dispatcher, on +// `RestServer`'s registered handler and in process (`protocol.getMetaItem`), +// for both forms of the environment's entry (a stamp-less registration in the +// registry's bare slot, and a package-less stored row hydrated as the +// hydrator lays it when it reads the row before the artifacts). CONTROL: each +// holder's exact address (`?package=X`) reads X's doc under X's envelope. +// +// Booted the way `createStandaloneStack` composes a compiled artifact, as the +// sibling `meta-disabled-holder-artifact-door.test.ts` rig is. +// +// FROM (origin/main 8338d070, this rig, all four cells, both forms, measured): +// every transport's plain read served the entry's body under the FIRST +// registered holder's envelope (`item._packageId` and `packageId` that +// holder, `_provenance` and `provenance` `package`), so with two holders the +// package it named followed registration order. `/layers` and `/published` +// carried no package envelope; the save naming no package answered `403 +// NOT_OVERRIDABLE` (and the delete, where a stored row exists), and the +// envelope said `lock: full`, `editable` and `deletable` false. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectKernel } from '@objectstack/core'; +import { MetadataPlugin } from '@objectstack/metadata'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { RestServer } from '@objectstack/rest'; +import { resolveThrownHttpError } from '@objectstack/types'; +import { HttpDispatcher } from '../http-dispatcher.js'; +import { AppPlugin } from '../app-plugin.js'; +import { loadArtifactBundle } from '../load-artifact-bundle.js'; + +const CALLER = { userId: 'u_bare_read_envelope', tenantId: 'org_qa', isSystem: true, positions: [], permissions: [], systemPermissions: ['manage_metadata'] }; +const ALPHA = 'com.qa.alpha'; +const BETA = 'com.qa.beta'; +const NAME = 'shared_doc'; +const labelOf = (id: string) => `${id.split('.').pop()} doc`; + +/** One package body; it ships the doc only when `ships` names it. */ +const docBodyOf = (ships: readonly string[]) => (id: string) => ({ + manifest: { + id, name: id.split('.').pop(), namespace: id.split('.').pop(), version: '1.0.0', type: 'app', + docs: ships.includes(id) ? [{ name: NAME, label: labelOf(id), content: `# ${id.split('.').pop()}` }] : [], + }, +}); + +interface Booted { kernel: ObjectKernel; engine: ObjectQL; root: string } + +async function bootArtifactKernel(order: readonly string[], ships: readonly string[]): Promise { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + const root = mkdtempSync(join(tmpdir(), 'os-meta-bare-read-envelope-')); + const engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as any, true); + const artifact = join(root, 'objectstack.json'); + writeFileSync(artifact, JSON.stringify({ + manifest: { id: 'com.qa.host', name: 'host', version: '0.0.1', type: 'app' }, + objects: [], views: [], apps: [], flows: [], requires: [], + packages: order.map(docBodyOf(ships)), + })); + await kernel.use(new MetadataPlugin({ watch: false, artifactWatch: false, artifactSource: { mode: 'local-file', path: artifact }, rootDir: root } as any)); + await kernel.use(new ObjectQLPlugin({ ql: engine })); + const bundle = await loadArtifactBundle(artifact, { tag: '[#38659 rig]', unwrapEnvelope: true }); + await kernel.use(new AppPlugin(bundle, undefined, { skipSeedData: true, securityMetadataRegistrar: 'artifact-door' })); + await kernel.bootstrap(); + await engine.syncSchemas(); + return { kernel, engine, root }; +} + +const errorCodeOf = (body: any): unknown => (body?.error && typeof body.error === 'object' ? body.error.code : body?.code); + +/** The plain read on the runtime dispatcher. */ +async function viaDispatcher(kernel: ObjectKernel, query: Record) { + const path = `/meta/doc/${NAME}`; + const dispatcher = new HttpDispatcher(kernel as any, undefined, { enforceProjectMembership: false }); + (dispatcher as any).timedResolveExecutionContext = async () => ({ ...CALLER }); + try { + const out: any = await dispatcher.dispatch('GET', path, {}, query, { request: new Request(`http://localhost/api/v1${path}`) } as any, '/api/v1'); + return { status: out.response?.status as number | undefined, body: out.response?.body?.data ?? out.response?.body }; + } catch (e) { + const thrown = resolveThrownHttpError(e); + return { status: thrown.status, body: { code: thrown.code, message: String((e as Error)?.message ?? '') } }; + } +} + +/** The plain read on `RestServer`, through its registered handler. */ +async function viaRest(booted: Booted, query: Record) { + const noop = () => {}; + const server = { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; + const rest: any = new RestServer(server as any, booted.kernel.getService('protocol') as any, { api: { requireAuth: false } } as any); + rest.resolveExecCtx = async () => ({ ...CALLER }); + rest.objectQLProvider = async () => booted.engine; + rest.metadataServiceProvider = async () => booted.kernel.getService('metadata'); + rest.registerRoutes(); + const handler = rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === '/api/v1/meta/:type/:name')?.handler; + expect(handler, 'precondition: RestServer registers GET /meta/:type/:name').toBeTruthy(); + const res: any = { statusCode: 200, body: undefined }; + res.status = (code: number) => { res.statusCode = code; return res; }; + res.json = (out: unknown) => { res.body = out; return res; }; + res.header = () => res; res.setHeader = noop; res.send = () => res; res.end = () => res; + await handler({ method: 'GET', path: `/api/v1/meta/doc/${NAME}`, params: { type: 'doc', name: NAME }, headers: {}, query }, res); + return { status: res.statusCode as number, body: res.body?.data ?? res.body }; +} + +/** The plain read in process, through the kernel's protocol. */ +async function inProcess(booted: Booted, query: Record) { + const protocol = booted.kernel.getService('protocol'); + try { + return { status: 200, body: await protocol.getMetaItem({ type: 'doc', name: NAME, ...(query.package ? { packageId: query.package } : {}) }) }; + } catch (e) { + const thrown = resolveThrownHttpError(e); + return { status: thrown.status, body: { code: thrown.code } }; + } +} + +/** The plain read of the doc on the three transports. */ +async function plainReads(booted: Booted, query: Record = {}) { + const at = query.package ? `?package=${query.package}` : ''; + return [ + { door: `dispatcher doc/${NAME}${at}`, ...(await viaDispatcher(booted.kernel, query)) }, + { door: `rest doc/${NAME}${at}`, ...(await viaRest(booted, query)) }, + { door: `in-process getMetaItem doc/${NAME}${at}`, ...(await inProcess(booted, query)) }, + ]; +} + +/** What an answer says about whose item it is: its body's stamp and its envelope. */ +const envelopeOf = (answer: { status: number | undefined; body: any }) => { + const item = answer.body?.item; + return { + status: answer.status, + label: item?.label, + itemPackageId: item?._packageId, + itemPackageVersion: item?._packageVersion, + itemProvenance: item?._provenance, + packageId: answer.body?.packageId, + packageVersion: answer.body?.packageVersion, + provenance: answer.body?.provenance, + }; +}; + +/** An outcome of a write door: resolved, or its refusal's code and status. */ +const settle = (write: Promise) => write.then( + () => ({ ok: true as const }), + (e: any) => ({ ok: false as const, code: e?.code, status: e?.status }), +); + +/** The environment's own entry, in each form it takes in the registry's bare slot. */ +const ENTRY_FORMS = [ + { + form: 'a stamp-less registration in the bare slot', + label: 'bare entry', + provenance: undefined, + storedRow: false, + lay: async (booted: Booted) => { + booted.engine.registry.registerItem('doc', { name: NAME, label: 'bare entry', content: '# bare' } as never, 'name' as never); + }, + }, + { + form: 'a package-less stored row, hydrated before the artifacts', + label: 'environment doc', + provenance: 'org', + storedRow: true, + lay: async (booted: Booted) => { + await booted.engine.insert('sys_metadata', { + type: 'doc', name: NAME, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', state: 'active', version: 1, + metadata: JSON.stringify({ name: NAME, label: 'environment doc', content: '# env' }), + }, { context: { isSystem: true } } as any); + booted.engine.registry.registerItem('doc', { name: NAME, label: 'environment doc', content: '# env', _provenance: 'org' } as never, 'name' as never); + }, + }, +] as const; + +async function clearEntry(booted: Booted): Promise { + (booted.engine.registry as unknown as { metadata: Map> }).metadata.get('doc')?.delete(NAME); + await booted.engine.delete('sys_metadata', { where: { type: 'doc', name: NAME }, multi: true, context: { isSystem: true } } as any); +} + +describe.each([ + { cell: 'one holder, registered first', order: [ALPHA, BETA], ships: [ALPHA] }, + { cell: 'one holder, registered last', order: [BETA, ALPHA], ships: [ALPHA] }, + { cell: 'two holders, alpha registered first', order: [ALPHA, BETA], ships: [ALPHA, BETA] }, + { cell: 'two holders, beta registered first', order: [BETA, ALPHA], ships: [ALPHA, BETA] }, +])('[#38659] the bare doc read of the environment\'s own entry: $cell', ({ order, ships }) => { + let booted: Booted | undefined; + + beforeAll(async () => { + booted = await bootArtifactKernel(order, ships); + }, 120_000); + + afterAll(async () => { + if (!booted) return; + if (booted.kernel.getState() === 'running') await booted.kernel.shutdown(); + rmSync(booted.root, { recursive: true, force: true }); + }); + + it.each(ENTRY_FORMS)('$form: every transport serves the entry under the environment\'s envelope, never a holder\'s', async ({ label, provenance, lay }) => { + await lay(booted!); + try { + for (const answer of await plainReads(booted!)) { + expect([answer.door, envelopeOf(answer)], JSON.stringify(answer.body)).toEqual([answer.door, { + status: 200, + label, + itemPackageId: undefined, + itemPackageVersion: undefined, + itemProvenance: provenance, + packageId: undefined, + packageVersion: undefined, + provenance, + }]); + for (const holder of ships) expect(JSON.stringify(answer.body), answer.door).not.toContain(holder); + } + } finally { + await clearEntry(booted!); + } + }); + + // The lock is not this card's change: the envelope keeps reporting the + // write doors' verdict. The save naming no package is refused in both + // forms; the delete is asked only where a stored row exists, since with + // none this host-config rig's delete door has no row to remove. + it.each(ENTRY_FORMS)('$form: the envelope\'s lock is the write doors\' answer at the same address', async ({ storedRow, lay }) => { + await lay(booted!); + try { + const protocol = booted!.kernel.getService('protocol'); + const save = await settle(protocol.saveMetaItem({ type: 'doc', name: NAME, item: { name: NAME, label: 'saved', content: '# saved' } })); + expect(save).toEqual({ ok: false, code: 'NOT_OVERRIDABLE', status: 403 }); + if (storedRow) { + const remove = await settle(protocol.deleteMetaItem({ type: 'doc', name: NAME })); + expect(remove).toEqual({ ok: false, code: 'NOT_OVERRIDABLE', status: 403 }); + } + for (const answer of await plainReads(booted!)) { + expect([answer.door, answer.status, answer.body?.lock, answer.body?.editable, answer.body?.deletable], JSON.stringify(answer.body)) + .toEqual([answer.door, 200, 'full', false, false]); + } + } finally { + await clearEntry(booted!); + } + }); + + it.each(ENTRY_FORMS)('CONTROL ($form present): each holder\'s `?package=` reads its own doc under its own envelope', async ({ lay }) => { + await lay(booted!); + try { + for (const holder of ships) { + for (const answer of await plainReads(booted!, { package: holder })) { + const seen = envelopeOf(answer); + expect([answer.door, seen.status, seen.label, seen.itemPackageId, seen.itemProvenance, seen.packageId, seen.provenance], JSON.stringify(answer.body)) + .toEqual([answer.door, 200, labelOf(holder), holder, 'package', holder, 'package']); + } + } + } finally { + await clearEntry(booted!); + } + }); + + it('CONTROL (no entry): one holder is served under its own envelope; two holders are refused 409 naming both', async () => { + for (const answer of await plainReads(booted!)) { + if (ships.length === 1) { + const seen = envelopeOf(answer); + expect([answer.door, seen.status, seen.label, seen.itemPackageId, seen.packageId, seen.provenance], JSON.stringify(answer.body)) + .toEqual([answer.door, 200, labelOf(ships[0]!), ships[0], ships[0], 'package']); + } else { + expect([answer.door, answer.status, errorCodeOf(answer.body)], JSON.stringify(answer.body)) + .toEqual([answer.door, 409, 'RESOURCE_CONFLICT']); + } + } + }); +}); diff --git a/packages/spec/src/migrations/entries/semantic/19.doc-bare-read-environment-entry-first.ts b/packages/spec/src/migrations/entries/semantic/19.doc-bare-read-environment-entry-first.ts index 985a8f5b58b..f3b95c7325e 100644 --- a/packages/spec/src/migrations/entries/semantic/19.doc-bare-read-environment-entry-first.ts +++ b/packages/spec/src/migrations/entries/semantic/19.doc-bare-read-environment-entry-first.ts @@ -13,8 +13,10 @@ import type { SemanticMigration } from '../../types.js'; // served the holder registered last. No key is added, removed or re-shaped // and no stored row changes shape, so no tombstone and no D2 conversion. No // relevance question: the move turns on which installed packages hold a name, -// which no question over one stack can name. The known envelope deviation the -// acceptance names is carried by #38659 (the printed guidance names no tracker). +// which no question over one stack can name. The plain read serves the +// environment's entry under the environment's own envelope (#38659): it once +// wore the first registered holder's, a deviation this entry's acceptance +// carried until that fix. export const entry: SemanticMigration = { id: 'doc-bare-read-environment-entry-first', surface: @@ -43,7 +45,6 @@ export const entry: SemanticMigration = { + 'read that names no package answers the environment\'s entry, and GET /api/v1/meta/doc/NAME?package=PACKAGE ' + 'answers that package\'s doc. For every doc name two or more enabled packages hold with no such entry: every ' + 'read that names no package, the in-process layered read included, answers 409 RESOURCE_CONFLICT naming each ' - + 'holder, and each read naming a holder answers its own doc. Known deviation, carried by a follow-up card: the plain read ' - + 'naming no package serves the environment\'s entry under a holder\'s envelope (`_packageId` that holder, ' - + '`_provenance` `package`), as it already did beside two or more holders; the content served is the entry\'s.', + + 'holder, and each read naming a holder answers its own doc. The plain read naming no package serves the environment\'s ' + + 'entry under the environment\'s own envelope (no `_packageId`, the entry\'s own `_provenance`), never a holder\'s.', };