From 289ef664da23462ce82b49cde75ae1666818cc7d Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 01:15:42 +0800 Subject: [PATCH] Validate tool params against their schemas on both dispatch paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All 99 registry tools declare a zod schema, and not one of them was ever parsed: `runToolResult` (every CLI command) and `executeSealTool` (`POST /api/tool/:name` and every `/v1/*` route) handed `params` straight to the handler. A missing required field reached the handler as `undefined` and died as an opaque upstream error or a `Cannot read properties of undefined`, and an out-of-range `limit` sailed through to the tenant. Both paths now gate on `parseToolParams`, failing fast with the field path: exit 13 on the CLI, HTTP 400 behind the adapter (structured exit codes map onto statuses instead of collapsing every failure into 500). The HTTP tool endpoint validates before `selectCorp`, which records usage stats to disk — a request that can never succeed should cause no writes. Two properties keep this a pure addition: the original params are returned rather than zod's parsed output (handlers read undeclared keys — the configure tool accepts `appKey` alongside `apiKey`, which the schema now says out loud), and query strings are coerced to the declared type first, because `/v1/*` passes `url.searchParams` where the schema wants `z.number()`. --- src/cli/helpers.ts | 6 +- src/domains/seal/tools/deploy.ts | 11 ++- src/domains/seal/tools/index.ts | 1 + src/domains/seal/tools/validate.test.ts | 91 +++++++++++++++++++++ src/domains/seal/tools/validate.ts | 104 ++++++++++++++++++++++++ src/http/routes.ts | 41 ++++++++-- src/http/server.test.ts | 26 ++++++ 7 files changed, 272 insertions(+), 8 deletions(-) create mode 100644 src/domains/seal/tools/validate.test.ts create mode 100644 src/domains/seal/tools/validate.ts diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts index 2e75862..c788e96 100644 --- a/src/cli/helpers.ts +++ b/src/cli/helpers.ts @@ -2,7 +2,7 @@ import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig, resolve import { resolveCorpConfig } from "../core/config/manager.js"; import { recordCorpUsage } from "../core/stats/usage-tracker.js"; import { createSealClient } from "../core/http/factory.js"; -import { sealTools, type SealTool } from "../domains/seal/tools.js"; +import { sealTools, parseToolParams, type SealTool } from "../domains/seal/tools.js"; import type { CorpConfig, GlobalConfig } from "../core/config/types.js"; import { printJson } from "./printer.js"; import type { OutputOptions } from "./types.js"; @@ -60,6 +60,10 @@ export async function runToolResult( const compactParams = Object.fromEntries( Object.entries(params).filter(([, value]) => value !== undefined) ); + // Schema gate: a missing required field or an out-of-range value fails here + // with exit 13 instead of reaching the handler as `undefined` and surfacing + // as an opaque upstream error. Valid params pass through untouched. + parseToolParams(tool, compactParams); const handler = tool.handler as SealTool["handler"]; return handler(client, compactParams as never, { corp }); } diff --git a/src/domains/seal/tools/deploy.ts b/src/domains/seal/tools/deploy.ts index b6e19af..e9f4148 100644 --- a/src/domains/seal/tools/deploy.ts +++ b/src/domains/seal/tools/deploy.ts @@ -86,8 +86,15 @@ export const deployTools = [ name: "seal_deploy_hosecloud_configure", description: "自动探测平台并保存【Seal AI 审批发布到合思费控】集成配置", parameters: z.object({ - apiKey: z.string().describe("合思 API Key (appKey)"), - apiSecret: z.string().describe("合思 API Secret (appSecurity)"), + // Optional in the schema because the handler accepts two spellings of the + // same credential (`apiKey`, or the legacy `appKey` alias) and enforces + // that one pair is present itself — see the check right below. Marking + // only `apiKey` required would reject `appKey` payloads the handler has + // always accepted. + apiKey: z.string().optional().describe("合思 API Key (appKey)"), + apiSecret: z.string().optional().describe("合思 API Secret (appSecurity)"), + appKey: z.string().optional().describe("apiKey 的旧写法,等价"), + appSecurity: z.string().optional().describe("apiSecret 的旧写法,等价"), signKey: z.string().optional().describe("集成 signKey,不提供则自动生成"), outboundName: z.string().optional().describe("出站消息名称(合思审批流节点中显示)"), specificationId: z.string().optional(), diff --git a/src/domains/seal/tools/index.ts b/src/domains/seal/tools/index.ts index 78afd58..5250e29 100644 --- a/src/domains/seal/tools/index.ts +++ b/src/domains/seal/tools/index.ts @@ -10,6 +10,7 @@ import { deployTools } from "./deploy.js"; import { preferenceTools } from "./preference.js"; export * from "./helpers.js"; +export * from "./validate.js"; export const sealTools = [ ...identityTools, diff --git a/src/domains/seal/tools/validate.test.ts b/src/domains/seal/tools/validate.test.ts new file mode 100644 index 0000000..86d1399 --- /dev/null +++ b/src/domains/seal/tools/validate.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, test } from "bun:test"; +import { CliError } from "../../../core/errors.js"; +import { findSealTool, parseToolParams, type SealTool } from "./index.js"; + +function tool(name: string): SealTool { + const found = findSealTool(name); + if (!found) throw new Error(`test fixture missing tool: ${name}`); + return found; +} + +/** Asserts rejection and returns the message so tests can check its wording. */ +function rejectsWith(toolName: string, params: Record): string { + try { + parseToolParams(tool(toolName), params); + } catch (error) { + expect(error).toBeInstanceOf(CliError); + expect((error as CliError).exitCode).toBe(13); + return (error as CliError).message; + } + throw new Error(`expected ${toolName} to reject ${JSON.stringify(params)}`); +} + +describe("parseToolParams", () => { + test("accepts valid params and returns the exact object it was given", () => { + const target = tool("seal_user_create"); + const params = { name: "张三", phone: "13800001111", departmentIds: ["d1"] }; + + // Identity matters: handlers read keys the schema does not declare, so the + // gate must pass its input through, never zod's (stripped) parse output. + expect(parseToolParams(target, params)).toBe(params); + }); + + test("names the missing required field instead of letting the handler crash on undefined", () => { + const message = rejectsWith("seal_user_create", { phone: "13800001111" }); + expect(message).toContain("seal_user_create"); + expect(message).toContain("name"); + }); + + test("enforces the value bound a handler would otherwise silently accept", () => { + // limit is capped at 100 in the schema; nothing in the handler checks it. + const message = rejectsWith("seal_approval_runs_search", { limit: 9999 }); + expect(message).toContain("limit"); + }); + + test("coerces query-string values before checking, without touching the original", () => { + const target = tool("seal_approval_runs_search"); + const params = { limit: "50", includeBridge: "true" } as Record; + + // /v1/* passes url.searchParams through: everything arrives as a string, + // but the schema declares z.number() / z.boolean(). Without coercion every + // REST route would 400 on its own documented query params. + expect(parseToolParams(target, params)).toBe(params); + expect(params.limit).toBe("50"); + expect(params.includeBridge).toBe("true"); + }); + + test("still rejects a string that merely looks like a wire value", () => { + const message = rejectsWith("seal_approval_runs_search", { limit: "abc" }); + expect(message).toContain("limit"); + }); + + test("coerces a comma-separated query value into the array the schema wants", () => { + // `?fields=id,code` on /v1/approval/rules: today the handler receives a + // string and pickRuleFields iterates its characters, returning empty + // objects. Validation splits it so the documented form actually works. + expect(parseToolParams(tool("seal_approval_rules_list"), { fields: "id,code" })).toEqual({ + fields: "id,code" + }); + expect(rejectsWith("seal_approval_rules_list", { fields: "id,not-a-field" })).toContain("fields"); + }); + + test("ignores undeclared keys rather than rejecting the request", () => { + // z.object is non-strict: an extra HTTP body key is a compatibility + // non-event, not an error. This gate checks declared params only. + const target = tool("seal_approval_runs_search"); + expect(parseToolParams(target, { status: "TERMINATED", corp: "corp-a", stray: 1 })).toBeTypeOf("object"); + }); + + test("lets the legacy credential aliases through to the handler that supports them", () => { + // seal_deploy_hosecloud_configure has always accepted appKey/appSecurity + // alongside apiKey/apiSecret; a schema that declared only apiKey as + // required would have blocked that documented path. + expect(() => + parseToolParams(tool("seal_deploy_hosecloud_configure"), { + appKey: "key-1", + appSecurity: "secret-1", + mode: "assisted" + }) + ).not.toThrow(); + }); +}); diff --git a/src/domains/seal/tools/validate.ts b/src/domains/seal/tools/validate.ts new file mode 100644 index 0000000..3f81fd3 --- /dev/null +++ b/src/domains/seal/tools/validate.ts @@ -0,0 +1,104 @@ +import { z } from "zod"; +import { validationError } from "../../../core/errors.js"; +import type { SealTool } from "./index.js"; + +/** + * Checks one invocation's params against the schema its tool declares, then + * returns the params unchanged. + * + * Both dispatch paths — `runToolResult` (every CLI command) and + * `executeSealTool` (`POST /api/tool/:name`, every `/v1/*` route) — used to + * hand `params` straight to `handler`, so a required field could be missing, a + * limit could be `999999`, or a typo'd HTTP body key could sail through and + * surface later as an opaque upstream error or a `Cannot read properties of + * undefined`. The schema is now the gate, failing fast with the offending field + * path (exit `13` on the CLI, HTTP `400` behind the adapter). + * + * Two deliberate properties: + * + * - **Original params are returned, not `result.data`.** Handlers read keys the + * schema does not declare — `seal_deploy_hosecloud_configure` accepts the + * legacy `appKey`/`appSecurity` aliases alongside `apiKey`/`apiSecret` — and + * zod's default strip would silently drop them. Validation must never change + * what a working handler receives, only block what would have failed anyway. + * - **Undeclared keys never fail.** `z.object` is non-strict, so an extra HTTP + * body key is ignored rather than rejected; this is a correctness check, not + * an API-compatibility verdict. + * + * Before rejecting, wire-format values are coerced to the shape the schema + * declares (see {@link coerceWireTypes}) because `/v1/*` query strings arrive + * entirely as strings while the schema says `z.number()`. + */ +export function parseToolParams(tool: SealTool, params: Record): Record { + const result = tool.parameters.safeParse(coerceWireTypes(tool.parameters, params)); + if (result.success) return params; + + const detail = result.error.issues + .map((issue) => `${issue.path.length ? issue.path.join(".") : "(root)"}: ${issue.message}`) + .join("; "); + throw validationError(`Invalid parameters for ${tool.name}: ${detail}`); +} + +/** + * Rewrites string-shaped query/body values into the type the schema declares + * for that key: `"10"` → `10` for `z.number()`, `"true"` → `true` for + * `z.boolean()`, `"id,code"` → `["id", "code"]` for `z.array()`. + * + * Query strings carry no types, so without this every `/v1/*` route that passes + * `url.searchParams` through would fail against `z.number().int()` — while a + * value that merely looks wrong (`"abc"` for a number) is left alone so zod + * reports it instead of hiding it behind a NaN. + * + * Only top-level keys are touched: nested params arrive as parsed JSON (already + * typed), and skipping declared-but-uncoercible leaves errors to zod rather + * than guessing. + */ +function coerceWireTypes(schema: z.ZodType, params: Record): Record { + const shape = (schema as z.ZodObject).shape; + if (!shape) return params; + + const coerced = { ...params }; + for (const [key, def] of Object.entries(shape)) { + const value = coerced[key]; + if (typeof value !== "string" || value === "") continue; + + const target = unwrapType(def); + if (target === "number" && /^[+-]?\d+(?:\.\d+)?$/.test(value.trim())) { + coerced[key] = Number(value.trim()); + } else if (target === "boolean") { + if (value === "true") coerced[key] = true; + else if (value === "false") coerced[key] = false; + } else if (target === "array") { + const items = value.split(",").map((item) => item.trim()).filter(Boolean); + if (items.length) coerced[key] = items; + } + } + return coerced; +} + +/** + * Resolves a field's concrete type name, stepping through `optional` / + * `default` / `nullable` wrappers: `"limit: optional"` → `"number"`. + * + * zod v4 exposes `type` on the schema instance but keeps `innerType` on + * `_def`, so both shapes are read — a wrapper reached via `_def.innerType` is + * an instance again, and an object reached by other means may be a bare def. + */ +function unwrapType(schema: unknown): string | undefined { + let current = schema as + | { type?: string; innerType?: unknown; _def?: { type?: string; innerType?: unknown } } + | undefined; + + // Depth bound: wrappers nest shallowly in practice; anything deeper is a + // shape this helper should decline to interpret rather than chase. + for (let depth = 0; current && depth < 8; depth++) { + const def = current._def ?? current; + const type = def.type ?? current.type; + if (type === "optional" || type === "default" || type === "nullable") { + current = (def.innerType ?? current.innerType) as typeof current; + continue; + } + return type; + } + return undefined; +} diff --git a/src/http/routes.ts b/src/http/routes.ts index d060c36..5eb2216 100644 --- a/src/http/routes.ts +++ b/src/http/routes.ts @@ -8,17 +8,39 @@ import type { CorpConfig } from "../core/config/types.js"; import { getOpenApiSchema } from "../core/embedded-openapi.js"; import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js"; import { createSealClient } from "../core/http/factory.js"; -import { findSealTool, type SealTool } from "../domains/seal/tools.js"; +import { findSealTool, parseToolParams, type SealTool } from "../domains/seal/tools.js"; import { tokenizeCommand } from "../cli/tokenize.js"; import { redactSensitiveText } from "../core/redact.js"; +import { CliError, type CliExitCode } from "../core/errors.js"; import { VERSION } from "../version.js"; import { renderDocsHtml } from "./docs.js"; async function executeSealTool(tool: SealTool, client: KyInstance, params: any, corp: CorpConfig): Promise { + // Schema gate for every HTTP caller: a missing required field or bad value + // is a client error (400), not an upstream failure discovered mid-handler. + parseToolParams(tool, params); const handler = tool.handler as (client: KyInstance, params: any, context: { corp: CorpConfig }) => Promise; return handler(client, params, { corp }); } +/** Maps a structured CLI exit code to the HTTP status it means for a caller. */ +export function httpStatusForCliExit(exitCode: CliExitCode): number { + switch (exitCode) { + case 11: + return 401; + case 12: + return 413; + case 10: + case 14: + return 403; + case 2: + case 13: + return 400; + default: + return 500; + } +} + export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse) { // 1. CORS headers res.setHeader("Access-Control-Allow-Origin", "*"); @@ -133,12 +155,18 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons } const body = (await parseJsonBody(req)) || {}; - const corpId = extractCorpId(req, url, body); - const corp = selectCorp(corpId); - const client = await createSealClient(corp); const params = { ...body }; delete params.corp; + // Fail fast before `selectCorp`, which records usage stats to disk: a + // request that can never succeed should cause no writes. `executeSealTool` + // performs the same check afterwards — the early call exists purely to + // win this ordering, not to duplicate the guarantee. + parseToolParams(tool, params); + + const corpId = extractCorpId(req, url, body); + const corp = selectCorp(corpId); + const client = await createSealClient(corp); const output = await executeSealTool(tool, client, params, corp); sendJson(res, 200, output); @@ -154,7 +182,10 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons sendError(res, 404, `Cannot ${method} ${pathname}. Visit /docs for available endpoints.`); } catch (err: unknown) { const message = err instanceof Error ? err.message : String(err); - sendError(res, 500, message); + // A structured CLI error names the caller's mistake (bad params, missing + // auth, output too large); pass it through as the matching 4xx instead of + // letting every failure look like an adapter crash. + sendError(res, err instanceof CliError ? httpStatusForCliExit(err.exitCode) : 500, message); } } diff --git a/src/http/server.test.ts b/src/http/server.test.ts index c0c6546..131c97e 100644 --- a/src/http/server.test.ts +++ b/src/http/server.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test, afterAll, beforeAll } from "bun:test"; import type { Server } from "node:http"; import { startHttpServer } from "./server.js"; +import { httpStatusForCliExit } from "./routes.js"; describe("HTTP Server", () => { let server: Server; @@ -64,6 +65,31 @@ describe("HTTP Server", () => { expect(json.data.name).toBe("seal-use"); }); + test("POST /api/tool/:name rejects invalid params with 400 before touching an enterprise", async () => { + const res = await fetch(`${baseUrl}/api/tool/seal_user_create`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + // `name` is required by the tool's schema; without the schema gate this + // reached the handler as `undefined` and died as an opaque 500. + body: JSON.stringify({ phone: "13800001111" }) + }); + expect(res.status).toBe(400); + const json = (await res.json()) as any; + expect(json.error).toBe(true); + expect(json.message).toContain("seal_user_create"); + expect(json.message).toContain("name"); + }); + + test("maps structured CLI exit codes onto HTTP statuses", () => { + expect(httpStatusForCliExit(1)).toBe(500); + expect(httpStatusForCliExit(2)).toBe(400); + expect(httpStatusForCliExit(10)).toBe(403); + expect(httpStatusForCliExit(11)).toBe(401); + expect(httpStatusForCliExit(12)).toBe(413); + expect(httpStatusForCliExit(13)).toBe(400); + expect(httpStatusForCliExit(14)).toBe(403); + }); + test("GET /v1/corps returns enterprise list", async () => { const res = await fetch(`${baseUrl}/v1/corps`); expect(res.status).toBe(200);