Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
refactor(secret-approval-request): streamline email sending logic and remove unused tests
Victor Hugo dos Santos3d32dd10b2f6
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.test.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.test.tsindex 51d0709a7e..7147be7c99 100644--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.test.ts+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.test.ts@@ -1,18 +1,14 @@-import { describe, expect, test, vi } from "vitest";+import { describe, expect, test } from "vitest";import { OrderByDirection } from "@app/lib/types";import {compareSecretApprovalRequests,mergeSecretApprovalRequestPages,- sendApprovalEmailsFn,TSecretApprovalRequestSortable} from "./secret-approval-request-fns";import { SecretApprovalRequestOrderBy } from "./secret-approval-request-types";-vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ SITE_URL: "https://app.test" }) }));-vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() } }));-const request = (overrides: Partial<TSecretApprovalRequestSortable> & { id: string }): TSecretApprovalRequestSortable => ({@@ -126,55 +122,3 @@ describe("mergeSecretApprovalRequestPages", () => {expect(merged.approvals.map((el) => el.id)).toEqual(["legacy-old", "global-old", "legacy-new", "global-new"]);});});--describe("sendApprovalEmailsFn", () => {- const build = () => {- const deps = {- secretApprovalPolicyDAL: {- findById: vi.fn().mockResolvedValue({- userApprovers: [- { userId: "user-2", firstName: "Bob", email: "[email protected]" },- { userId: "user-3", firstName: "Eve", email: "[email protected]" }- ]- })- },- projectDAL: {- findProjectWithOrg: vi- .fn()- .mockResolvedValue({ id: "project-1", name: "Project", orgId: "org-1", organization: { name: "Org" } })- },- smtpService: { sendMail: vi.fn().mockResolvedValue(undefined) },- notificationService: { createUserNotifications: vi.fn().mockResolvedValue(undefined) }- };- const run = () =>- sendApprovalEmailsFn({- ...(deps as unknown as Omit<Parameters<typeof sendApprovalEmailsFn>[0], "projectId" | "secretApprovalRequest">),- projectId: "project-1",- secretApprovalRequest: { id: "request-1", policyId: "policy-1" }- });- return { deps, run };- };-- test("resolves with no failures when every email is delivered", async () => {- const { deps, run } = build();-- await expect(run()).resolves.toEqual([]);- expect(deps.smtpService.sendMail).toHaveBeenCalledTimes(2);- });-- test("a failed email does not reject: it is returned and the next approver is still emailed", async () => {- const { deps, run } = build();- const smtpError = new Error("Invalid login: 535 Authentication Credentials Invalid");- deps.smtpService.sendMail.mockRejectedValueOnce(smtpError);-- await expect(run()).resolves.toEqual([smtpError]);- expect(deps.smtpService.sendMail).toHaveBeenCalledTimes(2);- expect(deps.smtpService.sendMail).toHaveBeenLastCalledWith(- expect.objectContaining({ recipients: ["[email protected]"] })- );- expect(deps.notificationService.createUserNotifications).toHaveBeenCalledWith([- expect.objectContaining({ userId: "user-2" }),- expect.objectContaining({ userId: "user-3" })- ]);- });-});diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.tsindex d3e1b4165b..519cff6493 100644--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts@@ -1,6 +1,5 @@import { TSecretApprovalRequests } from "@app/db/schemas";import { getConfig } from "@app/lib/config/env";-import { logger } from "@app/lib/logger";import { OrderByDirection } from "@app/lib/types";import { TNotificationServiceFactory } from "@app/services/notification/notification-service";import { NotificationType } from "@app/services/notification/notification-types";@@ -26,7 +25,7 @@ export const sendApprovalEmailsFn = async ({projectId,secretApprovalRequest,notificationService-}: TSendApprovalEmails): Promise<unknown[]> => {+}: TSendApprovalEmails) => {const cfg = getConfig();const policy = await secretApprovalPolicyDAL.findById(secretApprovalRequest.policyId);@@ -44,31 +43,20 @@ export const sendApprovalEmailsFn = async ({})));- const failures: unknown[] = [];for await (const reviewerUser of policy.userApprovers) {- try {- await smtpService.sendMail({- recipients: [reviewerUser?.email as string],- subjectLine: "Infisical Secret Change Request",-- substitutions: {- firstName: reviewerUser.firstName,- projectName: project.name,- organizationName: project.organization.name,- approvalUrl: `${cfg.SITE_URL}/organizations/${project.orgId}/projects/secret-management/${project.id}/approval?requestId=${secretApprovalRequest.id}`- },- template: SmtpTemplates.SecretApprovalRequestNeedsReview- });- } catch (error) {- logger.error(- error,- `Failed to send secret change request email to approver [requestId=${secretApprovalRequest.id}] [userId=${reviewerUser.userId}]`- );- failures.push(error);- }+ await smtpService.sendMail({+ recipients: [reviewerUser?.email as string],+ subjectLine: "Infisical Secret Change Request",++ substitutions: {+ firstName: reviewerUser.firstName,+ projectName: project.name,+ organizationName: project.organization.name,+ approvalUrl: `${cfg.SITE_URL}/organizations/${project.orgId}/projects/secret-management/${project.id}/approval?requestId=${secretApprovalRequest.id}`+ },+ template: SmtpTemplates.SecretApprovalRequestNeedsReview+ });}-- return failures;};export type TSecretUpdateCommitCandidate = {diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.tsindex 33b4b9e747..3c3a79f1c3 100644--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts@@ -1633,18 +1633,8 @@ export const secretApprovalRequestServiceFactory = ({return secretChangeGlobalRequestBridgeService.createSecretChangeRequestSideEffects(dto);}- const {- secretApprovalRequest,- projectId,- environment,- secretPath,- secretKeys,- actor,- actorId,- actorOrgId,- tx,- throwOnEmailFailure- } = dto;+ const { secretApprovalRequest, projectId, environment, secretPath, secretKeys, actor, actorId, actorOrgId, tx } =+ dto;const user =actor === ActorType.IDENTITY? undefined@@ -1684,7 +1674,7 @@ export const secretApprovalRequestServiceFactory = ({}});- const emailFailures = await sendApprovalEmailsFn({+ await sendApprovalEmailsFn({projectDAL,secretApprovalPolicyDAL,secretApprovalRequest,@@ -1741,8 +1731,6 @@ export const secretApprovalRequestServiceFactory = ({}}).catch(() => {});-- if (throwOnEmailFailure && emailFailures.length) throw emailFailures[0];};const generateSecretApprovalRequestV2Bridge = async (diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-types.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-types.tsindex 7d7e128b3a..cea86636be 100644--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-types.ts+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-types.ts@@ -122,7 +122,6 @@ export type TCreateSecretApprovalSideEffectsDTO = {secretPath: string;secretKeys: string[];tx?: Knex;- throwOnEmailFailure?: boolean;} & Omit<TProjectPermission, "actorAuthMethod">;export type TMergeSecretApprovalRequestDTO = {diff --git a/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-fns.test.ts b/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-fns.test.tsindex 8ee32310f6..e5497b58f0 100644--- a/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-fns.test.ts+++ b/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-fns.test.ts@@ -476,25 +476,4 @@ describe("runSecretChangeRequestSideEffects", () => {);expect(deps.telemetryService.sendPostHogEvents).toHaveBeenCalled();});-- test("with throwOnEmailFailure, rethrows the email error only after every other side effect ran", async () => {- const { fns, deps } = buildFns({ approvers: twoMailableApprovers });- deps.smtpService.sendMail.mockRejectedValueOnce(new Error("Invalid login: 535 Authentication Credentials Invalid"));-- await expect(fns.runSecretChangeRequestSideEffects({ ...input, throwOnEmailFailure: true })).rejects.toThrow(- "535 Authentication Credentials Invalid"- );-- expect(deps.smtpService.sendMail).toHaveBeenCalledTimes(2);- expect(deps.queueService.queue).toHaveBeenCalled();- expect(deps.telemetryService.sendPostHogEvents).toHaveBeenCalled();- });-- test("with throwOnEmailFailure, resolves when every email is delivered", async () => {- const { fns } = buildFns({ approvers: twoMailableApprovers });-- await expect(- fns.runSecretChangeRequestSideEffects({ ...input, throwOnEmailFailure: true })- ).resolves.toBeUndefined();- });});diff --git a/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-fns.ts b/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-fns.tsindex 6e3df7e7b2..70c52f4c3d 100644--- a/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-fns.ts+++ b/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-fns.ts@@ -84,7 +84,6 @@ export type TSecretChangeRequestSideEffectsDTO = {actorId: string;actorOrgId: string;tx?: Knex;- throwOnEmailFailure?: boolean;};export type TSecretChangeGlobalRequestFnsFactory = ReturnType<typeof secretChangeGlobalRequestFnsFactory>;@@ -202,9 +201,9 @@ export const secretChangeGlobalRequestFnsFactory = ({}: Pick<TSecretChangeRequestSideEffectsDTO, "policy" | "tx"> & {requestId: string;projectId: string;- }): Promise<unknown[]> => {+ }) => {const approverUserIds = unique(policy.userApprovers.map((approver) => approver.userId));- if (!approverUserIds.length) return [];+ if (!approverUserIds.length) return;const approvers = await userDAL.find({ $in: { id: approverUserIds } }, { tx });const project = await projectDAL.findProjectWithOrg(projectId, tx);@@ -221,7 +220,6 @@ export const secretChangeGlobalRequestFnsFactory = ({})));- const failures: unknown[] = [];for await (const approver of approvers) {if (!approver.email) continue;try {@@ -241,11 +239,8 @@ export const secretChangeGlobalRequestFnsFactory = ({error,`Failed to send secret change request email to approver [requestId=${requestId}] [userId=${approver.id}]`);- failures.push(error);}}-- return failures;};const queueChangeRequestWebhook = async ({@@ -320,8 +315,7 @@ export const secretChangeGlobalRequestFnsFactory = ({actor,actorId,actorOrgId,- tx,- throwOnEmailFailure+ tx}: TSecretChangeRequestSideEffectsDTO) => {const findUser = () => userDAL.findById(actorId, tx);const user =@@ -357,12 +351,7 @@ export const secretChangeGlobalRequestFnsFactory = ({}});- const emailFailures = await $sendApproverNotifications({- policy,- requestId: approvalRequest.id,- projectId: project.id,- tx- });+ await $sendApproverNotifications({ policy, requestId: approvalRequest.id, projectId: project.id, tx });try {await queueChangeRequestWebhook({@@ -400,8 +389,6 @@ export const secretChangeGlobalRequestFnsFactory = ({}}).catch(() => {});-- if (throwOnEmailFailure && emailFailures.length) throw emailFailures[0];};return { resolveRequester, queueChangeRequestWebhook, runSecretChangeRequestSideEffects };diff --git a/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-service.ts b/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-service.tsindex b624e3aeb8..0e4eff22bf 100644--- a/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-service.ts+++ b/backend/src/ee/services/secret-change-global-request-bridge/secret-change-global-request-bridge-service.ts@@ -575,8 +575,7 @@ export const secretChangeGlobalRequestBridgeServiceFactory = ({actor,actorId,actorOrgId,- tx,- throwOnEmailFailure+ tx}) => {const { approvalRequest, secretChangeRequest } = await $findSecretChangeRequestOrThrow(secretApprovalRequest.id,@@ -598,8 +597,7 @@ export const secretChangeGlobalRequestBridgeServiceFactory = ({actor,actorId,actorOrgId,- tx,- throwOnEmailFailure+ tx});};diff --git a/backend/src/services/external-migration/external-migration-queue.ts b/backend/src/services/external-migration/external-migration-queue.tsindex b838cc48c7..a5aa5870a6 100644--- a/backend/src/services/external-migration/external-migration-queue.ts+++ b/backend/src/services/external-migration/external-migration-queue.ts@@ -286,8 +286,7 @@ export const externalMigrationQueueFactory = ({secretKeys,actor,actorId,- actorOrgId,- throwOnEmailFailure: true+ actorOrgId});} catch (error) {// rethrown so the job's retries apply: a reviewer who never hears about the request is worse than a