Skip to content

Commit 7a8733f

Browse files
fix(runtime): the declarative-endpoint fallback reads the body after the match and the policies (#24285)
Fixes #24252 Clause-②: no Contract basis for the line above: only the order of refusals moves (the `404` and the `401` now answer ahead of the body's `400`). No request that was refused before is accepted, and no export moves. ## What was wrong On the standalone server (`HonoServerPlugin` + the dispatcher plugin), the declarative-endpoint fallback (`setFallbackHandler` in `packages/runtime/src/dispatcher-plugin.ts`) built `runAppEndpointStep`'s request with `body: req.body`, before the step matched an endpoint or ran its policy chain. The transport's `req.body` is an accessor that throws its `400 INVALID_REQUEST` refusal for a body it could not parse, records the refusal, and answers the request with it whatever the handler then writes (`packages/plugins/plugin-hono-server/src/adapter.ts`, `runHandler`). So: - a `POST` to `/api/v1/apps/ns/...` that no declaration owns, with an unparseable JSON body, answered `400` where the same request with a readable body answers `404 ENDPOINT_NOT_FOUND`, signed in or not; - an anonymous `POST` to an `authRequired: true` endpoint with an unparseable body answered `400` where `401 UNAUTHENTICATED` is owed. The card listed this case as inferred; it is now measured (below). ## What changes - `packages/runtime/src/dispatcher-plugin.ts`: the fallback hands the step `deferRequestBody(req)` (the #24151 pair, `packages/runtime/src/deferred-request-body.ts`) instead of `req.body`. - `packages/runtime/src/api-endpoint-step.ts`: the step reads it with `readDispatchedBody(request.body)` after `applyEndpointPolicies` has admitted the caller (rate limit, auth gate, `authRequired`), just before `inputMapping`. That is the step's one body read, and nothing above it touches the body. A body that was not deferred (a direct caller, a unit test) passes through unchanged, and with no mapping declared the request still rides on by reference. - The "scoping test FIRST" property is unchanged: a path outside the `/apps/` carve-out still returns before any resolution, and a miss still writes nothing. - New real-socket pins: `packages/runtime/src/dispatcher-plugin.endpoint-fallback-body-after-match.integration.test.ts`. - `.changeset/24252-endpoint-fallback-body-after-match.md`: `patch` for `@objectstack/runtime`. The deferred-body pair fits this seam without change: the step has exactly one body read, and it sits after the policy chain. The pair's guard also applies here: a future read of the deferred body before the resolve throws `UnresolvedRequestBodyRead` instead of quietly running the transport's refusal early. ## Measurements (dispatch assumptions A1 to A5) Tree: `origin/main` `53ef75243` (BASE), fix at `d8dbf8b1d`, head `f23824394`. - **A1, holds.** On BASE: `setFallbackHandler` at `:2151`, `runAppEndpointStep({` at `:2243`, `body: req.body` at `:2291`, built after `resolveRequestScope` and the multi-tenant decline and before any match. - **A2, holds.** In code, the adapter's `get body()` throws `bodyReading.refusal` and sets `refusedBodyRead`; after the handler, a recorded refusal is the answer. On a socket, the before-readings below show it. - **A3, holds.** Both functions exist. `runAppEndpointStep` reads the body once, at `applyInputMapping(match.endpoint, request.body)`, after the policy `deny` return. Neither the matcher nor `applyEndpointPolicies` receives the body. - **A4, measured.** Anonymous caller, `authRequired: true` endpoint, unparseable body: `400 INVALID_REQUEST` before the fix, `401 UNAUTHENTICATED` after. - **A5, no read before the match, in this repository.** `resolveRequestScope` runs `prepareResolverHints` (path and route params only), the host's `KernelResolver`, and `resolveExecutionContext` (no body reference). After the fix, the single-tenant socket pins answer `404` for an unmatched path, and that composition runs `resolveRequestScope` before the match. A throwaway probe (not committed) on the multi-tenant composition, with the existing multi-tenant test's stub resolver, read the same at the fixed head and with the fallback's `req.body` put back: | request (unparseable body) | fallback reads `req.body` | fixed | |---|---|---| | unplaced (no environment header), declared path | `404`, matcher asked 0 times | `404`, matcher asked 0 times | | unknown environment, declared path | `404` | `404` | | placed, unmatched path | `400 INVALID_REQUEST` | `404 ENDPOINT_NOT_FOUND` | | placed, `authRequired: false` path (admitted) | `400 INVALID_REQUEST` | `400 INVALID_REQUEST` | The decline branch returns before the step's argument is built, so it never read the body. The real `KernelResolver` is host-supplied (the cloud distribution) and has no implementation in this repository: whether it reads `context.request.body` is NOT MEASURED here. ## Tests New pins, on a real socket (LiteKernel + `HonoServerPlugin` on port 0 + the dispatcher plugin, with stubbed `auth`, `metadata.matchEndpoint` and `automation` slots). Refusal-shaped assertions check `status` and `error.code`. The transport refusal is told apart from a domain `INVALID_REQUEST` by its message, as #24151's pins do. | case | BASE `53ef75243` | fix `d8dbf8b1d` | |---|---|---| | anonymous, unmatched path, unparseable body: `404 ENDPOINT_NOT_FOUND` as for a readable body, matcher asked | red: `400` | green | | signed-in, unmatched path, unparseable body: `404`, as above | red: `400` | green | | anonymous, `authRequired: true`, unparseable body: `401 UNAUTHENTICATED` as for a readable body, target never runs | red: `400` | green | | control: signed-in, `authRequired: true`, unparseable body: transport `400` refusal, target never runs | green | green | | control: anonymous, `authRequired: false`, unparseable body: transport `400` refusal, target never runs | green | green | | control: signed-in, `authRequired: true`, readable body: `200`, flow receives `params: { days: 30 }` | green | green | Existing suites, all green at the fix, in one run (11 files, 231 tests, `VERDICT command-exit 0`): the new file, `dispatcher-plugin.endpoint-fallback.integration.test.ts`, `api-endpoint-step.test.ts`, #24151's `dispatcher-body-after-anonymous-floor.hono.integration.test.ts` and `deferred-request-body.test.ts`, `dispatcher-plugin.multi-tenant-endpoint.integration.test.ts`, `dispatcher-plugin.endpoint-principal-less-deny.integration.test.ts`, `dispatcher-plugin.streaming-fallback.test.ts`, `dispatcher-plugin.fallback-absence-warn.test.ts`, `endpoint-flow-dispatch-status.test.ts`, `endpoint-flow-elevated-door.test.ts`. Full package: `pnpm --filter @objectstack/runtime test` at `50f9caa35` (same code as the head; later commits touch only the changeset): 417 files passed, 6553 passed and 19 skipped, `VERDICT command-exit 0`. `pnpm --filter @objectstack/runtime typecheck`: exit 0. `tsc --listFiles -p tsconfig.test.json` lists the new test file, with no `error TS` lines naming it. `check:test-typecheck` OK, ledger unchanged. ## Ablation (one time, both legs, on `d8dbf8b1d`) Both subjects are imported relatively (`./dispatcher-plugin.js`, which vitest transforms from `src/`), so no `dist/` rebuild applies. Mutation and restore went through `scripts/ablation-replace.mjs`, which uses a must-hit anchor and verifies blob hashes, with a `trap` restore as well. - **Leg A**, fallback: `body: deferRequestBody(req),` changed to `body: req.body,` (anchor 1 to 0, blob `718ef188ae82` to `b872160649cf`). Red, the expected direction: the three `404` / `404` / `401` pins fail (`expected 400 to be 404`, `expected 400 to be 401`), and the three controls stay green. Restored: blob equals HEAD `718ef188ae82`, `git diff HEAD` empty. - **Leg B**, step: `readDispatchedBody(request.body)` changed to `request.body` (blob `88d109cebdcf` to `22f289504261`). Red, the expected direction: the three controls fail with `500` (the unresolved deferred body throws), and so do two existing fallback cases whose flow reads a body (`runs a flow through the automation slot ...`, `[#22147] hands the flow executor the guest ...`). The `404` / `401` pins stay green. Restored: blob equals HEAD `88d109cebdcf`, `git diff HEAD` empty. ## Gates (local, at head `8b5e3b7f4`) - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`, run with no paths (change set from merge base `93b4acb57`), derives 64 commands. All 64 ran, each exit code captured before any pipe, and all exited 0. `--ran` verdict: "64 derived famil(ies) accounted for — 64 run, 0 NOT-MEASURED (a DERIVED zero — all 64 recorded an exit code and none of them is 3)". Among them: `check:route-envelope`, `check:slot-lookup` ("ratchet holds: 101 unswept site(s) in 25 file(s), none new"), `check-system-context-census` (OK), `check:nul-bytes` (OK), `check:test-source-alias` (OK) and `check:cross-package-test-inputs` (OK). - Five roster families keep their roster under a directory this diff touches. They ran in addition and all exited 0: `check-changeset-fixed`, `check:authz-resolver`, `check:error-code-casing`, `check:filter-alias-parity` and `check:route-ledger-census`. - eslint: `pnpm exec eslint --no-inline-config` over the three changed source files exited 0 with no output. The repo-wide `pnpm lint` is CI's. - On the pre-merge head `f23824394`, two commands first exited 3 (prerequisite not met). `check-plugin-teardown-shape --self-test` needed its pinned fixture commit `621a4876`, which this shallow clone lacked; after fetching it, the re-run exited 0. `check:dual-build-cjs-loads` needed unbuilt workspace packages; on `8b5e3b7f4` it measured that 111 require entry points across 69 packages load. The merge of `origin/main` `93b4acb57` touched only `scripts/pm/dispatch-gates*`. - Left to CI, not run locally: the `repo` vitest project (`test:repo`; no file in this diff is in it), the workspace type-check lanes, Build Core, the Test Core shards and dogfood. `check-platform-checklist --changed-from` is not owed, because no exported symbol is renamed or removed. Diff: 4 files, +246 / -4 (`dispatcher-plugin.ts` +9/-1, `api-endpoint-step.ts` +20/-3, new pin file +201, changeset +16). ## Acceptance notes - `EndpointExecutionRequest.body`'s doc line in `packages/runtime/src/endpoint-executor.ts` ("The fallback seam populates it exactly as a route does") still holds for what the executor receives, which is the body the step read. The deferral is documented where it happens: in `AppEndpointExecutionInput.request` and at the step's read. `endpoint-executor.ts` is outside the claimed file surface, so it was left alone. Carrier: none. - The host-supplied `KernelResolver` sees `context.request` before the match. No implementation in this repository reads the body; the cloud one is NOT MEASURED here. Carrier: none. - `dispatcher-plugin.ts`'s route-handler mount (`body: req.body` near `:305`) reads the body after its own `route.auth` decision, so it is in the right order and not this defect. --- _Generated by [Claude Code](https://claude.ai/code/session_01SYEJqDL3NXxrJRBVqaMu9T)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9822b05 commit 7a8733f

4 files changed

Lines changed: 246 additions & 4 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/runtime': patch
3+
---
4+
5+
fix(runtime): a request to a declarative `apis:` endpoint path gets its `404` or `401` whatever its JSON body, not the transport's `400`
6+
7+
Clause-②: no
8+
9+
Only the order of refusals moves: the `404` and the `401` now answer ahead of the body's `400`. No request that was refused before is accepted, and no export changes.
10+
11+
On the standalone server (`os dev`, `os serve`: `HonoServerPlugin` with the dispatcher plugin), the fallback that serves metadata-declared `apis:` endpoints (`/api/v1/apps/NAMESPACE/...` under the default prefix) read the request body before it matched an endpoint or applied `authRequired`. The transport refuses a body it cannot parse when the body is read, so that refusal answered first:
12+
13+
- a `POST /api/v1/apps/ns/x` that no declaration owns, with `{"params": {"days": 30}` (the closing brace missing), got `400 INVALID_REQUEST`, while the same request with a well-formed body got `404 ENDPOINT_NOT_FOUND`, signed in or not;
14+
- an anonymous `POST` to an `authRequired: true` endpoint with that body got `400 INVALID_REQUEST`, while a well-formed body got `401 UNAUTHENTICATED`.
15+
16+
The fallback now hands the endpoint step the body unread, and the step reads it once the endpoint is matched and its policies (`rateLimit`, `authRequired`) have admitted the caller, just before `inputMapping`. A path no declaration owns answers `404`, and an anonymous caller of an `authRequired: true` endpoint answers `401`, whatever the body. A caller the endpoint admits still gets the transport's `400 INVALID_REQUEST` for an unparseable body, and a readable body reaches the target as before.

‎packages/runtime/src/api-endpoint-step.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272
import { DispatcherErrorCode } from '@objectstack/spec/api';
7373
import type { ApiEndpointMatch, IMetadataService } from '@objectstack/spec/contracts';
7474
import type { ExecutionContext } from '@objectstack/spec/kernel';
75+
import { readDispatchedBody } from './deferred-request-body.js';
7576
import { apiErrorResponse } from './error-envelope.js';
7677
import { applyEndpointPolicies, type EndpointPolicyContext } from './endpoint-policy.js';
7778
import {
@@ -151,7 +152,12 @@ export interface AppEndpointStepAnswer {
151152
* growing a second, weaker copy in a consumer.
152153
*/
153154
export interface AppEndpointExecutionInput {
154-
/** The request as the fallback seam sees it — body and `remoteAddress` included. */
155+
/**
156+
* The request as the fallback seam sees it — body and `remoteAddress`
157+
* included. The fallback hands the body deferred (`deferRequestBody`); the
158+
* step reads it with `readDispatchedBody` only once the policy chain has
159+
* admitted the caller, so the executor always receives the read body.
160+
*/
155161
request: EndpointExecutionRequest;
156162
/** The `callData` binding and the `automation` slot occupant. */
157163
deps: EndpointExecutorDeps;
@@ -273,11 +279,22 @@ export async function runAppEndpointStep(
273279

274280
const { request, deps, executionContext, environmentId, dataDriver } = input.execution;
275281

282+
// ── The body is read HERE, and nowhere above (#24252) ────────────────
283+
// The fallback hands it deferred (`deferRequestBody`): reading a body the
284+
// transport could not parse throws its `400` and answers the request with
285+
// it, so a read before the match or the policy chain would answer that
286+
// `400` where a miss is owed its `404` and an anonymous caller of an
287+
// `authRequired` endpoint its `401`. Read now, it refuses only a caller
288+
// this endpoint admitted. A body that was not deferred (a direct caller,
289+
// a test) is returned as it is.
290+
const requestBody = readDispatchedBody(request.body);
291+
276292
// ── inputMapping: project the request the executor will see ──────────
277293
// Nothing has been delegated yet, so a declaration this runtime cannot
278294
// serve is refused before it can have an effect. With no declaration the
279-
// caller's own request object rides on unchanged, by reference.
280-
const mappedBody = applyInputMapping(match.endpoint, request.body);
295+
// caller's own request object rides on unchanged, by reference — unless
296+
// its body was deferred, when it rides on carrying the body just read.
297+
const mappedBody = applyInputMapping(match.endpoint, requestBody);
281298
if (!mappedBody.ok) return mappedBody.rejection;
282299
const mappedRequest = mappedBody.value === request.body
283300
? request
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
4+
import { LiteKernel, Plugin, PluginContext } from '@objectstack/core';
5+
import { HonoServerPlugin } from '@objectstack/plugin-hono-server';
6+
import { ApiEndpointSchema, type ApiEndpoint } from '@objectstack/spec/api';
7+
import type { ApiEndpointMatch, IHttpServer } from '@objectstack/spec/contracts';
8+
9+
import { createDispatcherPlugin } from './dispatcher-plugin.js';
10+
11+
/**
12+
* The declarative-endpoint fallback reads the request body only after the
13+
* endpoint is matched and its policies admitted the caller (#24252) — over a
14+
* real Hono socket.
15+
*
16+
* `@objectstack/plugin-hono-server`'s `req.body` throws its `400
17+
* INVALID_REQUEST` refusal when a body it could not parse is READ, and answers
18+
* the request with that refusal whatever the handler then writes. The fallback
19+
* used to read `req.body` while building `runAppEndpointStep`'s argument, so
20+
* the refusal fired before the step matched an endpoint or applied
21+
* `authRequired`: an unmatched path answered `400` where the same request with
22+
* a readable body answered `404`, and an anonymous caller of an
23+
* `authRequired: true` endpoint answered `400` where `401` is owed. The
24+
* fallback now hands the step a deferred body (`deferRequestBody`), and the
25+
* step reads it with `readDispatchedBody` once the policy chain passed.
26+
*
27+
* Readings:
28+
*
29+
* 1. no declaration owns the path → the transport's `404`, whatever the body,
30+
* signed in or not — and the matcher WAS asked, so the miss is the step's,
31+
* not the scoping test's;
32+
* 2. anonymous caller of an `authRequired: true` endpoint → `401`, whatever
33+
* the body, and the target never runs;
34+
* 3. the control: a caller the endpoint admits (signed in at
35+
* `authRequired: true`, anonymous at `authRequired: false`) still gets the
36+
* transport's refusal for an unparseable body — the body is read later,
37+
* not dropped — and a readable one reaches the target.
38+
*
39+
* The refusal is told from a domain's own `INVALID_REQUEST` by its message, as
40+
* `request-body-refusal.test.ts` in `plugin-hono-server` tells it.
41+
*/
42+
43+
const USER_HEADER = 'x-test-user';
44+
/** `{"params": {"days": 30}` — the closing brace missing. */
45+
const UNPARSEABLE = '{"params": {"days": 30}';
46+
const WELL_FORMED = '{"params": {"days": 30}}';
47+
48+
const UNMATCHED_PATH = '/api/v1/apps/ns/nothing_declared_here';
49+
const GUARDED_PATH = '/api/v1/apps/ns/guarded';
50+
const OPEN_PATH = '/api/v1/apps/ns/open';
51+
52+
const DECLARED: ApiEndpoint[] = [
53+
ApiEndpointSchema.parse({
54+
name: 'ns_guarded',
55+
path: GUARDED_PATH,
56+
method: 'POST',
57+
type: 'flow',
58+
target: 'ns_guarded_flow',
59+
authRequired: true,
60+
}),
61+
ApiEndpointSchema.parse({
62+
name: 'ns_open',
63+
path: OPEN_PATH,
64+
method: 'POST',
65+
type: 'flow',
66+
target: 'ns_open_flow',
67+
authRequired: false,
68+
}),
69+
];
70+
71+
/** Every `matchEndpoint` query, in order. */
72+
const queries: Array<{ path: string; method: string }> = [];
73+
/** Every flow the automation slot ran, with the context it was handed. */
74+
const flowRuns: Array<{ name: string; context: Record<string, unknown> }> = [];
75+
76+
function servicesPlugin(): Plugin {
77+
return {
78+
name: 'com.objectstack.test.endpoint-body-after-match',
79+
version: '1.0.0',
80+
init: async (ctx: PluginContext) => {
81+
ctx.registerService('auth', {
82+
api: {
83+
async getSession({ headers }: { headers: Headers }) {
84+
const uid = headers.get(USER_HEADER);
85+
return uid ? { user: { id: uid } } : null;
86+
},
87+
},
88+
});
89+
ctx.registerService('metadata', {
90+
list: async () => [],
91+
matchEndpoint: async (q: { path: string; method: string }): Promise<ApiEndpointMatch | undefined> => {
92+
queries.push(q);
93+
const hit = DECLARED.find((e) => e.path === q.path && e.method === q.method.toUpperCase());
94+
return hit ? { endpoint: hit, params: {} } : undefined;
95+
},
96+
});
97+
ctx.registerService('automation', {
98+
async execute(name: string, context: Record<string, unknown>) {
99+
flowRuns.push({ name, context });
100+
return { runId: 'run_1', status: 'completed' };
101+
},
102+
});
103+
},
104+
};
105+
}
106+
107+
describe('the declarative-endpoint fallback reads the body after the match and the policies (integration, #24252)', () => {
108+
let kernel: LiteKernel;
109+
let baseUrl: string;
110+
111+
beforeAll(async () => {
112+
kernel = new LiteKernel();
113+
kernel.use(new HonoServerPlugin({ port: 0, cors: false }));
114+
kernel.use(servicesPlugin());
115+
kernel.use(createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false }));
116+
await kernel.bootstrap();
117+
baseUrl = `http://127.0.0.1:${kernel.getService<IHttpServer>('http.server').getPort!()}`;
118+
}, 30_000);
119+
120+
afterAll(async () => {
121+
if (kernel) {
122+
await Promise.race([
123+
kernel.shutdown(),
124+
new Promise<void>((resolve) => setTimeout(resolve, 10_000)),
125+
]);
126+
}
127+
}, 30_000);
128+
129+
async function post(path: string, body: string, user?: string): Promise<{ status: number; json: Record<string, any> }> {
130+
const res = await fetch(`${baseUrl}${path}`, {
131+
method: 'POST',
132+
headers: { 'content-type': 'application/json', ...(user ? { [USER_HEADER]: user } : {}) },
133+
body,
134+
});
135+
return { status: res.status, json: (await res.json()) as Record<string, any> };
136+
}
137+
138+
function expectRefusal(answer: { status: number; json: Record<string, any> }): void {
139+
expect(answer.status).toBe(400);
140+
expect(answer.json.success).toBe(false);
141+
expect(answer.json.error.code).toBe('INVALID_REQUEST');
142+
expect(answer.json.error.message).toMatch(/parsed as JSON/);
143+
}
144+
145+
for (const user of [undefined, 'u_body_after_match']) {
146+
const who = user ? 'signed-in' : 'anonymous';
147+
it(`${who} POST to a path no declaration owns, unparseable body → the transport's 404, as for a well-formed one`, async () => {
148+
queries.length = 0;
149+
const unparseable = await post(UNMATCHED_PATH, UNPARSEABLE, user);
150+
const wellFormed = await post(UNMATCHED_PATH, WELL_FORMED, user);
151+
152+
expect(unparseable.status).toBe(404);
153+
expect(unparseable.json.success).toBe(false);
154+
expect(unparseable.json.error.code).toBe('ENDPOINT_NOT_FOUND');
155+
expect({ status: wellFormed.status, code: wellFormed.json.error?.code })
156+
.toEqual({ status: unparseable.status, code: unparseable.json.error.code });
157+
// The step asked the matcher for both requests: the 404 is its miss,
158+
// not the scoping test turning the path away before any body could be read.
159+
expect(queries).toEqual([
160+
{ path: UNMATCHED_PATH, method: 'POST' },
161+
{ path: UNMATCHED_PATH, method: 'POST' },
162+
]);
163+
});
164+
}
165+
166+
it('anonymous POST to an authRequired: true endpoint, unparseable body → 401 UNAUTHENTICATED, as for a well-formed one', async () => {
167+
flowRuns.length = 0;
168+
const unparseable = await post(GUARDED_PATH, UNPARSEABLE);
169+
const wellFormed = await post(GUARDED_PATH, WELL_FORMED);
170+
171+
expect(unparseable.status).toBe(401);
172+
expect(unparseable.json.success).toBe(false);
173+
expect(unparseable.json.error.code).toBe('UNAUTHENTICATED');
174+
expect({ status: wellFormed.status, code: wellFormed.json.error?.code })
175+
.toEqual({ status: unparseable.status, code: unparseable.json.error.code });
176+
expect(flowRuns).toEqual([]);
177+
});
178+
179+
it('signed-in POST to an authRequired: true endpoint, unparseable body → the transport\'s 400 refusal, and the target never runs', async () => {
180+
flowRuns.length = 0;
181+
expectRefusal(await post(GUARDED_PATH, UNPARSEABLE, 'u_body_after_match'));
182+
expect(flowRuns).toEqual([]);
183+
});
184+
185+
it('anonymous POST to an authRequired: false endpoint, unparseable body → the transport\'s 400 refusal, and the target never runs', async () => {
186+
flowRuns.length = 0;
187+
expectRefusal(await post(OPEN_PATH, UNPARSEABLE));
188+
expect(flowRuns).toEqual([]);
189+
});
190+
191+
it('signed-in POST to an authRequired: true endpoint, readable body → the target runs on the parsed body', async () => {
192+
flowRuns.length = 0;
193+
const { status, json } = await post(GUARDED_PATH, WELL_FORMED, 'u_body_after_match');
194+
195+
expect(status).toBe(200);
196+
expect(json).toEqual({ success: true, data: { runId: 'run_1', status: 'completed' } });
197+
expect(flowRuns).toHaveLength(1);
198+
expect(flowRuns[0]!.name).toBe('ns_guarded_flow');
199+
expect(flowRuns[0]!.context).toMatchObject({ userId: 'u_body_after_match', params: { days: 30 } });
200+
});
201+
});

‎packages/runtime/src/dispatcher-plugin.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2288,7 +2288,15 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu
22882288
path,
22892289
query: req.query ?? {},
22902290
headers: req.headers ?? {},
2291-
body: req.body,
2291+
// [#24252] Deferred, ⛔ never `req.body`: this
2292+
// object is built before the step matches an
2293+
// endpoint or runs its policies, and reading a
2294+
// body the transport could not parse here would
2295+
// answer its `400` ahead of the miss's `404`
2296+
// and `authRequired`'s `401`. The step reads it
2297+
// with `readDispatchedBody` once the policy
2298+
// chain admitted the caller.
2299+
body: deferRequestBody(req),
22922300
...(req.remoteAddress ? { remoteAddress: req.remoteAddress } : {}),
22932301
},
22942302
deps: {

0 commit comments

Comments
 (0)