@terreno/admin-backend 57.16.1 → 57.17.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.
package/src/adminApp.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  import {
2
2
  ADMIN_PAGE_ACTION,
3
3
  type AdminAccessConfig,
4
+ type AdminConfig,
4
5
  type AdminModelAdminMap,
5
6
  type AnyTerrenoAccess,
6
7
  APIError,
8
+ assertCanWriteTargetUser,
9
+ assertCanWriteUserIdentity,
7
10
  asyncHandler,
8
11
  auditActorIdFromRequest,
9
12
  authenticateMiddleware,
@@ -15,6 +18,8 @@ import {
15
18
  describeModel,
16
19
  findSyncEntryByModelName,
17
20
  getOrgContext,
21
+ isRbacUserModelName,
22
+ isWriteKeyForField,
18
23
  type JSONValue,
19
24
  logger,
20
25
  type ModelRouterOptions,
@@ -46,6 +51,7 @@ import type {Model} from "mongoose";
46
51
  import mongoose from "mongoose";
47
52
  import {assignUniqueAdminConfigNames, findAdminModelMetaByRoutePath} from "./adminConfigIdentity";
48
53
  import {mountAdminMigrationRoutes} from "./adminMigrations";
54
+ import {assertAdminRowScopeAfterUpdate, buildAdminRowScopePermission} from "./adminRowScope";
49
55
  import {
50
56
  ADMIN_SCRIPT_JOB_NAME,
51
57
  defineAdminScriptJob,
@@ -154,7 +160,8 @@ export interface AdminModelConfig {
154
160
  /** Allowlisted keys for POST .../bulk-patch (defaults from listFields minus system/readonly/hidden) */
155
161
  bulkPatchAllowlist?: string[];
156
162
  /**
157
- * Per-model `modelRouter` query filter (list and other query-shaped reads).
163
+ * Per-model admin row scope. List and search add it to the query; by-id read/update/delete,
164
+ * bulk-patch, and admin-window sync writes deny documents outside it.
158
165
  * Same contract as {@link ModelRouterOptions.queryFilter} in `@terreno/api`: merge into the
159
166
  * Mongoose query, return the incoming `query` unchanged if allowed, or return `null` to yield
160
167
  * an empty list without error.
@@ -437,13 +444,16 @@ const buildAdminListQueryFilter = (
437
444
  merged = {...merged, ...OrgQueryFilter(user, merged)};
438
445
  }
439
446
  const result = andMongoFilters(merged, searchClause);
440
- const overrides: Record<string, unknown> = {...filter};
441
- for (const key of consumedKeys) {
442
- if (!(key in overrides)) {
443
- overrides[key] = undefined;
447
+ // modelRouter spreads this over the raw request query. Clear consumed raw keys that the
448
+ // result does not set, and spread the result last so the row scope always wins over a
449
+ // client filter on the same field.
450
+ const cleared: Record<string, unknown> = {};
451
+ for (const key of [...consumedKeys, ...Object.keys(filter)]) {
452
+ if (!(key in result)) {
453
+ cleared[key] = undefined;
444
454
  }
445
455
  }
446
- return {...result, ...overrides, [ADMIN_LIST_SEARCH_PARAM]: undefined};
456
+ return {...cleared, ...result, [ADMIN_LIST_SEARCH_PARAM]: undefined};
447
457
  };
448
458
  };
449
459
 
@@ -749,7 +759,27 @@ export class AdminApp {
749
759
  return ownerId != null && String(ownerId) === String(user.id);
750
760
  }
751
761
 
762
+ /**
763
+ * Admin permissions for one model action: the admin page gate plus RBAC (or IsAdmin), ANDed
764
+ * with the model's `admin.adminPermissions[action]` methods. An explicitly empty array denies
765
+ * the action.
766
+ */
752
767
  private resourceActionPermissions(
768
+ config: Pick<AdminModelConfig, "adminAccess" | "model"> & {admin?: AdminConfig},
769
+ action: "list" | "read" | "create" | "update" | "delete"
770
+ ): PermissionMethod<unknown>[] {
771
+ const base = this.baseResourceActionPermissions(config, action);
772
+ const configured = config.admin?.adminPermissions?.[action];
773
+ if (!configured) {
774
+ return base;
775
+ }
776
+ if (configured.length === 0 || base.length === 0) {
777
+ return [];
778
+ }
779
+ return [...base, ...configured];
780
+ }
781
+
782
+ private baseResourceActionPermissions(
753
783
  config: Pick<AdminModelConfig, "adminAccess" | "model">,
754
784
  action: "list" | "read" | "create" | "update" | "delete"
755
785
  ): PermissionMethod<unknown>[] {
@@ -1427,31 +1457,50 @@ export class AdminApp {
1427
1457
  return permissions;
1428
1458
  };
1429
1459
 
1430
- const updatePermissions = adminPermission(config.permissions?.update, "update");
1460
+ // Read/update/delete of one document must stay inside the same row scope list and search use.
1461
+ const rowScopePermission = config.queryFilter
1462
+ ? buildAdminRowScopePermission(config)
1463
+ : undefined;
1464
+ const withRowScope = (
1465
+ permissions: PermissionMethod<unknown>[]
1466
+ ): PermissionMethod<unknown>[] => {
1467
+ if (!rowScopePermission || permissions.length === 0) {
1468
+ return permissions;
1469
+ }
1470
+ return [...permissions, rowScopePermission];
1471
+ };
1472
+
1473
+ const updatePermissions = withRowScope(adminPermission(config.permissions?.update, "update"));
1474
+ // The RBAC user model: "User" or the userModel given to createAccess, whatever its name.
1475
+ const isRbacUserModel = isRbacUserModelName(
1476
+ config.model.modelName,
1477
+ this.options.accessControl
1478
+ );
1431
1479
 
1432
1480
  const stripProtectedFromBody = (body: unknown): Record<string, unknown> => {
1433
1481
  if (!body || typeof body !== "object" || Array.isArray(body)) {
1434
1482
  return {};
1435
1483
  }
1436
- const next = {...(body as Record<string, unknown>)};
1437
- for (const key of readonlySet) {
1438
- delete next[key];
1439
- }
1440
- for (const key of hiddenFieldSet) {
1441
- delete next[key];
1442
- }
1443
- for (const key of excludeFieldSet) {
1444
- delete next[key];
1445
- }
1446
- for (const key of SYSTEM_ADMIN_FIELDS) {
1447
- delete next[key];
1448
- }
1484
+ const protectedFields = [
1485
+ ...readonlySet,
1486
+ ...hiddenFieldSet,
1487
+ ...excludeFieldSet,
1488
+ ...SYSTEM_ADMIN_FIELDS,
1489
+ ];
1449
1490
  // Self-service never writes these fields. Admin CRUD may set `admin`.
1450
1491
  // When RBAC is enabled, `roles` must go through RoleManager.assign and
1451
1492
  // tenant membership is not a generic User document field.
1452
- if (config.model.modelName === "User" && this.options.accessControl) {
1453
- delete next.organizationIds;
1454
- delete next.roles;
1493
+ if (isRbacUserModel) {
1494
+ protectedFields.push("organizationIds", "roles");
1495
+ }
1496
+ // Mongoose applies dotted keys (`roles.0`) as paths, so drop paths inside a protected
1497
+ // field as well as the field itself.
1498
+ const next: Record<string, unknown> = {};
1499
+ for (const [key, value] of Object.entries(body as Record<string, unknown>)) {
1500
+ if (protectedFields.some((field) => isWriteKeyForField(key, field))) {
1501
+ continue;
1502
+ }
1503
+ next[key] = value;
1455
1504
  }
1456
1505
  return next;
1457
1506
  };
@@ -1467,7 +1516,7 @@ export class AdminApp {
1467
1516
  body: Record<string, unknown>,
1468
1517
  request: express.Request
1469
1518
  ): void => {
1470
- if (config.model.modelName !== "User" || !this.options.accessControl) {
1519
+ if (!isRbacUserModel) {
1471
1520
  return;
1472
1521
  }
1473
1522
  if (!("roles" in body)) {
@@ -1674,7 +1723,7 @@ export class AdminApp {
1674
1723
  currentAdmin = false,
1675
1724
  targetUserId?: string
1676
1725
  ): Promise<void> => {
1677
- if (config.model.modelName !== "User" || !("admin" in body)) {
1726
+ if (!isRbacUserModel || !("admin" in body)) {
1678
1727
  return;
1679
1728
  }
1680
1729
  const accessControl = this.options.accessControl;
@@ -1726,15 +1775,29 @@ export class AdminApp {
1726
1775
  return Boolean((existing as {admin?: boolean} | null)?.admin);
1727
1776
  };
1728
1777
 
1778
+ // The document an update applies to: the one the REST permission check loaded, or (for
1779
+ // admin-window sync updates, which set req.params.id) the stored row.
1780
+ const currentDocumentForUpdate = async (request: express.Request): Promise<unknown> => {
1781
+ const loaded = (request as express.Request & {obj?: unknown}).obj;
1782
+ if (loaded) {
1783
+ return loaded;
1784
+ }
1785
+ const id = request.params?.id;
1786
+ if (!id || !rowScopePermission) {
1787
+ return undefined;
1788
+ }
1789
+ const query: Record<string, unknown> = {_id: id};
1790
+ if (config.model.schema.path("deleted")) {
1791
+ query.deleted = {$in: [true, false]};
1792
+ }
1793
+ return config.model.findById(id).where(query).lean();
1794
+ };
1795
+
1729
1796
  const markAuthorizedUserAdminWrite = (
1730
1797
  body: Record<string, unknown>,
1731
1798
  request: express.Request
1732
1799
  ): void => {
1733
- if (
1734
- config.model.modelName !== "User" ||
1735
- !this.options.accessControl ||
1736
- !("admin" in body)
1737
- ) {
1800
+ if (!isRbacUserModel || !("admin" in body)) {
1738
1801
  return;
1739
1802
  }
1740
1803
  (
@@ -1789,10 +1852,10 @@ export class AdminApp {
1789
1852
  maxLimit: 500,
1790
1853
  permissions: {
1791
1854
  create: adminPermission(config.permissions?.create, "create"),
1792
- delete: adminPermission(config.permissions?.delete, "delete"),
1855
+ delete: withRowScope(adminPermission(config.permissions?.delete, "delete")),
1793
1856
  list: adminPermission(true, "list"),
1794
- read: adminPermission(true, "read"),
1795
- update: adminPermission(config.permissions?.update, "update"),
1857
+ read: withRowScope(adminPermission(true, "read")),
1858
+ update: updatePermissions,
1796
1859
  },
1797
1860
  postCreate: async (value, request) => {
1798
1861
  await applyPendingUserRoles(value, request, true);
@@ -1838,7 +1901,14 @@ export class AdminApp {
1838
1901
  takePendingUserRoles(record, req);
1839
1902
  await assertCanWriteUserAdminFlag(record, req, await currentUserAdminFlag(req));
1840
1903
  markAuthorizedUserAdminWrite(record, req);
1841
- return stripProtectedFromBody(body) as typeof body;
1904
+ const stripped = stripProtectedFromBody(body) as Record<string, unknown>;
1905
+ await assertAdminRowScopeAfterUpdate({
1906
+ config,
1907
+ current: await currentDocumentForUpdate(req),
1908
+ patch: stripped,
1909
+ user: req.user as User | undefined,
1910
+ });
1911
+ return stripped as typeof body;
1842
1912
  },
1843
1913
  queryFields: buildAdminModelQueryFields({
1844
1914
  filters: config.filters,
@@ -1854,6 +1924,7 @@ export class AdminApp {
1854
1924
  responseHandler: async (value, _method, request): Promise<JSONValue> =>
1855
1925
  addRecordCapabilities(value, request),
1856
1926
  sort: config.defaultSort ?? "-created",
1927
+ sortFields: modelMeta?.sortableFields ?? [],
1857
1928
  ...(config.populatePaths ? {populatePaths: config.populatePaths} : {}),
1858
1929
  ...(auditHooks.postDelete ? {postDelete: auditHooks.postDelete} : {}),
1859
1930
  };
@@ -1873,7 +1944,7 @@ export class AdminApp {
1873
1944
  registerAdminWindowMutationScope(config.model.modelName, {
1874
1945
  accessControl: this.options.accessControl,
1875
1946
  createPermissions: adminPermission(config.permissions?.create, "create"),
1876
- deletePermissions: adminPermission(config.permissions?.delete, "delete"),
1947
+ deletePermissions: withRowScope(adminPermission(config.permissions?.delete, "delete")),
1877
1948
  modelName: config.model.modelName,
1878
1949
  permissions: {
1879
1950
  create: config.permissions?.create !== false,
@@ -1886,7 +1957,7 @@ export class AdminApp {
1886
1957
  preCreate: routerOptions.preCreate,
1887
1958
  preUpdate: routerOptions.preUpdate,
1888
1959
  stripMutationData: (data) => stripProtectedFromBody(data),
1889
- updatePermissions: adminPermission(config.permissions?.update, "update"),
1960
+ updatePermissions,
1890
1961
  });
1891
1962
  }
1892
1963
 
@@ -1936,11 +2007,7 @@ export class AdminApp {
1936
2007
  }
1937
2008
  const patch = stripProtectedFromBody(rawPatch);
1938
2009
  let pendingRoles: string[] | undefined;
1939
- if (
1940
- config.model.modelName === "User" &&
1941
- this.options.accessControl &&
1942
- "roles" in rawPatch
1943
- ) {
2010
+ if (isRbacUserModel && "roles" in rawPatch) {
1944
2011
  pendingRoles = parseRoleNames(rawPatch.roles);
1945
2012
  }
1946
2013
  if (Object.keys(patch).length === 0 && pendingRoles === undefined) {
@@ -1967,6 +2034,20 @@ export class AdminApp {
1967
2034
  failures.push({id, title: "Forbidden"});
1968
2035
  continue;
1969
2036
  }
2037
+ await assertAdminRowScopeAfterUpdate({config, current: doc, patch, user: actor});
2038
+ await assertCanWriteTargetUser({
2039
+ accessControl: this.options.accessControl,
2040
+ actor,
2041
+ modelName: config.model.modelName,
2042
+ target: doc,
2043
+ });
2044
+ await assertCanWriteUserIdentity({
2045
+ accessControl: this.options.accessControl,
2046
+ actor,
2047
+ body: patch,
2048
+ modelName: config.model.modelName,
2049
+ target: doc,
2050
+ });
1970
2051
  await assertCanWriteUserAdminFlag(
1971
2052
  rawPatch,
1972
2053
  req,
@@ -0,0 +1,230 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import type {User} from "@terreno/api";
3
+ import mongoose from "mongoose";
4
+
5
+ import {
6
+ type AdminRowScopeConfig,
7
+ assertAdminRowScopeAfterUpdate,
8
+ buildAdminRowScopePermission,
9
+ } from "./adminRowScope";
10
+
11
+ interface StubModel {
12
+ model: AdminRowScopeConfig["model"];
13
+ queries: Record<string, unknown>[];
14
+ }
15
+
16
+ const tenantSchema = new mongoose.Schema({
17
+ ownerId: {type: String},
18
+ tenantId: {type: String},
19
+ });
20
+
21
+ const softDeleteSchema = new mongoose.Schema({
22
+ deleted: {type: Boolean},
23
+ tenantId: {type: String},
24
+ });
25
+
26
+ const buildStubModel = ({
27
+ schema = tenantSchema,
28
+ isFound = true,
29
+ }: {
30
+ schema?: mongoose.Schema;
31
+ isFound?: boolean;
32
+ } = {}): StubModel => {
33
+ const queries: Record<string, unknown>[] = [];
34
+ const model = {
35
+ exists: async (query: Record<string, unknown>): Promise<{_id: string} | null> => {
36
+ queries.push(query);
37
+ return isFound ? {_id: "doc"} : null;
38
+ },
39
+ schema,
40
+ } as unknown as AdminRowScopeConfig["model"];
41
+ return {model, queries};
42
+ };
43
+
44
+ const user = {_id: "admin-1"} as unknown as User;
45
+
46
+ describe("buildAdminRowScopePermission", () => {
47
+ it("allows collection-level checks without an instance", async () => {
48
+ const {model} = buildStubModel();
49
+ const permission = buildAdminRowScopePermission({model, queryFilter: () => null});
50
+ expect(await permission("list", user, undefined)).toBe(true);
51
+ expect(await permission("list", user, null)).toBe(true);
52
+ });
53
+
54
+ it("allows every row when no queryFilter is configured", async () => {
55
+ const {model, queries} = buildStubModel();
56
+ const permission = buildAdminRowScopePermission({model});
57
+ expect(await permission("read", user, {_id: "doc"})).toBe(true);
58
+ expect(queries).toHaveLength(0);
59
+ });
60
+
61
+ it("denies every row when the queryFilter returns null", async () => {
62
+ const {model, queries} = buildStubModel();
63
+ const permission = buildAdminRowScopePermission({model, queryFilter: () => null});
64
+ expect(await permission("read", user, {_id: "doc"})).toBe(false);
65
+ expect(queries).toHaveLength(0);
66
+ });
67
+
68
+ it("allows every row when the queryFilter returns an empty filter", async () => {
69
+ const {model, queries} = buildStubModel();
70
+ const permission = buildAdminRowScopePermission({model, queryFilter: () => ({})});
71
+ expect(await permission("update", user, {_id: "doc"})).toBe(true);
72
+ expect(queries).toHaveLength(0);
73
+ });
74
+
75
+ it("denies an instance that has no id", async () => {
76
+ const {model, queries} = buildStubModel();
77
+ const permission = buildAdminRowScopePermission({
78
+ model,
79
+ queryFilter: () => ({tenantId: "t1"}),
80
+ });
81
+ expect(await permission("read", user, {tenantId: "t1"})).toBe(false);
82
+ expect(await permission("read", user, "not-a-document")).toBe(false);
83
+ expect(queries).toHaveLength(0);
84
+ });
85
+
86
+ it("checks the stored document against the scope", async () => {
87
+ const inScope = buildStubModel({isFound: true});
88
+ const outOfScope = buildStubModel({isFound: false});
89
+ const queryFilter = (): Record<string, unknown> => ({tenantId: "t1"});
90
+
91
+ expect(
92
+ await buildAdminRowScopePermission({model: inScope.model, queryFilter})("read", user, {
93
+ _id: "doc",
94
+ })
95
+ ).toBe(true);
96
+ expect(
97
+ await buildAdminRowScopePermission({model: outOfScope.model, queryFilter})("read", user, {
98
+ _id: "doc",
99
+ })
100
+ ).toBe(false);
101
+ expect(inScope.queries).toEqual([{$and: [{tenantId: "t1"}, {_id: "doc"}]}]);
102
+ });
103
+
104
+ it("includes soft-deleted rows when the model has a deleted path", async () => {
105
+ const {model, queries} = buildStubModel({schema: softDeleteSchema});
106
+ const permission = buildAdminRowScopePermission({
107
+ model,
108
+ queryFilter: async () => ({tenantId: "t1"}),
109
+ });
110
+ expect(await permission("delete", user, {_id: "doc"})).toBe(true);
111
+ expect(queries).toEqual([
112
+ {$and: [{tenantId: "t1"}, {_id: "doc"}], deleted: {$in: [true, false]}},
113
+ ]);
114
+ });
115
+ });
116
+
117
+ describe("assertAdminRowScopeAfterUpdate", () => {
118
+ const current = {_id: "doc", ownerId: "o1", tenantId: "t1"};
119
+
120
+ it("skips models without a queryFilter", async () => {
121
+ const {model} = buildStubModel();
122
+ await assertAdminRowScopeAfterUpdate({
123
+ config: {model},
124
+ current,
125
+ patch: {tenantId: "t2"},
126
+ user,
127
+ });
128
+ });
129
+
130
+ it("skips when there is no current document", async () => {
131
+ const {model} = buildStubModel();
132
+ await assertAdminRowScopeAfterUpdate({
133
+ config: {model, queryFilter: () => null},
134
+ current: undefined,
135
+ patch: {tenantId: "t2"},
136
+ user,
137
+ });
138
+ });
139
+
140
+ it("skips an empty patch without resolving the scope", async () => {
141
+ const {model} = buildStubModel();
142
+ let calls = 0;
143
+ await assertAdminRowScopeAfterUpdate({
144
+ config: {
145
+ model,
146
+ queryFilter: () => {
147
+ calls += 1;
148
+ return null;
149
+ },
150
+ },
151
+ current,
152
+ patch: {},
153
+ user,
154
+ });
155
+ expect(calls).toBe(0);
156
+ });
157
+
158
+ it("rejects writes when the scope denies every row", async () => {
159
+ const {model} = buildStubModel();
160
+ await expect(
161
+ assertAdminRowScopeAfterUpdate({
162
+ config: {model, queryFilter: () => null},
163
+ current,
164
+ patch: {ownerId: "o2"},
165
+ user,
166
+ })
167
+ ).rejects.toMatchObject({status: 403});
168
+ });
169
+
170
+ it("allows writes when the scope is unrestricted", async () => {
171
+ const {model} = buildStubModel();
172
+ await assertAdminRowScopeAfterUpdate({
173
+ config: {model, queryFilter: () => ({})},
174
+ current,
175
+ patch: {tenantId: "t2"},
176
+ user,
177
+ });
178
+ });
179
+
180
+ it("allows writes that do not touch a scoped field", async () => {
181
+ const {model} = buildStubModel();
182
+ await assertAdminRowScopeAfterUpdate({
183
+ config: {model, queryFilter: () => ({tenantId: "t1"})},
184
+ current,
185
+ patch: {ownerId: "o2"},
186
+ user,
187
+ });
188
+ });
189
+
190
+ it("rejects a write that moves the row out of scope", async () => {
191
+ const {model} = buildStubModel();
192
+ await expect(
193
+ assertAdminRowScopeAfterUpdate({
194
+ config: {model, queryFilter: () => ({tenantId: "t1"})},
195
+ current: {toObject: (): Record<string, unknown> => current},
196
+ patch: {tenantId: "t2"},
197
+ user,
198
+ })
199
+ ).rejects.toMatchObject({status: 403});
200
+ });
201
+
202
+ it("treats fields inside $or clauses as scoped", async () => {
203
+ const {model} = buildStubModel();
204
+ await expect(
205
+ assertAdminRowScopeAfterUpdate({
206
+ config: {model, queryFilter: () => ({$or: [{ownerId: "o1"}, {ownerId: "o2"}]})},
207
+ current,
208
+ patch: {ownerId: "o3"},
209
+ user,
210
+ })
211
+ ).rejects.toMatchObject({status: 403});
212
+ });
213
+
214
+ it("ignores operators and malformed logical clauses when finding scoped fields", async () => {
215
+ const {model} = buildStubModel();
216
+ await assertAdminRowScopeAfterUpdate({
217
+ config: {
218
+ model,
219
+ queryFilter: () => ({
220
+ $and: [null, "ignored"],
221
+ $comment: "scope",
222
+ $nor: "not-an-array",
223
+ }),
224
+ },
225
+ current,
226
+ patch: {tenantId: "t2"},
227
+ user,
228
+ });
229
+ });
230
+ });
@@ -0,0 +1,155 @@
1
+ import {APIError, matchesQuery, type PermissionMethod, type User} from "@terreno/api";
2
+ import type {Model} from "mongoose";
3
+
4
+ /**
5
+ * AdminApp row scope: the per-model `queryFilter` (or `adminFilter`, which resolves to it) that
6
+ * limits which rows an admin may see. List and search apply it as a query constraint; the helpers
7
+ * here apply the same scope to routes that resolve one document by id.
8
+ */
9
+ export interface AdminRowScopeConfig {
10
+ model: Pick<Model<unknown>, "exists" | "schema">;
11
+ queryFilter?: (
12
+ user?: User,
13
+ query?: Record<string, unknown>
14
+ ) => Record<string, unknown> | null | Promise<Record<string, unknown> | null>;
15
+ }
16
+
17
+ interface ResolvedAdminRowScope {
18
+ denied: boolean;
19
+ filter?: Record<string, unknown>;
20
+ }
21
+
22
+ const resolveAdminRowScope = async (
23
+ config: AdminRowScopeConfig,
24
+ user: User | undefined
25
+ ): Promise<ResolvedAdminRowScope> => {
26
+ if (!config.queryFilter) {
27
+ return {denied: false};
28
+ }
29
+ const resolved = await config.queryFilter(user, {});
30
+ if (resolved === null) {
31
+ return {denied: true};
32
+ }
33
+ if (Object.keys(resolved).length === 0) {
34
+ return {denied: false};
35
+ }
36
+ return {denied: false, filter: resolved};
37
+ };
38
+
39
+ const documentId = (instance: unknown): unknown => {
40
+ if (!instance || typeof instance !== "object") {
41
+ return undefined;
42
+ }
43
+ return (instance as {_id?: unknown})._id;
44
+ };
45
+
46
+ const toPlainDocument = (instance: unknown): Record<string, unknown> => {
47
+ const withToObject = instance as {toObject?: () => Record<string, unknown>};
48
+ if (typeof withToObject?.toObject === "function") {
49
+ return withToObject.toObject();
50
+ }
51
+ return {...(instance as Record<string, unknown>)};
52
+ };
53
+
54
+ /** Top-level field names a Mongo filter constrains, including those inside `$and` / `$or` / `$nor`. */
55
+ const filterRootKeys = (filter: Record<string, unknown>, keys = new Set<string>()): Set<string> => {
56
+ for (const [key, value] of Object.entries(filter)) {
57
+ if (key === "$and" || key === "$or" || key === "$nor") {
58
+ if (Array.isArray(value)) {
59
+ for (const clause of value) {
60
+ if (clause && typeof clause === "object") {
61
+ filterRootKeys(clause as Record<string, unknown>, keys);
62
+ }
63
+ }
64
+ }
65
+ continue;
66
+ }
67
+ if (key.startsWith("$")) {
68
+ continue;
69
+ }
70
+ keys.add(key.split(".")[0] ?? key);
71
+ }
72
+ return keys;
73
+ };
74
+
75
+ /**
76
+ * Whether the stored document is inside the row scope. Evaluated by MongoDB so the scope has the
77
+ * same semantics here as on the list query. Soft-deleted rows are included so admin-window writes
78
+ * on them are judged by scope, not by the deleted flag.
79
+ */
80
+ const isStoredDocumentInScope = async (
81
+ config: AdminRowScopeConfig,
82
+ instance: unknown,
83
+ filter: Record<string, unknown>
84
+ ): Promise<boolean> => {
85
+ const id = documentId(instance);
86
+ if (id == null) {
87
+ return false;
88
+ }
89
+ const query: Record<string, unknown> = {$and: [filter, {_id: id}]};
90
+ if (config.model.schema.path("deleted")) {
91
+ query.deleted = {$in: [true, false]};
92
+ }
93
+ return (await config.model.exists(query)) !== null;
94
+ };
95
+
96
+ /**
97
+ * Permission method that denies read/update/delete of a document outside the admin row scope.
98
+ * Collection-level checks (no instance) pass, so list and the bulk-patch pre-check are unchanged.
99
+ */
100
+ export const buildAdminRowScopePermission = (
101
+ config: AdminRowScopeConfig
102
+ ): PermissionMethod<unknown> => {
103
+ return async (_method, user, instance): Promise<boolean> => {
104
+ if (instance === undefined || instance === null) {
105
+ return true;
106
+ }
107
+ const scope = await resolveAdminRowScope(config, user);
108
+ if (scope.denied) {
109
+ return false;
110
+ }
111
+ if (!scope.filter) {
112
+ return true;
113
+ }
114
+ return isStoredDocumentInScope(config, instance, scope.filter);
115
+ };
116
+ };
117
+
118
+ /**
119
+ * Rejects an update whose result would leave the admin row scope (for example changing the
120
+ * scoped tenant or owner field). Only runs when the patch writes a field the scope constrains.
121
+ */
122
+ export const assertAdminRowScopeAfterUpdate = async ({
123
+ config,
124
+ current,
125
+ patch,
126
+ user,
127
+ }: {
128
+ config: AdminRowScopeConfig;
129
+ current: unknown;
130
+ patch: Record<string, unknown>;
131
+ user: User | undefined;
132
+ }): Promise<void> => {
133
+ if (!config.queryFilter || !current) {
134
+ return;
135
+ }
136
+ const touched = Object.keys(patch).map((key) => key.split(".")[0] ?? key);
137
+ if (touched.length === 0) {
138
+ return;
139
+ }
140
+ const scope = await resolveAdminRowScope(config, user);
141
+ if (scope.denied) {
142
+ throw new APIError({status: 403, title: "Admin write outside row scope"});
143
+ }
144
+ if (!scope.filter) {
145
+ return;
146
+ }
147
+ const scopedKeys = filterRootKeys(scope.filter);
148
+ if (!touched.some((key) => scopedKeys.has(key))) {
149
+ return;
150
+ }
151
+ const nextState = {...toPlainDocument(current), ...patch};
152
+ if (!matchesQuery(nextState, scope.filter)) {
153
+ throw new APIError({status: 403, title: "Admin write outside row scope"});
154
+ }
155
+ };