@terreno/admin-backend 0.3.2 → 0.4.2

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,311 @@
1
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
+ import {
3
+ addAuthRoutes,
4
+ apiErrorMiddleware,
5
+ apiUnauthorizedMiddleware,
6
+ BackgroundTask,
7
+ setupAuth,
8
+ } from "@terreno/api";
9
+ import {authAsUser, getBaseServer, setupDb, UserModel} from "@terreno/api/src/tests";
10
+ import type express from "express";
11
+ import supertest from "supertest";
12
+ import type TestAgent from "supertest/lib/agent";
13
+
14
+ import {AdminApp} from "./adminApp";
15
+
16
+ const createTestScript = (overrides?: {runner?: any; name?: string; description?: string}) => ({
17
+ description: overrides?.description ?? "A test script",
18
+ name: overrides?.name ?? "test-script",
19
+ runner:
20
+ overrides?.runner ??
21
+ (async (wetRun: boolean) => ({
22
+ results: [`Ran in ${wetRun ? "wet" : "dry"} mode`],
23
+ success: true,
24
+ })),
25
+ });
26
+
27
+ const createSlowScript = () => ({
28
+ description: "A slow script for testing async behavior",
29
+ name: "slow-script",
30
+ runner: async (_wetRun: boolean) => {
31
+ await new Promise((resolve) => setTimeout(resolve, 200));
32
+ return {results: ["Done"], success: true};
33
+ },
34
+ });
35
+
36
+ const createFailingScript = () => ({
37
+ description: "A script that throws",
38
+ name: "failing-script",
39
+ runner: async () => {
40
+ throw new Error("Script exploded");
41
+ },
42
+ });
43
+
44
+ const buildApp = (scripts = [createTestScript()]): express.Application => {
45
+ const app = getBaseServer();
46
+ setupAuth(app, UserModel as any);
47
+ addAuthRoutes(app, UserModel as any);
48
+
49
+ const admin = new AdminApp({
50
+ basePath: "/admin",
51
+ models: [],
52
+ scripts,
53
+ });
54
+ admin.register(app);
55
+
56
+ // Error middleware must come after routes
57
+ app.use(apiUnauthorizedMiddleware);
58
+ app.use(apiErrorMiddleware);
59
+
60
+ return app;
61
+ };
62
+
63
+ /** Wait long enough for async scripts to settle before cleanup. */
64
+ const waitForScripts = () => new Promise((resolve) => setTimeout(resolve, 500));
65
+
66
+ describe("AdminApp script routes", () => {
67
+ let app: express.Application;
68
+ let adminAgent: TestAgent;
69
+ let notAdminAgent: TestAgent;
70
+
71
+ afterEach(async () => {
72
+ // Wait for any async script runners to finish before deleting tasks
73
+ await waitForScripts();
74
+ await BackgroundTask.deleteMany({});
75
+ });
76
+
77
+ describe("POST /admin/scripts/:name/run", () => {
78
+ beforeEach(async () => {
79
+ await setupDb();
80
+ app = buildApp();
81
+ adminAgent = await authAsUser(app, "admin");
82
+ notAdminAgent = await authAsUser(app, "notAdmin");
83
+ });
84
+
85
+ it("starts a script and returns a taskId", async () => {
86
+ const res = await adminAgent.post("/admin/scripts/test-script/run").expect(201);
87
+
88
+ expect(res.body.taskId).toBeDefined();
89
+ expect(typeof res.body.taskId).toBe("string");
90
+
91
+ // Verify the task was created in the database
92
+ const task = await BackgroundTask.findById(res.body.taskId);
93
+ expect(task).not.toBeNull();
94
+ expect(task!.taskType).toBe("test-script");
95
+ expect(task!.isDryRun).toBe(true);
96
+ });
97
+
98
+ it("creates a wet run task when wetRun=true", async () => {
99
+ const res = await adminAgent.post("/admin/scripts/test-script/run?wetRun=true").expect(201);
100
+
101
+ const task = await BackgroundTask.findById(res.body.taskId);
102
+ expect(task).not.toBeNull();
103
+ expect(task!.isDryRun).toBe(false);
104
+ });
105
+
106
+ it("creates a dry run task by default", async () => {
107
+ const res = await adminAgent.post("/admin/scripts/test-script/run").expect(201);
108
+
109
+ const task = await BackgroundTask.findById(res.body.taskId);
110
+ expect(task).not.toBeNull();
111
+ expect(task!.isDryRun).toBe(true);
112
+ });
113
+
114
+ it("returns 404 for unknown script", async () => {
115
+ const res = await adminAgent.post("/admin/scripts/nonexistent/run").expect(404);
116
+
117
+ expect(res.body.title).toInclude("Script not found");
118
+ });
119
+
120
+ it("returns 403 for non-admin user", async () => {
121
+ const res = await notAdminAgent.post("/admin/scripts/test-script/run").expect(403);
122
+
123
+ expect(res.body.title).toInclude("Only admins can run scripts");
124
+ });
125
+
126
+ it("returns 401 for unauthenticated user", async () => {
127
+ const unauthAgent = supertest(app);
128
+ await unauthAgent.post("/admin/scripts/test-script/run").expect(401);
129
+ });
130
+
131
+ it("records initial log with admin name", async () => {
132
+ const res = await adminAgent.post("/admin/scripts/test-script/run").expect(201);
133
+
134
+ const task = await BackgroundTask.findById(res.body.taskId);
135
+ expect(task!.logs).toHaveLength(1);
136
+ expect(task!.logs[0].level).toBe("info");
137
+ expect(task!.logs[0].message).toInclude("Script started by");
138
+ });
139
+
140
+ it("completes the task asynchronously with results", async () => {
141
+ const res = await adminAgent.post("/admin/scripts/test-script/run").expect(201);
142
+
143
+ // Wait for async script execution
144
+ await new Promise((resolve) => setTimeout(resolve, 100));
145
+
146
+ const task = await BackgroundTask.findById(res.body.taskId);
147
+ expect(task!.status).toBe("completed");
148
+ expect(task!.result).toContain("Ran in dry mode");
149
+ expect(task!.completedAt).toBeDefined();
150
+ expect(task!.progress?.percentage).toBe(100);
151
+ });
152
+
153
+ it("marks task as failed when script throws", async () => {
154
+ app = buildApp([createFailingScript()]);
155
+ adminAgent = await authAsUser(app, "admin");
156
+
157
+ const res = await adminAgent.post("/admin/scripts/failing-script/run").expect(201);
158
+
159
+ await new Promise((resolve) => setTimeout(resolve, 100));
160
+
161
+ const task = await BackgroundTask.findById(res.body.taskId);
162
+ expect(task!.status).toBe("failed");
163
+ expect(task?.error).toBe("Script exploded");
164
+ expect(task!.result).toContain("Script exploded");
165
+ });
166
+ });
167
+
168
+ describe("GET /admin/scripts/tasks/:id", () => {
169
+ let taskId: string;
170
+
171
+ beforeEach(async () => {
172
+ await setupDb();
173
+ app = buildApp([createSlowScript()]);
174
+ adminAgent = await authAsUser(app, "admin");
175
+ notAdminAgent = await authAsUser(app, "notAdmin");
176
+
177
+ const res = await adminAgent.post("/admin/scripts/slow-script/run").expect(201);
178
+ taskId = res.body.taskId;
179
+ });
180
+
181
+ it("returns task status for admin", async () => {
182
+ const res = await adminAgent.get(`/admin/scripts/tasks/${taskId}`).expect(200);
183
+
184
+ expect(res.body.task).toBeDefined();
185
+ expect(res.body.task._id).toBe(taskId);
186
+ expect(res.body.task.taskType).toBe("slow-script");
187
+ expect(res.body.task.status).toBeDefined();
188
+ });
189
+
190
+ it("returns 403 for non-admin user", async () => {
191
+ const res = await notAdminAgent.get(`/admin/scripts/tasks/${taskId}`).expect(403);
192
+
193
+ expect(res.body.title).toInclude("Only admins can view tasks");
194
+ });
195
+
196
+ it("returns 404 for nonexistent task", async () => {
197
+ const fakeId = "000000000000000000000000";
198
+ const res = await adminAgent.get(`/admin/scripts/tasks/${fakeId}`).expect(404);
199
+
200
+ expect(res.body.title).toInclude("Task not found");
201
+ });
202
+
203
+ it("returns 400 for invalid task ID", async () => {
204
+ const res = await adminAgent.get("/admin/scripts/tasks/not-a-valid-id").expect(400);
205
+
206
+ expect(res.body.title).toInclude("Invalid task ID");
207
+ });
208
+
209
+ it("shows completed task with results after script finishes", async () => {
210
+ // Wait for the slow script to finish
211
+ await new Promise((resolve) => setTimeout(resolve, 400));
212
+
213
+ const res = await adminAgent.get(`/admin/scripts/tasks/${taskId}`).expect(200);
214
+
215
+ expect(res.body.task.status).toBe("completed");
216
+ expect(res.body.task.result).toContain("Done");
217
+ });
218
+ });
219
+
220
+ describe("DELETE /admin/scripts/tasks/:id", () => {
221
+ beforeEach(async () => {
222
+ await setupDb();
223
+ app = buildApp([createSlowScript()]);
224
+ adminAgent = await authAsUser(app, "admin");
225
+ notAdminAgent = await authAsUser(app, "notAdmin");
226
+ });
227
+
228
+ it("cancels a running task", async () => {
229
+ const res1 = await adminAgent.post("/admin/scripts/slow-script/run").expect(201);
230
+
231
+ const res = await adminAgent.delete(`/admin/scripts/tasks/${res1.body.taskId}`).expect(200);
232
+
233
+ expect(res.body.message).toBe("Task cancelled");
234
+ expect(res.body.task.status).toBe("cancelled");
235
+ expect(res.body.task.completedAt).toBeDefined();
236
+ });
237
+
238
+ it("adds cancellation log entry", async () => {
239
+ const res1 = await adminAgent.post("/admin/scripts/slow-script/run").expect(201);
240
+
241
+ const res = await adminAgent.delete(`/admin/scripts/tasks/${res1.body.taskId}`).expect(200);
242
+
243
+ const logs = res.body.task.logs;
244
+ const cancelLog = logs.find((l: any) => l.message.includes("cancelled"));
245
+ expect(cancelLog).toBeDefined();
246
+ expect(cancelLog.level).toBe("info");
247
+ });
248
+
249
+ it("returns 403 for non-admin user", async () => {
250
+ const res1 = await adminAgent.post("/admin/scripts/slow-script/run").expect(201);
251
+
252
+ const res = await notAdminAgent
253
+ .delete(`/admin/scripts/tasks/${res1.body.taskId}`)
254
+ .expect(403);
255
+
256
+ expect(res.body.title).toInclude("Only admins can cancel tasks");
257
+ });
258
+
259
+ it("returns 400 when cancelling a completed task", async () => {
260
+ const res1 = await adminAgent.post("/admin/scripts/slow-script/run").expect(201);
261
+
262
+ // Wait for task to complete
263
+ await new Promise((resolve) => setTimeout(resolve, 400));
264
+
265
+ const res = await adminAgent.delete(`/admin/scripts/tasks/${res1.body.taskId}`).expect(400);
266
+
267
+ expect(res.body.title).toInclude("Cannot cancel task with status");
268
+ });
269
+
270
+ it("returns 404 for nonexistent task", async () => {
271
+ const fakeId = "000000000000000000000000";
272
+ const res = await adminAgent.delete(`/admin/scripts/tasks/${fakeId}`).expect(404);
273
+
274
+ expect(res.body.title).toInclude("Task not found");
275
+ });
276
+
277
+ it("returns 400 for invalid task ID", async () => {
278
+ const res = await adminAgent.delete("/admin/scripts/tasks/not-a-valid-id").expect(400);
279
+
280
+ expect(res.body.title).toInclude("Invalid task ID");
281
+ });
282
+ });
283
+
284
+ describe("GET /admin/config with scripts", () => {
285
+ beforeEach(async () => {
286
+ await setupDb();
287
+ app = buildApp([
288
+ createTestScript({description: "Migrate old data", name: "migrate-data"}),
289
+ createTestScript({description: "Clean up orphans", name: "cleanup"}),
290
+ ]);
291
+ adminAgent = await authAsUser(app, "admin");
292
+ });
293
+
294
+ it("includes scripts in config response", async () => {
295
+ const res = await supertest(app).get("/admin/config").expect(200);
296
+
297
+ expect(res.body.scripts).toHaveLength(2);
298
+ expect(res.body.scripts[0].name).toBe("migrate-data");
299
+ expect(res.body.scripts[0].description).toBe("Migrate old data");
300
+ expect(res.body.scripts[1].name).toBe("cleanup");
301
+ expect(res.body.scripts[1].description).toBe("Clean up orphans");
302
+ });
303
+
304
+ it("returns empty scripts array when no scripts configured", async () => {
305
+ app = buildApp([]);
306
+ const res = await supertest(app).get("/admin/config").expect(200);
307
+
308
+ expect(res.body.scripts).toHaveLength(0);
309
+ });
310
+ });
311
+ });