feat: Domain-wide delegation for Google Calendar and Google Meet (#16622)

* Add endpoints for testing the flow

* Add MVP

* new route

* Fixes

* Fixes

* Remove enable toggle support from domainWideDelegation

* Fixes

* Revert "Remove enable toggle support from domainWideDelegation"

This reverts commit c29e729206cd1fa063f9c9ce0cf148ef1577d60b.

* Revert yarn.lock

* More fixes

* Fix new workspace platform add

* refactor: improvements

* refactor: bug fixes and improvements

* fix: type errors

* fix: conflicts

* chore: update test

* fix: logic

* chore: improvements

* fix: toglle

* fix: bugs

* fix: type err

* chore: check number type

* fix: after conflicts

* chore: fix type err

* fix: type errors and tests

* fix: tets

* test

* chore: remove unused

* fix: google meet url on booking page and secondary calendar

* fix: add property

* fix: type err

* fix: re assingment bug

* fix: use getAllCredentials

* chore: fix import

* fix: installed count

* fix: pass event type

* fix: import

* fix: [Stacked PR] Review fixes (#17958)

* Review fixes

* fix: destination calendar bug

---------

Co-authored-by: Udit Takkar <[email protected]>

* refactor: use repository

* chore: remove duplicate

* fix: More review fixes for domain wide delegation (#17969)

* Reuse buildCredentialPayloadForCalendar

* fixes

---------

Co-authored-by: Udit Takkar <[email protected]>

* fix ts error

* Fix getSchedule not using dwd credentials (#17995)

* fix: Remove direct DWD table access from google-calendar and remove delegatedToId column from Credential (#18015)

* Remove fn rename to reduce number of files changed

* chore: check feature globally

* test: add unit tests

* chore: move function

* test: add booking test

* wip

* Remove domain-wide-delegation team feature flag

* Make sure duplicate calendars are not shown due to DWD. Show DWD when there is conflict

* Fix tests and their ts errors

* Fix more tests

* Move findUsersForAvailabilityCheck to separate file as it has AppStore dependency causing problem with Routing Forms. Build crashes

* fix: Multiple calendar connections from Google not showing up in apps/installed

* DestinationCalendar must have either credentialId or domainWideDeelgationId. Also handle the case when DWD is disabled and there was a non-dwd credential that could be used

* Disable deletetion of DWD as it is destructive and prefer disabling instead

* Show DWD credential calendars at the top

* Fixed tests

* Calendar Cache DWD support

* Self-Review: Verify email required and add more selectedCalendar tests

* Self Review: shorten names

* Self ReviewL Dead code removal

* Revert "Calendar Cache DWD support"

This reverts commit 009f236470fa21eba5986117d4f6e4d4c5e38c34.

* Some misc fixes

* fixes

* Performance improvememt in slots loading and booking

* More cases for handling dwd credentials

* simplify the logic. Ensure that EventManager and the modules below it in the flow have CredentialForCalendarService available

* Fix tests

* Fix installed/conferencing not showing gogole meet

* Shorten name

* Fix ApI v2 tests

* Add some more tests

* add getSchedule tests

* Improve tests

* Make Google Meet default when DWD for google is enabled

* Enable feature flagging for DWD

* chore: bump libraries

* Encrypt serviceaccount private key

* Fix ts errors

* bump platform libraries

* org add dwd

* org add dwd

* bump platform libraries

* fix selected calendars

* fix remove selected dwd calendar

* remove oauthclient id aliad in authedCalendar

* remove oauthclient id aliad in authedCalendar

* refactor: OrganizationsDwdController

* chore: export toggleDwdEnabled from platform-libraries

* feat: v2 update (enable / disable) dwd

* refactor: SelectedCalendarsController check if user belongs to dwd org & for not dwd use previous logic

* wip: DestinationCalendar send domainWideDelegationCredentialId from frontend to api

* try fix set destination calendar api v2

* fixup! try fix set destination calendar api v2

* setting google meet as default location working for dwd

* bump platform libraries version

* allow office 365 workspace slug

* allow office 365 workspace slug

* chore: v2 create dwd MS and Google service keys input

* fix: CreateDwdInput serviceAccountKey

* fix: CredentialForCalendarService type

* fix: check workspace slug

* feat: update serviceAccessKey of DWD

* testing

* fixup! testing

* fix: getAuthUtl bug

* fix: unit tests

* fix: type err and unit test

* fix: e2e test

* fix: credentials bug and failing unit tests

* Update CalendarService.ts

* chore: refactor office365 calendar service and add testDomainWideDelegationSetup

* fix: office365Calendar use correct clientId/Secret for DWD

* fix: office365Calendar dwd no need refresh token

* test: add unit test for outlook dwd and setup

* feat: added dwd support for office365 calendar

* feat: added dwd support for office365 video

* test: finish test for outlook dwd

* fix: create dialog bug

* chore: remove console logs

* fix: refreshToken bug

* bump version libraries

* refactor: fetch dwd credentials only in findQualifiedHosts

* fixup! refactor: fetch dwd credentials only in findQualifiedHosts

* fix: type err

* fix: type err

* fix: getUserDisplayName

* fix: unit test

* chore: bump platform lib

---------

Co-authored-by: Syed Ali Shahbaz <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Morgan Vernay <[email protected]>
Co-authored-by: supalarry <[email protected]>
Co-authored-by: Somay Chauhan <[email protected]>
Co-authored-by: Morgan <[email protected]>
This commit is contained in:
173 files changed
+12277 -1137

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
export class CalendarAppError extends Error {
constructor(message: string) {
super(message);
this.name = "CalendarAppError";
}
}
export class CalendarAppDomainWideDelegationError extends CalendarAppError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationError";
}
}
export class CalendarAppDomainWideDelegationConfigurationError extends CalendarAppDomainWideDelegationError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationConfigurationError";
}
}
export class CalendarAppDomainWideDelegationInvalidGrantError extends CalendarAppDomainWideDelegationError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationInvalidGrantError";
}
}
export class CalendarAppDomainWideDelegationClientIdNotAuthorizedError extends CalendarAppDomainWideDelegationConfigurationError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationClientIdNotAuthorizedError";
}
}
export class CalendarAppDomainWideDelegationNotSetupError extends CalendarAppDomainWideDelegationConfigurationError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationNotSetupError";
}
}
@@ -4,6 +4,8 @@ import type { CredentialDataWithTeamName } from "@calcom/app-store/utils";
import getApps from "@calcom/app-store/utils";
import { prisma } from "@calcom/prisma";
import { isDwdCredential } from "../domainWideDelegation/clientAndServer";
type EnabledApp = ReturnType<typeof getApps>[number] & { enabled: boolean };
/**
@@ -30,6 +32,10 @@ const getEnabledAppsFromCredentials = async (
},
} satisfies Prisma.AppWhereInput;
const dwdCredentialsWithAppId = credentials
.filter((credential) => isDwdCredential({ credentialId: credential.id }))
.filter((credential): credential is typeof credential & { appId: string } => credential.appId !== null);
if (filterOnCredentials) {
const userIds: number[] = [],
teamIds: number[] = [];
@@ -48,10 +54,23 @@ const getEnabledAppsFromCredentials = async (
...(filterOnIds.credentials.some.OR.length && filterOnIds),
};
const enabledApps = await prisma.app.findMany({
let enabledApps = await prisma.app.findMany({
where,
select: { slug: true, enabled: true },
});
const dwdSupportedEnabledApps = await prisma.app.findMany({
where: {
enabled: true,
slug: {
in: dwdCredentialsWithAppId.map((credential) => credential.appId),
},
},
select: { slug: true, enabled: true },
});
enabledApps = [...enabledApps, ...dwdSupportedEnabledApps];
const apps = getApps(credentials, filterOnCredentials);
const filteredApps = apps.reduce((reducedArray, app) => {
const appDbQuery = enabledApps.find((metadata) => metadata.slug === app.slug);
@@ -1,6 +1,6 @@
import logger from "@calcom/lib/logger";
import type { SelectedCalendar } from "@calcom/prisma/client";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { RoutingFormResponse } from "../server/getLuckyUser";
import { getOrderedListOfLuckyUsers } from "../server/getLuckyUser";
@@ -12,7 +12,7 @@ export const errorCodes = {
type BaseUser = {
id: number;
email: string;
credentials: CredentialPayload[];
credentials: CredentialForCalendarService[];
userLevelSelectedCalendars: SelectedCalendar[];
} & Record<string, unknown>;
@@ -6,7 +6,7 @@ import type { Mock } from "vitest";
import { SchedulingType } from "@calcom/prisma/enums";
import { filterHostsByLeadThreshold } from "./filterHostsByLeadThreshold";
import { findQualifiedHosts } from "./findQualifiedHosts";
import { findQualifiedHostsWithDwdCredentials } from "./findQualifiedHostsWithDwdCredentials";
import * as getRoutedUsers from "./getRoutedUsers";
// Mock the filterHostsByLeadThreshold function
@@ -21,7 +21,7 @@ afterEach(() => {
(filterHostsByLeadThreshold as Mock).mockClear();
});
describe("findQualifiedHosts", async () => {
describe("findQualifiedHostsWithDwdCredentials", async () => {
it("should return qualified hosts based on mock of filterHostsByLeadThreshold", async () => {
const hosts = [
{
@@ -88,7 +88,7 @@ describe("findQualifiedHosts", async () => {
};
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: null,
@@ -139,7 +139,7 @@ describe("findQualifiedHosts", async () => {
};
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: null,
@@ -225,7 +225,7 @@ describe("findQualifiedHosts", async () => {
};
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: null,
@@ -313,7 +313,7 @@ describe("findQualifiedHosts", async () => {
};
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [1],
rescheduleUid: null,
@@ -390,7 +390,7 @@ describe("findQualifiedHosts", async () => {
};
prismaMock.booking.findFirst.mockResolvedValue({ userId: 2 });
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: "recheduleUid",
@@ -464,12 +464,12 @@ describe("findQualifiedHosts", async () => {
},
};
vi.spyOn(getRoutedUsers, "findMatchingHostsWithEventSegment").mockImplementation(async () => [hosts[0]]);
const filterSpy = vi.spyOn(Array.prototype, "filter");
const findMatchingHostsSpy = vi
.spyOn(getRoutedUsers, "findMatchingHostsWithEventSegment")
.mockImplementation(async () => [hosts[0]]);
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [0, 1, 2],
rescheduleUid: null,
@@ -477,14 +477,23 @@ describe("findQualifiedHosts", async () => {
routingFormResponse: null,
});
// check if we returned early after segment matching only returned one host
expect(filterSpy).toHaveBeenCalledTimes(2);
// Verify the result
expect(result).toEqual({
qualifiedRRHosts: [hosts[0]],
fixedHosts: [],
});
// Verify that findMatchingHostsWithEventSegment was called with correct parameters
expect(findMatchingHostsSpy).toHaveBeenCalledWith({
eventType,
hosts: hosts.filter((host) => !host.isFixed), // Only round-robin hosts should be passed
});
// Verify that filterHostsByLeadThreshold was not called since we returned early
expect(filterHostsByLeadThreshold).not.toHaveBeenCalled();
// Verify that allFallbackRRHosts is not present in the result
expect(result).not.toHaveProperty("allFallbackRRHosts");
});
it("should filter for segment matching and routed team member ids", async () => {
@@ -553,7 +562,7 @@ describe("findQualifiedHosts", async () => {
]);
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [2, 3],
rescheduleUid: null,
@@ -652,7 +661,7 @@ describe("findQualifiedHosts", async () => {
(filterHostsByLeadThreshold as Mock).mockResolvedValue(rrHostsAfterFairness);
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [2, 3],
rescheduleUid: null,
@@ -1,8 +1,11 @@
import { findMatchingHostsWithEventSegment, getNormalizedHosts } from "@calcom/lib/bookings/getRoutedUsers";
import {
findMatchingHostsWithEventSegment,
getNormalizedHostsWithDwdCredentials,
} from "@calcom/lib/bookings/getRoutedUsers";
import type { EventType } from "@calcom/lib/bookings/getRoutedUsers";
import type { SelectedCalendar } from "@calcom/prisma/client";
import type { SchedulingType } from "@calcom/prisma/enums";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import type { RoutingFormResponse } from "../server/getLuckyUser";
import { filterHostsByLeadThreshold } from "./filterHostsByLeadThreshold";
@@ -43,7 +46,7 @@ const isFixedHost = <T extends { isFixed: boolean }>(host: T): host is T & { isF
return host.isFixed;
};
export const findQualifiedHosts = async <
export const findQualifiedHostsWithDwdCredentials = async <
T extends {
email: string;
id: number;
@@ -76,14 +79,14 @@ export const findQualifiedHosts = async <
createdAt: Date | null;
priority?: number | null;
weight?: number | null;
user: T;
user: Omit<T, "credentials"> & { credentials: CredentialForCalendarService[] };
}[];
fixedHosts: {
isFixed: boolean;
createdAt: Date | null;
priority?: number | null;
weight?: number | null;
user: T;
user: Omit<T, "credentials"> & { credentials: CredentialForCalendarService[] };
}[];
// all hosts we want to fallback to including the qualifiedRRHosts (fairness + crm contact owner)
allFallbackRRHosts?: {
@@ -91,10 +94,14 @@ export const findQualifiedHosts = async <
createdAt: Date | null;
priority?: number | null;
weight?: number | null;
user: T;
user: Omit<T, "credentials"> & { credentials: CredentialForCalendarService[] };
}[];
}> => {
const { hosts: normalizedHosts, fallbackHosts: fallbackUsers } = getNormalizedHosts({ eventType });
const { hosts: normalizedHosts, fallbackHosts: fallbackUsers } = await getNormalizedHostsWithDwdCredentials(
{
eventType,
}
);
// not a team event type, or some other reason - segment matching isn't necessary.
if (!normalizedHosts) {
const fixedHosts = fallbackUsers.filter(isFixedHost);
+63
View File
@@ -3,6 +3,10 @@ import { findTeamMembersMatchingAttributeLogic } from "@calcom/lib/raqb/findTeam
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
import { safeStringify } from "@calcom/lib/safeStringify";
import { SchedulingType } from "@calcom/prisma/enums";
import type { CredentialPayload } from "@calcom/types/Credential";
import { enrichHostsWithDwdCredentials } from "../domainWideDelegation/server";
import getOrgIdFromMemberOrTeamId from "../getOrgIdFromMemberOrTeamId";
const log = logger.getSubLogger({ prefix: ["[getRoutedUsers]"] });
@@ -113,6 +117,65 @@ export function getNormalizedHosts<User extends BaseUser, Host extends BaseHost<
};
}
}
type BaseUserWithCredentialPayload = BaseUser & { credentials: CredentialPayload[] };
export async function getNormalizedHostsWithDwdCredentials<
User extends BaseUserWithCredentialPayload,
Host extends BaseHost<User>
>({
eventType,
}: {
eventType: {
schedulingType: SchedulingType | null;
hosts?: Host[];
users: User[];
teamId?: number;
};
}) {
if (eventType.hosts?.length && eventType.schedulingType) {
const hostsWithoutDwd = eventType.hosts.map((host) => ({
isFixed: host.isFixed,
user: host.user,
priority: host.priority,
weight: host.weight,
createdAt: host.createdAt,
}));
const firstHost = hostsWithoutDwd[0];
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
memberId: firstHost?.user?.id ?? null,
teamId: eventType.teamId,
});
const hostsEnrichedWithDwd = await enrichHostsWithDwdCredentials({
orgId: firstUserOrgId ?? null,
hosts: hostsWithoutDwd ?? null,
});
return {
hosts: hostsEnrichedWithDwd,
fallbackHosts: null,
};
} else {
const hostsWithoutDwd = eventType.users.map((user) => {
return {
isFixed: !eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE,
email: user.email,
user: user,
createdAt: null,
};
});
const firstHost = hostsWithoutDwd[0];
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
memberId: firstHost?.user?.id ?? null,
teamId: eventType.teamId,
});
const hostsEnrichedWithDwd = await enrichHostsWithDwdCredentials({
orgId: firstUserOrgId ?? null,
hosts: hostsWithoutDwd ?? null,
});
return {
hosts: null,
fallbackHosts: hostsEnrichedWithDwd,
};
}
}
// We don't allow fixed hosts when segment matching is enabled
// If this ever changes, we need to update this function and return fixed hosts
+3
View File
@@ -142,6 +142,9 @@ export const CREDENTIAL_SYNC_SECRET_HEADER_NAME =
export const CREDENTIAL_SYNC_ENDPOINT = process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT;
// Service Account Encryption Key for encrypting/decrypting service account keys
export const SERVICE_ACCOUNT_ENCRYPTION_KEY = process.env.CALCOM_SERVICE_ACCOUNT_ENCRYPTION_KEY;
export const DEFAULT_LIGHT_BRAND_COLOR = "#292929";
export const DEFAULT_DARK_BRAND_COLOR = "#fafafa";
@@ -0,0 +1,27 @@
export function isDwdCredential({ credentialId }: { credentialId: number | null | undefined }) {
// Though it is set as -1 right now, but we might want to set it to some other negative value.
return typeof credentialId === "number" && credentialId < 0;
}
export const buildNonDwdCredential = <T extends Record<string, unknown> | null>(credential: T) => {
type WithDelegatedCredential = T extends null
? null
: T & {
delegatedTo: null;
delegatedToId: null;
};
if (!credential) return null as WithDelegatedCredential;
return {
...credential,
delegatedTo: null,
delegatedToId: null,
} as WithDelegatedCredential;
};
export const buildNonDwdCredentials = <T extends Record<string, unknown>>(credentials: T[]) => {
return credentials.map(buildNonDwdCredential).filter((credential) => !!credential) as (T & {
delegatedTo: null;
delegatedToId: null;
})[];
};
@@ -0,0 +1,612 @@
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
import { describe, it, expect, beforeEach, vi } from "vitest";
import { metadata as googleCalendarMetadata } from "@calcom/app-store/googlecalendar/_metadata";
import { metadata as googleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
import type { ServiceAccountKey } from "@calcom/lib/server/repository/domainWideDelegation";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import { SMSLockState } from "@calcom/prisma/enums";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import {
getAllDwdCredentialsForUser,
buildAllCredentials,
getDwdOrRegularCredential,
enrichUsersWithDwdCredentials,
enrichHostsWithDwdCredentials,
enrichUserWithDwdCredentialsWithoutOrgId,
enrichUserWithDwdConferencingCredentialsWithoutOrgId,
} from "./server";
// Mock OrganizationRepository
vi.mock("@calcom/lib/server/repository/organization", () => ({
OrganizationRepository: {
findByMemberEmail: vi.fn(),
},
}));
// Mock DomainWideDelegationRepository
vi.mock("@calcom/lib/server/repository/domainWideDelegation", () => ({
DomainWideDelegationRepository: {
findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey: vi.fn(),
findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey: vi.fn(),
},
}));
const mockUser = {
email: "[email protected]",
id: 123,
};
const mockServiceAccountKey: ServiceAccountKey = {
client_email: "[email protected]",
client_id: "123456789",
private_key: "-----BEGIN PRIVATE KEY-----\nMIIE....\n-----END PRIVATE KEY-----\n",
};
const mockWorkspacePlatform = {
name: "Test Platform",
slug: "google",
};
const mockDwd = {
id: "dwd-1",
enabled: true,
domain: "example.com",
organizationId: 1,
serviceAccountKey: mockServiceAccountKey,
workspacePlatform: mockWorkspacePlatform,
createdAt: new Date(),
updatedAt: new Date(),
};
// Mock organization data
const mockOrganization = {
id: 1,
name: "Test Org",
metadata: {},
bio: null,
timeZone: "UTC",
weekStart: "Monday",
hideBranding: false,
theme: null,
timeFormat: null,
brandColor: null,
darkBrandColor: null,
createdAt: new Date(),
includeManagedEventsInLimits: false,
smsLockState: SMSLockState.LOCKED,
smsLockReviewedByAdmin: false,
slug: "test-org",
logoUrl: null,
bannerUrl: null,
isPrivate: false,
isOrganization: true,
isOrganizationVerified: true,
isOrganizationConfigured: true,
isOrganizationAdminReviewed: true,
orgAutoAcceptEmail: "example.com",
orgProfileRedirectsToVerifiedDomain: false,
allowSEOIndexing: true,
calVideoLogo: null,
appLogo: null,
appIconLogo: null,
hideBookATeamMember: false,
hideTeam: false,
hideCalendarNotes: false,
eventTypeMatchParentTeam: false,
lockEventTypeCreationForUsers: false,
parentId: null,
pendingPayment: false,
isPlatform: false,
createdByOAuthClientId: null,
bookingLimits: null,
};
// Credential Builders
const buildDwdCredential = (overrides = {}) => ({
type: "google_calendar",
appId: "google-calendar",
id: -1,
delegatedToId: mockDwd.id,
userId: mockUser.id,
user: { email: mockUser.email },
key: { access_token: "NOOP_UNUSED_DELEGATION_TOKEN" },
invalid: false,
teamId: null,
team: null,
delegatedTo: {
serviceAccountKey: mockServiceAccountKey,
},
...overrides,
});
const buildDwdGoogleCalendarCredential = (overrides = {}) => ({
...buildDwdCredential({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
}),
...overrides,
});
const buildDwdGoogleMeetCredential = (overrides = {}) => ({
...buildDwdCredential({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
}),
...overrides,
});
const buildRegularCredential = (overrides = {}): CredentialForCalendarService => ({
type: "google_calendar",
appId: "google-calendar",
id: 1,
userId: mockUser.id,
user: { email: mockUser.email },
key: JSON.stringify(mockServiceAccountKey),
invalid: false,
teamId: null,
delegatedToId: null,
delegatedTo: null,
...overrides,
});
const buildRegularGoogleCalendarCredential = (overrides = {}): CredentialPayload => ({
...buildRegularCredential({
appId: "google-calendar",
type: "google_calendar",
}),
...overrides,
});
const buildMockWorkspacePlatform = (overrides: Partial<typeof mockWorkspacePlatform> = {}) => ({
name: "Test Platform",
slug: "google",
...overrides,
});
const buildMockDwd = (overrides: Partial<typeof mockDwd> = {}) => ({
...mockDwd,
workspacePlatform: buildMockWorkspacePlatform(overrides.workspacePlatform || {}),
...overrides,
});
describe("getAllDwdCredentialsForUser", () => {
setupAndTeardown();
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(OrganizationRepository.findByMemberEmail).mockResolvedValue(mockOrganization);
});
it("should return empty array when no DWD found", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await getAllDwdCredentialsForUser({ user: mockUser });
expect(result).toEqual([]);
});
it("should return empty array when DWD is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
const result = await getAllDwdCredentialsForUser({ user: mockUser });
expect(result).toEqual([]);
});
it("should return credentials for enabled Google DWD", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await getAllDwdCredentialsForUser({ user: mockUser });
expect(result).toHaveLength(2);
expect(result).toEqual([buildDwdGoogleCalendarCredential(), buildDwdGoogleMeetCredential()]);
});
it("should return empty array for non-Google platforms(as they are not supported yet)", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(
buildMockDwd({
workspacePlatform: {
name: "Microsoft",
slug: "microsoft",
},
})
);
const result = await getAllDwdCredentialsForUser({ user: mockUser });
expect(result).toEqual([]);
});
});
describe("buildAllCredentials", () => {
const mockDwdGoogleCalendarCred = buildDwdGoogleCalendarCredential();
const mockRegularGoogleCalendarCred = buildRegularGoogleCalendarCredential();
it("should combine DWD and regular credentials", () => {
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred],
existingCredentials: [mockRegularGoogleCalendarCred],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDwdGoogleCalendarCred);
expect(result).toContainEqual(mockRegularGoogleCalendarCred);
});
it("should deduplicate DWD credentials with same delegatedToId and appId", () => {
const duplicateDwdCredential = buildDwdGoogleCalendarCredential();
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred, duplicateDwdCredential],
existingCredentials: [],
});
expect(result).toHaveLength(1);
expect(result[0]).toEqual(mockDwdGoogleCalendarCred);
});
it("should keep DWD credentials with same delegatedToId but different appId", () => {
const differentAppDwdCredential = buildDwdGoogleMeetCredential();
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred, differentAppDwdCredential],
existingCredentials: [],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDwdGoogleCalendarCred);
expect(result).toContainEqual(differentAppDwdCredential);
});
it("should filter out DWD credentials from existingCredentials", () => {
const dwdCalendarCredential = buildRegularGoogleCalendarCredential({ id: -2 });
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred],
existingCredentials: [mockRegularGoogleCalendarCred, dwdCalendarCredential],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDwdGoogleCalendarCred);
expect(result).toContainEqual(mockRegularGoogleCalendarCred);
});
});
describe("getDwdOrRegularCredential", () => {
const mockDwdGoogleCalendarCred = buildDwdGoogleCalendarCredential();
const mockRegularGoogleCalendarCred = buildRegularGoogleCalendarCredential();
const credentials = [mockDwdGoogleCalendarCred, mockRegularGoogleCalendarCred];
it("should find DWD credential by dwdId", () => {
const result = getDwdOrRegularCredential({
credentials,
id: { credentialId: null, dwdId: mockDwd.id },
});
expect(result).toEqual(mockDwdGoogleCalendarCred);
});
it("should find regular credential by credentialId", () => {
const result = getDwdOrRegularCredential({
credentials,
id: { credentialId: mockRegularGoogleCalendarCred.id, dwdId: null },
});
expect(result).toEqual(mockRegularGoogleCalendarCred);
});
it("should return null when no matching credential found", () => {
const result = getDwdOrRegularCredential({
credentials,
id: { credentialId: 999, dwdId: null },
});
expect(result).toBeNull();
});
it("should not match null to null for delegatedToId", () => {
const result = getDwdOrRegularCredential({
credentials,
id: { credentialId: null, dwdId: null },
});
expect(result).toBeNull();
});
});
describe("enrichUsersWithDwdCredentials", () => {
const mockUsers = [
{
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
},
{
id: 456,
email: "[email protected]",
credentials: [buildRegularGoogleCalendarCredential({ id: 2 })],
},
];
beforeEach(() => {
vi.clearAllMocks();
});
it("should return users as is when orgId is null", async () => {
const result = await enrichUsersWithDwdCredentials({
orgId: null,
users: mockUsers,
});
expect(result).toEqual(
mockUsers.map((user) => ({
...user,
credentials: user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
}))
);
});
it("should enrich users with DWD credentials when available", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await enrichUsersWithDwdCredentials({
orgId: 1,
users: mockUsers,
});
expect(result).toHaveLength(2);
result.forEach((enrichedUser) => {
expect(enrichedUser.credentials).toHaveLength(3); // 1 regular + 2 DWD (calendar + meet)
expect(enrichedUser.credentials).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
})
);
expect(enrichedUser.credentials).toContainEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
});
it("should not add DWD credentials when DWD is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
const result = await enrichUsersWithDwdCredentials({
orgId: 1,
users: mockUsers,
});
expect(result).toEqual(
mockUsers.map((user) => ({
...user,
credentials: user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
}))
);
});
});
describe("enrichHostsWithDwdCredentials", () => {
const mockHosts = [
{
user: {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
},
metadata: { key: "value" },
},
{
user: {
id: 456,
email: "[email protected]",
credentials: [buildRegularGoogleCalendarCredential({ id: 2 })],
},
metadata: { key: "value2" },
},
];
beforeEach(() => {
vi.clearAllMocks();
});
it("should return hosts as is when orgId is null", async () => {
const result = await enrichHostsWithDwdCredentials({
orgId: null,
hosts: mockHosts,
});
expect(result).toEqual(
mockHosts.map((host) => ({
...host,
user: {
...host.user,
credentials: host.user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
},
}))
);
});
it("should enrich hosts with DWD credentials when available", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await enrichHostsWithDwdCredentials({
orgId: 1,
hosts: mockHosts,
});
expect(result).toHaveLength(2);
result.forEach((enrichedHost) => {
expect(enrichedHost.metadata).toBeDefined(); // Preserve non-user data
expect(enrichedHost.user.credentials).toHaveLength(3); // 1 regular + 2 DWD (calendar + meet)
expect(enrichedHost.user.credentials).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
})
);
expect(enrichedHost.user.credentials).toContainEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
});
it("should not add DWD credentials when DWD is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
const result = await enrichHostsWithDwdCredentials({
orgId: 1,
hosts: mockHosts,
});
expect(result).toEqual(
mockHosts.map((host) => ({
...host,
user: {
...host.user,
credentials: host.user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
},
}))
);
});
});
describe("enrichUserWithDwdCredentialsWithoutOrgId", () => {
const mockUserWithCredentials = {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
};
beforeEach(() => {
vi.clearAllMocks();
});
it("should enrich user with DWD credentials when available", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await enrichUserWithDwdCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result.credentials).toHaveLength(3); // 1 regular + 2 DWD (calendar + meet)
expect(result.credentials).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
})
);
expect(result.credentials).toContainEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
it("should not add DWD credentials when DWD is not found", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await enrichUserWithDwdCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result).toEqual({
...mockUserWithCredentials,
credentials: mockUserWithCredentials.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
});
});
it("should not add DWD credentials when DWD is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
const result = await enrichUserWithDwdCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result).toEqual({
...mockUserWithCredentials,
credentials: mockUserWithCredentials.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
});
});
});
describe("enrichUserWithDwdConferencingCredentialsWithoutOrgId", () => {
const mockUserWithCredentials = {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
};
beforeEach(() => {
vi.clearAllMocks();
});
it("should only return conferencing credentials", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await enrichUserWithDwdConferencingCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result.credentials).toHaveLength(1); // Only Google Meet
expect(result.credentials[0]).toEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
it("should return empty credentials array when no conferencing credentials found", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await enrichUserWithDwdConferencingCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result.credentials).toEqual([]);
});
});
+459
View File
@@ -0,0 +1,459 @@
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { metadata as googleCalendarMetadata } from "@calcom/app-store/googlecalendar/_metadata";
import { metadata as googleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
import { metadata as office365CalendarMetaData } from "@calcom/app-store/office365calendar/_metadata";
import { metadata as office365VideoMetaData } from "@calcom/app-store/office365video/_metadata";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import type { ServiceAccountKey } from "@calcom/lib/server/repository/domainWideDelegation";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import { buildNonDwdCredentials, isDwdCredential } from "./clientAndServer";
export { buildNonDwdCredentials, buildNonDwdCredential } from "./clientAndServer";
const GOOGLE_WORKSPACE_SLUG = "google";
const OFFICE365_WORKSPACE_SLUG = "office365";
const WORKSPACE_PLATFORM_SLUGS = [GOOGLE_WORKSPACE_SLUG, OFFICE365_WORKSPACE_SLUG] as const;
type WORKSPACE_PLATFORM_SLUGS_TYPE = (typeof WORKSPACE_PLATFORM_SLUGS)[number];
const log = logger.getSubLogger({ prefix: ["lib/domainWideDelegation/server"] });
interface DomainWideDelegation {
id: string;
workspacePlatform: {
slug: string;
};
serviceAccountKey: ServiceAccountKey | null;
}
interface DomainWideDelegationWithSensitiveServiceAccountKey extends DomainWideDelegation {
serviceAccountKey: ServiceAccountKey;
}
interface User {
email: string;
id: number;
}
const isValidWorkspaceSlug = (slug: string) => {
return WORKSPACE_PLATFORM_SLUGS.includes(slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE);
};
const getDwdAppMetadata = (slug: WORKSPACE_PLATFORM_SLUGS_TYPE, isConferencing?: boolean) => {
switch (slug) {
case GOOGLE_WORKSPACE_SLUG:
return isConferencing
? { type: googleMeetMetadata.type, appId: googleMeetMetadata.slug }
: { type: googleCalendarMetadata.type, appId: googleCalendarMetadata.slug };
case OFFICE365_WORKSPACE_SLUG:
return isConferencing
? { type: office365VideoMetaData.type, appId: office365VideoMetaData.slug }
: { type: office365CalendarMetaData.type, appId: office365CalendarMetaData.slug };
default:
throw new Error("App metadata does not exist");
}
};
const _isConferencingCredential = (credential: CredentialPayload) => {
return (
credential.type.endsWith("_video") ||
credential.type.endsWith("_conferencing") ||
credential.type.endsWith("_messaging")
);
};
const _buildCommonUserCredential = ({ dwd, user }: { dwd: DomainWideDelegation; user: User }) => {
return {
id: -1,
delegatedToId: dwd.id,
userId: user.id,
user: {
email: user.email,
},
key: {
access_token: "NOOP_UNUSED_DELEGATION_TOKEN",
},
invalid: false,
teamId: null,
team: null,
delegatedTo: dwd.serviceAccountKey
? {
serviceAccountKey: dwd.serviceAccountKey,
}
: null,
};
};
const _buildDwdCalendarCredential = ({ dwd, user }: { dwd: DomainWideDelegation; user: User }) => {
log.debug("buildDomainWideDelegationCredential", safeStringify({ dwd, user }));
// TODO: Build for other platforms as well
if (!isValidWorkspaceSlug(dwd.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
dwd.workspacePlatform.slug
}`
);
return null;
}
return {
...getDwdAppMetadata(dwd.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE, false),
..._buildCommonUserCredential({ dwd, user }),
};
};
const _buildDwdCalendarCredentialWithServiceAccountKey = ({
dwd,
user,
}: {
dwd: DomainWideDelegationWithSensitiveServiceAccountKey;
user: User;
}) => {
const credential = _buildDwdCalendarCredential({ dwd, user });
if (!credential) {
return null;
}
return {
...credential,
delegatedTo: {
serviceAccountKey: dwd.serviceAccountKey,
},
};
};
const _buildDwdConferencingCredential = ({ dwd, user }: { dwd: DomainWideDelegation; user: User }) => {
// TODO: Build for other platforms as well
if (!isValidWorkspaceSlug(dwd.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
dwd.workspacePlatform.slug
}`
);
return null;
}
return {
...getDwdAppMetadata(dwd.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE, true),
..._buildCommonUserCredential({ dwd, user }),
};
};
/**
* Gets calendar as well as conferencing credentials(stored in-memory) for the user from the corresponding enabled DomainWideDelegation.
*/
export async function getAllDwdCredentialsForUser({ user }: { user: { email: string; id: number } }) {
log.debug("called with", safeStringify({ user }));
// We access the repository without checking for feature flag here.
// In case we need to disable the effects of DWD on credential we need to toggle DWD off from organization settings.
// We could think of the teamFeatures flag to just disable the UI. The actual effect of DWD on credentials is disabled by toggling DWD off from UI
const dwd =
await DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
email: user.email,
});
if (!dwd || !dwd.enabled) {
return [];
}
const domainWideDelegationCredentials = [
_buildDwdCalendarCredential({ dwd, user }),
_buildDwdConferencingCredential({ dwd, user }),
].filter((credential): credential is NonNullable<typeof credential> => credential !== null);
log.debug("Returned", safeStringify({ domainWideDelegationCredentials }));
return domainWideDelegationCredentials;
}
export async function getAllDwdCalendarCredentialsForUser({ user }: { user: { email: string; id: number } }) {
const dwdCredentials = await getAllDwdCredentialsForUser({ user });
return dwdCredentials.filter((credential) => credential.type.endsWith("_calendar"));
}
async function _getDwdCredentialsMapPerUser({
organizationId,
users,
}: {
organizationId: number | null;
users: User[];
}) {
const emptyMap = new Map<number, NonNullable<ReturnType<typeof _buildDwdCalendarCredential>>[]>();
if (!organizationId) {
return emptyMap;
}
const domain = users[0].email.split("@")[1];
log.debug("called with", safeStringify({ users }));
const dwd =
await DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
{
organizationId,
domain,
}
);
if (!dwd || !dwd.enabled) {
return emptyMap;
}
const credentialsByUserId = new Map<
number,
NonNullable<ReturnType<typeof _buildDwdCalendarCredential>>[]
>();
for (const user of users) {
const domainWideDelegationCredentials = [
_buildDwdCalendarCredential({ dwd, user }),
_buildDwdConferencingCredential({ dwd, user }),
].filter((credential): credential is NonNullable<typeof credential> => credential !== null);
log.debug("Returned for user", safeStringify({ user, domainWideDelegationCredentials }));
credentialsByUserId.set(user.id, domainWideDelegationCredentials);
}
return credentialsByUserId;
}
export async function checkIfSuccessfullyConfiguredInWorkspace({
dwd,
user,
}: {
dwd: DomainWideDelegationWithSensitiveServiceAccountKey;
user: User;
}) {
if (!isValidWorkspaceSlug(dwd.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
dwd.workspacePlatform.slug
}`
);
return false;
}
const credential = _buildDwdCalendarCredentialWithServiceAccountKey({
dwd,
user,
});
const calendar = await getCalendar(credential);
if (!calendar) {
throw new Error("Google Calendar App not found");
}
return await calendar?.testDomainWideDelegationSetup?.();
}
export async function getAllDwdCredentialsForUserByAppType({
user,
appType,
}: {
user: User;
appType: string;
}) {
const dwdCredentials = await getAllDwdCredentialsForUser({
user,
});
return dwdCredentials.filter((credential) => credential.type === appType);
}
export async function getAllDwdCredentialsForUserByAppSlug({
user,
appSlug,
}: {
user: User;
appSlug: string;
}) {
const dwdCredentials = await getAllDwdCredentialsForUser({ user });
return dwdCredentials.filter((credential) => credential.appId === appSlug);
}
type Host<TUser extends { id: number; email: string; credentials: CredentialPayload[] }> = {
user: TUser;
};
/**
* Prepares credentials for use by CalendarService and EventManager
* - Ensures no duplicate dwd credentials caused by enrichment at possibly multiple places
*/
export const buildAllCredentials = ({
dwdCredentials,
existingCredentials,
}: {
dwdCredentials: CredentialForCalendarService[];
existingCredentials: CredentialPayload[];
}) => {
const nonDwdCredentials = existingCredentials.filter((cred) => !isDwdCredential({ credentialId: cred.id }));
const allCredentials: CredentialForCalendarService[] = [
...dwdCredentials,
...buildNonDwdCredentials(nonDwdCredentials),
];
const uniqueAllCredentials = allCredentials.reduce((acc, credential) => {
if (!credential.delegatedToId) {
// Regular credential go as is
acc.push(credential);
return acc;
}
const existingDwdCredential = acc.find(
(c) => c.delegatedToId === credential.delegatedToId && c.appId === credential.appId
);
if (!existingDwdCredential) {
acc.push(credential);
}
return acc;
}, [] as typeof allCredentials);
return uniqueAllCredentials;
};
export async function enrichUsersWithDwdCredentials<
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({ orgId, users }: { orgId: number | null; users: TUser[] }) {
const dwdCredentialsMap = await _getDwdCredentialsMapPerUser({
organizationId: orgId,
users,
});
const enrichedUsers = users.map((user) => {
const { credentials, ...rest } = user;
const enrichedCredentials = buildAllCredentials({
dwdCredentials: dwdCredentialsMap.get(user.id) ?? [],
existingCredentials: credentials,
});
return {
...rest,
credentials: enrichedCredentials,
};
});
log.debug("enrichUsersWithDwdCredentials", safeStringify({ enrichedUsers, orgId }));
return enrichedUsers;
}
export const enrichHostsWithDwdCredentials = async <
THost extends Host<TUser>,
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({
orgId,
hosts,
}: {
orgId: number | null;
hosts: THost[];
}) => {
const dwdCredentialsMap = await _getDwdCredentialsMapPerUser({
organizationId: orgId,
users: hosts.map((host) => host.user),
});
const enrichedHosts = hosts.map((host) => {
const { credentials, ...restUser } = host.user;
return {
...host,
user: {
...restUser,
credentials: buildAllCredentials({
dwdCredentials: dwdCredentialsMap.get(restUser.id) ?? [],
existingCredentials: credentials,
}),
},
};
});
log.debug("enrichHostsWithDwdCredentials", safeStringify({ enrichedHosts, orgId }));
return enrichedHosts;
};
export const enrichUserWithDwdCredentialsWithoutOrgId = async <
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({
user,
}: {
user: TUser;
}) => {
const dwdCredentials = await getAllDwdCredentialsForUser({ user });
const { credentials, ...restUser } = user;
return {
...restUser,
credentials: buildAllCredentials({
dwdCredentials: dwdCredentials,
existingCredentials: credentials,
}),
};
};
export async function enrichUserWithDwdConferencingCredentialsWithoutOrgId<
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({ user }: { user: TUser }) {
const { credentials, ...restUser } = await enrichUserWithDwdCredentialsWithoutOrgId({ user });
return {
...restUser,
credentials: credentials.filter(_isConferencingCredential),
};
}
/**
* Either get DWD credential from dwdCredentials or find regular credential from Credential table
*/
export async function getDwdOrFindRegularCredential({
id,
dwdCredentials,
}: {
id: {
credentialId: number | null | undefined;
domainWideDelegationCredentialId: string | null | undefined;
};
dwdCredentials: CredentialForCalendarService[];
}) {
return id.domainWideDelegationCredentialId
? dwdCredentials.find((cred) => cred.delegatedToId === id.domainWideDelegationCredentialId)
: id.credentialId
? await CredentialRepository.findCredentialForCalendarServiceById({
id: id.credentialId,
})
: null;
}
/**
* Utility function to find a credential from a list of credentials, supporting both regular and DWD credentials
*/
export function getDwdOrRegularCredential<TCredential extends { delegatedToId?: string | null; id: number }>({
credentials,
id,
}: {
credentials: TCredential[];
id: { credentialId: number | null | undefined; dwdId: string | null | undefined };
}) {
return (
credentials.find((cred) => {
// Ensure that we don't match null to null
if (cred.delegatedToId) {
return cred.delegatedToId === id.dwdId;
} else if (id.credentialId) {
return cred.id === id.credentialId;
}
return false;
}) || null
);
}
export function getFirstDwdConferencingCredential({
credentials,
}: {
credentials: CredentialForCalendarService[];
}) {
return credentials.find((credential) => _isConferencingCredential(credential));
}
export function getFirstDwdConferencingCredentialAppLocation({
credentials,
}: {
credentials: CredentialForCalendarService[];
}) {
const dwdConferencingCredential = getFirstDwdConferencingCredential({ credentials });
if (dwdConferencingCredential?.appId === googleMeetMetadata.slug) {
return googleMeetMetadata.appData?.location?.type ?? null;
}
if (dwdConferencingCredential?.appId === office365VideoMetaData.slug) {
return office365VideoMetaData.appData?.location?.type ?? null;
}
return null;
}
+12 -4
View File
@@ -11,9 +11,10 @@ import { MembershipRole } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TeamQuery } from "@calcom/trpc/server/routers/loggedInViewer/integrations.handler";
import type { TIntegrationsInputSchema } from "@calcom/trpc/server/routers/loggedInViewer/integrations.schema";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { PaymentApp } from "@calcom/types/PaymentService";
import { buildNonDwdCredentials } from "./domainWideDelegation/clientAndServer";
export type ConnectedApps = Awaited<ReturnType<typeof getConnectedApps>>;
export async function getConnectedApps({
@@ -21,7 +22,7 @@ export async function getConnectedApps({
prisma,
input,
}: {
user: Pick<User, "id" | "name" | "avatarUrl"> & { avatar?: string };
user: Pick<User, "id" | "name" | "avatarUrl" | "email"> & { avatar?: string };
prisma: PrismaClient;
input: TIntegrationsInputSchema;
}) {
@@ -33,6 +34,7 @@ export async function getConnectedApps({
extendsFeature,
teamId,
sortByMostPopular,
sortByInstalledFirst,
appId,
} = input;
let credentials = await getUsersCredentials(user);
@@ -103,8 +105,8 @@ export async function getConnectedApps({
userTeams = [...teamsQuery, ...parentTeams];
const teamAppCredentials: CredentialPayload[] = userTeams.flatMap((teamApp) => {
return teamApp.credentials ? teamApp.credentials.flat() : [];
const teamAppCredentials = userTeams.flatMap((teamApp) => {
return teamApp.credentials ? buildNonDwdCredentials(teamApp.credentials.flat()) : [];
});
if (!includeTeamInstalledApps || teamId) {
credentials = teamAppCredentials;
@@ -226,6 +228,12 @@ export async function getConnectedApps({
});
}
if (sortByInstalledFirst) {
apps.sort((a, b) => {
return (a.isInstalled ? 0 : 1) - (b.isInstalled ? 0 : 1);
});
}
return {
items: apps,
};
@@ -1,4 +1,6 @@
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import logger from "@calcom/lib/logger";
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
@@ -14,7 +16,7 @@ const log = logger.getSubLogger({ prefix: ["getConnectedDestinationCalendarsAndE
type ReturnTypeGetConnectedCalendars = Awaited<ReturnType<typeof getConnectedCalendars>>;
type ConnectedCalendarsFromGetConnectedCalendars = ReturnTypeGetConnectedCalendars["connectedCalendars"];
export type UserWithCalendars = Pick<User, "id"> & {
export type UserWithCalendars = Pick<User, "id" | "email"> & {
allSelectedCalendars: Pick<SelectedCalendar, "externalId" | "integration" | "eventTypeId">[];
userLevelSelectedCalendars: Pick<SelectedCalendar, "externalId" | "integration" | "eventTypeId">[];
destinationCalendar: DestinationCalendar | null;
@@ -24,6 +26,51 @@ export type ConnectedDestinationCalendars = Awaited<
ReturnType<typeof getConnectedDestinationCalendarsAndEnsureDefaultsInDb>
>;
/**
* Ensures that when DWD is enabled and there is already a calendar connected for the corresponding domain, we only allow the DWD calendar to be returned
* This is to ensure that duplicate calendar connections aren't shown in UI(apps/installed/calendars). We choose DWD connection to be shown because we don't want users to be able to work with individual calendars
*/
const _ensureNoConflictingNonDwdConnectedCalendar = <
T extends {
integration: { slug: string };
primary?: { email?: string | null | undefined } | undefined;
domainWideDelegationCredentialId?: string | null | undefined;
}
>({
connectedCalendars,
loggedInUser,
}: {
connectedCalendars: T[];
loggedInUser: { email: string };
}) => {
return connectedCalendars.filter((connectedCalendar, index, array) => {
const allCalendarsWithSameAppSlug = array.filter(
(cal) => cal.integration.slug === connectedCalendar.integration.slug
);
// If no other calendar with this slug, keep it
if (allCalendarsWithSameAppSlug.length === 1) return true;
const dwdCalendarsWithSameAppSlug = allCalendarsWithSameAppSlug.filter(
(cal) => cal.domainWideDelegationCredentialId
);
if (!dwdCalendarsWithSameAppSlug.length) {
return true;
}
if (connectedCalendar.domainWideDelegationCredentialId) {
return true;
}
// DWD Credential is always of the loggedInUser
if (!connectedCalendar.primary?.email || connectedCalendar.primary.email !== loggedInUser.email) {
return true;
}
return false;
});
};
async function handleNoConnectedCalendars(user: UserWithCalendars) {
log.debug(`No connected calendars, deleting destination calendar if it exists for user ${user.id}`);
@@ -69,6 +116,7 @@ async function handleNoDestinationCalendar({
integration = "",
externalId = "",
credentialId,
domainWideDelegationCredentialId,
email: primaryEmail,
} = connectedCalendars[0].primary ?? {};
@@ -91,8 +139,14 @@ async function handleNoDestinationCalendar({
userId: user.id,
integration,
externalId,
credentialId,
primaryEmail,
...(!isDwdCredential({ credentialId })
? {
credentialId,
}
: {
domainWideDelegationCredentialId,
}),
},
});
@@ -231,9 +285,13 @@ export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
select: credentialForCalendarServiceSelect,
});
const { credentials: allCredentials } = await enrichUserWithDwdCredentialsWithoutOrgId({
user: { id: user.id, email: user.email, credentials: userCredentials },
});
const selectedCalendars = getSelectedCalendars({ user, eventTypeId: eventTypeId ?? null });
// get user's credentials + their connected integrations
const calendarCredentials = getCalendarCredentials(userCredentials);
const calendarCredentials = getCalendarCredentials(allCredentials);
// get all the connected integrations' calendars (from third party)
const getConnectedCalendarsResult = await getConnectedCalendars(
@@ -305,8 +363,12 @@ export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
});
}
return {
const noConflictingNonDwdConnectedCalendars = _ensureNoConflictingNonDwdConnectedCalendar({
connectedCalendars,
loggedInUser: { email: user.email },
});
return {
connectedCalendars: noConflictingNonDwdConnectedCalendars,
destinationCalendar: {
...(user.destinationCalendar as DestinationCalendar),
...destinationCalendar,
+6 -2
View File
@@ -9,6 +9,7 @@ import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/crede
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "../domainWideDelegation/server";
import { getBookerBaseUrl } from "../getBookerUrl/server";
async function getEventType(id: number) {
@@ -102,9 +103,12 @@ export async function getBooking(bookingId: number) {
const eventType = { ...eventTypeRaw, metadata: EventTypeMetaDataSchema.parse(eventTypeRaw?.metadata) };
const { user } = booking;
const { user: userWithoutDwdCredentials } = booking;
if (!user) throw new HttpCode({ statusCode: 204, message: "No user found" });
if (!userWithoutDwdCredentials) throw new HttpCode({ statusCode: 204, message: "No user found" });
const user = await enrichUserWithDwdCredentialsWithoutOrgId({
user: userWithoutDwdCredentials,
});
const t = await getTranslation(user.locale ?? "en", "common");
const attendeesListPromises = booking.attendees.map(async (attendee) => {
@@ -0,0 +1,28 @@
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
export function buildCredentialPayloadForPrisma({
credentialId,
domainWideDelegationCredentialId,
}: {
credentialId: number | null | undefined;
domainWideDelegationCredentialId: string | null | undefined;
}) {
if (credentialId === undefined) {
return {
credentialId,
domainWideDelegationCredentialId,
};
}
if (isDwdCredential({ credentialId })) {
return {
credentialId: null,
domainWideDelegationCredentialId,
};
} else {
return {
credentialId,
domainWideDelegationCredentialId: null,
};
}
}
@@ -0,0 +1,29 @@
import type { Prisma } from "@prisma/client";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { availabilityUserSelect } from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { withSelectedCalendars } from "./withSelectedCalendars";
export async function findUsersForAvailabilityCheck({ where }: { where: Prisma.UserWhereInput }) {
const user = await prisma.user.findFirst({
where,
select: {
...availabilityUserSelect,
selectedCalendars: true,
credentials: {
select: credentialForCalendarServiceSelect,
},
},
});
if (!user) {
return null;
}
return await enrichUserWithDwdCredentialsWithoutOrgId({
user: withSelectedCalendars(user),
});
}
@@ -9,6 +9,7 @@ import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = {
id: SessionUser["id"];
email: SessionUser["email"];
metadata: SessionUser["metadata"];
};
+3 -3
View File
@@ -15,7 +15,7 @@ import type { SelectedCalendar } from "@calcom/prisma/client";
import type { AttributeType } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
import type { EventBusyDate } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import { mergeOverlappingRanges } from "../date-ranges";
@@ -69,7 +69,7 @@ interface GetLuckyUserParams<T extends PartialUser> {
user: {
id: number;
email: string;
credentials: CredentialPayload[];
credentials: CredentialForCalendarService[];
userLevelSelectedCalendars: SelectedCalendar[];
};
createdAt: Date;
@@ -381,7 +381,7 @@ async function getCurrentMonthCalendarBusyTimes(
usersWithCredentials: {
id: number;
email: string;
credentials: CredentialPayload[];
credentials: CredentialForCalendarService[];
userLevelSelectedCalendars: SelectedCalendar[];
}[]
): Promise<{ userId: number; busyTimes: (EventBusyDate & { timeZone?: string })[] }[]> {
+17 -3
View File
@@ -2,9 +2,14 @@ import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = { id: SessionUser["id"] };
import { enrichUserWithDwdCredentialsWithoutOrgId } from "../domainWideDelegation/server";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = { id: SessionUser["id"]; email: SessionUser["email"] };
/**
* It includes in-memory DWD credentials as well.
*/
export async function getUsersCredentials(user: User) {
const credentials = await prisma.credential.findMany({
where: {
@@ -15,5 +20,14 @@ export async function getUsersCredentials(user: User) {
id: "asc",
},
});
return credentials;
const { credentials: allCredentials } = await enrichUserWithDwdCredentialsWithoutOrgId({
user: {
email: user.email,
id: user.id,
credentials,
},
});
return allCredentials;
}
@@ -0,0 +1,341 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it, beforeEach, vi } from "vitest";
import { encryptServiceAccountKey } from "@calcom/lib/server/serviceAccountKey";
import { DomainWideDelegationRepository } from "../domainWideDelegation";
import { OrganizationRepository } from "../organization";
vi.mock("../organization", () => ({
OrganizationRepository: {
findByMemberEmail: vi.fn(),
},
}));
// Mock service account key functions
vi.mock("@calcom/lib/crypto", async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const actual = await importOriginal<any>();
return {
...actual,
symmetricEncrypt: vi.fn((serviceAccountKey) => {
console.log({ mockEncrypted: serviceAccountKey });
return `encrypted(${serviceAccountKey})`;
}),
symmetricDecrypt: vi.fn((serviceAccountKey) => {
return serviceAccountKey.replace(/^encrypted\((.*)\)$/, "$1");
}),
};
});
// Test Data Helpers
const buildMockServiceAccountKey = () => ({
client_email: "[email protected]",
private_key: "private-key",
client_id: "client-id",
additional_field: "value",
});
const buildMockEncryptedServiceAccountKey = () => ({
client_email: "[email protected]",
client_id: "client-id",
encrypted_credentials: 'encrypted({"private_key":"private-key"})',
additional_field: "value",
});
const buildMockWorkspacePlatform = () => ({
id: 1,
name: "Test Platform",
slug: "test-platform",
});
const buildMockOrganization = () => ({
id: 1,
name: "Test Organization",
isOrganization: true,
});
const buildMockDomainWideDelegation = (overrides = {}) => ({
id: "test-id",
enabled: true,
domain: "example.com",
organizationId: 1,
workspacePlatformId: 1,
serviceAccountKey: buildMockServiceAccountKey(),
workspacePlatform: buildMockWorkspacePlatform(),
...overrides,
});
// Test Utilities
const createTestDomainWideDelegation = async (overrides = {}) => {
// Create organization first (as a team with isOrganization true)
await prismock.team.create({
data: buildMockOrganization(),
});
// Create workspace platform
await prismock.workspacePlatform.create({
data: buildMockWorkspacePlatform(),
});
const data = buildMockDomainWideDelegation(overrides);
return await prismock.domainWideDelegation.create({
data: {
...data,
serviceAccountKey: encryptServiceAccountKey(data.serviceAccountKey),
},
include: {
workspacePlatform: true,
},
});
};
const setupOrganizationMock = (returnValue: any) => {
vi.mocked(OrganizationRepository.findByMemberEmail).mockResolvedValue(returnValue);
};
describe("DomainWideDelegationRepository", () => {
beforeEach(() => {
prismock.domainWideDelegation.deleteMany();
prismock.workspacePlatform.deleteMany();
prismock.team.deleteMany();
vi.clearAllMocks();
});
describe("Service Account Key Access Control", () => {
beforeEach(async () => {
await createTestDomainWideDelegation();
});
describe("Regular Find Methods (No Service Account Key)", () => {
describe("findById", () => {
it("should not expose service account key in response", async () => {
const result = await DomainWideDelegationRepository.findById({ id: "test-id" });
expect(result).not.toHaveProperty("serviceAccountKey");
expect(result).toEqual(
expect.objectContaining({
id: "test-id",
enabled: true,
domain: "example.com",
})
);
});
});
describe("findAllByDomain", () => {
it("should not expose service account key in any of the results", async () => {
const results = await DomainWideDelegationRepository.findAllByDomain({ domain: "example.com" });
expect(results.length).toBeGreaterThan(0);
results.forEach((result) => {
expect(result).not.toHaveProperty("serviceAccountKey");
expect(result).toEqual(
expect.objectContaining({
domain: "example.com",
})
);
});
});
});
});
describe("Sensitive Methods (With Service Account Key)", () => {
describe("findByIdIncludeSensitiveServiceAccountKey", () => {
it("should expose valid service account key", async () => {
const result = await DomainWideDelegationRepository.findByIdIncludeSensitiveServiceAccountKey({
id: "test-id",
});
expect(result).toHaveProperty("serviceAccountKey");
expect(result?.serviceAccountKey).toEqual(buildMockServiceAccountKey());
});
});
describe("findByOrgIdIncludeSensitiveServiceAccountKey", () => {
it("should expose validated service account keys", async () => {
const results = await DomainWideDelegationRepository.findByOrgIdIncludeSensitiveServiceAccountKey({
organizationId: 1,
});
expect(results.length).toEqual(1);
const result = results[0];
expect(result).toHaveProperty("serviceAccountKey");
expect(result.serviceAccountKey).toEqual(buildMockEncryptedServiceAccountKey());
});
});
describe("findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey", () => {
it("should expose validated service account key", async () => {
const result =
await DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
{
organizationId: 1,
domain: "example.com",
}
);
expect(result).toHaveProperty("serviceAccountKey");
expect(result?.serviceAccountKey).toEqual(buildMockServiceAccountKey());
});
});
describe("findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey", () => {
it("should return valid delegation when email exists in organization", async () => {
setupOrganizationMock({ id: 1 });
const result =
await DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
email: "[email protected]",
});
expect(result).toHaveProperty("serviceAccountKey");
expect(result?.serviceAccountKey).toEqual(buildMockServiceAccountKey());
expect(result?.domain).toBe("example.com");
});
it("should return null when email not found in any organization", async () => {
setupOrganizationMock(null);
const result =
await DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
email: "[email protected]",
});
expect(result).toBeNull();
});
});
});
});
describe("CRUD Operations", () => {
describe("create", () => {
it("should store domain wide delegation with all required fields and establish connections", async () => {
// Create organization first (as a team with isOrganization true)
await prismock.team.create({
data: buildMockOrganization(),
});
// Create workspace platform
const workspacePlatform = await prismock.workspacePlatform.create({
data: buildMockWorkspacePlatform(),
});
const data = buildMockDomainWideDelegation();
delete data.id; // ID is auto-generated
delete data.workspacePlatform; // Don't include the relation in create
const result = await DomainWideDelegationRepository.create(data);
expect(result).toEqual({
id: expect.any(String),
domain: data.domain,
enabled: data.enabled,
createdAt: expect.any(Date),
updatedAt: null,
organizationId: data.organizationId,
workspacePlatform: {
name: workspacePlatform.name,
slug: workspacePlatform.slug,
},
});
});
});
describe("update", () => {
it("should modify workspace platform connection when workspacePlatformId is provided", async () => {
const created = await createTestDomainWideDelegation();
// Create new workspace platform
const newWorkspacePlatform = await prismock.workspacePlatform.create({
data: {
id: 2,
name: "New Platform",
slug: "new-platform",
},
});
const result = await DomainWideDelegationRepository.updateById({
id: created.id,
data: { workspacePlatformId: newWorkspacePlatform.id },
});
expect(result).toEqual({
id: created.id,
domain: created.domain,
enabled: created.enabled,
createdAt: expect.any(Date),
updatedAt: null,
organizationId: created.organizationId,
workspacePlatform: {
name: newWorkspacePlatform.name,
slug: newWorkspacePlatform.slug,
},
});
});
it("should modify organization connection when organizationId is provided", async () => {
const created = await createTestDomainWideDelegation();
// Create new organization (as a team with isOrganization true)
const newOrganization = await prismock.team.create({
data: {
id: 2,
name: "New Organization",
isOrganization: true,
},
});
const result = await DomainWideDelegationRepository.updateById({
id: created.id,
data: { organizationId: newOrganization.id },
});
expect(result).toEqual({
id: created.id,
domain: created.domain,
enabled: created.enabled,
createdAt: expect.any(Date),
updatedAt: null,
organizationId: newOrganization.id,
workspacePlatform: {
name: expect.any(String),
slug: expect.any(String),
},
});
});
it("should modify specified fields while preserving others", async () => {
const created = await createTestDomainWideDelegation();
const result = await DomainWideDelegationRepository.updateById({
id: created.id,
data: { enabled: false },
});
expect(result).toEqual(
expect.objectContaining({
id: created.id,
enabled: false, // Changed
domain: created.domain, // Preserved
})
);
});
});
describe("delete", () => {
it("should remove the domain wide delegation completely", async () => {
const created = await createTestDomainWideDelegation();
await DomainWideDelegationRepository.deleteById({ id: created.id });
const result = await prismock.domainWideDelegation.findUnique({
where: { id: created.id },
});
expect(result).toBeNull();
});
});
});
});
+33 -4
View File
@@ -1,5 +1,8 @@
import { prisma } from "@calcom/prisma";
import { safeCredentialSelect } from "@calcom/prisma/selects/credential";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { buildNonDwdCredential } from "../../domainWideDelegation/server";
type CredentialCreateInput = {
type: string;
@@ -10,24 +13,36 @@ type CredentialCreateInput = {
export class CredentialRepository {
static async create(data: CredentialCreateInput) {
return await prisma.credential.create({ data: { ...data } });
const credential = await prisma.credential.create({ data: { ...data } });
return buildNonDwdCredential(credential);
}
static async findByAppIdAndUserId({ appId, userId }: { appId: string; userId: number }) {
const credential = await prisma.credential.findFirst({
where: {
appId,
userId,
},
});
return buildNonDwdCredential(credential);
}
/**
* Doesn't retrieve key field as that has credentials
*/
static async findFirstByIdWithUser({ id }: { id: number }) {
return await prisma.credential.findFirst({ where: { id }, select: safeCredentialSelect });
const credential = await prisma.credential.findFirst({ where: { id }, select: safeCredentialSelect });
return buildNonDwdCredential(credential);
}
/**
* Includes 'key' field which is sensitive data.
*/
static async findFirstByIdWithKeyAndUser({ id }: { id: number }) {
return await prisma.credential.findFirst({
const credential = await prisma.credential.findFirst({
where: { id },
select: { ...safeCredentialSelect, key: true },
});
return buildNonDwdCredential(credential);
}
static async findFirstByAppIdAndUserId({ appId, userId }: { appId: string; userId: number }) {
@@ -40,10 +55,24 @@ export class CredentialRepository {
}
static async findFirstByUserIdAndType({ userId, type }: { userId: number; type: string }) {
return await prisma.credential.findFirst({ where: { userId, type } });
const credential = await prisma.credential.findFirst({ where: { userId, type } });
return buildNonDwdCredential(credential);
}
static async deleteById({ id }: { id: number }) {
await prisma.credential.delete({ where: { id } });
}
static async findCredentialForCalendarServiceById({ id }: { id: number }) {
const dbCredential = await prisma.credential.findUnique({
where: { id },
select: credentialForCalendarServiceSelect,
});
if (!dbCredential) {
return dbCredential;
}
return buildNonDwdCredential(dbCredential);
}
}
@@ -2,6 +2,8 @@ import type { Prisma } from "@prisma/client";
import { prisma } from "@calcom/prisma";
import { buildCredentialPayloadForPrisma } from "../buildCredentialPayloadForCalendar";
export class DestinationCalendarRepository {
static async create(data: Prisma.DestinationCalendarCreateInput) {
return await prisma.destinationCalendar.create({
@@ -9,7 +11,7 @@ export class DestinationCalendarRepository {
});
}
static async getByUserId(userId: string) {
static async getByUserId(userId: number) {
return await prisma.destinationCalendar.findFirst({
where: {
userId,
@@ -24,4 +26,54 @@ export class DestinationCalendarRepository {
},
});
}
static async find({ where }: { where: Prisma.DestinationCalendarWhereInput }) {
return await prisma.destinationCalendar.findFirst({
where,
});
}
static async upsert({
where,
update,
create,
}: {
where: Prisma.DestinationCalendarUpsertArgs["where"];
update: {
integration?: string;
externalId?: string;
credentialId?: number | null;
primaryEmail?: string | null;
domainWideDelegationCredentialId?: string | null;
};
create: {
integration: string;
externalId: string;
credentialId: number | null;
primaryEmail?: string | null;
domainWideDelegationCredentialId?: string | null;
};
}) {
const credentialPayloadForUpdate = buildCredentialPayloadForPrisma({
credentialId: update.credentialId,
domainWideDelegationCredentialId: update.domainWideDelegationCredentialId,
});
const credentialPayloadForCreate = buildCredentialPayloadForPrisma({
credentialId: create.credentialId,
domainWideDelegationCredentialId: create.domainWideDelegationCredentialId,
});
return await prisma.destinationCalendar.upsert({
where,
update: {
...update,
...credentialPayloadForUpdate,
},
create: {
...create,
...credentialPayloadForCreate,
},
});
}
}
@@ -1,23 +1,18 @@
import type { Prisma } from "@prisma/client";
import z from "zod";
import type { IDomainWideDelegationRepository } from "@calcom/features/domain-wide-delegation/domain-wide-delegation-repository.interface";
import { getFeatureFlag } from "@calcom/features/flags/server/utils";
import logger from "@calcom/lib/logger";
import {
serviceAccountKeySchema,
type ServiceAccountKey,
type EncryptedServiceAccountKey,
encryptServiceAccountKey,
decryptServiceAccountKey,
} from "@calcom/lib/server/serviceAccountKey";
import { prisma } from "@calcom/prisma";
import { OrganizationRepository } from "./organization";
const serviceAccountKeySchema = z
.object({
client_email: z.string(),
private_key: z.string(),
client_id: z.string(),
})
.passthrough();
export type ServiceAccountKey = z.infer<typeof serviceAccountKeySchema>;
export type { ServiceAccountKey };
const repositoryLogger = logger.getSubLogger({ prefix: ["DomainWideDelegationRepository"] });
const domainWideDelegationSafeSelect = {
id: true,
@@ -39,28 +34,41 @@ const domainWideDelegationSelectIncludesServiceAccountKey = {
serviceAccountKey: true,
};
export class DomainWideDelegationRepository implements IDomainWideDelegationRepository {
export class DomainWideDelegationRepository {
private static encryptServiceAccountKey(serviceAccountKey: ServiceAccountKey): EncryptedServiceAccountKey {
return encryptServiceAccountKey(serviceAccountKey);
}
private static decryptServiceAccountKey(encryptedServiceAccountKey: Prisma.JsonValue): ServiceAccountKey {
return decryptServiceAccountKey(encryptedServiceAccountKey);
}
private static withParsedServiceAccountKey<T extends { serviceAccountKey: Prisma.JsonValue } | null>(
domainWideDelegation: T
) {
if (!domainWideDelegation) {
return null;
}
const parsedServiceAccountKey = serviceAccountKeySchema.safeParse(domainWideDelegation.serviceAccountKey);
const { serviceAccountKey, ...rest } = domainWideDelegation;
// Decrypt the service account key if it exists
const decryptedKey = this.decryptServiceAccountKey(serviceAccountKey);
const parsedServiceAccountKey = serviceAccountKeySchema.safeParse(decryptedKey);
return {
...domainWideDelegation,
...rest,
serviceAccountKey: parsedServiceAccountKey.success ? parsedServiceAccountKey.data : null,
};
}
async create(data: {
static async create(data: {
domain: string;
enabled: boolean;
organizationId: number;
workspacePlatformId: number;
serviceAccountKey: Exclude<Prisma.JsonValue, null>;
serviceAccountKey: ServiceAccountKey;
}) {
const encryptedKey = this.encryptServiceAccountKey(data.serviceAccountKey);
return await prisma.domainWideDelegation.create({
data: {
workspacePlatform: {
@@ -75,20 +83,34 @@ export class DomainWideDelegationRepository implements IDomainWideDelegationRepo
id: data.organizationId,
},
},
serviceAccountKey: data.serviceAccountKey,
serviceAccountKey: encryptedKey,
},
select: domainWideDelegationSafeSelect,
});
}
async findById({ id }: { id: string }) {
static async findById({ id }: { id: string }) {
return await prisma.domainWideDelegation.findUnique({
where: { id },
select: domainWideDelegationSafeSelect,
});
}
async findByIdIncludeSensitiveServiceAccountKey({ id }: { id: string }) {
static async findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey({
organizationId,
domain,
}: {
organizationId: number;
domain: string;
}) {
const dwd = await prisma.domainWideDelegation.findUnique({
where: { organizationId_domain: { organizationId, domain } },
select: domainWideDelegationSelectIncludesServiceAccountKey,
});
return DomainWideDelegationRepository.withParsedServiceAccountKey(dwd);
}
static async findByIdIncludeSensitiveServiceAccountKey({ id }: { id: string }) {
const domainWideDelegation = await prisma.domainWideDelegation.findUnique({
where: { id },
select: domainWideDelegationSelectIncludesServiceAccountKey,
@@ -97,8 +119,10 @@ export class DomainWideDelegationRepository implements IDomainWideDelegationRepo
return DomainWideDelegationRepository.withParsedServiceAccountKey(domainWideDelegation);
}
async findUniqueByOrganizationMemberEmail({ email }: { email: string }) {
const log = repositoryLogger.getSubLogger({ prefix: ["findUniqueByOrganizationMemberEmail"] });
static async findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({ email }: { email: string }) {
const log = repositoryLogger.getSubLogger({
prefix: ["findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey"],
});
log.debug("called with", { email });
const organization = await OrganizationRepository.findByMemberEmail({ email });
if (!organization) {
@@ -114,14 +138,10 @@ export class DomainWideDelegationRepository implements IDomainWideDelegationRepo
domain: emailDomain,
},
},
select: domainWideDelegationSafeSelect,
select: domainWideDelegationSelectIncludesServiceAccountKey,
});
return domainWideDelegation;
}
async findByUser({ user }: { user: { email: string } }) {
return await this.findUniqueByOrganizationMemberEmail({ email: user.email });
return DomainWideDelegationRepository.withParsedServiceAccountKey(domainWideDelegation);
}
static async findAllByDomain({ domain }: { domain: string }) {
@@ -131,19 +151,7 @@ export class DomainWideDelegationRepository implements IDomainWideDelegationRepo
});
}
static async findFirstByOrganizationId({ organizationId }: { organizationId: number }) {
const domainWideDelegationEnabled = await getFeatureFlag(prisma, "domain-wide-delegation");
if (!domainWideDelegationEnabled) {
return null;
}
return await prisma.domainWideDelegation.findFirst({
where: { organizationId },
select: domainWideDelegationSafeSelect,
});
}
async updateById({
static async updateById({
id,
data,
}: {
@@ -179,13 +187,13 @@ export class DomainWideDelegationRepository implements IDomainWideDelegationRepo
});
}
async deleteById({ id }: { id: string }) {
static async deleteById({ id }: { id: string }) {
return await prisma.domainWideDelegation.delete({
where: { id },
});
}
async findDelegationsWithServiceAccount({ organizationId }: { organizationId: number }) {
static async findByOrgIdIncludeSensitiveServiceAccountKey({ organizationId }: { organizationId: number }) {
return await prisma.domainWideDelegation.findMany({
where: { organizationId },
select: {
@@ -289,4 +289,154 @@ describe("SelectedCalendarRepository", () => {
});
});
});
describe("Domain Wide Delegation", () => {
it("should create a selected calendar with domainWideDelegationCredentialId", async () => {
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
domainWideDelegationCredentialId: "dwd-123",
};
const result = await SelectedCalendarRepository.create(data);
expect(result).toEqual(expect.objectContaining(data));
});
describe("upsert", () => {
describe("updation", () => {
it("should update existing record with domainWideDelegationCredentialId if credentialId is -1", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: -1,
domainWideDelegationCredentialId: "dwd-123",
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).not.toBe(null);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(null);
expect(result.domainWideDelegationCredentialId).toBe(data.domainWideDelegationCredentialId);
});
it("should update existing record with credentialId if credentialId is valid(>0) even if domainWideDelegationCredentialId is set", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 2,
domainWideDelegationCredentialId: "dwd-123",
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).not.toBe(null);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(data.credentialId);
expect(result.domainWideDelegationCredentialId).toBeNull();
});
});
describe("creation", () => {
it("should create a new record with domainWideDelegationCredentialId if credentialId is -1", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: -1,
domainWideDelegationCredentialId: "dwd-123",
};
// It will create a new record because of unique constraint violation
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).not.toBe(null);
expect(result.id).not.toBe(existingCalendar.id);
expect(result.credentialId).toBe(null);
expect(result.domainWideDelegationCredentialId).toBe(data.domainWideDelegationCredentialId);
});
});
it("shouldnt update existing domainWideDelegationCredentialId if upsert data doesn't have it", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
eventTypeId: null,
domainWideDelegationCredentialId: "dwd-123",
credentialId: 1,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(existingCalendar.credentialId);
expect(result.domainWideDelegationCredentialId).toBe(null);
});
it("shouldnt update domainWideDelegationCredentialId if it is undefined", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
eventTypeId: null,
domainWideDelegationCredentialId: "dwd-123",
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(existingCalendar.credentialId);
expect(result.domainWideDelegationCredentialId).toBe(
existingCalendar.domainWideDelegationCredentialId
);
});
});
});
});
@@ -4,6 +4,8 @@ import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { SelectedCalendarEventTypeIds } from "@calcom/types/Calendar";
import { buildCredentialPayloadForPrisma } from "../buildCredentialPayloadForCalendar";
export type UpdateArguments = {
where: FindManyArgs["where"];
data: Prisma.SelectedCalendarUpdateManyArgs["data"];
@@ -78,19 +80,28 @@ export class SelectedCalendarRepository {
static async upsert(data: Prisma.SelectedCalendarUncheckedCreateInput) {
// userId_integration_externalId_eventTypeId is a unique constraint but with eventTypeId being nullable
// So, this unique constraint can't be used in upsert. Prisma doesn't allow that, So, we do create and update separately
const conflictingCalendar = await SelectedCalendarRepository.findConflicting(data);
const credentialPayload = buildCredentialPayloadForPrisma({
credentialId: data.credentialId,
domainWideDelegationCredentialId: data.domainWideDelegationCredentialId,
});
const newData = {
...data,
...credentialPayload,
};
const conflictingCalendar = await SelectedCalendarRepository.findConflicting(newData);
if (conflictingCalendar) {
return await prisma.selectedCalendar.update({
where: {
id: conflictingCalendar.id,
},
data,
data: newData,
});
}
return await prisma.selectedCalendar.create({
data,
data: newData,
});
}
+9 -48
View File
@@ -3,7 +3,6 @@ import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import prisma from "@calcom/prisma";
import { availabilityUserSelect } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import type { User as UserType } from "@calcom/prisma/client";
import type { CreationSource } from "@calcom/prisma/enums";
@@ -13,9 +12,13 @@ import { userMetadata } from "@calcom/prisma/zod-utils";
import type { UpId, UserProfile } from "@calcom/types/UserProfile";
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "../../availability";
import { buildNonDwdCredentials } from "../../domainWideDelegation/clientAndServer";
import { withSelectedCalendars } from "../withSelectedCalendars";
import { ProfileRepository } from "./profile";
import { getParsedTeam } from "./teamUtils";
export type { UserWithLegacySelectedCalendars } from "../withSelectedCalendars";
export { withSelectedCalendars };
export type UserAdminTeams = number[];
const log = logger.getSubLogger({ prefix: ["[repository/user]"] });
@@ -74,32 +77,6 @@ const userSelect = Prisma.validator<Prisma.UserSelect>()({
teams: true,
});
export type UserWithLegacySelectedCalendars<TCalendar, TUser> = TUser & {
selectedCalendars: TCalendar[];
};
type UserWithSelectedCalendars<TCalendar, TUser> = Omit<TUser, "selectedCalendars"> & {
allSelectedCalendars: TCalendar[];
userLevelSelectedCalendars: TCalendar[];
};
export function withSelectedCalendars<
TCalendar extends {
eventTypeId: number | null;
},
TUser extends {
selectedCalendars: TCalendar[];
}
>(user: UserWithLegacySelectedCalendars<TCalendar, TUser>): UserWithSelectedCalendars<TCalendar, TUser> {
// We are renaming selectedCalendars to allSelectedCalendars to make it clear that it contains all the calendars including eventType calendars
const { selectedCalendars, ...restUser } = user;
return {
...restUser,
allSelectedCalendars: selectedCalendars,
userLevelSelectedCalendars: selectedCalendars.filter((calendar) => !calendar.eventTypeId),
};
}
export class UserRepository {
static async findTeamsByUserId({ userId }: { userId: UserType["id"] }) {
const teamMemberships = await prisma.membership.findMany({
@@ -806,27 +783,11 @@ export class UserRepository {
return null;
}
return withSelectedCalendars(user);
}
static async findForAvailabilityCheck({ where }: { where: Prisma.UserWhereInput }) {
const user = await prisma.user.findFirst({
where,
select: {
...availabilityUserSelect,
selectedCalendars: true,
credentials: {
select: credentialForCalendarServiceSelect,
},
},
});
if (!user) {
return null;
}
const userWithSelectedCalendars = withSelectedCalendars(user);
return userWithSelectedCalendars;
const { credentials, ...userWithSelectedCalendars } = withSelectedCalendars(user);
return {
...userWithSelectedCalendars,
credentials: buildNonDwdCredentials(credentials),
};
}
static async findUnlockedUserForSession({ userId }: { userId: number }) {
@@ -1,9 +1,10 @@
import type { Prisma } from "@prisma/client";
import { Prisma } from "@prisma/client";
import { prisma } from "@calcom/prisma";
import type { TServiceAccountKeySchema } from "@calcom/prisma/zod-utils";
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
type WorkspacePlatformServiceAccountKey = TServiceAccountKeySchema | null;
const safeWorkspacePlatformSelect = {
id: true,
name: true,
@@ -31,11 +32,19 @@ export class WorkspacePlatformRepository {
slug: string;
name: string;
description: string;
defaultServiceAccountKey: TServiceAccountKeySchema;
defaultServiceAccountKey?: WorkspacePlatformServiceAccountKey;
enabled: boolean;
}) {
const { defaultServiceAccountKey: _defaultServiceAccountKey, ...rest } = data;
const defaultServiceAccountKey =
_defaultServiceAccountKey === undefined || _defaultServiceAccountKey === null
? Prisma.JsonNull
: _defaultServiceAccountKey;
return await prisma.workspacePlatform.create({
data,
data: {
defaultServiceAccountKey,
...rest,
},
select: safeWorkspacePlatformSelect,
});
}
+74
View File
@@ -0,0 +1,74 @@
import type { Prisma } from "@prisma/client";
import { z } from "zod";
import { SERVICE_ACCOUNT_ENCRYPTION_KEY } from "@calcom/lib/constants";
import { symmetricEncrypt, symmetricDecrypt } from "@calcom/lib/crypto";
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
export type ServiceAccountKey = z.infer<typeof serviceAccountKeySchema>;
export { serviceAccountKeySchema };
// Schema for encrypted service account key (our storage format)
export const encryptedServiceAccountKeySchema = z
.object({
client_email: z.string().optional(),
client_id: z.string(),
encrypted_credentials: z.string(),
tenant_id: z.string().optional(),
})
.passthrough();
export type EncryptedServiceAccountKey = z.infer<typeof encryptedServiceAccountKeySchema>;
export function encryptServiceAccountKey(serviceAccountKey: ServiceAccountKey): EncryptedServiceAccountKey {
if (!SERVICE_ACCOUNT_ENCRYPTION_KEY) {
throw new Error("Service account encryption key is not set");
}
// Extract private_key to encrypt
const { private_key, ...rest } = serviceAccountKey;
const sensitiveData = { private_key };
// Create a new object with encrypted credentials
return {
...rest,
encrypted_credentials: symmetricEncrypt(JSON.stringify(sensitiveData), SERVICE_ACCOUNT_ENCRYPTION_KEY),
} as EncryptedServiceAccountKey;
}
export function decryptServiceAccountKey(encryptedServiceAccountKey: Prisma.JsonValue): ServiceAccountKey {
if (!SERVICE_ACCOUNT_ENCRYPTION_KEY) {
throw new Error("Service account encryption key is not set");
}
try {
// Parse and validate the encrypted format
const parsedEncrypted = encryptedServiceAccountKeySchema.safeParse(encryptedServiceAccountKey);
if (!parsedEncrypted.success) {
throw new Error(`Invalid service account key format: ${JSON.stringify(parsedEncrypted.error)}`);
}
const { encrypted_credentials, ...rest } = parsedEncrypted.data;
// Decrypt and parse the sensitive data
const decryptedData = JSON.parse(
symmetricDecrypt(encrypted_credentials, SERVICE_ACCOUNT_ENCRYPTION_KEY)
) as Record<string, string>;
// Reconstruct and validate the decrypted format
const decrypted = {
...rest,
...decryptedData,
};
const parsedDecrypted = serviceAccountKeySchema.safeParse(decrypted);
if (!parsedDecrypted.success) {
throw new Error("Invalid decrypted service account key format");
}
return parsedDecrypted.data;
} catch (error) {
if (error instanceof Error) {
throw new Error(`Failed to decrypt service account key: ${error.message}`);
}
throw new Error("Failed to decrypt service account key");
}
}
@@ -0,0 +1,25 @@
export type UserWithLegacySelectedCalendars<TCalendar, TUser> = TUser & {
selectedCalendars: TCalendar[];
};
type UserWithSelectedCalendars<TCalendar, TUser> = Omit<TUser, "selectedCalendars"> & {
allSelectedCalendars: TCalendar[];
userLevelSelectedCalendars: TCalendar[];
};
export function withSelectedCalendars<
TCalendar extends {
eventTypeId: number | null;
},
TUser extends {
selectedCalendars: TCalendar[];
}
>(user: UserWithLegacySelectedCalendars<TCalendar, TUser>): UserWithSelectedCalendars<TCalendar, TUser> {
// We are renaming selectedCalendars to allSelectedCalendars to make it clear that it contains all the calendars including eventType calendars
const { selectedCalendars, ...restUser } = user;
return {
...restUser,
allSelectedCalendars: selectedCalendars,
userLevelSelectedCalendars: selectedCalendars.filter((calendar) => !calendar.eventTypeId),
};
}