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

managedSettings.ts

549 lines21.5 KB

1import {
2 DEFAULT_SERVER_SETTINGS,
3 isRuntimeModeAbove,
4 type ManagedPolicySetting,
5 ProjectSettingsOverrides,
6 type RuntimeMode,
7 ServerSettings,
8 withIdleCompaction,
9} from "@t3tools/contracts";
10import * as Exit from "effect/Exit";
11import * as Schema from "effect/Schema";
12import * as SchemaAST from "effect/SchemaAST";
13​
14import { mapSettingsSecrets } from "../settingsSecrets.ts";
15​
16const encodeSettings = Schema.encodeSync(ServerSettings);
17const decodeSettings = Schema.decodeUnknownSync(ServerSettings);
18const decodeSettingsExit = Schema.decodeUnknownExit(ServerSettings);
19​
20/** Project overrides mirror these top-level keys, so a lock on one applies inside each project. */
21const PROJECT_OVERRIDE_KEYS: ReadonlySet<string> = new Set(
22 Object.keys(ProjectSettingsOverrides.fields),
23);
24/** Per-project stores; admins lock the top-level key and the lock reaches every project. */
25const UNMANAGEABLE_KEYS: ReadonlySet<string> = new Set([
26 "projectSettingsOverrides",
27 "projectAgentBrowserAccessOverrides",
28 "projectAutoPullOverrides",
29 "projectScriptOverrides",
30]);
31​
32/**
33 * Startup resolves OTLP endpoints from the settings file and desktop bootstrap input before the policy
34 * loads, and the user's OTLP environment variables outrank them, so a managed value would look
35 * enforced without being.
36 */
37const ENVIRONMENT_OVERRIDDEN_KEYS: ReadonlySet<string> = new Set(["observability"]);
38​
39/** Legacy settings the server derives from another on every write; manage that one instead. */
40const DERIVED_FROM: ReadonlyMap<string, string> = new Map([
41 ["compactIdleThreads", "idleCompaction"],
42]);
43​
44/**
45 * Settings another one overrides when it is set: `worktreeCleanup`, also per project, wins over
46 * the worktree rules in `storageCleanup`. A lock on the first alone would look enforced without
47 * being, so the second must be locked too.
48 */
49const OVERRIDDEN_BY: ReadonlyArray<readonly [overridden: string, by: string]> = [
50 ["storageCleanup.worktree", "worktreeCleanup"],
51];
52​
53type Segments = ReadonlyArray<string>;
54​
55/**
56 * The server derives the legacy switch from `idleCompaction` on every write, and shipped clients
57 * still read it, so values the policy sets carry the matching switch.
58 */
59const syncIdleCompaction = (settings: ServerSettings): ServerSettings =>
60 settings.idleCompaction === undefined
61 ? settings
62 : withIdleCompaction(settings, settings.idleCompaction);
63​
64const isRecord = (value: unknown): value is Record<string, unknown> =>
65 value !== null && typeof value === "object" && !Array.isArray(value);
66​
67const getPath = (tree: unknown, segments: Segments): unknown => {
68 let current = tree;
69 for (const segment of segments) {
70 if (!isRecord(current)) return undefined;
71 current = current[segment];
72 }
73 return current;
74};
75​
76const setPath = (tree: unknown, segments: Segments, value: unknown): unknown => {
77 const [head, ...rest] = segments;
78 if (head === undefined) return value;
79 const record = isRecord(tree) ? tree : {};
80 if (value === undefined && rest.length === 0) {
81 const { [head]: _removed, ...remaining } = record;
82 return remaining;
83 }
84 return { ...record, [head]: setPath(record[head], rest, value) };
85};
86​
87/** Fills keys `target` lacks from `defaults`, recursing into objects both sides hold. */
88const fillMissing = (target: unknown, defaults: unknown): unknown => {
89 if (!isRecord(target) || !isRecord(defaults)) return target;
90 const next: Record<string, unknown> = { ...target };
91 for (const [key, value] of Object.entries(defaults)) {
92 next[key] = key in target ? fillMissing(target[key], value) : value;
93 }
94 return next;
95};
96​
97const jsonEqual = (left: unknown, right: unknown): boolean => {
98 if (Object.is(left, right)) return true;
99 if (Array.isArray(left) && Array.isArray(right)) {
100 return (
101 left.length === right.length && left.every((item, index) => jsonEqual(item, right[index]))
102 );
103 }
104 if (!isRecord(left) || !isRecord(right)) return false;
105 const leftKeys = Object.keys(left).filter((key) => left[key] !== undefined);
106 const rightKeys = Object.keys(right).filter((key) => right[key] !== undefined);
107 return (
108 leftKeys.length === rightKeys.length &&
109 leftKeys.every((key) => jsonEqual(left[key], right[key]))
110 );
111};
112​
113/**
114 * Whether `value` agrees with a lock on every key it holds. Patches and project overrides carry
115 * only some of a locked object's keys, such as `{ enabled }` for a provider instance.
116 */
117const matchesLock = (value: unknown, lock: unknown): boolean =>
118 isRecord(value) && isRecord(lock)
119 ? Object.entries(value).every(
120 ([key, child]) => child === undefined || matchesLock(child, lock[key]),
121 )
122 : jsonEqual(value, lock);
123​
124/** Whether `value` holds a key `existing` does not, at any depth. */
125const addsKeys = (existing: unknown, value: unknown): boolean =>
126 isRecord(existing) &&
127 isRecord(value) &&
128 Object.entries(value).some(([key, child]) =>
129 key in existing ? addsKeys(existing[key], child) : true,
130 );
131​
132/**
133 * How a policy's `settings` shape the server's settings. Policy values are never written to
134 * the user's settings file: defaults fill keys the file leaves out, and locks are laid over the
135 * result on every read, so removing the policy brings the user's own settings back.
136 */
137export interface ManagedSettings {
138 /** Fill policy defaults into a parsed settings file before it is decoded. */
139 readonly withDefaults: (persisted: unknown) => unknown;
140 /** Built-in defaults with the policy's defaults applied; the settings file omits values equal to these. */
141 readonly defaults: ServerSettings;
142 /**
143 * Lay locked values over settings, including inside each project's overrides, and lower
144 * default runtime modes above the policy's ceiling to it.
145 */
146 readonly applyLocks: (settings: ServerSettings) => ServerSettings;
147 /**
148 * Vet a write from `current` to `next`. It is refused when it tries to move a locked path off
149 * its locked value, whether set in `patch` or changed by another route such as a legacy patch
150 * key. An allowed write keeps the user's stored values at locked paths, so a client re-sending
151 * the locked value does not overwrite what applies once the policy is gone.
152 */
153 readonly vetWrite: (
154 current: ServerSettings,
155 next: ServerSettings,
156 patch: unknown,
157 ) =>
158 | { readonly _tag: "Allowed"; readonly settings: ServerSettings }
159 | { readonly _tag: "Locked"; readonly path: string };
160 readonly lockedPaths: ReadonlyArray<string>;
161 /**
162 * Put back into a stripped settings file the values `stored`, the file before this write, held
163 * at or under paths the policy defaults: equal to the policy's default, they are still the
164 * user's choice. A key `isAtomic` names comes back whole or not at all. Undefined without
165 * policy defaults, so writers can skip reading the file.
166 */
167 readonly keepStored:
168 | ((
169 stripped: unknown,
170 settings: ServerSettings,
171 stored: unknown,
172 isAtomic: (key: string) => boolean,
173 ) => unknown)
174 | undefined;
176​
177export const unmanagedSettings: ManagedSettings = {
178 keepStored: undefined,
179 withDefaults: (persisted) => persisted,
180 defaults: DEFAULT_SERVER_SETTINGS,
181 applyLocks: (settings) => settings,
182 vetWrite: (_current, next) => ({ _tag: "Allowed", settings: next }),
183 lockedPaths: [],
184};
185​
186interface Entry {
187 readonly path: string;
188 readonly segments: Segments;
189 /** As written in the policy, the encoded form. */
190 readonly value: unknown;
192​
193interface Lock extends Entry {
194 /** The decoded form, which is what patches carry. */
195 readonly decodedValue: unknown;
197​
198/** Locked paths as stored in the top level and in each project's overrides of `encoded`. */
199const lockTargets = (encoded: unknown, entry: Entry): ReadonlyArray<Segments> => {
200 const [head] = entry.segments;
201 if (head === undefined || !PROJECT_OVERRIDE_KEYS.has(head)) return [entry.segments];
202 const projects = getPath(encoded, ["projectSettingsOverrides"]);
203 const projectTargets = isRecord(projects)
204 ? Object.entries(projects)
205 .filter(([, overrides]) => isRecord(overrides) && overrides[head] !== undefined)
206 .map(([projectId]) => ["projectSettingsOverrides", projectId, ...entry.segments])
207 : [];
208 return [entry.segments, ...projectTargets];
209};
210​
211/**
212 * A user's stored default runtime mode can sit above a ceiling deployed after it was chosen, and
213 * the built-in default is the broadest mode. Every new thread would then be refused, so the
214 * effective default is the ceiling instead. The stored value is untouched and returns with the
215 * policy's removal; existing threads keep their modes and are refused turns instead.
216 */
217const clampDefaultRuntimeModes = (
218 settings: ServerSettings,
219 ceiling: RuntimeMode,
220): ServerSettings => {
221 const projectsAbove = Object.entries(settings.projectSettingsOverrides).filter(
222 ([, overrides]) =>
223 overrides.defaultRuntimeMode !== undefined &&
224 isRuntimeModeAbove(overrides.defaultRuntimeMode, ceiling),
225 );
226 if (!isRuntimeModeAbove(settings.defaultRuntimeMode, ceiling) && projectsAbove.length === 0) {
227 return settings;
228 }
229 return {
230 ...settings,
231 defaultRuntimeMode: isRuntimeModeAbove(settings.defaultRuntimeMode, ceiling)
232 ? ceiling
233 : settings.defaultRuntimeMode,
234 projectSettingsOverrides: {
235 ...settings.projectSettingsOverrides,
236 ...Object.fromEntries(
237 projectsAbove.map(([projectId, overrides]) => [
238 projectId,
239 { ...overrides, defaultRuntimeMode: ceiling },
240 ]),
241 ),
242 },
243 };
244};
245​
246/**
247 * Every path a policy can manage, with its built-in default. Fields come from the schema, since
248 * optional ones have no default to find; keys from the default cover records.
249 */
250export function listManageableSettings() {
251 const builtIn = encodeSettings(DEFAULT_SERVER_SETTINGS);
252 const leaves = (
253 path: string,
254 value: unknown,
255 ast: SchemaAST.AST | undefined,
256 ): ReadonlyArray<readonly [string, unknown]> => {
257 const fields = new Map(
258 ast !== undefined && SchemaAST.isObjects(ast)
259 ? ast.propertySignatures.map(({ name, type }) => [String(name), type])
260 : [],
261 );
262 const children = isRecord(value) ? value : {};
263 const keys = new Set([...fields.keys(), ...Object.keys(children)]);
264 return keys.size > 0
265 ? [...keys].flatMap((key) => leaves(`${path}.${key}`, children[key], fields.get(key)))
266 : [[path, value]];
267 };
268 return Object.entries(ServerSettings.fields)
269 .filter(
270 ([key]) =>
271 !UNMANAGEABLE_KEYS.has(key) &&
272 !ENVIRONMENT_OVERRIDDEN_KEYS.has(key) &&
273 !DERIVED_FROM.has(key),
274 )
275 .flatMap(([key, field]) => leaves(key, getPath(builtIn, [key]), field.ast))
276 .toSorted(([left], [right]) => left.localeCompare(right));
278​
279/** Build the overlay for a policy's settings, or describe the first entry this build cannot apply. */
280export function makeManagedSettings(
281 settings: Readonly<Record<string, ManagedPolicySetting>>,
282 maxRuntimeMode?: RuntimeMode,
283):
284 | { readonly _tag: "Valid"; readonly settings: ManagedSettings }
285 | { readonly _tag: "Invalid"; readonly reason: string } {
286 const defaults: Entry[] = [];
287 const locks: Entry[] = [];
288 for (const [path, setting] of Object.entries(settings)) {
289 const segments = path.split(".");
290 const [head] = segments;
291 if (head === undefined || segments.some((segment) => segment.length === 0)) {
292 return { _tag: "Invalid", reason: `"${path}" is not a settings path` };
293 }
294 if (!(head in ServerSettings.fields) || UNMANAGEABLE_KEYS.has(head)) {
295 return { _tag: "Invalid", reason: `"${path}" is not a setting this version can manage` };
296 }
297 if (ENVIRONMENT_OVERRIDDEN_KEYS.has(head)) {
298 return {
299 _tag: "Invalid",
300 reason: `"${path}" is resolved at startup from each user's environment, settings file and desktop bootstrap input, which a policy cannot override`,
301 };
302 }
303 const source = DERIVED_FROM.get(head);
304 if (source !== undefined) {
305 return {
306 _tag: "Invalid",
307 reason: `"${head}" follows "${source}"; manage "${source}" instead`,
308 };
309 }
310 (setting.locked ? locks : defaults).push({ path, segments, value: setting.value });
311 }
312​
313 for (const lock of locks) {
314 const unheld = OVERRIDDEN_BY.find(
315 ([overridden, by]) =>
316 (lock.path.startsWith(overridden) || overridden.startsWith(`${lock.path}.`)) &&
317 !locks.some((other) => other.path === by),
318 );
319 if (unheld !== undefined) {
320 return {
321 _tag: "Invalid",
322 reason: `"${lock.path}" can be overridden by "${unheld[1]}"; lock "${unheld[1]}" too`,
323 };
324 }
325 // An instance's fields override each other: a variable replaces launch arguments, a home
326 // path rewrites a home variable, and a setup mode brings its own runtime.
327 const [head, instanceId] = lock.segments;
328 if (head === "providerInstances" && instanceId !== undefined && lock.segments.length > 2) {
329 return {
330 _tag: "Invalid",
331 reason: `"${lock.path}" is one field of a provider instance whose fields override each other; lock "providerInstances.${instanceId}" as a whole, or pin fields with limits.providers.instances`,
332 };
333 }
334 }
335​
336 // Apply every entry to the built-in defaults at once, and read each value back: a typo in a
337 // nested key or a value of the wrong type does not survive the round trip.
338 const builtIn = encodeSettings(DEFAULT_SERVER_SETTINGS);
339 const all = [...defaults, ...locks];
340 // A user's stored null would leave a nested lock building a partial object, so lock the whole
341 // setting instead.
342 const insideNullable = all.find((entry) =>
343 entry.segments
344 .slice(0, -1)
345 .some((_, index) =>
346 Exit.isSuccess(
347 decodeSettingsExit(setPath(builtIn, entry.segments.slice(0, index + 1), null)),
348 ),
349 ),
350 );
351 if (insideNullable !== undefined) {
352 return {
353 _tag: "Invalid",
354 reason: `"${insideNullable.path}" is inside a setting that can be empty; manage "${insideNullable.segments[0]}" as a whole`,
355 };
356 }
357 const applied = all.reduce<unknown>(
358 (tree, entry) => setPath(tree, entry.segments, entry.value),
359 builtIn,
360 );
361 const decoded = decodeSettingsExit(applied);
362 if (Exit.isFailure(decoded)) {
363 return { _tag: "Invalid", reason: "a managed setting has a value of the wrong type" };
364 }
365 const roundTrip = encodeSettings(decoded.value);
366 const lost = all.find((entry) => !jsonEqual(getPath(roundTrip, entry.segments), entry.value));
367 if (lost !== undefined) {
368 return {
369 _tag: "Invalid",
370 reason: `"${lost.path}" is not a setting this version can manage, or its value is invalid`,
371 };
372 }
373 // The server moves a credential it finds in settings into the user's secret store, where a
374 // policy's would outlive the policy. Built-in defaults hold none, so any found is the policy's.
375 let holdsCredential = false;
376 mapSettingsSecrets(decoded.value, (secret) => {
377 if (secret.sensitive && !secret.redacted && secret.value.length > 0) holdsCredential = true;
378 return secret;
379 });
380 if (holdsCredential) {
381 return {
382 _tag: "Invalid",
383 reason:
384 "a managed setting holds a credential, which every user can read in the policy; deploy credentials another way",
385 };
386 }
387 // Defaults fill in what the file leaves out, so an entry a default adds to a record such as
388 // `providerInstances` would come back each time the user removed it.
389 const addsEntry = defaults.find((entry) => {
390 const existing = getPath(builtIn, entry.segments);
391 return existing === undefined ? entry.segments.length > 1 : addsKeys(existing, entry.value);
392 });
393 if (addsEntry !== undefined) {
394 return {
395 _tag: "Invalid",
396 reason: `"${addsEntry.path}" adds entries users could not remove; lock it instead`,
397 };
398 }
399 // A managed default above the ceiling would start every thread in a mode the policy refuses.
400 if (
401 all.some((entry) => entry.path === "defaultRuntimeMode") &&
402 isRuntimeModeAbove(decoded.value.defaultRuntimeMode, maxRuntimeMode)
403 ) {
404 return {
405 _tag: "Invalid",
406 reason: `"defaultRuntimeMode" is above "limits.maxRuntimeMode"`,
407 };
408 }
409​
410 const defaultsTree = defaults.reduce<unknown>(
411 (tree, entry) => setPath(tree, entry.segments, entry.value),
412 {},
413 );
414 const lockEntries: ReadonlyArray<Lock> = locks.map((entry) => ({
415 ...entry,
416 decodedValue: getPath(decoded.value, entry.segments),
417 }));
418 const lockedPaths = locks.map((entry) => entry.path);
419 const idleCompactionLocked = lockedPaths.includes("idleCompaction");
420 const lockCache = new WeakMap<ServerSettings, ServerSettings>();
421​
422 const applyLocks = (current: ServerSettings): ServerSettings => {
423 if (locks.length === 0 && maxRuntimeMode === undefined) return current;
424 const cached = lockCache.get(current);
425 if (cached !== undefined) return cached;
426 const locked =
427 locks.length === 0
428 ? current
429 : // Validated against the built-in defaults above, so a failure here is a bug, not bad input.
430 decodeSettings(
431 locks.reduce<unknown>(
432 (tree, entry) =>
433 lockTargets(tree, entry).reduce<unknown>(
434 (next, target) => setPath(next, target, entry.value),
435 tree,
436 ),
437 encodeSettings(current),
438 ),
439 );
440 const derived = idleCompactionLocked ? syncIdleCompaction(locked) : locked;
441 const result =
442 maxRuntimeMode === undefined ? derived : clampDefaultRuntimeModes(derived, maxRuntimeMode);
443 lockCache.set(current, result);
444 return result;
445 };
446​
447 const vetWrite: ManagedSettings["vetWrite"] = (current, next, patch) => {
448 if (locks.length === 0) return { _tag: "Allowed", settings: next };
449 const before = encodeSettings(current);
450 const after = encodeSettings(next);
451 const changed = lockEntries.find(
452 (entry) =>
453 // Re-sending a stored value the lock overrides changes nothing on disk, but it is still
454 // an attempt to change what the user sees.
455 lockTargets(patch, entry).some((target) => {
456 const value = getPath(patch, target);
457 return value !== undefined && !matchesLock(value, entry.decodedValue);
458 }) ||
459 lockTargets(after, entry).some((target) => {
460 const value = getPath(after, target);
461 // Removing a project's override of a locked key is harmless; the lock applies either way.
462 return (
463 value !== undefined &&
464 !jsonEqual(value, getPath(before, target)) &&
465 !matchesLock(value, entry.value)
466 );
467 }),
468 );
469 if (changed !== undefined) return { _tag: "Locked", path: changed.path };
470 const kept = locks.reduce<unknown>(
471 (tree, entry) =>
472 lockTargets(tree, entry).reduce<unknown>((result, target) => {
473 // A parent the write adds holds the locked value already; removing only the locked key
474 // inside it would leave a partial object.
475 const added = target
476 .slice(0, -1)
477 .some((_, index) => getPath(before, target.slice(0, index + 1)) === undefined);
478 return added ? result : setPath(result, target, getPath(before, target));
479 }, tree),
480 after,
481 );
482 return { _tag: "Allowed", settings: decodeSettings(kept) };
483 };
484​
485 // A file from before a setting replaced its legacy key holds the user's choice in that key, which
486 // a default for the new setting would otherwise override.
487 const withoutLegacyChoices = (persisted: unknown): unknown => {
488 if (!isRecord(persisted) || !isRecord(defaultsTree)) return defaultsTree;
489 const kept = { ...defaultsTree };
490 for (const [legacy, source] of DERIVED_FROM) {
491 if (persisted[legacy] !== undefined && persisted[source] === undefined) delete kept[source];
492 }
493 return kept;
494 };
495​
496 // The paths keepStored puts back: each default, cut at an atomic setting, and the legacy key a
497 // defaulted setting replaced, which an older file holds the user's choice in.
498 const restoredPaths = (isAtomic: (key: string) => boolean): ReadonlyArray<Segments> => [
499 ...defaults.map((entry) => {
500 const atomicAt = entry.segments.findIndex(isAtomic);
501 return atomicAt === -1 ? entry.segments : entry.segments.slice(0, atomicAt + 1);
502 }),
503 ...[...DERIVED_FROM]
504 .filter(([, source]) => defaults.some((entry) => entry.path === source))
505 .map(([legacy]) => [legacy]),
506 ];
507​
508 const keepStored: ManagedSettings["keepStored"] =
509 defaults.length === 0
510 ? undefined
511 : (stripped, settings, stored, isAtomic) => {
512 const encoded = encodeSettings(settings);
513 const restore = (tree: unknown, segments: Segments): unknown => {
514 const previous = getPath(stored, segments);
515 if (previous === undefined) return tree;
516 if (isRecord(previous) && !isAtomic(segments.at(-1) ?? "")) {
517 return Object.keys(previous).reduce<unknown>(
518 (next, key) => restore(next, [...segments, key]),
519 tree,
520 );
521 }
522 return getPath(tree, segments) === undefined &&
523 jsonEqual(previous, getPath(encoded, segments))
524 ? setPath(tree, segments, getPath(settings, segments))
525 : tree;
526 };
527 // A default inside an atomic setting restores that whole setting, never part of it.
528 return restoredPaths(isAtomic).reduce<unknown>(restore, stripped);
529 };
530​
531 return {
532 _tag: "Valid",
533 settings: {
534 keepStored,
535 withDefaults: (persisted) => fillMissing(persisted, withoutLegacyChoices(persisted)),
536 defaults: syncIdleCompaction(
537 decodeSettings(
538 defaults.reduce<unknown>(
539 (tree, entry) => setPath(tree, entry.segments, entry.value),
540 builtIn,
541 ),
542 ),
543 ),
544 applyLocks,
545 vetWrite,
546 lockedPaths,
547 },
548 };