hmcp-core 0.0.1 → 0.2.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 +297 -0
- package/dist/audit.js +524 -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 +386 -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,1697 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
|
+
import { Document, isMap, isScalar, isSeq, parseDocument, YAMLMap, YAMLSeq } from "yaml";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { parseArgPath } from "./argpath.js";
|
|
6
|
+
import { canonicalJson } from "./canonical.js";
|
|
7
|
+
import { classifyByName } from "./classify-name.js";
|
|
8
|
+
import { decide } from "./decide.js";
|
|
9
|
+
import { globMatch } from "./glob.js";
|
|
10
|
+
import { ArgConstraintSchema, DecisionKindSchema, EffectSchema, expandPath, parsePolicy, PostureSchema, RuleSchema } from "./policy.js";
|
|
11
|
+
import { policyDigest } from "./runtime-state.js";
|
|
12
|
+
/**
|
|
13
|
+
* The per-tool rule a reviewer writes from the console or the CLI: what one
|
|
14
|
+
* tool is, what happens when it is called, and the bounds that qualify it.
|
|
15
|
+
*
|
|
16
|
+
* Why this exists. The product's defaults are good — reads run, writes wait for
|
|
17
|
+
* a human, deletes and unclassified tools are refused — but they were only ever
|
|
18
|
+
* defaults, with no way to depart from them short of hand-writing YAML, and the
|
|
19
|
+
* console said so next to every refused tool. Hand-writing has a trap too: a
|
|
20
|
+
* rule matching an unclassified tool with a `decision` and no `effect` changes
|
|
21
|
+
* nothing, because `resolveEffect` reads the matching rule's own `effect` and
|
|
22
|
+
* `decide()`'s unclassified branch returns before any rule is consulted.
|
|
23
|
+
*
|
|
24
|
+
* Why it writes the *file* rather than rows in the approvals database. The
|
|
25
|
+
* exposure switch is allowed to live in that database because it can only
|
|
26
|
+
* subtract: "off, for this one tool" is the only state it stores. This is
|
|
27
|
+
* additive — it is what makes a refused call reachable — so that argument does
|
|
28
|
+
* not carry. And `policy.yaml` is the artifact the product tells people to
|
|
29
|
+
* review in git; a second, hidden store would mean the Policy page, `hmcp
|
|
30
|
+
* policy` and `git diff` no longer describe what is enforced. The reload
|
|
31
|
+
* machinery adopts a written rule within about a second, fails closed on a
|
|
32
|
+
* half-written file, and audits every outcome.
|
|
33
|
+
*
|
|
34
|
+
* ## What this is forbidden to do
|
|
35
|
+
*
|
|
36
|
+
* Enforced here and checked per write by `assertOnlyOwnRuleChanged` and
|
|
37
|
+
* `assertOnlyRulesChanged`, not promised in prose:
|
|
38
|
+
*
|
|
39
|
+
* - it adds, rewrites or removes exactly **one** rule, the one whose id is
|
|
40
|
+
* `console-<tool>` and whose `match` is the literal `<tool>`. Such a rule is
|
|
41
|
+
* by construction about one tool, so writing it cannot change another tool's
|
|
42
|
+
* verdict — which `assertNoCollateralChange` then proves against the live
|
|
43
|
+
* tool list rather than assuming;
|
|
44
|
+
* - every other rule keeps its value **and its position**. An update never
|
|
45
|
+
* reorders; if a human has inserted a rule above ours that also matches the
|
|
46
|
+
* tool, the update is refused rather than quietly moved up;
|
|
47
|
+
* - the reserved id is not a licence. A rule sitting at `console-<tool>` is
|
|
48
|
+
* rewritten only if it is also *shaped* like one of ours — see `ownsRule`.
|
|
49
|
+
* Anything else is refused, naming the field, so a hand-edited rule is
|
|
50
|
+
* neither clobbered nor silently ignored;
|
|
51
|
+
* - nothing outside `rules` changes, except `defaults.on_unclassified` through
|
|
52
|
+
* its own function below. That is checked structurally rather than by a
|
|
53
|
+
* denylist of `egress`/`tenant`/`audit`/`approvals`/`tool_budget`, so it
|
|
54
|
+
* cannot go stale when `PolicySchema` grows a field;
|
|
55
|
+
* - `pattern` and `coerce` are never written. See `REFUSED_CONSTRAINTS`;
|
|
56
|
+
* - a policy inlined in `gateway.yaml` is refused: that file configures child
|
|
57
|
+
* processes and transports an edit cannot touch and no reload can adopt.
|
|
58
|
+
*
|
|
59
|
+
* ## What it *can* do, said plainly
|
|
60
|
+
*
|
|
61
|
+
* This can widen a permission. A refused `delete_*` tool can be made to run
|
|
62
|
+
* unasked. What stands in the way is not a refusal but visibility: the change
|
|
63
|
+
* is previewed against the real `decide()` first, lands as a readable line in
|
|
64
|
+
* a reviewed file, carries the actor and the overridden rule's own words in
|
|
65
|
+
* the audit log, and trips HMCP001 on the console's own Findings page the
|
|
66
|
+
* moment it leaves a write or destructive tool reachable. A deployment that
|
|
67
|
+
* does not want that sets `policy_overrides: false` and keeps the narrow,
|
|
68
|
+
* classify-only behaviour.
|
|
69
|
+
*/
|
|
70
|
+
/** A per-tool rule was written. */
|
|
71
|
+
export const TOOL_RULE_SET = "policy.tool-rule.set";
|
|
72
|
+
/** An existing per-tool rule was rewritten. */
|
|
73
|
+
export const TOOL_RULE_UPDATE = "policy.tool-rule.update";
|
|
74
|
+
/** A per-tool rule was removed, handing the tool back to the rest of the policy. */
|
|
75
|
+
export const TOOL_RULE_CLEAR = "policy.tool-rule.clear";
|
|
76
|
+
/**
|
|
77
|
+
* A write this module refused.
|
|
78
|
+
*
|
|
79
|
+
* Wired up, unlike its predecessor, which was exported and never emitted. A
|
|
80
|
+
* refused attempt to override a human's refusal is precisely the record a
|
|
81
|
+
* security log should carry; without it that attempt is a 422 and nothing else.
|
|
82
|
+
*/
|
|
83
|
+
export const TOOL_RULE_REFUSED = "policy.tool-rule.refused";
|
|
84
|
+
/** A change to `defaults.on_unclassified`. */
|
|
85
|
+
export const UNCLASSIFIED_POSTURE_RULE = "policy.unclassified-posture";
|
|
86
|
+
/** The id prefix this module reserves. */
|
|
87
|
+
const RULE_PREFIX = "console-";
|
|
88
|
+
/**
|
|
89
|
+
* Metacharacters `globToRegExp` reads. A tool whose name contains one cannot be
|
|
90
|
+
* written as a literal `match`, because the rule would match a *set* of names —
|
|
91
|
+
* possibly including names that do not exist yet.
|
|
92
|
+
*/
|
|
93
|
+
const GLOB_METACHARACTERS = ["*", "?", "{", "}", ","];
|
|
94
|
+
/**
|
|
95
|
+
* Constraints this writer will not author, whatever asks it to.
|
|
96
|
+
*
|
|
97
|
+
* `pattern` is the one that matters. `checkConstraint` builds `new
|
|
98
|
+
* RegExp(c.pattern)` and runs it **on every call to the tool**, inside
|
|
99
|
+
* `decide()`, which is synchronous and on the hot path. An unparseable pattern
|
|
100
|
+
* already fails closed; one that backtracks catastrophically does not. Letting
|
|
101
|
+
* a regex be typed into a browser form and installed into the enforcement path
|
|
102
|
+
* is a denial-of-service surface that "edit it in git" previously covered, and
|
|
103
|
+
* no confirmation checkbox substitutes for review there. If it is wanted later
|
|
104
|
+
* it needs a linear-time matcher or a complexity budget, which is its own job.
|
|
105
|
+
*
|
|
106
|
+
* `coerce` exists to accept a non-number as a number; it is the opposite of a
|
|
107
|
+
* bound and cannot be a checkbox. `required` collides with `optional` — the
|
|
108
|
+
* policy loader rejects a rule carrying both — and is a presence assertion
|
|
109
|
+
* rather than a bound.
|
|
110
|
+
*
|
|
111
|
+
* A rule that *already* carries one of these is carried over untouched and
|
|
112
|
+
* reported read-only. Refusing to author one must never become quietly
|
|
113
|
+
* dropping one, which is the same failure as not carrying bounds at all.
|
|
114
|
+
*/
|
|
115
|
+
const REFUSED_CONSTRAINTS = ["pattern", "coerce", "required"];
|
|
116
|
+
/**
|
|
117
|
+
* How a *rule* is serialised. Never the whole document — see `spliceRule`.
|
|
118
|
+
*
|
|
119
|
+
* `lineWidth: 0` disables folding, so a long reason is one line rather than
|
|
120
|
+
* wrapped at some column nobody chose.
|
|
121
|
+
*/
|
|
122
|
+
const TO_STRING = { lineWidth: 0 };
|
|
123
|
+
/** Caps, so a rule stays something a person can read in a diff. */
|
|
124
|
+
const MAX_ARG_PATHS = 32;
|
|
125
|
+
const MAX_PATH_LENGTH = 200;
|
|
126
|
+
const MAX_ENUM_MEMBERS = 64;
|
|
127
|
+
/** The plain-language choices, so the file's comment says what was picked. */
|
|
128
|
+
export const EFFECT_PROSE = {
|
|
129
|
+
read: "it only reads or looks things up",
|
|
130
|
+
write: "it changes or creates something",
|
|
131
|
+
destructive: "it deletes or removes something"
|
|
132
|
+
};
|
|
133
|
+
export const DECISION_PROSE = {
|
|
134
|
+
allow: "run it without asking",
|
|
135
|
+
approve: "ask a human first, every time",
|
|
136
|
+
deny: "never allow it"
|
|
137
|
+
};
|
|
138
|
+
const AcknowledgedSchema = z
|
|
139
|
+
.object({
|
|
140
|
+
overrideDeny: z.string().max(200).optional(),
|
|
141
|
+
dropBounds: z.boolean().optional(),
|
|
142
|
+
destructiveAllow: z.boolean().optional()
|
|
143
|
+
})
|
|
144
|
+
.strict();
|
|
145
|
+
export const ToolRuleDraftSchema = z
|
|
146
|
+
.object({
|
|
147
|
+
tool: z.string().min(1).max(200),
|
|
148
|
+
effect: EffectSchema,
|
|
149
|
+
decision: DecisionKindSchema,
|
|
150
|
+
args: z.record(z.string(), ArgConstraintSchema).optional(),
|
|
151
|
+
on_violation: DecisionKindSchema.exclude(["allow"]).optional(),
|
|
152
|
+
unknown_args: z.enum(["allow", "deny", "approve"]).optional(),
|
|
153
|
+
reason: z.string().max(500).optional(),
|
|
154
|
+
actor: z.string().min(1).max(200),
|
|
155
|
+
/** Where the rule was set from, for the comment above it. Defaults to the console. */
|
|
156
|
+
via: z.string().min(1).max(100).optional(),
|
|
157
|
+
acknowledged: AcknowledgedSchema.optional()
|
|
158
|
+
})
|
|
159
|
+
.strict();
|
|
160
|
+
export class PolicyWriteError extends Error {
|
|
161
|
+
constructor(message) {
|
|
162
|
+
super(message);
|
|
163
|
+
this.name = "PolicyWriteError";
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
export function parseToolRuleDraft(input) {
|
|
167
|
+
const result = ToolRuleDraftSchema.safeParse(input);
|
|
168
|
+
if (!result.success) {
|
|
169
|
+
const detail = result.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
|
|
170
|
+
throw new PolicyWriteError(`invalid rule: ${detail}`);
|
|
171
|
+
}
|
|
172
|
+
const draft = result.data;
|
|
173
|
+
for (const ch of GLOB_METACHARACTERS) {
|
|
174
|
+
if (draft.tool.includes(ch)) {
|
|
175
|
+
throw new PolicyWriteError(`"${draft.tool}" contains ${JSON.stringify(ch)}, which policy reads as a glob — ` +
|
|
176
|
+
`a rule written from here must name exactly one tool, so this one has to be written by hand`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const paths = Object.keys(draft.args ?? {});
|
|
180
|
+
if (paths.length > MAX_ARG_PATHS) {
|
|
181
|
+
throw new PolicyWriteError(`a rule written from here bounds at most ${MAX_ARG_PATHS} arguments; this one bounds ${paths.length}. ` +
|
|
182
|
+
`A rule nobody can read in a diff is not reviewable, which is the reason for writing to the file at all.`);
|
|
183
|
+
}
|
|
184
|
+
for (const path of paths) {
|
|
185
|
+
if (path.length > MAX_PATH_LENGTH) {
|
|
186
|
+
throw new PolicyWriteError(`the argument path "${path.slice(0, 40)}…" is longer than ${MAX_PATH_LENGTH} characters`);
|
|
187
|
+
}
|
|
188
|
+
/*
|
|
189
|
+
* Refused here rather than at load. `PolicySchema.superRefine` would catch
|
|
190
|
+
* it too, but its message names a rule index in a file instead of the box
|
|
191
|
+
* the person typed into — and an unwritable bound reads as protection while
|
|
192
|
+
* providing none.
|
|
193
|
+
*/
|
|
194
|
+
// `parseArgPath` reports rather than throws; reading it as a throwing call
|
|
195
|
+
// is how an unwritable bound reaches the file and reads as protection.
|
|
196
|
+
const parsed = parseArgPath(path);
|
|
197
|
+
if (!parsed.ok)
|
|
198
|
+
throw new PolicyWriteError(`"${path}" is not an argument path: ${parsed.error}`);
|
|
199
|
+
const constraint = draft.args[path];
|
|
200
|
+
for (const banned of REFUSED_CONSTRAINTS) {
|
|
201
|
+
if (constraint[banned] !== undefined) {
|
|
202
|
+
throw new PolicyWriteError(refusedConstraintReason(banned, path));
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (Array.isArray(constraint["enum"]) && constraint["enum"].length > MAX_ENUM_MEMBERS) {
|
|
206
|
+
throw new PolicyWriteError(`"${path}" lists more than ${MAX_ENUM_MEMBERS} allowed values`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return draft;
|
|
210
|
+
}
|
|
211
|
+
function refusedConstraintReason(name, path) {
|
|
212
|
+
if (name === "pattern") {
|
|
213
|
+
return (`a rule written from here cannot set a regular expression on "${path}". Policy runs the pattern on ` +
|
|
214
|
+
`every call to the tool, inside the synchronous decision, so a pattern that backtracks badly would ` +
|
|
215
|
+
`slow or stall every call — which is a thing to review in git rather than to type into a form.`);
|
|
216
|
+
}
|
|
217
|
+
if (name === "coerce") {
|
|
218
|
+
return (`a rule written from here cannot set "coerce" on "${path}". It makes a bound accept a value that is ` +
|
|
219
|
+
`not a number by converting it, which is the opposite of what a bound is for.`);
|
|
220
|
+
}
|
|
221
|
+
return (`a rule written from here cannot set "required" on "${path}". Use "absence is fine" (optional) to say ` +
|
|
222
|
+
`a bound tolerates the argument being missing; the two cannot both be set and policy rejects a file ` +
|
|
223
|
+
`that does.`);
|
|
224
|
+
}
|
|
225
|
+
/** The rule id for one tool. Stable, so a second change rewrites rather than duplicating. */
|
|
226
|
+
export function ruleIdFor(tool) {
|
|
227
|
+
return `${RULE_PREFIX}${tool}`;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Whether this module may rewrite or remove the rule sitting at our reserved id.
|
|
231
|
+
*
|
|
232
|
+
* The id alone is forgeable — a person can type `console-notes__delete` by hand
|
|
233
|
+
* — so the id is not the authority. What makes a rewrite safe is a *shape*
|
|
234
|
+
* check: the rule must name exactly this one tool literally, and must carry
|
|
235
|
+
* only fields and values this writer can itself emit. The round trip is the
|
|
236
|
+
* test, rather than a field list, so it cannot drift from what the writer
|
|
237
|
+
* actually produces.
|
|
238
|
+
*
|
|
239
|
+
* The point is not to detect a forgery. It is to make the failure safe: a rule
|
|
240
|
+
* at our id that we did not shape is neither clobbered nor silently ignored —
|
|
241
|
+
* `writeToolRule` refuses and names the field, and a human who meant to own it
|
|
242
|
+
* can rename it.
|
|
243
|
+
*/
|
|
244
|
+
export function ownsRule(rule, tool) {
|
|
245
|
+
if (rule.id !== ruleIdFor(tool))
|
|
246
|
+
return { ok: false, why: `its id is "${rule.id}"` };
|
|
247
|
+
if (rule.match !== tool) {
|
|
248
|
+
return { ok: false, why: `it matches "${rule.match}" rather than this tool's name exactly` };
|
|
249
|
+
}
|
|
250
|
+
if (rule.effect === undefined)
|
|
251
|
+
return { ok: false, why: "it carries no effect" };
|
|
252
|
+
for (const [path, constraint] of Object.entries(rule.args ?? {})) {
|
|
253
|
+
for (const banned of REFUSED_CONSTRAINTS) {
|
|
254
|
+
if (constraint[banned] !== undefined) {
|
|
255
|
+
return { ok: false, why: `it sets "${banned}" on "${path}", which this console never writes` };
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return { ok: true };
|
|
260
|
+
}
|
|
261
|
+
/** Our rule for this tool, if there is one at all (conformant or not). */
|
|
262
|
+
function ruleAtOurId(policy, tool) {
|
|
263
|
+
return policy.rules.find((r) => r.id === ruleIdFor(tool));
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* The rule that decides this tool when ours is not there — whose bounds must be
|
|
267
|
+
* carried, and above which the new rule is placed.
|
|
268
|
+
*/
|
|
269
|
+
function governingRule(policy, tool) {
|
|
270
|
+
return policy.rules.find((r) => r.id !== ruleIdFor(tool) && globMatch(r.match, tool));
|
|
271
|
+
}
|
|
272
|
+
function resolveDraft(policy, draft) {
|
|
273
|
+
const governing = governingRule(policy, draft.tool);
|
|
274
|
+
const carry = governing !== undefined && draft.args === undefined;
|
|
275
|
+
const args = draft.args ?? (carry ? governing.args : undefined);
|
|
276
|
+
const onViolation = draft.on_violation ?? (carry ? governing.on_violation : undefined);
|
|
277
|
+
const unknownArgs = draft.unknown_args ?? (carry ? governing.unknown_args : undefined);
|
|
278
|
+
const rule = {
|
|
279
|
+
id: ruleIdFor(draft.tool),
|
|
280
|
+
match: draft.tool,
|
|
281
|
+
effect: draft.effect,
|
|
282
|
+
decision: draft.decision,
|
|
283
|
+
on_violation: onViolation ?? "deny",
|
|
284
|
+
unknown_args: unknownArgs ?? "allow",
|
|
285
|
+
...(args && Object.keys(args).length > 0 ? { args } : {}),
|
|
286
|
+
...(draft.reason ? { reason: draft.reason } : {})
|
|
287
|
+
};
|
|
288
|
+
const carriedFrom = carry && hasBounds(governing) ? governing.id : null;
|
|
289
|
+
return { rule, carriedFrom };
|
|
290
|
+
}
|
|
291
|
+
function hasBounds(rule) {
|
|
292
|
+
if (!rule)
|
|
293
|
+
return false;
|
|
294
|
+
return Object.keys(rule.args ?? {}).length > 0 || rule.unknown_args !== "allow";
|
|
295
|
+
}
|
|
296
|
+
/** The rule a draft becomes, with anything it left unsaid carried from the policy. */
|
|
297
|
+
export function ruleFor(policy, draft) {
|
|
298
|
+
return resolveDraft(policy, draft).rule;
|
|
299
|
+
}
|
|
300
|
+
export function boundsOf(rule) {
|
|
301
|
+
if (!rule)
|
|
302
|
+
return null;
|
|
303
|
+
const paths = Object.keys(rule.args ?? {});
|
|
304
|
+
if (paths.length === 0 && rule.unknown_args === "allow")
|
|
305
|
+
return null;
|
|
306
|
+
return {
|
|
307
|
+
paths,
|
|
308
|
+
constraints: rule.args ?? {},
|
|
309
|
+
onViolation: rule.on_violation,
|
|
310
|
+
unknownArgs: rule.unknown_args
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
const RANK = { deny: 0, approve: 1, allow: 2 };
|
|
314
|
+
/**
|
|
315
|
+
* Where the rule goes so it actually takes effect.
|
|
316
|
+
*
|
|
317
|
+
* Rules are first-match-wins, so appending at the end lands it behind any
|
|
318
|
+
* earlier glob that also matches — `"*__{create,update}_*"` is in the shipped
|
|
319
|
+
* example and matches plenty — and a rule never consulted is the same silent
|
|
320
|
+
* no-op as a rule with no `effect`. So it goes immediately *above* the first
|
|
321
|
+
* other rule that matches, and at the end when nothing does. This only ever
|
|
322
|
+
* moves our own rule; no existing rule changes position relative to another.
|
|
323
|
+
*/
|
|
324
|
+
function placement(policy, tool) {
|
|
325
|
+
const at = policy.rules.findIndex((r) => r.id !== ruleIdFor(tool) && globMatch(r.match, tool));
|
|
326
|
+
return at === -1 ? policy.rules.length : at;
|
|
327
|
+
}
|
|
328
|
+
export function previewToolRule(args) {
|
|
329
|
+
const { policy, draft } = args;
|
|
330
|
+
const { rule, carriedFrom } = resolveDraft(policy, draft);
|
|
331
|
+
const existing = ruleAtOurId(policy, draft.tool) ?? null;
|
|
332
|
+
const governing = governingRule(policy, draft.tool);
|
|
333
|
+
const without = policy.rules.filter((r) => r.id !== ruleIdFor(draft.tool));
|
|
334
|
+
const index = existing
|
|
335
|
+
? policy.rules.indexOf(existing)
|
|
336
|
+
: placement({ ...policy, rules: without }, draft.tool);
|
|
337
|
+
const rules = [...without];
|
|
338
|
+
rules.splice(Math.min(index, rules.length), 0, rule);
|
|
339
|
+
const candidate = { ...policy, rules };
|
|
340
|
+
const ask = (p) => decide({ tool: draft.tool, policy: p, argsUnknown: true, disabled: args.disabled });
|
|
341
|
+
const current = ask(policy);
|
|
342
|
+
const verdict = ask(candidate);
|
|
343
|
+
/*
|
|
344
|
+
* A rule that no served tool reaches any more once ours sits above it.
|
|
345
|
+
* Deliberately not called "never fires": a tool that appears tomorrow and
|
|
346
|
+
* matches that glob but not our literal name would still reach it.
|
|
347
|
+
*/
|
|
348
|
+
const live = args.liveTools ?? [];
|
|
349
|
+
const strandedRule = governing && live.length > 0 && !live.some((t) => t !== draft.tool && globMatch(governing.match, t))
|
|
350
|
+
? governing.id
|
|
351
|
+
: null;
|
|
352
|
+
const named = classifyByName(draft.tool);
|
|
353
|
+
const nameContradiction = named && named !== draft.effect
|
|
354
|
+
? `this tool's name reads as ${named}, not ${draft.effect}. The gateway refuses to let an upstream's ` +
|
|
355
|
+
`own hint contradict its name for exactly this reason; a person may, but it is worth being sure.`
|
|
356
|
+
: null;
|
|
357
|
+
const currentBounds = boundsOf(governing ?? existing ?? undefined);
|
|
358
|
+
const nextBounds = boundsOf(rule);
|
|
359
|
+
const dropsBounds = currentBounds && !nextBounds ? (governing?.id ?? existing?.id ?? null) : null;
|
|
360
|
+
return {
|
|
361
|
+
policy: candidate,
|
|
362
|
+
rule,
|
|
363
|
+
index,
|
|
364
|
+
verdict,
|
|
365
|
+
current,
|
|
366
|
+
bounds: nextBounds,
|
|
367
|
+
currentBounds,
|
|
368
|
+
replaces: existing,
|
|
369
|
+
governedBy: governing?.id ?? null,
|
|
370
|
+
governedByConsole: governing?.id.startsWith(RULE_PREFIX) ?? false,
|
|
371
|
+
carriedFrom,
|
|
372
|
+
dropsBounds,
|
|
373
|
+
strandedRule,
|
|
374
|
+
nameContradiction,
|
|
375
|
+
overridden: args.disabled
|
|
376
|
+
? `this tool is switched off, so it stays refused until it is switched back on — this decides what ` +
|
|
377
|
+
`happens then`
|
|
378
|
+
: null,
|
|
379
|
+
overriddenReason: governing?.reason &&
|
|
380
|
+
!governing.id.startsWith(RULE_PREFIX) &&
|
|
381
|
+
RANK[draft.decision] > RANK[governing.decision]
|
|
382
|
+
? { ruleId: governing.id, decision: governing.decision, reason: governing.reason }
|
|
383
|
+
: null,
|
|
384
|
+
loosens: RANK[verdict.kind] > RANK[current.kind]
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
export function previewClearToolRule(args) {
|
|
388
|
+
const removed = ruleAtOurId(args.policy, args.tool);
|
|
389
|
+
if (!removed)
|
|
390
|
+
return null;
|
|
391
|
+
const candidate = {
|
|
392
|
+
...args.policy,
|
|
393
|
+
rules: args.policy.rules.filter((r) => r.id !== ruleIdFor(args.tool))
|
|
394
|
+
};
|
|
395
|
+
const ask = (p) => decide({ tool: args.tool, policy: p, argsUnknown: true, disabled: args.disabled });
|
|
396
|
+
const verdict = ask(candidate);
|
|
397
|
+
return {
|
|
398
|
+
policy: candidate,
|
|
399
|
+
removed,
|
|
400
|
+
verdict,
|
|
401
|
+
current: ask(args.policy),
|
|
402
|
+
becomesUnclassified: verdict.ruleId === "defaults.on_unclassified"
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
export function writeToolRule(options) {
|
|
406
|
+
const { draft } = options;
|
|
407
|
+
if (options.writesAllowed === false)
|
|
408
|
+
return refusedByConfig();
|
|
409
|
+
if (!options.knownToLiveSurface) {
|
|
410
|
+
return {
|
|
411
|
+
kind: "refused",
|
|
412
|
+
why: `no running gateway is serving a tool called "${draft.tool}". A rule naming a tool nobody serves ` +
|
|
413
|
+
`reads as a decision and governs nothing, so it is not written.`
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
const read = readPolicyFile(options.policyPath, options.expectedDigest);
|
|
417
|
+
if ("kind" in read)
|
|
418
|
+
return read;
|
|
419
|
+
const { text, before, actual } = read;
|
|
420
|
+
const existing = ruleAtOurId(before, draft.tool);
|
|
421
|
+
if (existing) {
|
|
422
|
+
const owned = ownsRule(existing, draft.tool);
|
|
423
|
+
if (!owned.ok) {
|
|
424
|
+
return {
|
|
425
|
+
kind: "refused",
|
|
426
|
+
why: `the rule "${existing.id}" in this policy is not one this console wrote — ${owned.why}. ` +
|
|
427
|
+
`It is left alone rather than rewritten. Rename it if you meant the console to own it.`
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
const preview = previewToolRule({ policy: before, draft, liveTools: options.liveTools });
|
|
432
|
+
/*
|
|
433
|
+
* An update must never reorder. If a human has inserted a rule above ours
|
|
434
|
+
* that also matches, moving ours up would reorder their rules; leaving it
|
|
435
|
+
* where it is would mean the change does not take effect. Both are wrong, so
|
|
436
|
+
* this refuses and says which rule is in the way.
|
|
437
|
+
*/
|
|
438
|
+
if (existing) {
|
|
439
|
+
const governingIndex = before.rules.findIndex((r) => r.id !== ruleIdFor(draft.tool) && globMatch(r.match, draft.tool));
|
|
440
|
+
if (governingIndex !== -1 && governingIndex < before.rules.indexOf(existing)) {
|
|
441
|
+
return {
|
|
442
|
+
kind: "refused",
|
|
443
|
+
why: `rule "${before.rules[governingIndex].id}" was added above this tool's rule and is consulted ` +
|
|
444
|
+
`first, so the change you previewed would not take effect. Moving the rule would reorder ` +
|
|
445
|
+
`somebody else's, so this is left for an edit you review.`
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
const ack = draft.acknowledged ?? {};
|
|
450
|
+
if (preview.dropsBounds && !ack.dropBounds) {
|
|
451
|
+
return {
|
|
452
|
+
kind: "refused",
|
|
453
|
+
needs: "dropBounds",
|
|
454
|
+
why: `"${preview.dropsBounds}" bounds this tool's arguments today, and this rule carries no bounds, so ` +
|
|
455
|
+
`the call would become unbounded. That is a real choice and has to be a deliberate one.`
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
if (preview.overriddenReason && !ack.overrideDeny) {
|
|
459
|
+
return {
|
|
460
|
+
kind: "refused",
|
|
461
|
+
needs: "overrideDeny",
|
|
462
|
+
why: `rule "${preview.overriddenReason.ruleId}" says ${preview.overriddenReason.decision} for this tool ` +
|
|
463
|
+
`— "${preview.overriddenReason.reason}". Reversing a decision somebody wrote down has to be a ` +
|
|
464
|
+
`deliberate act.`
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
if (preview.overriddenReason && options.overridesAllowed === false) {
|
|
468
|
+
return {
|
|
469
|
+
kind: "refused",
|
|
470
|
+
why: `this gateway has \`policy_overrides: false\`, so the console may classify a tool nothing ` +
|
|
471
|
+
`classified but not reverse rule "${preview.overriddenReason.ruleId}". That is an edit you review.`
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
if (draft.effect === "destructive" && draft.decision === "allow" && !ack.destructiveAllow) {
|
|
475
|
+
return {
|
|
476
|
+
kind: "refused",
|
|
477
|
+
needs: "destructiveAllow",
|
|
478
|
+
why: `this would let the model delete things with nobody asked. "Ask a human first" makes it just as ` +
|
|
479
|
+
`reachable with a person on each call.`
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
const edited = applyRule(text, preview, draft, options.now ?? new Date());
|
|
483
|
+
if (!edited.ok)
|
|
484
|
+
return { kind: "refused", why: edited.why };
|
|
485
|
+
return commit({
|
|
486
|
+
policyPath: options.policyPath,
|
|
487
|
+
text: edited.text,
|
|
488
|
+
before,
|
|
489
|
+
actual,
|
|
490
|
+
expect: { index: preview.index, rule: preview.rule },
|
|
491
|
+
tool: draft.tool,
|
|
492
|
+
action: existing ? "update" : "set",
|
|
493
|
+
previous: existing ?? null,
|
|
494
|
+
preview,
|
|
495
|
+
liveTools: options.liveTools
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
export function clearToolRule(options) {
|
|
499
|
+
if (options.writesAllowed === false)
|
|
500
|
+
return refusedByConfig();
|
|
501
|
+
const read = readPolicyFile(options.policyPath, options.expectedDigest);
|
|
502
|
+
if ("kind" in read)
|
|
503
|
+
return read;
|
|
504
|
+
const { text, before, actual } = read;
|
|
505
|
+
const existing = ruleAtOurId(before, options.tool);
|
|
506
|
+
if (!existing) {
|
|
507
|
+
return { kind: "refused", why: `there is no rule "${ruleIdFor(options.tool)}" to remove` };
|
|
508
|
+
}
|
|
509
|
+
const owned = ownsRule(existing, options.tool);
|
|
510
|
+
if (!owned.ok) {
|
|
511
|
+
return {
|
|
512
|
+
kind: "refused",
|
|
513
|
+
why: `the rule "${existing.id}" is not one this console wrote — ${owned.why}. Removing it is an edit ` +
|
|
514
|
+
`you review in git.`
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
const index = before.rules.indexOf(existing);
|
|
518
|
+
const removed = removeRule(text, options.tool);
|
|
519
|
+
if (!removed.ok)
|
|
520
|
+
return { kind: "refused", why: removed.why };
|
|
521
|
+
return commit({
|
|
522
|
+
policyPath: options.policyPath,
|
|
523
|
+
text: removed.text,
|
|
524
|
+
before,
|
|
525
|
+
actual,
|
|
526
|
+
expect: { index, rule: null },
|
|
527
|
+
tool: options.tool,
|
|
528
|
+
action: "cleared",
|
|
529
|
+
previous: existing,
|
|
530
|
+
preview: null,
|
|
531
|
+
liveTools: options.liveTools
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
function refusedByConfig() {
|
|
535
|
+
return {
|
|
536
|
+
kind: "refused",
|
|
537
|
+
why: "this gateway has `policy_writes: false` in its config, so policy may only change with a deployment. " +
|
|
538
|
+
"The rule below can be added to policy.yaml by hand."
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
function readPolicyFile(policyPath, expectedDigest) {
|
|
542
|
+
const full = expandPath(policyPath);
|
|
543
|
+
let text;
|
|
544
|
+
try {
|
|
545
|
+
text = readFileSync(full, "utf8");
|
|
546
|
+
}
|
|
547
|
+
catch (err) {
|
|
548
|
+
return { kind: "refused", why: `cannot read ${policyPath}: ${err.message}` };
|
|
549
|
+
}
|
|
550
|
+
const doc = parseDocument(text);
|
|
551
|
+
if (doc.errors.length > 0) {
|
|
552
|
+
return {
|
|
553
|
+
kind: "refused",
|
|
554
|
+
why: `${policyPath} is not valid YAML (${doc.errors[0].message}), so nothing is written to it`
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
/*
|
|
558
|
+
* Validated *before* the edit, so a file that was already broken is reported
|
|
559
|
+
* as broken rather than having a correct rule added to it and then being
|
|
560
|
+
* blamed on this write.
|
|
561
|
+
*/
|
|
562
|
+
let before;
|
|
563
|
+
try {
|
|
564
|
+
before = parsePolicy(doc.toJS(), policyPath);
|
|
565
|
+
}
|
|
566
|
+
catch (err) {
|
|
567
|
+
return {
|
|
568
|
+
kind: "refused",
|
|
569
|
+
why: `${policyPath} does not validate as a policy (${err.message}), so nothing is written to it`
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
const actual = policyDigest(before);
|
|
573
|
+
if (actual !== expectedDigest) {
|
|
574
|
+
return {
|
|
575
|
+
kind: "stale",
|
|
576
|
+
expected: expectedDigest,
|
|
577
|
+
actual,
|
|
578
|
+
why: `${policyPath} has changed since it was read, so the outcome shown is not the outcome this would ` +
|
|
579
|
+
`produce. Re-read it and choose again.`
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
return { text, before, actual };
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Validate the result and put it on disk.
|
|
586
|
+
*
|
|
587
|
+
* The read-back is what makes a bug in the YAML editing a failed write rather
|
|
588
|
+
* than a gateway reloading something nobody validated — and the reload would
|
|
589
|
+
* adopt it within a second.
|
|
590
|
+
*/
|
|
591
|
+
function commit(args) {
|
|
592
|
+
let after;
|
|
593
|
+
try {
|
|
594
|
+
after = parsePolicy(parseDocument(args.text).toJS(), args.policyPath);
|
|
595
|
+
}
|
|
596
|
+
catch (err) {
|
|
597
|
+
return {
|
|
598
|
+
kind: "refused",
|
|
599
|
+
why: `the change could not be made without producing an invalid policy (${err.message}); nothing was written`
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
const violation = assertOnlyRulesChanged(args.before, after) ??
|
|
603
|
+
assertOnlyOwnRuleChanged(args.before, after, args.tool, args.expect) ??
|
|
604
|
+
assertNoCollateralChange(args.before, after, args.liveTools ?? [], args.tool);
|
|
605
|
+
if (violation)
|
|
606
|
+
return { kind: "refused", why: `${violation}; nothing was written` };
|
|
607
|
+
writeAtomically(expandPath(args.policyPath), args.text);
|
|
608
|
+
return {
|
|
609
|
+
kind: "written",
|
|
610
|
+
rule: args.expect.rule,
|
|
611
|
+
action: args.action,
|
|
612
|
+
previous: args.previous,
|
|
613
|
+
digest: policyDigest(after),
|
|
614
|
+
previousDigest: args.actual,
|
|
615
|
+
preview: args.preview
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
/** `rules: []`, with or without a trailing comment: an empty list written on one line. */
|
|
619
|
+
const EMPTY_FLOW_RULES = /^(\s*)rules\s*:\s*\[\s*\]\s*(#.*)?$/;
|
|
620
|
+
function layoutRules(text) {
|
|
621
|
+
const lines = text.split("\n");
|
|
622
|
+
const keyAt = lines.findIndex((l) => /^\s*rules\s*:/.test(l));
|
|
623
|
+
if (keyAt === -1)
|
|
624
|
+
return { error: "the policy file has no `rules:` key to write into" };
|
|
625
|
+
/*
|
|
626
|
+
* An empty list has to be written `rules: []` -- YAML has no block form for
|
|
627
|
+
* "nothing" -- and that is what a freshly generated policy contains. There
|
|
628
|
+
* is nothing inside it to reformat, so it is opened into a block list here
|
|
629
|
+
* and whatever is written goes under it. Without this the first rule could
|
|
630
|
+
* never be written to a new policy at all.
|
|
631
|
+
*/
|
|
632
|
+
const empty = EMPTY_FLOW_RULES.exec(lines[keyAt]);
|
|
633
|
+
if (empty) {
|
|
634
|
+
lines[keyAt] = `${empty[1]}rules:${empty[2] ? ` ${empty[2]}` : ""}`;
|
|
635
|
+
}
|
|
636
|
+
else if (/^\s*rules\s*:\s*\[/.test(lines[keyAt])) {
|
|
637
|
+
return {
|
|
638
|
+
error: "this policy writes `rules` as a single-line list, which cannot be edited here without " +
|
|
639
|
+
"reformatting the rest of it. Write the rules as a block list to set them from here."
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
const keyIndent = lines[keyAt].match(/^\s*/)[0].length;
|
|
643
|
+
let indent = null;
|
|
644
|
+
const spans = [];
|
|
645
|
+
let pending = null;
|
|
646
|
+
let current = null;
|
|
647
|
+
const close = (to) => {
|
|
648
|
+
if (current)
|
|
649
|
+
spans.push({ id: current.id, from: current.from, to });
|
|
650
|
+
current = null;
|
|
651
|
+
};
|
|
652
|
+
for (let i = keyAt + 1; i < lines.length; i++) {
|
|
653
|
+
const line = lines[i];
|
|
654
|
+
if (line.trim() === "" || line.trim().startsWith("#")) {
|
|
655
|
+
// Blank and comment lines are claimed by whatever rule comes next.
|
|
656
|
+
pending ??= i;
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
const lineIndent = line.match(/^\s*/)[0].length;
|
|
660
|
+
if (lineIndent <= keyIndent) {
|
|
661
|
+
const stop = pending ?? i;
|
|
662
|
+
close(stop);
|
|
663
|
+
return { lines, spans, indent: indent ?? " ", end: stop, keyAt };
|
|
664
|
+
}
|
|
665
|
+
const item = line.match(/^(\s*)-\s/);
|
|
666
|
+
if (item && (indent === null || item[1].length === indent.length)) {
|
|
667
|
+
indent ??= item[1];
|
|
668
|
+
close(pending ?? i);
|
|
669
|
+
current = { from: pending ?? i, id: undefined };
|
|
670
|
+
}
|
|
671
|
+
pending = null;
|
|
672
|
+
/*
|
|
673
|
+
* The rule's own `id:`, read only at the rule's own key depth — on the
|
|
674
|
+
* `- ` line itself or indented one level under it. Without the depth
|
|
675
|
+
* check a key called `id` nested inside `args:` could be read as the
|
|
676
|
+
* rule's, and the rule would then be looked up under the wrong name:
|
|
677
|
+
* an update would insert a duplicate instead of replacing. The
|
|
678
|
+
* assertions downstream catch that and refuse, so it fails closed either
|
|
679
|
+
* way — but failing closed on a valid file is still a bug.
|
|
680
|
+
*/
|
|
681
|
+
if (current && current.id === undefined && indent !== null) {
|
|
682
|
+
const own = `${indent} `;
|
|
683
|
+
const atItemLine = line.startsWith(`${indent}- `);
|
|
684
|
+
if (atItemLine || line.startsWith(own)) {
|
|
685
|
+
const body = atItemLine ? line.slice(indent.length + 2) : line.slice(own.length);
|
|
686
|
+
if (!/^\s/.test(body)) {
|
|
687
|
+
const id = body.match(/^id\s*:\s*(\S+)\s*$/);
|
|
688
|
+
if (id)
|
|
689
|
+
current = { from: current.from, id: id[1].replace(/^["']|["']$/g, "") };
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
const stop = pending ?? lines.length;
|
|
695
|
+
close(stop);
|
|
696
|
+
return { lines, spans, indent: indent ?? " ", end: stop, keyAt };
|
|
697
|
+
}
|
|
698
|
+
/** The rule as the lines that go into the file, comment and all. */
|
|
699
|
+
function ruleBlock(rule, comment, indent) {
|
|
700
|
+
const doc = new Document([ruleToPlain(rule)]);
|
|
701
|
+
const body = doc.toString(TO_STRING).trimEnd().split("\n");
|
|
702
|
+
return [...comment.split("\n").map((c) => `${indent}#${c}`), ...body.map((l) => `${indent}${l}`)];
|
|
703
|
+
}
|
|
704
|
+
function commentFor(preview, draft, now) {
|
|
705
|
+
return (
|
|
706
|
+
// No name here: policy.yaml is meant to be safe to commit and share, and
|
|
707
|
+
// the person's login name is in the audit log, where it belongs.
|
|
708
|
+
` Set ${draft.via ? `via ${draft.via}` : "from the console"} on ${now.toISOString().slice(0, 10)}:\n` +
|
|
709
|
+
` "${EFFECT_PROSE[draft.effect]}" → ${DECISION_PROSE[draft.decision]}.` +
|
|
710
|
+
(preview.carriedFrom ? `\n Argument bounds copied from "${preview.carriedFrom}".` : "") +
|
|
711
|
+
(preview.overriddenReason
|
|
712
|
+
? `\n Overrides "${preview.overriddenReason.ruleId}", which said ${preview.overriddenReason.decision}.`
|
|
713
|
+
: "") +
|
|
714
|
+
(preview.governedBy && !preview.replaces
|
|
715
|
+
? `\n Placed above "${preview.governedBy}", which also matches this name.`
|
|
716
|
+
: ""));
|
|
717
|
+
}
|
|
718
|
+
/** Insert or rewrite our rule, leaving every other line of the file alone. */
|
|
719
|
+
function applyRule(text, preview, draft, now) {
|
|
720
|
+
const layout = layoutRules(text);
|
|
721
|
+
if ("error" in layout)
|
|
722
|
+
return { ok: false, why: layout.error };
|
|
723
|
+
const id = ruleIdFor(draft.tool);
|
|
724
|
+
const block = ruleBlock(preview.rule, commentFor(preview, draft, now), layout.indent);
|
|
725
|
+
const lines = [...layout.lines];
|
|
726
|
+
const mine = layout.spans.findIndex((sp) => sp.id === id);
|
|
727
|
+
if (mine !== -1) {
|
|
728
|
+
const span = layout.spans[mine];
|
|
729
|
+
lines.splice(span.from, span.to - span.from, ...block);
|
|
730
|
+
}
|
|
731
|
+
else {
|
|
732
|
+
const at = preview.index < layout.spans.length ? layout.spans[preview.index].from : layout.end;
|
|
733
|
+
lines.splice(at, 0, ...block);
|
|
734
|
+
}
|
|
735
|
+
return { ok: true, text: lines.join("\n") };
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Set `defaults.on_unclassified`, by line, for the same reason the rules are
|
|
739
|
+
* spliced: a file people review should come back with one line changed.
|
|
740
|
+
*/
|
|
741
|
+
function setUnclassifiedLine(text, value) {
|
|
742
|
+
const lines = text.split("\n");
|
|
743
|
+
const at = lines.findIndex((l) => /^\s*on_unclassified\s*:/.test(l));
|
|
744
|
+
if (at !== -1) {
|
|
745
|
+
const indent = lines[at].match(/^\s*/)[0];
|
|
746
|
+
// Keep whatever the author wrote after the value, which is usually a note
|
|
747
|
+
// about why it is set that way.
|
|
748
|
+
const trailing = lines[at].match(/#.*$/)?.[0];
|
|
749
|
+
lines[at] = `${indent}on_unclassified: ${value}${trailing ? ` ${trailing}` : ""}`;
|
|
750
|
+
return { ok: true, text: lines.join("\n") };
|
|
751
|
+
}
|
|
752
|
+
const defaults = lines.findIndex((l) => /^\s*defaults\s*:\s*$/.test(l));
|
|
753
|
+
if (defaults === -1) {
|
|
754
|
+
return { ok: false, why: "the policy file has no `defaults:` block to write into" };
|
|
755
|
+
}
|
|
756
|
+
const indent = `${lines[defaults].match(/^\s*/)[0]} `;
|
|
757
|
+
lines.splice(defaults + 1, 0, `${indent}on_unclassified: ${value}`);
|
|
758
|
+
return { ok: true, text: lines.join("\n") };
|
|
759
|
+
}
|
|
760
|
+
function removeRule(text, tool) {
|
|
761
|
+
const layout = layoutRules(text);
|
|
762
|
+
if ("error" in layout)
|
|
763
|
+
return { ok: false, why: layout.error };
|
|
764
|
+
const span = layout.spans.find((sp) => sp.id === ruleIdFor(tool));
|
|
765
|
+
if (!span)
|
|
766
|
+
return { ok: false, why: `no rule "${ruleIdFor(tool)}" in the file` };
|
|
767
|
+
const lines = [...layout.lines];
|
|
768
|
+
lines.splice(span.from, span.to - span.from);
|
|
769
|
+
// The last rule is gone. A `rules:` key with nothing under it is null, not
|
|
770
|
+
// an empty list, so the file would no longer load: say "empty" the one way
|
|
771
|
+
// YAML can.
|
|
772
|
+
if (layout.spans.length === 1) {
|
|
773
|
+
const key = lines[layout.keyAt];
|
|
774
|
+
const indent = key.match(/^\s*/)[0];
|
|
775
|
+
const trailing = key.match(/#.*$/)?.[0];
|
|
776
|
+
lines[layout.keyAt] = `${indent}rules: []${trailing ? ` ${trailing}` : ""}`;
|
|
777
|
+
}
|
|
778
|
+
return { ok: true, text: lines.join("\n") };
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* The rule as it is written to the file.
|
|
782
|
+
*
|
|
783
|
+
* A parsed rule carries schema defaults (`on_violation: deny`,
|
|
784
|
+
* `unknown_args: allow`); writing them out would put fields nobody chose into a
|
|
785
|
+
* file people read. They are written only when they differ from the default —
|
|
786
|
+
* which is exactly when they are load-bearing.
|
|
787
|
+
*/
|
|
788
|
+
function ruleToPlain(rule) {
|
|
789
|
+
const out = {
|
|
790
|
+
id: rule.id,
|
|
791
|
+
match: rule.match,
|
|
792
|
+
effect: rule.effect,
|
|
793
|
+
decision: rule.decision
|
|
794
|
+
};
|
|
795
|
+
if (rule.reason)
|
|
796
|
+
out["reason"] = rule.reason;
|
|
797
|
+
if (rule.on_violation !== "deny")
|
|
798
|
+
out["on_violation"] = rule.on_violation;
|
|
799
|
+
if (rule.unknown_args !== "allow")
|
|
800
|
+
out["unknown_args"] = rule.unknown_args;
|
|
801
|
+
if (rule.args && Object.keys(rule.args).length > 0)
|
|
802
|
+
out["args"] = rule.args;
|
|
803
|
+
return out;
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* One source of truth for the rule as YAML text.
|
|
807
|
+
*
|
|
808
|
+
* The console and the CLI both show the rule before it is written. Two
|
|
809
|
+
* hand-rolled emitters that each knew four fields is how both come to omit a
|
|
810
|
+
* carried bound on the day bounds are added, so the displayed YAML is produced
|
|
811
|
+
* from the same object the file write serialises.
|
|
812
|
+
*/
|
|
813
|
+
export function ruleToYaml(rule, indent = " ") {
|
|
814
|
+
const doc = new Document([ruleToPlain(rule)]);
|
|
815
|
+
return doc
|
|
816
|
+
.toString({ lineWidth: 100 })
|
|
817
|
+
.trimEnd()
|
|
818
|
+
.split("\n")
|
|
819
|
+
.map((line) => `${indent}${line}`)
|
|
820
|
+
.join("\n");
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Nothing outside `rules` moved.
|
|
824
|
+
*
|
|
825
|
+
* Structural rather than a denylist of `egress`/`tenant`/`audit`/`approvals`/
|
|
826
|
+
* `tool_budget`/`defaults`: strictly stronger, and it cannot go stale when
|
|
827
|
+
* `PolicySchema` grows a field.
|
|
828
|
+
*/
|
|
829
|
+
function assertOnlyRulesChanged(before, after) {
|
|
830
|
+
const { rules: _b, ...beforeRest } = before;
|
|
831
|
+
const { rules: _a, ...afterRest } = after;
|
|
832
|
+
return canonicalJson(beforeRest) === canonicalJson(afterRest)
|
|
833
|
+
? null
|
|
834
|
+
: `the edit changed something outside "rules"`;
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Exactly one rule added, rewritten or removed, and every other rule identical
|
|
838
|
+
* in value *and in position*.
|
|
839
|
+
*
|
|
840
|
+
* The editing above is a splice and is hard to get wrong, which is exactly why
|
|
841
|
+
* this is here: the cost of being wrong is a policy file edited in a way nobody
|
|
842
|
+
* reviewed, and the check is a comparison of two parsed lists.
|
|
843
|
+
*/
|
|
844
|
+
/*
|
|
845
|
+
* Compared with `canonicalJson` throughout, never `JSON.stringify`: one side of
|
|
846
|
+
* these comparisons is a rule object this module built and the other came back
|
|
847
|
+
* through Zod, which emits keys in schema order. Plain stringify would call two
|
|
848
|
+
* identical rules different and refuse every write that carries bounds.
|
|
849
|
+
*/
|
|
850
|
+
function assertOnlyOwnRuleChanged(before, after, tool, expect) {
|
|
851
|
+
const id = ruleIdFor(tool);
|
|
852
|
+
const beforeOthers = before.rules.filter((r) => r.id !== id);
|
|
853
|
+
const afterOthers = after.rules.filter((r) => r.id !== id);
|
|
854
|
+
if (beforeOthers.length !== afterOthers.length) {
|
|
855
|
+
return `the edit changed how many other rules there are (${beforeOthers.length} → ${afterOthers.length})`;
|
|
856
|
+
}
|
|
857
|
+
for (let i = 0; i < beforeOthers.length; i++) {
|
|
858
|
+
if (canonicalJson(beforeOthers[i]) !== canonicalJson(afterOthers[i])) {
|
|
859
|
+
return `the edit altered or reordered the existing rule "${beforeOthers[i].id}"`;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
const mine = after.rules.filter((r) => r.id === id);
|
|
863
|
+
if (expect.rule === null) {
|
|
864
|
+
if (mine.length !== 0)
|
|
865
|
+
return `the rule for "${tool}" was meant to be removed and is still there`;
|
|
866
|
+
return null;
|
|
867
|
+
}
|
|
868
|
+
if (mine.length !== 1)
|
|
869
|
+
return `the edit left ${mine.length} rules for "${tool}" rather than one`;
|
|
870
|
+
if (canonicalJson(mine[0]) !== canonicalJson(expect.rule)) {
|
|
871
|
+
return `the rule written is not the rule that was previewed`;
|
|
872
|
+
}
|
|
873
|
+
if (after.rules.indexOf(mine[0]) !== expect.index) {
|
|
874
|
+
return `the rule landed at position ${after.rules.indexOf(mine[0])} rather than ${expect.index}`;
|
|
875
|
+
}
|
|
876
|
+
return null;
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* No other tool's verdict moved.
|
|
880
|
+
*
|
|
881
|
+
* With a literal `match` this is provable rather than hoped for, which is
|
|
882
|
+
* exactly why it is worth asserting: it is the invariant the whole
|
|
883
|
+
* first-match-wins placement story rests on, and the one a future change to
|
|
884
|
+
* `placement` would break silently.
|
|
885
|
+
*/
|
|
886
|
+
function assertNoCollateralChange(before, after, liveTools, target) {
|
|
887
|
+
for (const tool of liveTools) {
|
|
888
|
+
if (tool === target)
|
|
889
|
+
continue;
|
|
890
|
+
const a = decide({ tool, policy: before, argsUnknown: true });
|
|
891
|
+
const b = decide({ tool, policy: after, argsUnknown: true });
|
|
892
|
+
if (a.kind !== b.kind || a.ruleId !== b.ruleId) {
|
|
893
|
+
return `the edit would also change "${tool}" (${a.kind} by ${a.ruleId} → ${b.kind} by ${b.ruleId})`;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
return null;
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Temp file and a rename, matching `writeRegistry`.
|
|
900
|
+
*
|
|
901
|
+
* The rename matters more here. `PolicySource.watch` polls mtime, size *and*
|
|
902
|
+
* inode, precisely so an atomic replace is seen as a change — and a reader that
|
|
903
|
+
* caught a partial write would be a gateway parsing half a policy. Failing
|
|
904
|
+
* closed covers that; not writing half a file at all is better than relying on
|
|
905
|
+
* it.
|
|
906
|
+
*
|
|
907
|
+
* The file's mode is preserved rather than forced to 0o600 as the registry's
|
|
908
|
+
* is: a policy file is routinely committed and read by more than one account,
|
|
909
|
+
* and silently tightening its permissions on first edit would be a surprise.
|
|
910
|
+
* Also how the console writes gateway.yaml, for the same reasons.
|
|
911
|
+
*/
|
|
912
|
+
export function writeAtomically(full, text) {
|
|
913
|
+
mkdirSync(dirname(full), { recursive: true });
|
|
914
|
+
let mode;
|
|
915
|
+
try {
|
|
916
|
+
mode = statSync(full).mode & 0o777;
|
|
917
|
+
}
|
|
918
|
+
catch {
|
|
919
|
+
mode = undefined;
|
|
920
|
+
}
|
|
921
|
+
const tmp = join(dirname(full), `.${Date.now()}.${process.pid}.${basename(full)}.tmp`);
|
|
922
|
+
writeFileSync(tmp, text, mode === undefined ? { encoding: "utf8" } : { encoding: "utf8", mode });
|
|
923
|
+
renameSync(tmp, full);
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* The other half of the answer to "an unclassified tool is a wall": leave the
|
|
927
|
+
* tool unclassified and change what that *means*, from refused outright to held
|
|
928
|
+
* for a human.
|
|
929
|
+
*
|
|
930
|
+
* The one field outside `rules` this module may touch, and only between the two
|
|
931
|
+
* values the schema already has. A posture change rather than a permission
|
|
932
|
+
* grant — nothing runs unasked under either value.
|
|
933
|
+
*/
|
|
934
|
+
export function writeUnclassifiedPosture(options) {
|
|
935
|
+
if (options.writesAllowed === false)
|
|
936
|
+
return refusedByConfig();
|
|
937
|
+
const read = readPolicyFile(options.policyPath, options.expectedDigest);
|
|
938
|
+
if ("kind" in read)
|
|
939
|
+
return read;
|
|
940
|
+
const { text, before, actual } = read;
|
|
941
|
+
if (before.defaults.on_unclassified === options.value) {
|
|
942
|
+
return { kind: "refused", why: `on_unclassified is already ${options.value}` };
|
|
943
|
+
}
|
|
944
|
+
const edited = setUnclassifiedLine(text, options.value);
|
|
945
|
+
if (!edited.ok)
|
|
946
|
+
return { kind: "refused", why: edited.why };
|
|
947
|
+
const next = edited.text;
|
|
948
|
+
let after;
|
|
949
|
+
try {
|
|
950
|
+
after = parsePolicy(parseDocument(next).toJS(), options.policyPath);
|
|
951
|
+
}
|
|
952
|
+
catch (err) {
|
|
953
|
+
return {
|
|
954
|
+
kind: "refused",
|
|
955
|
+
why: `the change produced an invalid policy (${err.message}); nothing was written`
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
if (canonicalJson({ ...before, defaults: { ...before.defaults, on_unclassified: options.value } }) !==
|
|
959
|
+
canonicalJson(after)) {
|
|
960
|
+
return {
|
|
961
|
+
kind: "refused",
|
|
962
|
+
why: "the change touched something other than on_unclassified; nothing was written"
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
writeAtomically(expandPath(options.policyPath), next);
|
|
966
|
+
return { kind: "written", digest: policyDigest(after), previousDigest: actual };
|
|
967
|
+
}
|
|
968
|
+
/* ======================================================================
|
|
969
|
+
* Every other policy edit: one setting, any rule, the whole file.
|
|
970
|
+
*
|
|
971
|
+
* The console used to write exactly two things -- one rule per tool and the
|
|
972
|
+
* unclassified posture -- and everything else was "an edit you review in
|
|
973
|
+
* git". The product's requirement is now that every policy feature be usable
|
|
974
|
+
* from the console, so these are the general writers. They keep the same
|
|
975
|
+
* discipline as the narrow ones above:
|
|
976
|
+
*
|
|
977
|
+
* - the digest the caller previewed against must still be the file's, or
|
|
978
|
+
* nothing is written (`readPolicyFile`);
|
|
979
|
+
* - `policy_writes: false` refuses all of them, and an inline policy never
|
|
980
|
+
* reaches here (the caller has no file path to give);
|
|
981
|
+
* - the result must validate with `parsePolicy`, and a canonical comparison
|
|
982
|
+
* proves that only the intended part of the policy changed;
|
|
983
|
+
* - the file is replaced atomically, and every line the edit did not concern
|
|
984
|
+
* comes back byte-identical wherever the YAML allows it;
|
|
985
|
+
* - anything that widens what the gateway lets through needs an explicit
|
|
986
|
+
* `acknowledged.loosens`, and is refused outright where the gateway's
|
|
987
|
+
* config sets `policy_overrides: false` ("the console may tighten anything
|
|
988
|
+
* but may not reverse a decision");
|
|
989
|
+
* - a regular expression is never authored here, for the reason given at
|
|
990
|
+
* `REFUSED_CONSTRAINTS`. One already in the file is carried untouched.
|
|
991
|
+
* ====================================================================== */
|
|
992
|
+
/** One policy setting changed. */
|
|
993
|
+
export const POLICY_SETTING_RULE = "policy.setting";
|
|
994
|
+
/** A policy rule rewritten in place. */
|
|
995
|
+
export const POLICY_RULE_SET = "policy.rule.set";
|
|
996
|
+
/** A policy rule added. */
|
|
997
|
+
export const POLICY_RULE_ADD = "policy.rule.add";
|
|
998
|
+
/** A policy rule removed. */
|
|
999
|
+
export const POLICY_RULE_DELETE = "policy.rule.delete";
|
|
1000
|
+
/** The policy's rules reordered. */
|
|
1001
|
+
export const POLICY_RULE_ORDER = "policy.rule.order";
|
|
1002
|
+
/** The policy file replaced as text. */
|
|
1003
|
+
export const POLICY_FILE_EDIT = "policy.file-edit";
|
|
1004
|
+
export const LoosenAcknowledgedSchema = z.object({ loosens: z.boolean().optional() }).strict();
|
|
1005
|
+
/* -------------------------------------------------------------- settings */
|
|
1006
|
+
const isWider = (order) => (before, after) => order.indexOf(after) > order.indexOf(before);
|
|
1007
|
+
const raised = (before, after) => after > before;
|
|
1008
|
+
const switchedOff = (before, after) => before && !after;
|
|
1009
|
+
const switchedOn = (before, after) => !before && after;
|
|
1010
|
+
const upper = (list) => list.map((s) => s.toUpperCase());
|
|
1011
|
+
const gainsAny = (before, after) => after.some((x) => !before.includes(x));
|
|
1012
|
+
const HostList = z.array(z.string().min(1).max(253)).max(500);
|
|
1013
|
+
const NameList = z.array(z.string().min(1).max(200)).max(500);
|
|
1014
|
+
const PositiveInt = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
|
|
1015
|
+
const spec = (schema, loosens) => ({ schema, loosens: loosens });
|
|
1016
|
+
/**
|
|
1017
|
+
* Every policy setting the console may change, with its own schema and the
|
|
1018
|
+
* one place that says which direction is the loosening one.
|
|
1019
|
+
*
|
|
1020
|
+
* An allow-list rather than "any path that validates": a path not here is not
|
|
1021
|
+
* writable from the console at all. Left out on purpose:
|
|
1022
|
+
*
|
|
1023
|
+
* - `audit.path` and `approvals.store_path`, which move where the record and
|
|
1024
|
+
* the queue live -- pointing the log somewhere else is the quietest way to
|
|
1025
|
+
* stop it being read;
|
|
1026
|
+
* - `admin`, which decides who may administer the gateway over HTTP;
|
|
1027
|
+
* - `tenant.source`, `tenant.field` and the rest of the tenant block's shape,
|
|
1028
|
+
* which decide *which* customer a call belongs to. Only the two switches
|
|
1029
|
+
* that make separation stricter or looser are here.
|
|
1030
|
+
*
|
|
1031
|
+
* Those stay edits to the file, and the raw-file writer grades any change to
|
|
1032
|
+
* them as loosening, because it cannot say which way they point.
|
|
1033
|
+
*
|
|
1034
|
+
* Loosening, per path -- the direction in which more gets through:
|
|
1035
|
+
*
|
|
1036
|
+
* | path | loosening |
|
|
1037
|
+
* |-------------------------------|---------------------------------------------|
|
|
1038
|
+
* | enforcement | enforce → observe |
|
|
1039
|
+
* | on_tool_change | deny → warn |
|
|
1040
|
+
* | defaults.mode | locked → read-only → approve-writes (wider) |
|
|
1041
|
+
* | defaults.on_unclassified | deny → approve |
|
|
1042
|
+
* | results.on_injection | quarantine → label → allow |
|
|
1043
|
+
* | results.on_secret | quarantine → warn → allow |
|
|
1044
|
+
* | approvals.mode | deny → cli → elicit → both |
|
|
1045
|
+
* | approvals.ttl_seconds | raised |
|
|
1046
|
+
* | approvals.single_use | true → false |
|
|
1047
|
+
* | tool_budget | raised |
|
|
1048
|
+
* | egress.allow / egress.methods | any entry added |
|
|
1049
|
+
* | egress.* byte, time, redirect | raised |
|
|
1050
|
+
* | egress.block_private_ips | true → false |
|
|
1051
|
+
* | egress.allow_http | false → true |
|
|
1052
|
+
* | egress.allow_ip_literals | false → true |
|
|
1053
|
+
* | audit.enabled / hash_chain | true → false |
|
|
1054
|
+
* | audit.record_args | true → false |
|
|
1055
|
+
* | audit.redact | any name removed |
|
|
1056
|
+
* | audit.on_failure | refuse → continue |
|
|
1057
|
+
* | tenant.on_mismatch | deny → override |
|
|
1058
|
+
* | tenant.required | true → false |
|
|
1059
|
+
*
|
|
1060
|
+
* `defaults.mode`: `approve-writes` is the widest because it is the only
|
|
1061
|
+
* posture under which a write is reachable at all (with a person's say-so);
|
|
1062
|
+
* `read-only` refuses writes outright, and `locked` refuses reads too.
|
|
1063
|
+
* `approvals.mode`: `deny` makes every hold a refusal, so moving *to* it
|
|
1064
|
+
* tightens; `elicit` lets the person at the agent's own client answer, which
|
|
1065
|
+
* is a channel the agent's host controls, so adding it widens.
|
|
1066
|
+
*/
|
|
1067
|
+
export const POLICY_SETTINGS = {
|
|
1068
|
+
enforcement: spec(z.enum(["enforce", "observe"]), isWider(["enforce", "observe"])),
|
|
1069
|
+
on_tool_change: spec(z.enum(["warn", "deny"]), isWider(["deny", "warn"])),
|
|
1070
|
+
"defaults.mode": spec(PostureSchema, isWider(["locked", "read-only", "approve-writes"])),
|
|
1071
|
+
"defaults.on_unclassified": spec(z.enum(["deny", "approve"]), isWider(["deny", "approve"])),
|
|
1072
|
+
"results.on_injection": spec(z.enum(["allow", "label", "quarantine"]), isWider(["quarantine", "label", "allow"])),
|
|
1073
|
+
"results.on_secret": spec(z.enum(["allow", "warn", "quarantine"]), isWider(["quarantine", "warn", "allow"])),
|
|
1074
|
+
"approvals.mode": spec(z.enum(["elicit", "cli", "both", "deny"]), isWider(["deny", "cli", "elicit", "both"])),
|
|
1075
|
+
"approvals.ttl_seconds": spec(PositiveInt, raised),
|
|
1076
|
+
"approvals.single_use": spec(z.boolean(), switchedOff),
|
|
1077
|
+
tool_budget: spec(PositiveInt, raised),
|
|
1078
|
+
"egress.allow": spec(HostList, gainsAny),
|
|
1079
|
+
"egress.methods": spec(z.array(z.string().regex(/^[A-Za-z]{1,16}$/)).max(16), (b, a) => gainsAny(upper(b), upper(a))),
|
|
1080
|
+
"egress.max_body_bytes": spec(PositiveInt, raised),
|
|
1081
|
+
"egress.max_request_body_bytes": spec(PositiveInt, raised),
|
|
1082
|
+
"egress.timeout_ms": spec(PositiveInt, raised),
|
|
1083
|
+
"egress.max_redirects": spec(z.number().int().min(0).max(100), raised),
|
|
1084
|
+
"egress.block_private_ips": spec(z.boolean(), switchedOff),
|
|
1085
|
+
"egress.allow_http": spec(z.boolean(), switchedOn),
|
|
1086
|
+
"egress.allow_ip_literals": spec(z.boolean(), switchedOn),
|
|
1087
|
+
"audit.enabled": spec(z.boolean(), switchedOff),
|
|
1088
|
+
"audit.hash_chain": spec(z.boolean(), switchedOff),
|
|
1089
|
+
"audit.record_args": spec(z.boolean(), switchedOff),
|
|
1090
|
+
"audit.redact": spec(NameList, (b, a) => gainsAny(a, b)),
|
|
1091
|
+
"audit.on_failure": spec(z.enum(["refuse", "continue"]), isWider(["refuse", "continue"])),
|
|
1092
|
+
"tenant.on_mismatch": spec(z.enum(["deny", "override"]), isWider(["deny", "override"])),
|
|
1093
|
+
"tenant.required": spec(z.boolean(), switchedOff)
|
|
1094
|
+
};
|
|
1095
|
+
export const POLICY_SETTING_PATHS = Object.keys(POLICY_SETTINGS);
|
|
1096
|
+
/** A path and a value, checked against that path's own schema. Throws `PolicyWriteError`. */
|
|
1097
|
+
export function parsePolicySetting(path, value) {
|
|
1098
|
+
if (typeof path !== "string" || !Object.hasOwn(POLICY_SETTINGS, path)) {
|
|
1099
|
+
throw new PolicyWriteError(`${JSON.stringify(path)} is not a setting the console can change. It can change: ${POLICY_SETTING_PATHS.join(", ")}.`);
|
|
1100
|
+
}
|
|
1101
|
+
const result = POLICY_SETTINGS[path].schema.safeParse(value);
|
|
1102
|
+
if (!result.success) {
|
|
1103
|
+
const detail = result.error.issues.map((i) => `${i.path.join(".") || "value"}: ${i.message}`).join("; ");
|
|
1104
|
+
throw new PolicyWriteError(`invalid value for ${path}: ${detail}`);
|
|
1105
|
+
}
|
|
1106
|
+
return { path, value: result.data };
|
|
1107
|
+
}
|
|
1108
|
+
/** The value a parsed policy holds at a setting path; undefined where its block is absent. */
|
|
1109
|
+
export function policySettingValue(policy, path) {
|
|
1110
|
+
let at = policy;
|
|
1111
|
+
for (const key of path.split(".")) {
|
|
1112
|
+
if (at === null || typeof at !== "object")
|
|
1113
|
+
return undefined;
|
|
1114
|
+
at = at[key];
|
|
1115
|
+
}
|
|
1116
|
+
return at;
|
|
1117
|
+
}
|
|
1118
|
+
/** Whether going from `before` to `after` at this path widens what policy lets through. */
|
|
1119
|
+
export function settingLoosens(path, before, after) {
|
|
1120
|
+
const s = POLICY_SETTINGS[path];
|
|
1121
|
+
if (!s || before === undefined)
|
|
1122
|
+
return false;
|
|
1123
|
+
return s.loosens(before, after);
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* The one gate for every loosening change. Refused outright under
|
|
1127
|
+
* `policy_overrides: false`; otherwise refused until it is acknowledged.
|
|
1128
|
+
*/
|
|
1129
|
+
function loosenGate(loosens, ack, overridesAllowed, what) {
|
|
1130
|
+
if (!loosens)
|
|
1131
|
+
return null;
|
|
1132
|
+
if (overridesAllowed === false) {
|
|
1133
|
+
return {
|
|
1134
|
+
kind: "refused",
|
|
1135
|
+
why: `${what}. This gateway has \`policy_overrides: false\`, so the console may tighten its policy but ` +
|
|
1136
|
+
`not loosen it; that is an edit you review.`
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
if (!ack?.loosens) {
|
|
1140
|
+
return {
|
|
1141
|
+
kind: "refused",
|
|
1142
|
+
needs: "loosens",
|
|
1143
|
+
why: `${what}. That lets more through than the policy does now, so it has to be confirmed first.`
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
return null;
|
|
1147
|
+
}
|
|
1148
|
+
/**
|
|
1149
|
+
* A scalar as it is written in YAML, for splicing into a line. In a flow list
|
|
1150
|
+
* a plain word is used only where it reads back as the same string: `*.x.com`
|
|
1151
|
+
* would be an alias, `a,b` two items and `true` a boolean, so those are quoted.
|
|
1152
|
+
*/
|
|
1153
|
+
function yamlScalar(value, inFlow) {
|
|
1154
|
+
if (typeof value !== "string")
|
|
1155
|
+
return String(value);
|
|
1156
|
+
if (inFlow) {
|
|
1157
|
+
return /^[A-Za-z0-9._\-/]+$/.test(value) && parseDocument(value).toJS() === value ? value : JSON.stringify(value);
|
|
1158
|
+
}
|
|
1159
|
+
return new Document(value).toString(TO_STRING).trimEnd();
|
|
1160
|
+
}
|
|
1161
|
+
/**
|
|
1162
|
+
* Set one value in the file's text.
|
|
1163
|
+
*
|
|
1164
|
+
* Where the key is already there as a scalar or a one-line list, only the
|
|
1165
|
+
* value's own characters are replaced, so a trailing comment and every other
|
|
1166
|
+
* byte survive. Otherwise the parsed document is edited (`setIn`) and written
|
|
1167
|
+
* back, which keeps comments but may respace a one-line list elsewhere; the
|
|
1168
|
+
* canonical check after this is what proves nothing else changed in value.
|
|
1169
|
+
*/
|
|
1170
|
+
function setValueInText(text, segments, value) {
|
|
1171
|
+
const doc = parseDocument(text);
|
|
1172
|
+
const node = doc.getIn(segments, true);
|
|
1173
|
+
const splice = (start, end, insert) => ({
|
|
1174
|
+
ok: true,
|
|
1175
|
+
text: text.slice(0, start) + insert + text.slice(end)
|
|
1176
|
+
});
|
|
1177
|
+
if (node?.range && isScalar(node) && !Array.isArray(value)) {
|
|
1178
|
+
return splice(node.range[0], node.range[1], yamlScalar(value, false));
|
|
1179
|
+
}
|
|
1180
|
+
if (node?.range && isSeq(node) && node.flow && Array.isArray(value)) {
|
|
1181
|
+
const padded = value.length > 0 && /^\[\s/.test(text.slice(node.range[0], node.range[1]));
|
|
1182
|
+
const pad = padded ? " " : "";
|
|
1183
|
+
return splice(node.range[0], node.range[1], `[${pad}${value.map((v) => yamlScalar(v, true)).join(", ")}${pad}]`);
|
|
1184
|
+
}
|
|
1185
|
+
const created = doc.createNode(value);
|
|
1186
|
+
if (isSeq(created))
|
|
1187
|
+
created.flow = true;
|
|
1188
|
+
try {
|
|
1189
|
+
doc.setIn(segments, created);
|
|
1190
|
+
}
|
|
1191
|
+
catch (err) {
|
|
1192
|
+
return { ok: false, why: `could not place ${segments.join(".")} in the file: ${err.message}` };
|
|
1193
|
+
}
|
|
1194
|
+
return { ok: true, text: doc.toString(TO_STRING) };
|
|
1195
|
+
}
|
|
1196
|
+
function withValue(policy, segments, value) {
|
|
1197
|
+
const copy = JSON.parse(JSON.stringify(policy));
|
|
1198
|
+
let at = copy;
|
|
1199
|
+
for (const key of segments.slice(0, -1)) {
|
|
1200
|
+
at[key] ??= {};
|
|
1201
|
+
at = at[key];
|
|
1202
|
+
}
|
|
1203
|
+
at[segments[segments.length - 1]] = value;
|
|
1204
|
+
return copy;
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Change one policy setting, comment-preserving.
|
|
1208
|
+
*
|
|
1209
|
+
* The general form of `writeUnclassifiedPosture`: the same read, digest check,
|
|
1210
|
+
* validation, canonical "only this changed" proof and atomic write, for any
|
|
1211
|
+
* path in `POLICY_SETTINGS`.
|
|
1212
|
+
*/
|
|
1213
|
+
export function writePolicySetting(options) {
|
|
1214
|
+
if (options.writesAllowed === false)
|
|
1215
|
+
return refusedByConfig();
|
|
1216
|
+
let parsed;
|
|
1217
|
+
try {
|
|
1218
|
+
parsed = parsePolicySetting(options.path, options.value);
|
|
1219
|
+
}
|
|
1220
|
+
catch (err) {
|
|
1221
|
+
return { kind: "refused", why: err.message };
|
|
1222
|
+
}
|
|
1223
|
+
const { path, value } = parsed;
|
|
1224
|
+
const segments = path.split(".");
|
|
1225
|
+
const read = readPolicyFile(options.policyPath, options.expectedDigest);
|
|
1226
|
+
if ("kind" in read)
|
|
1227
|
+
return read;
|
|
1228
|
+
const { text, before, actual } = read;
|
|
1229
|
+
if (segments[0] === "tenant" && !before.tenant) {
|
|
1230
|
+
return {
|
|
1231
|
+
kind: "refused",
|
|
1232
|
+
why: "this policy has no tenant block, so there is no customer separation to change. Adding one decides " +
|
|
1233
|
+
"where a call's customer comes from, which is an edit to the policy file."
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
const current = policySettingValue(before, path);
|
|
1237
|
+
if (canonicalJson(current) === canonicalJson(value)) {
|
|
1238
|
+
return { kind: "refused", why: `${path} is already ${JSON.stringify(value)}` };
|
|
1239
|
+
}
|
|
1240
|
+
const loosens = settingLoosens(path, current, value);
|
|
1241
|
+
const gate = loosenGate(loosens, options.acknowledged, options.overridesAllowed, `Changing ${path} from ${JSON.stringify(current)} to ${JSON.stringify(value)} loosens this policy`);
|
|
1242
|
+
if (gate)
|
|
1243
|
+
return gate;
|
|
1244
|
+
const edited = setValueInText(text, segments, value);
|
|
1245
|
+
if (!edited.ok)
|
|
1246
|
+
return { kind: "refused", why: edited.why };
|
|
1247
|
+
let after;
|
|
1248
|
+
try {
|
|
1249
|
+
after = parsePolicy(parseDocument(edited.text).toJS(), options.policyPath);
|
|
1250
|
+
}
|
|
1251
|
+
catch (err) {
|
|
1252
|
+
return {
|
|
1253
|
+
kind: "refused",
|
|
1254
|
+
why: `the change produced an invalid policy (${err.message}); nothing was written`
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
if (canonicalJson(withValue(before, segments, value)) !== canonicalJson(after)) {
|
|
1258
|
+
return { kind: "refused", why: `the change touched something other than ${path}; nothing was written` };
|
|
1259
|
+
}
|
|
1260
|
+
writeAtomically(expandPath(options.policyPath), edited.text);
|
|
1261
|
+
return {
|
|
1262
|
+
kind: "written",
|
|
1263
|
+
digest: policyDigest(after),
|
|
1264
|
+
previousDigest: actual,
|
|
1265
|
+
path,
|
|
1266
|
+
before: current,
|
|
1267
|
+
after: value,
|
|
1268
|
+
loosens
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
/** Constraints never authored from the console; one already in the file may be carried untouched. */
|
|
1272
|
+
const NEVER_AUTHORED = ["pattern", "coerce"];
|
|
1273
|
+
/**
|
|
1274
|
+
* A rule as the console sends it, validated by the policy schema itself.
|
|
1275
|
+
*
|
|
1276
|
+
* `pattern` and `coerce` are refused unless they are exactly what the same
|
|
1277
|
+
* rule already carries at the same path -- see `REFUSED_CONSTRAINTS`.
|
|
1278
|
+
*/
|
|
1279
|
+
export function parseRuleInput(input, existing) {
|
|
1280
|
+
const result = RuleSchema.safeParse(input);
|
|
1281
|
+
if (!result.success) {
|
|
1282
|
+
const detail = result.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
|
|
1283
|
+
throw new PolicyWriteError(`invalid rule: ${detail}`);
|
|
1284
|
+
}
|
|
1285
|
+
const rule = result.data;
|
|
1286
|
+
const paths = Object.keys(rule.args ?? {});
|
|
1287
|
+
if (paths.length > MAX_ARG_PATHS) {
|
|
1288
|
+
throw new PolicyWriteError(`a rule written from here bounds at most ${MAX_ARG_PATHS} arguments; this one bounds ${paths.length}`);
|
|
1289
|
+
}
|
|
1290
|
+
for (const path of paths) {
|
|
1291
|
+
if (path.length > MAX_PATH_LENGTH) {
|
|
1292
|
+
throw new PolicyWriteError(`the argument path "${path.slice(0, 40)}…" is longer than ${MAX_PATH_LENGTH} characters`);
|
|
1293
|
+
}
|
|
1294
|
+
const parsed = parseArgPath(path);
|
|
1295
|
+
if (!parsed.ok)
|
|
1296
|
+
throw new PolicyWriteError(`"${path}" is not an argument path: ${parsed.error}`);
|
|
1297
|
+
const constraint = rule.args[path];
|
|
1298
|
+
const had = (existing?.args?.[path] ?? {});
|
|
1299
|
+
for (const banned of NEVER_AUTHORED) {
|
|
1300
|
+
if (constraint[banned] !== undefined && canonicalJson(constraint[banned]) !== canonicalJson(had[banned])) {
|
|
1301
|
+
throw new PolicyWriteError(refusedConstraintReason(banned, path));
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
if (Array.isArray(constraint["enum"]) && constraint["enum"].length > MAX_ENUM_MEMBERS) {
|
|
1305
|
+
throw new PolicyWriteError(`"${path}" lists more than ${MAX_ENUM_MEMBERS} allowed values`);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
return rule;
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Every regular expression in `after` must already be in `before`, on the same
|
|
1312
|
+
* rule and the same argument. How the raw-file writer applies the same ReDoS
|
|
1313
|
+
* guard as the form: an edit that only moves or keeps a pattern passes.
|
|
1314
|
+
*/
|
|
1315
|
+
function newlyAuthored(before, after) {
|
|
1316
|
+
for (const rule of after.rules) {
|
|
1317
|
+
const was = before.rules.find((r) => r.id === rule.id);
|
|
1318
|
+
for (const [path, c] of Object.entries(rule.args ?? {})) {
|
|
1319
|
+
const had = (was?.args?.[path] ?? {});
|
|
1320
|
+
for (const banned of NEVER_AUTHORED) {
|
|
1321
|
+
const value = c[banned];
|
|
1322
|
+
if (value !== undefined && canonicalJson(value) !== canonicalJson(had[banned])) {
|
|
1323
|
+
return `rule "${rule.id}": ${refusedConstraintReason(banned, path)}`;
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
return null;
|
|
1329
|
+
}
|
|
1330
|
+
/** The rule list an op produces, or why it cannot. */
|
|
1331
|
+
export function applyRulesOp(policy, op) {
|
|
1332
|
+
const rules = [...policy.rules];
|
|
1333
|
+
const at = (id) => rules.findIndex((r) => r.id === id);
|
|
1334
|
+
switch (op.kind) {
|
|
1335
|
+
case "set": {
|
|
1336
|
+
const i = at(op.ruleId);
|
|
1337
|
+
if (i === -1)
|
|
1338
|
+
return { ok: false, missing: true, why: `there is no rule "${op.ruleId}" in this policy` };
|
|
1339
|
+
if (op.rule.id !== op.ruleId) {
|
|
1340
|
+
return {
|
|
1341
|
+
ok: false,
|
|
1342
|
+
why: `the rule's id is "${op.rule.id}" but "${op.ruleId}" is being edited. Ids are what the activity ` +
|
|
1343
|
+
`log records, so a rename is a delete and an add, done deliberately.`
|
|
1344
|
+
};
|
|
1345
|
+
}
|
|
1346
|
+
rules[i] = op.rule;
|
|
1347
|
+
return { ok: true, rules };
|
|
1348
|
+
}
|
|
1349
|
+
case "add": {
|
|
1350
|
+
if (at(op.rule.id) !== -1)
|
|
1351
|
+
return { ok: false, why: `a rule with id "${op.rule.id}" already exists` };
|
|
1352
|
+
const index = op.index ?? rules.length;
|
|
1353
|
+
if (!Number.isInteger(index) || index < 0 || index > rules.length) {
|
|
1354
|
+
return { ok: false, why: `position ${index} is outside the list, which has ${rules.length} rule(s)` };
|
|
1355
|
+
}
|
|
1356
|
+
rules.splice(index, 0, op.rule);
|
|
1357
|
+
return { ok: true, rules };
|
|
1358
|
+
}
|
|
1359
|
+
case "delete": {
|
|
1360
|
+
const i = at(op.ruleId);
|
|
1361
|
+
if (i === -1)
|
|
1362
|
+
return { ok: false, missing: true, why: `there is no rule "${op.ruleId}" in this policy` };
|
|
1363
|
+
rules.splice(i, 1);
|
|
1364
|
+
return { ok: true, rules };
|
|
1365
|
+
}
|
|
1366
|
+
case "order": {
|
|
1367
|
+
const ids = rules.map((r) => r.id);
|
|
1368
|
+
const unique = new Set(op.order);
|
|
1369
|
+
if (unique.size !== op.order.length || op.order.length !== ids.length || !ids.every((id) => unique.has(id))) {
|
|
1370
|
+
return {
|
|
1371
|
+
ok: false,
|
|
1372
|
+
why: `the new order must name every rule exactly once (${ids.length} rule(s): ${ids.join(", ")}). ` +
|
|
1373
|
+
`Reordering cannot also add or remove one.`
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
return { ok: true, rules: op.order.map((id) => rules[at(id)]) };
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* What changes for each live tool, comparing `decide()` before and after.
|
|
1382
|
+
*
|
|
1383
|
+
* Asked the way the Tools page asks (`argsUnknown`, the effect the gateway
|
|
1384
|
+
* published) and with the tenant block set aside: tenant separation is graded
|
|
1385
|
+
* as a setting of its own, and with it in place every tool reads "refused,
|
|
1386
|
+
* no tenant" in a process that has none, which would hide every rule change.
|
|
1387
|
+
*/
|
|
1388
|
+
export function verdictChanges(before, after, tools) {
|
|
1389
|
+
const ask = (policy, t) => decide({ tool: t.name, effect: t.effect ?? undefined, policy: { ...policy, tenant: undefined }, argsUnknown: true });
|
|
1390
|
+
const bounds = (policy, ruleId) => canonicalJson(boundsOf(policy.rules.find((r) => r.id === ruleId)));
|
|
1391
|
+
const changes = [];
|
|
1392
|
+
for (const t of tools) {
|
|
1393
|
+
const a = ask(before, t);
|
|
1394
|
+
const b = ask(after, t);
|
|
1395
|
+
const boundsMoved = bounds(before, a.ruleId) !== bounds(after, b.ruleId);
|
|
1396
|
+
if (a.kind === b.kind && a.ruleId === b.ruleId && !boundsMoved)
|
|
1397
|
+
continue;
|
|
1398
|
+
const hadBounds = bounds(before, a.ruleId) !== canonicalJson(null);
|
|
1399
|
+
changes.push({
|
|
1400
|
+
tool: t.name,
|
|
1401
|
+
before: a.kind,
|
|
1402
|
+
after: b.kind,
|
|
1403
|
+
beforeRule: a.ruleId,
|
|
1404
|
+
afterRule: b.ruleId,
|
|
1405
|
+
loosens: RANK[b.kind] > RANK[a.kind] || (RANK[b.kind] === RANK[a.kind] && b.kind !== "deny" && hadBounds && boundsMoved)
|
|
1406
|
+
});
|
|
1407
|
+
}
|
|
1408
|
+
return changes;
|
|
1409
|
+
}
|
|
1410
|
+
const UNKNOWN_ARGS_RANK = { deny: 0, approve: 1, allow: 2 };
|
|
1411
|
+
const VIOLATION_RANK = { deny: 0, approve: 1 };
|
|
1412
|
+
/** A rule that lets a write or a delete run with nobody asked. Always loosening, served tools or not. */
|
|
1413
|
+
function allowsMutation(rule) {
|
|
1414
|
+
return rule.decision === "allow" && (rule.effect === "write" || rule.effect === "destructive");
|
|
1415
|
+
}
|
|
1416
|
+
/**
|
|
1417
|
+
* Whether a rule list loosens, judged from the rules alone.
|
|
1418
|
+
*
|
|
1419
|
+
* Always applied beside the verdict comparison, never instead of it: verdicts
|
|
1420
|
+
* are only asked of the tools a gateway serves right now, and a rule written
|
|
1421
|
+
* for a tool that is not served yet -- or a refusal removed for one that has
|
|
1422
|
+
* gone away -- governs that tool the moment it comes back. Deliberately
|
|
1423
|
+
* conservative: a changed `match` counts, since whether a glob widens cannot
|
|
1424
|
+
* be proved from the text.
|
|
1425
|
+
*/
|
|
1426
|
+
function rulesLoosenByShape(before, after) {
|
|
1427
|
+
const reasons = [];
|
|
1428
|
+
const afterIds = after.map((r) => r.id);
|
|
1429
|
+
for (const rule of after) {
|
|
1430
|
+
const was = before.find((r) => r.id === rule.id);
|
|
1431
|
+
if (!was) {
|
|
1432
|
+
if (rule.decision !== "deny")
|
|
1433
|
+
reasons.push(`new rule "${rule.id}" says ${rule.decision}`);
|
|
1434
|
+
continue;
|
|
1435
|
+
}
|
|
1436
|
+
if (canonicalJson(was) === canonicalJson(rule))
|
|
1437
|
+
continue;
|
|
1438
|
+
if (RANK[rule.decision] > RANK[was.decision] ||
|
|
1439
|
+
rule.match !== was.match ||
|
|
1440
|
+
VIOLATION_RANK[rule.on_violation] > VIOLATION_RANK[was.on_violation] ||
|
|
1441
|
+
UNKNOWN_ARGS_RANK[rule.unknown_args] > UNKNOWN_ARGS_RANK[was.unknown_args] ||
|
|
1442
|
+
canonicalJson(rule.args ?? {}) !== canonicalJson(was.args ?? {})) {
|
|
1443
|
+
reasons.push(`rule "${rule.id}" may let more through than it did`);
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
for (const was of before) {
|
|
1447
|
+
if (!afterIds.includes(was.id) && (was.decision !== "allow" || hasBounds(was))) {
|
|
1448
|
+
reasons.push(`rule "${was.id}", which said ${was.decision}${hasBounds(was) ? " within bounds" : ""}, is removed`);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
/*
|
|
1452
|
+
* A reorder loosens when a rule now comes before one it used to follow and
|
|
1453
|
+
* is not stricter than it: an allow or approve moved above a deny, an allow
|
|
1454
|
+
* above an approve, or a rule overtaking a bounded one of the same kind.
|
|
1455
|
+
* Moving a refusal up, or two refusals past each other, only tightens.
|
|
1456
|
+
*/
|
|
1457
|
+
const beforeAt = new Map(before.map((r, i) => [r.id, i]));
|
|
1458
|
+
const kept = after.filter((r) => beforeAt.has(r.id));
|
|
1459
|
+
for (let i = 0; i < kept.length; i++) {
|
|
1460
|
+
for (let j = i + 1; j < kept.length; j++) {
|
|
1461
|
+
const up = kept[i];
|
|
1462
|
+
const passed = kept[j];
|
|
1463
|
+
if (beforeAt.get(up.id) < beforeAt.get(passed.id))
|
|
1464
|
+
continue;
|
|
1465
|
+
if (up.decision === "deny" || RANK[up.decision] < RANK[passed.decision])
|
|
1466
|
+
continue;
|
|
1467
|
+
if (RANK[up.decision] === RANK[passed.decision] && !hasBounds(passed))
|
|
1468
|
+
continue;
|
|
1469
|
+
reasons.push(`rule "${up.id}" now comes before rule "${passed.id}", which said ${passed.decision}`);
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
return reasons;
|
|
1473
|
+
}
|
|
1474
|
+
/** How a change from one policy to another moves what gets through. */
|
|
1475
|
+
export function assessPolicyChange(before, after, tools) {
|
|
1476
|
+
const changes = verdictChanges(before, after, tools);
|
|
1477
|
+
const reasons = [];
|
|
1478
|
+
for (const c of changes.filter((c) => c.loosens)) {
|
|
1479
|
+
reasons.push(c.before === c.after
|
|
1480
|
+
? `${c.tool}'s argument bounds change (now from "${c.afterRule}")`
|
|
1481
|
+
: `${c.tool} goes from ${c.before} to ${c.after}`);
|
|
1482
|
+
}
|
|
1483
|
+
for (const rule of after.rules) {
|
|
1484
|
+
const was = before.rules.find((r) => r.id === rule.id);
|
|
1485
|
+
if (allowsMutation(rule) && (!was || !allowsMutation(was) || canonicalJson(was) !== canonicalJson(rule))) {
|
|
1486
|
+
reasons.push(`rule "${rule.id}" lets a ${rule.effect} tool run with nobody asked`);
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
reasons.push(...rulesLoosenByShape(before.rules, after.rules));
|
|
1490
|
+
for (const path of POLICY_SETTING_PATHS) {
|
|
1491
|
+
const a = policySettingValue(before, path);
|
|
1492
|
+
const b = policySettingValue(after, path);
|
|
1493
|
+
if (a !== undefined && b !== undefined && settingLoosens(path, a, b)) {
|
|
1494
|
+
reasons.push(`${path} goes from ${JSON.stringify(a)} to ${JSON.stringify(b)}`);
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
if (before.tenant && !after.tenant)
|
|
1498
|
+
reasons.push("customer separation (the tenant block) is removed");
|
|
1499
|
+
/*
|
|
1500
|
+
* Everything the table does not grade -- where the log and the queue live,
|
|
1501
|
+
* who may administer, where a customer is read from -- is compared whole.
|
|
1502
|
+
* The console cannot say which way such a change points, so it says it
|
|
1503
|
+
* loosens and lets a person confirm it.
|
|
1504
|
+
*/
|
|
1505
|
+
const ungraded = (p) => {
|
|
1506
|
+
const copy = JSON.parse(JSON.stringify(p));
|
|
1507
|
+
for (const path of POLICY_SETTING_PATHS) {
|
|
1508
|
+
const segments = path.split(".");
|
|
1509
|
+
let at = copy;
|
|
1510
|
+
for (const key of segments.slice(0, -1))
|
|
1511
|
+
at = (at[key] ?? {});
|
|
1512
|
+
delete at[segments[segments.length - 1]];
|
|
1513
|
+
}
|
|
1514
|
+
delete copy["rules"];
|
|
1515
|
+
delete copy["name"];
|
|
1516
|
+
if (!after.tenant)
|
|
1517
|
+
delete copy["tenant"];
|
|
1518
|
+
return canonicalJson(copy);
|
|
1519
|
+
};
|
|
1520
|
+
if (ungraded(before) !== ungraded(after)) {
|
|
1521
|
+
reasons.push("something the console cannot grade changes (audit or approvals location, admin, or how a customer is identified)");
|
|
1522
|
+
}
|
|
1523
|
+
const loosenReasons = [...new Set(reasons)];
|
|
1524
|
+
return { changes, loosens: loosenReasons.length > 0, loosenReasons };
|
|
1525
|
+
}
|
|
1526
|
+
export function previewRulesOp(policy, op, tools) {
|
|
1527
|
+
const applied = applyRulesOp(policy, op);
|
|
1528
|
+
if (!applied.ok)
|
|
1529
|
+
return applied;
|
|
1530
|
+
const after = { ...policy, rules: applied.rules };
|
|
1531
|
+
const previous = op.kind === "set" || op.kind === "delete" ? (policy.rules.find((r) => r.id === op.ruleId) ?? null) : null;
|
|
1532
|
+
return { ok: true, rules: applied.rules, previous, ...assessPolicyChange(policy, after, tools) };
|
|
1533
|
+
}
|
|
1534
|
+
/** The rule's own lines, without a comment: the person editing it owns whatever note sits above. */
|
|
1535
|
+
function ruleLines(rule, indent) {
|
|
1536
|
+
return new Document([ruleToPlain(rule)])
|
|
1537
|
+
.toString(TO_STRING)
|
|
1538
|
+
.trimEnd()
|
|
1539
|
+
.split("\n")
|
|
1540
|
+
.map((l) => `${indent}${l}`);
|
|
1541
|
+
}
|
|
1542
|
+
/** The op, applied to the file's lines. Comments above a rule travel with it. */
|
|
1543
|
+
function spliceRulesOp(text, op, rulesBefore) {
|
|
1544
|
+
const layout = layoutRules(text);
|
|
1545
|
+
if ("error" in layout)
|
|
1546
|
+
return { ok: false, why: layout.error };
|
|
1547
|
+
const { spans, indent } = layout;
|
|
1548
|
+
if (spans.length !== rulesBefore.length || spans.some((s, i) => s.id !== rulesBefore[i].id)) {
|
|
1549
|
+
return {
|
|
1550
|
+
ok: false,
|
|
1551
|
+
why: "the rules in this file are not written one block per rule with an `id:` line each, so they cannot be " +
|
|
1552
|
+
"edited here without reformatting them. Use the policy file editor instead."
|
|
1553
|
+
};
|
|
1554
|
+
}
|
|
1555
|
+
const lines = [...layout.lines];
|
|
1556
|
+
const spanOf = (id) => spans.find((s) => s.id === id);
|
|
1557
|
+
switch (op.kind) {
|
|
1558
|
+
case "set": {
|
|
1559
|
+
const span = spanOf(op.ruleId);
|
|
1560
|
+
let body = span.from;
|
|
1561
|
+
while (body < span.to && (lines[body].trim() === "" || lines[body].trim().startsWith("#")))
|
|
1562
|
+
body++;
|
|
1563
|
+
lines.splice(body, span.to - body, ...ruleLines(op.rule, indent));
|
|
1564
|
+
break;
|
|
1565
|
+
}
|
|
1566
|
+
case "add": {
|
|
1567
|
+
const index = op.index ?? spans.length;
|
|
1568
|
+
lines.splice(index < spans.length ? spans[index].from : layout.end, 0, ...ruleLines(op.rule, indent));
|
|
1569
|
+
break;
|
|
1570
|
+
}
|
|
1571
|
+
case "delete": {
|
|
1572
|
+
const span = spanOf(op.ruleId);
|
|
1573
|
+
lines.splice(span.from, span.to - span.from);
|
|
1574
|
+
if (spans.length === 1) {
|
|
1575
|
+
const key = lines[layout.keyAt];
|
|
1576
|
+
const trailing = key.match(/#.*$/)?.[0];
|
|
1577
|
+
lines[layout.keyAt] = `${key.match(/^\s*/)[0]}rules: []${trailing ? ` ${trailing}` : ""}`;
|
|
1578
|
+
}
|
|
1579
|
+
break;
|
|
1580
|
+
}
|
|
1581
|
+
case "order": {
|
|
1582
|
+
if (spans.length === 0)
|
|
1583
|
+
break;
|
|
1584
|
+
const blocks = op.order.map((id) => {
|
|
1585
|
+
const s = spanOf(id);
|
|
1586
|
+
return layout.lines.slice(s.from, s.to);
|
|
1587
|
+
});
|
|
1588
|
+
const from = spans[0].from;
|
|
1589
|
+
const to = spans[spans.length - 1].to;
|
|
1590
|
+
lines.splice(from, to - from, ...blocks.flat());
|
|
1591
|
+
break;
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
return { ok: true, text: lines.join("\n") };
|
|
1595
|
+
}
|
|
1596
|
+
/**
|
|
1597
|
+
* Add, rewrite, remove or reorder any rule -- including hand-written globs.
|
|
1598
|
+
*
|
|
1599
|
+
* Unlike `writeToolRule` this is not confined to one literal tool, which is
|
|
1600
|
+
* exactly why loosening is graded across every live tool before anything is
|
|
1601
|
+
* written, and why the proof afterwards is that the rule list is precisely
|
|
1602
|
+
* the one previewed and nothing outside `rules` moved.
|
|
1603
|
+
*/
|
|
1604
|
+
export function writePolicyRules(options) {
|
|
1605
|
+
if (options.writesAllowed === false)
|
|
1606
|
+
return refusedByConfig();
|
|
1607
|
+
const read = readPolicyFile(options.policyPath, options.expectedDigest);
|
|
1608
|
+
if ("kind" in read)
|
|
1609
|
+
return read;
|
|
1610
|
+
const { text, before, actual } = read;
|
|
1611
|
+
const { op } = options;
|
|
1612
|
+
if (op.kind === "set" || op.kind === "add") {
|
|
1613
|
+
const existing = op.kind === "set" ? before.rules.find((r) => r.id === op.ruleId) : undefined;
|
|
1614
|
+
try {
|
|
1615
|
+
parseRuleInput(op.rule, existing);
|
|
1616
|
+
}
|
|
1617
|
+
catch (err) {
|
|
1618
|
+
return { kind: "refused", why: err.message };
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
const preview = previewRulesOp(before, op, options.tools);
|
|
1622
|
+
if (!preview.ok)
|
|
1623
|
+
return preview;
|
|
1624
|
+
if (canonicalJson(preview.rules) === canonicalJson(before.rules)) {
|
|
1625
|
+
return { kind: "refused", why: "that leaves the rules exactly as they are; nothing was written" };
|
|
1626
|
+
}
|
|
1627
|
+
const gate = loosenGate(preview.loosens, options.acknowledged, options.overridesAllowed, `This loosens the policy: ${preview.loosenReasons.join("; ")}`);
|
|
1628
|
+
if (gate)
|
|
1629
|
+
return gate;
|
|
1630
|
+
const edited = spliceRulesOp(text, op, before.rules);
|
|
1631
|
+
if (!edited.ok)
|
|
1632
|
+
return { kind: "refused", why: edited.why };
|
|
1633
|
+
let after;
|
|
1634
|
+
try {
|
|
1635
|
+
after = parsePolicy(parseDocument(edited.text).toJS(), options.policyPath);
|
|
1636
|
+
}
|
|
1637
|
+
catch (err) {
|
|
1638
|
+
return {
|
|
1639
|
+
kind: "refused",
|
|
1640
|
+
why: `the change could not be made without producing an invalid policy (${err.message}); nothing was written`
|
|
1641
|
+
};
|
|
1642
|
+
}
|
|
1643
|
+
const violation = assertOnlyRulesChanged(before, after) ??
|
|
1644
|
+
(canonicalJson(after.rules) === canonicalJson(preview.rules) ? null : "the rules written are not the rules previewed");
|
|
1645
|
+
if (violation)
|
|
1646
|
+
return { kind: "refused", why: `${violation}; nothing was written` };
|
|
1647
|
+
writeAtomically(expandPath(options.policyPath), edited.text);
|
|
1648
|
+
return { kind: "written", digest: policyDigest(after), previousDigest: actual, ...preview };
|
|
1649
|
+
}
|
|
1650
|
+
/**
|
|
1651
|
+
* What replacing the policy file with `text` would do. Writes nothing.
|
|
1652
|
+
*
|
|
1653
|
+
* Invalid YAML and an invalid policy are answers here, not errors: the editor
|
|
1654
|
+
* shows them beside the text.
|
|
1655
|
+
*/
|
|
1656
|
+
export function previewPolicyFile(before, text, tools) {
|
|
1657
|
+
const invalid = (error) => ({
|
|
1658
|
+
valid: false,
|
|
1659
|
+
error,
|
|
1660
|
+
policy: null,
|
|
1661
|
+
changes: [],
|
|
1662
|
+
loosens: false,
|
|
1663
|
+
loosenReasons: []
|
|
1664
|
+
});
|
|
1665
|
+
const doc = parseDocument(text, { prettyErrors: true });
|
|
1666
|
+
if (doc.errors.length > 0)
|
|
1667
|
+
return invalid(`not valid YAML: ${doc.errors[0].message}`);
|
|
1668
|
+
let after;
|
|
1669
|
+
try {
|
|
1670
|
+
after = parsePolicy(doc.toJS(), "the edited policy");
|
|
1671
|
+
}
|
|
1672
|
+
catch (err) {
|
|
1673
|
+
return invalid(err.message);
|
|
1674
|
+
}
|
|
1675
|
+
const authored = newlyAuthored(before, after);
|
|
1676
|
+
if (authored)
|
|
1677
|
+
return invalid(authored);
|
|
1678
|
+
return { valid: true, error: null, policy: after, ...assessPolicyChange(before, after, tools) };
|
|
1679
|
+
}
|
|
1680
|
+
/** Replace the policy file with `text`, after the same checks as every other write. */
|
|
1681
|
+
export function writePolicyFile(options) {
|
|
1682
|
+
if (options.writesAllowed === false)
|
|
1683
|
+
return refusedByConfig();
|
|
1684
|
+
const read = readPolicyFile(options.policyPath, options.expectedDigest);
|
|
1685
|
+
if ("kind" in read)
|
|
1686
|
+
return read;
|
|
1687
|
+
if (read.text === options.text)
|
|
1688
|
+
return { kind: "refused", why: "the text is unchanged; nothing was written" };
|
|
1689
|
+
const preview = previewPolicyFile(read.before, options.text, options.tools);
|
|
1690
|
+
if (!preview.valid)
|
|
1691
|
+
return { kind: "refused", why: `${preview.error}; nothing was written` };
|
|
1692
|
+
const gate = loosenGate(preview.loosens, options.acknowledged, options.overridesAllowed, `This loosens the policy: ${preview.loosenReasons.join("; ")}`);
|
|
1693
|
+
if (gate)
|
|
1694
|
+
return gate;
|
|
1695
|
+
writeAtomically(expandPath(options.policyPath), options.text);
|
|
1696
|
+
return { kind: "written", digest: policyDigest(preview.policy), previousDigest: read.actual, ...preview };
|
|
1697
|
+
}
|