Files
unkernel/test/tailscale-exit.test.ts
Pooya Parsa a9c8aef517 js: add Tailscale exit nodes, and rework the page's Tailscale settings
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.
2026-11-29 11:16:22 +00:00

285 lines
15 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// The guest behind an exit node (NetSpec.tailscale.exitNode): the bundled
// kernel's base shell joins a local headscale (embedded DERP,
// 127.0.0.1:18150-18153) next to a real tailscaled (userspace networking,
// UDP 18155) that advertises itself as an exit node, its 0.0.0.0/0
// approved in headscale; inline and in worker mode. The destination is an
// HTTP server (18157) and a DNS server (UDP 18158) on this host's first
// non-loopback IPv4 address: an exit node keeps its own LANs and addresses
// out of what it offers (a "guest wifi"), so the real node also advertises
// that address as a /32 (not approved: the JS node routes it by 0.0.0.0/0
// alone, and takes the replies from it by that route too). The guest
// fetches from it through the exit node (not NetStack's backend), from its
// 100.x address; resolves a name through the tunnel (the exit node's DNS
// servers are pointed at the local DNS server, since the netmap's can only
// be port 53); with an exit node chosen that the netmap lacks, gets host
// unreachable and SERVFAIL and nothing goes to the backend; with none, uses
// the direct backend again; and, where this host reaches the internet,
// resolves and fetches example.com through the public fallback resolvers.
// Last, the same through the rewrite of 10.0.2.15 (guestAddress: false).
// Skips without the headscale or tailscale binaries.
//
// node --test test/tailscale-exit.test.ts
import test, { after, before, describe } from "node:test";
import assert from "node:assert/strict";
import { createSocket, type Socket } from "node:dgram";
import { createServer, type Server } from "node:http";
import { networkInterfaces } from "node:os";
import { createKernel, type KernelHandle, type NetSpec, type TailscaleControlState } from "../js/node.ts";
import { ip4 } from "../js/core/net.ts";
import { headscaleAvailable, startHeadscale, startTailscaled, tailscaleAvailable, type Headscale, type Tailscaled } from "./tailscale-fixture.ts";
const HTTP_PORT = 18157, DNS_PORT = 18158;
const PROBE_NAME = "probe.exit.test", PROBE_ADDR = "192.0.2.77";
const hostIp = Object.values(networkInterfaces()).flat()
.find((a) => a && a.family === "IPv4" && !a.internal && !a.address.startsWith("100.") && !a.address.startsWith("10.0.2."))?.address;
const skip = !headscaleAvailable() ? "no headscale binary" : !tailscaleAvailable() ? "no tailscale binaries (vendor/toolchain/tailscale)"
: !hostIp ? "no non-loopback IPv4 address on this host" : false;
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
/** Whether this host gets an answer from 1.1.1.1 (the internet checks skip without one). */
async function internet(): Promise<boolean> {
const s = createSocket("udp4");
try {
return await new Promise<boolean>((resolve) => {
s.on("message", () => resolve(true));
s.on("error", () => resolve(false));
setTimeout(() => resolve(false), 2000);
s.send(dnsQuery("example.com"), 53, "1.1.1.1");
});
} finally {
s.close();
}
}
function dnsQuery(name: string): Uint8Array {
const labels = name.split(".").flatMap((l) => [l.length, ...new TextEncoder().encode(l)]);
return Uint8Array.from([0x12, 0x34, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, ...labels, 0, 0, 1, 0, 1]);
}
describe("guest behind an exit node", { skip, concurrency: 1 }, () => {
let hs: Headscale;
let tsd: Tailscaled;
let http: Server;
let dns: Socket;
let authKey = "";
let exitIp = "";
let online = false;
const hits: string[] = [];
const dnsHits: string[] = [];
before(async () => {
http = createServer((req, res) => {
hits.push(req.url ?? "");
res.end(`hello from ${hostIp}: ${req.url}\n`);
});
await new Promise<void>((r) => http.listen(HTTP_PORT, hostIp, r));
// Any A query: PROBE_ADDR; anything else: no answers.
dns = createSocket("udp4");
dns.on("message", (m, from) => {
let i = 12;
const labels: string[] = [];
while (i < m.length && m[i]) { labels.push(m.subarray(i + 1, i + 1 + m[i]!).toString()); i += 1 + m[i]!; }
const qend = i + 5, qtype = m.readUInt16BE(i + 1);
dnsHits.push(`${labels.join(".")}/${qtype}`);
const a = qtype === 1 ? Buffer.from([0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, ...PROBE_ADDR.split(".").map(Number)]) : Buffer.alloc(0);
const r = Buffer.concat([m.subarray(0, qend), a]);
r.writeUInt16BE(0x8180, 2);
r.writeUInt16BE(qtype === 1 ? 1 : 0, 6);
r.writeUInt32BE(0, 8);
dns.send(r, from.port, from.address);
});
await new Promise<void>((r) => dns.bind(DNS_PORT, hostIp, r));
online = await internet();
hs = await startHeadscale({ portBase: 18150, embeddedDerp: true });
const user = await hs.createUser("exits");
authKey = await hs.createAuthKey(user.id, { reusable: true });
tsd = await startTailscaled({ port: 18155 });
await tsd.up(hs.url, authKey, "exit", ["--advertise-exit-node", `--advertise-routes=${hostIp}/32`]);
exitIp = await tsd.ip4();
const node = (await hs.nodes()).find((n) => n.name === "exit" || n.given_name === "exit") as { id: number | string } | undefined;
assert.ok(node, "the exit node is registered");
await hs.cli(["nodes", "approve-routes", "--identifier", String(node.id), "--routes", "0.0.0.0/0,::/0"]);
});
after(async () => {
await tsd?.stop();
await hs?.stop();
http?.close();
http?.closeAllConnections();
dns?.close();
});
for (const worker of [false, true]) {
describe(worker ? "worker mode" : "inline", { concurrency: 1 }, () => {
let vm: KernelHandle;
let state: TailscaleControlState | undefined;
const logs: string[] = [];
const hostname = worker ? "exit-w" : "exit-i";
let guestIp = "";
const spec = (): NetSpec => ({
kind: "net", backend: { kind: "direct" }, hostLoopback: true,
tailscale: { controlURL: hs.url, authKey, hostname, state, exitNode: "exit" },
});
const sh = async (cmd: string) => {
const r = await vm.exec("sh", ["-c", cmd]);
return r.stdout + r.stderr;
};
/** Stats; in worker mode a snapshot taken after now (the worker sends one every 500 ms). */
const freshStats = async () => {
if (worker) await sleep(700);
return vm.stats().net!;
};
/** Waits until the guest owns the tailnet address with these routes. */
const guestRoutes = async (routes: string[]) => {
const ok = () => { const g = vm.tailscale!.status().guest; return g.mode === "address" && g.routes?.join() === routes.join(); };
for (let i = 0; i < 400 && !ok(); i++) await sleep(100);
assert.ok(ok(), JSON.stringify(vm.tailscale!.status().guest));
if (worker) await sleep(100); // the worker's RemoteTunnel hears it with the next status
};
const exitRoutes = ["100.64.0.0/10", "0.0.0.0/1", "128.0.0.0/1"];
const usable = async () => {
for (let i = 0; i < 200 && !vm.tailscale!.status().exitNode?.usable; i++) await sleep(100);
assert.equal(vm.tailscale!.status().exitNode?.usable, true, JSON.stringify(vm.tailscale!.status().exitNode));
};
const wget = (path: string, extra = "") => sh(`wget -q -T 8 ${extra} -O - http://${hostIp}:${HTTP_PORT}${path} 2>&1; echo "exit=$?"`);
const esc = (s: string) => s.replace(/\./g, "\\.");
before(async () => {
vm = await createKernel({ worker, log: (m) => logs.push(m), net: spec(), onTailscale: (e) => { if (e.type === "state") state = e.state; } } as Parameters<typeof createKernel>[0] & { worker: boolean });
await vm.tailscale!.ready(30000);
guestIp = vm.tailscale!.addresses[0]!;
await usable();
await guestRoutes(exitRoutes);
});
after(async () => {
await vm?.stop({ reason: "test cleanup" });
if (process.env.UNKERNEL_TS_LOG) console.log(logs.join("\n"));
});
test("the status lists the exit node, the chosen one is usable, the guest routes both halves of IPv4 from 100.x", async () => {
const s = vm.tailscale!.status();
assert.deepEqual(s.exitNodes.map((n) => [n.name, n.address, n.online]), [["exit.ts.test", exitIp, true]]);
assert.deepEqual(s.exitNode, { selected: "exit", usable: true, peer: { id: s.exitNodes[0]!.id, name: "exit.ts.test", hostname: "exit", address: exitIp, online: true } });
assert.ok(vm.tailscale!.routeTable().some((r) => r.prefix === "0.0.0.0/0" && r.peer === "exit.ts.test"));
assert.match(await sh(`ip route get ${hostIp}`), new RegExp(`src ${esc(guestIp)}`));
assert.match(await sh("ip route"), /^default via 10\.0\.2\.2/m, "the guest's own default route is still there");
});
test("HTTP to an address beyond the tailnet goes through the exit node, from 100.x, not to the backend", async () => {
const before = await freshStats();
const n = hits.length;
const out = await wget("/via-exit");
assert.match(out, new RegExp(`hello from ${esc(hostIp!)}: /via-exit`), out);
assert.match(out, /exit=0/);
const now = await freshStats();
assert.equal(now.tcpOpened, before.tcpOpened, "no NetStack TCP connection (the backend was not used)");
assert.ok(now.tunnel!.tx > before.tunnel!.tx && now.tunnel!.rx > before.tunnel!.rx, JSON.stringify(now.tunnel));
assert.ok(now.tunnel!.passed > before.tunnel!.passed, "from the guest's own 100.x, unrewritten");
assert.equal(hits.length, n + 1);
});
test("where this host reaches the internet: example.com resolves through the public fallback via the exit node, and HTTP to it works", async (t) => {
if (!online) return t.skip("no internet from this host");
assert.deepEqual(vm.tailscale!.exitDNS?.map((r) => r.port), [53, 53], "1.1.1.1 and 8.8.8.8 (headscale names no resolver here)");
const before = await freshStats();
const out = await sh("nslookup example.com");
assert.match(out, /Address:?\s+\d+\.\d+\.\d+\.\d+/, out);
assert.doesNotMatch(out, /198\.18\./, "a real address");
const now = await freshStats();
assert.ok(now.tunnel!.dnsForwarded > before.tunnel!.dnsForwarded, JSON.stringify(now.tunnel));
const page = await sh("wget -q -T 15 -O - http://example.com/ 2>&1 | head -c 2000; echo; echo exit=$?");
assert.match(page, /Example Domain/i, page);
assert.equal((await freshStats()).tcpOpened, now.tcpOpened, "not through the backend");
});
test("fail closed: an exit node the netmap lacks means host unreachable and SERVFAIL, and nothing reaches the backend", async () => {
vm.tailscale!.setExitNode("nobody");
assert.deepEqual(vm.tailscale!.status().exitNode, { selected: "nobody", usable: false, reason: "not found" });
if (worker) await sleep(200);
const before = await freshStats();
const n = hits.length, d = dnsHits.length;
const t0 = performance.now();
const out = await wget("/closed");
assert.doesNotMatch(out, /exit=0/, out);
assert.match(out, /unreachable|No route/i, out);
assert.ok(performance.now() - t0 < 6000, "refused at once, not timed out");
const dnsOut = await sh(`nslookup ${PROBE_NAME}`);
assert.doesNotMatch(dnsOut, new RegExp(esc(PROBE_ADDR)), dnsOut);
assert.match(await sh("ping -c 1 -W 3 1.1.1.1"), /0 packets received|unreachable/i);
const now = await freshStats();
assert.equal(now.tcpOpened, before.tcpOpened, "no backend TCP");
assert.ok(now.tunnel!.noRoute > before.tunnel!.noRoute);
assert.ok(now.tunnel!.dnsFailed > before.tunnel!.dnsFailed);
assert.deepEqual([hits.length, dnsHits.length], [n, d], "the servers saw nothing");
assert.match(await sh(`ip route get ${hostIp}`), new RegExp(`src ${esc(guestIp)}`), "the guest still routes through 100.x");
});
test("none chosen: the guest's routes and the direct backend as without an exit node", async () => {
vm.tailscale!.setExitNode(null);
await guestRoutes(["100.64.0.0/10"]);
assert.equal(vm.tailscale!.status().exitNode, null);
assert.match(await sh(`ip route get ${hostIp}`), /src 10\.0\.2\.15/);
assert.match(await sh("ip route"), /^default via 10\.0\.2\.2/m);
const before = await freshStats();
const out = await wget("/direct");
assert.match(out, /hello from .*: \/direct/, out);
const now = await freshStats();
assert.equal(now.tcpOpened, before.tcpOpened + 1, "a NetStack TCP connection to the backend");
assert.equal(now.tunnel!.tx, before.tunnel!.tx, "nothing into the tunnel");
});
test("chosen again at run time (by its 100.x address): HTTP and DNS through it", async () => {
// The exit node's DNS servers: the local one (the netmap can only name port 53).
const ts = vm.tailscale!;
const get = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ts), "exitDNS")!.get!;
Object.defineProperty(ts, "exitDNS", { configurable: true, get: () => { const r = get.call(ts); return r?.length ? [{ ip: ip4(hostIp!), port: DNS_PORT }] : r; } });
try {
ts.setExitNode(exitIp);
await usable();
await guestRoutes(exitRoutes);
const before = await freshStats();
const out = await wget("/again");
assert.match(out, /: \/again/, out);
const d = dnsHits.length;
const dnsOut = await sh(`nslookup ${PROBE_NAME}`);
assert.match(dnsOut, new RegExp(esc(PROBE_ADDR)), dnsOut);
assert.ok(dnsHits.slice(d).includes(`${PROBE_NAME}/1`), dnsHits.join());
assert.ok(!dnsHits.slice(d).some((h) => h.endsWith("/28")), "AAAA stays local");
// MagicDNS still answers first.
assert.match(await sh("nslookup exit"), new RegExp(`Address:?\\s+${esc(exitIp)}`));
assert.ok(!dnsHits.slice(d).some((h) => h.startsWith("exit")));
const now = await freshStats();
assert.equal(now.tcpOpened, before.tcpOpened);
assert.ok(now.tunnel!.dnsForwarded > before.tunnel!.dnsForwarded);
} finally {
delete (ts as unknown as Record<string, unknown>).exitDNS;
}
});
});
}
test("the rewrite of 10.0.2.15 alone (guestAddress: false): HTTP through the exit node, and none chosen the backend", async (t) => {
const vm = await createKernel({
log: () => {},
net: { kind: "net", backend: { kind: "direct" }, tailscale: { controlURL: hs.url, authKey, hostname: "exit-rw", guestAddress: false, exitNode: "exit.ts.test" } },
});
t.after(() => vm.stop({ reason: "test cleanup" }));
await vm.tailscale!.ready(30000);
for (let i = 0; i < 200 && !vm.tailscale!.status().exitNode?.usable; i++) await sleep(100);
const sh = async (cmd: string) => { const r = await vm.exec("sh", ["-c", cmd]); return r.stdout + r.stderr; };
assert.match(await sh(`ip route get ${hostIp}`), /src 10\.0\.2\.15/);
const before = vm.stats().net!;
assert.match(await sh(`wget -q -T 8 -O - http://${hostIp}:${HTTP_PORT}/rewritten`), /: \/rewritten/);
const now = vm.stats().net!;
assert.equal(now.tcpOpened, before.tcpOpened, "not the backend");
assert.equal(now.tunnel!.mode, "rewrite");
assert.ok(now.tunnel!.tx > before.tunnel!.tx);
vm.tailscale!.setExitNode(null);
assert.match(await sh(`wget -q -T 8 -O - http://${hostIp}:${HTTP_PORT}/plain`), /: \/plain/);
assert.equal(vm.stats().net!.tcpOpened, now.tcpOpened + 1, "the backend again");
});
});