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