diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 49e742b936c..dca9159c37e 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -110,6 +110,11 @@ jobs: if: ${{ !cancelled() }} run: nix develop --command just js bench varint + # Report malformed-input growth separately from deterministic unit tests. + - name: JS parsing benchmark + if: ${{ !cancelled() }} + run: nix develop --command just js bench parsing + # Bytes and time for lite-06 against lite-07 frames, groups, and requests. No # threshold: it only has to keep running. - name: JS lite varint benchmark diff --git a/js/justfile b/js/justfile index 03fadd9333a..63d4a2e1a89 100644 --- a/js/justfile +++ b/js/justfile @@ -43,7 +43,7 @@ test: bun test common/declarations.test.ts common/deps.test.ts common/worklet.test.ts bun run --filter='*' --elide-lines=0 test -# Run one net benchmark: broadcasts, forward, reader, frames, track, varint, or lite-varint. +# Run one net benchmark: broadcasts, forward, reader, frames, track, varint, lite-varint, or parsing. bench name: bun install --frozen-lockfile bun net/bench/{{ name }}.ts diff --git a/js/net/bench/parsing.ts b/js/net/bench/parsing.ts new file mode 100644 index 00000000000..6499074ada0 --- /dev/null +++ b/js/net/bench/parsing.ts @@ -0,0 +1,42 @@ +/** Measure malformed certificate and path rejection as their inputs grow. */ +import { certificateHash } from "../src/connection/connect.ts"; +import * as Path from "../src/path.ts"; + +let rejected = 0; + +console.log("parser,input_bytes,ns_per_op"); +for (const parser of ["pem", "path"] as const) { + for (const count of [256, 1024, 4096, 16384]) { + const input = parser === "pem" ? "-----BEGIN CERTIFICATE-----a".repeat(count) : "a/".repeat(count); + // Materialize the string before timing, so rope flattening isn't mistaken for parsing. + input.charCodeAt(input.length - 1); + const reject = async () => { + try { + if (parser === "pem") await certificateHash(input); + else Path.encode(input as Path.Valid); + } catch (error) { + const expected = parser === "pem" ? "armor" : "parts"; + if (!(error instanceof Error) || !error.message.includes(expected)) throw error; + rejected++; + return; + } + throw new Error(`${parser} accepted malformed input`); + }; + + // Calibrate independently so a slow baseline remains practical to compare. + let runs = 0; + const warmup = performance.now(); + do { + await reject(); + runs++; + } while (performance.now() - warmup < 20); + let best = Number.POSITIVE_INFINITY; + for (let rep = 0; rep < 5; rep++) { + const start = performance.now(); + for (let i = 0; i < runs; i++) await reject(); + best = Math.min(best, ((performance.now() - start) * 1e6) / runs); + } + console.log(`${parser},${input.length},${best.toFixed(1)}`); + } +} +if (rejected === 0) throw new Error("benchmark did no work"); diff --git a/js/net/src/connection/cert.test.ts b/js/net/src/connection/cert.test.ts index 2edced00b25..a94e7096317 100644 --- a/js/net/src/connection/cert.test.ts +++ b/js/net/src/connection/cert.test.ts @@ -24,6 +24,28 @@ test("certificateHash rejects a PEM string without armor", async () => { await expect(certificateHash("YWJj")).rejects.toThrow(/armor/); }); +test("certificateHash rejects incomplete or empty PEM armor", async () => { + for (const pem of [ + "-----BEGIN CERTIFICATE-----\nYWJj\n", + "-----END CERTIFICATE-----\nYWJj\n-----BEGIN CERTIFICATE-----", + "-----BEGIN CERTIFICATE----------END CERTIFICATE-----", + "-----BEGIN CERTIFICATE-----\n \t\r\n-----END CERTIFICATE-----", + "-----BEGIN CERTIFICATE-----a".repeat(256), + ]) { + await expect(certificateHash(pem)).rejects.toThrow(/armor/); + } +}); + +test("certificateHash preserves whitespace and first-certificate handling", async () => { + const pem = + "prefix -----END CERTIFICATE-----\n-----BEGIN CERTIFICATE-----\r\nY W\tJj\n-----END CERTIFICATE-----\n-----BEGIN CERTIFICATE-----\nZA==\n-----END CERTIFICATE----- suffix"; + expect(Hex.fromBytes(await certificateHash(pem))).toBe(ABC_SHA256); +}); + +test("certificateHash rejects invalid base64 inside PEM armor", async () => { + await expect(certificateHash("-----BEGIN CERTIFICATE-----!-----END CERTIFICATE-----")).rejects.toThrow(); +}); + test("hex round-trips through fromBytes/toBytes", () => { expect(Hex.fromBytes(Hex.toBytes(ABC_SHA256))).toBe(ABC_SHA256); }); diff --git a/js/net/src/connection/connect.ts b/js/net/src/connection/connect.ts index 28fce7e3764..70d058ec09f 100644 --- a/js/net/src/connection/connect.ts +++ b/js/net/src/connection/connect.ts @@ -385,12 +385,16 @@ type WebTransportHash = NonNullable { - const match = pem.match(/-----BEGIN CERTIFICATE-----([\s\S]+?)-----END CERTIFICATE-----/); - if (!match) { + // indexOf rather than a lazy regex, which goes quadratic on repeated BEGIN lines without an END. + const begin = "-----BEGIN CERTIFICATE-----"; + const start = pem.indexOf(begin); + const end = start < 0 ? -1 : pem.indexOf("-----END CERTIFICATE-----", start + begin.length); + const body = end < 0 ? "" : pem.slice(start + begin.length, end).replace(/\s+/g, ""); + if (!body) { throw new Error("invalid PEM certificate: missing -----BEGIN/END CERTIFICATE----- armor"); } - const binary = atob(match[1].replace(/\s+/g, "")); + const binary = atob(body); const der = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { der[i] = binary.charCodeAt(i); diff --git a/js/net/src/path.test.ts b/js/net/src/path.test.ts index 96ef51fd722..88a32484b8b 100644 --- a/js/net/src/path.test.ts +++ b/js/net/src/path.test.ts @@ -326,3 +326,12 @@ test("encode enforces the max part count", () => { expect(Path.encode(atLimit)).toBe(atLimit); expect(() => Path.encode(`${atLimit}/extra` as Path.Valid)).toThrow(); }); + +test("path limits apply after normalizing separators", () => { + const atLimit = Array(Path.MAX_PARTS).fill("part").join("/"); + expect(Path.decode(`///${atLimit.replaceAll("/", "///")}///`)).toBe(atLimit as Path.Valid); + expect(Path.decode("/".repeat(4096))).toBe(Path.empty()); + expect(Path.encode(Path.empty())).toBe(Path.empty()); + expect(() => Path.decode("a/".repeat(4096))).toThrow(/parts/); + expect(() => Path.encode("a/".repeat(4096) as Path.Valid)).toThrow(/parts/); +}); diff --git a/js/net/src/path.ts b/js/net/src/path.ts index f9de73ac066..873edf022c1 100644 --- a/js/net/src/path.ts +++ b/js/net/src/path.ts @@ -82,8 +82,12 @@ export function decode(raw: string): Valid { * emit a path the remote side is required to reject. */ export function encode(path: Valid): Valid { - if (parts(path).length > MAX_PARTS) { - throw new Error(`path exceeds ${MAX_PARTS} parts`); + // Count separators with an early exit instead of splitting, so a hostile path never allocates per part. + let count = path === "" ? 0 : 1; + for (let i = path.indexOf("/"); i !== -1; i = path.indexOf("/", i + 1)) { + if (++count > MAX_PARTS) { + throw new Error(`path exceeds ${MAX_PARTS} parts`); + } } return path; }