Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as PlatformError from "effect/PlatformError";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as TestConsole from "effect/testing/TestConsole";
11import { Command } from "effect/cli";
12import { ChildProcessSpawner } from "effect/process";
13
14import packageJson from "../../package.json" with { type: "json" };
15import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts";
16import { browserCommand } from "./browser.ts";
17
18const USERNS_RESTRICTION = "/proc/sys/kernel/apparmor_restrict_unprivileged_userns";
19const BROWSER_ROOT = "/home/me/.t3/tools/chrome-headless-shell";
20const BROWSER = `${BROWSER_ROOT}/linux64/154/chrome-headless-shell`;
21
22const notFound = (method: string, path: string) =>
23 PlatformError.systemError({
24 _tag: "NotFound",
25 module: "FileSystem",
26 method,
27 pathOrDescriptor: path,
28 });
29
30/**
31 * A French-locale Ubuntu host with the browser installed and a system font: either the userns
32 * restriction on, or the restriction off and the browser missing libasound.
33 */
34const runSetupAsRoot = (input: {
35 readonly profile: string | undefined;
36 readonly missingAudioLibrary?: boolean;
37}) => {
38 const environment = { SUDO_USER: "me", LC_ALL: "fr_FR.UTF-8" };
39 const files = new Map([
40 [USERNS_RESTRICTION, input.missingAudioLibrary ? "0\n" : "1\n"],
41 [BROWSER, ""],
42 ["/usr/bin/apt-get", ""],
43 ]);
44 if (input.profile !== undefined) {
45 files.set(PreviewBrowserHost.APPARMOR_PROFILE_PATH, input.profile);
46 }
47 const directories = new Map([
48 [BROWSER_ROOT, ["linux64"]],
49 [`${BROWSER_ROOT}/linux64`, ["154"]],
50 ]);
51 const commands: Array<string> = [];
52 const fileSystem = FileSystem.makeNoop({
53 exists: (path) => Effect.succeed(files.has(path)),
54 readFileString: (path) => {
55 const content = files.get(path);
56 return content === undefined
57 ? Effect.fail(notFound("readFileString", path))
58 : Effect.succeed(content);
59 },
60 readDirectory: (path) => {
61 const entries = directories.get(path);
62 return entries === undefined
63 ? Effect.fail(notFound("readDirectory", path))
64 : Effect.succeed(entries);
65 },
66 writeFileString: (path, content) => Effect.sync(() => void files.set(path, content)),
67 });
68 const spawner = ChildProcessSpawner.make((command) =>
69 Effect.sync(() => {
70 if (command._tag !== "StandardCommand") throw new Error("Expected a standard command");
71 const { command: name, args, options } = command;
72 commands.push([name, ...args].join(" "));
73 let output = "";
74 if (name === "fc-match") output = "/usr/share/fonts/sans.ttf";
75 if (name === BROWSER) {
76 output = input.missingAudioLibrary
77 ? "error while loading shared libraries: libasound.so.2: cannot open shared object file\n"
78 : "Chrome 154\n";
79 }
80 if (name === "apt-cache" && args[1] === "libasound2") {
81 const locale = options.env?.LC_ALL ?? environment.LC_ALL;
82 output = locale === "C" ? "Candidate: 1.2.8-1\n" : "Candidat : 1.2.8-1\n";
83 }
84 return ChildProcessSpawner.makeHandle({
85 pid: ChildProcessSpawner.ProcessId(1),
86 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
87 exitStatus: Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) }),
88 isRunning: Effect.succeed(false),
89 kill: () => Effect.void,
90 unref: Effect.succeed(Effect.void),
91 stdin: Sink.drain,
92 stdout: Stream.make(new TextEncoder().encode(output)),
93 stderr: Stream.empty,
94 all: Stream.make(new TextEncoder().encode(output)),
95 getInputFd: () => Sink.drain,
96 getOutputFd: () => Stream.empty,
97 });
98 }),
99 );
100 return Effect.gen(function* () {
101 yield* Command.runWith(browserCommand, { version: packageJson.version })([
102 "setup",
103 "--base-dir",
104 "/home/me/.t3",
105 ]);
106 return {
107 output: (yield* TestConsole.logLines).join("\n"),
108 profile: files.get(PreviewBrowserHost.APPARMOR_PROFILE_PATH),
109 loads: commands.filter((command) => command.startsWith("apparmor_parser")),
110 audioPackages: commands
111 .find((command) => command.startsWith("apt-get install "))
112 ?.split(" ")
113 .filter((arg) => arg.startsWith("libasound")),
114 };
115 }).pipe(
116 Effect.provideService(HostProcess.Platform, "linux"),
117 Effect.provideService(HostProcess.UserId, 0),
118 Effect.provideService(HostProcess.Environment, environment),
119 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
120 Effect.provideService(FileSystem.FileSystem, fileSystem),
121 Effect.provide(Layer.mergeAll(NodeServices.layer, Layer.fresh(TestConsole.layer))),
122 );
123};
124
125const LOAD = `apparmor_parser -r ${PreviewBrowserHost.APPARMOR_PROFILE_PATH}`;
126
127const CUSTOMIZED_PROFILE = PreviewBrowserHost.APPARMOR_PROFILE.replace(
128 " userns,\n",
129 " userns,\n deny /tmp/t3-admin-private/** rw,\n",
130);
131
132it.effect.each([
133 {
134 label: "reloads a profile that is on disk",
135 profile: PreviewBrowserHost.APPARMOR_PROFILE,
136 written: PreviewBrowserHost.APPARMOR_PROFILE,
137 said: "Reloaded the AppArmor profile",
138 },
139 {
140 label: "writes and loads a missing profile",
141 profile: undefined,
142 written: PreviewBrowserHost.APPARMOR_PROFILE,
143 said: "Wrote and loaded",
144 },
145 {
146 label: "reloads a customized profile without rewriting it",
147 profile: CUSTOMIZED_PROFILE,
148 written: CUSTOMIZED_PROFILE,
149 said: "Reloaded the AppArmor profile",
150 },
151])("t3 browser setup as root $label", (input) =>
152 Effect.gen(function* () {
153 const result = yield* runSetupAsRoot({ profile: input.profile });
154 expect(result.loads).toEqual([LOAD]);
155 expect(result.profile).toBe(input.written);
156 expect(result.output).toContain(input.said);
157 expect(result.output).toContain("This host is ready for T3's browser.");
158 }),
159);
160
161it.effect("selects the available library alias under a French apt locale", () =>
162 Effect.gen(function* () {
163 const result = yield* runSetupAsRoot({ profile: undefined, missingAudioLibrary: true });
164 expect(result.audioPackages).toEqual(["libasound2"]);
165 }),
166);