Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

managedPolicyFile.test.ts

358 lines14.1 KB

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 Schema from "effect/Schema";
6import * as Sink from "effect/Sink";
7import * as Stream from "effect/Stream";
8import { ChildProcessSpawner } from "effect/process";
9​
10import * as HostProcess from "./HostProcess.ts";
11​
12import {
13 MACOS_MANAGED_PREFERENCES_PATH,
14 managedPolicyPath,
15 readManagedPolicy,
16 type RegistryKey,
17 WINDOWS_POLICY_KEY,
18 layerWindowsRegistry,
19 WindowsRegistry,
20 WindowsRegistryError,
21} from "./managedPolicyFile.ts";
22​
23const policy = JSON.stringify({ schemaVersion: 1, organization: "Example Corp" });
24​
25/** What a command prints and exits with. */
26type Result = { readonly stdout: string; readonly exitCode: number };
27​
28/** Keys below the policy key ("" for the key itself), or the error every read fails with. */
29type RegistryAnswer = Readonly<Record<string, RegistryKey>> | WindowsRegistryError;
30const isRegistryError = Schema.is(WindowsRegistryError);
31const POLICY_SUBKEY = WINDOWS_POLICY_KEY.slice("HKLM\\".length);
32​
33/** Files that exist, what a command prints and exits with by command name, and the registry. */
34const machine = (
35 files: Readonly<Record<string, string>>,
36 commands: Readonly<Record<string, Result>>,
37 registry: RegistryAnswer,
38) =>
39 Layer.mergeAll(
40 Layer.succeed(
41 WindowsRegistry,
42 WindowsRegistry.of({
43 readMachineKey: (subkey) =>
44 isRegistryError(registry)
45 ? Effect.fail(registry)
46 : Effect.succeed(registry[subkey.slice(POLICY_SUBKEY.length + 1)]),
47 }),
48 ),
49 FileSystem.layerNoop({
50 exists: (path) => Effect.succeed(path in files),
51 readFileString: (path) => Effect.succeed(files[path] ?? ""),
52 }),
53 Layer.succeed(
54 ChildProcessSpawner.ChildProcessSpawner,
55 ChildProcessSpawner.make((command) => {
56 const { command: name } = command as unknown as { readonly command: string };
57 const result = commands[name] ?? { stdout: "", exitCode: 127 };
58 return Effect.succeed(
59 ChildProcessSpawner.makeHandle({
60 pid: ChildProcessSpawner.ProcessId(1),
61 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
62 exitStatus: Effect.succeed({
63 _tag: "Exited",
64 code: ChildProcessSpawner.ExitCode(result.exitCode),
65 }),
66 isRunning: Effect.succeed(false),
67 kill: () => Effect.void,
68 unref: Effect.succeed(Effect.void),
69 stdin: Sink.drain,
70 stdout: Stream.make(new TextEncoder().encode(result.stdout)),
71 stderr: Stream.empty,
72 all: Stream.empty,
73 getInputFd: () => Sink.drain,
74 getOutputFd: () => Stream.empty,
75 }),
76 );
77 }),
78 ),
79 );
80​
81/** A policy key holding `values`, with checkbox subkeys of `name=0|1` entries. */
82const policyKey = (
83 values: RegistryKey["values"],
84 subkeys: Readonly<Record<string, Readonly<Record<string, number>>>> = {},
85): Readonly<Record<string, RegistryKey>> => ({
86 "": { values, subkeys: Object.keys(subkeys) },
87 ...Object.fromEntries(
88 Object.entries(subkeys).map(([name, boxes]) => [
89 name,
90 {
91 values: Object.entries(boxes).map(([box, data]) => ({
92 name: box,
93 type: "REG_DWORD" as const,
94 data,
95 })),
96 subkeys: [],
97 },
98 ]),
99 ),
100});
101const text = (name: string, data: string) => ({ name, type: "REG_SZ" as const, data });
102const dword = (name: string, data: number) => ({ name, type: "REG_DWORD" as const, data });
103​
104const read = (
105 platform: NodeJS.Platform,
106 files: Readonly<Record<string, string>>,
107 commands: Parameters<typeof machine>[1] = {},
108 registry: RegistryAnswer = {},
109) =>
110 readManagedPolicy(platform).pipe(
111 Effect.map((found) => found?.source),
112 Effect.catchTags({
113 ManagedPolicyFileError: (error) => Effect.succeed(`error: ${error.reason}`),
114 }),
115 Effect.provide(machine(files, commands, registry)),
116 );
117​
118describe("readManagedPolicy", () => {
119 it.effect("reads a macOS configuration profile, and refuses one beside a policy file", () =>
120 Effect.gen(function* () {
121 const plutil = { "/usr/bin/plutil": { stdout: policy, exitCode: 0 } };
122 const profile = { [MACOS_MANAGED_PREFERENCES_PATH]: "<binary plist>" };
123 const file = { [managedPolicyPath("darwin")]: policy };
124​
125 assert.equal(yield* read("darwin", profile, plutil), MACOS_MANAGED_PREFERENCES_PATH);
126 const plist = (contents: object) => ({
127 "/usr/bin/plutil": { stdout: JSON.stringify(contents), exitCode: 0 },
128 });
129 const settings = JSON.parse(policy);
130 // What macOS 27 writes for a manually installed profile.
131 assert.equal(
132 yield* read(
133 "darwin",
134 profile,
135 plist({ ...settings, PayloadUUID: "e8c7f49b", _manualProfile: true }),
136 ),
137 MACOS_MANAGED_PREFERENCES_PATH,
138 );
139 assert.equal(
140 yield* read("darwin", profile, plist({ Forced: [{ mcx_preference_settings: settings }] })),
141 MACOS_MANAGED_PREFERENCES_PATH,
142 );
143 // Keys beside the wrapper, or a second entry, are refused rather than dropped or merged.
144 for (const ambiguous of [
145 { Forced: [{ mcx_preference_settings: settings }], limits: { telemetry: false } },
146 { Forced: [{ mcx_preference_settings: settings }, { mcx_preference_settings: settings }] },
147 ]) {
148 assert.include(
149 yield* read("darwin", profile, plist(ambiguous)),
150 "does not match the policy schema",
151 );
152 }
153 assert.equal(yield* read("darwin", file), managedPolicyPath("darwin"));
154 const typo = JSON.stringify({ ...settings, limits: { maxRuntimeMod: "auto" } });
155 assert.include(
156 yield* read("darwin", { [managedPolicyPath("darwin")]: typo }),
157 '["limits"]["maxRuntimeMod"]',
158 );
159 assert.isUndefined(yield* read("darwin", {}));
160 assert.include(
161 yield* read("darwin", { ...profile, ...file }, plutil),
162 "deploy the policy one way",
163 );
164 // A profile plutil cannot convert fails closed rather than reading as no policy.
165 assert.include(
166 yield* read("darwin", profile, { "/usr/bin/plutil": { stdout: "", exitCode: 1 } }),
167 "cannot be read",
168 );
169 }),
170 );
171​
172 it.effect(
173 "reads a Policy value of JSON from the registry, and treats only an absent key as none",
174 () =>
175 Effect.gen(function* () {
176 const file = { [managedPolicyPath("win32")]: policy };
177 const win32 = (files: Readonly<Record<string, string>>, registry: RegistryAnswer) =>
178 read("win32", files, {}, registry);
179 const json = policyKey([text("Policy", policy)]);
180​
181 assert.equal(yield* win32({}, json), WINDOWS_POLICY_KEY);
182 assert.isUndefined(yield* win32({}, {}));
183 assert.equal(yield* win32(file, {}), managedPolicyPath("win32"));
184 assert.include(yield* win32(file, json), "deploy the policy one way");
185 // A read that fails, here access denied, is not read as no policy, file or not.
186 for (const files of [{}, file]) {
187 assert.include(
188 yield* win32(files, new WindowsRegistryError({ code: 5 })),
189 "the registry cannot be read (Windows error 5)",
190 );
191 }
192 assert.include(
193 yield* win32({}, new WindowsRegistryError({})),
194 "cannot load its registry reader; reinstall T3 Code",
195 );
196 assert.include(
197 yield* win32({}, policyKey([{ name: "Policy", type: "other" }])),
198 "its Policy value is not a string (REG_SZ)",
199 );
200 assert.include(
201 yield* win32({}, policyKey([text("Policy", "{ not json")])),
202 "does not match the policy schema",
203 );
204 for (const both of [
205 policyKey([text("Policy", policy), text("Organization", "Example")]),
206 policyKey([text("Policy", policy)], { Clients: { desktop: 1 } }),
207 ]) {
208 assert.include(yield* win32({}, both), "both a Policy value and Group Policy settings");
209 }
210 // Not Configured clears a list policy's values but can leave its empty subkey behind.
211 assert.equal(
212 yield* win32({}, policyKey([text("Policy", policy)], { Clients: {} })),
213 WINDOWS_POLICY_KEY,
214 );
215 }),
216 );
217​
218 it.effect("builds the policy from the values the Group Policy template writes", () =>
219 Effect.gen(function* () {
220 const organization = text("Organization", "Société 日本 ✓");
221 const document = (registry: RegistryAnswer) =>
222 readManagedPolicy("win32", ["codex", "claudeAgent"]).pipe(
223 Effect.map((found): unknown => found?.document),
224 Effect.catchTags({
225 ManagedPolicyFileError: (error) => Effect.succeed(`error: ${error.reason}`),
226 }),
227 Effect.provide(machine({}, {}, registry)),
228 );
229​
230 assert.deepStrictEqual(
231 yield* document(
232 policyKey(
233 [
234 organization,
235 text("SupportUrl", ""),
236 // Registry names ignore case.
237 text("maxRuntimeMode", "auto-accept-edits"),
238 dword("Telemetry", 0),
239 text("Settings", '{"enableAgentBrowserAccess": {"value": false, "locked": true}}'),
240 text("UpdatesMode", "off"),
241 dword("AllowNightly", 1),
242 dword("Updates", 1),
243 dword("Clients", 1),
244 dword("AllowedDrivers", 1),
245 ],
246 // Registry names ignore case, so a subkey written in other case still counts.
247 {
248 clients: { Desktop: 1, "LOCAL-BROWSER": 1, REMOTE: 1 },
249 AllowedDrivers: { Codex: 1, CLAUDEAGENT: 1, UnknownDriver: 1 },
250 },
251 ),
252 ),
253 {
254 schemaVersion: 1,
255 organization: "Société 日本 ✓",
256 settings: { enableAgentBrowserAccess: { value: false, locked: true } },
257 limits: {
258 maxRuntimeMode: "auto-accept-edits",
259 telemetry: false,
260 updates: { mode: "off", allowNightly: true },
261 clients: ["desktop", "local-browser", "remote"],
262 providers: { allowedDrivers: ["codex", "claudeAgent", "UnknownDriver"] },
263 },
264 },
265 );
266​
267 // Disabling a policy leaves each checkbox's falseValue behind; it restricts nothing.
268 const disabledGroups = {
269 Clients: { desktop: 0, "local-browser": 0, remote: 0 },
270 AllowedDrivers: { codex: 0, claudeAgent: 0 },
271 };
272 assert.deepStrictEqual(
273 yield* document(
274 policyKey(
275 [
276 organization,
277 dword("Clients", 0),
278 dword("AllowedDrivers", 0),
279 dword("Updates", 0),
280 dword("AllowNightly", 0),
281 dword("Telemetry", 0),
282 ],
283 disabledGroups,
284 ),
285 ),
286 { schemaVersion: 1, organization: "Société 日本 ✓", limits: { telemetry: false } },
287 );
288 // With nothing else configured, that is no policy rather than one missing Organization.
289 assert.isUndefined(
290 yield* document(
291 policyKey([dword("AllowedDrivers", 0)], {
292 AllowedDrivers: disabledGroups.AllowedDrivers,
293 }),
294 ),
295 );
296 assert.isUndefined(yield* document(policyKey([])));
297​
298 // Anything the template does not write fails closed rather than being ignored.
299 for (const [registry, reason] of [
300 [policyKey([organization, dword("Telemetry", 2)]), "DWORD of 0 or 1"],
301 [policyKey([organization, text("MaxMode", "auto")]), "not a T3 Code policy value"],
302 [policyKey([organization], { Other: { x: 1 } }), "Other is not a T3 Code policy key"],
303 [
304 {
305 ...policyKey([organization, dword("Clients", 1)], { Clients: { desktop: 1 } }),
306 Clients: { values: [dword("desktop", 1)], subkeys: ["Nested"] },
307 },
308 "Clients\\Nested is not a T3 Code policy key",
309 ],
310 [policyKey([organization, text("Settings", "{")]), "not valid JSON"],
311 [policyKey([organization, dword("Clients", 2)]), "DWORD of 0 or 1"],
312 [
313 policyKey([organization, dword("Clients", 1)], { Clients: { UnknownClient: 1 } }),
314 "does not match the policy schema",
315 ],
316 [
317 policyKey([organization, dword("Clients", 1)], { Clients: { desktop: 0 } }),
318 "does not match the policy schema",
319 ],
320 [policyKey([dword("Organization", 1)]), "Organization must be a string"],
321 // REG_EXPAND_SZ would fill in the reading user's variables.
322 [policyKey([{ name: "Organization", type: "other" }]), "Organization must be a string"],
323 [
324 policyKey([text("MaxRuntimeMode", "auto-accept-edits")]),
325 "set the Organization policy whenever another T3 Code policy is set",
326 ],
327 ] as const) {
328 assert.include(yield* document(registry), reason);
329 }
330 }),
331 );
332​
333 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
334 "lists registry values and subkeys through the Win32 API",
335 () =>
336 Effect.gen(function* () {
337 const registry = yield* WindowsRegistry;
338 const version = yield* registry.readMachineKey(
339 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
340 );
341 const value = (name: string) => version?.values.find((entry) => entry.name === name);
342 const product = value("ProductName");
343 assert.match(product?.type === "REG_SZ" ? product.data : "", /Windows/);
344 assert.equal(value("CurrentMajorVersionNumber")?.type, "REG_DWORD");
345 assert.isUndefined(yield* registry.readMachineKey("SOFTWARE\\T3CodeNoSuchKey"));
346 const windows = yield* registry.readMachineKey(
347 "SOFTWARE\\Microsoft\\Windows\\CurrentVersion",
348 );
349 // REG_EXPAND_SZ, which would otherwise expand the user's variables.
350 assert.equal(
351 windows?.values.find((entry) => entry.name === "ProgramFilesPath")?.type,
352 "other",
353 );
354 const parent = yield* registry.readMachineKey("SOFTWARE\\Microsoft\\Windows NT");
355 assert.isTrue(parent?.subkeys.includes("CurrentVersion"));
356 }).pipe(Effect.provide(layerWindowsRegistry(() => import("ffi-rs")))),
357 );
358});