@app-vitals/agent-admin 1.116.0 → 1.118.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.
@@ -0,0 +1,516 @@
1
+ /**
2
+ * admin/src/tools-token-policy.ts
3
+ * The single route policy for tools-kind agent tokens.
4
+ *
5
+ * A tools-kind token (AdminScope.tokenKind === "tools") is handed to code that
6
+ * runs inside an agent session (hooks, scripts), so it must not be able to
7
+ * mint credentials or change what the agent runs. Every /agents/{id}/** route
8
+ * has an explicit allow|deny decision in TOOLS_TOKEN_POLICY, keyed by method
9
+ * and path template; one function (toolsTokenDecision) and two enforcement
10
+ * points consume it:
11
+ *
12
+ * 1. createAdminAuthMiddleware (DB-token path) — covers the runtime app and
13
+ * the admin app, and any extension route that authenticates with it.
14
+ * 2. createToolsTokenGuard — mounted by startAdmin on /agents/* ahead of
15
+ * extension API routes, which authenticate on their own and so never reach
16
+ * (1) with a scope. It resolves the token kind itself.
17
+ *
18
+ * Two content-level exceptions are driven from this module: the config bundle
19
+ * env is blanked (blankEnvForToolsToken) and a cron preCheck must be a
20
+ * `plugin:script` reference (assertToolsTokenPreCheck).
21
+ *
22
+ * Runtime-kind tokens, admin keys, platform keys and session callers are never
23
+ * touched. Routes with no declaration, including extension routes that do not
24
+ * declare a policy, default to allowed.
25
+ *
26
+ * Known limit: an extension route mounted outside /agents/* is not covered
27
+ * (tools tokens are per-agent and every agent route lives under /agents).
28
+ */
29
+
30
+ import type { MiddlewareHandler } from "hono";
31
+ import type { AdminApiKey, AdminScope } from "./api-auth.ts";
32
+ import { ForbiddenError } from "./errors.ts";
33
+
34
+ export type ToolsTokenDecision = "allow" | "deny";
35
+
36
+ export interface ToolsTokenPolicyRule {
37
+ method: string;
38
+ /** Path template; `{name}` matches exactly one segment. */
39
+ path: string;
40
+ decision: ToolsTokenDecision;
41
+ /** Also match any deeper path below `path`. */
42
+ subpaths?: boolean;
43
+ /** Why; recorded for the platform table, optional for extensions. */
44
+ note?: string;
45
+ }
46
+
47
+ const A = "allow" as const;
48
+ const D = "deny" as const;
49
+ const ADMIN_ONLY =
50
+ "already admin-only: agent bearers are rejected by the handler";
51
+
52
+ /**
53
+ * Platform routes. The policy test walks admin/openapi.platform.json and
54
+ * requires an entry here for every /agents/** method+path, and no stale ones.
55
+ */
56
+ export const TOOLS_TOKEN_POLICY: readonly ToolsTokenPolicyRule[] = [
57
+ { method: "POST", path: "/agents/reconcile", decision: D, note: ADMIN_ONLY },
58
+ {
59
+ method: "POST",
60
+ path: "/agents/federation/strip-credentials",
61
+ decision: D,
62
+ note: ADMIN_ONLY,
63
+ },
64
+ { method: "GET", path: "/agents", decision: D, note: ADMIN_ONLY },
65
+ { method: "POST", path: "/agents", decision: D, note: ADMIN_ONLY },
66
+ { method: "GET", path: "/agents/{id}", decision: D, note: ADMIN_ONLY },
67
+ { method: "PATCH", path: "/agents/{id}", decision: D, note: ADMIN_ONLY },
68
+ { method: "DELETE", path: "/agents/{id}", decision: D, note: ADMIN_ONLY },
69
+ {
70
+ method: "POST",
71
+ path: "/agents/{id}/provision",
72
+ decision: D,
73
+ note: ADMIN_ONLY,
74
+ },
75
+ { method: "POST", path: "/agents/{id}/repos", decision: D, note: ADMIN_ONLY },
76
+ {
77
+ method: "DELETE",
78
+ path: "/agents/{id}/repos/{owner}/{name}",
79
+ decision: D,
80
+ note: ADMIN_ONLY,
81
+ },
82
+ {
83
+ method: "GET",
84
+ path: "/agents/{id}/repos/{owner}/{name}/removal-preview",
85
+ decision: D,
86
+ note: ADMIN_ONLY,
87
+ },
88
+ // Credentials and what the agent runs: denied for tools tokens.
89
+ {
90
+ method: "POST",
91
+ path: "/agents/{id}/tokens",
92
+ decision: D,
93
+ subpaths: true,
94
+ note: "token minting",
95
+ },
96
+ {
97
+ method: "GET",
98
+ path: "/agents/{id}/tokens",
99
+ decision: D,
100
+ subpaths: true,
101
+ note: "token listing",
102
+ },
103
+ {
104
+ method: "DELETE",
105
+ path: "/agents/{id}/tokens/{tokenId}",
106
+ decision: D,
107
+ subpaths: true,
108
+ note: "token revocation",
109
+ },
110
+ {
111
+ method: "POST",
112
+ path: "/agents/{id}/envs",
113
+ decision: D,
114
+ subpaths: true,
115
+ note: "env write",
116
+ },
117
+ {
118
+ method: "GET",
119
+ path: "/agents/{id}/envs",
120
+ decision: A,
121
+ note: "masked read",
122
+ },
123
+ {
124
+ method: "PATCH",
125
+ path: "/agents/{id}/envs",
126
+ decision: D,
127
+ subpaths: true,
128
+ note: "env write",
129
+ },
130
+ {
131
+ method: "DELETE",
132
+ path: "/agents/{id}/envs/{key}",
133
+ decision: D,
134
+ subpaths: true,
135
+ note: "env write",
136
+ },
137
+ {
138
+ method: "POST",
139
+ path: "/agents/{id}/tools",
140
+ decision: D,
141
+ subpaths: true,
142
+ note: "allowed-tools write",
143
+ },
144
+ { method: "GET", path: "/agents/{id}/tools", decision: A, note: "read" },
145
+ {
146
+ method: "PATCH",
147
+ path: "/agents/{id}/tools/{toolId}",
148
+ decision: D,
149
+ subpaths: true,
150
+ note: "allowed-tools write",
151
+ },
152
+ {
153
+ method: "DELETE",
154
+ path: "/agents/{id}/tools/{toolId}",
155
+ decision: D,
156
+ subpaths: true,
157
+ note: "allowed-tools write",
158
+ },
159
+ {
160
+ method: "POST",
161
+ path: "/agents/{id}/plugins",
162
+ decision: D,
163
+ subpaths: true,
164
+ note: "plugin write",
165
+ },
166
+ { method: "GET", path: "/agents/{id}/plugins", decision: A, note: "read" },
167
+ {
168
+ method: "PATCH",
169
+ path: "/agents/{id}/plugins",
170
+ decision: D,
171
+ subpaths: true,
172
+ note: "plugin write",
173
+ },
174
+ {
175
+ method: "DELETE",
176
+ path: "/agents/{id}/plugins",
177
+ decision: D,
178
+ subpaths: true,
179
+ note: "plugin write",
180
+ },
181
+ {
182
+ method: "GET",
183
+ path: "/agents/{id}/marketplaces",
184
+ decision: A,
185
+ note: "read",
186
+ },
187
+ {
188
+ method: "POST",
189
+ path: "/agents/{id}/marketplaces",
190
+ decision: D,
191
+ subpaths: true,
192
+ note: "marketplace write",
193
+ },
194
+ {
195
+ method: "DELETE",
196
+ path: "/agents/{id}/marketplaces/{marketplaceId}",
197
+ decision: D,
198
+ subpaths: true,
199
+ note: "marketplace write",
200
+ },
201
+ // Crons: reads allowed; create/PATCH allowed with the preCheck content rule.
202
+ {
203
+ method: "POST",
204
+ path: "/agents/{id}/crons",
205
+ decision: A,
206
+ note: "allowed; preCheck must be plugin:script (assertToolsTokenPreCheck)",
207
+ },
208
+ { method: "GET", path: "/agents/{id}/crons", decision: A, note: "read" },
209
+ {
210
+ method: "POST",
211
+ path: "/agents/{id}/crons/reconcile",
212
+ decision: A,
213
+ note: "system cron reconcile, no caller-supplied content",
214
+ },
215
+ {
216
+ method: "PATCH",
217
+ path: "/agents/{id}/crons/{cronId}",
218
+ decision: A,
219
+ note: "allowed; preCheck must be plugin:script (assertToolsTokenPreCheck)",
220
+ },
221
+ {
222
+ method: "DELETE",
223
+ path: "/agents/{id}/crons/{cronId}",
224
+ decision: A,
225
+ note: "not a credential or code-execution change",
226
+ },
227
+ {
228
+ method: "GET",
229
+ path: "/agents/{id}/crons/summary",
230
+ decision: A,
231
+ note: "read",
232
+ },
233
+ {
234
+ method: "POST",
235
+ path: "/agents/{id}/crons/{cronId}/runs",
236
+ decision: A,
237
+ note: "run reporting",
238
+ },
239
+ {
240
+ method: "GET",
241
+ path: "/agents/{id}/crons/{cronId}/runs",
242
+ decision: A,
243
+ note: "read",
244
+ },
245
+ {
246
+ method: "PATCH",
247
+ path: "/agents/{id}/crons/{cronId}/runs/{runId}",
248
+ decision: A,
249
+ note: "run reporting",
250
+ },
251
+ {
252
+ method: "POST",
253
+ path: "/agents/{id}/crons/{cronId}/run-now",
254
+ decision: A,
255
+ note: "runs an existing cron; no caller-supplied content",
256
+ },
257
+ {
258
+ method: "GET",
259
+ path: "/agents/all/cron-runs/stats",
260
+ decision: D,
261
+ note: ADMIN_ONLY,
262
+ },
263
+ {
264
+ method: "GET",
265
+ path: "/agents/all/cron-runs/outcomes",
266
+ decision: D,
267
+ note: ADMIN_ONLY,
268
+ },
269
+ {
270
+ method: "GET",
271
+ path: "/agents/{id}/cron-runs/stats",
272
+ decision: A,
273
+ note: "read",
274
+ },
275
+ {
276
+ method: "GET",
277
+ path: "/agents/{id}/cron-runs/outcomes",
278
+ decision: A,
279
+ note: "read",
280
+ },
281
+ // Template management is admin/member gated in the handlers.
282
+ {
283
+ method: "POST",
284
+ path: "/agents/{id}/template/reconcile",
285
+ decision: A,
286
+ note: "agent boot calls this; no caller-supplied content",
287
+ },
288
+ {
289
+ method: "POST",
290
+ path: "/agents/{id}/template/detach",
291
+ decision: D,
292
+ note: ADMIN_ONLY,
293
+ },
294
+ {
295
+ method: "POST",
296
+ path: "/agents/{id}/template/reattach",
297
+ decision: D,
298
+ note: ADMIN_ONLY,
299
+ },
300
+ {
301
+ method: "POST",
302
+ path: "/agents/{id}/template/reset",
303
+ decision: D,
304
+ note: ADMIN_ONLY,
305
+ },
306
+ {
307
+ method: "POST",
308
+ path: "/agents/{id}/chat-credentials",
309
+ decision: D,
310
+ subpaths: true,
311
+ note: ADMIN_ONLY,
312
+ },
313
+ {
314
+ method: "GET",
315
+ path: "/agents/{id}/chat-credentials",
316
+ decision: D,
317
+ subpaths: true,
318
+ note: ADMIN_ONLY,
319
+ },
320
+ {
321
+ method: "DELETE",
322
+ path: "/agents/{id}/chat-credentials/{tokenId}",
323
+ decision: D,
324
+ subpaths: true,
325
+ note: ADMIN_ONLY,
326
+ },
327
+ {
328
+ method: "POST",
329
+ path: "/agents/{id}/ask",
330
+ decision: A,
331
+ note: "handler binds `from` to the caller's agent",
332
+ },
333
+ { method: "GET", path: "/agents/{id}/asks", decision: A, note: "read" },
334
+ {
335
+ method: "GET",
336
+ path: "/agents/chat-tokens/daily/stats",
337
+ decision: D,
338
+ note: ADMIN_ONLY,
339
+ },
340
+ {
341
+ method: "GET",
342
+ path: "/agents/{id}/chat-tokens/daily/stats",
343
+ decision: A,
344
+ note: "read",
345
+ },
346
+ {
347
+ method: "POST",
348
+ path: "/agents/{id}/chat-tokens/daily",
349
+ decision: A,
350
+ note: "usage reporting",
351
+ },
352
+ {
353
+ method: "PUT",
354
+ path: "/agents/{id}/github-installations",
355
+ decision: A,
356
+ note: "runtime snapshot report",
357
+ },
358
+ {
359
+ method: "GET",
360
+ path: "/agents/{id}/github-installations",
361
+ decision: A,
362
+ note: "read",
363
+ },
364
+ {
365
+ method: "PUT",
366
+ path: "/agents/{id}/baked-marketplaces",
367
+ decision: A,
368
+ note: "runtime report; handler requires the agent's own key",
369
+ },
370
+ {
371
+ method: "GET",
372
+ path: "/agents/{id}/github-installation/repos",
373
+ decision: D,
374
+ note: ADMIN_ONLY,
375
+ },
376
+ {
377
+ method: "GET",
378
+ path: "/agents/{id}/github-sync/preview",
379
+ decision: D,
380
+ note: ADMIN_ONLY,
381
+ },
382
+ {
383
+ method: "POST",
384
+ path: "/agents/{id}/github-sync/apply",
385
+ decision: D,
386
+ note: ADMIN_ONLY,
387
+ },
388
+ {
389
+ method: "GET",
390
+ path: "/agents/{id}/config",
391
+ decision: A,
392
+ note: "allowed with env blanked (blankEnvForToolsToken)",
393
+ },
394
+ ];
395
+
396
+ // ─── Matching ─────────────────────────────────────────────────────────────────
397
+
398
+ /** Decode, collapse repeated slashes and drop a trailing slash. */
399
+ export function normalizePolicyPath(path: string): string {
400
+ let p = path;
401
+ try {
402
+ p = decodeURIComponent(p);
403
+ } catch {
404
+ // keep the raw path
405
+ }
406
+ p = p.replace(/\/{2,}/g, "/");
407
+ return p.length > 1 && p.endsWith("/") ? p.slice(0, -1) : p;
408
+ }
409
+
410
+ export function ruleMatches(
411
+ rule: ToolsTokenPolicyRule,
412
+ method: string,
413
+ path: string,
414
+ ): boolean {
415
+ if (rule.method !== method.toUpperCase()) return false;
416
+ const body = rule.path
417
+ .split(/(\{[^}]+\})/)
418
+ .map((part) =>
419
+ /^\{[^}]+\}$/.test(part)
420
+ ? "[^/]+"
421
+ : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
422
+ )
423
+ .join("");
424
+ const re = new RegExp(`^${body}${rule.subpaths ? "(?:/.*)?" : ""}$`);
425
+ return re.test(normalizePolicyPath(path));
426
+ }
427
+
428
+ /**
429
+ * The decision for a tools-kind caller on method+path. Any matching deny
430
+ * (platform table or extension rule) wins; otherwise allow, which is also the
431
+ * default for undeclared routes.
432
+ */
433
+ export function toolsTokenDecision(
434
+ method: string,
435
+ path: string,
436
+ extensionRules: readonly ToolsTokenPolicyRule[] = [],
437
+ ): ToolsTokenDecision {
438
+ const denied = [...TOOLS_TOKEN_POLICY, ...extensionRules].some(
439
+ (r) => r.decision === D && ruleMatches(r, method, path),
440
+ );
441
+ return denied ? D : A;
442
+ }
443
+
444
+ export function isToolsKindScope(scope: AdminScope | undefined): boolean {
445
+ return scope?.kind === "agent" && scope.tokenKind === "tools";
446
+ }
447
+
448
+ // ─── Content-level exceptions ─────────────────────────────────────────────────
449
+
450
+ // Each part must start alphanumeric so `.`/`..` can't traverse out of the
451
+ // plugin dir when the runtime joins `<cache>/<plugin>/scripts/<script>`.
452
+ const PRECHECK_PART = "[A-Za-z0-9][A-Za-z0-9_.-]*";
453
+ const TOOLS_PRECHECK_RE = new RegExp(`^${PRECHECK_PART}:${PRECHECK_PART}$`);
454
+
455
+ /** True for a `plugin:script` reference (no path forms, no spaces or slashes). */
456
+ export function isPluginScriptPreCheck(preCheck: string): boolean {
457
+ return TOOLS_PRECHECK_RE.test(preCheck);
458
+ }
459
+
460
+ /**
461
+ * Throws 403 when a tools-kind caller supplies a preCheck that is not
462
+ * `plugin:script`. A null/undefined preCheck (absent or clearing) is fine.
463
+ */
464
+ export function assertToolsTokenPreCheck(
465
+ scope: AdminScope | undefined,
466
+ preCheck: string | null | undefined,
467
+ ): void {
468
+ if (!isToolsKindScope(scope) || preCheck == null) return;
469
+ if (!isPluginScriptPreCheck(preCheck)) {
470
+ throw new ForbiddenError(
471
+ "Tools tokens may only set a preCheck of the form plugin:script",
472
+ );
473
+ }
474
+ }
475
+
476
+ /** Config bundle env for the caller: `{}` for tools-kind, unchanged otherwise. */
477
+ export function blankEnvForToolsToken(
478
+ scope: AdminScope | undefined,
479
+ env: Record<string, string>,
480
+ ): Record<string, string> {
481
+ return isToolsKindScope(scope) ? {} : env;
482
+ }
483
+
484
+ // ─── Enforcement ──────────────────────────────────────────────────────────────
485
+
486
+ /**
487
+ * Guard for routes that authenticate on their own (extension API routes). It
488
+ * resolves a bearer's kind itself and applies the policy to tools-kind tokens;
489
+ * everything else (no bearer, env keys, runtime tokens, invalid tokens) passes
490
+ * through for the route's own auth to decide.
491
+ */
492
+ export function createToolsTokenGuard(deps: {
493
+ agentTokenService: {
494
+ validate(raw: string): Promise<{ agentId: string; kind?: string } | null>;
495
+ };
496
+ adminApiKeys?: Map<string, AdminApiKey>;
497
+ extensionRules?: readonly ToolsTokenPolicyRule[];
498
+ }): MiddlewareHandler {
499
+ return async (c, next) => {
500
+ const header = c.req.header("Authorization");
501
+ if (header?.startsWith("Bearer ")) {
502
+ const raw = header.slice(7);
503
+ if (!deps.adminApiKeys?.has(raw)) {
504
+ const result = await deps.agentTokenService.validate(raw);
505
+ if (
506
+ result?.kind === "tools" &&
507
+ toolsTokenDecision(c.req.method, c.req.path, deps.extensionRules) ===
508
+ D
509
+ ) {
510
+ return c.json({ error: "Forbidden" }, 403);
511
+ }
512
+ }
513
+ }
514
+ return next();
515
+ };
516
+ }