@terreno/admin-backend 57.0.0 → 57.2.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 (43) hide show
  1. package/README.md +3 -0
  2. package/dist/adminApp.d.ts +25 -4
  3. package/dist/adminApp.js +1195 -269
  4. package/dist/adminConfigIdentity.d.ts +16 -0
  5. package/dist/adminConfigIdentity.js +100 -0
  6. package/dist/adminTextSearch.d.ts +17 -0
  7. package/dist/adminTextSearch.js +117 -0
  8. package/dist/adminUiV2.js +1 -1
  9. package/dist/aggregateAdmin.d.ts +20 -0
  10. package/dist/aggregateAdmin.js +276 -0
  11. package/dist/documentStorageApp.d.ts +3 -1
  12. package/dist/documentStorageApp.js +20 -42
  13. package/dist/filterParser.d.ts +11 -0
  14. package/dist/filterParser.js +260 -0
  15. package/dist/index.d.ts +10 -1
  16. package/dist/index.js +16 -1
  17. package/dist/legacy.d.ts +9 -0
  18. package/dist/legacy.js +61 -0
  19. package/dist/resolvedAdminModel.d.ts +23 -0
  20. package/dist/resolvedAdminModel.js +131 -0
  21. package/dist/routePath.d.ts +2 -0
  22. package/dist/routePath.js +18 -0
  23. package/package.json +5 -4
  24. package/src/adminApp.models.test.ts +1321 -1
  25. package/src/adminApp.test.ts +35 -1
  26. package/src/adminApp.ts +873 -102
  27. package/src/adminConfigIdentity.test.ts +56 -0
  28. package/src/adminConfigIdentity.ts +87 -0
  29. package/src/adminTextSearch.test.ts +73 -0
  30. package/src/adminTextSearch.ts +74 -0
  31. package/src/adminUiV2.test.ts +1 -0
  32. package/src/adminUiV2.ts +1 -1
  33. package/src/aggregateAdmin.test.ts +220 -0
  34. package/src/aggregateAdmin.ts +207 -0
  35. package/src/documentStorageApp.test.ts +11 -0
  36. package/src/documentStorageApp.ts +20 -39
  37. package/src/filterParser.test.ts +68 -0
  38. package/src/filterParser.ts +229 -0
  39. package/src/index.ts +36 -1
  40. package/src/legacy.test.ts +34 -0
  41. package/src/legacy.ts +63 -0
  42. package/src/resolvedAdminModel.ts +115 -0
  43. package/src/routePath.ts +14 -0
@@ -1,10 +1,18 @@
1
1
  import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
2
  import {
3
+ ADMIN_MODEL_ACCESS,
3
4
  addAuthRoutes,
4
5
  apiErrorMiddleware,
5
6
  apiUnauthorizedMiddleware,
6
7
  BackgroundTask,
8
+ createAccess,
9
+ findOneOrNoneFor,
10
+ modelRouter,
11
+ Permissions,
7
12
  setupAuth,
13
+ type TerrenoApp,
14
+ type TerrenoPlugin,
15
+ terrenoStatements,
8
16
  type UserModel as UserModelType,
9
17
  VersionConfig,
10
18
  } from "@terreno/api";
@@ -16,6 +24,7 @@ import {
16
24
  setupDb,
17
25
  UserModel,
18
26
  } from "@terreno/api/testing";
27
+ import {assert} from "chai";
19
28
  import type express from "express";
20
29
  import mongoose from "mongoose";
21
30
  import supertest from "supertest";
@@ -108,6 +117,96 @@ describe("AdminApp /admin/config", () => {
108
117
  expect(foodMeta.routePath).toBe("/admin/foods");
109
118
  expect(foodMeta.defaultSort).toBe("-created");
110
119
  expect(foodMeta.fieldOrder).toEqual(["name", "calories", "tags"]);
120
+ expect(res.body.capabilities).toEqual({
121
+ actions: true,
122
+ fieldsets: true,
123
+ filters: true,
124
+ realtime: false,
125
+ });
126
+ expect(res.body.widgetIds).toEqual([]);
127
+ });
128
+
129
+ it("exposes plugin widgetIds and aggregates models from TerrenoApp registrations", async () => {
130
+ const plugin: TerrenoPlugin = {
131
+ adminContribution: () => ({
132
+ homeWidgets: [{displayName: "Overrides", id: "feature-flags-overrides"}],
133
+ models: [
134
+ {
135
+ admin: {displayName: "Flags", listFields: ["key"]},
136
+ model: FoodModel,
137
+ routePath: "/feature-flags",
138
+ },
139
+ ],
140
+ }),
141
+ register() {},
142
+ };
143
+ const terrenoApp = {
144
+ getPlugins: () => [plugin],
145
+ getRegistrations: () => [
146
+ modelRouter("/foods", FoodModel, {
147
+ admin: {displayName: "Registered Foods", listFields: ["name"]},
148
+ permissions: {
149
+ create: [Permissions.IsAny],
150
+ delete: [Permissions.IsAny],
151
+ list: [Permissions.IsAny],
152
+ read: [Permissions.IsAny],
153
+ update: [Permissions.IsAny],
154
+ },
155
+ }),
156
+ ],
157
+ } as unknown as TerrenoApp;
158
+
159
+ const appWithAggregation = getBaseServer();
160
+ setupAuth(appWithAggregation, UserModel as unknown as UserModelType);
161
+ addAuthRoutes(appWithAggregation, UserModel as unknown as UserModelType);
162
+ new AdminApp({basePath: "/admin"}).register(appWithAggregation, undefined, terrenoApp);
163
+ appWithAggregation.use(apiUnauthorizedMiddleware);
164
+ appWithAggregation.use(apiErrorMiddleware);
165
+
166
+ const agent = await authAsUser(appWithAggregation, "admin");
167
+ const res = await agent.get("/admin/config").expect(200);
168
+
169
+ expect(res.body.widgetIds).toEqual(["feature-flags-overrides"]);
170
+ expect(res.body.models.map((m: {routePath: string}) => m.routePath).sort()).toEqual([
171
+ "/admin/feature-flags",
172
+ "/admin/foods",
173
+ ]);
174
+ const foods = res.body.models.find((m: {routePath: string}) => m.routePath === "/admin/foods");
175
+ expect(foods?.displayName).toBe("Registered Foods");
176
+ expect(foods?.name).toBe("Food");
177
+ const flags = res.body.models.find(
178
+ (m: {routePath: string}) => m.routePath === "/admin/feature-flags"
179
+ );
180
+ expect(flags?.name).toBe("Food-feature-flags");
181
+ });
182
+
183
+ it("gives each mounted path unique config names and per-path searchFields", async () => {
184
+ const localApp = buildApp([
185
+ {
186
+ ...foodModelConfig,
187
+ searchFields: ["name"],
188
+ },
189
+ {
190
+ displayName: "Archived Foods",
191
+ listFields: ["name", "calories"],
192
+ model: FoodModel,
193
+ routePath: "/archived-foods",
194
+ searchFields: [],
195
+ },
196
+ ]);
197
+ await FoodModel.create({calories: 100, name: "GreenApple"});
198
+ await FoodModel.create({calories: 2, name: "Banana"});
199
+ const agent = await authAsUser(localApp, "admin");
200
+ const config = await agent.get("/admin/config").expect(200);
201
+ const names = config.body.models.map((m: {name: string}) => m.name).sort();
202
+ expect(names).toEqual(["Food", "Food-archived-foods"]);
203
+
204
+ const byName = await agent.get("/admin/foods?q=apple").expect(200);
205
+ expect(byName.body.data).toHaveLength(1);
206
+ expect(byName.body.data[0].name).toBe("GreenApple");
207
+
208
+ const archivedIgnoresNameSearch = await agent.get("/admin/archived-foods?q=apple").expect(200);
209
+ expect(archivedIgnoresNameSearch.body.data).toHaveLength(2);
111
210
  });
112
211
 
113
212
  it("includes recordTitleField in config when set on the model", async () => {
@@ -240,6 +339,430 @@ describe("AdminApp /admin/config", () => {
240
339
  expect(res.body.home.title).toBe("Ops");
241
340
  expect(res.body.home.slots.sidebar).toEqual(["versionConfig", "recentActivity"]);
242
341
  });
342
+
343
+ it("filters screens and platform tools from the caller's RBAC grants", async () => {
344
+ const accessControl = createAccess({
345
+ connection: mongoose.connection,
346
+ resolvePermissions: async () => ({
347
+ admin: ["access"],
348
+ adminFood: ["read"],
349
+ adminScreen: ["allowed"],
350
+ }),
351
+ statements: {
352
+ ...terrenoStatements,
353
+ adminFood: ADMIN_MODEL_ACCESS,
354
+ adminScreen: ["allowed", "hidden"],
355
+ },
356
+ });
357
+ const localApp = buildApp([{...foodModelConfig, adminAccess: {}}], {
358
+ accessControl,
359
+ customScreens: [
360
+ {
361
+ adminAccess: {action: "allowed", resource: "adminScreen"},
362
+ displayName: "Allowed",
363
+ name: "allowed",
364
+ },
365
+ {
366
+ adminAccess: {action: "hidden", resource: "adminScreen"},
367
+ displayName: "Hidden",
368
+ name: "hidden",
369
+ },
370
+ ],
371
+ scripts: [
372
+ {
373
+ description: "Seed",
374
+ name: "seed",
375
+ runner: async () => ({results: [], success: true}),
376
+ },
377
+ ],
378
+ });
379
+ const agent = await authAsUser(localApp, "admin");
380
+
381
+ const response = await agent.get("/admin/config").expect(200);
382
+
383
+ assert.deepEqual(
384
+ response.body.models.map((model: {name: string}) => model.name),
385
+ ["Food"]
386
+ );
387
+ assert.deepInclude(response.body.models[0].permissions, {
388
+ create: false,
389
+ delete: false,
390
+ update: false,
391
+ });
392
+ assert.deepEqual(response.body.customScreens, [{displayName: "Allowed", name: "allowed"}]);
393
+ assert.deepEqual(response.body.platformTools, {
394
+ configuration: false,
395
+ roles: false,
396
+ runScripts: false,
397
+ scripts: false,
398
+ version: false,
399
+ viewScripts: false,
400
+ });
401
+ assert.deepEqual(response.body.scripts, []);
402
+ });
403
+
404
+ it("enforces writeOwned with the configured ownership callback", async () => {
405
+ const accessControl = createAccess({
406
+ connection: mongoose.connection,
407
+ resolvePermissions: async () => ({
408
+ admin: ["access"],
409
+ adminFood: ["read", "writeOwned"],
410
+ }),
411
+ statements: {...terrenoStatements, adminFood: ADMIN_MODEL_ACCESS},
412
+ });
413
+ const localApp = buildApp(
414
+ [
415
+ {
416
+ ...foodModelConfig,
417
+ adminAccess: {
418
+ isOwned: ({instance, user}) =>
419
+ String((instance as {ownerId?: unknown}).ownerId) === String(user.id),
420
+ },
421
+ },
422
+ ],
423
+ {accessControl}
424
+ );
425
+ const agent = await authAsUser(localApp, "admin");
426
+ const actor = await findOneOrNoneFor(UserModel, {email: "admin@example.com"});
427
+ assert.exists(actor);
428
+ const owned = await FoodModel.create({calories: 1, name: "Owned", ownerId: actor?._id});
429
+ const other = await FoodModel.create({
430
+ calories: 2,
431
+ name: "Other",
432
+ ownerId: new mongoose.Types.ObjectId(),
433
+ });
434
+
435
+ await agent.patch(`/admin/foods/${owned._id}`).send({calories: 3}).expect(200);
436
+ await agent.patch(`/admin/foods/${other._id}`).send({calories: 4}).expect(403);
437
+ const ownedRead = await agent.get(`/admin/foods/${owned._id}`).expect(200);
438
+ const otherRead = await agent.get(`/admin/foods/${other._id}`).expect(200);
439
+ assert.deepEqual(ownedRead.body.data._adminCapabilities, {delete: true, update: true});
440
+ assert.deepEqual(otherRead.body.data._adminCapabilities, {delete: false, update: false});
441
+ await agent.delete(`/admin/foods/${other._id}`).expect(403);
442
+ await agent
443
+ .post("/admin/foods")
444
+ .send({calories: 5, name: "Created", ownerId: actor?._id})
445
+ .expect(201);
446
+ await agent
447
+ .post("/admin/foods")
448
+ .send({calories: 6, name: "Foreign", ownerId: new mongoose.Types.ObjectId()})
449
+ .expect(201);
450
+ await agent.post("/admin/foods").send({calories: 7, name: "Unassigned"}).expect(201);
451
+ });
452
+
453
+ it("supports completely custom per-model authorization", async () => {
454
+ const accessControl = createAccess({
455
+ connection: mongoose.connection,
456
+ resolvePermissions: async () => ({admin: ["access"]}),
457
+ statements: terrenoStatements,
458
+ });
459
+ const localApp = buildApp(
460
+ [
461
+ {
462
+ ...foodModelConfig,
463
+ adminAccess: {
464
+ authorize: ({action}) => action === "list" || action === "read",
465
+ },
466
+ },
467
+ ],
468
+ {accessControl}
469
+ );
470
+ const agent = await authAsUser(localApp, "admin");
471
+
472
+ const config = await agent.get("/admin/config").expect(200);
473
+ assert.deepInclude(config.body.models[0].permissions, {
474
+ create: false,
475
+ delete: false,
476
+ update: false,
477
+ });
478
+ await agent.get("/admin/foods").expect(200);
479
+ await agent.post("/admin/foods").send({calories: 1, name: "Denied"}).expect(405);
480
+ });
481
+ });
482
+
483
+ describe("AdminApp adminAccess role matrix", () => {
484
+ const ADMIN_EMAIL = "admin@example.com";
485
+ const MEMBER_EMAIL = "notAdmin@example.com";
486
+ const matrixStatements = {
487
+ ...terrenoStatements,
488
+ adminFood: ADMIN_MODEL_ACCESS,
489
+ adminScreen: ["showcase"],
490
+ };
491
+
492
+ const buildMatrixApp = (
493
+ grantsByEmail: Record<string, Record<string, string[]>>
494
+ ): express.Application => {
495
+ const accessControl = createAccess({
496
+ connection: mongoose.connection,
497
+ resolvePermissions: async ({user}) => {
498
+ const email = "email" in user && typeof user.email === "string" ? user.email : "";
499
+ return grantsByEmail[email] ?? {};
500
+ },
501
+ statements: matrixStatements,
502
+ });
503
+ return buildApp(
504
+ [
505
+ {
506
+ ...foodModelConfig,
507
+ adminAccess: {
508
+ isOwned: ({instance, user}) => {
509
+ return String((instance as {ownerId?: unknown}).ownerId) === String(user.id);
510
+ },
511
+ },
512
+ },
513
+ ],
514
+ {
515
+ accessControl,
516
+ customScreens: [
517
+ {
518
+ adminAccess: {action: "showcase", resource: "adminScreen"},
519
+ displayName: "Showcase",
520
+ name: "showcase",
521
+ },
522
+ ],
523
+ scripts: [
524
+ {
525
+ description: "Seed",
526
+ name: "seed",
527
+ runner: async () => ({results: [], success: true}),
528
+ },
529
+ ],
530
+ }
531
+ );
532
+ };
533
+
534
+ beforeEach(async () => {
535
+ await setupDb();
536
+ });
537
+
538
+ afterEach(async () => {
539
+ await FoodModel.deleteMany({});
540
+ });
541
+
542
+ it("denies the admin shell when the caller lacks admin:access", async () => {
543
+ const app = buildMatrixApp({
544
+ [ADMIN_EMAIL]: {admin: ["access"], adminFood: ["read"]},
545
+ [MEMBER_EMAIL]: {},
546
+ });
547
+ const member = await authAsUser(app, "notAdmin");
548
+ await member.get("/admin/config").expect(403);
549
+ await member.get("/admin/foods").expect(405);
550
+ });
551
+
552
+ it("does not open the admin page with other admin permissions alone", async () => {
553
+ const app = buildMatrixApp({
554
+ [ADMIN_EMAIL]: {admin: ["runScripts", "viewBackgroundTasks"], adminFood: ["read", "write"]},
555
+ });
556
+ const agent = await authAsUser(app, "admin");
557
+ await agent.get("/admin/config").expect(403);
558
+ await agent.get("/admin/foods").expect(405);
559
+ });
560
+
561
+ it("hides models and mutations when the caller only has admin:access", async () => {
562
+ const app = buildMatrixApp({
563
+ [ADMIN_EMAIL]: {admin: ["access"]},
564
+ });
565
+ const agent = await authAsUser(app, "admin");
566
+ const config = await agent.get("/admin/config").expect(200);
567
+ assert.deepEqual(config.body.models, []);
568
+ assert.deepEqual(config.body.customScreens, []);
569
+ await agent.get("/admin/foods").expect(405);
570
+ await agent.post("/admin/foods").send({calories: 1, name: "Nope"}).expect(405);
571
+ });
572
+
573
+ it("allows reads and denies writes for a read-only role", async () => {
574
+ const app = buildMatrixApp({
575
+ [ADMIN_EMAIL]: {admin: ["access"], adminFood: ["read"]},
576
+ });
577
+ const agent = await authAsUser(app, "admin");
578
+ const actor = await findOneOrNoneFor(UserModel, {email: ADMIN_EMAIL});
579
+ assert.exists(actor);
580
+ const food = await FoodModel.create({calories: 1, name: "Owned", ownerId: actor?._id});
581
+
582
+ const config = await agent.get("/admin/config").expect(200);
583
+ assert.deepInclude(config.body.models[0].permissions, {
584
+ create: false,
585
+ delete: false,
586
+ update: false,
587
+ });
588
+ await agent.get("/admin/foods").expect(200);
589
+ await agent.get(`/admin/foods/${food._id}`).expect(200);
590
+ await agent.post("/admin/foods").send({calories: 2, name: "Denied"}).expect(405);
591
+ await agent.patch(`/admin/foods/${food._id}`).send({calories: 3}).expect(405);
592
+ await agent.delete(`/admin/foods/${food._id}`).expect(405);
593
+ });
594
+
595
+ it("allows full CRUD for a write role, including records the caller does not own", async () => {
596
+ const app = buildMatrixApp({
597
+ [ADMIN_EMAIL]: {admin: ["access"], adminFood: ["read", "write"]},
598
+ });
599
+ const agent = await authAsUser(app, "admin");
600
+ const other = await FoodModel.create({
601
+ calories: 1,
602
+ name: "Other",
603
+ ownerId: new mongoose.Types.ObjectId(),
604
+ });
605
+
606
+ const config = await agent.get("/admin/config").expect(200);
607
+ assert.deepInclude(config.body.models[0].permissions, {
608
+ create: true,
609
+ delete: true,
610
+ update: true,
611
+ });
612
+ await agent.post("/admin/foods").send({calories: 2, name: "Created"}).expect(201);
613
+ const patched = await agent.patch(`/admin/foods/${other._id}`).send({calories: 9}).expect(200);
614
+ assert.equal(patched.body.data.calories, 9);
615
+ await agent.delete(`/admin/foods/${other._id}`).expect(204);
616
+ });
617
+
618
+ it("scopes writeOwned updates and deletes to owned records for that role", async () => {
619
+ const app = buildMatrixApp({
620
+ [ADMIN_EMAIL]: {admin: ["access"], adminFood: ["read", "writeOwned"]},
621
+ });
622
+ const agent = await authAsUser(app, "admin");
623
+ const actor = await findOneOrNoneFor(UserModel, {email: ADMIN_EMAIL});
624
+ assert.exists(actor);
625
+ const owned = await FoodModel.create({calories: 1, name: "Owned", ownerId: actor?._id});
626
+ const other = await FoodModel.create({
627
+ calories: 2,
628
+ name: "Other",
629
+ ownerId: new mongoose.Types.ObjectId(),
630
+ });
631
+
632
+ const ownedRead = await agent.get(`/admin/foods/${owned._id}`).expect(200);
633
+ const otherRead = await agent.get(`/admin/foods/${other._id}`).expect(200);
634
+ assert.deepEqual(ownedRead.body.data._adminCapabilities, {delete: true, update: true});
635
+ assert.deepEqual(otherRead.body.data._adminCapabilities, {delete: false, update: false});
636
+ await agent.patch(`/admin/foods/${owned._id}`).send({calories: 4}).expect(200);
637
+ await agent.patch(`/admin/foods/${other._id}`).send({calories: 5}).expect(403);
638
+ await agent.delete(`/admin/foods/${other._id}`).expect(403);
639
+ await agent.delete(`/admin/foods/${owned._id}`).expect(204);
640
+ await agent.post("/admin/foods").send({calories: 6, name: "Unassigned"}).expect(201);
641
+ });
642
+
643
+ it("applies different adminAccess grants to different users on the same app", async () => {
644
+ const app = buildMatrixApp({
645
+ [ADMIN_EMAIL]: {admin: ["access"], adminFood: ["read", "write"]},
646
+ [MEMBER_EMAIL]: {admin: ["access"], adminFood: ["read"]},
647
+ });
648
+ const writer = await authAsUser(app, "admin");
649
+ const reader = await authAsUser(app, "notAdmin");
650
+ const writerUser = await findOneOrNoneFor(UserModel, {email: ADMIN_EMAIL});
651
+ assert.exists(writerUser);
652
+ const food = await FoodModel.create({calories: 1, name: "Shared", ownerId: writerUser?._id});
653
+
654
+ const writerConfig = await writer.get("/admin/config").expect(200);
655
+ const readerConfig = await reader.get("/admin/config").expect(200);
656
+ assert.deepInclude(writerConfig.body.models[0].permissions, {
657
+ create: true,
658
+ delete: true,
659
+ update: true,
660
+ });
661
+ assert.deepInclude(readerConfig.body.models[0].permissions, {
662
+ create: false,
663
+ delete: false,
664
+ update: false,
665
+ });
666
+ await writer.patch(`/admin/foods/${food._id}`).send({calories: 8}).expect(200);
667
+ await reader.patch(`/admin/foods/${food._id}`).send({calories: 9}).expect(405);
668
+ await reader.get("/admin/foods").expect(200);
669
+ await reader.post("/admin/foods").send({calories: 3, name: "Reader"}).expect(405);
670
+ });
671
+
672
+ it("exposes platform tools and custom screens only for roles that grant them", async () => {
673
+ const app = buildMatrixApp({
674
+ [ADMIN_EMAIL]: {
675
+ admin: ["access", "runScripts", "viewBackgroundTasks"],
676
+ adminScreen: ["showcase"],
677
+ configuration: ["read"],
678
+ rbac: ["read"],
679
+ },
680
+ [MEMBER_EMAIL]: {admin: ["access"], adminFood: ["read"]},
681
+ });
682
+ const operator = await authAsUser(app, "admin");
683
+ const reader = await authAsUser(app, "notAdmin");
684
+
685
+ const operatorConfig = await operator.get("/admin/config").expect(200);
686
+ const readerConfig = await reader.get("/admin/config").expect(200);
687
+ const operatorScreens = operatorConfig.body.customScreens.map(
688
+ (screen: {name: string}) => screen.name
689
+ );
690
+ const readerScreens = readerConfig.body.customScreens.map(
691
+ (screen: {name: string}) => screen.name
692
+ );
693
+ assert.include(operatorScreens, "showcase");
694
+ assert.notInclude(readerScreens, "showcase");
695
+ assert.deepEqual(operatorConfig.body.platformTools, {
696
+ configuration: true,
697
+ roles: true,
698
+ runScripts: true,
699
+ scripts: true,
700
+ version: true,
701
+ viewScripts: true,
702
+ });
703
+ assert.deepEqual(
704
+ operatorConfig.body.scripts.map((script: {name: string}) => script.name),
705
+ ["seed"]
706
+ );
707
+ assert.deepEqual(readerConfig.body.customScreens, []);
708
+ assert.deepEqual(readerConfig.body.platformTools, {
709
+ configuration: false,
710
+ roles: false,
711
+ runScripts: false,
712
+ scripts: false,
713
+ version: false,
714
+ viewScripts: false,
715
+ });
716
+ assert.deepEqual(readerConfig.body.scripts, []);
717
+ assert.deepEqual(
718
+ readerConfig.body.models.map((model: {name: string}) => model.name),
719
+ ["Food"]
720
+ );
721
+ });
722
+
723
+ it("lets authorize allow writes for one user and deny them for another", async () => {
724
+ const accessControl = createAccess({
725
+ connection: mongoose.connection,
726
+ resolvePermissions: async () => ({admin: ["access"]}),
727
+ statements: terrenoStatements,
728
+ });
729
+ const app = buildApp(
730
+ [
731
+ {
732
+ ...foodModelConfig,
733
+ adminAccess: {
734
+ authorize: ({action, user}) => {
735
+ const email =
736
+ user && "email" in user && typeof user.email === "string" ? user.email : "";
737
+ if (email === ADMIN_EMAIL) {
738
+ return true;
739
+ }
740
+ return action === "list" || action === "read";
741
+ },
742
+ },
743
+ },
744
+ ],
745
+ {accessControl}
746
+ );
747
+ const writer = await authAsUser(app, "admin");
748
+ const reader = await authAsUser(app, "notAdmin");
749
+
750
+ const writerConfig = await writer.get("/admin/config").expect(200);
751
+ const readerConfig = await reader.get("/admin/config").expect(200);
752
+ assert.deepInclude(writerConfig.body.models[0].permissions, {
753
+ create: true,
754
+ delete: true,
755
+ update: true,
756
+ });
757
+ assert.deepInclude(readerConfig.body.models[0].permissions, {
758
+ create: false,
759
+ delete: false,
760
+ update: false,
761
+ });
762
+ await writer.post("/admin/foods").send({calories: 1, name: "Allowed"}).expect(201);
763
+ await reader.post("/admin/foods").send({calories: 1, name: "Denied"}).expect(405);
764
+ await reader.get("/admin/foods").expect(200);
765
+ });
243
766
  });
244
767
 
245
768
  describe("AdminApp model CRUD routes", () => {
@@ -307,11 +830,12 @@ describe("AdminApp model CRUD routes", () => {
307
830
  expect([401, 403, 405]).toContain(res.status);
308
831
  });
309
832
 
310
- it("supports models without hiddenFields (no responseHandler installed)", async () => {
833
+ it("scrubs responses even when the parent model has no hidden or exclude fields", async () => {
311
834
  app = buildApp([foodModelConfig]);
312
835
  const agent = await authAsUser(app, "admin");
313
836
  await FoodModel.create({calories: 120, hidden: true, name: "Apple"});
314
837
  const res = await agent.get("/admin/foods").expect(200);
838
+ expect(res.body.data[0].name).toBe("Apple");
315
839
  expect(res.body.data[0].hidden).toBe(true);
316
840
  });
317
841
 
@@ -420,6 +944,47 @@ describe("AdminApp /admin/version-config", () => {
420
944
  await notAdminAgent.put("/admin/version-config").send({}).expect(403);
421
945
  });
422
946
 
947
+ it("requires configuration:update to PUT version-config when accessControl is set", async () => {
948
+ const accessControl = createAccess({
949
+ connection: mongoose.connection,
950
+ sources: [
951
+ {
952
+ getGrants: async () => ({permissions: {admin: ["access"]}}),
953
+ name: "admin-access-only",
954
+ },
955
+ ],
956
+ statements: terrenoStatements,
957
+ });
958
+ await accessControl.roles.seedDefaults();
959
+ const localApp = buildApp([], {accessControl});
960
+ const agent = await authAsUser(localApp, "admin");
961
+ await agent.get("/admin/version-config").expect(403);
962
+ await agent.put("/admin/version-config").send({mobileRequiredVersion: 3}).expect(403);
963
+ });
964
+
965
+ it("allows configuration:update to PUT version-config", async () => {
966
+ const accessControl = createAccess({
967
+ connection: mongoose.connection,
968
+ sources: [
969
+ {
970
+ getGrants: async () => ({
971
+ permissions: {admin: ["access"], configuration: ["read", "update"]},
972
+ }),
973
+ name: "config-admin",
974
+ },
975
+ ],
976
+ statements: terrenoStatements,
977
+ });
978
+ await accessControl.roles.seedDefaults();
979
+ const localApp = buildApp([], {accessControl});
980
+ const agent = await authAsUser(localApp, "admin");
981
+ const res = await agent
982
+ .put("/admin/version-config")
983
+ .send({mobileRequiredVersion: 3})
984
+ .expect(200);
985
+ expect(res.body.mobileRequiredVersion).toBe(3);
986
+ });
987
+
423
988
  it("returns 401 for unauthenticated users", async () => {
424
989
  await supertest(app).get("/admin/version-config").expect(401);
425
990
  });
@@ -620,6 +1185,42 @@ describe("AdminApp admin UI v2 routes", () => {
620
1185
  await notAdminAgent.post("/admin/background-tasks").send({kind: "x"}).expect(403);
621
1186
  });
622
1187
 
1188
+ it("requires admin:runScripts to enqueue background tasks when accessControl is set", async () => {
1189
+ const accessControl = createAccess({
1190
+ connection: mongoose.connection,
1191
+ sources: [
1192
+ {
1193
+ getGrants: async () => ({permissions: {admin: ["access"]}}),
1194
+ name: "admin-access-only",
1195
+ },
1196
+ ],
1197
+ statements: terrenoStatements,
1198
+ });
1199
+ await accessControl.roles.seedDefaults();
1200
+ const localApp = buildApp([foodModelConfig], {accessControl});
1201
+ const agent = await authAsUser(localApp, "admin");
1202
+ await agent.post("/admin/background-tasks").send({kind: "reindex-search"}).expect(403);
1203
+ });
1204
+
1205
+ it("allows admin:runScripts to enqueue background tasks", async () => {
1206
+ const accessControl = createAccess({
1207
+ connection: mongoose.connection,
1208
+ sources: [
1209
+ {
1210
+ getGrants: async () => ({
1211
+ permissions: {admin: ["access", "runScripts"]},
1212
+ }),
1213
+ name: "admin-run-scripts",
1214
+ },
1215
+ ],
1216
+ statements: terrenoStatements,
1217
+ });
1218
+ await accessControl.roles.seedDefaults();
1219
+ const localApp = buildApp([foodModelConfig], {accessControl});
1220
+ const agent = await authAsUser(localApp, "admin");
1221
+ await agent.post("/admin/background-tasks").send({kind: "reindex-search"}).expect(201);
1222
+ });
1223
+
623
1224
  it("strips readonly fields from PATCH updates", async () => {
624
1225
  app = buildApp([
625
1226
  {
@@ -791,4 +1392,723 @@ describe("AdminApp per-model queryFilter", () => {
791
1392
  expect(res.body.data).toHaveLength(1);
792
1393
  expect(res.body.data[0].name).toBe("FilteredOnly");
793
1394
  });
1395
+
1396
+ it("fails closed on list and mutating CRUD when the model is missing from RBAC statements", async () => {
1397
+ await setupDb();
1398
+ const accessControl = createAccess({
1399
+ connection: mongoose.connection,
1400
+ sources: [
1401
+ {
1402
+ getGrants: async () => ({permissions: {admin: ["access"]}}),
1403
+ name: "admin-access",
1404
+ },
1405
+ ],
1406
+ statements: terrenoStatements,
1407
+ });
1408
+ await accessControl.roles.seedDefaults();
1409
+
1410
+ const localApp = buildApp([foodModelConfig], {accessControl});
1411
+ const agent = await authAsUser(localApp, "admin");
1412
+
1413
+ await agent.get("/admin/foods").expect(405);
1414
+ await agent.get("/admin/foods/search?q=x").expect(403);
1415
+ await agent.post("/admin/foods").send({calories: 1, name: "Nope"}).expect(405);
1416
+ });
1417
+
1418
+ it("applies queryFilter to admin search so autocomplete cannot leak out-of-scope rows", async () => {
1419
+ const localApp = buildApp([
1420
+ {
1421
+ ...foodModelConfig,
1422
+ queryFilter: (_user, query): Record<string, unknown> => ({
1423
+ ...(query ?? {}),
1424
+ name: "FilteredOnly",
1425
+ }),
1426
+ },
1427
+ ]);
1428
+ await FoodModel.create({calories: 1, name: "OtherApple"});
1429
+ await FoodModel.create({calories: 2, name: "FilteredOnly"});
1430
+ const agent = await authAsUser(localApp, "admin");
1431
+ const res = await agent.get("/admin/foods/search?q=e").expect(200);
1432
+ expect(res.body.data).toHaveLength(1);
1433
+ expect(res.body.data[0].name).toBe("FilteredOnly");
1434
+ });
1435
+
1436
+ it("accepts Mongo operators from queryFilter without treating them as client filters", async () => {
1437
+ const localApp = buildApp([
1438
+ {
1439
+ ...foodModelConfig,
1440
+ queryFilter: (): Record<string, unknown> => ({
1441
+ $or: [{name: "Alpha"}, {name: "Beta"}],
1442
+ }),
1443
+ },
1444
+ ]);
1445
+ await FoodModel.create({calories: 1, name: "Alpha"});
1446
+ await FoodModel.create({calories: 2, name: "Other"});
1447
+ const agent = await authAsUser(localApp, "admin");
1448
+ const res = await agent.get("/admin/foods").expect(200);
1449
+ expect(res.body.data).toHaveLength(1);
1450
+ expect(res.body.data[0].name).toBe("Alpha");
1451
+ });
1452
+
1453
+ it("applies q against searchFields derived from listFields when none are configured", async () => {
1454
+ const localApp = buildApp([foodModelConfig]);
1455
+ await FoodModel.create({calories: 1, name: "GreenApple"});
1456
+ await FoodModel.create({calories: 2, name: "Banana"});
1457
+ const agent = await authAsUser(localApp, "admin");
1458
+ const res = await agent.get("/admin/foods?q=apple").expect(200);
1459
+ expect(res.body.data).toHaveLength(1);
1460
+ expect(res.body.data[0].name).toBe("GreenApple");
1461
+ });
1462
+
1463
+ it("applies q as a case-insensitive partial match across searchFields", async () => {
1464
+ const localApp = buildApp([
1465
+ {
1466
+ ...foodModelConfig,
1467
+ searchFields: ["name"],
1468
+ },
1469
+ ]);
1470
+ await FoodModel.create({calories: 1, name: "GreenApple"});
1471
+ await FoodModel.create({calories: 2, name: "Banana"});
1472
+ const agent = await authAsUser(localApp, "admin");
1473
+ const res = await agent.get("/admin/foods?q=apple").expect(200);
1474
+ expect(res.body.data).toHaveLength(1);
1475
+ expect(res.body.data[0].name).toBe("GreenApple");
1476
+ });
1477
+
1478
+ it("allows default -created sort even when created is not in listDisplay", async () => {
1479
+ const localApp = buildApp([
1480
+ {
1481
+ displayName: "Foods",
1482
+ listFields: ["name"],
1483
+ model: FoodModel,
1484
+ routePath: "/foods",
1485
+ },
1486
+ ]);
1487
+ const agent = await authAsUser(localApp, "admin");
1488
+ await agent.get("/admin/foods?sort=-created").expect(200);
1489
+ });
1490
+
1491
+ it("strips excludeFields from admin create and update bodies", async () => {
1492
+ const localApp = buildApp([
1493
+ {
1494
+ ...foodModelConfig,
1495
+ excludeFields: ["calories"],
1496
+ },
1497
+ ]);
1498
+ const agent = await authAsUser(localApp, "admin");
1499
+ const created = await agent
1500
+ .post("/admin/foods")
1501
+ .send({calories: 999, name: "Stripped"})
1502
+ .expect(201);
1503
+ expect(created.body.data.calories).toBeUndefined();
1504
+ const createdId = created.body.data._id as string;
1505
+ const stored = await FoodModel.findById(createdId).lean();
1506
+ expect(stored?.calories).toBeUndefined();
1507
+
1508
+ await FoodModel.updateOne({_id: createdId}, {calories: 12});
1509
+ const patched = await agent
1510
+ .patch(`/admin/foods/${createdId}`)
1511
+ .send({calories: 50, name: "Renamed"})
1512
+ .expect(200);
1513
+ expect(patched.body.data.name).toBe("Renamed");
1514
+ const after = await FoodModel.findById(createdId).lean();
1515
+ expect(after?.calories).toBe(12);
1516
+ });
1517
+ });
1518
+
1519
+ describe("AdminApp user elevation and scoped bulk-patch", () => {
1520
+ beforeEach(async () => {
1521
+ await setupDb();
1522
+ });
1523
+
1524
+ afterEach(async () => {
1525
+ await FoodModel.deleteMany({});
1526
+ await VersionConfig.deleteMany({});
1527
+ });
1528
+
1529
+ it("allows admin CRUD to set the User admin flag", async () => {
1530
+ const localApp = buildApp([
1531
+ {
1532
+ displayName: "Users",
1533
+ listFields: ["email", "admin"],
1534
+ model: UserModel,
1535
+ routePath: "/users",
1536
+ },
1537
+ ]);
1538
+ const agent = await authAsUser(localApp, "admin");
1539
+ const target = await UserModel.findOne({email: "notAdmin@example.com"});
1540
+ expect(target).toBeTruthy();
1541
+
1542
+ await agent
1543
+ .patch(`/admin/users/${String(target?._id)}`)
1544
+ .send({admin: true})
1545
+ .expect(200);
1546
+
1547
+ const after = await UserModel.findById(target?._id);
1548
+ expect(after?.admin).toBe(true);
1549
+ });
1550
+
1551
+ it("requires rbac:assignRoles to set User admin when accessControl is enabled", async () => {
1552
+ const accessControl = createAccess({
1553
+ connection: mongoose.connection,
1554
+ sources: [
1555
+ {
1556
+ getGrants: async () => ({
1557
+ permissions: {
1558
+ admin: ["access"],
1559
+ user: ["create", "list", "read", "update"],
1560
+ },
1561
+ }),
1562
+ name: "admin-without-assign",
1563
+ },
1564
+ ],
1565
+ statements: terrenoStatements,
1566
+ userModel: UserModel as unknown as UserModelType,
1567
+ });
1568
+ await accessControl.roles.seedDefaults();
1569
+
1570
+ const localApp = buildApp(
1571
+ [
1572
+ {
1573
+ displayName: "Users",
1574
+ listFields: ["email", "admin"],
1575
+ model: UserModel,
1576
+ routePath: "/users",
1577
+ },
1578
+ ],
1579
+ {accessControl}
1580
+ );
1581
+ const agent = await authAsUser(localApp, "admin");
1582
+ const target = await UserModel.findOne({email: "notAdmin@example.com"});
1583
+ expect(target).toBeTruthy();
1584
+ expect(target?.admin).toBe(false);
1585
+
1586
+ await agent
1587
+ .patch(`/admin/users/${String(target?._id)}`)
1588
+ .send({admin: true})
1589
+ .expect(403);
1590
+
1591
+ const afterDenied = await UserModel.findById(target?._id);
1592
+ expect(afterDenied?.admin).toBe(false);
1593
+
1594
+ await agent
1595
+ .patch(`/admin/users/${String(target?._id)}`)
1596
+ .send({admin: false, name: "Kept"})
1597
+ .expect(200);
1598
+ const afterEcho = await UserModel.findById(target?._id);
1599
+ expect(afterEcho?.admin).toBe(false);
1600
+ expect(afterEcho?.name).toBe("Kept");
1601
+
1602
+ const created = await agent
1603
+ .post("/admin/users")
1604
+ .send({admin: false, email: "form-echo-admin@example.com"})
1605
+ .expect(201);
1606
+ expect(created.body.data.admin).toBe(false);
1607
+ expect(await UserModel.findOne({email: "form-echo-admin@example.com"})).toBeTruthy();
1608
+
1609
+ await UserModel.updateOne({_id: target?._id}, {admin: true});
1610
+ await agent
1611
+ .patch(`/admin/users/${String(target?._id)}`)
1612
+ .send({admin: "false"})
1613
+ .expect(403);
1614
+ expect((await UserModel.findById(target?._id))?.admin).toBe(true);
1615
+ });
1616
+
1617
+ it("does not let assignRoles grant the legacy admin flag", async () => {
1618
+ const accessControl = createAccess({
1619
+ connection: mongoose.connection,
1620
+ sources: [
1621
+ {
1622
+ getGrants: async () => ({
1623
+ permissions: {
1624
+ admin: ["access"],
1625
+ rbac: ["assignRoles"],
1626
+ user: ["create", "list", "read", "update"],
1627
+ },
1628
+ }),
1629
+ name: "assigner-without-legacy-admin",
1630
+ },
1631
+ ],
1632
+ statements: terrenoStatements,
1633
+ userModel: UserModel as unknown as UserModelType,
1634
+ });
1635
+ await accessControl.roles.seedDefaults();
1636
+
1637
+ const localApp = buildApp(
1638
+ [
1639
+ {
1640
+ displayName: "Users",
1641
+ listFields: ["email", "admin"],
1642
+ model: UserModel,
1643
+ routePath: "/users",
1644
+ },
1645
+ ],
1646
+ {accessControl}
1647
+ );
1648
+ const agent = await authAsUser(localApp, "notAdmin");
1649
+ const target = await UserModel.findOne({email: "notAdmin@example.com"});
1650
+ expect(target?.admin).toBe(false);
1651
+
1652
+ await agent
1653
+ .patch(`/admin/users/${String(target?._id)}`)
1654
+ .send({admin: true})
1655
+ .expect(403);
1656
+ expect((await UserModel.findById(target?._id))?.admin).toBe(false);
1657
+ });
1658
+
1659
+ it("does not let assignRoles revoke the legacy admin flag", async () => {
1660
+ const accessControl = createAccess({
1661
+ connection: mongoose.connection,
1662
+ sources: [
1663
+ {
1664
+ getGrants: async () => ({
1665
+ permissions: {
1666
+ admin: ["access"],
1667
+ rbac: ["assignRoles"],
1668
+ user: ["create", "list", "read", "update"],
1669
+ },
1670
+ }),
1671
+ name: "assigner-without-legacy-admin",
1672
+ },
1673
+ ],
1674
+ statements: terrenoStatements,
1675
+ userModel: UserModel as unknown as UserModelType,
1676
+ });
1677
+ await accessControl.roles.seedDefaults();
1678
+
1679
+ const localApp = buildApp(
1680
+ [
1681
+ {
1682
+ displayName: "Users",
1683
+ listFields: ["email", "admin"],
1684
+ model: UserModel,
1685
+ routePath: "/users",
1686
+ },
1687
+ ],
1688
+ {accessControl}
1689
+ );
1690
+ const agent = await authAsUser(localApp, "notAdmin");
1691
+ const target = await UserModel.findOne({email: "admin@example.com"});
1692
+ expect(target?.admin).toBe(true);
1693
+
1694
+ await agent
1695
+ .patch(`/admin/users/${String(target?._id)}`)
1696
+ .send({admin: false})
1697
+ .expect(403);
1698
+ expect((await UserModel.findById(target?._id))?.admin).toBe(true);
1699
+ });
1700
+
1701
+ it("does not let manageRoles mint the legacy admin flag", async () => {
1702
+ const accessControl = createAccess({
1703
+ connection: mongoose.connection,
1704
+ sources: [
1705
+ {
1706
+ getGrants: async () => ({
1707
+ permissions: {
1708
+ admin: ["access"],
1709
+ rbac: ["assignRoles", "manageRoles"],
1710
+ user: ["create", "list", "read", "update"],
1711
+ },
1712
+ }),
1713
+ name: "manager-without-legacy-admin",
1714
+ },
1715
+ ],
1716
+ statements: terrenoStatements,
1717
+ userModel: UserModel as unknown as UserModelType,
1718
+ });
1719
+ await accessControl.roles.seedDefaults();
1720
+
1721
+ const localApp = buildApp(
1722
+ [
1723
+ {
1724
+ displayName: "Users",
1725
+ listFields: ["email", "admin"],
1726
+ model: UserModel,
1727
+ routePath: "/users",
1728
+ },
1729
+ ],
1730
+ {accessControl}
1731
+ );
1732
+ const agent = await authAsUser(localApp, "notAdmin");
1733
+ const target = await UserModel.findOne({email: "notAdmin@example.com"});
1734
+ expect(target?.admin).toBe(false);
1735
+
1736
+ await agent
1737
+ .patch(`/admin/users/${String(target?._id)}`)
1738
+ .send({admin: true})
1739
+ .expect(403);
1740
+ expect((await UserModel.findById(target?._id))?.admin).toBe(false);
1741
+
1742
+ await agent
1743
+ .post("/admin/users")
1744
+ .send({admin: true, email: "minted-admin@example.com"})
1745
+ .expect(403);
1746
+ expect(await UserModel.findOne({email: "minted-admin@example.com"})).toBeNull();
1747
+ });
1748
+
1749
+ it("does not let manageRoles revoke the legacy admin flag", async () => {
1750
+ const accessControl = createAccess({
1751
+ connection: mongoose.connection,
1752
+ sources: [
1753
+ {
1754
+ getGrants: async () => ({
1755
+ permissions: {
1756
+ admin: ["access"],
1757
+ rbac: ["assignRoles", "manageRoles"],
1758
+ user: ["create", "list", "read", "update"],
1759
+ },
1760
+ }),
1761
+ name: "manager-without-legacy-admin",
1762
+ },
1763
+ ],
1764
+ statements: terrenoStatements,
1765
+ userModel: UserModel as unknown as UserModelType,
1766
+ });
1767
+ await accessControl.roles.seedDefaults();
1768
+
1769
+ const localApp = buildApp(
1770
+ [
1771
+ {
1772
+ displayName: "Users",
1773
+ listFields: ["email", "admin"],
1774
+ model: UserModel,
1775
+ routePath: "/users",
1776
+ },
1777
+ ],
1778
+ {accessControl}
1779
+ );
1780
+ const agent = await authAsUser(localApp, "notAdmin");
1781
+ const target = await UserModel.findOne({email: "admin@example.com"});
1782
+ expect(target?.admin).toBe(true);
1783
+
1784
+ await agent
1785
+ .patch(`/admin/users/${String(target?._id)}`)
1786
+ .send({admin: false})
1787
+ .expect(403);
1788
+ expect((await UserModel.findById(target?._id))?.admin).toBe(true);
1789
+ });
1790
+
1791
+ it("does not persist organizationIds on RBAC admin User writes", async () => {
1792
+ const accessControl = createAccess({
1793
+ connection: mongoose.connection,
1794
+ sources: [
1795
+ {
1796
+ getGrants: async () => ({
1797
+ permissions: {
1798
+ admin: ["access"],
1799
+ rbac: ["assignRoles"],
1800
+ user: ["create", "list", "read", "update"],
1801
+ },
1802
+ }),
1803
+ name: "admin-user-editor",
1804
+ },
1805
+ ],
1806
+ statements: terrenoStatements,
1807
+ userModel: UserModel as unknown as UserModelType,
1808
+ });
1809
+ await accessControl.roles.seedDefaults();
1810
+
1811
+ const localApp = buildApp(
1812
+ [
1813
+ {
1814
+ bulkPatchAllowlist: ["name", "organizationIds"],
1815
+ displayName: "Users",
1816
+ listFields: ["email", "admin"],
1817
+ model: UserModel,
1818
+ routePath: "/users",
1819
+ },
1820
+ ],
1821
+ {accessControl}
1822
+ );
1823
+ const agent = await authAsUser(localApp, "admin");
1824
+ const target = await UserModel.findOne({email: "notAdmin@example.com"});
1825
+ expect(target).toBeTruthy();
1826
+
1827
+ await agent
1828
+ .patch(`/admin/users/${String(target?._id)}`)
1829
+ .send({name: "Org-stripped", organizationIds: ["other-tenant"]})
1830
+ .expect(200);
1831
+ const afterPatch = await UserModel.findById(target?._id);
1832
+ expect(afterPatch?.name).toBe("Org-stripped");
1833
+ expect(
1834
+ (afterPatch as {organizationIds?: string[]} | null)?.organizationIds ?? []
1835
+ ).not.toContain("other-tenant");
1836
+
1837
+ const created = await agent
1838
+ .post("/admin/users")
1839
+ .send({email: "org-stripped@example.com", organizationIds: ["other-tenant"]})
1840
+ .expect(201);
1841
+ expect(created.body.data.organizationIds ?? []).not.toContain("other-tenant");
1842
+ const createdDoc = await UserModel.findOne({email: "org-stripped@example.com"});
1843
+ expect(
1844
+ (createdDoc as {organizationIds?: string[]} | null)?.organizationIds ?? []
1845
+ ).not.toContain("other-tenant");
1846
+
1847
+ await agent
1848
+ .post("/admin/users/bulk-patch")
1849
+ .send({
1850
+ ids: [String(target?._id)],
1851
+ patch: {organizationIds: ["bulk-tenant"]},
1852
+ })
1853
+ .expect(400);
1854
+ expect(
1855
+ ((await UserModel.findById(target?._id)) as {organizationIds?: string[]} | null)
1856
+ ?.organizationIds ?? []
1857
+ ).not.toContain("bulk-tenant");
1858
+ });
1859
+
1860
+ it("checks each bulk-patch target document against RBAC scopes", async () => {
1861
+ const foodStatements = {
1862
+ ...terrenoStatements,
1863
+ food: ["create", "list", "read", "update", "delete"],
1864
+ } as const;
1865
+ const accessControl = createAccess({
1866
+ connection: mongoose.connection,
1867
+ scopes: {
1868
+ "food.update": {
1869
+ check: ({doc, user}) => {
1870
+ if (!doc) {
1871
+ return true;
1872
+ }
1873
+ const ownerId = (doc as {ownerId?: unknown}).ownerId;
1874
+ return String(ownerId) === String(user.id);
1875
+ },
1876
+ },
1877
+ },
1878
+ sources: [
1879
+ {
1880
+ getGrants: async () => ({
1881
+ permissions: {admin: ["access"], food: ["list", "read", "update"]},
1882
+ }),
1883
+ name: "scoped-food-update",
1884
+ },
1885
+ ],
1886
+ statements: foodStatements,
1887
+ });
1888
+ await accessControl.roles.seedDefaults();
1889
+
1890
+ const localApp = buildApp([{...foodModelConfig, bulkPatchAllowlist: ["calories", "name"]}], {
1891
+ accessControl,
1892
+ });
1893
+ const agent = await authAsUser(localApp, "admin");
1894
+ const actor = await UserModel.findOne({email: "admin@example.com"});
1895
+ const other = await UserModel.findOne({email: "notAdmin@example.com"});
1896
+ expect(actor).toBeTruthy();
1897
+ expect(other).toBeTruthy();
1898
+
1899
+ const owned = await FoodModel.create({
1900
+ calories: 1,
1901
+ name: "Owned",
1902
+ ownerId: actor?._id,
1903
+ });
1904
+ const foreign = await FoodModel.create({
1905
+ calories: 2,
1906
+ name: "Foreign",
1907
+ ownerId: other?._id,
1908
+ });
1909
+
1910
+ const res = await agent
1911
+ .post("/admin/foods/bulk-patch")
1912
+ .send({
1913
+ ids: [String(owned._id), String(foreign._id)],
1914
+ patch: {calories: 50},
1915
+ })
1916
+ .expect(200);
1917
+
1918
+ expect(res.body.updated).toBe(1);
1919
+ expect(res.body.failures).toEqual([{id: String(foreign._id), title: "Forbidden"}]);
1920
+ expect((await FoodModel.findById(owned._id).lean())?.calories).toBe(50);
1921
+ expect((await FoodModel.findById(foreign._id).lean())?.calories).toBe(2);
1922
+ });
1923
+
1924
+ it("returns assigned User roles in the admin update response", async () => {
1925
+ if (!UserModel.schema.path("roles")) {
1926
+ UserModel.schema.add({
1927
+ roles: {default: [], description: "RBAC role names", type: [String]},
1928
+ });
1929
+ }
1930
+ const accessControl = createAccess({
1931
+ connection: mongoose.connection,
1932
+ sources: [
1933
+ {
1934
+ getGrants: async () => ({
1935
+ permissions: {
1936
+ admin: ["access"],
1937
+ rbac: ["assignRoles", "manageRoles"],
1938
+ user: ["create", "list", "read", "update"],
1939
+ },
1940
+ }),
1941
+ name: "admin-user-role-editor",
1942
+ },
1943
+ ],
1944
+ statements: terrenoStatements,
1945
+ userModel: UserModel as unknown as UserModelType,
1946
+ });
1947
+ await accessControl.roles.seedDefaults();
1948
+
1949
+ const localApp = buildApp(
1950
+ [
1951
+ {
1952
+ displayName: "Users",
1953
+ listFields: ["email", "roles"],
1954
+ model: UserModel,
1955
+ routePath: "/users",
1956
+ },
1957
+ ],
1958
+ {accessControl}
1959
+ );
1960
+ const agent = await authAsUser(localApp, "admin");
1961
+ const target = await UserModel.findOne({email: "notAdmin@example.com"});
1962
+ expect(target).toBeTruthy();
1963
+
1964
+ const response = await agent
1965
+ .patch(`/admin/users/${String(target?._id)}`)
1966
+ .send({roles: ["member"]})
1967
+ .expect(200);
1968
+
1969
+ expect(response.body.data.roles).toEqual(["member"]);
1970
+ });
1971
+
1972
+ it("deletes a newly created User when role assignment fails", async () => {
1973
+ const accessControl = createAccess({
1974
+ connection: mongoose.connection,
1975
+ sources: [
1976
+ {
1977
+ getGrants: async () => ({
1978
+ permissions: {
1979
+ admin: ["access"],
1980
+ rbac: ["assignRoles"],
1981
+ user: ["create", "list", "read", "update"],
1982
+ },
1983
+ }),
1984
+ name: "admin-user-create",
1985
+ },
1986
+ ],
1987
+ statements: terrenoStatements,
1988
+ userModel: UserModel as unknown as UserModelType,
1989
+ });
1990
+ await accessControl.roles.seedDefaults();
1991
+
1992
+ const localApp = buildApp(
1993
+ [
1994
+ {
1995
+ displayName: "Users",
1996
+ listFields: ["email"],
1997
+ model: UserModel,
1998
+ routePath: "/users",
1999
+ },
2000
+ ],
2001
+ {accessControl}
2002
+ );
2003
+ const agent = await authAsUser(localApp, "admin");
2004
+ const email = "rollback-roles@example.com";
2005
+
2006
+ const res = await agent.post("/admin/users").send({email, roles: ["does-not-exist"]});
2007
+ expect(res.status).toBeGreaterThanOrEqual(400);
2008
+ expect(await UserModel.findOne({email})).toBeNull();
2009
+ });
2010
+
2011
+ it("does not persist other User fields when role assignment fails on update", async () => {
2012
+ if (!UserModel.schema.path("roles")) {
2013
+ UserModel.schema.add({
2014
+ roles: {default: [], description: "RBAC role names", type: [String]},
2015
+ });
2016
+ }
2017
+ const accessControl = createAccess({
2018
+ connection: mongoose.connection,
2019
+ sources: [
2020
+ {
2021
+ getGrants: async () => ({
2022
+ permissions: {
2023
+ admin: ["access"],
2024
+ rbac: ["assignRoles"],
2025
+ user: ["create", "list", "read", "update"],
2026
+ },
2027
+ }),
2028
+ name: "admin-user-update-rollback",
2029
+ },
2030
+ ],
2031
+ statements: terrenoStatements,
2032
+ userModel: UserModel as unknown as UserModelType,
2033
+ });
2034
+ await accessControl.roles.seedDefaults();
2035
+
2036
+ const localApp = buildApp(
2037
+ [
2038
+ {
2039
+ displayName: "Users",
2040
+ listFields: ["email", "name", "roles"],
2041
+ model: UserModel,
2042
+ routePath: "/users",
2043
+ },
2044
+ ],
2045
+ {accessControl}
2046
+ );
2047
+ const agent = await authAsUser(localApp, "admin");
2048
+ const target = await UserModel.findOne({email: "notAdmin@example.com"});
2049
+ expect(target).toBeTruthy();
2050
+ const originalName = target?.name;
2051
+
2052
+ const res = await agent
2053
+ .patch(`/admin/users/${String(target?._id)}`)
2054
+ .send({name: "Should-not-stick", roles: ["does-not-exist"]});
2055
+ expect(res.status).toBeGreaterThanOrEqual(400);
2056
+
2057
+ const after = await UserModel.findById(target?._id);
2058
+ expect(after?.name).toBe(originalName);
2059
+ });
2060
+
2061
+ it("does not persist bulk-patch fields when role assignment fails", async () => {
2062
+ if (!UserModel.schema.path("roles")) {
2063
+ UserModel.schema.add({
2064
+ roles: {default: [], description: "RBAC role names", type: [String]},
2065
+ });
2066
+ }
2067
+ const accessControl = createAccess({
2068
+ connection: mongoose.connection,
2069
+ sources: [
2070
+ {
2071
+ getGrants: async () => ({
2072
+ permissions: {
2073
+ admin: ["access"],
2074
+ rbac: ["assignRoles"],
2075
+ user: ["create", "list", "read", "update"],
2076
+ },
2077
+ }),
2078
+ name: "admin-user-bulk-rollback",
2079
+ },
2080
+ ],
2081
+ statements: terrenoStatements,
2082
+ userModel: UserModel as unknown as UserModelType,
2083
+ });
2084
+ await accessControl.roles.seedDefaults();
2085
+
2086
+ const localApp = buildApp(
2087
+ [
2088
+ {
2089
+ bulkPatchAllowlist: ["name", "roles"],
2090
+ displayName: "Users",
2091
+ listFields: ["email", "name", "roles"],
2092
+ model: UserModel,
2093
+ routePath: "/users",
2094
+ },
2095
+ ],
2096
+ {accessControl}
2097
+ );
2098
+ const agent = await authAsUser(localApp, "admin");
2099
+ const target = await UserModel.findOne({email: "notAdmin@example.com"});
2100
+ expect(target).toBeTruthy();
2101
+ const originalName = target?.name;
2102
+
2103
+ const res = await agent.post("/admin/users/bulk-patch").send({
2104
+ ids: [String(target?._id)],
2105
+ patch: {name: "Should-not-stick", roles: ["does-not-exist"]},
2106
+ });
2107
+ expect(res.status).toBe(200);
2108
+ expect(res.body.updated).toBe(0);
2109
+ expect(res.body.failures?.length).toBeGreaterThan(0);
2110
+
2111
+ const after = await UserModel.findById(target?._id);
2112
+ expect(after?.name).toBe(originalName);
2113
+ });
794
2114
  });