Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

tailscale.test.ts

248 lines9.0 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Sink from "effect/Sink";
6import * as Stream from "effect/Stream";
7import { ChildProcessSpawner } from "effect/process";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9​
10import {
11 ensureTailscaleServe,
12 parseTailscaleExitNode,
13 parseTailscaleSshEnabled,
14 parseTailscaleStatus,
15 readTailscaleSshEnabled,
16 readTailscaleStatus,
17 TailscaleCommandExitError,
18 TailscaleCommandSpawnError,
19 TailscaleStatusParseError,
20} from "./tailscale.ts";
21​
22const encoder = new TextEncoder();
23​
24function assertCarriesNoSecret(error: object, secret: string): void {
25 const seen = new WeakSet<object>();
26​
27 const walk = (value: unknown, path: string): void => {
28 if (typeof value === "string") {
29 assert.notInclude(value, secret, `${path} leaked stderr`);
30 return;
31 }
32 if (typeof value !== "object" || value === null || seen.has(value)) {
33 return;
34 }
35 seen.add(value);
36​
37 if (Array.isArray(value)) {
38 value.forEach((entry, index) => walk(entry, `${path}[${String(index)}]`));
39 return;
40 }
41 // `message` and `cause` are getters on Error subclasses, so they are not
42 // own enumerable properties and Object.entries alone would skip them.
43 walk((value as { message?: unknown }).message, `${path}.message`);
44 walk((value as { cause?: unknown }).cause, `${path}.cause`);
45 for (const [key, nested] of Object.entries(value)) {
46 walk(nested, `${path}.${key}`);
47 }
48 };
49​
50 walk(error, "error");
52const tailscaleStatusJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.100.100.100","fd7a:115c:a1e0::1","192.168.1.20"]}}`;
53​
54function mockHandle(result: { stdout?: string; stderr?: string; code?: number }) {
55 return ChildProcessSpawner.makeHandle({
56 pid: ChildProcessSpawner.ProcessId(1),
57 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
58 isRunning: Effect.succeed(false),
59 kill: () => Effect.void,
60 unref: Effect.succeed(Effect.void),
61 stdin: Sink.drain,
62 stdout: Stream.make(encoder.encode(result.stdout ?? "")),
63 stderr: Stream.make(encoder.encode(result.stderr ?? "")),
64 all: Stream.empty,
65 getInputFd: () => Sink.drain,
66 getOutputFd: () => Stream.empty,
67 });
69​
70// The executable name depends on the host platform (`tailscale.exe` on
71// Windows), so pin it: these tests assert the posix spelling.
72function layerSpawner(spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) {
73 return Layer.merge(
74 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
75 Layer.succeed(HostProcess.Platform, "linux"),
76 );
78​
79function layerMockSpawner(
80 handler: (
81 command: string,
82 args: ReadonlyArray<string>,
83 ) => { stdout?: string; stderr?: string; code?: number },
84) {
85 return layerSpawner(
86 ChildProcessSpawner.make((command) => {
87 const childProcess = command as unknown as {
88 readonly command: string;
89 readonly args: ReadonlyArray<string>;
90 };
91 return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
92 }),
93 );
95​
96describe("tailscale", () => {
97 it.effect("parses status facts", () =>
98 Effect.gen(function* () {
99 const status = yield* parseTailscaleStatus(tailscaleStatusJson);
100 assert.deepEqual(status, {
101 magicDnsName: "desktop.tail.ts.net",
102 tailnetIpv4Addresses: ["100.100.100.100"],
103 httpsServeEnabled: null,
104 });
105 }),
106 );
107​
108 it.effect("names the exit node in use", () =>
109 Effect.gen(function* () {
110 const inUse = yield* parseTailscaleExitNode(
111 JSON.stringify({
112 ExitNodeStatus: { ID: "nX", Online: true, TailscaleIPs: ["100.101.102.103/32"] },
113 Peer: {
114 "nodekey:a": { HostName: "laptop", DNSName: "laptop.tail.ts.net.", ExitNode: false },
115 "nodekey:b": {
116 HostName: "raspberrypi",
117 DNSName: "home-pi.tail.ts.net.",
118 ExitNode: true,
119 },
120 },
121 }),
122 );
123 assert.deepEqual(inUse, { name: "home-pi", online: true });
124​
125 const unnamed = yield* parseTailscaleExitNode(`{"ExitNodeStatus":{"Online":false}}`);
126 assert.deepEqual(unnamed, { name: null, online: false });
127​
128 assert.equal(yield* parseTailscaleExitNode(tailscaleStatusJson), null);
129 }),
130 );
131​
132 it.effect("reads the HTTPS serve capability from the status capability map", () =>
133 Effect.gen(function* () {
134 const enabled = yield* parseTailscaleStatus(
135 `{"Self":{"CapMap":{"https":null,"funnel":null}}}`,
136 );
137 assert.equal(enabled.httpsServeEnabled, true);
138​
139 const disabled = yield* parseTailscaleStatus(`{"Self":{"CapMap":{"funnel":null}}}`);
140 assert.equal(disabled.httpsServeEnabled, false);
141 }),
142 );
143​
144 it.effect("reads Tailscale SSH enablement from local prefs", () => {
145 const prefsJson =
146 '{\n\t"ControlURL": "https://controlplane.tailscale.com",\n\t"RunSSH": true,\n\t"WantRunning": true\n}\n';
147 const layer = layerMockSpawner((command, args) => {
148 assert.equal(command, "tailscale");
149 assert.deepEqual(args, ["debug", "prefs"]);
150 return { stdout: prefsJson };
151 });
152​
153 return Effect.gen(function* () {
154 assert.isTrue(yield* readTailscaleSshEnabled.pipe(Effect.provide(layer)));
155 assert.isFalse(yield* parseTailscaleSshEnabled('{"RunSSH":false,"WantRunning":true}'));
156 assert.isFalse(yield* parseTailscaleSshEnabled('{"RunSSH":true,"WantRunning":false}'));
157 assert.isFalse(yield* parseTailscaleSshEnabled("{}"));
158 const error = yield* parseTailscaleSshEnabled("{not-json").pipe(Effect.flip);
159 assert.instanceOf(error, TailscaleStatusParseError);
160 });
161 });
162​
163 it.effect("turns spawn defects into typed spawn failures", () => {
164 // A non-directory entry on PATH makes node's spawn throw ENOTDIR
165 // synchronously. The platform spawner calls `NodeChildProcess.spawn` from
166 // inside an `Effect.callback` registration, so that throw arrives as a
167 // defect rather than a typed error - the shape reproduced here.
168 const defect = Object.assign(new Error("spawn tailscale ENOTDIR"), { code: "ENOTDIR" });
169 const layer = layerSpawner(
170 ChildProcessSpawner.make(() =>
171 Effect.callback<never, never>(() => {
172 throw defect;
173 }),
174 ),
175 );
176​
177 return Effect.gen(function* () {
178 const statusError = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
179 assert.instanceOf(statusError, TailscaleCommandSpawnError);
180 assert.equal(statusError.subcommand, "status");
181 assert.strictEqual(statusError.cause, defect);
182​
183 const serveError = yield* ensureTailscaleServe({ localPort: 13773, servePort: 8443 }).pipe(
184 Effect.flip,
185 Effect.provide(layer),
186 );
187 assert.instanceOf(serveError, TailscaleCommandSpawnError);
188 assert.equal(serveError.subcommand, "serve");
189 assert.strictEqual(serveError.cause, defect);
190​
191 const degraded = yield* readTailscaleStatus.pipe(
192 Effect.orElseSucceed(() => null),
193 Effect.provide(layer),
194 );
195 assert.equal(degraded, null);
196 });
197 });
198​
199 it.effect("keeps nonzero exit diagnostics structured", () => {
200 const layer = layerMockSpawner(() => ({
201 code: 7,
202 stderr: "not logged in tskey-auth-secret-token-value",
203 }));
204​
205 return Effect.gen(function* () {
206 const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
207​
208 assert.instanceOf(error, TailscaleCommandExitError);
209 assert.equal(error.executable, "tailscale");
210 assert.equal(error.subcommand, "status");
211 assert.equal(error.argumentCount, 2);
212 assert.equal(error.exitCode, 7);
213 assert.equal(error.stdoutLength, 0);
214 assert.equal(error.stderrLength, 43);
215 assert.notProperty(error, "command");
216 assert.notProperty(error, "stderr");
217 assert.notInclude(error.message, "tskey-auth-secret-token-value");
218 assert.equal(error.message, "tailscale status exited with code 7.");
219 assert.equal(error.stderrDiagnostic, "not-logged-in");
220 assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
221 });
222 });
223​
224 // regression: #21609 - without forceKillAfter a timed-out probe only gets
225 // SIGTERM, so a group member that ignores it outlives the call.
226 it.effect("escalates timed-out probes to SIGKILL", () => {
227 const killGraces: Array<number | undefined> = [];
228 const layer = layerSpawner(
229 ChildProcessSpawner.make((command) => {
230 if (command._tag === "StandardCommand") {
231 const { forceKillAfter } = command.options;
232 killGraces.push(
233 forceKillAfter === undefined
234 ? undefined
235 : Duration.toMillis(Duration.fromInputUnsafe(forceKillAfter)),
236 );
237 }
238 return Effect.succeed(mockHandle({ stdout: "{}" }));
239 }),
240 );
241​
242 return Effect.gen(function* () {
243 yield* readTailscaleStatus.pipe(Effect.provide(layer));
244 yield* readTailscaleSshEnabled.pipe(Effect.provide(layer));
245 assert.deepEqual(killGraces, [500, 500]);
246 });
247 });
248});