Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/strict-number-parameters.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"chanfana": patch
---

Reject partially numeric query, path, and header parameters instead of silently accepting their numeric prefix.
5 changes: 4 additions & 1 deletion src/parameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { AnyZodObject, RouteParameter } from "./types";

extendZodWithOpenApi(z);

const DECIMAL_NUMBER_PATTERN = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;

/**
* Helper function to unwrap optional/nullable types and check instanceof.
* Handles Zod's wrapper types like ZodOptional, ZodNullable, ZodDefault.
Expand Down Expand Up @@ -84,7 +86,8 @@ export function coerceInputs(data: Record<string, any>, schema?: RouteParameter)
params[key] = _val === "true";
}
} else if (unwrapAndCheck(innerType, z.ZodNumber) && typeof params[key] === "string") {
params[key] = Number.parseFloat(params[key]);
const numericValue = params[key].trim();
params[key] = DECIMAL_NUMBER_PATTERN.test(numericValue) ? Number(numericValue) : Number.NaN;
} else if (unwrapAndCheck(innerType, z.ZodBigInt) && typeof params[key] === "string") {
try {
params[key] = BigInt(params[key]);
Expand Down
62 changes: 62 additions & 0 deletions tests/integration/parameters.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,69 @@
import { AutoRouter } from "itty-router";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { fromIttyRouter, OpenAPIRoute } from "../../src";
import { ToDoList, todoRouter } from "../router";
import { buildRequest, findError } from "../utils";

class NumericParametersEndpoint extends OpenAPIRoute {
schema = {
request: {
params: z.object({ pathValue: z.number() }),
query: z.object({ queryValue: z.number() }),
headers: z.object({ "x-number": z.number() }),
},
};

async handle() {
return this.getValidatedData<typeof this.schema>();
}
}

const numericParametersRouter = fromIttyRouter(AutoRouter());
numericParametersRouter.get("/numeric-parameters/:pathValue", NumericParametersEndpoint);

describe("numeric parameter coercion", () => {
it.each([
["query", "https://example.com/numeric-parameters/1?queryValue=12abc", "1"],
["path", "https://example.com/numeric-parameters/12abc?queryValue=1", "1"],
["header", "https://example.com/numeric-parameters/1?queryValue=1", "12abc"],
])("rejects a partially numeric %s parameter", async (_location, url, headerValue) => {
const response = await numericParametersRouter.fetch(new Request(url, { headers: { "x-number": headerValue } }));

expect(response.status).toBe(400);
});

it.each([
["empty query", "https://example.com/numeric-parameters/1?queryValue=", "1"],
["empty header", "https://example.com/numeric-parameters/1?queryValue=1", ""],
["whitespace query", "https://example.com/numeric-parameters/1?queryValue=%20%20%20", "1"],
["whitespace path", "https://example.com/numeric-parameters/%20%20%20?queryValue=1", "1"],
["whitespace header", "https://example.com/numeric-parameters/1?queryValue=1", " "],
["hex query", "https://example.com/numeric-parameters/1?queryValue=0x10", "1"],
["binary path", "https://example.com/numeric-parameters/0b10?queryValue=1", "1"],
["octal header", "https://example.com/numeric-parameters/1?queryValue=1", "0o10"],
])("rejects an unsupported %s parameter", async (_case, url, headerValue) => {
const response = await numericParametersRouter.fetch(new Request(url, { headers: { "x-number": headerValue } }));

expect(response.status).toBe(400);
});

it("preserves signed decimals and exponent notation", async () => {
const response = await numericParametersRouter.fetch(
new Request("https://example.com/numeric-parameters/-.5?queryValue=%2B1.25e2", {
headers: { "x-number": "-2.5E-1" },
}),
);

expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({
params: { pathValue: -0.5 },
query: { queryValue: 125 },
headers: { "x-number": -0.25 },
});
});
});

describe("queryParametersValidation", () => {
it("requiredFields", async () => {
const request = await todoRouter.fetch(buildRequest({ method: "GET", path: "/todos" }));
Expand Down
Loading