From 76420411b9b62e74b7202dd66d7ba7dfe91c8077 Mon Sep 17 00:00:00 2001 From: Hariom Balhara Date: Fri, 7 Mar 2025 18:41:07 +0530 Subject: [PATCH] fix: fixes the crash when empty `users` or `hosts` array is passed to _getDelegationCredentialsMapPerUser (#19834) * fix crash when no users are there * typo fix --- packages/lib/delegationCredential/server.test.ts | 16 ++++++++++++++++ packages/lib/delegationCredential/server.ts | 8 +++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/lib/delegationCredential/server.test.ts b/packages/lib/delegationCredential/server.test.ts index 4884110661..efaa1e4562 100644 --- a/packages/lib/delegationCredential/server.test.ts +++ b/packages/lib/delegationCredential/server.test.ts @@ -399,6 +399,14 @@ describe("enrichUsersWithDelegationCredentials", () => { })) ); }); + + it("should return empty array when users is empty", async () => { + const result = await enrichUsersWithDelegationCredentials({ + orgId: 1, + users: [], + }); + expect(result).toEqual([]); + }); }); describe("enrichHostsWithDelegationCredentials", () => { @@ -498,6 +506,14 @@ describe("enrichHostsWithDelegationCredentials", () => { })) ); }); + + it("should return empty array when hosts is empty", async () => { + const result = await enrichHostsWithDelegationCredentials({ + orgId: 1, + hosts: [], + }); + expect(result).toEqual([]); + }); }); describe("enrichUserWithDelegationCredentialsWithoutOrgId", () => { diff --git a/packages/lib/delegationCredential/server.ts b/packages/lib/delegationCredential/server.ts index f21c8e4cc0..4e43372c99 100644 --- a/packages/lib/delegationCredential/server.ts +++ b/packages/lib/delegationCredential/server.ts @@ -214,7 +214,13 @@ async function _getDelegationCredentialsMapPerUser({ if (!organizationId) { return emptyMap; } - const domain = users[0].email.split("@")[1]; + // We assume that all users in an organization are from the same domain, so first one should be fine. + // TODO: There could be multiple domains in an organization(if an organization is migrating maybe from one to another or for some other reason) and we should actually consider all of them, maybe group by domain. + const userThatDeterminesDomain = users[0]; + if (!userThatDeterminesDomain) { + return emptyMap; + } + const domain = userThatDeterminesDomain.email.split("@")[1]; log.debug("called with", safeStringify({ users })); const delegationCredential = await DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(