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
12 changes: 12 additions & 0 deletions .changeset/38123-returned-answer-varies-by-language.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/runtime': patch
'@objectstack/hono': patch
'@objectstack/types': patch
---

fix(runtime,hono): an error answer a dispatcher domain returns with a `userMessage` says it varies by `Accept-Language`

Clause-②: no
Metadata-protocol: none

An error answer whose body carries a `userMessage` is in the caller's language, so it now carries `Vary: Accept-Language`, as the thrown refusals already do. This covers the answers a dispatcher domain catches and composes itself: `HttpDispatcher.errorFromThrown`, a `deps.error` call carrying a `userMessage` (the automation resume and trigger doors' `FLOW_FAILED`), the `/actions` door, and the dispatch foot's marked `PERMISSION_DENIED`. Both exits that send such an answer ask the body: `@objectstack/runtime`'s dispatcher plugin and `@objectstack/hono`'s `createHonoApp`. The token is appended, so a `Vary` that CORS, compression or the route writes keeps its own tokens. Status codes, error codes and bodies are unchanged, and an answer with no `userMessage` gets no new header.
85 changes: 84 additions & 1 deletion packages/adapters/hono/src/hono-response-header-array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
* real door produces.
*/

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import type { Hono } from 'hono';
import { LOCALIZED_ANSWER_VARY } from '@objectstack/types';

const mockDispatcher = {
getDiscoveryInfo: vi.fn().mockReturnValue({ version: '1.0', routes: {} }),
Expand Down Expand Up @@ -102,3 +103,85 @@ describe('#27506: a string[] header value is one header line per element', () =>
expect(res.headers.get('x-one')).toBe('line');
});
});

/**
* [#38123] `toResponse`'s `response` arm asks #37828's rule of the body it
* sends: an answer a dispatcher domain caught and composed itself never reaches
* `thrownJson`, and a `userMessage` in its body is in the caller's language.
*
* Each row is the nested ADR-0112 body one of the dispatcher's returning
* producers composes, written out because this package's `@objectstack/runtime`
* is a stub (the real producers are driven through their mounted routes in
* `@objectstack/runtime`'s `dispatcher-plugin.declared-user-message.test.ts`):
* `errorFromThrown` over the real `recordNotFoundError` for a zh-CN caller, the
* resume door's `deps.error` and the `/actions` door's `FLOW_FAILED` with an
* app hook's mark, and the dispatch foot's marked `PERMISSION_DENIED`.
*/
describe('[#38123] the returned answer: a userMessage varies by Accept-Language', () => {
const ORIG_CORS_ORIGIN = process.env.OS_CORS_ORIGIN;
afterAll(() => {
if (ORIG_CORS_ORIGIN === undefined) delete process.env.OS_CORS_ORIGIN;
else process.env.OS_CORS_ORIGIN = ORIG_CORS_ORIGIN;
});
beforeEach(() => {
vi.clearAllMocks();
mockDispatcher.handleAuth.mockResolvedValue({ handled: false });
});

const MARK = '该客户名称已被另一位销售代表占用,请联系主管。';
const refusal = (status: number, code: string, message: string, userMessage?: string) => ({
handled: true,
response: {
status,
body: { success: false, error: { code, message, httpStatus: status, ...(userMessage !== undefined ? { userMessage } : {}) } },
},
});
const PRODUCERS: Array<[string, number, string, string, string]> = [
['errorFromThrown', 404, 'RECORD_NOT_FOUND', 'Record l_nowhere not found in crm_lead', '该记录不存在,或您无权访问它。'],
['deps.error, the resume door', 400, 'FLOW_FAILED', "Node 'create_account' failed", MARK],
['the /actions door', 400, 'FLOW_FAILED', "Flow 'crm_convert_lead_wizard' failed", MARK],
['the dispatch foot', 403, 'PERMISSION_DENIED', 'principal lacks cube_read on pipeline', 'Ask an admin for the Reporting role.'],
];
const varyTokens = (res: Response): string[] =>
(res.headers.get('vary') ?? '').split(',').map((token) => token.trim()).filter(Boolean);
const noCors = (): Hono => createHonoApp({ kernel, prefix: PREFIX, cors: false });

for (const [producer, status, code, message, mark] of PRODUCERS) {
it(`${producer}: ${status} ${code} with its userMessage on the wire, and Vary: Accept-Language`, async () => {
mockDispatcher.dispatch.mockResolvedValueOnce(refusal(status, code, message, mark));
const res = await noCors().request(`http://localhost${PATH}`, { method: 'POST', headers: { 'Accept-Language': 'zh-CN' } });
const body = await res.json() as any;
expect(res.status, JSON.stringify(body)).toBe(status);
expect(body.error.code).toBe(code);
expect(body.error.userMessage).toBe(mark);
expect(varyTokens(res)).toEqual([LOCALIZED_ANSWER_VARY]);
});

it(`CONTROL ${producer}: the unmarked ${status} gets no Vary`, async () => {
mockDispatcher.dispatch.mockResolvedValueOnce(refusal(status, code, message));
const res = await noCors().request(`http://localhost${PATH}`, { method: 'POST' });
expect(res.status).toBe(status);
expect(res.headers.get('vary')).toBeNull();
});
}

it('appended, not set: a Vary the route wrote keeps its token beside Accept-Language', async () => {
const answer = refusal(404, 'RECORD_NOT_FOUND', 'Record l_nowhere not found in crm_lead', '该记录不存在,或您无权访问它。');
mockDispatcher.dispatch.mockResolvedValueOnce({ ...answer, response: { ...answer.response, headers: { Vary: 'Accept-Encoding' } } });
const res = await noCors().request(`http://localhost${PATH}`, { method: 'POST' });
expect(res.status).toBe(404);
expect(varyTokens(res)).toEqual(['Accept-Encoding', LOCALIZED_ANSWER_VARY]);
});

it('appended, not set: with CORS on, Origin keeps its place beside Accept-Language', async () => {
process.env.OS_CORS_ORIGIN = 'https://app.example.com';
mockDispatcher.dispatch.mockResolvedValueOnce(refusal(404, 'RECORD_NOT_FOUND', 'Record l_nowhere not found in crm_lead', '该记录不存在,或您无权访问它。'));
const res = await createHonoApp({ kernel, prefix: PREFIX }).request(`http://localhost${PATH}`, {
method: 'POST',
headers: { Origin: 'https://app.example.com' },
});
expect(res.status).toBe(404);
expect(varyTokens(res)).toContain(LOCALIZED_ANSWER_VARY);
expect(varyTokens(res)).toContain('Origin');
});
});
9 changes: 9 additions & 0 deletions packages/adapters/hono/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,15 @@ export function createHonoApp(options: ObjectStackHonoOptions): Hono {
if (result.response.headers) {
Object.entries(result.response.headers).forEach(([k, v]) => setResponseHeader(c, k, v));
}
// [#38123] The RETURNED answer's half of #37828's rule: an answer a
// dispatcher domain caught and composed itself (`errorFromThrown`, a
// `deps.error` carrying a `userMessage`, the `/actions` door) never
// reaches `thrownJson`. A `userMessage` in its body is in the caller's
// language, so the answer varies by `Accept-Language`
// (`answerVariesByLanguage`, `@objectstack/types`). Appended after the
// dispatcher's own headers, so CORS's `Vary: Origin` and a route's own
// `Vary` keep their tokens.
if (answerVariesByLanguage(result.response.body)) c.header('Vary', LOCALIZED_ANSWER_VARY, { append: true });
return c.json(result.response.body, result.response.status);
}
if (result.result) {
Expand Down
170 changes: 170 additions & 0 deletions packages/runtime/src/dispatcher-plugin.declared-user-message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,3 +508,173 @@ describe('[#37828] the dispatcher throw-transparent exit: a userMessage varies b
expect(varyWrites(res)).toEqual([]);
});
});

/**
* [#38123] The RETURNED exit (`sendResultBase`) asks #37828's rule of the body
* it sends. A domain that catches its own fault composes the answer and RETURNS
* it, so it never reaches the throw-transparent exit above: every producer of a
* returned `userMessage` leaves through the plugin's `sendResult`, and each is
* driven here through its REAL mounted route:
*
* - `errorFromThrown`: `POST /automation/_record-starts`, whose catch hands the
* `/data` read's throw over; the throw is the real `recordNotFoundError` with
* the caller's own context, so its sentence follows `Accept-Language`;
* - `deps.error` carrying a `userMessage`: the resume door's `FLOW_FAILED`
* (`POST /automation/:name/runs/:runId/resume`, ruling B′ on #24914);
* - the trigger door's `FLOW_FAILED` (`POST /automation/:name/trigger`);
* - the `/actions` door (`POST /actions/:object/:action`, a flow action);
* - the dispatch foot's `PERMISSION_DENIED` 403, answered with its mark.
*
* Each case reads the one `Vary` write, in the contract's multi-value form (the
* form the hosts APPEND), written after every other header the answer carries;
* each producer's unmarked answer writes none.
*/
describe('[#38123] the dispatcher RETURNED exit: a userMessage varies by Accept-Language', () => {
let errSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => { errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); });
afterEach(() => { errSpy.mockRestore(); });

const varyWrites = (res: any) => res.headers.filter(([name]: [string]) => name.toLowerCase() === 'vary');
/** The Vary write is the LAST header written: nothing after it can replace it. */
const lastHeaderName = (res: any) => res.headers[res.headers.length - 1]?.[0];

const FLOW = 'crm_convert_lead_wizard';
const MARK = '该客户名称已被另一位销售代表占用,请联系主管。';
const failed = (mark?: string) => ({
success: false, status: 'failed', error: `Node 'create_account' failed`, durationMs: 9,
...(mark !== undefined ? { userMessage: mark } : {}),
});

/**
* One kernel serving the routes above, from one scripted engine and one
* `/data` read that refuses every id with the protocol's own error.
*/
async function mount(result: Record<string, unknown>) {
const { server, handlers } = makeFakeServer();
const automation = {
handlerReady: true,
execute: vi.fn(async () => result),
resume: vi.fn(async () => ({ ...result, status: 'stranded' })),
getFlow: vi.fn(async (name: string) => (name === FLOW ? { name } : null)),
listRecordUpdateStarts: vi.fn(() => []),
};
const flowAction = { name: 'convert_lead', label: 'Convert Lead', objectName: 'crm_lead', type: 'flow', target: FLOW };
const objects: Record<string, any> = {
crm_lead: { name: 'crm_lead', actions: [flowAction], fields: { status: {} } },
};
const objectql: any = {
executeAction: vi.fn(),
getSchema: (n: string) => objects[n],
registry: { getObject: (n: string) => objects[n], getItem: () => undefined },
find: vi.fn(async () => []),
insert: vi.fn(), update: vi.fn(), delete: vi.fn(),
};
const metadata: any = {
load: vi.fn(async () => null),
loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })),
listObjects: vi.fn(async () => Object.values(objects)),
getObject: vi.fn(async (n: string) => objects[n]),
};
const protocol = { getData: vi.fn(async ({ object, id, context }: any) => { throw recordNotFoundError(object, id, context); }) };
const services: Record<string, unknown> = { automation, objectql, data: objectql, metadata, protocol, auth: SIGNED_IN_AUTH };
const resolve = (name: string) => services[name];
const kernel = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } };
const plugin = createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false });
await plugin.start?.({
getKernel: () => kernel,
getService: (name: string) => (name === 'http.server' ? server : undefined),
environmentId: undefined,
logger: { info() {}, warn() {}, error() {}, debug() {} },
hook: () => {},
on: () => {},
} as any);
return async (route: string, params: Record<string, string>, body: unknown, lang = 'en') => {
const handler = handlers[`POST /api/v1${route}`];
expect(handler, `POST /api/v1${route} must be mounted`).toBeTypeOf('function');
const res = makeRes();
await handler({ body, query: {}, params, headers: { 'accept-language': lang } }, res);
return res;
};
}

const RECORD_STARTS = { object: 'crm_lead', recordId: 'l_nowhere', changes: { status: 'won' } };

describe('errorFromThrown — the record-update preview refusing an id the caller cannot read', () => {
const SENTENCES: Array<[string, string]> = [
['en', 'This record does not exist, or you do not have access to it.'],
['zh-CN', '该记录不存在,或您无权访问它。'],
['ja-JP', 'このレコードは存在しないか、アクセスする権限がありません。'],
];
for (const [lang, sentence] of SENTENCES) {
it(`${lang}: 404 RECORD_NOT_FOUND in that language, and Vary: Accept-Language appended last`, async () => {
const send = await mount(failed());
const res = await send('/automation/_record-starts', {}, RECORD_STARTS, lang);
expect(res.statusCode).toBe(404);
expect(res.body.error.code).toBe('RECORD_NOT_FOUND');
expect(res.body.error.userMessage).toBe(sentence);
expect(varyWrites(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
expect(lastHeaderName(res)).toBe('Vary');
});
}

it('CONTROL the same route\'s unmarked 400 VALIDATION_FAILED writes no Vary', async () => {
const send = await mount(failed());
const res = await send('/automation/_record-starts', {}, { object: 'crm_lead', recordId: 'l_nowhere' }, 'zh-CN');
expect(res.statusCode).toBe(400);
expect(res.body.error.code).toBe('VALIDATION_FAILED');
expectNoUserMessageAnywhere(res);
expect(varyWrites(res)).toEqual([]);
});
});

/** Each door's MOUNTED route pattern, and the params its handler reads. */
const FLOW_DOORS: Array<[string, string, Record<string, string>]> = [
['deps.error with a userMessage — the resume door', '/automation/:name/runs/:runId/resume', { name: FLOW, runId: 'run_1' }],
['the trigger door', '/automation/:name/trigger', { name: FLOW }],
['the /actions door', '/actions/:object/:action', { object: 'crm_lead', action: 'convert_lead' }],
];
for (const [door, route, params] of FLOW_DOORS) {
describe(`${door}: 400 FLOW_FAILED`, () => {
it('marked: the userMessage on the wire, and Vary: Accept-Language appended last', async () => {
const send = await mount(failed(MARK));
const res = await send(route, params, {});
expect(res.statusCode).toBe(400);
expect(res.body.error.code).toBe('FLOW_FAILED');
expect(res.body.error.userMessage).toBe(MARK);
expect(varyWrites(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
expect(lastHeaderName(res)).toBe('Vary');
});

it('CONTROL unmarked: no userMessage, no Vary', async () => {
const send = await mount(failed());
const res = await send(route, params, {});
expect(res.statusCode).toBe(400);
expect(res.body.error.code).toBe('FLOW_FAILED');
expectNoUserMessageAnywhere(res);
expect(varyWrites(res)).toEqual([]);
});
});
}

describe('the dispatch foot\'s PERMISSION_DENIED 403', () => {
it('marked: the userMessage on the wire, and Vary: Accept-Language appended last', async () => {
const res = await throwFromAnalyticsQuery(
declaring({ status: 403, code: 'PERMISSION_DENIED', userMessage: 'Ask an admin for the Reporting role.' }, 'principal lacks cube_read on pipeline'),
);
expect(res.statusCode).toBe(403);
expect(res.body.error.code).toBe('PERMISSION_DENIED');
expect(res.body.error.userMessage).toBe('Ask an admin for the Reporting role.');
expect(varyWrites(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
expect(lastHeaderName(res)).toBe('Vary');
});

it('CONTROL unmarked: no userMessage, no Vary', async () => {
const res = await throwFromAnalyticsQuery(
declaring({ status: 403, code: 'PERMISSION_DENIED' }, 'principal lacks cube_read on pipeline'),
);
expect(res.statusCode).toBe(403);
expectNoUserMessageAnywhere(res);
expect(varyWrites(res)).toEqual([]);
});
});
});
14 changes: 14 additions & 0 deletions packages/runtime/src/dispatcher-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,20 @@ function sendResultBase(
res.header(k, v);
}
}
// [#38123] The RETURNED exit's half of #37828's rule. A domain that
// catches its own fault answers through `errorFromThrown`, `deps.error`
// with a `userMessage` (the automation resume and trigger doors), the
// dispatch foot's `PERMISSION_DENIED` or the `/actions` door, and every
// one of those HTTP answers leaves here, never through
// `errorResponseBase`. (mcp.ts's `resumeDoorError` answers the in-process
// `dispatchActionResume`, not a route, so no header applies to it.)
// When the body carries a `userMessage` it is in the caller's
// language, so the answer varies by `Accept-Language`
// (`answerVariesByLanguage`, `@objectstack/types`, asked of the body
// actually sent). Written after the route's own
// headers and in the contract's multi-value form, which the hosts
// APPEND, so a `Vary` the route or another layer wrote keeps its tokens.
if (answerVariesByLanguage(result.response.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]);
res.json(result.response.body);
return;
}
Expand Down
9 changes: 9 additions & 0 deletions packages/types/src/localized-answer-vary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@
* - `@objectstack/hono`: `thrownJson`, both of `createHonoApp`'s catch arms;
* - `@objectstack/runtime`: `dispatcher-plugin`'s `errorResponseBase`.
*
* Those three answer a THROW. An answer a dispatcher domain catches and composes
* itself is RETURNED instead (`HttpDispatcher.errorFromThrown`, `deps.error`
* with a `userMessage`, the dispatch foot's `PERMISSION_DENIED`, the `/actions`
* door), and it leaves through the two exits that send a returned answer, which
* ask the same question of its body (#38123):
*
* - `@objectstack/runtime`: `dispatcher-plugin`'s `sendResultBase`;
* - `@objectstack/hono`: `createHonoApp`'s `toResponse`.
*
* Each exit adds the token with its host's APPEND form, never a set, so a `Vary`
* already on the response (CORS's `Origin`, compression's `Accept-Encoding`)
* keeps its tokens.
Expand Down
Loading