feat: PBAC on team members page + org members page to use specific permissi… (#23004)

* PBAC on team members page + org members page to use specific permissions with fallbacks

* Implement checks on edit sheet fetch to check for permisisons

* WIP permission fixes

* fix tests

* WIP

* fix edit mode perms

* fix remove and list view permissions

* fix add

* feat: add pbac permissions for impersonation (#23035)

* registery + migration + i18n

* UI for can impersonate

* impersonation backend

* remove permission from db query

* add missing prisma import

* add resend invitation and edit mode checks for delete/changeRole

* fix canChangeRole

* canChangeRole gate

* fix permission logic

* fix depends on

* push migration

* fix migration

* fix scoped advanced permissions

* use listMembers instead of invite proxy

* remove isOrgAdmin check to rely on pbac

* wait for session to load before navigating

* use event-types testId to ensure session loaded

* use profile page instead of eventTypes

* use correct roles

* fix wait for session

* correct orgs private isFallBackRoles

* set a timeout on waiting for session

* remove adminOrOwner check since its in fallpack

---------

Co-authored-by: Volnei Munhoz <[email protected]>
Co-authored-by: Eunjae Lee <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-09-02 12:52:45 -03:00
1 parent 2dbd0b3832
commit 75465ac4bf
28 files changed
+830 -214

No files matched your search

@@ -1,7 +1,9 @@
import { TeamBilling } from "@calcom/ee/billing/teams";
import { isOrganisationAdmin } from "@calcom/lib/server/queries/organisations";
import { Resource, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
@@ -21,9 +23,38 @@ export async function bulkDeleteUsersHandler({ ctx, input }: BulkDeleteUsersHand
if (!currentUserOrgId) throw new TRPCError({ code: "UNAUTHORIZED" });
// check if user is admin of organization
if (!(await isOrganisationAdmin(currentUser?.id, currentUserOrgId)))
// Get user's membership role in the organization
const membership = await prisma.membership.findFirst({
where: {
userId: currentUser.id,
teamId: currentUserOrgId,
},
select: {
role: true,
},
});
if (!membership) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "User is not a member of this organization." });
}
// Check PBAC permissions for removing organization members
const permissions = await getSpecificPermissions({
userId: currentUser.id,
teamId: currentUserOrgId,
resource: Resource.Organization,
userRole: membership.role,
actions: [CustomAction.Remove],
fallbackRoles: {
[CustomAction.Remove]: {
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
},
},
});
if (!permissions[CustomAction.Remove]) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
// Loop over all users in input.userIds and remove all memberships for the organization including child teams
const deleteMany = prisma.membership.deleteMany({
@@ -1,5 +1,7 @@
import { isOrganisationAdmin } from "@calcom/lib/server/queries/organisations";
import { Resource, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
@@ -18,9 +20,42 @@ export async function getUserHandler({ input, ctx }: AdminVerifyOptions) {
if (!currentUser.organizationId) throw new TRPCError({ code: "UNAUTHORIZED" });
// check if user is admin of organization
if (!(await isOrganisationAdmin(currentUser?.id, currentUser.organizationId)))
// Get user's membership role in the organization
const currentUserMembership = await prisma.membership.findFirst({
where: {
userId: currentUser.id,
teamId: currentUser.organizationId,
},
select: {
role: true,
},
});
if (!currentUserMembership) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "User is not a member of this organization." });
}
// Check PBAC permissions for viewing/editing organization members
const permissions = await getSpecificPermissions({
userId: currentUser.id,
teamId: currentUser.organizationId,
resource: Resource.Organization,
userRole: currentUserMembership.role,
actions: [CustomAction.ListMembers, CustomAction.ChangeMemberRole],
fallbackRoles: {
[CustomAction.ListMembers]: {
roles: [MembershipRole.MEMBER, MembershipRole.ADMIN, MembershipRole.OWNER],
},
[CustomAction.ChangeMemberRole]: {
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
},
},
});
// User needs either ListMembers (to view) or ChangeMemberRole (to edit) permission
if (!permissions[CustomAction.ListMembers] || !permissions[CustomAction.ChangeMemberRole]) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
// get requested user from database and ensure they are in the same organization
const [requestedUser, membership, teams] = await prisma.$transaction([
@@ -9,6 +9,7 @@ const prismaMock = {
membership: {
findMany: vi.fn().mockResolvedValue([]),
count: vi.fn().mockResolvedValue(0),
findFirst: vi.fn().mockResolvedValue({ role: "ADMIN" }),
},
attributeOption: {
findMany: vi.fn().mockResolvedValue([
@@ -16,11 +17,16 @@ const prismaMock = {
{ id: "2", value: "value2", isGroup: false },
]),
},
attributeToUser: {
findMany: vi.fn().mockResolvedValue([]),
},
};
vi.spyOn(prisma.membership, "findMany").mockImplementation(prismaMock.membership.findMany);
vi.spyOn(prisma.membership, "count").mockImplementation(prismaMock.membership.count);
vi.spyOn(prisma.membership, "findFirst").mockImplementation(prismaMock.membership.findFirst);
vi.spyOn(prisma.attributeOption, "findMany").mockImplementation(prismaMock.attributeOption.findMany);
vi.spyOn(prisma.attributeToUser, "findMany").mockImplementation(prismaMock.attributeToUser.findMany);
// Mock FeaturesRepository
const mockCheckIfTeamHasFeature = vi.fn();
@@ -30,6 +36,20 @@ vi.mock("@calcom/features/flags/features.repository", () => ({
})),
}));
// Mock PBAC permissions
vi.mock("@calcom/features/pbac/lib/resource-permissions", () => ({
getSpecificPermissions: vi.fn().mockResolvedValue({
listMembers: true,
}),
}));
// Mock UserRepository
vi.mock("@calcom/lib/server/repository/user", () => ({
UserRepository: vi.fn().mockImplementation(() => ({
enrichUserWithItsProfile: vi.fn().mockImplementation(({ user }) => user),
})),
}));
const ORGANIZATION_ID = 123;
const mockUser = {
@@ -1,9 +1,12 @@
import { makeWhereClause } from "@calcom/features/data-table/lib/server";
import { type TypedColumnFilter, ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { Resource, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { MembershipRole } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
@@ -69,7 +72,38 @@ export const listMembersHandler = async ({ ctx, input }: GetOptions) => {
throw new TRPCError({ code: "NOT_FOUND", message: "User is not part of any organization." });
}
if (ctx.user.organization.isPrivate && !ctx.user.organization.isOrgAdmin) {
// Get user's membership role in the organization
const membership = await prisma.membership.findFirst({
where: {
userId: ctx.user.id,
teamId: organizationId,
},
select: {
role: true,
},
});
if (!membership) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "User is not a member of this organization." });
}
// Check PBAC permissions for listing organization members
const permissions = await getSpecificPermissions({
userId: ctx.user.id,
teamId: organizationId,
resource: Resource.Organization,
userRole: membership.role,
actions: [CustomAction.ListMembers],
fallbackRoles: {
[CustomAction.ListMembers]: {
roles: ctx.user.organization.isPrivate
? [MembershipRole.ADMIN, MembershipRole.OWNER]
: [MembershipRole.MEMBER, MembershipRole.ADMIN, MembershipRole.OWNER],
},
},
});
if (!permissions[CustomAction.ListMembers]) {
return {
canUserGetMembers: false,
rows: [],
@@ -78,7 +112,6 @@ export const listMembersHandler = async ({ ctx, input }: GetOptions) => {
},
};
}
const { limit, offset } = input;
const roleFilter = filters.find((filter) => filter.id === "role") as
@@ -1,11 +1,13 @@
import type { Prisma } from "@prisma/client";
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
import { Resource, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
import { RoleManagementFactory } from "@calcom/features/pbac/services/role-management.factory";
import { getBookerBaseUrlSync } from "@calcom/lib/getBookerUrl/client";
import { TeamRepository } from "@calcom/lib/server/repository/team";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { TRPCError } from "@trpc/server";
@@ -146,26 +148,17 @@ export const listMembersHandler = async ({ ctx, input }: ListMembersHandlerOptio
};
const checkCanAccessMembers = async (ctx: ListMembersHandlerOptions["ctx"], teamId: number) => {
const isOrgPrivate = ctx.user.profile?.organization?.isPrivate;
const isOrgAdminOrOwner = ctx.user.organization?.isOrgAdmin;
const orgId = ctx.user.organizationId;
const isTargetingOrg = teamId === ctx.user.organizationId;
if (isTargetingOrg) {
return isOrgAdminOrOwner || !isOrgPrivate;
}
// Get team info to check if it's private
const team = await prisma.team.findUnique({
where: {
id: teamId,
},
where: { id: teamId },
select: { isPrivate: true },
});
if (!team) return false;
if (isOrgAdminOrOwner && team?.parentId === orgId) {
return true;
}
// Get user's membership in the team
const membership = await prisma.membership.findFirst({
where: {
teamId,
@@ -176,12 +169,26 @@ const checkCanAccessMembers = async (ctx: ListMembersHandlerOptions["ctx"], team
if (!membership) return false;
const isTeamAdminOrOwner = checkAdminOrOwner(membership?.role);
// Determine the resource type based on whether this is an org or team
const resource = isTargetingOrg ? Resource.Organization : Resource.Team;
if (team?.isPrivate && !isTeamAdminOrOwner) {
return false;
}
return true;
// Check PBAC permissions for listing members
const permissions = await getSpecificPermissions({
userId: ctx.user.id,
teamId: teamId,
resource: resource,
userRole: membership.role,
actions: [CustomAction.ListMembers],
fallbackRoles: {
[CustomAction.ListMembers]: {
roles: team.isPrivate
? [MembershipRole.ADMIN, MembershipRole.OWNER]
: [MembershipRole.MEMBER, MembershipRole.ADMIN, MembershipRole.OWNER],
},
},
});
return permissions[CustomAction.ListMembers];
};
export default listMembersHandler;
@@ -1,6 +1,11 @@
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { Resource, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { isTeamAdmin, isTeamOwner } from "@calcom/lib/server/queries/teams";
import { isTeamOwner } from "@calcom/lib/server/queries/teams";
import { TeamService } from "@calcom/lib/server/service/teamService";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { TRPCError } from "@trpc/server";
@@ -22,42 +27,93 @@ export const removeMemberHandler = async ({ ctx, input }: RemoveMemberOptions) =
const { memberIds, teamIds, isOrg } = input;
const isAdmin = await Promise.all(
teamIds.map(async (teamId) => await isTeamAdmin(ctx.user.id, teamId))
// Check PBAC permissions for each team
const hasRemovePermission = await Promise.all(
teamIds.map(async (teamId) => {
// Get user's membership role in this team
const membership = await prisma.membership.findFirst({
where: {
userId: ctx.user.id,
teamId: teamId,
},
select: {
role: true,
},
});
if (!membership) return false;
// Check PBAC permissions for removing team members
const permissions = await getSpecificPermissions({
userId: ctx.user.id,
teamId: teamId,
resource: isOrg ? Resource.Organization : Resource.Team,
userRole: membership.role,
actions: [CustomAction.Remove],
fallbackRoles: {
[CustomAction.Remove]: {
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
},
},
});
return permissions[CustomAction.Remove];
})
).then((results) => results.every((result) => result));
const isOrgAdmin = ctx.user.profile?.organizationId
? await isTeamAdmin(ctx.user.id, ctx.user.profile?.organizationId)
: false;
// Check if user is trying to remove themselves (allowed for non-owners)
const isRemovingSelf = memberIds.length === 1 && memberIds[0] === ctx.user.id;
if (!(isAdmin || isOrgAdmin) && memberIds.every((memberId) => ctx.user.id !== memberId))
// Allow if user has remove permission OR if they're removing themselves
if (!hasRemovePermission && !isRemovingSelf) {
throw new TRPCError({ code: "UNAUTHORIZED" });
// Only a team owner can remove another team owner.
const isAnyMemberOwnerAndCurrentUserNotOwner = await Promise.all(
memberIds.map(async (memberId) => {
const isAnyTeamOwnerAndCurrentUserNotOwner = await Promise.all(
teamIds.map(async (teamId) => {
return (await isTeamOwner(memberId, teamId)) && !(await isTeamOwner(ctx.user.id, teamId));
})
).then((results) => results.some((result) => result));
return isAnyTeamOwnerAndCurrentUserNotOwner;
})
).then((results) => results.some((result) => result));
if (isAnyMemberOwnerAndCurrentUserNotOwner) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Only a team owner can remove another team owner.",
});
}
if (memberIds.some((memberId) => ctx.user.id === memberId) && isAdmin && !isOrgAdmin)
throw new TRPCError({
code: "FORBIDDEN",
message: "You can not remove yourself from a team you own.",
});
// TODO(SEAN): Remove this after PBAC is rolled out.
// Check if any team has PBAC enabled
const featuresRepository = new FeaturesRepository(prisma);
const pbacEnabledForTeams = await Promise.all(
teamIds.map(async (teamId) => await featuresRepository.checkIfTeamHasFeature(teamId, "pbac"))
);
const isAnyTeamPBACEnabled = pbacEnabledForTeams.some((enabled) => enabled);
// Only apply traditional owner-based logic if PBAC is not enabled for any teams
if (!isAnyTeamPBACEnabled) {
// Only a team owner can remove another team owner.
const isAnyMemberOwnerAndCurrentUserNotOwner = await Promise.all(
memberIds.map(async (memberId) => {
const isAnyTeamOwnerAndCurrentUserNotOwner = await Promise.all(
teamIds.map(async (teamId) => {
return (await isTeamOwner(memberId, teamId)) && !(await isTeamOwner(ctx.user.id, teamId));
})
).then((results) => results.some((result) => result));
return isAnyTeamOwnerAndCurrentUserNotOwner;
})
).then((results) => results.some((result) => result));
if (isAnyMemberOwnerAndCurrentUserNotOwner) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Only a team owner can remove another team owner.",
});
}
// Check if user is trying to remove themselves from a team they own (prevent this)
if (isRemovingSelf && hasRemovePermission) {
// Additional check: ensure they're not an owner trying to remove themselves
const isOwnerOfAnyTeam = await Promise.all(
teamIds.map(async (teamId) => await isTeamOwner(ctx.user.id, teamId))
).then((results) => results.some((result) => result));
if (isOwnerOfAnyTeam) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You can not remove yourself from a team you own.",
});
}
}
}
await TeamService.removeMembers({ teamIds, userIds: memberIds, isOrg });
};