Open History to see the last commit
1import type { ManagedPolicyDocument } from "@t3tools/contracts";
2import { assert, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as PlatformError from "effect/PlatformError";
6import * as Sink from "effect/Sink";
7import * as Stream from "effect/Stream";
8import * as TestClock from "effect/testing/TestClock";
9import { ChildProcessSpawner } from "effect/process";
10
11import * as NetService from "@t3tools/shared/Net";
12
13import * as EnvironmentAuthPolicy from "../auth/EnvironmentAuthPolicy.ts";
14import * as ManagedLimits from "./managedLimits.ts";
15import * as ManagedPolicy from "./ManagedPolicy.ts";
16
17const policy = (limits?: ManagedPolicyDocument["limits"]) => ({
18 document: {
19 schemaVersion: 1 as const,
20 organization: "Example Corp",
21 ...(limits === undefined ? {} : { limits }),
22 },
23});
24
25const desktopAndLocal = policy({ clients: ["desktop", "local-browser"] });
26
27it.effect("refuses to listen on a non-loopback host when remote clients are not allowed", () =>
28 Effect.gen(function* () {
29 const error = yield* ManagedLimits.checkServerReachability(desktopAndLocal, {
30 authPolicy: "remote-reachable",
31 host: "0.0.0.0",
32 tailscaleServeEnabled: false,
33 }).pipe(Effect.flip);
34 assert.equal(
35 error.message,
36 "Example Corp's policy does not allow remote clients, so the server cannot listen on 0.0.0.0.",
37 );
38 }),
39);
40
41it.effect("binds only the loopback address it approved when remote clients are not allowed", () =>
42 Effect.gen(function* () {
43 const bind = (
44 host: string | undefined,
45 policy: { readonly document: ManagedPolicyDocument | undefined } = desktopAndLocal,
46 ) =>
47 ManagedLimits.checkServerReachability(policy, {
48 authPolicy: EnvironmentAuthPolicy.resolveServerAuthPolicy({ mode: "web", host }),
49 host,
50 tailscaleServeEnabled: false,
51 });
52 // Node listens on every interface for an empty host, and a name resolves through DNS.
53 for (const host of ["", "127.office.example", "127.0.0.1e0", "0.0.0.0"]) {
54 const error = yield* bind(host).pipe(Effect.flip);
55 assert.include(error.message, "does not allow remote clients", host);
56 }
57 for (const [host, address] of [
58 [undefined, "127.0.0.1"],
59 ["localhost", "127.0.0.1"],
60 ["127.0.0.2", "127.0.0.2"],
61 ["[::1]", "::1"],
62 ] as const) {
63 assert.equal(yield* bind(host), address);
64 }
65 const service = yield* ManagedLimits.checkServerReachability(desktopAndLocal, {
66 authPolicy: "remote-reachable",
67 host: "0.0.0.0",
68 tailscaleServeEnabled: false,
69 privateNetworkOnly: true,
70 }).pipe(Effect.flip);
71 assert.include(service.message, "set T3CODE_HOST=127.0.0.1 in its service.env");
72 assert.equal(yield* bind("localhost", { document: undefined }), "localhost");
73 assert.equal(yield* bind(undefined, { document: undefined }), "127.0.0.1");
74 }),
75);
76
77it.effect("refuses Tailscale Serve when remote clients are not allowed", () =>
78 Effect.gen(function* () {
79 const error = yield* ManagedLimits.checkServerReachability(desktopAndLocal, {
80 authPolicy: "loopback-browser",
81 host: undefined,
82 tailscaleServeEnabled: true,
83 }).pipe(Effect.flip);
84 assert.include(error.message, "Tailscale Serve");
85 }),
86);
87
88it.effect("refuses an auth policy the clients list leaves out", () =>
89 Effect.gen(function* () {
90 const error = yield* ManagedLimits.checkServerReachability(policy({ clients: ["desktop"] }), {
91 authPolicy: "loopback-browser",
92 host: undefined,
93 tailscaleServeEnabled: false,
94 }).pipe(Effect.flip);
95 assert.equal(error.message, "Example Corp's policy does not allow browsers on this machine.");
96 }),
97);
98
99it.effect("refuses unsafe-no-auth under any policy file, even one without limits", () =>
100 Effect.gen(function* () {
101 const error = yield* ManagedLimits.checkServerReachability(policy(), {
102 authPolicy: "unsafe-no-auth",
103 host: undefined,
104 tailscaleServeEnabled: false,
105 }).pipe(Effect.flip);
106 assert.include(error.message, "without authentication");
107 assert.isTrue(ManagedLimits.allowsAuthPolicy({ document: undefined }, "unsafe-no-auth"));
108 }),
109);
110
111it.effect("allows the clients the policy lists", () =>
112 ManagedLimits.checkServerReachability(policy({ clients: ["remote"] }), {
113 authPolicy: "remote-reachable",
114 host: "0.0.0.0",
115 tailscaleServeEnabled: true,
116 }),
117);
118
119it.effect("tells clients Connect is off when the policy leaves out remote clients", () =>
120 Effect.gen(function* () {
121 const managed = yield* ManagedPolicy.fromDocument("/test/policy.json", {
122 ...desktopAndLocal.document,
123 });
124 assert.deepEqual(managed.summary?.limits, {
125 clients: ["desktop", "local-browser"],
126 connect: false,
127 });
128 assert.isTrue(ManagedLimits.allowsConnect(policy({ clients: ["remote"] })));
129 assert.isFalse(ManagedLimits.allowsConnect(policy({ connect: false })));
130 }),
131);
132
133it.effect(
134 "turns off only the Tailscale Serve routes that forward here, and refuses to start if one stays",
135 () => {
136 type Web = Record<string, Record<string, string>>;
137 interface Answers {
138 /** Serve handlers by host:port, then mount, to proxy target. */
139 readonly web?: Web;
140 /** TCP forwards by port. */
141 readonly tcp?: Record<string, string>;
142 /** The name `off` acts on: the machine's current one. */
143 readonly currentName?: string;
144 readonly status?: {
145 readonly stdout: string;
146 readonly exitCode: number;
147 readonly stderr?: string;
148 };
149 readonly offExitCode?: number;
150 /** `serve status` never answers, as on a Mac where Tailscale was never set up. */
151 readonly statusHangs?: boolean;
152 /** `off` exits as told but leaves the config alone. */
153 readonly offIgnored?: boolean;
154 }
155 // Acts as the real CLI: `serve status --json` prints the config; `serve --https=<port> off`
156 // drops every handler on that port of the current name unless `--set-path` names one
157 // (serve_v2.go removeWebServe), and `serve --tcp=<port> off` drops that port's forward.
158 const close = (answers: Answers, offCalls: Array<ReadonlyArray<string>> = []) => {
159 const web: Web = answers.web ?? {
160 "box.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" },
161 };
162 const tcp = answers.tcp ?? {};
163 const currentName = answers.currentName ?? "box.tailnet.ts.net";
164 return ManagedLimits.closeTailscaleServeTo(desktopAndLocal, {
165 host: "127.0.0.1",
166 port: 3773,
167 }).pipe(
168 Effect.provideService(
169 ChildProcessSpawner.ChildProcessSpawner,
170 ChildProcessSpawner.make((command) => {
171 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
172 // `tailscale status --json` names the machine; `tailscale serve status --json` routes.
173 if (args[0] === "status") {
174 return Effect.succeed(
175 ChildProcessSpawner.makeHandle({
176 pid: ChildProcessSpawner.ProcessId(1),
177 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
178 exitStatus: Effect.succeed({
179 _tag: "Exited",
180 code: ChildProcessSpawner.ExitCode(0),
181 }),
182 isRunning: Effect.succeed(false),
183 kill: () => Effect.void,
184 unref: Effect.succeed(Effect.void),
185 stdin: Sink.drain,
186 stdout: Stream.make(
187 new TextEncoder().encode(
188 JSON.stringify({ Self: { DNSName: `${currentName}.` } }),
189 ),
190 ),
191 stderr: Stream.empty,
192 all: Stream.empty,
193 getInputFd: () => Sink.drain,
194 getOutputFd: () => Stream.empty,
195 }),
196 );
197 }
198 const isStatus = args.includes("status");
199 if (!isStatus) {
200 offCalls.push(args);
201 const port = args.find((arg) => arg.startsWith("--https="))?.slice(8);
202 const tcpPort = args.find((arg) => arg.startsWith("--tcp="))?.slice(6);
203 const mount = args.find((arg) => arg.startsWith("--set-path="))?.slice(11);
204 const site = web[`${currentName}:${port}`];
205 if (answers.offIgnored !== true) {
206 if (tcpPort !== undefined) delete tcp[tcpPort];
207 for (const handler of Object.keys(site ?? {})) {
208 if (mount === undefined || mount === handler) delete site![handler];
209 }
210 }
211 }
212 const status = answers.status ?? {
213 stdout: JSON.stringify({
214 TCP: Object.fromEntries(
215 Object.entries(tcp).map(([port, forward]) => [port, { TCPForward: forward }]),
216 ),
217 Web: Object.fromEntries(
218 Object.entries(web).map(([hostPort, handlers]) => [
219 hostPort,
220 {
221 Handlers: Object.fromEntries(
222 Object.entries(handlers).map(([mount, proxy]) => [mount, { Proxy: proxy }]),
223 ),
224 },
225 ]),
226 ),
227 }),
228 exitCode: 0,
229 };
230 const text = (value: string | undefined) =>
231 value === undefined ? Stream.empty : Stream.make(new TextEncoder().encode(value));
232 return Effect.succeed(
233 ChildProcessSpawner.makeHandle({
234 pid: ChildProcessSpawner.ProcessId(1),
235 exitCode:
236 isStatus && answers.statusHangs === true
237 ? Effect.never
238 : Effect.succeed(
239 ChildProcessSpawner.ExitCode(
240 isStatus ? status.exitCode : (answers.offExitCode ?? 0),
241 ),
242 ),
243 exitStatus:
244 isStatus && answers.statusHangs === true
245 ? Effect.never
246 : Effect.succeed({
247 _tag: "Exited",
248 code: ChildProcessSpawner.ExitCode(
249 isStatus ? status.exitCode : (answers.offExitCode ?? 0),
250 ),
251 }),
252 isRunning: Effect.succeed(false),
253 kill: () => Effect.void,
254 unref: Effect.succeed(Effect.void),
255 stdin: Sink.drain,
256 stdout: isStatus ? text(status.stdout) : Stream.empty,
257 stderr: isStatus ? text(status.stderr) : Stream.empty,
258 all: Stream.empty,
259 getInputFd: () => Sink.drain,
260 getOutputFd: () => Stream.empty,
261 }),
262 );
263 }),
264 ),
265 );
266 };
267 const portFree = { ...NetService.make(), canListenOnHost: () => Effect.succeed(true) };
268 const portHeld = { ...portFree, canListenOnHost: () => Effect.succeed(false) };
269 return Effect.gen(function* () {
270 // A route that shares the port with this server's stays, as does one to another loopback
271 // address on the same port; a TCP forward here goes too.
272 for (const mount of ["/t3", "/"]) {
273 const web: Web = {
274 "box.tailnet.ts.net:443": {
275 [mount]: "http://127.0.0.1:3773",
276 "/dashboard": "http://127.0.0.1:9000",
277 "/other": "http://127.0.0.2:3773",
278 },
279 };
280 const tcp: Record<string, string> = { "7000": "127.0.0.1:3773" };
281 const offCalls: Array<ReadonlyArray<string>> = [];
282 yield* close({ web, tcp }, offCalls);
283 assert.deepEqual(web, {
284 "box.tailnet.ts.net:443": {
285 "/dashboard": "http://127.0.0.1:9000",
286 "/other": "http://127.0.0.2:3773",
287 },
288 });
289 assert.deepEqual(tcp, {});
290 assert.deepEqual(offCalls, [
291 ["serve", "--tcp=7000", "off"],
292 ["serve", "--https=443", `--set-path=${mount}`, "off"],
293 ]);
294 }
295 // `off` acts on the current name: a route under a former one is left, with how to clear it,
296 // while one under the current name goes even if a former name has routes too.
297 const renamed: Web = {
298 "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" },
299 "new.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" },
300 };
301 const renamedOffCalls: Array<ReadonlyArray<string>> = [];
302 const former = yield* close(
303 { web: renamed, currentName: "new.tailnet.ts.net" },
304 renamedOffCalls,
305 ).pipe(Effect.flip);
306 assert.deepEqual(renamedOffCalls, []);
307 assert.deepEqual(renamed["new.tailnet.ts.net:443"], { "/": "http://127.0.0.1:9000" });
308 assert.include(
309 former.message,
310 'under old.tailnet.ts.net, a former name of this machine, which "tailscale serve ... off" cannot reach; run "tailscale serve reset"',
311 );
312 const current: Web = {
313 "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" },
314 "new.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" },
315 };
316 yield* close({ web: current, currentName: "new.tailnet.ts.net" });
317 assert.deepEqual(current, {
318 "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" },
319 "new.tailnet.ts.net:443": {},
320 });
321 // A `localhost` target might reach another service on the other loopback, so it stays.
322 const localhostOffCalls: Array<ReadonlyArray<string>> = [];
323 const localhost = yield* close(
324 { web: { "box.tailnet.ts.net:443": { "/": "http://localhost:3773" } } },
325 localhostOffCalls,
326 ).pipe(Effect.flip);
327 assert.deepEqual(localhostOffCalls, []);
328 assert.include(localhost.message, "its target localhost might be another service");
329 // Only a fresh read confirms the route is gone, whatever `off` exits with.
330 for (const answers of [{ offIgnored: true }, { offIgnored: true, offExitCode: 1 }]) {
331 const stuck = yield* close(answers).pipe(Effect.flip);
332 assert.include(
333 stuck.message,
334 'Tailscale Serve forwards port 443 at / here; turn it off with "tailscale serve --https=443 --set-path=/ off"',
335 );
336 }
337 // Routes the server must not remove itself: a Service's, and a foreground command's.
338 const owners = {
339 stdout: JSON.stringify({
340 Foreground: {
341 session1: {
342 Web: { "box:443": { Handlers: { "/": { Proxy: "http://127.0.0.1:3773" } } } },
343 },
344 },
345 Services: {
346 "svc:t3": {
347 Web: { "t3:443": { Handlers: { "/t3": { Proxy: "http://127.0.0.1:3773" } } } },
348 },
349 },
350 }),
351 exitCode: 0,
352 };
353 const ownedOffCalls: Array<ReadonlyArray<string>> = [];
354 const owned = yield* close({ status: owners }, ownedOffCalls).pipe(Effect.flip);
355 assert.deepEqual(ownedOffCalls, []);
356 assert.include(owned.message, 'stop the "tailscale serve" command that runs it');
357 assert.include(
358 owned.message,
359 '"tailscale serve --service=svc:t3 --https=443 --set-path=/t3 off"',
360 );
361 // An answer that cannot be read might hide a mapping, so the server does not start.
362 const dialFailure = (reason: string) =>
363 `Failed to connect to local Tailscale daemon for /localapi/v0/serve-config; not running? Error: dial unix /var/run/tailscale/tailscaled.sock: connect: ${reason}`;
364 for (const status of [
365 { stdout: "", exitCode: 1, stderr: "something unexpected" },
366 { stdout: "not json", exitCode: 0 },
367 { stdout: "", exitCode: 1, stderr: "Access denied: serve config denied" },
368 { stdout: "", exitCode: 1, stderr: dialFailure("permission denied") },
369 ]) {
370 const unread = yield* close({ status }).pipe(Effect.flip);
371 assert.include(unread.message, "does not start until Tailscale Serve can be checked");
372 }
373 // A Tailscale that never answers is not read as nothing to close, and the refusal says why.
374 const hung = yield* close({ statusHangs: true }).pipe(Effect.flip, Effect.forkChild);
375 yield* TestClock.adjust("10 seconds");
376 assert.include((yield* Fiber.join(hung)).message, "Tailscale did not answer");
377 // Tailscale down, logged out, or not installed forwards nothing now.
378 for (const stderr of [
379 dialFailure("connection refused"),
380 "NeedsLogin: not logged in",
381 String.raw`Get "http://local-tailscaled.sock/localapi/v0/serve-config": open \\.\pipe\ProtectedPrefix\Administrators\Tailscale\tailscaled: The system cannot find the file specified.`,
382 ]) {
383 yield* close({ status: { stdout: "", exitCode: 1, stderr } });
384 }
385 const spawnFailing = (tag: "NotFound" | "PermissionDenied") =>
386 ManagedLimits.closeTailscaleServeTo(desktopAndLocal, {
387 host: "127.0.0.1",
388 port: 3773,
389 }).pipe(
390 Effect.provideService(
391 ChildProcessSpawner.ChildProcessSpawner,
392 ChildProcessSpawner.make(() =>
393 Effect.fail(
394 PlatformError.systemError({ _tag: tag, module: "ChildProcess", method: "spawn" }),
395 ),
396 ),
397 ),
398 );
399 yield* spawnFailing("NotFound");
400 // Node throws this instead when PATH ends in a file.
401 yield* ManagedLimits.closeTailscaleServeTo(desktopAndLocal, {
402 host: "127.0.0.1",
403 port: 3773,
404 }).pipe(
405 Effect.provideService(
406 ChildProcessSpawner.ChildProcessSpawner,
407 ChildProcessSpawner.make(() =>
408 Effect.die(Object.assign(new Error("spawn tailscale ENOTDIR"), { code: "ENOTDIR" })),
409 ),
410 ),
411 );
412 // Effect's spawner types that throw.
413 yield* ManagedLimits.closeTailscaleServeTo(desktopAndLocal, {
414 host: "127.0.0.1",
415 port: 3773,
416 }).pipe(
417 Effect.provideService(
418 ChildProcessSpawner.ChildProcessSpawner,
419 ChildProcessSpawner.make(() =>
420 Effect.fail(
421 PlatformError.systemError({
422 _tag: "BadResource",
423 module: "ChildProcess",
424 method: "spawn",
425 cause: Object.assign(new Error("spawn ENOTDIR"), { code: "ENOTDIR" }),
426 }),
427 ),
428 ),
429 ),
430 );
431 // A CLI that is there but will not run might still front a daemon with a mapping.
432 yield* spawnFailing("PermissionDenied").pipe(Effect.flip);
433 // Another app holds the port: its route is not ours, and it could let go before the bind.
434 const heldOffCalls: Array<ReadonlyArray<string>> = [];
435 const held = yield* close({}, heldOffCalls).pipe(
436 Effect.provideService(NetService.NetService, portHeld),
437 Effect.flip,
438 );
439 assert.deepEqual(heldOffCalls, []);
440 assert.include(held.message, "while it cannot bind 127.0.0.1:3773");
441 }).pipe(Effect.provideService(NetService.NetService, portFree));
442 },
443);