Scheduling infrastructure for absolutely everyone.
refactor: forbidden 403 v2 guard messages (#20794)
Lauris Skraucis7f02464fedec
diff --git a/apps/api/v2/README.md b/apps/api/v2/README.mdindex f8206c0d212..dbb5cc135e6 100644--- a/apps/api/v2/README.md+++ b/apps/api/v2/README.md@@ -107,6 +107,12 @@ $ yarn test:e2e:watch --testPathPattern=filePath$ yarn run test:cov```+## Conventions++### Guards+1. In case a guard would return "false" for "canActivate" instead throw ForbiddenException with an error message containing guard name and the error.+2. In case a guard would return "false" for "canActivate" DO NOT cache the result in redis, because we don't want that someone is forbidden, updates whatever was the problem, and then has to wait for cache to expire. We only cache in redis guard results where "canAccess" is "true".+## SupportNest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/guards/booking-uid.guard.ts b/apps/api/v2/src/ee/bookings/2024-08-13/guards/booking-uid.guard.tsindex 05d508a4fb3..bdea73fb6a9 100644--- a/apps/api/v2/src/ee/bookings/2024-08-13/guards/booking-uid.guard.ts+++ b/apps/api/v2/src/ee/bookings/2024-08-13/guards/booking-uid.guard.ts@@ -8,7 +8,7 @@ export class BookingUidGuard implements CanActivate {const bookingUid = request.params.bookingUid;if (!bookingUid) {- throw new BadRequestException("Booking UID missing in the request path");+ throw new BadRequestException("BookingUidGuard - Booking UID missing in the request path");}return true;diff --git a/apps/api/v2/src/ee/me/me.module.ts b/apps/api/v2/src/ee/me/me.module.tsindex 1ee07742cf4..d762faba777 100644--- a/apps/api/v2/src/ee/me/me.module.ts+++ b/apps/api/v2/src/ee/me/me.module.ts@@ -1,11 +1,12 @@import { MeController } from "@/ee/me/me.controller";import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";+import { OAuthClientModule } from "@/modules/oauth-clients/oauth-client.module";import { TokensModule } from "@/modules/tokens/tokens.module";import { UsersModule } from "@/modules/users/users.module";import { Module } from "@nestjs/common";@Module({- imports: [UsersModule, SchedulesModule_2024_04_15, TokensModule],+ imports: [UsersModule, SchedulesModule_2024_04_15, TokensModule, OAuthClientModule],controllers: [MeController],})export class MeModule {}diff --git a/apps/api/v2/src/lib/throttler-guard.ts b/apps/api/v2/src/lib/throttler-guard.tsindex f9979ff44c2..66aad5cf3bf 100644--- a/apps/api/v2/src/lib/throttler-guard.ts+++ b/apps/api/v2/src/lib/throttler-guard.ts@@ -82,7 +82,7 @@ export class CustomThrottlerGuard extends ThrottlerGuard {}if (allLimitsBlocked) {- throw new ThrottlerException("Too many requests. Please try again later.");+ throw new ThrottlerException("CustomThrottlerGuard - Too many requests. Please try again later.");}return true;@@ -96,7 +96,7 @@ export class CustomThrottlerGuard extends ThrottlerGuard {const { isBlocked } = await this.incrementRateLimit(tracker, rateLimit, response);if (isBlocked) {- throw new ThrottlerException("Too many requests. Please try again later.");+ throw new ThrottlerException("CustomThrottlerGuard - Too many requests. Please try again later.");}return true;@@ -150,7 +150,7 @@ export class CustomThrottlerGuard extends ThrottlerGuard {});if (!apiKeyRecord) {- throw new UnauthorizedException("Invalid API Key");+ throw new UnauthorizedException("CustomThrottlerGuard - Invalid API Key");}rateLimits = await this.dbRead.prisma.rateLimit.findMany({diff --git a/apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.spec.ts b/apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.spec.tsindex 93c67ee001c..33017e44371 100644--- a/apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.spec.ts+++ b/apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.spec.ts@@ -104,13 +104,6 @@ describe("PlatformPlanGuard", () => {await expect(guard.canActivate(mockContext)).resolves.toBe(true);});- it("should throw ForbiddenException if the result is cached as false in Redis", async () => {- jest.spyOn(reflector, "get").mockReturnValue("ESSENTIALS");- jest.spyOn(redisService.redis, "get").mockResolvedValue(JSON.stringify(false));-- await expect(guard.canActivate(mockContext)).rejects.toThrow(ForbiddenException);- });-function createMockExecutionContext(context: Record<string, string | object>): ExecutionContext {return createMock<ExecutionContext>({switchToHttp: () => ({diff --git a/apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.ts b/apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.tsindex 61faa42521b..db162eabcfb 100644--- a/apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.ts@@ -16,65 +16,63 @@ export class PlatformPlanGuard implements CanActivate {) {}async canActivate(context: ExecutionContext): Promise<boolean> {- const request = context.switchToHttp().getRequest<Request>();- const teamId = request.params.teamId as string;- const orgId = request.params.orgId as string;- const user = request.user as ApiAuthGuardUser;const minimumPlan = this.reflector.get(PlatformPlan, context.getHandler()) as PlatformPlanType;- const { canAccess } = await this.checkPlatformPlanAccess({ teamId, orgId, user, minimumPlan });- return canAccess;- }+ if (!minimumPlan) {+ return true;+ }- async checkPlatformPlanAccess({- teamId,- orgId,- user,- minimumPlan,- }: {- teamId?: string;- orgId?: string;- user: ApiAuthGuardUser;- minimumPlan: PlatformPlanType;- }): Promise<{ canAccess: boolean }> {- const REDIS_CACHE_KEY = `apiv2:user:${user?.id ?? "none"}:org:${orgId ?? "none"}:team:${- teamId ?? "none"- }:guard:platformbilling:${minimumPlan}`;+ const request = context.switchToHttp().getRequest<Request>();+ const orgId = request.params.orgId;+ const user = request.user as ApiAuthGuardUser;+ if (!user) {+ throw new ForbiddenException("PlatformPlanGuard - No user associated with the request.");+ }+ if (!orgId) {+ throw new ForbiddenException("PlatformPlanGuard - No organization associated with the request.");+ }- const cachedAccess = JSON.parse((await this.redisService.redis.get(REDIS_CACHE_KEY)) ?? "false");+ return await this.checkPlatformPlanAccess(orgId, minimumPlan);+ }- if (cachedAccess) {- return { canAccess: cachedAccess };+ async checkPlatformPlanAccess(orgId: string, minimumPlan: PlatformPlanType) {+ const REDIS_CACHE_KEY = `apiv2:org:${orgId}:guard:platformbilling:${minimumPlan}`;+ const cachedValue = await this.redisService.redis.get(REDIS_CACHE_KEY);+ if (cachedValue !== null) {+ return cachedValue === "true";}- let canAccess = false;-- if (user && orgId) {- const team = await this.organizationsRepository.findByIdIncludeBilling(Number(orgId));- const isPlatform = team?.isPlatform;- const hasSubscription = team?.platformBilling?.subscriptionId;+ const organization = await this.organizationsRepository.findByIdIncludeBilling(Number(orgId));+ const isPlatform = organization?.isPlatform;+ const hasSubscription = organization?.platformBilling?.subscriptionId;- if (!team) {- canAccess = false;- } else if (!isPlatform) {- canAccess = true;- } else if (!hasSubscription) {- canAccess = false;- } else {- canAccess = hasMinimumPlan({- currentPlan: team.platformBilling?.plan as PlatformPlanType,- minimumPlan: minimumPlan,- plans: ["FREE", "STARTER", "ESSENTIALS", "SCALE", "ENTERPRISE"],- });- }+ if (!organization) {+ throw new ForbiddenException(`PlatformPlanGuard - No organization found with id=${orgId}.`);}-- await this.redisService.redis.set(REDIS_CACHE_KEY, String(canAccess), "EX", 300);- if (canAccess) {- return { canAccess };+ if (!isPlatform) {+ await this.redisService.redis.set(REDIS_CACHE_KEY, "true", "EX", 300);+ return true;}- throw new ForbiddenException(- `Platform plan - you do not have required plan for this operation. Minimum plan is ${minimumPlan}.`- );+ if (!hasSubscription) {+ throw new ForbiddenException(+ `PlatformPlanGuard - No platform subscription found for organization with id=${orgId}.`+ );+ }+ if (+ !hasMinimumPlan({+ currentPlan: organization.platformBilling?.plan as PlatformPlanType,+ minimumPlan: minimumPlan,+ plans: ["FREE", "STARTER", "ESSENTIALS", "SCALE", "ENTERPRISE"],+ })+ ) {+ throw new ForbiddenException(+ `PlatformPlanGuard - organization with id=${orgId} does not have required plan for this operation. Minimum plan is ${minimumPlan} while the organization has ${+ organization.platformBilling?.plan || "undefined"+ }.`+ );+ }++ await this.redisService.redis.set(REDIS_CACHE_KEY, "true", "EX", 300);+ return true;}}@@ -90,7 +88,7 @@ export function hasMinimumPlan(props: HasMinimumPlanProp): boolean {if (currentPlanIndex === -1 || minimumPlanIndex === -1) {throw new Error(- `Invalid platform billing plan provided. Current plan: ${props.currentPlan}, Minimum plan: ${props.minimumPlan}`+ `PlatformPlanGuard - Invalid platform billing plan provided. Current plan: ${props.currentPlan}, Minimum plan: ${props.minimumPlan}`);}diff --git a/apps/api/v2/src/modules/auth/guards/memberships/is-membership-in-org.guard.ts b/apps/api/v2/src/modules/auth/guards/memberships/is-membership-in-org.guard.tsindex 75fca8654d8..f90e2a01e2d 100644--- a/apps/api/v2/src/modules/auth/guards/memberships/is-membership-in-org.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/memberships/is-membership-in-org.guard.ts@@ -20,11 +20,11 @@ export class IsMembershipInOrg implements CanActivate {const orgId: string = request.params.orgId;if (!orgId) {- throw new ForbiddenException("No org id found in request params.");+ throw new ForbiddenException("IsMembershipInOrg - No org id found in request params.");}if (!membershipId) {- throw new ForbiddenException("No membership id found in request params.");+ throw new ForbiddenException("IsMembershipInOrg - No membership id found in request params.");}const membership = await this.organizationsMembershipRepository.findOrgMembership(@@ -33,7 +33,7 @@ export class IsMembershipInOrg implements CanActivate {);if (!membership) {- throw new NotFoundException(`Membership (${membershipId}) not found.`);+ throw new NotFoundException(`IsMembershipInOrg - Membership (${membershipId}) not found.`);}request.membership = membership;diff --git a/apps/api/v2/src/modules/auth/guards/optional-api-auth/optional-api-auth.guard.ts b/apps/api/v2/src/modules/auth/guards/optional-api-auth/optional-api-auth.guard.tsindex 3e03924bd6d..dd22e1f9606 100644--- a/apps/api/v2/src/modules/auth/guards/optional-api-auth/optional-api-auth.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/optional-api-auth/optional-api-auth.guard.ts@@ -4,7 +4,7 @@ import { NO_AUTH_PROVIDED_MESSAGE } from "@/modules/auth/strategies/api-auth/apiexport class OptionalApiAuthGuard extends ApiAuthGuard {handleRequest(error: Error, user: any) {// note(Lauris): optional means that auth is not required but if it is invalid then still throw error.- const noAuthProvided = error && error.message === NO_AUTH_PROVIDED_MESSAGE;+ const noAuthProvided = error && error.message.includes(NO_AUTH_PROVIDED_MESSAGE);if (user || noAuthProvided || !error) {return user || null;} else {diff --git a/apps/api/v2/src/modules/auth/guards/organizations/is-admin-api-enabled.guard.ts b/apps/api/v2/src/modules/auth/guards/organizations/is-admin-api-enabled.guard.tsindex 9789522c4b8..7efa0b32d55 100644--- a/apps/api/v2/src/modules/auth/guards/organizations/is-admin-api-enabled.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/organizations/is-admin-api-enabled.guard.ts@@ -22,14 +22,19 @@ export class IsAdminAPIEnabledGuard implements CanActivate {const organizationId: string = request.params.orgId;if (!organizationId) {- throw new ForbiddenException("No organization id found in request params.");+ throw new ForbiddenException("IsAdminAPIEnabledGuard - No organization id found in request params.");}const { canAccess, organization } = await this.checkAdminAPIEnabled(organizationId);if (organization) {request.organization = organization;}- return canAccess;+ if (!canAccess) {+ throw new ForbiddenException(+ `IsAdminAPIEnabledGuard - Organization with id=${organizationId} does not have Admin API access. Please contact https://cal.com/sales to upgrade.`+ );+ }+ return true;}async checkAdminAPIEnabled(@@ -57,18 +62,21 @@ export class IsAdminAPIEnabledGuard implements CanActivate {);if (!adminAPIAccessIsEnabledInOrg) {throw new ForbiddenException(- `Organization does not have Admin API access, please contact https://cal.com/sales to upgrade`+ `IsAdminAPIEnabledGuard - Organization does not have Admin API access, please contact https://cal.com/sales to upgrade`);}}canAccess = true;- org &&- (await this.redisService.redis.set(++ if (org && canAccess) {+ await this.redisService.redis.set(REDIS_CACHE_KEY,JSON.stringify({ org: org, canAccess } satisfies CachedData),"EX",300- ));+ );+ }+return { canAccess, organization: org };}}diff --git a/apps/api/v2/src/modules/auth/guards/organizations/is-managed-org-in-manager-org.guard.ts b/apps/api/v2/src/modules/auth/guards/organizations/is-managed-org-in-manager-org.guard.tsindex 9ac6c8cce18..5052d3dcbb8 100644--- a/apps/api/v2/src/modules/auth/guards/organizations/is-managed-org-in-manager-org.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/organizations/is-managed-org-in-manager-org.guard.ts@@ -1,11 +1,5 @@import { ManagedOrganizationsRepository } from "@/modules/organizations/organizations/managed-organizations.repository";-import {- Injectable,- CanActivate,- ExecutionContext,- ForbiddenException,- NotFoundException,-} from "@nestjs/common";+import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";import { Request } from "express";import { Team } from "@calcom/prisma/client";@@ -20,11 +14,11 @@ export class IsManagedOrgInManagerOrg implements CanActivate {const managerOrgId: string = request.params.orgId;if (!managerOrgId) {- throw new ForbiddenException("No manager org id found in request params.");+ throw new ForbiddenException("IsManagedOrgInManagerOrg - No manager org id found in request params.");}if (!managedOrgId) {- throw new ForbiddenException("No managed org id found in request params.");+ throw new ForbiddenException("IsManagedOrgInManagerOrg - No managed org id found in request params.");}const managedOrganization = await this.managedOrganizationsRepository.getByManagerManagedIds(@@ -33,8 +27,8 @@ export class IsManagedOrgInManagerOrg implements CanActivate {);if (!managedOrganization) {- throw new NotFoundException(- `Managed organization with id=${managedOrgId} within manager organization with id=${managerOrgId} not found.`+ throw new ForbiddenException(+ `IsManagedOrgInManagerOrg - Managed organization with id=${managedOrgId} is not owned by manager organization with id=${managerOrgId}.`);}diff --git a/apps/api/v2/src/modules/auth/guards/organizations/is-org.guard.ts b/apps/api/v2/src/modules/auth/guards/organizations/is-org.guard.tsindex 08a25dca3d8..fb161d708ca 100644--- a/apps/api/v2/src/modules/auth/guards/organizations/is-org.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/organizations/is-org.guard.ts@@ -22,7 +22,7 @@ export class IsOrgGuard implements CanActivate {const organizationId: string = request.params.orgId;if (!organizationId) {- throw new ForbiddenException("No organization id found in request params.");+ throw new ForbiddenException("IsOrgGuard - No organization id found in request params.");}const { canAccess, org } = await this.checkOrgAccess(organizationId);@@ -31,7 +31,13 @@ export class IsOrgGuard implements CanActivate {request.organization = org;}- return canAccess;+ if (!canAccess) {+ throw new ForbiddenException(+ `IsOrgGuard - provided organization id=${organizationId} does not represent any existing organization.`+ );+ }++ return true;}async checkOrgAccess(organizationId: string): Promise<{ canAccess: boolean; org?: Team | null }> {@@ -55,7 +61,7 @@ export class IsOrgGuard implements CanActivate {canAccess = true;}- if (org) {+ if (org && canAccess) {await this.redisService.redis.set(REDIS_CACHE_KEY,JSON.stringify({ org, canAccess } satisfies CachedData),diff --git a/apps/api/v2/src/modules/auth/guards/organizations/is-webhook-in-org.guard.ts b/apps/api/v2/src/modules/auth/guards/organizations/is-webhook-in-org.guard.tsindex 5505c8fed1a..eef472ac1f1 100644--- a/apps/api/v2/src/modules/auth/guards/organizations/is-webhook-in-org.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/organizations/is-webhook-in-org.guard.ts@@ -26,10 +26,10 @@ export class IsWebhookInOrg implements CanActivate {const organizationId: string = request.params.orgId;if (!organizationId) {- throw new ForbiddenException("No organization id found in request params.");+ throw new ForbiddenException("IsWebhookInOrg - No organization id found in request params.");}if (!webhookId) {- throw new ForbiddenException("No webhook id found in request params.");+ throw new ForbiddenException("IsWebhookInOrg - No webhook id found in request params.");}const REDIS_CACHE_KEY = `apiv2:org:${webhookId}:guard:isWebhookInOrg`;@@ -53,7 +53,7 @@ export class IsWebhookInOrg implements CanActivate {if (isWebhookInOrg) canAccess = true;}- if (org) {+ if (org && canAccess) {await this.redisService.redis.set(REDIS_CACHE_KEY,JSON.stringify({ org: org, canAccess } satisfies CachedData),@@ -62,6 +62,12 @@ export class IsWebhookInOrg implements CanActivate {);}- return canAccess;+ if (!canAccess) {+ throw new ForbiddenException(+ `IsWebhookInOrg - webhook with id=${webhookId} is not part of the organization with id=${organizationId}.`+ );+ }++ return true;}}diff --git a/apps/api/v2/src/modules/auth/guards/permissions/permissions.guard.spec.ts b/apps/api/v2/src/modules/auth/guards/permissions/permissions.guard.spec.tsindex 116721308fc..3f1f6f0bcdf 100644--- a/apps/api/v2/src/modules/auth/guards/permissions/permissions.guard.spec.ts+++ b/apps/api/v2/src/modules/auth/guards/permissions/permissions.guard.spec.ts@@ -1,4 +1,5 @@import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";+import { OAuthClientsOutputService } from "@/modules/oauth-clients/services/oauth-clients/oauth-clients-output.service";import { TokensRepository } from "@/modules/tokens/tokens.repository";import { createMock } from "@golevelup/ts-jest";import { ExecutionContext } from "@nestjs/common";@@ -28,7 +29,21 @@ describe("PermissionsGuard", () => {}}),}),- createMock<OAuthClientRepository>()+ createMock<OAuthClientRepository>(),+ createMock<OAuthClientsOutputService>({+ transformOAuthClientPermission: jest.fn().mockImplementation((permission: number) => {+ switch (permission) {+ case SCHEDULE_WRITE:+ return "SCHEDULE_WRITE";+ case SCHEDULE_READ:+ return "SCHEDULE_READ";+ case APPS_WRITE:+ return "APPS_WRITE";+ default:+ return "UNKNOWN";+ }+ }),+ }));});@@ -36,13 +51,22 @@ describe("PermissionsGuard", () => {expect(guard).toBeDefined();});+ function getMockOAuthClient(permissions: number) {+ return {+ id: "100",+ permissions,+ };+ }+describe("when access token is missing", () => {it("should return false", async () => {const mockContext = createMockExecutionContext({});jest.spyOn(reflector, "get").mockReturnValue([SCHEDULE_WRITE]);- jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(0);+ jest.spyOn(guard, "getOAuthClientByAccessToken").mockResolvedValue(getMockOAuthClient(0));- await expect(guard.canActivate(mockContext)).resolves.toBe(false);+ await expect(guard.canActivate(mockContext)).rejects.toThrow(+ "PermissionsGuard - no authentication provided. Provide either authorization bearer token containing managed user access token or oAuth client id in 'x-cal-client-id' header."+ );});});@@ -53,7 +77,9 @@ describe("PermissionsGuard", () => {let oAuthClientPermissions = 0;oAuthClientPermissions |= SCHEDULE_WRITE;- jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(oAuthClientPermissions);+ jest+ .spyOn(guard, "getOAuthClientByAccessToken")+ .mockResolvedValue(getMockOAuthClient(oAuthClientPermissions));await expect(guard.canActivate(mockContext)).resolves.toBe(true);});@@ -64,7 +90,9 @@ describe("PermissionsGuard", () => {let oAuthClientPermissions = 0;oAuthClientPermissions |= SCHEDULE_WRITE;oAuthClientPermissions |= SCHEDULE_READ;- jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(oAuthClientPermissions);+ jest+ .spyOn(guard, "getOAuthClientByAccessToken")+ .mockResolvedValue(getMockOAuthClient(oAuthClientPermissions));await expect(guard.canActivate(mockContext)).resolves.toBe(true);});@@ -75,7 +103,9 @@ describe("PermissionsGuard", () => {let oAuthClientPermissions = 0;oAuthClientPermissions |= SCHEDULE_WRITE;- jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(oAuthClientPermissions);+ jest+ .spyOn(guard, "getOAuthClientByAccessToken")+ .mockResolvedValue(getMockOAuthClient(oAuthClientPermissions));await expect(guard.canActivate(mockContext)).resolves.toBe(true);});@@ -85,9 +115,13 @@ describe("PermissionsGuard", () => {let oAuthClientPermissions = 0;oAuthClientPermissions |= APPS_WRITE;- jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(oAuthClientPermissions);+ jest+ .spyOn(guard, "getOAuthClientByAccessToken")+ .mockResolvedValue(getMockOAuthClient(oAuthClientPermissions));- await expect(guard.canActivate(mockContext)).resolves.toBe(false);+ await expect(guard.canActivate(mockContext)).rejects.toThrow(+ "PermissionsGuard - oAuth client with id=100 does not have the required permissions=SCHEDULE_WRITE"+ );});it("should return false for a missing permission", async () => {@@ -96,9 +130,13 @@ describe("PermissionsGuard", () => {let oAuthClientPermissions = 0;oAuthClientPermissions |= SCHEDULE_WRITE;- jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(oAuthClientPermissions);+ jest+ .spyOn(guard, "getOAuthClientByAccessToken")+ .mockResolvedValue(getMockOAuthClient(oAuthClientPermissions));- await expect(guard.canActivate(mockContext)).resolves.toBe(false);+ await expect(guard.canActivate(mockContext)).rejects.toThrow(+ "PermissionsGuard - oAuth client with id=100 does not have the required permissions=SCHEDULE_WRITE, SCHEDULE_READ"+ );});});@@ -109,7 +147,7 @@ describe("PermissionsGuard", () => {let oAuthClientPermissions = 0;oAuthClientPermissions |= SCHEDULE_WRITE;- jest.spyOn(guard, "getOAuthClientPermissionsById").mockResolvedValue(oAuthClientPermissions);+ jest.spyOn(guard, "getOAuthClientById").mockResolvedValue(getMockOAuthClient(oAuthClientPermissions));await expect(guard.canActivate(mockContext)).resolves.toBe(true);});@@ -120,7 +158,7 @@ describe("PermissionsGuard", () => {let oAuthClientPermissions = 0;oAuthClientPermissions |= SCHEDULE_WRITE;oAuthClientPermissions |= SCHEDULE_READ;- jest.spyOn(guard, "getOAuthClientPermissionsById").mockResolvedValue(oAuthClientPermissions);+ jest.spyOn(guard, "getOAuthClientById").mockResolvedValue(getMockOAuthClient(oAuthClientPermissions));await expect(guard.canActivate(mockContext)).resolves.toBe(true);});@@ -131,7 +169,7 @@ describe("PermissionsGuard", () => {let oAuthClientPermissions = 0;oAuthClientPermissions |= SCHEDULE_WRITE;- jest.spyOn(guard, "getOAuthClientPermissionsById").mockResolvedValue(oAuthClientPermissions);+ jest.spyOn(guard, "getOAuthClientById").mockResolvedValue(getMockOAuthClient(oAuthClientPermissions));await expect(guard.canActivate(mockContext)).resolves.toBe(true);});@@ -141,9 +179,11 @@ describe("PermissionsGuard", () => {let oAuthClientPermissions = 0;oAuthClientPermissions |= APPS_WRITE;- jest.spyOn(guard, "getOAuthClientPermissionsById").mockResolvedValue(oAuthClientPermissions);+ jest.spyOn(guard, "getOAuthClientById").mockResolvedValue(getMockOAuthClient(oAuthClientPermissions));- await expect(guard.canActivate(mockContext)).resolves.toBe(false);+ await expect(guard.canActivate(mockContext)).rejects.toThrow(+ "PermissionsGuard - oAuth client with id=100 does not have the required permissions=SCHEDULE_WRITE"+ );});it("should return false for a missing permission", async () => {@@ -152,9 +192,11 @@ describe("PermissionsGuard", () => {let oAuthClientPermissions = 0;oAuthClientPermissions |= SCHEDULE_WRITE;- jest.spyOn(guard, "getOAuthClientPermissionsById").mockResolvedValue(oAuthClientPermissions);+ jest.spyOn(guard, "getOAuthClientById").mockResolvedValue(getMockOAuthClient(oAuthClientPermissions));- await expect(guard.canActivate(mockContext)).resolves.toBe(false);+ await expect(guard.canActivate(mockContext)).rejects.toThrow(+ "PermissionsGuard - oAuth client with id=100 does not have the required permissions=SCHEDULE_WRITE, SCHEDULE_READ"+ );});});diff --git a/apps/api/v2/src/modules/auth/guards/permissions/permissions.guard.ts b/apps/api/v2/src/modules/auth/guards/permissions/permissions.guard.tsindex 176bab52a8b..28c6710909b 100644--- a/apps/api/v2/src/modules/auth/guards/permissions/permissions.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/permissions/permissions.guard.ts@@ -1,14 +1,16 @@import { isApiKey } from "@/lib/api-key";import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";+import { OAuthClientsOutputService } from "@/modules/oauth-clients/services/oauth-clients/oauth-clients-output.service";import { TokensRepository } from "@/modules/tokens/tokens.repository";-import { Injectable, CanActivate, ExecutionContext } from "@nestjs/common";+import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";import { ConfigService } from "@nestjs/config";import { Reflector } from "@nestjs/core";import { getToken } from "next-auth/jwt";import { X_CAL_CLIENT_ID } from "@calcom/platform-constants";import { hasPermissions } from "@calcom/platform-utils";+import { PlatformOAuthClient } from "@calcom/prisma/client";@Injectable()export class PermissionsGuard implements CanActivate {@@ -16,7 +18,8 @@ export class PermissionsGuard implements CanActivate {private reflector: Reflector,private tokensRepository: TokensRepository,private readonly config: ConfigService,- private readonly oAuthClientRepository: OAuthClientRepository+ private readonly oAuthClientRepository: OAuthClientRepository,+ private readonly oAuthClientsOutputService: OAuthClientsOutputService) {}async canActivate(context: ExecutionContext): Promise<boolean> {@@ -27,42 +30,61 @@ export class PermissionsGuard implements CanActivate {}const request = context.switchToHttp().getRequest();- const authString = request.get("Authorization")?.replace("Bearer ", "");+ const bearerToken = request.get("Authorization")?.replace("Bearer ", "");const nextAuthSecret = this.config.get("next.authSecret", { infer: true });const nextAuthToken = await getToken({ req: request, secret: nextAuthSecret });const oAuthClientId = request.params?.clientId || request.get(X_CAL_CLIENT_ID);+ const apiKey = bearerToken && isApiKey(bearerToken, this.config.get("api.apiKeyPrefix") ?? "cal_");- if (nextAuthToken) {+ // only check permissions for accessTokens attached to an oAuth Client or oAuth credentials, not for next token or api key+ if (nextAuthToken || apiKey) {return true;}- if (!authString && !oAuthClientId) {- return false;+ if (!bearerToken && !oAuthClientId) {+ throw new ForbiddenException(+ "PermissionsGuard - no authentication provided. Provide either authorization bearer token containing managed user access token or oAuth client id in 'x-cal-client-id' header."+ );}- // only check permissions for accessTokens attached to an oAuth Client- if (isApiKey(authString, this.config.get("api.apiKeyPrefix") ?? "cal_")) {- return true;- }+ const oAuthClient = bearerToken+ ? await this.getOAuthClientByAccessToken(bearerToken)+ : await this.getOAuthClientById(oAuthClientId);- const oAuthClientPermissions = authString- ? await this.getOAuthClientPermissionsByAccessToken(authString)- : await this.getOAuthClientPermissionsById(oAuthClientId);+ const hasRequiredPermissions = hasPermissions(oAuthClient.permissions, [...requiredPermissions]);- if (!oAuthClientPermissions) {- return false;+ if (!hasRequiredPermissions) {+ throw new ForbiddenException(+ `PermissionsGuard - oAuth client with id=${+ oAuthClient.id+ } does not have the required permissions=${requiredPermissions+ .map((permission) => this.oAuthClientsOutputService.transformOAuthClientPermission(permission))+ .join(+ ", "+ )}. Go to platform dashboard settings and add the required permissions to the oAuth client.`+ );}- return hasPermissions(oAuthClientPermissions, [...requiredPermissions]);+ return true;}- async getOAuthClientPermissionsByAccessToken(accessToken: string) {+ async getOAuthClientByAccessToken(+ accessToken: string+ ): Promise<Pick<PlatformOAuthClient, "id" | "permissions">> {const oAuthClient = await this.tokensRepository.getAccessTokenClient(accessToken);- return oAuthClient?.permissions;+ if (!oAuthClient) {+ throw new ForbiddenException(+ `PermissionsGuard - no oAuth client found for access token=${accessToken}`+ );+ }+ return oAuthClient;}- async getOAuthClientPermissionsById(id: string) {+ async getOAuthClientById(id: string): Promise<Pick<PlatformOAuthClient, "id" | "permissions">> {const oAuthClient = await this.oAuthClientRepository.getOAuthClient(id);- return oAuthClient?.permissions;+ if (!oAuthClient) {+ throw new ForbiddenException(`PermissionsGuard - no oAuth client found for client id=${id}`);+ }+ return oAuthClient;}}diff --git a/apps/api/v2/src/modules/auth/guards/roles/roles.guard.ts b/apps/api/v2/src/modules/auth/guards/roles/roles.guard.tsindex 0ecdb35f41b..d3c1f5b3a89 100644--- a/apps/api/v2/src/modules/auth/guards/roles/roles.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/roles/roles.guard.ts@@ -25,8 +25,27 @@ export class RolesGuard implements CanActivate {const user = request.user as ApiAuthGuardUser;const allowedRole = this.reflector.get(Roles, context.getHandler());const { canAccess } = await this.checkUserRoleAccess(user, orgId, teamId, allowedRole);- return canAccess;++ if (!canAccess) {+ this.throwForbiddenError(user, orgId, teamId, allowedRole);+ }++ return true;+ }++ throwForbiddenError(user: ApiAuthGuardUser, orgId: string, teamId: string, allowedRole: string) {+ let errorMessage = `RolesGuard - user with id=${user.id} does not have the minimum required role=${allowedRole} within`;+ if (orgId) {+ errorMessage += ` organization with id=${orgId}`;+ }+ if (teamId) {+ errorMessage += ` team with id=${teamId}`;+ }+ errorMessage += `.`;++ throw new ForbiddenException(errorMessage);}+async checkUserRoleAccess(user: ApiAuthGuardUser,orgId: string,@@ -67,7 +86,9 @@ export class RolesGuard implements CanActivate {const membership = await this.membershipRepository.findMembershipByOrgId(Number(orgId), user.id);if (!membership) {this.logger.log(`User (${user.id}) is not a member of the organization (${orgId}), denying access.`);- throw new ForbiddenException(`User is not a member of the organization.`);+ throw new ForbiddenException(+ `RolesGuard - User is not a member of the organization with id=${orgId}.`+ );}if (ORG_ROLES.includes(allowedRole as unknown as (typeof ORG_ROLES)[number])) {@@ -84,7 +105,7 @@ export class RolesGuard implements CanActivate {const membership = await this.membershipRepository.findMembershipByTeamId(Number(teamId), user.id);if (!membership) {this.logger.log(`User (${user.id}) is not a member of the team (${teamId}), denying access.`);- throw new ForbiddenException(`User is not a member of the team.`);+ throw new ForbiddenException(`RolesGuard - User is not a member of the team with id=${teamId}.`);}if (TEAM_ROLES.includes(allowedRole as unknown as (typeof TEAM_ROLES)[number])) {canAccess = hasMinimumRole({@@ -102,7 +123,7 @@ export class RolesGuard implements CanActivate {if (!orgMembership) {this.logger.log(`User (${user.id}) is not part of the organization (${orgId}), denying access.`);- throw new ForbiddenException(`User is not part of the organization.`);+ throw new ForbiddenException(`RolesGuard - User is not part of the organization with id=${orgId}.`);}// if the role checked is a TEAM role@@ -116,7 +137,7 @@ export class RolesGuard implements CanActivate {`User (${user.id}) is not part of the team (${teamId}) and/or, is not an admin nor an owner of the organization (${orgId}).`);throw new ForbiddenException(- "User is not part of the team and/or, is not an admin nor an owner of the organization."+ `RolesGuard - User is not part of the team with id=${teamId} and/or, is not an admin nor an owner of the organization with id=${orgId}.`);}@@ -138,7 +159,11 @@ export class RolesGuard implements CanActivate {});}}- await this.redisService.redis.set(REDIS_CACHE_KEY, String(canAccess), "EX", 300);++ if (canAccess) {+ await this.redisService.redis.set(REDIS_CACHE_KEY, String(canAccess), "EX", 300);+ }+return { canAccess };}}@@ -165,7 +190,7 @@ export function hasMinimumRole(props: HasMinimumRoleProp): boolean {// minimum role given does not existif (checkedRoleIndex === -1 || requiredRoleIndex === -1) {- throw new Error("Invalid role");+ throw new Error("RolesGuard - Invalid role");}return checkedRoleIndex <= requiredRoleIndex;diff --git a/apps/api/v2/src/modules/auth/guards/routing-forms/is-routing-form-in-team.guard.ts b/apps/api/v2/src/modules/auth/guards/routing-forms/is-routing-form-in-team.guard.tsindex 5dc2ab93e68..5cdd9920877 100644--- a/apps/api/v2/src/modules/auth/guards/routing-forms/is-routing-form-in-team.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/routing-forms/is-routing-form-in-team.guard.ts@@ -1,11 +1,5 @@import { RoutingFormsRepository } from "@/modules/routing-forms/routing-forms.repository";-import {- Injectable,- CanActivate,- ExecutionContext,- ForbiddenException,- NotFoundException,-} from "@nestjs/common";+import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";import { Request } from "express";import { Team } from "@calcom/prisma/client";@@ -20,18 +14,18 @@ export class IsRoutingFormInTeam implements CanActivate {const routingFormId: string = request.params.routingFormId;if (!routingFormId) {- throw new ForbiddenException("No routing form id found in request params.");+ throw new ForbiddenException("IsRoutingFormInTeam - No routing form id found in request params.");}if (!teamId) {- throw new ForbiddenException("No team id found in request params.");+ throw new ForbiddenException("IsRoutingFormInTeam - No team id found in request params.");}const routingForm = await this.routingFormsRepository.getTeamRoutingForm(Number(teamId), routingFormId);if (!routingForm) {- throw new NotFoundException(- `Team with id=(${teamId}) routing form with id=(${routingFormId}) not found.`+ throw new ForbiddenException(+ `IsRoutingFormInTeam - team with id=(${teamId}) does not own routing form with id=(${routingFormId}).`);}diff --git a/apps/api/v2/src/modules/auth/guards/teams/is-team-in-org.guard.ts b/apps/api/v2/src/modules/auth/guards/teams/is-team-in-org.guard.tsindex b4f28326262..55e855389b1 100644--- a/apps/api/v2/src/modules/auth/guards/teams/is-team-in-org.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/teams/is-team-in-org.guard.ts@@ -20,26 +20,30 @@ export class IsTeamInOrg implements CanActivate {const orgId: string = request.params.orgId;if (!orgId) {- throw new ForbiddenException("No org id found in request params.");+ throw new ForbiddenException("IsTeamInOrg - No org id found in request params.");}if (!teamId) {- throw new ForbiddenException("No team id found in request params.");+ throw new ForbiddenException("IsTeamInOrg - No team id found in request params.");}const { canAccess, team } = await this.checkIfTeamIsInOrg(orgId, teamId);- if (canAccess && team) {- request.team = team;+ if (!canAccess) {+ throw new ForbiddenException(+ `IsTeamInOrg - Team with id=${teamId} is not part of the organization with id=${orgId}.`+ );}- return canAccess;++ request.team = team;+ return true;}async checkIfTeamIsInOrg(orgId: string, teamId: string): Promise<{ canAccess: boolean; team?: Team }> {const team = await this.organizationsTeamsRepository.findOrgTeam(Number(orgId), Number(teamId));if (!team) {- throw new NotFoundException(`Team (${teamId}) not found.`);+ throw new NotFoundException(`IsTeamInOrg - Team (${teamId}) not found.`);}if (!team.isOrganization && team.parentId === Number(orgId)) {diff --git a/apps/api/v2/src/modules/auth/guards/users/is-user-in-org-team.guard.ts b/apps/api/v2/src/modules/auth/guards/users/is-user-in-org-team.guard.tsindex f88eb9ef1ac..267190bf1d9 100644--- a/apps/api/v2/src/modules/auth/guards/users/is-user-in-org-team.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/users/is-user-in-org-team.guard.ts@@ -15,15 +15,15 @@ export class IsUserInOrgTeam implements CanActivate {const userId: string = request.params.userId;if (!userId) {- throw new ForbiddenException("No user id found in request params.");+ throw new ForbiddenException("IsUserInOrgTeam - No user id found in request params.");}if (!orgId) {- throw new ForbiddenException("No org id found in request params.");+ throw new ForbiddenException("IsUserInOrgTeam - No org id found in request params.");}if (!teamId) {- throw new ForbiddenException("No team id found in request params.");+ throw new ForbiddenException("IsUserInOrgTeam - No team id found in request params.");}const user = await this.organizationsRepository.findOrgTeamUser(@@ -37,6 +37,8 @@ export class IsUserInOrgTeam implements CanActivate {return true;}- return false;+ throw new ForbiddenException(+ `IsUserInOrgTeam - user with id=(${userId}) is not part of the team with id=(${teamId}) in the organization with id=(${orgId})`+ );}}diff --git a/apps/api/v2/src/modules/auth/guards/users/is-user-in-org.guard.ts b/apps/api/v2/src/modules/auth/guards/users/is-user-in-org.guard.tsindex f9119f0abc9..0ba4d0490ca 100644--- a/apps/api/v2/src/modules/auth/guards/users/is-user-in-org.guard.ts+++ b/apps/api/v2/src/modules/auth/guards/users/is-user-in-org.guard.ts@@ -14,20 +14,22 @@ export class IsUserInOrg implements CanActivate {const userId: string = request.params.userId;if (!userId) {- throw new ForbiddenException("No user id found in request params.");+ throw new ForbiddenException("IsUserInOrg - No user id found in request params.");}if (!orgId) {- throw new ForbiddenException("No org id found in request params.");+ throw new ForbiddenException("IsUserInOrg - No org id found in request params.");}const user = await this.organizationsRepository.findOrgUser(Number(orgId), Number(userId));- if (user) {- request.user = user;- return true;+ if (!user) {+ throw new ForbiddenException(+ `IsUserInOrg - user with id=${userId} is not part of the organization with id=${orgId}.`+ );}- return false;+ request.user = user;+ return true;}}diff --git a/apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.ts b/apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.tsindex 916fe5cf991..a46d0b8a84c 100644--- a/apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.ts+++ b/apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.ts@@ -70,13 +70,15 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")return await this.authenticateNextAuth(nextAuthToken, request);}- throw new UnauthorizedException(NO_AUTH_PROVIDED_MESSAGE);+ throw new UnauthorizedException(`ApiAuthStrategy - ${NO_AUTH_PROVIDED_MESSAGE}`);} catch (err) {if (err instanceof Error) {return this.error(err);}return this.error(- new InternalServerErrorException("An error occurred while authenticating the request")+ new InternalServerErrorException(+ "ApiAuthStrategy - An error occurred while authenticating the request"+ ));}}@@ -106,23 +108,29 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")const client = await this.oauthRepository.getOAuthClient(oAuthClientId);if (!client) {- throw new UnauthorizedException(`Client with ID ${oAuthClientId} not found`);+ throw new UnauthorizedException(+ `ApiAuthStrategy - oAuth client - Client with ID ${oAuthClientId} not found`+ );}if (client.secret !== oAuthClientSecret) {- throw new UnauthorizedException("Invalid client secret");+ throw new UnauthorizedException("ApiAuthStrategy - oAuth client - Invalid client secret");}const platformCreatorId = await this.profilesRepository.getPlatformOwnerUserId(client.organizationId);if (!platformCreatorId) {- throw new UnauthorizedException("No owner ID found for this OAuth client");+ throw new UnauthorizedException(+ "ApiAuthStrategy - oAuth client - No owner ID found for this OAuth client"+ );}const user = await this.userRepository.findByIdWithProfile(platformCreatorId);if (!user) {- throw new UnauthorizedException("No user associated with the provided OAuth client");+ throw new UnauthorizedException(+ "ApiAuthStrategy - oAuth client - No user associated with the provided OAuth client"+ );}request.organizationId = client.organizationId;@@ -141,7 +149,11 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth"): await this.accessTokenStrategy(authString, request, requestOrigin);if (!user) {- return this.error(new UnauthorizedException("No user associated with the provided token"));+ return this.error(+ new UnauthorizedException(+ "ApiAuthStrategy - bearer token - No user associated with the provided token"+ )+ );}return this.success(this.getSuccessUser(user));@@ -158,24 +170,26 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")async apiKeyStrategy(apiKey: string, request: ApiAuthGuardRequest) {const isLicenseValid = await this.deploymentsService.checkLicense();if (!isLicenseValid) {- throw new UnauthorizedException("Invalid or missing CALCOM_LICENSE_KEY environment variable");+ throw new UnauthorizedException(+ "ApiAuthStrategy - api key - Invalid or missing CALCOM_LICENSE_KEY environment variable"+ );}const strippedApiKey = stripApiKey(apiKey, this.config.get<string>("api.keyPrefix"));const apiKeyHash = hashAPIKey(strippedApiKey);const keyData = await this.apiKeyRepository.getApiKeyFromHash(apiKeyHash);if (!keyData) {- throw new UnauthorizedException("Your api key is not valid");+ throw new UnauthorizedException("ApiAuthStrategy - api key - Your api key is not valid");}const isKeyExpired =keyData.expiresAt && new Date().setHours(0, 0, 0, 0) > keyData.expiresAt.setHours(0, 0, 0, 0);if (isKeyExpired) {- throw new UnauthorizedException("Your api key is expired");+ throw new UnauthorizedException("ApiAuthStrategy - api key - Your api key is expired");}const apiKeyOwnerId = keyData.userId;if (!apiKeyOwnerId) {- throw new UnauthorizedException("No user tied to this apiKey");+ throw new UnauthorizedException("ApiAuthStrategy - api key - No user tied to this apiKey");}const user: UserWithProfile | null = await this.userRepository.findByIdWithProfile(apiKeyOwnerId);@@ -187,29 +201,35 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")async accessTokenStrategy(accessToken: string, request: ApiAuthGuardRequest, origin?: string) {const accessTokenValid = await this.oauthFlowService.validateAccessToken(accessToken);if (!accessTokenValid) {- throw new UnauthorizedException(INVALID_ACCESS_TOKEN);+ throw new UnauthorizedException(`ApiAuthStrategy - access token - ${INVALID_ACCESS_TOKEN}`);}const client = await this.tokensRepository.getAccessTokenClient(accessToken);if (!client) {- throw new UnauthorizedException("OAuth client not found given the access token");+ throw new UnauthorizedException(+ "ApiAuthStrategy - access token - OAuth client not found given the access token"+ );}if (origin && !isOriginAllowed(origin, client.redirectUris)) {throw new UnauthorizedException(- `Invalid request origin - please open https://app.cal.com/settings/platform and add the origin '${origin}' to the 'Redirect uris' of your OAuth client with ID '${client.id}'`+ `ApiAuthStrategy - access token - Invalid request origin - please open https://app.cal.com/settings/platform and add the origin '${origin}' to the 'Redirect uris' of your OAuth client with ID '${client.id}'`);}const ownerId = await this.tokensRepository.getAccessTokenOwnerId(accessToken);if (!ownerId) {- throw new UnauthorizedException(INVALID_ACCESS_TOKEN);+ throw new UnauthorizedException(+ `ApiAuthStrategy - access token - ${INVALID_ACCESS_TOKEN}. No owner found for this access token.`+ );}const user: UserWithProfile | null = await this.userRepository.findByIdWithProfile(ownerId);if (!user) {- throw new UnauthorizedException("User associated with the authentication api key not found.");+ throw new UnauthorizedException(+ "ApiAuthStrategy - access token - User associated with the access token not found."+ );}const organizationId = this.usersService.getUserMainOrgId(user) as number;@@ -220,12 +240,16 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")async nextAuthStrategy(token: { email?: string | null }, request: ApiAuthGuardRequest) {if (!token.email) {- throw new UnauthorizedException("Email not found in the authentication token.");+ throw new UnauthorizedException(+ "ApiAuthStrategy - next auth - Email not found in the authentication token."+ );}const user = await this.userRepository.findByEmailWithProfile(token.email);if (!user) {- throw new UnauthorizedException("User associated with the authentication token email not found.");+ throw new UnauthorizedException(+ "ApiAuthStrategy - next auth - User associated with the authentication token email not found."+ );}const organizationId = this.usersService.getUserMainOrgId(user) as number;request.organizationId = organizationId;diff --git a/apps/api/v2/src/modules/auth/strategies/next-auth/next-auth.strategy.ts b/apps/api/v2/src/modules/auth/strategies/next-auth/next-auth.strategy.tsindex a34b0608822..a81fb3126da 100644--- a/apps/api/v2/src/modules/auth/strategies/next-auth/next-auth.strategy.ts+++ b/apps/api/v2/src/modules/auth/strategies/next-auth/next-auth.strategy.ts@@ -18,23 +18,27 @@ export class NextAuthStrategy extends PassportStrategy(NextAuthPassportStrategy,const payload = await getToken({ req, secret: nextAuthSecret });if (!payload) {- throw new UnauthorizedException("Authentication token is missing or invalid.");+ throw new UnauthorizedException("NextAuthStrategy - Authentication token is missing or invalid.");}if (!payload.email) {- throw new UnauthorizedException("Email not found in the authentication token.");+ throw new UnauthorizedException("NextAuthStrategy - Email not found in the authentication token.");}const user = await this.userRepository.findByEmailWithProfile(payload.email);if (!user) {- throw new UnauthorizedException("User associated with the authentication token email not found.");+ throw new UnauthorizedException(+ "NextAuthStrategy - User associated with the authentication token email not found."+ );}return this.success(user);} catch (error) {if (error instanceof Error) return this.error(error);return this.error(- new InternalServerErrorException("An error occurred while authenticating the request")+ new InternalServerErrorException(+ "NextAuthStrategy - An error occurred while authenticating the request"+ ));}}diff --git a/apps/api/v2/src/modules/oauth-clients/guards/oauth-client-guard.ts b/apps/api/v2/src/modules/oauth-clients/guards/oauth-client-guard.tsindex 4c61ccc4f4e..4813771b949 100644--- a/apps/api/v2/src/modules/oauth-clients/guards/oauth-client-guard.ts+++ b/apps/api/v2/src/modules/oauth-clients/guards/oauth-client-guard.ts@@ -9,7 +9,6 @@ import {ForbiddenException,NotFoundException,} from "@nestjs/common";-import { Request } from "express";@Injectable()export class OAuthClientGuard implements CanActivate {@@ -35,7 +34,13 @@ export class OAuthClientGuard implements CanActivate {throw new NotFoundException("OAuthClientGuard - OAuth client not found.");}- return Boolean(user.isSystemAdmin || oAuthClient.organizationId === organizationId);+ const allowed = Boolean(user.isSystemAdmin || oAuthClient.organizationId === organizationId);+ if (!allowed) {+ throw new ForbiddenException(+ `OAuthClientGuard - forbidden. oAuth client with id=${oAuthClientId} does not belong to the organization with id=${organizationId}.`+ );+ }+ return true;}getOrganizationId(context: ExecutionContext) {diff --git a/apps/api/v2/src/modules/oauth-clients/oauth-client.module.ts b/apps/api/v2/src/modules/oauth-clients/oauth-client.module.tsindex 462f41e3c6f..095faa6f508 100644--- a/apps/api/v2/src/modules/oauth-clients/oauth-client.module.ts+++ b/apps/api/v2/src/modules/oauth-clients/oauth-client.module.ts@@ -62,6 +62,6 @@ import { JwtService } from "@nestjs/jwt";OAuthClientUsersOutputService,],controllers: [OAuthClientUsersController, OAuthClientsController, OAuthFlowController],- exports: [OAuthClientRepository, OAuthClientUsersOutputService],+ exports: [OAuthClientRepository, OAuthClientsOutputService, OAuthClientUsersOutputService],})export class OAuthClientModule {}diff --git a/apps/api/v2/src/modules/oauth-clients/services/oauth-clients/oauth-clients-output.service.ts b/apps/api/v2/src/modules/oauth-clients/services/oauth-clients/oauth-clients-output.service.tsindex ddd0285f910..9aefacd52db 100644--- a/apps/api/v2/src/modules/oauth-clients/services/oauth-clients/oauth-clients-output.service.ts+++ b/apps/api/v2/src/modules/oauth-clients/services/oauth-clients/oauth-clients-output.service.ts@@ -6,17 +6,8 @@ import { PlatformOAuthClientDto } from "@calcom/platform-types";@Injectable()export class OAuthClientsOutputService {- transformPermissions(permissionsNumber: number): Array<keyof typeof PERMISSION_MAP> {- const permissionNumbers = PERMISSIONS.filter(- (permission) => (permissionsNumber & permission) === permission- );-- return permissionNumbers.map(- (permission) =>- Object.entries(PERMISSION_MAP).find(- ([_, value]) => value === permission- )?.[0] as keyof typeof PERMISSION_MAP- );+ transformOAuthClients(clients: PlatformOAuthClient[]): PlatformOAuthClientDto[] {+ return clients.map((client) => this.transformOAuthClient(client));}transformOAuthClient(client: PlatformOAuthClient): PlatformOAuthClientDto {@@ -24,7 +15,7 @@ export class OAuthClientsOutputService {id: client.id,name: client.name,secret: client.secret,- permissions: this.transformPermissions(client.permissions),+ permissions: this.transformOAuthClientPermissions(client.permissions),logo: client.logo,redirectUris: client.redirectUris,organizationId: client.organizationId,@@ -37,7 +28,15 @@ export class OAuthClientsOutputService {};}- transformOAuthClients(clients: PlatformOAuthClient[]): PlatformOAuthClientDto[] {- return clients.map((client) => this.transformOAuthClient(client));+ transformOAuthClientPermissions(permissions: number): Array<keyof typeof PERMISSION_MAP> {+ const permissionsNumbers = PERMISSIONS.filter((permission) => (permissions & permission) === permission);++ return permissionsNumbers.map((permission) => this.transformOAuthClientPermission(permission));+ }++ transformOAuthClientPermission(permission: (typeof PERMISSIONS)[number]): keyof typeof PERMISSION_MAP {+ return Object.entries(PERMISSION_MAP).find(+ ([_, value]) => value === permission+ )?.[0] as keyof typeof PERMISSION_MAP;}}diff --git a/apps/api/v2/src/modules/proxy/proxy.guard.ts b/apps/api/v2/src/modules/proxy/proxy.guard.tsdeleted file mode 100644index 16074913d46..00000000000--- a/apps/api/v2/src/modules/proxy/proxy.guard.ts+++ /dev/null@@ -1,10 +0,0 @@-import { Injectable } from "@nestjs/common";-import { ThrottlerGuard } from "@nestjs/throttler";--@Injectable()-export class ThrottlerBehindProxyGuard extends ThrottlerGuard {- // TODO: adapt if required for CF / AWS / FlightControl proxying.- protected async getTracker(req: Record<string, any>): Promise<string> {- return req.ips.length ? req.ips[0] : req.ip;- }-}diff --git a/apps/api/v2/src/modules/webhooks/guards/is-oauth-client-webhook-guard.ts b/apps/api/v2/src/modules/webhooks/guards/is-oauth-client-webhook-guard.tsindex ae4cd803e0f..8cd8586b2a9 100644--- a/apps/api/v2/src/modules/webhooks/guards/is-oauth-client-webhook-guard.ts+++ b/apps/api/v2/src/modules/webhooks/guards/is-oauth-client-webhook-guard.ts@@ -32,21 +32,25 @@ export class IsOAuthClientWebhookGuard implements CanActivate {const organizationId = this.usersService.getUserMainOrgId(user);if (!user) {- throw new ForbiddenException("User not authenticated");+ throw new ForbiddenException("IsOAuthClientWebhookGuard - User not authenticated");}if (!webhookId) {- throw new BadRequestException("webhookId parameter not specified in the request");+ throw new BadRequestException(+ "IsOAuthClientWebhookGuard - webhookId parameter not specified in the request"+ );}if (!oAuthClientId) {- throw new BadRequestException("oAuthClientId parameter not specified in the request");+ throw new BadRequestException(+ "IsOAuthClientWebhookGuard - oAuthClientId parameter not specified in the request"+ );}const oAuthClient = await this.oAuthClientRepository.getOAuthClient(oAuthClientId);if (!oAuthClient) {- throw new NotFoundException(`OAuthClient (${oAuthClientId}) not found`);+ throw new NotFoundException(`IsOAuthClientWebhookGuard - OAuthClient (${oAuthClientId}) not found`);}const webhook = await this.webhooksService.getWebhookById(webhookId);@@ -56,7 +60,7 @@ export class IsOAuthClientWebhookGuard implements CanActivate {}if (webhook.platformOAuthClientId !== oAuthClientId) {- throw new ForbiddenException("Webhook does not belong to this oAuthClient");+ throw new ForbiddenException("IsOAuthClientWebhookGuard - Webhook does not belong to this oAuthClient");}request.webhook = webhook;diff --git a/apps/api/v2/src/modules/webhooks/guards/is-user-event-type-webhook-guard.ts b/apps/api/v2/src/modules/webhooks/guards/is-user-event-type-webhook-guard.tsindex 2ff90ea6ac6..ad28a42503d 100644--- a/apps/api/v2/src/modules/webhooks/guards/is-user-event-type-webhook-guard.ts+++ b/apps/api/v2/src/modules/webhooks/guards/is-user-event-type-webhook-guard.ts@@ -28,16 +28,18 @@ export class IsUserEventTypeWebhookGuard implements CanActivate {const eventTypeId = request.params.eventTypeId;if (!user) {- return false;+ throw new ForbiddenException("IsUserEventTypeWebhookGuard - No user associated with the request.");}if (eventTypeId) {const eventType = await this.eventtypesRepository.getEventTypeById(parseInt(eventTypeId));if (!eventType) {- throw new NotFoundException(`Event type (${eventTypeId}) not found`);+ throw new NotFoundException(`IsUserEventTypeWebhookGuard - Event type (${eventTypeId}) not found`);}if (eventType.userId !== user.id) {- throw new ForbiddenException(`User (${user.id}) is not the owner of event type (${eventTypeId})`);+ throw new ForbiddenException(+ `IsUserEventTypeWebhookGuard - User (${user.id}) is not the owner of event type (${eventTypeId})`+ );}request.eventType = eventType;}@@ -45,11 +47,13 @@ export class IsUserEventTypeWebhookGuard implements CanActivate {if (webhookId) {const webhook = await this.webhooksService.getWebhookById(webhookId);if (!webhook.eventTypeId) {- throw new BadRequestException(`Webhook (${webhookId}) is not associated with an event type`);+ throw new BadRequestException(+ `IsUserEventTypeWebhookGuard - Webhook (${webhookId}) is not associated with an event type`+ );}if (webhook.eventTypeId !== parseInt(eventTypeId)) {throw new ForbiddenException(- `Webhook (${webhookId}) is not associated with event type (${eventTypeId})`+ `IsUserEventTypeWebhookGuard - Webhook (${webhookId}) is not associated with event type (${eventTypeId})`);}request.webhook = webhook;diff --git a/apps/api/v2/src/modules/webhooks/guards/is-user-webhook-guard.ts b/apps/api/v2/src/modules/webhooks/guards/is-user-webhook-guard.tsindex 95cc4ea6eec..ef2c253abe7 100644--- a/apps/api/v2/src/modules/webhooks/guards/is-user-webhook-guard.ts+++ b/apps/api/v2/src/modules/webhooks/guards/is-user-webhook-guard.ts@@ -1,6 +1,6 @@import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";import { WebhooksService } from "@/modules/webhooks/services/webhooks.service";-import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";+import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from "@nestjs/common";import { Request } from "express";import { Webhook } from "@calcom/prisma/client";@@ -14,18 +14,23 @@ export class IsUserWebhookGuard implements CanActivate {const user = request.user as ApiAuthGuardUser;const webhookId = request.params.webhookId;- if (!user || !webhookId) {- return false;+ if (!user) {+ throw new ForbiddenException("IsUserWebhookGuard - No user associated with the request.");+ }++ if (!webhookId) {+ throw new ForbiddenException("IsUserWebhookGuard - No webhook id found in request params.");}const webhook = await this.webhooksService.getWebhookById(webhookId);- if (webhook.userId !== user.id) {- return user.isSystemAdmin;+ if (webhook.userId !== user.id && !user.isSystemAdmin) {+ throw new ForbiddenException(+ `IsUserWebhookGuard - user with id=(${user.id}) is not the owner of webhook with id=(${webhookId})`+ );}request.webhook = webhook;-return true;}}diff --git a/apps/api/v2/swagger/documentation.json b/apps/api/v2/swagger/documentation.jsonindex 97c335f356a..2d59fdd640a 100644--- a/apps/api/v2/swagger/documentation.json+++ b/apps/api/v2/swagger/documentation.json@@ -13337,7 +13337,6 @@},"enabledLayouts": {"type": "array",- "description": "Array of valid layouts - month, week or column","items": {"type": "string","enum": [@@ -21104,20 +21103,10 @@"description": "The start time of the booking in ISO 8601 format in UTC timezone.","example": "2024-08-13T09:00:00Z"},- "attendee": {- "description": "The attendee's details.",- "allOf": [- {- "$ref": "#/components/schemas/Attendee"- }- ]- },- "bookingFieldsResponses": {- "type": "object",- "description": "Booking field responses consisting of an object with booking field slug as keys and user response as values for custom booking fields added by you.",- "example": {- "customField": "customValue"- }+ "lengthInMinutes": {+ "type": "number",+ "example": 30,+ "description": "If it is an event type that has multiple possible lengths that attendee can pick from, you can pass the desired booking length here.\n If not provided then event type default length will be used for the booking."},"eventTypeId": {"type": "number",@@ -21144,6 +21133,14 @@"description": "The organization slug. Optional, only used when booking with eventTypeSlug + username or eventTypeSlug + teamSlug.","example": "acme-corp"},+ "attendee": {+ "description": "The attendee's details.",+ "allOf": [+ {+ "$ref": "#/components/schemas/Attendee"+ }+ ]+ },"guests": {"description": "An optional list of guest emails attending the event.","example": [@@ -21197,10 +21194,12 @@"key": "value"}},- "lengthInMinutes": {- "type": "number",- "example": 30,- "description": "If it is an event type that has multiple possible lengths that attendee can pick from, you can pass the desired booking length here.\n If not provided then event type default length will be used for the booking."+ "bookingFieldsResponses": {+ "type": "object",+ "description": "Booking field responses consisting of an object with booking field slug as keys and user response as values.",+ "example": {+ "customField": "customValue"+ }}},"required": [@@ -21216,20 +21215,10 @@"description": "The start time of the booking in ISO 8601 format in UTC timezone.","example": "2024-08-13T09:00:00Z"},- "attendee": {- "description": "The attendee's details.",- "allOf": [- {- "$ref": "#/components/schemas/Attendee"- }- ]- },- "bookingFieldsResponses": {- "type": "object",- "description": "Booking field responses consisting of an object with booking field slug as keys and user response as values for custom booking fields added by you.",- "example": {- "customField": "customValue"- }+ "lengthInMinutes": {+ "type": "number",+ "example": 30,+ "description": "If it is an event type that has multiple possible lengths that attendee can pick from, you can pass the desired booking length here.\n If not provided then event type default length will be used for the booking."},"eventTypeId": {"type": "number",@@ -21256,6 +21245,14 @@"description": "The organization slug. Optional, only used when booking with eventTypeSlug + username or eventTypeSlug + teamSlug.","example": "acme-corp"},+ "attendee": {+ "description": "The attendee's details.",+ "allOf": [+ {+ "$ref": "#/components/schemas/Attendee"+ }+ ]+ },"guests": {"description": "An optional list of guest emails attending the event.","example": [@@ -21309,10 +21306,12 @@"key": "value"}},- "lengthInMinutes": {- "type": "number",- "example": 30,- "description": "If it is an event type that has multiple possible lengths that attendee can pick from, you can pass the desired booking length here.\n If not provided then event type default length will be used for the booking."+ "bookingFieldsResponses": {+ "type": "object",+ "description": "Booking field responses consisting of an object with booking field slug as keys and user response as values.",+ "example": {+ "customField": "customValue"+ }},"instant": {"type": "boolean",@@ -21334,20 +21333,10 @@"description": "The start time of the booking in ISO 8601 format in UTC timezone.","example": "2024-08-13T09:00:00Z"},- "attendee": {- "description": "The attendee's details.",- "allOf": [- {- "$ref": "#/components/schemas/Attendee"- }- ]- },- "bookingFieldsResponses": {- "type": "object",- "description": "Booking field responses consisting of an object with booking field slug as keys and user response as values for custom booking fields added by you.",- "example": {- "customField": "customValue"- }+ "lengthInMinutes": {+ "type": "number",+ "example": 30,+ "description": "If it is an event type that has multiple possible lengths that attendee can pick from, you can pass the desired booking length here.\n If not provided then event type default length will be used for the booking."},"eventTypeId": {"type": "number",@@ -21374,6 +21363,14 @@"description": "The organization slug. Optional, only used when booking with eventTypeSlug + username or eventTypeSlug + teamSlug.","example": "acme-corp"},+ "attendee": {+ "description": "The attendee's details.",+ "allOf": [+ {+ "$ref": "#/components/schemas/Attendee"+ }+ ]+ },"guests": {"description": "An optional list of guest emails attending the event.","example": [@@ -21427,10 +21424,12 @@"key": "value"}},- "lengthInMinutes": {- "type": "number",- "example": 30,- "description": "If it is an event type that has multiple possible lengths that attendee can pick from, you can pass the desired booking length here.\n If not provided then event type default length will be used for the booking."+ "bookingFieldsResponses": {+ "type": "object",+ "description": "Booking field responses consisting of an object with booking field slug as keys and user response as values.",+ "example": {+ "customField": "customValue"+ }},"recurrenceCount": {"type": "number",