Files
unkernel/test/tailscale-h2.test.ts
Pooya Parsa d382f7fa9b js: add a pure-JS Tailscale network device (work in progress)
The guest joins a tailnet from Node or the page: ts2021 control over
WebSocket, DERP relays, WireGuard and the packet filter in JS, loaded as
a separate chunk only when the option is used. SDK net option, CLI
--tailscale* flags and a page panel. Relay only; exit nodes, IPv6 and
real peer traffic are not covered yet.
2026-11-28 22:06:18 +00:00

476 lines
17 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Unit tests for the Tailscale control client's HPACK (RFC 7541 Appendix C
// vectors) and HTTP/2 client (js/core/tailscale/h2.ts), the latter against
// Node's own HTTP/2 server over an in-memory stream pair.
//
// node --test test/tailscale-h2.test.ts
import test, { describe } from "node:test";
import assert from "node:assert/strict";
import http2 from "node:http2";
import { duplexPair, type Duplex } from "node:stream";
import { HpackDecoder, HpackEncoder, HpackError, huffmanDecode, huffmanEncode, type HeaderField } from "../js/core/tailscale/control-hpack.ts";
import { H2Connection, H2Error } from "../js/core/tailscale/h2.ts";
const VECTORS: Record<string, { headers: HeaderField[]; hex: string; tableSize: number }[]> = {
"C.3": [
{
headers: [
[":method", "GET"],
[":scheme", "http"],
[":path", "/"],
[":authority", "www.example.com"],
],
hex: "828684410f7777772e6578616d706c652e636f6d",
tableSize: 57,
},
{
headers: [
[":method", "GET"],
[":scheme", "http"],
[":path", "/"],
[":authority", "www.example.com"],
["cache-control", "no-cache"],
],
hex: "828684be58086e6f2d6361636865",
tableSize: 110,
},
{
headers: [
[":method", "GET"],
[":scheme", "https"],
[":path", "/index.html"],
[":authority", "www.example.com"],
["custom-key", "custom-value"],
],
hex: "828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565",
tableSize: 164,
},
],
"C.4": [
{
headers: [
[":method", "GET"],
[":scheme", "http"],
[":path", "/"],
[":authority", "www.example.com"],
],
hex: "828684418cf1e3c2e5f23a6ba0ab90f4ff",
tableSize: 57,
},
{
headers: [
[":method", "GET"],
[":scheme", "http"],
[":path", "/"],
[":authority", "www.example.com"],
["cache-control", "no-cache"],
],
hex: "828684be5886a8eb10649cbf",
tableSize: 110,
},
{
headers: [
[":method", "GET"],
[":scheme", "https"],
[":path", "/index.html"],
[":authority", "www.example.com"],
["custom-key", "custom-value"],
],
hex: "828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf",
tableSize: 164,
},
],
"C.5": [
{
headers: [
[":status", "302"],
["cache-control", "private"],
["date", "Mon, 21 Oct 2013 20:13:21 GMT"],
["location", "https://www.example.com"],
],
hex: "4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d",
tableSize: 222,
},
{
headers: [
[":status", "307"],
["cache-control", "private"],
["date", "Mon, 21 Oct 2013 20:13:21 GMT"],
["location", "https://www.example.com"],
],
hex: "4803333037c1c0bf",
tableSize: 222,
},
{
headers: [
[":status", "200"],
["cache-control", "private"],
["date", "Mon, 21 Oct 2013 20:13:22 GMT"],
["location", "https://www.example.com"],
["content-encoding", "gzip"],
["set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"],
],
hex: "88c1611d4d6f6e2c203231204f637420323031332032303a31333a323220474d54c05a04677a69707738666f6f3d4153444a4b48514b425a584f5157454f50495541585157454f49553b206d61782d6167653d333630303b2076657273696f6e3d31",
tableSize: 215,
},
],
"C.6": [
{
headers: [
[":status", "302"],
["cache-control", "private"],
["date", "Mon, 21 Oct 2013 20:13:21 GMT"],
["location", "https://www.example.com"],
],
hex: "488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3",
tableSize: 222,
},
{
headers: [
[":status", "307"],
["cache-control", "private"],
["date", "Mon, 21 Oct 2013 20:13:21 GMT"],
["location", "https://www.example.com"],
],
hex: "4883640effc1c0bf",
tableSize: 222,
},
{
headers: [
[":status", "200"],
["cache-control", "private"],
["date", "Mon, 21 Oct 2013 20:13:22 GMT"],
["location", "https://www.example.com"],
["content-encoding", "gzip"],
["set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"],
],
hex: "88c16196d07abe941054d444a8200595040b8166e084a62d1bffc05a839bd9ab77ad94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c003ed4ee5b1063d5007",
tableSize: 215,
},
],
};
const fromHex = (h: string): Uint8Array => Uint8Array.from(Buffer.from(h, "hex"));
const toHex = (b: Uint8Array): string => Buffer.from(b).toString("hex");
describe("hpack", () => {
for (const [name, huffman, tableSize] of [["C.3", false, 4096], ["C.4", true, 4096], ["C.5", false, 256], ["C.6", true, 256]] as const) {
test(`${name} decode`, () => {
const d = new HpackDecoder(tableSize);
for (const v of VECTORS[name]!) {
assert.deepEqual(d.decode(fromHex(v.hex)), v.headers);
assert.equal(d.dynamicTableSize, v.tableSize);
}
});
test(`${name} encode`, () => {
const e = new HpackEncoder(tableSize);
for (const v of VECTORS[name]!) {
assert.equal(toHex(e.encode(v.headers, { huffman })), v.hex);
}
});
}
test("huffman round trip of every byte value", () => {
const all = Uint8Array.from({ length: 256 }, (_, i) => i);
assert.deepEqual(huffmanDecode(huffmanEncode(all)), all);
assert.equal(toHex(huffmanEncode(new TextEncoder().encode("www.example.com"))), "f1e3c2e5f23a6ba0ab90f4ff");
});
test("huffman rejects bad padding and EOS", () => {
// "a" is 00011 (5 bits); padding with zeros is invalid.
assert.throws(() => huffmanDecode(Uint8Array.of(0x18)), HpackError);
// Eight bits of padding (a whole 0xff octet) is invalid.
assert.throws(() => huffmanDecode(Uint8Array.of(0x1f, 0xff)), HpackError);
// EOS (30 ones) inside the string.
assert.throws(() => huffmanDecode(Uint8Array.of(0xff, 0xff, 0xff, 0xff)), HpackError);
assert.deepEqual(huffmanDecode(Uint8Array.of(0x1f)), Uint8Array.of(0x61));
});
test("table size update, multi-octet integers, never-indexed literals", () => {
const d = new HpackDecoder(4096);
d.decode(fromHex(VECTORS["C.3"]![0]!.hex));
assert.equal(d.dynamicTable.length, 1);
// Size update to 0 clears the table; then a never-indexed literal (C.2.3).
const block = fromHex("20" + "100870617373776f726406736563726574");
assert.deepEqual(d.decode(block), [["password", "secret"]]);
assert.equal(d.dynamicTable.length, 0);
// Size update above the allowed maximum.
assert.throws(() => d.decode(fromHex("3fe21f")), HpackError); // 4097 = 31 + 4066
// C.1.2: 1337 with a 5-bit prefix, as a table size update of 1337.
d.decode(fromHex("3f9a0a"));
assert.equal(d.dynamicTableSize, 0);
// Encoder: a table size change is sent at the start of the next block.
const e = new HpackEncoder();
e.setMaxTableSize(1337);
assert.equal(toHex(e.encode([[":method", "GET"]])), "3f9a0a82");
});
test("a decoded header list is capped (a small block naming a large entry many times)", () => {
const d = new HpackDecoder();
// One 4000-byte literal added to the table, then 100 references to it (index 62).
const value = "x".repeat(4000);
const lit = Uint8Array.of(0x40, 0x01, 0x61, 0x7f, ...[4000 - 127].flatMap((n) => [0x80 | (n & 0x7f), n >> 7]), ...new TextEncoder().encode(value));
assert.equal(d.decode(lit)[0]![1].length, 4000);
assert.throws(() => d.decode(new Uint8Array(100).fill(0xbe)), /header list over/);
});
test("index out of range", () => {
assert.throws(() => new HpackDecoder().decode(Uint8Array.of(0xbe)), HpackError);
assert.throws(() => new HpackDecoder().decode(Uint8Array.of(0x80)), HpackError);
});
});
/** An HTTP/2 client connection to a Node HTTP/2 server through a stream pair. */
function connect(handler: (req: http2.Http2ServerRequest, res: http2.Http2ServerResponse) => void, opts: { onSession?: (s: http2.ServerHttp2Session) => void; settings?: http2.Settings } = {}) {
const server = http2.createServer({ settings: opts.settings }, handler);
if (opts.onSession) server.on("session", opts.onSession);
const [clientSide, serverSide] = duplexPair();
server.emit("connection", serverSide);
const h2: H2Connection = new H2Connection({
write: (data) => { clientSide.write(data); },
close: () => { clientSide.end(); },
});
const closed = new Promise<Error | undefined>((resolve) => {
h2.onclose = resolve;
});
(clientSide as Duplex).on("data", (chunk: Buffer) => h2.receive(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.length)));
clientSide.on("end", () => h2.transportClosed());
clientSide.on("error", () => h2.transportClosed());
const done = () => {
h2.close();
server.close();
serverSide.destroy();
};
return { h2, closed, done, server };
}
const AUTH = "example.test";
describe("h2 against node:http2", () => {
test("GET and POST JSON", async () => {
const c = connect((req, res) => {
const parts: Buffer[] = [];
req.on("data", (d: Buffer) => parts.push(d));
req.on("end", () => {
res.setHeader("content-type", "application/json");
res.setHeader("x-custom", "Hello, World ~ with huffman");
res.end(JSON.stringify({ method: req.method, path: req.url, auth: req.headers[":authority"], ct: req.headers["content-type"], body: Buffer.concat(parts).toString() }));
});
});
try {
await c.h2.ready;
const r1 = await c.h2.request({ path: "/a?b=c", authority: AUTH });
assert.equal(r1.status, 200);
assert.equal(r1.header("x-custom"), "Hello, World ~ with huffman");
assert.deepEqual(await r1.json(), { method: "GET", path: "/a?b=c", auth: AUTH, body: "" });
const r2 = await c.h2.request({ path: "/p", authority: AUTH, body: '{"x":1}', headers: { "Content-Type": "application/json" } });
assert.deepEqual(await r2.json(), { method: "POST", path: "/p", auth: AUTH, ct: "application/json", body: '{"x":1}' });
assert.equal(c.h2.activeStreams, 0);
} finally {
c.done();
}
});
test("large bodies both ways (flow control)", async () => {
const size = 9 << 20; // over the 4 MiB stream window and the 64 KiB default send window
const c = connect((req, res) => {
let n = 0;
let sum = 0;
req.on("data", (d: Buffer) => { n += d.length; for (const b of d) sum = (sum + b) % 65521; });
req.on("end", () => {
res.setHeader("x-got", `${n}:${sum}`);
const chunk = Buffer.alloc(1 << 16);
for (let i = 0; i < chunk.length; i++) chunk[i] = i & 0xff;
let left = size;
const pump = () => {
while (left > 0) {
const part = chunk.subarray(0, Math.min(left, chunk.length));
left -= part.length;
if (!res.write(part)) return void res.once("drain", pump);
}
res.end();
};
pump();
});
});
try {
const body = new Uint8Array(3 << 20);
let sum = 0;
for (let i = 0; i < body.length; i++) { body[i] = (i * 7) & 0xff; sum = (sum + body[i]!) % 65521; }
const r = await c.h2.request({ path: "/big", authority: AUTH, body });
assert.equal(r.header("x-got"), `${body.length}:${sum}`);
const got = await r.bytes();
assert.equal(got.length, size);
assert.equal(got[size - 1], (size - 1) & 0xff);
} finally {
c.done();
}
});
test("many concurrent streams", async () => {
const c = connect((req, res) => {
setTimeout(() => res.end(req.url), 5);
});
try {
const all = await Promise.all(Array.from({ length: 40 }, (_, i) => c.h2.request({ path: `/${i}`, authority: AUTH }).then((r) => r.text())));
assert.deepEqual(all, Array.from({ length: 40 }, (_, i) => `/${i}`));
} finally {
c.done();
}
});
// Node's server frees a stream slot only after its JS side has closed the
// stream, so it refuses streams the protocol allows: this limit is tested
// against a frame-level fake server instead.
test("MAX_CONCURRENT_STREAMS is respected (fake server)", async () => {
const [clientSide, serverSide] = duplexPair();
const h2 = new H2Connection({ write: (d) => { clientSide.write(d); }, close: () => { clientSide.end(); } });
clientSide.on("data", (b: Buffer) => h2.receive(new Uint8Array(b)));
const frame = (type: number, flags: number, id: number, payload: Uint8Array) => {
const f = Buffer.alloc(9 + payload.length);
f.writeUIntBE(payload.length, 0, 3);
f[3] = type;
f[4] = flags;
f.writeUInt32BE(id, 5);
f.set(payload, 9);
serverSide.write(f);
};
let buf = Buffer.alloc(0);
let prefaceSeen = false;
let active = 0;
let peak = 0;
serverSide.on("data", (b: Buffer) => {
buf = Buffer.concat([buf, b]);
if (!prefaceSeen) {
if (buf.length < 24) return;
buf = buf.subarray(24);
prefaceSeen = true;
}
while (buf.length >= 9 && buf.length >= 9 + buf.readUIntBE(0, 3)) {
const len = buf.readUIntBE(0, 3);
const type = buf[3]!;
const id = buf.readUInt32BE(5) & 0x7fffffff;
buf = buf.subarray(9 + len);
if (type === 1) {
active++;
peak = Math.max(peak, active);
// :status 200 (static index 8), then a body and END_STREAM.
setTimeout(() => {
active--;
frame(1, 4, id, Uint8Array.of(0x88));
frame(0, 1, id, new TextEncoder().encode(`#${id}`));
}, 3);
}
}
});
const settings = Buffer.alloc(6);
settings.writeUInt16BE(3, 0);
settings.writeUInt32BE(2, 2);
frame(4, 0, 0, settings);
await h2.ready;
const all = await Promise.all(Array.from({ length: 10 }, () => h2.request({ path: "/", authority: AUTH }).then((r) => r.text())));
assert.deepEqual(all, Array.from({ length: 10 }, (_, i) => `#${2 * i + 1}`));
assert.equal(peak, 2);
h2.close();
serverSide.destroy();
});
test("a header block that keeps growing through CONTINUATION frames ends the connection", async () => {
const sent: Uint8Array[] = [];
const h2 = new H2Connection({ write: (d) => { sent.push(d); }, close: () => {} });
let closed: Error | undefined;
h2.onclose = (e) => (closed = e);
const frame = (type: number, flags: number, id: number, payload: Uint8Array) => {
const f = new Uint8Array(9 + payload.length);
f[0] = payload.length >> 16; f[1] = (payload.length >> 8) & 255; f[2] = payload.length & 255;
f[3] = type; f[4] = flags; f[8] = id;
f.set(payload, 9);
h2.receive(f);
};
frame(4, 0, 0, new Uint8Array(0));
const r = h2.request({ path: "/", authority: AUTH });
frame(1, 0, 1, new Uint8Array(16384)); // HEADERS without END_HEADERS
for (let i = 0; i < 8 && !closed; i++) frame(9, 0, 1, new Uint8Array(16384));
assert.match(String(closed?.message), /header block over 65536 bytes/);
await assert.rejects(r);
});
test("streaming response body arrives before the end", async () => {
let finish!: () => void;
const c = connect((_req, res) => {
res.write("first;");
finish = () => res.end("last");
});
try {
const r = await c.h2.request({ path: "/s", authority: AUTH });
const reader = r.body.getReader();
const first = await reader.read();
assert.equal(new TextDecoder().decode(first.value), "first;");
finish();
const second = await reader.read();
assert.equal(new TextDecoder().decode(second.value), "last");
assert.equal((await reader.read()).done, true);
} finally {
c.done();
}
});
test("RST_STREAM from the server errors the body", async () => {
const c = connect((req, res) => {
res.write("partial");
setTimeout(() => req.stream.close(http2.constants.NGHTTP2_INTERNAL_ERROR), 10);
});
try {
const r = await c.h2.request({ path: "/rst", authority: AUTH });
await assert.rejects(r.bytes(), (e: H2Error) => e instanceof H2Error && e.code === 2);
// The connection stays usable.
assert.equal(c.h2.closed, false);
} finally {
c.done();
}
});
test("abort signal resets the stream", async () => {
let serverClosed!: () => void;
const sawClose = new Promise<void>((r) => (serverClosed = r));
const c = connect((req) => {
req.stream.on("close", () => serverClosed());
});
try {
const ac = new AbortController();
const p = c.h2.request({ path: "/hang", authority: AUTH, signal: ac.signal });
setTimeout(() => ac.abort(new Error("stop")), 20);
await assert.rejects(p, /stop/);
await sawClose;
} finally {
c.done();
}
});
test("PING and server GOAWAY", async () => {
let session!: http2.ServerHttp2Session;
const c = connect((_req, res) => res.end("ok"), { onSession: (s) => (session = s) });
await c.h2.ready;
const rtt = await c.h2.ping();
assert.ok(rtt >= 0);
assert.equal(await (await c.h2.request({ path: "/", authority: AUTH })).text(), "ok");
session.goaway(http2.constants.NGHTTP2_NO_ERROR);
const err = await c.closed;
assert.equal(err, undefined);
assert.equal(c.h2.closed, true);
await assert.rejects(c.h2.request({ path: "/", authority: AUTH }), (e: H2Error) => e.retryable);
c.done();
});
test("transport loss fails open requests", async () => {
const c = connect(() => {});
const p = c.h2.request({ path: "/x", authority: AUTH });
await c.h2.ready;
c.h2.transportClosed(new Error("gone"));
await assert.rejects(p, /gone/);
assert.equal((await c.closed)?.message, "gone");
c.done();
});
});