feat: add organization.passwordReset PBAC permission (#27377)
* feat: add organization.passwordReset PBAC permission Allow org admins/owners to reset passwords for members of their organization via a new PBAC permission. Previously this was only available to system-level admins. - Add PasswordReset to CustomAction enum and PERMISSION_REGISTRY - Create migration to grant permission to admin_role (owner has wildcard) - Add org-scoped tRPC endpoint using createOrgPbacProcedure - Handler validates org membership, prevents self-targeting, and blocks resetting owner passwords - Wire permission through MemberPermissions, getOrgMembersPageData, and the org members table UI dropdown Co-Authored-By: Claude Opus 4.5 <[email protected]> * fix: use targeted select in org password reset to avoid over-fetching Replace findById with findForPasswordReset repository method that only selects email, name, and locale instead of the full userSelect which includes sensitive fields like twoFactorSecret and backupCodes. Co-Authored-By: Claude Opus 4.5 <[email protected]> * test: add unit tests for sendPasswordReset handler Co-Authored-By: Claude Opus 4.5 <[email protected]> --------- Co-authored-by: Claude Opus 4.5 <[email protected]>
This commit is contained in:
1 parent
1f8f134854
commit
08a2b0bfb5
12 files changed
+410
-132
No files matched your search
@@ -36,6 +36,7 @@ export enum CustomAction {
|
||||
ReadRecordings = "readRecordings",
|
||||
Impersonate = "impersonate",
|
||||
EditUsers = "editUsers",
|
||||
PasswordReset = "passwordReset",
|
||||
ReadTeamAuditLogs = "readTeamAuditLogs",
|
||||
ReadOrgAuditLogs = "readOrgAuditLogs",
|
||||
}
|
||||
@@ -436,6 +437,14 @@ export const PERMISSION_REGISTRY: PermissionRegistry = {
|
||||
descriptionI18nKey: "pbac_desc_impersonate_organization_members",
|
||||
scope: [Scope.Organization],
|
||||
},
|
||||
[CustomAction.PasswordReset]: {
|
||||
description: "Reset passwords for organization members",
|
||||
category: "org",
|
||||
i18nKey: "pbac_action_password_reset",
|
||||
descriptionI18nKey: "pbac_desc_reset_password_organization_members",
|
||||
scope: [Scope.Organization],
|
||||
dependsOn: ["organization.listMembers"],
|
||||
},
|
||||
[CrudAction.Update]: {
|
||||
description: "Edit organization settings",
|
||||
category: "org",
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { Resource, CustomAction } from "../domain/types/permission-registry";
|
||||
import { CustomAction, Resource } from "../domain/types/permission-registry";
|
||||
import { getSpecificPermissions } from "./resource-permissions";
|
||||
|
||||
export interface MemberPermissions {
|
||||
@@ -9,10 +8,11 @@ export interface MemberPermissions {
|
||||
canChangeMemberRole: boolean;
|
||||
canRemove: boolean;
|
||||
canImpersonate: boolean;
|
||||
canResetPassword?: boolean;
|
||||
canEditAttributesForUser?: boolean;
|
||||
canViewAttributes?: boolean;
|
||||
}
|
||||
|
||||
|
||||
interface TeamWithMembership {
|
||||
id: number;
|
||||
isPrivate: boolean;
|
||||
|
||||
@@ -1339,6 +1339,17 @@ export class UserRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async findForPasswordReset({ id }: { id: number }) {
|
||||
return this.prismaClient.user.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
email: true,
|
||||
name: true,
|
||||
locale: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a user by ID returning only their username
|
||||
* @param userId - The user ID
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
-- Add passwordReset permission to admin role for organizations
|
||||
-- Owner role already has wildcard permissions (*.*) so no migration needed for it
|
||||
INSERT INTO "RolePermission" (id, "roleId", resource, action, "createdAt")
|
||||
SELECT
|
||||
gen_random_uuid(), 'admin_role', resource, action, NOW()
|
||||
FROM (
|
||||
VALUES
|
||||
('organization', 'passwordReset')
|
||||
) AS permissions(resource, action)
|
||||
ON CONFLICT ("roleId", resource, action) DO NOTHING;
|
||||
@@ -1,15 +1,16 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
import { createPhoneCallSchema } from "@calcom/features/calAIPhone/zod-utils";
|
||||
import { ZVerifyCodeInputSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import type { NextApiRequest } from "next";
|
||||
import authedProcedure, {
|
||||
authedAdminProcedure,
|
||||
authedOrgAdminProcedure,
|
||||
} from "../../../procedures/authedProcedure";
|
||||
import { createOrgPbacProcedure } from "../../../procedures/pbacProcedures";
|
||||
import { router } from "../../../trpc";
|
||||
import { eventOwnerProcedure } from "../eventTypes/util";
|
||||
import { ZAddMembersToEventTypes } from "./addMembersToEventTypes.schema";
|
||||
import { ZAddMembersToTeams } from "./addMembersToTeams.schema";
|
||||
import { ZAddToWatchlistInputSchema } from "./addToWatchlist.schema";
|
||||
import { ZAdminDeleteInput } from "./adminDelete.schema";
|
||||
import { ZAdminGet } from "./adminGet.schema";
|
||||
import { ZAdminUpdate } from "./adminUpdate.schema";
|
||||
@@ -22,18 +23,18 @@ import { ZCreateWatchlistEntryInputSchema } from "./createWatchlistEntry.schema"
|
||||
import { ZCreateWithPaymentIntentInputSchema } from "./createWithPaymentIntent.schema";
|
||||
import { ZDeleteTeamInputSchema } from "./deleteTeam.schema";
|
||||
import { ZDeleteWatchlistEntryInputSchema } from "./deleteWatchlistEntry.schema";
|
||||
import { ZDismissBookingReportInputSchema } from "./dismissBookingReport.schema";
|
||||
import { ZGetMembersInput } from "./getMembers.schema";
|
||||
import { ZGetOtherTeamInputSchema } from "./getOtherTeam.handler";
|
||||
import { ZGetUserInput } from "./getUser.schema";
|
||||
import { ZGetWatchlistEntryDetailsInputSchema } from "./getWatchlistEntryDetails.schema";
|
||||
import { ZIntentToCreateOrgInputSchema } from "./intentToCreateOrg.schema";
|
||||
import { ZAddToWatchlistInputSchema } from "./addToWatchlist.schema";
|
||||
import { ZDismissBookingReportInputSchema } from "./dismissBookingReport.schema";
|
||||
import { ZListBookingReportsInputSchema } from "./listBookingReports.schema";
|
||||
import { ZListMembersInputSchema } from "./listMembers.schema";
|
||||
import { ZListOtherTeamMembersSchema } from "./listOtherTeamMembers.handler";
|
||||
import { ZListWatchlistEntriesInputSchema } from "./listWatchlistEntries.schema";
|
||||
import { ZRemoveHostsFromEventTypes } from "./removeHostsFromEventTypes.schema";
|
||||
import { ZOrgPasswordResetSchema } from "./sendPasswordReset.schema";
|
||||
import { ZSetPasswordSchema } from "./setPassword.schema";
|
||||
import { ZUpdateInputSchema } from "./update.schema";
|
||||
import { ZUpdateUserInputSchema } from "./updateUser.schema";
|
||||
@@ -86,6 +87,12 @@ export const viewerOrganizationsRouter = router({
|
||||
const { default: handler } = await import("./setPassword.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
sendPasswordReset: createOrgPbacProcedure("organization.passwordReset")
|
||||
.input(ZOrgPasswordResetSchema)
|
||||
.mutation(async (opts) => {
|
||||
const { default: handler } = await import("./sendPasswordReset.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
getMembers: authedProcedure.input(ZGetMembersInput).query(async (opts) => {
|
||||
const { default: handler } = await import("./getMembers.handler");
|
||||
return handler(opts);
|
||||
@@ -195,18 +202,14 @@ export const viewerOrganizationsRouter = router({
|
||||
const { getWatchlistEntryDetailsHandler: handler } = await import("./getWatchlistEntryDetails.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
listBookingReports: authedOrgAdminProcedure
|
||||
.input(ZListBookingReportsInputSchema)
|
||||
.query(async (opts) => {
|
||||
const { default: handler } = await import("./listBookingReports.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
addToWatchlist: authedOrgAdminProcedure
|
||||
.input(ZAddToWatchlistInputSchema)
|
||||
.mutation(async (opts) => {
|
||||
const { addToWatchlistHandler: handler } = await import("./addToWatchlist.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
listBookingReports: authedOrgAdminProcedure.input(ZListBookingReportsInputSchema).query(async (opts) => {
|
||||
const { default: handler } = await import("./listBookingReports.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
addToWatchlist: authedOrgAdminProcedure.input(ZAddToWatchlistInputSchema).mutation(async (opts) => {
|
||||
const { addToWatchlistHandler: handler } = await import("./addToWatchlist.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
dismissBookingReport: authedOrgAdminProcedure
|
||||
.input(ZDismissBookingReportInputSchema)
|
||||
.mutation(async (opts) => {
|
||||
@@ -217,5 +220,4 @@ export const viewerOrganizationsRouter = router({
|
||||
const { default: handler } = await import("./pendingReportsCount.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import sendPasswordResetHandler from "./sendPasswordReset.handler";
|
||||
|
||||
const { mockFindUniqueByUserIdAndTeamId, MockMembershipRepository } = vi.hoisted(() => {
|
||||
const mockFindUniqueByUserIdAndTeamId = vi.fn();
|
||||
|
||||
class MockMembershipRepository {
|
||||
findUniqueByUserIdAndTeamId = mockFindUniqueByUserIdAndTeamId;
|
||||
}
|
||||
|
||||
return { mockFindUniqueByUserIdAndTeamId, MockMembershipRepository };
|
||||
});
|
||||
|
||||
const { mockFindForPasswordReset, MockUserRepository } = vi.hoisted(() => {
|
||||
const mockFindForPasswordReset = vi.fn();
|
||||
|
||||
class MockUserRepository {
|
||||
findForPasswordReset = mockFindForPasswordReset;
|
||||
}
|
||||
|
||||
return { mockFindForPasswordReset, MockUserRepository };
|
||||
});
|
||||
|
||||
const { mockPasswordResetRequest } = vi.hoisted(() => {
|
||||
const mockPasswordResetRequest = vi.fn();
|
||||
return { mockPasswordResetRequest };
|
||||
});
|
||||
|
||||
vi.mock("@calcom/features/membership/repositories/MembershipRepository", () => ({
|
||||
MembershipRepository: MockMembershipRepository,
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/users/repositories/UserRepository", () => ({
|
||||
UserRepository: MockUserRepository,
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/auth/lib/passwordResetRequest", () => ({
|
||||
passwordResetRequest: mockPasswordResetRequest,
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
prisma: {},
|
||||
}));
|
||||
|
||||
describe("sendPasswordResetHandler", () => {
|
||||
const mockUser: NonNullable<TrpcSessionUser> = {
|
||||
id: 1,
|
||||
name: "Admin User",
|
||||
email: "[email protected]",
|
||||
} as NonNullable<TrpcSessionUser>;
|
||||
|
||||
const organizationId = 100;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("self-reset prevention", () => {
|
||||
it("should throw BAD_REQUEST when user tries to reset their own password", async () => {
|
||||
await expect(
|
||||
sendPasswordResetHandler({
|
||||
ctx: { user: mockUser, organizationId },
|
||||
input: { userId: mockUser.id },
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "BAD_REQUEST",
|
||||
message: "You cannot reset your own password through this endpoint.",
|
||||
});
|
||||
|
||||
expect(mockFindUniqueByUserIdAndTeamId).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("membership validation", () => {
|
||||
it("should throw NOT_FOUND when target user is not a member of the organization", async () => {
|
||||
mockFindUniqueByUserIdAndTeamId.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
sendPasswordResetHandler({
|
||||
ctx: { user: mockUser, organizationId },
|
||||
input: { userId: 2 },
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "NOT_FOUND",
|
||||
message: "User is not a member of this organization.",
|
||||
});
|
||||
|
||||
expect(mockFindUniqueByUserIdAndTeamId).toHaveBeenCalledWith({
|
||||
userId: 2,
|
||||
teamId: organizationId,
|
||||
});
|
||||
expect(mockFindForPasswordReset).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should throw FORBIDDEN when target user is an organization OWNER", async () => {
|
||||
mockFindUniqueByUserIdAndTeamId.mockResolvedValue({
|
||||
userId: 2,
|
||||
teamId: organizationId,
|
||||
role: MembershipRole.OWNER,
|
||||
});
|
||||
|
||||
await expect(
|
||||
sendPasswordResetHandler({
|
||||
ctx: { user: mockUser, organizationId },
|
||||
input: { userId: 2 },
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "FORBIDDEN",
|
||||
message: "Cannot reset password for an organization owner.",
|
||||
});
|
||||
|
||||
expect(mockFindForPasswordReset).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("user validation", () => {
|
||||
it("should throw NOT_FOUND when user does not exist", async () => {
|
||||
mockFindUniqueByUserIdAndTeamId.mockResolvedValue({
|
||||
userId: 2,
|
||||
teamId: organizationId,
|
||||
role: MembershipRole.MEMBER,
|
||||
});
|
||||
mockFindForPasswordReset.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
sendPasswordResetHandler({
|
||||
ctx: { user: mockUser, organizationId },
|
||||
input: { userId: 2 },
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "NOT_FOUND",
|
||||
message: "User not found.",
|
||||
});
|
||||
|
||||
expect(mockFindForPasswordReset).toHaveBeenCalledWith({ id: 2 });
|
||||
expect(mockPasswordResetRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("successful password reset", () => {
|
||||
it("should send password reset for a MEMBER", async () => {
|
||||
const targetUser = { id: 2, email: "[email protected]", name: "Member User" };
|
||||
|
||||
mockFindUniqueByUserIdAndTeamId.mockResolvedValue({
|
||||
userId: 2,
|
||||
teamId: organizationId,
|
||||
role: MembershipRole.MEMBER,
|
||||
});
|
||||
mockFindForPasswordReset.mockResolvedValue(targetUser);
|
||||
mockPasswordResetRequest.mockResolvedValue(undefined);
|
||||
|
||||
const result = await sendPasswordResetHandler({
|
||||
ctx: { user: mockUser, organizationId },
|
||||
input: { userId: 2 },
|
||||
});
|
||||
|
||||
expect(result).toEqual({ success: true });
|
||||
expect(mockPasswordResetRequest).toHaveBeenCalledWith(targetUser);
|
||||
});
|
||||
|
||||
it("should send password reset for an ADMIN", async () => {
|
||||
const targetUser = { id: 3, email: "[email protected]", name: "Admin User 2" };
|
||||
|
||||
mockFindUniqueByUserIdAndTeamId.mockResolvedValue({
|
||||
userId: 3,
|
||||
teamId: organizationId,
|
||||
role: MembershipRole.ADMIN,
|
||||
});
|
||||
mockFindForPasswordReset.mockResolvedValue(targetUser);
|
||||
mockPasswordResetRequest.mockResolvedValue(undefined);
|
||||
|
||||
const result = await sendPasswordResetHandler({
|
||||
ctx: { user: mockUser, organizationId },
|
||||
input: { userId: 3 },
|
||||
});
|
||||
|
||||
expect(result).toEqual({ success: true });
|
||||
expect(mockPasswordResetRequest).toHaveBeenCalledWith(targetUser);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { passwordResetRequest } from "@calcom/features/auth/lib/passwordResetRequest";
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TOrgPasswordResetSchema } from "./sendPasswordReset.schema";
|
||||
|
||||
type SendPasswordResetOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
organizationId: number;
|
||||
};
|
||||
input: TOrgPasswordResetSchema;
|
||||
};
|
||||
|
||||
const sendPasswordResetHandler = async ({ ctx, input }: SendPasswordResetOptions) => {
|
||||
const { organizationId } = ctx;
|
||||
const { userId } = input;
|
||||
|
||||
if (userId === ctx.user.id) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "You cannot reset your own password through this endpoint.",
|
||||
});
|
||||
}
|
||||
|
||||
const membershipRepository = new MembershipRepository();
|
||||
const targetMembership = await membershipRepository.findUniqueByUserIdAndTeamId({
|
||||
userId,
|
||||
teamId: organizationId,
|
||||
});
|
||||
|
||||
if (!targetMembership) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "User is not a member of this organization.",
|
||||
});
|
||||
}
|
||||
|
||||
if (targetMembership.role === MembershipRole.OWNER) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Cannot reset password for an organization owner.",
|
||||
});
|
||||
}
|
||||
|
||||
const userRepository = new UserRepository(prisma);
|
||||
const user = await userRepository.findForPasswordReset({ id: userId });
|
||||
|
||||
if (!user) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "User not found." });
|
||||
}
|
||||
|
||||
await passwordResetRequest(user);
|
||||
|
||||
return { success: true };
|
||||
};
|
||||
|
||||
export default sendPasswordResetHandler;
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZOrgPasswordResetSchema = z.object({
|
||||
userId: z.number(),
|
||||
});
|
||||
|
||||
export type TOrgPasswordResetSchema = z.infer<typeof ZOrgPasswordResetSchema>;
|
||||
Reference in new issue
Block a user