@terreno/admin-backend 57.1.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.
@@ -51,6 +51,7 @@ var contributionScriptToConfig = function (script) { return ({
51
51
  runner: script.runner,
52
52
  }); };
53
53
  var contributionScreenToConfig = function (screen) { return ({
54
+ adminAccess: screen.adminAccess,
54
55
  displayName: screen.displayName,
55
56
  name: screen.name,
56
57
  }); };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export type { AdminChangeEvent, AdminChangeType, AdminConfig, AdminContribution, AdminCustomScreen, AdminFieldset, AdminFilter, AdminFilterBoolean, AdminFilterChoice, AdminFilterDateRange, AdminFilterKind, AdminFilterRef, AdminFilterText, AdminHomeConfig, AdminHomeSlots, AdminHomeWidgetContribution, AdminModelContribution, AdminModelPermissions, AdminScriptContribution, TerrenoAppAdminEvent, } from "@terreno/api";
2
2
  export type { AdminAuditEvent, AdminCustomScreenConfig, AdminFieldOverride, AdminModelConfig, AdminOptions, AdminScriptConfig, } from "./adminApp";
3
- export { AdminApp } from "./adminApp";
3
+ export { AdminApp, adminOwnedBy } from "./adminApp";
4
4
  export * from "./adminUiV2";
5
5
  export type { AggregatedAdminContributions } from "./aggregateAdmin";
6
6
  export { aggregateAdminContributions, aggregateFromTerrenoApp, collectPluginAdminContributions, collectRegisteredAdminModels, } from "./aggregateAdmin";
package/dist/index.js CHANGED
@@ -14,9 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.runScriptCli = exports.normalizeAdminRoutePath = exports.resolvedModelFromAdminConfig = exports.resetLegacyDeprecationWarningsForTests = exports.convertLegacyModelConfig = exports.parseAdminListFilters = exports.DocumentStorageApp = exports.collectRegisteredAdminModels = exports.collectPluginAdminContributions = exports.aggregateFromTerrenoApp = exports.aggregateAdminContributions = exports.AdminApp = void 0;
17
+ exports.runScriptCli = exports.normalizeAdminRoutePath = exports.resolvedModelFromAdminConfig = exports.resetLegacyDeprecationWarningsForTests = exports.convertLegacyModelConfig = exports.parseAdminListFilters = exports.DocumentStorageApp = exports.collectRegisteredAdminModels = exports.collectPluginAdminContributions = exports.aggregateFromTerrenoApp = exports.aggregateAdminContributions = exports.adminOwnedBy = exports.AdminApp = void 0;
18
18
  var adminApp_1 = require("./adminApp");
19
19
  Object.defineProperty(exports, "AdminApp", { enumerable: true, get: function () { return adminApp_1.AdminApp; } });
20
+ Object.defineProperty(exports, "adminOwnedBy", { enumerable: true, get: function () { return adminApp_1.adminOwnedBy; } });
20
21
  __exportStar(require("./adminUiV2"), exports);
21
22
  var aggregateAdmin_1 = require("./aggregateAdmin");
22
23
  Object.defineProperty(exports, "aggregateAdminContributions", { enumerable: true, get: function () { return aggregateAdmin_1.aggregateAdminContributions; } });
@@ -96,6 +96,7 @@ var resolvedModelFromAdminConfig = function (_a) {
96
96
  return {
97
97
  actions: admin.actions,
98
98
  admin: admin,
99
+ adminAccess: admin.adminAccess,
99
100
  autocompleteFields: admin.autocompleteFields,
100
101
  bulkPatchAllowlist: admin.bulkPatchAllowlist,
101
102
  defaultSort: defaultSort,
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  },
6
6
  "dependencies": {
7
7
  "@google-cloud/storage": "^7.15.0",
8
- "@terreno/api": "57.1.0",
8
+ "@terreno/api": "57.2.0",
9
9
  "express": "^5.2.1",
10
10
  "luxon": "^3.7.2",
11
11
  "multer": "2.2.0"
@@ -13,8 +13,8 @@
13
13
  "description": "Admin panel backend plugin for @terreno/api",
14
14
  "devDependencies": {
15
15
  "@biomejs/biome": "^2.3.6",
16
- "@terreno/test": "57.1.0",
17
- "@types/bun": "^1.3.8",
16
+ "@terreno/test": "57.2.0",
17
+ "@types/bun": "^1.4.0",
18
18
  "@types/express": "^5.0.6",
19
19
  "@types/luxon": "^3.7.1",
20
20
  "@types/multer": "^1.4.12",
@@ -55,5 +55,5 @@
55
55
  "test:coverage": "bun run ../scripts/check-coverage.ts"
56
56
  },
57
57
  "types": "dist/index.d.ts",
58
- "version": "57.1.0"
58
+ "version": "57.2.0"
59
59
  }
@@ -1,10 +1,12 @@
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,
7
8
  createAccess,
9
+ findOneOrNoneFor,
8
10
  modelRouter,
9
11
  Permissions,
10
12
  setupAuth,
@@ -22,6 +24,7 @@ import {
22
24
  setupDb,
23
25
  UserModel,
24
26
  } from "@terreno/api/testing";
27
+ import {assert} from "chai";
25
28
  import type express from "express";
26
29
  import mongoose from "mongoose";
27
30
  import supertest from "supertest";
@@ -336,6 +339,430 @@ describe("AdminApp /admin/config", () => {
336
339
  expect(res.body.home.title).toBe("Ops");
337
340
  expect(res.body.home.slots.sidebar).toEqual(["versionConfig", "recentActivity"]);
338
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
+ });
339
766
  });
340
767
 
341
768
  describe("AdminApp model CRUD routes", () => {