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
10 changes: 10 additions & 0 deletions .changeset/38567-send-error-vary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/types': patch
---

Clause-②: yes (widening)
Metadata-protocol: none

`sendError` now says `Vary: Accept-Language` when the nested error envelope it writes carries a `userMessage`, so every REST door that re-sends a classified, localized refusal through it says its answer varies by language: Change Owner (single and bulk, including the missing record's localized `404 RECORD_NOT_FOUND`), the recycle bin, the packages routes and the analytics batch (whose house-envelope wrapper now forwards headers to the response). Before, a shared cache in front of these doors could serve one caller's localized sentence to a caller asking in another language. 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. A refusal with no `userMessage` gets no `Vary`.

`EnvelopeResponse` gains an optional `header(name, value)` member, the shape `IHttpResponse.header` already has; a response object without it still satisfies the interface and simply gets no header.
4 changes: 3 additions & 1 deletion packages/rest/src/analytics-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,10 +317,12 @@ function writtenAnswer(gate: (recorder: { status(code: number): any; json(body:
* written. This is what makes the batch a house-envelope door end to end
* while it asks those gates exactly as the single door does.
*/
function houseEnvelopeResponse(wire: any): { status(code: number): any; json(body: unknown): any } {
function houseEnvelopeResponse(wire: any): { status(code: number): any; header(name: string, value: string | string[]): any; json(body: unknown): any } {
let status = 200;
const res = {
status(code: number) { status = code; return res; },
// [#38567] A header a gate sets (`sendError`'s `Vary` on a `userMessage`) reaches the wire.
header(name: string, value: string | string[]) { wire.header(name, value); return res; },
json(body: unknown) {
if (status >= 400 && !(isRecord(body) && body.success === false)) sendWholeBatchRefusal(wire, { status, body });
else wire.status(status).json(body);
Expand Down
102 changes: 102 additions & 0 deletions packages/rest/src/change-owner-vary-38567.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#38567] Change Owner re-sends the `/data` door's classified answer through
* `sendError` (`@objectstack/types`), not through `handleRouteError`, so the
* `Vary` #38542 put on that exit never reached it. `sendError`'s envelope write
* now asks `answerVariesByLanguage` of the body it writes; this pins it through
* the real route handler: the missing record's localized `404 RECORD_NOT_FOUND`
* says `Vary: Accept-Language`, and a refusal with no `userMessage` does not.
*/

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.
import '@objectstack/objectql';
import { RestServer } from './rest-server';

const PATH = '/api/v1/data/:object/:id/change-owner';
const CALLER = { userId: 'u_manager', tenantId: 'org_1', locale: 'fr-FR' };
const SCHEMAS = { lead: { name: 'lead', label: 'Lead', sharingModel: 'private', fields: { owner_id: OWNER_FIELD_DEF } } };

function engineOf(refusal?: () => unknown) {
const rows = [{ id: 'l1', owner_id: 'u_a' }];
const users = [{ id: 'u_next', banned: false }];
const tableOf = (o: string) => (o === 'sys_user' ? users : rows);
return {
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 r[k] === v;
}));
return typeof q?.limit === 'number' ? matched.slice(0, q.limit) : matched;
},
update: vi.fn(async (o: string, data: any, opts: any) => {
assertEngineUpdateDispatch(data, opts);
if (refusal) throw refusal();
throw recordNotFoundError(o, String(opts.where.id), opts.context);
}),
};
}

function handlerOf(engine: unknown) {
const noop = () => {};
const rest = new RestServer(
{ get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} } 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();
const route = rest.getRoutes().find((r: any) => r.method === 'POST' && r.path === PATH);
expect(route, PATH).toBeDefined();
return route!.handler;
}

function headerRes() {
const res: any = {
headers: [] as Array<[string, string | string[]]>,
header: (name: string, value: string | string[]) => { res.headers.push([name, value]); return res; },
status: (code: number) => { res.statusCode = code; return res; },
json: (body: any) => { res.body = body; return res; },
end: () => res,
};
return res;
}

const vary = (res: any) => res.headers.filter(([name]: [string]) => name.toLowerCase() === 'vary');
const req = (id: string) => ({ method: 'POST', params: { object: 'lead', id }, headers: {}, query: {}, body: { ownerId: 'u_next' } }) as any;

describe('[#38567] POST /data/:object/:id/change-owner says when its refusal varies by language', () => {
it('a missing record: the localized 404 RECORD_NOT_FOUND carries Vary: Accept-Language, once', async () => {
const engine = engineOf();
const res = headerRes();
await handlerOf(engine)(req('l9'), res);
expect(engine.update).toHaveBeenCalledTimes(1);
expect(res.statusCode, JSON.stringify(res.body)).toBe(404);
expect(res.body.error.code).toBe('RECORD_NOT_FOUND');
expect(res.body.error.userMessage).toEqual(expect.any(String));
// The multi-value form the hosts append, never a set that would drop CORS's `Origin`.
expect(vary(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
});

it('CONTROL: a refusal with no userMessage gets no Vary', async () => {
const denied = () => Object.assign(new Error('Access denied'), { name: 'PermissionDeniedError', code: 'PERMISSION_DENIED', status: 403 });
const res = headerRes();
await handlerOf(engineOf(denied))(req('l1'), res);
expect(res.statusCode, JSON.stringify(res.body)).toBe(403);
expect(res.body.error.code).toBe('PERMISSION_DENIED');
expect(res.body.error.userMessage).toBeUndefined();
expect(vary(res)).toEqual([]);
});
});
5 changes: 4 additions & 1 deletion packages/types/src/localized-answer-vary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@
* `form-routes.ts`), and `handleRouteError` (`error-response.ts`), the shared
* exit of the metadata, batch, approval and other data-action routes;
* - `@objectstack/hono`: `thrownJson`, both of `createHonoApp`'s catch arms;
* - `@objectstack/runtime`: `dispatcher-plugin`'s `errorResponseBase`.
* - `@objectstack/runtime`: `dispatcher-plugin`'s `errorResponseBase`;
* - `@objectstack/types`: `sendError`'s envelope write (`response-envelope.ts`),
* the exit of every door that re-sends a classified answer in the nested
* envelope (change-owner, the recycle bin, packages, the analytics batch).
*
* Those three answer a THROW. An answer a dispatcher domain catches and composes
* itself is RETURNED instead (`HttpDispatcher.errorFromThrown`, `deps.error`
Expand Down
16 changes: 15 additions & 1 deletion packages/types/src/response-envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
*/

import type { ApiError, ErrorCode } from '@objectstack/spec/api';
import { answerVariesByLanguage, LOCALIZED_ANSWER_VARY } from './localized-answer-vary.js';
import { logServerFault, type ServerFaultRequest } from './server-fault-log.js';

/**
Expand All @@ -64,6 +65,13 @@ import { logServerFault, type ServerFaultRequest } from './server-fault-log.js';
export interface EnvelopeResponse {
status(code: number): EnvelopeResponse;
json(body: unknown): unknown;
/**
* [#38567] Set a response header, `IHttpResponse.header`'s shape: an array
* value is the multi-value form the hosts APPEND. Optional because a
* capturing sink (a batch entry's recorder, a row's classified answer) has
* no response to vary; every live response carries it.
*/
header?(name: string, value: string | string[]): unknown;
}

/**
Expand Down Expand Up @@ -297,5 +305,11 @@ function writeErrorEnvelope(
message: string,
extra?: Pick<ApiError, 'category' | 'httpStatus' | 'details' | 'requestId' | 'declaredCode' | 'userMessage'>,
): void {
res.status(status).json({ success: false, error: { code, message, ...extra } });
const body = { success: false, error: { code, message, ...extra } };
// [#38567] A body carrying a `userMessage` says it varies by
// `Accept-Language`, asked at the one write so no door re-sending a
// classified answer can forget it; appended, so other `Vary` tokens stay.
// The rule and its reasons are `answerVariesByLanguage`'s.
if (answerVariesByLanguage(body)) res.header?.('Vary', [LOCALIZED_ANSWER_VARY]);
res.status(status).json(body);
}
35 changes: 35 additions & 0 deletions packages/types/src/send-error-vary-38567.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#38567] `sendError`'s envelope write says `Vary: Accept-Language` when the
* body it writes carries a `userMessage` (`answerVariesByLanguage`), so every
* door that re-sends a classified answer through it is covered at once.
*/

import { describe, it, expect } from 'vitest';
import { sendError } from './response-envelope.js';
import { LOCALIZED_ANSWER_VARY } from './localized-answer-vary.js';

function res() {
const r: any = { headers: [] as unknown[] };
r.header = (name: string, value: string | string[]) => { r.headers.push([name, value]); return r; };
r.status = (code: number) => { r.statusCode = code; return r; };
r.json = (body: unknown) => { r.body = body; return r; };
return r;
}

describe('[#38567] sendError and Vary: Accept-Language', () => {
it('a userMessage on the body appends Vary: Accept-Language', () => {
const r = res();
sendError(r, 404, 'RECORD_NOT_FOUND', 'Record not found', { userMessage: 'Enregistrement introuvable.' });
expect(r.statusCode).toBe(404);
expect(r.body).toEqual({ success: false, error: { code: 'RECORD_NOT_FOUND', message: 'Record not found', userMessage: 'Enregistrement introuvable.' } });
expect(r.headers).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
});

it('CONTROL: no userMessage, no header', () => {
const r = res();
sendError(r, 404, 'RECORD_NOT_FOUND', 'Record not found');
expect(r.headers).toEqual([]);
});
});
5 changes: 5 additions & 0 deletions scripts/engine-double-contract.pinned.json
Original file line number Diff line number Diff line change
Expand Up @@ -5111,6 +5111,11 @@
"verb": "update",
"pinned": 1
},
{
"file": "packages/rest/src/change-owner-vary-38567.test.ts",
"verb": "update",
"pinned": 1
},
{
"file": "packages/rest/src/email-send-display-name.test.ts",
"verb": "update",
Expand Down
Loading