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:
28 files changed
+830
-214
No files matched your search
@@ -2,12 +2,14 @@ import type { Session } from "next-auth";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { UserPermissionRole } from "@calcom/prisma/enums";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import {
|
||||
parseTeamId,
|
||||
checkSelfImpersonation,
|
||||
checkUserIdentifier,
|
||||
checkGlobalPermission,
|
||||
checkPBACImpersonationPermission,
|
||||
} from "./ImpersonationProvider";
|
||||
|
||||
const session: Session = {
|
||||
@@ -79,3 +81,41 @@ describe("checkPermission", () => {
|
||||
expect(() => checkGlobalPermission(session)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkPBACImpersonationPermission", () => {
|
||||
it("should return true for admin users", async () => {
|
||||
const result = await checkPBACImpersonationPermission({
|
||||
userId: 123,
|
||||
teamId: 456,
|
||||
userRole: MembershipRole.ADMIN,
|
||||
});
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true for owner users", async () => {
|
||||
const result = await checkPBACImpersonationPermission({
|
||||
userId: 123,
|
||||
teamId: 456,
|
||||
userRole: MembershipRole.OWNER,
|
||||
});
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for member users", async () => {
|
||||
const result = await checkPBACImpersonationPermission({
|
||||
userId: 123,
|
||||
teamId: 456,
|
||||
userRole: MembershipRole.MEMBER,
|
||||
});
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle organization context", async () => {
|
||||
const result = await checkPBACImpersonationPermission({
|
||||
userId: 123,
|
||||
organizationId: 789,
|
||||
userRole: MembershipRole.ADMIN,
|
||||
});
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -5,12 +5,16 @@ import { z } from "zod";
|
||||
|
||||
import { ensureOrganizationIsReviewed } from "@calcom/ee/organizations/lib/ensureOrganizationIsReviewed";
|
||||
import { getSession } from "@calcom/features/auth/lib/getSession";
|
||||
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import type { Membership } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { OrgProfile, PersonalProfile, UserAsPersonalProfile } from "@calcom/types/UserProfile";
|
||||
|
||||
import { Resource, CustomAction } from "../../../pbac/domain/types/permission-registry";
|
||||
|
||||
const teamIdschema = z.object({
|
||||
teamId: z.preprocess((a) => parseInt(z.string().parse(a), 10), z.number().positive()),
|
||||
});
|
||||
@@ -113,6 +117,69 @@ export function checkGlobalPermission(session: Session | null) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check PBAC permissions for impersonation
|
||||
* This function integrates with the new PBAC system to determine impersonation permissions
|
||||
*/
|
||||
export async function checkPBACImpersonationPermission({
|
||||
userId,
|
||||
teamId,
|
||||
userRole,
|
||||
organizationId,
|
||||
}: {
|
||||
userId: number;
|
||||
teamId?: number;
|
||||
userRole: MembershipRole;
|
||||
organizationId?: number | null;
|
||||
}): Promise<boolean> {
|
||||
try {
|
||||
// For organization-level impersonation
|
||||
if (organizationId) {
|
||||
const orgPermissions = await getSpecificPermissions({
|
||||
userId,
|
||||
teamId: organizationId,
|
||||
resource: Resource.Organization,
|
||||
userRole,
|
||||
actions: [CustomAction.Impersonate],
|
||||
fallbackRoles: {
|
||||
[CustomAction.Impersonate]: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (orgPermissions[CustomAction.Impersonate]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// For team-level impersonation
|
||||
if (teamId) {
|
||||
const teamPermissions = await getSpecificPermissions({
|
||||
userId,
|
||||
teamId,
|
||||
resource: Resource.Team,
|
||||
userRole,
|
||||
actions: [CustomAction.Impersonate],
|
||||
fallbackRoles: {
|
||||
[CustomAction.Impersonate]: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return teamPermissions[CustomAction.Impersonate] ?? false;
|
||||
}
|
||||
|
||||
// Fallback to role-based check if no team/org context
|
||||
return userRole === MembershipRole.ADMIN || userRole === MembershipRole.OWNER;
|
||||
} catch (error) {
|
||||
console.error("Error checking PBAC impersonation permission:", error);
|
||||
// Fallback to role-based check on error
|
||||
return userRole === MembershipRole.ADMIN || userRole === MembershipRole.OWNER;
|
||||
}
|
||||
}
|
||||
|
||||
async function getImpersonatedUser({
|
||||
session,
|
||||
teamId,
|
||||
@@ -295,11 +362,6 @@ const ImpersonationProvider = CredentialsProvider({
|
||||
teams: {
|
||||
where: {
|
||||
AND: [
|
||||
{
|
||||
role: {
|
||||
in: ["ADMIN", "OWNER"],
|
||||
},
|
||||
},
|
||||
{
|
||||
team: {
|
||||
id: teamId,
|
||||
@@ -318,6 +380,19 @@ const ImpersonationProvider = CredentialsProvider({
|
||||
throw new Error("Error-UserHasNoTeams: You do not have permission to do this.");
|
||||
}
|
||||
|
||||
// Check PBAC permissions for impersonation
|
||||
const hasImpersonationPermission = await checkPBACImpersonationPermission({
|
||||
userId: session?.user.id as number,
|
||||
teamId,
|
||||
userRole: sessionUserFromDb?.teams[0].role as MembershipRole,
|
||||
organizationId: session?.user.org?.id,
|
||||
});
|
||||
|
||||
if (!hasImpersonationPermission) {
|
||||
throw new Error("You do not have permission to impersonate this user.");
|
||||
}
|
||||
|
||||
// Legacy role check as additional safeguard (PBAC should handle this but keeping for backwards compatibility)
|
||||
// We find team by ID so we know there is only one team in the array
|
||||
if (sessionUserFromDb?.teams[0].role === "ADMIN" && impersonatedUser.teams[0].role === "OWNER") {
|
||||
throw new Error("You do not have permission to do this.");
|
||||
|
||||
@@ -15,7 +15,6 @@ import { useQueryState, parseAsBoolean } from "nuqs";
|
||||
import { useMemo, useReducer, useRef, useState } from "react";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import {
|
||||
DataTableProvider,
|
||||
@@ -30,10 +29,10 @@ import {
|
||||
} from "@calcom/features/data-table";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import { DynamicLink } from "@calcom/features/users/components/UserTable/BulkActions/DynamicLink";
|
||||
import type { MemberPermissions } from "@calcom/features/users/components/UserTable/types";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
@@ -163,6 +162,7 @@ interface Props {
|
||||
}[];
|
||||
}[];
|
||||
};
|
||||
permissions: MemberPermissions;
|
||||
}
|
||||
|
||||
export default function MemberList(props: Props) {
|
||||
@@ -292,8 +292,6 @@ function MemberListContent(props: Props) {
|
||||
// return owners.length;
|
||||
// };
|
||||
|
||||
const isAdminOrOwner = checkAdminOrOwner(props.team.membership.role);
|
||||
|
||||
const removeMember = () =>
|
||||
removeMemberMutation.mutate({
|
||||
teamIds: [props.team?.id],
|
||||
@@ -429,17 +427,19 @@ function MemberListContent(props: Props) {
|
||||
cell: ({ row }) => {
|
||||
const user = row.original;
|
||||
const isSelf = user.id === session?.user.id;
|
||||
// TODO(SEAN) In a follow up can we rename canChangeMemberRole to canEditMembers - role is a bit specific.
|
||||
const canChangeRole = props.permissions?.canChangeMemberRole ?? false;
|
||||
const canRemove = props.permissions?.canRemove ?? false;
|
||||
const canImpersonate = props.permissions?.canImpersonate ?? false;
|
||||
const canResendInvitation = props.permissions?.canInvite ?? false;
|
||||
const editMode =
|
||||
(props.team.membership?.role === MembershipRole.OWNER &&
|
||||
(user.role !== MembershipRole.OWNER || !isSelf)) ||
|
||||
(props.team.membership?.role === MembershipRole.ADMIN && user.role !== MembershipRole.OWNER) ||
|
||||
props.isOrgAdminOrOwner;
|
||||
[canChangeRole, canRemove, canImpersonate, canResendInvitation].some(Boolean) && !isSelf;
|
||||
|
||||
const impersonationMode =
|
||||
editMode &&
|
||||
canImpersonate &&
|
||||
!user.disableImpersonation &&
|
||||
user.accepted &&
|
||||
process.env.NEXT_PUBLIC_TEAM_IMPERSONATION === "true";
|
||||
const resendInvitation = editMode && !user.accepted;
|
||||
return (
|
||||
<>
|
||||
{props.team.membership?.accepted && (
|
||||
@@ -495,22 +495,24 @@ function MemberListContent(props: Props) {
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "EDIT_USER_SHEET",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
StartIcon="pencil">
|
||||
{t("edit")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
{canChangeRole ? (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "EDIT_USER_SHEET",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
StartIcon="pencil">
|
||||
{t("edit")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{impersonationMode && (
|
||||
<>
|
||||
<DropdownMenuItem>
|
||||
@@ -532,7 +534,7 @@ function MemberListContent(props: Props) {
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
{resendInvitation && (
|
||||
{canResendInvitation && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
@@ -548,23 +550,25 @@ function MemberListContent(props: Props) {
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "SET_DELETE_ID",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
color="destructive"
|
||||
StartIcon="user-x">
|
||||
{t("remove")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
{canRemove ? (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "SET_DELETE_ID",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
color="destructive"
|
||||
StartIcon="user-x">
|
||||
{t("remove")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenuPortal>
|
||||
</Dropdown>
|
||||
@@ -713,7 +717,7 @@ function MemberListContent(props: Props) {
|
||||
ToolbarRight={
|
||||
<>
|
||||
<DataTableFilters.ClearFiltersButton />
|
||||
{isAdminOrOwner && (
|
||||
{props.permissions.canInvite && (
|
||||
<DataTableToolbar.CTA
|
||||
type="button"
|
||||
color="primary"
|
||||
|
||||
Reference in new issue
Block a user