hmcp-web 0.0.0-stage → 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/LICENSE +77 -0
- package/README.md +50 -2
- package/THIRD-PARTY-NOTICES.md +110 -0
- package/bin/hmcp-web.js +20 -0
- package/dist/api.d.ts +11 -0
- package/dist/api.js +1404 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +40 -0
- package/dist/contracts/onboarding.d.ts +233 -0
- package/dist/contracts/onboarding.js +1 -0
- package/dist/http.d.ts +72 -0
- package/dist/http.js +319 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/model/console-settings.d.ts +37 -0
- package/dist/model/console-settings.js +74 -0
- package/dist/model/doctor.d.ts +68 -0
- package/dist/model/doctor.js +254 -0
- package/dist/model/fs-browse.d.ts +9 -0
- package/dist/model/fs-browse.js +184 -0
- package/dist/model/gateway-config.d.ts +287 -0
- package/dist/model/gateway-config.js +760 -0
- package/dist/model/metrics.d.ts +65 -0
- package/dist/model/metrics.js +198 -0
- package/dist/model/oauth-flows.d.ts +60 -0
- package/dist/model/oauth-flows.js +79 -0
- package/dist/model/pipeline.d.ts +58 -0
- package/dist/model/pipeline.js +84 -0
- package/dist/model/probe.d.ts +155 -0
- package/dist/model/probe.js +385 -0
- package/dist/model/process.d.ts +100 -0
- package/dist/model/process.js +278 -0
- package/dist/model/protection.d.ts +378 -0
- package/dist/model/protection.js +470 -0
- package/dist/model/registry-cache.d.ts +59 -0
- package/dist/model/registry-cache.js +238 -0
- package/dist/model/scan.d.ts +48 -0
- package/dist/model/scan.js +59 -0
- package/dist/model/server.d.ts +127 -0
- package/dist/model/server.js +243 -0
- package/dist/model/tools.d.ts +61 -0
- package/dist/model/tools.js +72 -0
- package/dist/routes/catalog.d.ts +8 -0
- package/dist/routes/catalog.js +47 -0
- package/dist/routes/connect.d.ts +14 -0
- package/dist/routes/connect.js +633 -0
- package/dist/routes/oauth.d.ts +55 -0
- package/dist/routes/oauth.js +406 -0
- package/dist/routes/policy.d.ts +34 -0
- package/dist/routes/policy.js +513 -0
- package/dist/routes/runtime.d.ts +6 -0
- package/dist/routes/runtime.js +921 -0
- package/dist/routes/servers-add.d.ts +24 -0
- package/dist/routes/servers-add.js +1091 -0
- package/dist/routes/system.d.ts +4 -0
- package/dist/routes/system.js +13 -0
- package/dist/start.d.ts +56 -0
- package/dist/start.js +164 -0
- package/dist-ui/assets/Activity-BqKGpXMN.js +1 -0
- package/dist-ui/assets/Approvals-Qo7bCcli.js +1 -0
- package/dist-ui/assets/AttachApp-0zRSPgSY.js +5 -0
- package/dist-ui/assets/Connections-CE0JGe8c.js +2 -0
- package/dist-ui/assets/Gallery-B39L2Yma.js +17 -0
- package/dist-ui/assets/PreApprovals-BsIhjMqb.js +1 -0
- package/dist-ui/assets/Protection-DlB09ABa.js +1 -0
- package/dist-ui/assets/Safety-CN-oHO2h.js +1 -0
- package/dist-ui/assets/Settings-BLD7G1Ag.js +1 -0
- package/dist-ui/assets/StartPage-HuZSnmSr.js +1 -0
- package/dist-ui/assets/Suggestions-Dp7pofcs.js +1 -0
- package/dist-ui/assets/Tools-Bfot3bx5.js +4 -0
- package/dist-ui/assets/index-Khp0l1zp.js +16 -0
- package/dist-ui/assets/index-Ylyt4DEr.css +2 -0
- package/dist-ui/assets/kit-DQ7Oxf5n.js +4 -0
- package/dist-ui/brand/logo-256.png +0 -0
- package/dist-ui/brand/logo-512.png +0 -0
- package/dist-ui/brand/logo.svg +6 -0
- package/dist-ui/brand/mark.svg +5 -0
- package/dist-ui/fonts/OFL.txt +99 -0
- package/dist-ui/fonts/README.md +21 -0
- package/dist-ui/fonts/jetbrainsmono-latin.woff2 +0 -0
- package/dist-ui/fonts/manrope-latin.woff2 +0 -0
- package/dist-ui/index.html +51 -0
- package/package.json +71 -4
package/dist/api.js
ADDED
|
@@ -0,0 +1,1404 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { AuditLog, applyExposureChange, TOOL_RULE_CLEAR, TOOL_RULE_REFUSED, TOOL_RULE_SET, TOOL_RULE_UPDATE, boundsOf, globMatch, clearToolRule, decide, parseToolRuleDraft, policyDigest, previewClearToolRule, previewToolRule, ruleToYaml, UNCLASSIFIED_POSTURE_RULE, UNCLASSIFIED_RULE, writeToolRule, writeUnclassifiedPosture, approvalViolations, MAX_GRANT_TTL_SECONDS, REMEMBER_DEFAULT_TTL_SECONDS, REMEMBER_DEFAULT_USES, RememberError, rememberOnApprove, NO_TENANT, grantBoundGaps, grantCoversTool, grantMatches, hasLooseListItems, isOlderRemembered, parseExposureChange, parseGrantDraft, queryAuditLog, readRegistry, runtimeStateIsLive, verifyAuditLog, writeRegistry } from "hmcp-core";
|
|
4
|
+
import { badRequest, conflict, notFound, route, unprocessable } from "./http.js";
|
|
5
|
+
import { buildProtection, effectiveReach, recentActivity, toolProtection } from "./model/protection.js";
|
|
6
|
+
import { chooseTenant, knownTenants, loadServer, scopeFor, scopedFor, storeFor } from "./model/server.js";
|
|
7
|
+
import { surfaceWritable, toolSurfaceFor } from "./model/tools.js";
|
|
8
|
+
import { buildMetrics, isWindow } from "./model/metrics.js";
|
|
9
|
+
import { buildScan } from "./model/scan.js";
|
|
10
|
+
import { toSarif } from "hmcp-scanner";
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
import { ENFORCEMENT_PIPELINE } from "./model/pipeline.js";
|
|
13
|
+
import { processes } from "./model/process.js";
|
|
14
|
+
import { runtimeRoutes } from "./routes/runtime.js";
|
|
15
|
+
import { policyRoutes } from "./routes/policy.js";
|
|
16
|
+
import { connectRoutes } from "./routes/connect.js";
|
|
17
|
+
import { doctorPathDirs } from "./model/doctor.js";
|
|
18
|
+
import { serversAddRoutes } from "./routes/servers-add.js";
|
|
19
|
+
import { catalogRoutes } from "./routes/catalog.js";
|
|
20
|
+
import { oauthRoutes } from "./routes/oauth.js";
|
|
21
|
+
import { systemRoutes } from "./routes/system.js";
|
|
22
|
+
/* ------------------------------------------------------------------ helpers */
|
|
23
|
+
function registry(options) {
|
|
24
|
+
return readRegistry(options.registryPath);
|
|
25
|
+
}
|
|
26
|
+
function entryById(options, id) {
|
|
27
|
+
const found = registry(options).servers.find((s) => s.id === id);
|
|
28
|
+
if (!found)
|
|
29
|
+
throw notFound(`no registered server with id "${id}"`);
|
|
30
|
+
return found;
|
|
31
|
+
}
|
|
32
|
+
function serverById(options, id) {
|
|
33
|
+
try {
|
|
34
|
+
return loadServer(entryById(options, id));
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
if (err.status)
|
|
38
|
+
throw err;
|
|
39
|
+
throw unprocessable(`server "${id}" could not be loaded: ${err.message}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The components of the other registered toolboxes that write to the same
|
|
44
|
+
* audit log as this one. Every toolbox writes to `~/.hmcp/audit.jsonl`
|
|
45
|
+
* unless told otherwise, so without this one toolbox's Home counted and
|
|
46
|
+
* listed its neighbours' calls as its own (UT5 round 4). The console's own
|
|
47
|
+
* records (`hmcp-web`) stay: they are written to the log of the toolbox
|
|
48
|
+
* they changed.
|
|
49
|
+
*/
|
|
50
|
+
function otherComponentsSharingLog(options, server) {
|
|
51
|
+
const out = new Set();
|
|
52
|
+
for (const entry of registry(options).servers) {
|
|
53
|
+
if (entry.id === server.entry.id)
|
|
54
|
+
continue;
|
|
55
|
+
let other;
|
|
56
|
+
try {
|
|
57
|
+
other = loadServer(entry);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (other.auditPath === server.auditPath && other.component !== server.component)
|
|
63
|
+
out.add(other.component);
|
|
64
|
+
}
|
|
65
|
+
return [...out];
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* One server, and the tenant whose rows this request is about.
|
|
69
|
+
*
|
|
70
|
+
* Every scoped route goes through this rather than resolving a tenant of its
|
|
71
|
+
* own, so no route can be written that forgets to and quietly falls back to the
|
|
72
|
+
* empty tenant. `chooseTenant` refuses where the console cannot legitimately
|
|
73
|
+
* know the answer, and the refusal surfaces as a 422 explaining how to name one.
|
|
74
|
+
*/
|
|
75
|
+
function scopedRequest(options, id, query) {
|
|
76
|
+
const server = serverById(options, id);
|
|
77
|
+
const choice = chooseTenant(server, query.get("tenant"));
|
|
78
|
+
if (!choice.ok)
|
|
79
|
+
throw unprocessable(choice.why);
|
|
80
|
+
return { server, tenant: choice.tenant, explicit: choice.explicit };
|
|
81
|
+
}
|
|
82
|
+
/** An audit log scoped to one server's own configuration. */
|
|
83
|
+
function auditFor(server, actor) {
|
|
84
|
+
return new AuditLog({
|
|
85
|
+
config: server.policy.audit,
|
|
86
|
+
actor,
|
|
87
|
+
component: "hmcp-web",
|
|
88
|
+
cwd: server.cwd
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The tool a rule is about, checked against what a *live* gateway says it is
|
|
93
|
+
* serving.
|
|
94
|
+
*
|
|
95
|
+
* The same check the exposure route makes, and for the same reason: a rule
|
|
96
|
+
* naming a tool nobody serves reads as a decision and governs nothing. It
|
|
97
|
+
* matters twice over here, because the rule is also written into a file and
|
|
98
|
+
* reviewed in git by someone with no way to tell.
|
|
99
|
+
*/
|
|
100
|
+
function toolRuleTarget(server, tenant, body, actor) {
|
|
101
|
+
const raw = (body ?? {});
|
|
102
|
+
const surface = toolSurfaceFor(server, tenant);
|
|
103
|
+
// From the last list the toolbox published, so a rule can be set while no AI app is running it.
|
|
104
|
+
const writable = surfaceWritable(surface, { allowStale: true });
|
|
105
|
+
if (!writable.ok)
|
|
106
|
+
throw unprocessable(`cannot set a rule on "${server.entry.id}": ${writable.why}`);
|
|
107
|
+
/*
|
|
108
|
+
* Anything this route does not understand is a 422, not a dropped key.
|
|
109
|
+
*
|
|
110
|
+
* The draft is built field by field, so an unknown key could never reach the
|
|
111
|
+
* policy file — but it would be accepted with a 200, and a client that sent
|
|
112
|
+
* something and got a success would reasonably believe it took. "Not
|
|
113
|
+
* written" and "refused" are the same outcome on disk and opposite outcomes
|
|
114
|
+
* for whoever asked. `id` and `match` are refused by name: a client does not
|
|
115
|
+
* get to choose the rule id it is writing.
|
|
116
|
+
*/
|
|
117
|
+
const allowed = new Set([
|
|
118
|
+
"tool",
|
|
119
|
+
"effect",
|
|
120
|
+
"decision",
|
|
121
|
+
"args",
|
|
122
|
+
"on_violation",
|
|
123
|
+
"unknown_args",
|
|
124
|
+
"reason",
|
|
125
|
+
"acknowledged",
|
|
126
|
+
"expectedDigest"
|
|
127
|
+
]);
|
|
128
|
+
const unknown = Object.keys(raw).filter((k) => !allowed.has(k));
|
|
129
|
+
if (unknown.length > 0) {
|
|
130
|
+
throw unprocessable(`a tool rule carries a tool, an effect, a decision, argument bounds and an optional reason — ` +
|
|
131
|
+
`this request also carried ${unknown.join(", ")}. The rule's id and match are not the caller's ` +
|
|
132
|
+
`to choose, and everything else about the policy stays an edit you review in git.`);
|
|
133
|
+
}
|
|
134
|
+
const name = typeof raw["tool"] === "string" ? raw["tool"] : "";
|
|
135
|
+
const entry = surface.entries.find((t) => t.name === name);
|
|
136
|
+
if (!entry) {
|
|
137
|
+
throw notFound(`no tool "${name}" in what "${server.entry.id}" is currently serving. ` +
|
|
138
|
+
`Its upstreams advertise: ${surface.entries.map((t) => t.name).join(", ") || "nothing"}.`);
|
|
139
|
+
}
|
|
140
|
+
let draft;
|
|
141
|
+
try {
|
|
142
|
+
draft = parseToolRuleDraft({
|
|
143
|
+
tool: name,
|
|
144
|
+
effect: raw["effect"],
|
|
145
|
+
decision: raw["decision"],
|
|
146
|
+
...(raw["args"] !== undefined ? { args: raw["args"] } : {}),
|
|
147
|
+
...(raw["on_violation"] !== undefined ? { on_violation: raw["on_violation"] } : {}),
|
|
148
|
+
...(raw["unknown_args"] !== undefined ? { unknown_args: raw["unknown_args"] } : {}),
|
|
149
|
+
...(typeof raw["reason"] === "string" && raw["reason"] ? { reason: raw["reason"] } : {}),
|
|
150
|
+
...(raw["acknowledged"] !== undefined ? { acknowledged: raw["acknowledged"] } : {}),
|
|
151
|
+
actor
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
throw unprocessable(err.message);
|
|
156
|
+
}
|
|
157
|
+
return { draft, entry, liveTools: surface.entries.map((t) => t.name) };
|
|
158
|
+
}
|
|
159
|
+
function toolRulePreviewDto(server, preview) {
|
|
160
|
+
return {
|
|
161
|
+
rule: preview.rule,
|
|
162
|
+
/*
|
|
163
|
+
* Rendered by the same function the file write serialises through, so the
|
|
164
|
+
* YAML someone approves and the YAML that lands cannot differ about a
|
|
165
|
+
* carried bound.
|
|
166
|
+
*/
|
|
167
|
+
yaml: ruleToYaml(preview.rule),
|
|
168
|
+
verdict: {
|
|
169
|
+
kind: preview.verdict.kind,
|
|
170
|
+
ruleId: preview.verdict.ruleId,
|
|
171
|
+
reason: preview.verdict.reason
|
|
172
|
+
},
|
|
173
|
+
current: {
|
|
174
|
+
kind: preview.current.kind,
|
|
175
|
+
ruleId: preview.current.ruleId,
|
|
176
|
+
reason: preview.current.reason
|
|
177
|
+
},
|
|
178
|
+
/*
|
|
179
|
+
* Sent beside the verdict, never folded into it. The verdict is computed
|
|
180
|
+
* with `argsUnknown`, which skips bounds entirely — it describes the
|
|
181
|
+
* tool's posture, not any real call. A page that printed only the verdict
|
|
182
|
+
* would tell someone their bounded tool "runs" when half its calls are
|
|
183
|
+
* held.
|
|
184
|
+
*/
|
|
185
|
+
bounds: preview.bounds,
|
|
186
|
+
currentBounds: preview.currentBounds,
|
|
187
|
+
replaces: preview.replaces,
|
|
188
|
+
governedBy: preview.governedBy,
|
|
189
|
+
governedByConsole: preview.governedByConsole,
|
|
190
|
+
carriedFrom: preview.carriedFrom,
|
|
191
|
+
dropsBounds: preview.dropsBounds,
|
|
192
|
+
strandedRule: preview.strandedRule,
|
|
193
|
+
nameContradiction: preview.nameContradiction,
|
|
194
|
+
overridden: preview.overridden,
|
|
195
|
+
overriddenReason: preview.overriddenReason,
|
|
196
|
+
loosens: preview.loosens,
|
|
197
|
+
expectedDigest: policyDigest(server.policy),
|
|
198
|
+
policyPath: server.policyFile,
|
|
199
|
+
writable: server.policyWritable,
|
|
200
|
+
overridesAllowed: server.policyOverrides,
|
|
201
|
+
reloads: server.gateway.config.policy_reload,
|
|
202
|
+
approvalsReachable: server.policy.approvals.mode !== "deny",
|
|
203
|
+
onUnclassified: server.policy.defaults.on_unclassified
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Classifying from the approval queue: the same writer, with the decision
|
|
208
|
+
* pinned to `approve`.
|
|
209
|
+
*
|
|
210
|
+
* It refuses anything that is not the case it exists for -- a call held
|
|
211
|
+
* because nothing classified the tool -- so the queue cannot become a second,
|
|
212
|
+
* quieter route into the policy file.
|
|
213
|
+
*/
|
|
214
|
+
function classifyFromApproval(server, tenant, row, effect, actor) {
|
|
215
|
+
if (row.rule_id !== UNCLASSIFIED_RULE) {
|
|
216
|
+
throw new Error(`this call was held by rule "${row.rule_id}", not for want of a classification, so classifying ` +
|
|
217
|
+
`the tool would not change what happens to the next one`);
|
|
218
|
+
}
|
|
219
|
+
if (server.policyFile === null || !server.policyWritable.ok) {
|
|
220
|
+
throw new Error(server.policyWritable.why ?? "this gateway's policy cannot be written from here");
|
|
221
|
+
}
|
|
222
|
+
const surface = toolSurfaceFor(server, tenant);
|
|
223
|
+
const writable = surfaceWritable(surface);
|
|
224
|
+
if (!writable.ok)
|
|
225
|
+
throw new Error(writable.why);
|
|
226
|
+
const entry = surface.entries.find((t) => t.name === row.tool);
|
|
227
|
+
if (!entry)
|
|
228
|
+
throw new Error(`"${row.tool}" is not in what this gateway is currently serving`);
|
|
229
|
+
if (entry.effect !== null) {
|
|
230
|
+
throw new Error(`"${row.tool}" is already classified as ${entry.effect}`);
|
|
231
|
+
}
|
|
232
|
+
const draft = parseToolRuleDraft({
|
|
233
|
+
tool: row.tool,
|
|
234
|
+
effect,
|
|
235
|
+
// Fixed. See the call site.
|
|
236
|
+
decision: "approve",
|
|
237
|
+
reason: `classified while approving a held call`,
|
|
238
|
+
actor
|
|
239
|
+
});
|
|
240
|
+
const result = writeToolRule({
|
|
241
|
+
policyPath: server.policyFile,
|
|
242
|
+
draft,
|
|
243
|
+
expectedDigest: policyDigest(server.policy),
|
|
244
|
+
knownToLiveSurface: true,
|
|
245
|
+
liveTools: surface.entries.map((t) => t.name),
|
|
246
|
+
writesAllowed: true
|
|
247
|
+
});
|
|
248
|
+
if (result.kind !== "written")
|
|
249
|
+
throw new Error(result.why);
|
|
250
|
+
auditFor(server, actor).append({
|
|
251
|
+
tool: draft.tool,
|
|
252
|
+
effect: draft.effect,
|
|
253
|
+
decision: "approve",
|
|
254
|
+
tenant: tenant || null,
|
|
255
|
+
rule_id: TOOL_RULE_SET,
|
|
256
|
+
reason: `${draft.tool} classified as ${draft.effect} by ${actor} while approving a held call; ` +
|
|
257
|
+
`rule "${result.rule.id}" written to ${server.policyFile}. Calls still wait for a person.`,
|
|
258
|
+
outcome: "completed",
|
|
259
|
+
args_redacted: {
|
|
260
|
+
tool: draft.tool,
|
|
261
|
+
effect: draft.effect,
|
|
262
|
+
decision: "approve",
|
|
263
|
+
rule_id: result.rule.id,
|
|
264
|
+
origin: "approval-queue",
|
|
265
|
+
policy_digest_before: result.previousDigest,
|
|
266
|
+
policy_digest_after: result.digest
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
return { ruleId: result.rule.id };
|
|
270
|
+
}
|
|
271
|
+
/** Arguments reach the console already redacted; this only decodes them. */
|
|
272
|
+
function parseArgs(row) {
|
|
273
|
+
try {
|
|
274
|
+
return { args: JSON.parse(row.args_redacted), argsError: null };
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
return { args: row.args_redacted, argsError: "stored arguments are not valid JSON" };
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
function approvalDto(row) {
|
|
281
|
+
const { args, argsError } = parseArgs(row);
|
|
282
|
+
return {
|
|
283
|
+
id: row.id,
|
|
284
|
+
createdAt: row.created_at,
|
|
285
|
+
expiresAt: row.expires_at,
|
|
286
|
+
tool: row.tool,
|
|
287
|
+
effect: row.effect,
|
|
288
|
+
reason: row.reason,
|
|
289
|
+
actor: row.actor,
|
|
290
|
+
session: row.session,
|
|
291
|
+
state: row.state,
|
|
292
|
+
decidedAt: row.decided_at,
|
|
293
|
+
decidedBy: row.decided_by,
|
|
294
|
+
decisionNote: row.decision_note,
|
|
295
|
+
bindingHash: row.binding_hash,
|
|
296
|
+
/*
|
|
297
|
+
* Which bounds the call failed. `args` below is redacted and truncated, so
|
|
298
|
+
* for a call held by an argument bound this can be the only place the
|
|
299
|
+
* value being decided on appears — and a reviewer approving a binding over
|
|
300
|
+
* a value they were never shown is the worst version of this feature.
|
|
301
|
+
*/
|
|
302
|
+
violations: approvalViolations(row),
|
|
303
|
+
ruleId: row.rule_id,
|
|
304
|
+
policyDigest: row.policy_digest,
|
|
305
|
+
args,
|
|
306
|
+
argsError,
|
|
307
|
+
/*
|
|
308
|
+
* Whether "approve and remember" can be offered at all, by the same rules
|
|
309
|
+
* `rememberDraft` refuses by: nothing unclassified, nothing destructive,
|
|
310
|
+
* nothing whose held arguments were not recorded, no pattern-like name.
|
|
311
|
+
* Answered here so the queue hides the option instead of offering one
|
|
312
|
+
* that is refused.
|
|
313
|
+
*/
|
|
314
|
+
rememberAllowed: row.effect !== null &&
|
|
315
|
+
row.effect !== "destructive" &&
|
|
316
|
+
row.held_args !== null &&
|
|
317
|
+
!/[*?{},]/.test(row.tool)
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
/** `remember` on a decision: how long and how many calls. Bounds beyond the shape are core's. */
|
|
321
|
+
const RememberSchema = z
|
|
322
|
+
.object({
|
|
323
|
+
ttlSeconds: z.number().int().positive(),
|
|
324
|
+
maxUses: z.number().int().positive().nullable()
|
|
325
|
+
})
|
|
326
|
+
.strict();
|
|
327
|
+
function grantDto(row) {
|
|
328
|
+
let constraints = {};
|
|
329
|
+
try {
|
|
330
|
+
constraints = JSON.parse(row.constraints);
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
constraints = {};
|
|
334
|
+
}
|
|
335
|
+
return {
|
|
336
|
+
id: row.id,
|
|
337
|
+
createdAt: row.created_at,
|
|
338
|
+
expiresAt: row.expires_at,
|
|
339
|
+
toolMatch: row.tool_match,
|
|
340
|
+
effect: row.effect,
|
|
341
|
+
constraints,
|
|
342
|
+
maxUses: row.max_uses,
|
|
343
|
+
uses: row.uses,
|
|
344
|
+
reason: row.reason,
|
|
345
|
+
createdBy: row.created_by,
|
|
346
|
+
state: row.state,
|
|
347
|
+
revokedAt: row.revoked_at,
|
|
348
|
+
revokedBy: row.revoked_by,
|
|
349
|
+
// Made by "don't ask again" in an older build: it releases only what it names now.
|
|
350
|
+
// Or one that bounded each field of a list's items on its own: it releases nothing now (R4-1).
|
|
351
|
+
olderVersion: isOlderRemembered(row) || hasLooseListItems(row)
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
function csv(query, key) {
|
|
355
|
+
const raw = query.get(key);
|
|
356
|
+
if (!raw)
|
|
357
|
+
return undefined;
|
|
358
|
+
return raw
|
|
359
|
+
.split(",")
|
|
360
|
+
.map((s) => s.trim())
|
|
361
|
+
.filter(Boolean);
|
|
362
|
+
}
|
|
363
|
+
function intParam(query, key) {
|
|
364
|
+
const raw = query.get(key);
|
|
365
|
+
if (raw === null)
|
|
366
|
+
return undefined;
|
|
367
|
+
const value = Number(raw);
|
|
368
|
+
if (!Number.isFinite(value))
|
|
369
|
+
throw badRequest(`${key} must be a number`);
|
|
370
|
+
return value;
|
|
371
|
+
}
|
|
372
|
+
/* ------------------------------------------------------------------- routes */
|
|
373
|
+
export function buildRoutes(options) {
|
|
374
|
+
return [
|
|
375
|
+
...runtimeRoutes(options),
|
|
376
|
+
...policyRoutes(options),
|
|
377
|
+
// Absolute folders of node, uv, docker... so an app with a minimal PATH finds them.
|
|
378
|
+
...connectRoutes(options, { pathDirs: doctorPathDirs }),
|
|
379
|
+
...serversAddRoutes(options),
|
|
380
|
+
...catalogRoutes(options),
|
|
381
|
+
...oauthRoutes(options),
|
|
382
|
+
...systemRoutes(options),
|
|
383
|
+
route("GET", "/api/v1/health", () => ({ ok: true, pipelineSteps: ENFORCEMENT_PIPELINE.length })),
|
|
384
|
+
/**
|
|
385
|
+
* The redaction legend. The UI explains markers rather than printing them,
|
|
386
|
+
* and the patterns live in core, so they are served rather than duplicated.
|
|
387
|
+
*/
|
|
388
|
+
route("GET", "/api/v1/meta/redaction", () => ({
|
|
389
|
+
markers: [
|
|
390
|
+
{ marker: "[redacted:key]", meaning: "the argument's name looked like a secret" },
|
|
391
|
+
{ marker: "[redacted:<pattern>]", meaning: "the value matched a known credential shape" },
|
|
392
|
+
{ marker: "[redacted:circular]", meaning: "the value referred back to itself" },
|
|
393
|
+
{ marker: "[redacted:max-depth]", meaning: "nested deeper than the redactor follows" },
|
|
394
|
+
{ marker: "…[truncated N chars]", meaning: "a long string was cut short" },
|
|
395
|
+
{ marker: "[truncated N items]", meaning: "a long array was cut short" }
|
|
396
|
+
],
|
|
397
|
+
note: "Names are redacted by name, not by content, so a value may be harmless and still hidden. " +
|
|
398
|
+
"An argument called `session` is redacted for this reason. The original values were never " +
|
|
399
|
+
"written to disk, so nothing here can be un-redacted.",
|
|
400
|
+
grantTtlMaxSeconds: MAX_GRANT_TTL_SECONDS,
|
|
401
|
+
/** What "approve and remember" offers unless the reviewer changes it. */
|
|
402
|
+
rememberDefaults: { ttlSeconds: REMEMBER_DEFAULT_TTL_SECONDS, maxUses: REMEMBER_DEFAULT_USES },
|
|
403
|
+
/*
|
|
404
|
+
* The audit vocabulary, served for the same reason the markers are: these
|
|
405
|
+
* are core's enums, and the filter UI had its own copy of both lists. A
|
|
406
|
+
* value added to `DecisionKind` would have been unfilterable until
|
|
407
|
+
* someone noticed the dropdown was short.
|
|
408
|
+
*/
|
|
409
|
+
decisions: [
|
|
410
|
+
{ value: "allow", label: "allowed" },
|
|
411
|
+
{ value: "approve", label: "approved" },
|
|
412
|
+
{ value: "deny", label: "denied" }
|
|
413
|
+
],
|
|
414
|
+
outcomes: [
|
|
415
|
+
{ value: "completed", label: "completed" },
|
|
416
|
+
{ value: "denied", label: "denied" },
|
|
417
|
+
{ value: "pending-approval", label: "held for approval" },
|
|
418
|
+
{ value: "error", label: "error" }
|
|
419
|
+
]
|
|
420
|
+
})),
|
|
421
|
+
/* servers */
|
|
422
|
+
route("GET", "/api/v1/servers", () => registry(options).servers.map((entry) => {
|
|
423
|
+
try {
|
|
424
|
+
const server = loadServer(entry);
|
|
425
|
+
/*
|
|
426
|
+
* The inventory is process-wide, so the tool count needs no tenant.
|
|
427
|
+
* Reach does: it subtracts whatever that tenant switched off. Where
|
|
428
|
+
* the console cannot know which tenant to speak for, it says so with
|
|
429
|
+
* a null rather than quietly reporting the empty tenant's answer as
|
|
430
|
+
* the gateway's.
|
|
431
|
+
*/
|
|
432
|
+
const choice = chooseTenant(server, null);
|
|
433
|
+
const surface = toolSurfaceFor(server, choice.ok ? choice.tenant : NO_TENANT);
|
|
434
|
+
const announced = storeFor(server).runtimeState(server.component);
|
|
435
|
+
return {
|
|
436
|
+
id: entry.id,
|
|
437
|
+
kind: entry.kind,
|
|
438
|
+
label: entry.label,
|
|
439
|
+
ok: true,
|
|
440
|
+
component: server.component,
|
|
441
|
+
upstreams: server.gateway.config.upstreams.map((u) => u.name),
|
|
442
|
+
/*
|
|
443
|
+
* Null, not zero, when nothing has been published. A gateway that
|
|
444
|
+
* has not reported is not a gateway serving no tools, and the two
|
|
445
|
+
* used to be the same number here.
|
|
446
|
+
*/
|
|
447
|
+
toolCount: surface.live ? surface.entries.length : null,
|
|
448
|
+
surfaceLive: surface.live,
|
|
449
|
+
surfaceStale: surface.stale,
|
|
450
|
+
posture: server.policy.defaults.mode,
|
|
451
|
+
// Whether that posture is applied or only recorded. The console
|
|
452
|
+
// draws a page-level banner from this: a gateway that is only
|
|
453
|
+
// observing must not look like one that is guarding.
|
|
454
|
+
enforcement: server.policy.enforcement,
|
|
455
|
+
reach: choice.ok ? effectiveReach(server, choice.tenant, surface) : null,
|
|
456
|
+
tenantScope: choice.ok ? choice.tenant : null,
|
|
457
|
+
tenantRequired: !choice.ok,
|
|
458
|
+
tenantHint: choice.ok ? null : choice.why,
|
|
459
|
+
running: announced !== undefined && runtimeStateIsLive(announced),
|
|
460
|
+
auditPath: server.auditPath,
|
|
461
|
+
storePath: server.storePath,
|
|
462
|
+
tenantError: server.tenantError
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
catch (err) {
|
|
466
|
+
// A broken entry is listed with its error. Failing the whole list
|
|
467
|
+
// would hide every working server behind one bad path.
|
|
468
|
+
return { id: entry.id, kind: entry.kind, label: entry.label, ok: false, error: err.message };
|
|
469
|
+
}
|
|
470
|
+
})),
|
|
471
|
+
route("POST", "/api/v1/servers", (ctx) => {
|
|
472
|
+
const body = (ctx.body ?? {});
|
|
473
|
+
const reg = registry(options);
|
|
474
|
+
const id = typeof body["id"] === "string" && body["id"] ? body["id"] : `srv_${randomBytes(3).toString("hex")}`;
|
|
475
|
+
if (reg.servers.some((s) => s.id === id))
|
|
476
|
+
throw conflict(`a server with id "${id}" is already registered`);
|
|
477
|
+
const entry = { ...body, id, added_at: new Date().toISOString() };
|
|
478
|
+
// Probe before persisting, so the registry cannot hold an entry that
|
|
479
|
+
// never loads. A gateway probe stops at the config: registering a server
|
|
480
|
+
// must not spawn its upstream child processes.
|
|
481
|
+
let loaded;
|
|
482
|
+
try {
|
|
483
|
+
loaded = loadServer(entry);
|
|
484
|
+
}
|
|
485
|
+
catch (err) {
|
|
486
|
+
throw unprocessable(`that server could not be loaded: ${err.message}`);
|
|
487
|
+
}
|
|
488
|
+
writeRegistry({ ...reg, servers: [...reg.servers, entry] }, options.registryPath);
|
|
489
|
+
return { id, component: loaded.component };
|
|
490
|
+
}),
|
|
491
|
+
route("DELETE", "/api/v1/servers/:id", async (ctx) => {
|
|
492
|
+
const reg = registry(options);
|
|
493
|
+
const id = ctx.params["id"];
|
|
494
|
+
if (!reg.servers.some((s) => s.id === id))
|
|
495
|
+
throw notFound(`no registered server with id "${id}"`);
|
|
496
|
+
// A gateway this console started would otherwise keep running with no
|
|
497
|
+
// entry left to stop it from. One an AI app runs is not ours to stop.
|
|
498
|
+
if (processes.isActive(id))
|
|
499
|
+
await processes.stop(id);
|
|
500
|
+
// Only the registry entry is removed; the referenced files are never touched.
|
|
501
|
+
writeRegistry({ ...reg, servers: reg.servers.filter((s) => s.id !== id) }, options.registryPath);
|
|
502
|
+
return { removed: id };
|
|
503
|
+
}),
|
|
504
|
+
/* tools and protection */
|
|
505
|
+
/**
|
|
506
|
+
* Which tenants this gateway has any trace of.
|
|
507
|
+
*
|
|
508
|
+
* Served so the console can offer a choice instead of a blank box, and so
|
|
509
|
+
* nothing in the UI has to carry a tenant list of its own. Historical, not
|
|
510
|
+
* authoritative: a tenant that has never made a call or had a row written
|
|
511
|
+
* will not be here, which is why naming one directly stays possible.
|
|
512
|
+
*/
|
|
513
|
+
route("GET", "/api/v1/servers/:id/tenants", (ctx) => {
|
|
514
|
+
const server = serverById(options, ctx.params["id"]);
|
|
515
|
+
const config = server.policy.tenant;
|
|
516
|
+
const assumed = chooseTenant(server, null);
|
|
517
|
+
return {
|
|
518
|
+
tenants: knownTenants(server),
|
|
519
|
+
configured: config !== null && config !== undefined,
|
|
520
|
+
sourceKind: config?.source.kind ?? null,
|
|
521
|
+
required: config?.required ?? false,
|
|
522
|
+
/** Null when the request has to name one. */
|
|
523
|
+
assumed: assumed.ok ? assumed.tenant : null,
|
|
524
|
+
whyNotAssumed: assumed.ok ? null : assumed.why
|
|
525
|
+
};
|
|
526
|
+
}),
|
|
527
|
+
route("GET", "/api/v1/servers/:id/protection", (ctx) => {
|
|
528
|
+
const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
529
|
+
return buildProtection(server, tenant, explicit);
|
|
530
|
+
}),
|
|
531
|
+
route("GET", "/api/v1/servers/:id/tools", (ctx) => {
|
|
532
|
+
const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
533
|
+
return buildProtection(server, tenant, explicit).tools;
|
|
534
|
+
}),
|
|
535
|
+
route("GET", "/api/v1/servers/:id/tools/:tool", (ctx) => {
|
|
536
|
+
const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
537
|
+
const name = ctx.params["tool"];
|
|
538
|
+
const tool = buildProtection(server, tenant, explicit).tools.find((t) => t.name === name);
|
|
539
|
+
if (!tool)
|
|
540
|
+
throw notFound(`no tool "${name}" on server "${server.entry.id}"`);
|
|
541
|
+
const entry = toolSurfaceFor(server, tenant).entries.find((t) => t.name === name);
|
|
542
|
+
return { ...tool, inputSchema: entry?.inputSchema ?? null, activity: recentActivity(server, name, 10, otherComponentsSharingLog(options, server)) };
|
|
543
|
+
}),
|
|
544
|
+
/**
|
|
545
|
+
* The exposure switch: take one tool off the model's menu, or hand it back
|
|
546
|
+
* to policy.
|
|
547
|
+
*
|
|
548
|
+
* This is the one mutation the console makes to what a server exposes, and
|
|
549
|
+
* it is deliberately one-directional in effect. Switching a tool off
|
|
550
|
+
* refuses it before anything else is weighed and hides it from
|
|
551
|
+
* `tools/list`. Switching it back on only *deletes* that row: the tool
|
|
552
|
+
* returns to whatever `policy.yaml` already said, which may still be deny
|
|
553
|
+
* or approve. Nothing stored here can release a call `decide()` refuses, so
|
|
554
|
+
* the console still cannot widen a policy — which is why it may do this at
|
|
555
|
+
* all without writing to `policy.yaml`.
|
|
556
|
+
*/
|
|
557
|
+
route("PUT", "/api/v1/servers/:id/tools/:tool/exposure", (ctx) => {
|
|
558
|
+
const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
559
|
+
const name = ctx.params["tool"];
|
|
560
|
+
/*
|
|
561
|
+
* The tool name is checked against what a *live* gateway says it is
|
|
562
|
+
* serving, which is the whole reason this route can exist at all now.
|
|
563
|
+
* A name taken from a stale list would write a row that reads as
|
|
564
|
+
* protection and guards nothing -- the gateway's own admin API refuses
|
|
565
|
+
* for exactly this reason before it writes.
|
|
566
|
+
*/
|
|
567
|
+
const surface = toolSurfaceFor(server, tenant);
|
|
568
|
+
const writable = surfaceWritable(surface);
|
|
569
|
+
if (!writable.ok)
|
|
570
|
+
throw unprocessable(`cannot change exposure for "${server.entry.id}": ${writable.why}`);
|
|
571
|
+
const entry = surface.entries.find((t) => t.name === name);
|
|
572
|
+
if (!entry) {
|
|
573
|
+
throw notFound(`no tool "${name}" in what "${server.entry.id}" is currently serving. ` +
|
|
574
|
+
`Its upstreams advertise: ${surface.entries.map((t) => t.name).join(", ") || "nothing"}.`);
|
|
575
|
+
}
|
|
576
|
+
const body = (ctx.body ?? {});
|
|
577
|
+
let change;
|
|
578
|
+
try {
|
|
579
|
+
change = parseExposureChange({ tool: name, disabled: body["disabled"], reason: body["reason"] ?? "" });
|
|
580
|
+
}
|
|
581
|
+
catch (err) {
|
|
582
|
+
throw unprocessable(`invalid exposure change: ${err.message}`);
|
|
583
|
+
}
|
|
584
|
+
const scoped = scopedFor(server, tenant);
|
|
585
|
+
/*
|
|
586
|
+
* The disable-keeps / enable-rolls-back asymmetry lives in core, because
|
|
587
|
+
* the gateway's admin API and its CLI flip the same bit and three
|
|
588
|
+
* hand-copied versions of that rule is how two of them end up wrong.
|
|
589
|
+
*/
|
|
590
|
+
const { changed, warning } = applyExposureChange({
|
|
591
|
+
scoped,
|
|
592
|
+
audit: auditFor(server, ctx.actor),
|
|
593
|
+
change,
|
|
594
|
+
actor: ctx.actor,
|
|
595
|
+
effect: entry.effect ?? undefined,
|
|
596
|
+
channel: `the console, for tenant ${tenant === "" ? "(none)" : tenant}`
|
|
597
|
+
});
|
|
598
|
+
// Re-read, so the row returned reflects the write that just happened
|
|
599
|
+
// rather than the surface as it was before it.
|
|
600
|
+
const updated = toolSurfaceFor(server, tenant).entries.find((t) => t.name === name) ?? entry;
|
|
601
|
+
const tool = toolProtection(server, updated, scoped.listGrants({ activeOnly: true }));
|
|
602
|
+
return { tool, changed, warning, tenant, explicitTenant: explicit };
|
|
603
|
+
}),
|
|
604
|
+
/* per-tool rules
|
|
605
|
+
*
|
|
606
|
+
* The console's one policy writer, and the thing that ended its "can only
|
|
607
|
+
* narrow" posture.
|
|
608
|
+
*
|
|
609
|
+
* The exposure switch is allowed to live in the approvals database because
|
|
610
|
+
* it can only subtract. Setting a tool's rule is not: it can turn a refused
|
|
611
|
+
* tool into one that runs. So it writes `policy.yaml` instead — the file
|
|
612
|
+
* people review in git — which keeps the Policy page, `hmcp policy` and a
|
|
613
|
+
* diff describing everything in force, and the gateway adopts it within
|
|
614
|
+
* about a second.
|
|
615
|
+
*
|
|
616
|
+
* The boundary is in `policy-write.ts` and is checked per write: one rule
|
|
617
|
+
* per tool, named literally, every other rule identical in value and in
|
|
618
|
+
* position, nothing outside `rules` touched, no regex and no `coerce`, and
|
|
619
|
+
* a confirmation for each of the three ways a change can widen something.
|
|
620
|
+
*
|
|
621
|
+
* The general writers -- any setting, any rule, the file as text -- are in
|
|
622
|
+
* `routes/policy.ts`, under `/policy/setting`, `/policy/rules` and
|
|
623
|
+
* `/policy/file`, with a loosening acknowledgement of their own. `PUT
|
|
624
|
+
* /policy` itself still does not exist, and two tests assert the 404.
|
|
625
|
+
*/
|
|
626
|
+
route("POST", "/api/v1/servers/:id/policy/tool-rule/preview", (ctx) => {
|
|
627
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
628
|
+
const { draft, entry, liveTools } = toolRuleTarget(server, tenant, ctx.body, ctx.actor);
|
|
629
|
+
const preview = previewToolRule({
|
|
630
|
+
policy: server.policy,
|
|
631
|
+
draft,
|
|
632
|
+
disabled: entry.disabled !== null,
|
|
633
|
+
liveTools
|
|
634
|
+
});
|
|
635
|
+
return toolRulePreviewDto(server, preview);
|
|
636
|
+
}),
|
|
637
|
+
/** What reverting to policy would leave behind, before anything is removed. */
|
|
638
|
+
route("GET", "/api/v1/servers/:id/policy/tool-rule/:tool/preview-clear", (ctx) => {
|
|
639
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
640
|
+
const name = ctx.params["tool"];
|
|
641
|
+
const entry = toolSurfaceFor(server, tenant).entries.find((t) => t.name === name);
|
|
642
|
+
const preview = previewClearToolRule({
|
|
643
|
+
policy: server.policy,
|
|
644
|
+
tool: name,
|
|
645
|
+
disabled: entry?.disabled != null
|
|
646
|
+
});
|
|
647
|
+
if (!preview)
|
|
648
|
+
throw notFound(`no console-written rule for "${name}"`);
|
|
649
|
+
return {
|
|
650
|
+
removed: preview.removed,
|
|
651
|
+
yaml: ruleToYaml(preview.removed),
|
|
652
|
+
verdict: { kind: preview.verdict.kind, ruleId: preview.verdict.ruleId, reason: preview.verdict.reason },
|
|
653
|
+
current: { kind: preview.current.kind, ruleId: preview.current.ruleId },
|
|
654
|
+
/* What will bound the tool once ours is gone — the rule that governed
|
|
655
|
+
it before, bounds and all. */
|
|
656
|
+
bounds: boundsOf(preview.policy.rules.find((r) => globMatch(r.match, name))),
|
|
657
|
+
becomesUnclassified: preview.becomesUnclassified,
|
|
658
|
+
expectedDigest: policyDigest(server.policy)
|
|
659
|
+
};
|
|
660
|
+
}),
|
|
661
|
+
route("POST", "/api/v1/servers/:id/policy/tool-rule", (ctx) => {
|
|
662
|
+
const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
663
|
+
const { draft, entry, liveTools } = toolRuleTarget(server, tenant, ctx.body, ctx.actor);
|
|
664
|
+
if (server.policyFile === null || !server.policyWritable.ok) {
|
|
665
|
+
throw unprocessable(server.policyWritable.why ?? "this gateway's policy cannot be written from here");
|
|
666
|
+
}
|
|
667
|
+
const body = (ctx.body ?? {});
|
|
668
|
+
const expectedDigest = typeof body["expectedDigest"] === "string" ? body["expectedDigest"] : "";
|
|
669
|
+
if (!expectedDigest) {
|
|
670
|
+
throw badRequest("expectedDigest is required: it is the digest of the policy the preview was computed from, " +
|
|
671
|
+
"and without it a file edited in the meantime would be overwritten");
|
|
672
|
+
}
|
|
673
|
+
const preview = previewToolRule({ policy: server.policy, draft, liveTools });
|
|
674
|
+
const result = writeToolRule({
|
|
675
|
+
policyPath: server.policyFile,
|
|
676
|
+
draft,
|
|
677
|
+
expectedDigest,
|
|
678
|
+
knownToLiveSurface: true,
|
|
679
|
+
liveTools,
|
|
680
|
+
writesAllowed: true,
|
|
681
|
+
overridesAllowed: server.policyOverrides
|
|
682
|
+
});
|
|
683
|
+
if (result.kind === "stale")
|
|
684
|
+
throw conflict(result.why);
|
|
685
|
+
if (result.kind === "refused") {
|
|
686
|
+
/*
|
|
687
|
+
* A refused widening is exactly the record a security log should carry.
|
|
688
|
+
* Written before the 422 so the attempt is in the chain, with what the
|
|
689
|
+
* operator was shown — the predecessor of this route exported a
|
|
690
|
+
* refusal id and emitted it nowhere.
|
|
691
|
+
*/
|
|
692
|
+
try {
|
|
693
|
+
auditFor(server, ctx.actor).append({
|
|
694
|
+
tool: draft.tool,
|
|
695
|
+
effect: draft.effect,
|
|
696
|
+
decision: "deny",
|
|
697
|
+
tenant: tenant || null,
|
|
698
|
+
rule_id: TOOL_RULE_REFUSED,
|
|
699
|
+
reason: `${ctx.actor} tried to set a rule for ${draft.tool} and it was refused: ${result.why}`,
|
|
700
|
+
outcome: "denied",
|
|
701
|
+
args_redacted: {
|
|
702
|
+
tool: draft.tool,
|
|
703
|
+
effect: draft.effect,
|
|
704
|
+
decision: draft.decision,
|
|
705
|
+
needs: result.needs ?? null,
|
|
706
|
+
origin: "console"
|
|
707
|
+
}
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
catch {
|
|
711
|
+
/* the refusal below is the outcome; an unwritable log must not change it */
|
|
712
|
+
}
|
|
713
|
+
throw unprocessable(result.why);
|
|
714
|
+
}
|
|
715
|
+
/*
|
|
716
|
+
* Audited after the write and deliberately not rolled back when the
|
|
717
|
+
* record fails.
|
|
718
|
+
*
|
|
719
|
+
* The grants route rolls back for the opposite reason: a grant releasing
|
|
720
|
+
* calls with nobody recorded as granting it is the thing the log exists
|
|
721
|
+
* to prevent. Here the file is already on disk and the gateway may have
|
|
722
|
+
* reloaded it, so undoing would be a second write — removing a rule,
|
|
723
|
+
* which is itself unaudited. A rule visible in the file and in `git diff`
|
|
724
|
+
* with no log line is a smaller problem than a writer that deletes rules
|
|
725
|
+
* on an I/O error. The failure is reported.
|
|
726
|
+
*/
|
|
727
|
+
let warning = null;
|
|
728
|
+
try {
|
|
729
|
+
auditFor(server, ctx.actor).appendStrict({
|
|
730
|
+
tool: draft.tool,
|
|
731
|
+
effect: draft.effect,
|
|
732
|
+
/* What policy now says, not what was asked for — so the Audit page's
|
|
733
|
+
decision filter means something for every op. */
|
|
734
|
+
decision: preview.verdict.kind,
|
|
735
|
+
tenant: tenant || null,
|
|
736
|
+
rule_id: result.action === "update" ? TOOL_RULE_UPDATE : TOOL_RULE_SET,
|
|
737
|
+
reason: `${draft.tool} set to ${draft.effect}/${draft.decision} via the console by ${ctx.actor}` +
|
|
738
|
+
(draft.reason ? `: ${draft.reason}` : "") +
|
|
739
|
+
`; rule "${result.rule.id}" written to ${server.policyFile}` +
|
|
740
|
+
(preview.carriedFrom ? `, carrying the bounds from "${preview.carriedFrom}"` : "") +
|
|
741
|
+
(preview.overriddenReason
|
|
742
|
+
? `, overriding "${preview.overriddenReason.ruleId}" ("${preview.overriddenReason.reason}")`
|
|
743
|
+
: ""),
|
|
744
|
+
outcome: "completed",
|
|
745
|
+
args_redacted: {
|
|
746
|
+
op: result.action,
|
|
747
|
+
tool: draft.tool,
|
|
748
|
+
effect: draft.effect,
|
|
749
|
+
decision: draft.decision,
|
|
750
|
+
rule_id: result.rule.id,
|
|
751
|
+
args: result.rule.args ?? null,
|
|
752
|
+
on_violation: result.rule.on_violation,
|
|
753
|
+
unknown_args: result.rule.unknown_args,
|
|
754
|
+
bounds_carried_from: preview.carriedFrom,
|
|
755
|
+
/* The rule as it was: the only way the log can restore a change. */
|
|
756
|
+
previous: result.previous,
|
|
757
|
+
overrode: preview.overriddenReason,
|
|
758
|
+
acknowledged: draft.acknowledged ?? null,
|
|
759
|
+
stranded: preview.strandedRule,
|
|
760
|
+
loosens: preview.loosens,
|
|
761
|
+
/*
|
|
762
|
+
* A per-tool rule is process-wide: it applies to every tenant of
|
|
763
|
+
* this gateway, unlike the exposure switch beside it. Recorded so
|
|
764
|
+
* the log does not imply otherwise.
|
|
765
|
+
*/
|
|
766
|
+
scope: "all tenants",
|
|
767
|
+
origin: "console",
|
|
768
|
+
policy_digest_before: result.previousDigest,
|
|
769
|
+
policy_digest_after: result.digest
|
|
770
|
+
}
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
catch (err) {
|
|
774
|
+
warning =
|
|
775
|
+
`${draft.tool} was set but the audit record failed: ${err.message}. ` +
|
|
776
|
+
`The rule is in ${server.policyFile}.`;
|
|
777
|
+
}
|
|
778
|
+
/*
|
|
779
|
+
* Re-read from disk, so what comes back is what a reader of the file
|
|
780
|
+
* would see — including that the gateway has probably not reloaded yet,
|
|
781
|
+
* which is why the tool's verdict here may still describe the old policy
|
|
782
|
+
* for a moment.
|
|
783
|
+
*/
|
|
784
|
+
const reloaded = loadServer(server.entry);
|
|
785
|
+
const after = toolSurfaceFor(reloaded, tenant).entries.find((t) => t.name === draft.tool);
|
|
786
|
+
const tool = after
|
|
787
|
+
? toolProtection(reloaded, after, scopedFor(reloaded, tenant).listGrants({ activeOnly: true }))
|
|
788
|
+
: null;
|
|
789
|
+
return {
|
|
790
|
+
rule: result.rule,
|
|
791
|
+
action: result.action,
|
|
792
|
+
digest: result.digest,
|
|
793
|
+
previousDigest: result.previousDigest,
|
|
794
|
+
policyPath: server.policyFile,
|
|
795
|
+
yaml: ruleToYaml(result.rule),
|
|
796
|
+
carriedFrom: preview.carriedFrom,
|
|
797
|
+
strandedRule: preview.strandedRule,
|
|
798
|
+
tool,
|
|
799
|
+
warning,
|
|
800
|
+
tenant,
|
|
801
|
+
explicitTenant: explicit
|
|
802
|
+
};
|
|
803
|
+
}),
|
|
804
|
+
/** Revert to policy: remove the console's rule and nothing else. */
|
|
805
|
+
route("DELETE", "/api/v1/servers/:id/policy/tool-rule/:tool", (ctx) => {
|
|
806
|
+
const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
807
|
+
const name = ctx.params["tool"];
|
|
808
|
+
if (server.policyFile === null || !server.policyWritable.ok) {
|
|
809
|
+
throw unprocessable(server.policyWritable.why ?? "this gateway's policy cannot be written from here");
|
|
810
|
+
}
|
|
811
|
+
const expectedDigest = ctx.query.get("expectedDigest") ?? "";
|
|
812
|
+
if (!expectedDigest)
|
|
813
|
+
throw badRequest("expectedDigest is required");
|
|
814
|
+
const liveTools = toolSurfaceFor(server, tenant).entries.map((t) => t.name);
|
|
815
|
+
const before = previewClearToolRule({ policy: server.policy, tool: name });
|
|
816
|
+
const result = clearToolRule({
|
|
817
|
+
policyPath: server.policyFile,
|
|
818
|
+
tool: name,
|
|
819
|
+
expectedDigest,
|
|
820
|
+
liveTools,
|
|
821
|
+
writesAllowed: true
|
|
822
|
+
});
|
|
823
|
+
if (result.kind === "stale")
|
|
824
|
+
throw conflict(result.why);
|
|
825
|
+
if (result.kind === "refused")
|
|
826
|
+
throw unprocessable(result.why);
|
|
827
|
+
let warning = null;
|
|
828
|
+
try {
|
|
829
|
+
auditFor(server, ctx.actor).appendStrict({
|
|
830
|
+
tool: name,
|
|
831
|
+
effect: result.previous?.effect ?? null,
|
|
832
|
+
decision: before?.verdict.kind ?? "deny",
|
|
833
|
+
tenant: tenant || null,
|
|
834
|
+
rule_id: TOOL_RULE_CLEAR,
|
|
835
|
+
reason: `${name} handed back to policy by ${ctx.actor}; rule "${result.previous?.id}" removed from ` +
|
|
836
|
+
`${server.policyFile}. It is now ${before?.verdict.kind ?? "decided by policy"} under ` +
|
|
837
|
+
`"${before?.verdict.ruleId}".`,
|
|
838
|
+
outcome: "completed",
|
|
839
|
+
args_redacted: {
|
|
840
|
+
op: "cleared",
|
|
841
|
+
tool: name,
|
|
842
|
+
/* The removed rule in full: the log is the only place it survives. */
|
|
843
|
+
previous: result.previous,
|
|
844
|
+
becomes_unclassified: before?.becomesUnclassified ?? false,
|
|
845
|
+
scope: "all tenants",
|
|
846
|
+
origin: "console",
|
|
847
|
+
policy_digest_before: result.previousDigest,
|
|
848
|
+
policy_digest_after: result.digest
|
|
849
|
+
}
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
catch (err) {
|
|
853
|
+
warning =
|
|
854
|
+
`the rule was removed but the audit record failed: ${err.message}. ` +
|
|
855
|
+
`It was: ${JSON.stringify(result.previous)}`;
|
|
856
|
+
}
|
|
857
|
+
const reloaded = loadServer(server.entry);
|
|
858
|
+
const after = toolSurfaceFor(reloaded, tenant).entries.find((t) => t.name === name);
|
|
859
|
+
const tool = after
|
|
860
|
+
? toolProtection(reloaded, after, scopedFor(reloaded, tenant).listGrants({ activeOnly: true }))
|
|
861
|
+
: null;
|
|
862
|
+
return {
|
|
863
|
+
removed: result.previous,
|
|
864
|
+
digest: result.digest,
|
|
865
|
+
becomesUnclassified: before?.becomesUnclassified ?? false,
|
|
866
|
+
tool,
|
|
867
|
+
warning,
|
|
868
|
+
tenant,
|
|
869
|
+
explicitTenant: explicit
|
|
870
|
+
};
|
|
871
|
+
}),
|
|
872
|
+
/**
|
|
873
|
+
* The other half of the answer to "an unclassified tool is a wall": leave
|
|
874
|
+
* the tool unclassified and change what that means, from refused outright
|
|
875
|
+
* to held for a human.
|
|
876
|
+
*
|
|
877
|
+
* A posture change rather than a permission grant -- nothing runs unasked
|
|
878
|
+
* under either value -- which is why it is a toggle between the schema's
|
|
879
|
+
* two existing values and not a form.
|
|
880
|
+
*/
|
|
881
|
+
route("PUT", "/api/v1/servers/:id/policy/unclassified", (ctx) => {
|
|
882
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
883
|
+
const body = (ctx.body ?? {});
|
|
884
|
+
const value = body["value"];
|
|
885
|
+
if (value !== "deny" && value !== "approve") {
|
|
886
|
+
throw badRequest('value must be "deny" or "approve"');
|
|
887
|
+
}
|
|
888
|
+
if (server.policyFile === null || !server.policyWritable.ok) {
|
|
889
|
+
throw unprocessable(server.policyWritable.why ?? "this gateway's policy cannot be written from here");
|
|
890
|
+
}
|
|
891
|
+
const expectedDigest = typeof body["expectedDigest"] === "string" ? body["expectedDigest"] : "";
|
|
892
|
+
if (!expectedDigest)
|
|
893
|
+
throw badRequest("expectedDigest is required");
|
|
894
|
+
const result = writeUnclassifiedPosture({
|
|
895
|
+
policyPath: server.policyFile,
|
|
896
|
+
value,
|
|
897
|
+
expectedDigest,
|
|
898
|
+
actor: ctx.actor,
|
|
899
|
+
writesAllowed: true
|
|
900
|
+
});
|
|
901
|
+
if (result.kind === "stale")
|
|
902
|
+
throw conflict(result.why);
|
|
903
|
+
if (result.kind === "refused")
|
|
904
|
+
throw unprocessable(result.why);
|
|
905
|
+
let warning = null;
|
|
906
|
+
try {
|
|
907
|
+
auditFor(server, ctx.actor).appendStrict({
|
|
908
|
+
tool: "(policy)",
|
|
909
|
+
effect: null,
|
|
910
|
+
decision: value === "approve" ? "approve" : "deny",
|
|
911
|
+
tenant: tenant || null,
|
|
912
|
+
rule_id: UNCLASSIFIED_POSTURE_RULE,
|
|
913
|
+
reason: `defaults.on_unclassified set to ${value} via the console by ${ctx.actor}; ` +
|
|
914
|
+
(value === "approve"
|
|
915
|
+
? "a tool nothing classifies is now held for a human rather than refused outright"
|
|
916
|
+
: "a tool nothing classifies is now refused outright rather than held for a human"),
|
|
917
|
+
outcome: "completed",
|
|
918
|
+
args_redacted: {
|
|
919
|
+
on_unclassified: value,
|
|
920
|
+
policy_digest_before: result.previousDigest,
|
|
921
|
+
policy_digest_after: result.digest
|
|
922
|
+
}
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
catch (err) {
|
|
926
|
+
warning = `the change was written but the audit record failed: ${err.message}`;
|
|
927
|
+
}
|
|
928
|
+
return { value, digest: result.digest, previousDigest: result.previousDigest, warning };
|
|
929
|
+
}),
|
|
930
|
+
/* approvals */
|
|
931
|
+
route("GET", "/api/v1/servers/:id/approvals/pending", (ctx) => {
|
|
932
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
933
|
+
return scopedFor(server, tenant)
|
|
934
|
+
.listPending(intParam(ctx.query, "limit") ?? 50)
|
|
935
|
+
.map(approvalDto);
|
|
936
|
+
}),
|
|
937
|
+
route("GET", "/api/v1/servers/:id/approvals", (ctx) => {
|
|
938
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
939
|
+
return scopedFor(server, tenant)
|
|
940
|
+
.list(intParam(ctx.query, "limit") ?? 50)
|
|
941
|
+
.map(approvalDto);
|
|
942
|
+
}),
|
|
943
|
+
route("POST", "/api/v1/servers/:id/approvals/:aprId/decide", (ctx) => {
|
|
944
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
945
|
+
const body = (ctx.body ?? {});
|
|
946
|
+
if (body.state !== "granted" && body.state !== "denied") {
|
|
947
|
+
throw badRequest('state must be "granted" or "denied"');
|
|
948
|
+
}
|
|
949
|
+
const note = typeof body.note === "string" ? body.note : "";
|
|
950
|
+
/*
|
|
951
|
+
* "Approve, and allow calls like this for a while": the grant is built
|
|
952
|
+
* from this call by core's `rememberOnApprove`, the same code `hmcp
|
|
953
|
+
* approve --remember` runs, and created *before* the decision, so a
|
|
954
|
+
* grant that cannot be written leaves the call undecided rather than
|
|
955
|
+
* released with the question unanswered.
|
|
956
|
+
*/
|
|
957
|
+
let remembered = null;
|
|
958
|
+
if (body.remember !== undefined && body.remember !== null) {
|
|
959
|
+
if (body.state !== "granted")
|
|
960
|
+
throw badRequest("remember goes with approving a call, not refusing one");
|
|
961
|
+
const parsed = RememberSchema.safeParse(body.remember);
|
|
962
|
+
if (!parsed.success) {
|
|
963
|
+
throw badRequest(`remember must be {ttlSeconds, maxUses}: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
|
|
964
|
+
}
|
|
965
|
+
const scoped = scopedFor(server, tenant);
|
|
966
|
+
const row = scoped.get(ctx.params["aprId"]);
|
|
967
|
+
if (!row)
|
|
968
|
+
throw notFound(`no approval request with id ${ctx.params["aprId"]}`);
|
|
969
|
+
if (row.state !== "pending")
|
|
970
|
+
throw conflict(`approval ${row.id} is already ${row.state} and cannot be decided again`);
|
|
971
|
+
try {
|
|
972
|
+
remembered = rememberOnApprove({
|
|
973
|
+
scoped,
|
|
974
|
+
audit: auditFor(server, ctx.actor),
|
|
975
|
+
row,
|
|
976
|
+
policy: server.policy,
|
|
977
|
+
ttlSeconds: parsed.data.ttlSeconds,
|
|
978
|
+
maxUses: parsed.data.maxUses,
|
|
979
|
+
actor: ctx.actor,
|
|
980
|
+
via: "the console"
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
catch (err) {
|
|
984
|
+
if (err instanceof RememberError)
|
|
985
|
+
throw unprocessable(`${err.message} Nothing was approved.`);
|
|
986
|
+
throw err;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
/*
|
|
990
|
+
* "Approve, and stop asking me about this tool."
|
|
991
|
+
*
|
|
992
|
+
* Only offered for a call held because nothing classified the tool --
|
|
993
|
+
* under `on_unclassified: approve`, where the queue is the only place
|
|
994
|
+
* the gap shows up -- and it may only ever write `decision: approve`.
|
|
995
|
+
*
|
|
996
|
+
* The reviewer approved *one call*. Turning that into a standing
|
|
997
|
+
* permission from a checkbox beside a queue row is exactly the widening
|
|
998
|
+
* this whole boundary exists to prevent, so the effect is theirs to pick
|
|
999
|
+
* and the decision is fixed: the tool stops being unclassified and keeps
|
|
1000
|
+
* asking. Making it run unasked is the full form on the Functions page,
|
|
1001
|
+
* with its preview and its confirmation.
|
|
1002
|
+
*/
|
|
1003
|
+
const classifyEffect = typeof body.classify?.["effect"] === "string"
|
|
1004
|
+
? body.classify["effect"]
|
|
1005
|
+
: null;
|
|
1006
|
+
const result = scopedFor(server, tenant).decideChecked(ctx.params["aprId"], body.state, ctx.actor, note);
|
|
1007
|
+
if (!result.ok && remembered) {
|
|
1008
|
+
// Lost a race after the grant was made: withdraw it, and say so in the log.
|
|
1009
|
+
scopedFor(server, tenant).revokeGrant(remembered.id, "system");
|
|
1010
|
+
auditFor(server, ctx.actor).append({
|
|
1011
|
+
tool: remembered.tool_match,
|
|
1012
|
+
decision: "deny",
|
|
1013
|
+
rule_id: "standing_grant.revoke",
|
|
1014
|
+
reason: `standing grant ${remembered.id} withdrawn: the approval it remembered could not be decided (${result.error})`,
|
|
1015
|
+
outcome: "completed",
|
|
1016
|
+
grant_id: remembered.id
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
if (!result.ok) {
|
|
1020
|
+
throw result.error.includes("no approval request") ? notFound(result.error) : conflict(result.error);
|
|
1021
|
+
}
|
|
1022
|
+
// The CLI leaves no audit trace when a human approves; the console should
|
|
1023
|
+
// not inherit that gap. A decision is itself a security event.
|
|
1024
|
+
const { args } = parseArgs(result.row);
|
|
1025
|
+
auditFor(server, ctx.actor).append({
|
|
1026
|
+
tool: result.row.tool,
|
|
1027
|
+
effect: result.row.effect ?? null,
|
|
1028
|
+
decision: body.state === "granted" ? "approve" : "deny",
|
|
1029
|
+
rule_id: "approval.decide",
|
|
1030
|
+
reason: `${body.state === "granted" ? "approved" : "denied"} by ${ctx.actor} in the console${note ? `: ${note}` : ""}`,
|
|
1031
|
+
outcome: "completed",
|
|
1032
|
+
approval_id: result.row.id,
|
|
1033
|
+
args_redacted: (args ?? null)
|
|
1034
|
+
});
|
|
1035
|
+
/*
|
|
1036
|
+
* After the decision, never before, and its failure never undoes it.
|
|
1037
|
+
*
|
|
1038
|
+
* The call in flight was already released; a file write that fails must
|
|
1039
|
+
* not turn an approval the reviewer gave into a refusal, and it must not
|
|
1040
|
+
* leave them to answer the same question twice. So the outcome of the
|
|
1041
|
+
* classification is reported beside the decision rather than replacing
|
|
1042
|
+
* it.
|
|
1043
|
+
*/
|
|
1044
|
+
let classified = null;
|
|
1045
|
+
let classifyWarning = null;
|
|
1046
|
+
if (classifyEffect && body.state === "granted") {
|
|
1047
|
+
try {
|
|
1048
|
+
classified = classifyFromApproval(server, tenant, result.row, classifyEffect, ctx.actor);
|
|
1049
|
+
}
|
|
1050
|
+
catch (err) {
|
|
1051
|
+
classifyWarning = `the call was approved, but ${result.row.tool} was not classified: ${err.message}`;
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
return {
|
|
1055
|
+
...approvalDto(result.row),
|
|
1056
|
+
classified,
|
|
1057
|
+
classifyWarning,
|
|
1058
|
+
remembered: remembered ? grantDto(scopedFor(server, tenant).getGrant(remembered.id) ?? remembered) : null
|
|
1059
|
+
};
|
|
1060
|
+
}),
|
|
1061
|
+
/* standing grants */
|
|
1062
|
+
route("GET", "/api/v1/servers/:id/grants", (ctx) => {
|
|
1063
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
1064
|
+
const activeOnly = ctx.query.get("state") === "active";
|
|
1065
|
+
return scopedFor(server, tenant)
|
|
1066
|
+
.listGrants({ activeOnly, limit: intParam(ctx.query, "limit") ?? 100 })
|
|
1067
|
+
.map(grantDto);
|
|
1068
|
+
}),
|
|
1069
|
+
route("POST", "/api/v1/servers/:id/grants", (ctx) => {
|
|
1070
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
1071
|
+
const body = (ctx.body ?? {});
|
|
1072
|
+
// Accept a TTL and derive the deadline, which is what a form can express.
|
|
1073
|
+
const ttl = Number(body["ttl_seconds"]);
|
|
1074
|
+
const expires = Number.isFinite(ttl) ? Date.now() + ttl * 1000 : Number(body["expires_at"]);
|
|
1075
|
+
let draft;
|
|
1076
|
+
try {
|
|
1077
|
+
draft = parseGrantDraft({
|
|
1078
|
+
tool_match: body["tool_match"],
|
|
1079
|
+
effect: body["effect"] ?? null,
|
|
1080
|
+
constraints: body["constraints"] ?? {},
|
|
1081
|
+
expires_at: expires,
|
|
1082
|
+
max_uses: body["max_uses"] ?? null,
|
|
1083
|
+
reason: body["reason"],
|
|
1084
|
+
created_by: ctx.actor
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
catch (err) {
|
|
1088
|
+
throw unprocessable(err.message);
|
|
1089
|
+
}
|
|
1090
|
+
const scoped = scopedFor(server, tenant);
|
|
1091
|
+
const grant = scoped.createGrant(draft);
|
|
1092
|
+
// The requirement is that no pre-approval exists unaudited, so this uses
|
|
1093
|
+
// appendStrict (which throws) rather than append (which only warns), and
|
|
1094
|
+
// the grant is withdrawn if the record cannot be written.
|
|
1095
|
+
try {
|
|
1096
|
+
auditFor(server, ctx.actor).appendStrict({
|
|
1097
|
+
tool: grant.tool_match,
|
|
1098
|
+
effect: grant.effect ?? null,
|
|
1099
|
+
decision: "approve",
|
|
1100
|
+
rule_id: "standing_grant.create",
|
|
1101
|
+
reason: `standing grant ${grant.id} created by ${ctx.actor}: ${grant.reason} ` +
|
|
1102
|
+
`(matches ${grant.tool_match}, ${grant.max_uses === null ? "unlimited uses" : `${grant.max_uses} use(s)`}, ` +
|
|
1103
|
+
`expires ${new Date(grant.expires_at).toISOString()})`,
|
|
1104
|
+
outcome: "completed",
|
|
1105
|
+
grant_id: grant.id,
|
|
1106
|
+
args_redacted: {
|
|
1107
|
+
tool_match: grant.tool_match,
|
|
1108
|
+
effect: grant.effect,
|
|
1109
|
+
constraints: draft.constraints ?? {},
|
|
1110
|
+
max_uses: grant.max_uses,
|
|
1111
|
+
expires_at: grant.expires_at
|
|
1112
|
+
}
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
catch (err) {
|
|
1116
|
+
scoped.revokeGrant(grant.id, "system");
|
|
1117
|
+
throw new Error(`the grant was withdrawn because it could not be audited: ${err.message}`);
|
|
1118
|
+
}
|
|
1119
|
+
return grantDto(scoped.getGrant(grant.id));
|
|
1120
|
+
}),
|
|
1121
|
+
route("DELETE", "/api/v1/servers/:id/grants/:grantId", (ctx) => {
|
|
1122
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
1123
|
+
const scoped = scopedFor(server, tenant);
|
|
1124
|
+
const id = ctx.params["grantId"];
|
|
1125
|
+
const existing = scoped.getGrant(id);
|
|
1126
|
+
if (!existing)
|
|
1127
|
+
throw notFound(`no standing grant with id "${id}"`);
|
|
1128
|
+
const revoked = scoped.revokeGrant(id, ctx.actor);
|
|
1129
|
+
if (!revoked)
|
|
1130
|
+
throw conflict(`standing grant ${id} is already ${existing.state}`);
|
|
1131
|
+
// Revocation tightens, so unlike creation it is kept even if the audit
|
|
1132
|
+
// append fails; the failure is reported instead of undoing the fix.
|
|
1133
|
+
let warning = null;
|
|
1134
|
+
try {
|
|
1135
|
+
auditFor(server, ctx.actor).appendStrict({
|
|
1136
|
+
tool: revoked.tool_match,
|
|
1137
|
+
decision: "deny",
|
|
1138
|
+
rule_id: "standing_grant.revoke",
|
|
1139
|
+
reason: `standing grant ${revoked.id} revoked by ${ctx.actor} after ${revoked.uses} use(s)`,
|
|
1140
|
+
outcome: "completed",
|
|
1141
|
+
grant_id: revoked.id
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
catch (err) {
|
|
1145
|
+
warning = `the grant was revoked but the audit record failed: ${err.message}`;
|
|
1146
|
+
}
|
|
1147
|
+
return { ...grantDto(revoked), warning };
|
|
1148
|
+
}),
|
|
1149
|
+
/**
|
|
1150
|
+
* Dry run: what would this grant release, right now?
|
|
1151
|
+
*
|
|
1152
|
+
* Writes nothing and claims no uses. This is what makes the settings page
|
|
1153
|
+
* honest — you see the blast radius before you create the grant.
|
|
1154
|
+
*/
|
|
1155
|
+
route("POST", "/api/v1/servers/:id/grants/preview", (ctx) => {
|
|
1156
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
1157
|
+
const body = (ctx.body ?? {});
|
|
1158
|
+
/*
|
|
1159
|
+
* The point of a preview is to show the blast radius before a grant is
|
|
1160
|
+
* created, so an empty list has to mean "covers nothing" and nothing
|
|
1161
|
+
* else. Reading an unpublished surface would have it quietly claim that
|
|
1162
|
+
* about a grant covering every tool the gateway serves.
|
|
1163
|
+
*/
|
|
1164
|
+
const surface = toolSurfaceFor(server, tenant);
|
|
1165
|
+
const writable = surfaceWritable(surface);
|
|
1166
|
+
const ttl = Number(body["ttl_seconds"]);
|
|
1167
|
+
const expires = Number.isFinite(ttl) ? Date.now() + ttl * 1000 : Date.now() + 3600_000;
|
|
1168
|
+
let draft;
|
|
1169
|
+
try {
|
|
1170
|
+
draft = parseGrantDraft({
|
|
1171
|
+
tool_match: body["tool_match"],
|
|
1172
|
+
effect: body["effect"] ?? null,
|
|
1173
|
+
constraints: body["constraints"] ?? {},
|
|
1174
|
+
expires_at: expires,
|
|
1175
|
+
max_uses: body["max_uses"] ?? null,
|
|
1176
|
+
reason: typeof body["reason"] === "string" && body["reason"] ? body["reason"] : "preview",
|
|
1177
|
+
created_by: ctx.actor
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
catch (err) {
|
|
1181
|
+
throw unprocessable(err.message);
|
|
1182
|
+
}
|
|
1183
|
+
const candidate = {
|
|
1184
|
+
id: "sg_preview",
|
|
1185
|
+
...scopeFor(server, tenant),
|
|
1186
|
+
created_at: Date.now(),
|
|
1187
|
+
expires_at: draft.expires_at,
|
|
1188
|
+
tool_match: draft.tool_match,
|
|
1189
|
+
effect: draft.effect ?? null,
|
|
1190
|
+
constraints: JSON.stringify(draft.constraints ?? {}),
|
|
1191
|
+
max_uses: draft.max_uses ?? null,
|
|
1192
|
+
uses: 0,
|
|
1193
|
+
reason: draft.reason,
|
|
1194
|
+
created_by: draft.created_by,
|
|
1195
|
+
state: "active",
|
|
1196
|
+
revoked_at: null,
|
|
1197
|
+
revoked_by: null,
|
|
1198
|
+
closed: draft.closed ? 1 : 0
|
|
1199
|
+
};
|
|
1200
|
+
return {
|
|
1201
|
+
expiresAt: draft.expires_at,
|
|
1202
|
+
surfaceKnown: writable.ok,
|
|
1203
|
+
surfaceUnknownWhy: writable.ok ? null : writable.why,
|
|
1204
|
+
tools: surface.entries.map((entry) => {
|
|
1205
|
+
/*
|
|
1206
|
+
* Tool and effect only: there is no call here, and weighing the
|
|
1207
|
+
* grant's own bounds against an invented empty one reports every
|
|
1208
|
+
* value bound as broken.
|
|
1209
|
+
*/
|
|
1210
|
+
const match = grantCoversTool(candidate, entry.name, entry.effect);
|
|
1211
|
+
/*
|
|
1212
|
+
* Matching the tool is not the whole answer. A grant releases a call
|
|
1213
|
+
* held by a rule's bound only when the grant bounds that argument
|
|
1214
|
+
* too, so the rule that governs this tool decides how much of it
|
|
1215
|
+
* this grant actually reaches. `heldBounds` is what it does not:
|
|
1216
|
+
* each one is an argument whose calls will still stop and still ask
|
|
1217
|
+
* a person. Empty for a tool the grant does not cover at all, where
|
|
1218
|
+
* it would only be noise.
|
|
1219
|
+
*/
|
|
1220
|
+
const rule = server.policy.rules.find((r) => globMatch(r.match, entry.name));
|
|
1221
|
+
return {
|
|
1222
|
+
name: entry.name,
|
|
1223
|
+
effect: entry.effect,
|
|
1224
|
+
covers: match.matches,
|
|
1225
|
+
why: match.reason,
|
|
1226
|
+
heldBounds: match.matches ? grantBoundGaps(draft.constraints ?? {}, rule?.args) : [],
|
|
1227
|
+
/*
|
|
1228
|
+
* A call can also be held over an argument no bound names at all,
|
|
1229
|
+
* which a preview cannot enumerate in advance -- only say to
|
|
1230
|
+
* expect.
|
|
1231
|
+
*/
|
|
1232
|
+
unknownArgsHeld: match.matches && rule !== undefined && rule.unknown_args === "approve"
|
|
1233
|
+
};
|
|
1234
|
+
})
|
|
1235
|
+
};
|
|
1236
|
+
}),
|
|
1237
|
+
/* overview */
|
|
1238
|
+
/**
|
|
1239
|
+
* Aggregates for the overview, with the bound they were read under.
|
|
1240
|
+
*
|
|
1241
|
+
* `tenant=*` reads every tenant, which is the only honest way to answer
|
|
1242
|
+
* "what is this gateway doing" on a deployment serving several. Anything
|
|
1243
|
+
* else goes through `scopedRequest`, so a `jwt-verified` gateway is still
|
|
1244
|
+
* refused rather than guessed at.
|
|
1245
|
+
*/
|
|
1246
|
+
route("GET", "/api/v1/servers/:id/metrics", (ctx) => {
|
|
1247
|
+
const requested = ctx.query.get("window") ?? "24h";
|
|
1248
|
+
if (!isWindow(requested))
|
|
1249
|
+
throw badRequest(`window must be one of 1h, 24h, 7d, 30d, all`);
|
|
1250
|
+
const window = requested;
|
|
1251
|
+
if (ctx.query.get("tenant") === "*") {
|
|
1252
|
+
const whole = serverById(options, ctx.params["id"]);
|
|
1253
|
+
return buildMetrics(whole, null, window, otherComponentsSharingLog(options, whole));
|
|
1254
|
+
}
|
|
1255
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
1256
|
+
return buildMetrics(server, tenant, window, otherComponentsSharingLog(options, server));
|
|
1257
|
+
}),
|
|
1258
|
+
/**
|
|
1259
|
+
* The scanner rules over what this gateway published.
|
|
1260
|
+
*
|
|
1261
|
+
* The same rules `hmcp-gateway scan` runs, over the same kind of target, so
|
|
1262
|
+
* the console cannot report a different answer than the CLI for one
|
|
1263
|
+
* gateway. It reads the upstream's own description rather than the rewritten
|
|
1264
|
+
* one, because the rewrite is what injection detection already did and
|
|
1265
|
+
* scanning its output would report nothing on the surfaces that needed it.
|
|
1266
|
+
*/
|
|
1267
|
+
route("GET", "/api/v1/servers/:id/scan", (ctx) => {
|
|
1268
|
+
const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
1269
|
+
const format = ctx.query.get("format");
|
|
1270
|
+
if (format !== null && format !== "json" && format !== "sarif")
|
|
1271
|
+
throw badRequest('format must be "json" or "sarif"');
|
|
1272
|
+
const report = buildScan(server, tenant);
|
|
1273
|
+
/*
|
|
1274
|
+
* The document `hmcp-gateway scan --sarif` writes, from the same
|
|
1275
|
+
* function, so a CI upload and a download from here agree.
|
|
1276
|
+
*/
|
|
1277
|
+
if (format === "sarif")
|
|
1278
|
+
return JSON.parse(toSarif(report, "upstream MCP servers"));
|
|
1279
|
+
return report;
|
|
1280
|
+
}),
|
|
1281
|
+
/**
|
|
1282
|
+
* The policy on disk, beside the digest the running process is enforcing.
|
|
1283
|
+
*
|
|
1284
|
+
* `protection.runtime.policyApplied` already says whether the two agree,
|
|
1285
|
+
* which is enough to raise an alarm and not enough to act on: a reviewer
|
|
1286
|
+
* who is told the running gateway is enforcing something else immediately
|
|
1287
|
+
* needs to know *what*. The text is the file the console already reads to
|
|
1288
|
+
* build every other page, and policy is reviewed in git, so this discloses
|
|
1289
|
+
* nothing new.
|
|
1290
|
+
*
|
|
1291
|
+
* There is no `PUT` here: a test asserts the 404. Editing the file as
|
|
1292
|
+
* text is `PUT /policy/file` (routes/policy.ts), digest-locked and graded
|
|
1293
|
+
* for loosening like every other policy write.
|
|
1294
|
+
*/
|
|
1295
|
+
route("GET", "/api/v1/servers/:id/policy", (ctx) => {
|
|
1296
|
+
const { server } = scopedRequest(options, ctx.params["id"], ctx.query);
|
|
1297
|
+
const announced = storeFor(server).runtimeState(server.component);
|
|
1298
|
+
let text = null;
|
|
1299
|
+
let readError = null;
|
|
1300
|
+
try {
|
|
1301
|
+
text = readFileSync(server.policyPath, "utf8");
|
|
1302
|
+
}
|
|
1303
|
+
catch (err) {
|
|
1304
|
+
readError = err.message;
|
|
1305
|
+
}
|
|
1306
|
+
return {
|
|
1307
|
+
path: server.policyPath,
|
|
1308
|
+
text,
|
|
1309
|
+
readError,
|
|
1310
|
+
policy: server.policy,
|
|
1311
|
+
runningDigest: announced?.policy_digest ?? null,
|
|
1312
|
+
runningPolicyPath: announced?.policy_path ?? null
|
|
1313
|
+
};
|
|
1314
|
+
}),
|
|
1315
|
+
/* audit */
|
|
1316
|
+
route("GET", "/api/v1/servers/:id/audit", (ctx) => {
|
|
1317
|
+
const server = serverById(options, ctx.params["id"]);
|
|
1318
|
+
// A log shared with other toolboxes: their calls are left out unless a component is asked for by name.
|
|
1319
|
+
const others = csv(ctx.query, "component") ? [] : otherComponentsSharingLog(options, server);
|
|
1320
|
+
const page = queryAuditLog(server.auditPath, {
|
|
1321
|
+
limit: intParam(ctx.query, "limit") ?? 50,
|
|
1322
|
+
...(others.length > 0 ? { excludeComponent: others } : {}),
|
|
1323
|
+
...(intParam(ctx.query, "cursor") !== undefined ? { beforeSeq: intParam(ctx.query, "cursor") } : {}),
|
|
1324
|
+
...(csv(ctx.query, "decision") ? { decision: csv(ctx.query, "decision") } : {}),
|
|
1325
|
+
...(csv(ctx.query, "outcome") ? { outcome: csv(ctx.query, "outcome") } : {}),
|
|
1326
|
+
...(csv(ctx.query, "component") ? { component: csv(ctx.query, "component") } : {}),
|
|
1327
|
+
// One log holds every tenant's records, so this is how a reviewer
|
|
1328
|
+
// reads one customer's history out of it. `?tenant=` with an empty
|
|
1329
|
+
// value selects the records that carry no tenant.
|
|
1330
|
+
...(ctx.query.has("tenant") ? { tenant: csv(ctx.query, "tenant") ?? [""] } : {}),
|
|
1331
|
+
// Recording which agent made a call is only half the requirement;
|
|
1332
|
+
// without this it would be written down and unaskable.
|
|
1333
|
+
...(csv(ctx.query, "actor") ? { actor: csv(ctx.query, "actor") } : {}),
|
|
1334
|
+
...(ctx.query.get("tool") ? { tool: ctx.query.get("tool") } : {}),
|
|
1335
|
+
...(ctx.query.get("since") ? { since: ctx.query.get("since") } : {}),
|
|
1336
|
+
// `until` has existed in AuditQuery all along with no way to ask for
|
|
1337
|
+
// it, which left the log readable forwards from a point but not
|
|
1338
|
+
// bounded at both ends -- the shape every "what happened during the
|
|
1339
|
+
// incident" question has.
|
|
1340
|
+
...(ctx.query.get("until") ? { until: ctx.query.get("until") } : {}),
|
|
1341
|
+
...(ctx.query.get("noteworthy") ? { noteworthy: true } : {})
|
|
1342
|
+
});
|
|
1343
|
+
return { ...page, auditPath: server.auditPath };
|
|
1344
|
+
}),
|
|
1345
|
+
route("GET", "/api/v1/servers/:id/audit/verify", (ctx) => {
|
|
1346
|
+
const server = serverById(options, ctx.params["id"]);
|
|
1347
|
+
/*
|
|
1348
|
+
* `hmcp audit verify --expect-head`: a head recorded earlier, somewhere
|
|
1349
|
+
* the log's owner does not control. The chain alone cannot see its own
|
|
1350
|
+
* end being cut off; this is the check that can.
|
|
1351
|
+
*/
|
|
1352
|
+
const expectHead = ctx.query.get("expectHead")?.trim() || undefined;
|
|
1353
|
+
if (expectHead !== undefined && !/^[0-9a-f]{16,128}$/i.test(expectHead)) {
|
|
1354
|
+
throw badRequest("expectHead must be a hash as the log records it");
|
|
1355
|
+
}
|
|
1356
|
+
return verifyAuditLog(server.auditPath, expectHead ? { expectHead } : {});
|
|
1357
|
+
}),
|
|
1358
|
+
/**
|
|
1359
|
+
* Combined view across servers.
|
|
1360
|
+
*
|
|
1361
|
+
* Deduped by audit path, because two servers legitimately share one log by
|
|
1362
|
+
* default. Where a path is shared, records are attributed by `component`
|
|
1363
|
+
* and the ambiguity is reported rather than guessed at.
|
|
1364
|
+
*/
|
|
1365
|
+
route("GET", "/api/v1/audit", (ctx) => {
|
|
1366
|
+
const wanted = csv(ctx.query, "servers");
|
|
1367
|
+
const entries = registry(options).servers.filter((s) => !wanted || wanted.includes(s.id));
|
|
1368
|
+
const limit = intParam(ctx.query, "limit") ?? 50;
|
|
1369
|
+
const byPath = new Map();
|
|
1370
|
+
const broken = [];
|
|
1371
|
+
for (const entry of entries) {
|
|
1372
|
+
try {
|
|
1373
|
+
const server = loadServer(entry);
|
|
1374
|
+
const list = byPath.get(server.auditPath) ?? [];
|
|
1375
|
+
list.push(server);
|
|
1376
|
+
byPath.set(server.auditPath, list);
|
|
1377
|
+
}
|
|
1378
|
+
catch (err) {
|
|
1379
|
+
broken.push({ id: entry.id, error: err.message });
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
const records = [];
|
|
1383
|
+
for (const [path, servers] of byPath) {
|
|
1384
|
+
const page = queryAuditLog(path, { limit, ...(ctx.query.get("noteworthy") ? { noteworthy: true } : {}) });
|
|
1385
|
+
for (const record of page.records) {
|
|
1386
|
+
const byComponent = servers.find((s) => s.component === record.component);
|
|
1387
|
+
const attribution = byComponent ? "component" : servers.length === 1 ? "path" : "ambiguous";
|
|
1388
|
+
records.push({
|
|
1389
|
+
...record,
|
|
1390
|
+
serverId: byComponent?.entry.id ?? (servers.length === 1 ? servers[0].entry.id : null),
|
|
1391
|
+
attribution
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
records.sort((a, b) => (a.ts === b.ts ? b.seq - a.seq : a.ts < b.ts ? 1 : -1));
|
|
1396
|
+
// Surfaced so the UI can say why some records are attributed by
|
|
1397
|
+
// component rather than simply by which server was asked for.
|
|
1398
|
+
const sharedPaths = [...byPath.entries()]
|
|
1399
|
+
.filter(([, servers]) => servers.length > 1)
|
|
1400
|
+
.map(([path, servers]) => ({ path, servers: servers.map((s) => s.entry.id) }));
|
|
1401
|
+
return { records: records.slice(0, limit), sharedPaths, broken };
|
|
1402
|
+
})
|
|
1403
|
+
];
|
|
1404
|
+
}
|