Skip to content
Merged
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 .github/workflows/nightly.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion js/justfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 42 additions & 0 deletions js/net/bench/parsing.ts
Original file line number Diff line number Diff line change
@@ -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");
22 changes: 22 additions & 0 deletions js/net/src/connection/cert.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
10 changes: 7 additions & 3 deletions js/net/src/connection/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,12 +385,16 @@ type WebTransportHash = NonNullable<WebTransportOptions["serverCertificateHashes

// Strip PEM armor and base64-decode to the raw DER bytes.
function pemToDer(pem: string): Uint8Array<ArrayBuffer> {
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);
Expand Down
9 changes: 9 additions & 0 deletions js/net/src/path.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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/);
});
8 changes: 6 additions & 2 deletions js/net/src/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Loading