Skip to content

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

revert stream alerts

Thiago Araujo da Silva3c974f5f6c21
diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-schemas.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-schemas.ts
index 5cdd43b835..4fba791078 100644
--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-schemas.ts
+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-schemas.ts
@@ -1,5 +1,3 @@
-import { z } from "zod";
-
import { AuditLogStreamsSchema } from "@app/db/schemas";
export const BaseProviderSchema = AuditLogStreamsSchema.omit({
@@ -13,7 +11,4 @@ export const BaseProviderSchema = AuditLogStreamsSchema.omit({
encryptedHeadersKeyEncoding: true,
encryptedHeadersTag: true,
url: true
-}).extend({
- lastErrorMessage: z.string().nullish(),
- lastErrorTimestamp: z.date().nullish()
});
diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-service.test.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-service.test.ts
deleted file mode 100644
index 8aaf142422..0000000000
--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-service.test.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-
-import { KeyStorePrefixes } from "@app/keystore/keystore";
-
-import { auditLogStreamServiceFactory } from "./audit-log-stream-service";
-
-const FAILURE_THRESHOLD = 20;
-const STREAM_ID = "stream-1";
-const ORG_ID = "org-1";
-const PROVIDER = "datadog";
-
-const FAILURE_MESSAGE = "upstream failure";
-const failingProviderStreamLog = vi.fn(async () => {
- throw new Error(FAILURE_MESSAGE);
-});
-
-vi.mock("@app/lib/config/env", () => ({
- getConfig: () => ({ SITE_URL: "https://app.infisical.com" })
-}));
-
-vi.mock("@app/lib/logger", () => ({
- logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
-}));
-
-// Override the factory map so every provider lookup returns a streamLog that rejects.
-vi.mock("./audit-log-stream-factory", () => ({
- LOG_STREAM_FACTORY_MAP: new Proxy(
- {},
- {
- get: () => () => ({
- streamLog: failingProviderStreamLog,
- validateCredentials: async ({ credentials }: { credentials: unknown }) => credentials
- })
- }
- )
-}));
-
-vi.mock("@app/ee/services/audit-log-stream/audit-log-stream-fns", () => ({
- decryptLogStream: async (s: unknown) => s,
- decryptLogStreamCredentials: async () => ({}),
- encryptLogStreamCredentials: async () => "encrypted",
- listProviderOptions: () => []
-}));
-
-const createService = () => {
- const store: Record<string, string | undefined> = {};
-
- const keyStore = {
- getItem: vi.fn(async (key: string) => store[key] ?? null),
- setItemWithExpiryNX: vi.fn(async (key: string, _ttl: number, value: string) => {
- if (store[key] !== undefined) return null;
- store[key] = value;
- return "OK";
- }),
- deleteItem: vi.fn(async (key: string) => {
- const existed = store[key] !== undefined;
- delete store[key];
- return existed ? 1 : 0;
- }),
- deleteItemsByKeyIn: vi.fn(async (keys: string[]) => {
- let deleted = 0;
- for (const k of keys) {
- if (store[k] !== undefined) {
- delete store[k];
- deleted += 1;
- }
- }
- return deleted;
- }),
- incrementByWithExpiry: vi.fn(async (key: string, value: number) => {
- const current = store[key] ? parseInt(store[key] as string, 10) : 0;
- const next = current + value;
- store[key] = String(next);
- return next;
- })
- };
-
- const auditLogStreamDAL = {
- find: vi.fn(async () => [
- {
- id: STREAM_ID,
- provider: PROVIDER,
- encryptedCredentials: Buffer.from("x"),
- orgId: ORG_ID
- }
- ])
- };
-
- const notificationService = {
- createUserNotifications: vi.fn(async () => undefined)
- };
- const smtpService = {
- sendMail: vi.fn<
- (payload: { substitutions: { lastErrorMessage: string; lastErrorTimestamp: string } }) => Promise<void>
- >(async () => undefined)
- };
- const orgDAL = {
- findOrgMembersByRole: vi.fn(async () => [
- { status: "accepted", user: { id: "user-1", email: "[email protected]" } }
- ])
- };
-
- const service = auditLogStreamServiceFactory({
- auditLogStreamDAL: auditLogStreamDAL as never,
- permissionService: {} as never,
- licenseService: {} as never,
- kmsService: {} as never,
- keyStore: keyStore as never,
- notificationService: notificationService as never,
- smtpService: smtpService as never,
- orgDAL: orgDAL as never
- });
-
- return { service, keyStore, auditLogStreamDAL, notificationService, smtpService, orgDAL, store };
-};
-
-const driveFailures = async (service: ReturnType<typeof createService>["service"], times: number) => {
- for (let i = 0; i < times; i += 1) {
- // eslint-disable-next-line no-await-in-loop
- await service.streamLog(ORG_ID, { id: `log-${i}` } as never);
- }
-};
-
-describe("auditLogStreamServiceFactory failure tracking", () => {
- beforeEach(() => {
- failingProviderStreamLog.mockClear();
- });
-
- afterEach(() => {
- vi.clearAllMocks();
- });
-
- test("does not fire an alert below the failure threshold", async () => {
- const { service, notificationService, smtpService, keyStore } = createService();
-
- await driveFailures(service, FAILURE_THRESHOLD - 1);
-
- expect(notificationService.createUserNotifications).not.toHaveBeenCalled();
- expect(smtpService.sendMail).not.toHaveBeenCalled();
- expect(keyStore.setItemWithExpiryNX).not.toHaveBeenCalled();
- });
-
- test("fires an alert exactly once when the threshold is reached", async () => {
- const { service, notificationService, smtpService } = createService();
-
- await driveFailures(service, FAILURE_THRESHOLD);
-
- expect(notificationService.createUserNotifications).toHaveBeenCalledTimes(1);
- expect(smtpService.sendMail).toHaveBeenCalledTimes(1);
-
- expect(notificationService.createUserNotifications).toHaveBeenCalledWith([
- expect.objectContaining({
- userId: "user-1",
- orgId: ORG_ID,
- type: "audit-log-stream-failed"
- })
- ]);
- });
-
- test("does not re-fire while the cooldown lock is held", async () => {
- const { service, notificationService } = createService();
-
- await driveFailures(service, FAILURE_THRESHOLD);
- expect(notificationService.createUserNotifications).toHaveBeenCalledTimes(1);
-
- await driveFailures(service, FAILURE_THRESHOLD * 2);
- expect(notificationService.createUserNotifications).toHaveBeenCalledTimes(1);
- });
-
- test("releases the cooldown lock when notification delivery throws", async () => {
- const { service, keyStore, notificationService } = createService();
- notificationService.createUserNotifications.mockRejectedValueOnce(new Error("downstream"));
-
- await driveFailures(service, FAILURE_THRESHOLD);
-
- expect(keyStore.deleteItem).toHaveBeenCalledWith(KeyStorePrefixes.AuditLogStreamAlertSent(STREAM_ID));
- });
-
- test("skips alerting orgs with no active admins", async () => {
- const { service, orgDAL, notificationService, smtpService } = createService();
- orgDAL.findOrgMembersByRole.mockResolvedValueOnce([
- { status: "invited", user: { id: "user-1", email: "[email protected]" } }
- ]);
-
- await driveFailures(service, FAILURE_THRESHOLD);
-
- expect(notificationService.createUserNotifications).not.toHaveBeenCalled();
- expect(smtpService.sendMail).not.toHaveBeenCalled();
- });
-
- test("honors a preset cooldown lock and skips alert evaluation entirely", async () => {
- const { service, keyStore, store, notificationService } = createService();
- store[KeyStorePrefixes.AuditLogStreamAlertSent(STREAM_ID)] = "1";
-
- await driveFailures(service, FAILURE_THRESHOLD * 2);
-
- expect(keyStore.incrementByWithExpiry).not.toHaveBeenCalled();
- expect(keyStore.setItemWithExpiryNX).not.toHaveBeenCalled();
- expect(notificationService.createUserNotifications).not.toHaveBeenCalled();
- });
-
- test("stores the last error message and timestamp in the cooldown payload", async () => {
- const { service, store, smtpService } = createService();
-
- await driveFailures(service, FAILURE_THRESHOLD);
-
- const payload = store[KeyStorePrefixes.AuditLogStreamAlertSent(STREAM_ID)];
- expect(payload).toBeDefined();
- const parsed = JSON.parse(payload as string) as { message: string; timestamp: string };
- expect(parsed.message).toContain(FAILURE_MESSAGE);
- expect(typeof parsed.timestamp).toBe("string");
- expect(Number.isNaN(new Date(parsed.timestamp).getTime())).toBe(false);
-
- expect(smtpService.sendMail).toHaveBeenCalledTimes(1);
- const mailCall = smtpService.sendMail.mock.calls[0]?.[0] as {
- substitutions: { lastErrorMessage: string; lastErrorTimestamp: string };
- };
- expect(mailCall.substitutions.lastErrorMessage).toContain(FAILURE_MESSAGE);
- expect(mailCall.substitutions.lastErrorTimestamp).toBe(parsed.timestamp);
- });
-});
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 0727edab8c..64d1cfe2f6 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
@@ -1,23 +1,17 @@
import { ForbiddenError } from "@casl/ability";
import { isAxiosError } from "axios";
-import { OrganizationActionScope, OrgMembershipRole, OrgMembershipStatus, TAuditLogs } from "@app/db/schemas";
+import { OrganizationActionScope, TAuditLogs } from "@app/db/schemas";
import {
decryptLogStream,
decryptLogStreamCredentials,
encryptLogStreamCredentials,
listProviderOptions
} from "@app/ee/services/audit-log-stream/audit-log-stream-fns";
-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
-import { getConfig } from "@app/lib/config/env";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
-import { NotificationType } from "@app/services/notification/notification-types";
-import { TOrgDALFactory } from "@app/services/org/org-dal";
-import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
import { TLicenseServiceFactory } from "../license/license-service";
import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";
@@ -28,24 +22,11 @@ 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";
-const FAILURE_THRESHOLD = 20; // 20 errors threshold
-const FAILURE_WINDOW_MINUTES = 5; // counter expires after this much idle time since the last error
-const FAILURE_WINDOW_SECONDS = FAILURE_WINDOW_MINUTES * 60;
-const FAILURE_ALERT_COOLDOWN_SECONDS = 24 * 60 * 60; // 24 hours alert cooldown
-const LAST_ERROR_MESSAGE_MAX_LENGTH = 1000;
-
export type TAuditLogStreamServiceFactoryDep = {
auditLogStreamDAL: TAuditLogStreamDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- keyStore: Pick<
- TKeyStoreFactory,
- "incrementByWithExpiry" | "getItem" | "setItemWithExpiryNX" | "deleteItem" | "deleteItemsByKeyIn"
- >;
- notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
- smtpService: Pick<TSmtpService, "sendMail">;
- orgDAL: Pick<TOrgDALFactory, "findOrgMembersByRole">;
};
export type TAuditLogStreamServiceFactory = ReturnType<typeof auditLogStreamServiceFactory>;
@@ -54,11 +35,7 @@ export const auditLogStreamServiceFactory = ({
auditLogStreamDAL,
permissionService,
licenseService,
- kmsService,
- keyStore,
- notificationService,
- smtpService,
- orgDAL
+ kmsService
}: TAuditLogStreamServiceFactoryDep) => {
const create = async ({ provider, credentials }: TCreateAuditLogStreamDTO, actor: OrgServiceActor) => {
const plan = await licenseService.getPlan(actor.orgId);
@@ -104,31 +81,6 @@ export const auditLogStreamServiceFactory = ({
return { ...logStream, credentials: validatedCredentials } as TAuditLogStream;
};
- const resetFailureTracking = async (streamId: string) => {
- await keyStore.deleteItemsByKeyIn([
- KeyStorePrefixes.AuditLogStreamAlertSent(streamId),
- KeyStorePrefixes.AuditLogStreamFailureCount(streamId)
- ]);
- };
-
- const readLastErrorFromCooldown = async (streamId: string) => {
- const raw = await keyStore.getItem(KeyStorePrefixes.AuditLogStreamAlertSent(streamId));
- if (!raw) return { lastErrorMessage: null, lastErrorTimestamp: null };
-
- try {
- const parsed = JSON.parse(raw) as { message?: unknown; timestamp?: unknown };
- const message = typeof parsed.message === "string" ? parsed.message : null;
- const timestampStr = typeof parsed.timestamp === "string" ? parsed.timestamp : null;
- const timestamp = timestampStr ? new Date(timestampStr) : null;
- return {
- lastErrorMessage: message,
- lastErrorTimestamp: timestamp && !Number.isNaN(timestamp.getTime()) ? timestamp : null
- };
- } catch {
- return { lastErrorMessage: null, lastErrorTimestamp: null };
- }
- };
-
const updateById = async (
{ logStreamId, provider, credentials }: TUpdateAuditLogStreamDTO,
actor: OrgServiceActor
@@ -203,9 +155,6 @@ export const auditLogStreamServiceFactory = ({
encryptedCredentials
});
- // Reset the cooldown lock AND any live failure buckets so a reconfigured stream starts from a clean state.
- await resetFailureTracking(logStreamId);
-
return { ...updatedLogStream, credentials: validatedCredentials } as TAuditLogStream;
};
@@ -232,8 +181,6 @@ export const auditLogStreamServiceFactory = ({
const deletedLogStream = await auditLogStreamDAL.deleteById(logStreamId);
- await resetFailureTracking(logStreamId);
-
return decryptLogStream(deletedLogStream, kmsService);
};
@@ -258,9 +205,7 @@ export const auditLogStreamServiceFactory = ({
});
}
- const decrypted = await decryptLogStream(logStream, kmsService);
- const lastError = await readLastErrorFromCooldown(logStream.id);
- return { ...decrypted, ...lastError };
+ return decryptLogStream(logStream, kmsService);
};
const list = async (actor: OrgServiceActor) => {
@@ -277,124 +222,14 @@ export const auditLogStreamServiceFactory = ({
const logStreams = await auditLogStreamDAL.find({ orgId: actor.orgId });
- return Promise.all(
- logStreams.map(async (stream) => {
- const decrypted = await decryptLogStream(stream, kmsService);
- const lastError = await readLastErrorFromCooldown(stream.id);
- return { ...decrypted, ...lastError };
- })
- );
- };
-
- const notifyStreamFailure = async (
- orgId: string,
- streamId: string,
- provider: string,
- failureCount: number,
- lastError: { message: string; timestamp: string }
- ) => {
- const appCfg = getConfig();
- const orgAdmins = await orgDAL.findOrgMembersByRole(orgId, OrgMembershipRole.Admin);
- const activeAdmins = orgAdmins.filter((admin) => admin.status !== OrgMembershipStatus.Invited);
- if (activeAdmins.length === 0) {
- logger.warn({ orgId }, "Organization has no admins to notify about audit stream failure.");
- return;
- }
-
- const streamPath = `/organizations/${orgId}/settings?selectedTab=tag-audit-log-streams`;
- const streamUrl = `${appCfg.SITE_URL}${streamPath}`;
-
- await notificationService.createUserNotifications(
- activeAdmins.map((admin) => ({
- userId: admin.user.id,
- orgId,
- type: NotificationType.AUDIT_LOG_STREAM_FAILED,
- title: "Audit Log Stream Failure",
- body: `Your **${provider}** audit log stream has failed ${failureCount} times in a row, with no more than ${FAILURE_WINDOW_MINUTES} minutes between failures. Audit logs may not be reaching their destination.`,
- link: streamPath
- }))
- );
-
- const adminEmails = activeAdmins.map((admin) => admin.user.email).filter(Boolean) as string[];
- if (adminEmails.length === 0) {
- return;
- }
- await smtpService
- .sendMail({
- recipients: adminEmails,
- subjectLine: "Audit Log Stream Failure Alert",
- template: SmtpTemplates.AuditLogStreamFailed,
- substitutions: {
- provider,
- windowFailureCount: failureCount,
- windowMinutes: FAILURE_WINDOW_MINUTES,
- streamUrl,
- lastErrorMessage: lastError.message,
- lastErrorTimestamp: lastError.timestamp
- }
- })
- .catch((err) =>
- logger.error(err, `Failed to send audit log stream failure email [streamId=${streamId}] [orgId=${orgId}]`)
- );
- };
-
- const evaluateErrorSlidingWindow = async (
- orgId: string,
- streamId: string,
- provider: string,
- errorMessage: string
- ) => {
- try {
- const alertKey = KeyStorePrefixes.AuditLogStreamAlertSent(streamId);
-
- // Skip tracking while the stream is in alert cooldown — counts won't be acted on until cooldown expires.
- const inCooldown = await keyStore.getItem(alertKey);
- if (inCooldown) return;
-
- // Increment a single counter and roll its TTL forward on every error. The window is anchored on
- // the latest activity — if no new error arrives within FAILURE_WINDOW_SECONDS, the counter expires.
- const counterKey = KeyStorePrefixes.AuditLogStreamFailureCount(streamId);
- const failureCount = await keyStore.incrementByWithExpiry(counterKey, 1, FAILURE_WINDOW_SECONDS);
-
- if (failureCount < FAILURE_THRESHOLD) return;
-
- // Capture the last error message and timestamp inside the cooldown payload so list reads and
- // the failure email both surface the most recent root cause to admins.
- const truncatedMessage =
- errorMessage.length > LAST_ERROR_MESSAGE_MAX_LENGTH
- ? `${errorMessage.slice(0, LAST_ERROR_MESSAGE_MAX_LENGTH)}...`
- : errorMessage;
- const lastError = { message: truncatedMessage, timestamp: new Date().toISOString() };
-
- // NX lock ensures only one worker fires the alert within the cooldown window.
- const acquired = await keyStore.setItemWithExpiryNX(
- alertKey,
- FAILURE_ALERT_COOLDOWN_SECONDS,
- JSON.stringify(lastError)
- );
- if (!acquired) return;
-
- await notifyStreamFailure(orgId, streamId, provider, failureCount, lastError).catch(async (notifyErr) => {
- logger.error(
- notifyErr,
- `Failed to send audit log stream failure notification [streamId=${streamId}] [orgId=${orgId}]`
- );
- // Release the lock so the next threshold breach can retry delivery.
- await keyStore.deleteItem(alertKey);
- });
- } catch (trackingErr) {
- logger.error(
- trackingErr,
- `Failed to track audit log stream failure count [streamId=${streamId}] [orgId=${orgId}]`
- );
- }
+ return Promise.all(logStreams.map((stream) => decryptLogStream(stream, kmsService)));
};
const streamLog = async (orgId: string, auditLog: TAuditLogs) => {
const logStreams = await auditLogStreamDAL.find({ orgId });
await Promise.allSettled(
logStreams.map(async (logStream) => {
- const { id, provider, encryptedCredentials } = logStream;
+ const { provider, encryptedCredentials } = logStream;
const credentials = await decryptLogStreamCredentials({
encryptedCredentials,
orgId,
@@ -406,21 +241,16 @@ export const auditLogStreamServiceFactory = ({
try {
await factory.streamLog({ credentials, auditLog });
} catch (error) {
- let errorMessage: string;
if (isAxiosError(error)) {
- errorMessage = `${error?.message ?? "Request failed"} — ${JSON.stringify(error?.response?.data) ?? ""}`;
logger.error(
`audit-log-queue: Failed to stream audit log due to request error [auditLogId=${auditLog.id}] [event=${auditLog.eventType}] [provider=${provider}] [orgId=${orgId}] [projectId=${auditLog.projectId}] [message=${error?.message}] [response=${JSON.stringify(error?.response?.data)}]`
);
} else {
- errorMessage = (error as Error)?.message ?? "Unknown error";
logger.error(
error,
`audit-log-queue: Failed to stream audit log [auditLogId=${auditLog.id}] [event=${auditLog.eventType}] [provider=${provider}] [orgId=${orgId}] [projectId=${auditLog.projectId}]: ${(error as Error)?.message}`
);
}
-
- await evaluateErrorSlidingWindow(orgId, id, provider, errorMessage);
}
})
);
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index ece6702c60..0a388e121e 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -130,10 +130,7 @@ export const KeyStorePrefixes = {
TelemetryEvent: (event: string, bucketId: string, distinctId: string, uuid: string) =>
`telemetry-event-${event}-${bucketId}-${distinctId}-${uuid}` as const,
- TelemetryEventByBucketPattern: (event: string, bucketId: string) => `telemetry-event-${event}-${bucketId}-*` as const,
-
- AuditLogStreamFailureCount: (streamId: string) => `audit-log-stream:${streamId}:failures` as const,
- AuditLogStreamAlertSent: (streamId: string) => `audit-log-stream:${streamId}:alert-sent` as const
+ TelemetryEventByBucketPattern: (event: string, bucketId: string) => `telemetry-event-${event}-${bucketId}-*` as const
};
export const KeyStoreTtls = {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 9e21e2d855..e9e7428b01 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -866,11 +866,7 @@ export const registerRoutes = async (
licenseService,
permissionService,
auditLogStreamDAL,
- kmsService,
- keyStore,
- notificationService,
- smtpService,
- orgDAL
+ kmsService
});
const auditLogQueue = await auditLogQueueServiceFactory({
diff --git a/backend/src/services/notification/notification-types.ts b/backend/src/services/notification/notification-types.ts
index 34dc534e26..ad347a7231 100644
--- a/backend/src/services/notification/notification-types.ts
+++ b/backend/src/services/notification/notification-types.ts
@@ -22,8 +22,7 @@ export enum NotificationType {
APPROVAL_REQUIRED = "approval-required",
PKI_ALERT_CHANNEL_FAILED = "pki-alert-channel-failed",
CREDENTIAL_ROTATION_FAILED = "credential-rotation-failed",
- AUDIT_LOG_MIGRATION_RECOMMENDED = "audit-log-migration-recommended",
- AUDIT_LOG_STREAM_FAILED = "audit-log-stream-failed"
+ AUDIT_LOG_MIGRATION_RECOMMENDED = "audit-log-migration-recommended"
}
export interface TCreateUserNotificationDTO {
diff --git a/backend/src/services/smtp/emails/AuditLogStreamFailedTemplate.tsx b/backend/src/services/smtp/emails/AuditLogStreamFailedTemplate.tsx
deleted file mode 100644
index 60da48977c..0000000000
--- a/backend/src/services/smtp/emails/AuditLogStreamFailedTemplate.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { Heading, Section, Text } from "@react-email/components";
-import React from "react";
-
-import { BaseButton } from "./BaseButton";
-import { BaseEmailWrapper, BaseEmailWrapperProps } from "./BaseEmailWrapper";
-
-interface AuditLogStreamFailedTemplateProps extends Omit<BaseEmailWrapperProps, "title" | "preview" | "children"> {
- provider: string;
- windowFailureCount: number;
- windowMinutes: number;
- streamUrl: string;
- lastErrorMessage?: string;
- lastErrorTimestamp?: string;
-}
-
-export const AuditLogStreamFailedTemplate = ({
- provider,
- windowFailureCount,
- windowMinutes,
- streamUrl,
- siteUrl,
- lastErrorMessage,
- lastErrorTimestamp
-}: AuditLogStreamFailedTemplateProps) => {
- return (
- <BaseEmailWrapper
- title="Audit Log Stream Failure"
- preview="Your audit log stream is experiencing repeated failures."
- siteUrl={siteUrl}
- >
- <Heading className="text-black text-[18px] leading-[28px] text-center font-normal p-0 mx-0">
- Your <strong>{provider}</strong> audit log stream is failing
- </Heading>
- <Section className="px-[24px] mb-[28px] mt-[36px] pt-[26px] pb-[4px] text-[14px] border border-solid border-gray-200 rounded-md bg-gray-50">
- <strong>Provider</strong>
- <Text className="text-[14px] mt-[4px]">{provider}</Text>
- <strong>Consecutive failures</strong>
- <Text className="text-[14px] text-red-600 mt-[4px]">{windowFailureCount}</Text>
- {lastErrorTimestamp && (
- <>
- <strong>Last Error At</strong>
- <Text className="text-[14px] mt-[4px]">{lastErrorTimestamp}</Text>
- </>
- )}
- {lastErrorMessage && (
- <>
- <strong>Last Error Message</strong>
- <Text className="text-[14px] text-red-600 mt-[4px] break-all">{lastErrorMessage}</Text>
- </>
- )}
- </Section>
- <Text className="text-[14px]">
- Your stream has logged {windowFailureCount} failures in a row, with no more than {windowMinutes} minutes between
- them. Audit logs may not be reaching their destination. This is likely caused by a configuration issue or
- connectivity problem with your audit log stream endpoint. Please review your stream settings.
- </Text>
- <Section className="text-center">
- <BaseButton href={streamUrl}>View Audit Log Streams</BaseButton>
- </Section>
- </BaseEmailWrapper>
- );
-};
-
-export default AuditLogStreamFailedTemplate;
-
-AuditLogStreamFailedTemplate.PreviewProps = {
- provider: "Datadog",
- windowFailureCount: 12,
- windowMinutes: 5,
- streamUrl: "https://app.infisical.com/organizations/example-org/settings?selectedTab=tag-audit-log-streams",
- siteUrl: "https://app.infisical.com",
- lastErrorMessage: "Request failed with status code 401 — {\"errors\":[\"Invalid API key\"]}",
- lastErrorTimestamp: "2026-05-19T14:32:11.000Z"
-} as AuditLogStreamFailedTemplateProps;
diff --git a/backend/src/services/smtp/emails/index.ts b/backend/src/services/smtp/emails/index.ts
index 779a560df3..33ed3c140e 100644
--- a/backend/src/services/smtp/emails/index.ts
+++ b/backend/src/services/smtp/emails/index.ts
@@ -3,7 +3,6 @@ export * from "./AccessApprovalRequestUpdatedTemplate";
export * from "./AccessPamRequestBypassedTemplate";
export * from "./AccountDeletionConfirmationTemplate";
export * from "./AuditLogMigrationAlertTemplate";
-export * from "./AuditLogStreamFailedTemplate";
export * from "./CredentialRotationFailedTemplate";
export * from "./EmailChangeRequestNotificationTemplate";
export * from "./EmailMfaTemplate";
diff --git a/backend/src/services/smtp/smtp-service.ts b/backend/src/services/smtp/smtp-service.ts
index d0d1ca5a62..52814d7246 100644
--- a/backend/src/services/smtp/smtp-service.ts
+++ b/backend/src/services/smtp/smtp-service.ts
@@ -13,7 +13,6 @@ import {
AccessPamRequestBypassedTemplate,
AccountDeletionConfirmationTemplate,
AuditLogMigrationAlertTemplate,
- AuditLogStreamFailedTemplate,
CredentialRotationFailedTemplate,
EmailChangeRequestNotificationTemplate,
EmailMfaTemplate,
@@ -107,8 +106,7 @@ export enum SmtpTemplates {
DynamicSecretLeaseRevocationFailed = "dynamicSecretLeaseRevocationFailed",
CredentialRotationFailed = "credentialRotationFailed",
AuditLogMigrationAlert = "auditLogMigrationAlert",
- HoneyTokenTriggered = "honeyTokenTriggered",
- AuditLogStreamFailed = "auditLogStreamFailed"
+ HoneyTokenTriggered = "honeyTokenTriggered"
}
export enum SmtpHost {
@@ -164,8 +162,7 @@ const EmailTemplateMap: Record<SmtpTemplates, React.FC<any>> = {
[SmtpTemplates.DynamicSecretLeaseRevocationFailed]: DynamicSecretLeaseRevocationFailedTemplate,
[SmtpTemplates.CredentialRotationFailed]: CredentialRotationFailedTemplate,
[SmtpTemplates.AuditLogMigrationAlert]: AuditLogMigrationAlertTemplate,
- [SmtpTemplates.HoneyTokenTriggered]: HoneyTokenTriggeredTemplate,
- [SmtpTemplates.AuditLogStreamFailed]: AuditLogStreamFailedTemplate
+ [SmtpTemplates.HoneyTokenTriggered]: HoneyTokenTriggeredTemplate
};
export const smtpServiceFactory = (cfg: TSmtpConfig) => {
diff --git a/frontend/src/hooks/api/auditLogStreams/types/providers/root-provider.ts b/frontend/src/hooks/api/auditLogStreams/types/providers/root-provider.ts
index 3dfc0215dc..5ea3137e59 100644
--- a/frontend/src/hooks/api/auditLogStreams/types/providers/root-provider.ts
+++ b/frontend/src/hooks/api/auditLogStreams/types/providers/root-provider.ts
@@ -3,6 +3,4 @@ export type TRootProviderLogStream = {
orgId: string;
createdAt: string;
updatedAt: string;
- lastErrorMessage?: string | null;
- lastErrorTimestamp?: string | null;
};
diff --git a/frontend/src/hooks/api/notifications/types.ts b/frontend/src/hooks/api/notifications/types.ts
index 227ec30ce8..6a4e3f31a4 100644
--- a/frontend/src/hooks/api/notifications/types.ts
+++ b/frontend/src/hooks/api/notifications/types.ts
@@ -21,8 +21,7 @@ export enum NotificationType {
RELAY_HEALTH_ALERT = "relay-health-alert",
APPROVAL_REQUIRED = "approval-required",
PKI_ALERT_CHANNEL_FAILED = "pki-alert-channel-failed",
- CREDENTIAL_ROTATION_FAILED = "credential-rotation-failed",
- AUDIT_LOG_STREAM_FAILED = "audit-log-stream-failed"
+ CREDENTIAL_ROTATION_FAILED = "credential-rotation-failed"
}
export interface TUserNotification {
@@ -38,8 +37,7 @@ export interface TUserNotification {
export const CRITICAL_NOTIFICATION_TYPES: NotificationType[] = [
NotificationType.GATEWAY_HEALTH_ALERT,
- NotificationType.RELAY_HEALTH_ALERT,
- NotificationType.AUDIT_LOG_STREAM_FAILED
+ NotificationType.RELAY_HEALTH_ALERT
];
export const isCriticalNotification = (type: NotificationType): boolean =>
diff --git a/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx b/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
index 035b9a9625..b7833031d5 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
@@ -14,15 +14,11 @@ import { apiRequest } from "@app/config/request";
import { useOrganization, useOrgPermission } from "@app/context";
import {
OrgGatewayPermissionActions,
- OrgPermissionActions,
OrgPermissionSubjects,
OrgRelayPermissionActions
} from "@app/context/OrgPermissionContext/types";
import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
-import { useUpdateNotification } from "@app/hooks/api/notifications/mutations";
-import { useGetMyNotifications } from "@app/hooks/api/notifications/queries";
-import { NotificationType } from "@app/hooks/api/notifications/types";
import { relayQueryKeys } from "@app/hooks/api/relays/queries";
import { TRelay } from "@app/hooks/api/relays/types";
@@ -85,7 +81,6 @@ const SingleAlertRow = ({ alert, isChild }: SingleAlertRowProps) => (
export const NetworkHealthBanner = () => {
const [isExpanded, setIsExpanded] = useState(true);
const [networkDismissed, setNetworkDismissed] = useState(() => wasDismissedWithinLastDay());
- const [dismissedAlertIds, setDismissedAlertIds] = useState<Set<string>>(() => new Set());
const { currentOrg } = useOrganization();
const { permission } = useOrgPermission();
@@ -98,7 +93,6 @@ export const NetworkHealthBanner = () => {
OrgRelayPermissionActions.ListRelays,
OrgPermissionSubjects.Relay
);
- const canReadSettings = permission.can(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);
const { data: gateways } = useQuery({
...gatewaysQueryKeys.list(),
@@ -112,8 +106,6 @@ export const NetworkHealthBanner = () => {
},
enabled: canListRelays
});
- const { data: notifications } = useGetMyNotifications();
- const { mutate: updateNotification } = useUpdateNotification();
const unreachableGatewayCount = useMemo(
() =>
@@ -131,16 +123,6 @@ export const NetworkHealthBanner = () => {
[relays]
);
- const failedStreamNotifications = useMemo(
- () =>
- canReadSettings
- ? (notifications?.filter(
- (n) => n.type === NotificationType.AUDIT_LOG_STREAM_FAILED && !n.isRead
- ) ?? [])
- : [],
- [notifications, canReadSettings]
- );
-
const alerts = useMemo<AlertItem[]>(() => {
const items: AlertItem[] = [];
@@ -165,35 +147,10 @@ export const NetworkHealthBanner = () => {
});
}
- const visibleStreamNotifications = failedStreamNotifications.filter(
- (n) => !dismissedAlertIds.has(n.id)
- );
- if (visibleStreamNotifications.length > 0) {
- const ids = visibleStreamNotifications.map((n) => n.id);
- items.push({
- id: "audit-log-stream-failed",
- message: "Unable to stream audit logs.",
- linkLabel: "Click to view stream configuration.",
- linkTo: visibleStreamNotifications[0].link ?? undefined,
- onDismiss: () => {
- ids.forEach((id) => updateNotification({ notificationId: id, isRead: true }));
- setDismissedAlertIds((prev) => new Set([...prev, ...ids]));
- }
- });
- }
-
return items;
- }, [
- networkDismissed,
- unreachableGatewayCount,
- unreachableRelayCount,
- failedStreamNotifications,
- dismissedAlertIds,
- currentOrg.id,
- updateNotification
- ]);
-
- if (!canListGateways && !canListRelays && !canReadSettings) return null;
+ }, [networkDismissed, unreachableGatewayCount, unreachableRelayCount, currentOrg.id]);
+
+ if (!canListGateways && !canListRelays) return null;
if (alerts.length === 0) return null;
if (alerts.length === 1) {
diff --git a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/AuditLogStreamRow.tsx b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/AuditLogStreamRow.tsx
index 3e02681555..bfbee82cab 100644
--- a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/AuditLogStreamRow.tsx
+++ b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/AuditLogStreamRow.tsx
@@ -18,8 +18,6 @@ import { OrgPermissionActions } from "@app/context/OrgPermissionContext/types";
import { AUDIT_LOG_STREAM_PROVIDER_MAP, getProviderUrl } from "@app/helpers/auditLogStreams";
import { TAuditLogStream } from "@app/hooks/api/types";
-import { LastErrorDialog } from "./LastErrorDialog";
-
type Props = {
logStream: TAuditLogStream;
onDelete: (logStream: TAuditLogStream) => void;
@@ -27,13 +25,11 @@ type Props = {
};
export const AuditLogStreamRow = ({ logStream, onDelete, onEditCredentials }: Props) => {
- const { id, provider, lastErrorMessage, lastErrorTimestamp } = logStream;
+ const { id, provider } = logStream;
const providerDetails = AUDIT_LOG_STREAM_PROVIDER_MAP[provider];
const url = getProviderUrl(logStream);
- const hasLastError = Boolean(lastErrorMessage || lastErrorTimestamp);
-
return (
<Tr
className={twMerge("group h-12 transition-colors duration-100 hover:bg-mineshaft-700")}
@@ -63,12 +59,6 @@ export const AuditLogStreamRow = ({ logStream, onDelete, onEditCredentials }: Pr
<Td className="max-w-0 min-w-32!">
<div className="flex w-full items-center gap-2">
<p className="truncate">{url}</p>
- {hasLastError && (
- <LastErrorDialog
- lastErrorMessage={lastErrorMessage ?? null}
- lastErrorTimestamp={lastErrorTimestamp ?? null}
- />
- )}
</div>
</Td>
<Td>
diff --git a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/LastErrorDialog.tsx b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/LastErrorDialog.tsx
deleted file mode 100644
index 29a6cde94b..0000000000
--- a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/components/LastErrorDialog.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { useState } from "react";
-import { format } from "date-fns";
-import { AlertTriangleIcon, CheckIcon, CopyIcon } from "lucide-react";
-
-import { createNotification } from "@app/components/notifications";
-import {
- Button,
- Dialog,
- DialogClose,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
-import { useTimedReset } from "@app/hooks";
-
-type Props = {
- lastErrorMessage: string | null;
- lastErrorTimestamp: string | null;
-};
-
-export const LastErrorDialog = ({ lastErrorMessage, lastErrorTimestamp }: Props) => {
- const [isOpen, setIsOpen] = useState(false);
- const [, isCopied, setCopied] = useTimedReset<string>({ initialState: "" });
-
- const handleCopy = async () => {
- if (!lastErrorMessage) return;
- await navigator.clipboard.writeText(lastErrorMessage);
- setCopied("copied");
- createNotification({ type: "success", text: "Error message copied to clipboard" });
- };
-
- return (
- <Dialog open={isOpen} onOpenChange={setIsOpen}>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- type="button"
- aria-label="View last error"
- onClick={() => setIsOpen(true)}
- className="flex shrink-0 cursor-pointer items-center rounded-sm p-0.5 text-yellow-500 outline-none hover:bg-foreground/10 focus-visible:ring-2 focus-visible:ring-ring"
- >
- <AlertTriangleIcon className="size-4" />
- </button>
- </TooltipTrigger>
- <TooltipContent>Click to view error</TooltipContent>
- </Tooltip>
- <DialogContent className="max-w-2xl">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <AlertTriangleIcon className="size-5 text-yellow-500" />
- Last Error
- </DialogTitle>
- {lastErrorTimestamp && (
- <p className="text-xs text-accent">{format(lastErrorTimestamp, "PPpp")}</p>
- )}
- </DialogHeader>
- {lastErrorMessage ? (
- <pre className="max-h-80 overflow-auto rounded-md border border-border bg-container/50 p-3 font-mono text-xs whitespace-pre-wrap text-foreground select-all">
- {lastErrorMessage}
- </pre>
- ) : (
- <p className="text-sm text-accent">No error message available.</p>
- )}
- <DialogFooter>
- <DialogClose asChild>
- <Button variant="ghost">Close</Button>
- </DialogClose>
- {lastErrorMessage && (
- <Button variant="neutral" onClick={handleCopy}>
- {isCopied ? <CheckIcon /> : <CopyIcon />}
- {isCopied ? "Copied" : "Copy"}
- </Button>
- )}
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-};