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

managedSettings.ts

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