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
@@ -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