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
fix(audit-log-stream): bound stale-claim sweeps and keep a failed alert from blocking delivery
Calvin4b46d093465b
diff --git a/backend/e2e-test/audit-log-stream-outbox.integration.spec.ts b/backend/e2e-test/audit-log-stream-outbox.integration.spec.tsindex a98c084894..2842d6dcdc 100644--- a/backend/e2e-test/audit-log-stream-outbox.integration.spec.ts+++ b/backend/e2e-test/audit-log-stream-outbox.integration.spec.ts@@ -345,7 +345,7 @@ describe("audit log stream outbox (postgres)", () => {expect(await outboxRow(rowId)).toBeUndefined();const health = await streamHealth(stream.id);expect(health?.failingSince).toBeInstanceOf(Date);- expect(health?.lastDeliveryError).toContain("Failed to decrypt stream credentials");+ expect(health?.lastDeliveryError).toContain("Could not decrypt this stream's credentials");expect(await events()).toHaveLength(1);});});diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.tsindex d255d6c5fd..eb5317aea2 100644--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts@@ -18,6 +18,7 @@ export type TInsertOutboxRow = {};const OUTBOX_INSERT_CHUNK_SIZE = 1_000;+const STALE_SWEEP_STATEMENT_TIMEOUT_MS = 30_000;export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {const batchInsert = async (rows: TInsertOutboxRow[], tx?: Knex) => {@@ -175,6 +176,10 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {tx: Knex): Promise<{ retried: number; dropped: { streamId: string; orgId: string; provider: string | null }[] }> => {try {+ // SET LOCAL lasts until the caller's transaction ends, so it also bounds the stream writes the+ // sweeper makes in the same batch after this returns.+ await tx.raw(`SET LOCAL statement_timeout = ${STALE_SWEEP_STATEMENT_TIMEOUT_MS}`);+const staleRows = await tx(TableName.AuditLogStreamOutbox).where("status", AuditLogStreamOutboxStatus.Processing).andWhereRaw(`"lockedAt" < NOW() - (? || ' milliseconds')::INTERVAL`, [thresholdMs])@@ -294,7 +299,8 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {// Flips the stream to failing only if it was healthy, so the caller emits the alert event on// the null -> set edge exactly once even when two workers race. Returns the timestamp it set,- // or null when the stream was already failing (or no longer exists).+ // or null when the stream was already failing (or no longer exists). An already failing stream+ // still gets the latest drop reason, so lastDeliveryError never reports a cause that was fixed.const markStreamFailing = async ({ streamId, errorMessage }: { streamId: string; errorMessage: string },tx: Knex@@ -305,7 +311,10 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {.whereNull("failingSince").update({ failingSince: new Date(), lastDeliveryError: errorMessage }).returning<{ failingSince: Date }[]>("failingSince");- return row?.failingSince ?? null;+ if (row) return row.failingSince;++ await tx(TableName.AuditLogStream).where("id", streamId).update({ lastDeliveryError: errorMessage });+ return null;} catch (error) {throw new DatabaseError({ error, name: "AuditLogStreamOutbox: markStreamFailing" });}diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.tsindex 59b666c509..777f58aea1 100644--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts@@ -80,7 +80,9 @@ const buildRow = (overrides: Partial<TAuditLogStreamOutboxRow> = {}): TAuditLogS...overrides});-const TX = { tx: true };+// flagStreamFailing opens a savepoint on the transaction it is given; handing back TX keeps the+// DAL calls inside it asserting against the same object.+const TX = { tx: true, transaction: async (cb: (savepoint: unknown) => Promise<unknown>) => cb(TX) };const createService = () => {const auditLogStreamOutboxDAL = {diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.tsindex 5c6c613426..f66c86558a 100644--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts@@ -54,6 +54,8 @@ const STALE_SWEEP_BATCH_SIZE = 1_000;const STALE_SWEEP_MAX_BATCHES = 10;// Shown to customers in the delivery-failed alert, where a stale claim has no provider error to report.const STALE_CLAIM_DROP_MESSAGE = "Events were dropped because the delivery worker stopped during their final attempt.";+const STREAM_CREDENTIALS_DECRYPT_MESSAGE =+ "Could not decrypt this stream's credentials. Check that the organization's KMS key is available, then update the stream's credentials.";// Retention for 'delivered' outbox rows. The row is the dedup guard against a// re-fanout from the ingest consumer (e.g. after a Redis streamTrim failure),@@ -219,14 +221,31 @@ export const auditLogStreamOutboxServiceFactory = ({// rejects payloads over 16KB, and a throw from emit here would roll back the drop and leave the// stream unflagged with no alert.const boundedError = errorMessage.slice(0, 500);- const failingSince = await auditLogStreamOutboxDAL.markStreamFailing({ streamId, errorMessage: boundedError }, tx);- if (!failingSince) return;- await emitAuditLogStreamDeliveryFailed(- eventEmitter,- { orgId, streamId, provider, errorMessage: boundedError, droppedCount, failingSince },- tx- );+ // A savepoint, so a failed flag or emit rolls back on its own instead of taking the drop (or the+ // sweeper's whole batch) with it. A plain try/catch is not enough: a failed insert aborts the+ // outer transaction and its next statement fails with 25P02. The flag and the event roll back+ // together, so the stream stays healthy and the next drop tries again.+ try {+ await tx.transaction(async (savepoint) => {+ const failingSince = await auditLogStreamOutboxDAL.markStreamFailing(+ { streamId, errorMessage: boundedError },+ savepoint+ );+ if (!failingSince) return;++ await emitAuditLogStreamDeliveryFailed(+ eventEmitter,+ { orgId, streamId, provider, errorMessage: boundedError, droppedCount, failingSince },+ savepoint+ );+ });+ } catch (error) {+ logger.error(+ error,+ `audit-log-stream-outbox: failed to flag stream as failing, no alert was sent [streamId=${streamId}] [orgId=${orgId}] [provider=${provider}]`+ );+ }};// Worker entrypoint. Loops claim→send→ack while there are still rows pending@@ -258,7 +277,12 @@ export const auditLogStreamOutboxServiceFactory = ({kmsService});} catch (error) {- credentialsError = new Error(`Failed to decrypt stream credentials: ${(error as Error)?.message}`);+ // This message reaches the alert and the stream's lastDeliveryError, so the KMS detail stays in the log.+ logger.error(+ error,+ `audit-log-stream-outbox: failed to decrypt stream credentials [streamId=${streamId}] [orgId=${orgId}] [provider=${provider}]`+ );+ credentialsError = new Error(STREAM_CREDENTIALS_DECRYPT_MESSAGE);}const providerImpl = factory();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.tsindex aa5736e2ef..f988ee1d0d 100644--- a/backend/src/services/alert/providers/audit-log-stream-alert-provider.ts+++ b/backend/src/services/alert/providers/audit-log-stream-alert-provider.ts@@ -14,6 +14,7 @@ import { getConfig } from "@app/lib/config/env";import { BadRequestError } from "@app/lib/errors";import { TAlertPayload } from "../alert-channel-types";+import { formatUtcDate } from "../alert-format-fns";import {AlertPermissionAction,AlertTriggerType,@@ -43,17 +44,6 @@ export type TAuditLogStreamAlertProviderDep = {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@@ -102,7 +92,7 @@ export const auditLogStreamAlertProviderFactory = ({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 the ${providerLabel(first)} stream`: `Audit log events are being dropped on ${targets.length} streams`,items: targets.map((target) => ({id: target.streamId,diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.tsindex e7c403748d..049960698a 100644--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@ -95,7 +95,7 @@ export const ALERT_EVENT_TYPE_DESCRIPTIONS: Record<AlertEventType, string> = {[AlertEventType.IdentityAuthMethodChanged]:"Notify whenever an auth method is added, updated, or removed, or one of its credentials is created, updated, or revoked.",[AlertEventType.AuditLogStreamDeliveryFailed]:- "Notify when an external log stream cannot be reached and audit log events are being dropped."+ "Notify when audit log events are being dropped because an external log stream keeps failing to deliver them."};export const ALERT_CHANNEL_TYPE_LABELS: Record<AlertChannelType, string> = {