@terreno/admin-backend 0.20.2 → 0.21.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.
@@ -3,6 +3,7 @@ import {
3
3
  addAuthRoutes,
4
4
  apiErrorMiddleware,
5
5
  apiUnauthorizedMiddleware,
6
+ BackgroundTask,
6
7
  setupAuth,
7
8
  type UserModel as UserModelType,
8
9
  VersionConfig,
@@ -19,10 +20,13 @@ import type express from "express";
19
20
  import supertest from "supertest";
20
21
  import type TestAgent from "supertest/lib/agent";
21
22
 
22
- import type {AdminModelConfig} from "./adminApp";
23
+ import type {AdminAuditEvent, AdminModelConfig, AdminOptions} from "./adminApp";
23
24
  import {AdminApp} from "./adminApp";
24
25
 
25
- const buildApp = (models: AdminModelConfig[] = []): express.Application => {
26
+ const buildApp = (
27
+ models: AdminModelConfig[] = [],
28
+ adminOverrides?: Partial<AdminOptions>
29
+ ): express.Application => {
26
30
  const app = getBaseServer();
27
31
  setupAuth(app, UserModel as unknown as UserModelType);
28
32
  addAuthRoutes(app, UserModel as unknown as UserModelType);
@@ -30,6 +34,7 @@ const buildApp = (models: AdminModelConfig[] = []): express.Application => {
30
34
  const admin = new AdminApp({
31
35
  basePath: "/admin",
32
36
  models,
37
+ ...adminOverrides,
33
38
  });
34
39
  admin.register(app);
35
40
 
@@ -73,6 +78,9 @@ describe("AdminApp /admin/config", () => {
73
78
  it("returns metadata for configured models to admins", async () => {
74
79
  const res = await adminAgent.get("/admin/config").expect(200);
75
80
 
81
+ expect(res.body.schemaVersion).toBe(2);
82
+ expect(res.body.home?.title).toBe("Administration");
83
+ expect(res.body.home?.slots?.main).toEqual(["modelsGrid"]);
76
84
  expect(res.body.models).toHaveLength(1);
77
85
  const [foodMeta] = res.body.models;
78
86
  expect(foodMeta.name).toBe("Food");
@@ -83,6 +91,13 @@ describe("AdminApp /admin/config", () => {
83
91
  expect(foodMeta.fieldOrder).toEqual(["name", "calories", "tags"]);
84
92
  });
85
93
 
94
+ it("includes recordTitleField in config when set on the model", async () => {
95
+ const appWithTitle = buildApp([{...foodModelConfig, recordTitleField: "name"}]);
96
+ const agent = await authAsUser(appWithTitle, "admin");
97
+ const res = await agent.get("/admin/config").expect(200);
98
+ expect(res.body.models[0].recordTitleField).toBe("name");
99
+ });
100
+
86
101
  it("applies fieldOverrides to generated config", async () => {
87
102
  const res = await adminAgent.get("/admin/config").expect(200);
88
103
  const [foodMeta] = res.body.models;
@@ -179,6 +194,19 @@ describe("AdminApp /admin/config", () => {
179
194
  {displayName: "Version Config", name: "version-config"},
180
195
  ]);
181
196
  });
197
+
198
+ it("normalizes home.slots so recentActivity is last in sidebar", async () => {
199
+ app = buildApp([foodModelConfig], {
200
+ home: {
201
+ slots: {sidebar: ["recentActivity", "versionConfig"]},
202
+ title: "Ops",
203
+ },
204
+ });
205
+ const agent = await authAsUser(app, "admin");
206
+ const res = await agent.get("/admin/config").expect(200);
207
+ expect(res.body.home.title).toBe("Ops");
208
+ expect(res.body.home.slots.sidebar).toEqual(["versionConfig", "recentActivity"]);
209
+ });
182
210
  });
183
211
 
184
212
  describe("AdminApp model CRUD routes", () => {
@@ -477,3 +505,257 @@ describe("AdminApp with scripts that use context", () => {
477
505
  expect(task?.progress?.percentage).toBe(100);
478
506
  });
479
507
  });
508
+
509
+ describe("AdminApp admin UI v2 routes", () => {
510
+ let app: express.Application;
511
+ let adminAgent: TestAgent;
512
+ let notAdminAgent: TestAgent;
513
+
514
+ beforeEach(async () => {
515
+ await setupDb();
516
+ app = buildApp([{...foodModelConfig, hiddenFields: ["hidden"]}]);
517
+ adminAgent = await authAsUser(app, "admin");
518
+ notAdminAgent = await authAsUser(app, "notAdmin");
519
+ });
520
+
521
+ afterEach(async () => {
522
+ await FoodModel.deleteMany({});
523
+ await BackgroundTask.deleteMany({});
524
+ });
525
+
526
+ it("rejects bulk-patch with an empty ids array", async () => {
527
+ const res = await adminAgent
528
+ .post("/admin/foods/bulk-patch")
529
+ .send({ids: [], patch: {calories: 1}})
530
+ .expect(400);
531
+ expect(res.body.title).toInclude("at least one");
532
+ });
533
+
534
+ it("bulk-patches allowlisted fields for many ids", async () => {
535
+ const a = await FoodModel.create({calories: 1, name: "A"});
536
+ const b = await FoodModel.create({calories: 2, name: "B"});
537
+ const res = await adminAgent
538
+ .post("/admin/foods/bulk-patch")
539
+ .send({
540
+ ids: [String(a._id), String(b._id)],
541
+ patch: {calories: 50},
542
+ })
543
+ .expect(200);
544
+ expect(res.body.updated).toBe(2);
545
+ expect(res.body.failures).toBeUndefined();
546
+ const updated = await FoodModel.find({_id: {$in: [a._id, b._id]}})
547
+ .lean()
548
+ .exec();
549
+ for (const row of updated) {
550
+ expect(row.calories).toBe(50);
551
+ }
552
+ });
553
+
554
+ it("rejects bulk-patch with more than 1000 ids", async () => {
555
+ const ids = Array.from({length: 1001}, (_, index) => index.toString(16).padStart(24, "0"));
556
+ const res = await adminAgent
557
+ .post("/admin/foods/bulk-patch")
558
+ .send({ids, patch: {calories: 1}})
559
+ .expect(400);
560
+ expect(res.body.title).toInclude("1000");
561
+ });
562
+
563
+ it("rejects bulk-patch keys outside the allowlist", async () => {
564
+ const a = await FoodModel.create({calories: 1, name: "A"});
565
+ const res = await adminAgent
566
+ .post("/admin/foods/bulk-patch")
567
+ .send({
568
+ ids: [String(a._id)],
569
+ patch: {thisFieldIsNotAllowlisted: true},
570
+ })
571
+ .expect(400);
572
+ expect(res.body.title).toInclude("allowlisted");
573
+ });
574
+
575
+ it("enqueues a background task and returns taskId", async () => {
576
+ const res = await adminAgent
577
+ .post("/admin/background-tasks")
578
+ .send({kind: "reindex-search", metadata: {scope: "foods"}})
579
+ .expect(201);
580
+ expect(typeof res.body.taskId).toBe("string");
581
+ const task = await BackgroundTask.findById(res.body.taskId);
582
+ expect(task?.taskType).toBe("reindex-search");
583
+ expect(task?.status).toBe("pending");
584
+ });
585
+
586
+ it("returns 403 for background-tasks when not admin", async () => {
587
+ await notAdminAgent.post("/admin/background-tasks").send({kind: "x"}).expect(403);
588
+ });
589
+
590
+ it("strips readonly fields from PATCH updates", async () => {
591
+ app = buildApp([
592
+ {
593
+ ...foodModelConfig,
594
+ readonlyFields: ["name"],
595
+ },
596
+ ]);
597
+ const agent = await authAsUser(app, "admin");
598
+ const food = await FoodModel.create({calories: 10, name: "KeepMe"});
599
+ await agent.patch(`/admin/foods/${food._id}`).send({calories: 99, name: "Changed"}).expect(200);
600
+ const reRead = await FoodModel.findById(food._id).lean();
601
+ expect(reRead?.name).toBe("KeepMe");
602
+ expect(reRead?.calories).toBe(99);
603
+ });
604
+
605
+ it("strips readonly fields from POST create", async () => {
606
+ app = buildApp([
607
+ {
608
+ ...foodModelConfig,
609
+ readonlyFields: ["name"],
610
+ },
611
+ ]);
612
+ const agent = await authAsUser(app, "admin");
613
+ const res = await agent
614
+ .post("/admin/foods")
615
+ .send({calories: 5, name: "IgnoredName"})
616
+ .expect(201);
617
+ expect(res.body.data.name).toBeUndefined();
618
+ expect(res.body.data.calories).toBe(5);
619
+ const stored = await FoodModel.findById(res.body.data._id).lean();
620
+ expect(stored?.name).toBeUndefined();
621
+ expect(stored?.calories).toBe(5);
622
+ });
623
+
624
+ it("disables DELETE when permissions.delete is false", async () => {
625
+ app = buildApp([
626
+ {
627
+ ...foodModelConfig,
628
+ permissions: {delete: false},
629
+ },
630
+ ]);
631
+ const agent = await authAsUser(app, "admin");
632
+ const food = await FoodModel.create({calories: 1, name: "Nope"});
633
+ const res = await agent.delete(`/admin/foods/${food._id}`);
634
+ expect([403, 405]).toContain(res.status);
635
+ });
636
+ });
637
+
638
+ describe("AdminApp onAdminAudit", () => {
639
+ let app: express.Application;
640
+ let adminAgent: TestAgent;
641
+ const auditEvents: AdminAuditEvent[] = [];
642
+
643
+ beforeEach(async () => {
644
+ await setupDb();
645
+ auditEvents.length = 0;
646
+ app = buildApp([{...foodModelConfig, hiddenFields: ["hidden"]}], {
647
+ onAdminAudit: async (event): Promise<void> => {
648
+ auditEvents.push(event);
649
+ },
650
+ });
651
+ adminAgent = await authAsUser(app, "admin");
652
+ });
653
+
654
+ afterEach(async () => {
655
+ await FoodModel.deleteMany({});
656
+ });
657
+
658
+ it("invokes onAdminAudit with verb created after POST", async () => {
659
+ await adminAgent.post("/admin/foods").send({calories: 5, name: "Audited"}).expect(201);
660
+ expect(auditEvents.some((e) => e.verb === "created" && e.modelName === "Food")).toBe(true);
661
+ });
662
+
663
+ it("invokes onAdminAudit with verb updated after PATCH", async () => {
664
+ const food = await FoodModel.create({calories: 10, name: "PatchMe"});
665
+ await adminAgent.patch(`/admin/foods/${food._id}`).send({calories: 42}).expect(200);
666
+ expect(auditEvents.some((e) => e.verb === "updated" && e.modelName === "Food")).toBe(true);
667
+ });
668
+
669
+ it("invokes onAdminAudit with verb deleted after DELETE", async () => {
670
+ const food = await FoodModel.create({calories: 1, name: "DeleteMe"});
671
+ await adminAgent.delete(`/admin/foods/${food._id}`).expect(204);
672
+ expect(auditEvents.some((e) => e.verb === "deleted" && e.modelName === "Food")).toBe(true);
673
+ });
674
+ });
675
+
676
+ describe("AdminApp onAdminAudit is best-effort", () => {
677
+ beforeEach(async () => {
678
+ await setupDb();
679
+ });
680
+
681
+ afterEach(async () => {
682
+ await FoodModel.deleteMany({});
683
+ });
684
+
685
+ const throwingAudit = {
686
+ onAdminAudit: async (): Promise<void> => {
687
+ throw new Error("audit sink failure");
688
+ },
689
+ };
690
+
691
+ it("returns 201 on POST when onAdminAudit throws", async () => {
692
+ const localApp = buildApp([foodModelConfig], throwingAudit);
693
+ const agent = await authAsUser(localApp, "admin");
694
+ const res = await agent
695
+ .post("/admin/foods")
696
+ .send({calories: 5, name: "StillCreated"})
697
+ .expect(201);
698
+ const stored = await FoodModel.findById(res.body.data._id).lean();
699
+ expect(stored?.name).toBe("StillCreated");
700
+ });
701
+
702
+ it("returns 200 on PATCH when onAdminAudit throws", async () => {
703
+ const localApp = buildApp([foodModelConfig], throwingAudit);
704
+ const agent = await authAsUser(localApp, "admin");
705
+ const food = await FoodModel.create({calories: 10, name: "PatchMe"});
706
+ const res = await agent.patch(`/admin/foods/${food._id}`).send({calories: 99}).expect(200);
707
+ expect(res.body.data.calories).toBe(99);
708
+ const stored = await FoodModel.findById(food._id).lean();
709
+ expect(stored?.calories).toBe(99);
710
+ });
711
+
712
+ it("returns 204 on DELETE when onAdminAudit throws", async () => {
713
+ const localApp = buildApp([foodModelConfig], throwingAudit);
714
+ const agent = await authAsUser(localApp, "admin");
715
+ const food = await FoodModel.create({calories: 1, name: "DeleteMe"});
716
+ await agent.delete(`/admin/foods/${food._id}`).expect(204);
717
+ expect(await FoodModel.findById(food._id)).toBeNull();
718
+ });
719
+ });
720
+
721
+ describe("AdminApp per-model queryFilter", () => {
722
+ beforeEach(async () => {
723
+ await setupDb();
724
+ });
725
+
726
+ afterEach(async () => {
727
+ await FoodModel.deleteMany({});
728
+ await VersionConfig.deleteMany({});
729
+ });
730
+
731
+ it("returns an empty list when queryFilter returns null", async () => {
732
+ const localApp = buildApp([
733
+ {
734
+ ...foodModelConfig,
735
+ queryFilter: (): null => null,
736
+ },
737
+ ]);
738
+ await FoodModel.create({calories: 1, name: "HiddenRow"});
739
+ const agent = await authAsUser(localApp, "admin");
740
+ const res = await agent.get("/admin/foods").expect(200);
741
+ expect(res.body.data).toEqual([]);
742
+ });
743
+
744
+ it("merges queryFilter constraints into list queries for that model only", async () => {
745
+ const localApp = buildApp([
746
+ {
747
+ ...foodModelConfig,
748
+ queryFilter: (_user, query): Record<string, unknown> => ({
749
+ ...(query ?? {}),
750
+ name: "FilteredOnly",
751
+ }),
752
+ },
753
+ ]);
754
+ await FoodModel.create({calories: 1, name: "Other"});
755
+ await FoodModel.create({calories: 2, name: "FilteredOnly"});
756
+ const agent = await authAsUser(localApp, "admin");
757
+ const res = await agent.get("/admin/foods").expect(200);
758
+ expect(res.body.data).toHaveLength(1);
759
+ expect(res.body.data[0].name).toBe("FilteredOnly");
760
+ });
761
+ });
@@ -289,6 +289,101 @@ describe("AdminApp script routes", () => {
289
289
  });
290
290
  });
291
291
 
292
+ describe("GET /admin/scripts/runs", () => {
293
+ beforeEach(async () => {
294
+ await setupDb();
295
+ app = buildApp([
296
+ createTestScript({description: "Migrate old data", name: "migrate-data"}),
297
+ createTestScript({description: "Clean up orphans", name: "cleanup"}),
298
+ ]);
299
+ adminAgent = await authAsUser(app, "admin");
300
+ notAdminAgent = await authAsUser(app, "notAdmin");
301
+ });
302
+
303
+ it("returns runs for registered scripts, newest first", async () => {
304
+ await adminAgent.post("/admin/scripts/migrate-data/run").expect(201);
305
+ await adminAgent.post("/admin/scripts/cleanup/run?wetRun=true").expect(201);
306
+ await waitForScripts();
307
+
308
+ const res = await adminAgent.get("/admin/scripts/runs").expect(200);
309
+
310
+ expect(res.body.data).toHaveLength(2);
311
+ expect(res.body.total).toBe(2);
312
+ // Newest run (cleanup) is listed first.
313
+ expect(res.body.data[0].taskType).toBe("cleanup");
314
+ expect(res.body.data[1].taskType).toBe("migrate-data");
315
+ });
316
+
317
+ it("narrows history to a single script via the name query", async () => {
318
+ await adminAgent.post("/admin/scripts/migrate-data/run").expect(201);
319
+ await adminAgent.post("/admin/scripts/cleanup/run").expect(201);
320
+ await waitForScripts();
321
+
322
+ const res = await adminAgent.get("/admin/scripts/runs?name=cleanup").expect(200);
323
+
324
+ expect(res.body.data).toHaveLength(1);
325
+ expect(res.body.data[0].taskType).toBe("cleanup");
326
+ });
327
+
328
+ it("returns no runs when the name query is not a registered script", async () => {
329
+ await adminAgent.post("/admin/scripts/migrate-data/run").expect(201);
330
+ await adminAgent.post("/admin/scripts/cleanup/run").expect(201);
331
+ await waitForScripts();
332
+
333
+ const res = await adminAgent.get("/admin/scripts/runs?name=does-not-exist").expect(200);
334
+
335
+ expect(res.body.data).toHaveLength(0);
336
+ expect(res.body.total).toBe(0);
337
+ });
338
+
339
+ it("excludes tasks whose taskType is not a registered script", async () => {
340
+ await BackgroundTask.create({
341
+ isDryRun: false,
342
+ logs: [],
343
+ status: "completed",
344
+ taskType: "some-other-task",
345
+ });
346
+ await adminAgent.post("/admin/scripts/migrate-data/run").expect(201);
347
+ await waitForScripts();
348
+
349
+ const res = await adminAgent.get("/admin/scripts/runs").expect(200);
350
+
351
+ expect(res.body.data).toHaveLength(1);
352
+ expect(res.body.data[0].taskType).toBe("migrate-data");
353
+ });
354
+
355
+ it("paginates and reports `more`", async () => {
356
+ await adminAgent.post("/admin/scripts/migrate-data/run").expect(201);
357
+ await adminAgent.post("/admin/scripts/cleanup/run").expect(201);
358
+ await waitForScripts();
359
+
360
+ const res = await adminAgent.get("/admin/scripts/runs?limit=1&page=1").expect(200);
361
+
362
+ expect(res.body.data).toHaveLength(1);
363
+ expect(res.body.limit).toBe(1);
364
+ expect(res.body.more).toBe(true);
365
+ expect(res.body.total).toBe(2);
366
+ });
367
+
368
+ it("includes the triggering admin's display name", async () => {
369
+ await adminAgent.post("/admin/scripts/migrate-data/run").expect(201);
370
+ await waitForScripts();
371
+
372
+ const res = await adminAgent.get("/admin/scripts/runs").expect(200);
373
+
374
+ expect(res.body.data[0].createdByName).toBeDefined();
375
+ });
376
+
377
+ it("returns 403 for non-admin user", async () => {
378
+ const res = await notAdminAgent.get("/admin/scripts/runs").expect(403);
379
+ expect(res.body.title).toInclude("Only admins can view run history");
380
+ });
381
+
382
+ it("returns 401 for unauthenticated user", async () => {
383
+ await supertest(app).get("/admin/scripts/runs").expect(401);
384
+ });
385
+ });
386
+
292
387
  describe("GET /admin/config with scripts", () => {
293
388
  beforeEach(async () => {
294
389
  await setupDb();