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
add bucket sliding window for error tracking in audit logs
Thiago Araujo da Silva766d5ef92791
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 c0c2418f6d..0005971fb0 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,17 +1,23 @@import { ForbiddenError } from "@casl/ability";import { isAxiosError } from "axios";-import { OrganizationActionScope, TAuditLogs } from "@app/db/schemas";+import { OrganizationActionScope, OrgMembershipRole, OrgMembershipStatus, 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";@@ -22,11 +28,20 @@ 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 = 10; // 10 errors threshold+const FAILURE_WINDOW_MINUTES = 5; // sliding window width in 1 minute buckets+const FAILURE_ALERT_COOLDOWN_SECONDS = 24 * 60 * 60; // 24 hours alert cooldown+const BUCKET_TTL_SECONDS = (FAILURE_WINDOW_MINUTES + 2) * 60; // 7 minutes bucket TTL+export type TAuditLogStreamServiceFactoryDep = {auditLogStreamDAL: TAuditLogStreamDALFactory;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ keyStore: Pick<TKeyStoreFactory, "incrementBy" | "setExpiry" | "getItems" | "setItemWithExpiryNX">;+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;+ smtpService: Pick<TSmtpService, "sendMail">;+ orgDAL: Pick<TOrgDALFactory, "findOrgMembersByRole">;};export type TAuditLogStreamServiceFactory = ReturnType<typeof auditLogStreamServiceFactory>;@@ -35,7 +50,11 @@ export const auditLogStreamServiceFactory = ({auditLogStreamDAL,permissionService,licenseService,- kmsService+ kmsService,+ keyStore,+ notificationService,+ smtpService,+ orgDAL}: TAuditLogStreamServiceFactoryDep) => {const create = async ({ provider, credentials }: TCreateAuditLogStreamDTO, actor: OrgServiceActor) => {const plan = await licenseService.getPlan(actor.orgId);@@ -225,10 +244,93 @@ export const auditLogStreamServiceFactory = ({return Promise.all(logStreams.map((stream) => decryptLogStream(stream, kmsService)));};+ const notifyStreamFailure = async (orgId: string, streamId: string, provider: string, failureCount: number) => {+ 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 adminEmails = activeAdmins.map((admin) => admin.user.email).filter(Boolean) as string[];+ const streamUrl = `${appCfg.SITE_URL}/org/${orgId}/settings`;++ 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 the last ${FAILURE_WINDOW_MINUTES} minutes. Audit logs may not be reaching their destination.`,+ link: streamUrl+ }))+ );+ await smtpService+ .sendMail({+ recipients: adminEmails,+ subjectLine: "Audit Log Stream Failure Alert",+ template: SmtpTemplates.AuditLogStreamFailed,+ substitutions: {+ provider,+ windowFailureCount: failureCount,+ windowMinutes: FAILURE_WINDOW_MINUTES,+ streamUrl+ }+ })+ .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) => {+ try {+ const nowMinuteBucket = Math.floor(Date.now() / 60000);++ // Increment the current minute's bucket, anchoring its TTL on the first write so it+ // self-expires after the window passes without any cleanup needed on the success path.+ const currentBucketKey = KeyStorePrefixes.AuditLogStreamFailureBucket(streamId, nowMinuteBucket);+ const bucketCount = await keyStore.incrementBy(currentBucketKey, 1);+ if (bucketCount === 1) {+ await keyStore.setExpiry(currentBucketKey, BUCKET_TTL_SECONDS);+ }++ // Sum all buckets in the window with a single MGET round-trip.+ const bucketKeys = Array.from({ length: FAILURE_WINDOW_MINUTES }, (_, i) =>+ KeyStorePrefixes.AuditLogStreamFailureBucket(streamId, nowMinuteBucket - i)+ );+ const bucketValues = await keyStore.getItems(bucketKeys);+ const windowFailureCount = bucketValues.reduce((sum, val) => sum + (parseInt(val ?? "0", 10) || 0), 0);++ if (windowFailureCount < FAILURE_THRESHOLD) return;++ // NX lock ensures only one worker fires the alert within the cooldown window.+ const acquired = await keyStore.setItemWithExpiryNX(+ KeyStorePrefixes.AuditLogStreamAlertSent(streamId),+ FAILURE_ALERT_COOLDOWN_SECONDS,+ "1"+ );+ if (!acquired) return;++ void notifyStreamFailure(orgId, streamId, provider, windowFailureCount).catch((notifyErr) =>+ logger.error(+ notifyErr,+ `Failed to send audit log stream failure notification [streamId=${streamId}] [orgId=${orgId}]`+ )+ );+ } catch (trackingErr) {+ logger.error(+ trackingErr,+ `Failed to track audit log stream failure count [streamId=${streamId}] [orgId=${orgId}]`+ );+ }+ };+const streamLog = async (orgId: string, auditLog: TAuditLogs) => {const logStreams = await auditLogStreamDAL.find({ orgId });await Promise.allSettled(- logStreams.map(async ({ provider, encryptedCredentials }) => {+ logStreams.map(async (logStream) => {+ const { id, provider, encryptedCredentials } = logStream;const credentials = await decryptLogStreamCredentials({encryptedCredentials,orgId,@@ -238,10 +340,7 @@ export const auditLogStreamServiceFactory = ({const factory = LOG_STREAM_FACTORY_MAP[provider as LogProvider]();try {- await factory.streamLog({- credentials,- auditLog- });+ await factory.streamLog({ credentials, auditLog });} catch (error) {if (isAxiosError(error)) {logger.error(@@ -253,6 +352,8 @@ export const auditLogStreamServiceFactory = ({`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);}}));diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 08b8b70916..0ccf048e7b 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -130,7 +130,11 @@ 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+ TelemetryEventByBucketPattern: (event: string, bucketId: string) => `telemetry-event-${event}-${bucketId}-*` as const,++ AuditLogStreamFailureBucket: (streamId: string, minuteBucket: number) =>+ `audit-log-stream:${streamId}:failures:${minuteBucket}` as const,+ AuditLogStreamAlertSent: (streamId: string) => `audit-log-stream:${streamId}:alert-sent` as const};export const KeyStoreTtls = {@@ -524,6 +528,6 @@ export const keyStoreFactory = (streamAdd,streamRange,streamTrim,- streamCollect+ streamCollect,};};diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex 3dd7881182..465a85b8d7 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -79,8 +79,11 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {pgIncrementBy: async () => {return 1;},- incrementBy: async () => {- return 1;+ incrementBy: async (key, value) => {+ const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;+ const next = current + value;+ store[key] = String(next);+ return next;},incrementByAndRefreshExpiryIfUnderLimit: async () => {return 1;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 259384ef0a..c4a3176838 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -848,11 +848,22 @@ export const registerRoutes = async (permissionService});+ const notificationQueue = notificationQueueServiceFactory({+ userNotificationDAL,+ queueService+ });++ const notificationService = notificationServiceFactory({ notificationQueue, userNotificationDAL });+const auditLogStreamService = auditLogStreamServiceFactory({licenseService,permissionService,auditLogStreamDAL,- kmsService+ kmsService,+ keyStore,+ notificationService,+ smtpService,+ orgDAL});const auditLogQueue = await auditLogQueueServiceFactory({@@ -865,13 +876,6 @@ export const registerRoutes = async (keyStore});- const notificationQueue = notificationQueueServiceFactory({- userNotificationDAL,- queueService- });-- const notificationService = notificationServiceFactory({ notificationQueue, userNotificationDAL });-const announcementService = announcementServiceFactory({ userDAL, keyStore });const clickhouseAuditLogDAL = clickhousediff --git a/backend/src/services/notification/notification-types.ts b/backend/src/services/notification/notification-types.tsindex ad347a7231..34dc534e26 100644--- a/backend/src/services/notification/notification-types.ts+++ b/backend/src/services/notification/notification-types.ts@@ -22,7 +22,8 @@ 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_MIGRATION_RECOMMENDED = "audit-log-migration-recommended",+ AUDIT_LOG_STREAM_FAILED = "audit-log-stream-failed"}export interface TCreateUserNotificationDTO {diff --git a/backend/src/services/smtp/emails/AuditLogStreamFailedTemplate.tsx b/backend/src/services/smtp/emails/AuditLogStreamFailedTemplate.tsxnew file mode 100644index 0000000000..2b39bf5892--- /dev/null+++ b/backend/src/services/smtp/emails/AuditLogStreamFailedTemplate.tsx@@ -0,0 +1,55 @@+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;+}++export const AuditLogStreamFailedTemplate = ({+ provider,+ windowFailureCount,+ windowMinutes,+ streamUrl,+ siteUrl+}: 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>Failures in last {windowMinutes} min</strong>+ <Text className="text-[14px] text-red-600 mt-[4px]">{windowFailureCount}</Text>+ </Section>+ <Text className="text-[14px]">+ 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/org/example-org/audit-log-streams",+ siteUrl: "https://app.infisical.com"+} as AuditLogStreamFailedTemplateProps;diff --git a/backend/src/services/smtp/emails/index.ts b/backend/src/services/smtp/emails/index.tsindex 33ed3c140e..779a560df3 100644--- a/backend/src/services/smtp/emails/index.ts+++ b/backend/src/services/smtp/emails/index.ts@@ -3,6 +3,7 @@ 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.tsindex 52814d7246..d0d1ca5a62 100644--- a/backend/src/services/smtp/smtp-service.ts+++ b/backend/src/services/smtp/smtp-service.ts@@ -13,6 +13,7 @@ import {AccessPamRequestBypassedTemplate,AccountDeletionConfirmationTemplate,AuditLogMigrationAlertTemplate,+ AuditLogStreamFailedTemplate,CredentialRotationFailedTemplate,EmailChangeRequestNotificationTemplate,EmailMfaTemplate,@@ -106,7 +107,8 @@ export enum SmtpTemplates {DynamicSecretLeaseRevocationFailed = "dynamicSecretLeaseRevocationFailed",CredentialRotationFailed = "credentialRotationFailed",AuditLogMigrationAlert = "auditLogMigrationAlert",- HoneyTokenTriggered = "honeyTokenTriggered"+ HoneyTokenTriggered = "honeyTokenTriggered",+ AuditLogStreamFailed = "auditLogStreamFailed"}export enum SmtpHost {@@ -162,7 +164,8 @@ const EmailTemplateMap: Record<SmtpTemplates, React.FC<any>> = {[SmtpTemplates.DynamicSecretLeaseRevocationFailed]: DynamicSecretLeaseRevocationFailedTemplate,[SmtpTemplates.CredentialRotationFailed]: CredentialRotationFailedTemplate,[SmtpTemplates.AuditLogMigrationAlert]: AuditLogMigrationAlertTemplate,- [SmtpTemplates.HoneyTokenTriggered]: HoneyTokenTriggeredTemplate+ [SmtpTemplates.HoneyTokenTriggered]: HoneyTokenTriggeredTemplate,+ [SmtpTemplates.AuditLogStreamFailed]: AuditLogStreamFailedTemplate};export const smtpServiceFactory = (cfg: TSmtpConfig) => {