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

ManagedPolicy.test.ts

467 lines18.0 KB

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