mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-04 00:49:58 +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.
330 lines
12 KiB
TypeScript
330 lines
12 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// Test fixture: a throwaway headscale (vendor/toolchain/headscale/headscale,
|
|
// or $UNKERNEL_HEADSCALE) with its config, sqlite database and sockets in a
|
|
// temp dir, listening on 127.0.0.1 only. Ports from the base: +0 HTTP
|
|
// (control, and the embedded DERP's /derp), +1 metrics, +2 gRPC, +3 STUN
|
|
// (UDP, embedded DERP only). Tests use bases within 18080-18089.
|
|
//
|
|
// const hs = await startHeadscale({ portBase: 18080 });
|
|
// const user = await hs.createUser("alice");
|
|
// const key = await hs.createAuthKey(user.id, { reusable: true });
|
|
// ... new ControlClient({ controlURL: hs.url, authKey: key, ... })
|
|
// await hs.stop();
|
|
|
|
import { spawn, execFile, type ChildProcess } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
/** The headscale binary the fixture runs. */
|
|
export const HEADSCALE_BIN = process.env.UNKERNEL_HEADSCALE ?? fileURLToPath(new URL("../vendor/toolchain/headscale/headscale", import.meta.url));
|
|
|
|
/** Whether the binary is there (tests skip without it). */
|
|
export function headscaleAvailable(): boolean {
|
|
return existsSync(HEADSCALE_BIN);
|
|
}
|
|
|
|
export interface HeadscaleOptions {
|
|
/** First port, default 18080. */
|
|
portBase?: number;
|
|
/**
|
|
* Run headscale's embedded DERP server (region 999, at the control URL's
|
|
* /derp, STUN on portBase+3). Otherwise the DERP map is a static region
|
|
* 900 pointing at 127.0.0.1:portBase+9 with nothing behind it, unless
|
|
* derpMap replaces it.
|
|
*/
|
|
embeddedDerp?: boolean;
|
|
/** A static DERP map (YAML-able: tailcfg.DERPMap with lower-case field names). */
|
|
derpMap?: unknown;
|
|
/** headscale log level, default "warn" ($UNKERNEL_HEADSCALE_LOG overrides). */
|
|
logLevel?: string;
|
|
/** Extra top-level config (merged over the defaults, shallowly). */
|
|
config?: Record<string, unknown>;
|
|
}
|
|
|
|
export interface HeadscaleUser {
|
|
id: number;
|
|
name: string;
|
|
}
|
|
|
|
export interface Headscale {
|
|
/** Control URL, http://127.0.0.1:<portBase>. */
|
|
url: string;
|
|
port: number;
|
|
/** The temp dir (config, db, keys, socket). */
|
|
dir: string;
|
|
config: string;
|
|
/** Runs the headscale CLI against this server; resolves with stdout. */
|
|
cli(args: string[]): Promise<string>;
|
|
/** Runs the CLI with -o json and parses the output. */
|
|
cliJSON<T = unknown>(args: string[]): Promise<T>;
|
|
createUser(name: string): Promise<HeadscaleUser>;
|
|
/** Creates a pre-auth key for a user ID. */
|
|
createAuthKey(userId: number, opts?: { reusable?: boolean; ephemeral?: boolean; tags?: string[]; expiration?: string }): Promise<string>;
|
|
/** Completes an interactive login: authId is the last path segment of the AuthURL. */
|
|
registerAuthId(authId: string, user: string): Promise<void>;
|
|
/** headscale nodes list. */
|
|
nodes(): Promise<Record<string, unknown>[]>;
|
|
/** stdout and stderr so far. */
|
|
logs(): string;
|
|
/** Stops the server and removes the temp dir. */
|
|
stop(): Promise<void>;
|
|
}
|
|
|
|
/** YAML for plain JSON-like data (enough for headscale's config). */
|
|
function yaml(v: unknown, indent = ""): string {
|
|
if (v === null || v === undefined) return "null";
|
|
if (typeof v === "string") return JSON.stringify(v);
|
|
if (typeof v !== "object") return String(v);
|
|
if (Array.isArray(v)) {
|
|
if (!v.length) return "[]";
|
|
return v.map((x) => `\n${indent}- ${yaml(x, indent + " ").replace(/^\n\s*/, "")}`).join("");
|
|
}
|
|
const entries = Object.entries(v as Record<string, unknown>);
|
|
if (!entries.length) return "{}";
|
|
return entries.map(([k, x]) => {
|
|
const inner = yaml(x, indent + " ");
|
|
const block = typeof x === "object" && x !== null && (Array.isArray(x) ? x.length : Object.keys(x).length);
|
|
return `\n${indent}${k}:${block ? "" : " "}${inner}`;
|
|
}).join("");
|
|
}
|
|
|
|
function run(cmd: string, args: string[]): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
execFile(cmd, args, { timeout: 30000 }, (err, stdout, stderr) => {
|
|
if (err) reject(new Error(`${args.join(" ")}: ${err.message}\n${stderr}${stdout}`));
|
|
else resolve(stdout);
|
|
});
|
|
});
|
|
}
|
|
|
|
/** Starts headscale and waits until it answers GET /key. */
|
|
export async function startHeadscale(opts: HeadscaleOptions = {}): Promise<Headscale> {
|
|
const port = opts.portBase ?? 18080;
|
|
const dir = await mkdtemp(join(tmpdir(), "unkernel-headscale-"));
|
|
const url = `http://127.0.0.1:${port}`;
|
|
const derp: Record<string, unknown> = {
|
|
server: opts.embeddedDerp
|
|
? {
|
|
enabled: true,
|
|
region_id: 999,
|
|
region_code: "headscale",
|
|
region_name: "Headscale Embedded DERP",
|
|
verify_clients: true,
|
|
stun_listen_addr: `127.0.0.1:${port + 3}`,
|
|
private_key_path: join(dir, "derp_server_private.key"),
|
|
automatically_add_embedded_derp_region: true,
|
|
ipv4: "127.0.0.1",
|
|
}
|
|
: { enabled: false },
|
|
urls: [],
|
|
paths: [],
|
|
auto_update_enabled: false,
|
|
update_frequency: "24h",
|
|
};
|
|
if (!opts.embeddedDerp || opts.derpMap) {
|
|
const map = opts.derpMap ?? {
|
|
regions: {
|
|
900: {
|
|
regionid: 900,
|
|
regioncode: "test",
|
|
regionname: "Test",
|
|
nodes: [{ name: "900a", regionid: 900, hostname: "127.0.0.1", ipv4: "127.0.0.1", stunport: -1, derpport: port + 9, insecurefortests: true }],
|
|
},
|
|
},
|
|
};
|
|
const derpFile = join(dir, "derp.yaml");
|
|
await writeFile(derpFile, yaml(map).trimStart() + "\n");
|
|
derp.paths = [derpFile];
|
|
}
|
|
const config = {
|
|
server_url: url,
|
|
listen_addr: `127.0.0.1:${port}`,
|
|
metrics_listen_addr: `127.0.0.1:${port + 1}`,
|
|
grpc_listen_addr: `127.0.0.1:${port + 2}`,
|
|
grpc_allow_insecure: false,
|
|
noise: { private_key_path: join(dir, "noise_private.key") },
|
|
prefixes: { v4: "100.64.0.0/10", v6: "fd7a:115c:a1e0::/48", allocation: "sequential" },
|
|
derp,
|
|
disable_check_updates: true,
|
|
database: { type: "sqlite", sqlite: { path: join(dir, "db.sqlite"), write_ahead_log: true } },
|
|
log: { level: process.env.UNKERNEL_HEADSCALE_LOG ?? opts.logLevel ?? "warn", format: "text" },
|
|
policy: { mode: "file", path: "" },
|
|
dns: { magic_dns: true, base_domain: "ts.test", override_local_dns: false, nameservers: { global: [], split: {} }, search_domains: [], extra_records: [] },
|
|
unix_socket: join(dir, "headscale.sock"),
|
|
unix_socket_permission: "0770",
|
|
logtail: { enabled: false },
|
|
taildrop: { enabled: false },
|
|
...opts.config,
|
|
};
|
|
const configFile = join(dir, "config.yaml");
|
|
await writeFile(configFile, yaml(config).trimStart() + "\n");
|
|
|
|
let out = "";
|
|
const child: ChildProcess = spawn(HEADSCALE_BIN, ["-c", configFile, "serve"], { stdio: ["ignore", "pipe", "pipe"] });
|
|
child.stdout!.on("data", (d: Buffer) => (out += d.toString()));
|
|
child.stderr!.on("data", (d: Buffer) => (out += d.toString()));
|
|
const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
|
|
let dead = false;
|
|
void exited.then(() => (dead = true));
|
|
|
|
const stop = async () => {
|
|
if (!dead) {
|
|
child.kill("SIGTERM");
|
|
const t = setTimeout(() => child.kill("SIGKILL"), 5000);
|
|
await exited;
|
|
clearTimeout(t);
|
|
}
|
|
await rm(dir, { recursive: true, force: true });
|
|
};
|
|
|
|
const deadline = Date.now() + 20000;
|
|
for (;;) {
|
|
if (dead) {
|
|
await stop();
|
|
throw new Error(`headscale exited:\n${out}`);
|
|
}
|
|
try {
|
|
const res = await fetch(`${url}/key?v=130`);
|
|
if (res.ok) break;
|
|
} catch {
|
|
// not up yet
|
|
}
|
|
if (Date.now() > deadline) {
|
|
await stop();
|
|
throw new Error(`headscale did not start:\n${out}`);
|
|
}
|
|
await new Promise((r) => setTimeout(r, 100));
|
|
}
|
|
|
|
const cli = (args: string[]) => run(HEADSCALE_BIN, ["-c", configFile, ...args]);
|
|
const cliJSON = async <T>(args: string[]) => JSON.parse(await cli([...args, "-o", "json"])) as T;
|
|
return {
|
|
url,
|
|
port,
|
|
dir,
|
|
config: configFile,
|
|
cli,
|
|
cliJSON,
|
|
async createUser(name) {
|
|
const u = await cliJSON<{ id: number | string; name: string }>(["users", "create", name]);
|
|
return { id: Number(u.id), name: u.name };
|
|
},
|
|
async createAuthKey(userId, o = {}) {
|
|
const args = ["preauthkeys", "create", "--user", String(userId), "--expiration", o.expiration ?? "1h"];
|
|
if (o.reusable) args.push("--reusable");
|
|
if (o.ephemeral) args.push("--ephemeral");
|
|
if (o.tags?.length) args.push("--tags", o.tags.join(","));
|
|
const k = await cliJSON<{ key: string }>(args);
|
|
return k.key;
|
|
},
|
|
async registerAuthId(authId, user) {
|
|
await cli(["auth", "register", "--auth-id", authId, "--user", user]);
|
|
},
|
|
async nodes() {
|
|
return (await cliJSON<Record<string, unknown>[] | null>(["nodes", "list"])) ?? [];
|
|
},
|
|
logs: () => out,
|
|
stop,
|
|
};
|
|
}
|
|
|
|
/** Tailscale's static linux binaries (tailscale, tailscaled) the tailscaled fixture runs. */
|
|
export const TAILSCALE_DIR = process.env.UNKERNEL_TAILSCALE_DIR ?? fileURLToPath(new URL("../vendor/toolchain/tailscale", import.meta.url));
|
|
|
|
/** Whether both binaries are there (tests skip without them). */
|
|
export function tailscaleAvailable(): boolean {
|
|
return existsSync(join(TAILSCALE_DIR, "tailscaled")) && existsSync(join(TAILSCALE_DIR, "tailscale"));
|
|
}
|
|
|
|
export interface TailscaledOptions {
|
|
/** Its WireGuard UDP port. */
|
|
port: number;
|
|
/** Also serve a SOCKS5 proxy into the tailnet on 127.0.0.1:<socks5>. */
|
|
socks5?: number;
|
|
}
|
|
|
|
export interface Tailscaled {
|
|
dir: string;
|
|
socket: string;
|
|
/** Runs the tailscale CLI against this daemon; resolves with stdout (rejects on a non-zero exit). */
|
|
cli(args: string[], timeoutMs?: number): Promise<string>;
|
|
/** tailscale up against a control URL with an auth key. */
|
|
up(controlURL: string, authKey: string, hostname: string): Promise<void>;
|
|
/** tailscale status --json. */
|
|
status(): Promise<{ Self: Record<string, unknown>; Peer?: Record<string, Record<string, unknown>> }>;
|
|
/** Its first IPv4 tailnet address. */
|
|
ip4(): Promise<string>;
|
|
logs(): string;
|
|
stop(): Promise<void>;
|
|
}
|
|
|
|
/**
|
|
* Starts a real tailscaled (userspace networking, no root) with its state
|
|
* and socket in a temp dir. TS_DEBUG_USE_DERP_HTTP=1 makes it reach
|
|
* headscale's embedded DERP over plain HTTP, as the fixture serves it.
|
|
*/
|
|
export async function startTailscaled(opts: TailscaledOptions): Promise<Tailscaled> {
|
|
const dir = await mkdtemp(join(tmpdir(), "unkernel-tailscaled-"));
|
|
const socket = join(dir, "tailscaled.sock");
|
|
const env = { ...process.env, TS_DEBUG_USE_DERP_HTTP: "1", TS_LOGS_DIR: dir, TS_NO_LOGS_NO_SUPPORT: "true" };
|
|
const args = ["--tun=userspace-networking", `--socket=${socket}`, `--statedir=${dir}`, `--port=${opts.port}`];
|
|
if (opts.socks5) args.push(`--socks5-server=127.0.0.1:${opts.socks5}`);
|
|
let out = "";
|
|
const child = spawn(join(TAILSCALE_DIR, "tailscaled"), args, { env, stdio: ["ignore", "pipe", "pipe"] });
|
|
child.stdout!.on("data", (d: Buffer) => (out += d.toString()));
|
|
child.stderr!.on("data", (d: Buffer) => (out += d.toString()));
|
|
const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
|
|
let dead = false;
|
|
void exited.then(() => (dead = true));
|
|
const cli = (a: string[], timeoutMs = 30000) => new Promise<string>((resolve, reject) => {
|
|
execFile(join(TAILSCALE_DIR, "tailscale"), [`--socket=${socket}`, ...a], { env, timeout: timeoutMs }, (err, stdout, stderr) => {
|
|
if (err) reject(new Error(`tailscale ${a.join(" ")}: ${err.message}\n${stderr}${stdout}`));
|
|
else resolve(stdout);
|
|
});
|
|
});
|
|
const stop = async () => {
|
|
if (!dead) {
|
|
child.kill("SIGTERM");
|
|
const t = setTimeout(() => child.kill("SIGKILL"), 5000);
|
|
await exited;
|
|
clearTimeout(t);
|
|
}
|
|
await rm(dir, { recursive: true, force: true });
|
|
};
|
|
const deadline = Date.now() + 15000;
|
|
for (;;) {
|
|
if (dead) {
|
|
await stop();
|
|
throw new Error(`tailscaled exited:\n${out}`);
|
|
}
|
|
if (existsSync(socket) && await cli(["status", "--json"], 5000).then(() => true, () => false)) break;
|
|
if (Date.now() > deadline) {
|
|
await stop();
|
|
throw new Error(`tailscaled did not start:\n${out}`);
|
|
}
|
|
await new Promise((r) => setTimeout(r, 100));
|
|
}
|
|
const status = async () => JSON.parse(await cli(["status", "--json"])) as Awaited<ReturnType<Tailscaled["status"]>>;
|
|
return {
|
|
dir,
|
|
socket,
|
|
cli,
|
|
async up(controlURL, authKey, hostname) {
|
|
await cli(["up", `--login-server=${controlURL}`, `--authkey=${authKey}`, `--hostname=${hostname}`], 60000);
|
|
},
|
|
status,
|
|
async ip4() {
|
|
const s = await status();
|
|
const ip = (s.Self.TailscaleIPs as string[] | undefined)?.find((a) => !a.includes(":"));
|
|
if (!ip) throw new Error("tailscaled has no IPv4 address");
|
|
return ip;
|
|
},
|
|
logs: () => out,
|
|
stop,
|
|
};
|
|
}
|