@app-vitals/agent-admin 1.121.0 → 1.123.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.
@@ -4579,6 +4579,26 @@
4579
4579
  ],
4580
4580
  "description": "null for agents",
4581
4581
  "example": "o@acme.com"
4582
+ },
4583
+ "accountId": {
4584
+ "type": [
4585
+ "string",
4586
+ "null"
4587
+ ],
4588
+ "description": "Account the user belongs to; null for users without membership (e.g. platform admins), omitted for agents",
4589
+ "example": "clx1acc"
4590
+ },
4591
+ "role": {
4592
+ "type": [
4593
+ "string",
4594
+ "null"
4595
+ ],
4596
+ "enum": [
4597
+ "owner",
4598
+ "member",
4599
+ null
4600
+ ],
4601
+ "description": "Membership role; null for users without membership (e.g. platform admins), omitted for agents"
4582
4602
  }
4583
4603
  },
4584
4604
  "required": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.121.0",
3
+ "version": "1.123.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.121.0",
47
+ "@app-vitals/agent-lib": "1.123.0",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -0,0 +1,237 @@
1
+ /**
2
+ * admin/src/admin-ui-account-filter.smoke.test.ts
3
+ * Admin account filter on the Agents and Chat pages: two accounts; admin sees
4
+ * all or one account's agents, owners and members are pinned and see no
5
+ * selector. Chat thread/message/upload routes keep their access check
6
+ * regardless of the selection.
7
+ */
8
+
9
+ import { beforeAll, describe, expect, it } from "bun:test";
10
+ import { makeMockDeps, makeSessionCookie } from "./admin-ui.fixtures.ts";
11
+ import { type AdminUIDeps, createAdminUIApp } from "./admin-ui.ts";
12
+ import type { ChatClient, ChatThread } from "./http-chat-client.ts";
13
+
14
+ const SECRET = "test-admin-session-secret-32-bytes!";
15
+ const ACCOUNTS = [
16
+ { id: "acct-one", name: "Account One" },
17
+ { id: "acct-two", name: "Account Two" },
18
+ ];
19
+ const AGENTS = [
20
+ { id: "agent-one", name: "Alpha Agent", accountId: "acct-one" },
21
+ { id: "agent-two", name: "Bravo Agent", accountId: "acct-two" },
22
+ ];
23
+
24
+ type Role = "admin" | "owner" | "member";
25
+ const EMAIL: Record<Role, string> = {
26
+ admin: "admin@example.com",
27
+ owner: "owner@example.com",
28
+ member: "member@example.com",
29
+ };
30
+ const cookies = {} as Record<Role, string>;
31
+
32
+ beforeAll(async () => {
33
+ for (const role of ["admin", "owner", "member"] as Role[]) {
34
+ cookies[role] = await makeSessionCookie(
35
+ SECRET,
36
+ `sub-${role}`,
37
+ EMAIL[role],
38
+ role === "admin",
39
+ );
40
+ }
41
+ });
42
+
43
+ const thread = (agentId: string): ChatThread => ({
44
+ id: `thread-${agentId}`,
45
+ agentId,
46
+ title: "Thread",
47
+ memberId: null,
48
+ createdAt: "2024-01-01T00:00:00.000Z",
49
+ updatedAt: "2024-01-01T00:00:00.000Z",
50
+ });
51
+
52
+ function deps(): AdminUIDeps {
53
+ const base = makeMockDeps();
54
+ const full = AGENTS.map((a) => ({
55
+ ...a,
56
+ slackId: null,
57
+ createdAt: new Date("2024-01-01"),
58
+ }));
59
+ const chatClient: ChatClient = {
60
+ listThreads: async (agentId: string) => ({
61
+ threads: [thread(agentId)],
62
+ total: 1,
63
+ limit: 50,
64
+ offset: 0,
65
+ }),
66
+ getThread: async (id: string) => thread(id.replace("thread-", "")),
67
+ createThread: async (agentId: string) => thread(agentId),
68
+ updateThread: async (id: string) => thread(id.replace("thread-", "")),
69
+ deleteThread: async () => {},
70
+ listMessages: async () => ({
71
+ messages: [],
72
+ total: 0,
73
+ limit: 50,
74
+ offset: 0,
75
+ }),
76
+ createMessage: async () => {
77
+ throw new Error("unused");
78
+ },
79
+ getThreadStats: async () => ({
80
+ messageCount: 0,
81
+ totalInputTokens: 0,
82
+ totalOutputTokens: 0,
83
+ totalCostUsd: 0,
84
+ }),
85
+ getAttachment: async () => null,
86
+ } as ChatClient;
87
+ return makeMockDeps({
88
+ sessionSecret: SECRET,
89
+ chatClient,
90
+ accountServices: {
91
+ accounts: {
92
+ getByMemberEmail: async () => null,
93
+ listWithCounts: async () => ACCOUNTS,
94
+ },
95
+ members: {
96
+ getByEmail: async (email: string) =>
97
+ email === EMAIL.owner
98
+ ? { role: "owner" }
99
+ : email === EMAIL.member
100
+ ? { role: "member" }
101
+ : null,
102
+ },
103
+ } as never,
104
+ callerScopeResolver: async (email: string, isAdmin: boolean) =>
105
+ isAdmin || email === EMAIL.admin
106
+ ? { kind: "all" }
107
+ : {
108
+ kind: "scoped",
109
+ accountId: email === EMAIL.owner ? "acct-one" : null,
110
+ agentIds: ["agent-one"],
111
+ },
112
+ agentService: {
113
+ ...base.agentService,
114
+ listAll: async () => full as never,
115
+ listByIds: async (ids: string[]) =>
116
+ full.filter((a) => ids.includes(a.id)) as never,
117
+ listOptions: async () => AGENTS,
118
+ },
119
+ });
120
+ }
121
+
122
+ async function get(role: Role, path: string): Promise<string> {
123
+ const res = await createAdminUIApp(deps()).request(path, {
124
+ headers: { Cookie: `admin_session=${cookies[role]}` },
125
+ });
126
+ expect(res.status).toBe(200);
127
+ return res.text();
128
+ }
129
+
130
+ describe("Agents page account filter", () => {
131
+ it("admin: all accounts by default, with the selector", async () => {
132
+ const html = await get("admin", "/admin/agents");
133
+ expect(html).toContain("Alpha Agent");
134
+ expect(html).toContain("Bravo Agent");
135
+ expect(html).toContain('class="account-filter"');
136
+ expect(html).toContain("All accounts");
137
+ });
138
+
139
+ for (const [id, shown, hidden] of [
140
+ ["acct-one", "Alpha Agent", "Bravo Agent"],
141
+ ["acct-two", "Bravo Agent", "Alpha Agent"],
142
+ ] as const) {
143
+ it(`admin: ${id} shows only its agents`, async () => {
144
+ const html = await get("admin", `/admin/agents?accountId=${id}`);
145
+ expect(html).toContain(shown);
146
+ expect(html).not.toContain(hidden);
147
+ expect(html).toContain(`<option value="${id}" selected>`);
148
+ });
149
+ }
150
+
151
+ it("admin: an unknown account falls back to all accounts", async () => {
152
+ const html = await get("admin", "/admin/agents?accountId=nope");
153
+ expect(html).toContain("Alpha Agent");
154
+ expect(html).toContain("Bravo Agent");
155
+ });
156
+
157
+ for (const role of ["owner", "member"] as Role[]) {
158
+ it(`${role}: pinned, no selector, accountId ignored`, async () => {
159
+ const html = await get(role, "/admin/agents?accountId=acct-two");
160
+ expect(html).toContain("Alpha Agent");
161
+ expect(html).not.toContain("Bravo Agent");
162
+ expect(html).not.toContain('class="account-filter"');
163
+ });
164
+ }
165
+ });
166
+
167
+ describe("Chat page account filter", () => {
168
+ it("admin: all agents by default, with the selector", async () => {
169
+ const html = await get("admin", "/admin/chat");
170
+ expect(html).toContain("Alpha Agent");
171
+ expect(html).toContain("Bravo Agent");
172
+ expect(html).toContain('class="account-filter"');
173
+ });
174
+
175
+ for (const [id, shown, hidden] of [
176
+ ["acct-one", "Alpha Agent", "Bravo Agent"],
177
+ ["acct-two", "Bravo Agent", "Alpha Agent"],
178
+ ] as const) {
179
+ it(`admin: ${id} narrows the agent picker`, async () => {
180
+ const html = await get("admin", `/admin/chat?accountId=${id}`);
181
+ expect(html).toContain(shown);
182
+ expect(html).not.toContain(hidden);
183
+ });
184
+ }
185
+
186
+ it("admin: the selection is carried by the picker and search forms", async () => {
187
+ const html = await get(
188
+ "admin",
189
+ "/admin/chat?accountId=acct-one&agentId=agent-one",
190
+ );
191
+ expect(html).toContain('name="accountId" value="acct-one"');
192
+ });
193
+
194
+ it("admin: an agent outside the selected account is ignored", async () => {
195
+ const html = await get(
196
+ "admin",
197
+ "/admin/chat?accountId=acct-one&agentId=agent-two",
198
+ );
199
+ expect(html).toContain("Alpha Agent");
200
+ expect(html).not.toContain("Bravo Agent");
201
+ expect(html).not.toContain('name="q"');
202
+ });
203
+
204
+ for (const role of ["owner", "member"] as Role[]) {
205
+ it(`${role}: pinned, no selector`, async () => {
206
+ const html = await get(role, "/admin/chat?accountId=acct-two");
207
+ expect(html).toContain("Alpha Agent");
208
+ expect(html).not.toContain("Bravo Agent");
209
+ expect(html).not.toContain('class="account-filter"');
210
+ });
211
+ }
212
+
213
+ it("access checks are unchanged by the selection", async () => {
214
+ const app = createAdminUIApp(deps());
215
+ for (const role of ["owner", "member"] as Role[]) {
216
+ const res = await app.request(
217
+ "/admin/chat/agent-two/threads/thread-agent-two?accountId=acct-two",
218
+ { headers: { Cookie: `admin_session=${cookies[role]}` } },
219
+ );
220
+ expect(res.status).toBe(403);
221
+ }
222
+ const up = await app.request(
223
+ "/admin/chat/agent-two/threads/thread-agent-two/messages/upload?accountId=acct-one",
224
+ {
225
+ method: "POST",
226
+ headers: { Cookie: `admin_session=${cookies.member}` },
227
+ body: new FormData(),
228
+ },
229
+ );
230
+ expect(up.status).toBe(403);
231
+ const adminRes = await app.request(
232
+ "/admin/chat/agent-two/threads/thread-agent-two?accountId=acct-one",
233
+ { headers: { Cookie: `admin_session=${cookies.admin}` } },
234
+ );
235
+ expect(adminRes.status).toBe(200);
236
+ });
237
+ });
@@ -404,6 +404,39 @@ export function renderLoginPage(opts?: {
404
404
  });
405
405
  }
406
406
 
407
+ // ─── Admin account filter ─────────────────────────────────────────────────────
408
+
409
+ /**
410
+ * Account selector shown to platform admins on the Agents and Chat pages.
411
+ * A GET form: "All accounts" (empty value) is the default. `hidden` carries
412
+ * other query params (e.g. the selected chat agent) across the switch.
413
+ */
414
+ export function renderAccountFilter(opts: {
415
+ action: string;
416
+ accounts: { id: string; name: string }[];
417
+ accountId?: string;
418
+ hidden?: Record<string, string | undefined>;
419
+ }): string {
420
+ const options = [
421
+ `<option value=""${opts.accountId ? "" : " selected"}>All accounts</option>`,
422
+ ...opts.accounts.map(
423
+ (a) =>
424
+ `<option value="${escapeHtml(a.id)}"${a.id === opts.accountId ? " selected" : ""}>${escapeHtml(a.name)}</option>`,
425
+ ),
426
+ ].join("");
427
+ const hidden = Object.entries(opts.hidden ?? {})
428
+ .filter(([, v]) => v)
429
+ .map(
430
+ ([k, v]) =>
431
+ `<input type="hidden" name="${escapeHtml(k)}" value="${escapeHtml(v as string)}">`,
432
+ )
433
+ .join("");
434
+ return `<form method="GET" action="${escapeHtml(opts.action)}" class="account-filter" style="display:flex;gap:8px;align-items:center;margin:0 0 16px">
435
+ ${hidden}<label>Account <select name="accountId" class="form-input" onchange="this.form.submit()">${options}</select></label>
436
+ <noscript><button type="submit" class="btn btn-secondary" style="font-size:12px;padding:4px 10px">Filter</button></noscript>
437
+ </form>`;
438
+ }
439
+
407
440
  // ─── Agents list page ─────────────────────────────────────────────────────────
408
441
 
409
442
  export function renderAgentsPage(
@@ -426,8 +459,20 @@ export function renderAgentsPage(
426
459
  * mounts /admin/agents/:id/queue-activity; absent/false omits the link.
427
460
  */
428
461
  queueActivityLinks?: boolean;
462
+ /** Admin-only account filter (Account selector above the table). */
463
+ accountFilter?: {
464
+ accounts: { id: string; name: string }[];
465
+ accountId?: string;
466
+ };
429
467
  },
430
468
  ): string {
469
+ const accountFilterHtml =
470
+ isAdmin && opts?.accountFilter
471
+ ? renderAccountFilter({
472
+ action: "/admin/agents",
473
+ ...opts.accountFilter,
474
+ })
475
+ : "";
431
476
  const showAccount = isAdmin && opts?.accountNames !== undefined;
432
477
  const accountCell = (a: AgentListItem): string => {
433
478
  if (!showAccount) return "";
@@ -490,6 +535,7 @@ export function renderAgentsPage(
490
535
  </div>
491
536
  ${successHtml}
492
537
  ${manualStepsHtml}
538
+ ${accountFilterHtml}
493
539
  <div class="card">
494
540
  <table class="data-table">
495
541
  <thead>
@@ -2708,6 +2754,8 @@ export function renderProvisionXappTokenPage(
2708
2754
  export interface AgentOption {
2709
2755
  id: string;
2710
2756
  name: string;
2757
+ /** Owning account; used by the admin account filter. */
2758
+ accountId?: string | null;
2711
2759
  }
2712
2760
 
2713
2761
  export function renderProvisionCompletePage(
@@ -3155,8 +3203,19 @@ export function renderChatPage(
3155
3203
  threads: ChatThread[] | null,
3156
3204
  userName: string,
3157
3205
  q?: string,
3206
+ accountFilter?: {
3207
+ accounts: { id: string; name: string }[];
3208
+ accountId?: string;
3209
+ },
3158
3210
  ): string {
3159
3211
  const activePath = "/admin/chat";
3212
+ const accountId = accountFilter?.accountId;
3213
+ const accountFilterHtml = accountFilter
3214
+ ? renderAccountFilter({
3215
+ action: "/admin/chat",
3216
+ ...accountFilter,
3217
+ })
3218
+ : "";
3160
3219
 
3161
3220
  const agentOptions = agents
3162
3221
  .map(
@@ -3167,6 +3226,7 @@ export function renderChatPage(
3167
3226
 
3168
3227
  const agentSelector = `
3169
3228
  <form method="GET" action="/admin/chat" class="form-row" style="margin-bottom:24px">
3229
+ ${accountId ? `<input type="hidden" name="accountId" value="${escapeHtml(accountId)}">` : ""}
3170
3230
  <div class="form-group" style="max-width:320px">
3171
3231
  <label class="form-label" for="agentId">Agent</label>
3172
3232
  <select name="agentId" id="agentId" class="form-input" onchange="this.form.submit()">
@@ -3196,6 +3256,7 @@ export function renderChatPage(
3196
3256
  const searchForm = `
3197
3257
  <form method="GET" action="/admin/chat" class="form-row" style="margin-bottom:16px">
3198
3258
  <input type="hidden" name="agentId" value="${escapeHtml(selectedAgentId)}">
3259
+ ${accountId ? `<input type="hidden" name="accountId" value="${escapeHtml(accountId)}">` : ""}
3199
3260
  <div class="form-group" style="max-width:320px">
3200
3261
  <input type="text" name="q" class="form-input" placeholder="Search threads…" value="${escapeHtml(q ?? "")}">
3201
3262
  </div>
@@ -3249,6 +3310,7 @@ export function renderChatPage(
3249
3310
  <div class="page-header">
3250
3311
  <h1 class="page-title">Chat</h1>
3251
3312
  </div>
3313
+ ${accountFilterHtml}
3252
3314
  ${agentSelector}
3253
3315
  ${content}
3254
3316
  </div>`,
package/src/admin-ui.ts CHANGED
@@ -1011,6 +1011,23 @@ function normalizePluginSpec(spec: string): string {
1011
1011
  return spec.includes("@") ? spec : `${spec}@${DEFAULT_PLUGIN_MARKETPLACE}`;
1012
1012
  }
1013
1013
 
1014
+ interface AccountFilter {
1015
+ accounts: { id: string; name: string }[];
1016
+ accountId?: string;
1017
+ }
1018
+
1019
+ /** Admin account filter state; an unknown accountId falls back to all accounts. */
1020
+ function adminAccountFilter(
1021
+ accounts: { id: string; name: string }[],
1022
+ requested: string | undefined,
1023
+ ): AccountFilter {
1024
+ const list = accounts.map((a) => ({ id: a.id, name: a.name }));
1025
+ const accountId = list.some((a) => a.id === requested)
1026
+ ? requested
1027
+ : undefined;
1028
+ return { accounts: list, accountId };
1029
+ }
1030
+
1014
1031
  export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1015
1032
  const {
1016
1033
  prisma,
@@ -1708,17 +1725,21 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1708
1725
  }
1709
1726
  // SSP-5.2: admins get an Account column.
1710
1727
  let accountNames: Map<string, string> | undefined;
1728
+ let accountFilter: AccountFilter | undefined;
1729
+ let visibleAgents = agents;
1711
1730
  if (c.var.isAdmin && accountServices) {
1712
- accountNames = new Map(
1713
- (await accountServices.accounts.listWithCounts()).map((a) => [
1714
- a.id,
1715
- a.name,
1716
- ]),
1717
- );
1731
+ const accountList = await accountServices.accounts.listWithCounts();
1732
+ accountNames = new Map(accountList.map((a) => [a.id, a.name]));
1733
+ accountFilter = adminAccountFilter(accountList, c.req.query("accountId"));
1734
+ const selected = accountFilter.accountId;
1735
+ if (selected) {
1736
+ visibleAgents = agents.filter((a) => a.accountId === selected);
1737
+ }
1718
1738
  }
1719
1739
  return html(
1720
- renderAgentsPage(agents, c.var.userEmail, c.var.isAdmin, tzOf(c), {
1740
+ renderAgentsPage(visibleAgents, c.var.userEmail, c.var.isAdmin, tzOf(c), {
1721
1741
  accountNames,
1742
+ accountFilter,
1722
1743
  queueActivityLinks: deps.queueActivityLinks,
1723
1744
  successMsg,
1724
1745
  manualSteps,
@@ -4926,25 +4947,48 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4926
4947
  }
4927
4948
 
4928
4949
  app.get("/admin/chat", requireAuth, async (c) => {
4929
- const selectedAgentId = c.req.query("agentId") || undefined;
4950
+ const requestedAgentId = c.req.query("agentId") || undefined;
4930
4951
  const q = c.req.query("q") || undefined;
4931
- const agents: AgentOption[] = c.var.isAdmin
4932
- ? await agentService.listOptions()
4933
- : (await resolveAccessibleAgents(c.var.userEmail, false)).map((a) => ({
4952
+ // Admin account filter: narrows the agent picker only. Every thread,
4953
+ // message and upload route still goes through canAccessChat.
4954
+ let accountFilter: AccountFilter | undefined;
4955
+ let agents: AgentOption[];
4956
+ if (c.var.isAdmin) {
4957
+ agents = await agentService.listOptions();
4958
+ if (accountServices) {
4959
+ accountFilter = adminAccountFilter(
4960
+ await accountServices.accounts.listWithCounts(),
4961
+ c.req.query("accountId"),
4962
+ );
4963
+ const selected = accountFilter.accountId;
4964
+ if (selected) agents = agents.filter((a) => a.accountId === selected);
4965
+ }
4966
+ } else {
4967
+ agents = (await resolveAccessibleAgents(c.var.userEmail, false)).map(
4968
+ (a) => ({
4934
4969
  id: a.id,
4935
4970
  name: a.name,
4936
- }));
4937
- if (
4938
- selectedAgentId &&
4939
- !c.var.isAdmin &&
4940
- !agents.some((a) => a.id === selectedAgentId)
4941
- ) {
4971
+ }),
4972
+ );
4973
+ }
4974
+ const inList = agents.some((a) => a.id === requestedAgentId);
4975
+ if (requestedAgentId && !c.var.isAdmin && !inList) {
4942
4976
  return new Response("Forbidden", { status: 403 });
4943
4977
  }
4978
+ // An admin's stale agent from outside the selected account is ignored.
4979
+ const selectedAgentId =
4980
+ accountFilter?.accountId && !inList ? undefined : requestedAgentId;
4944
4981
 
4945
4982
  if (!chatClient) {
4946
4983
  return html(
4947
- renderChatPage(agents, selectedAgentId, null, c.var.userEmail, q),
4984
+ renderChatPage(
4985
+ agents,
4986
+ selectedAgentId,
4987
+ null,
4988
+ c.var.userEmail,
4989
+ q,
4990
+ accountFilter,
4991
+ ),
4948
4992
  );
4949
4993
  }
4950
4994
 
@@ -4966,7 +5010,14 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4966
5010
  }
4967
5011
 
4968
5012
  return html(
4969
- renderChatPage(agents, selectedAgentId, threads, c.var.userEmail, q),
5013
+ renderChatPage(
5014
+ agents,
5015
+ selectedAgentId,
5016
+ threads,
5017
+ c.var.userEmail,
5018
+ q,
5019
+ accountFilter,
5020
+ ),
4970
5021
  );
4971
5022
  });
4972
5023
 
@@ -7,15 +7,7 @@
7
7
  * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
8
8
  */
9
9
 
10
- import {
11
- afterAll,
12
- afterEach,
13
- beforeAll,
14
- beforeEach,
15
- describe,
16
- expect,
17
- it,
18
- } from "bun:test";
10
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
19
11
  import type { PrismaClient } from "../prisma/client/client.ts";
20
12
  import { AgentMarketplaceService } from "./agent-marketplaces.ts";
21
13
  import { AgentTokenService } from "./agent-tokens.ts";
@@ -36,19 +28,8 @@ const SESSION_SECRET = "test-admin-session-secret-32-bytes!";
36
28
  const ADMIN_KEY = "admin-key-token";
37
29
 
38
30
  describeOrSkip("AgentMarketplaceService + routes (integration)", () => {
39
- // These routes are exercised with agent-scoped (runtime-kind) tokens; the
40
- // runtime denylist would 403 the writes, so it is switched off here. The
41
- // denylist itself is covered in tools-token-policy.*.test.ts.
42
- const savedPolicy = process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
43
- beforeAll(() => {
44
- process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY = "off";
45
- });
46
- afterAll(() => {
47
- if (savedPolicy === undefined)
48
- delete process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
49
- else process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY = savedPolicy;
50
- });
51
-
31
+ // Marketplace writes are on the runtime-token denylist, so writes through
32
+ // the admin app use the admin key; per-agent tokens cover scoping and reads.
52
33
  let prisma: PrismaClient;
53
34
  let service: AgentMarketplaceService;
54
35
  let tokens: AgentTokenService;
@@ -173,7 +154,7 @@ describeOrSkip("AgentMarketplaceService + routes (integration)", () => {
173
154
  it("POST upserts (201), GET lists, DELETE removes (204)", async () => {
174
155
  const created = await adminApp.request(
175
156
  `/agents/${agentA}/marketplaces`,
176
- json(tokenA, {
157
+ json(ADMIN_KEY, {
177
158
  name: "shipwright",
178
159
  source: "app-vitals/shipwright",
179
160
  ref: "main",
@@ -197,7 +178,7 @@ describeOrSkip("AgentMarketplaceService + routes (integration)", () => {
197
178
 
198
179
  const del = await adminApp.request(
199
180
  `/agents/${agentA}/marketplaces/${marketplace.id}`,
200
- json(tokenA, undefined, "DELETE"),
181
+ json(ADMIN_KEY, undefined, "DELETE"),
201
182
  );
202
183
  expect(del.status).toBe(204);
203
184
  expect(await service.list(agentA)).toEqual([]);
@@ -220,7 +201,7 @@ describeOrSkip("AgentMarketplaceService + routes (integration)", () => {
220
201
  ]) {
221
202
  const res = await adminApp.request(
222
203
  `/agents/${agentA}/marketplaces`,
223
- json(tokenA, { name: "m", source }),
204
+ json(ADMIN_KEY, { name: "m", source }),
224
205
  );
225
206
  expect(res.status).toBe(422);
226
207
  }
@@ -231,7 +212,7 @@ describeOrSkip("AgentMarketplaceService + routes (integration)", () => {
231
212
  const row = await service.upsert(agentB, { name: "m", source: "o/r" });
232
213
  const res = await adminApp.request(
233
214
  `/agents/${agentA}/marketplaces/${row.id}`,
234
- json(tokenA, undefined, "DELETE"),
215
+ json(ADMIN_KEY, undefined, "DELETE"),
235
216
  );
236
217
  expect(res.status).toBe(404);
237
218
  expect(await service.list(agentB)).toHaveLength(1);
@@ -275,7 +256,7 @@ describeOrSkip("AgentMarketplaceService + routes (integration)", () => {
275
256
  const tpl = await seedTemplate(agentA);
276
257
  const res = await adminApp.request(
277
258
  `/agents/${agentA}/marketplaces`,
278
- json(tokenA, { name: "tpl", source: "o/other" }),
259
+ json(ADMIN_KEY, { name: "tpl", source: "o/other" }),
279
260
  );
280
261
  expect(res.status).toBe(201);
281
262
  const body = (await res.json()).marketplace;
@@ -297,7 +278,7 @@ describeOrSkip("AgentMarketplaceService + routes (integration)", () => {
297
278
  for (const id of [tpl.id, custom.id]) {
298
279
  const res = await adminApp.request(
299
280
  `/agents/${agentA}/marketplaces/${id}`,
300
- json(tokenA, undefined, "DELETE"),
281
+ json(ADMIN_KEY, undefined, "DELETE"),
301
282
  );
302
283
  expect(res.status).toBe(204);
303
284
  }
@@ -353,7 +334,7 @@ describeOrSkip("AgentMarketplaceService + routes (integration)", () => {
353
334
  await service.upsert(agentA, { name: "kept", source: "o/k" });
354
335
  await adminApp.request(
355
336
  `/agents/${agentA}/marketplaces/${tpl.id}`,
356
- json(tokenA, undefined, "DELETE"),
337
+ json(ADMIN_KEY, undefined, "DELETE"),
357
338
  );
358
339
  const list = await adminApp.request(
359
340
  `/agents/${agentA}/marketplaces`,
package/src/agents.ts CHANGED
@@ -250,6 +250,8 @@ interface AgentIdAndRepos {
250
250
  export interface AgentOption {
251
251
  id: string;
252
252
  name: string;
253
+ /** Owning account; present when the lister selects it (admin account filter). */
254
+ accountId?: string | null;
253
255
  }
254
256
 
255
257
  export interface UpdateAgentFieldsInput {
@@ -663,7 +665,7 @@ export class AgentService {
663
665
  */
664
666
  async listOptions(): Promise<AgentOption[]> {
665
667
  return this.prisma.agent.findMany({
666
- select: { id: true, name: true },
668
+ select: { id: true, name: true, accountId: true },
667
669
  orderBy: { name: "asc" },
668
670
  });
669
671
  }
package/src/api-auth.ts CHANGED
@@ -384,8 +384,7 @@ export function createAdminAuthMiddleware(deps: {
384
384
  return c.json({ error: "Forbidden" }, 403);
385
385
  }
386
386
  // Tools-kind tokens are restricted by one route policy (see
387
- // tools-token-policy.ts); runtime-kind tokens get the smaller denylist
388
- // unless SHIPWRIGHT_RUNTIME_TOKEN_POLICY=off.
387
+ // tools-token-policy.ts); runtime-kind tokens get the smaller denylist.
389
388
  if (
390
389
  (result.kind === "tools" &&
391
390
  toolsTokenDecision(
@@ -1627,6 +1627,15 @@ export const PrincipalSchema = z
1627
1627
  .string()
1628
1628
  .nullable()
1629
1629
  .openapi({ description: "null for agents", example: "o@acme.com" }),
1630
+ accountId: z.string().nullable().optional().openapi({
1631
+ description:
1632
+ "Account the user belongs to; null for users without membership (e.g. platform admins), omitted for agents",
1633
+ example: "clx1acc",
1634
+ }),
1635
+ role: z.enum(["owner", "member"]).nullable().optional().openapi({
1636
+ description:
1637
+ "Membership role; null for users without membership (e.g. platform admins), omitted for agents",
1638
+ }),
1630
1639
  })
1631
1640
  .openapi("Principal");
1632
1641
 
@@ -15,6 +15,14 @@ export interface Principal {
15
15
  id: string;
16
16
  type: "user" | "agent";
17
17
  email: string | null;
18
+ /** Owning account of a user principal; null with no membership, omitted for agents. */
19
+ accountId?: string | null;
20
+ /** Membership role of a user principal ("owner" | "member"); null with no membership. */
21
+ role?: "owner" | "member" | null;
22
+ }
23
+
24
+ function toRole(role: string | null | undefined): "owner" | "member" | null {
25
+ return role === "owner" || role === "member" ? role : null;
18
26
  }
19
27
 
20
28
  export interface PrincipalLookupResult {
@@ -33,7 +41,7 @@ export class PrincipalLookupService {
33
41
  const [members, agents] = await Promise.all([
34
42
  this.prisma.accountMember.findMany({
35
43
  where: { id: { in: unique } },
36
- select: { id: true, email: true },
44
+ select: { id: true, email: true, accountId: true, role: true },
37
45
  }),
38
46
  this.prisma.agent.findMany({
39
47
  where: { id: { in: unique } },
@@ -45,7 +53,13 @@ export class PrincipalLookupService {
45
53
  byId.set(a.id, { id: a.id, type: "agent", email: null });
46
54
  // Ids are cuids so collisions are not expected; a member wins if one occurs.
47
55
  for (const m of members)
48
- byId.set(m.id, { id: m.id, type: "user", email: m.email });
56
+ byId.set(m.id, {
57
+ id: m.id,
58
+ type: "user",
59
+ email: m.email,
60
+ accountId: m.accountId ?? null,
61
+ role: toRole(m.role),
62
+ });
49
63
 
50
64
  const principals: Principal[] = [];
51
65
  const notFound: string[] = [];
@@ -60,8 +74,16 @@ export class PrincipalLookupService {
60
74
  async findIdByEmail(email: string): Promise<Principal | null> {
61
75
  const member = await this.prisma.accountMember.findUnique({
62
76
  where: { email: normalizeEmail(email) },
63
- select: { id: true, email: true },
77
+ select: { id: true, email: true, accountId: true, role: true },
64
78
  });
65
- return member ? { id: member.id, type: "user", email: member.email } : null;
79
+ return member
80
+ ? {
81
+ id: member.id,
82
+ type: "user",
83
+ email: member.email,
84
+ accountId: member.accountId ?? null,
85
+ role: toRole(member.role),
86
+ }
87
+ : null;
66
88
  }
67
89
  }
@@ -7,7 +7,7 @@ import { describe, expect, it } from "bun:test";
7
7
  import { PrincipalLookupService } from "./principal-lookup.ts";
8
8
 
9
9
  function fakePrisma(
10
- members: { id: string; email: string }[],
10
+ members: { id: string; email: string; accountId?: string; role?: string }[],
11
11
  agents: { id: string }[],
12
12
  ) {
13
13
  const calls = { member: 0, agent: 0 };
@@ -33,7 +33,7 @@ function fakePrisma(
33
33
  describe("PrincipalLookupService.resolveMany", () => {
34
34
  it("resolves a mixed list of member and agent ids", async () => {
35
35
  const { prisma } = fakePrisma(
36
- [{ id: "m1", email: "a@x.com" }],
36
+ [{ id: "m1", email: "a@x.com", accountId: "acc1", role: "owner" }],
37
37
  [{ id: "a1" }],
38
38
  );
39
39
  const res = await new PrincipalLookupService(prisma).resolveMany([
@@ -41,7 +41,13 @@ describe("PrincipalLookupService.resolveMany", () => {
41
41
  "a1",
42
42
  ]);
43
43
  expect(res.principals).toEqual([
44
- { id: "m1", type: "user", email: "a@x.com" },
44
+ {
45
+ id: "m1",
46
+ type: "user",
47
+ email: "a@x.com",
48
+ accountId: "acc1",
49
+ role: "owner",
50
+ },
45
51
  { id: "a1", type: "agent", email: null },
46
52
  ]);
47
53
  expect(res.notFound).toEqual([]);
@@ -84,14 +90,65 @@ describe("PrincipalLookupService.resolveMany", () => {
84
90
  });
85
91
  });
86
92
 
93
+ describe("PrincipalLookupService account id and role", () => {
94
+ const members = [
95
+ { id: "m1", email: "o@x.com", accountId: "acc1", role: "owner" },
96
+ { id: "m2", email: "m@x.com", accountId: "acc1", role: "member" },
97
+ ];
98
+
99
+ it("resolveMany returns accountId and role for users, none for agents", async () => {
100
+ const { prisma } = fakePrisma(members, [{ id: "a1" }]);
101
+ const res = await new PrincipalLookupService(prisma).resolveMany([
102
+ "m1",
103
+ "m2",
104
+ "a1",
105
+ ]);
106
+ expect(res.principals).toEqual([
107
+ {
108
+ id: "m1",
109
+ type: "user",
110
+ email: "o@x.com",
111
+ accountId: "acc1",
112
+ role: "owner",
113
+ },
114
+ {
115
+ id: "m2",
116
+ type: "user",
117
+ email: "m@x.com",
118
+ accountId: "acc1",
119
+ role: "member",
120
+ },
121
+ { id: "a1", type: "agent", email: null },
122
+ ]);
123
+ });
124
+
125
+ it("findIdByEmail returns accountId and role", async () => {
126
+ const { prisma } = fakePrisma(members, []);
127
+ expect(
128
+ await new PrincipalLookupService(prisma).findIdByEmail("m@x.com"),
129
+ ).toEqual({
130
+ id: "m2",
131
+ type: "user",
132
+ email: "m@x.com",
133
+ accountId: "acc1",
134
+ role: "member",
135
+ });
136
+ });
137
+ });
138
+
87
139
  describe("PrincipalLookupService.findIdByEmail", () => {
88
140
  it("normalizes case and whitespace before matching", async () => {
89
- const { prisma } = fakePrisma([{ id: "m1", email: "a@x.com" }], []);
141
+ const { prisma } = fakePrisma(
142
+ [{ id: "m1", email: "a@x.com", accountId: "acc1", role: "member" }],
143
+ [],
144
+ );
90
145
  const svc = new PrincipalLookupService(prisma);
91
146
  expect(await svc.findIdByEmail(" A@X.com ")).toEqual({
92
147
  id: "m1",
93
148
  type: "user",
94
149
  email: "a@x.com",
150
+ accountId: "acc1",
151
+ role: "member",
95
152
  });
96
153
  });
97
154
 
@@ -56,7 +56,13 @@ describeOrSkip("/principals API (integration)", () => {
56
56
  expect(res.status).toBe(200);
57
57
  expect(await res.json()).toEqual({
58
58
  principals: [
59
- { id: member.id, type: "user", email: "owner@acme.com" },
59
+ {
60
+ id: member.id,
61
+ type: "user",
62
+ email: "owner@acme.com",
63
+ accountId: account.id,
64
+ role: "owner",
65
+ },
60
66
  { id: agent.id, type: "agent", email: null },
61
67
  ],
62
68
  notFound: ["missing"],
@@ -76,6 +82,8 @@ describeOrSkip("/principals API (integration)", () => {
76
82
  id: member.id,
77
83
  type: "user",
78
84
  email: "owner@acme.com",
85
+ accountId: account.id,
86
+ role: "owner",
79
87
  });
80
88
  const miss = await app.request(
81
89
  "/principals/by-email?email=nobody@acme.com",
@@ -0,0 +1,96 @@
1
+ /**
2
+ * admin/src/principals-api.smoke.test.ts
3
+ * Smoke tests for the admin-only /principals user lookup: accountId and role
4
+ * on the response. In-process app.request(), in-memory lookup double.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import { parseAdminApiKeys } from "./api-auth.ts";
9
+ import type { Principal } from "./principal-lookup.ts";
10
+ import { createPrincipalsApp } from "./principals-api.ts";
11
+
12
+ const KEY = "admin-key";
13
+ const headers = { Authorization: `Bearer ${KEY}` };
14
+
15
+ const users: Principal[] = [
16
+ {
17
+ id: "m1",
18
+ type: "user",
19
+ email: "owner@acme.test",
20
+ accountId: "acc1",
21
+ role: "owner",
22
+ },
23
+ {
24
+ id: "m2",
25
+ type: "user",
26
+ email: "member@acme.test",
27
+ accountId: "acc1",
28
+ role: "member",
29
+ },
30
+ {
31
+ id: "m3",
32
+ type: "user",
33
+ email: "admin@acme.test",
34
+ accountId: null,
35
+ role: null,
36
+ },
37
+ ];
38
+
39
+ function build() {
40
+ return createPrincipalsApp({
41
+ lookup: {
42
+ resolveMany: async (ids: string[]) => ({
43
+ principals: users.filter((u) => ids.includes(u.id)),
44
+ notFound: ids.filter((i) => !users.some((u) => u.id === i)),
45
+ }),
46
+ findIdByEmail: async (email: string) =>
47
+ users.find((u) => u.email === email) ?? null,
48
+ },
49
+ sessionSecret: "principals-smoke-secret-32-bytes!",
50
+ adminApiKeys: parseAdminApiKeys(`admin:${KEY}:*`),
51
+ agentTokenService: { validate: async () => null } as never,
52
+ });
53
+ }
54
+
55
+ describe("GET /principals/by-email account fields", () => {
56
+ it.each([
57
+ ["owner@acme.test", "acc1", "owner"],
58
+ ["member@acme.test", "acc1", "member"],
59
+ ["admin@acme.test", null, null],
60
+ ])("%s -> accountId %p, role %p", async (email, accountId, role) => {
61
+ const res = await build().request(
62
+ `/principals/by-email?email=${encodeURIComponent(email)}`,
63
+ { headers },
64
+ );
65
+ expect(res.status).toBe(200);
66
+ const body = (await res.json()) as Record<string, unknown>;
67
+ expect(body.id).toBeDefined();
68
+ expect(body.type).toBe("user");
69
+ expect(body.email).toBe(email);
70
+ expect(body.accountId).toBe(accountId);
71
+ expect(body.role).toBe(role);
72
+ });
73
+
74
+ it("unknown email is still 404", async () => {
75
+ const res = await build().request(
76
+ "/principals/by-email?email=nobody@acme.test",
77
+ { headers },
78
+ );
79
+ expect(res.status).toBe(404);
80
+ });
81
+ });
82
+
83
+ describe("POST /principals/lookup account fields", () => {
84
+ it("includes accountId and role per user", async () => {
85
+ const res = await build().request("/principals/lookup", {
86
+ method: "POST",
87
+ headers: { ...headers, "Content-Type": "application/json" },
88
+ body: JSON.stringify({ ids: ["m1", "m2", "m3", "zz"] }),
89
+ });
90
+ expect(res.status).toBe(200);
91
+ expect(await res.json()).toEqual({
92
+ principals: users,
93
+ notFound: ["zz"],
94
+ });
95
+ });
96
+ });
@@ -214,15 +214,7 @@ describeOrSkip("tools-kind token policy (integration)", () => {
214
214
  });
215
215
 
216
216
  describe("runtime-kind denylist", () => {
217
- const saved = process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
218
- afterEach(() => {
219
- if (saved === undefined)
220
- delete process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
221
- else process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY = saved;
222
- });
223
-
224
217
  it("runtime token is 403 on token mint and env write", async () => {
225
- delete process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
226
218
  const mint = await call(
227
219
  runtimeToken,
228
220
  "POST",
@@ -237,7 +229,6 @@ describeOrSkip("tools-kind token policy (integration)", () => {
237
229
  });
238
230
 
239
231
  it("runtime token is 200 on config, crons reconcile and cron run reports", async () => {
240
- delete process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
241
232
  expect(
242
233
  (await call(runtimeToken, "GET", `/agents/${agentId}/config`)).status,
243
234
  ).toBe(200);
@@ -267,16 +258,5 @@ describeOrSkip("tools-kind token policy (integration)", () => {
267
258
  );
268
259
  expect(patch.status).not.toBe(403);
269
260
  });
270
-
271
- it("SHIPWRIGHT_RUNTIME_TOKEN_POLICY=off restores access", async () => {
272
- process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY = "off";
273
- const mint = await call(
274
- runtimeToken,
275
- "POST",
276
- `/agents/${agentId}/tokens`,
277
- { label: "x" },
278
- );
279
- expect(mint.status).toBe(201);
280
- });
281
261
  });
282
262
  });
@@ -155,9 +155,7 @@ describe("tools-kind token through the in-process admin app", () => {
155
155
  });
156
156
 
157
157
  it("runtime-kind token is denied credential writes but receives env", async () => {
158
- const saved = process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
159
- delete process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
160
- try {
158
+ {
161
159
  const mint = await send(root, RUNTIME, "POST", `/agents/${ID}/tokens`, {
162
160
  label: "x",
163
161
  });
@@ -166,15 +164,6 @@ describe("tools-kind token through the in-process admin app", () => {
166
164
  (await send(root, RUNTIME, "POST", `/agents/${ID}/envs`, { env: {} }))
167
165
  .status,
168
166
  ).toBe(403);
169
- process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY = "off";
170
- const off = await send(root, RUNTIME, "POST", `/agents/${ID}/tokens`, {
171
- label: "x",
172
- });
173
- expect(off.status).toBe(201);
174
- } finally {
175
- if (saved === undefined)
176
- delete process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
177
- else process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY = saved;
178
167
  }
179
168
  const cfg = await send(root, RUNTIME, "GET", `/agents/${ID}/config`);
180
169
  expect(((await cfg.json()) as { env: unknown }).env).toEqual({
@@ -443,17 +443,7 @@ export const RUNTIME_TOKEN_DENYLIST: readonly ToolsTokenPolicyRule[] = [
443
443
  RD("DELETE", "/agents/{id}/crons/{cronId}", "cron delete"),
444
444
  ];
445
445
 
446
- /** Env var: `enforce` (default) or `off` (runtime-kind tokens unrestricted). */
447
- export const RUNTIME_TOKEN_POLICY_ENV = "SHIPWRIGHT_RUNTIME_TOKEN_POLICY";
448
-
449
- /** Read on every call, so flipping the var needs no restart of anything else. */
450
- export function isRuntimePolicyEnforced(
451
- env: Record<string, string | undefined> = process.env,
452
- ): boolean {
453
- return env[RUNTIME_TOKEN_POLICY_ENV]?.trim().toLowerCase() !== "off";
454
- }
455
-
456
- /** Pure decision for a runtime-kind caller (ignores the kill switch). */
446
+ /** Pure decision for a runtime-kind caller . */
457
447
  export function runtimeTokenDecision(
458
448
  method: string,
459
449
  path: string,
@@ -467,12 +457,7 @@ export function runtimeTokenDecision(
467
457
  * Enforcement helper: true (and one log line) when a runtime-kind token must
468
458
  * be denied on method+path. The log line is read by the observation gate.
469
459
  */
470
- export function runtimeTokenDenied(
471
- method: string,
472
- path: string,
473
- env: Record<string, string | undefined> = process.env,
474
- ): boolean {
475
- if (!isRuntimePolicyEnforced(env)) return false;
460
+ export function runtimeTokenDenied(method: string, path: string): boolean {
476
461
  if (runtimeTokenDecision(method, path) !== D) return false;
477
462
  console.warn(
478
463
  `[token-policy] runtime token denied ${method.toUpperCase()} ${JSON.stringify(path)}`,
@@ -12,7 +12,6 @@ import {
12
12
  blankEnvForToolsToken,
13
13
  createToolsTokenGuard,
14
14
  isPluginScriptPreCheck,
15
- isRuntimePolicyEnforced,
16
15
  RUNTIME_TOKEN_DENYLIST,
17
16
  ruleMatches,
18
17
  runtimeTokenDecision,
@@ -329,39 +328,22 @@ describe("runtime-kind denylist", () => {
329
328
  for (const r of RUNTIME_TOKEN_DENYLIST) expect(r.decision).toBe("deny");
330
329
  });
331
330
 
332
- describe("kill switch and logging", () => {
331
+ describe("denial logging", () => {
333
332
  afterEach(() => spyOn(console, "warn").mockRestore());
334
- it("defaults to enforce; only `off` disables", () => {
335
- expect(isRuntimePolicyEnforced({})).toBe(true);
336
- expect(
337
- isRuntimePolicyEnforced({ SHIPWRIGHT_RUNTIME_TOKEN_POLICY: "enforce" }),
338
- ).toBe(true);
339
- expect(
340
- isRuntimePolicyEnforced({ SHIPWRIGHT_RUNTIME_TOKEN_POLICY: "garbage" }),
341
- ).toBe(true);
342
- expect(
343
- isRuntimePolicyEnforced({ SHIPWRIGHT_RUNTIME_TOKEN_POLICY: "off" }),
344
- ).toBe(false);
345
- });
346
- it("logs one line per denial and nothing when off or allowed", () => {
333
+ it("logs one line per denial and nothing when allowed", () => {
347
334
  const warn = spyOn(console, "warn").mockImplementation(() => {});
348
- expect(runtimeTokenDenied("post", `/agents/${ID}/envs`, {})).toBe(true);
335
+ expect(runtimeTokenDenied("post", `/agents/${ID}/envs`)).toBe(true);
349
336
  expect(warn).toHaveBeenCalledTimes(1);
350
337
  expect(warn.mock.calls[0]?.[0]).toBe(
351
338
  `[token-policy] runtime token denied POST "/agents/${ID}/envs"`,
352
339
  );
353
- expect(
354
- runtimeTokenDenied("POST", `/agents/${ID}/envs`, {
355
- SHIPWRIGHT_RUNTIME_TOKEN_POLICY: "off",
356
- }),
357
- ).toBe(false);
358
- expect(runtimeTokenDenied("GET", `/agents/${ID}/config`, {})).toBe(false);
340
+ expect(runtimeTokenDenied("GET", `/agents/${ID}/config`)).toBe(false);
359
341
  expect(warn).toHaveBeenCalledTimes(1);
360
342
  });
361
343
  it("escapes control characters in the logged path (no log forging)", () => {
362
344
  const warn = spyOn(console, "warn").mockImplementation(() => {});
363
345
  const path = `/agents/${ID}/envs/x\n[token-policy] runtime token denied POST /forged`;
364
- expect(runtimeTokenDenied("DELETE", path, {})).toBe(true);
346
+ expect(runtimeTokenDenied("DELETE", path)).toBe(true);
365
347
  expect(warn).toHaveBeenCalledTimes(1);
366
348
  const msg = String(warn.mock.calls[0]?.[0]);
367
349
  expect(msg).not.toContain("\n");
@@ -371,10 +353,7 @@ describe("runtime-kind denylist", () => {
371
353
  });
372
354
 
373
355
  describe("runtime-kind enforcement points", () => {
374
- const prev = process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
375
356
  afterEach(() => {
376
- if (prev === undefined) delete process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
377
- else process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY = prev;
378
357
  spyOn(console, "warn").mockRestore();
379
358
  });
380
359
  const mk = (guard: boolean) => {
@@ -392,10 +371,9 @@ describe("runtime-kind enforcement points", () => {
392
371
  return app;
393
372
  };
394
373
  for (const guard of [false, true]) {
395
- it(`${guard ? "guard" : "auth middleware"}: 403 on denied, 200 on allowed, switch off restores`, async () => {
374
+ it(`${guard ? "guard" : "auth middleware"}: 403 on denied, 200 on allowed on allowed`, async () => {
396
375
  spyOn(console, "warn").mockImplementation(() => {});
397
376
  const app = mk(guard);
398
- delete process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY;
399
377
  expect(
400
378
  (await call(app, RUNTIME_KEY, "POST", `/agents/${ID}/tokens`)).status,
401
379
  ).toBe(403);
@@ -403,10 +381,6 @@ describe("runtime-kind enforcement points", () => {
403
381
  (await call(app, RUNTIME_KEY, "POST", `/agents/${ID}/crons/reconcile`))
404
382
  .status,
405
383
  ).toBe(200);
406
- process.env.SHIPWRIGHT_RUNTIME_TOKEN_POLICY = "off";
407
- expect(
408
- (await call(app, RUNTIME_KEY, "POST", `/agents/${ID}/tokens`)).status,
409
- ).toBe(200);
410
384
  });
411
385
  }
412
386
  });