@app-vitals/agent-admin 1.117.0 → 1.119.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.117.0",
3
+ "version": "1.119.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@anthropic-ai/sdk": "0.137.0",
47
- "@app-vitals/agent-lib": "1.117.0",
47
+ "@app-vitals/agent-lib": "1.119.0",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -142,6 +142,7 @@ import { runStartupPolicyReconcile } from "./startup-policy-reconcile.ts";
142
142
  import { runTemplateSeed } from "./template-seed.ts";
143
143
  import { createTimezoneResolver } from "./timezone-resolver.ts";
144
144
  import { makeStrictTokenCrypto, makeTokenCrypto } from "./token-crypto.ts";
145
+ import { createToolsTokenGuard } from "./tools-token-policy.ts";
145
146
  import {
146
147
  resolveTrialExpirySweepIntervalMs,
147
148
  TrialExpirySweeper,
@@ -553,6 +554,7 @@ export async function startAdmin(
553
554
  : {}),
554
555
  sessionSecret,
555
556
  adminApiKeys,
557
+ toolsTokenPolicy: resolvedExtensions.toolsTokenPolicy,
556
558
  agentTokenService,
557
559
  anthropicFederationEnabled,
558
560
  repoAccessCheckEnabled: repoAccessConfig.enabled,
@@ -589,6 +591,7 @@ export async function startAdmin(
589
591
  toolsTokenService,
590
592
  sessionSecret,
591
593
  adminApiKeys,
594
+ toolsTokenPolicy: resolvedExtensions.toolsTokenPolicy,
592
595
  sentryClient: process.env.SENTRY_DSN ? Sentry : undefined,
593
596
  pool: adminPool,
594
597
  selfServe,
@@ -667,6 +670,17 @@ export async function startAdmin(
667
670
 
668
671
  // 3c. Extension API routes — after every platform API, before the admin UI
669
672
  // (same no-shadowing rule as the admin CRUD API above).
673
+ // Extension routes authenticate on their own, so the tools-token guard
674
+ // (registered after the platform APIs, so it only sees fall-through
675
+ // requests) applies the route policy to tools-kind bearers here.
676
+ root.use(
677
+ "/agents/*",
678
+ createToolsTokenGuard({
679
+ agentTokenService,
680
+ adminApiKeys,
681
+ extensionRules: resolvedExtensions.toolsTokenPolicy,
682
+ }),
683
+ );
670
684
  mountRouteContributions(root, resolvedExtensions.apiRoutes);
671
685
 
672
686
  // 4. Admin UI — /admin/* — session JWT
@@ -81,6 +81,7 @@ import type {
81
81
  SpecialtyOption,
82
82
  SpecialtyTypeResolver,
83
83
  } from "./specialty-types.ts";
84
+ import type { ToolsTokenPolicyRule } from "./tools-token-policy.ts";
84
85
 
85
86
  /** The platform services an extension may build on. */
86
87
  export interface AdminPlatformServices {
@@ -239,6 +240,14 @@ export interface AdminExtension {
239
240
  backgroundPasses?(ctx: AdminExtensionContext): AdminBackgroundPass[];
240
241
  settingsNavItems?(ctx: AdminExtensionContext): SettingsNavContribution[];
241
242
  openApi?(): AdminOpenApiContribution;
243
+ /**
244
+ * Allow/deny decisions for tools-kind agent tokens on routes this extension
245
+ * adds, keyed by method and `{param}` path template (`subpaths` also covers
246
+ * deeper paths). Optional and additive. A route with no declaration is
247
+ * allowed; a platform deny cannot be lifted from here. See
248
+ * tools-token-policy.ts.
249
+ */
250
+ toolsTokenPolicy?(): ReadonlyArray<ToolsTokenPolicyRule>;
242
251
  }
243
252
 
244
253
  /** The order resolveAdminExtensions calls the context hooks in. */
@@ -261,6 +270,8 @@ export interface ResolvedAdminExtensions {
261
270
  agentDetailCards: AgentDetailCardSlot[];
262
271
  backgroundPasses: AdminBackgroundPass[];
263
272
  settingsNavItems: SettingsNavContribution[];
273
+ /** Every extension's toolsTokenPolicy() rules, concatenated in order. */
274
+ toolsTokenPolicy?: ToolsTokenPolicyRule[];
264
275
  }
265
276
 
266
277
  /**
@@ -308,6 +319,9 @@ export function resolveAdminExtensions(
308
319
  agentDetailCards,
309
320
  backgroundPasses,
310
321
  settingsNavItems,
322
+ toolsTokenPolicy: extensions.flatMap((ext) => [
323
+ ...(ext.toolsTokenPolicy?.() ?? []),
324
+ ]),
311
325
  };
312
326
  }
313
327
 
@@ -54,6 +54,7 @@ describe("resolveAdminExtensions", () => {
54
54
  agentDetailCards: [],
55
55
  backgroundPasses: [],
56
56
  settingsNavItems: [],
57
+ toolsTokenPolicy: [],
57
58
  });
58
59
  });
59
60
 
@@ -15,6 +15,7 @@ import { readFileSync } from "node:fs";
15
15
  import { join } from "node:path";
16
16
  import {
17
17
  CHILD_ALLOWED_SECRET_ENV_VARS,
18
+ MAPPED_ENV_VARS,
18
19
  RUNTIME_ONLY_ENV_VARS,
19
20
  } from "@app-vitals/agent-lib/child-env";
20
21
  import {
@@ -53,6 +54,7 @@ const NON_SECRET_SYSTEM_ENV_VARS: readonly string[] = [
53
54
  const classified = new Set<string>([
54
55
  ...RUNTIME_ONLY_ENV_VARS,
55
56
  ...CHILD_ALLOWED_SECRET_ENV_VARS,
57
+ ...MAPPED_ENV_VARS,
56
58
  ...NON_SECRET_SYSTEM_ENV_VARS,
57
59
  ]);
58
60
 
@@ -142,6 +144,7 @@ describe("system-provisioned agent env classification", () => {
142
144
  const secretish = new Set<string>([
143
145
  ...RUNTIME_ONLY_ENV_VARS,
144
146
  ...CHILD_ALLOWED_SECRET_ENV_VARS,
147
+ ...MAPPED_ENV_VARS,
145
148
  ]);
146
149
  for (const name of NON_SECRET_SYSTEM_ENV_VARS)
147
150
  expect(secretish.has(name)).toBe(false);
package/src/agents-api.ts CHANGED
@@ -182,6 +182,10 @@ import type { SelfServeConfig } from "./self-serve-config.ts";
182
182
  import type { SpecialtyDefaultsResolver } from "./specialty-defaults.ts";
183
183
  import type { SpecialtyTypeResolver } from "./specialty-types.ts";
184
184
  import { managedReconcileTargets } from "./startup-policy-reconcile.ts";
185
+ import {
186
+ assertToolsTokenPreCheck,
187
+ type ToolsTokenPolicyRule,
188
+ } from "./tools-token-policy.ts";
185
189
 
186
190
  // ─── Types ────────────────────────────────────────────────────────────────────
187
191
 
@@ -339,6 +343,8 @@ export interface AdminDeps {
339
343
  sessionSecret: string;
340
344
  /** Parsed SHIPWRIGHT_ADMIN_API_KEYS — optional; absent means env key auth is disabled. */
341
345
  adminApiKeys?: Map<string, AdminApiKey>;
346
+ /** Extension-declared tools-token rules (tools-token-policy.ts). */
347
+ toolsTokenPolicy?: readonly ToolsTokenPolicyRule[];
342
348
  /**
343
349
  * Optional Sentry client for reporting unhandled errors. Undefined means
344
350
  * Sentry is not initialized (SENTRY_DSN unset) — onError simply skips the
@@ -2150,6 +2156,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2150
2156
  callerScopeResolver,
2151
2157
  getAgentAccountId: async (id) =>
2152
2158
  (await agentService.getDetail(id))?.accountId,
2159
+ toolsTokenPolicy: deps.toolsTokenPolicy,
2153
2160
  });
2154
2161
 
2155
2162
  // Platform readers/operators (platform.read / platform.ops admin keys): the
@@ -2814,6 +2821,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2814
2821
  app.openapi(createCronRoute, async (c) => {
2815
2822
  const { id: agentId } = c.req.valid("param");
2816
2823
  const body = c.req.valid("json");
2824
+ assertToolsTokenPreCheck(c.get("scope"), body.preCheck);
2817
2825
  const cron = await agentCronJobService.create(agentId, body);
2818
2826
  return c.json({ cron: serializeCron(cron) }, 201);
2819
2827
  });
@@ -2889,6 +2897,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2889
2897
  app.openapi(patchCronRoute, async (c) => {
2890
2898
  const { id: agentId, cronId } = c.req.valid("param");
2891
2899
  const body = c.req.valid("json");
2900
+ assertToolsTokenPreCheck(c.get("scope"), body.preCheck);
2892
2901
 
2893
2902
  const hasSchedule = body.schedule != null;
2894
2903
  const hasPrompt = body.prompt != null;
package/src/api-auth.ts CHANGED
@@ -21,6 +21,10 @@ import {
21
21
  scopeIncludesAgent,
22
22
  } from "./caller-scope.ts";
23
23
  import { ForbiddenError } from "./errors.ts";
24
+ import {
25
+ type ToolsTokenPolicyRule,
26
+ toolsTokenDecision,
27
+ } from "./tools-token-policy.ts";
24
28
 
25
29
  // ─── Types ────────────────────────────────────────────────────────────────────
26
30
 
@@ -260,6 +264,11 @@ export function createAdminAuthMiddleware(deps: {
260
264
  * that are not admins never pass the management check (fail closed).
261
265
  */
262
266
  getAgentAccountId?: (agentId: string) => Promise<string | null | undefined>;
267
+ /**
268
+ * Extension-declared allow/deny rules for tools-kind tokens, merged with the
269
+ * platform table (tools-token-policy.ts). Undeclared routes are allowed.
270
+ */
271
+ toolsTokenPolicy?: readonly ToolsTokenPolicyRule[];
263
272
  }): MiddlewareHandler<AdminAuthEnv> {
264
273
  const { sessionSecret, agentTokenService, adminApiKeys, agentMemberService } =
265
274
  deps;
@@ -373,6 +382,15 @@ export function createAdminAuthMiddleware(deps: {
373
382
  ) {
374
383
  return c.json({ error: "Forbidden" }, 403);
375
384
  }
385
+ // Tools-kind tokens are restricted by one route policy (see
386
+ // tools-token-policy.ts); runtime-kind tokens are unaffected.
387
+ if (
388
+ result.kind === "tools" &&
389
+ toolsTokenDecision(c.req.method, c.req.path, deps.toolsTokenPolicy) ===
390
+ "deny"
391
+ ) {
392
+ return c.json({ error: "Forbidden" }, 403);
393
+ }
376
394
  // DB token path — per-agent bearer, not an admin.
377
395
  c.set("isAdmin", false);
378
396
  c.set("caller", { name: result.agentId, scope: result.agentId });
package/src/api.ts CHANGED
@@ -24,7 +24,11 @@ import type { AgentCronJob } from "./agent-cron-jobs.ts";
24
24
  import type { AgentEnvBundle } from "./agent-envs.ts";
25
25
  import type { AgentTokenService } from "./agent-tokens.ts";
26
26
  import { anthropicCredentialKeysIn } from "./anthropic-credential-guard.ts";
27
- import { type AdminApiKey, createAdminAuthMiddleware } from "./api-auth.ts";
27
+ import {
28
+ type AdminApiKey,
29
+ type AdminScope,
30
+ createAdminAuthMiddleware,
31
+ } from "./api-auth.ts";
28
32
  import {
29
33
  AGENT_PHASES,
30
34
  AgentConfigResponseSchema,
@@ -32,6 +36,10 @@ import {
32
36
  AgentIdParamSchema,
33
37
  RuntimeErrorSchema,
34
38
  } from "./openapi-schemas.ts";
39
+ import {
40
+ blankEnvForToolsToken,
41
+ type ToolsTokenPolicyRule,
42
+ } from "./tools-token-policy.ts";
35
43
 
36
44
  // ─── Types ────────────────────────────────────────────────────────────────────
37
45
 
@@ -200,6 +208,8 @@ export interface AgentRuntimeDeps {
200
208
  sessionSecret: string;
201
209
  /** Parsed SHIPWRIGHT_ADMIN_API_KEYS — optional; absent means env key auth is disabled. */
202
210
  adminApiKeys?: Map<string, AdminApiKey>;
211
+ /** Extension-declared tools-token rules (tools-token-policy.ts). */
212
+ toolsTokenPolicy?: readonly ToolsTokenPolicyRule[];
203
213
  /** Token service for per-agent bearer token validation. */
204
214
  agentTokenService: Pick<AgentTokenService, "validate">;
205
215
  /** WIF-2.1: Anthropic federation is enabled; defaults to false. */
@@ -293,6 +303,7 @@ export function createAgentRuntimeApp(deps: AgentRuntimeDeps): OpenAPIHono {
293
303
  sessionSecret: deps.sessionSecret,
294
304
  adminApiKeys: deps.adminApiKeys,
295
305
  agentTokenService: deps.agentTokenService,
306
+ toolsTokenPolicy: deps.toolsTokenPolicy,
296
307
  });
297
308
 
298
309
  // ─── GET /:id/config ─────────────────────────────────────────────────────
@@ -321,7 +332,12 @@ export function createAgentRuntimeApp(deps: AgentRuntimeDeps): OpenAPIHono {
321
332
  // WIF-2.1: with federation enabled, a non-self-hosted agent must never be
322
333
  // handed Anthropic credentials, even ones already stored in its bundle
323
334
  // (the agent re-reads this endpoint every 60s). Log names only.
324
- let env = bundle?.env ?? {};
335
+ // Tools-kind tokens never receive the env values (the auth middleware has
336
+ // set the scope; the app has no typed Env, hence the cast).
337
+ const scope = (
338
+ c as unknown as { get(k: "scope"): AdminScope | undefined }
339
+ ).get("scope");
340
+ let env = blankEnvForToolsToken(scope, bundle?.env ?? {});
325
341
  if (deps.anthropicFederationEnabled && !agent.selfHosted) {
326
342
  const blocked = anthropicCredentialKeysIn(Object.keys(env));
327
343
  if (blocked.length > 0) {
@@ -0,0 +1,220 @@
1
+ /**
2
+ * admin/src/tools-token-policy.integration.test.ts
3
+ * Tools-kind agent tokens against the real admin + runtime apps and a real
4
+ * PostgreSQL DB (tokens minted through AgentTokenService, validated by the
5
+ * auth middleware). Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
6
+ */
7
+
8
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
9
+ import type { PrismaClient } from "../prisma/client/client.ts";
10
+ import { AgentChatTokenService } from "./agent-chat-tokens.ts";
11
+ import { AgentCronJobService } from "./agent-cron-jobs.ts";
12
+ import { AgentCronRunStatsService } from "./agent-cron-run-stats.ts";
13
+ import { AgentCronRunService } from "./agent-cron-runs.ts";
14
+ import { AgentEnvService } from "./agent-envs.ts";
15
+ import { AgentGitHubInstallationsService } from "./agent-github-installations.ts";
16
+ import { AgentMemberService } from "./agent-members.ts";
17
+ import { AgentPluginService } from "./agent-plugins.ts";
18
+ import { NoopAgentProvisioner } from "./agent-provisioner.ts";
19
+ import { AgentTokenService } from "./agent-tokens.ts";
20
+ import { AgentToolService } from "./agent-tools.ts";
21
+ import { AgentService } from "./agents.ts";
22
+ import { type AdminDeps, createAdminApp } from "./agents-api.ts";
23
+ import { createAgentRuntimeApp } from "./api.ts";
24
+ import { NoopChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
25
+ import { createAdminPrismaClient } from "./prisma-client.ts";
26
+ import { makeTokenCrypto } from "./token-crypto.ts";
27
+
28
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
29
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
30
+
31
+ const SESSION_SECRET = "test-admin-session-secret-32-bytes!";
32
+ const REAL_KEY =
33
+ "0000000000000000000000000000000000000000000000000000000000000001";
34
+
35
+ describeOrSkip("tools-kind token policy (integration)", () => {
36
+ let prisma: PrismaClient;
37
+ let agentId: string;
38
+ let toolsToken: string;
39
+ let runtimeToken: string;
40
+ let root: {
41
+ request: (path: string, init?: RequestInit) => Response | Promise<Response>;
42
+ };
43
+
44
+ beforeEach(async () => {
45
+ prisma = createAdminPrismaClient(TEST_DB as string);
46
+ for (const model of [
47
+ "agentWorkQueueSnapshot",
48
+ "agentPlugin",
49
+ "agentPhaseMethodology",
50
+ "agentToken",
51
+ "agentCronJob",
52
+ "agentTool",
53
+ "agentEnv",
54
+ "agentMember",
55
+ "agent",
56
+ ] as const) {
57
+ await (prisma[model] as { deleteMany(): Promise<unknown> }).deleteMany();
58
+ }
59
+ agentId = (await prisma.agent.create({ data: { name: "Policy Agent" } }))
60
+ .id;
61
+
62
+ const saved = process.env.SHIPWRIGHT_ENCRYPTION_KEY;
63
+ process.env.SHIPWRIGHT_ENCRYPTION_KEY = REAL_KEY;
64
+ const crypto = makeTokenCrypto();
65
+ if (saved === undefined) delete process.env.SHIPWRIGHT_ENCRYPTION_KEY;
66
+ else process.env.SHIPWRIGHT_ENCRYPTION_KEY = saved;
67
+
68
+ const agentTokenService = new AgentTokenService(prisma);
69
+ toolsToken = (await agentTokenService.create(agentId, "t", "tools"))
70
+ .rawToken;
71
+ runtimeToken = (await agentTokenService.create(agentId, "r", "runtime"))
72
+ .rawToken;
73
+
74
+ const agentService = new AgentService(prisma);
75
+ const agentEnvService = new AgentEnvService(prisma, crypto);
76
+ const agentPluginService = new AgentPluginService(prisma);
77
+ const agentCronJobService = new AgentCronJobService(prisma);
78
+ const admin = createAdminApp({
79
+ agentService,
80
+ agentEnvService,
81
+ agentCronJobService,
82
+ agentCronRunService: new AgentCronRunService(prisma),
83
+ agentCronRunStatsService: new AgentCronRunStatsService(prisma),
84
+ agentToolService: new AgentToolService(prisma),
85
+ agentTokenService,
86
+ agentPluginService,
87
+ agentMemberService: new AgentMemberService(prisma),
88
+ agentChatTokenService: new AgentChatTokenService(prisma),
89
+ agentGitHubInstallationsService: new AgentGitHubInstallationsService(
90
+ prisma,
91
+ ),
92
+ prisma,
93
+ provisioner: new NoopAgentProvisioner(),
94
+ serviceIntegrations: [],
95
+ chatService: new NoopChatServiceProvisioningClient(),
96
+ slack: { deleteApp: async () => {} },
97
+ decrypt: (v: string) => crypto.decrypt(v),
98
+ sessionSecret: SESSION_SECRET,
99
+ } as unknown as AdminDeps);
100
+ const runtime = createAgentRuntimeApp({
101
+ agentEnvService,
102
+ agentCronJobService,
103
+ agentService,
104
+ agentPluginService,
105
+ agentTokenService,
106
+ sessionSecret: SESSION_SECRET,
107
+ } as unknown as Parameters<typeof createAgentRuntimeApp>[0]);
108
+ // Same mount order as platform-routes.ts: runtime under /agents, then admin.
109
+ const { Hono } = await import("hono");
110
+ const app = new Hono();
111
+ app.route("/agents", runtime);
112
+ app.route("/", admin);
113
+ root = app;
114
+ });
115
+
116
+ afterEach(async () => {
117
+ await prisma.$disconnect();
118
+ });
119
+
120
+ const call = (token: string, method: string, path: string, body?: unknown) =>
121
+ root.request(path, {
122
+ method,
123
+ headers: {
124
+ Authorization: `Bearer ${token}`,
125
+ "Content-Type": "application/json",
126
+ },
127
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
128
+ });
129
+
130
+ const denied: Array<[string, string, unknown?]> = [
131
+ ["POST", "tokens", { label: "x" }],
132
+ ["GET", "tokens"],
133
+ ["DELETE", "tokens/some-id"],
134
+ ["POST", "envs", { A: "1" }],
135
+ ["PATCH", "envs", { env: { A: "1" } }],
136
+ ["DELETE", "envs/A"],
137
+ ["POST", "tools", { toolName: "Bash" }],
138
+ ["PATCH", "tools/some-id", {}],
139
+ ["DELETE", "tools/some-id"],
140
+ ["POST", "plugins", { name: "p" }],
141
+ ["PATCH", "plugins", { name: "p", enabled: false }],
142
+ ["DELETE", "plugins", { name: "p" }],
143
+ ["POST", "marketplaces", { name: "m", source: "x" }],
144
+ ["DELETE", "marketplaces/some-id"],
145
+ ];
146
+
147
+ for (const [method, suffix, body] of denied) {
148
+ it(`tools token is 403 on ${method} /agents/{id}/${suffix}`, async () => {
149
+ const res = await call(
150
+ toolsToken,
151
+ method,
152
+ `/agents/${agentId}/${suffix}`,
153
+ body,
154
+ );
155
+ expect(res.status).toBe(403);
156
+ });
157
+ }
158
+
159
+ it("tools token is 403 on a cron create with a path-form preCheck", async () => {
160
+ const res = await call(toolsToken, "POST", `/agents/${agentId}/crons`, {
161
+ schedule: "* * * * *",
162
+ prompt: "p",
163
+ preCheck: "/usr/bin/true",
164
+ });
165
+ expect(res.status).toBe(403);
166
+ });
167
+
168
+ it("tools token may create a cron with a plugin:script preCheck", async () => {
169
+ const res = await call(toolsToken, "POST", `/agents/${agentId}/crons`, {
170
+ schedule: "0 9 * * 1-5",
171
+ prompt: "p",
172
+ preCheck: "plugin:check.sh",
173
+ silent: true,
174
+ });
175
+ expect(res.status).toBe(201);
176
+ });
177
+
178
+ it("tools token reads stay allowed", async () => {
179
+ for (const suffix of [
180
+ "envs",
181
+ "crons",
182
+ "tools",
183
+ "plugins",
184
+ "marketplaces",
185
+ ]) {
186
+ const res = await call(toolsToken, "GET", `/agents/${agentId}/${suffix}`);
187
+ expect(res.status).toBe(200);
188
+ }
189
+ });
190
+
191
+ it("config gives a tools token env {} and a runtime token its env", async () => {
192
+ const write = await call(runtimeToken, "POST", `/agents/${agentId}/envs`, {
193
+ SECRET_KEY: "s3cr3t",
194
+ });
195
+ expect([200, 201]).toContain(write.status);
196
+
197
+ const asTools = await call(toolsToken, "GET", `/agents/${agentId}/config`);
198
+ expect(asTools.status).toBe(200);
199
+ expect(((await asTools.json()) as { env: unknown }).env).toEqual({});
200
+
201
+ const asRuntime = await call(
202
+ runtimeToken,
203
+ "GET",
204
+ `/agents/${agentId}/config`,
205
+ );
206
+ expect(asRuntime.status).toBe(200);
207
+ expect(
208
+ ((await asRuntime.json()) as { env: Record<string, string> }).env,
209
+ ).toEqual({
210
+ SECRET_KEY: "s3cr3t",
211
+ });
212
+ });
213
+
214
+ it("runtime token can still mint a token", async () => {
215
+ const res = await call(runtimeToken, "POST", `/agents/${agentId}/tokens`, {
216
+ label: "x",
217
+ });
218
+ expect(res.status).toBe(201);
219
+ });
220
+ });
@@ -0,0 +1,188 @@
1
+ /**
2
+ * admin/src/tools-token-policy.smoke.test.ts
3
+ *
4
+ * A tools-kind agent token driven through the real runtime and admin route
5
+ * tables and auth middleware, mounted like startAdmin does (in-process
6
+ * app.request, in-memory fakes, no DB): minting a token or writing env is 403,
7
+ * the config bundle carries env {}, and a runtime-kind token is unchanged.
8
+ */
9
+
10
+ import { describe, expect, it } from "bun:test";
11
+ import { Hono } from "hono";
12
+ import { type AdminDeps, createAdminApp } from "./agents-api.ts";
13
+ import { createAgentRuntimeApp } from "./api.ts";
14
+ import { createToolsTokenGuard } from "./tools-token-policy.ts";
15
+
16
+ const ID = "agent-1";
17
+ const TOOLS = "tools-token";
18
+ const RUNTIME = "runtime-token";
19
+
20
+ const agentTokenService = {
21
+ validate: async (raw: string) =>
22
+ raw === TOOLS
23
+ ? { agentId: ID, kind: "tools" as const }
24
+ : raw === RUNTIME
25
+ ? { agentId: ID, kind: "runtime" as const }
26
+ : null,
27
+ create: async (agentId: string, label?: string, kind = "runtime") => ({
28
+ token: {
29
+ id: "t1",
30
+ agentId,
31
+ token: "hash",
32
+ label: label ?? null,
33
+ kind,
34
+ createdAt: new Date(0),
35
+ revokedAt: null,
36
+ },
37
+ rawToken: "raw-minted",
38
+ }),
39
+ listForAgent: async () => [],
40
+ };
41
+
42
+ function makeRoot() {
43
+ const agent = {
44
+ id: ID,
45
+ repos: [],
46
+ reviewAuthorAllowlist: [],
47
+ patchAuthorAllowlist: [],
48
+ restrictSlackToMembers: false,
49
+ memberEmails: [],
50
+ specialty: "general",
51
+ autoPostReviews: false,
52
+ allowSelfReview: false,
53
+ minConfidence: 0,
54
+ maxFindings: 0,
55
+ cleanupMergedWorktrees: false,
56
+ cleanupAfterDays: 0,
57
+ };
58
+ const sessionSecret = "s".repeat(32);
59
+ const extensionRules = [
60
+ { method: "PUT", path: "/agents/{id}/widgets/{w}", decision: "deny" },
61
+ ] as const;
62
+ const runtime = createAgentRuntimeApp({
63
+ agentEnvService: {
64
+ getConfigBundle: async () => ({
65
+ env: { SECRET_KEY: "s3cr3t" },
66
+ allowedTools: [],
67
+ }),
68
+ },
69
+ agentCronJobService: { list: async () => [] },
70
+ agentService: { getById: async () => agent },
71
+ agentPluginService: { listEnabled: async () => [] },
72
+ agentTokenService,
73
+ sessionSecret,
74
+ toolsTokenPolicy: extensionRules,
75
+ } as unknown as Parameters<typeof createAgentRuntimeApp>[0]);
76
+ const admin = createAdminApp({
77
+ agentService: { exists: async () => true },
78
+ agentTokenService,
79
+ agentMemberService: { listByEmail: async () => [] },
80
+ agentEnvService: {
81
+ upsert: async () => {
82
+ throw new Error("env write must not be reached by a tools token");
83
+ },
84
+ patch: async () => {
85
+ throw new Error("env write must not be reached by a tools token");
86
+ },
87
+ },
88
+ sessionSecret,
89
+ toolsTokenPolicy: extensionRules,
90
+ } as unknown as AdminDeps);
91
+
92
+ const root = new Hono();
93
+ root.route("/agents", runtime);
94
+ root.route("/", admin);
95
+ // Extension route: authenticates on its own; the guard supplies the policy.
96
+ root.use(
97
+ "/agents/*",
98
+ createToolsTokenGuard({
99
+ agentTokenService,
100
+ extensionRules: [...extensionRules],
101
+ }),
102
+ );
103
+ root.put("/agents/:id/widgets/:w", (c) => c.json({ ok: true }));
104
+ root.put("/agents/:id/gadgets/:g", (c) => c.json({ ok: true }));
105
+ return root;
106
+ }
107
+
108
+ const send = (
109
+ root: Hono,
110
+ token: string,
111
+ method: string,
112
+ path: string,
113
+ body?: unknown,
114
+ ) =>
115
+ root.request(path, {
116
+ method,
117
+ headers: {
118
+ Authorization: `Bearer ${token}`,
119
+ "Content-Type": "application/json",
120
+ },
121
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
122
+ });
123
+
124
+ describe("tools-kind token through the in-process admin app", () => {
125
+ const root = makeRoot();
126
+
127
+ it("cannot mint a token", async () => {
128
+ const res = await send(root, TOOLS, "POST", `/agents/${ID}/tokens`, {
129
+ label: "x",
130
+ });
131
+ expect(res.status).toBe(403);
132
+ expect(
133
+ (await send(root, TOOLS, "GET", `/agents/${ID}/tokens`)).status,
134
+ ).toBe(403);
135
+ });
136
+
137
+ it("cannot write env", async () => {
138
+ const post = await send(root, TOOLS, "POST", `/agents/${ID}/envs`, {
139
+ env: { A: "1" },
140
+ });
141
+ expect(post.status).toBe(403);
142
+ const patch = await send(root, TOOLS, "PATCH", `/agents/${ID}/envs`, {
143
+ env: { A: "1" },
144
+ });
145
+ expect(patch.status).toBe(403);
146
+ expect(
147
+ (await send(root, TOOLS, "DELETE", `/agents/${ID}/envs/A`)).status,
148
+ ).toBe(403);
149
+ });
150
+
151
+ it("gets the config bundle with env {}", async () => {
152
+ const res = await send(root, TOOLS, "GET", `/agents/${ID}/config`);
153
+ expect(res.status).toBe(200);
154
+ expect(((await res.json()) as { env: unknown }).env).toEqual({});
155
+ });
156
+
157
+ it("runtime-kind token still mints a token and receives env", async () => {
158
+ const mint = await send(root, RUNTIME, "POST", `/agents/${ID}/tokens`, {
159
+ label: "x",
160
+ });
161
+ expect(mint.status).toBe(201);
162
+ const cfg = await send(root, RUNTIME, "GET", `/agents/${ID}/config`);
163
+ expect(((await cfg.json()) as { env: unknown }).env).toEqual({
164
+ SECRET_KEY: "s3cr3t",
165
+ });
166
+ });
167
+
168
+ it("extension routes: declared deny is 403, undeclared is allowed", async () => {
169
+ expect(
170
+ (await send(root, TOOLS, "PUT", `/agents/${ID}/widgets/w`)).status,
171
+ ).toBe(403);
172
+ expect(
173
+ (await send(root, TOOLS, "PUT", `/agents/${ID}/gadgets/g`)).status,
174
+ ).toBe(200);
175
+ expect(
176
+ (await send(root, RUNTIME, "PUT", `/agents/${ID}/widgets/w`)).status,
177
+ ).toBe(200);
178
+ });
179
+
180
+ it("cron preCheck: path forms are 403, plugin:script passes the policy", async () => {
181
+ const bad = await send(root, TOOLS, "POST", `/agents/${ID}/crons`, {
182
+ schedule: "* * * * *",
183
+ prompt: "hi",
184
+ preCheck: "/usr/bin/true",
185
+ });
186
+ expect(bad.status).toBe(403);
187
+ });
188
+ });