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