Skip to content

Commit d5fa237

Browse files
fix(rest): the email send door refuses an array or null body with its own 400 INVALID_REQUEST (#31541)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1X7uEuwPgByNvHxnrsUYacTB)_ Fixes #31496 Clause-②: no Metadata-protocol: none ## 维护者速读 1. 改了什么:`POST /api/v1/email/send` 收到 JSON 数组或 JSON `null` 作为请求体时,现在在路由自己这一层直接回 `400 INVALID_REQUEST`("JSON body required"),邮件服务不再被调用。 2. 为什么改:数组的 `typeof` 也是 `object`,能穿过路由原来的检查;`null` 原来被默认成 `{}`。两者都被送进邮件服务,再由服务以 `400 VALIDATION_FAILED`("subject is required")拒绝,错误码与路由自己的约定不一致(QA #31486 C3a)。 3. 风险与回滚:改前改后都是 400,只是错误码从服务的 `VALIDATION_FAILED` 变为路由的 `INVALID_REQUEST`;对象请求体和不带请求体的请求行为不变。回滚即 revert 本 PR。 4. 先看:`packages/rest/src/email-routes.ts`(请求体检查那 7 行),再看 `packages/rest/src/email-send-door-bounds.test.ts` 末尾新增的 describe。 5. 两分钟验证:`pnpm --filter @objectstack/rest exec vitest run src/email-send-door-bounds.test.ts`,预期 50 个用例全绿;把检查改回 `typeof body !== 'object'` 后数组三个用例转红。 6. 需要你做的:无,席位落地。 ## What changes The send door's body check, in `registerEmailEndpoints` (`packages/rest/src/email-routes.ts`), was the only route body check in that file: - **Before:** `const body = req.body ?? {}; if (!body || typeof body !== 'object')`. An array passes `typeof body !== 'object'`, and a JSON `null` was defaulted to `{}`. Both reached `emailService.send`, which refused them as malformed messages (`400 VALIDATION_FAILED`, "subject is required" from plugin-email's `normalizeMessage`). - **After:** `const body = req.body === undefined ? {} : req.body; if (!isPlainObject(body))`. `isPlainObject` is the helper the same file already uses for `headers` (it excludes arrays with `Array.isArray`). An array or `null` now takes the route's own `400 INVALID_REQUEST` "JSON body required", before the service is reached. - **Unchanged:** an absent body is still the empty message for the service to judge. (The Hono adapter already gives `{}` for an empty body; the `undefined` arm covers an embedder whose adapter leaves it unset.) Every object body is forwarded exactly as before, and a string or number body keeps the same answer. **Sweep of the same file.** `email-routes.ts` registers one route, so this is the only route body check in it. The other object-shape check in the file, `headersRefusal`, already goes through `isPlainObject`. **Clause-② read from the diff: `no`.** The shipped service refuses every array and `null` body with a 400, because none of them carries a `subject`. After this change they are still refused with a 400, now with the route's own code. Nothing that answered 200 before is refused now. ## Tests `packages/rest/src/email-send-door-bounds.test.ts` gets a new top-level `describe` in the existing harness. It runs through the real `HonoHttpServer` transport, with a contract-typed email double: - Six cases, each answering `400` with `code: 'INVALID_REQUEST'` while `send` is never called: an array of numbers, an empty array, an array holding a well-formed message, a JSON `null`, a JSON string and a JSON number. - CONTROL: an object body still reaches `send`, as sent. - CONTROL: an empty object `{}` still reaches `send`, stamped only with `sentBy`. It is a message for the service to judge, not a missing body. The file also gains a module-top `import '@objectstack/objectql';`. `check:test-source-alias` asks for it on any edited test whose server reach loads objectql dynamically inside a handler. <details><summary>Red on main first (4 of the 6 refusal cases; the string and number cases were already green)</summary> ``` × an array of numbers is refused 400 INVALID_REQUEST, and nothing is sent 12ms × an empty array is refused 400 INVALID_REQUEST, and nothing is sent 2ms × an array holding a well-formed message is refused 400 INVALID_REQUEST, and nothing is sent 2ms × a JSON null is refused 400 INVALID_REQUEST, and nothing is sent 2ms AssertionError: expected 200 to be 400 // Object.is equality Tests 4 failed | 46 passed (50) ``` </details> <details><summary>Ablation (scripts/ablation-replace.mjs, src is what the suite imports, so no build leg)</summary> Leg 1 puts back `if (!body || typeof body !== 'object') {`. Mutation landed (anchor 1 → 0, blob 626f40e → 895cf1968604): ``` × an array of numbers is refused 400 INVALID_REQUEST, and nothing is sent 8ms × an empty array is refused 400 INVALID_REQUEST, and nothing is sent 2ms × an array holding a well-formed message is refused 400 INVALID_REQUEST, and nothing is sent 2ms Tests 3 failed | 47 passed (50) ablation-replace: ok restored: blob == HEAD (626f40e) and `git diff HEAD` is empty ``` Leg 2 puts back `const body = req.body ?? {};`. Mutation landed (blob 626f40e → 47919d207c32): ``` × a JSON null is refused 400 INVALID_REQUEST, and nothing is sent 12ms Tests 1 failed | 49 passed (50) ablation-replace: ok restored: blob == HEAD (626f40e) and `git diff HEAD` is empty ``` </details> ## Acceptance notes - **Same-shape checks elsewhere in `packages/rest` (not in this diff).** I searched `packages/rest/src`, excluding tests, for every `typeof …body… !== 'object'` check. There are four. Three already exclude arrays: `analytics-dataset-body-door.ts`, `meta-record-currency-backfill-route.ts` and `user-work-routes.ts`. The fourth is this one. Nothing is left to list. - The door's `INVALID_REQUEST` and `VALIDATION_FAILED` answers are still the flat `{ code, error }` body, while its bounds answer the nested ADR-0112 envelope. That predates this card, and this PR does not change it. ## Verification `HEAD` 0319dc5 (after merging `origin/main` once): - `pnpm --filter @objectstack/rest test`: 394 files and 7546 tests passed, 332 skipped (run on 1dfcd3e, before the merge and the test-only import commit). - `pnpm --filter @objectstack/rest exec vitest run src/email-send-door-bounds.test.ts src/email-send-display-name.test.ts` on 0319dc5: 2 files, 69 tests passed. - `pnpm --filter @objectstack/rest typecheck`: exit 0. - `pnpm exec eslint --no-inline-config` on the two touched source files: exit 0. - `dispatch-gates --commands`: 64 commands. Their exit codes are in the seat report on the card. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5mNZhe975x6zR3ULqS)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent dc8479e commit d5fa237

3 files changed

Lines changed: 65 additions & 2 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/rest': patch
3+
---
4+
5+
fix(rest): `POST /api/v1/email/send` refuses a JSON array or `null` body with its own `400 INVALID_REQUEST` before the email service is reached
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The send door's body check read `typeof body !== 'object'`, which an array passes, and it defaulted a JSON `null` body to `{}`. Either way the message reached the email service, which refused it as a malformed message (`400 VALIDATION_FAILED`, "subject is required"). The door now admits a present body only when it is a plain JSON object, so an array or `null` gets the same `400 INVALID_REQUEST` ("JSON body required") as a string or a number, and the service is never called. A request with no body is still the empty message for the service to judge, and every object body is forwarded exactly as before. Both kinds of body were refused with a 400 before this change and are refused with a 400 after it; only the code changes, from the service's `VALIDATION_FAILED` to the route's `INVALID_REQUEST`.

‎packages/rest/src/email-routes.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -264,8 +264,13 @@ export function registerEmailEndpoints(this: EmailRouteHost, basePath: string):
264264
return;
265265
}
266266

267-
const body = req.body ?? {};
268-
if (!body || typeof body !== 'object') {
267+
// An absent body is the empty message, for the service to
268+
// judge. A body that is present must be a JSON object: an
269+
// array is `typeof 'object'` and a JSON `null` is present, and
270+
// neither is a message, so both take this route's own 400
271+
// before the service is reached.
272+
const body = req.body === undefined ? {} : req.body;
273+
if (!isPlainObject(body)) {
269274
res.status(400).json({ code: 'INVALID_REQUEST', error: 'JSON body required' });
270275
return;
271276
}

‎packages/rest/src/email-send-door-bounds.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@
1515
* each admission case proves what it was called WITH.
1616
*/
1717

18+
// The server under test reaches `@objectstack/objectql` only through a dynamic
19+
// import inside a handler (`meta-object-state-routes.ts`), so the first case to
20+
// call one would pay that module graph's load inside its clocked window. This
21+
// module-top import pays it during collection instead.
22+
import '@objectstack/objectql';
23+
1824
import { describe, it, expect, vi } from 'vitest';
1925
import { HonoHttpServer } from '@objectstack/plugin-hono-server';
2026
import type { EmailAddress, IEmailService, SendEmailInput } from '@objectstack/spec/contracts';
@@ -413,3 +419,45 @@ describe('POST /api/v1/email/send — identity mail is not sent through this doo
413419
expect(input.organizationId).toBe(ORG_ADMIN.tenantId);
414420
});
415421
});
422+
423+
describe('POST /api/v1/email/send — a body that is not a JSON object is the route\'s own 400, before the service', () => {
424+
// An array is `typeof 'object'`, and a JSON `null` used to be defaulted to
425+
// `{}`; either way the message reached `send` and the service answered
426+
// VALIDATION_FAILED for a request the route itself should have refused.
427+
it.each([
428+
['an array of numbers', [1, 2]],
429+
['an empty array', []],
430+
['an array holding a well-formed message', [MESSAGE]],
431+
['a JSON null', null],
432+
['a JSON string', 'not an object'],
433+
['a JSON number', 42],
434+
])('%s is refused 400 INVALID_REQUEST, and nothing is sent', async (_label, body) => {
435+
const { service, send } = emailDouble();
436+
const { post } = boot({ service, ctx: ADMIN });
437+
const out = await post(body);
438+
439+
expect(out.status).toBe(400);
440+
expect(out.body.code).toBe('INVALID_REQUEST');
441+
expect(send).not.toHaveBeenCalled();
442+
});
443+
444+
it('CONTROL: an object body still reaches the service, as sent', async () => {
445+
const { service, send } = emailDouble();
446+
const { post } = boot({ service, ctx: ADMIN });
447+
const out = await post(MESSAGE);
448+
449+
expect(out.status).toBe(200);
450+
expect(send).toHaveBeenCalledTimes(1);
451+
expect(send.mock.calls[0][0]).toMatchObject(MESSAGE);
452+
});
453+
454+
it('CONTROL: an empty object is a message for the service to judge, not a missing body', async () => {
455+
const { service, send } = emailDouble();
456+
const { post } = boot({ service, ctx: ADMIN });
457+
const out = await post({});
458+
459+
expect(out.status).toBe(200);
460+
expect(send).toHaveBeenCalledTimes(1);
461+
expect(send.mock.calls[0][0]).toEqual({ sentBy: ADMIN.userId });
462+
});
463+
});

0 commit comments

Comments
 (0)