Skip to content
8 changes: 8 additions & 0 deletions .changeset/38542-handle-route-error-vary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@objectstack/rest': patch
---

Clause-②: no
Metadata-protocol: none

A refusal carrying a `userMessage` now says it varies by `Accept-Language` on every REST route that answers its errors through the shared route error exit: the metadata reads and writes, the batch and bulk writes (`/batch`, `createMany`, `updateMany`, `deleteMany`), the data actions (clone, import, export), the approval, ownership-change and UI routes. The status, code and body are unchanged; the header is added in the multi-value form the hosts append, so a `Vary` another layer sets keeps its tokens. Before, a shared cache in front of these routes could serve one caller's localized sentence (the localized `404 RECORD_NOT_FOUND`, a hook refusal's own message) to a caller asking in another language. A refusal with no `userMessage` gets no `Vary` from this exit.
5 changes: 5 additions & 0 deletions packages/rest/src/analytics-fault-user-message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@

import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
import { INTERNAL_ERROR_MESSAGE } from '@objectstack/types';
// The first load of the engine is paid at collection, not inside a test's clock:
// the server under test reaches it through dynamic imports.
import '@objectstack/objectql';
import { RestServer } from './rest-server';
import { handleRouteError } from './error-response.js';

Expand Down Expand Up @@ -132,6 +135,8 @@ function mockRes() {
const res: any = { statusCode: 200, body: undefined };
res.status = vi.fn((c: number) => { res.statusCode = c; return res; });
res.json = vi.fn((b: any) => { res.body = b; return res; });
// [#38542] The shared exit says `Vary` on a body carrying a `userMessage`.
res.header = vi.fn(() => res);
res.end = vi.fn(() => res);
return res;
}
Expand Down
5 changes: 4 additions & 1 deletion packages/rest/src/change-owner-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,12 @@ function sendBodyRefusal(res: any, refusal: BodyRefusal): void {
* `handleRouteError` through a sink, so it logs exactly as that door does.
*/
function classifiedAnswer(err: unknown, object: string): { status: number; body: Record<string, unknown> } {
const sink: { httpStatus: number; body?: Record<string, unknown>; status(httpStatus: number): typeof sink; json(body: Record<string, unknown>): typeof sink } = {
// [#38542] `header()` too: the door says `Vary: Accept-Language` on a body
// carrying a `userMessage`, and a row's answer has no response to vary.
const sink: { httpStatus: number; body?: Record<string, unknown>; status(httpStatus: number): typeof sink; header(name: string, value: string | string[]): typeof sink; json(body: Record<string, unknown>): typeof sink } = {
httpStatus: 500,
status(httpStatus) { sink.httpStatus = httpStatus; return sink; },
header() { return sink; },
json(body) { sink.body = body; return sink; },
};
handleRouteError(sink, err, object);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ function through(send: (res: any, error: any, object?: string) => void) {
let body: Record<string, unknown> = {};
const res = {
status(s: number) { status = s; return this; },
// [#38542] The shared exit says `Vary` on a body carrying a `userMessage`.
header() { return this; },
json(b: Record<string, unknown>) { body = b; return this; },
};
send(res, error, object);
Expand Down
16 changes: 15 additions & 1 deletion packages/rest/src/error-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
*/

import {
answerVariesByLanguage,
LOCALIZED_ANSWER_VARY,
declaredRefusalMessage,
INTERNAL_ERROR_MESSAGE,
boundedDeclaredRefusalMessage,
Expand Down Expand Up @@ -1176,13 +1178,25 @@ export function thrownAnswerIsBareNotFound(error: any, object?: string): boolean

/**
* The single door a route catch block should use: resolve the response once,
* log it only if it is a real fault, then send it. Wire behaviour is identical
* log it only if it is a real fault, then send it. The body is identical
* to a bare `sendThrownError(res, error, object)` — this only decides whether the log
* line is printed.
*
* [#38542] An answer whose body carries a `userMessage` says it varies by
* `Accept-Language`, whatever its status, as the `/data` routes' exit does
* (`crud-routes.ts`'s `sendRefusal`). Every arm of {@link resolveErrorResponse}
* can carry one — each ends in `mapDataError` or `withDeclaredUserMessage`,
* which ride a producer-declared `userMessage` onto any body — so the question
* is asked of the body here, once, for every caller (the metadata, batch,
* approval and data-action routes). The token goes on in the contract's
* multi-value form, which the hosts APPEND, so a `Vary` another layer adds
* keeps its tokens. The rule and its reasons are `answerVariesByLanguage`'s
* (`@objectstack/types`).
*/
export function handleRouteError(res: any, error: any, object?: string, options?: RouteErrorOptions): void {
const resolved = resolveErrorResponse(error, object, options);
logUnexpectedRouteError(error, resolved);
if (answerVariesByLanguage(resolved.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]);
res.status(resolved.status).json(resolved.body);
}

Expand Down
5 changes: 5 additions & 0 deletions packages/rest/src/rest-user-facing-refusal-marking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@

import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
import { INTERNAL_ERROR_MESSAGE } from '@objectstack/types';
// The first load of the engine is paid at collection, not inside a test's clock:
// the server under test reaches it through dynamic imports.
import '@objectstack/objectql';
import { mapDataError, RestServer } from './rest-server.js';
import { handleRouteError } from './error-response.js';

Expand Down Expand Up @@ -186,6 +189,8 @@ describe('[#9934] the handleRouteError passthrough carries the marking too', ()
const res: any = { statusCode: 200, body: undefined };
res.status = vi.fn((c: number) => { res.statusCode = c; return res; });
res.json = vi.fn((b: any) => { res.body = b; return res; });
// [#38542] The shared exit says `Vary` on a body carrying a `userMessage`.
res.header = vi.fn(() => res);
return res;
}

Expand Down
248 changes: 248 additions & 0 deletions packages/rest/src/route-error-vary-38542.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#38542] `handleRouteError`, the shared error exit of the metadata, batch,
* approval and data-action routes, says its answer varies by `Accept-Language`
* when the body carries a `userMessage`, as the `/data` routes' exit does
* (#37828, #38316) and the four catches #38507 fixed.
*
* Read on the base (`688fddbd`): it sent `res.status(resolved.status).json(
* resolved.body)` with no `Vary`. Every arm of `resolveErrorResponse` ends in
* `mapDataError` or `withDeclaredUserMessage`, both of which ride a
* producer-declared `userMessage` onto the body, so any caller can answer one.
* The rule is `answerVariesByLanguage`'s (`@objectstack/types`).
*
* One route per caller family, each driven through the real route and the
* real exit:
* - a data action, `POST /data/:object/:id/clone`: the no-row answer,
* `recordNotFoundError` (`@objectstack/core`), whose `userMessage` is
* rendered in the caller's language;
* - a metadata read, `GET /meta/:type/:name/references`: a refusal with its
* own `userMessage` thrown by the protocol;
* - a batch write, `POST /data/:object/batch`: a hook refusal with its own
* `userMessage`, relayed by the protocol's batch.
* Each CONTROL is the same refusal with no `userMessage`, which gets no `Vary`.
*
* Two callers read the exit's answer through a sink rather than a response, to
* word a refused row of a bulk hand-over: the assigned-work transfer
* (`user-work-routes.ts`) and the bulk Change Owner (`change-owner-routes.ts`).
* The exit stays strict to the response contract, so each sink answers
* `header()`; the last two cases pin that a row refusal carrying a
* `userMessage` is still listed as a failed row, not turned into a 500.
*/

import { describe, it, expect, vi } from 'vitest';
import { LOCALIZED_ANSWER_VARY } from '@objectstack/types';
import { recordNotFoundError } from '@objectstack/core';
import { OWNER_FIELD_DEF } from '@objectstack/spec/data';
import { assertEngineUpdateDispatch } from '@objectstack/metadata-core';
// The first load of the engine is paid at collection, not inside a test's clock:
// the server under test reaches it through dynamic imports.
import '@objectstack/objectql';
import { RestServer } from './rest-server';

const OBJECT = 'ticket_38542';
const ID = 'r_38542';
const CTX = { userId: 'usr_38542_member', positions: [], permissions: [], posture: 'MEMBER', locale: 'fr-FR' };
const SENTENCE = 'Ce créneau est déjà réservé.';

function createMockServer() {
const noop = () => {};
return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} };
}

function makeHeaderRes() {
const res: any = {
_headers: [] as Array<[string, string | string[]]>,
write: () => true, end: () => {}, send: () => res,
header: (name: string, value: string | string[]) => { res._headers.push([name, value]); return res; },
status: (code: number) => { res._status = code; return res; },
json: (body: any) => { res._json = body; return res; },
};
return res;
}

const varyHeaders = (res: any) => res._headers.filter(([name]: [string]) => name.toLowerCase() === 'vary');

/** What a hook refusal declaring its own sentence throws. */
const refusalWithSentence = () =>
Object.assign(new Error('The slot is already booked.'), { status: 409, code: 'RESOURCE_CONFLICT', userMessage: SENTENCE });
/** The same refusal with no sentence for the end user. */
const refusalWithoutSentence = () =>
Object.assign(new Error('The slot is already booked.'), { status: 409, code: 'RESOURCE_CONFLICT' });

function routeOf(rest: RestServer, method: string, path: string) {
const route = rest.getRoutes().find((r: any) => r.method === method && r.path === path);
expect(route, `${method} ${path}`).toBeDefined();
return route!;
}

/** A server over a stub protocol, past the auth and exposure gates. */
function stubServer(protocol: Record<string, unknown>) {
const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any);
(rest as any).resolveExecCtx = async () => CTX;
(rest as any).enforceApiAccess = async () => false;
rest.registerRoutes();
return rest;
}

describe('[#38542] a data action: POST /data/:object/:id/clone', () => {
const PATH = '/api/v1/data/:object/:id/clone';
const req = { params: { object: OBJECT, id: ID }, query: {}, headers: {}, body: {} };

it('no such row: the localized 404 RECORD_NOT_FOUND says Vary: Accept-Language', async () => {
const calls: string[] = [];
const rest = stubServer({ cloneData: async () => { calls.push('cloneData'); throw recordNotFoundError(OBJECT, ID, CTX as any); } });
const res = makeHeaderRes();
await routeOf(rest, 'POST', PATH).handler(req as any, res);
expect(calls).toEqual(['cloneData']);
expect(res._status, JSON.stringify(res._json)).toBe(404);
expect(res._json.code).toBe('RECORD_NOT_FOUND');
expect(res._json.userMessage).toEqual(expect.any(String));
// The multi-value form the hosts append, never a set that would drop CORS's `Origin`.
expect(varyHeaders(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
});

it('CONTROL: a refusal with no userMessage gets no Vary from this exit', async () => {
const rest = stubServer({ cloneData: async () => { throw refusalWithoutSentence(); } });
const res = makeHeaderRes();
await routeOf(rest, 'POST', PATH).handler(req as any, res);
expect(res._status, JSON.stringify(res._json)).toBe(409);
expect(res._json.code).toBe('RESOURCE_CONFLICT');
expect(res._json.userMessage).toBeUndefined();
expect(varyHeaders(res)).toEqual([]);
});
});

describe('[#38542] a metadata read: GET /meta/:type/:name/references', () => {
const PATH = '/api/v1/meta/:type/:name/references';
const req = { params: { type: 'object', name: OBJECT }, query: {}, headers: {} };

async function read(thrown: () => Error) {
const calls: string[] = [];
const rest = stubServer({ findReferencesToMeta: async () => { calls.push('findReferencesToMeta'); throw thrown(); } });
const res = makeHeaderRes();
await routeOf(rest, 'GET', PATH).handler(req as any, res);
// The refusal came from the read, not from a gate in front of it.
expect(calls).toEqual(['findReferencesToMeta']);
return res;
}

it('a refusal with its own userMessage says Vary: Accept-Language', async () => {
const res = await read(refusalWithSentence);
expect(res._status, JSON.stringify(res._json)).toBe(409);
expect(res._json.code).toBe('RESOURCE_CONFLICT');
expect(res._json.userMessage).toBe(SENTENCE);
expect(varyHeaders(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
});

it('CONTROL: the same refusal with no userMessage gets no Vary from this exit', async () => {
const res = await read(refusalWithoutSentence);
expect(res._status, JSON.stringify(res._json)).toBe(409);
expect(res._json.userMessage).toBeUndefined();
expect(varyHeaders(res)).toEqual([]);
});
});

describe('[#38542] a batch write: POST /data/:object/batch', () => {
const PATH = '/api/v1/data/:object/batch';
const req = {
params: { object: OBJECT }, query: {}, headers: {},
body: { operation: 'update', records: [{ id: ID, data: { name: 'x' } }] },
};

async function write(thrown: () => Error) {
const calls: string[] = [];
const rest = stubServer({ batchData: async () => { calls.push('batchData'); throw thrown(); } });
const res = makeHeaderRes();
await routeOf(rest, 'POST', PATH).handler(req as any, res);
expect(calls).toEqual(['batchData']);
return res;
}

it('a hook refusal with its own userMessage says Vary: Accept-Language', async () => {
const res = await write(refusalWithSentence);
expect(res._status, JSON.stringify(res._json)).toBe(409);
expect(res._json.code).toBe('RESOURCE_CONFLICT');
expect(res._json.userMessage).toBe(SENTENCE);
expect(varyHeaders(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
});

it('CONTROL: the same refusal with no userMessage gets no Vary from this exit', async () => {
const res = await write(refusalWithoutSentence);
expect(res._status, JSON.stringify(res._json)).toBe(409);
expect(res._json.userMessage).toBeUndefined();
expect(varyHeaders(res)).toEqual([]);
});
});

/** A server over a stub data engine, for the two hand-over doors. */
function engineServer(engine: unknown, caller: unknown) {
const rest = new RestServer(
createMockServer() as any,
{ getDiscovery: async () => ({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: async () => [], getMetaItems: async () => [] } as any,
{ api: { requireAuth: false } } as any,
undefined, undefined, undefined, undefined,
async () => engine,
);
(rest as any).resolveExecCtx = async () => caller;
(rest as any).kernelServiceProvider = async () => undefined;
rest.registerRoutes();
return rest;
}

describe('[#38542] the sinks that word a refused row through the exit', () => {
it('assigned-work transfer: a row refusal with its own userMessage is listed as a failed row, not a 500', async () => {
const rows = [{ id: 't1', owner_id: 'u_gone' }];
const users = [{ id: 'u_gone', banned: true }, { id: 'u_next', banned: false }];
const engine = {
getConfigs: () => ({ ticket: { name: 'ticket', fields: { owner_id: { type: 'lookup', reference: 'sys_user' } } } }),
count: async () => rows.length,
find: async (o: string, q: any) => {
const matched = (o === 'sys_user' ? users : rows).filter((r: any) => Object.entries(q.where ?? {}).every(([k, v]) => {
if (k.startsWith('$')) throw new Error(`fake engine: the ${k} combinator is not implemented`);
return r[k] === v;
}));
return typeof q?.limit === 'number' ? matched.slice(0, q.limit) : matched;
},
update: vi.fn(async (_object: string, data: any, options: any) => { assertEngineUpdateDispatch(data, options); throw refusalWithSentence(); }),
};
const rest = engineServer(engine, { userId: 'u_admin', tenantId: 'org_1' });
const res = makeHeaderRes();
await routeOf(rest, 'POST', '/api/v1/security/users/:id/assigned-work/transfer')
.handler({ method: 'POST', params: { id: 'u_gone' }, headers: {}, query: {}, body: { toUserId: 'u_next' } } as any, res);
expect(engine.update).toHaveBeenCalledTimes(1);
expect(res._status ?? 200, JSON.stringify(res._json)).toBe(200);
expect(res._json.data).toMatchObject({ updated: 0, failed: 1 });
expect(res._json.data.objects[0].failures).toEqual([{ id: 't1', code: 'RESOURCE_CONFLICT', message: 'The slot is already booked.' }]);
});

it('bulk Change Owner: a row refusal with its own userMessage is listed as a failed row, not a 500', async () => {
const schemas = { lead: { name: 'lead', label: 'Lead', sharingModel: 'private', fields: { owner_id: OWNER_FIELD_DEF } } };
const rows = [{ id: 'l1', owner_id: 'u_a' }];
const users = [{ id: 'u_next', banned: false }];
const tableOf = (o: string) => (o === 'sys_user' ? users : rows);
const engine = {
getSchema: (name: string) => (schemas as any)[name],
registry: { isObjectPackageDisabled: () => false },
getConfigs: () => schemas,
count: async (o: string) => tableOf(o).length,
find: async (o: string, q: any) => {
const matched = tableOf(o).filter((r: any) => Object.entries(q.where ?? {}).every(([k, v]) => {
if (k.startsWith('$')) throw new Error(`fake engine: the ${k} combinator is not implemented`);
return v !== null && typeof v === 'object' && Array.isArray((v as any).$in) ? (v as any).$in.includes(r[k]) : r[k] === v;
}));
return typeof q?.limit === 'number' ? matched.slice(0, q.limit) : matched;
},
update: vi.fn(async (_object: string, data: any, options: any) => { assertEngineUpdateDispatch(data, options); throw refusalWithSentence(); }),
};
const rest = engineServer(engine, { userId: 'u_manager', tenantId: 'org_1' });
const res = makeHeaderRes();
await routeOf(rest, 'POST', '/api/v1/data/:object/change-owner')
.handler({ method: 'POST', params: { object: 'lead' }, headers: {}, query: {}, body: { ids: ['l1'], ownerId: 'u_next' } } as any, res);
expect(engine.update).toHaveBeenCalledTimes(1);
expect(res._status ?? 200, JSON.stringify(res._json)).toBe(200);
expect(res._json.data).toMatchObject({ updated: 0, failed: 1 });
expect(res._json.data.failures.map((f: any) => [f.id, f.code])).toEqual([['l1', 'RESOURCE_CONFLICT']]);
});
});
5 changes: 4 additions & 1 deletion packages/rest/src/user-work-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,11 @@ const TRANSFER_BODY_KEYS = new Set(['toUserId', 'objects']);
* withheld and is logged, and nothing here is a second rule.
*/
function rowFailureAnswer(err: unknown, object: string): { code: string; message: string } {
const sink: { body?: Record<string, unknown>; status(code: number): typeof sink; json(body: Record<string, unknown>): typeof sink } = {
// [#38542] `header()` too: the door says `Vary: Accept-Language` on a body
// carrying a `userMessage`, and a row's answer has no response to vary.
const sink: { body?: Record<string, unknown>; status(code: number): typeof sink; header(name: string, value: string | string[]): typeof sink; json(body: Record<string, unknown>): typeof sink } = {
status() { return sink; },
header() { return sink; },
json(body) { sink.body = body; return sink; },
};
handleRouteError(sink, err, object);
Expand Down
Loading
Loading