mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 07:59:39 +08:00
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.
367 lines
18 KiB
TypeScript
367 lines
18 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// The guest on a tailnet (NetSpec.tailscale): the bundled kernel's base
|
|
// shell joins a local headscale (embedded DERP, 127.0.0.1:18120-18123) next
|
|
// to a real tailscaled (userspace networking, UDP 18125), inline and in
|
|
// worker mode. The guest pings the real node, fetches from a host HTTP
|
|
// server through it (tailscaled forwards inbound tailnet TCP to
|
|
// 127.0.0.1:18127) including an 8 MiB body checked by SHA-256, resolves
|
|
// MagicDNS names, serves a connection the real node opens (tailscale nc),
|
|
// and still reaches the host (10.0.2.2, hostLoopback) through the direct
|
|
// backend; then a snapshot with the tunnel on, restored. Skips without
|
|
// the headscale or tailscale binaries.
|
|
//
|
|
// node --test test/tailscale-guest.test.ts
|
|
import test, { after, before, describe } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { spawn } from "node:child_process";
|
|
import { createHash, randomBytes } from "node:crypto";
|
|
import { createServer, type Server } from "node:http";
|
|
import { join } from "node:path";
|
|
import { createKernel, decodeSnapshot, encodeSnapshot, type KernelHandle, type NetSpec, type TailscaleControlState, type TailscaleEvent } from "../js/node.ts";
|
|
import { TAILSCALE_DIR, headscaleAvailable, startHeadscale, startTailscaled, tailscaleAvailable, type Headscale, type Tailscaled } from "./tailscale-fixture.ts";
|
|
|
|
const HTTP_PORT = 18127;
|
|
const BIG = 8 << 20;
|
|
const skip = !headscaleAvailable() ? "no headscale binary" : !tailscaleAvailable() ? "no tailscale binaries (vendor/toolchain/tailscale)" : false;
|
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
|
|
describe("guest on a tailnet", { skip, concurrency: 1 }, () => {
|
|
let hs: Headscale;
|
|
let tsd: Tailscaled;
|
|
let http: Server;
|
|
let authKey = "";
|
|
let realIp = "";
|
|
const big = randomBytes(BIG);
|
|
const bigSha = createHash("sha256").update(big).digest("hex");
|
|
let hostHits = 0;
|
|
|
|
before(async () => {
|
|
http = createServer((req, res) => {
|
|
hostHits++;
|
|
if (req.url === "/up") {
|
|
const h = createHash("sha256");
|
|
let n = 0;
|
|
req.on("data", (d: Buffer) => { h.update(d); n += d.length; });
|
|
req.on("end", () => res.end(`${n} ${h.digest("hex")}\n`));
|
|
return;
|
|
}
|
|
if (req.url === "/slow") {
|
|
setTimeout(() => res.end("slow\n"), 3000);
|
|
return;
|
|
}
|
|
if (req.url === "/big") {
|
|
res.writeHead(200, { "content-length": String(big.length) });
|
|
res.end(big);
|
|
} else res.end(`hello from the host: ${req.url}\n`);
|
|
});
|
|
await new Promise<void>((r) => http.listen(HTTP_PORT, "127.0.0.1", r));
|
|
hs = await startHeadscale({ portBase: 18120, embeddedDerp: true });
|
|
const user = await hs.createUser("guests");
|
|
authKey = await hs.createAuthKey(user.id, { reusable: true });
|
|
tsd = await startTailscaled({ port: 18125 });
|
|
await tsd.up(hs.url, authKey, "real");
|
|
realIp = await tsd.ip4();
|
|
});
|
|
|
|
after(async () => {
|
|
await tsd?.stop();
|
|
await hs?.stop();
|
|
http?.close();
|
|
http?.closeAllConnections();
|
|
});
|
|
|
|
for (const worker of [false, true]) {
|
|
describe(worker ? "worker mode" : "inline", { concurrency: 1 }, () => {
|
|
let vm: KernelHandle;
|
|
let state: TailscaleControlState | undefined;
|
|
const events: TailscaleEvent[] = [];
|
|
const logs: string[] = [];
|
|
const hostname = worker ? "guest-w" : "guest";
|
|
const spec = (): NetSpec => ({
|
|
kind: "net", backend: { kind: "direct" }, hostLoopback: true,
|
|
tailscale: { controlURL: hs.url, authKey, hostname, state },
|
|
});
|
|
const onTailscale = (e: TailscaleEvent) => {
|
|
events.push(e);
|
|
if (e.type === "state") state = e.state;
|
|
};
|
|
const sh = async (cmd: string) => {
|
|
const r = await vm.exec("sh", ["-c", cmd]);
|
|
return r.stdout + r.stderr;
|
|
};
|
|
let guestIp = "";
|
|
/** Sources of the TCP SYNs the guest sent into the tunnel. */
|
|
const synSources: string[] = [];
|
|
/** Waits until the guest owns the tailnet address (or for "rewrite": no longer). */
|
|
const guestMode = async (mode: "address" | "rewrite") => {
|
|
for (let i = 0; i < 400 && vm.tailscale!.status().guest.mode !== mode; i++) await sleep(100);
|
|
assert.equal(vm.tailscale!.status().guest.mode, mode, JSON.stringify(vm.tailscale!.status().guest));
|
|
};
|
|
const watchSyns = () => {
|
|
const ts = vm.tailscale! as unknown as { sendPacket(ip: Uint8Array): boolean };
|
|
const send = ts.sendPacket.bind(ts);
|
|
ts.sendPacket = (ip) => {
|
|
if (ip[9] === 6 && (ip[33]! & 0x12) === 0x02) synSources.push(ip.subarray(12, 16).join("."));
|
|
return send(ip);
|
|
};
|
|
};
|
|
/** 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();
|
|
};
|
|
|
|
before(async () => {
|
|
vm = await createKernel({ worker, log: (m) => logs.push(m), net: spec(), onTailscale } as Parameters<typeof createKernel>[0] & { worker: boolean });
|
|
await vm.tailscale!.ready(30000);
|
|
guestIp = vm.tailscale!.addresses[0]!;
|
|
watchSyns();
|
|
await guestMode("address");
|
|
});
|
|
|
|
after(async () => {
|
|
await vm?.stop({ reason: "test cleanup" });
|
|
if (process.env.UNKERNEL_TS_LOG) console.log(logs.join("\n"));
|
|
});
|
|
|
|
test("joins: state, status events and the node's address", () => {
|
|
assert.match(guestIp, /^100\.64\./);
|
|
assert.ok(state?.authorized, "a state event with the registration");
|
|
assert.ok(events.some((e) => e.type === "status" && e.status.state === "running"));
|
|
assert.equal(vm.tailscale!.status().homeDERP, 999);
|
|
});
|
|
|
|
test("the guest has the tailnet address on tailscale0 and routes the tailnet from it", async () => {
|
|
assert.match(await sh("ip -4 addr show dev tailscale0"), new RegExp(`inet ${guestIp.replace(/\./g, "\\.")}/32`));
|
|
assert.match(await sh(`ip route get ${realIp}`), new RegExp(`src ${guestIp.replace(/\./g, "\\.")}`));
|
|
assert.match(await sh("ip route get 1.1.1.1"), /src 10\.0\.2\.15/);
|
|
const g = vm.tailscale!.status().guest;
|
|
assert.deepEqual([g.mode, g.interface, g.address, g.routes], ["address", "tailscale0", guestIp, ["100.64.0.0/10"]]);
|
|
});
|
|
|
|
test("outbound from the guest leaves from 100.x, and the guest's socket says so", async () => {
|
|
const before = synSources.length;
|
|
const hex = (ip: string) => ip.split(".").map(Number).reverse().map((b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();
|
|
const out = await sh(`wget -q -O - http://${realIp}:${HTTP_PORT}/slow >/dev/null & sleep 1; cat /proc/net/tcp; wait`);
|
|
const row = out.split("\n").find((l) => l.includes(`${hex(realIp)}:${HTTP_PORT.toString(16).toUpperCase().padStart(4, "0")}`));
|
|
assert.ok(row, out);
|
|
assert.match(row!, new RegExp(`^\\s*\\d+: ${hex(guestIp)}:`), "the local address is 100.x");
|
|
assert.deepEqual(synSources.slice(before), [guestIp], "the SYN went into the tunnel from 100.x, unrewritten");
|
|
});
|
|
|
|
test("a guest server bound to the 100.x address takes the real node's connection", async () => {
|
|
const srv = await vm.spawn("nc", ["-lk", "-s", guestIp, "-p", "8082", "-e", "sh", "-c", "read line; echo \"bound-ok $line\""], { pty: false });
|
|
void new Response(srv.stdout).arrayBuffer().catch(() => {});
|
|
void new Response(srv.stderr).arrayBuffer().catch(() => {});
|
|
let out = "";
|
|
for (let i = 0; i < 20 && !out.includes("bound-ok"); i++) {
|
|
out = await tailscaleNc(tsd, guestIp, 8082, "to the bound server\n").catch((e) => String(e));
|
|
if (!out.includes("bound-ok")) await sleep(250);
|
|
}
|
|
assert.match(out, /^bound-ok to the bound server$/m);
|
|
srv.kill();
|
|
assert.equal((await freshStats()).net!.tunnel!.mode, "address");
|
|
});
|
|
|
|
test("the guest pings the real node's 100.x address", async () => {
|
|
const out = await sh(`ping -c 3 -W 5 ${realIp}`);
|
|
assert.match(out, /3 packets transmitted, 3 packets received/, out);
|
|
});
|
|
|
|
test("MagicDNS names resolve in the guest (short, full, at 100.100.100.100)", async () => {
|
|
assert.match(await sh("nslookup real"), new RegExp(`Address: ${realIp.replace(/\./g, "\\.")}`));
|
|
assert.match(await sh("nslookup real.ts.test 100.100.100.100"), new RegExp(`Address: ${realIp.replace(/\./g, "\\.")}`));
|
|
assert.match(await sh(`ping -c 1 -W 5 ${hostname}`), /1 packets received/, "its own name");
|
|
});
|
|
|
|
test("HTTP through the real node, by name: a small body and 8 MiB checked by SHA-256", async () => {
|
|
assert.match(await sh(`wget -q -O - http://real:${HTTP_PORT}/hi`), /hello from the host: \/hi/);
|
|
const t0 = performance.now();
|
|
const out = await sh(`wget -q -O - http://real.ts.test:${HTTP_PORT}/big | sha256sum`);
|
|
const s = (performance.now() - t0) / 1000;
|
|
assert.ok(out.startsWith(bigSha), out);
|
|
console.log(`# ${worker ? "worker" : "inline"}: 8 MiB through the tunnel in ${s.toFixed(2)} s (${(BIG / 1048576 / s).toFixed(2)} MiB/s)`);
|
|
const st = (await freshStats()).net?.tunnel;
|
|
assert.ok(st && st.rxBytes > BIG, JSON.stringify(st));
|
|
assert.ok(st.passed > BIG / 1400, "unrewritten");
|
|
});
|
|
|
|
test("an upload from the guest (TSO segments cut to the tunnel's MTU, MSS clamped): 4 MiB checked by SHA-256", async () => {
|
|
// Text: busybox wget's --post-file stops at the first NUL.
|
|
const out = await sh("dd if=/dev/urandom bs=3072 count=1024 2>/dev/null | base64 -w 0 | head -c 4194304 >/tmp/up; sha256sum /tmp/up");
|
|
const sha = out.split(" ")[0]!;
|
|
const t0 = performance.now();
|
|
const got = await sh(`wget -q -O - --post-file=/tmp/up http://real:${HTTP_PORT}/up`);
|
|
const s = (performance.now() - t0) / 1000;
|
|
assert.equal(got.trim(), `${4 << 20} ${sha}`);
|
|
console.log(`# ${worker ? "worker" : "inline"}: 4 MiB up through the tunnel in ${s.toFixed(2)} s (${(4 / s).toFixed(2)} MiB/s)`);
|
|
const st = (await freshStats()).net!.tunnel!;
|
|
assert.ok(st.txBytes > 4 << 20, JSON.stringify(st));
|
|
assert.equal(st.fragNeeded, 0);
|
|
assert.ok(st.segmented > 0, "the guest's TSO segments were cut");
|
|
});
|
|
|
|
test("the real node connects to a server in the guest (tailscale nc)", async () => {
|
|
// One line in, one out (unread input would make the guest's close a reset).
|
|
const srv = await vm.spawn("nc", ["-lk", "-p", "8080", "-e", "sh", "-c", "read line; echo \"guest-ok $line\""], { pty: false });
|
|
void new Response(srv.stdout).arrayBuffer().catch(() => {});
|
|
void new Response(srv.stderr).arrayBuffer().catch(() => {});
|
|
let out = "";
|
|
for (let i = 0; i < 20 && !out.includes("guest-ok"); i++) {
|
|
out = await tailscaleNc(tsd, guestIp, 8080, "hello from the real node\n").catch((e) => String(e));
|
|
if (!out.includes("guest-ok")) await sleep(250);
|
|
}
|
|
assert.match(out, /^guest-ok hello from the real node$/m);
|
|
srv.kill();
|
|
});
|
|
|
|
test("tailscale ping --icmp from the real node is answered by the guest", async () => {
|
|
const out = await tsd.cli(["ping", "--icmp", "--c", "2", guestIp]);
|
|
assert.match(out, new RegExp(`pong from ${hostname} `));
|
|
});
|
|
|
|
test("traffic outside the tailnet keeps the direct backend", async () => {
|
|
const before = (await freshStats()).net!;
|
|
const hits = hostHits;
|
|
assert.match(await sh(`wget -q -O - http://10.0.2.2:${HTTP_PORT}/direct`), /hello from the host: \/direct/);
|
|
const now = (await freshStats()).net!;
|
|
assert.ok(now.tcpOpened > before.tcpOpened, "a NetStack TCP connection");
|
|
assert.equal(hostHits, hits + 1);
|
|
});
|
|
|
|
test("the guest's network set up again (a DHCP discover): its address is configured again", async () => {
|
|
const configured = () => logs.filter((l) => l.includes(`guest: ${guestIp} on tailscale0`)).length;
|
|
const n = configured();
|
|
await sh("ip link del tailscale0; udhcpc -i eth0 -n -q >/dev/null 2>&1; true");
|
|
for (let i = 0; i < 300 && configured() === n; i++) await sleep(100);
|
|
assert.equal(configured(), n + 1, "configured once more");
|
|
await guestMode("address");
|
|
assert.match(await sh("ip -4 addr show dev tailscale0"), new RegExp(`inet ${guestIp.replace(/\./g, "\\.")}/32`));
|
|
assert.match(await sh(`ping -c 1 -W 5 ${realIp}`), /1 packets received/);
|
|
});
|
|
|
|
{
|
|
test("a snapshot with the tunnel on, restored: the node comes back with the saved state", async () => {
|
|
let snap;
|
|
for (let i = 0; ; i++) {
|
|
try {
|
|
snap = await vm.snapshot({ stop: true });
|
|
break;
|
|
} catch (e) {
|
|
if (i >= 40 || !/in flight/.test(String((e as Error)?.message))) throw e;
|
|
await sleep(50);
|
|
}
|
|
}
|
|
await vm.exited;
|
|
assert.equal(vm.tailscale!.status().state, "stopped", "closed with the kernel");
|
|
const restored = decodeSnapshot(encodeSnapshot(snap));
|
|
vm = await createKernel({ worker, log: (m) => logs.push(m), net: spec(), onTailscale, restore: restored } as Parameters<typeof createKernel>[0] & { worker: boolean });
|
|
await vm.tailscale!.ready(30000);
|
|
assert.equal(vm.tailscale!.addresses[0], guestIp, "the same node");
|
|
watchSyns();
|
|
await guestMode("address");
|
|
// The restored guest had the address already: configured again, it has it once.
|
|
assert.equal((await sh("ip -4 addr show dev tailscale0 | grep -c inet")).trim(), "1");
|
|
const out = await sh(`ping -c 2 -W 5 ${realIp}`);
|
|
assert.match(out, /2 packets received/, out);
|
|
assert.match(await sh(`wget -q -O - http://real:${HTTP_PORT}/after`), /hello from the host: \/after/);
|
|
});
|
|
|
|
test("logout takes the address away from the guest", async () => {
|
|
await vm.tailscale!.logout();
|
|
assert.equal(vm.tailscale!.status().guest.mode, "rewrite");
|
|
assert.match(await sh("ip link show tailscale0 || echo gone"), /gone/);
|
|
assert.match(await sh("ip route"), /^(?![\s\S]*100\.64\.0\.0\/10)/, "no tailnet route left");
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
// The rewrite: asked for (guestAddress: false), and where nothing can configure the guest (no kwtty).
|
|
for (const fallback of ["guestAddress: false", "vsock: false"] as const) {
|
|
test(`the rewrite of 10.0.2.15 alone (${fallback}): ping, HTTP both ways, inbound`, async (t) => {
|
|
const hostname = fallback === "vsock: false" ? "guest-nv" : "guest-rw";
|
|
let text = "";
|
|
const vm = await createKernel({
|
|
log: () => {}, onOutput: (b) => (text += new TextDecoder().decode(b)),
|
|
...(fallback === "vsock: false" ? { vsock: false } : {}),
|
|
net: { kind: "net", backend: { kind: "direct" }, tailscale: { controlURL: hs.url, authKey, hostname, ...(fallback === "guestAddress: false" ? { guestAddress: false } : {}) } },
|
|
});
|
|
t.after(() => vm.stop({ reason: "test cleanup" }));
|
|
await vm.tailscale!.ready(30000);
|
|
const ip = vm.tailscale!.addresses[0]!;
|
|
const g = vm.tailscale!.status().guest;
|
|
assert.deepEqual([g.mode, g.enabled], ["rewrite", false]);
|
|
if (fallback === "vsock: false") {
|
|
// No exec: the console. The same checks, by their output.
|
|
vm.write(`ip -4 addr show dev tailscale0 2>&1 | head -1; ping -c 2 -W 5 ${realIp}; wget -q -O - http://real:${HTTP_PORT}/big | sha256sum; echo DONE-MARK\n`);
|
|
for (let i = 0; i < 600 && !/DONE-MARK\s*$/m.test(text.split("echo DONE-MARK").at(-1) ?? ""); i++) await sleep(100);
|
|
const out = text.split("echo DONE-MARK").at(-1)!;
|
|
assert.match(out, /2 packets received/, out);
|
|
assert.match(out, new RegExp(bigSha));
|
|
assert.doesNotMatch(out, /inet 100\./);
|
|
const back = await tsd.cli(["ping", "--icmp", "--c", "2", ip]);
|
|
assert.match(back, new RegExp(`pong from ${hostname} `));
|
|
return;
|
|
}
|
|
const sh = async (cmd: string) => { const r = await vm.exec("sh", ["-c", cmd]); return r.stdout + r.stderr; };
|
|
assert.match(await sh("ip link show tailscale0 || echo none"), /none/);
|
|
assert.match(await sh(`ping -c 2 -W 5 ${realIp}`), /2 packets received/);
|
|
assert.ok((await sh(`wget -q -O - http://real:${HTTP_PORT}/big | sha256sum`)).startsWith(bigSha));
|
|
const up = await sh("dd if=/dev/urandom bs=3072 count=256 2>/dev/null | base64 -w 0 >/tmp/up; sha256sum /tmp/up");
|
|
assert.equal((await sh(`wget -q -O - --post-file=/tmp/up http://real:${HTTP_PORT}/up`)).trim().split(" ")[1], up.split(" ")[0]);
|
|
const srv = await vm.spawn("nc", ["-lk", "-p", "8083", "-e", "sh", "-c", "read line; echo \"rw-ok $line\""], { pty: false });
|
|
void new Response(srv.stdout).arrayBuffer().catch(() => {});
|
|
void new Response(srv.stderr).arrayBuffer().catch(() => {});
|
|
let out = "";
|
|
for (let i = 0; i < 20 && !out.includes("rw-ok"); i++) {
|
|
out = await tailscaleNc(tsd, ip, 8083, "hi\n").catch((e) => String(e));
|
|
if (!out.includes("rw-ok")) await sleep(250);
|
|
}
|
|
assert.match(out, /^rw-ok hi$/m);
|
|
const st = vm.stats().net!.tunnel!;
|
|
assert.equal(st.mode, "rewrite");
|
|
assert.equal(st.passed, 0);
|
|
});
|
|
}
|
|
});
|
|
|
|
/** `tailscale nc` on the real node: sends `input`, returns what came back once the guest closed. */
|
|
function tailscaleNc(tsd: Tailscaled, ip: string, port: number, input: string): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
const child = spawn(join(TAILSCALE_DIR, "tailscale"), [`--socket=${tsd.socket}`, "nc", ip, String(port)], { stdio: ["pipe", "pipe", "pipe"] });
|
|
let out = "", err = "";
|
|
child.stdout.on("data", (d: Buffer) => (out += d));
|
|
child.stderr.on("data", (d: Buffer) => (err += d));
|
|
const t = setTimeout(() => child.kill(), 10000);
|
|
child.on("exit", () => {
|
|
clearTimeout(t);
|
|
if (out) resolve(out);
|
|
else reject(new Error(`tailscale nc: ${err}`));
|
|
});
|
|
child.stdin.write(input);
|
|
});
|
|
}
|
|
|
|
test("a boot that fails after the node started still closes the node", async () => {
|
|
const states: string[] = [];
|
|
await assert.rejects(createKernel({
|
|
log: () => {},
|
|
memoryMiB: 1 << 20, memoryFallbackMiB: [], // more memory than any host gives: the boot fails
|
|
net: { kind: "net", backend: { kind: "direct" }, tailscale: { controlURL: "http://127.0.0.1:18139", authKey: "unused", hostname: "never" } },
|
|
onTailscale: (e) => { if (e.type === "status") states.push(e.status.state); },
|
|
}));
|
|
for (let i = 0; i < 100 && !states.includes("stopped"); i++) await sleep(20);
|
|
assert.ok(states.includes("stopped"), states.join());
|
|
// A network spec whose backend this platform lacks fails after the node started.
|
|
const states2: string[] = [];
|
|
await assert.rejects(createKernel({
|
|
log: () => {},
|
|
net: { kind: "net", backend: { kind: "nope" } as never, tailscale: { controlURL: "http://127.0.0.1:18139", authKey: "unused", hostname: "never" } },
|
|
onTailscale: (e) => { if (e.type === "status") states2.push(e.status.state); },
|
|
}), /not available/);
|
|
for (let i = 0; i < 100 && !states2.includes("stopped"); i++) await sleep(20);
|
|
assert.ok(states2.includes("stopped"), states2.join());
|
|
});
|