* feat(booking-audit): extract core audit system changes from PR 25125 This PR extracts core audit infrastructure changes without integration changes: 1. New action services introduced: - SeatBookedAuditActionService - SeatRescheduledAuditActionService 2. Simplification of ActionService interface: - Streamlined IAuditActionService interface - Reduced TypeScript burden with cleaner type definitions 3. ActionSource support: - Added BookingAuditSource enum (API_V1, API_V2, WEBAPP, WEBHOOK, UNKNOWN) - Added source and operationId fields to BookingAudit model 4. New AuditAction types: - SEAT_BOOKED - SEAT_RESCHEDULED - APP actor type 5. New BookingAuditAccessService: - Permission-based access control for audit logs - Added readTeamAuditLogs and readOrgAuditLogs permissions 6. Fixes in the logs viewer flow: - Enhanced BookingAuditViewerService with improved filtering - Local AttendeeRepository for actor enrichment Changes are contained within packages/features/booking-audit with minimal outside changes (permission registry only). Co-Authored-By: [email protected] <[email protected]> * refactor(booking-audit): streamline action handling and enhance localization - Replaced action icon retrieval with a mapping object for improved clarity and performance. - Introduced constants for actor role labels to simplify role retrieval. - Added new localization strings for audit log permission errors and organization requirements. - Updated various service and repository interfaces to enhance type safety and clarity. - Removed deprecated architecture documentation and adjusted related imports for consistency. These changes aim to improve code maintainability and user experience in the booking audit system. * fix(booking-audit): enhance actor role localization and operation ID tracking - Updated actor role labels in the booking logs view to use lowercase for consistency. - Improved localization by wrapping actor role display in a translation function. - Added operationId field to audit logs for better correlation of actions across multiple bookings. - Enhanced BookingAuditViewerService to include operationId in enriched audit logs. - Updated integration tests to verify consistent operationId across related audit logs. These changes aim to improve localization accuracy and facilitate better tracking of user actions in the booking audit system. * feat: integrate credential repository and enhance app actor handling - Added CredentialRepository to manage app credentials, including a method to find credentials by ID. - Updated BookingAudit system to support app actors identified by credential ID, improving actor attribution and audit clarity. - Introduced a new utility function to map app slugs to display names, enhancing the user experience in audit logs. - Modified relevant interfaces and types to accommodate the new credential handling and app actor structure. - Enhanced BookingAuditViewerService to display app names based on credentials, ensuring accurate representation in audit logs. --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
268 lines
11 KiB
TypeScript
268 lines
11 KiB
TypeScript
import { describe, it, expect, beforeEach, vi, type Mock } from "vitest";
|
|
|
|
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
|
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
|
|
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
|
import { MembershipRole } from "@calcom/prisma/enums";
|
|
|
|
import { BookingAuditAccessService, BookingAuditErrorCode, BookingAuditPermissionError } from "../BookingAuditAccessService";
|
|
|
|
vi.mock("@calcom/features/pbac/services/permission-check.service");
|
|
vi.mock("@calcom/features/bookings/repositories/BookingRepository");
|
|
vi.mock("@calcom/features/membership/repositories/MembershipRepository");
|
|
const DB = {
|
|
bookings: {} as Record<string, {
|
|
uid: string;
|
|
userId: number | null;
|
|
eventType: {
|
|
teamId: number | null;
|
|
parent: { teamId: number } | null;
|
|
hosts: never[];
|
|
users: never[];
|
|
};
|
|
user: { id: number; email: string };
|
|
attendees: never[];
|
|
}>,
|
|
memberships: {} as Record<string, boolean>,
|
|
}
|
|
|
|
const createMockTeamBooking = (overrides: {
|
|
bookingUid: string;
|
|
userId?: number;
|
|
teamId?: number | null;
|
|
parentTeamId?: number;
|
|
}) => {
|
|
const booking = {
|
|
uid: overrides.bookingUid,
|
|
userId: overrides?.userId ?? 456,
|
|
eventType: {
|
|
teamId: (overrides && "teamId" in overrides ? overrides.teamId : overrides?.teamId ?? 100) ?? null,
|
|
parent: (overrides?.parentTeamId ? { teamId: overrides.parentTeamId } : undefined) ?? null,
|
|
hosts: [],
|
|
users: []
|
|
},
|
|
user: {
|
|
id: overrides?.userId ?? 456,
|
|
email: "[email protected]",
|
|
},
|
|
attendees: [],
|
|
}
|
|
DB.bookings[booking.uid] = booking;
|
|
return booking;
|
|
}
|
|
|
|
const createMockPersonalBooking = (overrides: { userId?: number; bookingUid: string }) => {
|
|
const booking = {
|
|
uid: overrides.bookingUid,
|
|
userId: overrides?.userId ?? 456,
|
|
eventType: {
|
|
teamId: null,
|
|
parent: null,
|
|
hosts: [],
|
|
users: [],
|
|
},
|
|
attendees: [],
|
|
user: {
|
|
id: overrides?.userId ?? 456,
|
|
email: "[email protected]",
|
|
},
|
|
};
|
|
DB.bookings[booking.uid] = booking;
|
|
return booking;
|
|
}
|
|
|
|
const createMockMembership = ({ userId, teamId }: { userId: number; teamId: number }) => {
|
|
const key = `${userId}-${teamId}`;
|
|
DB.memberships[key] = true;
|
|
};
|
|
|
|
type MockPermissionCheckService = {
|
|
checkPermission: Mock<PermissionCheckService["checkPermission"]>;
|
|
}
|
|
|
|
const provideReadTeamAuditLogsPermission = ({ mockPermissionCheckService, value, targetUserId, targetTeamId }: { mockPermissionCheckService: MockPermissionCheckService, value: boolean, targetUserId: number, targetTeamId: number }) => {
|
|
mockPermissionCheckService.checkPermission.mockImplementation(({ userId, teamId, permission, _fallbackRoles }) => {
|
|
if (permission === "booking.readTeamAuditLogs" && userId === targetUserId && teamId === targetTeamId) {
|
|
return Promise.resolve(value);
|
|
}
|
|
return Promise.resolve(false);
|
|
});
|
|
}
|
|
|
|
const provideReadOrgAuditLogsPermission = ({ mockPermissionCheckService, value, targetUserId, targetTeamId }: { mockPermissionCheckService: MockPermissionCheckService, value: boolean, targetUserId: number, targetTeamId: number }) => {
|
|
mockPermissionCheckService.checkPermission.mockImplementation(({ userId, teamId, permission, _fallbackRoles }) => {
|
|
if (permission === "booking.readOrgAuditLogs" && userId === targetUserId && teamId === targetTeamId) {
|
|
return Promise.resolve(value);
|
|
}
|
|
return Promise.resolve(false);
|
|
});
|
|
}
|
|
|
|
const mockBookingRepository: {
|
|
findByUidIncludeEventType: Mock<BookingRepository["findByUidIncludeEventType"]>;
|
|
} = {
|
|
findByUidIncludeEventType: vi.fn().mockImplementation(({ bookingUid }) => {
|
|
return Promise.resolve(DB.bookings[bookingUid] ?? null);
|
|
}),
|
|
};
|
|
|
|
const mockMembershipRepository: {
|
|
hasMembership: Mock<MembershipRepository["hasMembership"]>;
|
|
} = {
|
|
hasMembership: vi.fn().mockImplementation(({ userId, teamId }) => {
|
|
const key = `${userId}-${teamId}`;
|
|
return Promise.resolve(DB.memberships[key] ?? false);
|
|
}),
|
|
};
|
|
|
|
describe("BookingAuditAccessService - Permission Checks", () => {
|
|
let service: BookingAuditAccessService;
|
|
let mockPermissionCheckService: MockPermissionCheckService;
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
|
|
// Clear in-memory DB
|
|
DB.bookings = {};
|
|
DB.memberships = {};
|
|
|
|
mockPermissionCheckService = {
|
|
checkPermission: vi.fn(),
|
|
};
|
|
|
|
vi.mocked(BookingRepository).mockImplementation(() => mockBookingRepository as unknown as BookingRepository);
|
|
vi.mocked(MembershipRepository).mockImplementation(() => mockMembershipRepository as unknown as MembershipRepository);
|
|
vi.mocked(PermissionCheckService).mockImplementation(() => mockPermissionCheckService as unknown as PermissionCheckService);
|
|
|
|
service = new BookingAuditAccessService({
|
|
bookingRepository: mockBookingRepository as unknown as BookingRepository,
|
|
membershipRepository: mockMembershipRepository as unknown as MembershipRepository,
|
|
});
|
|
});
|
|
|
|
describe("assertPermissions - Team Bookings", () => {
|
|
it("should grant access when user has booking.readTeamAuditLogs permission for the booking's team", async () => {
|
|
const bookingUid = "test-booking-uid";
|
|
const userId = 123;
|
|
const teamId = 100;
|
|
createMockTeamBooking({ teamId, bookingUid });
|
|
provideReadTeamAuditLogsPermission({ mockPermissionCheckService, value: true, targetUserId: userId, targetTeamId: teamId });
|
|
|
|
await expect(service.assertPermissions({ bookingUid, userId, organizationId: 200 })).resolves.not.toThrow();
|
|
});
|
|
|
|
it("should throw PERMISSION_DENIED error when user lacks booking.readTeamAuditLogs permission and also doesn't even have a membership in the organization for the booking's team", async () => {
|
|
const bookingUid = "test-booking-uid";
|
|
const userId = 123;
|
|
const teamId = 100;
|
|
const organizationId = 200;
|
|
createMockTeamBooking({ teamId, bookingUid, userId: 456 });
|
|
createMockMembership({ userId: 456, teamId: organizationId });
|
|
provideReadTeamAuditLogsPermission({ mockPermissionCheckService, value: false, targetUserId: userId, targetTeamId: teamId });
|
|
provideReadOrgAuditLogsPermission({ mockPermissionCheckService, value: false, targetUserId: userId, targetTeamId: organizationId });
|
|
const promise = service.assertPermissions({ bookingUid, userId, organizationId });
|
|
await expect(promise).rejects.toThrow(BookingAuditPermissionError);
|
|
await expect(promise).rejects.toThrow(BookingAuditErrorCode.PERMISSION_DENIED);
|
|
});
|
|
});
|
|
|
|
describe("assertPermissions - Organization Bookings (Personal)", () => {
|
|
it("should grant access to personal bookings when user is an org member and has booking.readOrgAuditLogs permission for the organization", async () => {
|
|
const bookingUid = "test-booking-uid";
|
|
const userId = 123;
|
|
const organizationId = 200;
|
|
createMockPersonalBooking({ userId: 456, bookingUid });
|
|
createMockMembership({ userId: 456, teamId: organizationId });
|
|
provideReadOrgAuditLogsPermission({ mockPermissionCheckService, value: true, targetUserId: userId, targetTeamId: organizationId });
|
|
|
|
await service.assertPermissions({ bookingUid, userId, organizationId });
|
|
|
|
expect(mockPermissionCheckService.checkPermission).toHaveBeenCalledWith({
|
|
userId,
|
|
teamId: organizationId,
|
|
permission: "booking.readOrgAuditLogs",
|
|
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("assertPermissions - Managed Events", () => {
|
|
it("should grant access to managed event's booking when user has booking.readTeamAuditLogs permission on parent event's team", async () => {
|
|
const bookingUid = "test-booking-uid";
|
|
const userId = 123;
|
|
const parentTeamId = 500;
|
|
createMockTeamBooking({ teamId: null, parentTeamId, bookingUid });
|
|
provideReadTeamAuditLogsPermission({ mockPermissionCheckService, value: true, targetUserId: userId, targetTeamId: parentTeamId });
|
|
|
|
await service.assertPermissions({ bookingUid, userId, organizationId: 200 });
|
|
|
|
expect(mockPermissionCheckService.checkPermission).toHaveBeenCalledWith({
|
|
userId,
|
|
teamId: parentTeamId,
|
|
permission: "booking.readTeamAuditLogs",
|
|
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
|
});
|
|
});
|
|
|
|
it("should throw error when user lacks booking.readTeamAuditLogs permission on parent team", async () => {
|
|
const bookingUid = "test-booking-uid";
|
|
const userId = 123;
|
|
const parentTeamId = 500;
|
|
const organizationId = 200;
|
|
createMockTeamBooking({ teamId: null, parentTeamId, bookingUid, userId: 456 });
|
|
createMockMembership({ userId: 456, teamId: organizationId });
|
|
provideReadTeamAuditLogsPermission({ mockPermissionCheckService, value: false, targetUserId: userId, targetTeamId: parentTeamId });
|
|
provideReadOrgAuditLogsPermission({ mockPermissionCheckService, value: false, targetUserId: userId, targetTeamId: organizationId });
|
|
|
|
await expect(service.assertPermissions({ bookingUid, userId, organizationId })).rejects.toThrow(BookingAuditPermissionError);
|
|
});
|
|
});
|
|
|
|
describe("assertPermissions - Edge Cases", () => {
|
|
it("should throw error when organizationId is null", async () => {
|
|
await expect(service.assertPermissions({ bookingUid: "test-booking-uid", userId: 123, organizationId: null })).rejects.toThrow(BookingAuditPermissionError);
|
|
await expect(service.assertPermissions({ bookingUid: "test-booking-uid", userId: 123, organizationId: null })).rejects.toThrow(BookingAuditErrorCode.ORGANIZATION_ID_REQUIRED);
|
|
});
|
|
|
|
it("should throw error when booking not found", async () => {
|
|
const bookingUid = "non-existent-booking-uid";
|
|
// Don't create any booking in DB
|
|
|
|
await expect(service.assertPermissions({ bookingUid, userId: 123, organizationId: 200 })).rejects.toThrow(BookingAuditPermissionError);
|
|
await expect(service.assertPermissions({ bookingUid, userId: 123, organizationId: 200 })).rejects.toThrow(BookingAuditErrorCode.BOOKING_NOT_FOUND_OR_PERMISSION_DENIED);
|
|
});
|
|
|
|
it("should throw error when booking has no userId", async () => {
|
|
const bookingUid = "test-booking-uid";
|
|
const booking = {
|
|
uid: bookingUid,
|
|
userId: null,
|
|
eventType: {
|
|
teamId: null,
|
|
parent: null,
|
|
hosts: [],
|
|
users: [],
|
|
},
|
|
attendees: [],
|
|
user: {
|
|
id: 456,
|
|
email: "[email protected]",
|
|
},
|
|
};
|
|
DB.bookings[bookingUid] = booking;
|
|
|
|
await expect(service.assertPermissions({ bookingUid, userId: 123, organizationId: 200 })).rejects.toThrow(BookingAuditPermissionError);
|
|
await expect(service.assertPermissions({ bookingUid, userId: 123, organizationId: 200 })).rejects.toThrow(BookingAuditErrorCode.BOOKING_HAS_NO_OWNER);
|
|
});
|
|
|
|
it("should throw error when booking owner is not member of organization", async () => {
|
|
const bookingUid = "test-booking-uid";
|
|
createMockPersonalBooking({ userId: 456, bookingUid });
|
|
// Don't create membership for userId 456 in organization 200
|
|
|
|
await expect(service.assertPermissions({ bookingUid, userId: 123, organizationId: 200 })).rejects.toThrow(BookingAuditPermissionError);
|
|
await expect(service.assertPermissions({ bookingUid, userId: 123, organizationId: 200 })).rejects.toThrow(BookingAuditErrorCode.OWNER_NOT_IN_ORGANIZATION);
|
|
});
|
|
});
|
|
});
|