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