feat: pbac - private teams (#23998)
* Add permission + migration for listMembersPrivate + depends on lsitMember * Add legacy list members PBAC private logic * Add checks in team pages + handler * add list memeber checks for private orgs * Add permision visibility scope to loading permissions * getMembers handler * fix fallback permission * Verify private teams work with private org * Apply suggestion from @eunjae-lee Co-authored-by: Eunjae Lee <[email protected]> * Remove and private scope function and add param to old --------- Co-authored-by: Eunjae Lee <[email protected]>
This commit is contained in:
1 parent
b17eab3aeb
commit
239e6085ba
16 files changed
+294
-63
No files matched your search
@@ -27,6 +27,7 @@ export enum CustomAction {
|
||||
Remove = "remove",
|
||||
ChangeMemberRole = "changeMemberRole",
|
||||
ListMembers = "listMembers",
|
||||
ListMembersPrivate = "listMembersPrivate",
|
||||
ManageBilling = "manageBilling",
|
||||
ReadTeamBookings = "readTeamBookings",
|
||||
ReadOrgBookings = "readOrgBookings",
|
||||
@@ -46,6 +47,9 @@ export interface PermissionDetails {
|
||||
descriptionI18nKey: string;
|
||||
scope?: Scope[]; // Optional for backward compatibility
|
||||
dependsOn?: PermissionString[]; // Dependencies that must be enabled when this permission is enabled
|
||||
visibleWhen?: {
|
||||
teamPrivacy?: "private" | "public" | "both"; // Control visibility based on team privacy setting
|
||||
};
|
||||
}
|
||||
|
||||
export type ResourceConfig = {
|
||||
@@ -122,12 +126,14 @@ export const filterResourceConfig = (config: ResourceConfig): Omit<ResourceConfi
|
||||
};
|
||||
|
||||
/**
|
||||
* Filter resources and actions based on scope
|
||||
* Filter resources and actions based on scope and optionally team privacy settings
|
||||
* @param scope The scope to filter by (Team or Organization)
|
||||
* @param isPrivate Whether the team/organization is private (optional)
|
||||
* @returns Filtered permission registry
|
||||
*/
|
||||
export const getPermissionsForScope = (scope: Scope): PermissionRegistry => {
|
||||
export const getPermissionsForScope = (scope: Scope, isPrivate?: boolean): PermissionRegistry => {
|
||||
const filteredRegistry: Partial<PermissionRegistry> = {};
|
||||
const teamPrivacy = isPrivate !== undefined ? (isPrivate ? "private" : "public") : undefined;
|
||||
|
||||
Object.entries(PERMISSION_REGISTRY).forEach(([resource, config]) => {
|
||||
const filteredConfig: ResourceConfig = { _resource: config._resource };
|
||||
@@ -136,9 +142,17 @@ export const getPermissionsForScope = (scope: Scope): PermissionRegistry => {
|
||||
if (action === "_resource") return;
|
||||
|
||||
const permissionDetails = details as PermissionDetails;
|
||||
// If no scope is defined, include in both Team and Organization (backward compatibility)
|
||||
// If scope is defined, only include if it matches the requested scope
|
||||
if (!permissionDetails.scope || permissionDetails.scope.includes(scope)) {
|
||||
|
||||
// Check scope
|
||||
const scopeMatches = !permissionDetails.scope || permissionDetails.scope.includes(scope);
|
||||
|
||||
// Check privacy visibility (only if isPrivate is provided)
|
||||
const privacyMatches = teamPrivacy === undefined ||
|
||||
!permissionDetails.visibleWhen?.teamPrivacy ||
|
||||
permissionDetails.visibleWhen.teamPrivacy === "both" ||
|
||||
permissionDetails.visibleWhen.teamPrivacy === teamPrivacy;
|
||||
|
||||
if (scopeMatches && privacyMatches) {
|
||||
filteredConfig[action as CrudAction | CustomAction] = permissionDetails;
|
||||
}
|
||||
});
|
||||
@@ -282,6 +296,19 @@ export const PERMISSION_REGISTRY: PermissionRegistry = {
|
||||
category: "team",
|
||||
i18nKey: "pbac_action_list_members",
|
||||
descriptionI18nKey: "pbac_desc_list_team_members",
|
||||
visibleWhen: {
|
||||
teamPrivacy: "public", // Only show for public teams
|
||||
},
|
||||
},
|
||||
[CustomAction.ListMembersPrivate]: {
|
||||
description: "List private team members",
|
||||
category: "team",
|
||||
i18nKey: "pbac_action_list_members", // Use same UI label as listMembers for consistency
|
||||
descriptionI18nKey: "pbac_desc_list_team_members", // Use same description as listMembers
|
||||
dependsOn: ["team.read"],
|
||||
visibleWhen: {
|
||||
teamPrivacy: "private", // Only show for private teams
|
||||
},
|
||||
},
|
||||
[CustomAction.ChangeMemberRole]: {
|
||||
description: "Change role of team members",
|
||||
@@ -330,6 +357,20 @@ export const PERMISSION_REGISTRY: PermissionRegistry = {
|
||||
descriptionI18nKey: "pbac_desc_list_organization_members",
|
||||
scope: [Scope.Organization],
|
||||
dependsOn: ["organization.read"],
|
||||
visibleWhen: {
|
||||
teamPrivacy: "public", // Only show for public orgs
|
||||
},
|
||||
},
|
||||
[CustomAction.ListMembersPrivate]: {
|
||||
description: "List private organization members",
|
||||
category: "org",
|
||||
i18nKey: "pbac_action_list_members", // Same UI label as listMembers for consistency
|
||||
descriptionI18nKey: "pbac_desc_list_organization_members", // Same description as listMembers
|
||||
scope: [Scope.Organization],
|
||||
dependsOn: ["organization.read"],
|
||||
visibleWhen: {
|
||||
teamPrivacy: "private", // Only show for private orgs
|
||||
},
|
||||
},
|
||||
[CustomAction.Invite]: {
|
||||
description: "Invite organization members",
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
-- This permission allows admin users to view members of private teams and organizations
|
||||
|
||||
INSERT INTO "RolePermission" (id, "roleId", resource, action, "createdAt")
|
||||
SELECT
|
||||
gen_random_uuid(), 'admin_role', resource, action, NOW()
|
||||
FROM (
|
||||
VALUES
|
||||
-- Team listMembersPrivate permission
|
||||
('team', 'listMembersPrivate'),
|
||||
|
||||
-- Organization listMembersPrivate permission
|
||||
('organization', 'listMembersPrivate')
|
||||
) AS permissions(resource, action)
|
||||
ON CONFLICT ("roleId", resource, action) DO NOTHING;
|
||||
|
||||
-- Note: Owner role already has wildcard permissions (*.*) so it inherits all listMembersPrivate permissions automatically
|
||||
@@ -1,4 +1,6 @@
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TGetMembersInputSchema } from "./getMembers.schema";
|
||||
@@ -16,9 +18,21 @@ export const getMembersHandler = async ({ input, ctx }: CreateOptions) => {
|
||||
if (!ctx.user.organizationId) return [];
|
||||
|
||||
const isOrgPrivate = ctx.user.organization.isPrivate;
|
||||
const isOrgAdmin = ctx.user.organization.isOrgAdmin;
|
||||
|
||||
if (isOrgPrivate && !isOrgAdmin) return [];
|
||||
const permissionCheckService = new PermissionCheckService();
|
||||
|
||||
const hasPermissionToViewMembers = await permissionCheckService.checkPermission({
|
||||
userId: ctx.user.id,
|
||||
teamId: ctx.user.organizationId,
|
||||
permission: ctx.user.organization.isPrivate
|
||||
? "organization.listMembersPrivate"
|
||||
: "organization.listMembers",
|
||||
fallbackRoles: ctx.user.organization.isPrivate
|
||||
? [MembershipRole.ADMIN, MembershipRole.OWNER]
|
||||
: [MembershipRole.MEMBER, MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
});
|
||||
|
||||
if (!hasPermissionToViewMembers) return [];
|
||||
|
||||
const teamQuery = await prisma.team.findUnique({
|
||||
where: {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { listMembersHandler } from "./listMembers.handler";
|
||||
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
prisma,
|
||||
default: prisma, // Add default export for db
|
||||
}));
|
||||
|
||||
// Mock FeaturesRepository
|
||||
@@ -22,9 +23,18 @@ vi.mock("@calcom/features/flags/features.repository", () => ({
|
||||
vi.mock("@calcom/features/pbac/lib/resource-permissions", () => ({
|
||||
getSpecificPermissions: vi.fn().mockResolvedValue({
|
||||
listMembers: true,
|
||||
listMembersPrivate: true,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock PermissionCheckService
|
||||
const mockCheckPermission = vi.fn().mockResolvedValue(true);
|
||||
vi.mock("@calcom/features/pbac/services/permission-check.service", () => ({
|
||||
PermissionCheckService: vi.fn().mockImplementation(() => ({
|
||||
checkPermission: mockCheckPermission,
|
||||
})),
|
||||
}));
|
||||
|
||||
// Mock UserRepository
|
||||
vi.mock("@calcom/lib/server/repository/user", () => ({
|
||||
UserRepository: vi.fn().mockImplementation(() => ({
|
||||
@@ -65,6 +75,8 @@ describe("listMembersHandler", () => {
|
||||
prisma.membership.findMany.mockResolvedValue([]);
|
||||
prisma.membership.count.mockResolvedValue(0);
|
||||
prisma.membership.findFirst.mockResolvedValue({ role: "ADMIN" });
|
||||
// Mock team.findUnique to return only isPrivate field since that's what the handler selects
|
||||
prisma.team.findUnique.mockResolvedValue({ isPrivate: false } as any);
|
||||
});
|
||||
|
||||
it("should filter by customRoleId when PBAC is enabled", async () => {
|
||||
@@ -234,4 +246,72 @@ describe("listMembersHandler", () => {
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should check listMembersPrivate permission for private organizations", async () => {
|
||||
// Clear previous calls
|
||||
mockCheckPermission.mockClear();
|
||||
mockCheckPermission.mockResolvedValue(true);
|
||||
|
||||
// Mock private organization
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
prisma.team.findUnique.mockResolvedValue({ isPrivate: true } as any);
|
||||
|
||||
const privateOrgUser = {
|
||||
...mockUser,
|
||||
organization: {
|
||||
...mockUser.organization,
|
||||
isPrivate: true,
|
||||
},
|
||||
};
|
||||
|
||||
await listMembersHandler({
|
||||
ctx: {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
user: privateOrgUser as any,
|
||||
},
|
||||
input: {
|
||||
limit: 25,
|
||||
offset: 0,
|
||||
filters: [],
|
||||
},
|
||||
});
|
||||
|
||||
// Verify that checkPermission was called with listMembersPrivate
|
||||
expect(mockCheckPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
permission: "organization.listMembersPrivate",
|
||||
fallbackRoles: ["ADMIN", "OWNER"],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should check listMembers permission for public organizations", async () => {
|
||||
// Clear previous calls
|
||||
mockCheckPermission.mockClear();
|
||||
mockCheckPermission.mockResolvedValue(true);
|
||||
|
||||
// Mock public organization (default)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
prisma.team.findUnique.mockResolvedValue({ isPrivate: false } as any);
|
||||
|
||||
await listMembersHandler({
|
||||
ctx: {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
user: mockUser as any,
|
||||
},
|
||||
input: {
|
||||
limit: 25,
|
||||
offset: 0,
|
||||
filters: [],
|
||||
},
|
||||
});
|
||||
|
||||
// Verify that checkPermission was called with listMembers
|
||||
expect(mockCheckPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
permission: "organization.listMembers",
|
||||
fallbackRoles: ["MEMBER", "ADMIN", "OWNER"],
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { type TypedColumnFilter, ColumnFilterType } from "@calcom/features/data-
|
||||
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 { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
@@ -87,23 +88,20 @@ export const listMembersHandler = async ({ ctx, input }: GetOptions) => {
|
||||
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({
|
||||
const permissionCheckService = new PermissionCheckService();
|
||||
|
||||
const hasPermission = await permissionCheckService.checkPermission({
|
||||
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],
|
||||
},
|
||||
},
|
||||
permission: ctx.user.organization.isPrivate
|
||||
? "organization.listMembersPrivate"
|
||||
: "organization.listMembers",
|
||||
fallbackRoles: ctx.user.organization.isPrivate
|
||||
? [MembershipRole.ADMIN, MembershipRole.OWNER]
|
||||
: [MembershipRole.MEMBER, MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
});
|
||||
|
||||
if (!permissions[CustomAction.ListMembers]) {
|
||||
if (!hasPermission) {
|
||||
return {
|
||||
canUserGetMembers: false,
|
||||
rows: [],
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { Resource, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
@@ -16,14 +19,18 @@ type ListMembersOptions = {
|
||||
|
||||
export const legacyListMembers = async ({ ctx, input }: ListMembersOptions) => {
|
||||
const { prisma } = ctx;
|
||||
const { isOrgAdmin } = ctx.user.organization;
|
||||
const hasPermsToView = !ctx.user.organization.isPrivate || isOrgAdmin;
|
||||
const orgId = ctx.user.organizationId;
|
||||
|
||||
if (!hasPermsToView) {
|
||||
return {
|
||||
members: [],
|
||||
nextCursor: undefined,
|
||||
};
|
||||
// Check PBAC permissions for the organization if it's private
|
||||
if (orgId) {
|
||||
const hasPermsToView = await checkCanAccessOrgMembers(ctx, orgId);
|
||||
|
||||
if (!hasPermsToView) {
|
||||
return {
|
||||
members: [],
|
||||
nextCursor: undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const limit = input.limit ?? 10;
|
||||
@@ -129,4 +136,30 @@ export const legacyListMembers = async ({ ctx, input }: ListMembersOptions) => {
|
||||
};
|
||||
};
|
||||
|
||||
const checkCanAccessOrgMembers = async (ctx: ListMembersOptions["ctx"], orgId: number): Promise<boolean> => {
|
||||
const { prisma } = ctx;
|
||||
|
||||
// Get organization info to verify it's private
|
||||
const org = await prisma.team.findUnique({
|
||||
where: { id: orgId },
|
||||
select: { isPrivate: true },
|
||||
});
|
||||
|
||||
if (!org) return false;
|
||||
|
||||
// Check PBAC permissions for listing members
|
||||
const permissionCheckService = new PermissionCheckService();
|
||||
|
||||
const hasPermission = await permissionCheckService.checkPermission({
|
||||
userId: ctx.user.id,
|
||||
teamId: orgId,
|
||||
permission: org.isPrivate ? "organization.listMembersPrivate" : "organization.listMembers",
|
||||
fallbackRoles: org.isPrivate
|
||||
? [MembershipRole.ADMIN, MembershipRole.OWNER]
|
||||
: [MembershipRole.MEMBER, MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
});
|
||||
|
||||
return hasPermission;
|
||||
};
|
||||
|
||||
export default legacyListMembers;
|
||||
@@ -1,5 +1,10 @@
|
||||
import { Resource, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import {
|
||||
Resource,
|
||||
CustomAction,
|
||||
PermissionString,
|
||||
} from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
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";
|
||||
@@ -157,37 +162,22 @@ const checkCanAccessMembers = async (ctx: ListMembersHandlerOptions["ctx"], team
|
||||
|
||||
if (!team) return false;
|
||||
|
||||
// Get user's membership in the team
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
teamId,
|
||||
userId: ctx.user.id,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) return false;
|
||||
|
||||
// Determine the resource type based on whether this is an org or team
|
||||
const resource = isTargetingOrg ? Resource.Organization : Resource.Team;
|
||||
const targetAction = team.isPrivate ? CustomAction.ListMembersPrivate : CustomAction.ListMembers;
|
||||
const permissionString = `${resource}.${targetAction}` as PermissionString;
|
||||
|
||||
// Check PBAC permissions for listing members
|
||||
const permissions = await getSpecificPermissions({
|
||||
const permissionCheckService = new PermissionCheckService();
|
||||
|
||||
return permissionCheckService.checkPermission({
|
||||
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],
|
||||
},
|
||||
},
|
||||
permission: permissionString,
|
||||
fallbackRoles: team.isPrivate
|
||||
? [MembershipRole.ADMIN, MembershipRole.OWNER]
|
||||
: [MembershipRole.MEMBER, MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
});
|
||||
|
||||
return permissions[CustomAction.ListMembers];
|
||||
};
|
||||
|
||||
export default listMembersHandler;
|
||||
Reference in new issue
Block a user