Skip to content

Scheduling infrastructure for absolutely everyone.

fix: Selected calendar delegation credentials (#24190)

Volnei Munhoz2ac310456e8d
diff --git a/packages/features/calendar-subscription/lib/CalendarSubscriptionService.ts b/packages/features/calendar-subscription/lib/CalendarSubscriptionService.ts
index e1408259f96..0dfe81febc6 100644
--- a/packages/features/calendar-subscription/lib/CalendarSubscriptionService.ts
+++ b/packages/features/calendar-subscription/lib/CalendarSubscriptionService.ts
@@ -9,10 +9,10 @@ import type {
import type { CalendarCacheEventService } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService";
import type { CalendarSyncService } from "@calcom/features/calendar-subscription/lib/sync/CalendarSyncService";
import type { FeaturesRepository } from "@calcom/features/flags/features.repository";
-import { getCredentialForCalendarCache } from "@calcom/lib/delegationCredential/server";
+import { getCredentialForSelectedCalendar } from "@calcom/lib/delegationCredential/server";
import logger from "@calcom/lib/logger";
import type { ISelectedCalendarRepository } from "@calcom/lib/server/repository/SelectedCalendarRepository.interface";
-import type { SelectedCalendar } from "@calcom/prisma/client";
+import { SelectedCalendar } from "@calcom/prisma/client";
const log = logger.getSubLogger({ prefix: ["CalendarSubscriptionService"] });
@@ -35,15 +35,18 @@ export class CalendarSubscriptionService {
*/
async subscribe(selectedCalendarId: string): Promise<void> {
log.debug("subscribe", { selectedCalendarId });
- const selectedCalendar = await this.deps.selectedCalendarRepository.findByIdWithCredentials(
- selectedCalendarId
- );
- if (!selectedCalendar?.credentialId) {
+ const selectedCalendar = await this.deps.selectedCalendarRepository.findById(selectedCalendarId);
+ if (!selectedCalendar) {
log.debug("Selected calendar not found", { selectedCalendarId });
return;
}
- const credential = await this.getCredential(selectedCalendar.credentialId);
+ if (!selectedCalendar.credentialId && !selectedCalendar.delegationCredentialId) {
+ log.debug("Selected calendar doesn't have credentials", { selectedCalendarId });
+ return;
+ }
+
+ const credential = await this.getCredential(selectedCalendar);
if (!credential) {
log.debug("Calendar credential not found", { selectedCalendarId });
return;
@@ -72,12 +75,18 @@ export class CalendarSubscriptionService {
*/
async unsubscribe(selectedCalendarId: string): Promise<void> {
log.debug("unsubscribe", { selectedCalendarId });
- const selectedCalendar = await this.deps.selectedCalendarRepository.findByIdWithCredentials(
- selectedCalendarId
- );
- if (!selectedCalendar?.credentialId) return;
+ const selectedCalendar = await this.deps.selectedCalendarRepository.findById(selectedCalendarId);
+ if (!selectedCalendar) {
+ log.debug("Selected calendar not found", { selectedCalendarId });
+ return;
+ }
+
+ if (!selectedCalendar.credentialId && !selectedCalendar.delegationCredentialId) {
+ log.debug("Selected calendar doesn't have credentials", { selectedCalendarId });
+ return;
+ }
- const credential = await this.getCredential(selectedCalendar.credentialId);
+ const credential = await this.getCredential(selectedCalendar);
if (!credential) return;
const calendarSubscriptionAdapter = this.deps.adapterFactory.get(
@@ -133,10 +142,11 @@ export class CalendarSubscriptionService {
selectedCalendar.integration as CalendarSubscriptionProvider
);
- if (!selectedCalendar.credentialId) {
- log.debug("Selected calendar credential not found", { channelId: selectedCalendar.channelId });
+ if (!selectedCalendar.credentialId && !selectedCalendar.delegationCredentialId) {
+ log.debug("Selected Calendar doesn't have credentials", { selectedCalendarId: selectedCalendar.id });
return;
}
+
// for cache the feature should be enabled globally and by user/team features
const [cacheEnabled, syncEnabled, cacheEnabledForUser] = await Promise.all([
this.isCacheEnabled(),
@@ -150,7 +160,7 @@ export class CalendarSubscriptionService {
}
log.debug("Processing events", { channelId: selectedCalendar.channelId });
- const credential = await this.getCredential(selectedCalendar.credentialId);
+ const credential = await this.getCredential(selectedCalendar);
if (!credential) return;
let events: CalendarSubscriptionEvent | null = null;
@@ -236,8 +246,12 @@ export class CalendarSubscriptionService {
/**
* Get credential with delegation if available
*/
- private async getCredential(credentialId: number): Promise<CalendarCredential | null> {
- const credential = await getCredentialForCalendarCache({ credentialId });
+ private async getCredential(selectedCalendar: SelectedCalendar): Promise<CalendarCredential | null> {
+ if (!selectedCalendar.credentialId && !selectedCalendar.delegationCredentialId) {
+ log.debug("Selected calendar doesn't have any credential");
+ return null;
+ }
+ const credential = await getCredentialForSelectedCalendar(selectedCalendar);
if (!credential) return null;
return {
...credential,
diff --git a/packages/features/calendar-subscription/lib/__mocks__/delegationCredential.ts b/packages/features/calendar-subscription/lib/__mocks__/delegationCredential.ts
index b115540e09a..40ca631e654 100644
--- a/packages/features/calendar-subscription/lib/__mocks__/delegationCredential.ts
+++ b/packages/features/calendar-subscription/lib/__mocks__/delegationCredential.ts
@@ -1,6 +1,6 @@
import { vi } from "vitest";
-export const getCredentialForCalendarCache = vi.fn().mockResolvedValue({
+export const getCredentialForSelectedCalendar = vi.fn().mockResolvedValue({
id: 1,
key: { access_token: "test-token" },
user: { email: "[email protected]" },
@@ -8,5 +8,5 @@ export const getCredentialForCalendarCache = vi.fn().mockResolvedValue({
});
vi.doMock("@calcom/lib/delegationCredential/server", () => ({
- getCredentialForCalendarCache,
+ getCredentialForSelectedCalendar,
}));
diff --git a/packages/features/calendar-subscription/lib/__tests__/CalendarSubscriptionService.test.ts b/packages/features/calendar-subscription/lib/__tests__/CalendarSubscriptionService.test.ts
index 539ca71d23e..a1081a2b1aa 100644
--- a/packages/features/calendar-subscription/lib/__tests__/CalendarSubscriptionService.test.ts
+++ b/packages/features/calendar-subscription/lib/__tests__/CalendarSubscriptionService.test.ts
@@ -115,7 +115,7 @@ describe("CalendarSubscriptionService", () => {
};
mockSelectedCalendarRepository = {
- findByIdWithCredentials: vi.fn().mockResolvedValue(mockSelectedCalendar),
+ findById: vi.fn().mockResolvedValue(mockSelectedCalendar),
findByChannelId: vi.fn().mockResolvedValue(mockSelectedCalendar),
findNextSubscriptionBatch: vi.fn().mockResolvedValue([mockSelectedCalendar]),
updateSyncStatus: vi.fn().mockResolvedValue(mockSelectedCalendar),
@@ -145,15 +145,15 @@ describe("CalendarSubscriptionService", () => {
calendarSyncService: mockCalendarSyncService,
});
- const { getCredentialForCalendarCache } = await import("../__mocks__/delegationCredential");
- getCredentialForCalendarCache.mockResolvedValue(mockCredential);
+ const { getCredentialForSelectedCalendar } = await import("../__mocks__/delegationCredential");
+ getCredentialForSelectedCalendar.mockResolvedValue(mockCredential);
});
describe("subscribe", () => {
test("should successfully subscribe to a calendar", async () => {
await service.subscribe("test-calendar-id");
- expect(mockSelectedCalendarRepository.findByIdWithCredentials).toHaveBeenCalledWith("test-calendar-id");
+ expect(mockSelectedCalendarRepository.findById).toHaveBeenCalledWith("test-calendar-id");
expect(mockAdapterFactory.get).toHaveBeenCalledWith("google_calendar");
expect(mockAdapter.subscribe).toHaveBeenCalledWith(mockSelectedCalendar, mockCredential);
expect(mockSelectedCalendarRepository.updateSubscription).toHaveBeenCalledWith("test-calendar-id", {
@@ -167,7 +167,7 @@ describe("CalendarSubscriptionService", () => {
});
test("should return early if selected calendar not found", async () => {
- mockSelectedCalendarRepository.findByIdWithCredentials.mockResolvedValue(null);
+ mockSelectedCalendarRepository.findById.mockResolvedValue(null);
await service.subscribe("non-existent-id");
@@ -175,10 +175,11 @@ describe("CalendarSubscriptionService", () => {
expect(mockSelectedCalendarRepository.updateSubscription).not.toHaveBeenCalled();
});
- test("should return early if selected calendar has no credentialId", async () => {
- mockSelectedCalendarRepository.findByIdWithCredentials.mockResolvedValue({
+ test("should return early if selected calendar has no credentialId or delegationCredentialId", async () => {
+ mockSelectedCalendarRepository.findById.mockResolvedValue({
...mockSelectedCalendar,
credentialId: null,
+ delegationCredentialId: null,
});
await service.subscribe("test-calendar-id");
@@ -194,7 +195,7 @@ describe("CalendarSubscriptionService", () => {
await service.unsubscribe("test-calendar-id");
- expect(mockSelectedCalendarRepository.findByIdWithCredentials).toHaveBeenCalledWith("test-calendar-id");
+ expect(mockSelectedCalendarRepository.findById).toHaveBeenCalledWith("test-calendar-id");
expect(mockAdapter.unsubscribe).toHaveBeenCalledWith(mockSelectedCalendar, mockCredential);
expect(mockSelectedCalendarRepository.updateSubscription).toHaveBeenCalledWith("test-calendar-id", {
syncSubscribedAt: null,
@@ -211,7 +212,7 @@ describe("CalendarSubscriptionService", () => {
});
test("should return early if selected calendar not found", async () => {
- mockSelectedCalendarRepository.findByIdWithCredentials.mockResolvedValue(null);
+ mockSelectedCalendarRepository.findById.mockResolvedValue(null);
await service.unsubscribe("non-existent-id");
@@ -356,10 +357,11 @@ describe("CalendarSubscriptionService", () => {
expect(mockCalendarSyncService.handleEvents).not.toHaveBeenCalled();
});
- test("should return early when selected calendar has no credentialId", async () => {
+ test("should return early when selected calendar has no credentialId or delegationCredentialId", async () => {
const calendarWithoutCredential = {
...mockSelectedCalendar,
credentialId: null,
+ delegationCredentialId: null,
};
await service.processEvents(calendarWithoutCredential);
diff --git a/packages/features/calendar-subscription/lib/cache/CalendarCacheWrapper.ts b/packages/features/calendar-subscription/lib/cache/CalendarCacheWrapper.ts
index be7ea8dcf2e..1f179f7e6c2 100644
--- a/packages/features/calendar-subscription/lib/cache/CalendarCacheWrapper.ts
+++ b/packages/features/calendar-subscription/lib/cache/CalendarCacheWrapper.ts
@@ -60,14 +60,10 @@ export class CalendarCacheWrapper implements Calendar {
async getAvailability(
dateFrom: string,
dateTo: string,
- selectedCalendars: IntegrationCalendar[],
- shouldServeCache?: boolean
+ selectedCalendars: IntegrationCalendar[]
+ // _shouldServeCache?: boolean
// _fallbackToPrimary?: boolean
): Promise<EventBusyDate[]> {
- if (!shouldServeCache) {
- return this.deps.originalCalendar.getAvailability(dateFrom, dateTo, selectedCalendars);
- }
-
log.debug("getAvailability from cache", { dateFrom, dateTo, selectedCalendars });
const selectedCalendarIds = selectedCalendars.map((e) => e.id).filter((id): id is string => Boolean(id));
if (!selectedCalendarIds.length) {
diff --git a/packages/lib/delegationCredential/server.ts b/packages/lib/delegationCredential/server.ts
index 4abe3426281..c470ce71b89 100644
--- a/packages/lib/delegationCredential/server.ts
+++ b/packages/lib/delegationCredential/server.ts
@@ -8,7 +8,8 @@ import { safeStringify } from "@calcom/lib/safeStringify";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import type { ServiceAccountKey } from "@calcom/lib/server/repository/delegationCredential";
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
-import prisma from "@calcom/prisma";
+import { prisma } from "@calcom/prisma";
+import type { SelectedCalendar } from "@calcom/prisma/client";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import { UserRepository } from "../server/repository/user";
@@ -650,3 +651,32 @@ export async function getCredentialForCalendarCache({ credentialId }: { credenti
}
return credentialForCalendarService;
}
+
+/**
+ * Find the credential for a selected calendar
+ * @param selectedCalendar
+ */
+export async function getCredentialForSelectedCalendar({
+ credentialId,
+ delegationCredentialId,
+ userId,
+}: Partial<SelectedCalendar>) {
+ if (credentialId) {
+ const credentialRepository = new CredentialRepository(prisma);
+ const credential = await credentialRepository.findByIdWithDelegationCredential(credentialId);
+ if (credential?.delegationCredential?.id && credential.userId) {
+ return findUniqueDelegationCalendarCredential({
+ userId: credential.userId,
+ delegationCredentialId: credential.delegationCredential.id,
+ });
+ }
+ return credential ? buildNonDelegationCredential(credential) : undefined;
+ }
+ if (delegationCredentialId && userId) {
+ return findUniqueDelegationCalendarCredential({
+ userId,
+ delegationCredentialId,
+ });
+ }
+ return undefined;
+}
diff --git a/packages/lib/server/repository/SelectedCalendarRepository.interface.ts b/packages/lib/server/repository/SelectedCalendarRepository.interface.ts
index 45939e99be5..55b49b7b5ec 100644
--- a/packages/lib/server/repository/SelectedCalendarRepository.interface.ts
+++ b/packages/lib/server/repository/SelectedCalendarRepository.interface.ts
@@ -2,11 +2,11 @@ import type { Prisma, SelectedCalendar } from "@calcom/prisma/client";
export interface ISelectedCalendarRepository {
/**
- * Find selected calendar by id with credentials
+ * Find selected calendar by id
*
* @param id
*/
- findByIdWithCredentials(id: string): Promise<SelectedCalendar | null>;
+ findById(id: string): Promise<SelectedCalendar | null>;
/**
* Find selected calendar by channel id
diff --git a/packages/lib/server/repository/SelectedCalendarRepository.ts b/packages/lib/server/repository/SelectedCalendarRepository.ts
index 5eb6c585b19..b40cfc70a37 100644
--- a/packages/lib/server/repository/SelectedCalendarRepository.ts
+++ b/packages/lib/server/repository/SelectedCalendarRepository.ts
@@ -5,16 +5,9 @@ import type { Prisma } from "@calcom/prisma/client";
export class SelectedCalendarRepository implements ISelectedCalendarRepository {
constructor(private prismaClient: PrismaClient) {}
- async findByIdWithCredentials(id: string) {
+ async findById(id: string) {
return this.prismaClient.selectedCalendar.findUnique({
where: { id },
- include: {
- credential: {
- select: {
- delegationCredential: true,
- },
- },
- },
});
}
diff --git a/packages/lib/server/repository/__tests__/SelectedCalendarRepository.test.ts b/packages/lib/server/repository/__tests__/SelectedCalendarRepository.test.ts
index 032454a7f18..d649c6da175 100644
--- a/packages/lib/server/repository/__tests__/SelectedCalendarRepository.test.ts
+++ b/packages/lib/server/repository/__tests__/SelectedCalendarRepository.test.ts
@@ -55,7 +55,7 @@ describe("SelectedCalendarRepository", () => {
vi.clearAllMocks();
});
- describe("findByIdWithCredentials", () => {
+ describe("findById", () => {
test("should find selected calendar by id with credential delegation", async () => {
const mockCalendarWithCredential = {
...mockSelectedCalendar,
@@ -69,17 +69,10 @@ describe("SelectedCalendarRepository", () => {
vi.mocked(mockPrismaClient.selectedCalendar.findUnique).mockResolvedValue(mockCalendarWithCredential);
- const result = await repository.findByIdWithCredentials("test-calendar-id");
+ const result = await repository.findById("test-calendar-id");
expect(mockPrismaClient.selectedCalendar.findUnique).toHaveBeenCalledWith({
where: { id: "test-calendar-id" },
- include: {
- credential: {
- select: {
- delegationCredential: true,
- },
- },
- },
});
expect(result).toEqual(mockCalendarWithCredential);
@@ -88,7 +81,7 @@ describe("SelectedCalendarRepository", () => {
test("should return null when calendar not found", async () => {
vi.mocked(mockPrismaClient.selectedCalendar.findUnique).mockResolvedValue(null);
- const result = await repository.findByIdWithCredentials("non-existent-id");
+ const result = await repository.findById("non-existent-id");
expect(result).toBeNull();
});
diff --git a/packages/lib/server/repository/credential.ts b/packages/lib/server/repository/credential.ts
index 97c9bc939bd..e08713c948b 100644
--- a/packages/lib/server/repository/credential.ts
+++ b/packages/lib/server/repository/credential.ts
@@ -1,6 +1,6 @@
import logger from "@calcom/lib/logger";
import { prisma } from "@calcom/prisma";
-import type { Prisma } from "@calcom/prisma/client";
+import type { Prisma, PrismaClient } from "@calcom/prisma/client";
import { safeCredentialSelect } from "@calcom/prisma/selects/credential";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -10,7 +10,7 @@ const log = logger.getSubLogger({ prefix: ["CredentialRepository"] });
type CredentialCreateInput = {
type: string;
- key: any;
+ key: object;
userId: number;
appId: string;
delegationCredentialId?: string | null;
@@ -18,7 +18,7 @@ type CredentialCreateInput = {
type CredentialUpdateInput = {
type?: string;
- key?: any;
+ key?: object;
userId?: number;
appId?: string;
delegationCredentialId?: string | null;
@@ -26,6 +26,15 @@ type CredentialUpdateInput = {
};
export class CredentialRepository {
+ constructor(private primaClient: PrismaClient) {}
+
+ async findByIdWithDelegationCredential(id: number) {
+ return this.primaClient.credential.findUnique({
+ where: { id },
+ select: { ...credentialForCalendarServiceSelect, delegationCredential: true },
+ });
+ }
+
static async create(data: CredentialCreateInput) {
const credential = await prisma.credential.create({ data: { ...data } });
return buildNonDelegationCredential(credential);
@@ -157,7 +166,7 @@ export class CredentialRepository {
return {
...rest,
// We queried only those where delegationCredentialId is not null
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+
delegationCredentialId: delegationCredentialId!,
};
});