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
Address PR comments
Carlos Monastyrski9e4afe54c144
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 6fe56994fc..37faacb0dc 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -678,7 +678,7 @@ See `src/services/health-alert/health-alert-queue.ts` for a minimal example, `sr`src/services/alert/` is **the** alerting module: one `alerts` table, one channel stack (email, Slack, webhook, PagerDuty), one recipient resolver, one encryption story for channel configs, one dedup + history + retention path, one cron tick that fans out into the `AlertDispatch` queue, and one set of routes (`src/server/routes/v1/alert-router.ts`, including `POST /channels/test`).-**Any new "notify someone when X happens" capability belongs here as a provider.** Do not write a per-domain alert service, per-domain channel table, or per-domain notification cron — that path produces N half-featured implementations (only one of which gets PagerDuty, or dedup, or a test button). `src/services/pki-alert-v2/` predates this module and is legacy. New PKI application alerts live here (`cert-manager.application`); existing PKI Alerts V2 rows were not migrated and keep firing, both project-wide and application-scoped, and can still be read and deleted through the deprecated routes. Creating and editing them is refused by `LEGACY_ALERT_WRITES_BLOCKED` (`pki-alert-v2-constants.ts`). Certificate code paths still queue it directly through `pkiAlertV2Queue`, next to the `certificateAlertEventEmitter` call that feeds this module (`emit` inside the certificate transaction, `notify` where there is none). Don't add features to it or copy it.+**Any new "notify someone when X happens" capability belongs here as a provider.** Do not write a per-domain alert service, per-domain channel table, or per-domain notification cron — that path produces N half-featured implementations (only one of which gets PagerDuty, or dedup, or a test button). `src/services/pki-alert-v2/` predates this module and is legacy. New PKI application alerts live here (`cert-manager.application`); existing PKI Alerts V2 rows were not migrated and keep firing, both project-wide and application-scoped, and can still be read and deleted through the deprecated routes. Creating and editing them is refused by `LEGACY_ALERT_WRITES_BLOCKED` (`pki-alert-v2-constants.ts`). Certificate code paths still queue it directly through `pkiAlertV2Queue`, next to the `certificateAlertEventEmitter` call that feeds this module (`emit` inside the issuance and renewal transactions, `notify` where there is none and after a revocation commits, so a failed event insert can never roll back a revocation the upstream CA already made). Don't add features to it or copy it.Adding a new alertable resource type:@@ -689,14 +689,14 @@ That's it — CRUD routes, channel creation/rotation, recipient resolution, KMS**Each event declares how it fires**, and the trigger decides which discovery method the provider owes:-- `AlertTriggerType.Scheduled` → **`findDueTargets`**. The daily cron asks what is currently due, and the engine dedups per `(channel, target)` so a target rediscovered tomorrow is not alerted on twice.-- `AlertTriggerType.Event` → **`findTargetsByIds`**. The target is already known, so nothing is scanned for and **nothing is deduped**: an event that fired is one the customer asked to hear about, and unlike a daily scan it is never rediscovered. These reach the engine from the event outbox (below), never from the cron. The input carries the outbox row's whole `payload` next to `targetIds`: the module only reads `targetIds`, so an emitter can add the facts the notification needs (which auth method, who changed it) and the provider validates them with its own schema at delivery. Encoding facts into the target id is the wrong tool for that.+- `AlertTriggerType.Scheduled` → **`findScheduledTargets`**. The daily cron asks what is currently due, and the engine dedups per `(channel, target)` so a target rediscovered tomorrow is not alerted on twice.+- `AlertTriggerType.Event` → **`findEventTargets`**. The target is already known, so nothing is scanned for and **nothing is deduped**: an event that fired is one the customer asked to hear about, and unlike a daily scan it is never rediscovered. These reach the engine from the event outbox (below), never from the cron. The input carries the outbox row's whole `payload` next to `targetIds`: the module only reads `targetIds`, so an emitter can add the facts the notification needs (which auth method, who changed it) and the provider validates them with its own schema at delivery. Encoding facts into the target id is the wrong tool for that.**`findEnabledForEvent` with no `projectId` matches every alert bound to the resource, any scope.** A resource that has no project of its own (an org-level identity) can still be watched from a project it is a member of, and `assertResourceInScope` already checked that binding at create. Given a `projectId`, it matches that project's alerts plus org-scoped ones.-`alertProviderRegistry.register` asserts that pairing at boot, so a provider that declares an event trigger without `findTargetsByIds` fails the process rather than silently no-op'ing in production. `triggerType` is derived from the provider's event definition inside `createAlert` and is never accepted from a request.+`alertProviderRegistry.register` asserts that pairing at boot, so a provider that declares an event trigger without `findEventTargets` fails the process rather than silently no-op'ing in production. `triggerType` is derived from the provider's event definition inside `createAlert` and is never accepted from a request.-**Event-path reads go to the primary, `findTargetsByIds` included.** An empty read there is terminal (the event is marked delivered and never asked about again), so a replica that hasn't seen the commit loses the notification. `findEnabledForEvent` and the engine's channel lookup already do this; a provider's `findTargetsByIds` must too, since the target usually commits in the same transaction as the event. The scheduled path keeps the replica because tomorrow's scan asks again.+**Event-path reads go to the primary, `findEventTargets` included.** An empty read there is terminal (the event is marked delivered and never asked about again), so a replica that hasn't seen the commit loses the notification. `findEnabledForEvent` and the engine's channel lookup already do this; a provider's `findEventTargets` must too, since the target usually commits in the same transaction as the event. The scheduled path keeps the replica because tomorrow's scan asks again.**The history write is retried, then logged, never thrown.** The channels have already sent by then, so a throw can't undo anything and would re-notify on the event path.@@ -705,10 +705,10 @@ Invariants worth knowing before extending it:- **The alert module owns no CASL subject.** Each provider reuses its own resource's existing permissions inside `assertPermission`, so authorization stays with the domain that owns the resource.- **New delivery mediums are channel definitions**, not providers: add one under `src/services/alert/channels/` and register it in `ALERT_CHANNEL_REGISTRY`. `directed: true` means the channel addresses principals and needs recipients (email); undirected channels carry their destination in config. `secretFields` drives masking on read and merge-from-stored on update.- **Channel configs are encrypted** with the org/project KMS cipher (`alert-channel-crypto-fns.ts`) — never store or return them in plaintext.-- **One alert per `(scope, resource, event)`**, enforced by `alert_unique_scope_resource_event`. `assertChannelTypesAllowed` is where a provider gates paid channel types on create and on update (new types only). `getResourceNames` (batched) supplies the human-readable name the alert audit events carry next to `resourceId`; without it the name is `null`. `resolveProjectId` lets create, list and test sends omit `projectId` when the resource already belongs to one project (`resolveAlertProjectId` in `alert-types.ts`). `getTelemetryEvent` lets a provider map alert create, update and delete to its own PostHog event, so the shared router never branches on a resource type. The deprecated `pki/alerts` and `applications/:applicationId/alerts` routes only serve legacy PKI Alerts V2 rows. Add features to `/api/v1/alerts`, not to them.-- **Email channels accept plain addresses as `EMAIL` recipients**, with the address as `principalId`, besides users and groups. Every address must be on one of the org's verified email domains, checked on create, update and test sends (`alert-channel-service.ts`). The resolver sends to them directly and skips an address that a user recipient on the same channel already covers.-- **`findDueTargets` must return most-urgent-first.** The engine's per-channel `maxTargetsPerRun` cap keeps the head of the list and defers the tail, so ordering is what guarantees the closest-to-expiry targets are never the dropped ones.-- **Deleting an alertable resource does NOT delete its alerts. You have to reap them yourself.** `alerts.resourceId` is a plain string column with **no foreign key** to the resource's table (a provider's `resourceType` can point at anything), so nothing cascades. Skip the reap and the row survives as a dangling alert whose `findDueTargets` matches nothing and whose "view" link 404s. Two helpers on `alertService`, and picking the wrong one is the bug:+- **One alert per `(scope, resource, event)`**, enforced by `alert_unique_scope_resource_event`. **Every provider hook is opt-in, and its absence must reproduce the behaviour identity alerts had before any other provider existed.** `recipientPolicy` decides who can receive: `atOrgScope` validates and resolves user and group recipients against the org instead of the alert's project, and `allowEmailAddresses` accepts plain `EMAIL` recipients and makes test sends validate recipients like create and update do, instead of silently dropping out-of-scope ones (application alerts set both). `includeLastRun` adds `lastRun` to alert responses, and `resourceName` is only returned by providers that implement `getResourceNames`. `assertChannelTypesAllowed` is where a provider gates paid channel types on create and on update (new types only). `getResourceNames` (batched) supplies the resource's display name for alert responses and for a provider's own audit events. `resolveProjectId` lets create, list and test sends omit `projectId` when the resource already belongs to one project (`resolveAlertProjectId` in `alert-types.ts`). `getTelemetryEvent` lets a provider map alert create, update and delete to its own PostHog event, so the shared router never branches on a resource type. `getAuditEvent` does the same for audit logs: a provider that needs distinct event types (application alerts log `create-pki-application-alert` and its siblings, with the application's ID and name) returns its own event, and every other provider falls back to the generic `create-alert` family via `buildGenericAlertAuditEvent`. Add a provider's own event interfaces next to the generic ones; never widen the generic ones. The deprecated `pki/alerts` and `applications/:applicationId/alerts` routes only serve legacy PKI Alerts V2 rows. Add features to `/api/v1/alerts`, not to them.+- **Email channels accept plain addresses as `EMAIL` recipients when the provider opts in** (`recipientPolicy.allowEmailAddresses`), with the address as `principalId`, besides users and groups. Every address must be on one of the org's verified email domains, checked on create, update and test sends (`alert-channel-service.ts`). The resolver sends to them directly and skips an address that a user recipient on the same channel already covers.+- **`findScheduledTargets` must return most-urgent-first.** The engine's per-channel `maxTargetsPerRun` cap keeps the head of the list and defers the tail, so ordering is what guarantees the closest-to-expiry targets are never the dropped ones.+- **Deleting an alertable resource does NOT delete its alerts. You have to reap them yourself.** `alerts.resourceId` is a plain string column with **no foreign key** to the resource's table (a provider's `resourceType` can point at anything), so nothing cascades. Skip the reap and the row survives as a dangling alert whose `findScheduledTargets` matches nothing and whose "view" link 404s. Two helpers on `alertService`, and picking the wrong one is the bug:- **`deleteAlertsForDeletedResource({ resourceType, resourceId })`** when the resource **row is gone**. It has **no scope filter** and reaps across every org and project. This is required, not just tidier: the same resource can be watched from another org (a root-org identity invited into a child org), so an `orgId`-filtered reap leaves those rows orphaned.- **`deleteAlertsForResource({ orgId, projectId?, resourceType, resourceId })`** when the resource merely **left a scope** (removed from a project, removed from an org) but still exists. Narrow on purpose: leaving one project must not drop the org-level alert, and leaving one org must not touch another org's alerts. Omitting `projectId` reaps the whole org, which is what org-membership removal wants since it cascades the project memberships.@@ -729,7 +729,7 @@ at-least-once delivery of a domain event registers next to it.`EventOutboxStatus`, `TOutboxFlushKey`) describe the mechanism and stay inside the module and itswiring. A dependency field for the emitter is `eventEmitter`, not `eventOutboxService`.-**Emitting:** `eventEmitter.emit(event, tx)`. `tx` is required on purpose.+**Emitting:** `eventEmitter.emit(event, tx)`. Pass the transaction of the write the event describes, so the event is exactly as durable as that write. Omit `tx` only when there is no such write left to be atomic with (for example after it already committed); the insert then runs on its own.```tsawait someDAL.transaction(async (tx) => {@@ -803,7 +803,7 @@ stuck claim alike. `lag` and `exhausted.count` are recorded by the outbox, labelnew consumer gets them for free.**Adding an event-triggered alert** needs no outbox code: declare the event with-`triggerType: AlertTriggerType.Event`, implement `findTargetsByIds`, and emit with+`triggerType: AlertTriggerType.Event`, implement `findEventTargets`, and emit with`payload: { orgId, projectId, resourceType, resourceId, targetIds, ...facts }` where `resourceType` is theprovider's. A`resourceType` that doesn't declare the `eventType` fails the row terminally with both named, so a baddiff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 6ae64a2503..fcc49605eb 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -953,7 +953,11 @@ export enum EventType {CREATE_ALERT = "create-alert",UPDATE_ALERT = "update-alert",DELETE_ALERT = "delete-alert",- TEST_ALERT_CHANNEL = "test-alert-channel"+ TEST_ALERT_CHANNEL = "test-alert-channel",+ CREATE_PKI_APPLICATION_ALERT = "create-pki-application-alert",+ UPDATE_PKI_APPLICATION_ALERT = "update-pki-application-alert",+ DELETE_PKI_APPLICATION_ALERT = "delete-pki-application-alert",+ TEST_PKI_APPLICATION_ALERT_CHANNEL = "test-pki-application-alert-channel"}// Maps each actor type to the JSONB key that holds the actor's primary ID in actorMetadata.@@ -7775,7 +7779,6 @@ interface CreateAlertEvent {name: string;resourceType: string;resourceId?: string | null;- resourceName?: string | null;eventType: string;};}@@ -7786,8 +7789,6 @@ interface UpdateAlertEvent {alertId: string;name: string;resourceType: string;- resourceId?: string | null;- resourceName?: string | null;eventType: string;};}@@ -7798,8 +7799,6 @@ interface DeleteAlertEvent {alertId: string;name: string;resourceType: string;- resourceId?: string | null;- resourceName?: string | null;eventType: string;};}@@ -7817,11 +7816,47 @@ interface TestAlertChannelEvent {};}+type TPkiApplicationAlertEventMetadata = {+ applicationId: string | null;+ applicationName: string | null;+};++interface CreatePkiApplicationAlertEvent {+ type: EventType.CREATE_PKI_APPLICATION_ALERT;+ metadata: TPkiApplicationAlertEventMetadata & { alertId: string; name: string; eventType: string };+}++interface UpdatePkiApplicationAlertEvent {+ type: EventType.UPDATE_PKI_APPLICATION_ALERT;+ metadata: TPkiApplicationAlertEventMetadata & { alertId: string; name: string; eventType: string };+}++interface DeletePkiApplicationAlertEvent {+ type: EventType.DELETE_PKI_APPLICATION_ALERT;+ metadata: TPkiApplicationAlertEventMetadata & { alertId: string; name: string; eventType: string };+}++interface TestPkiApplicationAlertEvent {+ type: EventType.TEST_PKI_APPLICATION_ALERT_CHANNEL;+ metadata: TPkiApplicationAlertEventMetadata & {+ alertId?: string;+ channelId?: string;+ channelType: string;+ success: boolean;+ deliveredTo?: number;+ error?: string;+ };+}+export type Event =| CreateAlertEvent| UpdateAlertEvent| DeleteAlertEvent| TestAlertChannelEvent+ | CreatePkiApplicationAlertEvent+ | UpdatePkiApplicationAlertEvent+ | DeletePkiApplicationAlertEvent+ | TestPkiApplicationAlertEvent| CreateSubOrganizationEvent| UpdateSubOrganizationEvent| DeleteSubOrganizationEventdiff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.tsindex 1d922b4096..7fb9b286e7 100644--- a/backend/src/server/routes/v1/alert-router.ts+++ b/backend/src/server/routes/v1/alert-router.ts@@ -1,12 +1,12 @@import { FastifyRequest } from "fastify";import { z } from "zod";-import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AlertChannelType } from "@app/services/alert/alert-channel-types";import {+ AlertAuditAction,AlertPrincipalType,AlertRunStatus,AlertTelemetryAction,@@ -49,7 +49,7 @@ const AlertResponseSchema = z.object({enabled: z.boolean(),orgId: z.string(),projectId: z.string().nullable(),- resourceName: z.string().nullable(),+ resourceName: z.string().nullable().optional(),channels: z.array(z.object({id: z.string().uuid(),@@ -60,7 +60,10 @@ const AlertResponseSchema = z.object({recipients: z.array(z.object({ principalType: z.string(), principalId: z.string() }))})),- lastRun: z.object({ timestamp: z.date(), status: z.nativeEnum(AlertRunStatus) }).nullable(),+ lastRun: z+ .object({ timestamp: z.date(), status: z.nativeEnum(AlertRunStatus) })+ .nullable()+ .optional(),createdAt: z.date(),updatedAt: z.date()});@@ -112,17 +115,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {await server.services.auditLog.createAuditLog({...req.auditLogInfo,...(alert.projectId ? { projectId: alert.projectId } : { orgId: alert.orgId }),- event: {- type: EventType.CREATE_ALERT,- metadata: {- alertId: alert.id,- name: alert.name,- resourceType: alert.resourceType,- resourceId: alert.resourceId,- resourceName: alert.resourceName,- eventType: alert.eventType- }- }+ event: server.services.alert.getAuditEvent({ action: AlertAuditAction.Create, alert })});await $sendAlertTelemetry(req, AlertTelemetryAction.Create, alert);@@ -141,6 +134,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {resourceType: z.string().min(1),resourceId: z.string().nullable().optional(),projectId: z.string().nullable().optional(),+ alertId: z.string().uuid().optional(),channelId: z.string().uuid().optional(),channelType: z.nativeEnum(AlertChannelType),config: z.record(z.unknown()).default({}),@@ -156,7 +150,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),handler: async (req) => {- const { projectId, ...result } = await server.services.alertChannelTest.testChannel({+ const { projectId, resourceName, ...result } = await server.services.alertChannelTest.testChannel({...req.body,actor: req.permission.type,actorId: req.permission.id,@@ -167,18 +161,20 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {await server.services.auditLog.createAuditLog({...req.auditLogInfo,...(projectId ? { projectId } : { orgId: req.permission.orgId }),- event: {- type: EventType.TEST_ALERT_CHANNEL,- metadata: {- channelId: req.body.channelId,- channelType: req.body.channelType,+ event: server.services.alert.getAuditEvent({+ action: AlertAuditAction.TestChannel,+ test: {resourceType: req.body.resourceType,resourceId: req.body.resourceId,+ resourceName,+ alertId: req.body.alertId,+ channelId: req.body.channelId,+ channelType: req.body.channelType,success: result.success,deliveredTo: result.deliveredTo,error: result.error}- }+ })});return result;@@ -267,17 +263,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {await server.services.auditLog.createAuditLog({...req.auditLogInfo,...(alert.projectId ? { projectId: alert.projectId } : { orgId: alert.orgId }),- event: {- type: EventType.UPDATE_ALERT,- metadata: {- alertId: alert.id,- name: alert.name,- resourceType: alert.resourceType,- resourceId: alert.resourceId,- resourceName: alert.resourceName,- eventType: alert.eventType- }- }+ event: server.services.alert.getAuditEvent({ action: AlertAuditAction.Update, alert })});await $sendAlertTelemetry(req, AlertTelemetryAction.Update, alert);@@ -308,17 +294,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {await server.services.auditLog.createAuditLog({...req.auditLogInfo,...(alert.projectId ? { projectId: alert.projectId } : { orgId: alert.orgId }),- event: {- type: EventType.DELETE_ALERT,- metadata: {- alertId: alert.id,- name: alert.name,- resourceType: alert.resourceType,- resourceId: alert.resourceId,- resourceName: alert.resourceName,- eventType: alert.eventType- }- }+ event: server.services.alert.getAuditEvent({ action: AlertAuditAction.Delete, alert })});await $sendAlertTelemetry(req, AlertTelemetryAction.Delete, alert);diff --git a/backend/src/services/alert/alert-channel-service.test.ts b/backend/src/services/alert/alert-channel-service.test.tsindex 3fb4da6ef4..495f769ee4 100644--- a/backend/src/services/alert/alert-channel-service.test.ts+++ b/backend/src/services/alert/alert-channel-service.test.ts@@ -11,6 +11,8 @@ const cipher = { encryptor, decryptor } as never;const encConfig = (config: unknown) => Buffer.from(JSON.stringify(config));const tx = {} as Knex;const CREATOR = { createdByActorId: "11111111-1111-1111-1111-111111111111", createdByActorType: "user" };+const RECIPIENT_SCOPE = { projectId: null, allowEmailAddresses: true };+const CHANNEL_INPUT = { ...CREATOR, recipientScope: RECIPIENT_SCOPE };type TRow = {id: string;@@ -98,7 +100,7 @@ const seedRow = (enabled: true,orgId: "org-1",projectId: null,- ...CREATOR,+ ...CHANNEL_INPUT,createdAt: new Date(),updatedAt: new Date(),...over@@ -113,7 +115,7 @@ describe("alert channel service", () => {channelType: AlertChannelType.WEBHOOK,config: { url: "https://example.com/hook", signingSecret: "s3cr3t" },orgId: "org-1",- ...CREATOR+ ...CHANNEL_INPUT},encryptor as never,tx@@ -130,7 +132,7 @@ describe("alert channel service", () => {const { service } = buildService();await expect(service.createChannelInTx(- { name: "Team email", channelType: AlertChannelType.EMAIL, config: {}, orgId: "org-1", ...CREATOR },+ { name: "Team email", channelType: AlertChannelType.EMAIL, config: {}, orgId: "org-1", ...CHANNEL_INPUT },encryptor as never,tx)@@ -144,7 +146,7 @@ describe("alert channel service", () => {config: { url: "https://example.com/hook" },recipients: [{ principalType: AlertPrincipalType.USER, principalId: "user-1" }],orgId: "org-1",- ...CREATOR+ ...CHANNEL_INPUT},encryptor as never,tx@@ -161,7 +163,7 @@ describe("alert channel service", () => {config: {},recipients: [{ principalType: AlertPrincipalType.USER, principalId: "user-1" }],orgId: "org-1",- ...CREATOR+ ...CHANNEL_INPUT},encryptor as never,tx@@ -172,28 +174,61 @@ describe("alert channel service", () => {expect(recipients.get(channel.id)).toHaveLength(1);});- test("collapses email recipients that differ only by case or spacing", async () => {+ test("rejects duplicate recipients instead of dropping them", async () => {+ const { service } = buildService();+ await expect(+ service.createChannelInTx(+ {+ name: "Team email",+ channelType: AlertChannelType.EMAIL,+ config: {},+ recipients: [+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" },+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }+ ],+ orgId: "org-1",+ ...CHANNEL_INPUT+ },+ encryptor as never,+ tx+ )+ ).rejects.toThrow("Duplicate recipients: [email protected]");+ await expect(+ service.validateRecipients("org-1", RECIPIENT_SCOPE, [+ { principalType: AlertPrincipalType.USER, principalId: "user-1" },+ { principalType: AlertPrincipalType.USER, principalId: "user-1" }+ ])+ ).rejects.toThrow("Duplicate recipients: user-1");+ });++ test("stores email recipients exactly as sent", async () => {const { service, recipients } = buildService();const channel = await service.createChannelInTx({name: "Team email",channelType: AlertChannelType.EMAIL,config: {},- recipients: [- { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" },- { principalType: AlertPrincipalType.EMAIL, principalId: " [email protected] " }- ],+ recipients: [{ principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }],orgId: "org-1",- ...CREATOR+ ...CHANNEL_INPUT},encryptor as never,tx);expect(recipients.get(channel.id)).toEqual([- { channelId: channel.id, principalType: "email", principalId: "[email protected]" }+ { channelId: channel.id, principalType: "email", principalId: "[email protected]" }]);});+ test("rejects email address recipients for alert types that don't accept them", async () => {+ const { service } = buildService();+ await expect(+ service.validateRecipients("org-1", { projectId: null, allowEmailAddresses: false }, [+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }+ ])+ ).rejects.toThrow("doesn't accept email address recipients");+ });+test("rejects an email recipient on an unverified domain", async () => {const { service } = buildService();await expect(@@ -203,7 +238,7 @@ describe("alert channel service", () => {channelType: AlertChannelType.EMAIL,config: {},orgId: "org-1",- ...CREATOR,+ ...CHANNEL_INPUT,recipients: [{ principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }]},encryptor as never,@@ -215,12 +250,12 @@ describe("alert channel service", () => {test("validates standalone email recipients against the verified domains", async () => {const { service } = buildService();await expect(- service.validateEmailRecipients("org-1", [+ service.validateRecipients("org-1", RECIPIENT_SCOPE, [{ principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }])).rejects.toThrow("Not on a verified domain: [email protected]");await expect(- service.validateEmailRecipients("org-1", [+ service.validateRecipients("org-1", RECIPIENT_SCOPE, [{ principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }])).resolves.toBeUndefined();@@ -239,7 +274,7 @@ describe("alert channel service", () => {// Config sent without signingSecret -> keep the existing one.await service.updateChannelInTx(- { channelId: "ch-1", config: { url: "https://example.com/hook" } },+ { recipientScope: RECIPIENT_SCOPE, channelId: "ch-1", config: { url: "https://example.com/hook" } },store.get("ch-1") as never,cipher,tx@@ -259,7 +294,7 @@ describe("alert channel service", () => {await expect(service.updateChannelInTx(- { channelId: "ch-1", channelType: AlertChannelType.SLACK },+ { recipientScope: RECIPIENT_SCOPE, channelId: "ch-1", channelType: AlertChannelType.SLACK },channel as never,cipher,tx@@ -276,7 +311,11 @@ describe("alert channel service", () => {});await service.updateChannelInTx(- { channelId: "ch-1", config: { url: "https://example.com/hook", signingSecret: "" } },+ {+ recipientScope: RECIPIENT_SCOPE,+ channelId: "ch-1",+ config: { url: "https://example.com/hook", signingSecret: "" }+ },channel as never,cipher,tx@@ -296,7 +335,11 @@ describe("alert channel service", () => {});await service.updateChannelInTx(- { channelId: "ch-1", config: { url: "https://example.com/hook", signingSecret: "new" } },+ {+ recipientScope: RECIPIENT_SCOPE,+ channelId: "ch-1",+ config: { url: "https://example.com/hook", signingSecret: "new" }+ },channel as never,cipher,tx@@ -314,7 +357,12 @@ describe("alert channel service", () => {});await expect(- service.updateChannelInTx({ channelId: "ch-1", config: { webhookUrl: "" } }, channel as never, cipher, tx)+ service.updateChannelInTx(+ { recipientScope: RECIPIENT_SCOPE, channelId: "ch-1", config: { webhookUrl: "" } },+ channel as never,+ cipher,+ tx+ )).rejects.toThrow(/Invalid slack channel config/);});});diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.tsindex a56d38e0e2..3442d9d36d 100644--- a/backend/src/services/alert/alert-channel-service.ts+++ b/backend/src/services/alert/alert-channel-service.ts@@ -24,7 +24,7 @@ import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal"import { TAlertChannelEmbedded, TChannelRecipientInput } from "./alert-channel-service-types";import { AlertChannelType } from "./alert-channel-types";import { findVerifiedEmailDomains, isOnVerifiedDomain, resolvePrincipalsInScope } from "./alert-principal-scope-fns";-import { AlertPrincipalType } from "./alert-types";+import { AlertPrincipalType, TAlertRecipientScope } from "./alert-types";import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";export type TAlertChannelServiceFactoryDep = {@@ -49,6 +49,7 @@ export type TCreateChannelInTxInput = {recipients?: TChannelRecipientInput[];orgId: string;projectId?: string | null;+ recipientScope: TAlertRecipientScope;createdByActorId: string;createdByActorType: string;};@@ -60,6 +61,7 @@ export type TUpdateChannelInTxInput = {config?: Record<string, unknown>;enabled?: boolean;recipients?: TChannelRecipientInput[];+ recipientScope: TAlertRecipientScope;};const capitalize = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);@@ -72,26 +74,24 @@ export const alertChannelServiceFactory = ({groupDAL,emailDomainDAL}: TAlertChannelServiceFactoryDep) => {- const $normalizeRecipients = (recipients: TChannelRecipientInput[]): TChannelRecipientInput[] => {+ const $assertNoDuplicateRecipients = (recipients: TChannelRecipientInput[]) => {const seen = new Set<string>();- return recipients- .map((recipient) =>+ const duplicates = new Set<string>();+ recipients.forEach((recipient) => {+ const principalId =recipient.principalType === AlertPrincipalType.EMAIL- ? { ...recipient, principalId: recipient.principalId.trim().toLowerCase() }- : recipient- )- .filter((recipient) => {- const key = `${recipient.principalType}:${recipient.principalId}`;- if (seen.has(key)) return false;- seen.add(key);- return true;- });+ ? recipient.principalId.toLowerCase()+ : recipient.principalId;+ const key = `${recipient.principalType}:${principalId}`;+ if (seen.has(key)) duplicates.add(recipient.principalId);+ seen.add(key);+ });+ if (duplicates.size) {+ throw new BadRequestError({ message: `Duplicate recipients: ${[...duplicates].join(", ")}` });+ }};- const $validateEmailRecipients = async (orgId: string, recipients: TChannelRecipientInput[], tx?: Knex) => {- const emails = [- ...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.EMAIL).map((r) => r.principalId))- ];+ const $validateEmailRecipients = async (orgId: string, emails: string[], tx?: Knex) => {if (!emails.length) return;const malformed = emails.filter((email) => !z.string().email().safeParse(email).success);@@ -108,20 +108,30 @@ export const alertChannelServiceFactory = ({}};+ const assertRecipientTypesAllowed = (scope: TAlertRecipientScope, recipients: TChannelRecipientInput[]) => {+ if (!scope.allowEmailAddresses && recipients.some((r) => r.principalType === AlertPrincipalType.EMAIL)) {+ throw new BadRequestError({ message: "This alert type doesn't accept email address recipients" });+ }+ };+// Confirms every recipient principal (user/group) actually belongs to the channel's scope so an// alert can't be made to notify a foreign principal.- const $validateRecipients = async (+ const validateRecipients = async (orgId: string,- projectId: string | null | undefined,+ scope: TAlertRecipientScope,recipients: TChannelRecipientInput[],tx?: Knex) => {- const userIds = [- ...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.USER).map((r) => r.principalId))- ];- const groupIds = [- ...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.GROUP).map((r) => r.principalId))- ];+ const { projectId } = scope;+ assertRecipientTypesAllowed(scope, recipients);+ $assertNoDuplicateRecipients(recipients);++ const idsOfType = (principalType: AlertPrincipalType) =>+ recipients.filter((r) => r.principalType === principalType).map((r) => r.principalId);+ const userIds = idsOfType(AlertPrincipalType.USER);+ const groupIds = idsOfType(AlertPrincipalType.GROUP);++ await $validateEmailRecipients(orgId, idsOfType(AlertPrincipalType.EMAIL), tx);if (userIds.length === 0 && groupIds.length === 0) return;const inScope = await resolvePrincipalsInScope(@@ -178,11 +188,10 @@ export const alertChannelServiceFactory = ({tx: Knex): Promise<TAlertChannels> => {const definition = getChannelDefinition(input.channelType);- const recipients = $normalizeRecipients(input.recipients ?? []);+ const recipients = input.recipients ?? [];$assertRecipientRules(definition, input.channelType, recipients);assertChannelConfigValid(definition, input.channelType, input.config);- await $validateRecipients(input.orgId, input.projectId, recipients, tx);- await $validateEmailRecipients(input.orgId, recipients, tx);+ await validateRecipients(input.orgId, input.recipientScope, recipients, tx);const created = await alertChannelDAL.create({@@ -229,11 +238,10 @@ export const alertChannelServiceFactory = ({finalConfig = merged;}- const recipients = input.recipients === undefined ? undefined : $normalizeRecipients(input.recipients);+ const { recipients } = input;if (recipients !== undefined) {$assertRecipientRules(definition, channel.channelType, recipients);- await $validateRecipients(channel.orgId, channel.projectId, recipients, tx);- await $validateEmailRecipients(channel.orgId, recipients, tx);+ await validateRecipients(channel.orgId, input.recipientScope, recipients, tx);}await alertChannelDAL.updateById(@@ -261,9 +269,6 @@ export const alertChannelServiceFactory = ({}};- const validateEmailRecipients = (orgId: string, recipients: TChannelRecipientInput[]) =>- $validateEmailRecipients(orgId, $normalizeRecipients(recipients));-const deleteChannelInTx = async (channelId: string, tx: Knex): Promise<void> => {await alertChannelDAL.deleteById(channelId, tx);};@@ -306,6 +311,7 @@ export const alertChannelServiceFactory = ({updateChannelInTx,deleteChannelInTx,getDetailsForChannels,- validateEmailRecipients+ validateRecipients,+ assertRecipientTypesAllowed};};diff --git a/backend/src/services/alert/alert-channel-test-service.test.ts b/backend/src/services/alert/alert-channel-test-service.test.tsindex 5c339eb6df..7c2995eea1 100644--- a/backend/src/services/alert/alert-channel-test-service.test.ts+++ b/backend/src/services/alert/alert-channel-test-service.test.ts@@ -33,6 +33,7 @@ const buildProvider = (opts?: {assertPermission?: (input: TAlertPermissionInput) => Promise<void>;resolvedProjectId?: string;blockedChannelTypes?: string[];+ webhookSource?: boolean;}) => {const provider: IResourceAlertProvider = {resourceType: RESOURCE_TYPE,@@ -43,7 +44,7 @@ const buildProvider = (opts?: {conditionSchema: z.object({}).optional()}],- findDueTargets: async () => [],+ findScheduledTargets: async () => [],buildViewUrl: async () => "https://app.infisical.com/x",buildPayload: (alert, targets, viewUrl) =>({@@ -66,7 +67,10 @@ const buildProvider = (opts?: {const blocked = channelTypes.find((channelType) => opts?.blockedChannelTypes?.includes(channelType));if (blocked) throw new Error(`plan does not include ${blocked}`);},- ...(opts?.resolvedProjectId ? { resolveProjectId: async () => opts.resolvedProjectId as string } : {})+ ...(opts?.resolvedProjectId ? { resolveProjectId: async () => opts.resolvedProjectId as string } : {}),+ ...(opts?.webhookSource+ ? { getWebhookSource: ({ alertId, resourceId }) => `/resources/${resourceId}/alerts/${alertId}` }+ : {})};const registry = alertProviderRegistryFactory();@@ -111,14 +115,16 @@ const buildDeps = (overrides?: {findById: async () => overrides?.channel ?? null},alertDAL: {- findByChannelId: async () => overrides?.channelOwners ?? [OWNING_ALERT]+ findByChannelId: async () => overrides?.channelOwners ?? [OWNING_ALERT],+ findActiveById: async (id: string) => (id === OWNING_ALERT.id ? OWNING_ALERT : undefined)},alertRecipientResolver: {resolveMany: async (rowsByChannel: Map<string, unknown[]>) =>new Map([...rowsByChannel.keys()].map((channelId) => [channelId, overrides?.recipients ?? []]))},alertChannelService: {- validateEmailRecipients: async () => {}+ validateRecipients: async () => {},+ assertRecipientTypesAllowed: () => {}},alertProviderRegistry: overrides?.registry ?? buildProvider(),kmsService: {@@ -143,6 +149,41 @@ const stubSend = (channelType: "slack" | "email", impl: (ctx: TAlertChannelSendC};describe("alertChannelTestService", () => {+ test("uses the provider's webhook source on a test send and main's source otherwise", async () => {+ const sent: TAlertChannelSendContext[] = [];+ const restore = stubSend("slack", async (ctx) => {+ sent.push(ctx);+ return { success: true };+ });+ try {+ const withSource = alertChannelTestServiceFactory(+ buildDeps({ registry: buildProvider({ webhookSource: true }) }).deps+ );+ await withSource.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ resourceId: "resource-1",+ alertId: OWNING_ALERT.id,+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }+ });+ expect(sent[0].payload.webhookSource).toBe(`/resources/resource-1/alerts/${OWNING_ALERT.id}`);+ expect(sent[0].payload.alert.resourceId).toBe("resource-1");++ const withoutSource = alertChannelTestServiceFactory(buildDeps().deps);+ await withoutSource.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/y" }+ });+ expect(sent[1].payload.webhookSource).toBeUndefined();+ expect(sent[1].payload.alert.resourceId).toBeUndefined();+ } finally {+ restore();+ }+ });+test("sends a test through an undirected channel with the supplied config", async () => {const sent: TAlertChannelSendContext[] = [];const restore = stubSend("slack", async (ctx) => {@@ -161,7 +202,7 @@ describe("alertChannelTestService", () => {config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }});- expect(result).toEqual({ success: true, deliveredTo: 1, projectId: null });+ expect(result).toEqual({ success: true, deliveredTo: 1, projectId: null, resourceName: null });expect(sent).toHaveLength(1);expect(sent[0].config).toEqual({ webhookUrl: "https://hooks.slack.com/services/T/B/x" });// A test must never page an on-call rotation at the severity a real firing would carry.@@ -317,6 +358,50 @@ describe("alertChannelTestService", () => {expect(checked).toContainEqual({ action: "edit", resourceId: OWNING_ALERT.resourceId });});+ test("checks Edit instead of Create when testing from an existing alert", async () => {+ const actions: string[] = [];+ const restore = stubSend("slack", async () => ({ success: true }));+ const { deps } = buildDeps({+ registry: buildProvider({+ assertPermission: async (input) => {+ actions.push(input.action);+ if (input.action === "create") throw new Error("forbidden");+ }+ })+ });+ const service = alertChannelTestServiceFactory(deps);+ const dto = {+ ...actor,+ resourceType: RESOURCE_TYPE,+ resourceId: OWNING_ALERT.resourceId,+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/new" }+ };++ await expect(service.testChannel({ ...dto, alertId: OWNING_ALERT.id })).resolves.toMatchObject({ success: true });+ await expect(service.testChannel(dto)).rejects.toThrow("forbidden");+ restore();+ expect(actions).toEqual(["edit", "create"]);+ });++ test("rejects an alert id from another resource or that does not exist", async () => {+ const { deps } = buildDeps();+ const service = alertChannelTestServiceFactory(deps);+ const dto = {+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/new" }+ };++ await expect(+ service.testChannel({ ...dto, resourceId: "another-resource", alertId: OWNING_ALERT.id })+ ).rejects.toThrow(`Alert with ID '${OWNING_ALERT.id}' was not found in this scope`);+ await expect(+ service.testChannel({ ...dto, resourceId: OWNING_ALERT.resourceId, alertId: "missing-alert" })+ ).rejects.toThrow("Alert with ID 'missing-alert' was not found in this scope");+ });+test("rejects a saved channel that no alert owns", async () => {const { deps } = buildDeps({channelOwners: [],@@ -373,7 +458,12 @@ describe("alertChannelTestService", () => {config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }};- await expect(service.testChannel(dto)).resolves.toEqual({ success: true, deliveredTo: 1, projectId: null });+ await expect(service.testChannel(dto)).resolves.toEqual({+ success: true,+ deliveredTo: 1,+ projectId: null,+ resourceName: null+ });await expect(service.testChannel(dto)).rejects.toThrow(/Try again in 60s/);} finally {restore();@@ -403,7 +493,7 @@ describe("alertChannelTestService", () => {config: {},recipients: [{ principalType: "user" as never, principalId: "user-1" }]})- ).resolves.toEqual({ success: true, deliveredTo: 1, projectId: null });+ ).resolves.toEqual({ success: true, deliveredTo: 1, projectId: null, resourceName: null });} finally {restoreSlack();restoreEmail();@@ -426,7 +516,7 @@ describe("alertChannelTestService", () => {config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }});- expect(result).toEqual({ success: false, error: "connect ECONNREFUSED", projectId: null });+ expect(result).toEqual({ success: false, error: "connect ECONNREFUSED", projectId: null, resourceName: null });} finally {restore();}diff --git a/backend/src/services/alert/alert-channel-test-service.ts b/backend/src/services/alert/alert-channel-test-service.tsindex f990e1bb1a..130508b043 100644--- a/backend/src/services/alert/alert-channel-test-service.ts+++ b/backend/src/services/alert/alert-channel-test-service.ts@@ -18,13 +18,21 @@ import { TAlertProviderRegistry } from "./alert-provider-registry";import { TAlertRecipientResolver } from "./alert-recipient-resolver";import { TTestAlertChannelDTO, TTestAlertChannelResponse, TTestAlertChannelResult } from "./alert-service-types";import { buildTestAlertPayload } from "./alert-test-payload-fns";-import { AlertPermissionAction, resolveAlertProjectId, toAlertActor } from "./alert-types";+import {+ AlertPermissionAction,+ getAlertResourceName,+ getRecipientScope,+ IResourceAlertProvider,+ resolveAlertProjectId,+ TAlertRecipientScope,+ toAlertActor+} from "./alert-types";export type TAlertChannelTestServiceFactoryDep = {alertChannelDAL: Pick<TAlertChannelDALFactory, "findById">;- alertDAL: Pick<TAlertDALFactory, "findByChannelId">;+ alertDAL: Pick<TAlertDALFactory, "findByChannelId" | "findActiveById">;alertRecipientResolver: Pick<TAlertRecipientResolver, "resolveMany">;- alertChannelService: Pick<TAlertChannelServiceFactory, "validateEmailRecipients">;+ alertChannelService: Pick<TAlertChannelServiceFactory, "validateRecipients" | "assertRecipientTypesAllowed">;alertProviderRegistry: TAlertProviderRegistry;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;smtpService: Pick<TSmtpService, "sendMail">;@@ -122,16 +130,20 @@ export const alertChannelTestServiceFactory = ({const $resolveRecipients = async (dto: TTestAlertChannelDTO,- projectId: string | null+ scope: TAlertRecipientScope): Promise<TAlertRecipient[]> => {const rows = dto.recipients ?? [];if (rows.length === 0) return [];- await alertChannelService.validateEmailRecipients(dto.actorOrgId, rows);+ if (scope.allowEmailAddresses) {+ await alertChannelService.validateRecipients(dto.actorOrgId, scope, rows);+ } else {+ alertChannelService.assertRecipientTypesAllowed(scope, rows);+ }const resolved = await alertRecipientResolver.resolveMany(new Map([[TEST_CHANNEL_ID, rows]]), {orgId: dto.actorOrgId,- projectId+ projectId: scope.projectId});return (resolved.get(TEST_CHANNEL_ID) ?? []).slice(0, MAX_TEST_RECIPIENTS);};@@ -141,10 +153,14 @@ export const alertChannelTestServiceFactory = ({return message.slice(0, MAX_ERROR_LENGTH);};- const $sendTest = async (dto: TTestAlertChannelDTO, projectId: string | null): Promise<TTestAlertChannelResponse> => {+ const $sendTest = async (+ dto: TTestAlertChannelDTO,+ projectId: string | null,+ provider: IResourceAlertProvider+ ): Promise<TTestAlertChannelResponse> => {const definition = getChannelDefinition(dto.channelType);const config = await $resolveConfig(dto, projectId);- const recipients = definition.directed ? await $resolveRecipients(dto, projectId) : [];+ const recipients = definition.directed ? await $resolveRecipients(dto, getRecipientScope(provider, projectId)) : [];if (definition.directed && recipients.length === 0) {return { success: false, error: `No ${dto.channelType} recipients could be resolved in this scope` };}@@ -153,7 +169,13 @@ export const alertChannelTestServiceFactory = ({await $assertCooldown(dto.actorOrgId, dto.actorId, dto.channelType);const deps: TAlertChannelDeps = { smtpService };- const payload = buildTestAlertPayload({ orgId: dto.actorOrgId, projectId });+ const payload = buildTestAlertPayload({+ orgId: dto.actorOrgId,+ projectId,+ ...(provider.getWebhookSource+ ? { alertId: dto.alertId, resourceId: dto.resourceId, getWebhookSource: provider.getWebhookSource }+ : {})+ });try {if (!definition.directed) {@@ -194,8 +216,21 @@ export const alertChannelTestServiceFactory = ({resourceId: dto.resourceId});+ if (dto.alertId) {+ const alert = await alertDAL.findActiveById(dto.alertId);+ if (+ !alert ||+ alert.orgId !== dto.actorOrgId ||+ alert.resourceType !== dto.resourceType ||+ (alert.resourceId ?? null) !== (dto.resourceId ?? null) ||+ (alert.projectId ?? null) !== projectId+ ) {+ throw new NotFoundError({ message: `Alert with ID '${dto.alertId}' was not found in this scope` });+ }+ }+await provider.assertPermission({- action: AlertPermissionAction.Create,+ action: dto.alertId ? AlertPermissionAction.Edit : AlertPermissionAction.Create,orgId: dto.actorOrgId,projectId,resourceId: dto.resourceId,@@ -207,7 +242,12 @@ export const alertChannelTestServiceFactory = ({await provider.assertChannelTypesAllowed?.({ orgId: dto.actorOrgId, channelTypes: [dto.channelType] });}- return { ...(await $sendTest(dto, projectId)), projectId };+ const result = await $sendTest(dto, projectId, provider);+ return {+ ...result,+ projectId,+ resourceName: await getAlertResourceName(provider, dto.actorOrgId, dto.resourceId)+ };};return { testChannel };diff --git a/backend/src/services/alert/alert-channel-types.ts b/backend/src/services/alert/alert-channel-types.tsindex a96df65437..d344c20dac 100644--- a/backend/src/services/alert/alert-channel-types.ts+++ b/backend/src/services/alert/alert-channel-types.ts@@ -26,6 +26,7 @@ export type TAlertItem = {fields?: Array<{ label: string; value: string }>; // extra display key-values (expiry date, days left, reason)summary?: string;severity?: TAlertSeverity;+ resource?: Record<string, unknown>;};export type TAlertPayload = {@@ -35,12 +36,14 @@ export type TAlertPayload = {orgId: string;projectId?: string;resourceType: string; // dot-namespaced, e.g. "pki.certificate"+ resourceId?: string;condition?: string; // display label for the "when", e.g. "30d"viewUrl: string; // deep link into the app, built by the provider};eventKey: string; // dot-namespaced event, e.g. "pki.certificate.expiration"eventLabel: string; // human label, e.g. "Expiration"webhookType: string; // CloudEvents `type` string, e.g. "com.infisical.pki.certificate.expiration"+ webhookSource?: string;resourceKind: string; // display noun, e.g. "Certificate", "Client Secret"resourceOwnerKind: string; // display noun of the entity the alert is configured on, e.g. "Machine Identity"severity: TAlertSeverity;diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.tsindex a6ff49c8b9..b3b51aeac1 100644--- a/backend/src/services/alert/alert-engine.test.ts+++ b/backend/src/services/alert/alert-engine.test.ts@@ -61,21 +61,21 @@ const makeAlert = () => ({const makeProvider = (targets: TTarget[],- onFindDueTargets?: () => void,- onFindTargetsByIds?: (payload: Record<string, unknown>) => void+ onFindScheduledTargets?: () => void,+ onFindEventTargets?: (payload: Record<string, unknown>) => void): IResourceAlertProvider<TTarget> => ({resourceType: RESOURCE_TYPE,events: [{ key: "test.resource.expiration", triggerType: AlertTriggerType.Scheduled, conditionSchema: z.any() },{ key: "test.resource.opened", triggerType: AlertTriggerType.Event, conditionSchema: z.any() }],- findDueTargets: async () => {- onFindDueTargets?.();+ findScheduledTargets: async () => {+ onFindScheduledTargets?.();return targets;},// Like a real provider, a target deleted between emit and delivery just drops out.- findTargetsByIds: async ({ targetIds, payload }) => {- onFindTargetsByIds?.(payload);+ findEventTargets: async ({ targetIds, payload }) => {+ onFindEventTargets?.(payload);return targets.filter((target) => targetIds.includes(target.id));},assertPermission: async () => undefined,@@ -125,13 +125,13 @@ const buildEngine = (opts: {failHistoryWriteTimes?: number;}) => {const registry = alertProviderRegistryFactory();- let findDueTargetsCalls = 0;+ let findScheduledTargetsCalls = 0;const eventPayloads: Record<string, unknown>[] = [];registry.register(makeProvider(opts.targets,() => {- findDueTargetsCalls += 1;+ findScheduledTargetsCalls += 1;},(payload) => eventPayloads.push(payload)) as IResourceAlertProvider@@ -223,7 +223,7 @@ const buildEngine = (opts: {eventPayloads,getHistoryAttempts: () => historyAttempts,getPeakConcurrentSends: () => peakConcurrentSends,- getFindDueTargetsCalls: () => findDueTargetsCalls+ getFindScheduledTargetsCalls: () => findScheduledTargetsCalls};};@@ -501,7 +501,7 @@ describe("alert engine", () => {});test("writes no history and skips the resource scan when there are no enabled channels", async () => {- const { engine, historyWrites, getFindDueTargetsCalls } = buildEngine({+ const { engine, historyWrites, getFindScheduledTargetsCalls } = buildEngine({targets: [{ id: "t1" }],channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: false }]});@@ -511,7 +511,7 @@ describe("alert engine", () => {expect(outcome).toBe(AlertDispatchOutcome.NoChannels);expect(historyWrites).toHaveLength(0);// The scan is the expensive part of a run; a channel-less alert must not pay for it daily.- expect(getFindDueTargetsCalls()).toBe(0);+ expect(getFindScheduledTargetsCalls()).toBe(0);});test("reports no due targets when nothing matches the condition", async () => {diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.tsindex bbe75752c8..a20dc61ebc 100644--- a/backend/src/services/alert/alert-engine.ts+++ b/backend/src/services/alert/alert-engine.ts@@ -13,7 +13,13 @@ import { AlertChannelType, TAlertChannelDeps, TAlertRecipient, TChannelTargetResimport { getDedupCutoff, TAlertHistoryDALFactory } from "./alert-history-dal";import { TAlertProviderRegistry } from "./alert-provider-registry";import { TAlertRecipientResolver } from "./alert-recipient-resolver";-import { AlertRunStatus, DEFAULT_DEDUP_WINDOW_HOURS, IResourceAlertProvider, TAlertContext } from "./alert-types";+import {+ AlertRunStatus,+ DEFAULT_DEDUP_WINDOW_HOURS,+ getRecipientScope,+ IResourceAlertProvider,+ TAlertContext+} from "./alert-types";import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";const ALERT_DELIVERY_CONCURRENCY = 10;@@ -102,7 +108,7 @@ export const alertEngineFactory = ({});recipientsByChannel = await alertRecipientResolver.resolveMany(rowsByChannel, {orgId: alert.orgId,- projectId: alert.projectId+ projectId: getRecipientScope(provider, alert.projectId).projectId});}@@ -245,7 +251,7 @@ export const alertEngineFactory = ({}).filter((work) => work.due.length > 0);- const $getProvider = (alert: TAlerts, discovery: "findDueTargets" | "findTargetsByIds") => {+ const $getProvider = (alert: TAlerts, discovery: "findScheduledTargets" | "findEventTargets") => {const provider = alertProviderRegistry.get(alert.resourceType);if (!provider) {logger.warn(`No alert provider registered for resource type '${alert.resourceType}' [alertId=${alert.id}]`);@@ -261,14 +267,14 @@ export const alertEngineFactory = ({};const runAlert = async (alert: TAlerts, opts?: { asOf?: Date }): Promise<AlertDispatchOutcome> => {- const provider = $getProvider(alert, "findDueTargets");- if (!provider?.findDueTargets) return AlertDispatchOutcome.NoProvider;+ const provider = $getProvider(alert, "findScheduledTargets");+ if (!provider?.findScheduledTargets) return AlertDispatchOutcome.NoProvider;const channels = await alertChannelDAL.findByAlertId(alert.id, { enabled: true });if (channels.length === 0) return AlertDispatchOutcome.NoChannels;const window = provider.dedupWindowHours?.(alert.condition) ?? DEFAULT_DEDUP_WINDOW_HOURS;- const dueTargets = await provider.findDueTargets({+ const dueTargets = await provider.findScheduledTargets({orgId: alert.orgId,projectId: alert.projectId,resourceId: alert.resourceId,@@ -302,8 +308,8 @@ export const alertEngineFactory = ({alert: TAlerts,input: { eventId: string; eventType: string; targetIds: string[]; payload: Record<string, unknown> }): Promise<AlertDispatchOutcome> => {- const provider = $getProvider(alert, "findTargetsByIds");- if (!provider?.findTargetsByIds) return AlertDispatchOutcome.NoProvider;+ const provider = $getProvider(alert, "findEventTargets");+ if (!provider?.findEventTargets) return AlertDispatchOutcome.NoProvider;const [enabledChannels, alreadyDelivered] = await Promise.all([alertChannelDAL.findByAlertId(alert.id, { enabled: true, readFromPrimary: true }),@@ -313,7 +319,7 @@ export const alertEngineFactory = ({const channels = enabledChannels.filter((channel) => !skip.has(channel.id));if (channels.length === 0) return AlertDispatchOutcome.NoChannels;- const resolved = await provider.findTargetsByIds({+ const resolved = await provider.findEventTargets({orgId: alert.orgId,projectId: alert.projectId,resourceId: alert.resourceId,diff --git a/backend/src/services/alert/alert-provider-registry.test.ts b/backend/src/services/alert/alert-provider-registry.test.tsindex 55f50534c1..130ebd8465 100644--- a/backend/src/services/alert/alert-provider-registry.test.ts+++ b/backend/src/services/alert/alert-provider-registry.test.ts@@ -24,7 +24,7 @@ describe("alert provider registry", () => {});// Both guards fail boot in routes/index.ts rather than letting a dispatch silently no-op in prod.- test("rejects a scheduled event with no findDueTargets", () => {+ test("rejects a scheduled event with no findScheduledTargets", () => {const registry = alertProviderRegistryFactory();expect(() =>@@ -33,10 +33,10 @@ describe("alert provider registry", () => {events: [{ key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled, conditionSchema: z.any() }]}))- ).toThrow("does not implement findDueTargets");+ ).toThrow("does not implement findScheduledTargets");});- test("rejects an event-triggered event with no findTargetsByIds", () => {+ test("rejects an event-triggered event with no findEventTargets", () => {const registry = alertProviderRegistryFactory();expect(() =>@@ -45,7 +45,7 @@ describe("alert provider registry", () => {events: [{ key: "test.resource.opened", triggerType: AlertTriggerType.Event, conditionSchema: z.any() }]}))- ).toThrow("does not implement findTargetsByIds");+ ).toThrow("does not implement findEventTargets");});test("accepts a provider that implements the method each of its events needs", () => {@@ -58,8 +58,8 @@ describe("alert provider registry", () => {{ key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled, conditionSchema: z.any() },{ key: "test.resource.opened", triggerType: AlertTriggerType.Event, conditionSchema: z.any() }],- findDueTargets: async () => [],- findTargetsByIds: async () => []+ findScheduledTargets: async () => [],+ findEventTargets: async () => []}))).not.toThrow();@@ -73,8 +73,8 @@ describe("alert provider registry", () => {{ key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled, conditionSchema: z.any() },{ key: "test.resource.opened", triggerType: AlertTriggerType.Event, conditionSchema: z.any() }],- findDueTargets: async () => [],- findTargetsByIds: async () => []+ findScheduledTargets: async () => [],+ findEventTargets: async () => []}));diff --git a/backend/src/services/alert/alert-provider-registry.ts b/backend/src/services/alert/alert-provider-registry.tsindex 1608dd0b1a..909e63b527 100644--- a/backend/src/services/alert/alert-provider-registry.ts+++ b/backend/src/services/alert/alert-provider-registry.ts@@ -12,14 +12,14 @@ export const alertProviderRegistryFactory = () => {}for (const event of provider.events) {- if (event.triggerType === AlertTriggerType.Scheduled && !provider.findDueTargets) {+ if (event.triggerType === AlertTriggerType.Scheduled && !provider.findScheduledTargets) {throw new Error(- `Alert provider '${provider.resourceType}' declares scheduled event '${event.key}' but does not implement findDueTargets`+ `Alert provider '${provider.resourceType}' declares scheduled event '${event.key}' but does not implement findScheduledTargets`);}- if (event.triggerType === AlertTriggerType.Event && !provider.findTargetsByIds) {+ if (event.triggerType === AlertTriggerType.Event && !provider.findEventTargets) {throw new Error(- `Alert provider '${provider.resourceType}' declares event-triggered event '${event.key}' but does not implement findTargetsByIds`+ `Alert provider '${provider.resourceType}' declares event-triggered event '${event.key}' but does not implement findEventTargets`);}}diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.tsindex 1b5b76cac4..356bad1900 100644--- a/backend/src/services/alert/alert-service-types.ts+++ b/backend/src/services/alert/alert-service-types.ts@@ -42,6 +42,7 @@ export type TTestAlertChannelDTO = TGenericPermission & {resourceType: string;resourceId?: string | null;projectId?: string | null;+ alertId?: string;channelId?: string;channelType: AlertChannelType;config?: Record<string, unknown>;@@ -54,7 +55,10 @@ export type TTestAlertChannelResponse = {error?: string;};-export type TTestAlertChannelResult = TTestAlertChannelResponse & { projectId: string | null };+export type TTestAlertChannelResult = TTestAlertChannelResponse & {+ projectId: string | null;+ resourceName?: string | null;+};export type TAlertResponse = {id: string;@@ -68,9 +72,9 @@ export type TAlertResponse = {enabled: boolean;orgId: string;projectId: string | null;- resourceName: string | null;+ resourceName?: string | null;channels: TAlertChannelEmbedded[];- lastRun: TAlertLastRun | null;+ lastRun?: TAlertLastRun | null;createdAt: Date;updatedAt: Date;};diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.tsindex 864dfa06a1..6d923e4c2c 100644--- a/backend/src/services/alert/alert-service.test.ts+++ b/backend/src/services/alert/alert-service.test.ts@@ -1,12 +1,16 @@import { z } from "zod";-import { ForbiddenRequestError } from "@app/lib/errors";-import { TAlertChannelInput } from "./alert-channel-service-types";import { AlertChannelType, TAlertPayload } from "./alert-channel-types";import { alertProviderRegistryFactory } from "./alert-provider-registry";import { alertServiceFactory, TAlertServiceFactoryDep } from "./alert-service";-import { AlertPrincipalType, AlertTriggerType, IResourceAlertProvider, TAlertPermissionInput } from "./alert-types";+import {+ AlertAuditAction,+ AlertPrincipalType,+ AlertTriggerType,+ IResourceAlertProvider,+ TAlertPermissionInput+} from "./alert-types";const RESOURCE_TYPE = "test.resource";@@ -27,12 +31,14 @@ const buildService = (opts?: {resourceScopeThrows?: boolean;duplicateExists?: boolean;resolvedProjectId?: string;+ atOrgScope?: boolean;// Runs right after a find() has taken its snapshot, to stand in for a concurrent transaction// committing between two statements of ours.afterFindAlerts?: (alerts: Map<string, Record<string, unknown>>) => void;}) => {const permissionCalls: TAlertPermissionInput[] = [];const gatedChannelTypeCalls: string[][] = [];+ const recipientProjectIds: (string | null)[] = [];const provider: IResourceAlertProvider = {resourceType: RESOURCE_TYPE,events: [@@ -47,8 +53,9 @@ const buildService = (opts?: {conditionSchema: z.object({}).strict().nullish()}],- findDueTargets: async () => [],- findTargetsByIds: async () => [],+ findScheduledTargets: async () => [],+ findEventTargets: async () => [],+ ...(opts?.atOrgScope ? { recipientPolicy: { atOrgScope: true } } : {}),buildViewUrl: async () => "https://app.infisical.com/x",buildPayload: () => ({}) as TAlertPayload,targetId: () => "t",@@ -165,7 +172,9 @@ const buildService = (opts?: {recipients?: { principalType: string; principalId: string }[];orgId: string;projectId?: string | null;+ recipientScope: { projectId: string | null };}) => {+ recipientProjectIds.push(input.recipientScope.projectId);channelSeq += 1;const row: TChannelRow = {id: `ch-${channelSeq}`,@@ -219,7 +228,16 @@ const buildService = (opts?: {alertProviderRegistry: registry} as unknown as TAlertServiceFactoryDep);- return { service, permissionCalls, gatedChannelTypeCalls, alerts, memberships, channels, findFilters };+ return {+ service,+ permissionCalls,+ gatedChannelTypeCalls,+ recipientProjectIds,+ alerts,+ memberships,+ channels,+ findFilters+ };};const actor = {@@ -266,6 +284,65 @@ describe("alert service", () => {expect(permissionCalls[0].action).toBe("create");});+ test("validates channel recipients at org scope when the provider asks for it", async () => {+ const projectScoped = buildService({ resolvedProjectId: "proj-resolved" });+ await projectScoped.service.createAlert({ ...validCreate, projectId: undefined });+ expect(projectScoped.recipientProjectIds).toEqual(["proj-resolved", "proj-resolved"]);++ const orgScoped = buildService({ resolvedProjectId: "proj-resolved", atOrgScope: true });+ await orgScoped.service.createAlert({ ...validCreate, projectId: undefined });+ expect(orgScoped.recipientProjectIds).toEqual([null, null]);+ });++ test("falls back to the generic alert audit events when the provider defines none", () => {+ const { service } = buildService();+ const alert = {+ id: "alert-1",+ name: "expiry",+ resourceType: RESOURCE_TYPE,+ resourceId: "resource-1",+ resourceName: "Resource One",+ eventType: "test.resource.expiration"+ };++ expect(service.getAuditEvent({ action: AlertAuditAction.Create, alert })).toEqual({+ type: "create-alert",+ metadata: {+ alertId: "alert-1",+ name: "expiry",+ resourceType: RESOURCE_TYPE,+ resourceId: "resource-1",+ eventType: "test.resource.expiration"+ }+ });+ expect(service.getAuditEvent({ action: AlertAuditAction.Delete, alert })).toEqual({+ type: "delete-alert",+ metadata: {+ alertId: "alert-1",+ name: "expiry",+ resourceType: RESOURCE_TYPE,+ eventType: "test.resource.expiration"+ }+ });+ expect(+ service.getAuditEvent({+ action: AlertAuditAction.TestChannel,+ test: { resourceType: RESOURCE_TYPE, resourceId: "resource-1", channelType: "slack", success: true }+ })+ ).toEqual({+ type: "test-alert-channel",+ metadata: {+ channelId: undefined,+ channelType: "slack",+ resourceType: RESOURCE_TYPE,+ resourceId: "resource-1",+ success: true,+ deliveredTo: undefined,+ error: undefined+ }+ });+ });+test("rejects an unknown resource type", async () => {const { service } = buildService();await expect(service.createAlert({ ...validCreate, resourceType: "nope.unknown" })).rejects.toThrow();@@ -411,33 +488,6 @@ describe("alert service", () => {expect(findFilters[0]).toMatchObject({ projectId: "proj-x" });});- test("a list without a resource hides alerts on resources the actor cannot read", async () => {- const { service, alerts } = buildService({- assertPermission: async (input) => {- if (input.resourceId === "hidden-resource") throw new ForbiddenRequestError({ message: "forbidden" });- }- });- alerts.set("unbound", { id: "unbound", name: "unbound", projectId: "proj-x", ...listBase });- alerts.set("visible", {- id: "visible",- name: "visible",- projectId: "proj-x",- ...listBase,- resourceId: "visible-resource"- });- alerts.set("hidden", {- id: "hidden",- name: "hidden",- projectId: "proj-x",- ...listBase,- resourceId: "hidden-resource"- });-- const result = await service.listAlerts({ resourceType: RESOURCE_TYPE, projectId: "proj-x", ...actor });-- expect(result.map((a) => a.id).sort()).toEqual(["unbound", "visible"]);- });-test("update reconciles channels: keeps the referenced ones, deletes the rest, adds new", async () => {const { service, memberships } = buildService();const created = await service.createAlert(validCreate);diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.tsindex 7a1bacfd91..2d40bdba6b 100644--- a/backend/src/services/alert/alert-service.ts+++ b/backend/src/services/alert/alert-service.ts@@ -1,9 +1,9 @@-import { ForbiddenError } from "@casl/ability";import { Knex } from "knex";import { z } from "zod";import { TAlertChannels, TAlerts } from "@app/db/schemas";-import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { Event as TAuditEvent } from "@app/ee/services/audit-log/audit-log-types";+import { BadRequestError, NotFoundError } from "@app/lib/errors";import { TGenericPermission } from "@app/lib/types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -25,12 +25,18 @@ import {TUpdateAlertDTO} from "./alert-service-types";import {+ AlertAuditAction,AlertPermissionAction,AlertRunStatus,AlertTelemetryAction,+ buildGenericAlertAuditEvent,+ getAlertResourceName,+ getRecipientScope,IResourceAlertProvider,resolveAlertProjectId,+ TAlertAuditInput,TAlertEventDefinition,+ TAlertRecipientScope,toAlertActor} from "./alert-types";@@ -80,53 +86,6 @@ export const alertServiceFactory = ({actor: toAlertActor(dto)});- const $isAllowed = async (- provider: IResourceAlertProvider,- action: AlertPermissionAction,- scope: { orgId: string; projectId?: string | null; resourceId?: string | null },- dto: TGenericPermission- ) => {- try {- await $assertAlertPermission(provider, action, scope, dto);- return true;- } catch (error) {- if (error instanceof ForbiddenError || error instanceof ForbiddenRequestError) return false;- throw error;- }- };-- const $findAllowedResourceIds = async (- provider: IResourceAlertProvider,- action: AlertPermissionAction,- resourceIds: (string | null)[],- projectId: string | null,- dto: TListAlertsDTO- ) => {- const allowed = await Promise.all(- resourceIds.map((resourceId) =>- $isAllowed(provider, action, { orgId: dto.actorOrgId, projectId, resourceId }, dto)- )- );- return new Set(resourceIds.filter((_, index) => allowed[index]));- };-- const $filterReadableAlerts = async (- provider: IResourceAlertProvider,- alerts: TAlerts[],- projectId: string | null,- dto: TListAlertsDTO- ) => {- const resourceIds = [...new Set(alerts.map((alert) => alert.resourceId).filter((id): id is string => Boolean(id)))];- const readableResourceIds = await $findAllowedResourceIds(- provider,- AlertPermissionAction.Read,- resourceIds,- projectId,- dto- );- return alerts.filter((alert) => !alert.resourceId || readableResourceIds.has(alert.resourceId));- };-const $getEvent = (provider: IResourceAlertProvider, eventType: string): TAlertEventDefinition => {const event = provider.events.find((candidate) => candidate.key === eventType);if (!event) {@@ -156,10 +115,14 @@ export const alertServiceFactory = ({return provider.getResourceNames({ orgId, resourceIds: ids });};- const $getResourceName = async (provider: IResourceAlertProvider, alert: Pick<TAlerts, "orgId" | "resourceId">) =>- (await $getResourceNames(provider, alert.orgId, [alert.resourceId])).get(alert.resourceId ?? "") ?? null;+ const $getResourceName = (provider: IResourceAlertProvider, alert: Pick<TAlerts, "orgId" | "resourceId">) =>+ getAlertResourceName(provider, alert.orgId, alert.resourceId);- const $getLastRuns = async (alertIds: string[]): Promise<Map<string, TAlertLastRun>> => {+ const $getLastRuns = async (+ provider: IResourceAlertProvider,+ alertIds: string[]+ ): Promise<Map<string, TAlertLastRun>> => {+ if (!provider.includeLastRun) return new Map();const runs = await alertHistoryDAL.findLatestByAlertIds(alertIds);return new Map(runs@@ -169,9 +132,10 @@ export const alertServiceFactory = ({};const $assembleResponse = (+ provider: IResourceAlertProvider,alert: TAlerts,channels: TAlertChannelEmbedded[],- extras: { resourceName: string | null; lastRun: TAlertLastRun | null }+ extras: { resourceName: string | null; lastRun?: TAlertLastRun }): TAlertResponse => ({id: alert.id,name: alert.name,@@ -184,9 +148,9 @@ export const alertServiceFactory = ({enabled: alert.enabled,orgId: alert.orgId,projectId: alert.projectId ?? null,- resourceName: extras.resourceName,+ ...(provider.getResourceNames ? { resourceName: extras.resourceName } : {}),channels,- lastRun: extras.lastRun,+ ...(provider.includeLastRun ? { lastRun: extras.lastRun ?? null } : {}),createdAt: alert.createdAt,updatedAt: alert.updatedAt});@@ -279,6 +243,7 @@ export const alertServiceFactory = ({recipients: channelInput.recipients,orgId: dto.actorOrgId,projectId: projectId ?? null,+ recipientScope: getRecipientScope(provider, projectId),createdByActorId: dto.actorId,createdByActorType: dto.actor},@@ -294,9 +259,8 @@ export const alertServiceFactory = ({return { created: createdAlert, channels: details };});- return $assembleResponse(created, channels, {- resourceName: await $getResourceName(provider, created),- lastRun: null+ return $assembleResponse(provider, created, channels, {+ resourceName: await $getResourceName(provider, created)});};@@ -315,10 +279,10 @@ export const alertServiceFactory = ({const channels = await alertChannelDAL.findByAlertId(alert.id);const cipher = await getAlertChannelCipher(kmsService, { orgId: alert.orgId, projectId: alert.projectId });const details = await alertChannelService.getDetailsForChannels(channels, cipher);- const lastRuns = await $getLastRuns([alert.id]);- return $assembleResponse(alert, details, {+ const lastRuns = await $getLastRuns(provider, [alert.id]);+ return $assembleResponse(provider, alert, details, {resourceName: await $getResourceName(provider, alert),- lastRun: lastRuns.get(alert.id) ?? null+ lastRun: lastRuns.get(alert.id)});};@@ -336,22 +300,23 @@ export const alertServiceFactory = ({dto);- const scopedAlerts = await alertDAL.findActiveByScope({+ const alerts = await alertDAL.findActiveByScope({orgId: dto.actorOrgId,resourceType: dto.resourceType,...(dto.resourceId !== undefined ? { resourceId: dto.resourceId } : {}),projectId,...(dto.enabled !== undefined ? { enabled: dto.enabled } : {})});- const alerts =- dto.resourceId !== undefined ? scopedAlerts : await $filterReadableAlerts(provider, scopedAlerts, projectId, dto);if (alerts.length === 0) return [];const channels = await alertChannelDAL.findByAlertIds(alerts.map((alert) => alert.id));const cipher = await getAlertChannelCipher(kmsService, { orgId: dto.actorOrgId, projectId });const details = await alertChannelService.getDetailsForChannels(channels, cipher);- const lastRuns = await $getLastRuns(alerts.map((alert) => alert.id));+ const lastRuns = await $getLastRuns(+ provider,+ alerts.map((alert) => alert.id)+ );const resourceNames = await $getResourceNames(provider,dto.actorOrgId,@@ -368,19 +333,21 @@ export const alertServiceFactory = ({return alerts.map((alert) =>$assembleResponse(+ provider,alert,(channelIdsByAlert.get(alert.id) ?? []).map((id) => detailById.get(id)).filter((detail): detail is TAlertChannelEmbedded => Boolean(detail)),{resourceName: (alert.resourceId && resourceNames.get(alert.resourceId)) || null,- lastRun: lastRuns.get(alert.id) ?? null+ lastRun: lastRuns.get(alert.id)}));};const $reconcileChannels = async (+ recipientScope: TAlertRecipientScope,alert: TAlerts,incoming: TAlertChannelInput[],cipher: Awaited<ReturnType<typeof getAlertChannelCipher>>,@@ -413,7 +380,8 @@ export const alertServiceFactory = ({name: channelInput.name,config: channelInput.config,enabled: channelInput.enabled,- recipients: channelInput.recipients+ recipients: channelInput.recipients,+ recipientScope},existingChannel,cipher,@@ -430,6 +398,7 @@ export const alertServiceFactory = ({recipients: channelInput.recipients,orgId: alert.orgId,projectId: alert.projectId,+ recipientScope,createdByActorId: alert.createdByActorId,createdByActorType: alert.createdByActorType},@@ -487,7 +456,7 @@ export const alertServiceFactory = ({const updatedAlert = Object.keys(patch).length > 0 ? await alertDAL.updateById(alert.id, patch, tx) : alert;if (dto.channels !== undefined) {- await $reconcileChannels(alert, dto.channels, cipher, tx);+ await $reconcileChannels(getRecipientScope(provider, alert.projectId), alert, dto.channels, cipher, tx);}const attachedChannels = await alertChannelDAL.findByAlertId(alert.id, {}, tx);@@ -495,10 +464,10 @@ export const alertServiceFactory = ({return { updated: updatedAlert, channels: details };});- const lastRuns = await $getLastRuns([alert.id]);- return $assembleResponse(updated, channels, {+ const lastRuns = await $getLastRuns(provider, [alert.id]);+ return $assembleResponse(provider, updated, channels, {resourceName: await $getResourceName(provider, alert),- lastRun: lastRuns.get(alert.id) ?? null+ lastRun: lastRuns.get(alert.id)});};@@ -596,8 +565,15 @@ export const alertServiceFactory = ({eventType: alert.eventType});+ const getAuditEvent = (input: TAlertAuditInput): TAuditEvent => {+ const resourceType =+ input.action === AlertAuditAction.TestChannel ? input.test.resourceType : input.alert.resourceType;+ return alertProviderRegistry.get(resourceType)?.getAuditEvent?.(input) ?? buildGenericAlertAuditEvent(input);+ };+return {getTelemetryEvent,+ getAuditEvent,createAlert,getAlertById,listAlerts,diff --git a/backend/src/services/alert/alert-test-payload-fns.ts b/backend/src/services/alert/alert-test-payload-fns.tsindex 63b7e132a4..3530e9b43c 100644--- a/backend/src/services/alert/alert-test-payload-fns.ts+++ b/backend/src/services/alert/alert-test-payload-fns.ts@@ -16,22 +16,31 @@ const TEST_ITEMS = [export const buildTestAlertPayload = ({orgId,- projectId+ projectId,+ alertId = crypto.randomUUID(),+ resourceId,+ getWebhookSource}: {orgId: string;projectId?: string | null;+ alertId?: string;+ resourceId?: string | null;+ getWebhookSource?: (input: { alertId: string; resourceId?: string | null }) => string | undefined;}): TAlertPayload => {const appCfg = getConfig();+ const webhookSource = getWebhookSource?.({ alertId, resourceId });return {alert: {- id: crypto.randomUUID(),+ id: alertId,name: TEST_ALERT_NAME,orgId,...(projectId ? { projectId } : {}),resourceType: "alert.channel.test",+ ...(webhookSource && resourceId ? { resourceId } : {}),viewUrl: appCfg.SITE_URL ?? ""},+ ...(webhookSource ? { webhookSource } : {}),eventKey: "alert.channel.test",eventLabel: "Test",webhookType: "com.infisical.alert.channel.test",diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.tsindex e4c31a3136..a3ea31facb 100644--- a/backend/src/services/alert/alert-types.ts+++ b/backend/src/services/alert/alert-types.ts@@ -1,5 +1,6 @@import { z } from "zod";+import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";import { TGenericPermission } from "@app/lib/types";import { TPostHogEvent } from "@app/services/telemetry/telemetry-types";@@ -58,6 +59,33 @@ export const resolveAlertProjectId = async (return provider.resolveProjectId({ orgId, resourceId });};+type TAlertRecipientPolicy = {+ atOrgScope?: boolean;+ allowEmailAddresses?: boolean;+};++export type TAlertRecipientScope = {+ projectId: string | null;+ allowEmailAddresses: boolean;+};++export const getRecipientScope = (+ provider: Pick<IResourceAlertProvider, "recipientPolicy">,+ projectId?: string | null+): TAlertRecipientScope => ({+ projectId: provider.recipientPolicy?.atOrgScope ? null : (projectId ?? null),+ allowEmailAddresses: Boolean(provider.recipientPolicy?.allowEmailAddresses)+});++export const getAlertResourceName = async (+ provider: Pick<IResourceAlertProvider, "getResourceNames">,+ orgId: string,+ resourceId?: string | null+): Promise<string | null> => {+ if (!resourceId || !provider.getResourceNames) return null;+ return (await provider.getResourceNames({ orgId, resourceIds: [resourceId] })).get(resourceId) ?? null;+};+export const DEFAULT_DEDUP_WINDOW_HOURS = 24;// Providers scan this many days ahead of `alertBefore` so alerts fire at LEAST `alertBefore` before@@ -84,7 +112,7 @@ export type TAlertContext = {condition: unknown;};-export type TFindTargetsByIdsInput = {+export type TFindEventTargetsInput = {orgId: string;projectId?: string | null;resourceId?: string | null;@@ -94,7 +122,7 @@ export type TFindTargetsByIdsInput = {payload: Record<string, unknown>;};-export type TFindDueTargetsInput = {+export type TFindScheduledTargetsInput = {orgId: string;projectId?: string | null;resourceId?: string | null;@@ -106,10 +134,72 @@ export type TFindDueTargetsInput = {// Lets a provider factory declare which discovery method it guarantees.export type IScheduledAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTarget> &- Required<Pick<IResourceAlertProvider<TTarget>, "findDueTargets">>;+ Required<Pick<IResourceAlertProvider<TTarget>, "findScheduledTargets">>;export type IEventAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTarget> &- Required<Pick<IResourceAlertProvider<TTarget>, "findTargetsByIds">>;+ Required<Pick<IResourceAlertProvider<TTarget>, "findEventTargets">>;++export enum AlertAuditAction {+ Create = "create",+ Update = "update",+ Delete = "delete",+ TestChannel = "test-channel"+}++type TAlertAuditAlert = {+ id: string;+ name: string;+ resourceType: string;+ resourceId: string | null;+ resourceName?: string | null;+ eventType: string;+};++type TAlertChannelTestAudit = {+ resourceType: string;+ resourceId?: string | null;+ resourceName?: string | null;+ alertId?: string;+ channelId?: string;+ channelType: string;+ success: boolean;+ deliveredTo?: number;+ error?: string;+};++export type TAlertAuditInput =+ | { action: AlertAuditAction.Create | AlertAuditAction.Update | AlertAuditAction.Delete; alert: TAlertAuditAlert }+ | { action: AlertAuditAction.TestChannel; test: TAlertChannelTestAudit };++export const buildGenericAlertAuditEvent = (input: TAlertAuditInput): TAuditEvent => {+ if (input.action === AlertAuditAction.TestChannel) {+ const { test } = input;+ return {+ type: EventType.TEST_ALERT_CHANNEL,+ metadata: {+ channelId: test.channelId,+ channelType: test.channelType,+ resourceType: test.resourceType,+ resourceId: test.resourceId,+ success: test.success,+ deliveredTo: test.deliveredTo,+ error: test.error+ }+ };+ }+ const { alert } = input;+ const metadata = {+ alertId: alert.id,+ name: alert.name,+ resourceType: alert.resourceType,+ eventType: alert.eventType+ };+ if (input.action === AlertAuditAction.Create) {+ return { type: EventType.CREATE_ALERT, metadata: { ...metadata, resourceId: alert.resourceId } };+ }+ if (input.action === AlertAuditAction.Update) return { type: EventType.UPDATE_ALERT, metadata };+ return { type: EventType.DELETE_ALERT, metadata };+};export enum AlertTelemetryAction {Create = "create",@@ -143,13 +233,13 @@ export interface IResourceAlertProvider<TTarget = unknown> {// keeps the head of this list and defers the tail, so urgency ordering ensures the targets closest// to expiry are never the ones dropped.// Required for any Scheduled event; the registry enforces that at boot.- findDueTargets?(input: TFindDueTargetsInput): Promise<TTarget[]>;+ findScheduledTargets?(input: TFindScheduledTargetsInput): Promise<TTarget[]>;// Loads the targets an event named. A missing row was deleted between emit and dispatch, so drop it,// don't throw. Must read the primary: the target usually commits in the same tx as the event, and an// empty result is terminal.// Required for any Event-triggered event; the registry enforces that at boot.- findTargetsByIds?(input: TFindTargetsByIdsInput): Promise<TTarget[]>;+ findEventTargets?(input: TFindEventTargetsInput): Promise<TTarget[]>;// Deep link to the alert's resource, honouring its scope (org- vs project-scoped). Resolved once// per run by the engine and passed into buildPayload, so it may perform async lookups.@@ -172,6 +262,14 @@ export interface IResourceAlertProvider<TTarget = unknown> {assertChannelTypesAllowed?(input: { orgId: string; channelTypes: string[] }): Promise<void>;+ recipientPolicy?: TAlertRecipientPolicy;++ includeLastRun?: boolean;++ getWebhookSource?: (input: { alertId: string; resourceId?: string | null }) => string | undefined;++ getAuditEvent?(input: TAlertAuditInput): TAuditEvent;+getResourceNames?(input: { orgId: string; resourceIds: string[] }): Promise<Map<string, string>>;resolveProjectId?(input: { orgId: string; resourceId: string }): Promise<string>;diff --git a/backend/src/services/alert/channels/alert-channel-webhook-fns.ts b/backend/src/services/alert/channels/alert-channel-webhook-fns.tsindex facb39e48a..d922ddebc4 100644--- a/backend/src/services/alert/channels/alert-channel-webhook-fns.ts+++ b/backend/src/services/alert/channels/alert-channel-webhook-fns.ts@@ -19,7 +19,7 @@ type TAlertWebhookPayload = {datacontenttype: "application/json";subject: string;data: {- alert: { id: string; name: string; resourceType: string; condition?: string };+ alert: { id: string; name: string; resourceType: string; resourceId?: string; condition?: string };items: TAlertPayload["items"];metadata: { totalItems: number; viewUrl: string };};@@ -28,9 +28,11 @@ type TAlertWebhookPayload = {export const buildWebhookPayload = (payload: TAlertPayload): TAlertWebhookPayload => ({specversion: "1.0",type: payload.webhookType,- source: payload.alert.projectId- ? `/projects/${payload.alert.projectId}/alerts/${payload.alert.id}`- : `/alerts/${payload.alert.id}`,+ source:+ payload.webhookSource ??+ (payload.alert.projectId+ ? `/projects/${payload.alert.projectId}/alerts/${payload.alert.id}`+ : `/alerts/${payload.alert.id}`),id: crypto.randomUUID(),time: new Date().toISOString(),datacontenttype: "application/json",@@ -40,6 +42,7 @@ export const buildWebhookPayload = (payload: TAlertPayload): TAlertWebhookPayloaid: payload.alert.id,name: payload.alert.name,resourceType: payload.alert.resourceType,+ ...(payload.alert.resourceId ? { resourceId: payload.alert.resourceId } : {}),...(payload.alert.condition ? { condition: payload.alert.condition } : {})},items: payload.items,diff --git a/backend/src/services/alert/channels/alert-channels.test.ts b/backend/src/services/alert/channels/alert-channels.test.tsindex bceb08b7ab..96ce0353bc 100644--- a/backend/src/services/alert/channels/alert-channels.test.ts+++ b/backend/src/services/alert/channels/alert-channels.test.ts@@ -98,6 +98,25 @@ describe("buildWebhookPayload", () => {expect(wh.data.alert.condition).toBe("30d");});+ test("carries each item's typed resource for receivers that act on it", () => {+ const payload = samplePayload();+ payload.items[0].resource = { serialNumber: "abc", notAfter: "2026-10-04T23:59:00.000Z" };+ expect(buildWebhookPayload(payload).data.items[0].resource).toEqual({+ serialNumber: "abc",+ notAfter: "2026-10-04T23:59:00.000Z"+ });+ });++ test("prefers the provider's source and exposes the alert's resource id", () => {+ const payload = samplePayload();+ payload.webhookSource = "/applications/app-1/alerts/alert-1";+ payload.alert.resourceId = "app-1";+ const wh = buildWebhookPayload(payload);+ expect(wh.source).toBe("/applications/app-1/alerts/alert-1");+ expect(wh.data.alert.resourceId).toBe("app-1");+ expect(buildWebhookPayload(samplePayload()).data.alert).not.toHaveProperty("resourceId");+ });+test("uses an org-less source when there is no project", () => {const payload = samplePayload();payload.alert.projectId = undefined;diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts b/backend/src/services/alert/providers/cert-manager-application-alert-dal.tsindex 10f88f7016..77610c66ef 100644--- a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts+++ b/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts@@ -14,8 +14,12 @@ export type TApplicationAlertCertificate = {commonName: string;altNames: string | null;profileName: string | null;+ status: string;+ notBefore: Date;notAfter: Date;+ revokedAt: Date | null;revocationReason: number | null;+ applicationId: string | null;applicationName: string | null;};@@ -38,8 +42,12 @@ export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {`${TableName.Certificate}.serialNumber`,`${TableName.Certificate}.commonName`,`${TableName.Certificate}.altNames`,+ `${TableName.Certificate}.status`,+ `${TableName.Certificate}.notBefore`,`${TableName.Certificate}.notAfter`,+ `${TableName.Certificate}.revokedAt`,`${TableName.Certificate}.revocationReason`,+ `${TableName.Certificate}.applicationId`,"profile.slug as profileName",`${TableName.PkiApplication}.name as applicationName`);diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-provider.test.ts b/backend/src/services/alert/providers/cert-manager-application-alert-provider.test.tsindex c56e0b67e0..fbe71bf42b 100644--- a/backend/src/services/alert/providers/cert-manager-application-alert-provider.test.ts+++ b/backend/src/services/alert/providers/cert-manager-application-alert-provider.test.ts@@ -4,7 +4,7 @@ import { vi } from "vitest";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import { AlertChannelType } from "../alert-channel-types";-import { AlertPermissionAction, AlertTelemetryAction, TAlertContext } from "../alert-types";+import { AlertAuditAction, AlertPermissionAction, AlertTelemetryAction, TAlertContext } from "../alert-types";import { TApplicationAlertCertificate } from "./cert-manager-application-alert-dal";import {certManagerApplicationAlertProviderFactory,@@ -28,8 +28,12 @@ const sampleCertificate = (overrides: Partial<TApplicationAlertCertificate> = {}commonName: "api.example.com",altNames: "api.example.com, www.api.example.com",profileName: "tls-server",+ status: "active",+ notBefore: new Date("2026-09-01T00:00:00.000Z"),notAfter: futureDate(5),+ revokedAt: null,revocationReason: null,+ applicationId: "app-1",applicationName: "payments-api",...overrides});@@ -80,7 +84,6 @@ const buildProvider = (opts?: {};const ability = () => createMongoAbility(opts?.abilityRules ?? [{ action: "read", subject: "pki-alerts" }]);const permissionService = {- getProjectPermission: vi.fn(async () => ({ permission: ability() })),getResourcePermission: vi.fn(async () => ({ permission: ability() }))};const licenseService = {@@ -123,14 +126,14 @@ describe("cert manager application alert provider", () => {});});- test("findDueTargets converts alertBefore to days and scopes the scan to the alert's application", async () => {+ test("findScheduledTargets converts alertBefore to days and scopes the scan to the alert's application", async () => {let args: Record<string, unknown> | undefined;const { provider } = buildProvider({onFindExpiring: (value) => {args = value;}});- await provider.findDueTargets({+ await provider.findScheduledTargets({orgId: "org-1",projectId: "proj-1",resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",@@ -145,10 +148,10 @@ describe("cert manager application alert provider", () => {});});- test("findDueTargets and findTargetsByIds return nothing for an alert with no application", async () => {+ test("findScheduledTargets and findEventTargets return nothing for an alert with no application", async () => {const { provider } = buildProvider({ certificates: [sampleCertificate()] });await expect(- provider.findDueTargets({+ provider.findScheduledTargets({orgId: "org-1",projectId: "proj-1",eventType: EXPIRY_EVENT,@@ -157,7 +160,7 @@ describe("cert manager application alert provider", () => {})).resolves.toEqual([]);await expect(- provider.findTargetsByIds({+ provider.findEventTargets({orgId: "org-1",projectId: "proj-1",eventType: ISSUANCE_EVENT,@@ -186,9 +189,44 @@ describe("cert manager application alert provider", () => {expect(payload.summary).toBe("1 certificate in application 'payments-api' expiring within 1 day");expect(payload.alert.condition).toBe("1d");expect(payload.webhookType).toBe(`com.infisical.${EXPIRY_EVENT}`);+ expect(payload.webhookSource).toBe(`/applications/${alertContext().resourceId}/alerts/alert-1`);+ expect(payload.alert.resourceId).toBe(alertContext().resourceId);expect(payload.severity).toBe("critical");- expect(payload.items[0]).toMatchObject({ id: "cert-1", title: "api.example.com", identifier: "105d3b4c" });- expect(payload.items[0].fields?.map((field) => field.label)).toEqual(["SANs", "Profile", "Expires"]);+ expect(payload.items[0]).toMatchObject({ id: "cert-1", title: "api.example.com" });+ expect(payload.items[0].fields?.map((field) => field.label)).toEqual([+ "Serial Number",+ "SANs",+ "Profile",+ "Expires"+ ]);+ expect(payload.items[0].resource).toEqual({+ id: "cert-1",+ serialNumber: "105d3b4c",+ commonName: "api.example.com",+ altNames: ["api.example.com", "www.api.example.com"],+ status: "active",+ notBefore: "2026-09-01T00:00:00.000Z",+ notAfter: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/) as string,+ revokedAt: null,+ revocationReason: null,+ profileName: "tls-server",+ applicationId: "app-1",+ applicationName: "payments-api"+ });+ });++ test("buildPayload names a certificate without a common name by its first SAN, then its serial", async () => {+ const { provider } = buildProvider();+ const issuance = alertContext({ eventType: ISSUANCE_EVENT, condition: null });+ const bySan = provider.buildPayload(issuance, [sampleCertificate({ commonName: "" })], "https://x");+ expect(bySan.summary).toBe("Certificate 'api.example.com' was issued in application 'payments-api'");+ expect(bySan.items[0].title).toBe("api.example.com");+ const bySerial = provider.buildPayload(+ issuance,+ [sampleCertificate({ commonName: "", altNames: null })],+ "https://x"+ );+ expect(bySerial.items[0].title).toBe("105d3b4c");});test("buildPayload for a revocation names the certificate and adds the revocation reason", async () => {@@ -202,11 +240,70 @@ describe("cert manager application alert provider", () => {expect(payload.severity).toBe("warning");expect(payload.alert.condition).toBeUndefined();expect(payload.items[0].fields).toEqual([+ { label: "Serial Number", value: "105d3b4c" },{ label: "Expires", value: expect.any(String) as string },{ label: "Revocation Reason", value: "Key Compromise" }]);});+ test("emits application-specific audit events carrying the application", () => {+ const { provider } = buildProvider();+ const alert = {+ id: "alert-1",+ name: "tls-expiry",+ resourceType: "cert-manager.application",+ resourceId: "app-1",+ resourceName: "payments-api",+ eventType: EXPIRY_EVENT+ };+ const metadata = {+ applicationId: "app-1",+ applicationName: "payments-api",+ alertId: "alert-1",+ name: "tls-expiry",+ eventType: EXPIRY_EVENT+ };++ expect(provider.getAuditEvent?.({ action: AlertAuditAction.Create, alert })).toEqual({+ type: "create-pki-application-alert",+ metadata+ });+ expect(provider.getAuditEvent?.({ action: AlertAuditAction.Update, alert })).toEqual({+ type: "update-pki-application-alert",+ metadata+ });+ expect(provider.getAuditEvent?.({ action: AlertAuditAction.Delete, alert })).toEqual({+ type: "delete-pki-application-alert",+ metadata+ });+ expect(+ provider.getAuditEvent?.({+ action: AlertAuditAction.TestChannel,+ test: {+ resourceType: "cert-manager.application",+ resourceId: "app-1",+ resourceName: "payments-api",+ alertId: "alert-1",+ channelType: "email",+ success: true,+ deliveredTo: 1+ }+ })+ ).toEqual({+ type: "test-pki-application-alert-channel",+ metadata: {+ applicationId: "app-1",+ applicationName: "payments-api",+ alertId: "alert-1",+ channelId: undefined,+ channelType: "email",+ success: true,+ deliveredTo: 1,+ error: undefined+ }+ });+ });+test("buildViewUrl deep-links to the application and falls back to the applications list", async () => {const { provider } = buildProvider();await expect(provider.buildViewUrl(alertContext())).resolves.toBe(@@ -238,15 +335,14 @@ describe("cert manager application alert provider", () => {})).rejects.toThrow();expect(permissionService.getResourcePermission).toHaveBeenCalled();- expect(permissionService.getProjectPermission).not.toHaveBeenCalled();});- test("assertPermission falls back to the project permission without an application and requires a project", async () => {+ test("assertPermission requires a project and an application", async () => {const { provider, permissionService } = buildProvider();await expect(provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", projectId: "proj-1", actor })- ).resolves.toBeUndefined();- expect(permissionService.getProjectPermission).toHaveBeenCalled();+ ).rejects.toThrow("Application alerts require an application ID");+ expect(permissionService.getResourcePermission).not.toHaveBeenCalled();await expect(provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", actor })).rejects.toThrow("Certificate alerts must be created in Certificate Manager");diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts b/backend/src/services/alert/providers/cert-manager-application-alert-provider.tsindex 2819a46390..651813f9e5 100644--- a/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts+++ b/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts@@ -1,10 +1,11 @@import { ForbiddenError } from "@casl/ability";import { z } from "zod";-import { ActionProjectType, ResourceType } from "@app/db/schemas";+import { ResourceType } from "@app/db/schemas";+import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";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 { ProjectPermissionActions } from "@app/ee/services/permission/project-permission";import { ResourcePermissionSub } from "@app/ee/services/permission/resource-permission";import { getConfig } from "@app/lib/config/env";import { BadRequestError, NotFoundError } from "@app/lib/errors";@@ -19,18 +20,20 @@ import { AlertChannelType, TAlertPayload, TAlertSeverity } from "../alert-channeimport { durationToDays, expirySeverity, formatUtcDate, humanizeDays } from "../alert-format-fns";import {ALERT_SCAN_LEAD_INTERVAL,+ AlertAuditAction,AlertPermissionAction,AlertTelemetryAction,AlertTriggerType,DEFAULT_DEDUP_WINDOW_HOURS,IEventAlertProvider,IScheduledAlertProvider,+ TAlertAuditInput,TAlertContext,TAlertPermissionInput,TAlertTelemetryEvent,TAlertTelemetryInput,- TFindDueTargetsInput,- TFindTargetsByIdsInput+ TFindEventTargetsInput,+ TFindScheduledTargetsInput} from "../alert-types";import {TApplicationAlertCertificate,@@ -99,12 +102,14 @@ const eventSeverity = (eventType: CertificateAlertEvent, targets: TApplicationAlreturn "info";};-const formatAltNames = (altNames: string | null): string =>+const splitAltNames = (altNames: string | null): string[] =>(altNames ?? "").split(",").map((name) => name.trim())- .filter(Boolean)- .join(", ");+ .filter(Boolean);++const certificateDisplayName = (certificate: TApplicationAlertCertificate): string =>+ certificate.commonName || splitAltNames(certificate.altNames)[0] || certificate.serialNumber;const buildSummary = (eventType: CertificateAlertEvent,@@ -117,16 +122,18 @@ const buildSummary = (const certificates = `${targets.length} certificate${targets.length === 1 ? "" : "s"}`;return `${certificates}${inApplication} expiring within ${humanizeDays(durationToDays(alertBefore))}`;}- if (targets.length === 1) return `Certificate '${targets[0].commonName}' ${EVENT_VERBS[eventType]}${inApplication}`;+ if (targets.length === 1) {+ return `Certificate '${certificateDisplayName(targets[0])}' ${EVENT_VERBS[eventType]}${inApplication}`;+ }return `${targets.length} certificates ${EVENT_VERBS[eventType]}${inApplication}`;};const buildItemSummary = (eventType: CertificateAlertEvent, certificate: TApplicationAlertCertificate): string => {const inApplication = certificate.applicationName ? ` in application '${certificate.applicationName}'` : "";if (eventType === CertificateAlertEvent.Expiry) {- return `Certificate '${certificate.commonName}'${inApplication} expires on ${formatUtcDate(certificate.notAfter)}`;+ return `Certificate '${certificateDisplayName(certificate)}'${inApplication} expires on ${formatUtcDate(certificate.notAfter)}`;}- return `Certificate '${certificate.commonName}' ${EVENT_VERBS[eventType]}${inApplication}`;+ return `Certificate '${certificateDisplayName(certificate)}' ${EVENT_VERBS[eventType]}${inApplication}`;};const DAILY_SCAN_DEDUP_MARGIN_HOURS = 4;@@ -142,7 +149,7 @@ const expirationDedupWindowHours = (days: number, dailyReminder?: boolean): numbexport type TCertManagerApplicationAlertProviderDep = {certManagerApplicationAlertDAL: TCertManagerApplicationAlertDALFactory;- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;+ permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;};@@ -160,7 +167,7 @@ export const certManagerApplicationAlertProviderFactory = ({return application ? `${base}/applications/${encodeURIComponent(application.name)}` : `${base}/applications`;};- const findDueTargets = async (input: TFindDueTargetsInput): Promise<TApplicationAlertCertificate[]> => {+ const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TApplicationAlertCertificate[]> => {if (!input.projectId || !input.resourceId) return [];const { alertBefore } = ExpirationConditionSchema.parse(input.condition);@@ -174,7 +181,7 @@ export const certManagerApplicationAlertProviderFactory = ({});};- const findTargetsByIds = async (input: TFindTargetsByIdsInput): Promise<TApplicationAlertCertificate[]> => {+ const findEventTargets = async (input: TFindEventTargetsInput): Promise<TApplicationAlertCertificate[]> => {if (!input.projectId || !input.resourceId) return [];EventConditionSchema.parse(input.condition);@@ -185,6 +192,39 @@ export const certManagerApplicationAlertProviderFactory = ({});};+ const getWebhookSource = ({ alertId, resourceId }: { alertId: string; resourceId?: string | null }) =>+ resourceId ? `/applications/${resourceId}/alerts/${alertId}` : undefined;++ const getAuditEvent = (input: TAlertAuditInput): TAuditEvent => {+ if (input.action === AlertAuditAction.TestChannel) {+ const { test } = input;+ return {+ type: EventType.TEST_PKI_APPLICATION_ALERT_CHANNEL,+ metadata: {+ applicationId: test.resourceId ?? null,+ applicationName: test.resourceName ?? null,+ alertId: test.alertId,+ channelId: test.channelId,+ channelType: test.channelType,+ success: test.success,+ deliveredTo: test.deliveredTo,+ error: test.error+ }+ };+ }++ const metadata = {+ applicationId: input.alert.resourceId,+ applicationName: input.alert.resourceName ?? null,+ alertId: input.alert.id,+ name: input.alert.name,+ eventType: input.alert.eventType+ };+ if (input.action === AlertAuditAction.Create) return { type: EventType.CREATE_PKI_APPLICATION_ALERT, metadata };+ if (input.action === AlertAuditAction.Update) return { type: EventType.UPDATE_PKI_APPLICATION_ALERT, metadata };+ return { type: EventType.DELETE_PKI_APPLICATION_ALERT, metadata };+ };+const getTelemetryEvent = ({action,orgId,@@ -226,12 +266,14 @@ export const certManagerApplicationAlertProviderFactory = ({orgId: alert.orgId,...(alert.projectId ? { projectId: alert.projectId } : {}),resourceType: alert.resourceType,+ ...(alert.resourceId ? { resourceId: alert.resourceId } : {}),...(alertBefore ? { condition: alertBefore } : {}),viewUrl},eventKey: eventType,eventLabel: EVENT_LABELS[eventType],webhookType: `com.infisical.${eventType}`,+ webhookSource: getWebhookSource({ alertId: alert.id, resourceId: alert.resourceId }),resourceKind: "Certificate",resourceOwnerKind: "Application",severity: eventSeverity(eventType, targets),@@ -241,20 +283,33 @@ export const certManagerApplicationAlertProviderFactory = ({eventType === CertificateAlertEvent.Revocation? getRevocationReasonLabel(certificate.revocationReason): undefined;+ const altNames = splitAltNames(certificate.altNames);return {id: certificate.id,- title: certificate.commonName,- identifier: certificate.serialNumber,+ title: certificateDisplayName(certificate),summary: buildItemSummary(eventType, certificate),severity: eventSeverity(eventType, [certificate]),fields: [- ...(formatAltNames(certificate.altNames)- ? [{ label: "SANs", value: formatAltNames(certificate.altNames) }]- : []),+ { label: "Serial Number", value: certificate.serialNumber },+ ...(altNames.length ? [{ label: "SANs", value: altNames.join(", ") }] : []),...(certificate.profileName ? [{ label: "Profile", value: certificate.profileName }] : []),{ label: "Expires", value: formatUtcDate(certificate.notAfter) },...(revocationReason ? [{ label: "Revocation Reason", value: revocationReason }] : [])- ]+ ],+ resource: {+ id: certificate.id,+ serialNumber: certificate.serialNumber,+ commonName: certificate.commonName,+ altNames,+ status: certificate.status,+ notBefore: certificate.notBefore.toISOString(),+ notAfter: certificate.notAfter.toISOString(),+ revokedAt: certificate.revokedAt?.toISOString() ?? null,+ revocationReason: certificate.revocationReason,+ profileName: certificate.profileName,+ applicationId: certificate.applicationId,+ applicationName: certificate.applicationName+ }};})};@@ -266,16 +321,7 @@ export const certManagerApplicationAlertProviderFactory = ({}if (!resourceId) {- const { permission } = await permissionService.getProjectPermission({- actor: actor.actor,- actorId: actor.actorId,- projectId,- actorAuthMethod: actor.actorAuthMethod,- actorOrgId: actor.actorOrgId,- actionProjectType: ActionProjectType.CertificateManager- });- ForbiddenError.from(permission).throwUnlessCan(PERMISSION_ACTIONS[action], ProjectPermissionSub.PkiAlerts);- return;+ throw new BadRequestError({ message: "Application alerts require an application ID" });}assertValidApplicationId(resourceId);@@ -344,8 +390,8 @@ export const certManagerApplicationAlertProviderFactory = ({}))],- findDueTargets,- findTargetsByIds,+ findScheduledTargets,+ findEventTargets,buildViewUrl,buildPayload,getTelemetryEvent,@@ -358,6 +404,10 @@ export const certManagerApplicationAlertProviderFactory = ({assertPermission,assertResourceInScope,assertChannelTypesAllowed,+ recipientPolicy: { atOrgScope: true, allowEmailAddresses: true },+ includeLastRun: true,+ getAuditEvent,+ getWebhookSource,resolveProjectId,getResourceNames: async ({ orgId, resourceIds }) =>new Map(diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.test.tsindex 68031fc72b..4fa39cae7c 100644--- a/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts@@ -222,10 +222,10 @@ describe("identity credential alert provider", () => {}});- test("findTargetsByIds rehydrates the identity and the change from the event payload", async () => {+ test("findEventTargets rehydrates the identity and the change from the event payload", async () => {const provider = buildProvider({ userLabel: "[email protected]" });- const targets = await provider.findTargetsByIds({+ const targets = await provider.findEventTargets({orgId: "org-1",resourceId: "ident-1",eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,@@ -246,9 +246,9 @@ describe("identity credential alert provider", () => {expect(provider.targetId(target)).toBe("auth-method-change:ident-1:universal-auth:added");});- test("findTargetsByIds drops an identity deleted between emit and delivery", async () => {+ test("findEventTargets drops an identity deleted between emit and delivery", async () => {const provider = buildProvider({ identities: [] });- const targets = await provider.findTargetsByIds({+ const targets = await provider.findEventTargets({orgId: "org-1",resourceId: "ident-1",eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,@@ -259,14 +259,14 @@ describe("identity credential alert provider", () => {expect(targets).toEqual([]);});- test("findTargetsByIds names a machine identity actor and falls back to the actor type", async () => {+ test("findEventTargets names a machine identity actor and falls back to the actor type", async () => {const provider = buildProvider({identities: [{ id: "ident-1", name: "ci-runner" },{ id: "ident-admin", name: "terraform" }]});- const byIdentity = await provider.findTargetsByIds({+ const byIdentity = await provider.findEventTargets({orgId: "org-1",resourceId: "ident-1",eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,@@ -278,7 +278,7 @@ describe("identity credential alert provider", () => {"terraform (machine identity)");- const byPlatform = await provider.findTargetsByIds({+ const byPlatform = await provider.findEventTargets({orgId: "org-1",resourceId: "ident-1",eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,@@ -290,10 +290,10 @@ describe("identity credential alert provider", () => {});// A drifted emit site must fail the event with a clear error, not send a notification with blank fields.- test("findTargetsByIds rejects a payload the emitter contract does not describe", async () => {+ test("findEventTargets rejects a payload the emitter contract does not describe", async () => {const provider = buildProvider();await expect(- provider.findTargetsByIds({+ provider.findEventTargets({orgId: "org-1",resourceId: "ident-1",eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,@@ -306,7 +306,7 @@ describe("identity credential alert provider", () => {test("a credential change carries the credential through the payload, the target id, and the fields", async () => {const provider = buildProvider({ userLabel: "[email protected]" });- const [target] = await provider.findTargetsByIds({+ const [target] = await provider.findEventTargets({orgId: "org-1",resourceId: "ident-1",eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,@@ -415,7 +415,7 @@ describe("identity credential alert provider", () => {expect(item.fields?.find((f) => f.label === "Changed At")?.value).toContain("2026");});- test("findDueTargets converts alertBefore to a postgres interval and tags credential type", async () => {+ test("findScheduledTargets converts alertBefore to a postgres interval and tags credential type", async () => {let seenArgs:| {alertBeforeInterval: string;@@ -433,7 +433,7 @@ describe("identity credential alert provider", () => {});const asOf = new Date("2026-07-24T00:00:00.000Z");- const targets = await provider.findDueTargets({+ const targets = await provider.findScheduledTargets({orgId: "org-1",resourceId: "ident-1",eventType: IDENTITY_AUTHENTICATION_EXPIRY_EVENT,@@ -449,7 +449,7 @@ describe("identity credential alert provider", () => {expect(provider.targetId(targets[0])).toBe("ua-client-secret:sec-1");});- test("findDueTargets scopes the query to the alert's project so it cannot leak org-wide credentials", async () => {+ test("findScheduledTargets scopes the query to the alert's project so it cannot leak org-wide credentials", async () => {let seenArgs: { projectId?: string | null } | undefined;const provider = buildProvider({onFind: (args) => {@@ -457,7 +457,7 @@ describe("identity credential alert provider", () => {}});- await provider.findDueTargets({+ await provider.findScheduledTargets({orgId: "org-1",projectId: "proj-1",resourceId: null,@@ -495,7 +495,7 @@ describe("identity credential alert provider", () => {expect(expires).toContain("UTC");});- test("findDueTargets scans Token Auth tokens with the same window and scope as client secrets", async () => {+ test("findScheduledTargets scans Token Auth tokens with the same window and scope as client secrets", async () => {let secretArgs: TScanArgs | undefined;let tokenArgs: TScanArgs | undefined;const provider = buildProvider({@@ -508,7 +508,7 @@ describe("identity credential alert provider", () => {}});- const targets = await provider.findDueTargets({+ const targets = await provider.findScheduledTargets({orgId: "org-1",projectId: "proj-1",resourceId: "ident-1",@@ -525,7 +525,7 @@ describe("identity credential alert provider", () => {expect(provider.targetId(targets[0])).toBe("token-auth-token:tok-1");});- test("findDueTargets merges client secrets and tokens ordered by soonest expiry", async () => {+ test("findScheduledTargets merges client secrets and tokens ordered by soonest expiry", async () => {const provider = buildProvider({secrets: [sampleSecret({ id: "sec-late", expiresAt: futureDate(20) })],tokens: [@@ -534,7 +534,7 @@ describe("identity credential alert provider", () => {]});- const targets = await provider.findDueTargets({+ const targets = await provider.findScheduledTargets({orgId: "org-1",resourceId: null,eventType: IDENTITY_AUTHENTICATION_EXPIRY_EVENT,@@ -812,11 +812,4 @@ describe("identity credential alert provider", () => {provider.assertResourceInScope({ orgId: "org-1", projectId: "proj-1", resourceId: "ident-1" })).resolves.toBeUndefined();});-- test("getResourceNames returns the identity's name for audit events", async () => {- const provider = buildProvider();- const names = await provider.getResourceNames?.({ orgId: "org-1", resourceIds: ["ident-1", "unknown"] });- expect(names?.get("ident-1")).toBe("ci-runner");- expect(names?.has("unknown")).toBe(false);- });});diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.tsindex 927886dfc1..0b342dc7f9 100644--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts@@ -28,8 +28,8 @@ import {MAX_DEDUP_WINDOW_HOURS,TAlertContext,TAlertPermissionInput,- TFindDueTargetsInput,- TFindTargetsByIdsInput+ TFindEventTargetsInput,+ TFindScheduledTargetsInput} from "../alert-types";import {TExpiringTokenAuthToken,@@ -238,7 +238,7 @@ export const identityCredentialAlertProviderFactory = ({: `${siteUrl}/organizations/${alert.orgId}/access-management?selectedTab=identities`;};- const findDueTargets = async (input: TFindDueTargetsInput): Promise<TIdentityCredentialTarget[]> => {+ const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TIdentityCredentialTarget[]> => {const { alertBefore } = IdentityCredentialConditionSchema.parse(input.condition);const scan = {@@ -286,7 +286,7 @@ export const identityCredentialAlertProviderFactory = ({return typeLabel;};- const findTargetsByIds = async (input: TFindTargetsByIdsInput): Promise<TIdentityCredentialTarget[]> => {+ const findEventTargets = async (input: TFindEventTargetsInput): Promise<TIdentityCredentialTarget[]> => {if (input.eventType !== IDENTITY_AUTH_METHOD_CHANGED_EVENT) return [];const parsed = IdentityAuthMethodChangePayloadSchema.safeParse(input.payload);@@ -511,8 +511,8 @@ export const identityCredentialAlertProviderFactory = ({conditionSchema: IdentityAuthMethodChangeConditionSchema}],- findDueTargets,- findTargetsByIds,+ findScheduledTargets,+ findEventTargets,buildViewUrl,buildPayload,targetId,@@ -526,13 +526,6 @@ export const identityCredentialAlertProviderFactory = ({);},assertPermission,- assertResourceInScope,- getResourceNames: async ({ orgId, resourceIds }) =>- new Map(- (await identityCredentialAlertDAL.findIdentitiesByIds(resourceIds, orgId)).map((identity) => [- identity.id,- identity.name- ])- )+ assertResourceInScope};};diff --git a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.tsindex 54d3c8eb27..3cca1dc8ab 100644--- a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts@@ -34,12 +34,12 @@ const HANDLER_TIMEOUT_MS = 30 * 60 * 1000;type TDigiCertRevocationSyncQueueFactoryDep = {cronJob: TCronJobFactory;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findWithAssociatedCa">;- certificateDAL: Pick<TCertificateDALFactory, "findActiveDigiCertCertsByOrderIds" | "updateById" | "transaction">;+ certificateDAL: Pick<TCertificateDALFactory, "findActiveDigiCertCertsByOrderIds" | "updateById">;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;- certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "emit">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;};export type TDigiCertRevocationSyncQueueFactory = ReturnType<typeof digicertRevocationSyncQueueFactory>;@@ -63,25 +63,17 @@ export const digicertRevocationSyncQueueFactory = ({projectId: string;applicationId?: string | null;}) => {- await certificateDAL.transaction(async (tx) => {- await certificateDAL.updateById(- cert.id,- {- status: CertStatus.REVOKED,- revokedAt: new Date(),- revocationReason: revocationReasonToCrlCode(CrlReason.UNSPECIFIED)- },- tx- );- await certificateAlertEventEmitter.emit(- {- certificateId: cert.id,- projectId: cert.projectId,- eventType: CertificateAlertEvent.Revocation,- applicationId: cert.applicationId ?? null- },- tx- );+ await certificateDAL.updateById(cert.id, {+ status: CertStatus.REVOKED,+ revokedAt: new Date(),+ revocationReason: revocationReasonToCrlCode(CrlReason.UNSPECIFIED)+ });++ await certificateAlertEventEmitter.notify({+ certificateId: cert.id,+ projectId: cert.projectId,+ eventType: CertificateAlertEvent.Revocation,+ applicationId: cert.applicationId ?? null});await auditLogService.createAuditLog({diff --git a/backend/src/services/certificate/certificate-alert-events.ts b/backend/src/services/certificate/certificate-alert-events.tsindex 6a0cfe91ce..30bd509837 100644--- a/backend/src/services/certificate/certificate-alert-events.ts+++ b/backend/src/services/certificate/certificate-alert-events.ts@@ -26,15 +26,15 @@ export type TCertificateAlertEventInput = {type TCertificateAlertEventEmitterDep = {eventEmitter: TEventEmitter;- projectDAL: Pick<TProjectDALFactory, "findById" | "transaction">;+ projectDAL: Pick<TProjectDALFactory, "findById">;};export type TCertificateAlertEventEmitter = ReturnType<typeof certificateAlertEventEmitterFactory>;export const certificateAlertEventEmitterFactory = ({ eventEmitter, projectDAL }: TCertificateAlertEventEmitterDep) => {- const emit = async (+ const $emit = async ({ certificateId, projectId, orgId, applicationId, eventType }: TCertificateAlertEventInput,- tx: Knex+ tx?: Knex) => {if (!applicationId) return;@@ -55,9 +55,11 @@ export const certificateAlertEventEmitterFactory = ({ eventEmitter, projectDAL }await eventEmitter.emit(event, tx);};+ const emit = (input: TCertificateAlertEventInput, tx: Knex) => $emit(input, tx);+const notify = async (input: TCertificateAlertEventInput) => {try {- await projectDAL.transaction((tx) => emit(input, tx));+ await $emit(input);} catch (error) {logger.warn(error,diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex 03fd385c37..903ac1e1d3 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -158,7 +158,7 @@ type TCertificateServiceFactoryDep = {certificateAuthorityService: Pick<TCertificateAuthorityServiceFactory, "revokeCertificate">;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;- certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "emit">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;usageCounterDAL: Pick<TUsageCounterDALFactory,@@ -769,17 +769,14 @@ export const certificateServiceFactory = ({if (!ca.externalCa?.id) {await internalCertificateAuthorityDAL.update({ caId: ca.id }, { $incr: { ocspGeneration: 1 } }, tx);}+ });- await certificateAlertEventEmitter.emit(- {- certificateId: revokedCertId,- projectId: ca.projectId,- orgId: actorOrgId,- eventType: CertificateAlertEvent.Revocation,- applicationId: revokedCertApplicationId- },- tx- );+ await certificateAlertEventEmitter.notify({+ certificateId: revokedCertId,+ projectId: ca.projectId,+ orgId: actorOrgId,+ eventType: CertificateAlertEvent.Revocation,+ applicationId: revokedCertApplicationId});usageMeteringService.emitForProject(ca.projectId, ActiveCerts.key);diff --git a/backend/src/services/event-outbox/event-outbox-dal.ts b/backend/src/services/event-outbox/event-outbox-dal.tsindex b8f498b96d..40ac53508e 100644--- a/backend/src/services/event-outbox/event-outbox-dal.ts+++ b/backend/src/services/event-outbox/event-outbox-dal.ts@@ -24,10 +24,10 @@ export type TOutboxInsertRow = {};export const eventOutboxDALFactory = (db: TDbClient) => {- const insertEvents = async (rows: TOutboxInsertRow[], tx: Knex): Promise<void> => {+ const insertEvents = async (rows: TOutboxInsertRow[], tx?: Knex): Promise<void> => {if (rows.length === 0) return;try {- await tx(TableName.EventOutbox)+ await (tx || db)(TableName.EventOutbox).insert(rows.map((row) => ({...row,diff --git a/backend/src/services/event-outbox/event-outbox-service.ts b/backend/src/services/event-outbox/event-outbox-service.tsindex de95abcf17..595fd4cbcc 100644--- a/backend/src/services/event-outbox/event-outbox-service.ts+++ b/backend/src/services/event-outbox/event-outbox-service.ts@@ -97,10 +97,11 @@ export type TEventOutboxServiceFactoryDep = {export type TEventOutboxServiceFactory = ReturnType<typeof eventOutboxServiceFactory>;export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry }: TEventOutboxServiceFactoryDep) => {- // `tx` is required so the row commits with the business write. Nothing is caught on purpose: a bad- // event is a bug at the emit site (500, not 400), and swallowing a failed insert would leave the- // caller with a poisoned transaction.- const emit = async (event: TEventInput, tx: Knex): Promise<void> => {+ // Pass the caller's `tx` so the row commits with the business write; omit it only when there is no+ // business write to be atomic with. Nothing is caught on purpose: a bad event is a bug at the emit+ // site (500, not 400), and swallowing a failed insert would leave the caller with a poisoned+ // transaction.+ const emit = async (event: TEventInput, tx?: Knex): Promise<void> => {const parsed = EventInputSchema.safeParse(event);if (!parsed.success) {throw new InternalServerError({diff --git a/backend/src/services/event-outbox/event-outbox-types.ts b/backend/src/services/event-outbox/event-outbox-types.tsindex c846044117..efd1a58a5a 100644--- a/backend/src/services/event-outbox/event-outbox-types.ts+++ b/backend/src/services/event-outbox/event-outbox-types.ts@@ -58,7 +58,7 @@ export const EventInputSchema = z.object({export type TEventInput = z.input<typeof EventInputSchema>;export type TEventEmitter = {- emit: (event: TEventInput, tx: Knex) => Promise<void>;+ emit: (event: TEventInput, tx?: Knex) => Promise<void>;};// What a consumer sees. Lock, attempt and status columns are the outbox's business.diff --git a/docs/documentation/platform/pki/applications/alerting/overview.mdx b/docs/documentation/platform/pki/applications/alerting/overview.mdxindex f641b939fc..7b8ff04cee 100644--- a/docs/documentation/platform/pki/applications/alerting/overview.mdx+++ b/docs/documentation/platform/pki/applications/alerting/overview.mdx@@ -23,11 +23,11 @@ Certificate alerting tells your team about certificate lifecycle events in an [A</Card></CardGroup>-Infisical checks expiration alerts once a day. Issuance, renewal, and revocation alerts are sent within seconds of the event. Importing a certificate into the application doesn't trigger an Issuance alert, but expiration and revocation alerts still cover imported certificates.+Expiration alerts are checked once a day. Issuance, renewal, and revocation alerts are sent within seconds of the event. Importing a certificate into the application doesn't trigger an Issuance alert, but expiration and revocation alerts still cover imported certificates.## Prerequisites-- For email alerts, recipients who are members of Certificate Manager, or addresses on one of your organization's [verified email domains](/documentation/platform/email-domain)+- For email alerts, recipients who are organization members, or addresses on one of your organization's [verified email domains](/documentation/platform/email-domain)## Create an alert@@ -58,7 +58,7 @@ An application can have one alert of each type. To notify more places about the| Channel | Sends to ||---------|----------|-| **Email** | Certificate Manager members, or any address on one of your organization's verified email domains |+| **Email** | Organization members, or any address on one of your organization's verified email domains || **[Slack](/documentation/platform/pki/applications/alerting/slack-alerts)** | A Slack channel through an Incoming Webhook || **[PagerDuty](/documentation/platform/pki/applications/alerting/pagerduty-alerts)** | A PagerDuty service through Events API v2 || **[Webhook](/documentation/platform/pki/applications/alerting/webhook-alerts)** | Any HTTPS endpoint, with an optional signature |@@ -67,22 +67,22 @@ An application can have one alert of each type. To notify more places about the<AccordionGroup><Accordion title="Who receives email alerts?">- The addresses you enter on the email channel. An address that belongs to a Certificate Manager member only receives alerts while that person is still a member. Any other address has to be on one of your organization's [verified email domains](/documentation/platform/email-domain) when you add it.+ The addresses you enter on the email channel. An address that belongs to an organization member only receives alerts while that person is still in the organization. Any other address has to be on one of your organization's [verified email domains](/documentation/platform/email-domain) when you add it.</Accordion><Accordion title="How often does an expiration alert notify about the same certificate?">- The alert repeats until the certificate is renewed or expires. How often it repeats depends on how many days before expiry the alert starts:+ The alert repeats until the certificate is renewed or expires. How often it repeats depends on the alert's **Alert Before** setting:- | Days before expiry | Repeats every |- |--------------------|---------------|- | 7 or fewer | Day |- | 8 to 30 | 2 days |- | 31 to 90 | 7 days |- | More than 90 | 30 days |+ | Alert before | Repeats every |+ |--------------|---------------|+ | 7 days or fewer | Day |+ | 8 to 30 days | 2 days |+ | 31 to 90 days | 7 days |+ | More than 90 days | 30 days |If you turn on **Repeat daily until expiry**, the alert repeats every day.</Accordion><Accordion title="What happens to an alert when I delete its application?">- Infisical deletes the application's alerts and their channels along with the application.+ The application's alerts and their channels are deleted along with the application.</Accordion></AccordionGroup>diff --git a/docs/documentation/platform/pki/applications/alerting/pagerduty-alerts.mdx b/docs/documentation/platform/pki/applications/alerting/pagerduty-alerts.mdxindex 9cae6e7492..afe15fa4a8 100644--- a/docs/documentation/platform/pki/applications/alerting/pagerduty-alerts.mdx+++ b/docs/documentation/platform/pki/applications/alerting/pagerduty-alerts.mdx@@ -47,7 +47,7 @@ A PagerDuty channel on a certificate [alert](/documentation/platform/pki/applica## Severity mapping-Infisical sets each incident's PagerDuty severity from the alert's event. For expiration alerts, each certificate gets its own incident, and that incident's severity comes from how close the certificate is to expiry.+Each incident's PagerDuty severity comes from the alert's event. For expiration alerts, it comes from how close the certificate is to expiry.### Expiration alerts@@ -68,9 +68,9 @@ Infisical sets each incident's PagerDuty severity from the alert's event. For ex## Incident grouping-Infisical opens one incident per certificate. If the same alert fires again for the same certificate, PagerDuty updates the existing incident instead of opening a new one.+Each certificate gets its own incident. If the same alert fires again for the same certificate, PagerDuty updates the existing incident instead of opening a new one.-Each PagerDuty channel opens at most 10 incidents per run. If more than 10 certificates are due for an expiration alert, Infisical sends the certificates closest to expiry first and sends the rest on the next daily run.+Each PagerDuty channel opens at most 10 incidents per run. If more than 10 certificates are due for an expiration alert, the ones closest to expiry go first and the rest go on the next daily run.## What's next?diff --git a/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx b/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdxindex 1269c45275..8f6b4d1c6a 100644--- a/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx+++ b/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx@@ -39,7 +39,7 @@ Each request is a [CloudEvents](https://cloudevents.io/) JSON payload. The `type## Webhook payload format-`data.items` lists the certificates the alert fired for. Each item has the certificate's ID, its common name as `title`, its serial number as `identifier`, a one-line `summary`, a `severity`, and a list of display `fields`. An expiration request can include several certificates, and `data.alert.condition` holds the alert's lead time as you entered it, such as `30d` or `2w`. Issuance, renewal, and revocation requests include the one certificate the event was about.+`data.items` lists the certificates the alert fired for. Each item has the certificate's ID, a `title` (its common name, or its first SAN or serial number when it has none), a one-line `summary`, a `severity`, and a list of display `fields`. To act on a certificate in code, read `resource` instead of `fields`: it holds the certificate's typed values, with ISO 8601 dates and the raw revocation reason code. An expiration request can include several certificates, and `data.alert.condition` holds the alert's lead time as you entered it, such as `30d` or `2w`. Issuance, renewal, and revocation requests include the one certificate the event was about.<Note>Only alerts created in an application send this payload. Alerts created before certificate alerts moved to applications keep sending the older `com.infisical.pki.certificate.*` event types with a `data.certificates` list. If one endpoint receives both, check the `type` field to tell them apart.@@ -51,7 +51,7 @@ Each request is a [CloudEvents](https://cloudevents.io/) JSON payload. The `type{"specversion": "1.0","type": "com.infisical.cert-manager.application.certificate.expiry",- "source": "/projects/<project-id>/alerts/<alert-id>",+ "source": "/applications/<application-id>/alerts/<alert-id>","id": "<unique-event-id>","time": "2026-09-24T00:00:09.664Z","datacontenttype": "application/json",@@ -61,20 +61,35 @@ Each request is a [CloudEvents](https://cloudevents.io/) JSON payload. The `type"id": "<alert-id>","name": "tls-expiry-alert","resourceType": "cert-manager.application",+ "resourceId": "<application-id>","condition": "30d"},"items": [{"id": "<certificate-id>","title": "api.example.com",- "identifier": "105d3b4c28132774ab17e350c0e8229ba1bef40d","summary": "Certificate 'api.example.com' in application 'payments-api' expires on October 4, 2026 at 11:59 PM UTC","severity": "error","fields": [+ { "label": "Serial Number", "value": "105d3b4c28132774ab17e350c0e8229ba1bef40d" },{ "label": "SANs", "value": "api.example.com, www.api.example.com" },{ "label": "Profile", "value": "tls-server" },{ "label": "Expires", "value": "October 4, 2026 at 11:59 PM UTC" }- ]+ ],+ "resource": {+ "id": "<certificate-id>",+ "serialNumber": "105d3b4c28132774ab17e350c0e8229ba1bef40d",+ "commonName": "api.example.com",+ "altNames": ["api.example.com", "www.api.example.com"],+ "status": "active",+ "notBefore": "2026-07-06T23:59:00.000Z",+ "notAfter": "2026-10-04T23:59:00.000Z",+ "revokedAt": null,+ "revocationReason": null,+ "profileName": "tls-server",+ "applicationId": "<application-id>",+ "applicationName": "payments-api"+ }}],"metadata": {@@ -92,7 +107,7 @@ Each request is a [CloudEvents](https://cloudevents.io/) JSON payload. The `type{"specversion": "1.0","type": "com.infisical.cert-manager.application.certificate.revocation",- "source": "/projects/<project-id>/alerts/<alert-id>",+ "source": "/applications/<application-id>/alerts/<alert-id>","id": "<unique-event-id>","time": "2026-09-24T14:22:00.000Z","datacontenttype": "application/json",@@ -101,20 +116,35 @@ Each request is a [CloudEvents](https://cloudevents.io/) JSON payload. The `type"alert": {"id": "<alert-id>","name": "prod-revocation-notify",- "resourceType": "cert-manager.application"+ "resourceType": "cert-manager.application",+ "resourceId": "<application-id>"},"items": [{"id": "<certificate-id>","title": "api.example.com",- "identifier": "105d3b4c28132774ab17e350c0e8229ba1bef40d","summary": "Certificate 'api.example.com' was revoked in application 'payments-api'","severity": "warning","fields": [+ { "label": "Serial Number", "value": "105d3b4c28132774ab17e350c0e8229ba1bef40d" },{ "label": "Profile", "value": "tls-server" },{ "label": "Expires", "value": "October 4, 2026 at 11:59 PM UTC" },{ "label": "Revocation Reason", "value": "Key Compromise" }- ]+ ],+ "resource": {+ "id": "<certificate-id>",+ "serialNumber": "105d3b4c28132774ab17e350c0e8229ba1bef40d",+ "commonName": "api.example.com",+ "altNames": [],+ "status": "revoked",+ "notBefore": "2026-07-06T23:59:00.000Z",+ "notAfter": "2026-10-04T23:59:00.000Z",+ "revokedAt": "2026-09-24T14:21:58.000Z",+ "revocationReason": 1,+ "profileName": "tls-server",+ "applicationId": "<application-id>",+ "applicationName": "payments-api"+ }}],"metadata": {@@ -129,7 +159,7 @@ Each request is a [CloudEvents](https://cloudevents.io/) JSON payload. The `type## Webhook signature verification-If you set a signing secret, Infisical adds an `x-infisical-signature` header to each request:+If you set a signing secret, each request carries an `x-infisical-signature` header:```x-infisical-signature: t=<timestamp>,v1=<signature>diff --git a/frontend/src/components/v3/generic/Combobox/Combobox.tsx b/frontend/src/components/v3/generic/Combobox/Combobox.tsxindex 8240103877..a6e967a3af 100644--- a/frontend/src/components/v3/generic/Combobox/Combobox.tsx+++ b/frontend/src/components/v3/generic/Combobox/Combobox.tsx@@ -27,6 +27,7 @@ type ComboboxCreationBaseConfig<TOption> = {isValid?: (inputValue: string, context: ComboboxCreationContext<TOption>) => boolean;isDuplicate?: (inputValue: string, option: TOption) => boolean;formatLabel?: (inputValue: string) => React.ReactNode;+ emptyLabel?: React.ReactNode;isDisabled?: boolean;};@@ -365,7 +366,7 @@ const ComboboxList = <TOption,>({const hasCreationError = Boolean(inlineCreation && creationError?.inputValue === item.inputValue);- let label: React.ReactNode = "Create";+ let label: React.ReactNode = creation?.emptyLabel ?? "Create";if (item.inputValue) {label = creation?.formatLabel?.(item.inputValue) ?? `Create "${item.inputValue}"`;}diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.tsindex 9d3de11e1d..779c289a47 100644--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@ -129,6 +129,7 @@ export type TTestAlertChannelDTO = {resourceType: string;resourceId?: string | null;projectId?: string | null;+ alertId?: string;channelId?: string;channelType: AlertChannelType;config?: Record<string, unknown>;diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex 43c2786fb3..0608740cb2 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -120,6 +120,10 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.UPDATE_ALERT]: "Update alert",[EventType.DELETE_ALERT]: "Delete alert",[EventType.TEST_ALERT_CHANNEL]: "Test alert channel",+ [EventType.CREATE_PKI_APPLICATION_ALERT]: "Create application alert",+ [EventType.UPDATE_PKI_APPLICATION_ALERT]: "Update application alert",+ [EventType.DELETE_PKI_APPLICATION_ALERT]: "Delete application alert",+ [EventType.TEST_PKI_APPLICATION_ALERT_CHANNEL]: "Test application alert channel",[EventType.CREATE_PKI_COLLECTION]: "Create PKI collection",[EventType.GET_PKI_COLLECTION]: "Get PKI collection",[EventType.UPDATE_PKI_COLLECTION]: "Update PKI collection",diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex 83fe5f4869..c93d7627ef 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -136,6 +136,10 @@ export enum EventType {UPDATE_ALERT = "update-alert",DELETE_ALERT = "delete-alert",TEST_ALERT_CHANNEL = "test-alert-channel",+ CREATE_PKI_APPLICATION_ALERT = "create-pki-application-alert",+ UPDATE_PKI_APPLICATION_ALERT = "update-pki-application-alert",+ DELETE_PKI_APPLICATION_ALERT = "delete-pki-application-alert",+ TEST_PKI_APPLICATION_ALERT_CHANNEL = "test-pki-application-alert-channel",CREATE_PKI_COLLECTION = "create-pki-collection",GET_PKI_COLLECTION = "get-pki-collection",UPDATE_PKI_COLLECTION = "update-pki-collection",diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsxindex ab1f0a7d80..d6eca1183c 100644--- a/frontend/src/hooks/api/users/queries.tsx+++ b/frontend/src/hooks/api/users/queries.tsx@@ -170,11 +170,11 @@ export const useGetUserProjectFavorites = (orgId: string) =>queryFn: () => fetchUserProjectFavorites(orgId)});-export const useGetOrgUsers = (orgId: string) =>+export const useGetOrgUsers = (orgId: string, options?: { enabled?: boolean }) =>useQuery({queryKey: userKeys.getOrgUsers(orgId),queryFn: () => fetchOrgUsers(orgId),- enabled: Boolean(orgId)+ enabled: Boolean(orgId) && (options?.enabled ?? true)});// mutationdiff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsxindex e3a55b51c6..d215370b1b 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx@@ -330,6 +330,7 @@ export const ApplicationAlertsCard = ({isOpen={deleteAlertModal.isOpen}confirmKey="delete"title={`Delete Alert "${deleteAlertModal.name ?? ""}"?`}+ description="The alert and its notification channels are deleted, and it stops sending notifications."onOpenChange={(isOpen) =>setDeleteAlertModal({ isOpen, alertId: undefined, name: undefined })}diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsxindex 5561c54e6b..ddb4c8d984 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx@@ -16,7 +16,13 @@ import {StepperList,StepperStep} from "@app/components/v3";-import { useGetWorkspaceUsers } from "@app/hooks/api";+import {+ OrgPermissionMemberActions,+ OrgPermissionSubjects,+ useOrganization,+ useOrgPermission+} from "@app/context";+import { useGetOrgUsers } from "@app/hooks/api";import {AlertChannelType,CertificateAlertEventType,@@ -26,7 +32,7 @@ import {useCreateAlert,useUpdateAlert} from "@app/hooks/api/alerts";-import { buildNewChannel, getNextChannelName } from "@app/views/Alerts";+import { buildNextChannel, canReceiveAlerts } from "@app/views/Alerts";import { CertificateAlertAddChannelMenu, ChannelsStep } from "./ChannelsStep";import { DetailsStep } from "./DetailsStep";@@ -37,9 +43,9 @@ import {STEP_FIELDS,STEPS,TCertificateAlertForm,+ TMemberEmails,toCertificateAlertForm,- toCondition,- TProjectMemberEmails+ toCondition} from "./types";type Props = {@@ -53,7 +59,7 @@ type Props = {usedEventTypes: CertificateAlertEventType[];};-type WizardProps = Omit<Props, "isOpen"> & { members: TProjectMemberEmails };+type WizardProps = Omit<Props, "isOpen"> & { members: TMemberEmails };const CertificateAlertWizard = ({onOpenChange,@@ -117,8 +123,7 @@ const CertificateAlertWizard = ({};const addChannel = (channelType: AlertChannelType) => {- const takenNames = new Set(form.getValues("channels").map((channel) => channel.name));- append(buildNewChannel(channelType, getNextChannelName(takenNames, channelType)));+ append(buildNextChannel(form.getValues("channels"), channelType));};const goNext = async () => {@@ -200,6 +205,7 @@ const CertificateAlertWizard = ({onRemove={remove}projectId={projectId}applicationId={applicationId}+ alertId={alert?.id}members={members}/>)}@@ -240,18 +246,20 @@ const CertificateAlertWizard = ({};export const CertificateAlertSheet = ({ isOpen, onOpenChange, ...props }: Props) => {- const { data: projectUsers, isPending: isUsersPending } = useGetWorkspaceUsers(- props.projectId,- true,- undefined,- { enabled: isOpen }+ const { currentOrg } = useOrganization();+ const { permission: orgPermission } = useOrgPermission();+ const canReadOrgMembers = orgPermission.can(+ OrgPermissionMemberActions.Read,+ OrgPermissionSubjects.Member);+ const { data: orgUsers, isLoading: isUsersPending } = useGetOrgUsers(currentOrg.id, {+ enabled: isOpen && canReadOrgMembers+ });- const members = useMemo((): TProjectMemberEmails => {+ const members = useMemo((): TMemberEmails => {const byUserId = new Map<string, string>();const byEmail = new Map<string, string>();- (projectUsers ?? []).forEach(({ user }) => {- if (!user.isOrgMembershipActive || user.isOrgMembershipPending) return;+ (orgUsers ?? []).filter(canReceiveAlerts).forEach(({ user }) => {const email = (user.email || user.username || "").toLowerCase();if (!email) return;byUserId.set(user.id, email);@@ -260,9 +268,9 @@ export const CertificateAlertSheet = ({ isOpen, onOpenChange, ...props }: Props)return {emailByUserId: byUserId,memberIdByEmail: byEmail,- isAvailable: Boolean(projectUsers)+ isAvailable: Boolean(orgUsers)};- }, [projectUsers]);+ }, [orgUsers]);return (<Sheet open={isOpen} onOpenChange={onOpenChange}>diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsxindex ab32fa6b7c..3b7d370777 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx@@ -24,8 +24,8 @@ import {MAX_CHANNELS,normalizeEmail,TCertificateAlertForm,- toRecipientEmails,- TProjectMemberEmails+ TMemberEmails,+ toRecipientEmails} from "./types";type TChannelField = FieldArrayWithId<TCertificateAlertForm, "channels">;@@ -54,6 +54,8 @@ export const CertificateAlertAddChannelMenu = ({isDisabled={channelCount >= MAX_CHANNELS}lockedChannelTypes={isEnterpriseAllowed ? [] : ENTERPRISE_CHANNEL_TYPES}onLockedSelect={() => setIsUpgradeOpen(true)}+ label="Add Channel"+ contentClassName="min-w-56"/><UpgradePlanModalisOpen={isUpgradeOpen}@@ -71,7 +73,7 @@ const EmailRecipientsField = ({onChange,isError,members-}: TChannelRecipientsRenderProps & { members: TProjectMemberEmails }) => {+}: TChannelRecipientsRenderProps & { members: TMemberEmails }) => {const emails = toRecipientEmails(value, members);const groups = value.filter((recipient) => recipient.principalType === AlertPrincipalType.Group);const unlistedUsers = value.filter(@@ -111,6 +113,7 @@ const EmailRecipientsField = ({isValid: (inputValue) => isValidEmail(normalizeEmail(inputValue)),isDuplicate: (inputValue, email) => normalizeEmail(inputValue) === email,formatLabel: (inputValue) => `Add "${normalizeEmail(inputValue)}"`,+ emptyLabel: "Add email",onCreate: (inputValue) => {const email = normalizeEmail(inputValue);if (!emails.includes(email)) setEmails([...emails, email]);@@ -118,8 +121,7 @@ const EmailRecipientsField = ({}}/><FieldDescription>- Pick Certificate Manager members or type any email address. Other addresses must use one of- your organization's verified email domains.+ Pick organization members or type an email address on a verified email domain.{unlistedUsers.length > 0 && ` Also sent to ${unlistedUsers.length} member(s).`}{groups.length > 0 && ` Also sent to ${groups.length} group(s).`}</FieldDescription>@@ -133,6 +135,7 @@ export const ChannelsStep = ({onRemove,projectId,applicationId,+ alertId,members}: {form: UseFormReturn<TCertificateAlertForm>;@@ -140,7 +143,8 @@ export const ChannelsStep = ({onRemove: (index: number) => void;projectId: string;applicationId: string;- members: TProjectMemberEmails;+ alertId?: string;+ members: TMemberEmails;}) => {const channelsError = form.formState.errors.channels?.root ?? form.formState.errors.channels;@@ -169,6 +173,7 @@ export const ChannelsStep = ({projectId={projectId}resourceType={CertificateAlertResourceType.Application}resourceId={applicationId}+ alertId={alertId}canRemoveonRemove={() => onRemove(index)}renderRecipients={(props) => <EmailRecipientsField {...props} members={members} />}diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsxindex f5e5357873..e5caa96ff1 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsx@@ -180,6 +180,7 @@ export const LegacyApplicationAlertsCard = ({ applicationId, canDelete }: Props)isOpen={Boolean(deleteAlert)}confirmKey="delete"title={`Delete Legacy Alert "${deleteAlert?.name ?? ""}"?`}+ description="It stops sending notifications, and legacy alerts can't be recreated. Create a new alert to keep getting them."onOpenChange={(isOpen) => !isOpen && setDeleteAlert(undefined)}onConfirm={handleDeleteAlert}/>diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsxindex aab27891e1..59dabcf4ab 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx@@ -13,11 +13,11 @@ import {import {CERTIFICATE_ALERT_EVENT_LABELS,TCertificateAlertForm,- toRecipientEmails,- TProjectMemberEmails+ TMemberEmails,+ toRecipientEmails} from "./types";-type Props = { form: UseFormReturn<TCertificateAlertForm>; members: TProjectMemberEmails };+type Props = { form: UseFormReturn<TCertificateAlertForm>; members: TMemberEmails };const Section = ({ title, children }: { title: string; children: ReactNode }) => (<div className="flex flex-col gap-4">@@ -37,7 +37,7 @@ const EnabledBadge = ({ enabled }: { enabled: boolean }) => (<Badge variant={enabled ? "success" : "neutral"}>{enabled ? "Enabled" : "Disabled"}</Badge>);-const describeChannel = (channel: TChannelForm, members: TProjectMemberEmails): string => {+const describeChannel = (channel: TChannelForm, members: TMemberEmails): string => {switch (channel.channelType) {case AlertChannelType.Email: {const groupCount = channel.recipients.filter(diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.tsindex d4565ebf8d..d03ffb7388 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts@@ -52,7 +52,7 @@ export const formatAlertBefore = (alertBefore?: string | null, fallback = "-"):export const normalizeEmail = (email: string) => email.trim().toLowerCase();-export type TProjectMemberEmails = {+export type TMemberEmails = {emailByUserId: Map<string, string>;memberIdByEmail: Map<string, string>;isAvailable: boolean;@@ -60,7 +60,7 @@ export type TProjectMemberEmails = {export const toRecipientEmails = (recipients: TAlertChannelRecipient[],- { emailByUserId }: Pick<TProjectMemberEmails, "emailByUserId">+ { emailByUserId }: Pick<TMemberEmails, "emailByUserId">) =>recipients.flatMap((recipient) => {if (recipient.principalType === AlertPrincipalType.User) {@@ -140,7 +140,7 @@ export const emptyCertificateAlertForm = (export const toCertificateAlertForm = (alert: TAlert,- { emailByUserId, isAvailable }: Pick<TProjectMemberEmails, "emailByUserId" | "isAvailable">+ { emailByUserId, isAvailable }: Pick<TMemberEmails, "emailByUserId" | "isAvailable">): TCertificateAlertForm => ({eventType: alert.eventType as CertificateAlertEventType,name: alert.name,diff --git a/frontend/src/views/Alerts/AddChannelMenu.tsx b/frontend/src/views/Alerts/AddChannelMenu.tsxindex ed9c06f601..a3741898a9 100644--- a/frontend/src/views/Alerts/AddChannelMenu.tsx+++ b/frontend/src/views/Alerts/AddChannelMenu.tsx@@ -17,23 +17,27 @@ type Props = {isDisabled?: boolean;lockedChannelTypes?: AlertChannelType[];onLockedSelect?: () => void;+ label?: string;+ contentClassName?: string;};export const AddChannelMenu = ({onAdd,isDisabled,lockedChannelTypes = [],- onLockedSelect+ onLockedSelect,+ label = "Add channel",+ contentClassName = "w-[var(--radix-dropdown-menu-trigger-width)]"}: Props) => (<DropdownMenu><DropdownMenuTrigger asChild><Button type="button" variant="outline" size="sm" isDisabled={isDisabled}><PlusIcon className="size-4" />- Add Channel+ {label}<ChevronDownIcon className="size-4" /></Button></DropdownMenuTrigger>- <DropdownMenuContent align="end" sideOffset={4} className="min-w-56">+ <DropdownMenuContent align="end" sideOffset={4} className={contentClassName}>{Object.values(AlertChannelType).map((channelType) => {const Icon = getChannelIcon(channelType);const isLocked = lockedChannelTypes.includes(channelType);diff --git a/frontend/src/views/Alerts/ChannelCard.tsx b/frontend/src/views/Alerts/ChannelCard.tsxindex d78b482e68..7ef4deb6a8 100644--- a/frontend/src/views/Alerts/ChannelCard.tsx+++ b/frontend/src/views/Alerts/ChannelCard.tsx@@ -42,6 +42,7 @@ type Props = {projectId?: string;resourceType: string;resourceId?: string | null;+ alertId?: string;onRemove: () => void;canRemove: boolean;renderRecipients?: (props: TChannelRecipientsRenderProps) => ReactElement;@@ -89,6 +90,7 @@ export const ChannelCard = ({projectId,resourceType,resourceId,+ alertId,onRemove,canRemove,renderRecipients@@ -120,6 +122,7 @@ export const ChannelCard = ({resourceType,resourceId,projectId: projectId ?? null,+ alertId,channelId: channel?.id,channelType,config,diff --git a/frontend/src/views/Alerts/ChannelRecipientsField.tsx b/frontend/src/views/Alerts/ChannelRecipientsField.tsxindex 7e78761e69..3a132981a6 100644--- a/frontend/src/views/Alerts/ChannelRecipientsField.tsx+++ b/frontend/src/views/Alerts/ChannelRecipientsField.tsx@@ -112,7 +112,7 @@ const RecipientSelect = ({);};-const canReceiveAlerts = (membership: { isActive: boolean; status: string }) =>+export const canReceiveAlerts = (membership: { isActive: boolean; status: string }) =>membership.isActive && membership.status !== "invited";const OrgRecipientSelect = ({ orgId, ...props }: SelectProps & { orgId: string }) => {diff --git a/frontend/src/views/Alerts/ChannelsField.tsx b/frontend/src/views/Alerts/ChannelsField.tsxindex 6c6be485bd..f87fd4633e 100644--- a/frontend/src/views/Alerts/ChannelsField.tsx+++ b/frontend/src/views/Alerts/ChannelsField.tsx@@ -18,7 +18,7 @@ type Props = {resourceId?: string | null;};-export const buildNewChannel = (channelType: AlertChannelType, name: string): TChannelForm => ({+const buildNewChannel = (channelType: AlertChannelType, name: string): TChannelForm => ({channelType,name,enabled: true,@@ -29,13 +29,14 @@ export const buildNewChannel = (channelType: AlertChannelType, name: string): TCintegrationKey: ""});-export const getNextChannelName = (takenNames: Set<string>, channelType: AlertChannelType) => {+export const buildNextChannel = (existing: { name: string }[], channelType: AlertChannelType) => {+ const takenNames = new Set(existing.map((channel) => channel.name));const baseName = ALERT_CHANNEL_TYPE_LABELS[channelType];let name = baseName;for (let suffix = 2; takenNames.has(name); suffix += 1) {name = `${baseName} ${suffix}`;}- return name;+ return buildNewChannel(channelType, name);};export const ChannelsField = ({ projectId, resourceType, resourceId }: Props) => {@@ -50,8 +51,7 @@ export const ChannelsField = ({ projectId, resourceType, resourceId }: Props) =>// The name input was dropped from the design; new channels are named after their type,// suffixed to stay unique so multiples remain distinguishable (e.g. in Terraform).const appendChannel = (channelType: AlertChannelType) => {- const takenNames = new Set((getValues("channels") ?? []).map((channel) => channel.name));- append(buildNewChannel(channelType, getNextChannelName(takenNames, channelType)));+ append(buildNextChannel(getValues("channels") ?? [], channelType));};return (diff --git a/frontend/src/views/Alerts/index.ts b/frontend/src/views/Alerts/index.tsindex ec302873d3..6c261bf074 100644--- a/frontend/src/views/Alerts/index.ts+++ b/frontend/src/views/Alerts/index.ts@@ -2,4 +2,5 @@ export { AddAlertModal } from "./AddAlertModal";export { AddChannelMenu } from "./AddChannelMenu";export { AlertAction } from "./AlertAction";export { ChannelCard, type TChannelRecipientsRenderProps } from "./ChannelCard";-export { buildNewChannel, getNextChannelName } from "./ChannelsField";+export { canReceiveAlerts } from "./ChannelRecipientsField";+export { buildNextChannel } from "./ChannelsField";