Validate tool params against their schemas on both dispatch paths

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()`.
This commit is contained in:
gitea committed 2026-09-30 01:15:42 +08:00
1 parent a55015ca26
commit 289ef664da
7 files changed
+272 -8

No files matched your search

+5 -1
View File
@@ -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 });
}
+9 -2
View File
@@ -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(),
+1
View File
@@ -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,
+91
View File
@@ -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, unknown>): 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<string, unknown>;
// /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();
});
});
+104
View File
@@ -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<string, unknown>): Record<string, unknown> {
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<string, unknown>): Record<string, unknown> {
const shape = (schema as z.ZodObject<z.ZodRawShape>).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;
}
+36 -5
View File
@@ -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<unknown> {
// 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<unknown>;
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);
}
}
+26
View File
@@ -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);