feat: add session endpoint and booking access pbac (#24637)

* feat: add session endpoint

* fix: remove participant id

* refactor; feedback

* fix: e2e test

* refactor: add pbac

* refactor: use constant

* tests: add booking tests

* fix: conflicts

* chore: test

* fix: tests

* fix: tests

* chore: remove un necessary

* chore: docs

* fix: desc

* fix: booking-pbac gurd

* fix: booking-pbac gurd

* test: add unit tests

* fix: remove legacy pbac

* fix: chore remove

* fix: update tests

* test: add more test

* test: move it to new file

* chore: comment auth

* chore: add message

* chore: add message

---------

Co-authored-by: Morgan <[email protected]>
This commit is contained in:
Udit TakkarandMorgan authored and GitHub committed 2025-12-04 05:45:17 +00:00
1 parent 3a8bf7014c
commit a11f7e6510
22 files changed
+1186 -71

No files matched your search

@@ -0,0 +1,340 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import type { PrismaClient } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import { BookingRepository } from "../repositories/BookingRepository";
import { BookingAccessService } from "./BookingAccessService";
vi.mock("../repositories/BookingRepository");
vi.mock("@calcom/features/users/repositories/UserRepository");
describe("BookingAccessService", () => {
let service: BookingAccessService;
let mockPrismaClient: PrismaClient;
let mockBookingRepo: {
findByUidIncludeEventType: ReturnType<typeof vi.fn>;
};
let mockUserRepo: {
getUserOrganizationAndTeams: ReturnType<typeof vi.fn>;
};
let mockPermissionCheckService: {
checkPermission: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
vi.clearAllMocks();
mockPrismaClient = {} as PrismaClient;
mockBookingRepo = {
findByUidIncludeEventType: vi.fn(),
};
mockUserRepo = {
getUserOrganizationAndTeams: vi.fn(),
};
mockPermissionCheckService = {
checkPermission: vi.fn(),
};
vi.mocked(BookingRepository).mockImplementation(() => mockBookingRepo as any);
vi.mocked(UserRepository).mockImplementation(() => mockUserRepo as any);
service = new BookingAccessService(mockPrismaClient);
(service as any).permissionCheckService = mockPermissionCheckService;
});
describe("doesUserIdHaveAccessToBooking", () => {
describe("Case 1: Booking Organizer", () => {
it("should return true when user is the booking organizer", async () => {
const mockBooking = {
userId: 123,
eventType: null,
attendees: [],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(true);
expect(mockBookingRepo.findByUidIncludeEventType).toHaveBeenCalledWith({
bookingUid: "test-booking-uid",
});
});
it("should return false when user is not the organizer and booking has no team", async () => {
const mockBooking = {
userId: 456,
eventType: null,
attendees: [],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
mockUserRepo.getUserOrganizationAndTeams.mockResolvedValue(null);
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(false);
});
});
describe("Case 2: Booking Host", () => {
it("should return true when user is a host in eventType.hosts", async () => {
const mockBooking = {
userId: 456,
user: { id: 456, email: "[email protected]" },
eventType: {
hosts: [
{ userId: 123, user: { email: "[email protected]" } },
{ userId: 789, user: { email: "[email protected]" } },
],
users: [],
},
attendees: [{ email: "[email protected]" }],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(true);
});
it("should return true when user is in eventType.users", async () => {
const mockBooking = {
userId: 456,
user: { id: 456, email: "[email protected]" },
eventType: {
hosts: [],
users: [
{ id: 123, email: "[email protected]" },
{ id: 789, email: "[email protected]" },
],
},
attendees: [{ email: "[email protected]" }],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(true);
});
it("should return false when user is not a host", async () => {
const mockBooking = {
userId: 456,
user: { id: 456, email: "[email protected]" },
eventType: {
hosts: [{ userId: 789, user: { email: "[email protected]" } }],
users: [],
},
attendees: [{ email: "[email protected]" }],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
mockUserRepo.getUserOrganizationAndTeams.mockResolvedValue(null);
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(false);
});
});
describe("Case 3: Team Event Access", () => {
it("should return true when user has booking.readTeamBookings permission", async () => {
const mockBooking = {
userId: 456,
eventType: {
teamId: 100,
},
attendees: [],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
mockPermissionCheckService.checkPermission.mockResolvedValue(true);
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(true);
expect(mockPermissionCheckService.checkPermission).toHaveBeenCalledWith({
userId: 123,
teamId: 100,
permission: "booking.readTeamBookings",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
});
it("should return false when user lacks booking.readTeamBookings permission", async () => {
const mockBooking = {
userId: 456,
eventType: {
teamId: 100,
},
attendees: [],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
mockPermissionCheckService.checkPermission.mockResolvedValue(false);
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(false);
expect(mockPermissionCheckService.checkPermission).toHaveBeenCalledWith({
userId: 123,
teamId: 100,
permission: "booking.readTeamBookings",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
});
});
describe("Case 4: Org Admin Access (Personal Bookings)", () => {
it("should return true when user has booking.readOrgBookings permission", async () => {
const mockBooking = {
userId: 456,
eventType: null,
attendees: [],
};
const mockBookingOwner = {
organizationId: 200,
teams: [],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
mockUserRepo.getUserOrganizationAndTeams.mockResolvedValue(mockBookingOwner);
mockPermissionCheckService.checkPermission.mockResolvedValue(true);
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(true);
expect(mockPermissionCheckService.checkPermission).toHaveBeenCalledWith({
userId: 123,
teamId: 200,
permission: "booking.readOrgBookings",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
});
it("should return false when user lacks booking.readOrgBookings permission", async () => {
const mockBooking = {
userId: 456,
eventType: null,
attendees: [],
};
const mockBookingOwner = {
organizationId: 200,
teams: [],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
mockUserRepo.getUserOrganizationAndTeams.mockResolvedValue(mockBookingOwner);
mockPermissionCheckService.checkPermission.mockResolvedValue(false);
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(false);
});
});
describe("Case 5: Team Admin Access (Personal Bookings)", () => {
it("should return true when user has booking.readTeamBookings on ANY team", async () => {
const mockBooking = {
userId: 456,
eventType: null,
attendees: [],
};
const mockBookingOwner = {
organizationId: null,
teams: [{ teamId: 300 }, { teamId: 400 }],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
mockUserRepo.getUserOrganizationAndTeams.mockResolvedValue(mockBookingOwner);
mockPermissionCheckService.checkPermission
.mockResolvedValueOnce(false) // Team 300 - no permission
.mockResolvedValueOnce(true); // Team 400 - has permission
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(true);
expect(mockPermissionCheckService.checkPermission).toHaveBeenCalledTimes(2);
expect(mockPermissionCheckService.checkPermission).toHaveBeenNthCalledWith(1, {
userId: 123,
teamId: 300,
permission: "booking.readTeamBookings",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
expect(mockPermissionCheckService.checkPermission).toHaveBeenNthCalledWith(2, {
userId: 123,
teamId: 400,
permission: "booking.readTeamBookings",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
});
it("should return false when user lacks permission on all teams", async () => {
const mockBooking = {
userId: 456,
eventType: null,
attendees: [],
};
const mockBookingOwner = {
organizationId: null,
teams: [{ teamId: 300 }, { teamId: 400 }],
};
mockBookingRepo.findByUidIncludeEventType.mockResolvedValue(mockBooking);
mockUserRepo.getUserOrganizationAndTeams.mockResolvedValue(mockBookingOwner);
mockPermissionCheckService.checkPermission.mockResolvedValue(false);
const result = await service.doesUserIdHaveAccessToBooking({
userId: 123,
bookingUid: "test-booking-uid",
});
expect(result).toBe(false);
expect(mockPermissionCheckService.checkPermission).toHaveBeenCalledTimes(2);
});
});
});
});
@@ -1,12 +1,18 @@
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import type { PrismaClient } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import { BookingRepository } from "../repositories/BookingRepository";
type BookingForAccessCheck = NonNullable<Awaited<ReturnType<BookingRepository["findByUidIncludeEventType"]>>>;
export class BookingAccessService {
constructor(private prismaClient: PrismaClient) {}
private permissionCheckService: PermissionCheckService;
constructor(private prismaClient: PrismaClient) {
this.permissionCheckService = new PermissionCheckService();
}
private isUserAHost(userId: number, booking: BookingForAccessCheck): boolean {
const hostMap = new Map<number, { id: number; email: string }>();
@@ -38,9 +44,9 @@ export class BookingAccessService {
* Determines if a user has access to a booking based on:
* 1. Being the booking organizer
* 2. Being one of the hosts in a multi-host booking
* 3. Being a team/org admin where the event type belongs
* 4. Being an org admin where the booking organizer belongs (for personal bookings)
* 5. Being a team admin of any team the booking organizer belongs to (for personal bookings)
* 3. Being a team/org admin where the event type belongs (uses PBAC if enabled)
* 4. Being an org admin where the booking organizer belongs (uses PBAC if enabled, for personal bookings)
* 5. Being a team admin of any team the booking organizer belongs to (uses PBAC if enabled, for personal bookings)
*/
async doesUserIdHaveAccessToBooking({
userId,
@@ -63,17 +69,23 @@ export class BookingAccessService {
if (!booking) return false;
// Case 1: User is the booking organizer
if (userId === booking.userId) return true;
// Case 2: User is one of the hosts
if (this.isUserAHost(userId, booking)) return true;
// If booking has a teamId, check if user is admin of that team/org
// Case 3: If booking has a teamId, check if user has access to team bookings
if (booking.eventType?.teamId) {
const isAdminOrUser = await userRepo.isAdminOfTeamOrParentOrg({
const teamId = booking.eventType.teamId;
const hasAccess = await this.permissionCheckService.checkPermission({
userId,
teamId: booking.eventType.teamId,
teamId,
permission: "booking.readTeamBookings",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
return isAdminOrUser;
return hasAccess;
}
// For managed events (child event types), check the parent's teamId
@@ -91,22 +103,30 @@ export class BookingAccessService {
if (!bookingOwner) return false;
// Check if user is admin of booking organizer's organization
// Case 4: Check if user is admin of booking organizer's organization
if (bookingOwner.organizationId) {
const isOrgAdmin = await userRepo.isAdminOfTeamOrParentOrg({
const orgId = bookingOwner.organizationId;
const hasAccess = await this.permissionCheckService.checkPermission({
userId,
teamId: bookingOwner.organizationId,
teamId: orgId,
permission: "booking.readOrgBookings",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
if (isOrgAdmin) return true;
if (hasAccess) return true;
}
// Check if user is admin of any team the booking organizer belongs to
// Case 5: Check if user is admin of any team the booking organizer belongs to
for (const membership of bookingOwner.teams) {
const isTeamAdmin = await userRepo.isAdminOfTeamOrParentOrg({
const teamId = membership.teamId;
const hasAccess = await this.permissionCheckService.checkPermission({
userId,
teamId: membership.teamId,
teamId,
permission: "booking.readTeamBookings",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
if (isTeamAdmin) return true;
if (hasAccess) return true;
}
return false;
@@ -6,6 +6,7 @@ import { getDailyAppKeys } from "@calcom/app-store/dailyvideo/lib/getDailyAppKey
import { getVideoAdapters } from "@calcom/app-store/getVideoAdapters";
import { sendBrokenIntegrationEmail } from "@calcom/emails/integration-email-service";
import { getUid } from "@calcom/lib/CalEventParser";
import { CAL_VIDEO, CAL_VIDEO_TYPE } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { getPiiFreeCalendarEvent, getPiiFreeCredential } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -167,8 +168,8 @@ const createMeetingWithCalVideo = async (calEvent: CalendarEvent) => {
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
appId: CAL_VIDEO,
type: CAL_VIDEO_TYPE,
userId: null,
user: { email: "" },
teamId: null,
@@ -190,8 +191,8 @@ export const createInstantMeetingWithCalVideo = async (endTime: string) => {
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
appId: CAL_VIDEO,
type: CAL_VIDEO_TYPE,
userId: null,
user: { email: "" },
teamId: null,
@@ -216,8 +217,8 @@ const getRecordingsOfCalVideoByRoomName = async (
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
appId: CAL_VIDEO,
type: CAL_VIDEO_TYPE,
userId: null,
user: { email: "" },
teamId: null,
@@ -242,8 +243,8 @@ const getDownloadLinkOfCalVideoByRecordingId = async (
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
appId: CAL_VIDEO,
type: CAL_VIDEO_TYPE,
userId: null,
user: { email: "" },
teamId: null,
@@ -266,8 +267,8 @@ const getAllTranscriptsAccessLinkFromRoomName = async (roomName: string) => {
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
appId: CAL_VIDEO,
type: CAL_VIDEO_TYPE,
userId: null,
user: { email: "" },
teamId: null,
@@ -290,8 +291,8 @@ const getAllTranscriptsAccessLinkFromMeetingId = async (meetingId: string) => {
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
appId: CAL_VIDEO,
type: CAL_VIDEO_TYPE,
userId: null,
user: { email: "" },
teamId: null,
@@ -314,8 +315,8 @@ const submitBatchProcessorTranscriptionJob = async (recordingId: string) => {
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
appId: CAL_VIDEO,
type: CAL_VIDEO_TYPE,
userId: null,
user: { email: "" },
teamId: null,
@@ -350,8 +351,8 @@ const getTranscriptsAccessLinkFromRecordingId = async (recordingId: string) => {
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
appId: CAL_VIDEO,
type: CAL_VIDEO_TYPE,
userId: null,
user: { email: "" },
teamId: null,
@@ -375,8 +376,8 @@ const checkIfRoomNameMatchesInRecording = async (roomName: string, recordingId:
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
appId: CAL_VIDEO,
type: CAL_VIDEO_TYPE,
userId: null,
user: { email: "" },
teamId: null,
@@ -389,6 +390,31 @@ const checkIfRoomNameMatchesInRecording = async (roomName: string, recordingId:
return videoAdapter?.checkIfRoomNameMatchesInRecording?.(roomName, recordingId);
};
const getCalVideoMeetingSessionsByRoomName = async (roomName: string) => {
let dailyAppKeys: Awaited<ReturnType<typeof getDailyAppKeys>>;
try {
dailyAppKeys = await getDailyAppKeys();
} catch (e) {
console.error("Error: Cal video provider is not installed.");
return { data: [] };
}
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: CAL_VIDEO,
type: CAL_VIDEO_TYPE,
userId: null,
user: { email: "" },
teamId: null,
key: dailyAppKeys,
invalid: false,
delegationCredentialId: null,
},
]);
return videoAdapter?.getMeetingInformation?.(roomName) ?? { data: [] };
};
export {
getBusyVideoTimes,
createMeeting,
@@ -401,4 +427,5 @@ export {
submitBatchProcessorTranscriptionJob,
getTranscriptsAccessLinkFromRecordingId,
checkIfRoomNameMatchesInRecording,
getCalVideoMeetingSessionsByRoomName,
};