@terreno/api 57.16.2 → 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/dist/actions.d.ts +26 -3
- package/dist/actions.js +102 -16
- package/dist/api.d.ts +7 -0
- package/dist/api.js +59 -3
- package/dist/auth.d.ts +28 -4
- package/dist/auth.js +140 -15
- package/dist/authRecovery.d.ts +31 -0
- package/dist/authRecovery.js +86 -6
- package/dist/betterAuth.d.ts +86 -0
- package/dist/betterAuthApp.d.ts +17 -0
- package/dist/betterAuthApp.js +12 -1
- package/dist/betterAuthOAuthHandoff.d.ts +24 -0
- package/dist/betterAuthOAuthHandoff.js +305 -0
- package/dist/betterAuthSetup.d.ts +37 -2
- package/dist/betterAuthSetup.js +304 -24
- package/dist/expressServer.d.ts +16 -0
- package/dist/expressServer.js +61 -14
- package/dist/githubAuth.d.ts +9 -0
- package/dist/githubAuth.js +230 -31
- package/dist/index.d.ts +9 -1
- package/dist/index.js +27 -3
- package/dist/mcp/actionTools.d.ts +4 -0
- package/dist/mcp/actionTools.js +158 -0
- package/dist/mcp/auth.d.ts +30 -0
- package/dist/mcp/auth.js +83 -28
- package/dist/mcp/createMCPRequest.d.ts +5 -1
- package/dist/mcp/createMCPRequest.js +3 -3
- package/dist/mcp/handlers.d.ts +3 -0
- package/dist/mcp/handlers.js +43 -27
- package/dist/mcp/oauth.d.ts +14 -0
- package/dist/mcp/oauth.js +618 -0
- package/dist/mcp/oauthMetadata.d.ts +89 -0
- package/dist/mcp/oauthMetadata.js +137 -0
- package/dist/mcp/registry.d.ts +5 -0
- package/dist/mcp/registry.js +9 -1
- package/dist/mcp/server.d.ts +6 -0
- package/dist/mcp/server.js +44 -7
- package/dist/mcp/serviceTokens.js +12 -2
- package/dist/mcp/toolExecution.d.ts +12 -0
- package/dist/mcp/toolExecution.js +60 -0
- package/dist/mcp/toolGenerator.d.ts +4 -1
- package/dist/mcp/toolGenerator.js +26 -60
- package/dist/mcp/types.d.ts +4 -4
- package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
- package/dist/models/mcpOAuthAuthorization.js +86 -0
- package/dist/models/mcpOAuthClient.d.ts +2 -0
- package/dist/models/mcpOAuthClient.js +42 -0
- package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
- package/dist/models/mcpOAuthRevokedFamily.js +36 -0
- package/dist/models/mcpOAuthToken.d.ts +12 -0
- package/dist/models/mcpOAuthToken.js +159 -0
- package/dist/models/mcpServiceToken.d.ts +1 -0
- package/dist/models/mcpServiceToken.js +21 -4
- package/dist/permissions.d.ts +7 -0
- package/dist/permissions.js +18 -1
- package/dist/rateLimit/policies.d.ts +4 -0
- package/dist/rateLimit/policies.js +46 -7
- package/dist/rbac/access.js +1 -0
- package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
- package/dist/rbac/membershipOrgAdminSource.js +5 -0
- package/dist/rbac/modelRouterAccess.d.ts +7 -1
- package/dist/rbac/modelRouterAccess.js +37 -24
- package/dist/rbac/realtimeAccess.js +17 -3
- package/dist/rbac/resolve.js +66 -9
- package/dist/rbac/roleManager.js +60 -5
- package/dist/rbac/roleModel.js +1 -1
- package/dist/rbac/statements.d.ts +1 -1
- package/dist/rbac/statements.js +13 -1
- package/dist/rbac/types.d.ts +12 -0
- package/dist/rbac/userWriteGuards.d.ts +50 -0
- package/dist/rbac/userWriteGuards.js +156 -0
- package/dist/realtime/changeStreamWatcher.d.ts +4 -1
- package/dist/realtime/changeStreamWatcher.js +157 -73
- package/dist/realtime/queryMatcher.d.ts +3 -0
- package/dist/realtime/queryMatcher.js +25 -10
- package/dist/realtime/realtimeApp.d.ts +16 -1
- package/dist/realtime/realtimeApp.js +76 -8
- package/dist/realtime/socketAuth.d.ts +17 -6
- package/dist/realtime/socketAuth.js +77 -16
- package/dist/realtime/types.d.ts +8 -5
- package/dist/requestContext.d.ts +22 -0
- package/dist/requestContext.js +22 -1
- package/dist/seedRunner.js +3 -1
- package/dist/sortFields.d.ts +33 -0
- package/dist/sortFields.js +55 -0
- package/dist/sync/executors.js +140 -2
- package/dist/sync/models.d.ts +2 -0
- package/dist/sync/models.js +5 -0
- package/dist/sync/mutationHandler.js +70 -7
- package/dist/sync/routes.js +4 -2
- package/dist/sync/syncSeqPlugin.js +6 -5
- package/dist/terrenoApp.d.ts +14 -0
- package/dist/terrenoApp.js +21 -6
- package/dist/types/mcpOAuth.d.ts +101 -0
- package/dist/types/mcpOAuth.js +2 -0
- package/dist/types/mcpServiceToken.d.ts +8 -0
- package/package.json +3 -3
- package/src/actions.test.ts +118 -0
- package/src/actions.ts +139 -17
- package/src/api.arrayOperations.test.ts +78 -0
- package/src/api.test.ts +36 -0
- package/src/api.ts +76 -4
- package/src/auth.test.ts +521 -3
- package/src/auth.ts +171 -17
- package/src/authRecovery.test.ts +99 -0
- package/src/authRecovery.ts +117 -5
- package/src/authVerification.test.ts +3 -3
- package/src/betterAuth.ts +104 -1
- package/src/betterAuthApp.test.ts +634 -1
- package/src/betterAuthApp.ts +28 -0
- package/src/betterAuthOAuthHandoff.test.ts +946 -0
- package/src/betterAuthOAuthHandoff.ts +375 -0
- package/src/betterAuthSetup.test.ts +393 -4
- package/src/betterAuthSetup.ts +402 -29
- package/src/expressServer.test.ts +93 -0
- package/src/expressServer.ts +81 -14
- package/src/githubAuth.test.ts +448 -6
- package/src/githubAuth.ts +276 -34
- package/src/index.ts +35 -1
- package/src/mcp/actionTools.test.ts +498 -0
- package/src/mcp/actionTools.ts +220 -0
- package/src/mcp/auth.test.ts +114 -1
- package/src/mcp/auth.ts +122 -35
- package/src/mcp/createMCPRequest.ts +8 -2
- package/src/mcp/handlers.test.ts +27 -0
- package/src/mcp/handlers.ts +21 -6
- package/src/mcp/oauth.test.ts +1026 -0
- package/src/mcp/oauth.ts +798 -0
- package/src/mcp/oauthMetadata.ts +234 -0
- package/src/mcp/registry.ts +11 -0
- package/src/mcp/server.ts +54 -14
- package/src/mcp/serviceTokens.ts +16 -3
- package/src/mcp/toolExecution.ts +67 -0
- package/src/mcp/toolGenerator.ts +27 -83
- package/src/mcp/types.ts +4 -4
- package/src/models/mcpOAuthAuthorization.ts +97 -0
- package/src/models/mcpOAuthClient.ts +49 -0
- package/src/models/mcpOAuthRevokedFamily.ts +47 -0
- package/src/models/mcpOAuthToken.test.ts +82 -0
- package/src/models/mcpOAuthToken.ts +195 -0
- package/src/models/mcpServiceToken.ts +26 -2
- package/src/permissions.ts +17 -0
- package/src/rateLimit/policies.ts +54 -10
- package/src/rateLimit/rateLimit.test.ts +41 -0
- package/src/rbac/access.ts +1 -0
- package/src/rbac/membershipOrgAdminSource.ts +5 -0
- package/src/rbac/modelRouterAccess.ts +40 -23
- package/src/rbac/realtimeAccess.test.ts +43 -0
- package/src/rbac/realtimeAccess.ts +23 -3
- package/src/rbac/resolve.test.ts +179 -1
- package/src/rbac/resolve.ts +78 -9
- package/src/rbac/roleManager.test.ts +132 -0
- package/src/rbac/roleManager.ts +69 -5
- package/src/rbac/roleModel.ts +1 -1
- package/src/rbac/statements.ts +14 -1
- package/src/rbac/types.ts +12 -0
- package/src/rbac/userWriteGuards.test.ts +407 -0
- package/src/rbac/userWriteGuards.ts +185 -0
- package/src/realtime/changeStreamWatcher.ts +203 -75
- package/src/realtime/queryMatcher.ts +30 -13
- package/src/realtime/realtime.test.ts +132 -0
- package/src/realtime/realtimeApp.ts +94 -10
- package/src/realtime/realtimeAppSetup.test.ts +282 -1
- package/src/realtime/socketAuth.test.ts +140 -8
- package/src/realtime/socketAuth.ts +90 -19
- package/src/realtime/types.ts +8 -5
- package/src/requestContext.ts +52 -1
- package/src/requestCredential.test.ts +89 -0
- package/src/seedRunner.test.ts +21 -0
- package/src/seedRunner.ts +3 -1
- package/src/sortFields.ts +69 -0
- package/src/sync/executors.test.ts +382 -3
- package/src/sync/executors.ts +179 -4
- package/src/sync/models.ts +8 -0
- package/src/sync/mutationHandler.test.ts +166 -2
- package/src/sync/mutationHandler.ts +97 -5
- package/src/sync/routes.ts +4 -2
- package/src/sync/syncFrontier.test.ts +11 -0
- package/src/sync/syncPhaseC.test.ts +18 -0
- package/src/sync/syncSeqPlugin.ts +6 -5
- package/src/sync/syncSocket.test.ts +92 -0
- package/src/terrenoApp.ts +36 -21
- package/src/types/mcpOAuth.ts +129 -0
- package/src/types/mcpServiceToken.ts +6 -1
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
import {beforeAll, beforeEach, describe, expect, it, mock} from "bun:test";
|
|
2
2
|
import {assert} from "chai";
|
|
3
3
|
import type express from "express";
|
|
4
|
-
import {model, Schema} from "mongoose";
|
|
4
|
+
import mongoose, {type Model, model, Schema} from "mongoose";
|
|
5
5
|
|
|
6
6
|
import type {ModelRouterOptions} from "../api";
|
|
7
|
-
import type {User} from "../auth";
|
|
7
|
+
import type {UserModel as AuthUserModel, User} from "../auth";
|
|
8
8
|
import {APIError} from "../errors";
|
|
9
9
|
import {Permissions} from "../permissions";
|
|
10
10
|
import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "../plugins";
|
|
11
|
-
import {
|
|
11
|
+
import {createAccess} from "../rbac/access";
|
|
12
|
+
import {resolveModelRouterAccess} from "../rbac/modelRouterAccess";
|
|
13
|
+
import {OwnerScope} from "../rbac/scopes";
|
|
14
|
+
import {terrenoStatements} from "../rbac/statements";
|
|
15
|
+
import type {AnyTerrenoAccess} from "../rbac/types";
|
|
16
|
+
import {setupDb, UserModel} from "../tests";
|
|
12
17
|
import {ExecutorConflictError, executeCreate, executeDelete, executeUpdate} from "./executors";
|
|
13
18
|
|
|
14
19
|
interface ExecStuff extends IsDeleted {
|
|
@@ -70,6 +75,14 @@ const execUserishSchema = new Schema<ExecUserish>({
|
|
|
70
75
|
});
|
|
71
76
|
const ExecUserishModel = model<ExecUserish>("ExecUserish", execUserishSchema);
|
|
72
77
|
|
|
78
|
+
interface UserishAccount {
|
|
79
|
+
admin?: boolean;
|
|
80
|
+
email: string;
|
|
81
|
+
name?: string;
|
|
82
|
+
roles?: string[];
|
|
83
|
+
tokenEpoch?: number;
|
|
84
|
+
}
|
|
85
|
+
|
|
73
86
|
const owner = {_id: "u-owner", admin: false, id: "u-owner"} as unknown as User;
|
|
74
87
|
const stranger = {_id: "u-stranger", admin: false, id: "u-stranger"} as unknown as User;
|
|
75
88
|
|
|
@@ -173,6 +186,28 @@ describe("executeCreate", () => {
|
|
|
173
186
|
assert.deepEqual(stored?.roles ?? [], []);
|
|
174
187
|
});
|
|
175
188
|
|
|
189
|
+
it("strips dotted-path User roles on create when writeModelName is User", async () => {
|
|
190
|
+
await ExecUserishModel.deleteMany({});
|
|
191
|
+
const {doc} = await executeCreate<ExecUserish>({
|
|
192
|
+
body: {email: "exec-dotted-roles@example.com", "roles.0": "superadmin"},
|
|
193
|
+
model: ExecUserishModel,
|
|
194
|
+
options: {
|
|
195
|
+
accessControl: {} as never,
|
|
196
|
+
permissions: {
|
|
197
|
+
create: [Permissions.IsAuthenticated],
|
|
198
|
+
delete: [],
|
|
199
|
+
list: [],
|
|
200
|
+
read: [],
|
|
201
|
+
update: [],
|
|
202
|
+
},
|
|
203
|
+
} as ModelRouterOptions<ExecUserish>,
|
|
204
|
+
user: owner,
|
|
205
|
+
writeModelName: "User",
|
|
206
|
+
});
|
|
207
|
+
const stored = await ExecUserishModel.findById(doc._id).lean();
|
|
208
|
+
assert.deepEqual(stored?.roles ?? [], []);
|
|
209
|
+
});
|
|
210
|
+
|
|
176
211
|
it("passes a {user} stub request to preCreate when no req is provided", async () => {
|
|
177
212
|
const options = baseOptions({
|
|
178
213
|
preCreate: (body, request) => ({
|
|
@@ -486,6 +521,33 @@ describe("executeUpdate", () => {
|
|
|
486
521
|
expect(error.detail).toBe(`preUpdate hook error on ${doc._id.toString()}: nope`);
|
|
487
522
|
});
|
|
488
523
|
|
|
524
|
+
it("strips dotted-path User roles on update when writeModelName is User", async () => {
|
|
525
|
+
await ExecUserishModel.deleteMany({});
|
|
526
|
+
const target = await ExecUserishModel.create({
|
|
527
|
+
email: "exec-dotted-update@example.com",
|
|
528
|
+
roles: ["support"],
|
|
529
|
+
});
|
|
530
|
+
await executeUpdate<ExecUserish>({
|
|
531
|
+
body: {"roles.0": "superadmin", "roles.1": "superadmin"},
|
|
532
|
+
id: String(target._id),
|
|
533
|
+
model: ExecUserishModel,
|
|
534
|
+
options: {
|
|
535
|
+
accessControl: {} as never,
|
|
536
|
+
permissions: {
|
|
537
|
+
create: [],
|
|
538
|
+
delete: [],
|
|
539
|
+
list: [],
|
|
540
|
+
read: [],
|
|
541
|
+
update: [Permissions.IsAuthenticated],
|
|
542
|
+
},
|
|
543
|
+
} as ModelRouterOptions<ExecUserish>,
|
|
544
|
+
user: owner,
|
|
545
|
+
writeModelName: "User",
|
|
546
|
+
});
|
|
547
|
+
const stored = await ExecUserishModel.findById(target._id).lean();
|
|
548
|
+
assert.deepEqual(stored?.roles ?? [], ["support"]);
|
|
549
|
+
});
|
|
550
|
+
|
|
489
551
|
it("strips _updatedAt from the body before preUpdate", async () => {
|
|
490
552
|
const doc = await createDoc();
|
|
491
553
|
let seenBody: Partial<ExecStuff> | undefined;
|
|
@@ -920,3 +982,320 @@ describe("executeDelete", () => {
|
|
|
920
982
|
expect(error.detail).toBe("cascade failed");
|
|
921
983
|
});
|
|
922
984
|
});
|
|
985
|
+
|
|
986
|
+
describe("RBAC user-model strip on a user model not compiled as User", () => {
|
|
987
|
+
// The configured RBAC user model, compiled under a name other than "User".
|
|
988
|
+
const AccountModel =
|
|
989
|
+
(mongoose.models.ExecRbacAccount as Model<UserishAccount> | undefined) ??
|
|
990
|
+
model<UserishAccount>("ExecRbacAccount", UserModel.schema.clone());
|
|
991
|
+
|
|
992
|
+
beforeAll(async () => {
|
|
993
|
+
await setupDb();
|
|
994
|
+
});
|
|
995
|
+
|
|
996
|
+
beforeEach(async () => {
|
|
997
|
+
await AccountModel.deleteMany({});
|
|
998
|
+
});
|
|
999
|
+
|
|
1000
|
+
it("strips authority fields on update for the configured user model", async () => {
|
|
1001
|
+
const access = createAccess({
|
|
1002
|
+
connection: mongoose.connection,
|
|
1003
|
+
statements: terrenoStatements,
|
|
1004
|
+
userModel: AccountModel as unknown as AuthUserModel,
|
|
1005
|
+
});
|
|
1006
|
+
const account = await AccountModel.create({email: "renamed-self@example.com", name: "Self"});
|
|
1007
|
+
const actor = account as unknown as User;
|
|
1008
|
+
|
|
1009
|
+
await executeUpdate<UserishAccount>({
|
|
1010
|
+
body: {admin: true, name: "renamed", roles: ["superadmin"], tokenEpoch: 99},
|
|
1011
|
+
id: String(account._id),
|
|
1012
|
+
model: AccountModel,
|
|
1013
|
+
options: {
|
|
1014
|
+
accessControl: access,
|
|
1015
|
+
permissions: {
|
|
1016
|
+
create: [],
|
|
1017
|
+
delete: [],
|
|
1018
|
+
list: [],
|
|
1019
|
+
read: [],
|
|
1020
|
+
update: [Permissions.IsAuthenticated],
|
|
1021
|
+
},
|
|
1022
|
+
} as unknown as ModelRouterOptions<UserishAccount>,
|
|
1023
|
+
user: actor,
|
|
1024
|
+
});
|
|
1025
|
+
|
|
1026
|
+
const stored = await AccountModel.findById(account._id).lean();
|
|
1027
|
+
expect(stored?.name).toBe("renamed");
|
|
1028
|
+
expect(stored?.admin).toBe(false);
|
|
1029
|
+
expect(stored?.roles ?? []).toEqual([]);
|
|
1030
|
+
expect(stored?.tokenEpoch ?? 0).toBe(0);
|
|
1031
|
+
});
|
|
1032
|
+
|
|
1033
|
+
it("strips authority fields on create for the configured user model", async () => {
|
|
1034
|
+
const access = createAccess({
|
|
1035
|
+
connection: mongoose.connection,
|
|
1036
|
+
statements: terrenoStatements,
|
|
1037
|
+
userModel: AccountModel as unknown as AuthUserModel,
|
|
1038
|
+
});
|
|
1039
|
+
const {doc} = await executeCreate<UserishAccount>({
|
|
1040
|
+
body: {admin: true, email: "renamed-create@example.com", roles: ["superadmin"]},
|
|
1041
|
+
model: AccountModel,
|
|
1042
|
+
options: {
|
|
1043
|
+
accessControl: access,
|
|
1044
|
+
permissions: {
|
|
1045
|
+
create: [Permissions.IsAuthenticated],
|
|
1046
|
+
delete: [],
|
|
1047
|
+
list: [],
|
|
1048
|
+
read: [],
|
|
1049
|
+
update: [],
|
|
1050
|
+
},
|
|
1051
|
+
} as unknown as ModelRouterOptions<UserishAccount>,
|
|
1052
|
+
user: owner,
|
|
1053
|
+
});
|
|
1054
|
+
const stored = await AccountModel.findById(doc._id).lean();
|
|
1055
|
+
expect(stored?.admin).toBe(false);
|
|
1056
|
+
expect(stored?.roles ?? []).toEqual([]);
|
|
1057
|
+
});
|
|
1058
|
+
});
|
|
1059
|
+
|
|
1060
|
+
describe("owner scope on the written document", () => {
|
|
1061
|
+
const admin = {_id: "u-admin", admin: true, id: "u-admin"} as unknown as User;
|
|
1062
|
+
const scopeStatements = {
|
|
1063
|
+
...terrenoStatements,
|
|
1064
|
+
execStuff: ["create", "read", "update", "delete", "list"],
|
|
1065
|
+
} as const;
|
|
1066
|
+
|
|
1067
|
+
beforeAll(async () => {
|
|
1068
|
+
await setupDb();
|
|
1069
|
+
});
|
|
1070
|
+
|
|
1071
|
+
beforeEach(async () => {
|
|
1072
|
+
await ExecStuffModel.deleteMany({});
|
|
1073
|
+
});
|
|
1074
|
+
|
|
1075
|
+
const ownerRouterOptions = (): ModelRouterOptions<ExecStuff> =>
|
|
1076
|
+
baseOptions({
|
|
1077
|
+
permissions: {
|
|
1078
|
+
create: [Permissions.IsAuthenticated],
|
|
1079
|
+
delete: [Permissions.IsOwner],
|
|
1080
|
+
list: [Permissions.IsAuthenticated],
|
|
1081
|
+
read: [Permissions.IsOwner],
|
|
1082
|
+
update: [Permissions.IsOwner],
|
|
1083
|
+
},
|
|
1084
|
+
});
|
|
1085
|
+
|
|
1086
|
+
const rbacOptions = async (): Promise<ModelRouterOptions<ExecStuff>> => {
|
|
1087
|
+
const access = createAccess({
|
|
1088
|
+
connection: mongoose.connection,
|
|
1089
|
+
defaultRoles: [
|
|
1090
|
+
{
|
|
1091
|
+
displayName: "Exec member",
|
|
1092
|
+
name: "execMember",
|
|
1093
|
+
permissions: {execStuff: ["create", "read", "update", "delete", "list"]},
|
|
1094
|
+
},
|
|
1095
|
+
],
|
|
1096
|
+
statements: scopeStatements,
|
|
1097
|
+
});
|
|
1098
|
+
await access.roles.seedDefaults();
|
|
1099
|
+
const routerAccess = {resource: "execStuff", scope: OwnerScope()};
|
|
1100
|
+
return {
|
|
1101
|
+
access: routerAccess,
|
|
1102
|
+
accessControl: access,
|
|
1103
|
+
permissions: resolveModelRouterAccess<ExecStuff>({
|
|
1104
|
+
access: routerAccess,
|
|
1105
|
+
accessControl: access as AnyTerrenoAccess,
|
|
1106
|
+
}).permissions,
|
|
1107
|
+
} as unknown as ModelRouterOptions<ExecStuff>;
|
|
1108
|
+
};
|
|
1109
|
+
|
|
1110
|
+
const member = (id: string): User =>
|
|
1111
|
+
({_id: id, admin: false, id, roles: ["execMember"]}) as unknown as User;
|
|
1112
|
+
|
|
1113
|
+
it("rejects an update that moves an owned document to another user", async () => {
|
|
1114
|
+
const doc = await ExecStuffModel.create({name: "mine", ownerId: owner.id});
|
|
1115
|
+
const error = await caught(
|
|
1116
|
+
executeUpdate<ExecStuff>({
|
|
1117
|
+
body: {name: "moved", ownerId: stranger.id},
|
|
1118
|
+
id: doc._id.toString(),
|
|
1119
|
+
model: ExecStuffModel,
|
|
1120
|
+
options: ownerRouterOptions(),
|
|
1121
|
+
user: owner,
|
|
1122
|
+
})
|
|
1123
|
+
);
|
|
1124
|
+
expect(error.status).toBe(403);
|
|
1125
|
+
const stored = await ExecStuffModel.findById(doc._id).lean();
|
|
1126
|
+
expect(stored?.ownerId).toBe(owner.id);
|
|
1127
|
+
expect(stored?.name).toBe("mine");
|
|
1128
|
+
});
|
|
1129
|
+
|
|
1130
|
+
it("still lets the owner update other fields and an admin reassign the owner", async () => {
|
|
1131
|
+
const doc = await ExecStuffModel.create({name: "mine", ownerId: owner.id});
|
|
1132
|
+
await executeUpdate<ExecStuff>({
|
|
1133
|
+
body: {name: "renamed", ownerId: owner.id},
|
|
1134
|
+
id: doc._id.toString(),
|
|
1135
|
+
model: ExecStuffModel,
|
|
1136
|
+
options: ownerRouterOptions(),
|
|
1137
|
+
user: owner,
|
|
1138
|
+
});
|
|
1139
|
+
await executeUpdate<ExecStuff>({
|
|
1140
|
+
body: {ownerId: stranger.id},
|
|
1141
|
+
id: doc._id.toString(),
|
|
1142
|
+
model: ExecStuffModel,
|
|
1143
|
+
options: ownerRouterOptions(),
|
|
1144
|
+
user: admin,
|
|
1145
|
+
});
|
|
1146
|
+
const stored = await ExecStuffModel.findById(doc._id).lean();
|
|
1147
|
+
expect(stored?.name).toBe("renamed");
|
|
1148
|
+
expect(stored?.ownerId).toBe(stranger.id);
|
|
1149
|
+
});
|
|
1150
|
+
|
|
1151
|
+
it("rejects a create that names another user as the owner", async () => {
|
|
1152
|
+
const error = await caught(
|
|
1153
|
+
executeCreate<ExecStuff>({
|
|
1154
|
+
body: {name: "planted", ownerId: stranger.id},
|
|
1155
|
+
model: ExecStuffModel,
|
|
1156
|
+
options: ownerRouterOptions(),
|
|
1157
|
+
user: owner,
|
|
1158
|
+
})
|
|
1159
|
+
);
|
|
1160
|
+
expect(error.status).toBe(403);
|
|
1161
|
+
expect(await ExecStuffModel.countDocuments({ownerId: stranger.id})).toBe(0);
|
|
1162
|
+
});
|
|
1163
|
+
|
|
1164
|
+
it("allows creates that name the caller or no owner", async () => {
|
|
1165
|
+
await executeCreate<ExecStuff>({
|
|
1166
|
+
body: {name: "self", ownerId: owner.id},
|
|
1167
|
+
model: ExecStuffModel,
|
|
1168
|
+
options: ownerRouterOptions(),
|
|
1169
|
+
user: owner,
|
|
1170
|
+
});
|
|
1171
|
+
await executeCreate<ExecStuff>({
|
|
1172
|
+
body: {name: "unowned"},
|
|
1173
|
+
model: ExecStuffModel,
|
|
1174
|
+
options: ownerRouterOptions(),
|
|
1175
|
+
user: owner,
|
|
1176
|
+
});
|
|
1177
|
+
await executeCreate<ExecStuff>({
|
|
1178
|
+
body: {name: "for someone", ownerId: stranger.id},
|
|
1179
|
+
model: ExecStuffModel,
|
|
1180
|
+
options: ownerRouterOptions(),
|
|
1181
|
+
user: admin,
|
|
1182
|
+
});
|
|
1183
|
+
expect(await ExecStuffModel.countDocuments({})).toBe(3);
|
|
1184
|
+
});
|
|
1185
|
+
|
|
1186
|
+
it("does not apply the owner check to routers without owner permissions", async () => {
|
|
1187
|
+
await executeCreate<ExecStuff>({
|
|
1188
|
+
body: {name: "open", ownerId: stranger.id},
|
|
1189
|
+
model: ExecStuffModel,
|
|
1190
|
+
options: baseOptions({
|
|
1191
|
+
permissions: {
|
|
1192
|
+
create: [Permissions.IsAuthenticated],
|
|
1193
|
+
delete: [Permissions.IsAdmin],
|
|
1194
|
+
list: [Permissions.IsAny],
|
|
1195
|
+
read: [Permissions.IsAny],
|
|
1196
|
+
update: [Permissions.IsAdmin],
|
|
1197
|
+
},
|
|
1198
|
+
}),
|
|
1199
|
+
user: owner,
|
|
1200
|
+
});
|
|
1201
|
+
expect(await ExecStuffModel.countDocuments({ownerId: stranger.id})).toBe(1);
|
|
1202
|
+
});
|
|
1203
|
+
|
|
1204
|
+
it("rejects RBAC OwnerScope updates and creates that leave the caller's scope", async () => {
|
|
1205
|
+
const options = await rbacOptions();
|
|
1206
|
+
const alice = member(new mongoose.Types.ObjectId().toString());
|
|
1207
|
+
const bob = member(new mongoose.Types.ObjectId().toString());
|
|
1208
|
+
|
|
1209
|
+
const {doc} = await executeCreate<ExecStuff>({
|
|
1210
|
+
body: {name: "alice's", ownerId: alice.id},
|
|
1211
|
+
model: ExecStuffModel,
|
|
1212
|
+
options,
|
|
1213
|
+
user: alice,
|
|
1214
|
+
});
|
|
1215
|
+
await executeUpdate<ExecStuff>({
|
|
1216
|
+
body: {name: "alice renamed"},
|
|
1217
|
+
id: doc._id.toString(),
|
|
1218
|
+
model: ExecStuffModel,
|
|
1219
|
+
options,
|
|
1220
|
+
user: alice,
|
|
1221
|
+
});
|
|
1222
|
+
|
|
1223
|
+
const moveError = await caught(
|
|
1224
|
+
executeUpdate<ExecStuff>({
|
|
1225
|
+
body: {name: "attacker-authored", ownerId: bob.id},
|
|
1226
|
+
id: doc._id.toString(),
|
|
1227
|
+
model: ExecStuffModel,
|
|
1228
|
+
options,
|
|
1229
|
+
user: alice,
|
|
1230
|
+
})
|
|
1231
|
+
);
|
|
1232
|
+
expect(moveError.status).toBe(403);
|
|
1233
|
+
const stored = await ExecStuffModel.findById(doc._id).lean();
|
|
1234
|
+
expect(stored?.ownerId).toBe(alice.id);
|
|
1235
|
+
expect(stored?.name).toBe("alice renamed");
|
|
1236
|
+
|
|
1237
|
+
const plantError = await caught(
|
|
1238
|
+
executeCreate<ExecStuff>({
|
|
1239
|
+
body: {name: "planted", ownerId: bob.id},
|
|
1240
|
+
model: ExecStuffModel,
|
|
1241
|
+
options,
|
|
1242
|
+
user: alice,
|
|
1243
|
+
})
|
|
1244
|
+
);
|
|
1245
|
+
expect(plantError.status).toBe(403);
|
|
1246
|
+
expect(await ExecStuffModel.countDocuments({ownerId: bob.id})).toBe(0);
|
|
1247
|
+
});
|
|
1248
|
+
});
|
|
1249
|
+
|
|
1250
|
+
describe("soft-delete flag in client write bodies", () => {
|
|
1251
|
+
beforeAll(async () => {
|
|
1252
|
+
await setupDb();
|
|
1253
|
+
});
|
|
1254
|
+
|
|
1255
|
+
beforeEach(async () => {
|
|
1256
|
+
await ExecStuffModel.deleteMany({deleted: {$in: [true, false]}} as never);
|
|
1257
|
+
});
|
|
1258
|
+
|
|
1259
|
+
const noDeleteOptions = (): ModelRouterOptions<ExecStuff> => {
|
|
1260
|
+
const options = baseOptions();
|
|
1261
|
+
options.permissions = {...options.permissions, delete: []};
|
|
1262
|
+
return options;
|
|
1263
|
+
};
|
|
1264
|
+
|
|
1265
|
+
it("ignores deleted in an update body, so update permission cannot soft-delete", async () => {
|
|
1266
|
+
const doc = await ExecStuffModel.create({name: "keep", ownerId: owner.id});
|
|
1267
|
+
const {doc: updated} = await executeUpdate<ExecStuff>({
|
|
1268
|
+
body: {deleted: true, name: "renamed"},
|
|
1269
|
+
id: doc._id.toString(),
|
|
1270
|
+
model: ExecStuffModel,
|
|
1271
|
+
options: noDeleteOptions(),
|
|
1272
|
+
user: owner,
|
|
1273
|
+
});
|
|
1274
|
+
expect(updated.name).toBe("renamed");
|
|
1275
|
+
expect(updated.deleted).toBe(false);
|
|
1276
|
+
expect(await ExecStuffModel.countDocuments({_id: doc._id})).toBe(1);
|
|
1277
|
+
});
|
|
1278
|
+
|
|
1279
|
+
it("ignores deleted in a create body", async () => {
|
|
1280
|
+
const {doc} = await executeCreate<ExecStuff>({
|
|
1281
|
+
body: {deleted: true, name: "fresh", ownerId: owner.id},
|
|
1282
|
+
model: ExecStuffModel,
|
|
1283
|
+
options: noDeleteOptions(),
|
|
1284
|
+
user: owner,
|
|
1285
|
+
});
|
|
1286
|
+
expect(doc.deleted).toBe(false);
|
|
1287
|
+
expect(await ExecStuffModel.countDocuments({_id: doc._id})).toBe(1);
|
|
1288
|
+
});
|
|
1289
|
+
|
|
1290
|
+
it("still lets a server-side preUpdate hook set deleted", async () => {
|
|
1291
|
+
const doc = await ExecStuffModel.create({name: "archive me", ownerId: owner.id});
|
|
1292
|
+
await executeUpdate<ExecStuff>({
|
|
1293
|
+
body: {name: "archived"},
|
|
1294
|
+
id: doc._id.toString(),
|
|
1295
|
+
model: ExecStuffModel,
|
|
1296
|
+
options: baseOptions({preUpdate: (body) => ({...body, deleted: true})}),
|
|
1297
|
+
user: owner,
|
|
1298
|
+
});
|
|
1299
|
+
expect(await ExecStuffModel.countDocuments({_id: doc._id})).toBe(0);
|
|
1300
|
+
});
|
|
1301
|
+
});
|
package/src/sync/executors.ts
CHANGED
|
@@ -32,8 +32,9 @@ import {
|
|
|
32
32
|
passthroughOrWrap,
|
|
33
33
|
passthroughOrWrapWrite,
|
|
34
34
|
} from "../errors";
|
|
35
|
-
import {checkPermissions} from "../permissions";
|
|
36
|
-
import {validateAccessWritePayload} from "../rbac/modelRouterAccess";
|
|
35
|
+
import {checkPermissions, type PermissionMethod, Permissions} from "../permissions";
|
|
36
|
+
import {buildAccessPermissions, validateAccessWritePayload} from "../rbac/modelRouterAccess";
|
|
37
|
+
import {assertCanWriteTargetUser, assertCanWriteUserIdentity} from "../rbac/userWriteGuards";
|
|
37
38
|
import {transform} from "../transformers";
|
|
38
39
|
|
|
39
40
|
/** A hydrated mongoose document joined with the router's base type. */
|
|
@@ -173,6 +174,133 @@ const reloadDocForConflict = async <T>(
|
|
|
173
174
|
}
|
|
174
175
|
};
|
|
175
176
|
|
|
177
|
+
/**
|
|
178
|
+
* True for legacy permissions whose object check binds a document to its owner. Read lazily:
|
|
179
|
+
* `permissions` and this module import each other.
|
|
180
|
+
*/
|
|
181
|
+
const isOwnerIdentityPermission = (permission: unknown): boolean =>
|
|
182
|
+
permission === Permissions.IsOwner || permission === Permissions.IsOwnerOrReadOnly;
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Owner and scope checks that must hold for the document as written, not only as loaded.
|
|
186
|
+
*
|
|
187
|
+
* - RBAC routers (`access` + `accessControl`): the framework-built role and scope checks for
|
|
188
|
+
* the method (the role grant evaluated against the document, plus the router `access.scope`),
|
|
189
|
+
* and any owner-identity entries in `access.also`. Other `also` entries are left out so
|
|
190
|
+
* state-dependent consumer checks keep running only against the pre-write document.
|
|
191
|
+
* - Legacy routers: `IsOwner` when the method's permissions use an owner-identity check.
|
|
192
|
+
*/
|
|
193
|
+
const getWriteScopeChecks = <T>(
|
|
194
|
+
options: ModelRouterOptions<T>,
|
|
195
|
+
method: "create" | "update"
|
|
196
|
+
): PermissionMethod<T>[] => {
|
|
197
|
+
if (options.access && options.accessControl) {
|
|
198
|
+
const scoped = buildAccessPermissions<T>(options.accessControl, {
|
|
199
|
+
...options.access,
|
|
200
|
+
also: undefined,
|
|
201
|
+
})[method];
|
|
202
|
+
const alsoOwner = ((options.access.also?.[method] ?? []) as PermissionMethod<T>[]).filter(
|
|
203
|
+
isOwnerIdentityPermission
|
|
204
|
+
);
|
|
205
|
+
return [...scoped, ...alsoOwner];
|
|
206
|
+
}
|
|
207
|
+
if (method === "update") {
|
|
208
|
+
return (options.permissions?.update ?? []).some(isOwnerIdentityPermission)
|
|
209
|
+
? [Permissions.IsOwner as PermissionMethod<T>]
|
|
210
|
+
: [];
|
|
211
|
+
}
|
|
212
|
+
// A create is owner-scoped when any method on the router binds documents to their owner.
|
|
213
|
+
const lists = [
|
|
214
|
+
options.permissions?.create,
|
|
215
|
+
options.permissions?.read,
|
|
216
|
+
options.permissions?.update,
|
|
217
|
+
options.permissions?.delete,
|
|
218
|
+
];
|
|
219
|
+
if (!lists.some((list) => (list ?? []).some(isOwnerIdentityPermission))) {
|
|
220
|
+
return [];
|
|
221
|
+
}
|
|
222
|
+
// Only a named owner is checked, so a create that leaves the owner for a hook or default
|
|
223
|
+
// to fill keeps working.
|
|
224
|
+
return [
|
|
225
|
+
(method_, user, obj) =>
|
|
226
|
+
(obj as {ownerId?: unknown} | undefined)?.ownerId == null ||
|
|
227
|
+
Permissions.IsOwner(method_, user, obj),
|
|
228
|
+
];
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Reject a write whose resulting document would fall outside the caller's owner or RBAC scope,
|
|
233
|
+
* for example a create naming another user as owner or an update that moves the owner field.
|
|
234
|
+
* Runs on REST, MCP and sync writes alike because they share these executors.
|
|
235
|
+
*/
|
|
236
|
+
const assertWriteStaysInScope = async <T>({
|
|
237
|
+
doc,
|
|
238
|
+
method,
|
|
239
|
+
model,
|
|
240
|
+
options,
|
|
241
|
+
user,
|
|
242
|
+
}: {
|
|
243
|
+
doc: unknown;
|
|
244
|
+
method: "create" | "update";
|
|
245
|
+
model: Model<T>;
|
|
246
|
+
options: ModelRouterOptions<T>;
|
|
247
|
+
user?: User;
|
|
248
|
+
}): Promise<void> => {
|
|
249
|
+
const checks = getWriteScopeChecks(options, method);
|
|
250
|
+
for (const check of checks) {
|
|
251
|
+
if (!(await check(method, user, doc as T))) {
|
|
252
|
+
throw new APIError({
|
|
253
|
+
status: 403,
|
|
254
|
+
title: `Write scope violation on ${model.modelName}`,
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Hydrate a create body item without saving it, so owner checks see defaults and virtuals the
|
|
262
|
+
* way they see a loaded document. Returns undefined when the item cannot be cast; `create`
|
|
263
|
+
* then reports the same validation error.
|
|
264
|
+
*/
|
|
265
|
+
const hydrateCreateCandidate = <T>(model: Model<T>, item: unknown): unknown => {
|
|
266
|
+
try {
|
|
267
|
+
return new (model as unknown as new (doc: unknown) => unknown)(item);
|
|
268
|
+
} catch {
|
|
269
|
+
return undefined;
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
/** Sync bookkeeping that `syncPlugin` stamps on every write; clients never set it. */
|
|
274
|
+
const SYNC_STAMP_FIELDS = ["_syncSeq", "_syncPrevStream"];
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Remove fields that only the server may set from a client write body:
|
|
278
|
+
* - `deleted` on a soft-delete model is set only by the delete operation, so update authority
|
|
279
|
+
* cannot soft-delete a record without delete permission, `preDelete` / `postDelete`, and the
|
|
280
|
+
* delete audit.
|
|
281
|
+
* - `_syncSeq` / `_syncPrevStream` order the sync streams, so a client cannot pin a document's
|
|
282
|
+
* seq and hide it from other members' snapshots and deltas.
|
|
283
|
+
* Server hooks (`preCreate` / `preUpdate`) run after this and may still set `deleted`.
|
|
284
|
+
*/
|
|
285
|
+
const stripServerOwnedFields = <T>(model: Model<T>, body: unknown): unknown => {
|
|
286
|
+
if (Array.isArray(body)) {
|
|
287
|
+
return body.map((item) => stripServerOwnedFields(model, item));
|
|
288
|
+
}
|
|
289
|
+
if (!body || typeof body !== "object") {
|
|
290
|
+
return body;
|
|
291
|
+
}
|
|
292
|
+
const isSoftDeleteModel = model.schema.path("deleted")?.instance === "Boolean";
|
|
293
|
+
const fields = isSoftDeleteModel ? [...SYNC_STAMP_FIELDS, "deleted"] : SYNC_STAMP_FIELDS;
|
|
294
|
+
if (!fields.some((field) => Object.hasOwn(body, field))) {
|
|
295
|
+
return body;
|
|
296
|
+
}
|
|
297
|
+
const rest = {...(body as Record<string, unknown>)};
|
|
298
|
+
for (const field of fields) {
|
|
299
|
+
delete rest[field];
|
|
300
|
+
}
|
|
301
|
+
return rest;
|
|
302
|
+
};
|
|
303
|
+
|
|
176
304
|
/**
|
|
177
305
|
* Create a document through the same pipeline as `POST /`: method-level permissions,
|
|
178
306
|
* `transformer.transform`, `preCreate`, `Model.create` (Mongoose validation), population,
|
|
@@ -223,7 +351,12 @@ export const executeCreate = async <T>({
|
|
|
223
351
|
|
|
224
352
|
let cleanedBody: Partial<T> | (Partial<T> | undefined)[] | null | undefined;
|
|
225
353
|
try {
|
|
226
|
-
cleanedBody = transform<T>(
|
|
354
|
+
cleanedBody = transform<T>(
|
|
355
|
+
options,
|
|
356
|
+
stripServerOwnedFields(model, body) as Partial<T> | Partial<T>[],
|
|
357
|
+
"create",
|
|
358
|
+
user
|
|
359
|
+
);
|
|
227
360
|
} catch (error: unknown) {
|
|
228
361
|
throw passthroughOrWrap(error, {
|
|
229
362
|
code: "transform-error",
|
|
@@ -276,6 +409,15 @@ export const executeCreate = async <T>({
|
|
|
276
409
|
phase: "create",
|
|
277
410
|
user,
|
|
278
411
|
});
|
|
412
|
+
if (!skipPermissionChecks) {
|
|
413
|
+
const items = Array.isArray(cleanedBody) ? cleanedBody : [cleanedBody];
|
|
414
|
+
for (const item of items) {
|
|
415
|
+
const candidate = item ? hydrateCreateCandidate(model, item) : undefined;
|
|
416
|
+
if (candidate) {
|
|
417
|
+
await assertWriteStaysInScope({doc: candidate, method: "create", model, options, user});
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
279
421
|
let data: ExecutorDoc<T>;
|
|
280
422
|
try {
|
|
281
423
|
data = (await model.create(cleanedBody as T)) as ExecutorDoc<T>;
|
|
@@ -406,9 +548,22 @@ export const executeUpdate = async <T>({
|
|
|
406
548
|
});
|
|
407
549
|
}
|
|
408
550
|
|
|
551
|
+
// Runs even for admin-window writes that skip modelRouter permissions.
|
|
552
|
+
await assertCanWriteTargetUser({
|
|
553
|
+
accessControl: options.accessControl,
|
|
554
|
+
actor: user,
|
|
555
|
+
modelName: writeModelName ?? model.modelName,
|
|
556
|
+
target: doc,
|
|
557
|
+
});
|
|
558
|
+
|
|
409
559
|
let cleanedBody: Partial<T> | T | null | undefined;
|
|
410
560
|
try {
|
|
411
|
-
cleanedBody = transform<T>(
|
|
561
|
+
cleanedBody = transform<T>(
|
|
562
|
+
options,
|
|
563
|
+
stripServerOwnedFields(model, body) as Partial<T>,
|
|
564
|
+
"update",
|
|
565
|
+
user
|
|
566
|
+
) as Partial<T>;
|
|
412
567
|
} catch (error: unknown) {
|
|
413
568
|
throw passthroughOrWrap(error, {
|
|
414
569
|
code: "transform-error",
|
|
@@ -454,6 +609,15 @@ export const executeUpdate = async <T>({
|
|
|
454
609
|
}
|
|
455
610
|
}
|
|
456
611
|
|
|
612
|
+
// Checked before the privileged-field strip so identity writes are rejected, not dropped.
|
|
613
|
+
await assertCanWriteUserIdentity({
|
|
614
|
+
accessControl: options.accessControl,
|
|
615
|
+
actor: user,
|
|
616
|
+
body: cleanedBody,
|
|
617
|
+
modelName: writeModelName ?? model.modelName,
|
|
618
|
+
target: doc,
|
|
619
|
+
});
|
|
620
|
+
|
|
457
621
|
cleanedBody = omitUserRolesFromWriteBody(
|
|
458
622
|
writeModelName ?? model.modelName,
|
|
459
623
|
options.accessControl,
|
|
@@ -533,6 +697,10 @@ export const executeUpdate = async <T>({
|
|
|
533
697
|
// updates. We won't wind up with corrupted data, just an API error.
|
|
534
698
|
try {
|
|
535
699
|
doc.set(cleanedBody);
|
|
700
|
+
// The pre-write document passed the update checks; the written state must stay in scope too.
|
|
701
|
+
if (!skipPermissionChecks) {
|
|
702
|
+
await assertWriteStaysInScope({doc, method: "update", model, options, user});
|
|
703
|
+
}
|
|
536
704
|
await doc.save();
|
|
537
705
|
} catch (error: unknown) {
|
|
538
706
|
// Task 9.13: `syncPlugin` enables Mongoose `optimisticConcurrency` on synced schemas, so
|
|
@@ -695,6 +863,13 @@ export const executeDelete = async <T>({
|
|
|
695
863
|
});
|
|
696
864
|
}
|
|
697
865
|
|
|
866
|
+
await assertCanWriteTargetUser({
|
|
867
|
+
accessControl: options.accessControl,
|
|
868
|
+
actor: user,
|
|
869
|
+
modelName: model.modelName,
|
|
870
|
+
target: doc,
|
|
871
|
+
});
|
|
872
|
+
|
|
698
873
|
if (options.preDelete) {
|
|
699
874
|
let body: T | null | undefined;
|
|
700
875
|
try {
|
package/src/sync/models.ts
CHANGED
|
@@ -436,6 +436,8 @@ export interface SyncMutationDocument {
|
|
|
436
436
|
_id: mongoose.Types.ObjectId;
|
|
437
437
|
mutationId: string;
|
|
438
438
|
userId: string;
|
|
439
|
+
/** Sync collection the mutation was claimed for; absent on rows recorded before it existed. */
|
|
440
|
+
collectionTag?: string;
|
|
439
441
|
status: SyncMutationStatus;
|
|
440
442
|
nackCode?: string;
|
|
441
443
|
resultId?: string;
|
|
@@ -464,6 +466,12 @@ const syncMutationSchema = new Schema<SyncMutationDocument>(
|
|
|
464
466
|
"SYNC_MUTATION_LEASE_MS may be taken over by a fresh delivery via findOneAndUpdate",
|
|
465
467
|
type: Date,
|
|
466
468
|
},
|
|
469
|
+
collectionTag: {
|
|
470
|
+
description:
|
|
471
|
+
"Sync collection the mutation was claimed for; a replay naming another collection is " +
|
|
472
|
+
"rejected",
|
|
473
|
+
type: String,
|
|
474
|
+
},
|
|
467
475
|
created: {
|
|
468
476
|
default: () => DateTime.now().toJSDate(),
|
|
469
477
|
description: "When the mutation was first claimed; TTL-indexed so rows expire after 30 days",
|