Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

35.3 KB
Raw Blame
import { ForbiddenError } from "@casl/ability";

import { ActionProjectType, ProjectMembershipRole, ResourceType } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { ResourcePermissionSub } from "@app/ee/services/permission/resource-permission";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
import { NotificationType } from "@app/services/notification/notification-types";
import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TSmtpService } from "@app/services/smtp/smtp-service";

import { TPkiAlertChannelDALFactory } from "./pki-alert-channel-dal";
import { TPkiAlertHistoryDALFactory } from "./pki-alert-history-dal";
import { sendEmailNotificationWithRetry } from "./pki-alert-v2-channel-email-fns";
import { sendPagerDutyNotificationWithRetry } from "./pki-alert-v2-channel-pagerduty-fns";
import { sendSlackNotificationWithRetry, validateSlackWebhookUrl } from "./pki-alert-v2-channel-slack-fns";
import { sendWebhookNotification } from "./pki-alert-v2-channel-webhook-fns";
import { LEGACY_ALERT_WRITES_BLOCKED } from "./pki-alert-v2-constants";
import { TAlertWithChannels, TPkiAlertV2DALFactory } from "./pki-alert-v2-dal";
import { parseTimeToDays, parseTimeToPostgresInterval } from "./pki-alert-v2-filter-utils";
import {
  alertEventTypeToWebhookEventType,
  CertificateOrigin,
  PkiAlertChannelType,
  PkiAlertEventType,
  PkiAlertRunStatus,
  PkiWebhookEventType,
  TAlertInfo,
  TAlertV2Response,
  TCertificatePreview,
  TChannelConfig,
  TChannelConfigResponse,
  TCreateAlertV2DTO,
  TDeleteAlertV2DTO,
  TEmailChannelConfig,
  TGetAlertV2DTO,
  TListAlertsV2DTO,
  TListAlertsV2Response,
  TListCurrentMatchingCertificatesDTO,
  TListMatchingCertificatesDTO,
  TListMatchingCertificatesResponse,
  TPagerDutyChannelConfig,
  TPkiFilterRule,
  TSlackChannelConfig,
  TTestWebhookConfigDTO,
  TUpdateAlertV2DTO,
  TWebhookChannelConfig
} from "./pki-alert-v2-types";

type TPkiAlertV2ServiceFactoryDep = {
  pkiAlertV2DAL: Pick<
    TPkiAlertV2DALFactory,
    | "create"
    | "findById"
    | "findByIdWithChannels"
    | "updateById"
    | "deleteById"
    | "findByProjectId"
    | "findByProjectIdWithCount"
    | "countByProjectId"
    | "findMatchingCertificates"
    | "transaction"
  >;
  pkiAlertChannelDAL: Pick<TPkiAlertChannelDALFactory, "create" | "findByAlertId" | "deleteByAlertId" | "insertMany">;
  pkiAlertHistoryDAL: Pick<TPkiAlertHistoryDALFactory, "createWithCertificates" | "findByAlertId">;
  permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
  licenseService: Pick<TLicenseServiceFactory, "getPlan">;
  smtpService: Pick<TSmtpService, "sendMail">;
  kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
  notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
  projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findAllProjectMembers">;
  projectDAL: Pick<TProjectDALFactory, "findById">;
  pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
};

export type TPkiAlertV2ServiceFactory = ReturnType<typeof pkiAlertV2ServiceFactory>;

export const pkiAlertV2ServiceFactory = ({
  pkiAlertV2DAL,
  pkiAlertChannelDAL,
  pkiAlertHistoryDAL,
  permissionService,
  licenseService,
  smtpService,
  kmsService,
  notificationService,
  projectMembershipDAL,
  projectDAL,
  pkiApplicationDAL
}: TPkiAlertV2ServiceFactoryDep) => {
  const $assertLegacyAlertWritesAllowed = () => {
    if (LEGACY_ALERT_WRITES_BLOCKED) {
      throw new BadRequestError({
        message:
          "Legacy PKI alerts can no longer be created or edited. Use the alerts API (/api/v1/alerts) or the Alerting section of an application instead. Existing legacy alerts can still be viewed and deleted."
      });
    }
  };

  const $assertCanActOnAlert = async (
    action: ProjectPermissionActions,
    projectId: string,
    applicationId: string | null | undefined,
    ctx: {
      actor: Parameters<TPermissionServiceFactory["getProjectPermission"]>[0]["actor"];
      actorId: string;
      actorAuthMethod: Parameters<TPermissionServiceFactory["getProjectPermission"]>[0]["actorAuthMethod"];
      actorOrgId?: string;
    }
  ) => {
    if (applicationId) {
      const { permission: resourcePerm } = await permissionService.getResourcePermission({
        actor: ctx.actor,
        actorId: ctx.actorId,
        projectId,
        resourceType: ResourceType.CertificateApplication,
        resourceId: applicationId,
        actorAuthMethod: ctx.actorAuthMethod,
        actorOrgId: ctx.actorOrgId
      });
      ForbiddenError.from(resourcePerm).throwUnlessCan(action, ResourcePermissionSub.PkiAlerts);
      return null;
    }

    const projectPerm = await permissionService.getProjectPermission({
      actor: ctx.actor,
      actorId: ctx.actorId,
      projectId,
      actorAuthMethod: ctx.actorAuthMethod,
      actorOrgId: ctx.actorOrgId,
      actionProjectType: ActionProjectType.CertificateManager
    });
    ForbiddenError.from(projectPerm.permission).throwUnlessCan(action, ProjectPermissionSub.PkiAlerts);
    return projectPerm;
  };

  // Helper to encrypt channel config before storing in DB
  const encryptChannelConfig = (
    config: TChannelConfig,
    encryptor: (data: { plainText: Buffer }) => { cipherTextBlob: Buffer }
  ): Buffer => {
    return encryptor({ plainText: Buffer.from(JSON.stringify(config)) }).cipherTextBlob;
  };

  // Helper to decrypt channel config from DB
  const decryptChannelConfig = <T extends TChannelConfig>(
    channel: { config?: unknown; encryptedConfig?: Buffer | null },
    decryptor: (data: { cipherTextBlob: Buffer }) => Buffer
  ): T => {
    if (channel.encryptedConfig) {
      const decrypted = decryptor({ cipherTextBlob: channel.encryptedConfig });
      return JSON.parse(decrypted.toString()) as T;
    }
    // Fallback for old unencrypted data
    return channel.config as T;
  };

  const formatAlertResponse = (
    alert: TAlertWithChannels,
    decryptor: (data: { cipherTextBlob: Buffer }) => Buffer
  ): TAlertV2Response => {
    return {
      id: alert.id,
      name: alert.name,
      description: alert.description ?? null,
      eventType: alert.eventType as PkiAlertEventType,
      alertBefore: alert.alertBefore ?? "",
      filters: (alert.filters ?? []) as TPkiFilterRule[],
      enabled: alert.enabled ?? true,
      projectId: alert.projectId,
      applicationId: alert.applicationId ?? null,
      applicationName: alert.applicationName ?? null,
      channels: (alert.channels || []).map((channel) => {
        const config = decryptChannelConfig<TChannelConfig>(channel, decryptor);

        // For webhook channels, replace signingSecret with hasSigningSecret
        let responseConfig: TChannelConfigResponse;
        if (channel.channelType === PkiAlertChannelType.WEBHOOK) {
          const webhookConfig = config as TWebhookChannelConfig;
          responseConfig = {
            url: webhookConfig.url,
            hasSigningSecret: Boolean(webhookConfig.signingSecret)
          };
        } else {
          // For email, slack, and pagerduty channels, the config is the same in request and response
          responseConfig = config as TEmailChannelConfig;
        }

        return {
          id: channel.id,
          channelType: channel.channelType as PkiAlertChannelType,
          config: responseConfig,
          enabled: channel.enabled,
          createdAt: channel.createdAt,
          updatedAt: channel.updatedAt
        };
      }),
      notificationConfig: (alert.notificationConfig as { enableDailyNotification: boolean }) ?? null,
      lastRun: alert.lastRunData
        ? {
            timestamp: alert.lastRunData.triggeredAt,
            status:
              !alert.lastRunData.notificationError && alert.lastRunData.hasNotificationSent
                ? PkiAlertRunStatus.SUCCESS
                : PkiAlertRunStatus.FAILED,
            error: alert.lastRunData.notificationError
          }
        : null,
      createdAt: alert.createdAt,
      updatedAt: alert.updatedAt
    };
  };

  const createAlert = async ({
    projectId,
    applicationId,
    name,
    description,
    eventType,
    alertBefore,
    filters,
    enabled = true,
    notificationConfig,
    channels,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId
  }: TCreateAlertV2DTO): Promise<TAlertV2Response> => {
    $assertLegacyAlertWritesAllowed();

    if (!applicationId) {
      throw new BadRequestError({
        message: "Alerts must be created inside an Application. Open the Application's Alerts tab and click Add Alert."
      });
    }

    await $assertCanActOnAlert(ProjectPermissionActions.Create, projectId, applicationId, {
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId
    });

    const nonEmailChannel = channels.find((channel) => channel.channelType !== PkiAlertChannelType.EMAIL);
    if (nonEmailChannel) {
      const plan = await licenseService.getPlan(actorOrgId);
      if (!plan.pkiEnterpriseAlerting) {
        throw new BadRequestError({
          message: `Failed to create alert with a ${nonEmailChannel.channelType} channel due to plan restriction. Upgrade plan to alert on channels other than email.`
        });
      }
    }

    if (eventType === PkiAlertEventType.EXPIRATION && !alertBefore) {
      throw new BadRequestError({ message: "alertBefore is required for expiration alerts" });
    }

    if (alertBefore) {
      try {
        parseTimeToPostgresInterval(alertBefore);
      } catch (error) {
        throw new BadRequestError({ message: "Invalid alertBefore format. Use format like '30d', '1w', '3m', '1y'" });
      }
    }

    // Validate webhook and Slack URLs early to provide immediate SSRF feedback
    for (const channel of channels) {
      if (channel.channelType === PkiAlertChannelType.WEBHOOK) {
        const webhookConfig = channel.config as TWebhookChannelConfig;
        // eslint-disable-next-line no-await-in-loop
        await blockLocalAndPrivateIpAddresses(webhookConfig.url);
      } else if (channel.channelType === PkiAlertChannelType.SLACK) {
        const slackConfig = channel.config as TSlackChannelConfig;
        // eslint-disable-next-line no-await-in-loop
        await validateSlackWebhookUrl(slackConfig.webhookUrl);
      }
    }

    // Create encryptor/decryptor for webhook configs
    const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.SecretManager,
      projectId
    });

    return pkiAlertV2DAL.transaction(async (tx) => {
      const alert = await pkiAlertV2DAL.create(
        {
          projectId,
          applicationId: applicationId ?? null,
          name,
          description,
          eventType,
          alertBefore: eventType === PkiAlertEventType.EXPIRATION ? alertBefore : null,
          filters,
          enabled,
          notificationConfig
        },
        tx
      );

      const channelInserts = channels.map((channel) => ({
        alertId: alert.id,
        channelType: channel.channelType,
        config: null,
        encryptedConfig: encryptChannelConfig(channel.config, encryptor),
        enabled: channel.enabled
      }));

      await pkiAlertChannelDAL.insertMany(channelInserts, tx);

      const completeAlert = await pkiAlertV2DAL.findByIdWithChannels(alert.id, tx);
      if (!completeAlert) {
        throw new NotFoundError({ message: "Failed to retrieve created alert" });
      }

      return formatAlertResponse(completeAlert, decryptor);
    });
  };

  const getAlertById = async ({
    alertId,
    applicationId,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId
  }: TGetAlertV2DTO): Promise<TAlertV2Response> => {
    const alert = await pkiAlertV2DAL.findByIdWithChannels(alertId);
    if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });
    if (applicationId && alert.applicationId !== applicationId) {
      throw new NotFoundError({
        message: `Alert with ID '${alertId}' is not scoped to application '${applicationId}'.`
      });
    }

    await $assertCanActOnAlert(ProjectPermissionActions.Read, alert.projectId, alert.applicationId, {
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId
    });

    const { decryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.SecretManager,
      projectId: alert.projectId
    });

    return formatAlertResponse(alert, decryptor);
  };

  const listAlerts = async ({
    projectId,
    applicationId,
    search,
    eventType,
    enabled,
    limit = 20,
    offset = 0,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId
  }: TListAlertsV2DTO): Promise<TListAlertsV2Response> => {
    await $assertCanActOnAlert(ProjectPermissionActions.Read, projectId, applicationId, {
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId
    });

    const filters = { search, eventType, enabled, limit, offset, applicationId };

    const { alerts, total } = await pkiAlertV2DAL.findByProjectIdWithCount(projectId, filters);

    const { decryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.SecretManager,
      projectId
    });

    return {
      alerts: alerts.map((alert) => formatAlertResponse(alert, decryptor)),
      total
    };
  };

  const updateAlert = async ({
    alertId,
    applicationId,
    name,
    description,
    eventType,
    alertBefore,
    filters,
    enabled,
    notificationConfig,
    channels,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId
  }: TUpdateAlertV2DTO): Promise<TAlertV2Response> => {
    $assertLegacyAlertWritesAllowed();

    let alert = await pkiAlertV2DAL.findById(alertId);
    if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });
    if (applicationId && alert.applicationId !== applicationId) {
      throw new NotFoundError({
        message: `Alert with ID '${alertId}' is not scoped to application '${applicationId}'.`
      });
    }

    await $assertCanActOnAlert(ProjectPermissionActions.Edit, alert.projectId, alert.applicationId, {
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId
    });

    const resultingEventType = eventType ?? (alert.eventType as PkiAlertEventType);
    const resultingAlertBefore = alertBefore !== undefined ? alertBefore : alert.alertBefore;
    if (resultingEventType === PkiAlertEventType.EXPIRATION && !resultingAlertBefore) {
      throw new BadRequestError({ message: "alertBefore is required for expiration alerts" });
    }

    if (alertBefore) {
      try {
        parseTimeToPostgresInterval(alertBefore);
      } catch (error) {
        throw new BadRequestError({ message: "Invalid alertBefore format. Use format like '30d', '1w', '3m', '1y'" });
      }
    }

    // An update replaces the channel set wholesale, so creation-only gating would let an org save an
    // email-only alert and patch Slack into it. Keeping the types it already has stays allowed.
    const addedChannelTypes = channels?.filter((channel) => channel.channelType !== PkiAlertChannelType.EMAIL);
    if (addedChannelTypes?.length) {
      const plan = await licenseService.getPlan(actorOrgId);
      if (!plan.pkiEnterpriseAlerting) {
        const existingChannels = await pkiAlertChannelDAL.findByAlertId(alertId);
        const existingTypes = new Set(existingChannels.map((channel) => channel.channelType));
        const newChannel = addedChannelTypes.find((channel) => !existingTypes.has(channel.channelType));
        if (newChannel) {
          throw new BadRequestError({
            message: `Failed to add a ${newChannel.channelType} channel to this alert due to plan restriction. Upgrade plan to alert on channels other than email.`
          });
        }
      }
    }

    const updateData: {
      name?: string;
      description?: string;
      eventType?: PkiAlertEventType;
      alertBefore?: string | null;
      filters?: TPkiFilterRule[];
      enabled?: boolean;
      notificationConfig?: { enableDailyNotification: boolean } | null;
    } = {};
    if (name !== undefined) updateData.name = name;
    if (description !== undefined) updateData.description = description;
    if (eventType !== undefined) updateData.eventType = eventType;
    if (resultingEventType !== PkiAlertEventType.EXPIRATION) {
      updateData.alertBefore = null;
    } else if (alertBefore !== undefined) {
      updateData.alertBefore = alertBefore;
    }
    if (filters !== undefined) updateData.filters = filters;
    if (enabled !== undefined) updateData.enabled = enabled;
    if (notificationConfig !== undefined) updateData.notificationConfig = notificationConfig;

    // Validate webhook and Slack URLs early to provide immediate SSRF feedback
    if (channels) {
      for (const channel of channels) {
        if (channel.channelType === PkiAlertChannelType.WEBHOOK) {
          const webhookConfig = channel.config as TWebhookChannelConfig;
          // eslint-disable-next-line no-await-in-loop
          await blockLocalAndPrivateIpAddresses(webhookConfig.url);
        } else if (channel.channelType === PkiAlertChannelType.SLACK) {
          const slackConfig = channel.config as TSlackChannelConfig;
          // eslint-disable-next-line no-await-in-loop
          await validateSlackWebhookUrl(slackConfig.webhookUrl);
        }
      }
    }

    // Create encryptor/decryptor for webhook configs
    const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.SecretManager,
      projectId: alert.projectId
    });

    return pkiAlertV2DAL.transaction(async (tx) => {
      alert = await pkiAlertV2DAL.updateById(alertId, updateData, tx);

      if (channels) {
        // Get existing channels to preserve signing secrets / integration keys if needed
        const existingChannels = await pkiAlertChannelDAL.findByAlertId(alertId, tx);
        const existingWebhookConfigs = new Map<string, TWebhookChannelConfig>();

        // Build a map of existing webhook configs by channel id for preserving signing secrets
        for (const existingChannel of existingChannels) {
          if (existingChannel.channelType === PkiAlertChannelType.WEBHOOK) {
            const config = decryptChannelConfig<TWebhookChannelConfig>(existingChannel, decryptor);
            existingWebhookConfigs.set(existingChannel.id, config);
          }
        }

        await pkiAlertChannelDAL.deleteByAlertId(alertId, tx);

        const channelInserts = channels.map((channel) => {
          let configToEncrypt = channel.config;

          // Handle webhook signing secret preserve/clear logic
          if (channel.channelType === PkiAlertChannelType.WEBHOOK) {
            const webhookConfig = channel.config as TWebhookChannelConfig;
            const existingConfig = channel.id ? existingWebhookConfigs.get(channel.id) : undefined;

            // If signingSecret is undefined and we have an existing config, preserve the existing secret
            // If signingSecret is null, explicitly clear it
            // If signingSecret has a value, use the new value
            let finalSigningSecret: string | undefined;
            if (webhookConfig.signingSecret === undefined && existingConfig?.signingSecret) {
              finalSigningSecret = existingConfig.signingSecret;
            } else if (webhookConfig.signingSecret === null) {
              finalSigningSecret = undefined;
            } else {
              finalSigningSecret = webhookConfig.signingSecret;
            }

            configToEncrypt = {
              url: webhookConfig.url,
              signingSecret: finalSigningSecret
            };
          }

          return {
            alertId,
            channelType: channel.channelType,
            config: null,
            encryptedConfig: encryptChannelConfig(configToEncrypt, encryptor),
            enabled: channel.enabled
          };
        });

        await pkiAlertChannelDAL.insertMany(channelInserts, tx);
      }

      const completeAlert = await pkiAlertV2DAL.findByIdWithChannels(alertId, tx);
      if (!completeAlert) {
        throw new NotFoundError({ message: "Failed to retrieve updated alert" });
      }

      return formatAlertResponse(completeAlert, decryptor);
    });
  };

  const deleteAlert = async ({
    alertId,
    applicationId,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId
  }: TDeleteAlertV2DTO): Promise<TAlertV2Response> => {
    const alert = await pkiAlertV2DAL.findByIdWithChannels(alertId);
    if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });
    if (applicationId && alert.applicationId !== applicationId) {
      throw new NotFoundError({
        message: `Alert with ID '${alertId}' is not scoped to application '${applicationId}'.`
      });
    }

    await $assertCanActOnAlert(ProjectPermissionActions.Delete, alert.projectId, alert.applicationId, {
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId
    });

    const { decryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.SecretManager,
      projectId: alert.projectId
    });

    const formattedAlert = formatAlertResponse(alert, decryptor);
    await pkiAlertV2DAL.deleteById(alertId);

    return formattedAlert;
  };

  const listMatchingCertificates = async ({
    alertId,
    limit = 20,
    offset = 0,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId
  }: TListMatchingCertificatesDTO): Promise<TListMatchingCertificatesResponse> => {
    const alert = await pkiAlertV2DAL.findById(alertId);
    if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });

    await $assertCanActOnAlert(ProjectPermissionActions.Read, alert.projectId, alert.applicationId, {
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId
    });

    const options: {
      limit: number;
      offset: number;
      showPreview?: boolean;
      excludeAlerted?: boolean;
      alertId?: string;
      applicationId?: string;
    } = {
      limit,
      offset,
      showPreview: true,
      excludeAlerted: alert.eventType === PkiAlertEventType.EXPIRATION,
      alertId,
      ...(alert.applicationId ? { applicationId: alert.applicationId } : {})
    };

    const result = await pkiAlertV2DAL.findMatchingCertificates(
      alert.projectId,
      alert.filters as TPkiFilterRule[],
      options
    );

    return {
      certificates: result.certificates,
      total: result.total
    };
  };

  const listCurrentMatchingCertificates = async ({
    projectId,
    filters,
    alertBefore,
    limit = 20,
    offset = 0,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId
  }: TListCurrentMatchingCertificatesDTO): Promise<TListMatchingCertificatesResponse> => {
    const { permission } = await permissionService.getProjectPermission({
      actor,
      actorId,
      projectId,
      actorAuthMethod,
      actorOrgId,
      actionProjectType: ActionProjectType.CertificateManager
    });

    ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts);

    const options: {
      limit: number;
      offset: number;
      showPreview?: boolean;
      alertBefore?: string;
    } = {
      limit,
      offset,
      showPreview: true
    };

    if (alertBefore) {
      try {
        options.alertBefore = parseTimeToPostgresInterval(alertBefore);
      } catch (error) {
        throw new BadRequestError({
          message: "Invalid alertBefore format. Use format like '30d', '1w', '3m', '1y'"
        });
      }
    }

    const result = await pkiAlertV2DAL.findMatchingCertificates(projectId, filters, options);

    return {
      certificates: result.certificates,
      total: result.total
    };
  };

  const dispatchToChannels = async ({
    alertId,
    alertName,
    alertBefore,
    projectId,
    applicationId,
    eventType,
    channels,
    matchingCertificates,
    certificateIds
  }: {
    alertId: string;
    alertName: string;
    alertBefore?: string;
    projectId: string;
    applicationId?: string;
    eventType: PkiAlertEventType;
    channels: Array<{
      id: string;
      channelType: string;
      config: unknown;
      encryptedConfig?: Buffer | null;
      enabled: boolean;
    }>;
    matchingCertificates: TCertificatePreview[];
    certificateIds: string[];
  }) => {
    let hasNotificationSent = false;
    let notificationError: string | undefined;
    const errors: string[] = [];

    const alertBeforeDays = alertBefore ? parseTimeToDays(alertBefore) : 0;
    const project = await requestMemoize(requestMemoKeys.projectFindById(projectId), () =>
      projectDAL.findById(projectId)
    );
    if (!project) throw new NotFoundError({ message: `Project '${projectId}' not found` });
    const application = applicationId ? await pkiApplicationDAL.findById(applicationId) : null;
    const alertData: TAlertInfo = {
      id: alertId,
      name: alertName,
      ...(alertBefore ? { alertBefore } : {}),
      projectId,
      orgId: project.orgId,
      ...(applicationId ? { applicationId } : {}),
      ...(application?.name ? { applicationName: application.name } : {})
    };
    const webhookEventType = alertEventTypeToWebhookEventType[eventType];

    // Get decryptor for channel configs
    const { decryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.SecretManager,
      projectId
    });

    // Process each channel
    const channelPromises = channels.map(async (channel) => {
      try {
        switch (channel.channelType) {
          case PkiAlertChannelType.EMAIL: {
            const config = decryptChannelConfig<TEmailChannelConfig>(channel, decryptor);
            const result = await sendEmailNotificationWithRetry(
              smtpService,
              config,
              alertData,
              alertBeforeDays,
              matchingCertificates,
              channel.id,
              eventType
            );
            return { ...result, channelType: channel.channelType };
          }
          case PkiAlertChannelType.WEBHOOK: {
            const config = decryptChannelConfig<TWebhookChannelConfig>(channel, decryptor);
            const result = await sendWebhookNotification(
              config,
              alertData,
              matchingCertificates,
              webhookEventType,
              channel.id
            );
            return { ...result, channelType: channel.channelType };
          }
          case PkiAlertChannelType.SLACK: {
            const config = decryptChannelConfig<TSlackChannelConfig>(channel, decryptor);
            const result = await sendSlackNotificationWithRetry(
              config,
              alertData,
              matchingCertificates,
              channel.id,
              eventType
            );
            return { ...result, channelType: channel.channelType };
          }
          case PkiAlertChannelType.PAGERDUTY: {
            const config = decryptChannelConfig<TPagerDutyChannelConfig>(channel, decryptor);
            const result = await sendPagerDutyNotificationWithRetry(
              config,
              alertData,
              matchingCertificates,
              channel.id,
              eventType
            );
            return { ...result, channelType: channel.channelType };
          }
          default:
            return { success: false, channelType: channel.channelType, error: "Unknown channel type" };
        }
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : "Unknown error";
        logger.error(err, `Failed to send ${channel.channelType} notification for alert ${alertId}`);

        return { success: false, channelType: channel.channelType, error: errorMessage };
      }
    });

    const results = await Promise.all(channelPromises);

    // After attempting all channels with retries, always mark as success
    // This ensures the alert history records the attempt, even if some channels failed
    // Error details are still captured and shown to admins via in-app notifications
    hasNotificationSent = true;

    // Collect errors from failed channels
    results.forEach((r) => {
      if (!r.success && r.error) {
        errors.push(`${r.channelType}: ${r.error}`);
      }
    });

    if (errors.length > 0) {
      notificationError = errors.join("\n");

      // Send in-app notifications to project admins
      try {
        const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId);

        const projectAdmins = projectMembers.filter((member) =>
          member.roles.some((role) => role.role === ProjectMembershipRole.Admin)
        );

        if (projectAdmins.length > 0) {
          const alertingPath = `/organizations/${project.orgId}/projects/cert-manager/${projectId}/alerting`;
          const truncatedError =
            notificationError.length > 200 ? `${notificationError.substring(0, 200)}...` : notificationError;

          await notificationService.createUserNotifications(
            projectAdmins.map((admin) => ({
              userId: admin.userId,
              orgId: project.orgId,
              type: NotificationType.PKI_ALERT_CHANNEL_FAILED,
              title: `PKI Alert Channel Failed: ${alertName}`,
              body: `Your PKI alert **${alertName}** failed to deliver notifications: \`${truncatedError}\``,
              link: alertingPath
            }))
          );
        }
      } catch (notifyErr) {
        logger.error(notifyErr, `Failed to send in-app notification for PKI alert channel failure: ${alertId}`);
      }
    }

    await pkiAlertHistoryDAL.createWithCertificates(alertId, certificateIds, {
      hasNotificationSent,
      notificationError
    });
  };

  const sendAlertNotifications = async (alertId: string, certificateIds: string[]) => {
    const alert = await pkiAlertV2DAL.findByIdWithChannels(alertId);
    if (!alert || !alert.enabled) return;

    const { projectId } = alert;
    const channels = alert.channels.filter((channel) => channel.enabled);
    if (channels.length === 0) return;

    const alertBefore = alert.alertBefore ?? "";
    const filters = (alert.filters ?? []) as TPkiFilterRule[];

    const { certificates } = await pkiAlertV2DAL.findMatchingCertificates(projectId, filters, {
      alertBefore: parseTimeToPostgresInterval(alertBefore),
      ...(alert.applicationId ? { applicationId: alert.applicationId } : {})
    });

    const matchingCertificates = certificates.filter(
      (cert) => certificateIds.includes(cert.id) && cert.enrollmentType !== CertificateOrigin.CA
    );

    if (matchingCertificates.length === 0) return;

    await dispatchToChannels({
      alertId,
      alertName: alert.name,
      alertBefore,
      projectId,
      applicationId: alert.applicationId ?? undefined,
      eventType: PkiAlertEventType.EXPIRATION,
      channels,
      matchingCertificates,
      certificateIds
    });
  };

  const sendEventNotifications = async (alertId: string, certificateIds: string[], eventType: PkiAlertEventType) => {
    const alert = await pkiAlertV2DAL.findByIdWithChannels(alertId);
    if (!alert || !alert.enabled) return;

    const { projectId } = alert;
    const channels = alert.channels.filter((channel) => channel.enabled);
    if (channels.length === 0) return;

    const filters = (alert.filters ?? []) as TPkiFilterRule[];
    const applicationScope = alert.applicationId ? { applicationId: alert.applicationId } : {};

    const matchingPerCert = await Promise.all(
      certificateIds.map((certId) =>
        // The event is queued right after the certificate commits, and an empty match ends the job
        // for good, so a lagging replica would silently drop the notification.
        pkiAlertV2DAL.findMatchingCertificates(projectId, filters, {
          certificateId: certId,
          ...applicationScope,
          readFromPrimary: true
        })
      )
    );
    const allCertificates: TCertificatePreview[] = matchingPerCert.flatMap((r) => r.certificates);

    const matchingCertificates = allCertificates.filter((cert) => cert.enrollmentType !== CertificateOrigin.CA);

    if (matchingCertificates.length === 0) return;

    await dispatchToChannels({
      alertId,
      alertName: alert.name,
      alertBefore: alert.alertBefore ?? undefined,
      projectId,
      applicationId: alert.applicationId ?? undefined,
      eventType,
      channels,
      matchingCertificates,
      certificateIds
    });
  };

  const testWebhookConfig = async ({
    projectId,
    applicationId,
    url,
    signingSecret,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId
  }: TTestWebhookConfigDTO): Promise<{ success: boolean; error?: string }> => {
    await $assertCanActOnAlert(ProjectPermissionActions.Edit, projectId, applicationId, {
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId
    });

    const project = await requestMemoize(requestMemoKeys.projectFindById(projectId), () =>
      projectDAL.findById(projectId)
    );
    if (!project) throw new NotFoundError({ message: `Project '${projectId}' not found` });
    const application = applicationId ? await pkiApplicationDAL.findById(applicationId) : null;

    // Create test data (SSRF validation is done in sendWebhookNotification)
    const alertData: TAlertInfo = {
      id: "00000000-0000-0000-0000-000000000000",
      name: "Test Alert",
      alertBefore: "30d",
      projectId,
      orgId: project.orgId,
      ...(applicationId ? { applicationId } : {}),
      ...(application?.name ? { applicationName: application.name } : {})
    };

    const testCertificates: TCertificatePreview[] = [
      {
        id: "00000000-0000-0000-0000-000000000000",
        serialNumber: "TEST-SERIAL-NUMBER",
        commonName: "test.example.com",
        san: ["test.example.com", "www.test.example.com"],
        profileName: "Test Profile",
        enrollmentType: CertificateOrigin.PROFILE,
        notBefore: new Date(),
        notAfter: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        status: "active"
      }
    ];

    try {
      const config: TWebhookChannelConfig = { url, signingSecret };
      const result = await sendWebhookNotification(
        config,
        alertData,
        testCertificates,
        PkiWebhookEventType.CERTIFICATE_TEST,
        "test"
      );

      if (!result.success) {
        return { success: false, error: result.error };
      }
      return { success: true };
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : "Unknown error occurred";
      logger.error(err, `Failed to test webhook config for project ${projectId}`);
      return { success: false, error: errorMessage };
    }
  };

  return {
    createAlert,
    getAlertById,
    listAlerts,
    updateAlert,
    deleteAlert,
    listMatchingCertificates,
    listCurrentMatchingCertificates,
    sendAlertNotifications,
    sendEventNotifications,
    testWebhookConfig
  };
};