@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.
@@ -0,0 +1,279 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { Hono } from "hono";
3
+ import {
4
+ type AdminExtension,
5
+ type AdminExtensionContext,
6
+ resolveAdminExtensions,
7
+ } from "./admin-extension.ts";
8
+ import { createAdminAuthMiddleware } from "./api-auth.ts";
9
+ import { ForbiddenError } from "./errors.ts";
10
+ import {
11
+ assertToolsTokenPreCheck,
12
+ blankEnvForToolsToken,
13
+ createToolsTokenGuard,
14
+ isPluginScriptPreCheck,
15
+ ruleMatches,
16
+ TOOLS_TOKEN_POLICY,
17
+ type ToolsTokenPolicyRule,
18
+ toolsTokenDecision,
19
+ } from "./tools-token-policy.ts";
20
+
21
+ const ID = "agent-1";
22
+ const ctx = { env: {} } as unknown as AdminExtensionContext;
23
+
24
+ describe("toolsTokenDecision", () => {
25
+ const denied: Array<[string, string]> = [
26
+ ["POST", `/agents/${ID}/tokens`],
27
+ ["GET", `/agents/${ID}/tokens`],
28
+ ["DELETE", `/agents/${ID}/tokens/t1`],
29
+ ["POST", `/agents/${ID}/envs`],
30
+ ["PATCH", `/agents/${ID}/envs`],
31
+ ["DELETE", `/agents/${ID}/envs/FOO`],
32
+ ["POST", `/agents/${ID}/tools`],
33
+ ["PATCH", `/agents/${ID}/tools/t1`],
34
+ ["DELETE", `/agents/${ID}/tools/t1`],
35
+ ["POST", `/agents/${ID}/plugins`],
36
+ ["PATCH", `/agents/${ID}/plugins`],
37
+ ["DELETE", `/agents/${ID}/plugins`],
38
+ ["POST", `/agents/${ID}/marketplaces`],
39
+ ["DELETE", `/agents/${ID}/marketplaces/m1`],
40
+ ];
41
+ for (const [method, path] of denied) {
42
+ it(`denies ${method} ${path}`, () => {
43
+ expect(toolsTokenDecision(method, path)).toBe("deny");
44
+ });
45
+ }
46
+
47
+ const allowed: Array<[string, string]> = [
48
+ ["GET", `/agents/${ID}/config`],
49
+ ["GET", `/agents/${ID}/envs`],
50
+ ["GET", `/agents/${ID}/crons`],
51
+ ["POST", `/agents/${ID}/crons`],
52
+ ["PATCH", `/agents/${ID}/crons/c1`],
53
+ ["GET", `/agents/${ID}/crons/c1/runs`],
54
+ ["GET", `/agents/${ID}/tools`],
55
+ ["GET", `/agents/${ID}/plugins`],
56
+ ["GET", `/agents/${ID}/marketplaces`],
57
+ ];
58
+ for (const [method, path] of allowed) {
59
+ it(`allows ${method} ${path}`, () => {
60
+ expect(toolsTokenDecision(method, path)).toBe("allow");
61
+ });
62
+ }
63
+
64
+ it("normalizes trailing slashes, repeated slashes and encoding", () => {
65
+ expect(toolsTokenDecision("POST", `/agents/${ID}/tokens/`)).toBe("deny");
66
+ expect(toolsTokenDecision("POST", `/agents//${ID}//tokens`)).toBe("deny");
67
+ expect(toolsTokenDecision("POST", `/agents/${ID}/%74okens`)).toBe("deny");
68
+ });
69
+
70
+ it("is case-insensitive on the method and a route with no rule is allowed", () => {
71
+ expect(toolsTokenDecision("post", `/agents/${ID}/tokens`)).toBe("deny");
72
+ expect(toolsTokenDecision("GET", `/agents/${ID}/something-new`)).toBe(
73
+ "allow",
74
+ );
75
+ });
76
+
77
+ it("every table entry has a unique method+path key", () => {
78
+ const keys = TOOLS_TOKEN_POLICY.map((r) => `${r.method} ${r.path}`);
79
+ expect(new Set(keys).size).toBe(keys.length);
80
+ });
81
+
82
+ it("ruleMatches treats {param} as exactly one segment", () => {
83
+ const rule: ToolsTokenPolicyRule = {
84
+ method: "GET",
85
+ path: "/agents/{id}/x",
86
+ decision: "deny",
87
+ };
88
+ expect(ruleMatches(rule, "GET", "/agents/a/x")).toBe(true);
89
+ expect(ruleMatches(rule, "GET", "/agents/a/b/x")).toBe(false);
90
+ expect(ruleMatches(rule, "GET", "/agents/a/x/y")).toBe(false);
91
+ expect(
92
+ ruleMatches({ ...rule, subpaths: true }, "GET", "/agents/a/x/y"),
93
+ ).toBe(true);
94
+ });
95
+ });
96
+
97
+ describe("preCheck pattern", () => {
98
+ for (const ok of ["plugin:script", "my-plugin:check_1.sh", "A9:b.c-d_e"]) {
99
+ it(`accepts ${ok}`, () => expect(isPluginScriptPreCheck(ok)).toBe(true));
100
+ }
101
+ for (const bad of [
102
+ "",
103
+ "script",
104
+ "plugin:",
105
+ ":script",
106
+ "/usr/bin/true",
107
+ "./check.sh",
108
+ "../x:y",
109
+ "..:x",
110
+ "x:..",
111
+ ".:x",
112
+ "x:.",
113
+ "plugin/x:script",
114
+ "plugin:dir/script",
115
+ "a:b:c",
116
+ "plugin:script arg",
117
+ "plugin:script;rm",
118
+ "plugin:script\n",
119
+ "plug in:script",
120
+ ]) {
121
+ it(`rejects ${JSON.stringify(bad)}`, () =>
122
+ expect(isPluginScriptPreCheck(bad)).toBe(false));
123
+ }
124
+
125
+ const tools = { kind: "agent", agentId: ID, tokenKind: "tools" } as const;
126
+ const runtime = { kind: "agent", agentId: ID, tokenKind: "runtime" } as const;
127
+ it("403s a tools-kind caller with a path-form preCheck only", () => {
128
+ expect(() => assertToolsTokenPreCheck(tools, "/bin/sh")).toThrow(
129
+ ForbiddenError,
130
+ );
131
+ expect(() => assertToolsTokenPreCheck(tools, "p:s")).not.toThrow();
132
+ expect(() => assertToolsTokenPreCheck(tools, null)).not.toThrow();
133
+ expect(() => assertToolsTokenPreCheck(tools, undefined)).not.toThrow();
134
+ });
135
+ it("leaves runtime, admin and unset scopes alone", () => {
136
+ expect(() => assertToolsTokenPreCheck(runtime, "/bin/sh")).not.toThrow();
137
+ expect(() =>
138
+ assertToolsTokenPreCheck({ kind: "admin" }, "/bin/sh"),
139
+ ).not.toThrow();
140
+ expect(() => assertToolsTokenPreCheck(undefined, "/bin/sh")).not.toThrow();
141
+ });
142
+ });
143
+
144
+ describe("blankEnvForToolsToken", () => {
145
+ it("blanks env for tools-kind only", () => {
146
+ const env = { A: "1" };
147
+ expect(
148
+ blankEnvForToolsToken({ kind: "agent", tokenKind: "tools" }, env),
149
+ ).toEqual({});
150
+ expect(
151
+ blankEnvForToolsToken({ kind: "agent", tokenKind: "runtime" }, env),
152
+ ).toBe(env);
153
+ expect(blankEnvForToolsToken({ kind: "admin" }, env)).toBe(env);
154
+ expect(blankEnvForToolsToken(undefined, env)).toBe(env);
155
+ });
156
+ });
157
+
158
+ describe("AdminExtension.toolsTokenPolicy hook", () => {
159
+ const ext: AdminExtension = {
160
+ toolsTokenPolicy: () => [
161
+ { method: "PUT", path: "/agents/{id}/widgets/{w}", decision: "deny" },
162
+ { method: "GET", path: "/agents/{id}/widgets", decision: "allow" },
163
+ { method: "POST", path: "/agents/{id}/config", decision: "allow" },
164
+ ],
165
+ };
166
+ const resolved = resolveAdminExtensions([ext, {}], ctx).toolsTokenPolicy;
167
+
168
+ it("is optional: extensions without it resolve to no rules", () => {
169
+ expect(resolveAdminExtensions([{}], ctx).toolsTokenPolicy).toEqual([]);
170
+ });
171
+
172
+ it("collects declared rules across extensions", () => {
173
+ expect(resolved).toHaveLength(3);
174
+ });
175
+
176
+ it("declared deny blocks, undeclared extension routes are allowed", () => {
177
+ expect(
178
+ toolsTokenDecision("PUT", `/agents/${ID}/widgets/w1`, resolved),
179
+ ).toBe("deny");
180
+ expect(toolsTokenDecision("PUT", `/agents/${ID}/other/w1`, resolved)).toBe(
181
+ "allow",
182
+ );
183
+ expect(toolsTokenDecision("GET", `/agents/${ID}/widgets`, resolved)).toBe(
184
+ "allow",
185
+ );
186
+ });
187
+
188
+ it("an extension allow cannot lift a platform deny", () => {
189
+ expect(
190
+ toolsTokenDecision("POST", `/agents/${ID}/tokens`, [
191
+ { method: "POST", path: "/agents/{id}/tokens", decision: "allow" },
192
+ ]),
193
+ ).toBe("deny");
194
+ });
195
+ });
196
+
197
+ const TOOLS_KEY = "tools-key";
198
+ const RUNTIME_KEY = "runtime-key";
199
+ const tokenService = {
200
+ validate: async (raw: string) =>
201
+ raw === TOOLS_KEY
202
+ ? { agentId: ID, kind: "tools" as const }
203
+ : raw === RUNTIME_KEY
204
+ ? { agentId: ID, kind: "runtime" as const }
205
+ : null,
206
+ };
207
+ const extensionRules: ToolsTokenPolicyRule[] = [
208
+ { method: "PUT", path: "/agents/{id}/widgets/{w}", decision: "deny" },
209
+ ];
210
+
211
+ function call(app: Hono, token: string | null, method: string, path: string) {
212
+ return app.request(path, {
213
+ method,
214
+ headers: token ? { Authorization: `Bearer ${token}` } : {},
215
+ });
216
+ }
217
+
218
+ describe("createAdminAuthMiddleware tools-token policy", () => {
219
+ const app = new Hono();
220
+ app.use(
221
+ "/agents/*",
222
+ createAdminAuthMiddleware({
223
+ sessionSecret: "s".repeat(32),
224
+ agentTokenService: tokenService,
225
+ toolsTokenPolicy: extensionRules,
226
+ }),
227
+ );
228
+ app.all("/agents/*", (c) => c.json({ ok: true }));
229
+
230
+ it("403s a tools token on a denied route and on a declared extension deny", async () => {
231
+ expect(
232
+ (await call(app, TOOLS_KEY, "POST", `/agents/${ID}/tokens`)).status,
233
+ ).toBe(403);
234
+ expect(
235
+ (await call(app, TOOLS_KEY, "PUT", `/agents/${ID}/widgets/w`)).status,
236
+ ).toBe(403);
237
+ });
238
+ it("allows reads, undeclared extension routes, and runtime tokens everywhere", async () => {
239
+ expect(
240
+ (await call(app, TOOLS_KEY, "GET", `/agents/${ID}/envs`)).status,
241
+ ).toBe(200);
242
+ expect(
243
+ (await call(app, TOOLS_KEY, "PUT", `/agents/${ID}/gadgets/g`)).status,
244
+ ).toBe(200);
245
+ expect(
246
+ (await call(app, RUNTIME_KEY, "POST", `/agents/${ID}/tokens`)).status,
247
+ ).toBe(200);
248
+ expect(
249
+ (await call(app, RUNTIME_KEY, "PUT", `/agents/${ID}/widgets/w`)).status,
250
+ ).toBe(200);
251
+ });
252
+ });
253
+
254
+ describe("createToolsTokenGuard (extension routes)", () => {
255
+ const app = new Hono();
256
+ app.use(
257
+ "/agents/*",
258
+ createToolsTokenGuard({
259
+ agentTokenService: tokenService,
260
+ adminApiKeys: new Map([["admin-key", { name: "a", scope: "*" }]]),
261
+ extensionRules,
262
+ }),
263
+ );
264
+ app.all("/agents/*", (c) => c.json({ ok: true }));
265
+
266
+ it("403s only tools-kind bearers on denied routes", async () => {
267
+ const path = `/agents/${ID}/widgets/w`;
268
+ expect((await call(app, TOOLS_KEY, "PUT", path)).status).toBe(403);
269
+ expect((await call(app, RUNTIME_KEY, "PUT", path)).status).toBe(200);
270
+ expect((await call(app, "admin-key", "PUT", path)).status).toBe(200);
271
+ expect((await call(app, "bogus", "PUT", path)).status).toBe(200);
272
+ expect((await call(app, null, "PUT", path)).status).toBe(200);
273
+ });
274
+ it("allows undeclared extension routes for tools tokens", async () => {
275
+ expect(
276
+ (await call(app, TOOLS_KEY, "PUT", `/agents/${ID}/gadgets/g`)).status,
277
+ ).toBe(200);
278
+ });
279
+ });