Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Sink from "effect/Sink";
6import * as Stream from "effect/Stream";
7import { ChildProcessSpawner } from "effect/process";
8
9import * as HostProcess from "./HostProcess.ts";
10
11import {
12 MACOS_MANAGED_PREFERENCES_PATH,
13 managedPolicyPath,
14 readManagedPolicy,
15 WINDOWS_POLICY_KEY,
16 layerWindowsRegistry,
17 WindowsRegistry,
18 WindowsRegistryError,
19} from "./managedPolicyFile.ts";
20
21const policy = JSON.stringify({ schemaVersion: 1, organization: "Example Corp" });
22
23/** What a command prints and exits with. */
24type Result = { readonly stdout: string; readonly exitCode: number };
25
26/** The registry's `Policy` value: its text, absent, or the Win32 error reading it fails with. */
27type RegistryAnswer = string | undefined | { readonly code?: number };
28
29/** Files that exist, what a command prints and exits with by command name, and the registry. */
30const machine = (
31 files: Readonly<Record<string, string>>,
32 commands: Readonly<Record<string, Result>>,
33 registry: RegistryAnswer,
34) =>
35 Layer.mergeAll(
36 Layer.succeed(
37 WindowsRegistry,
38 WindowsRegistry.of({
39 readMachineString: () =>
40 typeof registry === "object"
41 ? Effect.fail(new WindowsRegistryError(registry))
42 : Effect.succeed(registry),
43 }),
44 ),
45 FileSystem.layerNoop({
46 exists: (path) => Effect.succeed(path in files),
47 readFileString: (path) => Effect.succeed(files[path] ?? ""),
48 }),
49 Layer.succeed(
50 ChildProcessSpawner.ChildProcessSpawner,
51 ChildProcessSpawner.make((command) => {
52 const { command: name } = command as unknown as { readonly command: string };
53 const result = commands[name] ?? { stdout: "", exitCode: 127 };
54 return Effect.succeed(
55 ChildProcessSpawner.makeHandle({
56 pid: ChildProcessSpawner.ProcessId(1),
57 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
58 isRunning: Effect.succeed(false),
59 kill: () => Effect.void,
60 unref: Effect.succeed(Effect.void),
61 stdin: Sink.drain,
62 stdout: Stream.make(new TextEncoder().encode(result.stdout)),
63 stderr: Stream.empty,
64 all: Stream.empty,
65 getInputFd: () => Sink.drain,
66 getOutputFd: () => Stream.empty,
67 }),
68 );
69 }),
70 ),
71 );
72
73const read = (
74 platform: NodeJS.Platform,
75 files: Readonly<Record<string, string>>,
76 commands: Parameters<typeof machine>[1] = {},
77 registry: RegistryAnswer = undefined,
78) =>
79 readManagedPolicy(platform).pipe(
80 Effect.map((found) => found?.source),
81 Effect.catchTags({
82 ManagedPolicyFileError: (error) => Effect.succeed(`error: ${error.reason}`),
83 }),
84 Effect.provide(machine(files, commands, registry)),
85 );
86
87describe("readManagedPolicy", () => {
88 it.effect("reads a macOS configuration profile, and refuses one beside a policy file", () =>
89 Effect.gen(function* () {
90 const plutil = { "/usr/bin/plutil": { stdout: policy, exitCode: 0 } };
91 const profile = { [MACOS_MANAGED_PREFERENCES_PATH]: "<binary plist>" };
92 const file = { [managedPolicyPath("darwin")]: policy };
93
94 assert.equal(yield* read("darwin", profile, plutil), MACOS_MANAGED_PREFERENCES_PATH);
95 const plist = (contents: object) => ({
96 "/usr/bin/plutil": { stdout: JSON.stringify(contents), exitCode: 0 },
97 });
98 const settings = JSON.parse(policy);
99 // What macOS 27 writes for a manually installed profile.
100 assert.equal(
101 yield* read(
102 "darwin",
103 profile,
104 plist({ ...settings, PayloadUUID: "e8c7f49b", _manualProfile: true }),
105 ),
106 MACOS_MANAGED_PREFERENCES_PATH,
107 );
108 assert.equal(
109 yield* read("darwin", profile, plist({ Forced: [{ mcx_preference_settings: settings }] })),
110 MACOS_MANAGED_PREFERENCES_PATH,
111 );
112 // Keys beside the wrapper, or a second entry, are refused rather than dropped or merged.
113 for (const ambiguous of [
114 { Forced: [{ mcx_preference_settings: settings }], limits: { telemetry: false } },
115 { Forced: [{ mcx_preference_settings: settings }, { mcx_preference_settings: settings }] },
116 ]) {
117 assert.include(
118 yield* read("darwin", profile, plist(ambiguous)),
119 "does not match the policy schema",
120 );
121 }
122 assert.equal(yield* read("darwin", file), managedPolicyPath("darwin"));
123 const typo = JSON.stringify({ ...settings, limits: { maxRuntimeMod: "auto" } });
124 assert.include(
125 yield* read("darwin", { [managedPolicyPath("darwin")]: typo }),
126 '["limits"]["maxRuntimeMod"]',
127 );
128 assert.isUndefined(yield* read("darwin", {}));
129 assert.include(
130 yield* read("darwin", { ...profile, ...file }, plutil),
131 "deploy the policy one way",
132 );
133 // A profile plutil cannot convert fails closed rather than reading as no policy.
134 assert.include(
135 yield* read("darwin", profile, { "/usr/bin/plutil": { stdout: "", exitCode: 1 } }),
136 "cannot be read",
137 );
138 }),
139 );
140
141 it.effect(
142 "reads the Windows Policies registry value, and treats only an absent one as none",
143 () =>
144 Effect.gen(function* () {
145 const file = { [managedPolicyPath("win32")]: policy };
146 const win32 = (files: Readonly<Record<string, string>>, registry: RegistryAnswer) =>
147 read("win32", files, {}, registry);
148
149 assert.equal(yield* win32({}, policy), WINDOWS_POLICY_KEY);
150 assert.isUndefined(yield* win32({}, undefined));
151 assert.equal(yield* win32(file, undefined), managedPolicyPath("win32"));
152 assert.include(yield* win32(file, policy), "deploy the policy one way");
153 // A read that fails, here access denied, is not read as no policy, file or not.
154 for (const files of [{}, file]) {
155 assert.include(
156 yield* win32(files, { code: 5 }),
157 "the registry cannot be read (Windows error 5)",
158 );
159 }
160 assert.include(yield* win32({}, {}), "cannot load its registry reader; reinstall T3 Code");
161 assert.include(
162 yield* win32({}, { code: 1630 }),
163 "its Policy value is not a string (REG_SZ)",
164 );
165 assert.include(yield* win32({}, "{ not json"), "does not match the policy schema");
166 }),
167 );
168
169 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
170 "reads REG_SZ values through the Win32 API, and refuses other types",
171 () =>
172 Effect.gen(function* () {
173 const registry = yield* WindowsRegistry;
174 const version = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
175 assert.match((yield* registry.readMachineString(version, "ProductName")) ?? "", /Windows/);
176 assert.isUndefined(yield* registry.readMachineString(version, "T3CodeNoSuchValue"));
177 assert.isUndefined(
178 yield* registry.readMachineString("SOFTWARE\\T3CodeNoSuchKey", "Policy"),
179 );
180 // REG_DWORD, and REG_EXPAND_SZ, which would otherwise expand the user's variables.
181 for (const [key, value] of [
182 [version, "CurrentMajorVersionNumber"],
183 ["SOFTWARE\\Microsoft\\Windows\\CurrentVersion", "ProgramFilesPath"],
184 ] as const) {
185 const error = yield* registry.readMachineString(key, value).pipe(Effect.flip);
186 assert.equal(error.code, 1630);
187 }
188 }).pipe(Effect.provide(layerWindowsRegistry(() => import("ffi-rs")))),
189 );
190});