Something went wrong. Try again.
An experimental port of NetBSD, FreeBSD, OpenBSD, and XNU to unkernel unkernel.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349// SPDX-License-Identifier: MIT// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>// Tests for the Tailscale control client (js/core/tailscale/control.ts):// map-session delta handling on synthetic responses, then registration and// the map long-poll against a local headscale (test/tailscale-fixture.ts) on// 127.0.0.1:18080-18082. The headscale part skips when the binary is absent// (vendor/toolchain/headscale/headscale or $UNKERNEL_HEADSCALE).//// node --test test/tailscale-control.test.tsimport test, { after, before, describe } from "node:test";import assert from "node:assert/strict";import { ControlClient, controlWebSocketURL, keyToText, MapSession, type ControlState, type ControlStatus, type NetMap, type WireNode,} from "../js/core/tailscale/control.ts";import { ChunkQueue } from "../js/core/tailscale/bytes.ts";import { headscaleAvailable, startHeadscale, type Headscale } from "./tailscale-fixture.ts";
const node = (id: number, extra: Partial<WireNode> = {}): WireNode => ({ ID: id, Key: keyToText("nodekey", new Uint8Array(32).fill(id)), Addresses: [`100.64.0.${id}/32`], ...extra,});
describe("map session", () => { test("full and delta updates", () => { const s = new MapSession(); s.now = () => new Date("2026-01-02T03:04:05Z"); assert.equal(s.netmap(), null); assert.equal(s.apply({ KeepAlive: true }), false); s.apply({ Node: node(1, { KeyExpiry: "0001-01-01T00:00:00Z", Name: "self.ts.test." }), Peers: [node(3, { DERP: "127.3.3.40:7" }), node(2, { AllowedIPs: ["100.64.0.2/32", "10.0.0.0/24"], HomeDERP: 4 })], DERPMap: { Regions: { "7": { RegionID: 7, RegionCode: "r7", RegionName: "R7", Nodes: [] } } }, PacketFilter: [{ SrcIPs: ["*"] }], Domain: "example", UserProfiles: [{ ID: 9, LoginName: "u" }], }); let nm = s.netmap()!; assert.equal(nm.name, "self.ts.test"); assert.equal(nm.keyExpiry, null); assert.deepEqual(nm.peers.map((p) => p.ID), [2, 3]); assert.equal(nm.peers[1]!.HomeDERP, 7, "legacy DERP string"); assert.equal(nm.peers[1]!.DERP, undefined); assert.deepEqual(nm.peers[1]!.AllowedIPs, ["100.64.0.3/32"], "nil AllowedIPs means Addresses"); assert.deepEqual(nm.peers[0]!.AllowedIPs, ["100.64.0.2/32", "10.0.0.0/24"]); assert.equal(nm.userProfiles[9]!.LoginName, "u");
s.apply({ PeersChanged: [node(4)], PeersRemoved: [3] }); s.apply({ PeersChangedPatch: [{ NodeID: 2, DERPRegion: 9, Endpoints: ["1.2.3.4:41641"], Online: true }, { NodeID: 77, DERPRegion: 1 }] }); s.apply({ OnlineChange: { "4": true }, PeerSeenChange: { "2": true } }); // A DERPMap without Regions keeps the old regions. s.apply({ DERPMap: { Regions: undefined as never, HomeParams: { RegionScore: { "7": 1.5 } } } }); s.apply({ PacketFilters: { "*": null, extra: [{ SrcIPs: ["100.64.0.4"] }] } }); nm = s.netmap()!; assert.deepEqual(nm.peers.map((p) => p.ID), [2, 4]); assert.equal(nm.peers[0]!.HomeDERP, 9); assert.deepEqual(nm.peers[0]!.Endpoints, ["1.2.3.4:41641"]); assert.equal(nm.peers[0]!.Online, true); assert.equal(nm.peers[0]!.LastSeen, "2026-01-02T03:04:05.000Z"); assert.equal(nm.peers[1]!.Online, true); assert.deepEqual(Object.keys(nm.derpMap!.Regions), ["7"]); assert.deepEqual(nm.derpMap!.HomeParams, { RegionScore: { "7": 1.5 } }); assert.deepEqual(nm.packetFilter, [{ SrcIPs: ["100.64.0.4"] }], "\"*\": null clears the base filter too");
// A new full Peers list replaces everything. s.apply({ Peers: [node(5)] }); assert.deepEqual(s.netmap()!.peers.map((p) => p.ID), [5]); // Expiry from the clock. s.apply({ Node: node(1, { KeyExpiry: "2026-01-01T00:00:00Z" }) }); assert.equal(s.netmap()!.expired, true); });
test("the shapes Tailscale's control sends (2026-11-28): peers as PeersChanged, legacy DERP, an empty filter, Health alone", () => { const s = new MapSession(); // The first message of a stream lists the peers in PeersChanged (no Peers), each home region as "127.3.3.40:N" or absent. s.apply({ Node: node(1, { Name: "me.tail0.ts.net.", KeyExpiry: "2099-05-27T10:10:46Z", DiscoKey: `discokey:${"0".repeat(64)}`, CapMap: { "https://tailscale.com/cap/is-admin": null } }), DERPMap: { Regions: { "4": { RegionID: 4, RegionCode: "fra", RegionName: "Frankfurt", Nodes: [] } } }, PeersChanged: [node(2, { Expired: true, Online: false }), node(3, { DERP: "127.3.3.40:4", Online: true, AllowedIPs: null })], DNSConfig: { Routes: { "tail0.ts.net.": null, "ts.net.": [{ Addr: "199.247.155.53" }] }, Domains: ["tail0.ts.net"], Proxied: true }, PacketFilter: [], ControlDialPlan: { Candidates: [] }, CollectServices: true, DefaultAutoUpdate: true, ControlTime: "2026-11-28T10:10:46.369494257Z", }); let nm = s.netmap()!; assert.deepEqual(nm.peers.map((p) => [p.ID, p.HomeDERP]), [[2, 0], [3, 4]]); assert.equal(nm.self.HomeDERP, 0, "no home region for the node itself"); assert.deepEqual(nm.packetFilter, []); assert.deepEqual(nm.dns!.Domains, ["tail0.ts.net"]); // Then the expired peer removed, a keep-alive, a peer's new region as a whole node. s.apply({ PeersRemoved: [2], SSHPolicy: { rules: [] }, ControlTime: "2026-11-28T10:10:47Z" }); assert.equal(s.apply({ KeepAlive: true }), false); s.apply({ PeersChanged: [node(3, { DERP: "127.3.3.40:8", Online: true })] }); nm = s.netmap()!; assert.deepEqual(nm.peers.map((p) => [p.ID, p.HomeDERP]), [[3, 8]]); assert.deepEqual(nm.packetFilter, [], "a message without PacketFilter keeps it"); // A refused session: the node and Health only (here after a change of Hostinfo.OS). s.apply({ Node: node(1, { Name: "me.tail0.ts.net." }), Health: ["node OS changed since last connection, was node state copied between devices?"] }); assert.match(s.netmap()!.health[0]!, /OS changed/); });
test("a 20 MiB map message in 16 KiB chunks is put together once (ChunkQueue)", () => { const total = 20 << 20, chunk = 16384; const q = new ChunkQueue(); const t0 = performance.now(); const len = new Uint8Array(4); new DataView(len.buffer).setUint32(0, total, true); q.push(len); let got: Uint8Array | null = null; for (let sent = 0; sent < total; sent += chunk) { const c = new Uint8Array(chunk).fill((sent / chunk) & 255); q.push(c); const h = q.peek(4); const n = (h[0]! | (h[1]! << 8) | (h[2]! << 16) | (h[3]! << 24)) >>> 0; if (q.length - 4 >= n) { q.take(4); got = q.take(n); } } const ms = performance.now() - t0; assert.equal(got?.length, total); assert.equal(got![chunk * 300], 300 & 255); assert.equal(q.length, 0); assert.ok(ms < 1000, `${ms.toFixed(0)} ms`); });
test("WebSocket URL per control URL", () => { assert.equal(controlWebSocketURL("https://controlplane.tailscale.com"), "wss://controlplane.tailscale.com/ts2021"); assert.equal(controlWebSocketURL("http://127.0.0.1:18080"), "ws://127.0.0.1:18080/ts2021"); assert.equal(controlWebSocketURL("http://example.com"), "wss://example.com/ts2021"); assert.equal(controlWebSocketURL("https://hs.example:8443"), "wss://hs.example:8443/ts2021"); });});
const skip = headscaleAvailable() ? false : "headscale binary absent (vendor/toolchain/headscale/headscale)";
/** A WebSocket that remembers its instances, so a test can cut one. */const sockets: WebSocket[] = [];class TrackedWebSocket extends WebSocket { constructor(url: string | URL, protocols?: string | string[]) { super(url, protocols); sockets.push(this); }}
describe("against headscale", { skip }, () => { let hs: Headscale; let authKey: string; const clients: ControlClient[] = []; const log = process.env.UNKERNEL_TS_LOG ? (tag: string) => (m: string) => console.log(`[${tag}] ${m}`) : () => undefined;
const client = (hostname: string, extra: Partial<ConstructorParameters<typeof ControlClient>[0]> = {}) => { const c = new ControlClient({ controlURL: hs.url, hostname, authKey, logger: log(hostname), WebSocket: TrackedWebSocket, backoff: { min: 200, max: 1000 }, ...extra }); clients.push(c); return c; }; const peerOf = (nm: NetMap, c: ControlClient) => nm.peers.find((p) => p.Key === c.nodeKey);
before(async () => { hs = await startHeadscale({ portBase: 18080 }); const user = await hs.createUser("alice"); authKey = await hs.createAuthKey(user.id, { reusable: true }); });
after(async () => { await Promise.all(clients.map((c) => c.stop())); await hs?.stop(); });
let one: ControlClient; let two: ControlClient; let savedState: ControlState | null = null;
test("register with an auth key and follow the map", async () => { one = client("js-one"); const errors: Error[] = []; const statuses: ControlStatus[] = []; one.on("error", (e) => errors.push(e)); one.on("status", (s) => statuses.push(s)); one.on("state", (s) => (savedState = s)); one.start(); const nm = await one.waitForNetMap(undefined, { timeout: 15000 }); assert.equal(savedState!.authorized, true); assert.equal(nm.nodeKey, one.nodeKey); assert.ok(nm.addresses.some((a) => /^100\.64\.\d+\.\d+\/32$/.test(a)), nm.addresses.join()); assert.ok(nm.addresses.some((a) => a.startsWith("fd7a:115c:a1e0:"))); assert.equal(nm.name, "js-one.ts.test"); assert.equal(nm.keyExpiry, null); assert.equal(nm.self.DiscoKey, keyToText("discokey", one.discoPublicKey)); assert.deepEqual(Object.keys(nm.derpMap!.Regions), ["900"]); assert.equal(nm.derpMap!.Regions["900"]!.Nodes[0]!.HostName, "127.0.0.1"); assert.ok(nm.packetFilter.length > 0); assert.deepEqual(nm.dns?.Domains, ["ts.test"]); assert.deepEqual(nm.peers, []); assert.equal(one.status, "polling"); assert.ok(statuses.includes("registering") && statuses.includes("polling")); // Compress "" was honoured: a zstd frame would have been an error. assert.deepEqual(errors, []); });
test("a second node appears as a peer and reports its home DERP", async () => { two = client("js-two"); two.start(); const nm = await one.waitForNetMap((n) => peerOf(n, two)?.Online === true, { timeout: 15000 }); const p = peerOf(nm, two)!; assert.equal(p.DiscoKey, keyToText("discokey", two.discoPublicKey)); assert.deepEqual(p.AllowedIPs, p.Addresses); assert.equal(p.Name, "js-two.ts.test."); assert.equal(p.HomeDERP, 0); await two.waitForNetMap(undefined, { timeout: 15000 }); await two.setPreferredDERP(900); await one.waitForNetMap((n) => peerOf(n, two)?.HomeDERP === 900, { timeout: 15000 }); // And the second node sees the first. const nm3 = await two.waitForNetMap((n) => peerOf(n, one) !== undefined, { timeout: 15000 }); assert.deepEqual(peerOf(nm3, one)!.Addresses, one.netmap!.addresses); });
test("the map poll survives a dropped channel", async () => { const before = one.netmap!; const statuses: ControlStatus[] = []; const off = one.on("status", (s) => statuses.push(s)); const ws = sockets.filter((s) => s.readyState === WebSocket.OPEN); assert.ok(ws.length >= 2); const fresh = one.waitForNetMap((n) => n !== before, { timeout: 15000 }); // Cut every open control socket; both clients reconnect. for (const s of ws) s.close(); const nm = await fresh; off(); assert.ok(statuses.includes("backoff"), statuses.join()); assert.equal(one.status, "polling"); assert.ok(peerOf(nm, two)); // A lite update over the new connection. await one.setPreferredDERP(900); await two.waitForNetMap((n) => peerOf(n, one)?.HomeDERP === 900, { timeout: 15000 }); });
test("a stream that carried messages and then failed starts the backoff over (Tailscale's control closes streams every few minutes)", async () => { const own: WebSocket[] = []; const WS = class extends WebSocket { constructor(url: string | URL, protocols?: string | string[]) { super(url, protocols); own.push(this); } }; const delays: number[] = []; const c = client("rebackoff", { WebSocket: WS, backoff: { min: 200, max: 20000 }, logger: (m) => { const d = /reconnecting in (\d+) ms/.exec(m); if (d) delays.push(Number(d[1])); } }); c.start(); for (let i = 0; i < 4; i++) { const before = await c.waitForNetMap(() => true, { timeout: 15000 }); for (const s of own) if (s.readyState === WebSocket.OPEN) s.close(); await c.waitForNetMap((n) => n !== before, { timeout: 15000 }); } assert.equal(delays.length, 4, delays.join()); assert.ok(delays.every((d) => d <= 250), `every reconnect after the first delay (200 ms +-25%): ${delays.join(", ")}`); await c.stop(); });
test("a deleted peer goes away, and the deleted node registers again", async () => { const nodes = await hs.nodes(); const twoEntry = nodes.find((n) => n.name === "js-two" || n.given_name === "js-two")!; assert.ok(twoEntry, JSON.stringify(nodes)); const gone = one.waitForNetMap((n) => !peerOf(n, two), { timeout: 15000 }); await hs.cli(["nodes", "delete", "--identifier", String(twoEntry.id), "--force"]); await gone; // headscale tells the deleted node its key expired; with the reusable // key it registers again and comes back as a new node. const back = await one.waitForNetMap((n) => peerOf(n, two) !== undefined, { timeout: 20000 }); assert.notEqual(peerOf(back, two)!.ID, Number(twoEntry.id)); });
test("a node whose key expired without the Expired flag (Tailscale's control after a logout) registers again", async () => { // Real control's shape: the map keeps coming, KeyExpiry in the past, no Node.Expired (headscale sets it: taken out here). const strip = (r: { Node?: WireNode }) => { if (r.Node) delete r.Node.Expired; }; const c = client("expiring", { onMapResponse: strip }); c.start(); await c.waitForNetMap(() => true, { timeout: 15000 }); const entry = (await hs.nodes()).find((n) => n.name === "expiring" || n.given_name === "expiring")!; const expired = c.waitForNetMap((n) => n.expired && !n.self.Expired, { timeout: 15000 }); const registering = new Promise<void>((ok) => { const off = c.on("status", (st) => { if (st === "registering") { off(); ok(); } }); }); await hs.cli(["nodes", "expire", "--identifier", String(entry.id)]); await expired; await registering; // Registered again with the reusable key: a map that is not expired. const back = await c.waitForNetMap((n) => !n.expired, { timeout: 20000 }); assert.ok(back.keyExpiry === null || back.keyExpiry.getTime() > Date.now()); await c.stop(); });
test("interactive login through the AuthURL", async () => { const three = client("js-three", { authKey: undefined }); const urls: string[] = []; three.on("authurl", (u) => { urls.push(u); const id = new URL(u).pathname.split("/").pop()!; void hs.registerAuthId(id, "alice"); }); const res = await three.login(); assert.equal(res.machineAuthorized, true); assert.equal(urls.length, 1); assert.ok(urls[0]!.startsWith(`${hs.url}/register/`), urls[0]); assert.equal(three.state.authorized, true); three.start(); const nm = await three.waitForNetMap(undefined, { timeout: 15000 }); assert.ok(peerOf(nm, one)); await three.stop(); });
test("after stop() nothing opens a connection and none stays open", async () => { const four = client("js-four"); const first = sockets.length; four.start(); await four.waitForNetMap(undefined, { timeout: 15000 }); const before = sockets.length; await four.stop(); await new Promise((r) => setTimeout(r, 50)); for (const ws of sockets.slice(first, before)) assert.ok(ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED, "four's channel closed"); await assert.rejects(four.sendUpdate(), /stopped/); await assert.rejects(four.setPreferredDERP(900), /stopped/); await assert.rejects(four.fetchNetMap(), /stopped/); await new Promise((r) => setTimeout(r, 100)); assert.equal(sockets.length, before, "no new WebSocket"); });
test("persisted state resumes without registering", async () => { await one.stop(); const state = one.state; assert.equal(state.authorized, true); const again = client("js-one", { authKey: undefined, state }); const statuses: ControlStatus[] = []; again.on("status", (s) => statuses.push(s)); again.start(); const nm = await again.waitForNetMap(undefined, { timeout: 15000 }); assert.equal(again.nodeKey, one.nodeKey); assert.deepEqual(nm.addresses, one.netmap!.addresses); assert.ok(!statuses.includes("registering"), statuses.join()); await again.stop(); });});