@app-vitals/agent-admin 1.107.3 → 1.107.4

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.
@@ -5476,11 +5476,24 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5476
5476
  expect(((await res.json()) as { error: string }).error).toContain(fragment);
5477
5477
  });
5478
5478
 
5479
- it("account user can delete an agent in their account scope", async () => {
5480
- const { deps } = makeAccountDeps("acct-a");
5479
+ // Management (here: DELETE) needs a platform admin or the owner of the
5480
+ // agent's own account; members and owners of other accounts are 403.
5481
+ const deleteAs = async (
5482
+ role: "owner" | "member",
5483
+ agentAccountId: string | null,
5484
+ callerAccountId = "acct-a",
5485
+ ) => {
5486
+ const { deps } = makeAccountDeps(callerAccountId, role);
5481
5487
  const base = deps.prisma;
5482
5488
  const app = createAdminApp({
5483
5489
  ...deps,
5490
+ agentService: {
5491
+ ...deps.agentService,
5492
+ getDetail: async (id: string) => {
5493
+ const detail = await deps.agentService.getDetail(AGENT_ID);
5494
+ return detail && { ...detail, id, accountId: agentAccountId };
5495
+ },
5496
+ },
5484
5497
  prisma: {
5485
5498
  ...base,
5486
5499
  agent: {
@@ -5497,10 +5510,42 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5497
5510
  },
5498
5511
  } as unknown as AdminDeps["prisma"],
5499
5512
  });
5500
- const res = await app.request(`/agents/${ACCOUNT_AGENT_ID}`, {
5513
+ return app.request(`/agents/${ACCOUNT_AGENT_ID}`, {
5501
5514
  method: "DELETE",
5502
5515
  headers: { Cookie: `admin_session=${await accountCookie()}` },
5503
5516
  });
5517
+ };
5518
+
5519
+ it("account owner can delete an agent in their own account", async () => {
5520
+ expect((await deleteAs("owner", "acct-a")).status).toBe(200);
5521
+ });
5522
+
5523
+ it("account member gets 403 deleting an agent in their own account", async () => {
5524
+ expect((await deleteAs("member", "acct-a")).status).toBe(403);
5525
+ });
5526
+
5527
+ it("owner of another account gets 403 even when they hold access to the agent", async () => {
5528
+ expect((await deleteAs("owner", "acct-b")).status).toBe(403);
5529
+ });
5530
+
5531
+ it("owner gets 403 when the agent has no account", async () => {
5532
+ expect((await deleteAs("owner", null)).status).toBe(403);
5533
+ });
5534
+
5535
+ it("account member can still read the agent (GET) in their account scope", async () => {
5536
+ const { deps } = makeAccountDeps("acct-a", "member");
5537
+ const res = await createAdminApp({
5538
+ ...deps,
5539
+ agentService: {
5540
+ ...deps.agentService,
5541
+ getDetail: async (id: string) => {
5542
+ const detail = await deps.agentService.getDetail(AGENT_ID);
5543
+ return detail && { ...detail, id, accountId: "acct-a" };
5544
+ },
5545
+ },
5546
+ }).request(`/agents/${ACCOUNT_AGENT_ID}`, {
5547
+ headers: { Cookie: `admin_session=${await accountCookie()}` },
5548
+ });
5504
5549
  expect(res.status).toBe(200);
5505
5550
  });
5506
5551
 
@@ -6315,11 +6360,12 @@ describe("admin API — repo removal blocks open work", () => {
6315
6360
  expect(calls).toEqual([blockCall("a/one")]);
6316
6361
  });
6317
6362
 
6318
- it("DELETE as a session member blocks open work too", async () => {
6319
- const { app, calls } = makeApp(["a/one", "b/two"]);
6363
+ it("DELETE as a session member is 403 and touches nothing", async () => {
6364
+ const { app, calls, repos } = makeApp(["a/one", "b/two"]);
6320
6365
  const res = await memberCall(app, "DELETE", `${url}/a/one`);
6321
- expect(res.status).toBe(200);
6322
- expect(calls).toEqual([blockCall("a/one")]);
6366
+ expect(res.status).toBe(403);
6367
+ expect(calls).toEqual([]);
6368
+ expect(repos()).toEqual(["a/one", "b/two"]);
6323
6369
  });
6324
6370
 
6325
6371
  it("a port failure is a warning and the removal still succeeds", async () => {
@@ -6345,13 +6391,22 @@ describe("admin API — repo removal blocks open work", () => {
6345
6391
 
6346
6392
  it("PATCH that drops repos blocks only the dropped ones", async () => {
6347
6393
  const { app, calls } = makeApp(["a/one", "b/two", "c/three"]);
6348
- const res = await memberCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6394
+ const res = await adminCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6349
6395
  repos: ["b/two"],
6350
6396
  });
6351
6397
  expect(res.status).toBe(200);
6352
6398
  expect(calls).toEqual([blockCall("a/one"), blockCall("c/three")]);
6353
6399
  });
6354
6400
 
6401
+ it("PATCH as a session member is 403 and touches nothing", async () => {
6402
+ const { app, calls } = makeApp(["a/one", "b/two", "c/three"]);
6403
+ const res = await memberCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6404
+ repos: ["b/two"],
6405
+ });
6406
+ expect(res.status).toBe(403);
6407
+ expect(calls).toEqual([]);
6408
+ });
6409
+
6355
6410
  it("adding a repo (POST, or PATCH that only adds) never touches open work", async () => {
6356
6411
  const { app, calls } = makeApp(["a/one"]);
6357
6412
  expect(
package/src/agents-api.ts CHANGED
@@ -2215,6 +2215,8 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2215
2215
  adminApiKeys,
2216
2216
  agentMemberService,
2217
2217
  callerScopeResolver,
2218
+ getAgentAccountId: async (id) =>
2219
+ (await agentService.getDetail(id))?.accountId,
2218
2220
  });
2219
2221
 
2220
2222
  // Platform readers/operators (platform.read / platform.ops admin keys): the
package/src/api-auth.ts CHANGED
@@ -17,6 +17,7 @@ import type { AgentTokenService } from "./agent-tokens.ts";
17
17
  import {
18
18
  type CallerScopeResolver,
19
19
  memberOnlyCallerScopeResolver,
20
+ scopeCanManageAgent,
20
21
  scopeIncludesAgent,
21
22
  } from "./caller-scope.ts";
22
23
  import { ForbiddenError } from "./errors.ts";
@@ -132,6 +133,23 @@ function routeMatchers(routes: readonly PlatformOpsRoute[]) {
132
133
  matchers.some((m) => m.method === method && m.re.test(path));
133
134
  }
134
135
 
136
+ /**
137
+ * Routes a non-admin session caller who merely has access to an agent may
138
+ * use: reads, and asking the agent (chat-style use). Every other method/path
139
+ * on an agent is management and needs scopeCanManageAgent.
140
+ */
141
+ export const MEMBER_USE_ROUTES: readonly PlatformOpsRoute[] = [
142
+ { method: "POST", path: "/agents/{id}/ask" },
143
+ { method: "POST", path: "/agents/{id}/asks" },
144
+ ];
145
+
146
+ const isMemberUseListed = routeMatchers(MEMBER_USE_ROUTES);
147
+ function isMemberUseRoute(method: string, path: string): boolean {
148
+ return (
149
+ method === "GET" || method === "HEAD" || isMemberUseListed(method, path)
150
+ );
151
+ }
152
+
135
153
  const isPlatformOpsRoute = routeMatchers(PLATFORM_OPS_ROUTES);
136
154
  const isAgentCrossRoute = routeMatchers(AGENT_CROSS_ROUTES);
137
155
 
@@ -231,6 +249,12 @@ export function createAdminAuthMiddleware(deps: {
231
249
  * AgentMember-only resolver built from agentMemberService.
232
250
  */
233
251
  callerScopeResolver?: CallerScopeResolver;
252
+ /**
253
+ * The account an agent belongs to (null when none). Needed to let an
254
+ * account owner manage their account's agents; absent, session callers
255
+ * that are not admins never pass the management check (fail closed).
256
+ */
257
+ getAgentAccountId?: (agentId: string) => Promise<string | null | undefined>;
234
258
  }): MiddlewareHandler<AdminAuthEnv> {
235
259
  const { sessionSecret, agentTokenService, adminApiKeys, agentMemberService } =
236
260
  deps;
@@ -255,7 +279,13 @@ export function createAdminAuthMiddleware(deps: {
255
279
  if (path === "/templates" || path.startsWith("/templates/")) return true;
256
280
  const agentId = extractAgentId(path);
257
281
  if (!agentId || !callerScopeResolver) return false;
258
- return scopeIncludesAgent(await callerScopeResolver(email, false), agentId);
282
+ const scope = await callerScopeResolver(email, false);
283
+ if (!scopeIncludesAgent(scope, agentId)) return false;
284
+ if (isMemberUseRoute(method, path)) return true;
285
+ // Everything else on an agent is management: admins (handled earlier) and
286
+ // the owner of the agent's own account only.
287
+ if (!deps.getAgentAccountId) return false;
288
+ return scopeCanManageAgent(scope, await deps.getAgentAccountId(agentId));
259
289
  }
260
290
 
261
291
  return async (c, next) => {
@@ -462,7 +462,15 @@ async function makeMemberJwt(
462
462
  );
463
463
  }
464
464
 
465
- function buildScopedApp(memberOf: Array<[string, string]>) {
465
+ function buildScopedApp(
466
+ memberOf: Array<[string, string]>,
467
+ manage?: {
468
+ scope?: Parameters<
469
+ typeof createAdminAuthMiddleware
470
+ >[0]["callerScopeResolver"];
471
+ agentAccountId?: string | null;
472
+ },
473
+ ) {
466
474
  const app = new Hono<AdminAuthEnv>();
467
475
  app.use(
468
476
  "*",
@@ -475,6 +483,10 @@ function buildScopedApp(memberOf: Array<[string, string]>) {
475
483
  .filter(([, e]) => e === email)
476
484
  .map(([agentId]) => ({ agentId }) as never),
477
485
  },
486
+ ...(manage?.scope ? { callerScopeResolver: manage.scope } : {}),
487
+ ...(manage && "agentAccountId" in manage
488
+ ? { getAgentAccountId: async () => manage.agentAccountId }
489
+ : {}),
478
490
  }),
479
491
  );
480
492
  app.all("*", (c) =>
@@ -511,14 +523,102 @@ describe("createAdminAuthMiddleware — non-admin session cookie scoping", () =>
511
523
  expect(res.status).toBe(403);
512
524
  });
513
525
 
514
- it("allows /agents/:id/** for a member agent", async () => {
526
+ it("lets a member agent read /agents/:id/** and ask, but not manage it", async () => {
515
527
  const app = buildScopedApp(member);
516
528
  const jwt = await makeMemberJwt();
517
- const res = await app.request(`/agents/${AGENT_ID}/crons`, {
518
- method: "PATCH",
519
- headers: { Cookie: `admin_session=${jwt}` },
529
+ const allowed: Array<[string, string]> = [
530
+ ["GET", `/agents/${AGENT_ID}`],
531
+ ["GET", `/agents/${AGENT_ID}/crons`],
532
+ ["POST", `/agents/${AGENT_ID}/ask`],
533
+ ];
534
+ for (const [method, path] of allowed) {
535
+ const res = await app.request(path, {
536
+ method,
537
+ headers: { Cookie: `admin_session=${jwt}` },
538
+ });
539
+ expect([method, path, res.status]).toEqual([method, path, 200]);
540
+ }
541
+ const denied: Array<[string, string]> = [
542
+ ["PATCH", `/agents/${AGENT_ID}`],
543
+ ["DELETE", `/agents/${AGENT_ID}`],
544
+ ["PATCH", `/agents/${AGENT_ID}/crons`],
545
+ ["POST", `/agents/${AGENT_ID}/envs`],
546
+ ["POST", `/agents/${AGENT_ID}/tokens`],
547
+ ["DELETE", `/agents/${AGENT_ID}/tokens/t1`],
548
+ ["POST", `/agents/${AGENT_ID}/tools`],
549
+ ["POST", `/agents/${AGENT_ID}/chat-credentials`],
550
+ ["PUT", `/agents/${AGENT_ID}/github-installations`],
551
+ ];
552
+ for (const [method, path] of denied) {
553
+ const res = await app.request(path, {
554
+ method,
555
+ headers: { Cookie: `admin_session=${jwt}` },
556
+ });
557
+ expect([method, path, res.status]).toEqual([method, path, 403]);
558
+ }
559
+ });
560
+
561
+ describe("management (platform admin or owner of the agent's account)", () => {
562
+ const scopeOf =
563
+ (accountId: string | null, role: "owner" | "member" | null) =>
564
+ async () => ({
565
+ kind: "scoped" as const,
566
+ accountId,
567
+ agentIds: [AGENT_ID],
568
+ ...(role ? { role } : {}),
569
+ });
570
+ const manageStatus = async (
571
+ scope: ReturnType<typeof scopeOf>,
572
+ agentAccountId: string | null,
573
+ withLookup = true,
574
+ ) => {
575
+ const app = buildScopedApp(
576
+ member,
577
+ withLookup ? { scope, agentAccountId } : { scope },
578
+ );
579
+ const jwt = await makeMemberJwt();
580
+ const res = await app.request(`/agents/${AGENT_ID}`, {
581
+ method: "PATCH",
582
+ headers: { Cookie: `admin_session=${jwt}` },
583
+ });
584
+ return res.status;
585
+ };
586
+
587
+ it("allows the owner of the agent's account", async () => {
588
+ expect(await manageStatus(scopeOf("acct-1", "owner"), "acct-1")).toBe(
589
+ 200,
590
+ );
591
+ });
592
+ it("denies an owner of another account", async () => {
593
+ expect(await manageStatus(scopeOf("acct-2", "owner"), "acct-1")).toBe(
594
+ 403,
595
+ );
596
+ });
597
+ it("denies a member of the agent's own account", async () => {
598
+ expect(await manageStatus(scopeOf("acct-1", "member"), "acct-1")).toBe(
599
+ 403,
600
+ );
601
+ });
602
+ it("denies an owner when the agent has no account", async () => {
603
+ expect(await manageStatus(scopeOf("acct-1", "owner"), null)).toBe(403);
604
+ });
605
+ it("denies an owner when the account lookup is not wired (fail closed)", async () => {
606
+ expect(
607
+ await manageStatus(scopeOf("acct-1", "owner"), "acct-1", false),
608
+ ).toBe(403);
609
+ });
610
+ it("denies when self-serve is off (resolver yields no accountId)", async () => {
611
+ expect(await manageStatus(scopeOf(null, "owner"), "acct-1")).toBe(403);
612
+ });
613
+ it("allows a platform admin cookie", async () => {
614
+ const app = buildScopedApp([]);
615
+ const jwt = await makeMemberJwt("admin@example.com", true);
616
+ const res = await app.request(`/agents/${AGENT_ID}`, {
617
+ method: "DELETE",
618
+ headers: { Cookie: `admin_session=${jwt}` },
619
+ });
620
+ expect(res.status).toBe(200);
520
621
  });
521
- expect(res.status).toBe(200);
522
622
  });
523
623
 
524
624
  it("returns 403 for an agent outside the membership", async () => {
@@ -110,6 +110,27 @@ export function scopeIncludesAgent(
110
110
  return scope.kind === "all" || scope.agentIds.includes(agentId);
111
111
  }
112
112
 
113
+ /**
114
+ * The single "may manage this agent" predicate (settings, members,
115
+ * credentials, tools, crons, tokens, delete): platform admins, or the owner
116
+ * of the agent's own account. Everything else (members, owners of another
117
+ * account, callers with no account) only uses the agent. The scope carries
118
+ * an accountId only when the self-serve flag is on, so flag-off owners never
119
+ * manage. An unknown role or an agent with no account fails closed.
120
+ */
121
+ export function scopeCanManageAgent(
122
+ scope: CallerScope,
123
+ agentAccountId: string | null | undefined,
124
+ ): boolean {
125
+ if (scope.kind === "all") return true;
126
+ return (
127
+ scope.role === "owner" &&
128
+ scope.accountId !== null &&
129
+ !!agentAccountId &&
130
+ scope.accountId === agentAccountId
131
+ );
132
+ }
133
+
113
134
  /**
114
135
  * How a caller may read the admin UI's task-store views — Tasks, PRs and
115
136
  * Sessions (SSP-6.8). Platform admins see every account; an account user
@@ -5,6 +5,7 @@ import {
5
5
  resolveCallerScope,
6
6
  resolveMemberRepoScope,
7
7
  resolveViewerRole,
8
+ scopeCanManageAgent,
8
9
  scopeIncludesAgent,
9
10
  taskStoreViewScope,
10
11
  } from "./caller-scope.ts";
@@ -288,3 +289,41 @@ describe("resolveMemberRepoScope", () => {
288
289
  expect(await resolveMemberRepoScope(scoped(["a1"]), deps)).toEqual([]);
289
290
  });
290
291
  });
292
+
293
+ describe("scopeCanManageAgent", () => {
294
+ const scoped = (
295
+ accountId: string | null,
296
+ role?: "owner" | "member",
297
+ ): CallerScope => ({
298
+ kind: "scoped",
299
+ accountId,
300
+ agentIds: ["a1"],
301
+ ...(role ? { role } : {}),
302
+ });
303
+
304
+ it("platform admins (kind all) manage any agent, with or without an account", () => {
305
+ expect(scopeCanManageAgent({ kind: "all" }, "acct-1")).toBe(true);
306
+ expect(scopeCanManageAgent({ kind: "all" }, null)).toBe(true);
307
+ });
308
+ it("the owner of the agent's account manages it", () => {
309
+ expect(scopeCanManageAgent(scoped("acct-1", "owner"), "acct-1")).toBe(true);
310
+ });
311
+ it("an owner of another account does not", () => {
312
+ expect(scopeCanManageAgent(scoped("acct-2", "owner"), "acct-1")).toBe(
313
+ false,
314
+ );
315
+ });
316
+ it("a member of the agent's account does not", () => {
317
+ expect(scopeCanManageAgent(scoped("acct-1", "member"), "acct-1")).toBe(
318
+ false,
319
+ );
320
+ });
321
+ it("unknown role, no account on scope (flag off) or no agent account fail closed", () => {
322
+ expect(scopeCanManageAgent(scoped("acct-1"), "acct-1")).toBe(false);
323
+ expect(scopeCanManageAgent(scoped(null, "owner"), "acct-1")).toBe(false);
324
+ expect(scopeCanManageAgent(scoped("acct-1", "owner"), null)).toBe(false);
325
+ expect(scopeCanManageAgent(scoped("acct-1", "owner"), undefined)).toBe(
326
+ false,
327
+ );
328
+ });
329
+ });