mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 02:21:30 +08:00
With net.tailscale.exitNode (--tailscale-exit-node, setExitNode() at run time) a tailnet device that offers 0.0.0.0/0 takes all the guest's other IPv4 traffic and its DNS in place of the backend; while it is not usable that traffic is refused. WireGuard's source check is now the longest prefix across peers. The page lists the tailnet's devices, picks the exit node from a select box in Settings and the top bar panel, and shows a set-up node's status and live controls apart from the setup form. The README gains a section on joining a tailnet.
786 lines
39 KiB
TypeScript
786 lines
39 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();
|
|
});
|
|
});
|
|
|
|
describe("exit node", () => {
|
|
const keys = [randomBytes(32), randomBytes(32), randomBytes(32), randomBytes(32)];
|
|
const all = ["0.0.0.0/0", "::/0"];
|
|
/** peer1 offers itself as an exit node, peer2 has no default route, peer3 offers one and is offline, peer4 offers one too. */
|
|
const peers = (o: { online1?: boolean } = {}) => [
|
|
peerNode(1, keys[0]!, ["100.64.0.7/32", "fd7a::7/128"], { AllowedIPs: ["100.64.0.7/32", "fd7a::7/128", ...all], Hostinfo: { Hostname: "exit-box" }, Online: o.online1 ?? true }),
|
|
peerNode(2, keys[1]!, ["100.64.0.8/32"], { Online: true }),
|
|
peerNode(3, keys[2]!, ["100.64.0.9/32"], { AllowedIPs: ["100.64.0.9/32", ...all], Online: false }),
|
|
peerNode(4, keys[3]!, ["100.64.0.10/32"], { AllowedIPs: ["100.64.0.10/32", "192.168.9.0/24", ...all] }),
|
|
];
|
|
const INTERNET = parseIp4("93.184.215.14")!;
|
|
|
|
test("chosen by short name: 0.0.0.0/0 is its route, the last one; WireGuard takes any source from it; ::/0 and the others' default routes are not taken", () => {
|
|
const c = new TailscaleClient({ hostname: "t", exitNode: "peer1", log: () => {} });
|
|
c.applyNetMap(netmap(peers()));
|
|
assert.deepEqual(c.routeTable().map((r) => `${r.prefix} ${r.peer}`), [
|
|
"100.64.0.7/32 peer1.ts.test", "100.64.0.8/32 peer2.ts.test", "100.64.0.9/32 peer3.ts.test", "100.64.0.10/32 peer4.ts.test", "0.0.0.0/0 peer1.ts.test",
|
|
]);
|
|
assert.equal(c.route("93.184.215.14")?.peer, "peer1.ts.test");
|
|
assert.equal(c.route("100.64.0.8")?.peer, "peer2.ts.test", "longer prefixes first");
|
|
assert.equal(c.route("192.168.9.1")?.peer, "peer1.ts.test", "peer4's subnet route is not taken (no acceptRoutes)");
|
|
for (const local of ["10.0.2.2", "10.0.2.3", "127.0.0.1", "100.100.100.100", "198.18.0.1", "224.0.0.1"]) {
|
|
assert.equal(c.route(local), undefined, local);
|
|
assert.equal(c.routesIPv4(parseIp4(local)!), false, local);
|
|
}
|
|
const cfg = c.tunnelConfig();
|
|
assert.deepEqual(cfg.claims, ["100.64.0.0/10", "0.0.0.0/0"]);
|
|
assert.ok(cfg.routes.includes("0.0.0.0/0"));
|
|
assert.deepEqual(cfg.exitDNS, [{ ip: parseIp4("1.1.1.1"), port: 53 }, { ip: parseIp4("8.8.8.8"), port: 53 }], "no resolvers in the netmap: the public fallback");
|
|
const s = c.status();
|
|
assert.deepEqual(s.exitNode, { selected: "peer1", usable: true, peer: { id: 1, name: "peer1.ts.test", hostname: "exit-box", address: "100.64.0.7", online: true } });
|
|
assert.deepEqual(s.exitNodes.map((n) => [n.name, n.address, n.online]), [["peer1.ts.test", "100.64.0.7", true], ["peer3.ts.test", "100.64.0.9", false], ["peer4.ts.test", "100.64.0.10", null]]);
|
|
assert.ok(c.sendPacket(ipv4("100.64.0.5", "93.184.215.14", 17, udp(5000, 53))), "an internet destination has a route now");
|
|
void c.close();
|
|
});
|
|
|
|
test("WireGuard: the exit node's allowed IPs hold 0.0.0.0/0 (not ::/0); another peer's stay its own", () => {
|
|
const wg = new WgDevice({ privateKey: randomBytes(32), send() {}, onPacket() {} });
|
|
const t = new PeerTable();
|
|
const nodes = peers().map(normalizeNode);
|
|
t.exitNode = 1;
|
|
t.sync(nodes, wg);
|
|
const v4 = (k: Uint8Array) => wg.peer(x25519Public(k))!.allowedIPs.filter((p) => !p.includes(":"));
|
|
assert.deepEqual(v4(keys[0]!), ["100.64.0.7/32", "0.0.0.0/0"]);
|
|
assert.deepEqual(wg.peer(x25519Public(keys[0]!))!.allowedIPs.filter((p) => p.includes(":")), ["fd7a:0:0:0:0:0:0:7/128"], "its own IPv6 address, not ::/0");
|
|
assert.deepEqual(wg.peer(x25519Public(keys[3]!))!.allowedIPs, ["100.64.0.10/32"]);
|
|
t.exitNode = 4;
|
|
t.sync(nodes, wg);
|
|
assert.deepEqual(v4(keys[0]!), ["100.64.0.7/32"], "dropped when the choice moves");
|
|
assert.deepEqual(wg.peer(x25519Public(keys[3]!))!.allowedIPs, ["100.64.0.10/32", "0.0.0.0/0"]);
|
|
t.exitNode = 2;
|
|
t.sync(nodes, wg);
|
|
assert.ok(!t.routes.some((r) => r.bits === 0), "a peer without a default route gets none");
|
|
wg.close();
|
|
});
|
|
|
|
test("a choice by full name, host name or 100.x address; case and a trailing dot do not matter", () => {
|
|
for (const choice of ["PEER1.ts.test.", "exit-box", "100.64.0.7", " peer1 "]) {
|
|
const c = new TailscaleClient({ hostname: "t", exitNode: choice, log: () => {} });
|
|
c.applyNetMap(netmap(peers()));
|
|
assert.equal(c.status().exitNode?.peer?.id, 1, choice);
|
|
assert.equal(c.status().exitNode?.usable, true, choice);
|
|
void c.close();
|
|
}
|
|
});
|
|
|
|
test("fail closed: before the netmap, an unknown name, a peer without the route, an offline one: everything beyond the tailnet is claimed with no route, DNS has no server", () => {
|
|
const c = new TailscaleClient({ hostname: "t", exitNode: "peer1", log: () => {} });
|
|
assert.equal(c.routesIPv4(INTERNET), true, "claimed before the first netmap");
|
|
assert.deepEqual(c.exitDNS, []);
|
|
assert.deepEqual(c.status().exitNode, { selected: "peer1", usable: false, reason: "not connected" });
|
|
const cases: [string, string, WireNode[]][] = [
|
|
["nobody", "not found", peers()],
|
|
["peer2", "not an exit node", peers()],
|
|
["peer3", "offline", peers()],
|
|
["peer1", "offline", peers({ online1: false })],
|
|
];
|
|
for (const [choice, reason, ps] of cases) {
|
|
c.setExitNode(choice);
|
|
c.applyNetMap(netmap(ps));
|
|
const s = c.status().exitNode!;
|
|
assert.deepEqual([s.selected, s.usable, s.reason], [choice, false, reason], choice);
|
|
assert.equal(c.routesIPv4(INTERNET), true, `${choice}: claimed`);
|
|
assert.equal(c.route("93.184.215.14"), undefined, `${choice}: no route`);
|
|
assert.equal(c.sendPacket(ipv4("100.64.0.5", "93.184.215.14", 17, udp(5000, 53))), false);
|
|
assert.deepEqual(c.exitDNS, [], `${choice}: DNS fails`);
|
|
const cfg = c.tunnelConfig();
|
|
assert.ok(cfg.claims.includes("0.0.0.0/0") && !cfg.routes.includes("0.0.0.0/0"), choice);
|
|
}
|
|
// Back online (a later netmap): usable again.
|
|
c.setExitNode("peer1");
|
|
c.applyNetMap(netmap(peers()));
|
|
assert.equal(c.status().exitNode!.usable, true);
|
|
assert.equal(c.route("93.184.215.14")?.peer, "peer1.ts.test");
|
|
void c.close();
|
|
});
|
|
|
|
test("set to none: exactly the routes, claims and DNS of a node without one", () => {
|
|
const plain = new TailscaleClient({ hostname: "t", log: () => {} });
|
|
plain.applyNetMap(netmap(peers()));
|
|
const c = new TailscaleClient({ hostname: "t", exitNode: "peer1", log: () => {} });
|
|
c.applyNetMap(netmap(peers()));
|
|
c.setExitNode(null);
|
|
assert.deepEqual(c.tunnelConfig(), plain.tunnelConfig());
|
|
assert.deepEqual(c.routeTable(), plain.routeTable());
|
|
assert.equal(c.routesIPv4(INTERNET), false);
|
|
assert.equal(c.exitDNS, null);
|
|
assert.equal(c.status().exitNode, null);
|
|
assert.equal(c.exitNode, null);
|
|
c.setExitNode("");
|
|
assert.equal(c.exitNode, null, "\"\" is none too");
|
|
c.setExitNode("peer4");
|
|
assert.equal(c.route("8.8.8.8")?.peer, "peer4.ts.test");
|
|
void c.close();
|
|
void plain.close();
|
|
});
|
|
|
|
test("DNS through it: the netmap's plain IPv4 resolvers (ip:port too), not DoH, IPv6 or the local stack's ranges", () => {
|
|
const c = new TailscaleClient({ hostname: "t", exitNode: "peer1", log: () => {} });
|
|
const nm = netmap(peers());
|
|
nm.dns = { ...nm.dns, Resolvers: [{ Addr: "https://dns.example/dns-query" }, { Addr: "9.9.9.9" }, { Addr: "2620:fe::fe" }, { Addr: "100.100.100.100" }, { Addr: "100.64.0.8:5353" }, { Addr: "9.9.9.9" }] };
|
|
c.applyNetMap(nm);
|
|
assert.deepEqual(c.exitDNS, [{ ip: parseIp4("9.9.9.9"), port: 53 }, { ip: parseIp4("100.64.0.8"), port: 5353 }]);
|
|
void c.close();
|
|
});
|
|
|
|
test("the guest's routes get both halves of IPv4 from the tailnet address (its own default route stays), and lose them with the choice", async () => {
|
|
const scripts: string[] = [];
|
|
const c = new TailscaleClient({ hostname: "t", exitNode: "peer1", log: () => {} });
|
|
c.attachGuest(async (script) => { scripts.push(script); return { exitCode: 0, stdout: "", stderr: "" }; });
|
|
c.applyNetMap(netmap(peers()));
|
|
await waitFor(() => c.status().guest.mode === "address", "the guest configured");
|
|
assert.deepEqual(c.status().guest.routes, ["100.64.0.0/10", "0.0.0.0/1", "128.0.0.0/1"]);
|
|
assert.match(scripts.at(-1)!, /ip route replace 0\.0\.0\.0\/1 via 10\.0\.2\.2 src 100\.64\.0\.5/);
|
|
assert.match(scripts.at(-1)!, /ip route replace 128\.0\.0\.0\/1 via 10\.0\.2\.2 src 100\.64\.0\.5/);
|
|
assert.doesNotMatch(scripts.at(-1)!, /default/);
|
|
c.setExitNode(null);
|
|
await waitFor(() => c.status().guest.mode === "address" && c.status().guest.routes?.length === 1, "configured again");
|
|
assert.deepEqual(c.status().guest.routes, ["100.64.0.0/10"]);
|
|
assert.match(scripts.at(-1)!, /ip -4 addr flush dev tailscale0/, "the flush drops the halves with the address");
|
|
await c.close();
|
|
assert.match(scripts.at(-1)!, /ip link del tailscale0/);
|
|
});
|
|
|
|
test("close ends the claim: a stopped node routes nothing beyond the tailnet range", async () => {
|
|
const c = new TailscaleClient({ hostname: "t", exitNode: "peer1", log: () => {} });
|
|
c.applyNetMap(netmap(peers()));
|
|
await c.close();
|
|
assert.equal(c.routesIPv4(INTERNET), false);
|
|
assert.equal(c.routesIPv4(parseIp4("100.64.0.7")!), true);
|
|
assert.equal(c.exitDNS, null);
|
|
assert.deepEqual(c.tunnelConfig().claims, ["100.64.0.0/10"]);
|
|
assert.deepEqual(c.status().exitNodes, []);
|
|
assert.deepEqual(c.status().exitNode, { selected: "peer1", usable: false, reason: "not connected" });
|
|
});
|
|
});
|
|
|
|
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);
|
|
assert.equal(tailscaleArgs(["--tailscale"], env)?.exitNode, undefined);
|
|
assert.equal(tailscaleArgs(["--tailscale-exit-node", "exit-box"], env)?.exitNode, "exit-box", "the flag alone turns Tailscale on");
|
|
assert.equal(tailscaleArgs(["--tailscale-exit-node", "exit-box"], env)?.authKey, "tskey-from-env");
|
|
});
|