fix: DelegationCredential - Duplicate GoogleMeet and unnecessary serviceAccount key access (#21269)

* Remove unused return statement

* Fix return from fn instead of continuing the loop

* Ensure userId is set for existing records on update

* ensure that serviceAccountKey is only retrieved whenb assked
This commit is contained in:
Hariom Balhara authored and GitHub committed 2025-05-14 09:49:47 +00:00
1 parent deb55c0536
commit df75df7008
32 files changed
+196 -113

No files matched your search

@@ -11,13 +11,13 @@ import { SMSLockState } from "@calcom/prisma/enums";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import {
getAllDelegationCredentialsForUser,
buildAllCredentials,
getDelegationCredentialOrRegularCredential,
enrichUsersWithDelegationCredentials,
enrichHostsWithDelegationCredentials,
enrichUserWithDelegationCredentialsWithoutOrgId,
enrichUserWithDelegationCredentialsIncludeServiceAccountKey,
enrichUserWithDelegationConferencingCredentialsWithoutOrgId,
getAllDelegationCredentialsForUserIncludeServiceAccountKey,
} from "./server";
// Mock OrganizationRepository
@@ -177,7 +177,7 @@ const buildMockDelegationCredential = (overrides: Partial<typeof mockDelegationC
...overrides,
});
describe("getAllDelegationCredentialsForUser", () => {
describe("getAllDelegationCredentialsForUserIncludeServiceAccountKey", () => {
setupAndTeardown();
beforeEach(() => {
@@ -189,7 +189,7 @@ describe("getAllDelegationCredentialsForUser", () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await getAllDelegationCredentialsForUser({ user: mockUser });
const result = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({ user: mockUser });
expect(result).toEqual([]);
});
@@ -197,7 +197,7 @@ describe("getAllDelegationCredentialsForUser", () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
const result = await getAllDelegationCredentialsForUser({ user: mockUser });
const result = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({ user: mockUser });
expect(result).toEqual([]);
});
@@ -205,7 +205,7 @@ describe("getAllDelegationCredentialsForUser", () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await getAllDelegationCredentialsForUser({ user: mockUser });
const result = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({ user: mockUser });
expect(result).toHaveLength(2);
expect(result).toEqual([
@@ -225,7 +225,7 @@ describe("getAllDelegationCredentialsForUser", () => {
},
})
);
const result = await getAllDelegationCredentialsForUser({ user: mockUser });
const result = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({ user: mockUser });
expect(result).toEqual([]);
});
});
@@ -520,7 +520,7 @@ describe("enrichHostsWithDelegationCredentials", () => {
});
});
describe("enrichUserWithDelegationCredentialsWithoutOrgId", () => {
describe("enrichUserWithDelegationCredentialsIncludeServiceAccountKey", () => {
const mockUserWithCredentials = {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
@@ -535,7 +535,7 @@ describe("enrichUserWithDelegationCredentialsWithoutOrgId", () => {
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await enrichUserWithDelegationCredentialsWithoutOrgId({
const result = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: mockUserWithCredentials,
});
@@ -559,7 +559,7 @@ describe("enrichUserWithDelegationCredentialsWithoutOrgId", () => {
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await enrichUserWithDelegationCredentialsWithoutOrgId({
const result = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: mockUserWithCredentials,
});
@@ -578,7 +578,7 @@ describe("enrichUserWithDelegationCredentialsWithoutOrgId", () => {
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
const result = await enrichUserWithDelegationCredentialsWithoutOrgId({
const result = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: mockUserWithCredentials,
});
+61 -10
View File
@@ -188,7 +188,11 @@ const _buildDelegatedConferencingCredential = ({
/**
* Gets calendar as well as conferencing credentials(stored in-memory) for the user from the corresponding enabled DelegationCredential.
*/
export async function getAllDelegationCredentialsForUser({ user }: { user: { email: string; id: number } }) {
export async function getAllDelegationCredentialsForUserIncludeServiceAccountKey({
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 DelegationCredential on credential we need to toggle DelegationCredential off from organization settings.
@@ -211,13 +215,32 @@ export async function getAllDelegationCredentialsForUser({ user }: { user: { ema
return delegationCredentials;
}
export async function getAllDelegationCredentialsForUser({ user }: { user: { email: string; id: number } }) {
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
user,
});
return delegationCredentials.map(({ delegatedTo: _1, ...rest }) => {
return {
...rest,
};
});
}
export async function getAllDelegatedCalendarCredentialsForUser({
user,
}: {
user: { email: string; id: number };
}) {
const delegationCredentials = await getAllDelegationCredentialsForUser({ user });
return delegationCredentials.filter((credential) => credential.type.endsWith("_calendar"));
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
user,
});
const delegationCalendarCredentials = delegationCredentials.filter((credential) =>
credential.type.endsWith("_calendar")
);
return buildAllCredentials({
delegationCredentials: delegationCalendarCredentials,
existingCredentials: [],
});
}
async function _getDelegationCredentialsMapPerUser({
@@ -325,8 +348,14 @@ export async function getAllDelegationCredentialsForUserByAppSlug({
user: User;
appSlug: string;
}) {
const delegationCredentials = await getAllDelegationCredentialsForUser({ user });
return delegationCredentials.filter((credential) => credential.appId === appSlug);
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
user,
});
const appDelegationCredentials = delegationCredentials.filter((credential) => credential.appId === appSlug);
return buildAllCredentials({
delegationCredentials: appDelegationCredentials,
existingCredentials: [],
});
}
type Host<TUser extends { id: number; email: string; credentials: CredentialPayload[] }> = {
@@ -425,14 +454,16 @@ export const enrichHostsWithDelegationCredentials = async <
return enrichedHosts;
};
export const enrichUserWithDelegationCredentialsWithoutOrgId = async <
export const enrichUserWithDelegationCredentialsIncludeServiceAccountKey = async <
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({
user,
}: {
user: TUser;
}) => {
const delegationCredentials = await getAllDelegationCredentialsForUser({ user });
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
user,
});
const { credentials, ...restUser } = user;
return {
...restUser,
@@ -443,10 +474,28 @@ export const enrichUserWithDelegationCredentialsWithoutOrgId = async <
};
};
export const enrichUserWithDelegationCredentials = async <
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({
user,
}: {
user: TUser;
}) => {
const { credentials, ...restUser } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user,
});
return {
...restUser,
credentials: credentials.filter(_isConferencingCredential).map(({ delegatedTo: _1, ...rest }) => rest),
};
};
export async function enrichUserWithDelegationConferencingCredentialsWithoutOrgId<
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({ user }: { user: TUser }) {
const { credentials, ...restUser } = await enrichUserWithDelegationCredentialsWithoutOrgId({ user });
const { credentials, ...restUser } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user,
});
return {
...restUser,
credentials: credentials.filter(_isConferencingCredential),
@@ -456,7 +505,9 @@ export async function enrichUserWithDelegationConferencingCredentialsWithoutOrgI
/**
* Either get Delegation credential from delegationCredentials or find regular credential from Credential table
*/
export async function getDelegationCredentialOrFindRegularCredential({
export async function getDelegationCredentialOrFindRegularCredential<
TDelegationCredential extends { delegatedToId?: string | null }
>({
id,
delegationCredentials,
}: {
@@ -464,7 +515,7 @@ export async function getDelegationCredentialOrFindRegularCredential({
credentialId: number | null | undefined;
delegationCredentialId: string | null | undefined;
};
delegationCredentials: CredentialForCalendarService[];
delegationCredentials: TDelegationCredential[];
}) {
return id.delegationCredentialId
? delegationCredentials.find((cred) => cred.delegatedToId === id.delegationCredentialId)
+2 -2
View File
@@ -7,7 +7,7 @@ import { getAppFromSlug } from "@calcom/app-store/utils";
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
import getEnabledAppsFromCredentials from "@calcom/lib/apps/getEnabledAppsFromCredentials";
import getInstallCountPerApp from "@calcom/lib/apps/getInstallCountPerApp";
import { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
import { getUsersCredentialsIncludeServiceAccountKey } from "@calcom/lib/server/getUsersCredentials";
import type { PrismaClient } from "@calcom/prisma";
import type { User } from "@calcom/prisma/client";
import type { AppCategories } from "@calcom/prisma/enums";
@@ -66,7 +66,7 @@ export async function getConnectedApps({
sortByInstalledFirst,
appId,
} = input;
let credentials = await getUsersCredentials(user);
let credentials = await getUsersCredentialsIncludeServiceAccountKey(user);
let userTeams: TeamQuery[] = [];
if (includeTeamInstalledApps || teamId) {
@@ -1,6 +1,6 @@
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/lib/CalendarManager";
import { isDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "@calcom/lib/delegationCredential/server";
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "@calcom/lib/delegationCredential/server";
import logger from "@calcom/lib/logger";
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
@@ -285,7 +285,7 @@ export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
select: credentialForCalendarServiceSelect,
});
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsWithoutOrgId({
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: { id: user.id, email: user.email, credentials: userCredentials },
});
+2 -2
View File
@@ -10,7 +10,7 @@ import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/crede
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "../delegationCredential/server";
import { enrichUserWithDelegationCredentials } from "../delegationCredential/server";
import { getBookerBaseUrl } from "../getBookerUrl/server";
async function getEventType(id: number) {
@@ -109,7 +109,7 @@ export async function getBooking(bookingId: number) {
const { user: userWithoutDelegationCredentials } = booking;
if (!userWithoutDelegationCredentials) throw new HttpCode({ statusCode: 204, message: "No user found" });
const user = await enrichUserWithDelegationCredentialsWithoutOrgId({
const user = await enrichUserWithDelegationCredentials({
user: userWithoutDelegationCredentials,
});
+2 -2
View File
@@ -2,7 +2,7 @@ import type { Prisma } from "@prisma/client";
import { sendScheduledEmailsAndSMS } from "@calcom/emails";
import { doesBookingRequireConfirmation } from "@calcom/features/bookings/lib/doesBookingRequireConfirmation";
import { getAllCredentials } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import { getAllCredentialsIncludeServiceAccountKey } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import { handleBookingRequested } from "@calcom/features/bookings/lib/handleBookingRequested";
import { handleConfirmation } from "@calcom/features/bookings/lib/handleConfirmation";
import EventManager from "@calcom/lib/EventManager";
@@ -27,7 +27,7 @@ export async function handlePaymentSuccess(paymentId: number, bookingId: number)
status: BookingStatus.ACCEPTED,
};
const allCredentials = await getAllCredentials(userWithCredentials, {
const allCredentials = await getAllCredentialsIncludeServiceAccountKey(userWithCredentials, {
...booking.eventType,
metadata: booking.eventType?.metadata as EventTypeMetadata,
});
@@ -1,6 +1,6 @@
import type { Prisma } from "@prisma/client";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "@calcom/lib/delegationCredential/server";
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "@calcom/lib/delegationCredential/server";
import { availabilityUserSelect } from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -23,7 +23,7 @@ export async function findUsersForAvailabilityCheck({ where }: { where: Prisma.U
return null;
}
return await enrichUserWithDelegationCredentialsWithoutOrgId({
return await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: withSelectedCalendars(user),
});
}
+3 -2
View File
@@ -1,7 +1,7 @@
import getAppKeysFromSlug from "@calcom/app-store/_utils/getAppKeysFromSlug";
import { DailyLocationType } from "@calcom/app-store/locations";
import getApps from "@calcom/app-store/utils";
import { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
import { getUsersCredentialsIncludeServiceAccountKey } from "@calcom/lib/server/getUsersCredentials";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import type { EventTypeLocation } from "@calcom/prisma/zod/custom/eventtype";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
@@ -17,7 +17,8 @@ export async function getDefaultLocations(user: User): Promise<EventTypeLocation
const defaultConferencingData = userMetadataSchema.parse(user.metadata)?.defaultConferencingApp;
if (defaultConferencingData && defaultConferencingData.appSlug !== "daily-video") {
const credentials = await getUsersCredentials(user);
// We are not returning the credential, so we are fine with the service account key
const credentials = await getUsersCredentialsIncludeServiceAccountKey(user);
const foundApp = getApps(credentials, true).filter(
(app) => app.slug === defaultConferencingData.appSlug
+8 -3
View File
@@ -2,7 +2,7 @@ import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "../delegationCredential/server";
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "../delegationCredential/server";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = { id: SessionUser["id"]; email: SessionUser["email"] };
@@ -10,7 +10,7 @@ type User = { id: SessionUser["id"]; email: SessionUser["email"] };
/**
* It includes in-memory DelegationCredential credentials as well.
*/
export async function getUsersCredentials(user: User) {
export async function getUsersCredentialsIncludeServiceAccountKey(user: User) {
const credentials = await prisma.credential.findMany({
where: {
userId: user.id,
@@ -21,7 +21,7 @@ export async function getUsersCredentials(user: User) {
},
});
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsWithoutOrgId({
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: {
email: user.email,
id: user.id,
@@ -31,3 +31,8 @@ export async function getUsersCredentials(user: User) {
return allCredentials;
}
export async function getUsersCredentials(user: User) {
const credentials = await getUsersCredentialsIncludeServiceAccountKey(user);
return credentials.map(({ delegatedTo: _1, ...rest }) => rest);
}