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 ],
146 (contents) =>
147 loadFrom(contents).pipe(
148 Effect.flip,
149 Effect.map((error) => error.reason),
150 ),
151 );
152 assert.lengthOf(reasons, 13);
153 assert.include(reasons[3], "storageCleanup.logsAfterDayz");
154 assert.include(reasons[6], "adds entries users could not remove");
155 assert.include(reasons[7], "adds entries users could not remove");
156 assert.include(reasons[8], 'manage "defaultModelSelection" as a whole');
157 assert.include(reasons[9], 'manage "idleCompaction" instead');
158 assert.include(reasons[10], 'lock "worktreeCleanup" too');
159 assert.include(reasons[11], 'lock "providerInstances.codex" as a whole');
160 assert.include(reasons[12], "holds a credential");
161 }),
162 );
163
164 it.effect("tells clients the runtime mode ceiling", () =>
165 Effect.gen(function* () {
166 const policy = yield* loadFrom(
167 JSON.stringify({
168 schemaVersion: 1,
169 organization: "Example Corp",
170 settings: { defaultRuntimeMode: { value: "approval-required", locked: true } },
171 limits: { maxRuntimeMode: "auto-accept-edits" },
172 }),
173 );
174 const { providers, ...limits } = policy.summary?.limits ?? {};
175 assert.deepEqual(limits, { maxRuntimeMode: "auto-accept-edits" });
176 // Under a ceiling, each driver's launch configuration is the administrator's.
177 assert.deepEqual(providers?.lockedInstanceFields?.[ProviderDriverKind.make("claudeAgent")], [
178 "config.binaryPath",
179 "config.launchArgs",
180 "config.homePath",
181 "environment",
182 ]);
183 assert.deepEqual(providers?.lockedInstanceFields?.[ProviderDriverKind.make("acpRegistry")], [
184 "config.commandPath",
185 "config.commandArgs",
186 "environment",
187 ]);
188 // The host variable that replaces Codex's launch arguments is ignored too.
189 const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "-c mcp_servers.x.command=sh" };
190 assert.deepEqual(providerHostEnvironment(policy.summary, host), { PATH: "/usr/bin" });
191 assert.strictEqual(providerHostEnvironment(undefined, host), host);
192 }),
193 );
194
195 it.effect(
196 "locks a variable in every spelling on Windows only, and drops a Codex launch override",
197 () =>
198 Effect.gen(function* () {
199 const codex = ProviderDriverKind.make("codex");
200 const variable = (name: string, value: string) => ({ name, value, sensitive: false });
201 const settings = {
202 ...DEFAULT_SERVER_SETTINGS,
203 providerInstances: {
204 codex: {
205 driver: codex,
206 environment: [
207 variable("HTTPS_PROXY", "http://mine"),
208 variable("T3CODE_CODEX_LAUNCH_ARGS", "--dangerously-bypass-approvals-and-sandbox"),
209 ],
210 },
211 },
212 };
213 const policyOn = (platform: NodeJS.Platform) =>
214 ManagedPolicy.fromDocument("/test/policy.json", {
215 schemaVersion: 1,
216 organization: "Example Corp",
217 limits: {
218 providers: {
219 instances: {
220 [codex]: {
221 locked: true,
222 launchArgs: "--strict-config",
223 environment: [{ name: "Https_Proxy", value: "http://gateway" }],
224 },
225 },
226 },
227 },
228 }).pipe(Effect.provideService(HostProcess.Platform, platform));
229 const environmentOn = (platform: NodeJS.Platform) =>
230 Effect.map(
231 policyOn(platform),
232 (policy) =>
233 policy.providers.applyLimits(settings).providerInstances[
234 ProviderInstanceId.make("codex")
235 ]?.environment,
236 );
237 assert.deepEqual(yield* environmentOn("win32"), [
238 variable("Https_Proxy", "http://gateway"),
239 ]);
240 assert.deepEqual(yield* environmentOn("linux"), [
241 variable("HTTPS_PROXY", "http://mine"),
242 variable("Https_Proxy", "http://gateway"),
243 ]);
244 // Saving what the client was shown keeps the override it never saw.
245 const linux = yield* policyOn("linux");
246 const shown = linux.providers.applyLimits(settings);
247 const codexId = ProviderInstanceId.make("codex");
248 const saved = linux.providers.vetWrite(settings, {
249 ...shown,
250 providerInstances: {
251 ...shown.providerInstances,
252 [codexId]: { ...shown.providerInstances[codexId]!, displayName: "Codex (work)" },
253 },
254 });
255 assert.equal(saved._tag, "Allowed");
256 const savedEnvironment =
257 saved._tag === "Allowed"
258 ? (saved.settings.providerInstances[codexId]?.environment ?? [])
259 : [];
260 assert.isTrue(savedEnvironment.some((entry) => entry.name === "T3CODE_CODEX_LAUNCH_ARGS"));
261 // A home path setting would rewrite a locked home variable at launch, so the lock owns it.
262 const claude = ProviderDriverKind.make("claudeAgent");
263 const homeLocked = yield* ManagedPolicy.fromDocument("/test/policy.json", {
264 schemaVersion: 1,
265 organization: "Example Corp",
266 limits: {
267 providers: {
268 instances: {
269 [claude]: {
270 locked: true,
271 environment: [{ name: "CLAUDE_CONFIG_DIR", value: "/opt/claude-home" }],
272 },
273 },
274 },
275 },
276 });
277 const claudeId = ProviderInstanceId.make("claudeAgent");
278 const claudeConfig = homeLocked.providers.applyLimits({
279 ...DEFAULT_SERVER_SETTINGS,
280 providerInstances: {
281 [claudeId]: { driver: claude, config: { homePath: "/home/me/.other-claude" } },
282 },
283 }).providerInstances[claudeId]?.config;
284 assert.deepEqual(claudeConfig, {});
285 assert.include(
286 homeLocked.summary?.limits?.providers?.lockedInstanceFields?.[claude] ?? [],
287 "config.homePath",
288 );
289 // Codex has a second home setting, which a locked CODEX_HOME owns too.
290 const codexHome = yield* ManagedPolicy.fromDocument("/test/policy.json", {
291 schemaVersion: 1,
292 organization: "Example Corp",
293 limits: {
294 providers: {
295 instances: {
296 [codex]: {
297 locked: true,
298 environment: [{ name: "CODEX_HOME", value: "/opt/codex-home" }],
299 },
300 },
301 },
302 },
303 });
304 assert.includeMembers(
305 [...(codexHome.summary?.limits?.providers?.lockedInstanceFields?.[codex] ?? [])],
306 ["config.homePath", "config.shadowHomePath"],
307 );
308 // A server URL makes OpenCode skip the local launch a pin sets, so the pin owns it too.
309 const opencode = ProviderDriverKind.make("opencode");
310 const opencodePinned = yield* ManagedPolicy.fromDocument("/test/policy.json", {
311 schemaVersion: 1,
312 organization: "Example Corp",
313 limits: {
314 providers: { instances: { [opencode]: { locked: true, binaryPath: "/opt/opencode" } } },
315 },
316 });
317 assert.include(
318 opencodePinned.summary?.limits?.providers?.lockedInstanceFields?.[opencode] ?? [],
319 "config.serverUrl",
320 );
321 // The same override from the environment that starts the server is ignored too.
322 const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "--yolo" };
323 assert.deepEqual(providerHostEnvironment((yield* policyOn("linux")).summary, host), {
324 PATH: "/usr/bin",
325 });
326 }),
327 );
328
329 it.effect("refuses a default runtime mode above its own ceiling", () =>
330 Effect.gen(function* () {
331 const reasons = yield* Effect.forEach([false, true], (locked) =>
332 loadFrom(
333 JSON.stringify({
334 schemaVersion: 1,
335 organization: "Example Corp",
336 settings: { defaultRuntimeMode: { value: "auto", locked } },
337 limits: { maxRuntimeMode: "auto-accept-edits" },
338 }),
339 ).pipe(
340 Effect.flip,
341 Effect.map((error) => error.reason),
342 ),
343 );
344 assert.deepEqual(reasons, [
345 '"defaultRuntimeMode" is above "limits.maxRuntimeMode"',
346 '"defaultRuntimeMode" is above "limits.maxRuntimeMode"',
347 ]);
348 }),
349 );
350
351 it.effect("tells clients which drivers run and which instance fields are locked", () =>
352 Effect.gen(function* () {
353 // A provider the policy cannot name would also escape its launch-setting rules.
354 const everyDriver = BUILT_IN_DRIVERS.map((driver) => driver.driverKind);
355 const allowingAll = yield* loadFrom(
356 JSON.stringify({
357 schemaVersion: 1,
358 organization: "Example Corp",
359 limits: { providers: { allowedDrivers: everyDriver } },
360 }),
361 );
362 assert.deepEqual<unknown>(
363 allowingAll.summary?.limits?.providers?.allowedDrivers,
364 everyDriver,
365 );
366
367 const policy = yield* loadFrom(
368 JSON.stringify({
369 schemaVersion: 1,
370 organization: "Example Corp",
371 limits: {
372 providers: {
373 allowedDrivers: ["claudeAgent", "codex"],
374 instances: {
375 claudeAgent: {
376 locked: true,
377 environment: [{ name: "CLAUDE_CODE_USE_BEDROCK", value: "1" }],
378 binaryPath: "/opt/claude/bin/claude",
379 },
380 codex: { locked: false, launchArgs: "-c model_provider=gateway" },
381 },
382 },
383 },
384 }),
385 );
386 assert.deepEqual<unknown>(policy.summary?.limits, {
387 providers: {
388 allowedDrivers: ["claudeAgent", "codex"],
389 lockedInstanceFields: {
390 claudeAgent: ["config.binaryPath", "environment.CLAUDE_CODE_USE_BEDROCK"],
391 },
392 },
393 });
394 assert.equal(
395 disallowedDriverReason(policy.summary, ProviderDriverKind.make("cursor")),
396 "Example Corp's policy does not allow the Cursor provider.",
397 );
398 assert.isUndefined(disallowedDriverReason(policy.summary, ProviderDriverKind.make("codex")));
399 }),
400 );
401
402 it.effect("refuses provider limits it cannot enforce", () =>
403 Effect.gen(function* () {
404 const withProviders = (providers: unknown) =>
405 JSON.stringify({
406 schemaVersion: 1,
407 organization: "Example Corp",
408 limits: { providers },
409 });
410 const reasons = yield* Effect.forEach(
411 [
412 withProviders({ allowedDrivers: ["claudeAgent", "notAProvider"] }),
413 withProviders({ instances: { notAProvider: { locked: true, binaryPath: "/x" } } }),
414 // Cursor has no launch arguments setting to pin.
415 withProviders({ instances: { cursor: { locked: true, launchArgs: "--x" } } }),
416 withProviders({ instances: { codex: { locked: true, homePath: "/x" } } }),
417 withProviders({
418 instances: { codex: { locked: true, environment: [{ name: "1BAD", value: "" }] } },
419 }),
420 // No provider could run at all.
421 withProviders({ allowedDrivers: [] }),
422 ],
423 (contents) =>
424 loadFrom(contents).pipe(
425 Effect.flip,
426 Effect.map((error) => error.reason),
427 ),
428 );
429 assert.lengthOf(reasons, 6);
430 assert.include(reasons[0], "notAProvider");
431 assert.include(reasons[1], "notAProvider");
432 assert.include(reasons[2], "launchArgs");
433 }),
434 );
435
436 it.effect(
437 "tells clients how updates are managed and refuses an update feed it cannot trust",
438 () =>
439 Effect.gen(function* () {
440 const base = { schemaVersion: 1, organization: "Example Corp" };
441 const updates = {
442 mode: "auto" as const,
443 feedUrl: "https://updates.example/t3",
444 allowNightly: false,
445 };
446 const policy = yield* loadFrom(JSON.stringify({ ...base, limits: { updates } }));
447 const { feedUrl: _feedUrl, ...clientUpdates } = updates;
448 assert.deepEqual(policy.summary?.limits, { updates: clientUpdates });
449 for (const invalid of [
450 { mode: "auto", feedUrl: "http://updates.example/t3" },
451 { mode: "manual" },
452 { mode: "sometimes" },
453 { mode: "auto", pinVersion: "1.2.3" },
454 ]) {
455 yield* loadFrom(JSON.stringify({ ...base, limits: { updates: invalid } })).pipe(
456 Effect.flip,
457 );
458 }
459 }),
460 );
461});