|
| 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 | +}); |
0 commit comments