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

ManagedPolicy.test.ts

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