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

tailscale.test.ts

340 lines12.2 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as Cause from "effect/Cause";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as Layer from "effect/Layer";
6import * as PlatformError from "effect/PlatformError";
7import * as Sink from "effect/Sink";
8import * as Stream from "effect/Stream";
9import * as TestClock from "effect/testing/TestClock";
10import { ChildProcessSpawner } from "effect/unstable/process";
11​
12import {
13 buildTailscaleHttpsBaseUrl,
14 disableTailscaleServe,
15 ensureTailscaleServe,
16 isTailscaleIpv4Address,
17 parseTailscaleMagicDnsName,
18 parseTailscaleStatus,
19 readTailscaleStatus,
20 TAILSCALE_STATUS_TIMEOUT,
21 TailscaleCommandExitError,
22 TailscaleCommandSpawnError,
23 TailscaleCommandTimeoutError,
24 TailscaleStatusParseError,
25} from "./tailscale.ts";
26​
27const encoder = new TextEncoder();
28​
29/**
30 * Asserts nothing reachable from `error` contains `secret`. Recurses through
31 * nested objects, arrays, and `cause` chains rather than checking only
32 * top-level strings: a leak one level down (say, a wrapped cause carrying raw
33 * stderr) is just as visible in a log, and a shallow check would pass it.
34 *
35 * Walks values instead of serializing so it holds for fields added later, and
36 * tracks visited objects so a cyclic cause chain terminates.
37 */
38function assertCarriesNoSecret(error: object, secret: string): void {
39 const seen = new WeakSet<object>();
40​
41 const walk = (value: unknown, path: string): void => {
42 if (typeof value === "string") {
43 assert.notInclude(value, secret, `${path} leaked stderr`);
44 return;
45 }
46 if (typeof value !== "object" || value === null || seen.has(value)) {
47 return;
48 }
49 seen.add(value);
50​
51 if (Array.isArray(value)) {
52 value.forEach((entry, index) => walk(entry, `${path}[${String(index)}]`));
53 return;
54 }
55 // `message` and `cause` are getters on Error subclasses, so they are not
56 // own enumerable properties and Object.entries alone would skip them.
57 walk((value as { message?: unknown }).message, `${path}.message`);
58 walk((value as { cause?: unknown }).cause, `${path}.cause`);
59 for (const [key, nested] of Object.entries(value)) {
60 walk(nested, `${path}.${key}`);
61 }
62 };
63​
64 walk(error, "error");
66const tailscaleStatusJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.100.100.100","fd7a:115c:a1e0::1","192.168.1.20"]}}`;
67const tailscaleStatusWithSingleIpJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.90.1.2"]}}`;
68​
69function mockHandle(result: { stdout?: string; stderr?: string; code?: number }) {
70 return ChildProcessSpawner.makeHandle({
71 pid: ChildProcessSpawner.ProcessId(1),
72 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
73 isRunning: Effect.succeed(false),
74 kill: () => Effect.void,
75 unref: Effect.succeed(Effect.void),
76 stdin: Sink.drain,
77 stdout: Stream.make(encoder.encode(result.stdout ?? "")),
78 stderr: Stream.make(encoder.encode(result.stderr ?? "")),
79 all: Stream.empty,
80 getInputFd: () => Sink.drain,
81 getOutputFd: () => Stream.empty,
82 });
84​
85function neverFinishingMockHandle() {
86 return ChildProcessSpawner.makeHandle({
87 pid: ChildProcessSpawner.ProcessId(1),
88 exitCode: Effect.never,
89 isRunning: Effect.succeed(true),
90 kill: () => Effect.void,
91 unref: Effect.succeed(Effect.void),
92 stdin: Sink.drain,
93 stdout: Stream.empty,
94 stderr: Stream.empty,
95 all: Stream.empty,
96 getInputFd: () => Sink.drain,
97 getOutputFd: () => Stream.empty,
98 });
100​
101function mockSpawnerLayer(
102 handler: (
103 command: string,
104 args: ReadonlyArray<string>,
105 ) => { stdout?: string; stderr?: string; code?: number },
106) {
107 return Layer.succeed(
108 ChildProcessSpawner.ChildProcessSpawner,
109 ChildProcessSpawner.make((command) => {
110 const childProcess = command as unknown as {
111 readonly command: string;
112 readonly args: ReadonlyArray<string>;
113 };
114 return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
115 }),
116 );
118​
119describe("tailscale", () => {
120 it.effect("detects Tailnet IPv4 addresses", () =>
121 Effect.sync(() => {
122 assert.equal(isTailscaleIpv4Address("100.64.0.1"), true);
123 assert.equal(isTailscaleIpv4Address("100.127.255.254"), true);
124 assert.equal(isTailscaleIpv4Address("100.128.0.1"), false);
125 assert.equal(isTailscaleIpv4Address("192.168.1.44"), false);
126 }),
127 );
128​
129 it.effect("parses MagicDNS names from tailscale status", () =>
130 Effect.gen(function* () {
131 const dnsName = yield* parseTailscaleMagicDnsName(tailscaleStatusJson);
132 assert.equal(dnsName, "desktop.tail.ts.net");
133 assert.equal(yield* parseTailscaleMagicDnsName("{}"), null);
134 }),
135 );
136​
137 it.effect("parses status facts", () =>
138 Effect.gen(function* () {
139 const status = yield* parseTailscaleStatus(tailscaleStatusJson);
140 assert.deepEqual(status, {
141 magicDnsName: "desktop.tail.ts.net",
142 tailnetIpv4Addresses: ["100.100.100.100"],
143 });
144 }),
145 );
146​
147 it.effect("preserves status decoding failures without exposing cause text", () =>
148 Effect.gen(function* () {
149 const error = yield* parseTailscaleStatus("{not-json").pipe(Effect.flip);
150​
151 assert.instanceOf(error, TailscaleStatusParseError);
152 assert.equal(error.message, "Failed to decode tailscale status JSON.");
153 assert.isDefined(error.cause);
154 assert.notInclude(error.message, String(error.cause));
155 }),
156 );
157​
158 it.effect("builds clean HTTPS base URLs", () =>
159 Effect.sync(() => {
160 assert.equal(
161 buildTailscaleHttpsBaseUrl({ magicDnsName: "desktop.tail.ts.net" }),
162 "https://desktop.tail.ts.net/",
163 );
164 assert.equal(
165 buildTailscaleHttpsBaseUrl({ magicDnsName: "desktop.tail.ts.net", servePort: 8443 }),
166 "https://desktop.tail.ts.net:8443/",
167 );
168 }),
169 );
170​
171 it.effect("reads tailscale status through the process spawner service", () => {
172 const layer = mockSpawnerLayer((command, args) => {
173 assert.equal(command, "tailscale");
174 assert.deepEqual(args, ["status", "--json"]);
175 return {
176 stdout: tailscaleStatusWithSingleIpJson,
177 };
178 });
179​
180 return Effect.gen(function* () {
181 const status = yield* readTailscaleStatus.pipe(Effect.provide(layer));
182 assert.deepEqual(status, {
183 magicDnsName: "desktop.tail.ts.net",
184 tailnetIpv4Addresses: ["100.90.1.2"],
185 });
186 });
187 });
188​
189 it.effect("preserves tailscale spawn failures as causes", () => {
190 const systemCause = new Error("private executable lookup detail");
191 const cause = PlatformError.systemError({
192 _tag: "NotFound",
193 module: "ChildProcess",
194 method: "spawn",
195 cause: systemCause,
196 });
197 const layer = Layer.succeed(
198 ChildProcessSpawner.ChildProcessSpawner,
199 ChildProcessSpawner.make(() => Effect.fail(cause)),
200 );
201​
202 return Effect.gen(function* () {
203 const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
204​
205 assert.instanceOf(error, TailscaleCommandSpawnError);
206 assert.equal(error.executable, "tailscale");
207 assert.equal(error.subcommand, "status");
208 assert.equal(error.argumentCount, 2);
209 assert.strictEqual(error.cause, cause);
210 assert.equal(error.message, "Failed to spawn tailscale status.");
211 assert.notInclude(error.message, systemCause.message);
212 });
213 });
214​
215 it.effect("keeps nonzero exit diagnostics structured", () => {
216 const layer = mockSpawnerLayer(() => ({
217 code: 7,
218 stderr: "not logged in tskey-auth-secret-token-value",
219 }));
220​
221 return Effect.gen(function* () {
222 const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
223​
224 assert.instanceOf(error, TailscaleCommandExitError);
225 assert.equal(error.executable, "tailscale");
226 assert.equal(error.subcommand, "status");
227 assert.equal(error.argumentCount, 2);
228 assert.equal(error.exitCode, 7);
229 assert.equal(error.stdoutLength, 0);
230 assert.equal(error.stderrLength, 43);
231 assert.notProperty(error, "command");
232 assert.notProperty(error, "stderr");
233 assert.notInclude(error.message, "tskey-auth-secret-token-value");
234 assert.equal(error.message, "tailscale status exited with code 7.");
235 assert.equal(error.stderrDiagnostic, "not-logged-in");
236 assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
237 });
238 });
239​
240 it.effect("classifies unrecognized stderr without quoting it", () => {
241 const layer = mockSpawnerLayer(() => ({
242 code: 3,
243 stderr: "something novel went wrong for node fluffy-badger tskey-auth-secret-token-value",
244 }));
245​
246 return Effect.gen(function* () {
247 const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
248​
249 assert.instanceOf(error, TailscaleCommandExitError);
250 // Unmatched stderr degrades to "unknown" rather than passing text
251 // through — that fallback is what keeps novel output from leaking.
252 assert.equal(error.stderrDiagnostic, "unknown");
253 assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
254 assertCarriesNoSecret(error, "fluffy-badger");
255 });
256 });
257​
258 it.effect("times out tailscale status through TestClock", () => {
259 const layer = Layer.merge(
260 TestClock.layer(),
261 Layer.succeed(
262 ChildProcessSpawner.ChildProcessSpawner,
263 ChildProcessSpawner.make(() => Effect.succeed(neverFinishingMockHandle())),
264 ),
265 );
266​
267 return Effect.gen(function* () {
268 const fiber = yield* readTailscaleStatus.pipe(Effect.flip, Effect.forkScoped);
269 yield* Effect.yieldNow;
270 yield* TestClock.adjust(TAILSCALE_STATUS_TIMEOUT);
271 const error = yield* Fiber.join(fiber);
272​
273 assert.instanceOf(error, TailscaleCommandTimeoutError);
274 assert.equal(error.executable, "tailscale");
275 assert.equal(error.subcommand, "status");
276 assert.equal(error.argumentCount, 2);
277 assert.equal(error.timeoutMs, 1_500);
278 assert.isTrue(Cause.isTimeoutError(error.cause));
279 assert.equal(error.message, "tailscale status timed out after 1500ms.");
280 }).pipe(Effect.provide(layer));
281 });
282​
283 it.effect("configures tailscale serve through the process spawner service", () => {
284 const layer = mockSpawnerLayer((command, args) => {
285 assert.equal(command, "tailscale");
286 assert.deepEqual(args, ["serve", "--bg", "--https=8443", "http://127.0.0.1:13773"]);
287 return {};
288 });
289​
290 return ensureTailscaleServe({ localPort: 13773, servePort: 8443 }).pipe(Effect.provide(layer));
291 });
292​
293 it.effect("retains tailscale serve exit diagnostics", () => {
294 const layer = mockSpawnerLayer(() => ({
295 code: 1,
296 stderr: "serve permission denied tskey-auth-secret-token-value",
297 }));
298​
299 return Effect.gen(function* () {
300 const error = yield* ensureTailscaleServe({ localPort: 13773, servePort: 8443 }).pipe(
301 Effect.flip,
302 Effect.provide(layer),
303 );
304​
305 assert.instanceOf(error, TailscaleCommandExitError);
306 assert.equal(error.executable, "tailscale");
307 assert.equal(error.subcommand, "serve");
308 assert.equal(error.argumentCount, 4);
309 assert.equal(error.exitCode, 1);
310 assert.equal(error.stderrLength, 53);
311 assert.notProperty(error, "command");
312 assert.notProperty(error, "stderr");
313 assert.notInclude(error.message, "tskey-auth-secret-token-value");
314 // The diagnostic classifies the failure without quoting stderr, so the
315 // key cannot reach a log through it either.
316 assert.equal(error.stderrDiagnostic, "permission-denied");
317 assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
318 });
319 });
320​
321 it.effect("disables tailscale serve through the process spawner service", () => {
322 const commands: {
323 readonly command: string;
324 readonly args: ReadonlyArray<string>;
325 }[] = [];
326 const layer = mockSpawnerLayer((command, args) => {
327 commands.push({ command, args });
328 assert.equal(command, "tailscale");
329 assert.deepEqual(args, ["serve", "--https=8443", "off"]);
330 return {};
331 });
332​
333 return Effect.gen(function* () {
334 yield* disableTailscaleServe({ servePort: 8443 }).pipe(Effect.provide(layer));
335 assert.deepEqual(commands, [
336 { command: "tailscale", args: ["serve", "--https=8443", "off"] },
337 ]);
338 });
339 });
340});