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:
12 files changed
+795
-112
No files matched your search
@@ -0,0 +1,201 @@
|
||||
import prismock from "../../../../../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
|
||||
import type { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { handleCreateCredentials } from "../route";
|
||||
|
||||
type OrgParams = { id: number };
|
||||
const createOrg = async ({ id }: OrgParams) =>
|
||||
await prismock.team.create({ data: { id, name: `Org${id}`, isOrganization: true } });
|
||||
|
||||
type UserParams = { id: number; email: string };
|
||||
const createUser = async ({ id, email }: UserParams) => await prismock.user.create({ data: { id, email } });
|
||||
|
||||
type WorkspacePlatformParams = { id: number; name?: string; slug?: string; description?: string };
|
||||
const createWorkspacePlatform = async ({ id, name, slug, description }: WorkspacePlatformParams) =>
|
||||
await prismock.workspacePlatform.create({
|
||||
data: {
|
||||
id,
|
||||
name: name ?? "Google",
|
||||
slug: slug ?? "google",
|
||||
description: description ?? "Test platform",
|
||||
defaultServiceAccountKey: {},
|
||||
},
|
||||
});
|
||||
|
||||
type DelegationCredentialParams = {
|
||||
id: string;
|
||||
orgId: number;
|
||||
domain: string;
|
||||
workspacePlatformId: number;
|
||||
};
|
||||
|
||||
const createDelegationCredential = async ({
|
||||
id,
|
||||
orgId,
|
||||
domain,
|
||||
workspacePlatformId,
|
||||
}: DelegationCredentialParams) =>
|
||||
await prismock.delegationCredential.create({
|
||||
data: {
|
||||
id,
|
||||
enabled: true,
|
||||
domain,
|
||||
organizationId: orgId,
|
||||
workspacePlatformId,
|
||||
serviceAccountKey: {
|
||||
client_email: "[email protected]",
|
||||
private_key: "pk",
|
||||
client_id: "cid",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
type CredentialParams = { id?: number; userId?: number; delegationCredentialId?: string; key?: object };
|
||||
const createCredential = async ({
|
||||
id = 1,
|
||||
userId = 1,
|
||||
delegationCredentialId = "delegation-credential-1",
|
||||
key = {},
|
||||
}: CredentialParams = {}) =>
|
||||
await prismock.credential.create({
|
||||
data: {
|
||||
id,
|
||||
type: "google_calendar",
|
||||
key,
|
||||
userId,
|
||||
appId: "google_calendar",
|
||||
delegationCredentialId,
|
||||
},
|
||||
});
|
||||
|
||||
type MembershipParams = { teamId: number; userId: number; role?: MembershipRole };
|
||||
const createMembership = async ({ teamId, userId, role = "MEMBER" }: MembershipParams) =>
|
||||
await prismock.membership.create({ data: { teamId, userId, accepted: true, role } });
|
||||
|
||||
// Helper to assert credentials in DB match expected (partial, order-insensitive)
|
||||
type PartialCredential = Partial<Awaited<ReturnType<typeof prismock.credential.create>>>;
|
||||
async function expectCredentials(expected: PartialCredential[]) {
|
||||
const actual = await prismock.credential.findMany({});
|
||||
expect(actual.length).toBe(expected.length);
|
||||
expect(actual).toEqual(expect.arrayContaining(expected.map((exp) => expect.objectContaining(exp))));
|
||||
}
|
||||
|
||||
describe("Delegation Credentials: Organization-wide Google Calendar Access", () => {
|
||||
beforeEach(() => {
|
||||
prismock.delegationCredential.deleteMany();
|
||||
prismock.credential.deleteMany();
|
||||
prismock.user.deleteMany();
|
||||
prismock.team.deleteMany();
|
||||
prismock.workspacePlatform.deleteMany();
|
||||
prismock.membership.deleteMany();
|
||||
});
|
||||
|
||||
it("shows a helpful message when no Delegation Credentials are enabled", async () => {
|
||||
const result = await handleCreateCredentials();
|
||||
expect(result).toEqual({
|
||||
message: "No enabled delegation credentials found",
|
||||
success: 0,
|
||||
failures: 0,
|
||||
});
|
||||
await expectCredentials([]);
|
||||
});
|
||||
|
||||
it("creates credentials for all eligible organization members when Delegation Credential is enabled", async () => {
|
||||
const org = await createOrg({ id: 1 });
|
||||
const workspacePlatform = await createWorkspacePlatform({ id: 1 });
|
||||
const user1 = await createUser({ id: 1, email: "[email protected]" });
|
||||
const user2 = await createUser({ id: 2, email: "[email protected]" });
|
||||
await createMembership({ teamId: org.id, userId: user1.id });
|
||||
await createMembership({ teamId: org.id, userId: user2.id });
|
||||
await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: org.id,
|
||||
domain: "example.com",
|
||||
workspacePlatformId: workspacePlatform.id,
|
||||
});
|
||||
|
||||
const result = await handleCreateCredentials();
|
||||
expect(result.success).toBe(2);
|
||||
expect(result.failures).toBe(0);
|
||||
await expectCredentials([
|
||||
{ userId: user1.id, delegationCredentialId: "delegation-credential-1", type: "google_calendar" },
|
||||
{ userId: user2.id, delegationCredentialId: "delegation-credential-1", type: "google_calendar" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips credential creation for unsupported workspace platforms", async () => {
|
||||
const org = await createOrg({ id: 1 });
|
||||
// Create a non-google workspace platform
|
||||
const outlookPlatform = await createWorkspacePlatform({
|
||||
id: 2,
|
||||
name: "Outlook",
|
||||
slug: "outlook",
|
||||
description: "Test",
|
||||
});
|
||||
const user = await createUser({ id: 1, email: "[email protected]" });
|
||||
await createMembership({ teamId: org.id, userId: user.id });
|
||||
await createDelegationCredential({
|
||||
id: "delegation-credential-2",
|
||||
orgId: org.id,
|
||||
domain: "outlook.com",
|
||||
workspacePlatformId: outlookPlatform.id,
|
||||
});
|
||||
const result = await handleCreateCredentials();
|
||||
expect(result.success).toBe(0);
|
||||
await expectCredentials([]);
|
||||
});
|
||||
|
||||
it("does not create duplicate credentials for users who already have one", async () => {
|
||||
const org = await createOrg({ id: 1 });
|
||||
const workspacePlatform = await createWorkspacePlatform({ id: 1 });
|
||||
const user = await createUser({ id: 1, email: "[email protected]" });
|
||||
await createMembership({ teamId: org.id, userId: user.id });
|
||||
await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: org.id,
|
||||
domain: "example.com",
|
||||
workspacePlatformId: workspacePlatform.id,
|
||||
});
|
||||
await createCredential({ id: 1, userId: user.id, delegationCredentialId: "delegation-credential-1" });
|
||||
const result = await handleCreateCredentials();
|
||||
expect(result.success).toBe(0);
|
||||
await expectCredentials([
|
||||
{ userId: user.id, delegationCredentialId: "delegation-credential-1", type: "google_calendar" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("processes only a batch of members at a time if there are more than the batch size", async () => {
|
||||
const org = await createOrg({ id: 1 });
|
||||
const workspacePlatform = await createWorkspacePlatform({
|
||||
id: 1,
|
||||
name: "Google",
|
||||
slug: "google",
|
||||
description: "Test platform",
|
||||
});
|
||||
// Simulate more than 100 delegated members
|
||||
const users = [];
|
||||
for (let i = 1; i <= 120; i++) {
|
||||
const user = await createUser({ id: i, email: `user${i}@example.com` });
|
||||
users.push(user);
|
||||
await createMembership({ teamId: org.id, userId: user.id });
|
||||
}
|
||||
await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: org.id,
|
||||
domain: "example.com",
|
||||
workspacePlatformId: workspacePlatform.id,
|
||||
});
|
||||
const result = await handleCreateCredentials();
|
||||
expect(result.success).toBe(100); // Only batch size processed
|
||||
await expectCredentials(
|
||||
users.slice(0, 100).map((u) => ({
|
||||
userId: u.id,
|
||||
delegationCredentialId: "delegation-credential-1",
|
||||
type: "google_calendar",
|
||||
}))
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ import { DelegationCredentialRepository } from "@calcom/lib/server/repository/de
|
||||
|
||||
import { defaultResponderForAppDir } from "../../defaultResponderForAppDir";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["CreateCredentials"] });
|
||||
const moduleLogger = logger.getSubLogger({ prefix: ["[api]", "[delegation]", "[credentials/cron]"] });
|
||||
const batchSizeToCreateCredentials = 100;
|
||||
const validateRequest = (req: NextRequest) => {
|
||||
const url = new URL(req.url);
|
||||
@@ -24,9 +24,12 @@ const validateRequest = (req: NextRequest) => {
|
||||
}
|
||||
};
|
||||
|
||||
async function handleCreateCredentials() {
|
||||
export async function handleCreateCredentials() {
|
||||
const log = moduleLogger.getSubLogger({ prefix: ["CreateCredentials"] });
|
||||
const delegationCredentials = await DelegationCredentialRepository.findAllEnabledIncludeDelegatedMembers();
|
||||
|
||||
log.info(`Found ${delegationCredentials.length} enabled delegation credentials to create credentials for`);
|
||||
|
||||
if (!delegationCredentials.length) {
|
||||
return {
|
||||
message: "No enabled delegation credentials found",
|
||||
@@ -107,9 +110,12 @@ async function handleCreateCredentials() {
|
||||
}
|
||||
|
||||
async function handleDeleteCredentials() {
|
||||
const log = moduleLogger.getSubLogger({ prefix: ["DeleteCredentials"] });
|
||||
const delegationCredentials =
|
||||
await DelegationCredentialRepository.findAllDisabledAndIncludeNextBatchOfMembersToProcess();
|
||||
|
||||
log.info(`Found ${delegationCredentials.length} delegation credentials to delete credentials for`);
|
||||
|
||||
if (!delegationCredentials.length) {
|
||||
return {
|
||||
message: "No disabled delegation credentials found",
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
import prismock from "../../../../../../../tests/libs/__mocks__/prisma";
|
||||
import "@calcom/lib/server/__mocks__/serviceAccountKey";
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
|
||||
import { CalendarAppDelegationCredentialInvalidGrantError } from "@calcom/lib/CalendarAppError";
|
||||
|
||||
import { handleCreateSelectedCalendars } from "../route";
|
||||
|
||||
// Mock GoogleCalendarService
|
||||
const fetchPrimaryCalendarMock = vi.fn();
|
||||
vi.mock("@calcom/app-store/googlecalendar/lib/CalendarService", () => {
|
||||
return {
|
||||
default: vi.fn().mockImplementation(() => ({
|
||||
fetchPrimaryCalendar: fetchPrimaryCalendarMock,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
type OrgParams = { id?: number };
|
||||
const createOrg = async ({ id = 1 }: OrgParams = {}) =>
|
||||
await prismock.team.create({ data: { id, name: `Org${id}`, isOrganization: true } });
|
||||
|
||||
type UserParams = { id?: number; email?: string };
|
||||
const createUser = async ({ id = 1, email = `user${id}@example.com` }: UserParams = {}) =>
|
||||
await prismock.user.create({ data: { id, email } });
|
||||
|
||||
type WorkspacePlatformParams = { id?: number };
|
||||
const createWorkspacePlatform = async ({ id = 1 }: WorkspacePlatformParams = {}) =>
|
||||
await prismock.workspacePlatform.create({
|
||||
data: {
|
||||
id,
|
||||
name: "Google",
|
||||
slug: "google",
|
||||
description: "Test platform",
|
||||
defaultServiceAccountKey: {},
|
||||
},
|
||||
});
|
||||
|
||||
type DelegationCredentialParams = { id: string; orgId: number; domain: string };
|
||||
const createDelegationCredential = async ({ id, orgId, domain }: DelegationCredentialParams) =>
|
||||
await prismock.delegationCredential.create({
|
||||
data: {
|
||||
id,
|
||||
enabled: true,
|
||||
domain: domain ?? "example.com",
|
||||
organizationId: orgId ?? 1,
|
||||
workspacePlatformId: 1,
|
||||
serviceAccountKey: {
|
||||
client_email: "[email protected]",
|
||||
private_key: "pk",
|
||||
client_id: "cid",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
type CredentialParams = {
|
||||
id: number;
|
||||
userId: number;
|
||||
delegationCredentialId: string | null;
|
||||
key?: object;
|
||||
};
|
||||
const createCredential = async ({ id, userId, delegationCredentialId, key = {} }: CredentialParams) =>
|
||||
await prismock.credential.create({
|
||||
data: {
|
||||
id,
|
||||
type: "google_calendar",
|
||||
key,
|
||||
userId,
|
||||
appId: "google_calendar",
|
||||
delegationCredentialId,
|
||||
},
|
||||
});
|
||||
|
||||
type SelectedCalendarParams = {
|
||||
userId?: number;
|
||||
externalId?: string;
|
||||
error?: string | null;
|
||||
id?: string;
|
||||
delegationCredentialId?: string | null;
|
||||
credentialId?: number;
|
||||
};
|
||||
const createSelectedCalendar = async ({
|
||||
userId = 1,
|
||||
externalId = "[email protected]",
|
||||
error = null,
|
||||
id = `${userId}-sc`,
|
||||
delegationCredentialId = null,
|
||||
credentialId = 1,
|
||||
}: SelectedCalendarParams = {}) =>
|
||||
await prismock.selectedCalendar.create({
|
||||
data: {
|
||||
id,
|
||||
integration: "google_calendar",
|
||||
externalId,
|
||||
userId,
|
||||
delegationCredentialId,
|
||||
credentialId,
|
||||
error,
|
||||
},
|
||||
});
|
||||
|
||||
// Helper to assert selected calendars in DB match expected (partial, order-insensitive)
|
||||
type PartialSelectedCalendar = Partial<Awaited<ReturnType<typeof prismock.selectedCalendar.create>>>;
|
||||
async function expectSelectedCalendars(expected: PartialSelectedCalendar[]) {
|
||||
const actual = await prismock.selectedCalendar.findMany({});
|
||||
expect(actual.length).toBe(expected.length);
|
||||
expect(actual).toEqual(expect.arrayContaining(expected.map((exp) => expect.objectContaining(exp))));
|
||||
}
|
||||
|
||||
describe("handleCreateSelectedCalendars integration", () => {
|
||||
beforeEach(() => {
|
||||
prismock.delegationCredential.deleteMany();
|
||||
prismock.credential.deleteMany();
|
||||
prismock.selectedCalendar.deleteMany();
|
||||
prismock.user.deleteMany();
|
||||
prismock.team.deleteMany();
|
||||
prismock.workspacePlatform.deleteMany();
|
||||
fetchPrimaryCalendarMock.mockReset();
|
||||
});
|
||||
|
||||
it("shows a helpful message when no Delegation Credentials are set up in the system", async () => {
|
||||
const result = await handleCreateSelectedCalendars();
|
||||
expect(result).toEqual({
|
||||
message: "No delegation credentials found",
|
||||
success: 0,
|
||||
failures: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("automatically creates a Selected Calendar for every eligible user when Delegation Credential is enabled and user matches domain", async () => {
|
||||
await createOrg({ id: 1 });
|
||||
await createWorkspacePlatform({ id: 1 });
|
||||
const user = await createUser({ id: 1, email: "[email protected]" });
|
||||
const delegationCredential = await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: 1,
|
||||
domain: "example.com",
|
||||
});
|
||||
await createCredential({ id: 1, userId: user.id, delegationCredentialId: delegationCredential.id });
|
||||
fetchPrimaryCalendarMock.mockResolvedValue({ id: "[email protected]" });
|
||||
|
||||
const result = await handleCreateSelectedCalendars();
|
||||
expect(result.success).toBe(1);
|
||||
expect(result.failures).toBe(0);
|
||||
await expectSelectedCalendars([
|
||||
{ userId: user.id, externalId: "[email protected]", delegationCredentialId: delegationCredential.id },
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates a Selected Calendar even if the user's primary calendar ID does not match their email address", async () => {
|
||||
await createOrg({ id: 1 });
|
||||
await createWorkspacePlatform({ id: 1 });
|
||||
const user = await createUser({ id: 1, email: "[email protected]" });
|
||||
const delegationCredential = await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: 1,
|
||||
domain: "example.com",
|
||||
});
|
||||
await createCredential({ id: 1, userId: user.id, delegationCredentialId: delegationCredential.id });
|
||||
fetchPrimaryCalendarMock.mockResolvedValue({ id: "[email protected]" });
|
||||
|
||||
const result = await handleCreateSelectedCalendars();
|
||||
expect(result.success).toBe(1);
|
||||
await expectSelectedCalendars([
|
||||
{ userId: user.id, externalId: "[email protected]", delegationCredentialId: delegationCredential.id },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not create duplicate Selected Calendars for users who already have a valid one", async () => {
|
||||
await createOrg({ id: 1 });
|
||||
await createWorkspacePlatform({ id: 1 });
|
||||
const user = await createUser({ id: 1, email: "[email protected]" });
|
||||
const delegationCredential = await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: 1,
|
||||
domain: "example.com",
|
||||
});
|
||||
await createCredential({ id: 1, userId: user.id, delegationCredentialId: delegationCredential.id });
|
||||
await createSelectedCalendar({
|
||||
userId: user.id,
|
||||
externalId: "[email protected]",
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
credentialId: 1,
|
||||
});
|
||||
fetchPrimaryCalendarMock.mockResolvedValue({ id: "[email protected]" });
|
||||
|
||||
const result = await handleCreateSelectedCalendars();
|
||||
expect(result.success).toBe(0);
|
||||
await expectSelectedCalendars([
|
||||
{ userId: user.id, externalId: "[email protected]", delegationCredentialId: delegationCredential.id },
|
||||
]);
|
||||
});
|
||||
|
||||
it("replaces a Selected Calendar if the existing one has an error, ensuring users always have a working calendar connection", async () => {
|
||||
await createOrg({ id: 1 });
|
||||
await createWorkspacePlatform({ id: 1 });
|
||||
const user = await createUser({ id: 1, email: "[email protected]" });
|
||||
const delegationCredential = await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: 1,
|
||||
domain: "example.com",
|
||||
});
|
||||
// Create a Delegation User Credential
|
||||
await createCredential({
|
||||
id: 2,
|
||||
userId: user.id,
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
});
|
||||
// Create a Regular User Credential
|
||||
const regularCredential = await createCredential({
|
||||
id: 1,
|
||||
userId: user.id,
|
||||
delegationCredentialId: null,
|
||||
});
|
||||
// Create a SelectedCalendar attached to regular credential
|
||||
await createSelectedCalendar({
|
||||
userId: user.id,
|
||||
externalId: "[email protected]",
|
||||
error: "some error" as unknown as null,
|
||||
credentialId: regularCredential.id,
|
||||
});
|
||||
fetchPrimaryCalendarMock.mockResolvedValue({ id: "[email protected]" });
|
||||
|
||||
const result = await handleCreateSelectedCalendars();
|
||||
expect(result.success).toBe(1);
|
||||
await expectSelectedCalendars([
|
||||
{
|
||||
userId: user.id,
|
||||
externalId: "[email protected]",
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
error: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
describe("when GoogleCalendarService throws error", () => {
|
||||
it("creates SelectedCalendar with user.email when CalendarAppDelegationCredentialInvalidGrantError is thrown", async () => {
|
||||
await createOrg({ id: 1 });
|
||||
await createWorkspacePlatform({ id: 1 });
|
||||
const user = await createUser({ id: 1, email: "[email protected]" });
|
||||
const delegationCredential = await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: 1,
|
||||
domain: "example.com",
|
||||
});
|
||||
await createCredential({ id: 1, userId: user.id, delegationCredentialId: delegationCredential.id });
|
||||
fetchPrimaryCalendarMock.mockRejectedValue(
|
||||
new CalendarAppDelegationCredentialInvalidGrantError("some error")
|
||||
);
|
||||
|
||||
const result = await handleCreateSelectedCalendars();
|
||||
expect(result.success).toBe(1);
|
||||
await expectSelectedCalendars([
|
||||
{ userId: user.id, externalId: "[email protected]", delegationCredentialId: delegationCredential.id },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not create SelectedCalendar when some other error than CalendarAppDelegationCredentialInvalidGrantError is thrown", async () => {
|
||||
await createOrg({ id: 1 });
|
||||
await createWorkspacePlatform({ id: 1 });
|
||||
const user = await createUser({ id: 1, email: "[email protected]" });
|
||||
const delegationCredential = await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: 1,
|
||||
domain: "example.com",
|
||||
});
|
||||
await createCredential({ id: 1, userId: user.id, delegationCredentialId: delegationCredential.id });
|
||||
fetchPrimaryCalendarMock.mockRejectedValue(new Error("some error"));
|
||||
|
||||
const result = await handleCreateSelectedCalendars();
|
||||
expect(result.success).toBe(0);
|
||||
await expectSelectedCalendars([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import GoogleCalendarService from "@calcom/app-store/googlecalendar/lib/CalendarService";
|
||||
import { CalendarAppDelegationCredentialInvalidGrantError } from "@calcom/lib/CalendarAppError";
|
||||
import { findUniqueDelegationCalendarCredential } from "@calcom/lib/delegationCredential/server";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
@@ -19,7 +20,7 @@ import type { Ensure } from "@calcom/types/utils";
|
||||
import { defaultResponderForAppDir } from "../../defaultResponderForAppDir";
|
||||
|
||||
const limitOnQueryingGoogleCalendar = 50;
|
||||
const log = logger.getSubLogger({ prefix: ["[api] selected-calendars/cron"] });
|
||||
const log = logger.getSubLogger({ prefix: ["[api]", "[delegation]", "[selected-calendars/cron]"] });
|
||||
const validateRequest = (req: NextRequest) => {
|
||||
const url = new URL(req.url);
|
||||
const apiKey = req.headers.get("authorization") || url.searchParams.get("apiKey");
|
||||
@@ -28,13 +29,191 @@ const validateRequest = (req: NextRequest) => {
|
||||
}
|
||||
};
|
||||
|
||||
async function handleCreateSelectedCalendars() {
|
||||
type DelegationUserCredential = Awaited<
|
||||
ReturnType<typeof CredentialRepository.findAllDelegationByTypeIncludeUserAndTake>
|
||||
>[number];
|
||||
|
||||
type DelegationUserCredentialWithEnsuredUser = Ensure<DelegationUserCredential, "user">;
|
||||
|
||||
async function getDelegationUserCredentialsToProcess(delegationUserCredentials: DelegationUserCredential[]) {
|
||||
const delegationUserCredentialsToProcess = await Promise.all(
|
||||
delegationUserCredentials
|
||||
.filter(
|
||||
(delegationUserCredential): delegationUserCredential is DelegationUserCredentialWithEnsuredUser =>
|
||||
delegationUserCredential.user !== null
|
||||
)
|
||||
.map(async (delegationUserCredential) => {
|
||||
const userEmail = delegationUserCredential.user.email;
|
||||
// Consider existing SelectedCalendars for this user, regardless of credentialId as we want to reuse the existing SelectedCalendar(which has their googleChannel related column set) after Delegation Credential has been enabled
|
||||
// It is also important because SelectedCalendar has composite unique constraint on userId, externalId and integration and thus we couldn't have the same values for different credentialId
|
||||
const selectedCalendar = await SelectedCalendarRepository.findFirst({
|
||||
where: {
|
||||
userId: delegationUserCredential.user.id,
|
||||
externalId: userEmail,
|
||||
integration: "google_calendar",
|
||||
},
|
||||
});
|
||||
|
||||
if (selectedCalendar) {
|
||||
if (selectedCalendar.delegationCredentialId === delegationUserCredential.delegationCredentialId) {
|
||||
// In case this SelectedCalendar has an error, we would let CalendarCache cron handle it
|
||||
log.info(
|
||||
`Found an existing SelectedCalendar for userId: ${delegationUserCredential.user.id} and delegationCredentialId: ${delegationUserCredential.delegationCredentialId}`
|
||||
);
|
||||
return null;
|
||||
}
|
||||
if (!selectedCalendar.error) {
|
||||
log.info(`Found a reusable SelectedCalendar for userId: ${delegationUserCredential.user.id}`);
|
||||
return null;
|
||||
} else {
|
||||
log.error(
|
||||
`Found reusable Non-Delegation SelectedCalendar for ${delegationUserCredential.user.id} but it has an error: '${selectedCalendar.error}', so deleting it, new one will be created`
|
||||
);
|
||||
|
||||
// We found a SelectedCalendar attached to non-delegation credential, so we shouldn't reuse it as the non-delegation credential attached to it could be invalid
|
||||
// So, we delete it so that SelectedCalendarRepository allow creating a similar one with Delegation Credential
|
||||
// Also, we don't delete the possibly invalid credential due to false alarm and we would need that intact in case we disable Delegation Credential
|
||||
// Because credential isn't deleted, the corresponding CalendarCache entry would still exist and thus we will end up having two CalendarCache entries for same key and userId with different credentialId
|
||||
await SelectedCalendarRepository.deleteById({ id: selectedCalendar.id });
|
||||
return delegationUserCredential;
|
||||
}
|
||||
}
|
||||
return delegationUserCredential;
|
||||
})
|
||||
);
|
||||
|
||||
return delegationUserCredentialsToProcess.filter(
|
||||
(credential): credential is DelegationUserCredentialWithEnsuredUser => credential !== null
|
||||
);
|
||||
}
|
||||
|
||||
async function getCalendarService(delegationUserCredential: DelegationUserCredentialWithEnsuredUser) {
|
||||
const credentialForCalendarService = await findUniqueDelegationCalendarCredential({
|
||||
userId: delegationUserCredential.user.id,
|
||||
delegationCredentialId: delegationUserCredential.delegationCredentialId,
|
||||
});
|
||||
|
||||
if (!credentialForCalendarService) {
|
||||
log.error(
|
||||
`Credential not found for delegationCredentialId: ${delegationUserCredential.delegationCredentialId} and userId: ${delegationUserCredential.user.id}`
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
!credentialForCalendarService.delegatedTo ||
|
||||
!credentialForCalendarService.delegatedTo.serviceAccountKey ||
|
||||
!credentialForCalendarService.delegatedTo.serviceAccountKey.client_email
|
||||
) {
|
||||
log.error(
|
||||
`Invalid delegatedTo for delegationCredentialId: ${delegationUserCredential.delegationCredentialId}`,
|
||||
safeStringify({
|
||||
delegatedToSet: !!credentialForCalendarService.delegatedTo,
|
||||
serviceAccountKeySet: !!credentialForCalendarService.delegatedTo?.serviceAccountKey,
|
||||
clientEmailSet: !!credentialForCalendarService.delegatedTo?.serviceAccountKey?.client_email,
|
||||
})
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const googleCalendarService = new GoogleCalendarService(
|
||||
credentialForCalendarService as CredentialForCalendarServiceWithEmail
|
||||
);
|
||||
|
||||
return googleCalendarService;
|
||||
}
|
||||
|
||||
async function fetchPrimaryCalendarId({
|
||||
googleCalendarService,
|
||||
delegationUserCredential,
|
||||
}: {
|
||||
googleCalendarService: GoogleCalendarService;
|
||||
delegationUserCredential: DelegationUserCredentialWithEnsuredUser;
|
||||
}) {
|
||||
let primaryCalendarId;
|
||||
const userEmail = delegationUserCredential.user.email;
|
||||
|
||||
try {
|
||||
const primaryCalendar = await googleCalendarService.fetchPrimaryCalendar();
|
||||
primaryCalendarId = primaryCalendar?.id;
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`Error fetching primary calendar for delegationCredentialId: ${delegationUserCredential.delegationCredentialId}, credentialId: ${delegationUserCredential.id} and userId: ${delegationUserCredential.userId}`,
|
||||
safeStringify(error)
|
||||
);
|
||||
|
||||
if (error instanceof CalendarAppDelegationCredentialInvalidGrantError) {
|
||||
// It is known to happen in case [email protected] is the user email and the actual email is [email protected]. Google rejects the authorization for [email protected]
|
||||
log.info(
|
||||
`Error seems to be that the email isn't present in the third party workspace, further attempts would fail too, so we assume the user's email as the primary calendar id to skip this user in future cron runs`
|
||||
);
|
||||
// If we are unable to fetch the primary calendar, we assume the user's email as the primary calendar id
|
||||
// It ensures that this calendar is skipped in the future cron runs
|
||||
primaryCalendarId = userEmail;
|
||||
}
|
||||
}
|
||||
|
||||
return primaryCalendarId;
|
||||
}
|
||||
|
||||
async function processDelegationUserCredential(
|
||||
delegationUserCredential: DelegationUserCredentialWithEnsuredUser
|
||||
) {
|
||||
try {
|
||||
const userEmail = delegationUserCredential.user.email;
|
||||
const googleCalendarService = await getCalendarService(delegationUserCredential);
|
||||
if (!googleCalendarService) {
|
||||
return;
|
||||
}
|
||||
|
||||
const externalCalendarId = await fetchPrimaryCalendarId({
|
||||
googleCalendarService,
|
||||
delegationUserCredential,
|
||||
});
|
||||
|
||||
if (!externalCalendarId) {
|
||||
log.error(
|
||||
`External calendar not found for delegationCredentialId: ${delegationUserCredential.delegationCredentialId}, credentialId: ${delegationUserCredential.id} and userId: ${delegationUserCredential.userId}`
|
||||
);
|
||||
throw new Error("externalCalendarId could not be determined");
|
||||
}
|
||||
|
||||
if (externalCalendarId !== userEmail) {
|
||||
// We don't know the scenario when Delegation Credential allows access to an email that is not the primary calendar email
|
||||
// So log a warning for further investigation
|
||||
log.warn(
|
||||
`External calendar id mismatch for delegationCredentialId: ${delegationUserCredential.delegationCredentialId}, credentialId: ${delegationUserCredential.id} and userId: ${delegationUserCredential.userId}`,
|
||||
safeStringify({
|
||||
externalCalendarId,
|
||||
userEmail,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
await SelectedCalendarRepository.create({
|
||||
integration: "google_calendar",
|
||||
externalId: externalCalendarId,
|
||||
userId: delegationUserCredential.user.id,
|
||||
delegationCredentialId: delegationUserCredential.delegationCredentialId,
|
||||
credentialId: delegationUserCredential.id,
|
||||
});
|
||||
|
||||
log.debug(`Created SelectedCalendar for user ${delegationUserCredential.userId}`);
|
||||
} catch (error) {
|
||||
log.error(`Error processing credential ${delegationUserCredential.id}:`, safeStringify(error));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleCreateSelectedCalendars() {
|
||||
// These are in DB delegation user credentials in contrast to in-memory delegation user credentials that are used elsewhere
|
||||
const allDelegationUserCredentials = await CredentialRepository.findAllDelegationByTypeIncludeUserAndTake({
|
||||
type: "google_calendar",
|
||||
take: limitOnQueryingGoogleCalendar,
|
||||
});
|
||||
|
||||
log.info(`Found ${allDelegationUserCredentials.length} delegation user credentials to process`);
|
||||
|
||||
if (!allDelegationUserCredentials.length) {
|
||||
const message = "No delegation credentials found";
|
||||
log.info(message);
|
||||
@@ -57,106 +236,16 @@ async function handleCreateSelectedCalendars() {
|
||||
for (const [delegationCredentialId, delegationUserCredentials] of Object.entries(
|
||||
groupedDelegationUserCredentials
|
||||
)) {
|
||||
// First, create an array of promises that check if each credential should be processed
|
||||
const checkedDelegationUserCredentials = await Promise.all(
|
||||
delegationUserCredentials.map(async (delegationUserCredential) => {
|
||||
if (!delegationUserCredential.user) {
|
||||
log.error(`Credential ${delegationUserCredential.id} has no user`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get all selectedCalendars for this user, regardless of credentialId as we want to reuse the existing SelectedCalendar(which has their googleChannel related column set) after Delegation Credential has been enabled
|
||||
const hasSelectedCalendarForUserEmail = !!(await SelectedCalendarRepository.findFirst({
|
||||
where: {
|
||||
userId: delegationUserCredential.user.id,
|
||||
externalId: delegationUserCredential.user.email,
|
||||
},
|
||||
}));
|
||||
|
||||
if (hasSelectedCalendarForUserEmail) {
|
||||
log.info(`Found a reusable SelectedCalendar for ${delegationUserCredential.user.id}`);
|
||||
return null;
|
||||
}
|
||||
return delegationUserCredential;
|
||||
})
|
||||
log.info(`Processing delegation user credentials for delegationCredentialId: ${delegationCredentialId}`);
|
||||
const delegationUserCredentialsToProcess = await getDelegationUserCredentialsToProcess(
|
||||
delegationUserCredentials
|
||||
);
|
||||
|
||||
const delegationUserCredentialsToProcess = checkedDelegationUserCredentials.filter(
|
||||
(credential): credential is Ensure<(typeof delegationUserCredentials)[number], "user"> =>
|
||||
credential !== null
|
||||
);
|
||||
|
||||
log.info(
|
||||
`Found ${delegationUserCredentialsToProcess.length} delegationUserCredentials to process for delegationCredentialId: ${delegationCredentialId}`
|
||||
);
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
delegationUserCredentialsToProcess.map(async (delegationUserCredential) => {
|
||||
try {
|
||||
const credentialForCalendarService = await findUniqueDelegationCalendarCredential({
|
||||
userId: delegationUserCredential.user.id,
|
||||
delegationCredentialId: delegationUserCredential.delegationCredentialId,
|
||||
});
|
||||
|
||||
if (!credentialForCalendarService) {
|
||||
log.error(
|
||||
`Credential not found for delegationCredentialId: ${delegationUserCredential.delegationCredentialId} and userId: ${delegationUserCredential.user.id}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!credentialForCalendarService.delegatedTo ||
|
||||
!credentialForCalendarService.delegatedTo.serviceAccountKey ||
|
||||
!credentialForCalendarService.delegatedTo.serviceAccountKey.client_email
|
||||
) {
|
||||
log.error(
|
||||
`Invalid delegatedTo for delegationCredentialId: ${delegationUserCredential.delegationCredentialId}`,
|
||||
safeStringify({
|
||||
delegatedToSet: !!credentialForCalendarService.delegatedTo,
|
||||
serviceAccountKeySet: !!credentialForCalendarService.delegatedTo?.serviceAccountKey,
|
||||
clientEmailSet: !!credentialForCalendarService.delegatedTo?.serviceAccountKey?.client_email,
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const googleCalendarService = new GoogleCalendarService(
|
||||
credentialForCalendarService as CredentialForCalendarServiceWithEmail
|
||||
);
|
||||
|
||||
let primaryCalendar;
|
||||
try {
|
||||
primaryCalendar = await googleCalendarService.fetchPrimaryCalendar();
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`Error fetching primary calendar for delegationCredentialId: ${delegationUserCredential.delegationCredentialId} and userId: ${delegationUserCredential.userId}`,
|
||||
safeStringify(error)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!primaryCalendar || !primaryCalendar.id) {
|
||||
log.error(
|
||||
`Primary calendar not found for delegationCredentialId: ${delegationUserCredential.delegationCredentialId} and userId: ${delegationUserCredential.userId}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await SelectedCalendarRepository.create({
|
||||
integration: "google_calendar",
|
||||
externalId: primaryCalendar.id,
|
||||
userId: delegationUserCredential.user.id,
|
||||
delegationCredentialId: delegationUserCredential.delegationCredentialId,
|
||||
credentialId: delegationUserCredential.id,
|
||||
});
|
||||
|
||||
log.debug(`Created SelectedCalendar for user ${delegationUserCredential.userId}`);
|
||||
} catch (error) {
|
||||
log.error(`Error processing credential ${delegationUserCredential.id}:`, safeStringify(error));
|
||||
throw error;
|
||||
}
|
||||
})
|
||||
delegationUserCredentialsToProcess.map(processDelegationUserCredential)
|
||||
);
|
||||
const successCount = results.filter((r) => r.status === "fulfilled").length;
|
||||
const failureCount = results.filter((r) => r.status === "rejected").length;
|
||||
|
||||
Reference in new issue
Block a user