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

572 lines
27 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Opt-in end-to-end tests against Tailscale's real service (control at
// https://controlplane.tailscale.com, the real DERP map), on the tailnet
// of whoever gave the auth key. Skips unless TS_LIVE_STATE names a
// directory (mode 700) for the nodes' state; TS_AUTHKEY registers a node
// whose state is not there yet, and the state is written at once, so a
// single-use key serves the JS node and later runs reuse it (no
// re-registration). Never logs a secret. TS_AUTHKEY is read from the
// environment, so clear it (TS_AUTHKEY=) where the shell holds another
// one (a container's own tailscaled key, say).
//
// TS_LIVE_STATE=DIR TS_AUTHKEY="$(cat keyfile)" node --test test/tailscale-live.test.ts
//
// Nodes, named TS_LIVE_NAME-<role> (default unkernel-e2e-<role>): "js",
// the JS client under test (DIR/js.json, used by the client, the guest
// inline and in worker mode, one at a time), and "tsd", a real tailscaled
// (vendor/toolchain/tailscale, userspace networking, state in DIR/tsd, UDP
// 18141, its CLI socket in the system temp dir) as the peer. The peer's
// tests skip when it cannot register (a single-use key already spent by
// the JS node: the reason is printed). Nothing else of the tailnet is
// contacted; nothing is advertised.
//
// Other variables: TS_LIVE_CONTROL (another control URL, e.g. a local
// headscale's, to check this file itself), TS_LIVE_LONG=1 (a WireGuard
// rekey under traffic, 150 s, and 10 min idle), TS_LIVE_LOGOUT=1 (last:
// both nodes log out; their state is then useless). Ports 18141-18145.
import test, { after, before, describe } from "node:test";
import assert from "node:assert/strict";
import { spawn, execFile } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { open, rm } from "node:fs/promises";
import { createServer, type Server } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { ControlClient, DEFAULT_CONTROL_URL, controlWebSocketURL, keyFromText, type ControlState, type MapResponse } from "../js/core/tailscale/control.ts";
import { dialNoise } from "../js/core/tailscale/control-noise.ts";
import { parseRange4 } from "../js/core/tailscale/filter.ts";
import { randomBytes as tsRandom } from "../js/core/tailscale/crypto.ts";
import { TailscaleClient, type TailscaleClientOptions } from "../js/core/tailscale/client.ts";
import { createKernel, decodeSnapshot, encodeSnapshot, type KernelHandle, type NetSpec, type TailscaleEvent } from "../js/node.ts";
import { TAILSCALE_DIR, tailscaleAvailable } from "./tailscale-fixture.ts";
const DIR = process.env.TS_LIVE_STATE ?? "";
const AUTHKEY = process.env.TS_AUTHKEY ?? "";
const CONTROL = (process.env.TS_LIVE_CONTROL ?? DEFAULT_CONTROL_URL).replace(/\/+$/, "");
const NAME = process.env.TS_LIVE_NAME ?? "unkernel-e2e";
const LONG = process.env.TS_LIVE_LONG === "1";
const JS_FILE = join(DIR, "js.json");
const TSD_DIR = join(DIR, "tsd");
const TSD_PORT = 18141, HTTP_PORT = 18144;
const skip = !DIR ? "set TS_LIVE_STATE to a state directory (and TS_AUTHKEY for a first registration)"
: !existsSync(JS_FILE) && !AUTHKEY ? `no ${JS_FILE} and no TS_AUTHKEY` : false;
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
/** The text with the auth key and any private key taken out. */
function redact(s: string): string {
if (AUTHKEY) s = s.split(AUTHKEY).join("<authkey>");
return s.replace(/privkey:[0-9a-f]{64}/g, "privkey:<redacted>").replace(/tskey-[A-Za-z0-9-]+/g, "tskey-<redacted>");
}
const say = (m: string) => console.log(`# ${redact(m)}`);
function loadJs(): ControlState | undefined {
return existsSync(JS_FILE) ? JSON.parse(readFileSync(JS_FILE, "utf8")) as ControlState : undefined;
}
function saveJs(s: ControlState): void {
writeFileSync(JS_FILE + ".tmp", JSON.stringify(s), { mode: 0o600 });
renameSync(JS_FILE + ".tmp", JS_FILE);
}
/** A WebSocket whose instances a test can cut, or make never open (hosts matching `failing`). */
const sockets: TapSocket[] = [];
let failing: RegExp | null = null;
class TapSocket {
readonly ws: WebSocket;
readonly url: string;
constructor(url: string, protocols?: string | string[]) {
this.url = url;
this.ws = new WebSocket(failing?.test(url) ? "ws://127.0.0.1:18145/" : url, protocols);
sockets.push(this);
}
get binaryType() { return this.ws.binaryType; }
set binaryType(v: BinaryType) { this.ws.binaryType = v; }
get readyState() { return this.ws.readyState; }
get bufferedAmount() { return this.ws.bufferedAmount; }
get protocol() { return this.ws.protocol; }
send(d: Uint8Array) { this.ws.send(d as Uint8Array<ArrayBuffer>); }
close(code?: number, reason?: string) { this.ws.close(code, reason); }
set onopen(f: ((e: Event) => void) | null) { this.ws.onopen = f; }
get onopen() { return this.ws.onopen as never; }
set onmessage(f: ((e: MessageEvent) => void) | null) { this.ws.onmessage = f; }
get onmessage() { return this.ws.onmessage as never; }
set onclose(f: ((e: CloseEvent) => void) | null) { this.ws.onclose = f; }
get onclose() { return this.ws.onclose as never; }
set onerror(f: ((e: Event) => void) | null) { this.ws.onerror = f; }
get onerror() { return this.ws.onerror as never; }
}
const openSockets = (re: RegExp) => sockets.filter((s) => re.test(s.url) && s.ws.readyState === 1);
/** The JS client with the saved state (or the auth key for a first registration), the state saved on every change. */
function jsClient(extra: Partial<TailscaleClientOptions> = {}, logs: string[] = []): TailscaleClient {
const state = loadJs();
return new TailscaleClient({
controlURL: CONTROL, hostname: `${NAME}-js`, state, authKey: state?.authorized ? undefined : AUTHKEY || undefined,
WebSocket: TapSocket as never, onState: saveJs, log: (m) => logs.push(redact(m)), ...extra,
});
}
// ---- the real tailscaled ----
interface Peer {
cli(args: string[], ms?: number, input?: string): Promise<string>;
/** `tailscale nc`: sends `input` (stdin left open), resolves with what came back by the time `until` matches or 10 s passed. */
nc(ip: string, port: number, input: string, until: RegExp): Promise<string>;
ip4: string;
name: string;
stop(): Promise<void>;
}
async function startPeer(): Promise<Peer | string> {
if (!tailscaleAvailable()) return "no tailscale binaries";
mkdirSync(TSD_DIR, { recursive: true, mode: 0o700 });
const socket = join(tmpdir(), `unkernel-live-${process.pid}.sock`);
// TS_DEBUG_USE_DERP_HTTP: a plain-http control's embedded DERP (headscale's, for TS_LIVE_CONTROL).
const env = { ...process.env, TS_LOGS_DIR: TSD_DIR, TS_NO_LOGS_NO_SUPPORT: "true", TS_AUTHKEY: "", ...(CONTROL.startsWith("http:") ? { TS_DEBUG_USE_DERP_HTTP: "1" } : {}) };
let out = "";
const child = spawn(join(TAILSCALE_DIR, "tailscaled"), ["--tun=userspace-networking", `--socket=${socket}`, `--statedir=${TSD_DIR}`, `--port=${TSD_PORT}`], { env, stdio: ["ignore", "pipe", "pipe"] });
child.stdout!.on("data", (d: Buffer) => (out += d));
child.stderr!.on("data", (d: Buffer) => (out += d));
const exited = new Promise<void>((r) => child.once("exit", () => r()));
const stop = async () => {
child.kill("SIGTERM");
const t = setTimeout(() => child.kill("SIGKILL"), 5000);
await exited;
clearTimeout(t);
};
const cli = (args: string[], ms = 30000, input?: string) => new Promise<string>((resolve, reject) => {
const p = execFile(join(TAILSCALE_DIR, "tailscale"), [`--socket=${socket}`, ...args], { env, timeout: ms }, (err, stdout, stderr) => {
if (err) reject(new Error(redact(`tailscale ${args.join(" ")}: ${err.message}\n${stderr}${stdout}`)));
else resolve(stdout);
});
if (input !== undefined) p.stdin!.end(input);
});
/** tailscale up with the auth key read from a FIFO (never on a command line, never in a file). */
const up = async () => {
const fifo = join(DIR, `authkey-${process.pid}.fifo`);
await new Promise<void>((ok, fail) => execFile("mkfifo", ["-m", "600", fifo], (e) => (e ? fail(e) : ok())));
try {
const run = cli(["up", `--login-server=${CONTROL}`, `--auth-key=file:${fifo}`, `--hostname=${NAME}-tsd`, "--accept-dns=false"], 60000);
const w = await open(fifo, "w");
await w.writeFile(AUTHKEY);
await w.close();
await run;
return "";
} catch (e) {
return (e as Error).message;
} finally {
await rm(fifo, { force: true });
}
};
for (let i = 0; ; i++) {
if (await cli(["status", "--json"], 5000).then(() => true, () => false)) break;
if (i > 150) {
await stop();
return `tailscaled did not start: ${redact(out.slice(-500))}`;
}
await sleep(100);
}
const status = async () => JSON.parse(await cli(["status", "--json"])) as { BackendState: string; Self: { TailscaleIPs?: string[]; DNSName?: string } };
let state = "";
for (let i = 0; i < 150 && !/^(Running|NeedsLogin|NeedsMachineAuth|Stopped)$/.test(state = (await status()).BackendState); i++) await sleep(100);
if (state === "NeedsMachineAuth") {
await stop();
return "tailscaled needs machine approval in the admin console";
}
if (state !== "Running") {
if (!AUTHKEY) {
await stop();
return "tailscaled has no saved login and there is no TS_AUTHKEY";
}
const err = await up();
if (err) {
await stop();
return `the auth key did not register tailscaled (single-use and spent?): ${err.split("\n").find((l) => /error|invalid/i.test(l)) ?? err}`;
}
}
const s = await status();
const ip4 = s.Self.TailscaleIPs?.find((a) => !a.includes(":")) ?? "";
const nc = (ip: string, port: number, input: string, until: RegExp) => new Promise<string>((resolve) => {
const child = spawn(join(TAILSCALE_DIR, "tailscale"), [`--socket=${socket}`, "nc", ip, String(port)], { env, stdio: ["pipe", "pipe", "pipe"] });
let got = "";
const done = () => { clearTimeout(t); child.kill(); resolve(got); };
const t = setTimeout(done, 10000);
child.stdout.on("data", (d: Buffer) => { got += d; if (until.test(got)) done(); });
child.stderr.on("data", (d: Buffer) => (got += d));
child.on("exit", done);
child.stdin.write(input);
});
return { cli, nc, ip4, name: (s.Self.DNSName ?? "").split(".")[0]!, stop };
}
describe("Tailscale's real service", { skip, concurrency: 1 }, () => {
let peer: Peer | null = null;
let peerSkip: string | false = "not started";
let http: Server;
const big = randomBytes(4 << 20);
const bigSha = createHash("sha256").update(big).digest("hex");
before(async () => {
mkdirSync(DIR, { recursive: true, mode: 0o700 });
http = createServer((req, res) => {
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`));
} else if (req.url === "/big") {
res.writeHead(200, { "content-length": String(big.length) });
res.end(big);
} else res.end(`hello from the peer: ${req.url}\n`);
});
await new Promise<void>((r) => http.listen(HTTP_PORT, "127.0.0.1", r));
});
after(async () => {
await peer?.stop();
http?.close();
http?.closeAllConnections();
});
describe("control", { concurrency: 1 }, () => {
test("GET /key, the Noise handshake and the early payload (recorded)", async () => {
const keys = await (await fetch(`${CONTROL}/key?v=130`)).json() as { publicKey: string };
assert.match(keys.publicKey, /^mkey:[0-9a-f]{64}$/);
const t0 = performance.now();
const c = await dialNoise({ url: controlWebSocketURL(CONTROL), machinePrivateKey: tsRandom(32), controlPublicKey: keyFromText(keys.publicKey, "mkey"), protocolVersion: 130 });
const ms = performance.now() - t0;
// The server writes the early payload, if any, before its HTTP/2 settings, which it sends after our preface.
c.write(new TextEncoder().encode("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"));
c.write(new Uint8Array([0, 0, 0, 4, 0, 0, 0, 0, 0]));
const early = await Promise.race([c.earlyPayload, sleep(5000).then(() => "none in 5 s")]);
c.close();
say(`Noise handshake ${ms.toFixed(0)} ms; early payload: ${early === null ? "none (HTTP/2 first)" : typeof early === "string" ? early : `keys ${Object.keys(early).join(",")}`}`);
});
test("the JS node registers once (state written at once) or resumes without registering; the netmap's shapes", async () => {
const had = loadJs()?.authorized;
const logs: string[] = [];
const msgs: MapResponse[] = [];
const c = new ControlClient({
controlURL: CONTROL, hostname: `${NAME}-js`, state: loadJs(), authKey: had ? undefined : AUTHKEY || undefined,
hostinfo: { Userspace: true, UserspaceRouter: true, App: "unkernel" }, logger: (m) => logs.push(m), onMapResponse: (r) => msgs.push(r),
});
c.on("state", saveJs);
c.start();
try {
const nm = await c.waitForNetMap(() => true, { timeout: 30000 });
if (had) assert.ok(!logs.some((l) => /registering/.test(l)), "a saved, authorized state does not register again");
assert.ok(loadJs()?.authorized, "the state is saved, authorized");
assert.notEqual(nm.self.MachineAuthorized, false, "needs-machine-auth: the tailnet wants device approval (approve the node, then run again)");
assert.ok(nm.name.startsWith(`${NAME}-js`), nm.name);
const domains = nm.dns?.Domains ?? [];
say(`node ${nm.name} ${nm.addresses.join(" ")}, key expiry ${nm.keyExpiry?.toISOString() ?? "never"}, MagicDNS ${domains.join(",")} (Proxied ${nm.dns?.Proxied}), resolvers ${(nm.dns?.Resolvers ?? []).length}, routes ${Object.keys(nm.dns?.Routes ?? {}).join(",")}`);
assert.ok(domains.some((d) => nm.name.endsWith(`.${d}`)), "the node's name is under a MagicDNS domain");
assert.ok(!nm.expired && (!nm.keyExpiry || nm.keyExpiry.getTime() > Date.now()));
assert.ok(Object.keys(nm.derpMap?.Regions ?? {}).length > 0, "a DERP map");
// Every rule is one the filter reads (IPv4 sources and destinations), or one it may ignore (IPv6 only, capability grants).
const unread = nm.packetFilter.filter((r) => {
const v4src = (r.SrcIPs ?? []).some((s) => parseRange4(s) !== null);
const v4dst = (r.DstPorts ?? []).some((d) => parseRange4(d.IP, d.Bits) !== null);
const ipv6Only = (r.SrcIPs ?? []).every((s) => s.includes(":") || s.startsWith("cap:")) || (r.DstPorts ?? []).every((d) => d.IP.includes(":"));
return !(v4src && v4dst) && !ipv6Only && !r.CapGrant?.length;
});
say(`packet filter: ${nm.packetFilter.length} rules (${nm.packetFilter.map((r) => `src ${(r.SrcIPs ?? []).length} dst ${(r.DstPorts ?? []).length}${r.IPProto ? ` proto ${r.IPProto.join("/")}` : ""}${r.CapGrant ? " capgrant" : ""}`).join("; ") || "none"})`);
assert.deepEqual(unread, [], "a rule shape the filter does not read");
const fields = [...new Set(msgs.flatMap((m) => Object.keys(m)))].sort();
say(`map message fields: ${fields.join(",")}; PingRequests ${msgs.filter((m) => m.PingRequest).length}`);
say(`the node's own home region in its netmap: ${nm.self.HomeDERP || "none"}`);
if (CONTROL === DEFAULT_CONTROL_URL) assert.equal(nm.self.HomeDERP, 0, "Tailscale's control shows a node no home region of its own (client.ts depends on knowing whether it does)");
} finally {
await c.stop();
}
});
});
describe("the JS client", { concurrency: 1 }, () => {
let regions = 0;
test("running, with only the home region open after it; the region is saved; a second start reuses it with no probe", async () => {
for (const run of ["first", "second"]) {
sockets.length = 0;
const savedHome = loadJs()?.homeDERP;
const c = jsClient();
const t0 = performance.now();
c.start();
try {
await c.ready(20000);
const ms = performance.now() - t0;
const s = c.status();
regions = Object.keys(c.netmap!.derpMap!.Regions).length;
const derpSockets = sockets.filter((x) => /\/derp$/.test(x.url)).length;
say(`${run} start: running in ${ms.toFixed(0)} ms, home ${s.homeDERP}${savedHome ? ` (saved ${savedHome})` : ""}, ${derpSockets} DERP sockets opened (${new Date().toISOString().slice(0, 10)})`);
assert.ok(s.homeDERP > 0);
await sleep(300);
assert.deepEqual(c.status().derp.map((r) => r.region), [s.homeDERP], "the probe's other connections closed");
assert.equal(loadJs()?.homeDERP, s.homeDERP, "saved");
if (savedHome && savedHome === s.homeDERP) assert.equal(derpSockets, 1, "a returning node opens only its home region");
} finally {
await c.close();
}
}
});
test("the control channel cut, then the home region cut: both come back", async () => {
sockets.length = 0;
const c = jsClient();
c.start();
try {
await c.ready(20000);
const before = c.netmap;
for (const s of openSockets(/ts2021/)) s.close();
for (let i = 0; i < 200 && c.netmap === before; i++) await sleep(100);
assert.notEqual(c.netmap, before, "a new netmap after the cut");
const home = c.status().homeDERP;
const t0 = performance.now();
for (const s of openSockets(/\/derp$/)) s.close();
for (let i = 0; i < 100 && !(c.status().state === "running" && openSockets(/\/derp$/).length); i++) await sleep(100);
assert.equal(c.status().state, "running");
assert.equal(c.status().homeDERP, home);
say(`home region back in ${(performance.now() - t0).toFixed(0)} ms`);
} finally {
await c.close();
}
});
test("a saved home region that does not connect: another one within 10 s", async (ctx) => {
const home = loadJs()?.homeDERP;
assert.ok(home, "a saved home region (the test before saves it)");
if (regions < 2) return ctx.skip("one DERP region");
sockets.length = 0;
failing = new RegExp(`^wss?://derp${home}[a-z]\\.`);
const logs: string[] = [];
const c = jsClient({}, logs);
c.start();
try {
await c.ready(20000);
assert.notEqual(c.status().homeDERP, home);
say(`home ${home} unreachable: home ${c.status().homeDERP}`);
} finally {
failing = null;
await c.close();
}
});
});
describe("with a real tailscaled as the peer", { concurrency: 1 }, () => {
let c: TailscaleClient;
const t = (name: string, fn: () => Promise<void>, opts: { timeout?: number } = {}) => test(name, { timeout: opts.timeout ?? 60000 }, async (ctx) => {
if (peerSkip) return ctx.skip(peerSkip);
await fn();
});
before(async () => {
const p = await startPeer();
if (typeof p === "string") {
peerSkip = p;
say(`peer: ${p}`);
return;
}
peer = p;
peerSkip = false;
c = jsClient();
c.start();
await c.ready(20000);
});
after(async () => {
await c?.close();
});
t("tailscale status on the peer shows the JS node online, on our home region", async () => {
const me = c.addresses[0]!;
let p: Record<string, unknown> | undefined;
for (let i = 0; i < 60; i++) {
const st = JSON.parse(await peer!.cli(["status", "--json"])) as { Peer?: Record<string, Record<string, unknown>> };
p = Object.values(st.Peer ?? {}).find((x) => (x.TailscaleIPs as string[] | undefined)?.includes(me));
if (p?.Relay) break;
await sleep(500);
}
assert.ok(p, "the peer knows the JS node");
const region = c.netmap!.derpMap!.Regions[String(c.status().homeDERP)]!.RegionCode;
say(`the peer sees the JS node: online ${p!.Online}, relay ${p!.Relay} (ours: ${region})`);
assert.equal(p!.Relay, region, "the peer has our home region");
});
t("tailscale ping (disco over DERP), --tsmp and --icmp reach the JS node", async () => {
const me = c.addresses[0]!;
const disco = await peer!.cli(["ping", "--c", "3", me]).catch((e: Error) => e.message);
assert.match(disco, /pong from .* via DERP\(/, disco);
assert.match(await peer!.cli(["ping", "--tsmp", "--c", "2", me]), /pong from/);
// Echo requests are answered by the client (nothing consumes its packets) when the tailnet's filter lets them in.
const icmp = await peer!.cli(["ping", "--icmp", "--c", "2", "--timeout", "5s", me]).catch((e: Error) => e.message);
say(`--icmp: ${icmp.split("\n")[0]} (filter: ${c.status().lastFiltered ?? "nothing dropped"})`);
});
t("an ICMP echo from the JS node to the peer through WireGuard", async () => {
const got: Uint8Array[] = [];
c.onPacket = (ip) => got.push(ip);
try {
const pkt = echo(c.addresses[0]!, peer!.ip4, 7, 1);
assert.ok(c.sendPacket(pkt));
for (let i = 0; i < 100 && !got.some((p) => p[9] === 1 && p[20] === 0); i++) await sleep(100);
assert.ok(got.some((p) => p[9] === 1 && p[20] === 0), "an echo reply");
const w = c.status().peers.find((p) => p.addresses.includes(peer!.ip4));
assert.ok(w && w.lastHandshake > 0);
} finally {
c.onPacket = null;
}
});
if (LONG) t("150 s of pings across a WireGuard rekey (120 s): none lost for long", async () => {
const got = new Set<number>();
c.onPacket = (ip) => { if (ip[9] === 1 && ip[20] === 0) got.add((ip[26]! << 8) | ip[27]!); };
const first = c.status().peers.find((p) => p.addresses.includes(peer!.ip4))?.lastHandshake ?? 0;
try {
for (let seq = 1; seq <= 150; seq++) {
c.sendPacket(echo(c.addresses[0]!, peer!.ip4, 8, seq));
await sleep(1000);
}
await sleep(3000);
const lost = 150 - got.size;
const last = c.status().peers.find((p) => p.addresses.includes(peer!.ip4))?.lastHandshake ?? 0;
say(`rekey: ${lost} of 150 lost; handshake ${first} -> ${last}`);
assert.ok(last > first, "a new handshake during the run");
assert.ok(lost <= 5, `${lost} lost`);
} finally {
c.onPacket = null;
}
}, { timeout: 200000 });
if (LONG) t("10 min idle: the home region stays up and the peer still reaches us", async () => {
const opened = sockets.length;
await sleep(600_000);
assert.equal(c.status().state, "running");
assert.equal(sockets.length, opened, "no reconnect was needed");
assert.match(await peer!.cli(["ping", "--tsmp", "--c", "1", c.addresses[0]!]), /pong from/);
}, { timeout: 660000 });
});
for (const worker of [false, true]) {
describe(`the guest (${worker ? "worker mode" : "inline"})`, { concurrency: 1 }, () => {
let vm: KernelHandle;
const logs: string[] = [];
const spec = (): NetSpec => {
const state = loadJs();
return { kind: "net", backend: { kind: "direct" }, tailscale: { controlURL: CONTROL, hostname: `${NAME}-js`, state, authKey: state?.authorized ? undefined : AUTHKEY || undefined } };
};
const onTailscale = (e: TailscaleEvent) => { if (e.type === "state") saveJs(e.state); };
const sh = async (cmd: string) => {
const r = await vm.exec("sh", ["-c", cmd]);
return r.stdout + r.stderr;
};
const boot = (restore?: ReturnType<typeof decodeSnapshot>) =>
createKernel({ worker, log: (m) => logs.push(redact(m)), net: spec(), onTailscale, restore } as Parameters<typeof createKernel>[0] & { worker: boolean });
before(async () => {
const t0 = performance.now();
vm = await boot();
await vm.tailscale!.ready(30000);
say(`${worker ? "worker" : "inline"}: booted and running in ${(performance.now() - t0).toFixed(0)} ms`);
});
after(async () => {
await vm?.stop({ reason: "test cleanup" });
if (process.env.UNKERNEL_TS_LOG) console.log(logs.join("\n"));
});
test("MagicDNS in the guest: its own name short and full, a name that does not exist", async () => {
const name = vm.tailscale!.status().name;
const me = vm.tailscale!.addresses[0]!;
assert.match(await sh(`nslookup ${name.split(".")[0]}`), new RegExp(`Address: ${me.replace(/\./g, "\\.")}`));
assert.match(await sh(`nslookup ${name} 100.100.100.100`), new RegExp(`Address: ${me.replace(/\./g, "\\.")}`));
assert.match(await sh(`nslookup no-such-node-${process.pid}.${name.split(".").slice(1).join(".")} 2>&1`), /NXDOMAIN|can't find/);
});
test("the peer: ping, 4 MiB down and up checked by SHA-256, an inbound connection", { timeout: 300000 }, async (ctx) => {
if (peerSkip) return ctx.skip(peerSkip);
assert.match(await sh(`ping -c 3 -W 5 ${peer!.ip4}`), /3 packets received/);
let t0 = performance.now();
const down = await sh(`wget -q -O - http://${peer!.ip4}:${HTTP_PORT}/big | sha256sum`);
const sDown = (performance.now() - t0) / 1000;
assert.ok(down.startsWith(bigSha), down);
await sh("dd if=/dev/urandom bs=3072 count=1024 2>/dev/null | base64 -w 0 | head -c 4194304 >/tmp/up");
const sha = (await sh("sha256sum /tmp/up")).split(" ")[0]!;
t0 = performance.now();
const up = await sh(`wget -q -O - --post-file=/tmp/up http://${peer!.ip4}:${HTTP_PORT}/up`);
const sUp = (performance.now() - t0) / 1000;
assert.equal(up.trim(), `${4 << 20} ${sha}`);
say(`${worker ? "worker" : "inline"} through DERP: down ${(4 / sDown).toFixed(2)} MiB/s, up ${(4 / sUp).toFixed(2)} MiB/s (${new Date().toISOString().slice(0, 10)})`);
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 peer!.nc(vm.tailscale!.addresses[0]!, 8080, "hello\n", /guest-ok/);
if (!out.includes("guest-ok")) await sleep(250);
}
srv.kill();
assert.match(out, /guest-ok hello/, "(the tailnet's ACL must let the peer in)");
});
test("a snapshot with the tunnel on, restored: the same node comes back", { timeout: 120000 }, async () => {
const me = vm.tailscale!.addresses[0];
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;
vm = await boot(decodeSnapshot(encodeSnapshot(snap)));
await vm.tailscale!.ready(30000);
assert.equal(vm.tailscale!.addresses[0], me);
if (peer) assert.match(await sh(`ping -c 2 -W 5 ${peer.ip4}`), /2 packets received/);
});
});
}
test("logout (TS_LIVE_LOGOUT=1): both nodes log out", { skip: process.env.TS_LIVE_LOGOUT === "1" ? false : "TS_LIVE_LOGOUT not set" }, async () => {
const c = jsClient();
c.start();
await c.ready(20000).catch(() => {});
await c.logout();
assert.equal(loadJs()?.authorized, false);
if (peer) await peer.cli(["logout"], 30000);
say("logged out");
});
});
/** An ICMP echo request (8 bytes of payload). */
function echo(src: string, dst: string, id: number, seq: number): Uint8Array {
const p = new Uint8Array(36);
p[0] = 0x45;
p[3] = 36;
p[8] = 64;
p[9] = 1;
p.set(src.split(".").map(Number), 12);
p.set(dst.split(".").map(Number), 16);
const sum = (o: number, n: number) => {
let s = 0;
for (let i = o; i < o + n; i += 2) s += (p[i]! << 8) | p[i + 1]!;
while (s > 0xffff) s = (s & 0xffff) + (s >>> 16);
return ~s & 0xffff;
};
let c = sum(0, 20);
p[10] = c >> 8;
p[11] = c & 255;
p[20] = 8;
p[24] = id >> 8;
p[25] = id & 255;
p[26] = seq >> 8;
p[27] = seq & 255;
c = sum(20, 16);
p[22] = c >> 8;
p[23] = c & 255;
return p;
}