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
feat(alerts): add audit-log.stream alert provider
Calvin396607e6a7e5
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 47c62670a7..484fd2bc00 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -708,7 +708,7 @@ Adding a new alertable resource type:1. Implement `IResourceAlertProvider` (`alert-types.ts`) in `src/services/alert/providers/<name>-alert-provider.ts`, with its DAL alongside it. You supply: a dot-namespaced `resourceType` (e.g. `identity.authentication`), an `events` list (each event carries its own `conditionSchema` for the "when", so a scheduled expiry and an event-triggered change on the same resource type don't share one shape), `buildViewUrl` / `buildPayload` / `targetId`, one discovery method per trigger type you declare (below), and the two authorization hooks `assertPermission` + `assertResourceInScope`. Test sends need nothing from you: they go through the generic `buildTestAlertPayload` (`alert-test-payload-fns.ts`).2. Register it on the singleton registry in `src/server/routes/index.ts` (`alertProviderRegistry.register(...)`).-That's it — CRUD routes, channel creation/rotation, recipient resolution, KMS encryption, dedup, history, retention pruning, test sends, and dispatch metrics all come for free, because the cron tick enumerates `alertProviderRegistry.resourceTypes()`. See `src/services/alert/providers/identity-credential-alert-provider.ts` for a complete example that declares both trigger types (`identity.authentication.expiry` scheduled, `identity.authentication.auth-method-changed` event-triggered).+That's it — CRUD routes, channel creation/rotation, recipient resolution, KMS encryption, dedup, history, retention pruning, test sends, and dispatch metrics all come for free, because the cron tick enumerates `alertProviderRegistry.resourceTypes()`. See `src/services/alert/providers/identity-credential-alert-provider.ts` for a complete example that declares both trigger types (`identity.authentication.expiry` scheduled, `identity.authentication.auth-method-changed` event-triggered). `audit-log-stream-alert-provider.ts` is the smallest event-only example: the stream delivery path emits `audit-log.stream.delivery-failed` (contract in `ee/services/audit-log-stream/audit-log-stream-events.ts`) only on the healthy to failing edge, in the transaction that drops the rows, and `auditLogStreamService.deleteById` reaps the stream's alerts.**Each event declares how it fires**, and the trigger decides which discovery method the provider owes:diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-service.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-service.tsindex 015d5bf648..3ed6c238b8 100644--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-service.ts+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-service.ts@@ -9,6 +9,7 @@ import {} from "@app/ee/services/audit-log-stream/audit-log-stream-fns";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { OrgServiceActor } from "@app/lib/types";+import { TAlertServiceFactory } from "@app/services/alert/alert-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TLicenseServiceFactory } from "../license/license-service";@@ -16,6 +17,7 @@ import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-pimport { TPermissionServiceFactory } from "../permission/permission-service-types";import { TAuditLogStreamDALFactory } from "./audit-log-stream-dal";import { LogProvider, REDACTED_CREDENTIAL_VALUE, StreamMode } from "./audit-log-stream-enums";+import { AUDIT_LOG_STREAM_RESOURCE_TYPE } from "./audit-log-stream-events";import { LOG_STREAM_FACTORY_MAP } from "./audit-log-stream-factory";import { TAuditLogStream, TCreateAuditLogStreamDTO, TUpdateAuditLogStreamDTO } from "./audit-log-stream-types";import { TCustomProviderCredentials } from "./custom/custom-provider-types";@@ -27,6 +29,7 @@ export type TAuditLogStreamServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ alertService: Pick<TAlertServiceFactory, "deleteAlertsForDeletedResource">;};export type TAuditLogStreamServiceFactory = ReturnType<typeof auditLogStreamServiceFactory>;@@ -35,7 +38,8 @@ export const auditLogStreamServiceFactory = ({auditLogStreamDAL,permissionService,licenseService,- kmsService+ kmsService,+ alertService}: TAuditLogStreamServiceFactoryDep) => {const create = async ({ provider, credentials, filters }: TCreateAuditLogStreamDTO, actor: OrgServiceActor) => {const plan = await licenseService.getPlan(actor.orgId);@@ -233,7 +237,13 @@ export const auditLogStreamServiceFactory = ({});}- const deletedLogStream = await auditLogStreamDAL.deleteById(logStreamId);+ const deletedLogStream = await auditLogStreamDAL.transaction(async (tx) => {+ await alertService.deleteAlertsForDeletedResource(+ { resourceType: AUDIT_LOG_STREAM_RESOURCE_TYPE, resourceId: logStreamId },+ tx+ );+ return auditLogStreamDAL.deleteById(logStreamId, tx);+ });return decryptLogStream(deletedLogStream, kmsService);};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 27c70e1983..54cee45bbd 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -251,6 +251,8 @@ import { alertProviderRegistryFactory } from "@app/services/alert/alert-providerimport { alertQueueServiceFactory } from "@app/services/alert/alert-queue";import { alertRecipientResolverFactory } from "@app/services/alert/alert-recipient-resolver";import { alertServiceFactory } from "@app/services/alert/alert-service";+import { auditLogStreamAlertDALFactory } from "@app/services/alert/providers/audit-log-stream-alert-dal";+import { auditLogStreamAlertProviderFactory } from "@app/services/alert/providers/audit-log-stream-alert-provider";import { certManagerAlertProviderFactory } from "@app/services/alert/providers/cert-manager-alert-provider";import { certManagerApplicationAlertProviderFactory } from "@app/services/alert/providers/cert-manager-application-alert-provider";import { certManagerCertificateAlertDALFactory } from "@app/services/alert/providers/cert-manager-certificate-alert-dal";@@ -1111,6 +1113,12 @@ export const registerRoutes = async (permissionService}));+ alertProviderRegistry.register(+ auditLogStreamAlertProviderFactory({+ auditLogStreamAlertDAL: auditLogStreamAlertDALFactory(db),+ permissionService+ })+ );alertProviderRegistry.register(certManagerApplicationAlertProviderFactory({certManagerCertificateAlertDAL,@@ -1225,7 +1233,8 @@ export const registerRoutes = async (licenseService,permissionService,auditLogStreamDAL,- kmsService+ kmsService,+ alertService});const auditLogStreamOutboxService = auditLogStreamOutboxServiceFactory({diff --git a/backend/src/services/alert/providers/audit-log-stream-alert-dal.ts b/backend/src/services/alert/providers/audit-log-stream-alert-dal.tsnew file mode 100644index 0000000000..3dd443f5a4--- /dev/null+++ b/backend/src/services/alert/providers/audit-log-stream-alert-dal.ts@@ -0,0 +1,47 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";++export type TAuditLogStreamAlertDALFactory = ReturnType<typeof auditLogStreamAlertDALFactory>;++export type TAuditLogStreamRef = {+ id: string;+ provider: string;+};++export const auditLogStreamAlertDALFactory = (db: TDbClient) => {+ const findStreamInOrg = async (+ streamId: string,+ orgId: string,+ tx?: Knex+ ): Promise<TAuditLogStreamRef | undefined> => {+ try {+ const row = (await (tx || db.replicaNode())(TableName.AuditLogStream)+ .where({ id: streamId, orgId })+ .select("id", "provider")+ .first()) as TAuditLogStreamRef | undefined;+ return row;+ } catch (error) {+ throw new DatabaseError({ error, name: "AuditLogStreamAlert: findStreamInOrg" });+ }+ };++ // Primary on purpose: the event is emitted in the transaction that flips the stream to failing, and+ // an empty read here is terminal, so a lagging replica would swallow the notification.+ const findStreamsByIds = async (streamIds: string[], orgId: string): Promise<TAuditLogStreamRef[]> => {+ if (streamIds.length === 0) return [];+ try {+ return (await db+ .primaryNode()(TableName.AuditLogStream)+ .whereIn("id", streamIds)+ .where({ orgId })+ .select("id", "provider")) as TAuditLogStreamRef[];+ } catch (error) {+ throw new DatabaseError({ error, name: "AuditLogStreamAlert: findStreamsByIds" });+ }+ };++ return { findStreamInOrg, findStreamsByIds };+};diff --git a/backend/src/services/alert/providers/audit-log-stream-alert-provider.test.ts b/backend/src/services/alert/providers/audit-log-stream-alert-provider.test.tsnew file mode 100644index 0000000000..a58856d7e0--- /dev/null+++ b/backend/src/services/alert/providers/audit-log-stream-alert-provider.test.ts@@ -0,0 +1,194 @@+import { createMongoAbility } from "@casl/ability";+import { describe, expect, test, vi } from "vitest";++import {+ AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT,+ AUDIT_LOG_STREAM_RESOURCE_TYPE,+ AuditLogStreamDeliveryFailedPayloadSchema,+ emitAuditLogStreamDeliveryFailed+} from "@app/ee/services/audit-log-stream/audit-log-stream-events";+import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";+import { ActorType } from "@app/services/auth/auth-type";++import { AlertPermissionAction, AlertTriggerType, TAlertContext } from "../alert-types";+import { auditLogStreamAlertProviderFactory } from "./audit-log-stream-alert-provider";++vi.mock("@app/lib/config/env", () => ({+ getConfig: () => ({ SITE_URL: "https://app.infisical.com" })+}));++const ORG_ID = "org-1";+const STREAM_ID = "stream-1";+const FAILING_SINCE = new Date("2026-10-07T10:00:00.000Z");++const alertContext = (overrides: Partial<TAlertContext> = {}): TAlertContext => ({+ id: "alert-1",+ name: "stream-down",+ orgId: ORG_ID,+ resourceType: AUDIT_LOG_STREAM_RESOURCE_TYPE,+ resourceId: null,+ eventType: AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT,+ condition: null,+ ...overrides+});++const buildProvider = (abilityRules: Parameters<typeof createMongoAbility>[0] = []) => {+ const auditLogStreamAlertDAL = {+ findStreamInOrg: vi.fn<(id: string, orgId: string) => Promise<{ id: string; provider: string } | undefined>>(+ async (id) => ({ id, provider: "datadog" })+ ),+ findStreamsByIds: vi.fn<(ids: string[], orgId: string) => Promise<{ id: string; provider: string }[]>>(+ async (ids) => ids.map((id) => ({ id, provider: "datadog" }))+ )+ };+ const permissionService = {+ getOrgPermission: vi.fn(async () => ({ permission: createMongoAbility(abilityRules) }))+ };+ const provider = auditLogStreamAlertProviderFactory({+ auditLogStreamAlertDAL: auditLogStreamAlertDAL as never,+ permissionService: permissionService as never+ });+ return { provider, auditLogStreamAlertDAL, permissionService };+};++const actor = { actor: ActorType.USER, actorId: "user-1", actorAuthMethod: null, actorOrgId: ORG_ID };++describe("audit-log-stream alert provider", () => {+ test("declares one event-triggered event", () => {+ const { provider } = buildProvider();+ expect(provider.resourceType).toBe("audit-log.stream");+ expect(provider.events).toHaveLength(1);+ expect(provider.events[0].key).toBe(AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT);+ expect(provider.events[0].triggerType).toBe(AlertTriggerType.Event);+ });++ test("findEventTargets reads what the emit helper writes", async () => {+ const { provider, auditLogStreamAlertDAL } = buildProvider();+ const emit = vi.fn(async () => undefined);+ await emitAuditLogStreamDeliveryFailed(+ { emit },+ {+ orgId: ORG_ID,+ streamId: STREAM_ID,+ provider: "datadog",+ errorMessage: "Request failed with status code 403",+ droppedCount: 3,+ failingSince: FAILING_SINCE+ },+ {} as never+ );+ const { payload } = (emit.mock.calls[0] as unknown as [{ payload: Record<string, unknown> }])[0];++ expect(AuditLogStreamDeliveryFailedPayloadSchema.safeParse(payload).success).toBe(true);++ const targets = await provider.findEventTargets({+ orgId: ORG_ID,+ eventType: AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT,+ condition: null,+ targetIds: payload.targetIds as string[],+ payload+ });++ expect(auditLogStreamAlertDAL.findStreamsByIds).toHaveBeenCalledWith([STREAM_ID], ORG_ID);+ expect(targets).toEqual([+ {+ streamId: STREAM_ID,+ provider: "datadog",+ errorMessage: "Request failed with status code 403",+ droppedCount: 3,+ failingSince: FAILING_SINCE+ }+ ]);+ });++ test("findEventTargets drops a stream deleted before delivery", async () => {+ const { provider, auditLogStreamAlertDAL } = buildProvider();+ auditLogStreamAlertDAL.findStreamsByIds.mockResolvedValueOnce([]);++ const targets = await provider.findEventTargets({+ orgId: ORG_ID,+ eventType: AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT,+ condition: null,+ targetIds: [STREAM_ID],+ payload: {+ provider: "datadog",+ errorMessage: "boom",+ droppedCount: 1,+ failingSince: FAILING_SINCE.toISOString()+ }+ });++ expect(targets).toEqual([]);+ });++ test("findEventTargets throws on an unreadable payload", async () => {+ const { provider } = buildProvider();+ await expect(+ provider.findEventTargets({+ orgId: ORG_ID,+ eventType: AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT,+ condition: null,+ targetIds: [STREAM_ID],+ payload: {}+ })+ ).rejects.toThrow(/Unreadable/);+ });++ test("buildPayload names the stream, error and drop count and links to the streams tab", async () => {+ const { provider } = buildProvider();+ const viewUrl = await provider.buildViewUrl(alertContext());+ expect(viewUrl).toBe("https://app.infisical.com/organizations/org-1/audit-logs?selectedTab=streams");++ const payload = provider.buildPayload(+ alertContext(),+ [+ {+ streamId: STREAM_ID,+ provider: "sumo-logic",+ errorMessage: "timeout of 5000ms exceeded",+ droppedCount: 12,+ failingSince: FAILING_SINCE+ }+ ],+ viewUrl+ );++ expect(payload.severity).toBe("critical");+ expect(payload.summary).toContain("Sumo Logic");+ expect(payload.items[0].id).toBe(provider.targetId({ streamId: STREAM_ID } as never));+ expect(payload.items[0].fields).toEqual(+ expect.arrayContaining([+ { label: "Error", value: "timeout of 5000ms exceeded" },+ { label: "Dropped Events", value: "12" }+ ])+ );+ });++ test("assertResourceInScope rejects a stream from another org", async () => {+ const { provider, auditLogStreamAlertDAL } = buildProvider();+ auditLogStreamAlertDAL.findStreamInOrg.mockResolvedValueOnce(undefined);++ await expect(provider.assertResourceInScope({ orgId: ORG_ID, resourceId: STREAM_ID })).rejects.toThrow(+ /not found in this organization/+ );+ await expect(provider.assertResourceInScope({ orgId: ORG_ID, resourceId: null })).resolves.toBeUndefined();+ });++ test("assertPermission needs settings read to read and settings edit to write", async () => {+ const reader = buildProvider([{ action: OrgPermissionActions.Read, subject: OrgPermissionSubjects.Settings }]);+ await expect(+ reader.provider.assertPermission({ action: AlertPermissionAction.Read, orgId: ORG_ID, actor })+ ).resolves.toBeUndefined();+ await expect(+ reader.provider.assertPermission({ action: AlertPermissionAction.Create, orgId: ORG_ID, actor })+ ).rejects.toThrow();++ const editor = buildProvider([+ { action: OrgPermissionActions.Read, subject: OrgPermissionSubjects.Settings },+ { action: OrgPermissionActions.Edit, subject: OrgPermissionSubjects.Settings }+ ]);+ await expect(+ editor.provider.assertPermission({ action: AlertPermissionAction.Create, orgId: ORG_ID, actor })+ ).resolves.toBeUndefined();+ });+});diff --git a/backend/src/services/alert/providers/audit-log-stream-alert-provider.ts b/backend/src/services/alert/providers/audit-log-stream-alert-provider.tsnew file mode 100644index 0000000000..cb63d11f45--- /dev/null+++ b/backend/src/services/alert/providers/audit-log-stream-alert-provider.ts@@ -0,0 +1,179 @@+import { ForbiddenError } from "@casl/ability";+import { z } from "zod";++import { OrganizationActionScope } from "@app/db/schemas";+import {+ AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT,+ AUDIT_LOG_STREAM_RESOURCE_TYPE,+ AuditLogStreamDeliveryFailedPayloadSchema+} from "@app/ee/services/audit-log-stream/audit-log-stream-events";+import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { getConfig } from "@app/lib/config/env";+import { NotFoundError } from "@app/lib/errors";++import { TAlertPayload } from "../alert-channel-types";+import {+ AlertPermissionAction,+ AlertTriggerType,+ IEventAlertProvider,+ TAlertContext,+ TAlertPermissionInput,+ TFindEventTargetsInput+} from "../alert-types";+import { TAuditLogStreamAlertDALFactory } from "./audit-log-stream-alert-dal";++export { AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT, AUDIT_LOG_STREAM_RESOURCE_TYPE };++const DeliveryFailedConditionSchema = z.object({}).nullish();++const PROVIDER_LABELS: Record<string, string> = {+ azure: "Azure",+ cribl: "Cribl",+ custom: "Custom",+ datadog: "Datadog",+ splunk: "Splunk",+ "sumo-logic": "Sumo Logic"+};++type TAuditLogStreamTarget = {+ streamId: string;+ provider: string;+ errorMessage: string;+ droppedCount: number;+ failingSince: Date;+};++export type TAuditLogStreamAlertProviderDep = {+ auditLogStreamAlertDAL: TAuditLogStreamAlertDALFactory;+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;+};++const formatUtcDate = (date: Date): string =>+ new Date(date).toLocaleString("en-US", {+ year: "numeric",+ month: "long",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ timeZone: "UTC",+ timeZoneName: "short"+ });++export const auditLogStreamAlertProviderFactory = ({+ auditLogStreamAlertDAL,+ permissionService+}: TAuditLogStreamAlertProviderDep): IEventAlertProvider<TAuditLogStreamTarget> => {+ const buildViewUrl = async (alert: TAlertContext): Promise<string> =>+ `${getConfig().SITE_URL}/organizations/${alert.orgId}/audit-logs?selectedTab=streams`;++ const findEventTargets = async (input: TFindEventTargetsInput): Promise<TAuditLogStreamTarget[]> => {+ const parsed = AuditLogStreamDeliveryFailedPayloadSchema.safeParse(input.payload);+ if (!parsed.success) {+ throw new Error(+ `Unreadable '${AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT}' payload: ${parsed.error.issues+ .map((issue) => `${issue.path.join(".")} ${issue.message}`)+ .join(", ")}`+ );+ }++ const streams = await auditLogStreamAlertDAL.findStreamsByIds(input.targetIds, input.orgId);++ return streams.map((stream) => ({+ streamId: stream.id,+ provider: stream.provider,+ errorMessage: parsed.data.errorMessage,+ droppedCount: parsed.data.droppedCount,+ failingSince: parsed.data.failingSince+ }));+ };++ const buildPayload = (alert: TAlertContext, targets: TAuditLogStreamTarget[], viewUrl: string): TAlertPayload => {+ const [first] = targets;+ const providerLabel = (target: TAuditLogStreamTarget) => PROVIDER_LABELS[target.provider] ?? target.provider;++ return {+ alert: {+ id: alert.id,+ name: alert.name,+ orgId: alert.orgId,+ resourceType: alert.resourceType,+ viewUrl+ },+ eventKey: AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT,+ eventLabel: "Delivery Failed",+ webhookType: "com.infisical.audit-log.stream.delivery-failed",+ resourceKind: "Audit Log Stream",+ resourceOwnerKind: "Organization",+ severity: "critical",+ summary:+ targets.length === 1+ ? `Audit log events are being dropped because the ${providerLabel(first)} stream cannot be reached`+ : `Audit log events are being dropped on ${targets.length} streams`,+ items: targets.map((target) => ({+ id: target.streamId,+ title: `${providerLabel(target)} stream`,+ identifier: target.streamId,+ fields: [+ { label: "Provider", value: providerLabel(target) },+ { label: "Error", value: target.errorMessage },+ { label: "Dropped Events", value: String(target.droppedCount) },+ { label: "Failing Since", value: formatUtcDate(target.failingSince) }+ ]+ }))+ };+ };++ const assertResourceInScope = async (input: {+ orgId: string;+ projectId?: string | null;+ resourceId?: string | null;+ }): Promise<void> => {+ if (!input.resourceId) return;++ const stream = await auditLogStreamAlertDAL.findStreamInOrg(input.resourceId, input.orgId);+ if (!stream) {+ throw new NotFoundError({ message: `Audit Log Stream '${input.resourceId}' was not found in this organization` });+ }+ };++ const assertPermission = async (input: TAlertPermissionInput): Promise<void> => {+ const { permission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor: input.actor.actor,+ actorId: input.actor.actorId,+ orgId: input.orgId,+ actorAuthMethod: input.actor.actorAuthMethod,+ actorOrgId: input.actor.actorOrgId+ });++ const actions = (() => {+ if (input.action === AlertPermissionAction.Read) return [OrgPermissionActions.Read];+ if (input.action === AlertPermissionAction.Delete) return [OrgPermissionActions.Edit];+ return [OrgPermissionActions.Edit, OrgPermissionActions.Read];+ })();++ for (const action of actions) {+ ForbiddenError.from(permission).throwUnlessCan(action, OrgPermissionSubjects.Settings);+ }+ };++ return {+ resourceType: AUDIT_LOG_STREAM_RESOURCE_TYPE,+ events: [+ {+ key: AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT,+ triggerType: AlertTriggerType.Event,+ conditionSchema: DeliveryFailedConditionSchema+ }+ ],+ supportsScopeWideAlerts: true,+ recipientPolicy: { atOrgScope: true },+ findEventTargets,+ buildViewUrl,+ buildPayload,+ targetId: (target) => target.streamId,+ assertPermission,+ assertResourceInScope+ };+};