@terreno/admin-backend 57.3.0 → 57.4.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.
Files changed (44) hide show
  1. package/bunfig.toml +9 -1
  2. package/dist/adminApp.d.ts +20 -2
  3. package/dist/adminApp.js +468 -363
  4. package/dist/adminConfigIdentity.d.ts +1 -0
  5. package/dist/adminConfigIdentity.js +1 -0
  6. package/dist/adminMigrations.d.ts +10 -0
  7. package/dist/adminMigrations.js +205 -0
  8. package/dist/adminScriptJob.d.ts +32 -0
  9. package/dist/adminScriptJob.js +360 -0
  10. package/dist/adminTextSearch.d.ts +1 -0
  11. package/dist/adminTextSearch.js +1 -0
  12. package/dist/adminUiV2.d.ts +2 -0
  13. package/dist/aggregateAdmin.js +2 -0
  14. package/dist/enrichAdminListFilters.d.ts +7 -0
  15. package/dist/enrichAdminListFilters.js +37 -0
  16. package/dist/filterParser.js +139 -12
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.js +4 -1
  19. package/dist/legacy.js +4 -2
  20. package/dist/resolvedAdminModel.js +2 -1
  21. package/package.json +7 -7
  22. package/src/adminApp.migrations.test.ts +232 -0
  23. package/src/adminApp.models.test.ts +645 -1
  24. package/src/adminApp.syncMeta.test.ts +237 -0
  25. package/src/adminApp.test.ts +92 -0
  26. package/src/adminApp.ts +344 -124
  27. package/src/adminConfigIdentity.ts +1 -0
  28. package/src/adminHttpGoldens.test.ts +337 -0
  29. package/src/adminMigrations.ts +157 -0
  30. package/src/adminScriptJob.test.ts +297 -0
  31. package/src/adminScriptJob.ts +271 -0
  32. package/src/adminSyncMutationAuthMismatch.test.ts +650 -0
  33. package/src/adminTextSearch.test.ts +28 -0
  34. package/src/adminTextSearch.ts +1 -0
  35. package/src/adminUiV2.ts +2 -0
  36. package/src/aggregateAdmin.test.ts +125 -0
  37. package/src/aggregateAdmin.ts +2 -0
  38. package/src/enrichAdminListFilters.test.ts +44 -0
  39. package/src/enrichAdminListFilters.ts +29 -0
  40. package/src/filterParser.test.ts +95 -0
  41. package/src/filterParser.ts +156 -10
  42. package/src/index.ts +2 -0
  43. package/src/legacy.ts +5 -1
  44. package/src/resolvedAdminModel.ts +2 -1
@@ -0,0 +1,237 @@
1
+ import {afterEach, beforeEach, describe, it} from "bun:test";
2
+ import {
3
+ addAuthRoutes,
4
+ apiErrorMiddleware,
5
+ apiUnauthorizedMiddleware,
6
+ clearSyncRegistry,
7
+ createdUpdatedPlugin,
8
+ getAdminBroadcastScope,
9
+ getSyncRegistry,
10
+ isDeletedPlugin,
11
+ orgScopedPlugin,
12
+ Permissions,
13
+ registerSync,
14
+ SyncApp,
15
+ setupAuth,
16
+ syncPlugin,
17
+ type UserModel as UserModelType,
18
+ } from "@terreno/api";
19
+ import {authAsUser, getBaseServer, setupDb, UserModel} from "@terreno/api/testing";
20
+ import {assert} from "chai";
21
+ import type express from "express";
22
+ import mongoose from "mongoose";
23
+ import type TestAgent from "supertest/lib/agent";
24
+
25
+ import type {AdminModelConfig} from "./adminApp";
26
+ import {AdminApp} from "./adminApp";
27
+
28
+ interface ConfigSyncMetaTodo {
29
+ _id: string;
30
+ ownerId: string;
31
+ title: string;
32
+ }
33
+
34
+ const configSyncMetaTodoSchema = new mongoose.Schema<ConfigSyncMetaTodo>({
35
+ _id: {
36
+ default: (): string => new mongoose.Types.ObjectId().toHexString(),
37
+ description: "Client-minted string id",
38
+ type: String,
39
+ },
40
+ ownerId: {description: "The owner", type: String},
41
+ title: {description: "Todo title", required: true, type: String},
42
+ });
43
+ configSyncMetaTodoSchema.plugin(isDeletedPlugin);
44
+ configSyncMetaTodoSchema.plugin(createdUpdatedPlugin);
45
+ configSyncMetaTodoSchema.plugin(syncPlugin);
46
+
47
+ const ConfigSyncMetaTodoModel =
48
+ mongoose.models.ConfigSyncMetaTodo ??
49
+ mongoose.model<ConfigSyncMetaTodo>("ConfigSyncMetaTodo", configSyncMetaTodoSchema);
50
+
51
+ const todoModelConfig: AdminModelConfig = {
52
+ displayName: "Todos",
53
+ listFields: ["title"],
54
+ model: ConfigSyncMetaTodoModel,
55
+ routePath: "/todos",
56
+ };
57
+
58
+ const syncOptions = {
59
+ permissions: {
60
+ create: [Permissions.IsAuthenticated],
61
+ delete: [Permissions.IsAuthenticated],
62
+ list: [Permissions.IsAuthenticated],
63
+ read: [Permissions.IsAuthenticated],
64
+ update: [Permissions.IsAuthenticated],
65
+ },
66
+ sync: {scope: {type: "owner" as const}},
67
+ };
68
+
69
+ const buildApp = (): express.Application => {
70
+ const app = getBaseServer();
71
+ setupAuth(app, UserModel as unknown as UserModelType);
72
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
73
+ new AdminApp({basePath: "/admin", models: [todoModelConfig]}).register(app);
74
+ app.use(apiUnauthorizedMiddleware);
75
+ app.use(apiErrorMiddleware);
76
+ return app;
77
+ };
78
+
79
+ describe("GET /admin/config sync window meta", () => {
80
+ let adminAgent: TestAgent;
81
+
82
+ beforeEach(async () => {
83
+ clearSyncRegistry();
84
+ await setupDb();
85
+ adminAgent = await authAsUser(buildApp(), "admin");
86
+ });
87
+
88
+ afterEach(() => {
89
+ clearSyncRegistry();
90
+ });
91
+
92
+ it("omits syncCollection when the model is not registered for adminBroadcast", async () => {
93
+ const res = await adminAgent.get("/admin/config").expect(200);
94
+ const todoMeta = (res.body.models as Record<string, unknown>[]).find(
95
+ (model) => model.name === "ConfigSyncMetaTodo"
96
+ );
97
+ assert.isDefined(todoMeta);
98
+ assert.strictEqual(todoMeta?.adminBroadcast, false);
99
+ assert.notProperty(todoMeta as object, "syncCollection");
100
+ });
101
+
102
+ it("exposes adminBroadcast and syncCollection from the app sync registry", async () => {
103
+ clearSyncRegistry();
104
+ registerSync({
105
+ config: {adminBroadcast: true, scope: {type: "owner"}},
106
+ model: ConfigSyncMetaTodoModel,
107
+ options: syncOptions,
108
+ routePath: "/todos",
109
+ });
110
+ const agent = await authAsUser(buildApp(), "admin");
111
+ const res = await agent.get("/admin/config").expect(200);
112
+ const todoMeta = (res.body.models as Record<string, unknown>[]).find(
113
+ (model) => model.name === "ConfigSyncMetaTodo"
114
+ );
115
+ assert.isDefined(todoMeta);
116
+ assert.strictEqual(todoMeta?.adminBroadcast, true);
117
+ assert.strictEqual(todoMeta?.syncCollection, "todos");
118
+ });
119
+ });
120
+
121
+ interface ConfigOrgScopedTodo {
122
+ _id: string;
123
+ organizationId: mongoose.Types.ObjectId;
124
+ title: string;
125
+ }
126
+
127
+ const configOrgScopedTodoSchema = new mongoose.Schema<ConfigOrgScopedTodo>({
128
+ _id: {
129
+ default: (): string => new mongoose.Types.ObjectId().toHexString(),
130
+ description: "Client-minted string id",
131
+ type: String,
132
+ },
133
+ title: {description: "Todo title", required: true, type: String},
134
+ });
135
+ configOrgScopedTodoSchema.plugin(orgScopedPlugin);
136
+ configOrgScopedTodoSchema.plugin(isDeletedPlugin);
137
+ configOrgScopedTodoSchema.plugin(createdUpdatedPlugin);
138
+ configOrgScopedTodoSchema.plugin(syncPlugin);
139
+
140
+ const ConfigOrgScopedTodoModel =
141
+ mongoose.models.ConfigOrgScopedTodo ??
142
+ mongoose.model<ConfigOrgScopedTodo>("ConfigOrgScopedTodo", configOrgScopedTodoSchema);
143
+
144
+ const orgScopedTodoModelConfig: AdminModelConfig = {
145
+ displayName: "Org todos",
146
+ listFields: ["title"],
147
+ model: ConfigOrgScopedTodoModel,
148
+ routePath: "/org-todos",
149
+ };
150
+
151
+ describe("GET /admin/config org-scoped sync window meta", () => {
152
+ afterEach(() => {
153
+ clearSyncRegistry();
154
+ });
155
+
156
+ it("forces adminBroadcast false and organizationScoped true when organizations is enabled", async () => {
157
+ clearSyncRegistry();
158
+ await setupDb();
159
+ registerSync({
160
+ config: {adminBroadcast: true, scope: {field: "organizationId", type: "tenant"}},
161
+ model: ConfigOrgScopedTodoModel,
162
+ options: syncOptions,
163
+ routePath: "/org-todos",
164
+ });
165
+ const app = getBaseServer();
166
+ setupAuth(app, UserModel as unknown as UserModelType);
167
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
168
+ new AdminApp({
169
+ basePath: "/admin",
170
+ models: [orgScopedTodoModelConfig],
171
+ organizations: true,
172
+ }).register(app);
173
+ app.use(apiUnauthorizedMiddleware);
174
+ app.use(apiErrorMiddleware);
175
+
176
+ const agent = await authAsUser(app, "admin");
177
+ const res = await agent.get("/admin/config").expect(200);
178
+ const todoMeta = (res.body.models as Record<string, unknown>[]).find(
179
+ (model) => model.name === "ConfigOrgScopedTodo"
180
+ );
181
+ assert.isDefined(todoMeta);
182
+ assert.strictEqual(todoMeta?.adminBroadcast, false);
183
+ assert.strictEqual(todoMeta?.organizationScoped, true);
184
+ assert.notProperty(todoMeta as object, "syncCollection");
185
+ assert.strictEqual(getSyncRegistry()[0]?.config.adminBroadcast, false);
186
+ assert.isUndefined(getAdminBroadcastScope("ConfigOrgScopedTodo"));
187
+ });
188
+ });
189
+
190
+ describe("AdminApp adminBroadcast scope", () => {
191
+ afterEach(() => {
192
+ clearSyncRegistry();
193
+ });
194
+
195
+ it("applies per-model queryFilter to GET /sync/entities hydrate", async () => {
196
+ clearSyncRegistry();
197
+ await setupDb();
198
+ registerSync({
199
+ config: {adminBroadcast: true, scope: {type: "owner"}},
200
+ model: ConfigSyncMetaTodoModel,
201
+ options: syncOptions,
202
+ routePath: "/todos",
203
+ });
204
+ const app = getBaseServer();
205
+ setupAuth(app, UserModel as unknown as UserModelType);
206
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
207
+ new AdminApp({
208
+ basePath: "/admin",
209
+ models: [
210
+ {
211
+ ...todoModelConfig,
212
+ queryFilter: (): Record<string, unknown> => ({ownerId: "tenant-a"}),
213
+ },
214
+ ],
215
+ }).register(app);
216
+ new SyncApp().register(app);
217
+ app.use(apiUnauthorizedMiddleware);
218
+ app.use(apiErrorMiddleware);
219
+
220
+ const inScope = await ConfigSyncMetaTodoModel.create({
221
+ ownerId: "tenant-a",
222
+ title: "visible",
223
+ });
224
+ const outOfScope = await ConfigSyncMetaTodoModel.create({
225
+ ownerId: "tenant-b",
226
+ title: "hidden",
227
+ });
228
+ const agent = await authAsUser(app, "admin");
229
+ const res = await agent
230
+ .get(`/sync/entities?collection=todos&ids=${inScope._id},${outOfScope._id}`)
231
+ .expect(200);
232
+ assert.deepEqual(
233
+ (res.body.entities as {id: string}[]).map((entity) => entity.id),
234
+ [String(inScope._id)]
235
+ );
236
+ });
237
+ });
@@ -12,6 +12,7 @@ import {
12
12
  type UserModel as UserModelType,
13
13
  } from "@terreno/api";
14
14
  import {authAsUser, getBaseServer, setupDb, UserModel} from "@terreno/api/testing";
15
+ import {Job, JobsApp, unregisterJobsService} from "@terreno/jobs";
15
16
  import type express from "express";
16
17
  import mongoose from "mongoose";
17
18
  import supertest from "supertest";
@@ -520,6 +521,97 @@ describe("AdminApp script routes", () => {
520
521
  });
521
522
  });
522
523
 
524
+ describe("script runs through durable jobs when JobsApp is registered", () => {
525
+ let jobsApp: JobsApp;
526
+
527
+ beforeEach(async () => {
528
+ await setupDb();
529
+ await Job.deleteMany({});
530
+ await BackgroundTask.deleteMany({});
531
+ jobsApp = new JobsApp({pollIntervalMs: 25});
532
+ const server = getBaseServer();
533
+ setupAuth(server, UserModel as unknown as UserModelType);
534
+ addAuthRoutes(server, UserModel as unknown as UserModelType);
535
+ jobsApp.register(server);
536
+ const admin = new AdminApp({
537
+ basePath: "/admin",
538
+ models: [],
539
+ scripts: [createTestScript(), createFailingScript()],
540
+ });
541
+ admin.register(server);
542
+ server.use(apiUnauthorizedMiddleware);
543
+ server.use(apiErrorMiddleware);
544
+ app = server;
545
+ adminAgent = await authAsUser(app, "admin");
546
+ });
547
+
548
+ afterEach(async () => {
549
+ unregisterJobsService();
550
+ await Job.deleteMany({});
551
+ });
552
+
553
+ it("returns taskId, persists a job row, and completes the BackgroundTask", async () => {
554
+ const res = await adminAgent.post("/admin/scripts/test-script/run").expect(201);
555
+ const taskId = res.body.taskId as string;
556
+ const job = await Job.findOne({name: "admin/script", "payload.taskId": taskId});
557
+ expect(job).not.toBeNull();
558
+ expect(job?.maxAttempts).toBe(1);
559
+ const outcome = await jobsApp.executeQueuedJob(String(job?._id));
560
+ expect(outcome.kind).toBe("executed");
561
+ const task = await BackgroundTask.findById(taskId);
562
+ expect(task?.status).toBe("completed");
563
+ expect(task?.result).toContain("Ran in dry mode");
564
+ });
565
+
566
+ it("marks the BackgroundTask failed when the script throws", async () => {
567
+ const res = await adminAgent.post("/admin/scripts/failing-script/run").expect(201);
568
+ const job = await Job.findOne({
569
+ name: "admin/script",
570
+ "payload.taskId": res.body.taskId,
571
+ });
572
+ expect(job).not.toBeNull();
573
+ await jobsApp.executeQueuedJob(String(job?._id));
574
+ const task = await BackgroundTask.findById(res.body.taskId);
575
+ expect(task?.status).toBe("failed");
576
+ expect(task?.error).toBe("Script exploded");
577
+ });
578
+
579
+ it("marks the BackgroundTask failed when enqueue throws", async () => {
580
+ unregisterJobsService();
581
+ const throwingJobs = new JobsApp({
582
+ pollIntervalMs: 25,
583
+ runner: {
584
+ enqueue: async (): Promise<void> => {
585
+ throw new Error("Cloud Tasks unavailable");
586
+ },
587
+ id: "throw-enqueue",
588
+ },
589
+ });
590
+ const server = getBaseServer();
591
+ setupAuth(server, UserModel as unknown as UserModelType);
592
+ addAuthRoutes(server, UserModel as unknown as UserModelType);
593
+ throwingJobs.register(server);
594
+ const admin = new AdminApp({
595
+ basePath: "/admin",
596
+ models: [],
597
+ scripts: [createTestScript()],
598
+ });
599
+ admin.register(server);
600
+ server.use(apiUnauthorizedMiddleware);
601
+ server.use(apiErrorMiddleware);
602
+ const agent = await authAsUser(server, "admin");
603
+
604
+ const res = await agent.post("/admin/scripts/test-script/run").expect(500);
605
+ expect(res.body.title).toMatch(/enqueue/i);
606
+ const pending = await BackgroundTask.find({status: "pending"});
607
+ expect(pending).toHaveLength(0);
608
+ const failed = await BackgroundTask.find({taskType: "test-script"});
609
+ expect(failed).toHaveLength(1);
610
+ expect(failed[0]?.status).toBe("failed");
611
+ expect(failed[0]?.error).toContain("Cloud Tasks unavailable");
612
+ });
613
+ });
614
+
523
615
  describe("GET /admin/config with scripts", () => {
524
616
  beforeEach(async () => {
525
617
  await setupDb();