Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { describe, expect, it } from "@effect/vitest";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import type * as ChildProcess from "effect/process/ChildProcess";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16
17import * as ProcessRunner from "../processRunner.ts";
18import * as ServiceProtection from "./serviceProtection.ts";
19
20const temporaryDirectory = () =>
21 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-service-protection-"));
22
23describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("renderPrivilegedScript", () => {
24 it("writes and removes only its drop-ins and gives running main processes their score", () => {
25 const root = temporaryDirectory();
26 const target = NodeChildProcess.spawn("sleep", ["60"], { stdio: "ignore" });
27 try {
28 const systemUnitDir = NodePath.join(root, "system");
29 const plan = (uid: number, remoteAccessUnits: ReadonlyArray<string>) =>
30 ServiceProtection.protectionPlan({
31 uid,
32 userUnitDir: "/home/theo/.config/systemd/user",
33 remoteAccessUnits,
34 systemUnitDir,
35 });
36 const theo = plan(1000, ["tailscaled.service", "ssh.service"]);
37 expect(theo.system.find((dropIn) => dropIn.unit === "user@1000.service")?.contents).toBe(
38 "[Service]\nMemoryLow=2G\nOOMScoreAdjust=-900\n",
39 );
40 expect(theo.managerDefaults.path).toBe(
41 "/home/theo/.config/systemd/user.conf.d/90-t3code-protect.conf",
42 );
43 expect(theo.oomUnits).toEqual(["user@1000.service", "tailscaled.service", "ssh.service"]);
44
45 const unrelated = NodePath.join(systemUnitDir, "ssh.service.d", "50-admin.conf");
46 NodeFS.mkdirSync(NodePath.dirname(unrelated), { recursive: true });
47 NodeFS.writeFileSync(unrelated, "[Service]\nNice=1\n");
48 const bin = NodePath.join(root, "bin");
49 NodeFS.mkdirSync(bin);
50 // Raising a score needs no privilege, so the test's own child stands in for a main process.
51 NodeFS.writeFileSync(
52 NodePath.join(bin, "systemctl"),
53 [
54 "#!/bin/sh",
55 'echo "$*" >>"$CALLS"',
56 'case "$*" in',
57 ' *MainPID*) echo "$TARGET_PID" ;;',
58 " *OOMScoreAdjust*) echo 900 ;;",
59 "esac",
60 "",
61 ].join("\n"),
62 { mode: 0o755 },
63 );
64 const calls = NodePath.join(root, "calls");
65 const runScript = (protection: ServiceProtection.ProtectionPlan, mode: "apply" | "undo") => {
66 const result = NodeChildProcess.spawnSync(
67 "/bin/sh",
68 ["-c", ServiceProtection.renderPrivilegedScript(protection, mode)],
69 {
70 encoding: "utf8",
71 env: {
72 PATH: `${bin}:/usr/bin:/bin`,
73 CALLS: calls,
74 TARGET_PID: String(target.pid),
75 },
76 },
77 );
78 expect(result.stderr).toBe("");
79 expect(result.status).toBe(0);
80 };
81 const exists = (unit: string) =>
82 NodeFS.existsSync(NodePath.join(systemUnitDir, `${unit}.d`, "90-t3code-protect.conf"));
83
84 runScript(theo, "apply");
85 runScript(plan(1001, []), "apply");
86 for (const { path, contents } of theo.system) {
87 expect(NodeFS.readFileSync(path, "utf8")).toBe(contents);
88 }
89 expect(NodeFS.readFileSync(`/proc/${target.pid}/oom_score_adj`, "utf8").trim()).toBe("900");
90 expect(NodeFS.readFileSync(calls, "utf8").split("\n")[0]).toBe("daemon-reload");
91
92 // Undo removes every drop-in a user could own, and keeps shared ones while another user is protected.
93 const undo = (uid: number) => plan(uid, ServiceProtection.REMOTE_ACCESS_UNITS);
94 runScript(undo(1000), "undo");
95 expect(["user-1000.slice", "user@1000.service"].some(exists)).toBe(false);
96 expect(
97 ["user.slice", "system.slice", "tailscaled.service", "ssh.service"].every(exists),
98 ).toBe(true);
99
100 runScript(undo(1001), "undo");
101 for (const { path } of undo(1001).system) expect(NodeFS.existsSync(path)).toBe(false);
102 expect(NodeFS.existsSync(NodePath.join(systemUnitDir, "user.slice.d"))).toBe(false);
103 expect(NodeFS.readFileSync(unrelated, "utf8")).toBe("[Service]\nNice=1\n");
104 } finally {
105 target.kill();
106 NodeFS.rmSync(root, { recursive: true, force: true });
107 }
108 });
109});
110
111it.each([
112 [
113 "Debian, where sshd.service aliases ssh.service",
114 "Id=tailscaled.service\nLoadState=loaded\n\nId=ssh.service\nLoadState=loaded\n\nId=ssh.service\nLoadState=loaded\n",
115 ["tailscaled.service", "ssh.service"],
116 ],
117 [
118 "Fedora without Tailscale",
119 "Id=tailscaled.service\nLoadState=not-found\n\nId=ssh.service\nLoadState=not-found\n\nId=sshd.service\nLoadState=loaded\n",
120 ["sshd.service"],
121 ],
122])("finds remote-access services on %s", (_, shown, expected) => {
123 expect(ServiceProtection.loadedRemoteAccessUnits(shown)).toEqual(expected);
124});
125
126const fakeSudo = (exitCode: number, onRun: (command: ChildProcess.StandardCommand) => void) =>
127 ChildProcessSpawner.make((command) =>
128 Effect.gen(function* () {
129 if (command._tag !== "StandardCommand" || command.command !== "sudo") {
130 return yield* Effect.die("Unexpected command");
131 }
132 onRun(command);
133 return ChildProcessSpawner.makeHandle({
134 pid: ChildProcessSpawner.ProcessId(123),
135 stdout: Stream.empty,
136 stderr: Stream.empty,
137 all: Stream.empty,
138 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
139 isRunning: Effect.succeed(false),
140 kill: () => Effect.void,
141 stdin: Sink.drain,
142 getInputFd: () => Sink.drain,
143 getOutputFd: () => Stream.empty,
144 unref: Effect.succeed(Effect.void),
145 });
146 }),
147 );
148
149const runner = (stdout: string) =>
150 ProcessRunner.ProcessRunner.of({
151 run: () =>
152 Effect.succeed({
153 stdout,
154 stderr: "",
155 code: ChildProcessSpawner.ExitCode(0),
156 timedOut: false,
157 stdoutTruncated: false,
158 stderrTruncated: false,
159 stdoutInvalidUtf8: false,
160 stderrInvalidUtf8: false,
161 }),
162 });
163
164it.effect("lowers no score before the manager default is in place, and undoes in reverse", () => {
165 const home = temporaryDirectory();
166 return Effect.gen(function* () {
167 const plan = ServiceProtection.protectionPlan({
168 uid: 1000,
169 userUnitDir: NodePath.join(home, ".config", "systemd", "user"),
170 remoteAccessUnits: [],
171 systemUnitDir: NodePath.join(home, "system"),
172 });
173 const managerDropIn = plan.system.find(({ unit }) => unit === "user@1000.service")!.path;
174 const present = () => ({
175 managerDefaults: NodeFS.existsSync(plan.managerDefaults.path),
176 user: plan.user.filter(({ path }) => NodeFS.existsSync(path)).length,
177 });
178 const withSudo = <A, E, R>(
179 effect: Effect.Effect<A, E, R>,
180 exitCode: number,
181 writesManagerDropIn = false,
182 ) => {
183 let atSudo: ReturnType<typeof present> | undefined;
184 let sudoOptions: ChildProcess.CommandOptions | undefined;
185 return effect.pipe(
186 Effect.provideService(
187 ChildProcessSpawner.ChildProcessSpawner,
188 fakeSudo(exitCode, (command) => {
189 atSudo = present();
190 sudoOptions = command.options;
191 if (writesManagerDropIn) {
192 NodeFS.mkdirSync(NodePath.dirname(managerDropIn), { recursive: true });
193 NodeFS.writeFileSync(managerDropIn, "[Service]\nOOMScoreAdjust=-900\n");
194 }
195 }),
196 ),
197 Effect.exit,
198 Effect.map((exit) => ({ exit, atSudo, sudoOptions })),
199 );
200 };
201 const refused = yield* withSudo(ServiceProtection.applyProtection(plan), 1);
202 expect(refused.exit._tag).toBe("Failure");
203 expect(refused.atSudo).toEqual({ managerDefaults: true, user: 0 });
204 expect(present()).toEqual({ managerDefaults: false, user: 0 });
205
206 // Failing after it lowered the manager, sudo must leave the manager default in place.
207 const partial = yield* withSudo(ServiceProtection.applyProtection(plan), 1, true);
208 expect(partial.exit._tag).toBe("Failure");
209 expect(present()).toEqual({ managerDefaults: true, user: 0 });
210 NodeFS.rmSync(plan.managerDefaults.path);
211 NodeFS.rmSync(managerDropIn);
212
213 const applied = yield* withSudo(ServiceProtection.applyProtection(plan), 0);
214 expect(applied.atSudo).toEqual({ managerDefaults: true, user: 0 });
215 // sudo needs the controlling terminal to ask for a password.
216 expect(applied.sudoOptions).toMatchObject({ detached: false, stdin: "inherit" });
217 expect(present()).toEqual({ managerDefaults: true, user: plan.user.length });
218
219 const removed = yield* withSudo(ServiceProtection.removeProtection(plan), 0);
220 expect(removed.atSudo).toEqual({ managerDefaults: true, user: 0 });
221 expect(present()).toEqual({ managerDefaults: false, user: 0 });
222 }).pipe(
223 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(home, { recursive: true, force: true }))),
224 Effect.provideService(ProcessRunner.ProcessRunner, runner("")),
225 Effect.provide(NodeServices.layer),
226 );
227});
228
229it.effect("counts memory.min as protection and names the first cgroup that grants none", () => {
230 const root = temporaryDirectory();
231 const controlGroup = [
232 "user.slice",
233 "user-1000.slice",
234 "user@1000.service",
235 "app.slice",
236 "t3code.service",
237 ];
238 const write = (depth: number, file: string, value: string) => {
239 const directory = NodePath.join(root, ...controlGroup.slice(0, depth));
240 NodeFS.mkdirSync(directory, { recursive: true });
241 NodeFS.writeFileSync(NodePath.join(directory, file), `${value}\n`);
242 };
243 write(1, "memory.low", "0");
244 write(1, "memory.min", "805306368");
245 write(2, "memory.low", "2147483648");
246 write(3, "memory.low", "2147483648");
247 write(4, "memory.low", "0");
248 write(4, "memory.min", "0");
249 write(5, "memory.low", "1610612736");
250 return Effect.gen(function* () {
251 const fs = yield* FileSystem.FileSystem;
252 const read = ServiceProtection.readProtection("/home/theo/.config/systemd/user").pipe(
253 Effect.provideService(FileSystem.FileSystem, {
254 ...fs,
255 readFileString: (path, encoding) =>
256 fs.readFileString(path.replace("/sys/fs/cgroup", root), encoding),
257 }),
258 );
259 expect((yield* read)?.unprotected).toBe("app.slice");
260 write(4, "memory.low", "1610612736");
261 expect((yield* read)?.unprotected).toBeUndefined();
262 }).pipe(
263 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true }))),
264 Effect.provideService(
265 ProcessRunner.ProcessRunner,
266 runner(`ControlGroup=/${controlGroup.join("/")}\nMainPID=0\n`),
267 ),
268 Effect.provide(NodeServices.layer),
269 );
270});