@terreno/api 57.18.0 → 57.20.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/CHANGELOG.md +2071 -2
- package/dist/accountSecurity/accessActions.d.ts +38 -0
- package/dist/accountSecurity/accessActions.js +157 -0
- package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
- package/dist/accountSecurity/accountSecurityApp.js +438 -0
- package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
- package/dist/accountSecurity/accountSecurityService.js +481 -0
- package/dist/accountSecurity/credentialActions.d.ts +16 -0
- package/dist/accountSecurity/credentialActions.js +189 -0
- package/dist/accountSecurity/membershipActions.d.ts +15 -0
- package/dist/accountSecurity/membershipActions.js +81 -0
- package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
- package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
- package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
- package/dist/accountSecurity/securityEventHooks.js +223 -0
- package/dist/accountSecurity/securityEvents.d.ts +162 -0
- package/dist/accountSecurity/securityEvents.js +114 -0
- package/dist/accountSecurity/securityNotifications.d.ts +125 -0
- package/dist/accountSecurity/securityNotifications.js +333 -0
- package/dist/api.js +38 -6
- package/dist/audit/auditEventModel.d.ts +5 -3
- package/dist/audit/auditEventModel.js +8 -6
- package/dist/audit/processQueue.js +4 -2
- package/dist/audit/record.d.ts +2 -2
- package/dist/audit/record.js +3 -0
- package/dist/authRecovery.js +29 -1
- package/dist/betterAuth.d.ts +179 -10
- package/dist/betterAuthApp.d.ts +15 -0
- package/dist/betterAuthApp.js +23 -0
- package/dist/betterAuthChallengeHeaders.d.ts +37 -0
- package/dist/betterAuthChallengeHeaders.js +180 -0
- package/dist/betterAuthFeatures.d.ts +54 -0
- package/dist/betterAuthFeatures.js +239 -0
- package/dist/betterAuthMethods.d.ts +73 -0
- package/dist/betterAuthMethods.js +55 -0
- package/dist/betterAuthOAuthHandoff.d.ts +10 -2
- package/dist/betterAuthOAuthHandoff.js +222 -24
- package/dist/betterAuthSetPassword.d.ts +33 -0
- package/dist/betterAuthSetPassword.js +166 -0
- package/dist/betterAuthSetup.d.ts +57 -8
- package/dist/betterAuthSetup.js +327 -36
- package/dist/consentApp.d.ts +9 -4
- package/dist/consentApp.js +344 -28
- package/dist/consentStatus.d.ts +60 -0
- package/dist/consentStatus.js +111 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +41 -2
- package/dist/expressServer.js +3 -2
- package/dist/index.d.ts +14 -2
- package/dist/index.js +23 -3
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +28 -4
- package/dist/orgs/membershipGuards.d.ts +7 -0
- package/dist/orgs/membershipGuards.js +32 -0
- package/dist/orgs/orgsApp.d.ts +19 -1
- package/dist/orgs/orgsApp.js +55 -24
- package/dist/rateLimit/policies.js +8 -0
- package/dist/rbac/access.js +2 -1
- package/dist/rbac/resolve.d.ts +9 -1
- package/dist/rbac/resolve.js +21 -16
- package/dist/rbac/roleManager.d.ts +6 -0
- package/dist/rbac/roleManager.js +8 -7
- package/dist/rbac/roleModel.d.ts +1 -0
- package/dist/rbac/roleModel.js +45 -3
- package/dist/rbac/statements.d.ts +2 -2
- package/dist/rbac/statements.js +10 -1
- package/dist/rbac/types.d.ts +6 -0
- package/dist/rbac/userWriteGuards.js +2 -1
- package/dist/schemaMetadata.js +8 -1
- package/dist/seedRunner.js +7 -2
- package/dist/terrenoApp.d.ts +4 -0
- package/dist/terrenoApp.js +15 -0
- package/dist/tests/models.d.ts +5 -0
- package/dist/tests/models.js +8 -0
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpOAuth.d.ts +35 -2
- package/package.json +6 -3
- package/src/__snapshots__/openApi.test.ts.snap +288 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
- package/src/accountSecurity/accessActions.test.ts +723 -0
- package/src/accountSecurity/accessActions.ts +173 -0
- package/src/accountSecurity/accountSecurity.test.ts +947 -0
- package/src/accountSecurity/accountSecurityApp.ts +720 -0
- package/src/accountSecurity/accountSecurityService.ts +826 -0
- package/src/accountSecurity/credentialActions.test.ts +867 -0
- package/src/accountSecurity/credentialActions.ts +260 -0
- package/src/accountSecurity/membershipActions.ts +89 -0
- package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
- package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
- package/src/accountSecurity/securityEventHooks.ts +294 -0
- package/src/accountSecurity/securityEvents.ts +165 -0
- package/src/accountSecurity/securityNotifications.test.ts +1323 -0
- package/src/accountSecurity/securityNotifications.ts +516 -0
- package/src/api.arrayOperations.test.ts +71 -0
- package/src/api.ts +38 -7
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/authRecovery.test.ts +23 -0
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- package/src/betterAuth.ts +194 -8
- package/src/betterAuthApp.ts +32 -0
- package/src/betterAuthChallengeHeaders.test.ts +476 -0
- package/src/betterAuthChallengeHeaders.ts +227 -0
- package/src/betterAuthFeatures.test.ts +489 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +844 -0
- package/src/betterAuthMethods.test.ts +138 -0
- package/src/betterAuthMethods.ts +98 -0
- package/src/betterAuthOAuthHandoff.test.ts +482 -69
- package/src/betterAuthOAuthHandoff.ts +293 -33
- package/src/betterAuthOAuthProxy.test.ts +421 -0
- package/src/betterAuthPasswordReset.test.ts +190 -0
- package/src/betterAuthSetPassword.test.ts +378 -0
- package/src/betterAuthSetPassword.ts +213 -0
- package/src/betterAuthSetup.test.ts +39 -7
- package/src/betterAuthSetup.ts +457 -38
- package/src/consentApp.test.ts +869 -2
- package/src/consentApp.ts +438 -36
- package/src/consentStatus.test.ts +226 -0
- package/src/consentStatus.ts +171 -0
- package/src/errors.test.ts +81 -0
- package/src/errors.ts +50 -1
- package/src/expressServer.test.ts +29 -0
- package/src/expressServer.ts +3 -2
- package/src/index.ts +30 -0
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.ts +30 -5
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +101 -2
- package/src/orgs/orgsApp.ts +69 -28
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rbac/access.ts +4 -1
- package/src/rbac/resolve.test.ts +65 -0
- package/src/rbac/resolve.ts +37 -17
- package/src/rbac/roleManager.test.ts +64 -0
- package/src/rbac/roleManager.ts +15 -6
- package/src/rbac/roleModel.test.ts +174 -1
- package/src/rbac/roleModel.ts +66 -3
- package/src/rbac/routes.test.ts +58 -0
- package/src/rbac/statements.test.ts +4 -1
- package/src/rbac/statements.ts +11 -1
- package/src/rbac/types.ts +6 -1
- package/src/rbac/userWriteGuards.test.ts +48 -0
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/terrenoApp.ts +20 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +188 -0
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +13 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpOAuth.ts +39 -3
package/src/orgs/orgsApp.test.ts
CHANGED
|
@@ -5,7 +5,12 @@ import type {Application} from "express";
|
|
|
5
5
|
import mongoose from "mongoose";
|
|
6
6
|
import type {PassportLocalMongooseDocument} from "passport-local-mongoose";
|
|
7
7
|
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
type User as AuthUser,
|
|
10
|
+
type UserModel as AuthUserModel,
|
|
11
|
+
addAuthRoutes,
|
|
12
|
+
setupAuth,
|
|
13
|
+
} from "../auth";
|
|
9
14
|
import {apiErrorMiddleware, apiUnauthorizedMiddleware} from "../errors";
|
|
10
15
|
import {createAccess} from "../rbac/access";
|
|
11
16
|
import {terrenoStatements} from "../rbac/statements";
|
|
@@ -38,6 +43,7 @@ const createUser = async (args: {email: string; roles?: string[]}): Promise<User
|
|
|
38
43
|
describe("OrgsApp", () => {
|
|
39
44
|
let app: Application;
|
|
40
45
|
let auditEvents: OrgAuditEvent[];
|
|
46
|
+
let access: ReturnType<typeof createAccess>;
|
|
41
47
|
|
|
42
48
|
beforeEach(async () => {
|
|
43
49
|
await Promise.all([
|
|
@@ -46,7 +52,7 @@ describe("OrgsApp", () => {
|
|
|
46
52
|
UserModel.deleteMany({}),
|
|
47
53
|
]);
|
|
48
54
|
auditEvents = [];
|
|
49
|
-
|
|
55
|
+
access = createAccess({
|
|
50
56
|
connection: mongoose.connection,
|
|
51
57
|
organizations: true,
|
|
52
58
|
statements: terrenoStatements,
|
|
@@ -246,6 +252,99 @@ describe("OrgsApp", () => {
|
|
|
246
252
|
assert.equal(mixedCase.status, 409);
|
|
247
253
|
});
|
|
248
254
|
|
|
255
|
+
it("applies a membership's org-admin grants at once, not after the permission cache expires", async () => {
|
|
256
|
+
const operator = await createUser({email: "operator@example.com", roles: ["operator"]});
|
|
257
|
+
const member = await createUser({email: "new-org-admin@example.com"});
|
|
258
|
+
const org = await Organization.create({name: "Acme", ownerId: operator._id});
|
|
259
|
+
const operatorAgent = await loginWithPassword(app, {
|
|
260
|
+
email: "operator@example.com",
|
|
261
|
+
password: PASSWORD,
|
|
262
|
+
});
|
|
263
|
+
const memberUser = member as unknown as AuthUser;
|
|
264
|
+
// Resolve (and cache) the user's permissions before they join.
|
|
265
|
+
assert.isUndefined((await access.getPermissions({user: memberUser})).admin);
|
|
266
|
+
|
|
267
|
+
const attached = await operatorAgent
|
|
268
|
+
.post(`/orgs/${org._id}/members`)
|
|
269
|
+
.send({email: "new-org-admin@example.com", roleName: "org-admin"});
|
|
270
|
+
assert.equal(attached.status, 201);
|
|
271
|
+
assert.deepEqual((await access.getPermissions({user: memberUser})).admin, ["access"]);
|
|
272
|
+
|
|
273
|
+
const demoted = await operatorAgent
|
|
274
|
+
.patch(`/orgs/${org._id}/members/${attached.body.data._id}`)
|
|
275
|
+
.send({roleName: "member"});
|
|
276
|
+
// The operator's attach left the new member as the only org-admin, so demoting is refused;
|
|
277
|
+
// suspend instead, which another active org-admin makes possible.
|
|
278
|
+
assert.equal(demoted.status, 400);
|
|
279
|
+
await Membership.create({organizationId: org._id, roleName: "org-admin", userId: operator._id});
|
|
280
|
+
const suspended = await operatorAgent
|
|
281
|
+
.patch(`/orgs/${org._id}/members/${attached.body.data._id}`)
|
|
282
|
+
.send({status: "suspended"});
|
|
283
|
+
assert.equal(suspended.status, 200);
|
|
284
|
+
assert.isUndefined((await access.getPermissions({user: memberUser})).admin);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
describe("permission cache", () => {
|
|
288
|
+
const setUpOrgAdmins = async (): Promise<{
|
|
289
|
+
operatorAgent: Awaited<ReturnType<typeof loginWithPassword>>;
|
|
290
|
+
org: Awaited<ReturnType<typeof Organization.create>>;
|
|
291
|
+
orgAdmins: AuthUser[];
|
|
292
|
+
removable: Awaited<ReturnType<typeof Membership.create>>;
|
|
293
|
+
}> => {
|
|
294
|
+
const operator = await createUser({email: "operator@example.com", roles: ["operator"]});
|
|
295
|
+
const first = await createUser({email: "first-org-admin@example.com"});
|
|
296
|
+
const second = await createUser({email: "second-org-admin@example.com"});
|
|
297
|
+
const org = await Organization.create({name: "Acme", ownerId: operator._id});
|
|
298
|
+
const removable = await Membership.create({
|
|
299
|
+
organizationId: org._id,
|
|
300
|
+
roleName: "org-admin",
|
|
301
|
+
userId: first._id,
|
|
302
|
+
});
|
|
303
|
+
await Membership.create({organizationId: org._id, roleName: "org-admin", userId: second._id});
|
|
304
|
+
const orgAdmins = [first, second] as unknown as AuthUser[];
|
|
305
|
+
// Resolve (and cache) each org-admin's permissions before the change.
|
|
306
|
+
for (const orgAdmin of orgAdmins) {
|
|
307
|
+
assert.deepEqual((await access.getPermissions({user: orgAdmin})).admin, ["access"]);
|
|
308
|
+
}
|
|
309
|
+
const operatorAgent = await loginWithPassword(app, {
|
|
310
|
+
email: "operator@example.com",
|
|
311
|
+
password: PASSWORD,
|
|
312
|
+
});
|
|
313
|
+
return {operatorAgent, org, orgAdmins, removable};
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
it("takes a removed org-admin's permissions away at once", async () => {
|
|
317
|
+
const {operatorAgent, org, orgAdmins, removable} = await setUpOrgAdmins();
|
|
318
|
+
|
|
319
|
+
const removed = await operatorAgent.delete(`/orgs/${org._id}/members/${removable._id}`);
|
|
320
|
+
|
|
321
|
+
assert.equal(removed.status, 204);
|
|
322
|
+
assert.isUndefined((await access.getPermissions({user: orgAdmins[0] as AuthUser})).admin);
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
it("takes every org-admin's permissions away at once when the organization is disabled", async () => {
|
|
326
|
+
const {operatorAgent, org, orgAdmins} = await setUpOrgAdmins();
|
|
327
|
+
|
|
328
|
+
const disabled = await operatorAgent.patch(`/orgs/${org._id}`).send({disabled: true});
|
|
329
|
+
|
|
330
|
+
assert.equal(disabled.status, 200);
|
|
331
|
+
for (const orgAdmin of orgAdmins) {
|
|
332
|
+
assert.isUndefined((await access.getPermissions({user: orgAdmin})).admin);
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
it("takes every org-admin's permissions away at once when the organization is deleted", async () => {
|
|
337
|
+
const {operatorAgent, org, orgAdmins} = await setUpOrgAdmins();
|
|
338
|
+
|
|
339
|
+
const deleted = await operatorAgent.delete(`/orgs/${org._id}`);
|
|
340
|
+
|
|
341
|
+
assert.equal(deleted.status, 204);
|
|
342
|
+
for (const orgAdmin of orgAdmins) {
|
|
343
|
+
assert.isUndefined((await access.getPermissions({user: orgAdmin})).admin);
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
});
|
|
347
|
+
|
|
249
348
|
it("attaches an existing user by userId", async () => {
|
|
250
349
|
const operator = await createUser({email: "operator@example.com", roles: ["operator"]});
|
|
251
350
|
const member = await createUser({email: "member-id@example.com"});
|
package/src/orgs/orgsApp.ts
CHANGED
|
@@ -2,6 +2,11 @@ import type express from "express";
|
|
|
2
2
|
import {type Application, Router} from "express";
|
|
3
3
|
import type mongoose from "mongoose";
|
|
4
4
|
|
|
5
|
+
import type {AccountSecurityApp} from "../accountSecurity/accountSecurityApp";
|
|
6
|
+
import {
|
|
7
|
+
mountOrgSecurityRoutes,
|
|
8
|
+
type OrgRecoveryOptions,
|
|
9
|
+
} from "../accountSecurity/orgSecurityRoutes";
|
|
5
10
|
import {asyncHandler, type OpenApiMiddleware} from "../api";
|
|
6
11
|
import {authenticateMiddleware, type User, type UserModel} from "../auth";
|
|
7
12
|
import {APIError, ConflictError, ForbiddenError, NotFoundError} from "../errors";
|
|
@@ -9,9 +14,11 @@ import {logger} from "../logger";
|
|
|
9
14
|
import {createOpenApiBuilder, type OpenApiSchemaProperty} from "../openApiBuilder";
|
|
10
15
|
import {findOneOrNoneFor} from "../plugins";
|
|
11
16
|
import type {AnyTerrenoAccess} from "../rbac/types";
|
|
17
|
+
import type {TerrenoApp} from "../terrenoApp";
|
|
12
18
|
import type {TerrenoPlugin} from "../terrenoPlugin";
|
|
13
19
|
import type {MembershipDocument} from "../types/membership";
|
|
14
20
|
import type {OrganizationDocument} from "../types/organization";
|
|
21
|
+
import {assertNotLastOrgAdmin} from "./membershipGuards";
|
|
15
22
|
import {
|
|
16
23
|
assertOrganizationSlugAvailable,
|
|
17
24
|
Membership,
|
|
@@ -56,8 +63,15 @@ export interface OrgAuditEvent {
|
|
|
56
63
|
|
|
57
64
|
export interface OrgsAppOptions {
|
|
58
65
|
access: AnyTerrenoAccess;
|
|
66
|
+
/**
|
|
67
|
+
* The app's AccountSecurityApp. When set, org-admins get the member recovery routes at
|
|
68
|
+
* `{basePath}/:orgId/members/:userId/security/*`. TerrenoApp passes the registered one.
|
|
69
|
+
*/
|
|
70
|
+
accountSecurity?: AccountSecurityApp;
|
|
59
71
|
basePath?: string;
|
|
60
72
|
onOrgAudit?: (event: OrgAuditEvent, req: express.Request) => void | Promise<void>;
|
|
73
|
+
/** Hardening for the org-admin recovery routes, such as `{minMembershipDays: 7}`. */
|
|
74
|
+
orgRecovery?: OrgRecoveryOptions;
|
|
61
75
|
/** Nested schema for `Organization.settings`. Same as `registerOrganizationSettings`. */
|
|
62
76
|
settingsSchema?: mongoose.Schema;
|
|
63
77
|
userModel: UserModel;
|
|
@@ -121,33 +135,20 @@ const loadActiveMembership = async (
|
|
|
121
135
|
return membership ?? undefined;
|
|
122
136
|
};
|
|
123
137
|
|
|
124
|
-
|
|
138
|
+
/**
|
|
139
|
+
* Suspend every membership in the organization and clear each member's cached permissions, so an
|
|
140
|
+
* org-admin of a disabled or deleted organization loses its grants on the next request instead of
|
|
141
|
+
* after the permission cache TTL. The members are read after the update so a membership added
|
|
142
|
+
* meanwhile is covered too.
|
|
143
|
+
*/
|
|
144
|
+
const suspendOrganizationMemberships = async (
|
|
145
|
+
access: AnyTerrenoAccess,
|
|
125
146
|
organizationId: OrganizationDocument["_id"]
|
|
126
|
-
): Promise<number> => {
|
|
127
|
-
return Membership.countDocuments({
|
|
128
|
-
organizationId,
|
|
129
|
-
roleName: "org-admin",
|
|
130
|
-
status: "active",
|
|
131
|
-
});
|
|
132
|
-
};
|
|
133
|
-
|
|
134
|
-
const assertNotLastOrgAdmin = async (
|
|
135
|
-
membership: MembershipDocument,
|
|
136
|
-
nextRoleName?: string,
|
|
137
|
-
nextStatus?: string
|
|
138
147
|
): Promise<void> => {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
return;
|
|
144
|
-
}
|
|
145
|
-
if (membership.roleName !== "org-admin" || membership.status !== "active") {
|
|
146
|
-
return;
|
|
147
|
-
}
|
|
148
|
-
const activeAdmins = await countActiveOrgAdmins(membership.organizationId);
|
|
149
|
-
if (activeAdmins <= 1) {
|
|
150
|
-
throw new APIError({status: 400, title: "Cannot remove the last org-admin"});
|
|
148
|
+
await Membership.updateMany({organizationId}, {status: "suspended"});
|
|
149
|
+
const userIds: unknown[] = await Membership.distinct("userId", {organizationId});
|
|
150
|
+
for (const userId of userIds) {
|
|
151
|
+
access.invalidateCache({userId: String(userId)});
|
|
151
152
|
}
|
|
152
153
|
};
|
|
153
154
|
|
|
@@ -170,21 +171,26 @@ const assertCan = async (args: {
|
|
|
170
171
|
|
|
171
172
|
export class OrgsApp implements TerrenoPlugin {
|
|
172
173
|
private readonly access: AnyTerrenoAccess;
|
|
174
|
+
private readonly accountSecurity?: AccountSecurityApp;
|
|
173
175
|
private readonly basePath: string;
|
|
174
176
|
private readonly onOrgAudit?: OrgsAppOptions["onOrgAudit"];
|
|
177
|
+
private readonly orgRecovery?: OrgRecoveryOptions;
|
|
175
178
|
private readonly userModel: UserModel;
|
|
176
179
|
|
|
177
180
|
constructor(options: OrgsAppOptions) {
|
|
178
181
|
this.access = options.access;
|
|
182
|
+
this.accountSecurity = options.accountSecurity;
|
|
179
183
|
this.basePath = options.basePath ?? "/orgs";
|
|
180
184
|
this.onOrgAudit = options.onOrgAudit;
|
|
185
|
+
this.orgRecovery = options.orgRecovery;
|
|
181
186
|
this.userModel = options.userModel;
|
|
182
187
|
if (options.settingsSchema) {
|
|
183
188
|
registerOrganizationSettings(options.settingsSchema);
|
|
184
189
|
}
|
|
185
190
|
}
|
|
186
191
|
|
|
187
|
-
register(app: Application, openApi?: unknown): void {
|
|
192
|
+
register(app: Application, openApi?: unknown, terrenoApp?: TerrenoApp): void {
|
|
193
|
+
this.assertAccountSecurityRegistered(terrenoApp);
|
|
188
194
|
const router = Router();
|
|
189
195
|
const openApiMiddleware = openApi as OpenApiMiddleware | undefined;
|
|
190
196
|
const docs = (
|
|
@@ -338,7 +344,7 @@ export class OrgsApp implements TerrenoPlugin {
|
|
|
338
344
|
}
|
|
339
345
|
await organization.save();
|
|
340
346
|
if (wantsDisable) {
|
|
341
|
-
await
|
|
347
|
+
await suspendOrganizationMemberships(this.access, organization._id);
|
|
342
348
|
}
|
|
343
349
|
|
|
344
350
|
await emitOrgAudit({
|
|
@@ -365,7 +371,7 @@ export class OrgsApp implements TerrenoPlugin {
|
|
|
365
371
|
const organization = await loadOrganization(pathParam(req.params.id, "id is required"));
|
|
366
372
|
organization.deleted = true;
|
|
367
373
|
await organization.save();
|
|
368
|
-
await
|
|
374
|
+
await suspendOrganizationMemberships(this.access, organization._id);
|
|
369
375
|
await emitOrgAudit({
|
|
370
376
|
event: {
|
|
371
377
|
actorId: user.id,
|
|
@@ -446,6 +452,8 @@ export class OrgsApp implements TerrenoPlugin {
|
|
|
446
452
|
roleName,
|
|
447
453
|
userId: userIdOf(target),
|
|
448
454
|
});
|
|
455
|
+
// Membership grants (an org-admin's admin:access) apply at once, not after the cache TTL.
|
|
456
|
+
this.access.invalidateCache({userId: String(created.userId)});
|
|
449
457
|
await emitOrgAudit({
|
|
450
458
|
event: {
|
|
451
459
|
actorId: user.id,
|
|
@@ -504,6 +512,7 @@ export class OrgsApp implements TerrenoPlugin {
|
|
|
504
512
|
member.status = req.body.status === "suspended" ? "suspended" : "active";
|
|
505
513
|
}
|
|
506
514
|
await member.save();
|
|
515
|
+
this.access.invalidateCache({userId: String(member.userId)});
|
|
507
516
|
await emitOrgAudit({
|
|
508
517
|
event: {
|
|
509
518
|
actorId: user.id,
|
|
@@ -544,6 +553,7 @@ export class OrgsApp implements TerrenoPlugin {
|
|
|
544
553
|
}
|
|
545
554
|
await assertNotLastOrgAdmin(member, "member", "suspended");
|
|
546
555
|
await member.deleteOne();
|
|
556
|
+
this.access.invalidateCache({userId: String(member.userId)});
|
|
547
557
|
await emitOrgAudit({
|
|
548
558
|
event: {
|
|
549
559
|
actorId: user.id,
|
|
@@ -558,6 +568,37 @@ export class OrgsApp implements TerrenoPlugin {
|
|
|
558
568
|
})
|
|
559
569
|
);
|
|
560
570
|
|
|
571
|
+
if (this.accountSecurity) {
|
|
572
|
+
mountOrgSecurityRoutes({
|
|
573
|
+
access: this.access,
|
|
574
|
+
accountSecurity: this.accountSecurity,
|
|
575
|
+
orgRecovery: this.orgRecovery,
|
|
576
|
+
router,
|
|
577
|
+
userModel: this.userModel,
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
|
|
561
581
|
app.use(this.basePath, router);
|
|
562
582
|
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* The org recovery routes reuse AccountSecurityApp's pipeline, which only registration wires
|
|
586
|
+
* up: the AuditApp check, access control for the D9 reach check, and the user model. Refuse an
|
|
587
|
+
* instance that is neither registered nor about to be on the same TerrenoApp.
|
|
588
|
+
*/
|
|
589
|
+
private assertAccountSecurityRegistered = (terrenoApp?: TerrenoApp): void => {
|
|
590
|
+
const accountSecurity = this.accountSecurity;
|
|
591
|
+
if (!accountSecurity || accountSecurity.isRegistered()) {
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
if (terrenoApp?.getRegistrations().includes(accountSecurity)) {
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
throw new APIError({
|
|
598
|
+
detail:
|
|
599
|
+
"Register the AccountSecurityApp you pass to OrgsApp (app.register(accountSecurity)) so its audit check, access control, and user model apply to the org routes.",
|
|
600
|
+
status: 500,
|
|
601
|
+
title: "OrgsApp accountSecurity is not registered",
|
|
602
|
+
});
|
|
603
|
+
};
|
|
563
604
|
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
import type {Request} from "express";
|
|
3
|
+
import {classifyRateLimitPolicy} from "./policies";
|
|
4
|
+
|
|
5
|
+
const request = (path: string, method = "POST"): Request => ({method, path}) as Request;
|
|
6
|
+
|
|
7
|
+
describe("classifyRateLimitPolicy for Better Auth feature routes", () => {
|
|
8
|
+
it("puts two-factor verification in the auth bucket", () => {
|
|
9
|
+
expect(classifyRateLimitPolicy(request("/api/auth/two-factor/verify-totp"))).toBe("auth");
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it("puts every auth feature route in the auth bucket", () => {
|
|
13
|
+
const paths = [
|
|
14
|
+
"/api/auth/two-factor/enable",
|
|
15
|
+
"/api/auth/two-factor/verify-backup-code",
|
|
16
|
+
"/api/auth/passkey/generate-authenticate-options",
|
|
17
|
+
"/api/auth/passkey/verify-authentication",
|
|
18
|
+
"/api/auth/link-social",
|
|
19
|
+
"/api/auth/unlink-account",
|
|
20
|
+
"/api/auth/multi-session/set-active",
|
|
21
|
+
"/api/auth/one-time-token/verify",
|
|
22
|
+
"/api/auth/oauth-handoff/start",
|
|
23
|
+
"/api/auth/oauth-handoff/link-intent",
|
|
24
|
+
"/api/auth/oauth-handoff/link-start",
|
|
25
|
+
"/api/auth/oauth-proxy-callback",
|
|
26
|
+
"/api/auth/expo-authorization-proxy",
|
|
27
|
+
"/api/auth/terreno/set-password",
|
|
28
|
+
];
|
|
29
|
+
for (const path of paths) {
|
|
30
|
+
expect({path, policy: classifyRateLimitPolicy(request(path))}).toEqual({
|
|
31
|
+
path,
|
|
32
|
+
policy: "auth",
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("follows a custom Better Auth base path", () => {
|
|
38
|
+
expect(classifyRateLimitPolicy(request("/auth/v2/two-factor/verify-totp"), "/auth/v2")).toBe(
|
|
39
|
+
"auth"
|
|
40
|
+
);
|
|
41
|
+
expect(classifyRateLimitPolicy(request("/api/auth/two-factor/verify-totp"), "/auth/v2")).toBe(
|
|
42
|
+
"api"
|
|
43
|
+
);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("leaves the public methods discovery in the api bucket", () => {
|
|
47
|
+
expect(classifyRateLimitPolicy(request("/api/auth/terreno/methods", "GET"))).toBe("api");
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("does not match a route that only shares a prefix", () => {
|
|
51
|
+
expect(classifyRateLimitPolicy(request("/api/auth/passkeys-report", "GET"))).toBe("api");
|
|
52
|
+
});
|
|
53
|
+
});
|
|
@@ -125,6 +125,14 @@ const betterAuthAuthPrefixes = (basePath: string): string[] => {
|
|
|
125
125
|
`${base}/callback`,
|
|
126
126
|
`${base}/oauth-handoff`,
|
|
127
127
|
`${base}/one-time-token`,
|
|
128
|
+
`${base}/two-factor`,
|
|
129
|
+
`${base}/passkey`,
|
|
130
|
+
`${base}/link-social`,
|
|
131
|
+
`${base}/unlink-account`,
|
|
132
|
+
`${base}/multi-session`,
|
|
133
|
+
`${base}/oauth-proxy-callback`,
|
|
134
|
+
`${base}/expo-authorization-proxy`,
|
|
135
|
+
`${base}/terreno/set-password`,
|
|
128
136
|
];
|
|
129
137
|
};
|
|
130
138
|
|
package/src/rbac/access.ts
CHANGED
|
@@ -62,6 +62,8 @@ export const createAccess = <S extends Statements>(options: AccessOptions<S>): T
|
|
|
62
62
|
defaultRoles: extraRoles,
|
|
63
63
|
getActorPermissions: (user) => resolver.resolvePermissionsForUser(user),
|
|
64
64
|
getPreviewPermissions: (user) => resolver.resolvePermissionsForUserUncached(user),
|
|
65
|
+
getTargetPermissions: (user) =>
|
|
66
|
+
resolver.resolvePermissionsForUser(user, {requireComplete: true}),
|
|
65
67
|
invalidateCache: resolver.invalidateCache,
|
|
66
68
|
persistAudit,
|
|
67
69
|
statements: mergedStatements,
|
|
@@ -202,7 +204,8 @@ export const createAccess = <S extends Statements>(options: AccessOptions<S>): T
|
|
|
202
204
|
ac: resolver.ac,
|
|
203
205
|
can,
|
|
204
206
|
fieldMask,
|
|
205
|
-
getPermissions: ({user}) =>
|
|
207
|
+
getPermissions: ({requireComplete, user}) =>
|
|
208
|
+
resolver.resolvePermissionsForUser(user, {requireComplete}),
|
|
206
209
|
invalidateCache: resolver.invalidateCache,
|
|
207
210
|
middleware: createRequireAccess({can}),
|
|
208
211
|
permission: createIsPermitted({can}),
|
package/src/rbac/resolve.test.ts
CHANGED
|
@@ -515,6 +515,71 @@ describe("createPermissionResolver", () => {
|
|
|
515
515
|
).toEqual(["read", "update"]);
|
|
516
516
|
});
|
|
517
517
|
|
|
518
|
+
it("throws 503 with requireComplete when a failed source's grants were dropped", async () => {
|
|
519
|
+
const RbacRole = await seedWriter();
|
|
520
|
+
let isDown = false;
|
|
521
|
+
const source: PermissionSource = {
|
|
522
|
+
failClosedWhenDenyUnknown: false,
|
|
523
|
+
getGrants: async () => {
|
|
524
|
+
if (isDown) {
|
|
525
|
+
throw new Error("idp down");
|
|
526
|
+
}
|
|
527
|
+
return {permissions: {todo: ["delete"]}};
|
|
528
|
+
},
|
|
529
|
+
name: "idp-grants",
|
|
530
|
+
staleOnFailure: "deny",
|
|
531
|
+
ttlMs: 0,
|
|
532
|
+
};
|
|
533
|
+
const resolver = createPermissionResolver({
|
|
534
|
+
cacheTtlMs: 0,
|
|
535
|
+
rbacRoleModel: RbacRole,
|
|
536
|
+
sources: [source],
|
|
537
|
+
statements: appStatements,
|
|
538
|
+
});
|
|
539
|
+
const user = createTestUser({roles: ["writer"]});
|
|
540
|
+
expect(
|
|
541
|
+
(await resolver.resolvePermissionsForUser(user, {requireComplete: true})).todo
|
|
542
|
+
).toContain("delete");
|
|
543
|
+
|
|
544
|
+
isDown = true;
|
|
545
|
+
|
|
546
|
+
// Without requireComplete the source's grants drop out; with it the set is refused.
|
|
547
|
+
expect((await resolver.resolvePermissionsForUser(user)).todo).toEqual(["read", "update"]);
|
|
548
|
+
await expect(
|
|
549
|
+
resolver.resolvePermissionsForUser(user, {requireComplete: true})
|
|
550
|
+
).rejects.toMatchObject({status: 503, title: "Permission source unavailable"});
|
|
551
|
+
});
|
|
552
|
+
|
|
553
|
+
it("accepts stale grants with requireComplete when the source serves them", async () => {
|
|
554
|
+
const RbacRole = await seedWriter();
|
|
555
|
+
let isDown = false;
|
|
556
|
+
const source: PermissionSource = {
|
|
557
|
+
getGrants: async () => {
|
|
558
|
+
if (isDown) {
|
|
559
|
+
throw new Error("idp down");
|
|
560
|
+
}
|
|
561
|
+
return {permissions: {todo: ["delete"]}};
|
|
562
|
+
},
|
|
563
|
+
name: "idp-stale",
|
|
564
|
+
staleOnFailure: "use-stale",
|
|
565
|
+
ttlMs: 0,
|
|
566
|
+
};
|
|
567
|
+
const resolver = createPermissionResolver({
|
|
568
|
+
cacheTtlMs: 0,
|
|
569
|
+
rbacRoleModel: RbacRole,
|
|
570
|
+
sources: [source],
|
|
571
|
+
statements: appStatements,
|
|
572
|
+
});
|
|
573
|
+
const user = createTestUser({roles: ["writer"]});
|
|
574
|
+
await resolver.resolvePermissionsForUser(user);
|
|
575
|
+
|
|
576
|
+
isDown = true;
|
|
577
|
+
|
|
578
|
+
expect(
|
|
579
|
+
(await resolver.resolvePermissionsForUser(user, {requireComplete: true})).todo
|
|
580
|
+
).toContain("delete");
|
|
581
|
+
});
|
|
582
|
+
|
|
518
583
|
it("keeps the built-in membership source open on a cold failure", () => {
|
|
519
584
|
expect(membershipOrgAdminPermissionSource().failClosedWhenDenyUnknown).toBe(false);
|
|
520
585
|
});
|
package/src/rbac/resolve.ts
CHANGED
|
@@ -23,6 +23,17 @@ interface SourceCacheEntry {
|
|
|
23
23
|
interface SourceFetchResult {
|
|
24
24
|
grants: PermissionSourceGrants | null;
|
|
25
25
|
failed: boolean;
|
|
26
|
+
/** The source failed and its grants were dropped (not served from its stale cache). */
|
|
27
|
+
incomplete: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Options for {@link createPermissionResolver}'s `resolvePermissionsForUser`. */
|
|
31
|
+
export interface ResolvePermissionsOptions {
|
|
32
|
+
/**
|
|
33
|
+
* Throw 503 instead of returning a set missing a failed source's grants. Use it where fewer
|
|
34
|
+
* permissions would loosen a check, such as comparing a target's permissions to an actor's.
|
|
35
|
+
*/
|
|
36
|
+
requireComplete?: boolean;
|
|
26
37
|
}
|
|
27
38
|
|
|
28
39
|
const DEFAULT_CACHE_TTL_MS = 30_000;
|
|
@@ -210,18 +221,18 @@ export const createPermissionResolver = <S extends Statements>(args: {
|
|
|
210
221
|
source: PermissionSource,
|
|
211
222
|
cached: SourceCacheEntry | undefined,
|
|
212
223
|
now: number
|
|
213
|
-
):
|
|
224
|
+
): SourceFetchResult => {
|
|
214
225
|
const stale = grantsFromStaleCache(source, cached, now);
|
|
215
226
|
if (stale) {
|
|
216
|
-
return stale;
|
|
227
|
+
return {failed: true, grants: stale, incomplete: false};
|
|
217
228
|
}
|
|
218
229
|
if (cached) {
|
|
219
|
-
return denyOnlyFromCache(cached);
|
|
230
|
+
return {failed: true, grants: denyOnlyFromCache(cached), incomplete: true};
|
|
220
231
|
}
|
|
221
232
|
const userPosture = denyPosture.get(user.id);
|
|
222
233
|
if (userPosture?.has(source.name)) {
|
|
223
234
|
const deny = userPosture.get(source.name);
|
|
224
|
-
return deny ? {deny} : null;
|
|
235
|
+
return {failed: true, grants: deny ? {deny} : null, incomplete: true};
|
|
225
236
|
}
|
|
226
237
|
if (failsClosedWhenDenyUnknown(source)) {
|
|
227
238
|
throw new APIError({
|
|
@@ -230,7 +241,7 @@ export const createPermissionResolver = <S extends Statements>(args: {
|
|
|
230
241
|
title: "Permission source unavailable",
|
|
231
242
|
});
|
|
232
243
|
}
|
|
233
|
-
return null;
|
|
244
|
+
return {failed: true, grants: null, incomplete: true};
|
|
234
245
|
};
|
|
235
246
|
|
|
236
247
|
const fetchSourceGrants = async (
|
|
@@ -245,14 +256,14 @@ export const createPermissionResolver = <S extends Statements>(args: {
|
|
|
245
256
|
try {
|
|
246
257
|
const grants = await source.getGrants({user});
|
|
247
258
|
recordDenyPosture(user.id, source, grants);
|
|
248
|
-
return {failed: false, grants};
|
|
259
|
+
return {failed: false, grants, incomplete: false};
|
|
249
260
|
} catch (error) {
|
|
250
261
|
logger.warn("Permission source refresh failed during uncached resolution", {
|
|
251
262
|
error: error instanceof Error ? error.message : String(error),
|
|
252
263
|
policy: source.staleOnFailure ?? "deny",
|
|
253
264
|
source: source.name,
|
|
254
265
|
});
|
|
255
|
-
return
|
|
266
|
+
return grantsAfterSourceFailure(user, source, cached, now);
|
|
256
267
|
}
|
|
257
268
|
}
|
|
258
269
|
|
|
@@ -264,32 +275,31 @@ export const createPermissionResolver = <S extends Statements>(args: {
|
|
|
264
275
|
const cachedAfterTouch = userSources.get(source.name);
|
|
265
276
|
|
|
266
277
|
if (cachedAfterTouch && now - cachedAfterTouch.fetchedAt < ttlMs) {
|
|
267
|
-
return {failed: false, grants: cachedAfterTouch.grants};
|
|
278
|
+
return {failed: false, grants: cachedAfterTouch.grants, incomplete: false};
|
|
268
279
|
}
|
|
269
280
|
|
|
270
281
|
try {
|
|
271
282
|
const grants = await source.getGrants({user});
|
|
272
283
|
userSources.set(source.name, {fetchedAt: now, grants});
|
|
273
284
|
recordDenyPosture(user.id, source, grants);
|
|
274
|
-
return {failed: false, grants};
|
|
285
|
+
return {failed: false, grants, incomplete: false};
|
|
275
286
|
} catch (error) {
|
|
276
287
|
logger.warn("Permission source refresh failed", {
|
|
277
288
|
error: error instanceof Error ? error.message : String(error),
|
|
278
289
|
policy: source.staleOnFailure ?? "deny",
|
|
279
290
|
source: source.name,
|
|
280
291
|
});
|
|
281
|
-
return
|
|
282
|
-
failed: true,
|
|
283
|
-
grants: grantsAfterSourceFailure(user, source, cachedAfterTouch, now),
|
|
284
|
-
};
|
|
292
|
+
return grantsAfterSourceFailure(user, source, cachedAfterTouch, now);
|
|
285
293
|
}
|
|
286
294
|
};
|
|
287
295
|
|
|
288
296
|
const resolveEffectivePermissions = async (
|
|
289
297
|
user: User,
|
|
290
|
-
shouldCache: boolean
|
|
298
|
+
shouldCache: boolean,
|
|
299
|
+
requireComplete = false
|
|
291
300
|
): Promise<PermissionSet> => {
|
|
292
301
|
const cacheKey = permissionCacheKey(user);
|
|
302
|
+
// A cached set is always complete: a set computed during a source outage is never cached.
|
|
293
303
|
if (shouldCache) {
|
|
294
304
|
const cached = permissionCache.get(cacheKey);
|
|
295
305
|
if (cached && cached.expiresAt > DateTime.now().toMillis()) {
|
|
@@ -304,8 +314,15 @@ export const createPermissionResolver = <S extends Statements>(args: {
|
|
|
304
314
|
let anySourceFailed = false;
|
|
305
315
|
|
|
306
316
|
for (const source of sources) {
|
|
307
|
-
const {failed, grants} = await fetchSourceGrants(user, source, shouldCache);
|
|
317
|
+
const {failed, grants, incomplete} = await fetchSourceGrants(user, source, shouldCache);
|
|
308
318
|
anySourceFailed = anySourceFailed || failed;
|
|
319
|
+
if (incomplete && requireComplete) {
|
|
320
|
+
throw new APIError({
|
|
321
|
+
detail: `Permission source ${source.name} failed, so its grants are unknown`,
|
|
322
|
+
status: 503,
|
|
323
|
+
title: "Permission source unavailable",
|
|
324
|
+
});
|
|
325
|
+
}
|
|
309
326
|
sourceResults.set(source.name, grants);
|
|
310
327
|
if (!grants) {
|
|
311
328
|
continue;
|
|
@@ -348,8 +365,11 @@ export const createPermissionResolver = <S extends Statements>(args: {
|
|
|
348
365
|
return permissions;
|
|
349
366
|
};
|
|
350
367
|
|
|
351
|
-
const resolvePermissionsForUser = async (
|
|
352
|
-
|
|
368
|
+
const resolvePermissionsForUser = async (
|
|
369
|
+
user: User,
|
|
370
|
+
options: ResolvePermissionsOptions = {}
|
|
371
|
+
): Promise<PermissionSet> => {
|
|
372
|
+
return resolveEffectivePermissions(user, true, options.requireComplete === true);
|
|
353
373
|
};
|
|
354
374
|
|
|
355
375
|
const resolvePermissionsForUserUncached = async (user: User): Promise<PermissionSet> => {
|