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

managedLimits.ts

244 lines10.4 KB

1/**
2 * managedLimits - what `limits.clients` and `limits.connect` in the managed policy allow, and the
3 * one error every refusal uses so each transport can show the administrator's organization.
4 *
5 * @module managedLimits
6 */
7import type {
8 ManagedPolicyClient,
9 ManagedPolicyDocument,
10 ServerAuthPolicy,
11} from "@t3tools/contracts";
12import {
13 disableTailscaleServe,
14 disableTailscaleServeTcp,
15 readTailscaleServeRoutesTo,
16 tailscaleServeOffArgs,
17 readTailscaleStatus,
18 type TailscaleServeRoute,
19 type TailscaleStderrDiagnostic,
20} from "@t3tools/tailscale";
21import * as Effect from "effect/Effect";
22import * as PlatformError from "effect/PlatformError";
23import * as Schema from "effect/Schema";
24​
25import * as NetService from "@t3tools/shared/Net";
26​
27import { loopbackBindAddress } from "../auth/utils.ts";
28​
29type PolicyDocument = { readonly document: ManagedPolicyDocument | undefined };
30​
31export class ManagedPolicyRefusedError extends Schema.TaggedError<ManagedPolicyRefusedError>()(
32 "ManagedPolicyRefusedError",
33 {
34 organization: Schema.String,
35 /** What the policy does not allow, for example "T3 Connect". */
36 action: Schema.String,
37 /** What that means for this request, for example "so the server cannot listen on 0.0.0.0". */
38 detail: Schema.optionalKey(Schema.String),
39 },
40) {
41 override get message(): string {
42 return `${this.organization}'s policy does not allow ${this.action}${
43 this.detail === undefined ? "" : `, ${this.detail}`
44 }.`;
45 }
47​
48const CLIENT_AUTH_POLICY: Record<ManagedPolicyClient, ServerAuthPolicy> = {
49 desktop: "desktop-managed-local",
50 "local-browser": "loopback-browser",
51 remote: "remote-reachable",
52};
53​
54const AUTH_POLICY_ACTION: Record<ServerAuthPolicy, string> = {
55 "desktop-managed-local": "the desktop app",
56 "loopback-browser": "browsers on this machine",
57 "remote-reachable": "remote clients",
58 "unsafe-no-auth": "running without authentication",
59};
60​
61/** Whether the server may run with `authPolicy`. Any policy file rules out `unsafe-no-auth`. */
62export function allowsAuthPolicy(policy: PolicyDocument, authPolicy: ServerAuthPolicy): boolean {
63 if (policy.document === undefined) return true;
64 if (authPolicy === "unsafe-no-auth") return false;
65 const clients = policy.document.limits?.clients;
66 return (
67 clients === undefined || clients.some((client) => CLIENT_AUTH_POLICY[client] === authPolicy)
68 );
70​
71/** Whether anything off this machine may pair, by LAN, Tailscale, or a minted link. */
72export const allowsRemoteClients = (policy: PolicyDocument) =>
73 allowsAuthPolicy(policy, "remote-reachable");
74​
75/** T3 Connect is a way for remote clients in, so a policy without `remote` turns it off too. */
76export const allowsConnect = (policy: PolicyDocument) =>
77 policy.document?.limits?.connect !== false && allowsRemoteClients(policy);
78​
79const refuse = (policy: PolicyDocument, action: string, detail?: string) =>
80 new ManagedPolicyRefusedError({
81 organization: policy.document?.organization ?? "Your organization",
82 action,
83 ...(detail === undefined ? {} : { detail }),
84 });
85​
86export const refuseConnect = (policy: PolicyDocument) => refuse(policy, "T3 Connect");
87​
88const isEnotdir = (cause: unknown) =>
89 cause instanceof Error && "code" in cause && cause.code === "ENOTDIR";
90​
91// A PATH that ends in a file fails the spawn with ENOTDIR, typed or as a thrown defect.
92const isMissingCli = (cause: unknown) =>
93 PlatformError.isPlatformError(cause)
94 ? cause.reason._tag === "NotFound" ||
95 (cause.reason._tag === "BadResource" && isEnotdir(cause.reason.cause))
96 : isEnotdir(cause);
97​
98const NOTHING_FORWARDED: ReadonlyArray<TailscaleServeRoute> = [];
99​
100/** Tailscale answers that leave nothing forwarding here right now. */
101const NOTHING_TO_CLOSE: ReadonlySet<TailscaleStderrDiagnostic | undefined> = new Set([
102 "not-running",
103 "not-logged-in",
104]);
105​
106/**
107 * Turns off the Tailscale Serve routes that forward to the server at `target`, such as one
108 * `t3 pair --tailscale` left from before the policy, and keeps every other route. Runs before the
109 * server binds, and fails unless a fresh read shows no route here, since `off` can exit 0 and
110 * leave it. Without the CLI, or with Tailscale down or logged out, nothing forwards.
111 */
112export const closeTailscaleServeTo = Effect.fn("managedLimits.closeTailscaleServeTo")(function* (
113 policy: PolicyDocument,
114 target: { readonly host: string; readonly port: number },
115) {
116 if (allowsRemoteClients(policy)) return;
117 // Another app holds the port, so its routes are not ours to remove. It could let go before the
118 // bind, which would then take over those routes, so the server does not start.
119 if (!(yield* (yield* NetService.NetService).canListenOnHost(target.port, target.host))) {
120 return yield* refuseRemoteClients(
121 policy,
122 `so the server does not start while it cannot bind ${target.host}:${target.port}; if another app holds that port, the server would take over its Tailscale Serve routes`,
123 );
124 }
125 const readRoutes = readTailscaleServeRoutesTo(target).pipe(
126 Effect.catchTags({
127 // Only a CLI that is not there; one that will not run might still front a daemon.
128 TailscaleCommandSpawnError: (error) =>
129 isMissingCli(error.cause) ? Effect.succeed(NOTHING_FORWARDED) : Effect.fail(error),
130 TailscaleCommandExitError: (error) =>
131 NOTHING_TO_CLOSE.has(error.stderrDiagnostic)
132 ? Effect.succeed(NOTHING_FORWARDED)
133 : Effect.fail(error),
134 }),
135 // Tailscale errors carry only labelled diagnostics, never raw stderr, so they are safe to log.
136 Effect.tapError((cause) =>
137 Effect.logWarning("Tailscale Serve could not be checked", { cause }),
138 ),
139 Effect.mapError((error) =>
140 refuseRemoteClients(
141 policy,
142 error._tag === "TailscaleCommandTimeoutError"
143 ? // Seen on a Mac where Tailscale is installed but was never set up.
144 "so the server does not start until Tailscale Serve can be checked, and Tailscale did not answer; open Tailscale and finish setting it up, or remove it"
145 : "so the server does not start until Tailscale Serve can be checked",
146 ),
147 ),
148 );
149 const found = yield* readRoutes;
150 if (found.length === 0) return;
151 // `off` acts on the machine's current name, so a web route under a former name stays.
152 const currentName = found.some((route) => route.mount !== undefined && route.owner === undefined)
153 ? yield* readTailscaleStatus.pipe(
154 Effect.map((status) => status.magicDnsName?.toLowerCase() ?? null),
155 Effect.orElseSucceed(() => null),
156 )
157 : null;
158 const formerName = (route: TailscaleServeRoute) =>
159 route.owner === undefined &&
160 route.host !== undefined &&
161 currentName !== null &&
162 route.host.toLowerCase() !== currentName;
163 // A Service is shared across the tailnet, and a foreground route lives as long as its command.
164 const removable = (route: TailscaleServeRoute) =>
165 route.owner === undefined &&
166 route.ambiguous === undefined &&
167 (route.mount === undefined || (currentName !== null && !formerName(route)));
168 for (const route of found.filter(removable)) {
169 yield* (
170 route.mount === undefined
171 ? disableTailscaleServeTcp(route.servePort)
172 : disableTailscaleServe(route)
173 ).pipe(
174 Effect.catch((cause) =>
175 Effect.logWarning("Tailscale Serve route could not be turned off", { ...route, cause }),
176 ),
177 );
178 }
179 const left = yield* readRoutes;
180 if (left.length > 0) {
181 const describe = (route: TailscaleServeRoute) => {
182 const where = `port ${route.servePort}${route.mount === undefined ? "" : ` at ${route.mount}`} here`;
183 const off = tailscaleServeOffArgs(route);
184 if (off === undefined) return `${where}; stop the "tailscale serve" command that runs it`;
185 if (formerName(route)) {
186 return `${where} under ${route.host}, a former name of this machine, which "tailscale serve ... off" cannot reach; run "tailscale serve reset" and set up your other routes again`;
187 }
188 const command = `"tailscale ${off.join(" ")}"`;
189 // Without the current name, `off` might act on another name's route at this path.
190 if (currentName === null && route.owner === undefined && route.host !== undefined) {
191 return `${where} under ${route.host}; if that is this machine's current name, turn it off with ${command}`;
192 }
193 return route.ambiguous !== undefined
194 ? `${where}, and its target ${route.ambiguous} might be another service on this port; check it, then turn it off with ${command}`
195 : `${where}; turn it off with ${command}`;
196 };
197 return yield* refuseRemoteClients(
198 policy,
199 `so the server does not start while Tailscale Serve forwards ${left.map(describe).join(", and ")}`,
200 );
201 }
202 yield* Effect.logInfo("Turned off Tailscale Serve the managed policy does not allow", {
203 routes: found,
204 });
205});
206​
207export const refuseRemoteClients = (policy: PolicyDocument, detail?: string) =>
208 refuse(policy, AUTH_POLICY_ACTION["remote-reachable"], detail);
209​
210/**
211 * Fails when the server would accept clients the policy leaves out; otherwise returns the address
212 * to bind. Runs before the server binds, so a refused configuration never listens, not even
213 * briefly. Without `remote` that address is the loopback literal the check approved, never a name.
214 */
215export const checkServerReachability = Effect.fn("managedLimits.checkServerReachability")(
216 function* (
217 policy: PolicyDocument,
218 input: {
219 readonly authPolicy: ServerAuthPolicy;
220 readonly host: string | undefined;
221 readonly tailscaleServeEnabled: boolean;
222 /** The background service chose `host` to reach private networks; the user did not. */
223 readonly privateNetworkOnly?: boolean | undefined;
224 },
225 ) {
226 const cannotListen = () =>
227 refuseRemoteClients(
228 policy,
229 input.privateNetworkOnly === true
230 ? "so the background service cannot listen on private networks; set T3CODE_HOST=127.0.0.1 in its service.env"
231 : `so the server cannot listen on ${input.host === "" ? "every interface" : (input.host ?? "this host")}`,
232 );
233 if (!allowsAuthPolicy(policy, input.authPolicy)) {
234 return yield* input.authPolicy === "remote-reachable"
235 ? cannotListen()
236 : refuse(policy, AUTH_POLICY_ACTION[input.authPolicy]);
237 }
238 if (allowsRemoteClients(policy)) return input.host ?? "127.0.0.1";
239 if (input.tailscaleServeEnabled) {
240 return yield* refuseRemoteClients(policy, "so Tailscale Serve cannot be turned on");
241 }
242 return loopbackBindAddress(input.host) ?? (yield* cannotListen());
243 },
244);