Skip to content

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

keep retro compatibility with existing events after pre stream enrich

Thiago Araujo da Silva0329c3d36194
diff --git a/backend/src/db/migrations/20260601120000_audit-log-stream-mode.ts b/backend/src/db/migrations/20260601120000_audit-log-stream-mode.ts
index 37881fac09..c7f68cc9f5 100644
--- a/backend/src/db/migrations/20260601120000_audit-log-stream-mode.ts
+++ b/backend/src/db/migrations/20260601120000_audit-log-stream-mode.ts
@@ -13,11 +13,14 @@ export async function up(knex: Knex): Promise<void> {
t.string(STREAM_MODE_COLUMN).notNullable().defaultTo("batch");
});
- // Existing custom streams predate batched delivery and rely on one-event-per-request
- // POSTs. Keep them on "single" so we don't break their receivers; everything else
- // (vendor providers + all new streams) stays on the "batch" default.
+ // Existing custom and cribl streams predate batched delivery and rely on one-event-per-request
+ // POSTs (custom: a single JSON object; cribl: a single application/json body — not the NDJSON
+ // batch shape). Keep them on "single" so we don't break their receivers; everything else
+ // (other vendor providers + all new streams) stays on the "batch" default.
// Raw update because the column was just added and isn't in the generated types yet.
- await knex(TableName.AuditLogStream).where("provider", "custom").update(STREAM_MODE_COLUMN, "single");
+ await knex(TableName.AuditLogStream)
+ .whereIn("provider", ["custom", "cribl"])
+ .update(STREAM_MODE_COLUMN, "single");
}
}
}
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.ts
index c125d6e778..0f0fdcaa5e 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
@@ -189,7 +189,7 @@ export const auditLogStreamOutboxServiceFactory = ({
const providerImpl = factory();
- // "single" streams (legacy custom webhooks) get one event per request; everything
+ // "single" streams (legacy custom/cribl receivers) get one event per request; everything
// else gets a JSON array per request. Single mode treats each row as its own chunk.
const isSingleMode = stream.streamMode === StreamMode.Single;
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.ts
index 968458ebbf..f48e01e794 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
@@ -75,7 +75,7 @@ export const auditLogStreamServiceFactory = ({
provider,
encryptedCredentials,
// All new streams use batch delivery. "single" is reachable only by existing
- // custom streams that were migrated, and only as a one-way upgrade away from it.
+ // custom/cribl streams that were migrated, and only as a one-way upgrade away from it.
streamMode: StreamMode.Batch
});
diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts
index 955d7fc37f..cdd4f33c2e 100644
--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts
+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts
@@ -39,7 +39,7 @@ export type TLogStreamFactoryBatchStreamLog<C extends TAuditLogStreamCredentials
}) => Promise<void>;
// Single-event delivery: one log POSTed per request. Only providers that support
-// the legacy "single" stream mode (custom) implement this.
+// the legacy "single" stream mode (custom, cribl) implement this.
export type TLogStreamFactoryStreamLog<C extends TAuditLogStreamCredentials> = (input: {
credentials: C;
auditLog: TAuditLogs;
@@ -56,6 +56,6 @@ export type TLogStreamFactory<C extends TAuditLogStreamCredentials> = () => {
validateCredentials: TLogStreamFactoryValidateCredentials<C>;
batchStreamLog: TLogStreamFactoryBatchStreamLog<C>;
getProviderBatchLimit: TLogStreamFactoryGetProviderBatchLimit;
- // Present only for providers that support "single" stream mode (custom).
+ // Present only for providers that support "single" stream mode (custom, cribl).
streamLog?: TLogStreamFactoryStreamLog<C>;
};
diff --git a/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts b/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
index 73040a40b4..3a266ae5c0 100644
--- a/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
@@ -73,7 +73,6 @@ export const AzureProviderFactory = () => {
return credentials;
};
- // Azure Logs Ingestion API natively accepts a JSON array of events per request.
const batchStreamLog: TLogStreamFactoryBatchStreamLog<TAzureProviderCredentials> = async ({
credentials,
auditLogs
diff --git a/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts b/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts
index aff688699d..5b66586b69 100644
--- a/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts
@@ -8,6 +8,7 @@ import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../
import {
TLogStreamFactoryBatchStreamLog,
TLogStreamFactoryGetProviderBatchLimit,
+ TLogStreamFactoryStreamLog,
TLogStreamFactoryValidateCredentials
} from "../audit-log-stream-types";
import { TCriblProviderCredentials } from "./cribl-provider-types";
@@ -61,6 +62,22 @@ export const CriblProviderFactory = () => {
});
};
+ const streamLog: TLogStreamFactoryStreamLog<TCriblProviderCredentials> = async ({ credentials, auditLog }) => {
+ const { url, token } = credentials;
+
+ await blockLocalAndPrivateIpAddresses(url);
+
+ const streamHeaders: RawAxiosRequestHeaders = {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`
+ };
+
+ await request.post(url, JSON.stringify(auditLog), {
+ headers: streamHeaders,
+ timeout: AUDIT_LOG_STREAM_TIMEOUT
+ });
+ };
+
const getProviderBatchLimit: TLogStreamFactoryGetProviderBatchLimit = () => ({
maxLogs: 900,
maxBytes: 4 * 1024 * 1024
@@ -69,6 +86,7 @@ export const CriblProviderFactory = () => {
return {
validateCredentials,
batchStreamLog,
+ streamLog,
getProviderBatchLimit
};
};
diff --git a/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts b/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts
index 36395ae9fb..2be7d3eba4 100644
--- a/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts
@@ -45,7 +45,6 @@ export const CustomProviderFactory = () => {
return credentials;
};
- // Custom webhook receivers get a JSON array of events per batch POST.
const batchStreamLog: TLogStreamFactoryBatchStreamLog<TCustomProviderCredentials> = async ({
credentials,
auditLogs
@@ -70,8 +69,6 @@ export const CustomProviderFactory = () => {
});
};
- // Legacy single-event delivery: each log is POSTed individually as a JSON object.
- // Streams migrated to "single" mode keep this shape so their receivers don't break.
const streamLog: TLogStreamFactoryStreamLog<TCustomProviderCredentials> = async ({ credentials, auditLog }) => {
const { url, headers } = credentials;
diff --git a/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts b/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts
index 52c943a439..f181fbc31e 100644
--- a/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts
@@ -49,7 +49,6 @@ export const DatadogProviderFactory = () => {
return credentials;
};
- // Datadog v2 logs intake accepts a JSON array of events in a single POST.
const batchStreamLog: TLogStreamFactoryBatchStreamLog<TDatadogProviderCredentials> = async ({
credentials,
auditLogs
diff --git a/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts b/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts
index 2f7f5558ef..0053107e82 100644
--- a/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts
@@ -63,7 +63,6 @@ export const SplunkProviderFactory = () => {
return credentials;
};
- // Splunk HEC accepts multiple events in a single POST as concatenated JSON objects (no separator required).
const batchStreamLog: TLogStreamFactoryBatchStreamLog<TSplunkProviderCredentials> = async ({
credentials,
auditLogs
diff --git a/backend/src/ee/services/audit-log/audit-log-queue.test.ts b/backend/src/ee/services/audit-log/audit-log-queue.test.ts
index ef18aec648..3b068b3ae9 100644
--- a/backend/src/ee/services/audit-log/audit-log-queue.test.ts
+++ b/backend/src/ee/services/audit-log/audit-log-queue.test.ts
@@ -46,6 +46,23 @@ const streamEntry = (overrides: Record<string, unknown> = {}) => ({
...overrides
});
+const legacyEntry = (overrides: Record<string, unknown> = {}) => ({
+ id: "legacy-1",
+ actor: "platform",
+ actorMetadata: { k: "v" },
+ ipAddress: "",
+ eventType: "legacy-event",
+ eventMetadata: { e: "m" },
+ userAgent: "",
+ userAgentType: "",
+ projectId: "",
+ orgId: "org-1",
+ createdAt: new Date("2026-05-27T00:00:00.000Z").toISOString(),
+ expiresAt: new Date("2026-06-26T00:00:00.000Z").toISOString(),
+ updatedAt: new Date("2026-05-27T00:00:00.000Z").toISOString(),
+ ...overrides
+});
+
// streamCollect returns [entryId, ["data", json]] tuples; the consumer parses fields[1].
const collectResult = (payloads: Record<string, unknown>[], lastId = "9-0") => ({
entries: payloads.map((p, i) => [`${i + 1}-0`, ["data", JSON.stringify(p)]] as [string, string[]]),
@@ -381,6 +398,51 @@ describe("audit-log-queue unified consumer", () => {
expect(rows[0].id).toBe("ok");
});
+ test("drains legacy flat entries (rolling deploy) instead of choking on the missing event object", async () => {
+ const { consumer, clickhouseClient, keyStore } = await createHarness({ clickhouse: true });
+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([legacyEntry({ id: "legacy-A" })]));
+
+ await consumer();
+
+ expect(clickhouseClient!.insert).toHaveBeenCalledTimes(1);
+ const row = clickhouseClient!.insert.mock.calls[0][0].values[0];
+ expect(row.id).toBe("legacy-A");
+ expect(row.actor).toBe("platform");
+ expect(row.eventType).toBe("legacy-event");
+ // timestamps are re-hydrated from ISO strings into Date instances for insertion
+ expect(row.createdAt).toBeInstanceOf(Date);
+ expect(row.expiresAt).toBeInstanceOf(Date);
+ expect(keyStore.streamTrim).toHaveBeenCalledWith(STREAM_KEY, "9-0", true);
+ });
+
+ test("a legacy entry at the head does not abort the batch (no poison-pill stall)", async () => {
+ const { consumer, clickhouseClient, keyStore } = await createHarness({ clickhouse: true });
+ keyStore.streamCollect.mockResolvedValueOnce(
+ collectResult([legacyEntry({ id: "legacy-head" }), streamEntry({ id: "current-tail" })])
+ );
+
+ await consumer();
+
+ // both shapes mapped and inserted in the same batch, then trimmed
+ const rows = clickhouseClient!.insert.mock.calls[0][0].values;
+ expect(rows.map((r: Record<string, unknown>) => r.id)).toEqual(["legacy-head", "current-tail"]);
+ expect(keyStore.streamTrim).toHaveBeenCalledTimes(1);
+ });
+
+ test("drops a legacy entry missing resolved metadata but keeps draining", async () => {
+ const { consumer, auditLogDAL, keyStore } = await createHarness();
+ keyStore.streamCollect.mockResolvedValueOnce(
+ collectResult([legacyEntry({ id: "no-org", orgId: undefined }), legacyEntry({ id: "ok" })])
+ );
+
+ await consumer();
+
+ const rows = auditLogDAL.batchCreate.mock.calls[0][0];
+ expect(rows).toHaveLength(1);
+ expect(rows[0].id).toBe("ok");
+ expect(keyStore.streamTrim).toHaveBeenCalledTimes(1);
+ });
+
test("skips the tick when the consumer lock is already held by another runner", async () => {
const { consumer, auditLogDAL, keyStore, release } = await createHarness();
keyStore.acquireLock.mockRejectedValueOnce(new Error("ResourceLockedError"));
diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.ts
index 0e52b7c366..99dd65cdba 100644
--- a/backend/src/ee/services/audit-log/audit-log-queue.ts
+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts
@@ -180,11 +180,6 @@ export const auditLogQueueServiceFactory = async ({
if (entries.length === 0 || !lastId) return;
- // We filled the entire collection window, so the ingest stream is draining slower than
- // it's filling — typically a sustained insert outage holding back the trim. The stream is
- // capped at a MAXLEN ceiling (see keyStore.streamAdd), so a persistent backlog means Redis
- // will start dropping the OLDEST (still-undelivered) audit logs. Surface it loudly so the
- // backlog is visible before that silent loss happens.
if (entries.length >= AUDIT_LOG_STREAM_MAX_ENTRIES) {
logger.warn(
`audit-log-queue: ingest stream backlog hit the collection ceiling [collected=${entries.length}] [maxEntries=${AUDIT_LOG_STREAM_MAX_ENTRIES}] — stream is backing up; oldest entries risk being dropped by the Redis MAXLEN cap`
@@ -192,20 +187,55 @@ export const auditLogQueueServiceFactory = async ({
}
// Parse — a single corrupt entry is skipped, not allowed to abort the whole batch.
- const parsed: TAuditLogStreamEntry[] = [];
+ const parsed: unknown[] = [];
for (const [, fields] of entries) {
try {
- parsed.push(JSON.parse(fields[1]) as TAuditLogStreamEntry);
+ parsed.push(JSON.parse(fields[1]));
} catch (error) {
logger.error(error, "audit-log-queue: Skipping unparseable audit log stream entry");
}
}
- // Map a resolved stream entry into a persistable audit log. org/plan/TTL/projectName were all
+ // A pre-rollout pod (before this stream format shipped) wrote the already-mapped
+ // audit-log row to the ingest stream, not the resolved DTO. Those legacy entries are
+ // flat (`actor`/`eventType` are strings, there is no nested `event` object)
+ type TLegacyAuditLogStreamEntry = Omit<TAuditLogs, "createdAt" | "expiresAt" | "updatedAt"> & {
+ createdAt: string;
+ expiresAt: string;
+ };
+ const isCurrentShape = (raw: Record<string, unknown>): boolean =>
+ typeof raw.event === "object" && raw.event !== null;
+
+ // Map a stream entry into a persistable audit log. org/plan/TTL/projectName were all
// resolved at push time (see buildStreamEntry), so this is a pure shape transform with no DB
// lookups. Entries that predate push-time resolution (in-flight during a rolling deploy) lack
// `orgId`/`expiresAt`; drop them rather than persist a row with a missing org or expiry.
- const enrichEntry = (entry: TAuditLogStreamEntry): TAuditLogs | null => {
+ const enrichEntry = (raw: unknown): TAuditLogs | null => {
+ if (typeof raw !== "object" || raw === null) {
+ logger.error("audit-log-queue: Skipping non-object audit log stream entry");
+ return null;
+ }
+
+ // Legacy flat entry: it is already in the persisted shape (mapped + normalized by the
+ // old pod), so only the timestamps need re-hydrating from their JSON ISO strings.
+ if (!isCurrentShape(raw as Record<string, unknown>)) {
+ const legacy = raw as TLegacyAuditLogStreamEntry;
+ if (!legacy.orgId || !legacy.expiresAt) {
+ logger.error(
+ `audit-log-queue: Skipping legacy entry missing resolved metadata [eventType=${legacy.eventType}] [orgId=${legacy.orgId}]`
+ );
+ return null;
+ }
+ const legacyCreatedAt = new Date(legacy.createdAt);
+ return {
+ ...legacy,
+ expiresAt: new Date(legacy.expiresAt),
+ createdAt: legacyCreatedAt,
+ updatedAt: legacyCreatedAt
+ };
+ }
+
+ const entry = raw as TAuditLogStreamEntry;
if (!entry.orgId || !entry.expiresAt) {
logger.error(
`audit-log-queue: Skipping entry missing resolved metadata [event=${entry.event?.type}] [orgId=${entry.orgId}]`
@@ -233,7 +263,17 @@ export const auditLogQueueServiceFactory = async ({
};
};
- const enriched = parsed.map(enrichEntry).filter((log): log is TAuditLogs => log !== null);
+ // Per-entry guard: a single unmappable entry (corrupt or unexpected shape) is skipped,
+ // never allowed to throw out of the map and abort the whole batch
+ const enriched: TAuditLogs[] = [];
+ for (const raw of parsed) {
+ try {
+ const log = enrichEntry(raw);
+ if (log) enriched.push(log);
+ } catch (error) {
+ logger.error(error, "audit-log-queue: Skipping unmappable audit log stream entry");
+ }
+ }
if (enriched.length > 0) {
try {