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

626 lines
30 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Tests for the Tailscale client (js/core/tailscale/client.ts): the packet
// filter on synthetic packets, then interop with a real tailscaled
// (userspace networking, test/tailscale-fixture.ts) through a local
// headscale with its embedded DERP on 127.0.0.1:18100-18103 (tailscaled's
// UDP port 18105). Both are relay-free on the JS side: every datagram goes
// through DERP. The interop part skips when the headscale or tailscale
// binaries are absent (vendor/toolchain/headscale, vendor/toolchain/tailscale).
//
// node --test test/tailscale-client.test.ts
import test, { after, before, describe } from "node:test";
import assert from "node:assert/strict";
import { TailscaleClient, type TailscaleStatus } from "../js/core/tailscale/client.ts";
import { PacketFilter, parseIp4 } from "../js/core/tailscale/filter.ts";
import { keyFromText, keyToText, newControlState, normalizeNode, type ControlState, type DERPMap, type NetMap, type WireNode } from "../js/core/tailscale/control.ts";
import { PeerTable } from "../js/core/tailscale/peers.ts";
import { tailscaleArgs } from "../js/node/tailscale-args.ts";
import { WgDevice } from "../js/core/tailscale/wireguard.ts";
import { DiscoKey, encodePing } from "../js/core/tailscale/disco.ts";
import { naclBoxSeal, randomBytes, x25519Public } from "../js/core/tailscale/crypto.ts";
import { spawn } from "node:child_process";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { TAILSCALE_DIR, headscaleAvailable, startHeadscale, startTailscaled, tailscaleAvailable, type Headscale, type Tailscaled } from "./tailscale-fixture.ts";
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
function csum(b: Uint8Array, off: number, len: number, s = 0): number {
for (let i = 0; i < len; i += 2) s += (b[off + i]! << 8) | (i + 1 < len ? b[off + i + 1]! : 0);
while (s > 0xffff) s = (s & 0xffff) + (s >>> 16);
return ~s & 0xffff;
}
/** An IPv4 packet with `l4` as payload; TCP and UDP checksums filled in. */
function ipv4(src: string, dst: string, proto: number, l4: Uint8Array): Uint8Array {
const p = new Uint8Array(20 + l4.length);
const dv = new DataView(p.buffer);
p[0] = 0x45;
dv.setUint16(2, p.length);
dv.setUint16(4, Math.random() * 65536);
p[8] = 64;
p[9] = proto;
dv.setUint32(12, parseIp4(src)!);
dv.setUint32(16, parseIp4(dst)!);
dv.setUint16(10, csum(p, 0, 20));
p.set(l4, 20);
if (proto === 6 || proto === 17) {
const off = proto === 6 ? 36 : 26;
const ph = (dv.getUint16(12) + dv.getUint16(14) + dv.getUint16(16) + dv.getUint16(18) + proto + l4.length);
dv.setUint16(off, csum(p, 20, l4.length, ph) || 0xffff);
}
return p;
}
function echoRequest(src: string, dst: string, id: number, seq: number, data: Uint8Array): Uint8Array {
const m = new Uint8Array(8 + data.length);
m[0] = 8;
m[4] = id >> 8; m[5] = id & 255; m[6] = seq >> 8; m[7] = seq & 255;
m.set(data, 8);
const c = csum(m, 0, m.length);
m[2] = c >> 8; m[3] = c & 255;
return ipv4(src, dst, 1, m);
}
function tcp(sport: number, dport: number, flags: number): Uint8Array {
const t = new Uint8Array(20);
t[0] = sport >> 8; t[1] = sport & 255; t[2] = dport >> 8; t[3] = dport & 255;
t[12] = 0x50; t[13] = flags;
return t;
}
function udp(sport: number, dport: number, data = new Uint8Array(4)): Uint8Array {
const u = new Uint8Array(8 + data.length);
u[0] = sport >> 8; u[1] = sport & 255; u[2] = dport >> 8; u[3] = dport & 255;
u[4] = u.length >> 8; u[5] = u.length & 255;
u.set(data, 8);
return u;
}
describe("packet filter", () => {
const me = "100.64.0.9";
const f = new PacketFilter([
{ SrcIPs: ["100.64.0.1", "100.64.0.20-100.64.0.29"], DstPorts: [{ IP: "*", Ports: { First: 22, Last: 22 } }] },
{ SrcIPs: ["100.64.0.0/10"], DstPorts: [{ IP: me, Ports: { First: 8000, Last: 8099 } }], IPProto: [17] },
{ SrcIPs: ["fd7a:115c:a1e0::/48"], DstPorts: [{ IP: "*", Ports: { First: 0, Last: 65535 } }] },
], [parseIp4(me)!]);
test("TCP: SYN needs a rule, the rest of a connection passes", () => {
assert.equal(f.check(ipv4("100.64.0.1", me, 6, tcp(5000, 22, 0x02))), null);
assert.equal(f.check(ipv4("100.64.0.25", me, 6, tcp(5000, 22, 0x02))), null, "a range source");
assert.match(f.check(ipv4("100.64.0.2", me, 6, tcp(5000, 22, 0x02)))!, /no rule/);
assert.match(f.check(ipv4("100.64.0.1", me, 6, tcp(5000, 80, 0x02)))!, /no rule/);
assert.equal(f.check(ipv4("100.64.0.2", me, 6, tcp(80, 5000, 0x12))), null, "SYN-ACK");
assert.equal(f.check(ipv4("100.64.0.2", me, 6, tcp(80, 5000, 0x10))), null, "ACK");
assert.match(f.check(ipv4("100.64.0.1", "100.64.0.10", 6, tcp(5000, 22, 0x02)))!, /destination/);
});
test("UDP: replies to our flows, and rules with IPProto", () => {
assert.equal(f.check(ipv4("100.64.0.3", me, 17, udp(1, 8050))), null);
assert.match(f.check(ipv4("100.64.0.3", me, 17, udp(1, 9000)))!, /no rule for UDP/);
assert.equal(f.check(ipv4("100.64.0.1", me, 17, udp(1, 22))), null, "the port-22 rule has the default protocols, UDP among them");
f.noteOutbound(ipv4(me, "100.64.0.3", 17, udp(4444, 53)));
assert.equal(f.check(ipv4("100.64.0.3", me, 17, udp(53, 4444))), null, "reply");
assert.match(f.check(ipv4("100.64.0.3", me, 17, udp(54, 4444)))!, /no rule/, "another port");
});
test("ICMP: replies and errors pass, requests need a source rule", () => {
const reply = echoRequest("100.64.0.3", me, 1, 1, new Uint8Array(4));
reply[20] = 0;
assert.equal(f.check(reply), null);
assert.equal(f.check(echoRequest("100.64.0.1", me, 1, 1, new Uint8Array(4))), null);
assert.equal(f.check(echoRequest("100.64.0.3", me, 1, 1, new Uint8Array(4))), null, "the UDP rule's sources cover it (ports and protocol ignored, as Tailscale's)");
const g = new PacketFilter([{ SrcIPs: ["100.64.0.1"], DstPorts: [{ IP: "*", Ports: { First: 22, Last: 22 } }] }], [parseIp4(me)!]);
assert.match(g.check(echoRequest("100.64.0.3", me, 1, 1, new Uint8Array(4)))!, /no rule for ICMP/);
assert.match(g.check(ipv4("100.64.0.1", me, 47, new Uint8Array(8)))!, /protocol 47/);
assert.equal(g.check(ipv4("100.64.0.1", me, 99, new Uint8Array(9))), null, "TSMP");
});
test("SCTP's ports count; other protocols need a rule opening every port; early later fragments and short first ones are dropped", () => {
const g = new PacketFilter([
{ SrcIPs: ["100.64.0.7"], DstPorts: [{ IP: me, Ports: { First: 5000, Last: 5000 } }], IPProto: [132, 47] },
{ SrcIPs: ["100.64.0.8"], DstPorts: [{ IP: me, Ports: { First: 0, Last: 65535 } }], IPProto: [47] },
{ SrcIPs: ["100.64.0.7"], DstPorts: [{ IP: me, Ports: { First: 22, Last: 22 } }], IPProto: [6] },
], [parseIp4(me)!]);
const sctp = (dport: number) => { const b = new Uint8Array(12); b[2] = dport >> 8; b[3] = dport & 255; return b; };
assert.equal(g.check(ipv4("100.64.0.7", me, 132, sctp(5000))), null);
assert.match(g.check(ipv4("100.64.0.7", me, 132, sctp(9999)))!, /no rule for SCTP/);
assert.match(g.check(ipv4("100.64.0.7", me, 47, new Uint8Array(8)))!, /protocol 47/, "a port-limited rule does not admit GRE");
assert.equal(g.check(ipv4("100.64.0.8", me, 47, new Uint8Array(8))), null, "a rule for every port does");
const frag = (offsetBlocks: number) => {
const p = ipv4("100.64.0.7", me, 6, new Uint8Array(24));
p[6] = offsetBlocks >> 8; p[7] = offsetBlocks & 255;
return p;
};
assert.match(g.check(frag(1))!, /fragment offset/, "8 bytes in: inside a transport header");
assert.match(g.check(frag(9))!, /fragment offset/);
assert.equal(g.check(frag(10)), null, "80 bytes in: past any IPv4 + TCP header");
const shortTcp = ipv4("100.64.0.7", me, 99, new Uint8Array(12));
shortTcp[9] = 6;
assert.match(g.check(shortTcp)!, /malformed/, "a first fragment without a whole TCP header");
assert.match(g.check(ipv4("100.64.0.7", "224.0.0.1", 17, udp(1, 2)))!, /multicast/);
});
test("an empty filter denies new flows", () => {
const g = new PacketFilter([], [parseIp4(me)!]);
assert.match(g.check(ipv4("100.64.0.1", me, 6, tcp(5000, 22, 0x02)))!, /no rule/);
assert.equal(g.check(ipv4("100.64.0.1", me, 6, tcp(5000, 22, 0x10))), null);
});
});
const skip = !headscaleAvailable() ? "no headscale binary" : !tailscaleAvailable() ? "no tailscale binaries (vendor/toolchain/tailscale)" : false;
describe("interop with tailscaled over DERP", { skip, concurrency: 1 }, () => {
let hs: Headscale;
let tsd: Tailscaled;
let client: TailscaleClient;
let realIp = "";
let state: ControlState | undefined;
const logs: string[] = [];
const statuses: TailscaleStatus[] = [];
const inbound: Uint8Array[] = [];
before(async () => {
hs = await startHeadscale({ portBase: 18100, embeddedDerp: true });
const user = await hs.createUser("alice");
const key = await hs.createAuthKey(user.id, { reusable: true });
tsd = await startTailscaled({ port: 18105 });
await tsd.up(hs.url, key, "real");
realIp = await tsd.ip4();
client = new TailscaleClient({
controlURL: hs.url,
authKey: key,
hostname: "jsnode",
answerPings: true,
onState: (s) => (state = s),
onStatus: (s) => statuses.push(s),
onPacket: (ip) => inbound.push(ip.slice()),
log: (m) => logs.push(m),
});
client.start();
await client.ready(20000);
});
after(async () => {
await client?.close();
await tsd?.stop();
await hs?.stop();
if (process.env.UNKERNEL_TS_LOG) console.log(logs.join("\n"));
});
test("logs in, picks the embedded DERP as home and persists its state", () => {
const s = client.status();
assert.equal(s.state, "running");
assert.equal(s.homeDERP, 999);
assert.match(client.addresses[0]!, /^100\.64\./);
assert.ok(state?.authorized, "state reported authorized");
assert.ok(s.peers.some((p) => p.addresses.includes(realIp)), "the real node is a peer");
assert.ok(statuses.some((x) => x.state === "running"));
assert.deepEqual(client.resolve("real"), client.resolve("REAL.ts.test."));
assert.equal(client.resolve("real")![0], realIp);
assert.ok(client.routesIPv4(parseIp4(realIp)!));
assert.equal(client.route(realIp)?.prefix, `${realIp}/32`);
});
test("an ICMP echo to tailscaled through WireGuard over DERP gets its reply", async () => {
const me = client.addresses[0]!;
const data = new TextEncoder().encode("hello over derp");
for (let seq = 1; seq <= 3; seq++) assert.ok(client.sendPacket(echoRequest(me, realIp, 0x4242, seq, data)));
const end = Date.now() + 15000;
const replies = () => inbound.filter((p) => p[9] === 1 && p[20] === 0 && ((p[24]! << 8) | p[25]!) === 0x4242);
while (replies().length < 1 && Date.now() < end) await sleep(50);
const r = replies();
assert.ok(r.length >= 1, `an echo reply (got ${inbound.length} packets)`);
assert.equal(new TextDecoder().decode(r[0]!.subarray(28)), "hello over derp");
assert.ok(client.status().peers.find((p) => p.addresses.includes(realIp))!.lastHandshake > 0);
});
test("tailscale status on the real node shows the JS node online", async () => {
const end = Date.now() + 15000;
let peer: Record<string, unknown> | undefined;
while (Date.now() < end) {
const s = await tsd.status();
peer = Object.values(s.Peer ?? {}).find((p) => p.HostName === "jsnode");
if (peer?.Online && peer.Relay) break;
await sleep(250);
}
assert.ok(peer, "jsnode listed");
assert.equal(peer!.Online, true);
assert.deepEqual((peer!.TailscaleIPs as string[]).find((a) => !a.includes(":")), client.addresses[0]);
assert.equal(peer!.Relay, "headscale");
});
test("tailscale ping (disco) reaches the JS node via DERP", async () => {
const out = await tsd.cli(["ping", "--c", "3", "--until-direct=false", client.addresses[0]!]);
if (process.env.UNKERNEL_TS_LOG) console.log(out);
assert.match(out, /pong from jsnode .* via DERP\(headscale\)/);
assert.ok(client.stats.discoPongs > 0);
});
test("tailscale ping --tsmp gets a TSMP pong", async () => {
const out = await tsd.cli(["ping", "--tsmp", "--c", "2", client.addresses[0]!]);
assert.match(out, /pong from jsnode/);
assert.ok(client.stats.tsmpPongs > 0);
});
test("tailscale ping --icmp gets an echo reply from the client", async () => {
const out = await tsd.cli(["ping", "--icmp", "--c", "2", client.addresses[0]!]);
assert.match(out, /pong from jsnode/);
assert.ok(client.stats.echoReplies > 0);
});
test("close stops everything", async () => {
const me = client.addresses[0]!;
await client.close();
assert.equal(client.status().state, "stopped");
assert.equal(client.status().derp.length, 0);
assert.deepEqual(client.addresses, []);
assert.equal(client.sendPacket(echoRequest(me, realIp, 1, 1, new Uint8Array(1))), false);
});
});
describe("the netmap's packet filter against headscale's ACLs", { skip, concurrency: 1 }, () => {
let hs: Headscale;
let tsd: Tailscaled;
let client: TailscaleClient;
let policyDir = "";
const syns: number[] = [];
before(async () => {
// Only TCP port 22 of the JS node is open to the tailnet.
policyDir = await mkdtemp(join(tmpdir(), "unkernel-policy-"));
const policy = join(policyDir, "policy.hujson");
await writeFile(policy, JSON.stringify({ acls: [{ action: "accept", src: ["acl@"], dst: ["acl@:22"] }] }));
hs = await startHeadscale({ portBase: 18110, embeddedDerp: true, config: { policy: { mode: "file", path: policy } } });
const user = await hs.createUser("acl");
const key = await hs.createAuthKey(user.id, { reusable: true });
tsd = await startTailscaled({ port: 18115 });
await tsd.up(hs.url, key, "real");
client = new TailscaleClient({
controlURL: hs.url, authKey: key, hostname: "jsacl",
onPacket: (ip) => {
if (ip[9] === 6 && (ip[33]! & 0x12) === 0x02) syns.push((ip[22]! << 8) | ip[23]!);
},
});
client.start();
await client.ready(20000);
});
after(async () => {
await client?.close();
await tsd?.stop();
await hs?.stop();
if (policyDir) await rm(policyDir, { recursive: true, force: true });
});
test("a SYN to an allowed port reaches onPacket, one to another port is dropped", async () => {
assert.ok(client.netmap!.packetFilter.length > 0, "control sent a filter");
const nc = (port: number) => new Promise<void>((resolve) => {
const c = spawn(join(TAILSCALE_DIR, "tailscale"), [`--socket=${tsd.socket}`, "nc", client.addresses[0]!, String(port)], { stdio: "ignore" });
setTimeout(() => { c.kill(); resolve(); }, 2500);
});
await nc(22);
await nc(23);
assert.ok(syns.includes(22), `SYNs seen: ${syns}`);
assert.ok(!syns.includes(23), `SYNs seen: ${syns}`);
const s = client.status();
assert.ok(s.stats.filtered > 0);
assert.match(s.lastFiltered ?? "", /no rule for TCP SYN/);
});
});
// ---- the client without a control server: netmaps applied directly, a fake DERP server ----
const nodeKey = (k: Uint8Array) => keyToText("nodekey", x25519Public(k));
function peerNode(id: number, priv: Uint8Array, addrs: string[], extra: Partial<WireNode> = {}): WireNode {
return { ID: id, Name: `peer${id}.ts.test.`, Key: nodeKey(priv), Addresses: addrs, HomeDERP: 1, ...extra };
}
function netmap(peers: WireNode[], derpMap: DERPMap | null = null, self = "100.64.0.5/32"): NetMap {
const me = normalizeNode({ ID: 99, Name: "me.ts.test.", Key: keyToText("nodekey", new Uint8Array(32).fill(9)), Addresses: [self], HomeDERP: 1 });
return {
self: me, nodeKey: me.Key, addresses: me.Addresses, keyExpiry: null, expired: false, name: "me.ts.test",
peers: peers.map(normalizeNode), derpMap, dns: { Domains: ["ts.test"] }, packetFilter: [{ SrcIPs: ["*"], DstPorts: [{ IP: "*", Ports: { First: 0, Last: 65535 } }] }],
domain: "ts.test", userProfiles: {}, health: [], sshPolicy: null, controlTime: null,
};
}
const region = (id: number): DERPMap["Regions"][string] => ({ RegionID: id, RegionCode: `r${id}`, RegionName: `R${id}`, Nodes: [{ Name: `${id}a`, RegionID: id, HostName: `derp${id}.test` }] });
/** A DERP server per URL behind a fake WebSocket: login, ping, packets both ways. */
class FakeDerps {
priv = randomBytes(32);
pub = x25519Public(this.priv);
sockets: FakeDerpSocket[] = [];
/** Hosts whose sockets never open (a region that does not answer). */
silent = new Set<string>();
ctor() {
const derps = this;
return class extends FakeDerpSocket {
constructor(url: string) {
super(derps, url);
derps.sockets.push(this);
}
} as unknown as new (url: string, protocols?: string | string[]) => WebSocket;
}
}
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;
}
class FakeDerpSocket {
binaryType = "arraybuffer";
readyState = 0;
bufferedAmount = 0;
onopen: ((ev: unknown) => void) | null = null;
onmessage: ((ev: { data: unknown }) => void) | null = null;
onclose: ((ev: { code?: number }) => void) | null = null;
onerror: ((ev: unknown) => void) | null = null;
derps: FakeDerps;
url: string;
client: Uint8Array | null = null;
/** SendPacket frames: [destination, packet]. */
sent: [Uint8Array, Uint8Array][] = [];
constructor(derps: FakeDerps, url: string) {
this.derps = derps;
this.url = url;
if (derps.silent.has(new URL(url).hostname)) return;
queueMicrotask(() => {
this.readyState = 1;
this.onopen?.({});
const magic = Uint8Array.from([0x44, 0x45, 0x52, 0x50, 0xf0, 0x9f, 0x94, 0x91]);
const sk = new Uint8Array(40);
sk.set(magic);
sk.set(derps.pub, 8);
this.deliver(frame(1, sk));
});
}
deliver(b: Uint8Array): void {
this.onmessage?.({ data: b.slice().buffer });
}
send(d: Uint8Array): void {
const type = d[0]!, payload = d.subarray(5);
if (type === 2) {
this.client = payload.slice(0, 32);
const nonce = randomBytes(24);
const box = naclBoxSeal(new TextEncoder().encode('{"version":2}'), nonce, this.client, this.derps.priv);
const p = new Uint8Array(24 + box.length);
p.set(nonce);
p.set(box, 24);
queueMicrotask(() => this.deliver(frame(3, p)));
} else if (type === 0x12) queueMicrotask(() => this.deliver(frame(0x13, payload.slice(0, 8))));
else if (type === 4) this.sent.push([payload.slice(0, 32), payload.slice(32)]);
}
/** A packet from `src` (a node key) to the client. */
recv(src: Uint8Array, data: Uint8Array): void {
const p = new Uint8Array(32 + data.length);
p.set(src);
p.set(data, 32);
this.deliver(frame(5, p));
}
close(): void {
this.readyState = 3;
}
}
async function waitFor(pred: () => boolean, what: string, ms = 8000): Promise<void> {
const end = Date.now() + ms;
while (!pred()) {
if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);
await sleep(10);
}
}
describe("client without a control server", () => {
test("peer table: a shared prefix belongs to the lowest node ID and comes back when its holder drops it or leaves", () => {
const wg = new WgDevice({ privateKey: randomBytes(32), send() {}, onPacket() {} });
const [ka, kb] = [randomBytes(32), randomBytes(32)];
const a = normalizeNode(peerNode(5, ka, ["100.64.0.7/32"], { AllowedIPs: ["100.64.0.7/32", "10.9.0.0/24"] }));
const b = normalizeNode(peerNode(3, kb, ["100.64.0.8/32"], { AllowedIPs: ["100.64.0.8/32", "10.9.0.0/24"] }));
const t = new PeerTable({ acceptRoutes: true });
const allowed = (k: Uint8Array) => wg.peer(x25519Public(k))?.allowedIPs;
t.sync([a], wg);
assert.deepEqual(allowed(ka), ["100.64.0.7/32", "10.9.0.0/24"]);
t.sync([a, b], wg);
assert.deepEqual(allowed(ka), ["100.64.0.7/32"], "b's lower ID takes the route");
assert.deepEqual(allowed(kb), ["100.64.0.8/32", "10.9.0.0/24"]);
assert.equal(t.lookup(parseIp4("10.9.0.1")!)!.peer.node.ID, 3);
t.sync([a], wg);
assert.deepEqual(allowed(ka), ["100.64.0.7/32", "10.9.0.0/24"], "back to a once b left");
t.sync([a, { ...b, AllowedIPs: ["100.64.0.8/32"] }], wg);
assert.deepEqual(allowed(ka), ["100.64.0.7/32", "10.9.0.0/24"], "and when b no longer lists it");
assert.equal(t.lookup(parseIp4("10.9.0.1")!)!.peer.node.ID, 5);
// Without acceptRoutes WireGuard takes only the peers' own addresses (as sources too).
const wg2 = new WgDevice({ privateKey: randomBytes(32), send() {}, onPacket() {} });
new PeerTable().sync([a, b], wg2);
assert.deepEqual(wg2.peer(x25519Public(ka))!.allowedIPs, ["100.64.0.7/32"]);
assert.deepEqual(wg2.peer(x25519Public(kb))!.allowedIPs, ["100.64.0.8/32"]);
wg2.close();
wg.close();
});
test("routes: subnet routes only with acceptRoutes, never into the local stack's ranges", () => {
const k = randomBytes(32);
const sub = peerNode(1, k, ["100.64.0.7/32"], { AllowedIPs: ["100.64.0.7/32", "10.0.0.0/8", "10.0.2.0/24", "192.168.5.0/24", "0.0.0.0/0"] });
const off = new TailscaleClient({ hostname: "t", log: () => {} });
off.applyNetMap(netmap([sub]));
assert.deepEqual(off.routeTable().map((r) => r.prefix), ["100.64.0.7/32"], "default: the peer's own address only");
assert.equal(off.routesIPv4(parseIp4("192.168.5.1")!), false);
const on = new TailscaleClient({ hostname: "t", acceptRoutes: true, log: () => {} });
on.applyNetMap(netmap([sub]));
assert.deepEqual(on.routeTable().map((r) => r.prefix), ["100.64.0.7/32", "192.168.5.0/24", "10.0.0.0/8"], "10.0.2.0/24 and the default route left out");
assert.equal(on.route("10.9.9.9")?.prefix, "10.0.0.0/8");
for (const local of ["10.0.2.2", "10.0.2.3", "127.0.0.1", "100.100.100.100"]) {
assert.equal(on.route(local), undefined, local);
assert.equal(on.routesIPv4(parseIp4(local)!), false, local);
}
void off.close();
void on.close();
});
test("before the first netmap it claims the tailnet range and names under ts.net, answers none; after close it holds nothing", async () => {
const c = new TailscaleClient({ hostname: "t", log: () => {} });
assert.equal(c.ipv4, 0);
assert.equal(c.routesIPv4(parseIp4("100.101.102.103")!), true);
assert.equal(c.resolve("real"), null);
assert.equal(c.resolve("box.tail1234.ts.net."), null);
assert.equal(c.resolve("example.com"), undefined);
assert.equal(c.tunnelConfig().known, false);
c.applyNetMap(netmap([peerNode(1, randomBytes(32), ["100.64.0.7/32"])]));
assert.deepEqual(c.resolve("PEER1"), ["100.64.0.7"]);
assert.deepEqual(c.resolve("nobody.ts.test"), []);
assert.equal(c.resolve("box.tail1234.ts.net"), undefined, "ts.net is not this tailnet's domain");
assert.equal(c.tunnelConfig().ipv4, "100.64.0.5");
await c.close();
const cfg = c.tunnelConfig();
assert.equal(cfg.ipv4, "");
assert.deepEqual(cfg.routes, []);
assert.equal(cfg.known, false);
assert.deepEqual([c.status().addresses, c.status().name], [[], ""], "a stopped (or logged-out) node shows no address or name");
assert.equal(c.routesIPv4(parseIp4("100.64.0.7")!), true, "still claimed, so a NetStack answers host unreachable");
});
test("disco: a ping naming another disco key gets no pong and costs no key; a peer gets at most 8 pongs a second", async () => {
const derps = new FakeDerps();
const c = new TailscaleClient({ hostname: "t", log: () => {}, WebSocket: derps.ctor(), derpURL: (n) => `wss://${n.HostName}/derp` });
const kp = randomBytes(32);
const peerDisco = new DiscoKey();
c.applyNetMap(netmap([peerNode(1, kp, ["100.64.0.7/32"], { DiscoKey: keyToText("discokey", peerDisco.publicKey) })], { Regions: { "1": region(1) } }));
await waitFor(() => c.status().homeDERP === 1 && c.status().derp[0]?.state === "connected", "home DERP");
const ws = derps.sockets[0]!;
const myDisco = x25519Public(keyFromText(c.state.discoKey, "privkey"));
const src = x25519Public(kp);
ws.recv(src, peerDisco.seal(myDisco, encodePing(randomBytes(12))));
assert.equal(ws.sent.length, 1, "a pong");
assert.deepEqual(ws.sent[0]![0], src);
// The netmap peer's node key, another disco key: nothing, quickly (no X25519 per packet).
const other = new DiscoKey();
const forged = Array.from({ length: 300 }, () => other.seal(myDisco, encodePing(randomBytes(12))));
const t0 = performance.now();
for (const f of forged) ws.recv(src, f);
assert.ok(performance.now() - t0 < 300, `${performance.now() - t0} ms for 300 forged pings`);
assert.equal(ws.sent.length, 1);
for (let i = 0; i < 20; i++) ws.recv(src, peerDisco.seal(myDisco, encodePing(randomBytes(12))));
assert.equal(ws.sent.length, 8, "8 in this second");
await c.close();
});
test("a DERP map that changes during the home probe: the probe starts over and a home is taken", { timeout: 20000 }, async () => {
const derps = new FakeDerps();
derps.silent.add("derp2.test");
const c = new TailscaleClient({ hostname: "t", log: () => {}, WebSocket: derps.ctor(), derpURL: (n) => `wss://${n.HostName}/derp` });
c.applyNetMap(netmap([], { Regions: { "1": region(1), "2": region(2) } }));
await sleep(50); // probing: region 2 never answers
c.applyNetMap(netmap([], { Regions: { "3": region(3) } }));
await waitFor(() => c.status().homeDERP === 3, "home region 3", 10000);
await c.close();
});
// Tailscale's control never shows a node its own home region (the self node has no DERP or HomeDERP; headscale's does).
const asRealControl = (nm: NetMap): NetMap => ({ ...nm, self: { ...nm.self, HomeDERP: 0 } });
const three = (): DERPMap => ({ Regions: { "1": region(1), "2": region(2), "3": region(3) } });
/** Started (so that it has a state other than idle) against a control URL nothing answers: the netmaps are the test's. */
const started = (opts: Omit<ConstructorParameters<typeof TailscaleClient>[0], "hostname">) => {
const c = new TailscaleClient({ hostname: "t", log: () => {}, controlURL: "http://127.0.0.1:18179", derpURL: (n) => `wss://${n.HostName}/derp`, ...opts });
c.start();
return c;
};
test("a new node probes, reports its home and is running 1.5 s after the report is taken (no netmap echo); the state keeps the region", async () => {
const derps = new FakeDerps();
const states: ControlState[] = [];
const c = started({ WebSocket: derps.ctor(), onState: (s) => states.push(s) });
const t0 = performance.now();
c.applyNetMap(asRealControl(netmap([], three())));
await c.ready(3000);
const ms = performance.now() - t0;
assert.ok(ms >= 1400 && ms < 2500, `running after ${Math.round(ms)} ms`);
assert.equal(derps.sockets.length, 3, "all three probed");
const home = c.status().homeDERP;
assert.equal(c.state.homeDERP, home);
assert.equal(states.at(-1)?.homeDERP, home, "a state event carries it");
await c.close();
});
test("a node that comes back with a saved home region keeps it with no probe", async () => {
const derps = new FakeDerps();
const c = started({ WebSocket: derps.ctor(), state: { ...newControlState(), homeDERP: 2 } });
c.applyNetMap(asRealControl(netmap([], three())));
await c.ready(3000);
assert.equal(c.status().homeDERP, 2);
assert.deepEqual(derps.sockets.map((s) => s.url), ["wss://derp2.test/derp"], "no other region opened");
await c.close();
});
test("a saved home region that does not connect: the others are probed after 4 s", { timeout: 20000 }, async () => {
const derps = new FakeDerps();
derps.silent.add("derp2.test");
const logs: string[] = [];
const c = started({ log: (m) => logs.push(m), WebSocket: derps.ctor(), state: { ...newControlState(), homeDERP: 2 } });
c.applyNetMap(asRealControl(netmap([], three())));
await c.ready(10000);
assert.notEqual(c.status().homeDERP, 2);
assert.ok(logs.some((l) => /previous home DERP region 2 does not connect/.test(l)), logs.join("\n"));
assert.ok(!c.status().derp.some((r) => r.region === 2), "its connection closed");
assert.equal(c.state.homeDERP, c.status().homeDERP);
await c.close();
});
test("the home region's loss shows as the error until it is connected again", async () => {
const derps = new FakeDerps();
const c = started({ WebSocket: derps.ctor(), state: { ...newControlState(), homeDERP: 1 } });
c.applyNetMap(asRealControl(netmap([], three())));
await c.ready(3000);
const ws = derps.sockets[0]!;
ws.readyState = 3;
ws.onclose?.({ code: 1006 });
await waitFor(() => /derp 1: websocket closed \(1006\)/.test(c.status().error ?? ""), "the error");
await waitFor(() => derps.sockets.length === 2 && c.status().state === "running", "reconnected", 5000);
assert.doesNotMatch(c.status().error ?? "", /derp/, "(the unreachable control URL's error may stay)");
await c.close();
});
test("control's health messages show in the status", async () => {
const c = new TailscaleClient({ hostname: "t", log: () => {} });
c.applyNetMap({ ...netmap([]), health: ["node OS changed since last connection"] });
assert.deepEqual(c.status().health, ["node OS changed since last connection"]);
c.applyNetMap(netmap([]));
assert.equal(c.status().health, undefined);
await c.close();
});
test("on Node the connect attempt per address is at least 2.5 s (a far DERP region over IPv4 where IPv6 is unreachable)", async () => {
const net = await import("node:net");
const was = net.getDefaultAutoSelectFamilyAttemptTimeout();
net.setDefaultAutoSelectFamilyAttemptTimeout(250);
const c = new TailscaleClient({ hostname: "t", log: () => {} });
assert.equal(net.getDefaultAutoSelectFamilyAttemptTimeout(), 2500);
net.setDefaultAutoSelectFamilyAttemptTimeout(5000);
const d = new TailscaleClient({ hostname: "t", log: () => {} });
assert.equal(net.getDefaultAutoSelectFamilyAttemptTimeout(), 5000, "never lowered");
net.setDefaultAutoSelectFamilyAttemptTimeout(was);
await c.close();
await d.close();
});
});
test("CLI: TS_AUTHKEY in the environment turns nothing on; a --tailscale* flag does, and then it is the key", () => {
const env = { TS_AUTHKEY: "tskey-from-env" };
assert.equal(tailscaleArgs([], env), undefined);
assert.equal(tailscaleArgs(["--distro", "none", "--help"], env), undefined);
assert.equal(tailscaleArgs(["--tailscale"], env)?.authKey, "tskey-from-env");
assert.equal(tailscaleArgs(["--tailscale-login-server", "http://h"], env)?.authKey, "tskey-from-env");
assert.equal(tailscaleArgs(["--tailscale-authkey", "k"], env)?.authKey, "k");
assert.equal(tailscaleArgs(["--tailscale"], {})?.authKey, undefined);
assert.equal(tailscaleArgs(["--tailscale"], env)?.guestAddress, true);
assert.equal(tailscaleArgs(["--tailscale-rewrite"], env)?.guestAddress, false);
});