Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/34261-env-draft-layered-404.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@objectstack/rest': patch
'@objectstack/runtime': patch
---

fix(rest,runtime): the draft and layered `_env` reads of a name only disabled packages hold answer their own 404

Clause-②: no
Metadata-protocol: none

`GET /meta/:type/_env/:name` already answered `404` for a name that only disabled packages hold. Three spellings of the same read still answered `409 RESOURCE_CONFLICT` and named the disabled package: `?state=draft`, `?preview=draft` and `?layers=true`, for a caller who may read pending drafts. Each now answers what the bare by-name read answers, on both transports (`RestServer` and the runtime dispatcher), and names no package:

- `?state=draft` (any case): `404 NO_DRAFT`
- `?preview=draft`: `404 RESOURCE_NOT_FOUND`
- `?layers=true`: `404 RESOURCE_NOT_FOUND`

A package-less draft stored under such a name is the disabled holder's customization, so it is withheld too. Once the holder is enabled again, each read refuses `409` and names it, as before.

The door judges the read the caller actually gets. For a draft read, both the plain read and the draft read must withhold the name. Sometimes an enabled package holds a stored draft of the name that the plain read does not see, and the bare draft read serves that draft to an admitted builder. In that case `_env` keeps the `409` and never serves the draft. The layered view is judged by the plain read, because its chain withholds every layer whenever the plain read withholds a disabled holder's item.

FROM → TO for a client: a `409` on these three reads of a disabled-only name becomes a `404` (`NO_DRAFT` for `?state=draft`). Both are refusals, so code that already handles a missing item needs no change.
107 changes: 80 additions & 27 deletions packages/rest/src/meta-qualified-item-route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import { describe, it, expect, beforeEach, vi } from 'vitest';
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
import { PACKAGE_SCOPED_READ_TYPES, SchemaRegistry } from '@objectstack/objectql';
import { PACKAGE_SCOPED_READ_TYPES, SchemaRegistry, assertEngineFindOnePredicate } from '@objectstack/objectql';
import { RestServer } from './rest-server.js';

const A = 'com.acme.alpha';
Expand Down Expand Up @@ -82,8 +82,12 @@ const storedRowsMatching = (where: Record<string, unknown> | undefined) => store
return (row[key] ?? null) === value;
}));

/** [#34261] Whether the double's `findOne` reads {@link storedRows} — the read a stored draft is served through. */
let findOneReadsStoredRows = false;

beforeEach(() => {
storedRows = [];
findOneReadsStoredRows = false;
registry = new SchemaRegistry({ multiTenant: false });
for (const id of [A, B, C]) {
registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop()! } as never, 'code');
Expand All @@ -92,7 +96,11 @@ beforeEach(() => {
registry,
// [#33385] Stored `sys_metadata` rows for `find`: equality on each `where` key, nothing else.
find: vi.fn(async (_object: string, opts?: { where?: Record<string, unknown> }) => storedRowsMatching(opts?.where)),
findOne: vi.fn().mockResolvedValue(null),
// [#34261] …and for `findOne`, the first such row, only where a pin opts in.
findOne: vi.fn(async (object: string, opts?: { where?: Record<string, unknown> }) => {
assertEngineFindOnePredicate(object, opts);
return (findOneReadsStoredRows ? storedRowsMatching(opts?.where)[0] : undefined) ?? null;
}),
insert: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
Expand Down Expand Up @@ -432,41 +440,86 @@ describe('#32183 — a disabled package holds no name: the by-name read judges t
}
});

// [#33385, review S1] CONTROL — the door judges the read it admits. A
// draft read (`?state=draft`, `?preview=draft`) and the deprecated
// layered view (`?layers=`) are not the read naming no package that
// judged the name, so a marked refusal stands for them: `main`'s 409,
// never an enabled package's draft or stored row at `_env`.
it(`${type}: only a disabled holder in the registry — \`_env\` with an admitted draft switch or the layered view refuses 409, as on main, a caller not admitted to drafts is answered the plain read's 404, never an enabled package's draft or row`, async () => {
const refusedAtEnv = async (query: Record<string, string>) => {
const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query);
expect([env.status, codeOf(env), query], JSON.stringify(env.body)).toEqual([409, 'RESOURCE_CONFLICT', query]);
// [review#2 S4] Its candidate is the disabled registry holder, as on main;
// the enabled package holding the name through its row is not named.
expect(env.body?.details?.candidates, JSON.stringify(env.body)).toEqual([{ kind: 'package', packageId: B }]);
for (const label of [`gamma draft ${type}`, `gamma row ${type}`]) expect(JSON.stringify(env.body ?? null)).not.toContain(label);
};
// [#34261, ADR-0150 2026-11-26 note] FROM `_env` 409 naming the disabled
// holder (#33385 left an admitted draft switch and the layered view
// there) TO each read's own 404, naming no package: `?state=draft` the
// by-name draft read's `404 NO_DRAFT`, `?preview=draft` and `?layers=`
// the plain read's `404 RESOURCE_NOT_FOUND`.
it(`${type}: only a disabled holder — \`_env\` with an admitted draft switch or the layered view answers its own 404, naming no package; re-enabled, each refuses naming it`, async () => {
const answers: Array<[Record<string, string>, number, string]> = [
[{ state: 'draft' }, 404, 'NO_DRAFT'],
[{ state: 'DRAFT' }, 404, 'NO_DRAFT'],
[{ preview: 'draft' }, 404, 'RESOURCE_NOT_FOUND'],
[{ layers: 'true' }, 404, 'RESOURCE_NOT_FOUND'],
];
findOneReadsStoredRows = true;
ship(type, 'solo', B);
registry.disablePackage(B);
// An enabled package's draft row, and no active row of the name.
storedRows.push({ id: 'draft_gamma', type, name: 'solo', state: 'draft', package_id: C,
metadata: JSON.stringify({ name: 'solo', label: `gamma draft ${type}` }) });
const draftReads: Record<string, string>[] = [{ state: 'draft' }, { state: 'DRAFT' }, { preview: 'draft' }];
for (const query of draftReads) await refusedAtEnv(query);
// Its package-less draft is the holder's customization, withheld with it.
const customDraft = { id: 'draft_env', type, name: 'solo', state: 'draft', package_id: null,
metadata: JSON.stringify({ name: 'solo', label: `custom draft ${type}` }) };
for (const rows of [[], [customDraft]]) {
storedRows = rows;
for (const [query, status, code] of answers) {
const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query);
expect([env.status, codeOf(env), query, rows.length], JSON.stringify(env.body)).toEqual([status, code, query, rows.length]);
for (const text of [B, `custom draft ${type}`, `beta ${type}`]) expect(JSON.stringify(env.body ?? null)).not.toContain(text);
}
}
// A caller `mayReadPendingDrafts` does not admit is answered the plain
// read whatever it sends, so `_env` answers it as the plain read does:
// 404, never the draft, and never a 409 naming the disabled holder.
// read whatever it sends: 404, as before.
(rest as any).resolveExecCtx = async () => ({ userId: 'u_member' });
for (const query of draftReads) {
for (const query of [{ state: 'draft' }, { preview: 'draft' }]) {
const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query);
expect([env.status, codeOf(env), query], JSON.stringify(env.body)).toEqual([404, 'RESOURCE_NOT_FOUND', query]);
for (const text of [`gamma draft ${type}`, B]) expect(JSON.stringify(env.body ?? null)).not.toContain(text);
expect(JSON.stringify(env.body ?? null)).not.toContain(B);
}
(rest as any).resolveExecCtx = async () => ({ isSystem: true, userId: 'u1' });
// An enabled package's unhydrated active row: the layered view.
// CONTROL — the holder enabled: every one of these reads refuses naming it, unchanged.
registry.enablePackage(B);
for (const [query] of answers) refusedNaming(await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query), [B], [A]);
});

// [#34261] CONTROL — the guard the draft arms carry: an enabled package's
// stored draft that the plain read does not see. The bare draft reads
// serve it to an admitted builder, so `_env` keeps the refusal for them
// (judged by the draft read itself) and never serves it; the layered
// view withholds it, as the bare layered view does.
it(`${type}: only a disabled holder in the registry, and an enabled package's stored draft — the bare draft reads serve it, \`_env\` draft reads refuse 409 and the layered view answers 404, never that draft`, async () => {
findOneReadsStoredRows = true;
ship(type, 'solo', B);
registry.disablePackage(B);
storedRows = [{ id: 'draft_gamma', type, name: 'solo', state: 'draft', package_id: C,
metadata: JSON.stringify({ name: 'solo', label: `gamma draft ${type}` }) }];
for (const query of [{ state: 'draft' }, { preview: 'draft' }, { package: C, state: 'draft' }]) {
const bare = await drive(ITEM, { type, name: 'solo' }, query);
expect([bare.status, labelOf(bare), query], JSON.stringify(bare.body)).toEqual([200, `gamma draft ${type}`, query]);
}
for (const query of [{ state: 'draft' }, { preview: 'draft' }]) {
const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query);
expect([env.status, codeOf(env), query], JSON.stringify(env.body)).toEqual([409, 'RESOURCE_CONFLICT', query]);
expect(JSON.stringify(env.body ?? null)).not.toContain(`gamma draft ${type}`);
}
for (const [path, params] of [[ITEM, { type, name: 'solo' }], [QUALIFIED, { type, ns: '_env', name: 'solo' }]] as const) {
const layered = await drive(path, params, { layers: 'true' });
expect([layered.status, codeOf(layered), path], JSON.stringify(layered.body)).toEqual([404, 'RESOURCE_NOT_FOUND', path]);
expect(JSON.stringify(layered.body ?? null)).not.toContain(`gamma draft ${type}`);
}
// An enabled package's unhydrated active row: the layered view refuses
// where the plain read serves the row, as plain `_env` does, else 404.
storedRows = [{ id: 'row_gamma', type, name: 'solo', state: 'active', package_id: C,
metadata: JSON.stringify({ name: 'solo', label: `gamma row ${type}` }) }];
await refusedAtEnv({ layers: 'true' });
const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, { layers: 'true' });
expect([env.status, codeOf(env)], JSON.stringify(env.body))
.toEqual(ROW_SERVED_TYPES.includes(type) ? [409, 'RESOURCE_CONFLICT'] : [404, 'RESOURCE_NOT_FOUND']);
expect(JSON.stringify(env.body ?? null)).not.toContain(`gamma row ${type}`);
// CONTROL — an enabled registry holder's own draft is still served to
// an admitted builder at the bare read, and `_env` refuses naming it.
ship(type, 'own', A);
storedRows = [{ id: 'draft_alpha', type, name: 'own', state: 'draft', package_id: A,
metadata: JSON.stringify({ name: 'own', label: `alpha draft ${type}` }) }];
expect(labelOf(await drive(ITEM, { type, name: 'own' }, { state: 'draft' }))).toBe(`alpha draft ${type}`);
refusedNaming(await drive(QUALIFIED, { type, ns: '_env', name: 'own' }, { state: 'draft' }), [A], [B]);
});

it(`${type}: only disabled holders — the layered view serves none of their layers, at any address`, async () => {
Expand Down
76 changes: 51 additions & 25 deletions packages/rest/src/meta-qualified-item-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
* every holder;
* - `_env`: the environment's own item, or `409` naming every served
* holder (`admitEnvironmentQualifier`), read as a caller with no package;
* a name only disabled packages hold answers that read's `404` (#33385).
* a name only disabled packages hold answers that read's `404` (#33385),
* its draft and layered reads included (#34261).
*
* D5's order, as the runtime dispatcher's `/meta` domain reads the same path:
* a sub-resource literal in the last position keeps its route — registered
Expand Down Expand Up @@ -59,7 +60,8 @@ type MetaItemAddress =
interface QualifiedAddressProtocol {
resolveMetaItemAddress?(request: { type: string; segment: string; name: string }): MetaItemAddress | undefined;
admitEnvironmentQualifier?(request: { type: string; name: string; member?: string }): void;
getMetaItem?(request: { type: string; name: string; member?: string }): Promise<{ item?: unknown } | undefined>;
getMetaItem?(request: { type: string; name: string; member?: string; state?: 'draft'; previewDrafts?: true }): Promise<{ item?: unknown } | undefined>;
getMetaItemLayered?: unknown;
}

/**
Expand All @@ -71,6 +73,19 @@ interface QualifiedAddressProtocol {
*/
const DISABLED_HOLDERS_ONLY_REFUSAL = Symbol.for('objectstack.metadata-protocol.disabledHoldersOnlyRefusal');

/**
* [#34261] The switches of the read the item read answers this caller, beyond
* the plain read: an admitted draft switch (`?state=draft` is `state`,
* `?preview=draft` is `previewDrafts`), as the item read hands them to
* `getMetaItem`. The layered view (`?layers=`) adds none: its chain withholds
* every layer whenever the plain read withholds a disabled holder's item
* (`createMetaLayeredAnswer` step 1b).
*/
interface EnvironmentReadSwitches {
readonly state?: 'draft';
readonly previewDrafts?: true;
}

/**
* Admit `_env` for `request`, or throw the protocol's refusal. A refusal
* marked {@link DISABLED_HOLDERS_ONLY_REFUSAL} is admitted when the read
Expand All @@ -79,30 +94,38 @@ const DISABLED_HOLDERS_ONLY_REFUSAL = Symbol.for('objectstack.metadata-protocol.
* serves an item or refuses, a package holds the name through a stored row
* the registry has not read, and the refusal stands.
*
* [#33385, review S1] Only the read that judged the name is admitted this
* way. An admitted draft read (`?state=draft`, `?preview=draft`) or the
* deprecated layered view (`?layers=`) reads other rows than the plain read,
* so for it the marked refusal stands, as on `main` (`readsAsJudged`, asked
* only once the refusal is marked).
* [#34261, ADR-0150 2026-11-26 note] The read judged is the one the caller is
* answered. An admitted draft read (`?state=draft`, `?preview=draft`) is
* admitted when the plain read AND that draft read withhold the name, so it
* answers its own 404 (`404 NO_DRAFT` for `?state=draft`, as the by-name
* draft read answers); an enabled package's stored draft the plain read does
* not see keeps the refusal, and is never served at `_env`. The layered view
* (`?layers=`) is judged by the plain read and answers its own 404.
*/
async function admitEnvironmentAddress(
p: QualifiedAddressProtocol,
request: { type: string; name: string; member?: string },
readsAsJudged: () => Promise<boolean>,
answeredRead: () => Promise<EnvironmentReadSwitches>,
): Promise<void> {
try {
p.admitEnvironmentQualifier?.(request);
} catch (refusal) {
if ((refusal as Record<symbol, unknown> | null)?.[DISABLED_HOLDERS_ONLY_REFUSAL] !== true
|| typeof p.getMetaItem !== 'function'
|| !(await readsAsJudged())) throw refusal;
let withheld: boolean;
try {
withheld = (await p.getMetaItem(request))?.item == null;
} catch {
throw refusal;
}
if (!withheld) throw refusal;
|| typeof p.getMetaItem !== 'function') throw refusal;
const getMetaItem = p.getMetaItem.bind(p);
const withholds = async (switches: EnvironmentReadSwitches): Promise<boolean> => {
try {
return (await getMetaItem({ ...request, ...switches }))?.item == null;
} catch (error) {
// The strict draft read's absence is its `404 NO_DRAFT` (no
// other read throws it); any other failure is no withheld name.
if ((error as { code?: unknown } | null)?.code === 'NO_DRAFT') return true;
return false;
}
};
if (!(await withholds({}))) throw refusal;
const switches = await answeredRead();
if (Object.keys(switches).length > 0 && !(await withholds(switches))) throw refusal;
}
}

Expand Down Expand Up @@ -161,16 +184,19 @@ export function registerMetaQualifiedItemRoute(
query.package = address.packageId;
} else {
const member = typeof query.member === 'string' && query.member !== '' ? query.member : undefined;
// [#33385, review S1] The read the item read answers this caller: the
// plain read unless `?layers=` asks for the layered view, or a
// draft switch is sent by a caller `mayReadPendingDrafts` admits.
const readsAsJudged = async (): Promise<boolean> => {
if (wantsMetaItemLayers(query)) return false;
// [#33385, review S1, #34261] The read the item read answers this
// caller: the layered view when `?layers=` asks for it and the
// protocol has one (the item read answers it first, before
// either draft switch), else the draft switches a caller
// `mayReadPendingDrafts` admits, else the plain read.
const answeredRead = async (): Promise<EnvironmentReadSwitches> => {
if (wantsMetaItemLayers(query) && typeof p.getMetaItemLayered === 'function') return {};
const draft = (value: unknown) => typeof value === 'string' && value.toLowerCase() === 'draft';
if (!draft(query.state) && !draft(query.preview)) return true;
return !mayReadPendingDrafts(await this.resolveExecCtx(environmentId, req).catch(rethrowAuthzStoreUnavailable));
if (!draft(query.state) && !draft(query.preview)) return {};
if (!mayReadPendingDrafts(await this.resolveExecCtx(environmentId, req).catch(rethrowAuthzStoreUnavailable))) return {};
return { ...(draft(query.state) ? { state: 'draft' as const } : {}), ...(draft(query.preview) ? { previewDrafts: true as const } : {}) };
};
await admitEnvironmentAddress(p, { type: params.type, name: params.name, ...(member ? { member } : {}) }, readsAsJudged);
await admitEnvironmentAddress(p, { type: params.type, name: params.name, ...(member ? { member } : {}) }, answeredRead);
}
await readItem(asItemRead(req, params, query), res);
} catch (error: any) {
Expand Down
Loading
Loading