The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics nodeBuiltinImport:off |
| 2 | import * as NodeChildProcess from "node:child_process"; |
| 3 | import * as NodeFS from "node:fs"; |
| 4 | import * as NodeOS from "node:os"; |
| 5 | import * as NodePath from "node:path"; |
| 6 | |
| 7 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 8 | import { describe, expect, it } from "@effect/vitest"; |
| 9 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as FileSystem from "effect/FileSystem"; |
| 12 | import * as Sink from "effect/Sink"; |
| 13 | import * as Stream from "effect/Stream"; |
| 14 | import type * as ChildProcess from "effect/process/ChildProcess"; |
| 15 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 16 | |
| 17 | import * as ProcessRunner from "../processRunner.ts"; |
| 18 | import * as ServiceProtection from "./serviceProtection.ts"; |
| 19 | |
| 20 | const temporaryDirectory = () => |
| 21 | NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-service-protection-")); |
| 22 | |
| 23 | describe.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 | |
| 111 | it.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 | |
| 126 | const 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 | |
| 149 | const 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 | |
| 164 | it.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 | |
| 229 | it.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 | }); |
| 271 | |
| 272 | it.effect( |
| 273 | "tells a kernel without the memory controller apart from a cgroup that grants none", |
| 274 | () => { |
| 275 | const root = temporaryDirectory(); |
| 276 | NodeFS.mkdirSync(NodePath.join(root, "user.slice"), { recursive: true }); |
| 277 | NodeFS.writeFileSync(NodePath.join(root, "cgroup.controllers"), "cpuset cpu io pids\n"); |
| 278 | return Effect.gen(function* () { |
| 279 | const fs = yield* FileSystem.FileSystem; |
| 280 | const state = yield* ServiceProtection.readProtection("/home/theo/.config/systemd/user").pipe( |
| 281 | Effect.provideService(FileSystem.FileSystem, { |
| 282 | ...fs, |
| 283 | readFileString: (path, encoding) => |
| 284 | fs.readFileString(path.replace("/sys/fs/cgroup", root), encoding), |
| 285 | }), |
| 286 | ); |
| 287 | expect(state).toMatchObject({ memoryControllerAvailable: false }); |
| 288 | }).pipe( |
| 289 | Effect.ensuring(Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true }))), |
| 290 | Effect.provideService( |
| 291 | ProcessRunner.ProcessRunner, |
| 292 | runner( |
| 293 | "ControlGroup=/user.slice/user-1000.slice/user@1000.service/app.slice/t3code.service\nMainPID=0\n", |
| 294 | ), |
| 295 | ), |
| 296 | Effect.provide(NodeServices.layer), |
| 297 | ); |
| 298 | }, |
| 299 | ); |