fix: Handle invalid non-delegation credential in cron (#21270)

Co-authored-by: Benny Joo <[email protected]>
Co-authored-by: Omar López <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-05-20 03:17:13 +00:00
1 parent 5efc7f3856
commit 81bdb3dc91
12 files changed
+795 -112

No files matched your search

@@ -974,15 +974,15 @@ export default class GoogleCalendarService implements Calendar {
expiration: otherCalendarsWithSameSubscription[0].googleChannelExpiration,
}
: {};
let error: string | undefined;
let error: string | null = null;
if (!otherCalendarsWithSameSubscription.length) {
try {
googleChannelProps = await this.startWatchingCalendarsInGoogle({ calendarId });
} catch (error) {
this.log.error(`Failed to watch calendar ${calendarId}`, error);
} catch (_error) {
this.log.error(`Failed to watch calendar ${calendarId}`, _error);
// We set error to prevent attempting to watch on next cron run
error = error instanceof Error ? error.message : "Unknown error";
error = _error instanceof Error ? _error.message : "Unknown error";
}
} else {
logger.info(
@@ -2,6 +2,7 @@ import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
@@ -82,6 +83,13 @@ const handleCalendarsToUnwatch = async () => {
if (error instanceof Error) {
errorMessage = error.message;
}
log.error(
"Error unwatching calendar: ",
safeStringify({
selectedCalendarId: id,
error: errorMessage,
})
);
await SelectedCalendarRepository.updateById(id, {
error: `Error unwatching calendar: ${errorMessage}`,
});
@@ -117,6 +125,13 @@ const handleCalendarsToWatch = async () => {
if (error instanceof Error) {
errorMessage = error.message;
}
log.error(
"Error watching calendar: ",
safeStringify({
selectedCalendarId: id,
error: errorMessage,
})
);
await SelectedCalendarRepository.updateById(id, {
error: `Error watching calendar: ${errorMessage}`,
});
@@ -91,7 +91,9 @@ export class CalendarCacheRepository implements ICalendarCacheRepository {
log.debug("Getting cached availability", safeStringify({ credentialId, userId, args }));
const key = parseKeyForCache(args);
let cached;
let usedInMemoryDelegationCredential = false;
if (isInMemoryDelegationCredential({ credentialId })) {
usedInMemoryDelegationCredential = true;
if (!userId) {
log.warn("userId is not available when querying cache for in-memory delegation credential");
return null;
@@ -109,6 +111,11 @@ export class CalendarCacheRepository implements ICalendarCacheRepository {
key,
expiresAt: { gte: new Date(Date.now()) },
},
orderBy: {
// In case of multiple entries for same key and userId, we prefer the one with highest expiry, which will be the most updated one
// TODO: For better tracking we could also want to use updatedAt directly which doesn't exist yet in CalendarCache table
expiresAt: "desc",
},
});
} else {
cached = await prisma.calendarCache.findUnique({
@@ -121,7 +128,10 @@ export class CalendarCacheRepository implements ICalendarCacheRepository {
},
});
}
log.info("Got cached availability", safeStringify({ key, cached }));
log.info(
"Got cached availability",
safeStringify({ key, cached, credentialId, usedInMemoryDelegationCredential })
);
return cached;
}
async upsertCachedAvailability({
@@ -96,6 +96,8 @@ Step 6: Enable Delegation Credential(To Be taken By Cal.com organization Owner/A
- Delegation Credential: A Delegation Credential service account key along with user's email becomes the Delegation Credential which is an alternative to regular Credential in DB.
- Delegation User Credential: A Delegation User Credential is a Credential record in DB that uses DelegationCredential record to actually access the user's calendar. A Credential record with delegationCredentialId set is a Delegation User Credential.
- In-DB Delegation Credential: Another name for Delegation User Credential. This is used to build the CalendarCache records.
- In-Memory Delegation Credential: It is a Credential like object but only in-memory and has id=-1. This is used to to connect with the third party Calendar. We might want to move away from In-Memory Delegation Credential to use In-DB Delegation Credential in future.
### How Delegation Credential works
@@ -109,7 +111,7 @@ Step 6: Enable Delegation Credential(To Be taken By Cal.com organization Owner/A
### Cron Jobs
Cron jobs ensure that for each and every member of the organization that has Delegation Credential enabled, corresponding SelectedCalendar records are there. These crons currently run every 5 minutes, look at vercel.json for the up-to-date schedule.
Cron jobs ensure that for each and every member of the organization that has Delegation Credential enabled, corresponding SelectedCalendar records are there. These crons currently run every 5 minutes and process a batch in one run to avoid overloading the DB and third party CalendarAPIs, look at vercel.json for the up-to-date schedule.
- `credentials` cron job creates Delegation User Credential records for all the members of the organization who don't have Delegation User Credentials yet. It also ensures that on disabling Delegation Credential, the Delegation User Credentials are deleted which automatically deletes the SelectedCalendars through DB cascade.
- `selected-calendars` cron job creates SelectedCalendar records for all the Delegation User Credentials of the organization who don't have Selected Calendars yet.
@@ -137,6 +139,7 @@ Disabling effectively stops generating in-memory delegation user credentials. So
### Impact of enabling Delegation Credential
- Existing calendar-cache records are re-used as we identify the relevant record by userId and key of CalendarCache record.
- Any updates to those calendar-cache records keep on working by using the non-delegation credential attached with the SelectedCalendar record.
- In case there is an error while watching the SelectedCalendar using non-delegation credential, we will delete the SelectedCalendar record and create a new one using Delegation User Credential.
- For any new members, we create Credential records and SelectedCalendar records through cron jobs and thus their calendar-cache records will also be created.
### Notes when testing locally
@@ -146,8 +149,3 @@ Disabling effectively stops generating in-memory delegation user credentials. So
- Make sure to change the email of the user above to your workspace owner's email(other member's email might also work). This is necessary otherwise you won't be able to enable Delegation Credential for the organization.
- Note: After changing the email, you would have to logout and login again
## TODO
- Test what happens when credential expires that was used in CalendarCache/SelectedCalendar
- It seems that if refresh token is valid then it would still be refreshed but if it becomes invalid then it ends up causing the calendar-cache updates to break because it isn't able to renew the access token. How do you fix it?
@@ -0,0 +1,53 @@
/**
* How to verify that rate limit is different for different impersonated users?
* Open two terminals
* Terminal 1: Run `node rate-limit-test-google-service-account-impersonation.js [email protected] 1000` - This makes email1 hit the limit. 1000 is much more than 600, so it gives more reliability in reaching the limit.
* Terminal 1: Run `node rate-limit-test-google-service-account-impersonation.js [email protected] 100` - Verify that email1 is still hitting the limit
* // Run this immediately after the above commands
* Terminal 2: Run `node rate-limit-test-google-service-account-impersonation.js [email protected] 100` - Check for email2's limit, it should not hit the limit
*/
const { calendar_v3 } = require("@googleapis/calendar");
const { JWT } = require("googleapis-common");
// client_email in the service account key json file
const serviceAccountClientEmail = "";
// private_key in the service account key json file
const serviceAccountPrivateKey = ``;
if (!serviceAccountClientEmail || !serviceAccountPrivateKey) {
throw new Error("serviceAccountClientEmail and serviceAccountPrivateKey must be set");
}
async function sendRequest(calendar) {
const response = await calendar.calendarList.list({
fields: `items(id),nextPageToken`,
});
console.log(response.data);
}
const args = process.argv.slice(2);
const emailToImpersonate = args[0];
const totalRequestsArg = args[1];
(async function () {
console.log({ emailToImpersonate, totalRequestsArg });
const authClient = new JWT({
email: serviceAccountClientEmail,
key: serviceAccountPrivateKey,
scopes: ["https://www.googleapis.com/auth/calendar"],
subject: emailToImpersonate,
});
await authClient.authorize();
const calendar = new calendar_v3.Calendar({
auth: authClient,
});
// 600 requests per minute is the API limit per user
const totalRequests = parseInt(totalRequestsArg) || 600;
const promises = [];
for (let i = 0; i < totalRequests; i++) {
console.log(`Queuing request ${i + 1}/${totalRequests}`);
promises.push(sendRequest(calendar));
}
await Promise.all(promises);
console.log("All requests completed");
})();
+6 -2
View File
@@ -52,7 +52,9 @@ export const getCalendarsEventsWithTimezones = async (
if (!isADelegationCredential) {
// It was done to fix the secondary calendar connections from always checking the conflicts even if intentional no calendars are selected.
// https://github.com/calcom/cal.com/issues/8929
log.error("No selected calendars for non DWD credential: Skipping getAvailability call");
log.error(
`No selected calendars for non DWD credential: Skipping getAvailability call for credential ${credential?.id}`
);
return [];
}
// For delegation credential, we should allow getAvailability even without any selected calendars. It ensures that enabling Delegation Credential at Organization level always ensure one selected calendar for conflicts checking, without requiring any manual action from organization members
@@ -118,7 +120,9 @@ const getCalendarsEvents = async (
if (!isADelegationCredential) {
// It was done to fix the secondary calendar connections from always checking the conflicts even if intentional no calendars are selected.
// https://github.com/calcom/cal.com/issues/8929
log.error("No selected calendars for non DWD credential: Skipping getAvailability call");
log.error(
`No selected calendars for non DWD credential: Skipping getAvailability call for credential ${credential?.id}`
);
return [];
}
// For delegation credential, we should allow getAvailability even without any selected calendars. It ensures that enabling Delegation Credential at Organization level always ensure one selected calendar for conflicts checking, without requiring any manual action from organization members
@@ -0,0 +1,21 @@
import { vi } from "vitest";
vi.mock("@calcom/lib/server/serviceAccountKey", async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const actual = await importOriginal<any>();
return {
...actual,
decryptServiceAccountKey: vi.fn((input) => {
// If input is a string, parse it; otherwise, return as is
if (typeof input === "string") {
try {
return JSON.parse(input);
} catch {
return input;
}
}
return input;
}),
};
});
@@ -67,7 +67,9 @@ export class SelectedCalendarRepository {
const conflictingCalendar = await SelectedCalendarRepository.findConflicting(data);
if (conflictingCalendar) {
throw new Error("Selected calendar already exists");
throw new Error(
`Selected calendar already exists for userId: ${data.userId}, integration: ${data.integration}, externalId: ${data.externalId}, eventTypeId: ${data.eventTypeId}`
);
}
return await prisma.selectedCalendar.create({
@@ -125,6 +127,14 @@ export class SelectedCalendarRepository {
});
}
static async deleteById({ id }: { id: string }) {
return await prisma.selectedCalendar.delete({
where: {
id,
},
});
}
static async createIfNotExists(data: Prisma.SelectedCalendarUncheckedCreateInput) {
const conflictingCalendar = await SelectedCalendarRepository.findConflicting(data);