diff --git a/.changeset/32744-rest-candidates-element-check.md b/.changeset/32744-rest-candidates-element-check.md new file mode 100644 index 00000000000..1c79cdb0595 --- /dev/null +++ b/.changeset/32744-rest-candidates-element-check.md @@ -0,0 +1,13 @@ +--- +'@objectstack/types': patch +'@objectstack/rest': patch +--- + +fix(types, rest): a package-scoped refusal's `details.candidates` is answered only when every element is a holder + +Clause-②: no +Metadata-protocol: none + +`packageScopedRefusalCandidates` (`@objectstack/types`), the one recogniser every door reads for a package-scoped refusal's `details.candidates`, answered the refusal's list as `readonly unknown[]` without looking at its elements, and the rest door cast that to core's `PackageScopedHolder[]`. The recogniser now checks each element against the four holder kinds (`package` with a string `packageId`, `environment`, `platform`, `residual` with a string `ownerId`) and answers the list typed as those holders, so the rest door assigns it without a cast. Every holder core's `PackageScopedNameRefusedError` carries passes, so every answer a framework producer can cause is unchanged. + +One corner moves, for a refusal no framework producer throws: a `409 RESOURCE_CONFLICT` of the refusal's shape whose `refusal.candidates` holds an element that is not a holder. FROM `details.candidates` echoing the list as thrown TO no `details.candidates` member, the answer the recogniser already gave a `candidates` that is not an array. It moves on every door that reads the recogniser alike (the `/data` doors, a batch row's error, the `/meta` reads, the resolver's doors), so they keep agreeing. Status, `code` and the sentence are unchanged. diff --git a/packages/rest/src/data-package-scoped-refusal-candidates.test.ts b/packages/rest/src/data-package-scoped-refusal-candidates.test.ts index 1441e1945e2..4af901e79bd 100644 --- a/packages/rest/src/data-package-scoped-refusal-candidates.test.ts +++ b/packages/rest/src/data-package-scoped-refusal-candidates.test.ts @@ -29,7 +29,8 @@ * * Not measured here: the cross-object `POST /batch` (this harness has no * transactional batch and answers `501`); a throw there leaves through the - * same exit as `createMany`. + * same exit as `createMany`, and `rest-batch-endpoint.test.ts` pins its + * `details.candidates` over a transactional engine double. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; diff --git a/packages/rest/src/error-response.ts b/packages/rest/src/error-response.ts index 0a65e26b671..0d931a3463b 100644 --- a/packages/rest/src/error-response.ts +++ b/packages/rest/src/error-response.ts @@ -281,9 +281,14 @@ export interface RouteErrorOptions { * does an error that crossed a second copy of `@objectstack/core` — the read * `resolveThrownHttpError`, the `/data` classification and the batch row error * make, so the doors cannot recognise two different sets. + * + * [#32744] The recogniser checks each element of the list against the four + * holder kinds and answers it typed as holders, so this door assigns it to + * core's `PackageScopedHolder` without a cast: the compiler checks that the + * recogniser's holder shape is assignable to core's. */ function packageScopedRefusalCandidates(error: unknown): readonly PackageScopedHolder[] | undefined { - return sharedPackageScopedRefusalCandidates(error) as readonly PackageScopedHolder[] | undefined; + return sharedPackageScopedRefusalCandidates(error); } function resolveErrorResponse(error: any, object?: string, options?: RouteErrorOptions): { status: number; body: Record } { diff --git a/packages/rest/src/package-door-declared-code.test.ts b/packages/rest/src/package-door-declared-code.test.ts index 0c00bccbee5..3c948a21a48 100644 --- a/packages/rest/src/package-door-declared-code.test.ts +++ b/packages/rest/src/package-door-declared-code.test.ts @@ -209,6 +209,7 @@ import { demotedDeclaredCode, INTERNAL_ERROR_MESSAGE, } from '@objectstack/types'; +import { PackageScopedNameRefusedError, packageScopedRefusalMessage } from '@objectstack/core'; import { registerPackageRoutes } from './package-routes.js'; const PKGS = '/api/v1/packages'; @@ -705,3 +706,45 @@ describe('[#12405] the wire `declaredCode` IS the shared rule, not a second copy expect(answers.filter((a) => a === undefined).length).toBeGreaterThan(2); }); }); + +// --------------------------------------------------------------------------- +// 6. A census door: a package-scoped refusal names its candidates +// --------------------------------------------------------------------------- + +/** + * [#32744, ADR-0150 D5] This door forwards the resolver's `details`, so a + * package-scoped refusal (core's `PackageScopedNameRefusedError`) answers + * `details.candidates` here, beside the status and code it answered before. + * Pinned at the one production seam (**Seam census** above). + */ +describe('[#32744] a package-scoped refusal names its candidates at this door', () => { + const CANDIDATES = [ + { kind: 'package' as const, packageId: 'com.acme.crm' }, + { kind: 'package' as const, packageId: 'com.acme.sales' }, + ]; + const BASE = { + status: 'refused' as const, + reason: 'ambiguous-in-environment' as const, + type: 'permission' as const, + name: 'sales_rep', + callerPackageId: null, + candidates: CANDIDATES, + }; + const REFUSAL = { ...BASE, message: packageScopedRefusalMessage(BASE) }; + + it('POST /packages/publish: 409 RESOURCE_CONFLICT with details.candidates', async () => { + const publish = vi.fn(async () => { throw new PackageScopedNameRefusedError(REFUSAL); }); + const captured = await drive( + mount({ publish }), + 'POST', + `${PKGS}/publish`, + { body: { manifest: MANIFEST, metadata: { author: 'acme' } } }, + ); + + expect(publish.mock.calls.length, 'the throwing seam was never called').toBe(1); + const error = expectDeclaredEnvelope(captured); + expect(captured.status).toBe(409); + expect(error.code).toBe('RESOURCE_CONFLICT'); + expect(error.details).toEqual({ candidates: CANDIDATES }); + }); +}); diff --git a/packages/rest/src/rest-batch-endpoint.test.ts b/packages/rest/src/rest-batch-endpoint.test.ts index 8561b4021a8..f492bfd6317 100644 --- a/packages/rest/src/rest-batch-endpoint.test.ts +++ b/packages/rest/src/rest-batch-endpoint.test.ts @@ -8,6 +8,10 @@ import { describe, it, expect, vi } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; +import { PackageScopedNameRefusedError, packageScopedRefusalMessage } from '@objectstack/core'; +// Paid during collection, not inside a case's clocked window: the route +// source reaches `@objectstack/objectql` through a dynamic import. +import '@objectstack/objectql'; import { RestServer } from './rest-server'; // ── helpers ────────────────────────────────────────────────────────────────── @@ -403,3 +407,99 @@ describe('POST {basePath}/batch — cross-object transactional batch', () => { expect(res.body.code).toBe('VALIDATION_FAILED'); }); }); + +// ── a package-scoped refusal's candidates (ADR-0150 D5) ───────────────────── + +/** + * [#32744] The cross-object batch answers a package-scoped refusal (core's + * `PackageScopedNameRefusedError`, or an error of its shape that crossed a + * second copy of `@objectstack/core`) as every `/data` whole-request door + * does: `409 RESOURCE_CONFLICT`, its sentence and code, plus + * `details.candidates`. The member is answered only when every element of the + * refusal's list is a holder of one of core's four kinds. + */ +describe('POST {basePath}/batch — a package-scoped refusal names its candidates', () => { + const CANDIDATES = [ + { kind: 'package' as const, packageId: 'com.acme.crm' }, + { kind: 'package' as const, packageId: 'com.acme.sales' }, + ]; + const BASE = { + status: 'refused' as const, + reason: 'ambiguous-in-environment' as const, + type: 'permission' as const, + name: 'sales_rep', + callerPackageId: null, + candidates: CANDIDATES, + }; + const REFUSAL = { ...BASE, message: packageScopedRefusalMessage(BASE) }; + + /** A refusal of the class's shape, carrying `candidates` as given. */ + const shaped = (candidates: unknown): Error => Object.assign(new Error(REFUSAL.message), { + code: 'RESOURCE_CONFLICT', + status: 409, + refusal: { ...REFUSAL, candidates }, + }); + + /** Drive one create or update op whose engine call throws `error`. */ + async function refuse(error: unknown, action: 'create' | 'update' = 'create') { + const fail = vi.fn(async () => { throw error; }); + const ql = makeQl(action === 'create' ? { insert: fail } : { update: fail }); + const { route } = buildServer({ ql }); + const op = action === 'create' + ? { object: 'account', action: 'create', data: { name: 'Acme' } } + : { object: 'account', action: 'update', id: 'a1', data: { name: 'Acme' } }; + const res = await post(route, { operations: [op] }); + expect(fail, 'the throwing engine call was never reached').toHaveBeenCalledTimes(1); + return res; + } + + it('the class, thrown by a create op: 409 RESOURCE_CONFLICT with details.candidates', async () => { + const res = await refuse(new PackageScopedNameRefusedError(REFUSAL)); + expect(res.statusCode).toBe(409); + expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT', details: { candidates: CANDIDATES } }); + }); + + it('the class, thrown by an update op: the same answer', async () => { + const res = await refuse(new PackageScopedNameRefusedError(REFUSAL), 'update'); + expect(res.statusCode).toBe(409); + expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT', details: { candidates: CANDIDATES } }); + }); + + it('a plain error of the class\'s shape: the same answer', async () => { + const res = await refuse(shaped(CANDIDATES)); + expect(res.statusCode).toBe(409); + expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT', details: { candidates: CANDIDATES } }); + }); + + it('a holder of each of the four kinds is answered as it was thrown', async () => { + const every = [ + { kind: 'package', packageId: 'com.acme.crm' }, + { kind: 'environment' }, + { kind: 'platform' }, + { kind: 'residual', ownerId: 'com.acme.stack' }, + ]; + const res = await refuse(shaped(every)); + expect(res.statusCode).toBe(409); + expect(res.body.details).toEqual({ candidates: every }); + }); + + for (const [name, candidates] of [ + ['a package holder with no packageId', [{ kind: 'package' }]], + ['a bare string', ['com.acme.crm']], + ['a kind that is no package-scoped holder', [{ kind: 'built-in' }]], + ['one good holder beside a null', [{ kind: 'package', packageId: 'com.acme.crm' }, null]], + ['a residual holder with a numeric ownerId', [{ kind: 'residual', ownerId: 7 }]], + ] as const) { + it(`a list holding ${name}: 409 RESOURCE_CONFLICT with no details`, async () => { + const res = await refuse(shaped(candidates)); + expect(res.statusCode).toBe(409); + expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT' }); + }); + } + + it('CONTROL: a RESOURCE_CONFLICT thrown with no refusal carries no details', async () => { + const res = await refuse(Object.assign(new Error('The record is in conflict.'), { code: 'RESOURCE_CONFLICT', status: 409 })); + expect(res.statusCode).toBe(409); + expect(res.body).toEqual({ error: 'The record is in conflict.', code: 'RESOURCE_CONFLICT' }); + }); +}); diff --git a/packages/types/src/thrown-http-error.test.ts b/packages/types/src/thrown-http-error.test.ts index aea6447bbd4..3fcb5b0c368 100644 --- a/packages/types/src/thrown-http-error.test.ts +++ b/packages/types/src/thrown-http-error.test.ts @@ -166,6 +166,39 @@ describe('[#32250] resolveThrownHttpError carries a package-scoped refusal\'s ca } }); + it('[#32744] a holder of each of the four kinds passes the element check', () => { + const every = [ + { kind: 'package', packageId: 'com.acme.crm' }, + { kind: 'environment' }, + { kind: 'platform' }, + { kind: 'residual', ownerId: 'com.acme.stack' }, + ]; + const thrown = () => Object.assign(shaped(), { refusal: { ...REFUSAL, candidates: every } }); + expect(packageScopedRefusalCandidates(thrown())).toEqual(every); + expect(resolveThrownHttpError(thrown()).details).toEqual({ candidates: every }); + expect(mapDataError(thrown(), 'acct').body.details).toEqual({ candidates: every }); + }); + + it('[#32744] a list with any element that is not a holder carries none, on all three exits alike', () => { + const lists: Array<[string, unknown[]]> = [ + ['a package holder with no packageId', [{ kind: 'package' }]], + ['a bare string', ['com.acme.crm']], + ['a kind that is no package-scoped holder', [{ kind: 'built-in' }]], + ['one good holder beside a null', [{ kind: 'package', packageId: 'com.acme.crm' }, null]], + ['a residual holder with a numeric ownerId', [{ kind: 'residual', ownerId: 7 }]], + ]; + for (const [name, candidates] of lists) { + const thrown = () => Object.assign(shaped(), { refusal: { ...REFUSAL, candidates } }); + expect(packageScopedRefusalCandidates(thrown()), name).toBeUndefined(); + expect(resolveThrownHttpError(thrown()).details, name).toBeUndefined(); + expect(thrownAnswerOf(thrown(), 500).details, name).toBeUndefined(); + expect(mapDataError(thrown(), 'acct').body.details, name).toBeUndefined(); + // The refusal itself answers as before: only the member is withheld. + expect(resolveThrownHttpError(thrown()).status, name).toBe(409); + expect(resolveThrownHttpError(thrown()).code, name).toBe('RESOURCE_CONFLICT'); + } + }); + it('CONTROL: a refusal\'s candidates sit beside the context the resolver already carried', () => { const thrown = Object.assign(shaped(), { issues: [{ path: ['x'], message: 'y' }] }); expect(resolveThrownHttpError(thrown).details).toEqual({ issues: [{ path: ['x'], message: 'y' }], candidates: CANDIDATES }); diff --git a/packages/types/src/thrown-http-error.ts b/packages/types/src/thrown-http-error.ts index c9bbfb5fe47..cdde14b75cf 100644 --- a/packages/types/src/thrown-http-error.ts +++ b/packages/types/src/thrown-http-error.ts @@ -222,8 +222,14 @@ export interface ThrownHttpError { * error that crossed a second copy of `@objectstack/core`. Read here, by * {@link resolveThrownHttpError}, by the `/data` classification and by the * batch row error, so no door carries a second recogniser. + * + * [#32744] Each element of the list is checked against the four kinds of + * core's `PackageScopedHolder` ({@link isPackageScopedRefusalHolder}); a list + * with any element that is not a holder is answered as no list, as a + * `candidates` that is not an array is. Every holder core constructs passes, + * so the answer is typed as holders and no door casts it. */ -export function packageScopedRefusalCandidates(error: unknown): readonly unknown[] | undefined { +export function packageScopedRefusalCandidates(error: unknown): readonly PackageScopedRefusalHolder[] | undefined { if (typeof error !== 'object' || error === null) return undefined; const e = error as { code?: unknown; status?: unknown; statusCode?: unknown; refusal?: { status?: unknown; candidates?: unknown } | null }; if (e.code !== 'RESOURCE_CONFLICT') return undefined; @@ -237,7 +243,36 @@ export function packageScopedRefusalCandidates(error: unknown): readonly unknown if (declared === undefined || !(declared >= 400 && declared < 500)) return undefined; const refusal = e.refusal; if (typeof refusal !== 'object' || refusal === null || refusal.status !== 'refused') return undefined; - return Array.isArray(refusal.candidates) ? refusal.candidates : undefined; + const candidates: unknown = refusal.candidates; + if (!Array.isArray(candidates)) return undefined; + return candidates.every(isPackageScopedRefusalHolder) ? candidates : undefined; +} + +/** + * One holder a package-scoped refusal names: core's `PackageScopedHolder`, + * spelled by shape because this package cannot import core. + */ +type PackageScopedRefusalHolder = + | { readonly kind: 'package'; readonly packageId: string } + | { readonly kind: 'environment' } + | { readonly kind: 'platform' } + | { readonly kind: 'residual'; readonly ownerId: string }; + +/** + * Whether one element of a refusal's `candidates` is a holder of one of the + * four kinds: `package` (with a string `packageId`), `environment`, + * `platform` and `residual` (with a string `ownerId`). + */ +function isPackageScopedRefusalHolder(candidate: unknown): candidate is PackageScopedRefusalHolder { + if (typeof candidate !== 'object' || candidate === null) return false; + const holder = candidate as { kind?: unknown; packageId?: unknown; ownerId?: unknown }; + switch (holder.kind) { + case 'package': return typeof holder.packageId === 'string'; + case 'residual': return typeof holder.ownerId === 'string'; + case 'environment': + case 'platform': return true; + default: return false; + } } /**