Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6
7import {
8 DEFAULT_SERVER_SETTINGS,
9 ProviderDriverKind,
10 ProviderInstanceId,
11} from "@t3tools/contracts";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13
14import { BUILT_IN_DRIVERS } from "../provider/builtInDrivers.ts";
15import * as ManagedPolicy from "./ManagedPolicy.ts";
16import { disallowedDriverReason, providerHostEnvironment } from "./managedProviders.ts";
17import * as ManagedSettings from "./managedSettings.ts";
18
19it.layer(NodeServices.layer)("ManagedPolicy.load", (it) => {
20 const loadFrom = (contents: string | undefined) =>
21 Effect.gen(function* () {
22 const fs = yield* FileSystem.FileSystem;
23 const path = yield* Path.Path;
24 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-managed-policy-" });
25 const file = path.join(dir, "policy.json");
26 if (contents !== undefined) yield* fs.writeFileString(file, contents);
27 return yield* ManagedPolicy.load(file);
28 }).pipe(Effect.scoped);
29
30 it.effect("means no policy when the file is missing", () =>
31 Effect.gen(function* () {
32 const policy = yield* loadFrom(undefined);
33 assert.isUndefined(policy.summary);
34 }),
35 );
36
37 it.effect("summarizes locked settings for clients", () =>
38 Effect.gen(function* () {
39 const policy = yield* loadFrom(
40 JSON.stringify({
41 schemaVersion: 1,
42 organization: "Example Corp",
43 supportUrl: "https://it.example/t3",
44 settings: {
45 "storageCleanup.logsAfterDays": { value: 30, locked: true },
46 defaultRuntimeMode: { value: "approval-required", locked: false },
47 },
48 }),
49 );
50 assert.deepEqual(policy.summary, {
51 organization: "Example Corp",
52 supportUrl: "https://it.example/t3",
53 lockedSettings: ["storageCleanup.logsAfterDays"],
54 });
55 }),
56 );
57
58 it("lists only settings a policy can manage", () => {
59 const listed = ManagedSettings.listManageableSettings();
60 const paths = listed.map(([path]) => path);
61 assert.include(paths, "storageCleanup.logsAfterDays");
62 assert.include(paths, "backgroundActivity.baseProfile");
63 assert.include(paths, "backgroundActivity.overrides.pauseWhenOnBattery");
64 assert.notInclude(paths, "backgroundActivity.overrides");
65 assert.notInclude(paths, "projectSettingsOverrides");
66 assert.notInclude(paths, "compactIdleThreads");
67 assert.notOk(paths.some((path) => path.startsWith("observability")));
68 for (const [path, value] of listed) {
69 if (value === undefined) continue;
70 const managed = ManagedSettings.makeManagedSettings({ [path]: { value, locked: false } });
71 assert.equal(managed._tag, "Valid", path);
72 }
73 });
74
75 it.effect("tells clients which capabilities the policy switches off", () =>
76 Effect.gen(function* () {
77 const policy = yield* loadFrom(
78 JSON.stringify({
79 schemaVersion: 1,
80 organization: "Example Corp",
81 limits: { webhookTasks: false, telemetry: true, previewTunnel: false },
82 }),
83 );
84 assert.deepEqual(policy.summary?.limits, {
85 webhookTasks: false,
86 telemetry: true,
87 previewTunnel: false,
88 });
89 assert.equal(ManagedPolicy.deniedBy(policy, "webhookTasks"), "Example Corp");
90 assert.equal(ManagedPolicy.deniedBy(policy, "previewTunnel"), "Example Corp");
91 assert.isUndefined(ManagedPolicy.deniedBy(policy, "telemetry"));
92 }),
93 );
94
95 it.effect("refuses files it cannot fully enforce", () =>
96 Effect.gen(function* () {
97 const base = { schemaVersion: 1, organization: "Example Corp" };
98 const reasons = yield* Effect.forEach(
99 [
100 "{ not json",
101 // An unknown key may be a restriction from a newer release.
102 JSON.stringify({ ...base, limits: { connect: false, futureLimit: true } }),
103 JSON.stringify({ ...base, settings: { notASetting: { value: 1, locked: true } } }),
104 JSON.stringify({
105 ...base,
106 settings: { "storageCleanup.logsAfterDayz": { value: 30, locked: true } },
107 }),
108 JSON.stringify({
109 ...base,
110 settings: { defaultRuntimeMode: { value: "yolo", locked: true } },
111 }),
112 JSON.stringify({
113 ...base,
114 settings: { projectSettingsOverrides: { value: {}, locked: true } },
115 }),
116 // The user could never remove a provider instance a default keeps adding back.
117 JSON.stringify({
118 ...base,
119 settings: {
120 "providerInstances.codex_work": {
121 value: { driver: "codex", enabled: true },
122 locked: false,
123 },
124 },
125 }),
126 JSON.stringify({
127 ...base,
128 settings: {
129 providerInstances: { value: { codex_work: { driver: "codex" } }, locked: false },
130 },
131 }),
132 // A user's stored null would leave the lock building half a model selection.
133 JSON.stringify({
134 ...base,
135 settings: { "defaultModelSelection.model": { value: "gpt-5.4", locked: true } },
136 }),
137 // The server derives it from idleCompaction on every write.
138 JSON.stringify({
139 ...base,
140 settings: { compactIdleThreads: { value: false, locked: true } },
141 }),
142 // It would look locked while worktreeCleanup, which overrides it, stays the user's.
143 JSON.stringify({
144 ...base,
145 settings: { "storageCleanup.worktreeAfterDays": { value: 7, locked: true } },
146 }),
147 // An instance's own variables, home paths, and setup mode would override the lock.
148 JSON.stringify({
149 ...base,
150 settings: {
151 "providerInstances.codex.driver": { value: "codex", locked: true },
152 "providerInstances.codex.config.launchArgs": {
153 value: "-c model_provider=corp",
154 locked: true,
155 },
156 },
157 }),
158 // The server would move it into the user's secret store, past the policy's removal.
159 JSON.stringify({
160 ...base,
161 settings: {
162 providerInstances: {
163 value: { gemini: { driver: "antigravity", config: { apiKey: "corp-key" } } },
164 locked: true,
165 },
166 },
167 }),
168 // Startup reads OTLP endpoints before the policy, and environment variables outrank them.
169 JSON.stringify({
170 ...base,
171 settings: { "observability.otlpTracesUrl": { value: "", locked: true } },
172 }),
173 ],
174 (contents) =>
175 loadFrom(contents).pipe(
176 Effect.flip,
177 Effect.map((error) => error.reason),
178 ),
179 );
180 assert.lengthOf(reasons, 14);
181 assert.include(reasons[3], "storageCleanup.logsAfterDayz");
182 assert.include(reasons[6], "adds entries users could not remove");
183 assert.include(reasons[7], "adds entries users could not remove");
184 assert.include(reasons[8], 'manage "defaultModelSelection" as a whole');
185 assert.include(reasons[9], 'manage "idleCompaction" instead');
186 assert.include(reasons[10], 'lock "worktreeCleanup" too');
187 assert.include(reasons[11], 'lock "providerInstances.codex" as a whole');
188 assert.include(reasons[12], "holds a credential");
189 assert.include(reasons[13], "a policy cannot override");
190 }),
191 );
192
193 it.effect("tells clients the runtime mode ceiling", () =>
194 Effect.gen(function* () {
195 const policy = yield* loadFrom(
196 JSON.stringify({
197 schemaVersion: 1,
198 organization: "Example Corp",
199 settings: { defaultRuntimeMode: { value: "approval-required", locked: true } },
200 limits: { maxRuntimeMode: "auto-accept-edits" },
201 }),
202 );
203 const { providers, ...limits } = policy.summary?.limits ?? {};
204 assert.deepEqual(limits, { maxRuntimeMode: "auto-accept-edits" });
205 // Under a ceiling, each driver's launch configuration is the administrator's.
206 assert.deepEqual(providers?.lockedInstanceFields?.[ProviderDriverKind.make("claudeAgent")], [
207 "config.binaryPath",
208 "config.launchArgs",
209 "config.homePath",
210 "environment",
211 ]);
212 assert.deepEqual(providers?.lockedInstanceFields?.[ProviderDriverKind.make("acpRegistry")], [
213 "config.commandPath",
214 "config.commandArgs",
215 "environment",
216 ]);
217 // The host variable that replaces Codex's launch arguments is ignored too.
218 const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "-c mcp_servers.x.command=sh" };
219 const managedHost = providerHostEnvironment(policy.summary, host);
220 assert.deepEqual(managedHost, { PATH: "/usr/bin" });
221 // A PATH refresh after launch reaches drivers that hold the managed copy.
222 host.PATH = "/opt/new/bin:/usr/bin";
223 assert.strictEqual(managedHost.PATH, "/opt/new/bin:/usr/bin");
224 assert.strictEqual(providerHostEnvironment(undefined, host), host);
225 }),
226 );
227
228 it.effect(
229 "locks a variable in every spelling on Windows only, and drops a Codex launch override",
230 () =>
231 Effect.gen(function* () {
232 const codex = ProviderDriverKind.make("codex");
233 const variable = (name: string, value: string) => ({ name, value, sensitive: false });
234 const settings = {
235 ...DEFAULT_SERVER_SETTINGS,
236 providerInstances: {
237 codex: {
238 driver: codex,
239 environment: [
240 variable("HTTPS_PROXY", "http://mine"),
241 variable("T3CODE_CODEX_LAUNCH_ARGS", "--dangerously-bypass-approvals-and-sandbox"),
242 ],
243 },
244 },
245 };
246 const policyOn = (platform: NodeJS.Platform) =>
247 ManagedPolicy.fromDocument("/test/policy.json", {
248 schemaVersion: 1,
249 organization: "Example Corp",
250 limits: {
251 providers: {
252 instances: {
253 [codex]: {
254 locked: true,
255 launchArgs: "--strict-config",
256 environment: [{ name: "Https_Proxy", value: "http://gateway" }],
257 },
258 },
259 },
260 },
261 }).pipe(Effect.provideService(HostProcess.Platform, platform));
262 const environmentOn = (platform: NodeJS.Platform) =>
263 Effect.map(
264 policyOn(platform),
265 (policy) =>
266 policy.providers.applyLimits(settings).providerInstances[
267 ProviderInstanceId.make("codex")
268 ]?.environment,
269 );
270 assert.deepEqual(yield* environmentOn("win32"), [
271 variable("Https_Proxy", "http://gateway"),
272 ]);
273 assert.deepEqual(yield* environmentOn("linux"), [
274 variable("HTTPS_PROXY", "http://mine"),
275 variable("Https_Proxy", "http://gateway"),
276 ]);
277 // Saving what the client was shown keeps the override it never saw.
278 const linux = yield* policyOn("linux");
279 const shown = linux.providers.applyLimits(settings);
280 const codexId = ProviderInstanceId.make("codex");
281 const saved = linux.providers.vetWrite(settings, {
282 ...shown,
283 providerInstances: {
284 ...shown.providerInstances,
285 [codexId]: { ...shown.providerInstances[codexId]!, displayName: "Codex (work)" },
286 },
287 });
288 assert.equal(saved._tag, "Allowed");
289 const savedEnvironment =
290 saved._tag === "Allowed"
291 ? (saved.settings.providerInstances[codexId]?.environment ?? [])
292 : [];
293 assert.isTrue(savedEnvironment.some((entry) => entry.name === "T3CODE_CODEX_LAUNCH_ARGS"));
294 // A home path setting would rewrite a locked home variable at launch, so the lock owns it.
295 const claude = ProviderDriverKind.make("claudeAgent");
296 const homeLocked = yield* ManagedPolicy.fromDocument("/test/policy.json", {
297 schemaVersion: 1,
298 organization: "Example Corp",
299 limits: {
300 providers: {
301 instances: {
302 [claude]: {
303 locked: true,
304 environment: [{ name: "CLAUDE_CONFIG_DIR", value: "/opt/claude-home" }],
305 },
306 },
307 },
308 },
309 });
310 const claudeId = ProviderInstanceId.make("claudeAgent");
311 const claudeConfig = homeLocked.providers.applyLimits({
312 ...DEFAULT_SERVER_SETTINGS,
313 providerInstances: {
314 [claudeId]: { driver: claude, config: { homePath: "/home/me/.other-claude" } },
315 },
316 }).providerInstances[claudeId]?.config;
317 assert.deepEqual(claudeConfig, {});
318 assert.include(
319 homeLocked.summary?.limits?.providers?.lockedInstanceFields?.[claude] ?? [],
320 "config.homePath",
321 );
322 // Codex has a second home setting, which a locked CODEX_HOME owns too.
323 const codexHome = yield* ManagedPolicy.fromDocument("/test/policy.json", {
324 schemaVersion: 1,
325 organization: "Example Corp",
326 limits: {
327 providers: {
328 instances: {
329 [codex]: {
330 locked: true,
331 environment: [{ name: "CODEX_HOME", value: "/opt/codex-home" }],
332 },
333 },
334 },
335 },
336 });
337 assert.includeMembers(
338 [...(codexHome.summary?.limits?.providers?.lockedInstanceFields?.[codex] ?? [])],
339 ["config.homePath", "config.shadowHomePath"],
340 );
341 // A server URL makes OpenCode skip the local launch a pin sets, so the pin owns it too.
342 const opencode = ProviderDriverKind.make("opencode");
343 const opencodePinned = yield* ManagedPolicy.fromDocument("/test/policy.json", {
344 schemaVersion: 1,
345 organization: "Example Corp",
346 limits: {
347 providers: { instances: { [opencode]: { locked: true, binaryPath: "/opt/opencode" } } },
348 },
349 });
350 assert.include(
351 opencodePinned.summary?.limits?.providers?.lockedInstanceFields?.[opencode] ?? [],
352 "config.serverUrl",
353 );
354 // The same override from the environment that starts the server is ignored too.
355 const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "--yolo" };
356 assert.deepEqual(providerHostEnvironment((yield* policyOn("linux")).summary, host), {
357 PATH: "/usr/bin",
358 });
359 }),
360 );
361
362 it.effect("refuses a default runtime mode above its own ceiling", () =>
363 Effect.gen(function* () {
364 const reasons = yield* Effect.forEach([false, true], (locked) =>
365 loadFrom(
366 JSON.stringify({
367 schemaVersion: 1,
368 organization: "Example Corp",
369 settings: { defaultRuntimeMode: { value: "auto", locked } },
370 limits: { maxRuntimeMode: "auto-accept-edits" },
371 }),
372 ).pipe(
373 Effect.flip,
374 Effect.map((error) => error.reason),
375 ),
376 );
377 assert.deepEqual(reasons, [
378 '"defaultRuntimeMode" is above "limits.maxRuntimeMode"',
379 '"defaultRuntimeMode" is above "limits.maxRuntimeMode"',
380 ]);
381 }),
382 );
383
384 it.effect("tells clients which drivers run and which instance fields are locked", () =>
385 Effect.gen(function* () {
386 // A provider the policy cannot name would also escape its launch-setting rules.
387 const everyDriver = BUILT_IN_DRIVERS.map((driver) => driver.driverKind);
388 const allowingAll = yield* loadFrom(
389 JSON.stringify({
390 schemaVersion: 1,
391 organization: "Example Corp",
392 limits: { providers: { allowedDrivers: everyDriver } },
393 }),
394 );
395 assert.deepEqual<unknown>(
396 allowingAll.summary?.limits?.providers?.allowedDrivers,
397 everyDriver,
398 );
399
400 const policy = yield* loadFrom(
401 JSON.stringify({
402 schemaVersion: 1,
403 organization: "Example Corp",
404 limits: {
405 providers: {
406 allowedDrivers: ["claudeAgent", "codex"],
407 instances: {
408 claudeAgent: {
409 locked: true,
410 environment: [{ name: "CLAUDE_CODE_USE_BEDROCK", value: "1" }],
411 binaryPath: "/opt/claude/bin/claude",
412 },
413 codex: { locked: false, launchArgs: "-c model_provider=gateway" },
414 },
415 },
416 },
417 }),
418 );
419 assert.deepEqual<unknown>(policy.summary?.limits, {
420 providers: {
421 allowedDrivers: ["claudeAgent", "codex"],
422 lockedInstanceFields: {
423 claudeAgent: ["config.binaryPath", "environment.CLAUDE_CODE_USE_BEDROCK"],
424 },
425 },
426 });
427 assert.equal(
428 disallowedDriverReason(policy.summary, ProviderDriverKind.make("cursor")),
429 "Example Corp's policy does not allow the Cursor provider.",
430 );
431 assert.isUndefined(disallowedDriverReason(policy.summary, ProviderDriverKind.make("codex")));
432 }),
433 );
434
435 it.effect("refuses provider limits it cannot enforce", () =>
436 Effect.gen(function* () {
437 const withProviders = (providers: unknown) =>
438 JSON.stringify({
439 schemaVersion: 1,
440 organization: "Example Corp",
441 limits: { providers },
442 });
443 const reasons = yield* Effect.forEach(
444 [
445 withProviders({ allowedDrivers: ["claudeAgent", "notAProvider"] }),
446 withProviders({ instances: { notAProvider: { locked: true, binaryPath: "/x" } } }),
447 // Cursor has no launch arguments setting to pin.
448 withProviders({ instances: { cursor: { locked: true, launchArgs: "--x" } } }),
449 withProviders({ instances: { codex: { locked: true, homePath: "/x" } } }),
450 withProviders({
451 instances: { codex: { locked: true, environment: [{ name: "1BAD", value: "" }] } },
452 }),
453 // No provider could run at all.
454 withProviders({ allowedDrivers: [] }),
455 ],
456 (contents) =>
457 loadFrom(contents).pipe(
458 Effect.flip,
459 Effect.map((error) => error.reason),
460 ),
461 );
462 assert.lengthOf(reasons, 6);
463 assert.include(reasons[0], "notAProvider");
464 assert.include(reasons[1], "notAProvider");
465 assert.include(reasons[2], "launchArgs");
466 }),
467 );
468
469 it.effect(
470 "tells clients how updates are managed and refuses an update feed it cannot trust",
471 () =>
472 Effect.gen(function* () {
473 const base = { schemaVersion: 1, organization: "Example Corp" };
474 const updates = {
475 mode: "auto" as const,
476 feedUrl: "https://updates.example/t3",
477 allowNightly: false,
478 };
479 const policy = yield* loadFrom(JSON.stringify({ ...base, limits: { updates } }));
480 const { feedUrl: _feedUrl, ...clientUpdates } = updates;
481 assert.deepEqual(policy.summary?.limits, { updates: clientUpdates });
482 for (const invalid of [
483 { mode: "auto", feedUrl: "http://updates.example/t3" },
484 { mode: "manual" },
485 { mode: "sometimes" },
486 { mode: "auto", pinVersion: "1.2.3" },
487 ]) {
488 yield* loadFrom(JSON.stringify({ ...base, limits: { updates: invalid } })).pipe(
489 Effect.flip,
490 );
491 }
492 }),
493 );
494});