hmcp-web 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/LICENSE +77 -0
- package/README.md +49 -2
- package/THIRD-PARTY-NOTICES.md +110 -0
- package/bin/hmcp-web.js +20 -0
- package/dist/api.d.ts +22 -0
- package/dist/api.js +1458 -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/app-servers.d.ts +85 -0
- package/dist/model/app-servers.js +109 -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/import-record.d.ts +80 -0
- package/dist/model/import-record.js +179 -0
- package/dist/model/metrics.d.ts +65 -0
- package/dist/model/metrics.js +213 -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-import.d.ts +9 -0
- package/dist/routes/connect-import.js +594 -0
- package/dist/routes/connect.d.ts +50 -0
- package/dist/routes/connect.js +691 -0
- package/dist/routes/github.d.ts +97 -0
- package/dist/routes/github.js +587 -0
- package/dist/routes/guard.d.ts +3 -0
- package/dist/routes/guard.js +166 -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 +12 -0
- package/dist/routes/runtime.js +921 -0
- package/dist/routes/servers-add.d.ts +32 -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-CZ78RyRO.js +1 -0
- package/dist-ui/assets/Approvals-DPIlNZsv.js +1 -0
- package/dist-ui/assets/AttachApp-DjSeWCbS.js +5 -0
- package/dist-ui/assets/Connections-qcA96lXh.js +2 -0
- package/dist-ui/assets/Gallery-DB_OO7Vw.js +17 -0
- package/dist-ui/assets/PreApprovals-C4cKajcK.js +1 -0
- package/dist-ui/assets/Protection-B8h-5YAb.js +1 -0
- package/dist-ui/assets/Safety-BQqHyYdo.js +1 -0
- package/dist-ui/assets/Settings-Cx50zZSt.js +1 -0
- package/dist-ui/assets/StartPage-CdX-v7ej.js +1 -0
- package/dist-ui/assets/Suggestions-CRo5UOTT.js +1 -0
- package/dist-ui/assets/Tools-xo39lPKB.js +4 -0
- package/dist-ui/assets/index-DttDjRpu.js +16 -0
- package/dist-ui/assets/index-QeJyD5z2.css +2 -0
- package/dist-ui/assets/kit-DRVm92_t.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 +69 -6
- package/bin/notice.js +0 -7
|
@@ -0,0 +1,921 @@
|
|
|
1
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { writeAtomically } from "hmcp-core";
|
|
3
|
+
import { parseDocument } from "yaml";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { AuditLog, PIN_ACCEPT_RULE, contractDigest, describeContractChange, expandPath, readRegistry, runtimeStateIsLive } from "hmcp-core";
|
|
6
|
+
import { UpstreamSchema } from "hmcp-gateway";
|
|
7
|
+
import { HttpError, conflict, notFound, route, unprocessable } from "../http.js";
|
|
8
|
+
import { loadServer, storeFor } from "../model/server.js";
|
|
9
|
+
import { GUARDED_SETTINGS, KEPT_SECRET, commitGatewayText, lineDiff, parseGatewayText, readGatewayFile, readGatewayFileOrBroken, isBroken, repairGatewayText, redactConfig, redactText, redactUpstream, restoreSecretsInText, restoreSecretsInUpstream, sameExcept, assertGuardsUnchanged, gatewayLoosens, applyPolicyChanges, applyStateFor, plainRefusal, refusalNeedsRestart, digestText, egressChangesFor, liveRows, refuseIfOverridesOff, removeRulesWrittenFor } from "../model/gateway-config.js";
|
|
10
|
+
import { processes } from "../model/process.js";
|
|
11
|
+
/**
|
|
12
|
+
* The gateway as a running thing: what changed under it, how it is
|
|
13
|
+
* configured, and whether it is up.
|
|
14
|
+
*
|
|
15
|
+
* Three areas, one module, because each is about the gateway process rather
|
|
16
|
+
* than its policy -- none of them is tenant-scoped. A change to `upstreams` is
|
|
17
|
+
* applied live by a running gateway that has `upstream_reload` on; every other
|
|
18
|
+
* write here takes effect at the gateway's next start.
|
|
19
|
+
*/
|
|
20
|
+
/* ------------------------------------------------------------------ helpers */
|
|
21
|
+
function entryById(options, id) {
|
|
22
|
+
const found = readRegistry(options.registryPath).servers.find((s) => s.id === id);
|
|
23
|
+
if (!found)
|
|
24
|
+
throw notFound(`no registered server with id "${id}"`);
|
|
25
|
+
return found;
|
|
26
|
+
}
|
|
27
|
+
function serverById(options, id) {
|
|
28
|
+
const entry = entryById(options, id);
|
|
29
|
+
try {
|
|
30
|
+
return loadServer(entry);
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
if (err instanceof HttpError)
|
|
34
|
+
throw err;
|
|
35
|
+
throw unprocessable(`server "${id}" could not be loaded: ${err.message}`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function auditFor(server, actor) {
|
|
39
|
+
return new AuditLog({ config: server.policy.audit, actor, component: "hmcp-web", cwd: server.cwd });
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* One record, after the write, reported rather than rolled back on failure --
|
|
43
|
+
* the same choice the policy writers make, for the same reason: the file is
|
|
44
|
+
* already on disk, and undoing it would be a second, unaudited write.
|
|
45
|
+
*/
|
|
46
|
+
function auditAfter(server, actor, entry, what) {
|
|
47
|
+
try {
|
|
48
|
+
auditFor(server, actor).appendStrict(entry);
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
return `${what}, but the audit record failed: ${err.message}`;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function parseBody(schema, body) {
|
|
56
|
+
// An empty request body is an empty object; a JSON null is a value.
|
|
57
|
+
const parsed = schema.safeParse(body === undefined ? {} : body);
|
|
58
|
+
if (!parsed.success) {
|
|
59
|
+
throw unprocessable(parsed.error.issues.map((i) => `${i.path.map(String).join(".") || "(body)"}: ${i.message}`).join("; "));
|
|
60
|
+
}
|
|
61
|
+
return parsed.data;
|
|
62
|
+
}
|
|
63
|
+
function liveRuntime(server) {
|
|
64
|
+
const announced = storeFor(server).runtimeState(server.component);
|
|
65
|
+
return announced && runtimeStateIsLive(announced) ? announced : undefined;
|
|
66
|
+
}
|
|
67
|
+
const Acknowledged = z.object({ loosens: z.boolean().optional() }).strict();
|
|
68
|
+
/* -------------------------------------------------------------- tool changes */
|
|
69
|
+
function changeDto(row) {
|
|
70
|
+
return {
|
|
71
|
+
tool: row.tool,
|
|
72
|
+
pinnedAt: row.pinnedAt,
|
|
73
|
+
pinnedBy: row.pinnedBy,
|
|
74
|
+
wasDigest: row.wasDigest,
|
|
75
|
+
nowDigest: row.digest,
|
|
76
|
+
/*
|
|
77
|
+
* Empty with `previousKnown: false` when the old contract was never kept:
|
|
78
|
+
* the change is real, only its description is lost.
|
|
79
|
+
*/
|
|
80
|
+
changes: row.wasContract ? describeContractChange(row.wasContract, row.contract) : [],
|
|
81
|
+
previousKnown: row.wasContract !== null,
|
|
82
|
+
was: row.wasContract,
|
|
83
|
+
now: row.contract,
|
|
84
|
+
withheld: row.withheld,
|
|
85
|
+
detectedAt: row.detectedAt
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Accepts one published change, as the gateway saw it.
|
|
90
|
+
*
|
|
91
|
+
* The digest and contract come from the row the gateway wrote, never from the
|
|
92
|
+
* request: a reviewer who could name a digest could accept a contract nobody
|
|
93
|
+
* showed them. The row is also re-hashed, so a row that does not describe
|
|
94
|
+
* itself honestly is refused rather than pinned.
|
|
95
|
+
*/
|
|
96
|
+
function acceptChange(server, row, actor) {
|
|
97
|
+
if (contractDigest(row.contract) !== row.digest) {
|
|
98
|
+
throw unprocessable(`the published change for "${row.tool}" does not match its own digest, so it was not accepted`);
|
|
99
|
+
}
|
|
100
|
+
const store = storeFor(server);
|
|
101
|
+
const previous = store.getPin(server.component, row.tool);
|
|
102
|
+
store.acceptPin(server.component, row.tool, row.digest, actor, Date.now(), row.contract);
|
|
103
|
+
/*
|
|
104
|
+
* Unlike the config writes, this one is rolled back when it cannot be
|
|
105
|
+
* audited. Accepting is what lets a withheld tool be served again, and a
|
|
106
|
+
* permission with nobody recorded as granting it is the thing the log exists
|
|
107
|
+
* to prevent -- the grants route makes the same call.
|
|
108
|
+
*/
|
|
109
|
+
try {
|
|
110
|
+
auditFor(server, actor).appendStrict({
|
|
111
|
+
tool: row.tool,
|
|
112
|
+
effect: row.contract.effect,
|
|
113
|
+
decision: "allow",
|
|
114
|
+
rule_id: PIN_ACCEPT_RULE,
|
|
115
|
+
reason: `${actor} accepted what "${row.tool}" advertises now` +
|
|
116
|
+
(row.wasContract ? ` (changed: ${describeContractChange(row.wasContract, row.contract).join(", ") || "unnamed"})` : "") +
|
|
117
|
+
(row.withheld ? "; it was withheld and is served again after the gateway restarts" : ""),
|
|
118
|
+
outcome: "completed",
|
|
119
|
+
args_redacted: { was: row.wasDigest, now: row.digest, withheld: row.withheld, origin: "console" }
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
if (previous) {
|
|
124
|
+
store.acceptPin(server.component, row.tool, previous.digest, previous.pinnedBy, previous.pinnedAt, previous.contract);
|
|
125
|
+
}
|
|
126
|
+
throw new Error(`"${row.tool}" was not accepted because the acceptance could not be audited: ${err.message}`);
|
|
127
|
+
}
|
|
128
|
+
store.clearToolChange(server.component, row.tool);
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The changes a reviewer may act on: published by the process that is
|
|
133
|
+
* announcing itself now. A dead gateway's list is shown but not acted on --
|
|
134
|
+
* the next process to start re-checks every pin and may find something else.
|
|
135
|
+
*/
|
|
136
|
+
function actionableChanges(server) {
|
|
137
|
+
const live = liveRuntime(server);
|
|
138
|
+
if (!live) {
|
|
139
|
+
throw unprocessable("no running gateway is announcing itself for this server, so there is no current list of changed tools " +
|
|
140
|
+
"to accept. Start the gateway, then review what it reports.");
|
|
141
|
+
}
|
|
142
|
+
return storeFor(server)
|
|
143
|
+
.toolChanges(server.component)
|
|
144
|
+
.filter((row) => row.pid === live.pid);
|
|
145
|
+
}
|
|
146
|
+
/* ------------------------------------------------------------ gateway config */
|
|
147
|
+
/**
|
|
148
|
+
* The settings a form may write, each with its own value schema. `null`
|
|
149
|
+
* removes the key, which puts the schema's default back.
|
|
150
|
+
*
|
|
151
|
+
* Exactly `GatewayConfigSchema`'s top-level keys, less three: `version` is
|
|
152
|
+
* fixed, `upstreams` has its own routes, and `policy` is edited on the policy
|
|
153
|
+
* pages. `policy_writes` and `policy_overrides` are refused by name below.
|
|
154
|
+
*/
|
|
155
|
+
const SETTINGS = {
|
|
156
|
+
name: z.string().min(1).max(100).nullable(),
|
|
157
|
+
connect_timeout_ms: z.number().int().positive().nullable(),
|
|
158
|
+
on_injection: z.enum(["strip", "deny", "annotate"]).nullable(),
|
|
159
|
+
injection_overrides: z.record(z.string().min(1), z.enum(["strip", "deny", "annotate", "accept"])).nullable(),
|
|
160
|
+
namespace: z.boolean().nullable(),
|
|
161
|
+
policy_reload: z.boolean().nullable(),
|
|
162
|
+
max_tool_name_length: z.number().int().positive().nullable(),
|
|
163
|
+
notify: z.boolean().nullable()
|
|
164
|
+
};
|
|
165
|
+
const SettingBody = z
|
|
166
|
+
.object({
|
|
167
|
+
path: z.string().min(1),
|
|
168
|
+
value: z.unknown(),
|
|
169
|
+
expectedDigest: z.string().min(1),
|
|
170
|
+
acknowledged: Acknowledged.optional()
|
|
171
|
+
})
|
|
172
|
+
.strict();
|
|
173
|
+
const UpstreamBody = z
|
|
174
|
+
.object({ upstream: z.unknown(), expectedDigest: z.string().min(1), acknowledged: Acknowledged.optional() })
|
|
175
|
+
.strict();
|
|
176
|
+
const FileBody = z
|
|
177
|
+
.object({ text: z.string(), expectedDigest: z.string().min(1), acknowledged: Acknowledged.optional() })
|
|
178
|
+
.strict();
|
|
179
|
+
function readCurrent(path) {
|
|
180
|
+
return readFileSync(path, "utf8");
|
|
181
|
+
}
|
|
182
|
+
function gatewayFileFor(options, id) {
|
|
183
|
+
return readGatewayFile(expandPath(entryById(options, id).config_path));
|
|
184
|
+
}
|
|
185
|
+
function upstreamIndex(doc, name) {
|
|
186
|
+
const seq = doc.get("upstreams", true);
|
|
187
|
+
const items = seq?.items ?? [];
|
|
188
|
+
return items.findIndex((item) => item.get?.("name") === name);
|
|
189
|
+
}
|
|
190
|
+
function parseUpstream(raw) {
|
|
191
|
+
const parsed = UpstreamSchema.safeParse(raw);
|
|
192
|
+
if (!parsed.success) {
|
|
193
|
+
throw unprocessable(`not a valid connected server: ${parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ")}`);
|
|
194
|
+
}
|
|
195
|
+
return parsed.data;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* The upstream as it goes into YAML: the keys the person gave and nothing the
|
|
199
|
+
* schema would only have defaulted, so the file does not fill up with
|
|
200
|
+
* `args: []` and `env: {}`.
|
|
201
|
+
*/
|
|
202
|
+
function upstreamNode(raw, parsed) {
|
|
203
|
+
const restored = parsed;
|
|
204
|
+
const out = {};
|
|
205
|
+
for (const key of Object.keys(raw))
|
|
206
|
+
if (restored[key] !== undefined)
|
|
207
|
+
out[key] = restored[key];
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Why the running gateway is not running what gateway.yaml says, if it is not.
|
|
212
|
+
*
|
|
213
|
+
* A gateway that reports live state says so itself: a refusal (a change it
|
|
214
|
+
* cannot apply live) means a restart. One still on its way to applying an
|
|
215
|
+
* upstream change is not a reason to restart. A gateway from before live
|
|
216
|
+
* state is judged by the file's age against its start, as before.
|
|
217
|
+
*/
|
|
218
|
+
function restartPending(options, id, server, path) {
|
|
219
|
+
const rows = liveRows(storeFor(server), server.component);
|
|
220
|
+
if (rows.length > 0) {
|
|
221
|
+
let digest;
|
|
222
|
+
try {
|
|
223
|
+
digest = digestText(readFileSync(path, "utf8"));
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return [];
|
|
227
|
+
}
|
|
228
|
+
return [
|
|
229
|
+
...new Set(rows
|
|
230
|
+
.filter((r) => r.config_digest !== digest && r.refusal)
|
|
231
|
+
.map((r) => plainRefusal(r.refusal)))
|
|
232
|
+
];
|
|
233
|
+
}
|
|
234
|
+
const managed = processes.view(id);
|
|
235
|
+
const startedAt = managed.state === "running" || managed.state === "starting"
|
|
236
|
+
? managed.startedAt
|
|
237
|
+
: (liveRuntime(server)?.started_at ?? null);
|
|
238
|
+
if (startedAt === null)
|
|
239
|
+
return [];
|
|
240
|
+
let mtime = 0;
|
|
241
|
+
try {
|
|
242
|
+
mtime = statSync(path).mtimeMs;
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
return [];
|
|
246
|
+
}
|
|
247
|
+
/*
|
|
248
|
+
* Best effort for a gateway this console did not start: its announced
|
|
249
|
+
* `started_at` is refreshed when it reloads its policy, so a policy reload
|
|
250
|
+
* after a gateway.yaml edit hides the edit here.
|
|
251
|
+
*/
|
|
252
|
+
return mtime > startedAt ? ["gateway.yaml changed after the running gateway started"] : [];
|
|
253
|
+
}
|
|
254
|
+
/** What a write just did to what is running. See `applyStateFor`. */
|
|
255
|
+
export function applyStateAfter(options, id, result) {
|
|
256
|
+
const running = processes.isActive(id) || externalRuntime(options, id) !== null;
|
|
257
|
+
let rows = [];
|
|
258
|
+
try {
|
|
259
|
+
const server = loadServer(entryById(options, id));
|
|
260
|
+
rows = liveRows(storeFor(server), server.component);
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
/* a gateway that does not load reports nothing live */
|
|
264
|
+
}
|
|
265
|
+
return applyStateFor({
|
|
266
|
+
rows,
|
|
267
|
+
running,
|
|
268
|
+
upstreamsOnly: sameExcept(result.before, result.after, ["upstreams"]),
|
|
269
|
+
upstreamReload: result.after.upstream_reload,
|
|
270
|
+
digest: result.digest
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
/** Why a write needs a restart, in plain words, when a running gateway has said why. */
|
|
274
|
+
function restartWhyFor(options, id) {
|
|
275
|
+
try {
|
|
276
|
+
const server = loadServer(entryById(options, id));
|
|
277
|
+
const row = liveRows(storeFor(server), server.component).find((r) => refusalNeedsRestart(r.refusal));
|
|
278
|
+
return row ? plainRefusal(row.refusal) : null;
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function writeResponse(options, id, result, warning) {
|
|
285
|
+
const apply = applyStateAfter(options, id, result);
|
|
286
|
+
const upstreamsOnly = sameExcept(result.before, result.after, ["upstreams"]);
|
|
287
|
+
return {
|
|
288
|
+
digest: result.digest,
|
|
289
|
+
previousDigest: result.previousDigest,
|
|
290
|
+
config: redactConfig(result.after),
|
|
291
|
+
loosens: result.loosens,
|
|
292
|
+
/*
|
|
293
|
+
* True when something has to be restarted for this to take effect: a
|
|
294
|
+
* running gateway that cannot apply it live, or a change to anything but
|
|
295
|
+
* `upstreams`, which is only ever read at start.
|
|
296
|
+
*/
|
|
297
|
+
restartNeeded: apply === "needs-restart" || (apply === "not-running" && !upstreamsOnly),
|
|
298
|
+
/* Set when a running gateway already refused an earlier change: what to do about it. */
|
|
299
|
+
restartWhy: apply === "needs-restart" ? restartWhyFor(options, id) : null,
|
|
300
|
+
apply,
|
|
301
|
+
running: processes.isActive(id) || externalRuntime(options, id) !== null,
|
|
302
|
+
warning
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
function egressPlanFor(server, upstream) {
|
|
306
|
+
const changes = egressChangesFor(upstream);
|
|
307
|
+
if (changes.length === 0)
|
|
308
|
+
return null;
|
|
309
|
+
const host = upstream.transport === "http" ? new URL(upstream.url).hostname : "";
|
|
310
|
+
if (server.policyFile === null || !server.gateway.config.policy_writes) {
|
|
311
|
+
const allowed = server.policy.egress.allow.includes(host) && server.policy.egress.methods.includes("POST");
|
|
312
|
+
if (allowed)
|
|
313
|
+
return null;
|
|
314
|
+
return {
|
|
315
|
+
kind: "skipped",
|
|
316
|
+
warning: `this gateway's network rules could not be changed from here (${server.policyFile === null ? "its policy is inside gateway.yaml" : "it has policy_writes: false"}), ` +
|
|
317
|
+
`so ${host} has to be added to egress.allow, and POST to egress.methods, by hand before this server can connect`
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
const before = readFileSync(server.policyFile, "utf8");
|
|
321
|
+
const batch = applyPolicyChanges(before, changes, server.policyFile);
|
|
322
|
+
if (!batch.changed)
|
|
323
|
+
return null;
|
|
324
|
+
refuseIfOverridesOff(server.gateway.config, batch.loosens);
|
|
325
|
+
return { kind: "write", path: server.policyFile, before, after: batch.text, loosens: batch.loosens };
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Writes the policy half first, then the gateway.yaml half through
|
|
329
|
+
* `commitGatewayText`, and puts the policy back if the second write is
|
|
330
|
+
* refused -- so a server is never left half-added. Every loosening of both
|
|
331
|
+
* halves is gated together, before anything is written.
|
|
332
|
+
*/
|
|
333
|
+
function commitWithEgress(server, plan, file, text, expectedDigest, acknowledged, intended) {
|
|
334
|
+
if (file.digest !== expectedDigest) {
|
|
335
|
+
throw conflict("gateway.yaml changed since it was read. Reload it and make the change again, so nothing written in " +
|
|
336
|
+
"the meantime is overwritten.");
|
|
337
|
+
}
|
|
338
|
+
const write = plan?.kind === "write" ? plan : null;
|
|
339
|
+
if (write) {
|
|
340
|
+
const after = parseGatewayText(text);
|
|
341
|
+
assertGuardsUnchanged(file.config, after);
|
|
342
|
+
const loosens = [...gatewayLoosens(file.config, after), ...write.loosens];
|
|
343
|
+
if (loosens.length > 0 && !acknowledged) {
|
|
344
|
+
throw unprocessable(`this change lets more through and needs confirming: ${loosens.join("; ")}`, { needs: "loosens", loosens });
|
|
345
|
+
}
|
|
346
|
+
writeAtomically(write.path, write.after);
|
|
347
|
+
}
|
|
348
|
+
try {
|
|
349
|
+
const result = commitGatewayText({ file, text, expectedDigest, acknowledgedLoosens: acknowledged, intended });
|
|
350
|
+
return { ...result, loosens: [...result.loosens, ...(write?.loosens ?? [])], policyLoosens: write?.loosens ?? [] };
|
|
351
|
+
}
|
|
352
|
+
catch (err) {
|
|
353
|
+
if (write)
|
|
354
|
+
writeAtomically(write.path, write.before);
|
|
355
|
+
throw err;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/** Takes the ready-made rules written for a removed server out of policy.yaml, and says what happened. */
|
|
359
|
+
export function removeServerRules(server, name) {
|
|
360
|
+
const path = server.policyFile;
|
|
361
|
+
if (path === null || !server.gateway.config.policy_writes)
|
|
362
|
+
return { removed: [], note: null };
|
|
363
|
+
try {
|
|
364
|
+
const out = removeRulesWrittenFor(readFileSync(path, "utf8"), name);
|
|
365
|
+
if (out.removed.length === 0)
|
|
366
|
+
return { removed: [], note: null };
|
|
367
|
+
if (server.gateway.config.policy_overrides === false) {
|
|
368
|
+
return {
|
|
369
|
+
removed: [],
|
|
370
|
+
note: `${out.removed.length === 1 ? "1 ready-made rule" : `${out.removed.length} ready-made rules`} written for "${name}" ` +
|
|
371
|
+
`were left in the policy, because this toolbox is set so the console only tightens it. They match nothing now.`
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
writeAtomically(path, out.text);
|
|
375
|
+
return {
|
|
376
|
+
removed: out.removed,
|
|
377
|
+
note: `Also removed ${out.removed.length === 1 ? "1 ready-made rule" : `${out.removed.length} ready-made rules`} written for "${name}". ` +
|
|
378
|
+
`Rules you wrote yourself were kept, and the allowed addresses were left as they are, because another server may use them.`
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
catch (err) {
|
|
382
|
+
return {
|
|
383
|
+
removed: [],
|
|
384
|
+
note: `"${name}" was removed, but the ready-made rules written for it could not be taken out of the policy ` +
|
|
385
|
+
`(${err.message}). They match nothing now; you can delete them on the Protection settings page.`
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
function joinWarnings(warning, plan) {
|
|
390
|
+
const parts = [warning, plan?.kind === "skipped" ? plan.warning : null].filter((p) => p !== null);
|
|
391
|
+
return parts.length > 0 ? parts.join("; ") : null;
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* The processes running this gateway that the console did not start, by pid.
|
|
395
|
+
*
|
|
396
|
+
* Two sources, because one is not enough. `runtime_state` holds one row per
|
|
397
|
+
* gateway, so when a second AI app (or a second session of one) starts the
|
|
398
|
+
* same toolbox and then exits, the row names a dead process while the first
|
|
399
|
+
* one is still serving. The live-state table has a row per process, each with
|
|
400
|
+
* its own heartbeat, so it still sees the first. Either one beating is enough
|
|
401
|
+
* to say "running", and to refuse to start another copy beside it.
|
|
402
|
+
*/
|
|
403
|
+
function externalPids(options, id) {
|
|
404
|
+
try {
|
|
405
|
+
const server = loadServer(entryById(options, id));
|
|
406
|
+
const pids = new Set();
|
|
407
|
+
const live = liveRuntime(server);
|
|
408
|
+
if (live && processes.isForeign(live.pid))
|
|
409
|
+
pids.add(live.pid);
|
|
410
|
+
for (const row of liveRows(storeFor(server), server.component))
|
|
411
|
+
if (processes.isForeign(row.pid))
|
|
412
|
+
pids.add(row.pid);
|
|
413
|
+
return [...pids].sort((a, b) => a - b);
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
return [];
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
function externalRuntime(options, id) {
|
|
420
|
+
const pids = externalPids(options, id);
|
|
421
|
+
return pids.length > 0 ? { pid: pids[0], pids } : null;
|
|
422
|
+
}
|
|
423
|
+
function settingAudit(rule, reason, args) {
|
|
424
|
+
return {
|
|
425
|
+
tool: "(gateway)",
|
|
426
|
+
effect: null,
|
|
427
|
+
decision: "allow",
|
|
428
|
+
rule_id: rule,
|
|
429
|
+
reason,
|
|
430
|
+
outcome: "completed",
|
|
431
|
+
args_redacted: { ...args, origin: "console" }
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
/* ------------------------------------------------------------------ process */
|
|
435
|
+
const StartBody = z
|
|
436
|
+
.object({
|
|
437
|
+
http: z
|
|
438
|
+
.object({
|
|
439
|
+
port: z.number().int().min(0).max(65535).optional(),
|
|
440
|
+
/*
|
|
441
|
+
* Loopback only. The console is a local admin surface, and a gateway it
|
|
442
|
+
* starts on a public interface would be a socket anyone on the network
|
|
443
|
+
* could call tools through, started from a form.
|
|
444
|
+
*/
|
|
445
|
+
host: z.enum(["127.0.0.1", "::1", "localhost"]).optional(),
|
|
446
|
+
allowHosts: z.array(z.string().regex(/^[A-Za-z0-9.\-:[\]]{1,253}$/, "not a host name")).max(20).optional(),
|
|
447
|
+
allowOrigins: z
|
|
448
|
+
.array(z.string().regex(/^https?:\/\/[A-Za-z0-9.\-:[\]]+$/, "an origin is a scheme, a host and a port, with no path"))
|
|
449
|
+
.max(20)
|
|
450
|
+
.optional(),
|
|
451
|
+
requireToken: z.boolean().optional()
|
|
452
|
+
})
|
|
453
|
+
.strict()
|
|
454
|
+
.default({}),
|
|
455
|
+
acknowledged: Acknowledged.optional()
|
|
456
|
+
})
|
|
457
|
+
.strict();
|
|
458
|
+
const LOOPBACK_NAMES = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
|
|
459
|
+
/**
|
|
460
|
+
* What a start's HTTP options open beyond the loopback default, in plain words.
|
|
461
|
+
*
|
|
462
|
+
* An allowed origin lets a web page in a browser call the gateway, and an
|
|
463
|
+
* allowed host lets it answer to a name other than this machine's own; both
|
|
464
|
+
* reach further than a gateway only local apps can call, so each needs the
|
|
465
|
+
* same confirmation as any other loosening.
|
|
466
|
+
*/
|
|
467
|
+
function startLoosens(http) {
|
|
468
|
+
const out = [];
|
|
469
|
+
if (http.allowOrigins.length > 0) {
|
|
470
|
+
out.push(`web pages from ${http.allowOrigins.join(", ")} may call the gateway from a browser`);
|
|
471
|
+
}
|
|
472
|
+
const loopback = (h) => LOOPBACK_NAMES.has(h) || LOOPBACK_NAMES.has(h.replace(/:\d+$/, ""));
|
|
473
|
+
const hosts = http.allowHosts.filter((h) => !loopback(h.toLowerCase()));
|
|
474
|
+
if (hosts.length > 0)
|
|
475
|
+
out.push(`the gateway answers requests addressed to ${hosts.join(", ")}`);
|
|
476
|
+
return out;
|
|
477
|
+
}
|
|
478
|
+
/** The refusal to start a gateway beside one something else is already running. */
|
|
479
|
+
function refuseIfExternal(options, id) {
|
|
480
|
+
const external = externalRuntime(options, id);
|
|
481
|
+
if (external) {
|
|
482
|
+
throw conflict(`Your toolbox is already running, started by an AI app (${external.pids.length === 1 ? "process" : "processes"} ` +
|
|
483
|
+
`${external.pids.join(", ")}). Starting another copy here would get in its way. To restart it, quit that app ` +
|
|
484
|
+
`completely and open it again.`);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
function processDto(options, id) {
|
|
488
|
+
const view = processes.view(id);
|
|
489
|
+
const external = externalRuntime(options, id);
|
|
490
|
+
return {
|
|
491
|
+
...view,
|
|
492
|
+
/*
|
|
493
|
+
* A gateway announcing itself that this console did not start: almost
|
|
494
|
+
* always one an AI app launched over stdio. It cannot be stopped or
|
|
495
|
+
* restarted from here, so the page says which app to restart instead.
|
|
496
|
+
*/
|
|
497
|
+
externallyRunning: external !== null,
|
|
498
|
+
externalPid: external?.pid ?? null,
|
|
499
|
+
/* Every process running it: two apps (or two sessions of one) each run their own copy. */
|
|
500
|
+
externalPids: external?.pids ?? [],
|
|
501
|
+
externalHint: external
|
|
502
|
+
? external.pids.length === 1
|
|
503
|
+
? `Your toolbox is running, started by an AI app (process ${external.pid}). To restart it, quit that app ` +
|
|
504
|
+
`completely and open it again.`
|
|
505
|
+
: `Your toolbox is running in ${external.pids.length} AI apps or sessions (processes ${external.pids.join(", ")}). ` +
|
|
506
|
+
`To restart it, quit each of them completely and open them again.`
|
|
507
|
+
: null
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
/* ------------------------------------------------------------------- routes */
|
|
511
|
+
export function runtimeRoutes(options) {
|
|
512
|
+
return [
|
|
513
|
+
/* changed tools */
|
|
514
|
+
route("GET", "/api/v1/servers/:id/tool-changes", (ctx) => {
|
|
515
|
+
const server = serverById(options, ctx.params["id"]);
|
|
516
|
+
const live = liveRuntime(server);
|
|
517
|
+
const store = storeFor(server);
|
|
518
|
+
const rows = store.toolChanges(server.component);
|
|
519
|
+
return {
|
|
520
|
+
live: live !== undefined,
|
|
521
|
+
onToolChange: server.policy.on_tool_change,
|
|
522
|
+
/*
|
|
523
|
+
* Rows from a process that is no longer announcing itself are still
|
|
524
|
+
* shown, marked by `live: false`, because under `deny` they describe
|
|
525
|
+
* pins that are still waiting. They cannot be accepted until a gateway
|
|
526
|
+
* re-checks them.
|
|
527
|
+
*/
|
|
528
|
+
changed: rows.filter((r) => !live || r.pid === live.pid).map(changeDto),
|
|
529
|
+
pins: store.listPins(server.component)
|
|
530
|
+
};
|
|
531
|
+
}),
|
|
532
|
+
route("POST", "/api/v1/servers/:id/tool-changes/:tool/accept", (ctx) => {
|
|
533
|
+
// Strict and empty: nothing about what is accepted is the client's to say.
|
|
534
|
+
parseBody(z.object({}).strict(), ctx.body);
|
|
535
|
+
const server = serverById(options, ctx.params["id"]);
|
|
536
|
+
const name = ctx.params["tool"];
|
|
537
|
+
const row = actionableChanges(server).find((r) => r.tool === name);
|
|
538
|
+
if (!row)
|
|
539
|
+
throw unprocessable(`the running gateway has not reported a change to "${name}", so there is nothing to accept`);
|
|
540
|
+
acceptChange(server, row, ctx.actor);
|
|
541
|
+
return { accepted: [name], restartNeeded: row.withheld };
|
|
542
|
+
}),
|
|
543
|
+
route("POST", "/api/v1/servers/:id/tool-changes/accept-all", (ctx) => {
|
|
544
|
+
parseBody(z.object({}).strict(), ctx.body);
|
|
545
|
+
const server = serverById(options, ctx.params["id"]);
|
|
546
|
+
const rows = actionableChanges(server);
|
|
547
|
+
if (rows.length === 0)
|
|
548
|
+
throw unprocessable("the running gateway has not reported any changed tools");
|
|
549
|
+
for (const row of rows)
|
|
550
|
+
acceptChange(server, row, ctx.actor);
|
|
551
|
+
return { accepted: rows.map((r) => r.tool), restartNeeded: rows.some((r) => r.withheld) };
|
|
552
|
+
}),
|
|
553
|
+
/* gateway.yaml */
|
|
554
|
+
route("GET", "/api/v1/servers/:id/gateway", (ctx) => {
|
|
555
|
+
const id = ctx.params["id"];
|
|
556
|
+
const loose = readGatewayFileOrBroken(expandPath(entryById(options, id).config_path));
|
|
557
|
+
if (isBroken(loose)) {
|
|
558
|
+
/*
|
|
559
|
+
* A file the gateway cannot load is still shown, so it can be repaired
|
|
560
|
+
* from here: `broken` says what is wrong, and the raw editor's save
|
|
561
|
+
* takes the repair path (`repairGatewayText`).
|
|
562
|
+
*/
|
|
563
|
+
return {
|
|
564
|
+
path: loose.path,
|
|
565
|
+
text: loose.text,
|
|
566
|
+
config: null,
|
|
567
|
+
digest: loose.digest,
|
|
568
|
+
broken: loose.error,
|
|
569
|
+
policyInline: false,
|
|
570
|
+
restartNeededFor: [],
|
|
571
|
+
settings: Object.keys(SETTINGS),
|
|
572
|
+
guarded: {},
|
|
573
|
+
keptSecret: KEPT_SECRET
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
const server = serverById(options, id);
|
|
577
|
+
const file = gatewayFileFor(options, id);
|
|
578
|
+
return {
|
|
579
|
+
broken: null,
|
|
580
|
+
path: file.path,
|
|
581
|
+
text: redactText(file.text),
|
|
582
|
+
config: redactConfig(file.config),
|
|
583
|
+
digest: file.digest,
|
|
584
|
+
policyInline: typeof file.config.policy !== "string",
|
|
585
|
+
restartNeededFor: restartPending(options, id, server, file.path),
|
|
586
|
+
settings: Object.keys(SETTINGS),
|
|
587
|
+
/* Shown read-only, with why. */
|
|
588
|
+
guarded: Object.fromEntries(GUARDED_SETTINGS.map((k) => [k, file.config[k]])),
|
|
589
|
+
keptSecret: KEPT_SECRET
|
|
590
|
+
};
|
|
591
|
+
}),
|
|
592
|
+
route("PUT", "/api/v1/servers/:id/gateway/setting", (ctx) => {
|
|
593
|
+
const id = ctx.params["id"];
|
|
594
|
+
const body = parseBody(SettingBody, ctx.body);
|
|
595
|
+
if (GUARDED_SETTINGS.includes(body.path)) {
|
|
596
|
+
throw new HttpError(403, "forbidden", `${body.path} cannot be changed from the console. It decides whether the console may change policy ` +
|
|
597
|
+
`at all, so a console that could change it would be giving itself permission. Edit gateway.yaml directly.`);
|
|
598
|
+
}
|
|
599
|
+
const schema = SETTINGS[body.path];
|
|
600
|
+
if (!schema) {
|
|
601
|
+
throw unprocessable(`"${body.path}" is not a setting this page writes. It writes ${Object.keys(SETTINGS).join(", ")}; ` +
|
|
602
|
+
`connected servers have their own form and the policy is edited on the Protection settings page.`);
|
|
603
|
+
}
|
|
604
|
+
if (body.value === undefined)
|
|
605
|
+
throw unprocessable("value is required (null removes the setting)");
|
|
606
|
+
const value = parseBody(schema, body.value);
|
|
607
|
+
const server = serverById(options, id);
|
|
608
|
+
const file = gatewayFileFor(options, id);
|
|
609
|
+
const doc = parseDocument(file.text);
|
|
610
|
+
if (value === null)
|
|
611
|
+
doc.delete(body.path);
|
|
612
|
+
else
|
|
613
|
+
doc.set(body.path, doc.createNode(value));
|
|
614
|
+
const result = commitGatewayText({
|
|
615
|
+
file,
|
|
616
|
+
text: doc.toString(),
|
|
617
|
+
expectedDigest: body.expectedDigest,
|
|
618
|
+
acknowledgedLoosens: body.acknowledged?.loosens === true,
|
|
619
|
+
intended: (before, after) => sameExcept(before, after, [body.path]) ? null : `the edit to ${body.path} would have changed something else too`
|
|
620
|
+
});
|
|
621
|
+
const before = result.before[body.path];
|
|
622
|
+
const after = result.after[body.path];
|
|
623
|
+
const warning = auditAfter(server, ctx.actor, settingAudit("gateway.setting", `${body.path} set to ${JSON.stringify(after)} in ${file.path} via the console by ${ctx.actor}` +
|
|
624
|
+
(result.loosens.length > 0 ? `, confirmed as loosening: ${result.loosens.join("; ")}` : ""), {
|
|
625
|
+
path: body.path,
|
|
626
|
+
before: before ?? null,
|
|
627
|
+
after: after ?? null,
|
|
628
|
+
loosens: result.loosens,
|
|
629
|
+
digest_before: result.previousDigest,
|
|
630
|
+
digest_after: result.digest
|
|
631
|
+
}), `${body.path} was written`);
|
|
632
|
+
return writeResponse(options, id, result, warning);
|
|
633
|
+
}),
|
|
634
|
+
route("POST", "/api/v1/servers/:id/gateway/upstreams", (ctx) => {
|
|
635
|
+
const id = ctx.params["id"];
|
|
636
|
+
const body = parseBody(UpstreamBody, ctx.body);
|
|
637
|
+
const server = serverById(options, id);
|
|
638
|
+
const file = gatewayFileFor(options, id);
|
|
639
|
+
const raw = (body.upstream ?? {});
|
|
640
|
+
const upstream = restoreSecretsInUpstream(parseUpstream(raw), undefined);
|
|
641
|
+
if (file.config.upstreams.some((u) => u.name === upstream.name)) {
|
|
642
|
+
throw conflict(`a connected server called "${upstream.name}" already exists`);
|
|
643
|
+
}
|
|
644
|
+
const doc = parseDocument(file.text);
|
|
645
|
+
doc.addIn(["upstreams"], doc.createNode(upstreamNode(raw, upstream)));
|
|
646
|
+
const plan = egressPlanFor(server, upstream);
|
|
647
|
+
const result = commitWithEgress(server, plan, file, doc.toString(), body.expectedDigest, body.acknowledged?.loosens === true, (before, after) => sameExcept(before, after, ["upstreams"]) &&
|
|
648
|
+
after.upstreams.length === before.upstreams.length + 1 &&
|
|
649
|
+
before.upstreams.every((u, i) => JSON.stringify(u) === JSON.stringify(after.upstreams[i]))
|
|
650
|
+
? null
|
|
651
|
+
: "adding a server would have changed something else too");
|
|
652
|
+
const warning = auditAfter(server, ctx.actor, settingAudit("gateway.upstream.add", `connected server "${upstream.name}" added to ${file.path} by ${ctx.actor}` +
|
|
653
|
+
(result.policyLoosens.length > 0 ? `; network rules changed: ${result.policyLoosens.join("; ")}` : ""), {
|
|
654
|
+
upstream: redactUpstream(upstream),
|
|
655
|
+
loosens: result.loosens,
|
|
656
|
+
policy_changed: plan?.kind === "write",
|
|
657
|
+
digest_before: result.previousDigest,
|
|
658
|
+
digest_after: result.digest
|
|
659
|
+
}), `"${upstream.name}" was added`);
|
|
660
|
+
return writeResponse(options, id, result, joinWarnings(warning, plan));
|
|
661
|
+
}),
|
|
662
|
+
route("PUT", "/api/v1/servers/:id/gateway/upstreams/:name", (ctx) => {
|
|
663
|
+
const id = ctx.params["id"];
|
|
664
|
+
const name = ctx.params["name"];
|
|
665
|
+
const body = parseBody(UpstreamBody, ctx.body);
|
|
666
|
+
const server = serverById(options, id);
|
|
667
|
+
const file = gatewayFileFor(options, id);
|
|
668
|
+
const current = file.config.upstreams.find((u) => u.name === name);
|
|
669
|
+
if (!current)
|
|
670
|
+
throw notFound(`no connected server called "${name}"`);
|
|
671
|
+
const raw = { name, ...(body.upstream ?? {}) };
|
|
672
|
+
if (raw.name !== name) {
|
|
673
|
+
/*
|
|
674
|
+
* A rename is refused rather than performed. Under `namespace` every
|
|
675
|
+
* tool name carries the server's name, so a rename silently strands
|
|
676
|
+
* each switch, rule and pin stored under the old ones.
|
|
677
|
+
*/
|
|
678
|
+
throw unprocessable(`a connected server cannot be renamed here; remove "${name}" and add the new one`);
|
|
679
|
+
}
|
|
680
|
+
const upstream = restoreSecretsInUpstream(parseUpstream(raw), current);
|
|
681
|
+
const doc = parseDocument(file.text);
|
|
682
|
+
const index = upstreamIndex(doc, name);
|
|
683
|
+
if (index < 0)
|
|
684
|
+
throw notFound(`no connected server called "${name}"`);
|
|
685
|
+
const old = doc.getIn(["upstreams", index], true);
|
|
686
|
+
const node = doc.createNode(upstreamNode(raw, upstream));
|
|
687
|
+
// The item is replaced whole; the comment above it is kept.
|
|
688
|
+
node.commentBefore = old?.commentBefore ?? null;
|
|
689
|
+
node.comment = old?.comment ?? null;
|
|
690
|
+
doc.setIn(["upstreams", index], node);
|
|
691
|
+
const plan = egressPlanFor(server, upstream);
|
|
692
|
+
const result = commitWithEgress(server, plan, file, doc.toString(), body.expectedDigest, body.acknowledged?.loosens === true, (before, after) => sameExcept(before, after, ["upstreams"]) &&
|
|
693
|
+
after.upstreams.length === before.upstreams.length &&
|
|
694
|
+
before.upstreams.every((u, i) => u.name === after.upstreams[i].name && (u.name === name || JSON.stringify(u) === JSON.stringify(after.upstreams[i])))
|
|
695
|
+
? null
|
|
696
|
+
: `updating "${name}" would have changed something else too`);
|
|
697
|
+
const warning = auditAfter(server, ctx.actor, settingAudit("gateway.upstream.update", `connected server "${name}" updated in ${file.path} by ${ctx.actor}` +
|
|
698
|
+
(result.policyLoosens.length > 0 ? `; network rules changed: ${result.policyLoosens.join("; ")}` : ""), {
|
|
699
|
+
before: redactUpstream(current),
|
|
700
|
+
after: redactUpstream(upstream),
|
|
701
|
+
loosens: result.loosens,
|
|
702
|
+
policy_changed: plan?.kind === "write",
|
|
703
|
+
digest_before: result.previousDigest,
|
|
704
|
+
digest_after: result.digest
|
|
705
|
+
}), `"${name}" was updated`);
|
|
706
|
+
return writeResponse(options, id, result, joinWarnings(warning, plan));
|
|
707
|
+
}),
|
|
708
|
+
route("DELETE", "/api/v1/servers/:id/gateway/upstreams/:name", (ctx) => {
|
|
709
|
+
const id = ctx.params["id"];
|
|
710
|
+
const name = ctx.params["name"];
|
|
711
|
+
const expectedDigest = ctx.query.get("expectedDigest") ?? "";
|
|
712
|
+
if (!expectedDigest)
|
|
713
|
+
throw unprocessable("expectedDigest is required");
|
|
714
|
+
const server = serverById(options, id);
|
|
715
|
+
const file = gatewayFileFor(options, id);
|
|
716
|
+
const current = file.config.upstreams.find((u) => u.name === name);
|
|
717
|
+
if (!current)
|
|
718
|
+
throw notFound(`no connected server called "${name}"`);
|
|
719
|
+
if (file.config.upstreams.length === 1) {
|
|
720
|
+
throw unprocessable(`"${name}" is this gateway's only connected server, and a gateway needs at least one. Add another first, ` +
|
|
721
|
+
`or remove the gateway from the console.`);
|
|
722
|
+
}
|
|
723
|
+
const doc = parseDocument(file.text);
|
|
724
|
+
const index = upstreamIndex(doc, name);
|
|
725
|
+
if (index < 0)
|
|
726
|
+
throw notFound(`no connected server called "${name}"`);
|
|
727
|
+
doc.deleteIn(["upstreams", index]);
|
|
728
|
+
const result = commitGatewayText({
|
|
729
|
+
file,
|
|
730
|
+
text: doc.toString(),
|
|
731
|
+
expectedDigest,
|
|
732
|
+
acknowledgedLoosens: false,
|
|
733
|
+
intended: (before, after) => sameExcept(before, after, ["upstreams"]) &&
|
|
734
|
+
JSON.stringify(before.upstreams.filter((u) => u.name !== name)) === JSON.stringify(after.upstreams)
|
|
735
|
+
? null
|
|
736
|
+
: `removing "${name}" would have changed something else too`
|
|
737
|
+
});
|
|
738
|
+
/*
|
|
739
|
+
* Then the rules written for it, after the server is gone -- never
|
|
740
|
+
* before, so a refused gateway.yaml cannot leave a server running
|
|
741
|
+
* without its rules. A failure here leaves rules that match nothing,
|
|
742
|
+
* which is said, not undone.
|
|
743
|
+
*/
|
|
744
|
+
const cleanup = removeServerRules(server, name);
|
|
745
|
+
const warning = auditAfter(server, ctx.actor, settingAudit("gateway.upstream.remove", `connected server "${name}" removed from ${file.path} by ${ctx.actor}`, {
|
|
746
|
+
/* What was removed, so the log can restore it -- less its credentials. */
|
|
747
|
+
previous: redactUpstream(current),
|
|
748
|
+
rules_removed: cleanup.removed,
|
|
749
|
+
digest_before: result.previousDigest,
|
|
750
|
+
digest_after: result.digest
|
|
751
|
+
}), `"${name}" was removed`);
|
|
752
|
+
const note = [cleanup.note, warning].filter((p) => p !== null).join(" ");
|
|
753
|
+
return { ...writeResponse(options, id, result, note === "" ? null : note), removedRules: cleanup.removed };
|
|
754
|
+
}),
|
|
755
|
+
/**
|
|
756
|
+
* What a raw edit would do, before it is saved: whether it is valid, what
|
|
757
|
+
* it changes line by line, and what it loosens. Writes nothing.
|
|
758
|
+
*/
|
|
759
|
+
route("POST", "/api/v1/servers/:id/gateway/file/preview", (ctx) => {
|
|
760
|
+
const id = ctx.params["id"];
|
|
761
|
+
const body = parseBody(z.object({ text: z.string() }).strict(), ctx.body);
|
|
762
|
+
const loose = readGatewayFileOrBroken(expandPath(entryById(options, id).config_path));
|
|
763
|
+
if (isBroken(loose)) {
|
|
764
|
+
const diff = lineDiff(loose.text ?? "", body.text);
|
|
765
|
+
try {
|
|
766
|
+
parseGatewayText(loose.text === null ? body.text : restoreSecretsInText(body.text, readCurrent(loose.path)));
|
|
767
|
+
return { valid: true, error: null, diff, loosens: ["repairing a gateway.yaml that could not be loaded"], digest: loose.digest };
|
|
768
|
+
}
|
|
769
|
+
catch (err) {
|
|
770
|
+
if (!(err instanceof HttpError))
|
|
771
|
+
throw err;
|
|
772
|
+
return { valid: false, error: err.message, diff, loosens: [], digest: loose.digest };
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
const file = gatewayFileFor(options, id);
|
|
776
|
+
const diff = lineDiff(redactText(file.text), body.text);
|
|
777
|
+
try {
|
|
778
|
+
const after = parseGatewayText(restoreSecretsInText(body.text, file.text));
|
|
779
|
+
assertGuardsUnchanged(file.config, after);
|
|
780
|
+
return { valid: true, error: null, diff, loosens: gatewayLoosens(file.config, after), digest: file.digest };
|
|
781
|
+
}
|
|
782
|
+
catch (err) {
|
|
783
|
+
if (!(err instanceof HttpError))
|
|
784
|
+
throw err;
|
|
785
|
+
return { valid: false, error: err.message, diff, loosens: [], digest: file.digest };
|
|
786
|
+
}
|
|
787
|
+
}),
|
|
788
|
+
route("PUT", "/api/v1/servers/:id/gateway/file", (ctx) => {
|
|
789
|
+
const id = ctx.params["id"];
|
|
790
|
+
const body = parseBody(FileBody, ctx.body);
|
|
791
|
+
const loose = readGatewayFileOrBroken(expandPath(entryById(options, id).config_path));
|
|
792
|
+
if (isBroken(loose)) {
|
|
793
|
+
const repaired = repairGatewayText({
|
|
794
|
+
file: loose,
|
|
795
|
+
text: restoreSecretsInText(body.text, readCurrent(loose.path)),
|
|
796
|
+
expectedDigest: body.expectedDigest,
|
|
797
|
+
acknowledgedLoosens: body.acknowledged?.loosens === true
|
|
798
|
+
});
|
|
799
|
+
// The file loads now, so the record goes to the log it names.
|
|
800
|
+
const warning = auditAfter(serverById(options, id), ctx.actor, settingAudit("gateway.file-edit", `${loose.path} repaired via the console by ${ctx.actor} (it could not be loaded: ${loose.error})`, { repaired: true, digest_before: repaired.previousDigest, digest_after: repaired.digest }), "gateway.yaml was repaired");
|
|
801
|
+
return writeResponse(options, id, { before: repaired.after, after: repaired.after, previousDigest: repaired.previousDigest, digest: repaired.digest, loosens: ["repairing a gateway.yaml that could not be loaded"] }, warning);
|
|
802
|
+
}
|
|
803
|
+
const server = serverById(options, id);
|
|
804
|
+
const file = gatewayFileFor(options, id);
|
|
805
|
+
const text = restoreSecretsInText(body.text, file.text);
|
|
806
|
+
const result = commitGatewayText({
|
|
807
|
+
file,
|
|
808
|
+
text,
|
|
809
|
+
expectedDigest: body.expectedDigest,
|
|
810
|
+
acknowledgedLoosens: body.acknowledged?.loosens === true
|
|
811
|
+
});
|
|
812
|
+
const changedKeys = Object.keys({ ...result.before, ...result.after }).filter((k) => JSON.stringify(result.before[k]) !==
|
|
813
|
+
JSON.stringify(result.after[k]));
|
|
814
|
+
const warning = auditAfter(server, ctx.actor, settingAudit("gateway.file-edit", `${file.path} edited directly via the console by ${ctx.actor}` +
|
|
815
|
+
(changedKeys.length > 0 ? ` (changed: ${changedKeys.join(", ")})` : " (no setting changed)") +
|
|
816
|
+
(result.loosens.length > 0 ? `, confirmed as loosening: ${result.loosens.join("; ")}` : ""), {
|
|
817
|
+
changed: changedKeys,
|
|
818
|
+
loosens: result.loosens,
|
|
819
|
+
digest_before: result.previousDigest,
|
|
820
|
+
digest_after: result.digest
|
|
821
|
+
}), "gateway.yaml was written");
|
|
822
|
+
return writeResponse(options, id, result, warning);
|
|
823
|
+
}),
|
|
824
|
+
/* managed process */
|
|
825
|
+
route("GET", "/api/v1/servers/:id/process", (ctx) => {
|
|
826
|
+
entryById(options, ctx.params["id"]);
|
|
827
|
+
return processDto(options, ctx.params["id"]);
|
|
828
|
+
}),
|
|
829
|
+
route("POST", "/api/v1/servers/:id/process/start", async (ctx) => {
|
|
830
|
+
const id = ctx.params["id"];
|
|
831
|
+
const body = parseBody(StartBody, ctx.body);
|
|
832
|
+
const server = serverById(options, id);
|
|
833
|
+
if (processes.isActive(id))
|
|
834
|
+
throw conflict("this console is already running this gateway");
|
|
835
|
+
refuseIfExternal(options, id);
|
|
836
|
+
const http = {
|
|
837
|
+
port: body.http.port ?? 7878,
|
|
838
|
+
host: body.http.host ?? "127.0.0.1",
|
|
839
|
+
allowHosts: body.http.allowHosts ?? [],
|
|
840
|
+
allowOrigins: body.http.allowOrigins ?? [],
|
|
841
|
+
requireToken: body.http.requireToken ?? false
|
|
842
|
+
};
|
|
843
|
+
if (http.allowOrigins.length > 0 && !http.requireToken) {
|
|
844
|
+
throw unprocessable("a gateway that web pages may call must ask for a bearer token too, or any page on an allowed site " +
|
|
845
|
+
"could call its tools. Turn on the token, or remove the allowed origins.");
|
|
846
|
+
}
|
|
847
|
+
const loosens = startLoosens(http);
|
|
848
|
+
if (loosens.length > 0 && body.acknowledged?.loosens !== true) {
|
|
849
|
+
throw unprocessable(`this start lets more reach the gateway and needs confirming: ${loosens.join("; ")}`, {
|
|
850
|
+
needs: "loosens",
|
|
851
|
+
loosens
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
return startAndAudit(options, id, server, http, ctx.actor, false);
|
|
855
|
+
}),
|
|
856
|
+
route("POST", "/api/v1/servers/:id/process/stop", async (ctx) => {
|
|
857
|
+
parseBody(z.object({}).strict(), ctx.body);
|
|
858
|
+
const id = ctx.params["id"];
|
|
859
|
+
const server = serverById(options, id);
|
|
860
|
+
if (!processes.isActive(id))
|
|
861
|
+
return { ...processDto(options, id), changed: false };
|
|
862
|
+
const before = processes.view(id);
|
|
863
|
+
await processes.stop(id);
|
|
864
|
+
const warning = auditAfter(server, ctx.actor, settingAudit("gateway.process.stop", `gateway process ${before.pid} stopped from the console by ${ctx.actor}`, {
|
|
865
|
+
pid: before.pid,
|
|
866
|
+
started_at: before.startedAt
|
|
867
|
+
}), "the gateway was stopped");
|
|
868
|
+
return { ...processDto(options, id), changed: true, warning };
|
|
869
|
+
}),
|
|
870
|
+
route("POST", "/api/v1/servers/:id/process/restart", async (ctx) => {
|
|
871
|
+
parseBody(z.object({}).strict(), ctx.body);
|
|
872
|
+
const id = ctx.params["id"];
|
|
873
|
+
const server = serverById(options, id);
|
|
874
|
+
const before = processes.view(id);
|
|
875
|
+
if (!before.managed || before.http === null) {
|
|
876
|
+
throw unprocessable("this console has not started this gateway, so there is nothing to restart. Start it instead.");
|
|
877
|
+
}
|
|
878
|
+
const previous = processes.optionsFor(id);
|
|
879
|
+
// A live gateway on this config that is not ours -- usually an AI app's -- would get a second copy beside it.
|
|
880
|
+
refuseIfExternal(options, id);
|
|
881
|
+
if (processes.isActive(id)) {
|
|
882
|
+
await processes.stop(id);
|
|
883
|
+
auditAfter(server, ctx.actor, settingAudit("gateway.process.stop", `gateway process ${before.pid} stopped for a restart by ${ctx.actor}`, {
|
|
884
|
+
pid: before.pid,
|
|
885
|
+
restart: true
|
|
886
|
+
}), "the gateway was stopped");
|
|
887
|
+
}
|
|
888
|
+
return startAndAudit(options, id, server, previous, ctx.actor, true);
|
|
889
|
+
})
|
|
890
|
+
];
|
|
891
|
+
}
|
|
892
|
+
async function startAndAudit(options, id, server, http, actor, restart) {
|
|
893
|
+
const { view, token } = await processes.start(id, server.policyPath, http, restart);
|
|
894
|
+
const ok = view.state === "running" || view.state === "starting";
|
|
895
|
+
const warning = auditAfter(server, actor, {
|
|
896
|
+
...settingAudit("gateway.process.start", ok
|
|
897
|
+
? `gateway ${restart ? "restarted" : "started"} from the console by ${actor} as process ${view.pid}, on ` +
|
|
898
|
+
`${view.http?.url ?? `${http.host}:${http.port}`}` +
|
|
899
|
+
(http.requireToken ? ", requiring a bearer token" : ", with no bearer token (loopback only)")
|
|
900
|
+
: `the console tried to start the gateway for ${actor} and it exited (code ${view.exitCode})`, {
|
|
901
|
+
pid: view.pid,
|
|
902
|
+
host: http.host,
|
|
903
|
+
port: view.http?.port ?? http.port,
|
|
904
|
+
allow_hosts: http.allowHosts,
|
|
905
|
+
allow_origins: http.allowOrigins,
|
|
906
|
+
token_required: http.requireToken,
|
|
907
|
+
restart
|
|
908
|
+
}),
|
|
909
|
+
outcome: ok ? "completed" : "error"
|
|
910
|
+
}, "the gateway was started");
|
|
911
|
+
if (!ok) {
|
|
912
|
+
throw unprocessable(`the gateway exited while starting${view.exitCode !== null ? ` (exit code ${view.exitCode})` : ""}. ` +
|
|
913
|
+
`Its last lines: ${view.log.slice(-5).join(" | ") || "(none)"}`, { process: processDto(options, id) });
|
|
914
|
+
}
|
|
915
|
+
/*
|
|
916
|
+
* The token is in this response and nowhere else: not in the log, not in
|
|
917
|
+
* the audit record, not in `GET /process`. The page shows it once for the
|
|
918
|
+
* user to paste into their AI app.
|
|
919
|
+
*/
|
|
920
|
+
return { ...processDto(options, id), token, warning };
|
|
921
|
+
}
|