hmcp-core 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -3
- package/dist/approvals.d.ts +508 -0
- package/dist/approvals.js +1445 -0
- package/dist/argpath.d.ts +75 -0
- package/dist/argpath.js +189 -0
- package/dist/audit.d.ts +289 -0
- package/dist/audit.js +512 -0
- package/dist/canonical.d.ts +78 -0
- package/dist/canonical.js +146 -0
- package/dist/classify-held.d.ts +47 -0
- package/dist/classify-held.js +60 -0
- package/dist/classify-name.d.ts +55 -0
- package/dist/classify-name.js +255 -0
- package/dist/decide.d.ts +168 -0
- package/dist/decide.js +518 -0
- package/dist/egress.d.ts +123 -0
- package/dist/egress.js +544 -0
- package/dist/enforce.d.ts +78 -0
- package/dist/enforce.js +231 -0
- package/dist/exposure-apply.d.ts +51 -0
- package/dist/exposure-apply.js +69 -0
- package/dist/exposure.d.ts +81 -0
- package/dist/exposure.js +65 -0
- package/dist/file-lock.d.ts +70 -0
- package/dist/file-lock.js +165 -0
- package/dist/glob.d.ts +11 -0
- package/dist/glob.js +55 -0
- package/dist/grants.d.ts +204 -0
- package/dist/grants.js +372 -0
- package/dist/http-util.d.ts +52 -0
- package/dist/http-util.js +81 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +36 -0
- package/dist/inventory.d.ts +100 -0
- package/dist/inventory.js +88 -0
- package/dist/ip.d.ts +15 -0
- package/dist/ip.js +186 -0
- package/dist/jwt.d.ts +57 -0
- package/dist/jwt.js +199 -0
- package/dist/live-state.d.ts +76 -0
- package/dist/live-state.js +57 -0
- package/dist/migrate.d.ts +22 -0
- package/dist/migrate.js +318 -0
- package/dist/pins.d.ts +119 -0
- package/dist/pins.js +125 -0
- package/dist/policy-batch.d.ts +89 -0
- package/dist/policy-batch.js +340 -0
- package/dist/policy-source.d.ts +161 -0
- package/dist/policy-source.js +299 -0
- package/dist/policy-write.d.ts +627 -0
- package/dist/policy-write.js +1697 -0
- package/dist/policy.d.ts +456 -0
- package/dist/policy.js +448 -0
- package/dist/redact.d.ts +65 -0
- package/dist/redact.js +191 -0
- package/dist/registry.d.ts +41 -0
- package/dist/registry.js +121 -0
- package/dist/remember-defaults.d.ts +9 -0
- package/dist/remember-defaults.js +9 -0
- package/dist/remember.d.ts +91 -0
- package/dist/remember.js +371 -0
- package/dist/resolve.d.ts +22 -0
- package/dist/resolve.js +34 -0
- package/dist/runtime-state.d.ts +65 -0
- package/dist/runtime-state.js +35 -0
- package/dist/secrets.d.ts +159 -0
- package/dist/secrets.js +361 -0
- package/dist/tenant.d.ts +83 -0
- package/dist/tenant.js +182 -0
- package/dist/unicode.d.ts +40 -0
- package/dist/unicode.js +103 -0
- package/dist/within-host.d.ts +33 -0
- package/dist/within-host.js +91 -0
- package/dist/within-real.d.ts +7 -0
- package/dist/within-real.js +28 -0
- package/package.json +33 -4
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { isMap, isScalar, isSeq, parseDocument, YAMLSeq } from "yaml";
|
|
3
|
+
import { canonicalJson } from "./canonical.js";
|
|
4
|
+
import { globMatch } from "./glob.js";
|
|
5
|
+
import { expandPath, parsePolicy } from "./policy.js";
|
|
6
|
+
import { assessPolicyChange, parsePolicySetting, parseRuleInput, POLICY_SETTINGS, PolicyWriteError, ruleToYaml, settingLoosens, writeAtomically } from "./policy-write.js";
|
|
7
|
+
import { policyDigest } from "./runtime-state.js";
|
|
8
|
+
const TO_STRING = { lineWidth: 0 };
|
|
9
|
+
/** How each egress switch reads to someone who is not a network engineer. */
|
|
10
|
+
const EGRESS_WORDS = {
|
|
11
|
+
block_private_ips: "Your toolbox may connect to addresses on this computer and your local network",
|
|
12
|
+
allow_http: "Your toolbox may use unencrypted http:// connections",
|
|
13
|
+
allow_ip_literals: "Your toolbox may connect to bare IP addresses, not just names"
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Applies `changes` to a policy file's text. Pure: reads and writes nothing.
|
|
17
|
+
* Throws `PolicyWriteError` when the text is not a valid policy, a change is
|
|
18
|
+
* invalid, or the edited text would not say exactly what was asked.
|
|
19
|
+
*/
|
|
20
|
+
export function applyPolicyBatch(policyText, changes) {
|
|
21
|
+
// An empty file is a policy with every default, which is what the loader
|
|
22
|
+
// would make of it given a version; seed one so the edit has a document.
|
|
23
|
+
const source = policyText.trim() === "" ? "version: 1\n" : policyText;
|
|
24
|
+
const doc = parseDocument(source);
|
|
25
|
+
if (doc.errors.length > 0)
|
|
26
|
+
throw new PolicyWriteError(`the policy is not valid YAML: ${doc.errors[0].message}`);
|
|
27
|
+
let before;
|
|
28
|
+
try {
|
|
29
|
+
before = parsePolicy(doc.toJS(), "policy.yaml");
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
throw new PolicyWriteError(`the policy does not validate, so nothing was changed: ${err.message}`);
|
|
33
|
+
}
|
|
34
|
+
if (!isMap(doc.contents))
|
|
35
|
+
throw new PolicyWriteError("the policy file is not a mapping at its top level");
|
|
36
|
+
const egress = planEgress(before, changes);
|
|
37
|
+
const rules = planRules(before, changes);
|
|
38
|
+
const previousDigest = policyDigest(before);
|
|
39
|
+
const unchanged = () => ({
|
|
40
|
+
text: policyText,
|
|
41
|
+
changed: false,
|
|
42
|
+
loosens: [],
|
|
43
|
+
policy: before,
|
|
44
|
+
digest: previousDigest,
|
|
45
|
+
previousDigest,
|
|
46
|
+
egressAdded: [],
|
|
47
|
+
methodsAdded: [],
|
|
48
|
+
rulesAdded: [],
|
|
49
|
+
rulesReplaced: [],
|
|
50
|
+
rulesSkipped: rules.skipped
|
|
51
|
+
});
|
|
52
|
+
if (!egress.changed && !rules.changed)
|
|
53
|
+
return unchanged();
|
|
54
|
+
/* ---- edit the document ---- */
|
|
55
|
+
if (egress.changed)
|
|
56
|
+
editEgress(doc, egress);
|
|
57
|
+
if (rules.changed)
|
|
58
|
+
editRules(doc, before, rules, changes.comment);
|
|
59
|
+
const text = doc.toString(TO_STRING);
|
|
60
|
+
let after;
|
|
61
|
+
try {
|
|
62
|
+
after = parsePolicy(parseDocument(text).toJS(), "the edited policy");
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
throw new PolicyWriteError(`the change would produce an invalid policy, so nothing was changed: ${err.message}`);
|
|
66
|
+
}
|
|
67
|
+
// The proof: the file now says exactly what was planned, and nothing else moved.
|
|
68
|
+
const expected = { ...before, egress: egress.next, rules: rules.next };
|
|
69
|
+
if (canonicalJson(expected) !== canonicalJson(after)) {
|
|
70
|
+
throw new PolicyWriteError("the edit changed something other than what was asked; nothing was changed");
|
|
71
|
+
}
|
|
72
|
+
/* ---- grade ---- */
|
|
73
|
+
const loosens = [];
|
|
74
|
+
for (const host of egress.allowAdded)
|
|
75
|
+
loosens.push(`Your toolbox may connect to ${host}`);
|
|
76
|
+
for (const method of egress.methodsAdded)
|
|
77
|
+
loosens.push(`Your toolbox may send ${method} requests`);
|
|
78
|
+
for (const [key, value] of Object.entries(egress.settings)) {
|
|
79
|
+
const was = before.egress[key];
|
|
80
|
+
if (settingLoosens(`egress.${key}`, was, value)) {
|
|
81
|
+
loosens.push(EGRESS_WORDS[key] ?? `egress.${key} goes from ${JSON.stringify(was)} to ${JSON.stringify(value)}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const tools = changes.tools ?? [];
|
|
85
|
+
loosens.push(...assessPolicyChange(before, { ...before, rules: rules.next }, tools).loosenReasons);
|
|
86
|
+
// A backstop over the whole change, in case the two halves together loosen
|
|
87
|
+
// something neither does alone (or a grade above missed a case).
|
|
88
|
+
const whole = assessPolicyChange(before, after, tools);
|
|
89
|
+
if (whole.loosens && loosens.length === 0)
|
|
90
|
+
loosens.push(...whole.loosenReasons);
|
|
91
|
+
return {
|
|
92
|
+
text,
|
|
93
|
+
changed: true,
|
|
94
|
+
loosens: [...new Set(loosens)],
|
|
95
|
+
policy: after,
|
|
96
|
+
digest: policyDigest(after),
|
|
97
|
+
previousDigest,
|
|
98
|
+
egressAdded: egress.allowAdded,
|
|
99
|
+
methodsAdded: egress.methodsAdded,
|
|
100
|
+
rulesAdded: rules.added,
|
|
101
|
+
rulesReplaced: rules.replaced,
|
|
102
|
+
rulesSkipped: rules.skipped
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function planEgress(before, changes) {
|
|
106
|
+
const next = { ...before.egress, allow: [...before.egress.allow], methods: [...before.egress.methods] };
|
|
107
|
+
const allowAdded = [];
|
|
108
|
+
for (const raw of changes.egressAllowAdd ?? []) {
|
|
109
|
+
const host = raw.trim();
|
|
110
|
+
if (host === "" || /[\s/@]/.test(host))
|
|
111
|
+
throw new PolicyWriteError(`"${raw}" is not a host name that egress.allow can hold`);
|
|
112
|
+
if (next.allow.some((h) => h.toLowerCase() === host.toLowerCase()))
|
|
113
|
+
continue;
|
|
114
|
+
next.allow.push(host);
|
|
115
|
+
allowAdded.push(host);
|
|
116
|
+
}
|
|
117
|
+
const methodsAdded = [];
|
|
118
|
+
for (const raw of changes.egressMethodsAdd ?? []) {
|
|
119
|
+
const method = raw.trim().toUpperCase();
|
|
120
|
+
if (!/^[A-Z]{1,16}$/.test(method))
|
|
121
|
+
throw new PolicyWriteError(`"${raw}" is not an HTTP method`);
|
|
122
|
+
if (next.methods.some((m) => m.toUpperCase() === method))
|
|
123
|
+
continue;
|
|
124
|
+
next.methods.push(method);
|
|
125
|
+
methodsAdded.push(method);
|
|
126
|
+
}
|
|
127
|
+
// Checked against the settings page's own schemas, so this path accepts
|
|
128
|
+
// nothing the console could not set one at a time.
|
|
129
|
+
if (allowAdded.length > 0)
|
|
130
|
+
parsePolicySetting("egress.allow", next.allow);
|
|
131
|
+
if (methodsAdded.length > 0)
|
|
132
|
+
parsePolicySetting("egress.methods", next.methods);
|
|
133
|
+
const settings = {};
|
|
134
|
+
for (const [key, value] of Object.entries(changes.egress ?? {})) {
|
|
135
|
+
if (value === undefined)
|
|
136
|
+
continue;
|
|
137
|
+
const path = `egress.${key}`;
|
|
138
|
+
if (key === "allow" || key === "methods" || !Object.hasOwn(POLICY_SETTINGS, path)) {
|
|
139
|
+
throw new PolicyWriteError(`${path} cannot be set here${key === "allow" || key === "methods" ? `; use ${key === "allow" ? "egressAllowAdd" : "egressMethodsAdd"}` : ""}`);
|
|
140
|
+
}
|
|
141
|
+
const parsed = parsePolicySetting(path, value).value;
|
|
142
|
+
if (canonicalJson(before.egress[key]) === canonicalJson(parsed))
|
|
143
|
+
continue;
|
|
144
|
+
next[key] = parsed;
|
|
145
|
+
settings[key] = parsed;
|
|
146
|
+
}
|
|
147
|
+
const changed = allowAdded.length > 0 || methodsAdded.length > 0 || Object.keys(settings).length > 0;
|
|
148
|
+
return { changed, next, allowAdded, methodsAdded, settings };
|
|
149
|
+
}
|
|
150
|
+
/** Grows a list in place where it is already written, so its items' comments stay put. */
|
|
151
|
+
function growList(doc, path, full, added) {
|
|
152
|
+
if (added.length === 0)
|
|
153
|
+
return;
|
|
154
|
+
const node = doc.getIn(path, true);
|
|
155
|
+
if (isSeq(node)) {
|
|
156
|
+
for (const item of added)
|
|
157
|
+
node.add(doc.createNode(item));
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
// Absent: write the whole effective list, defaults included. Writing only
|
|
161
|
+
// the additions would *replace* the defaults (GET, HEAD) with them.
|
|
162
|
+
const created = doc.createNode([...full]);
|
|
163
|
+
created.flow = true;
|
|
164
|
+
doc.setIn(path, created);
|
|
165
|
+
}
|
|
166
|
+
function editEgress(doc, plan) {
|
|
167
|
+
if (!doc.has("egress") || !isMap(doc.get("egress", true))) {
|
|
168
|
+
if (doc.has("egress"))
|
|
169
|
+
throw new PolicyWriteError("egress in the policy file is not a mapping");
|
|
170
|
+
doc.set("egress", doc.createNode({}));
|
|
171
|
+
}
|
|
172
|
+
growList(doc, ["egress", "allow"], plan.next.allow, plan.allowAdded);
|
|
173
|
+
growList(doc, ["egress", "methods"], plan.next.methods, plan.methodsAdded);
|
|
174
|
+
for (const [key, value] of Object.entries(plan.settings)) {
|
|
175
|
+
const node = doc.getIn(["egress", key], true);
|
|
176
|
+
// An existing scalar keeps its node, and with it any comment beside it.
|
|
177
|
+
if (isScalar(node))
|
|
178
|
+
node.value = value;
|
|
179
|
+
else
|
|
180
|
+
doc.setIn(["egress", key], value);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/** A rule this module may overwrite: one a pack or the console wrote, judged by its id. */
|
|
184
|
+
const machineWritten = (rule) => rule.id.startsWith("pack-") || rule.id.startsWith("console-");
|
|
185
|
+
const isLiteral = (match) => !/[*?{},[\]]/.test(match);
|
|
186
|
+
function planRules(before, changes) {
|
|
187
|
+
const next = [...before.rules];
|
|
188
|
+
const steps = [];
|
|
189
|
+
const added = [];
|
|
190
|
+
const replaced = [];
|
|
191
|
+
const skipped = [];
|
|
192
|
+
const seen = new Set();
|
|
193
|
+
for (const input of changes.rules ?? []) {
|
|
194
|
+
const id = typeof input?.id === "string" ? input.id : undefined;
|
|
195
|
+
const existingIndex = id === undefined ? -1 : next.findIndex((r) => r.id === id);
|
|
196
|
+
const existing = existingIndex === -1 ? undefined : next[existingIndex];
|
|
197
|
+
let rule;
|
|
198
|
+
try {
|
|
199
|
+
rule = parseRuleInput(input, existing);
|
|
200
|
+
}
|
|
201
|
+
catch (err) {
|
|
202
|
+
throw new PolicyWriteError(`${id ? `rule "${id}": ` : ""}${err.message}`);
|
|
203
|
+
}
|
|
204
|
+
if (seen.has(rule.id))
|
|
205
|
+
throw new PolicyWriteError(`rule "${rule.id}" is given twice`);
|
|
206
|
+
seen.add(rule.id);
|
|
207
|
+
if (!isLiteral(rule.match)) {
|
|
208
|
+
throw new PolicyWriteError(`rule "${rule.id}" matches "${rule.match}", a pattern; a batch writes rules for exact tool names only`);
|
|
209
|
+
}
|
|
210
|
+
if (existing) {
|
|
211
|
+
if (!machineWritten(existing)) {
|
|
212
|
+
skipped.push({ id: rule.id, why: `a rule with this id was written by hand, so it is left as it is` });
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (canonicalJson(existing) === canonicalJson(rule))
|
|
216
|
+
continue;
|
|
217
|
+
next[existingIndex] = rule;
|
|
218
|
+
steps.push({ kind: "replace", index: existingIndex, rule });
|
|
219
|
+
replaced.push(rule.id);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
const handWritten = next.find((r) => r.match === rule.match && !machineWritten(r));
|
|
223
|
+
if (handWritten) {
|
|
224
|
+
skipped.push({ id: rule.id, why: `rule "${handWritten.id}" already decides ${rule.match}, and a person's rule wins` });
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
// Above the first rule that would otherwise decide this tool, so the new
|
|
228
|
+
// one is the one consulted. No existing rule moves relative to another.
|
|
229
|
+
const at = next.findIndex((r) => globMatch(r.match, rule.match));
|
|
230
|
+
const index = at === -1 ? next.length : at;
|
|
231
|
+
next.splice(index, 0, rule);
|
|
232
|
+
steps.push({ kind: "insert", index, rule });
|
|
233
|
+
added.push(rule.id);
|
|
234
|
+
}
|
|
235
|
+
return { changed: steps.length > 0, next, steps, added, replaced, skipped };
|
|
236
|
+
}
|
|
237
|
+
function ruleNode(rule) {
|
|
238
|
+
const parsed = parseDocument(ruleToYaml(rule, "")).contents;
|
|
239
|
+
if (!isSeq(parsed) || parsed.items.length !== 1)
|
|
240
|
+
throw new PolicyWriteError(`could not write rule "${rule.id}"`);
|
|
241
|
+
return parsed.items[0];
|
|
242
|
+
}
|
|
243
|
+
function editRules(doc, before, plan, comment) {
|
|
244
|
+
let seq = doc.get("rules", true);
|
|
245
|
+
if (seq === undefined || (isScalar(seq) && seq.value === null)) {
|
|
246
|
+
seq = new YAMLSeq();
|
|
247
|
+
doc.set("rules", seq);
|
|
248
|
+
}
|
|
249
|
+
if (!isSeq(seq))
|
|
250
|
+
throw new PolicyWriteError("rules in the policy file is not a list");
|
|
251
|
+
// Steps index into the rule list as it grows, which is the YAML list as long
|
|
252
|
+
// as the two started out the same length -- true unless the file uses
|
|
253
|
+
// anchors or merge keys in its rules, which a person would have to edit.
|
|
254
|
+
if (seq.items.length !== before.rules.length) {
|
|
255
|
+
throw new PolicyWriteError("the rules in this file are not one list entry per rule, so they cannot be edited here");
|
|
256
|
+
}
|
|
257
|
+
// A one-line `rules: []` becomes a block list: rules are read by people.
|
|
258
|
+
seq.flow = false;
|
|
259
|
+
const note = comment?.replace(/[\r\n]+/g, " ").trim();
|
|
260
|
+
for (const step of plan.steps) {
|
|
261
|
+
const node = ruleNode(step.rule);
|
|
262
|
+
if (step.kind === "replace") {
|
|
263
|
+
const old = seq.items[step.index];
|
|
264
|
+
if (old?.commentBefore)
|
|
265
|
+
node.commentBefore = old.commentBefore;
|
|
266
|
+
seq.items[step.index] = node;
|
|
267
|
+
}
|
|
268
|
+
else {
|
|
269
|
+
if (note)
|
|
270
|
+
node.commentBefore = ` ${note}`;
|
|
271
|
+
/*
|
|
272
|
+
* The parser hangs a comment above the first entry on the list itself,
|
|
273
|
+
* not on that entry. Inserting a new first entry would leave the comment
|
|
274
|
+
* describing the wrong rule, so it moves down with the entry it was
|
|
275
|
+
* written above.
|
|
276
|
+
*/
|
|
277
|
+
if (step.index === 0 && seq.items.length > 0 && seq.commentBefore) {
|
|
278
|
+
const first = seq.items[0];
|
|
279
|
+
first.commentBefore = first.commentBefore ? `${seq.commentBefore}\n${first.commentBefore}` : seq.commentBefore;
|
|
280
|
+
seq.commentBefore = undefined;
|
|
281
|
+
}
|
|
282
|
+
seq.items.splice(step.index, 0, node);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Reads policy.yaml, applies the batch, refuses a loosening that was not
|
|
288
|
+
* acknowledged, and writes the result atomically (temp file and rename, so a
|
|
289
|
+
* gateway polling the file never reads half of it).
|
|
290
|
+
*
|
|
291
|
+
* `expectedDigest`, when given, is the digest the person was shown; a policy
|
|
292
|
+
* changed since is `stale` rather than silently edited on top of.
|
|
293
|
+
*/
|
|
294
|
+
export function writePolicyBatch(options) {
|
|
295
|
+
if (options.writesAllowed === false) {
|
|
296
|
+
return {
|
|
297
|
+
kind: "refused",
|
|
298
|
+
why: "this gateway has `policy_writes: false` in its config, so policy may only change with a deployment."
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
const full = expandPath(options.policyPath);
|
|
302
|
+
let text;
|
|
303
|
+
try {
|
|
304
|
+
text = readFileSync(full, "utf8");
|
|
305
|
+
}
|
|
306
|
+
catch (err) {
|
|
307
|
+
return { kind: "refused", why: `cannot read ${options.policyPath}: ${err.message}` };
|
|
308
|
+
}
|
|
309
|
+
let result;
|
|
310
|
+
try {
|
|
311
|
+
result = applyPolicyBatch(text, options.changes);
|
|
312
|
+
}
|
|
313
|
+
catch (err) {
|
|
314
|
+
return { kind: "refused", why: err.message };
|
|
315
|
+
}
|
|
316
|
+
if (options.expectedDigest !== undefined && options.expectedDigest !== result.previousDigest) {
|
|
317
|
+
return {
|
|
318
|
+
kind: "stale",
|
|
319
|
+
expected: options.expectedDigest,
|
|
320
|
+
actual: result.previousDigest,
|
|
321
|
+
why: `${options.policyPath} has changed since it was read. Re-read it and choose again.`
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
if (!result.changed)
|
|
325
|
+
return { kind: "unchanged", ...result };
|
|
326
|
+
if (result.loosens.length > 0) {
|
|
327
|
+
const what = `This loosens the policy: ${result.loosens.join("; ")}`;
|
|
328
|
+
if (options.overridesAllowed === false) {
|
|
329
|
+
return {
|
|
330
|
+
kind: "refused",
|
|
331
|
+
why: `${what}. This gateway has \`policy_overrides: false\`, so the console may tighten its policy but not loosen it.`
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
if (!options.acknowledged?.loosens) {
|
|
335
|
+
return { kind: "refused", needs: "loosens", why: `${what}. That has to be confirmed first.` };
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
writeAtomically(full, result.text);
|
|
339
|
+
return { kind: "written", ...result };
|
|
340
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { type Policy } from "./policy.js";
|
|
2
|
+
/**
|
|
3
|
+
* The policy a running gateway is enforcing, and the one narrow way it can
|
|
4
|
+
* change without a restart.
|
|
5
|
+
*
|
|
6
|
+
* The problem this solves is an asymmetry: the console's exposure switch takes
|
|
7
|
+
* effect on the next call, because it is a row in a database both processes
|
|
8
|
+
* read, while tightening an argument bound meant editing `policy.yaml` and
|
|
9
|
+
* restarting. So the fastest control was the blunt one -- switch the whole tool
|
|
10
|
+
* off -- and the precise one was the slow one. An operator reacting to
|
|
11
|
+
* something in production reaches for whichever works now.
|
|
12
|
+
*
|
|
13
|
+
* Three properties make this safe enough to be on by default:
|
|
14
|
+
*
|
|
15
|
+
* 1. **It is all-or-nothing.** A reload either replaces the policy or keeps the
|
|
16
|
+
* one already in force. There is no state in which half of a policy file is
|
|
17
|
+
* being enforced.
|
|
18
|
+
* 2. **It fails closed.** A policy file that does not parse, or does not
|
|
19
|
+
* validate, leaves the previous policy enforcing. An empty or half-written
|
|
20
|
+
* file -- which is what a reader sees mid-save -- can never be read as
|
|
21
|
+
* "allow everything", because it is not a valid policy at all.
|
|
22
|
+
* 3. **It refuses what it cannot actually apply.** Most of a policy is consumed
|
|
23
|
+
* once, at startup: the audit log holds `audit`, the approvals database is opened from
|
|
24
|
+
* `approvals.store_path`, the tenant is resolved from `tenant`. Swapping the
|
|
25
|
+
* policy object would leave those reading the old values while the rules
|
|
26
|
+
* read the new ones, and the console would show the new digest for a process
|
|
27
|
+
* enforcing a mixture. So a change to any of them is refused in full and
|
|
28
|
+
* reported as needing a restart, rather than partly applied.
|
|
29
|
+
*
|
|
30
|
+
* What is left -- the live set below -- is the posture, the rules, the
|
|
31
|
+
* approval mode and the network rules. Which is to say: every argument bound,
|
|
32
|
+
* what happens to a call outside one, and where the gateway may connect.
|
|
33
|
+
*
|
|
34
|
+
* `egress` joined the live set so that adding a remote server from the console
|
|
35
|
+
* takes effect without restarting every AI app. It is live only because the
|
|
36
|
+
* holder of the guard applies it: on an `applied` reload with `egressChanged`,
|
|
37
|
+
* the gateway calls `EgressGuard.reconfigure(policy.egress)` in the same
|
|
38
|
+
* synchronous step that adopts the policy, so no call sees the new rules with
|
|
39
|
+
* the old allowlist or the other way round.
|
|
40
|
+
*
|
|
41
|
+
* Since classification landed, this file has writers other than a person in an
|
|
42
|
+
* editor: the console and `hmcp-gateway rule` write a rule through
|
|
43
|
+
* `policy-write.ts`. That is what the atomic rename in `writeAtomically` and
|
|
44
|
+
* the inode in `stamp()` below are an agreement about -- the safe way to
|
|
45
|
+
* replace a config file is a temporary file and a rename, and a watch that
|
|
46
|
+
* followed the inode would be left pointing at a file nobody writes again.
|
|
47
|
+
*/
|
|
48
|
+
/**
|
|
49
|
+
* The fields a reload may change, because every consumer of them reads them per
|
|
50
|
+
* call rather than at startup.
|
|
51
|
+
*
|
|
52
|
+
* This list is the contract. Adding a field here is a claim that nothing
|
|
53
|
+
* captures it at construction time. "The live/pinned contract" in
|
|
54
|
+
* `policy-source.test.ts` keeps that claim honest in both directions: it
|
|
55
|
+
* requires a case for every field named here, and it checks that every other
|
|
56
|
+
* field refuses a reload instead of being half-applied.
|
|
57
|
+
*/
|
|
58
|
+
export declare const LIVE_POLICY_FIELDS: readonly ["enforcement", "defaults", "rules", "approvals.mode", "approvals.ttl_seconds", "approvals.single_use", "egress"];
|
|
59
|
+
/** The administrative act of adopting a new policy. In the hash chain, so stable. */
|
|
60
|
+
export declare const POLICY_RELOAD_RULE = "policy.reload";
|
|
61
|
+
/**
|
|
62
|
+
* A reload changed how one or more tools are classified.
|
|
63
|
+
*
|
|
64
|
+
* Separate from `policy.reload` because it is a different fact: the reload
|
|
65
|
+
* record says a process adopted a file, this one says the adoption moved a
|
|
66
|
+
* tool out of (or into) the refused-by-default state. For the common case --
|
|
67
|
+
* someone classified a tool nothing classified -- this is the record that
|
|
68
|
+
* shows the tool becoming reachable.
|
|
69
|
+
*/
|
|
70
|
+
export declare const POLICY_RECLASSIFY_RULE = "policy.reclassify";
|
|
71
|
+
/** A policy change this process read and did not adopt, with the reason why. */
|
|
72
|
+
export declare const POLICY_RELOAD_REFUSED_RULE = "policy.reload-refused";
|
|
73
|
+
export type PolicyReload =
|
|
74
|
+
/** The file has not changed, or changed in no way that matters. */
|
|
75
|
+
{
|
|
76
|
+
readonly kind: "unchanged";
|
|
77
|
+
}
|
|
78
|
+
/** The new policy is in force from the next call. */
|
|
79
|
+
| {
|
|
80
|
+
readonly kind: "applied";
|
|
81
|
+
readonly from: string;
|
|
82
|
+
readonly to: string;
|
|
83
|
+
readonly summary: string;
|
|
84
|
+
/**
|
|
85
|
+
* The network rules changed. Whoever holds the egress guard must call
|
|
86
|
+
* `reconfigure(source.current().egress)` -- the policy object alone does
|
|
87
|
+
* not reach a guard built at startup.
|
|
88
|
+
*/
|
|
89
|
+
readonly egressChanged: boolean;
|
|
90
|
+
}
|
|
91
|
+
/** The file is unreadable or invalid. The previous policy is still in force. */
|
|
92
|
+
| {
|
|
93
|
+
readonly kind: "invalid";
|
|
94
|
+
readonly error: string;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Valid, but changes something this process consumed at startup. The previous
|
|
98
|
+
* policy is still in force and the change needs a restart.
|
|
99
|
+
*/
|
|
100
|
+
| {
|
|
101
|
+
readonly kind: "needs-restart";
|
|
102
|
+
readonly fields: readonly string[];
|
|
103
|
+
};
|
|
104
|
+
export interface PolicySourceOptions {
|
|
105
|
+
/**
|
|
106
|
+
* The policy file. Absent for a policy written inline in `gateway.yaml`,
|
|
107
|
+
* which cannot be reloaded: the rest of that file configures things this
|
|
108
|
+
* process consumed at startup, so re-reading it would mean a restart anyway.
|
|
109
|
+
*/
|
|
110
|
+
readonly path?: string | undefined;
|
|
111
|
+
/** Base for a relative path, as the config loader resolved it. */
|
|
112
|
+
readonly cwd?: string | undefined;
|
|
113
|
+
/** Overridable for tests. */
|
|
114
|
+
readonly now?: () => number;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Holds the policy in force and reloads it from disk on request.
|
|
118
|
+
*
|
|
119
|
+
* `current()` returns a snapshot. Callers deciding one call take that snapshot
|
|
120
|
+
* once and use it throughout, so a reload landing mid-call cannot have the
|
|
121
|
+
* classification read one policy and the rules another.
|
|
122
|
+
*/
|
|
123
|
+
export declare class PolicySource {
|
|
124
|
+
private policy;
|
|
125
|
+
private readonly file;
|
|
126
|
+
private last;
|
|
127
|
+
private timer;
|
|
128
|
+
constructor(initial: Policy, options?: PolicySourceOptions);
|
|
129
|
+
/** The policy in force. A snapshot: safe to hold for the length of one call. */
|
|
130
|
+
current(): Policy;
|
|
131
|
+
digest(): string;
|
|
132
|
+
/** The file being watched, or null for an inline policy. */
|
|
133
|
+
get path(): string | null;
|
|
134
|
+
/** True when this policy could be reloaded at all. */
|
|
135
|
+
get reloadable(): boolean;
|
|
136
|
+
/**
|
|
137
|
+
* Re-reads the file and adopts it if it is valid and adoptable.
|
|
138
|
+
*
|
|
139
|
+
* Parsing happens before anything is replaced, so an invalid file costs
|
|
140
|
+
* nothing: `this.policy` is only assigned once there is a complete,
|
|
141
|
+
* validated policy to assign.
|
|
142
|
+
*/
|
|
143
|
+
reload(): PolicyReload;
|
|
144
|
+
/**
|
|
145
|
+
* Polls for a change and reloads when one appears.
|
|
146
|
+
*
|
|
147
|
+
* Polling rather than `fs.watch`: a watch on a *file* follows the inode, and
|
|
148
|
+
* the safe way to write a config file is to write a temporary one and rename
|
|
149
|
+
* it over the original -- which is what every editor and every deploy tool
|
|
150
|
+
* does, and which leaves a watch pointing at a file nobody will write again.
|
|
151
|
+
* A stat compares the inode too, so a rename is a change here rather than
|
|
152
|
+
* silence.
|
|
153
|
+
*
|
|
154
|
+
* The timer is unreferenced, so watching never keeps the process alive on its
|
|
155
|
+
* own.
|
|
156
|
+
*/
|
|
157
|
+
watch(onReload: (result: PolicyReload) => void, intervalMs?: number): () => void;
|
|
158
|
+
stop(): void;
|
|
159
|
+
}
|
|
160
|
+
/** Rendered for a log line or an audit reason. */
|
|
161
|
+
export declare function describeReload(result: PolicyReload): string;
|