Files
unkernel/test/tailscale-derp.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

572 lines
21 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Tests for the DERP client (js/core/tailscale/derp.ts): framing and login
// against an in-process fake server, then live against headscale's
// embedded DERP server (vendor/toolchain/headscale/headscale, or
// HEADSCALE_BIN; skipped when absent) on 127.0.0.1:18094-18097: two
// clients exchanging packets, ping, peer-gone, reconnect, and two
// WireGuard devices talking through it.
//
// node --test test/tailscale-derp.test.ts
import test, { describe } from "node:test";
import assert from "node:assert/strict";
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { naclBoxOpen, naclBoxSeal, randomBytes, x25519Public } from "../js/core/tailscale/crypto.ts";
import {
DERP_MAGIC,
DerpClient,
FRAME_CLIENT_INFO,
FRAME_NOTE_PREFERRED,
FRAME_PING,
FRAME_PONG,
FRAME_RECV_PACKET,
FRAME_SEND_PACKET,
FRAME_SERVER_INFO,
FRAME_SERVER_KEY,
type DerpState,
type DerpWebSocket,
type DerpWebSocketConstructor,
} from "../js/core/tailscale/derp.ts";
import { DISCO_MAGIC, DiscoKey, derpMagicAddr, discoSender, encodeCallMeMaybe, encodePing, looksLikeDisco, v4Mapped } from "../js/core/tailscale/disco.ts";
import { WgDevice } from "../js/core/tailscale/wireguard.ts";
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
function frame(type: number, payload: Uint8Array): Uint8Array {
const f = new Uint8Array(5 + payload.length);
f[0] = type;
new DataView(f.buffer).setUint32(1, payload.length);
f.set(payload, 5);
return f;
}
function cat(...parts: Uint8Array[]): Uint8Array {
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
let o = 0;
for (const p of parts) {
out.set(p, o);
o += p.length;
}
return out;
}
async function until(pred: () => boolean, what: string, ms = 10_000): Promise<void> {
const end = Date.now() + ms;
while (!pred()) {
if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);
await sleep(10);
}
}
// --- fake server over a fake WebSocket ---
class FakeServer {
priv = randomBytes(32);
pub = x25519Public(this.priv);
sockets: FakeSocket[] = [];
received: { type: number; payload: Uint8Array }[] = [];
clientKey: Uint8Array | null = null;
clientInfo: Record<string, unknown> | null = null;
#buf: Uint8Array = new Uint8Array(0);
ctor(): DerpWebSocketConstructor {
const server = this;
return class extends FakeSocket {
constructor(url: string, protocols?: string | string[]) {
super(server, url, protocols);
server.sockets.push(this);
}
};
}
// Bytes from the client, reassembled into frames.
fromClient(b: Uint8Array): void {
this.#buf = cat(this.#buf, b);
while (this.#buf.length >= 5) {
const len = new DataView(this.#buf.buffer, this.#buf.byteOffset).getUint32(1);
if (this.#buf.length < 5 + len) break;
const type = this.#buf[0]!;
const payload = this.#buf.slice(5, 5 + len);
this.#buf = this.#buf.slice(5 + len);
this.received.push({ type, payload });
if (type === FRAME_CLIENT_INFO) {
this.clientKey = payload.slice(0, 32);
const msg = naclBoxOpen(payload.subarray(56), payload.subarray(32, 56), this.clientKey, this.priv);
assert.ok(msg, "client info opens with the server key");
this.clientInfo = JSON.parse(new TextDecoder().decode(msg!));
}
}
}
serverKeyFrame(): Uint8Array {
return frame(FRAME_SERVER_KEY, cat(DERP_MAGIC, this.pub));
}
serverInfoFrame(): Uint8Array {
const nonce = randomBytes(24);
const box = naclBoxSeal(new TextEncoder().encode('{"version":2}'), nonce, this.clientKey!, this.priv);
return frame(FRAME_SERVER_INFO, cat(nonce, box));
}
}
class FakeSocket implements DerpWebSocket {
binaryType = "blob";
readyState = 0;
bufferedAmount = 0;
onopen: ((ev: unknown) => void) | null = null;
onmessage: ((ev: { data: unknown }) => void) | null = null;
onclose: ((ev: { code?: number; reason?: string }) => void) | null = null;
onerror: ((ev: unknown) => void) | null = null;
server: FakeServer;
url: string;
protocols: string | string[] | undefined;
constructor(server: FakeServer, url: string, protocols?: string | string[]) {
this.server = server;
this.url = url;
this.protocols = protocols;
queueMicrotask(() => {
this.readyState = 1;
this.onopen?.({});
});
}
send(data: Uint8Array): void {
this.server.fromClient(data);
}
close(): void {
this.readyState = 3;
}
// Server -> client, as one message.
deliver(b: Uint8Array): void {
const ab = b.slice().buffer;
this.onmessage?.({ data: ab });
}
drop(): void {
this.readyState = 3;
this.onclose?.({ code: 1006 });
}
}
describe("derp client (fake server)", () => {
test("login, reassembly across and within messages, ping, preferred", async () => {
const server = new FakeServer();
const packets: { src: Uint8Array; data: string }[] = [];
const states: DerpState[] = [];
const c = new DerpClient({
url: "wss://fake/derp",
privateKey: randomBytes(32),
WebSocket: server.ctor(),
preferred: true,
onPacket: (src, data) => packets.push({ src: src.slice(), data: new TextDecoder().decode(data) }),
onState: (s) => states.push(s),
});
c.start();
await sleep(0);
const ws = server.sockets[0]!;
assert.deepEqual(ws.protocols, ["derp"]);
assert.equal(ws.binaryType, "arraybuffer");
// Server key split in two messages.
const sk = server.serverKeyFrame();
ws.deliver(sk.subarray(0, 3));
ws.deliver(sk.subarray(3));
assert.deepEqual(server.clientKey, c.publicKey);
assert.equal(server.clientInfo!.version, 2);
assert.deepEqual(c.serverKey, server.pub);
// Server info plus two packets in one message, a third byte by byte.
const src = randomBytes(32);
const p = (s: string) => frame(FRAME_RECV_PACKET, cat(src, new TextEncoder().encode(s)));
ws.deliver(cat(server.serverInfoFrame(), p("one"), p("two")));
await c.ready();
assert.equal(c.state, "connected");
const three = p("three");
for (let i = 0; i < three.length; i++) ws.deliver(three.subarray(i, i + 1));
assert.deepEqual(packets.map((x) => x.data), ["one", "two", "three"]);
assert.deepEqual(packets[0]!.src, src);
// NotePreferred(1) went out after login.
const np = server.received.find((f) => f.type === FRAME_NOTE_PREFERRED)!;
assert.deepEqual([...np.payload], [1]);
// Send.
const dst = randomBytes(32);
assert.equal(c.send(dst, new Uint8Array([1, 2, 3])), true);
const sp = server.received.at(-1)!;
assert.equal(sp.type, FRAME_SEND_PACKET);
assert.deepEqual(sp.payload, cat(dst, new Uint8Array([1, 2, 3])));
// Server ping -> pong.
ws.deliver(frame(FRAME_PING, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])));
assert.deepEqual(server.received.at(-1), { type: FRAME_PONG, payload: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]) });
// Client ping.
const rtt = c.ping();
const ping = server.received.at(-1)!;
assert.equal(ping.type, FRAME_PING);
ws.deliver(frame(FRAME_PONG, ping.payload));
assert.ok((await rtt) >= 0);
c.close();
assert.deepEqual(states, ["connecting", "connected", "closed"]);
});
test("a large frame over many small messages; a server's restart delay is capped at 60 s", async () => {
const server = new FakeServer();
const got: number[] = [];
const logs: string[] = [];
const c = new DerpClient({ url: "wss://fake/derp", privateKey: randomBytes(32), WebSocket: server.ctor(), log: (m) => logs.push(m),
onPacket: (_s, d) => got.push(d.length) });
c.start();
await sleep(0);
const ws = server.sockets[0]!;
ws.deliver(server.serverKeyFrame());
ws.deliver(server.serverInfoFrame());
await c.ready();
const big = frame(FRAME_RECV_PACKET, cat(randomBytes(32), randomBytes(60_000)));
const small = frame(FRAME_RECV_PACKET, cat(randomBytes(32), randomBytes(10)));
const both = cat(big, small);
const t0 = performance.now();
for (let i = 0; i < both.length; i += 7) ws.deliver(both.subarray(i, i + 7));
assert.deepEqual(got, [60_000, 10]);
assert.ok(performance.now() - t0 < 2000, "no copy of the whole buffer per message");
const restart = new Uint8Array(8);
new DataView(restart.buffer).setUint32(0, 0xffffffff);
ws.deliver(frame(0x15, restart));
assert.ok(logs.some((l) => /reconnect in 60000 ms/.test(l)), logs.join("\n"));
c.close();
});
test("reconnects with backoff, rejects a bad greeting", async () => {
const server = new FakeServer();
const states: DerpState[] = [];
const c = new DerpClient({
url: "wss://fake/derp",
privateKey: randomBytes(32),
WebSocket: server.ctor(),
minBackoff: 10,
maxBackoff: 20,
onState: (s) => states.push(s),
});
c.start();
await sleep(0);
server.sockets[0]!.deliver(frame(FRAME_SERVER_KEY, new Uint8Array(40))); // no magic
assert.equal(c.state, "disconnected");
await until(() => server.sockets.length === 2, "second connection");
await sleep(0);
const ws = server.sockets[1]!;
ws.deliver(server.serverKeyFrame());
ws.deliver(server.serverInfoFrame());
await c.ready();
ws.drop();
assert.equal(c.state, "disconnected");
assert.equal(c.send(randomBytes(32), new Uint8Array(1)), false);
await until(() => server.sockets.length === 3, "third connection");
c.close();
assert.deepEqual(states, ["connecting", "disconnected", "connecting", "connected", "disconnected", "connecting", "closed"]);
});
test("a region's server that does not log us in gives way to the next; a connection that was up retries its own server", async () => {
// Tailscale's map lists 3-7 servers per region; one of them refusing (or unreachable) must not cost the region.
const server = new FakeServer();
const c = new DerpClient({
url: "wss://derp5a/derp", fallbackURLs: ["wss://derp5b/derp", "wss://derp5c/derp"],
privateKey: randomBytes(32), WebSocket: server.ctor(), minBackoff: 5, maxBackoff: 10,
});
c.start();
await sleep(0);
server.sockets[0]!.drop(); // 5a: closed before any frame
await until(() => server.sockets.length === 2, "second connection");
assert.equal(server.sockets[1]!.url, "wss://derp5b/derp");
assert.equal(c.url, "wss://derp5b/derp");
await sleep(0);
const ws = server.sockets[1]!;
ws.deliver(server.serverKeyFrame());
ws.deliver(server.serverInfoFrame());
await c.ready();
ws.drop(); // was up: 5b again
await until(() => server.sockets.length === 3, "third connection");
assert.equal(server.sockets[2]!.url, "wss://derp5b/derp");
server.sockets[2]!.drop();
await until(() => server.sockets.length === 4, "fourth connection");
assert.equal(server.sockets[3]!.url, "wss://derp5c/derp");
server.sockets[3]!.drop();
await until(() => server.sockets.length === 5, "fifth connection");
assert.equal(server.sockets[4]!.url, "wss://derp5a/derp", "and round again");
c.close();
});
});
test("disco messages", () => {
const a = new DiscoKey();
const b = new DiscoKey();
const txid = randomBytes(12);
const nk = randomBytes(32);
const sealed = a.seal(b.publicKey, encodePing(txid, nk, 10));
// magic + key + nonce + box(2 + 12 + 32 + 10) + 16-byte tag.
assert.equal(sealed.length, 6 + 32 + 24 + 16 + 56);
const ping = b.open(sealed)!;
assert.deepEqual(ping.sender, a.publicKey);
assert.deepEqual(ping.message, { type: "ping", txid, nodeKey: nk, padding: 10 });
assert.equal(new DiscoKey().open(sealed), null, "wrong key");
const r = b.answerPing(sealed, derpMagicAddr(1))!;
const pong = a.open(r.pong)!.message;
assert.deepEqual(pong, { type: "pong", txid, src: { ip: v4Mapped(127, 3, 3, 40), port: 1 } });
const cmm = b.open(a.seal(b.publicKey, encodeCallMeMaybe([{ ip: v4Mapped(1, 2, 3, 4), port: 41641 }])))!.message;
assert.deepEqual(cmm, { type: "callMeMaybe", endpoints: [{ ip: v4Mapped(1, 2, 3, 4), port: 41641 }] });
assert.equal(b.answerPing(a.seal(b.publicKey, encodeCallMeMaybe([])), derpMagicAddr(1)), null);
// With the expected sender: another sender's packets cost no key computation.
const keys = b.stats.sharedKeys;
const t0 = performance.now();
for (let i = 0; i < 500; i++) {
const forged = new Uint8Array(6 + 32 + 24 + 40);
forged.set(DISCO_MAGIC);
forged.set(randomBytes(32), 6);
assert.equal(b.answerPing(forged, derpMagicAddr(1), a.publicKey), null);
}
assert.equal(b.stats.sharedKeys, keys);
assert.ok(performance.now() - t0 < 200, `${performance.now() - t0} ms`);
assert.ok(b.answerPing(a.seal(b.publicKey, encodePing(txid, nk)), derpMagicAddr(1), a.publicKey));
});
// --- live, against headscale's embedded DERP ---
const REPO = new URL("..", import.meta.url).pathname;
const HEADSCALE = process.env.HEADSCALE_BIN ?? join(REPO, "vendor/toolchain/headscale/headscale");
const PORT = 18094;
async function startHeadscale(): Promise<{ url: string; stop: () => void }> {
// Short path: headscale's unix socket must fit sun_path.
const dir = mkdtempSync(join(tmpdir().length < 40 ? tmpdir() : "/tmp", "ukderp-"));
const cfg = `server_url: http://127.0.0.1:${PORT}
listen_addr: 127.0.0.1:${PORT}
metrics_listen_addr: 127.0.0.1:${PORT + 1}
grpc_listen_addr: 127.0.0.1:${PORT + 2}
noise:
private_key_path: ${dir}/noise.key
prefixes:
v4: 100.64.0.0/10
v6: fd7a:115c:a1e0::/48
derp:
server:
enabled: true
region_id: 999
region_code: test
region_name: test
verify_clients: false
stun_listen_addr: 127.0.0.1:${PORT + 3}
private_key_path: ${dir}/derp.key
automatically_add_embedded_derp_region: true
ipv4: 127.0.0.1
urls: []
paths: []
auto_update_enabled: false
disable_check_updates: true
database:
type: sqlite
sqlite:
path: ${dir}/db.sqlite
log:
level: warn
policy:
mode: file
path: ""
dns:
magic_dns: false
base_domain: example.com
override_local_dns: false
nameservers:
global: []
unix_socket: ${dir}/hs.sock
logtail:
enabled: false
`;
writeFileSync(join(dir, "config.yaml"), cfg);
const child: ChildProcess = spawn(HEADSCALE, ["serve", "-c", join(dir, "config.yaml")], { stdio: ["ignore", "ignore", "pipe"] });
let stderr = "";
child.stderr!.on("data", (d) => (stderr += d));
const stop = () => {
child.kill();
rmSync(dir, { recursive: true, force: true });
};
const end = Date.now() + 15_000;
for (;;) {
if (child.exitCode !== null) {
stop();
throw new Error(`headscale exited: ${stderr}`);
}
try {
const r = await fetch(`http://127.0.0.1:${PORT}/health`);
if (r.ok) break;
} catch {
// not up yet
}
if (Date.now() > end) {
stop();
throw new Error(`headscale did not start: ${stderr}`);
}
await sleep(100);
}
return { url: `ws://127.0.0.1:${PORT}/derp`, stop };
}
// A WebSocket override that lets the test cut the connection.
const live: WebSocket[] = [];
const TrackedWS = class extends WebSocket {
constructor(url: string, protocols?: string | string[]) {
super(url, protocols);
live.push(this);
}
} as unknown as DerpWebSocketConstructor;
describe("derp client (headscale)", { skip: existsSync(HEADSCALE) ? false : `no headscale at ${HEADSCALE}`, concurrency: 1 }, () => {
let hs: { url: string; stop: () => void };
const clients: DerpClient[] = [];
const mk = (opts: Partial<ConstructorParameters<typeof DerpClient>[0]> = {}) => {
const c = new DerpClient({ url: hs.url, privateKey: randomBytes(32), WebSocket: TrackedWS, minBackoff: 50, maxBackoff: 200, ...opts });
clients.push(c);
c.start();
return c;
};
test("start headscale", async () => {
hs = await startHeadscale();
});
test("two clients exchange packets", async () => {
const gotA: Uint8Array[] = [];
const gotB: { src: Uint8Array; data: Uint8Array }[] = [];
const a = mk({ preferred: true, onPacket: (_s, d) => gotA.push(d.slice()) });
const b = mk({ onPacket: (s, d) => gotB.push({ src: s.slice(), data: d.slice() }) });
await Promise.all([a.ready(5000), b.ready(5000)]);
assert.equal(a.serverInfo?.version, 2);
assert.deepEqual(a.serverKey, b.serverKey);
const big = randomBytes(60_000);
// In bursts within the server's queue for a client (32 packets in derp_server.go; more are dropped under load).
for (let i = 0; i < 50; i++) {
assert.ok(a.send(b.publicKey, new Uint8Array([i])));
if (i === 24) await until(() => gotB.length === 25, "the first 25 packets at b", 3000);
}
assert.ok(a.send(b.publicKey, big));
await until(() => gotB.length === 51, "51 packets at b", 3000).catch((e) => { throw new Error(`${e.message}: got ${gotB.length} ${gotB.map((p) => p.data.length)}`); });
assert.deepEqual(gotB.slice(0, 50).map((p) => p.data[0]), [...Array(50).keys()]);
assert.deepEqual(gotB[0]!.src, a.publicKey);
assert.deepEqual(gotB[50]!.data, big);
b.send(a.publicKey, new TextEncoder().encode("back"));
await until(() => gotA.length === 1, "reply at a");
assert.equal(new TextDecoder().decode(gotA[0]), "back");
const rtt = await a.ping();
assert.ok(rtt >= 0 && rtt < 1000, `rtt ${rtt}`);
});
test("peer gone for an unknown destination", async () => {
const gone: { key: Uint8Array; reason: number }[] = [];
const a = mk({ onPeerGone: (key, reason) => gone.push({ key, reason }) });
await a.ready(5000);
const nobody = x25519Public(randomBytes(32));
// The server answers only disco-looking packets ("TS💬" + key + nonce).
a.send(nobody, cat(new Uint8Array([0x54, 0x53, 0xf0, 0x9f, 0x92, 0xac]), randomBytes(32 + 24 + 16)));
await until(() => gone.length > 0, "peer gone");
assert.deepEqual(gone[0]!.key, nobody);
assert.equal(gone[0]!.reason, 1);
});
test("reconnects after the connection drops", async () => {
const got: string[] = [];
const a = mk();
const b = mk({ onPacket: (_s, d) => got.push(new TextDecoder().decode(d)) });
await Promise.all([a.ready(5000), b.ready(5000)]);
const n = live.length;
// b was started last, so the newest socket is b's.
const seen: DerpState[] = [];
const ws = live.at(-1)!;
const bState = b.state;
assert.equal(bState, "connected");
ws.close();
await until(() => b.state !== "connected", "drop seen");
seen.push(b.state);
await b.ready(5000);
assert.ok(live.length > n, "a new socket");
assert.deepEqual(seen, ["disconnected"]);
a.send(b.publicKey, new TextEncoder().encode("after reconnect"));
await until(() => got.includes("after reconnect"), "packet after reconnect");
});
test("wireguard over derp", async () => {
const ka = randomBytes(32);
const kb = randomBytes(32);
const pa = x25519Public(ka);
const pb = x25519Public(kb);
const got: Record<string, string[]> = { a: [], b: [] };
let devA: WgDevice | null = null;
let devB: WgDevice | null = null;
const da = mk({ privateKey: ka, onPacket: (s, d) => devA?.receive(s, d) });
const db = mk({ privateKey: kb, onPacket: (s, d) => devB?.receive(s, d) });
await Promise.all([da.ready(5000), db.ready(5000)]);
devA = new WgDevice({ privateKey: ka, send: (to, dg) => da.send(to, dg), onPacket: (_f, ip) => got.a!.push(udpData(ip)) });
devB = new WgDevice({ privateKey: kb, send: (to, dg) => db.send(to, dg), onPacket: (_f, ip) => got.b!.push(udpData(ip)) });
try {
devA.setPeer(pb, { allowedIPs: ["100.64.0.2/32"] });
devB.setPeer(pa, { allowedIPs: ["100.64.0.1/32"] });
for (let i = 0; i < 20; i++) assert.ok(devA.sendPacket(udp4("100.64.0.1", "100.64.0.2", 1000, 2000, `a->b ${i}`)));
await until(() => got.b!.length === 20, "20 packets a->b");
for (let i = 0; i < 20; i++) devB.sendPacket(udp4("100.64.0.2", "100.64.0.1", 2000, 1000, `b->a ${i}`));
await until(() => got.a!.length === 20, "20 packets b->a");
assert.equal(got.b![0], "a->b 0");
assert.equal(got.a![19], "b->a 19");
assert.equal(devA.peer(pb)!.handshakes, 1);
} finally {
devA.close();
devB.close();
}
});
test("disco ping answered with a pong over derp", async () => {
const nodeA = mk({ onPacket: (_s, d) => fromB.push(d.slice()) });
const fromB: Uint8Array[] = [];
const discoA = new DiscoKey();
const discoB = new DiscoKey();
const nodeB = mk({
onPacket: (src, d) => {
const r = discoB.answerPing(d, derpMagicAddr(999));
if (r) nodeB.send(src, r.pong);
},
});
await Promise.all([nodeA.ready(5000), nodeB.ready(5000)]);
const txid = randomBytes(12);
nodeA.send(nodeB.publicKey, discoA.seal(discoB.publicKey, encodePing(txid, nodeA.publicKey)));
await until(() => fromB.length === 1, "pong");
assert.ok(looksLikeDisco(fromB[0]!));
assert.deepEqual(discoSender(fromB[0]!), discoB.publicKey);
const pong = discoA.open(fromB[0]!)!;
assert.equal(pong.message.type, "pong");
if (pong.message.type !== "pong") return;
assert.deepEqual(pong.message.txid, txid);
assert.deepEqual(pong.message.src, { ip: v4Mapped(127, 3, 3, 40), port: 999 });
});
test("stop", () => {
for (const c of clients) c.close();
hs?.stop();
});
});
function udp4(src: string, dst: string, sport: number, dport: number, msg: string): Uint8Array {
const payload = new TextEncoder().encode(msg);
const p = new Uint8Array(28 + payload.length);
p[0] = 0x45;
p[2] = p.length >> 8;
p[3] = p.length & 0xff;
p[8] = 64;
p[9] = 17;
p.set(src.split(".").map(Number), 12);
p.set(dst.split(".").map(Number), 16);
p[20] = sport >> 8;
p[21] = sport & 0xff;
p[22] = dport >> 8;
p[23] = dport & 0xff;
p[24] = (8 + payload.length) >> 8;
p[25] = (8 + payload.length) & 0xff;
p.set(payload, 28);
return p;
}
function udpData(ip: Uint8Array): string {
return new TextDecoder().decode(ip.subarray(28));
}