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 exitStatus: Effect.succeed({
140 _tag: "Exited",
141 code: ChildProcessSpawner.ExitCode(exitCode),
142 }),
143 isRunning: Effect.succeed(false),
144 kill: () => Effect.void,
145 stdin: Sink.drain,
146 getInputFd: () => Sink.drain,
147 getOutputFd: () => Stream.empty,
148 unref: Effect.succeed(Effect.void),
149 });
150 }),
151 );
152
153const runner = (stdout: string) =>
154 ProcessRunner.ProcessRunner.of({
155 run: () =>
156 Effect.succeed({
157 stdout,
158 stderr: "",
159 code: ChildProcessSpawner.ExitCode(0),
160 timedOut: false,
161 stdoutTruncated: false,
162 stderrTruncated: false,
163 stdoutInvalidUtf8: false,
164 stderrInvalidUtf8: false,
165 }),
166 });
167
168it.effect("lowers no score before the manager default is in place, and undoes in reverse", () => {
169 const home = temporaryDirectory();
170 return Effect.gen(function* () {
171 const plan = ServiceProtection.protectionPlan({
172 uid: 1000,
173 userUnitDir: NodePath.join(home, ".config", "systemd", "user"),
174 remoteAccessUnits: [],
175 systemUnitDir: NodePath.join(home, "system"),
176 });
177 const managerDropIn = plan.system.find(({ unit }) => unit === "user@1000.service")!.path;
178 const present = () => ({
179 managerDefaults: NodeFS.existsSync(plan.managerDefaults.path),
180 user: plan.user.filter(({ path }) => NodeFS.existsSync(path)).length,
181 });
182 const withSudo = <A, E, R>(
183 effect: Effect.Effect<A, E, R>,
184 exitCode: number,
185 writesManagerDropIn = false,
186 ) => {
187 let atSudo: ReturnType<typeof present> | undefined;
188 let sudoOptions: ChildProcess.CommandOptions | undefined;
189 return effect.pipe(
190 Effect.provideService(
191 ChildProcessSpawner.ChildProcessSpawner,
192 fakeSudo(exitCode, (command) => {
193 atSudo = present();
194 sudoOptions = command.options;
195 if (writesManagerDropIn) {
196 NodeFS.mkdirSync(NodePath.dirname(managerDropIn), { recursive: true });
197 NodeFS.writeFileSync(managerDropIn, "[Service]\nOOMScoreAdjust=-900\n");
198 }
199 }),
200 ),
201 Effect.exit,
202 Effect.map((exit) => ({ exit, atSudo, sudoOptions })),
203 );
204 };
205 const refused = yield* withSudo(ServiceProtection.applyProtection(plan), 1);
206 expect(refused.exit._tag).toBe("Failure");
207 expect(refused.atSudo).toEqual({ managerDefaults: true, user: 0 });
208 expect(present()).toEqual({ managerDefaults: false, user: 0 });
209
210 // Failing after it lowered the manager, sudo must leave the manager default in place.
211 const partial = yield* withSudo(ServiceProtection.applyProtection(plan), 1, true);
212 expect(partial.exit._tag).toBe("Failure");
213 expect(present()).toEqual({ managerDefaults: true, user: 0 });
214 NodeFS.rmSync(plan.managerDefaults.path);
215 NodeFS.rmSync(managerDropIn);
216
217 const applied = yield* withSudo(ServiceProtection.applyProtection(plan), 0);
218 expect(applied.atSudo).toEqual({ managerDefaults: true, user: 0 });
219 // sudo needs the controlling terminal to ask for a password.
220 expect(applied.sudoOptions).toMatchObject({ detached: false, stdin: "inherit" });
221 expect(present()).toEqual({ managerDefaults: true, user: plan.user.length });
222
223 const removed = yield* withSudo(ServiceProtection.removeProtection(plan), 0);
224 expect(removed.atSudo).toEqual({ managerDefaults: true, user: 0 });
225 expect(present()).toEqual({ managerDefaults: false, user: 0 });
226 }).pipe(
227 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(home, { recursive: true, force: true }))),
228 Effect.provideService(ProcessRunner.ProcessRunner, runner("")),
229 Effect.provide(NodeServices.layer),
230 );
231});
232
233it.effect("counts memory.min as protection and names the first cgroup that grants none", () => {
234 const root = temporaryDirectory();
235 const controlGroup = [
236 "user.slice",
237 "user-1000.slice",
238 "user@1000.service",
239 "app.slice",
240 "t3code.service",
241 ];
242 const write = (depth: number, file: string, value: string) => {
243 const directory = NodePath.join(root, ...controlGroup.slice(0, depth));
244 NodeFS.mkdirSync(directory, { recursive: true });
245 NodeFS.writeFileSync(NodePath.join(directory, file), `${value}\n`);
246 };
247 write(1, "memory.low", "0");
248 write(1, "memory.min", "805306368");
249 write(2, "memory.low", "2147483648");
250 write(3, "memory.low", "2147483648");
251 write(4, "memory.low", "0");
252 write(4, "memory.min", "0");
253 write(5, "memory.low", "1610612736");
254 return Effect.gen(function* () {
255 const fs = yield* FileSystem.FileSystem;
256 const read = ServiceProtection.readProtection("/home/theo/.config/systemd/user").pipe(
257 Effect.provideService(FileSystem.FileSystem, {
258 ...fs,
259 readFileString: (path, encoding) =>
260 fs.readFileString(path.replace("/sys/fs/cgroup", root), encoding),
261 }),
262 );
263 expect((yield* read)?.unprotected).toBe("app.slice");
264 write(4, "memory.low", "1610612736");
265 expect((yield* read)?.unprotected).toBeUndefined();
266 }).pipe(
267 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true }))),
268 Effect.provideService(
269 ProcessRunner.ProcessRunner,
270 runner(`ControlGroup=/${controlGroup.join("/")}\nMainPID=0\n`),
271 ),
272 Effect.provide(NodeServices.layer),
273 );
274});
275
276it.effect(
277 "tells a kernel without the memory controller apart from a cgroup that grants none",
278 () => {
279 const root = temporaryDirectory();
280 NodeFS.mkdirSync(NodePath.join(root, "user.slice"), { recursive: true });
281 NodeFS.writeFileSync(NodePath.join(root, "cgroup.controllers"), "cpuset cpu io pids\n");
282 return Effect.gen(function* () {
283 const fs = yield* FileSystem.FileSystem;
284 const state = yield* ServiceProtection.readProtection("/home/theo/.config/systemd/user").pipe(
285 Effect.provideService(FileSystem.FileSystem, {
286 ...fs,
287 readFileString: (path, encoding) =>
288 fs.readFileString(path.replace("/sys/fs/cgroup", root), encoding),
289 }),
290 );
291 expect(state).toMatchObject({ memoryControllerAvailable: false });
292 }).pipe(
293 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true }))),
294 Effect.provideService(
295 ProcessRunner.ProcessRunner,
296 runner(
297 "ControlGroup=/user.slice/user-1000.slice/user@1000.service/app.slice/t3code.service\nMainPID=0\n",
298 ),
299 ),
300 Effect.provide(NodeServices.layer),
301 );
302 },
303);