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
crypto and move trigger notification to honey token service
Matheus Nogueira8c7af86c52d6
diff --git a/backend/src/ee/routes/v1/honey-token-routers/honey-token-endpoints.ts b/backend/src/ee/routes/v1/honey-token-routers/honey-token-endpoints.tsindex eb7237e13e..539f39a404 100644--- a/backend/src/ee/routes/v1/honey-token-routers/honey-token-endpoints.ts+++ b/backend/src/ee/routes/v1/honey-token-routers/honey-token-endpoints.ts@@ -136,7 +136,7 @@ export const registerHoneyTokenEndpoints = <TConfig extends z.ZodTypeAny>({`Honey token trigger received [orgId=${req.params.orgId}] [type=${type}]`);- const { acknowledged } = await server.services.honeyTokenConfig.handleTrigger({+ const { acknowledged } = await server.services.honeyToken.handleTrigger({type,orgId: req.params.orgId,signature: req.headers["x-infisical-signature"] as string | undefined,diff --git a/backend/src/ee/services/honey-token/honey-token-aws-config-provider.ts b/backend/src/ee/services/honey-token/honey-token-aws-config-provider.tsindex ae42eb0131..b6f57bd91f 100644--- a/backend/src/ee/services/honey-token/honey-token-aws-config-provider.ts+++ b/backend/src/ee/services/honey-token/honey-token-aws-config-provider.ts@@ -1,12 +1,10 @@-import crypto from "node:crypto";+import { crypto } from "@app/lib/crypto/cryptography";import { CloudFormationClient, DescribeStacksCommand } from "@aws-sdk/client-cloudformation";import { ForbiddenError } from "@casl/ability";-import { OrganizationActionScope, OrgMembershipRole } from "@app/db/schemas";-import { getConfig as getAppConfig } from "@app/lib/config/env";-import { BadRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";-import { removeTrailingSlash } from "@app/lib/fn";+import { OrganizationActionScope } from "@app/db/schemas";+import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { OrgServiceActor } from "@app/lib/types";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";@@ -16,26 +14,15 @@ import { AwsConnectionSchema } from "@app/services/app-connection/aws/aws-connecimport { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";-import { TOrgDALFactory } from "@app/services/org/org-dal";-import { TProjectDALFactory } from "@app/services/project/project-dal";-import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";import { TLicenseServiceFactory } from "../license/license-service";import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPermissionServiceFactory } from "../permission/permission-service-types";import { THoneyTokenConfigDALFactory } from "./honey-token-config-dal";-import { THoneyTokenDALFactory } from "./honey-token-dal";-import { HoneyTokenEventType, HoneyTokenStatus, HoneyTokenType } from "./honey-token-enums";-import { THoneyTokenEventDALFactory } from "./honey-token-event-dal";-import {- AwsHoneyTokenConfigSchema,- AwsHoneyTokenEventMetadataSchema,- TAwsHoneyTokenEventMetadata-} from "./honey-token-types";+import { HoneyTokenType } from "./honey-token-enums";+import { AwsHoneyTokenConfigSchema } from "./honey-token-types";-const TRIGGER_NOTIFICATION_COOLDOWN_MS = 24 * 60 * 60 * 1000;const CF_COMPLETE_STATUSES = new Set(["CREATE_COMPLETE", "UPDATE_COMPLETE", "IMPORT_COMPLETE"]);-const SIGNATURE_TOLERANCE_MS = 5 * 60 * 1000;export interface THoneyTokenConfigRecord {id: string;@@ -59,18 +46,10 @@ export interface THoneyTokenConfigWithDecrypted {type TProviderDep = {honeyTokenConfigDAL: THoneyTokenConfigDALFactory;- honeyTokenDAL: Pick<- THoneyTokenDALFactory,- "findOne" | "updateById" | "tryMarkTriggered" | "findOneByTokenIdentifierAndOrgId"- >;- honeyTokenEventDAL: Pick<THoneyTokenEventDALFactory, "create">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;- orgDAL: Pick<TOrgDALFactory, "findOrgMembersByRole">;- projectDAL: Pick<TProjectDALFactory, "findById">;- smtpService: Pick<TSmtpService, "sendMail">;};const parseAwsConnectionConfig = (decryptedConnection: unknown): TAwsConnectionConfig => {@@ -86,15 +65,10 @@ const parseAwsConnectionConfig = (decryptedConnection: unknown): TAwsConnectionCexport const honeyTokenAwsConfigProviderFactory = ({honeyTokenConfigDAL,- honeyTokenDAL,- honeyTokenEventDAL,permissionService,kmsService,licenseService,- appConnectionDAL,- orgDAL,- projectDAL,- smtpService+ appConnectionDAL}: TProviderDep) => {const verifyStackDeployment = async ({connectionId: connId,@@ -278,125 +252,5 @@ export const honeyTokenAwsConfigProviderFactory = ({return { ...config, decryptedConfig };};- const sendTriggerNotification = async ({- orgId,- honeyToken,- eventMetadata- }: {- orgId: string;- honeyToken: { id: string; name: string; projectId: string };- eventMetadata: TAwsHoneyTokenEventMetadata;- }) => {- try {- const [project, orgAdmins] = await Promise.all([- projectDAL.findById(honeyToken.projectId),- orgDAL.findOrgMembersByRole(orgId, OrgMembershipRole.Admin)- ]);- const adminEmails = orgAdmins.map((admin) => admin.user.email).filter(Boolean) as string[];- if (adminEmails.length === 0 || !project) return;-- const cfg = getAppConfig();- const siteUrl = removeTrailingSlash(cfg.SITE_URL || "https://app.infisical.com");- await smtpService.sendMail({- recipients: adminEmails,- subjectLine: `Security Alert: Honey Token "${honeyToken.name}" Triggered`,- template: SmtpTemplates.HoneyTokenTriggered,- substitutions: {- honeyTokenName: honeyToken.name,- projectName: project.name,- eventName: eventMetadata.eventName,- eventTime: eventMetadata.eventTime,- sourceIp: eventMetadata.sourceIp || "Unknown",- awsRegion: eventMetadata.awsRegion,- projectUrl: `${siteUrl}/organizations/${orgId}/projects/secret-management/${project.id}/overview?honeyTokenId=${honeyToken.id}`- }- });- } catch (err) {- logger.error(- { err, orgId, honeyTokenId: honeyToken.id },- `Failed to send honey token trigger notification [orgId=${orgId}] [honeyTokenId=${honeyToken.id}]`- );- }- };-- const handleTrigger = async ({- orgId,- signature,- payload- }: {- orgId: string;- signature: string | undefined;- payload: unknown;- }) => {- if (!signature) throw new UnauthorizedError({ message: "Missing X-Infisical-Signature header" });-- const parts = Object.fromEntries(signature.split(",").map((p) => p.split("="))) as Record<string, string>;- const timestamp = parts.t;- const signatureHash = parts.v1;- if (!timestamp || !signatureHash) {- throw new UnauthorizedError({- message: "Invalid X-Infisical-Signature format. Expected t=<timestamp>,v1=<signature>"- });- }-- const timestampMs = Number(timestamp) * 1000;- if (Number.isNaN(timestampMs) || Math.abs(Date.now() - timestampMs) > SIGNATURE_TOLERANCE_MS) {- throw new UnauthorizedError({ message: "Request timestamp is too old or invalid" });- }-- const config = await honeyTokenConfigDAL.findOne({ orgId, type: HoneyTokenType.AWS });- if (!config?.encryptedConfig) {- throw new NotFoundError({ message: "No honey token configuration found for this organization" });- }-- const { decryptor } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.Organization, orgId });- const decrypted = decryptor({ cipherTextBlob: config.encryptedConfig });- const storedConfig = AwsHoneyTokenConfigSchema.parse(JSON.parse(decrypted.toString()) as unknown);-- const bodyString = JSON.stringify(payload);- const expectedSignature = crypto- .createHmac("sha256", storedConfig.webhookSigningKey)- .update(`${timestamp}.${bodyString}`)- .digest("hex");- const expectedBuf = Buffer.from(expectedSignature, "hex");- const receivedBuf = Buffer.from(signatureHash, "hex");- if (expectedBuf.byteLength !== receivedBuf.byteLength || !crypto.timingSafeEqual(expectedBuf, receivedBuf)) {- throw new UnauthorizedError({ message: "Invalid webhook signature" });- }-- const rawEvents = Array.isArray(payload) ? (payload as unknown[]) : [payload];- /* eslint-disable no-await-in-loop, no-continue */- for (const rawEvent of rawEvents) {- const wrapped = rawEvent as { event?: unknown };- const parsed = AwsHoneyTokenEventMetadataSchema.safeParse(wrapped.event ?? rawEvent);- if (!parsed.success) {- logger.warn(- { orgId, event: rawEvent, error: parsed.error },- `Failed to parse honey token event [orgId=${orgId}]`- );- continue;- }- const honeyToken = await honeyTokenDAL.findOneByTokenIdentifierAndOrgId(parsed.data.accessKeyId, orgId);- if (!honeyToken) continue;- if (honeyToken.status === HoneyTokenStatus.Revoked) continue;-- await honeyTokenEventDAL.create({- honeyTokenId: honeyToken.id,- eventType: HoneyTokenEventType.AWS,- metadata: parsed.data- });- const updatedToken = await honeyTokenDAL.tryMarkTriggered(- parsed.data.accessKeyId,- TRIGGER_NOTIFICATION_COOLDOWN_MS- );- if (updatedToken) {- void sendTriggerNotification({ orgId, honeyToken, eventMetadata: parsed.data });- }- }- /* eslint-enable no-await-in-loop, no-continue */-- return { acknowledged: true };- };-- return { upsertConfig, testConnection, getConfig, handleTrigger };+ return { upsertConfig, testConnection, getConfig };};diff --git a/backend/src/ee/services/honey-token/honey-token-aws-service-helpers.ts b/backend/src/ee/services/honey-token/honey-token-aws-service-helpers.tsindex 4c98982d77..1df17002bb 100644--- a/backend/src/ee/services/honey-token/honey-token-aws-service-helpers.ts+++ b/backend/src/ee/services/honey-token/honey-token-aws-service-helpers.ts@@ -1,4 +1,4 @@-import crypto from "node:crypto";+import { crypto } from "@app/lib/crypto/cryptography";import { CloudFormationClient, DescribeStacksCommand } from "@aws-sdk/client-cloudformation";import {diff --git a/backend/src/ee/services/honey-token/honey-token-config-service.ts b/backend/src/ee/services/honey-token/honey-token-config-service.tsindex c2c99b9dab..b796181f01 100644--- a/backend/src/ee/services/honey-token/honey-token-config-service.ts+++ b/backend/src/ee/services/honey-token/honey-token-config-service.ts@@ -2,9 +2,6 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";import { OrgServiceActor } from "@app/lib/types";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { TKmsServiceFactory } from "@app/services/kms/kms-service";-import { TOrgDALFactory } from "@app/services/org/org-dal";-import { TProjectDALFactory } from "@app/services/project/project-dal";-import { TSmtpService } from "@app/services/smtp/smtp-service";import { TLicenseServiceFactory } from "../license/license-service";import { TPermissionServiceFactory } from "../permission/permission-service-types";@@ -13,9 +10,7 @@ import {THoneyTokenConfigWithDecrypted} from "./honey-token-aws-config-provider";import { THoneyTokenConfigDALFactory } from "./honey-token-config-dal";-import { THoneyTokenDALFactory } from "./honey-token-dal";import { HoneyTokenType } from "./honey-token-enums";-import { THoneyTokenEventDALFactory } from "./honey-token-event-dal";import { THoneyTokenConfigByType, THoneyTokenTestConnectionResponseByType } from "./honey-token-provider-types";import {getHoneyTokenConfigProvidersByType,@@ -25,18 +20,10 @@ import {export type THoneyTokenConfigServiceFactoryDep = {honeyTokenConfigDAL: THoneyTokenConfigDALFactory;- honeyTokenDAL: Pick<- THoneyTokenDALFactory,- "findOne" | "updateById" | "tryMarkTriggered" | "findOneByTokenIdentifierAndOrgId"- >;- honeyTokenEventDAL: Pick<THoneyTokenEventDALFactory, "create">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;- orgDAL: Pick<TOrgDALFactory, "findOrgMembersByRole">;- projectDAL: Pick<TProjectDALFactory, "findById">;- smtpService: Pick<TSmtpService, "sendMail">;};export type THoneyTokenConfigServiceFactory = ReturnType<typeof honeyTokenConfigServiceFactory>;@@ -48,11 +35,6 @@ export type THoneyTokenConfigProvider<T extends HoneyTokenType = HoneyTokenType>}) => Promise<THoneyTokenConfigRecord>;testConnection: (input: { orgPermission: OrgServiceActor }) => Promise<THoneyTokenTestConnectionResponseByType[T]>;getConfig: (input: { orgPermission: OrgServiceActor }) => Promise<THoneyTokenConfigWithDecrypted>;- handleTrigger: (input: {- orgId: string;- signature: string | undefined;- payload: unknown;- }) => Promise<{ acknowledged: boolean }>;};const assertSupportedHoneyTokenType = (type: string): HoneyTokenType => {@@ -74,16 +56,16 @@ const assertHoneyTokenConnectionType = (type: HoneyTokenType, app: string) => {export const honeyTokenConfigServiceFactory = (deps: THoneyTokenConfigServiceFactoryDep) => {const honeyTokenConfigProviderByType = getHoneyTokenConfigProvidersByType(deps);- const upsertConfig = async ({+ const upsertConfig = async <T extends HoneyTokenType>({orgPermission,type,connectionId,config}: {orgPermission: OrgServiceActor;- type: HoneyTokenType;+ type: T;connectionId: string;- config: THoneyTokenConfigByType[HoneyTokenType];+ config: THoneyTokenConfigByType[T];}) => {const providerType = assertSupportedHoneyTokenType(type);const provider = honeyTokenConfigProviderByType[providerType];@@ -114,38 +96,24 @@ export const honeyTokenConfigServiceFactory = (deps: THoneyTokenConfigServiceFacreturn provider.testConnection({ orgPermission });};- const getConfig = async ({ orgPermission, type }: { orgPermission: OrgServiceActor; type: HoneyTokenType }) => {- const providerType = assertSupportedHoneyTokenType(type);- const provider = honeyTokenConfigProviderByType[providerType];- if (!provider) {- throw new BadRequestError({ message: "Unsupported honey token type" });- }- return provider.getConfig({ orgPermission });- };-- const handleTrigger = async ({- type,- orgId,- signature,- payload+ const getConfig = async <T extends HoneyTokenType>({+ orgPermission,+ type}: {- type: HoneyTokenType;- orgId: string;- signature: string | undefined;- payload: unknown;+ orgPermission: OrgServiceActor;+ type: T;}) => {const providerType = assertSupportedHoneyTokenType(type);const provider = honeyTokenConfigProviderByType[providerType];if (!provider) {throw new BadRequestError({ message: "Unsupported honey token type" });}- return provider.handleTrigger({ orgId, signature, payload });+ return provider.getConfig({ orgPermission });};return {upsertConfig,testConnection,- getConfig,- handleTrigger+ getConfig};};diff --git a/backend/src/ee/services/honey-token/honey-token-service-types.ts b/backend/src/ee/services/honey-token/honey-token-service-types.tsindex d6facc32d6..c95e88eaae 100644--- a/backend/src/ee/services/honey-token/honey-token-service-types.ts+++ b/backend/src/ee/services/honey-token/honey-token-service-types.ts@@ -3,7 +3,9 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { TFolderCommitServiceFactory } from "@app/services/folder-commit/folder-commit-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { TOrgDALFactory } from "@app/services/org/org-dal";import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";+import { TProjectDALFactory } from "@app/services/project/project-dal";import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";import { TSecretQueueFactory } from "@app/services/secret/secret-queue";import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";@@ -11,6 +13,7 @@ import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";import { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";+import { TSmtpService } from "@app/services/smtp/smtp-service";import { TSecretSnapshotServiceFactory } from "../secret-snapshot/secret-snapshot-service";import { THoneyTokenConfigDALFactory } from "./honey-token-config-dal";@@ -20,11 +23,17 @@ import { THoneyTokenEventDALFactory } from "./honey-token-event-dal";export type THoneyTokenServiceFactoryDep = {honeyTokenDAL: THoneyTokenDALFactory;honeyTokenConfigDAL: THoneyTokenConfigDALFactory;- honeyTokenEventDAL: Pick<THoneyTokenEventDALFactory, "find" | "countByHoneyTokenId" | "findByHoneyTokenId">;+ honeyTokenEventDAL: Pick<+ THoneyTokenEventDALFactory,+ "create" | "find" | "countByHoneyTokenId" | "findByHoneyTokenId"+ >;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;+ orgDAL: Pick<TOrgDALFactory, "findOrgMembersByRole">;+ projectDAL: Pick<TProjectDALFactory, "findById">;+ smtpService: Pick<TSmtpService, "sendMail">;folderDAL: Pick<TSecretFolderDALFactory,"findBySecretPath" | "findBySecretPathMultiEnv" | "findSecretPathByFolderIds"diff --git a/backend/src/ee/services/honey-token/honey-token-service.ts b/backend/src/ee/services/honey-token/honey-token-service.tsindex 18ebff4b3b..f1032c37cb 100644--- a/backend/src/ee/services/honey-token/honey-token-service.ts+++ b/backend/src/ee/services/honey-token/honey-token-service.ts@@ -1,19 +1,25 @@import { ForbiddenError } from "@casl/ability";-import { ActionProjectType, SecretType, TableName } from "@app/db/schemas";+import { ActionProjectType, OrgMembershipRole, SecretType, TableName } from "@app/db/schemas";import {ProjectPermissionHoneyTokenActions,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";-import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { crypto } from "@app/lib/crypto/cryptography";+import { getConfig as getAppConfig } from "@app/lib/config/env";+import { BadRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";+import { removeTrailingSlash } from "@app/lib/fn";+import { logger } from "@app/lib/logger";import { OrderByDirection, OrgServiceActor } from "@app/lib/types";import { ActorType } from "@app/services/auth/auth-type";import { KmsDataKey } from "@app/services/kms/kms-types";import { fnSecretBulkDelete, fnSecretBulkInsert } from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";+import { SmtpTemplates } from "@app/services/smtp/smtp-service";-import { HoneyTokenStatus, HoneyTokenType } from "./honey-token-enums";+import { HoneyTokenEventType, HoneyTokenStatus, HoneyTokenType } from "./honey-token-enums";import { THoneyTokenDeploymentStatus, THoneyTokenProviderHooks } from "./honey-token-provider-hook-types";import { THoneyTokenByIdInput, THoneyTokenCreateInput } from "./honey-token-provider-types";+import { AwsHoneyTokenConfigSchema, AwsHoneyTokenEventMetadataSchema } from "./honey-token-types";import {getHoneyTokenProviderDefinition,getHoneyTokenServiceHooksByType,@@ -21,6 +27,9 @@ import {} from "./honey-token-provider-registry";import { THoneyTokenServiceFactoryDep } from "./honey-token-service-types";+const TRIGGER_NOTIFICATION_COOLDOWN_MS = 24 * 60 * 60 * 1000;+const SIGNATURE_TOLERANCE_MS = 5 * 60 * 1000;+const assertSupportedHoneyTokenType = (type: string): HoneyTokenType => {if (Object.prototype.hasOwnProperty.call(HONEY_TOKEN_PROVIDER_MAP, type)) {return type as HoneyTokenType;@@ -61,6 +70,9 @@ export const honeyTokenServiceFactory = ({licenseService,kmsService,appConnectionDAL,+ orgDAL,+ projectDAL,+ smtpService,folderDAL,projectBotService,secretDAL,@@ -81,6 +93,9 @@ export const honeyTokenServiceFactory = ({licenseService,kmsService,appConnectionDAL,+ orgDAL,+ projectDAL,+ smtpService,folderDAL,projectBotService,secretDAL,@@ -689,6 +704,141 @@ export const honeyTokenServiceFactory = ({};};+ const sendTriggerNotification = async ({+ orgId,+ honeyToken,+ eventMetadata+ }: {+ orgId: string;+ honeyToken: { id: string; name: string; projectId: string };+ eventMetadata: {+ eventName: string;+ eventTime: string;+ sourceIp?: string;+ awsRegion: string;+ };+ }) => {+ try {+ const [project, orgAdmins] = await Promise.all([+ projectDAL.findById(honeyToken.projectId),+ orgDAL.findOrgMembersByRole(orgId, OrgMembershipRole.Admin)+ ]);+ const adminEmails = orgAdmins.map((admin) => admin.user.email).filter(Boolean) as string[];+ if (adminEmails.length === 0 || !project) return;++ const cfg = getAppConfig();+ const siteUrl = removeTrailingSlash(cfg.SITE_URL || "https://app.infisical.com");+ await smtpService.sendMail({+ recipients: adminEmails,+ subjectLine: `Security Alert: Honey Token "${honeyToken.name}" Triggered`,+ template: SmtpTemplates.HoneyTokenTriggered,+ substitutions: {+ honeyTokenName: honeyToken.name,+ projectName: project.name,+ eventName: eventMetadata.eventName,+ eventTime: eventMetadata.eventTime,+ sourceIp: eventMetadata.sourceIp || "Unknown",+ awsRegion: eventMetadata.awsRegion,+ projectUrl: `${siteUrl}/organizations/${orgId}/projects/secret-management/${project.id}/overview?honeyTokenId=${honeyToken.id}`+ }+ });+ } catch (err) {+ logger.error(+ { err, orgId, honeyTokenId: honeyToken.id },+ `Failed to send honey token trigger notification [orgId=${orgId}] [honeyTokenId=${honeyToken.id}]`+ );+ }+ };++ const handleTrigger = async ({+ type,+ orgId,+ signature,+ payload+ }: {+ type: HoneyTokenType;+ orgId: string;+ signature: string | undefined;+ payload: unknown;+ }) => {+ const providerType = assertSupportedHoneyTokenType(type);+ if (providerType !== HoneyTokenType.AWS) {+ throw new BadRequestError({ message: "Unsupported honey token type" });+ }++ if (!signature) throw new UnauthorizedError({ message: "Missing X-Infisical-Signature header" });++ const parts = Object.fromEntries(signature.split(",").map((p) => p.split("="))) as Record<string, string>;+ const timestamp = parts.t;+ const signatureHash = parts.v1;+ if (!timestamp || !signatureHash) {+ throw new UnauthorizedError({+ message: "Invalid X-Infisical-Signature format. Expected t=<timestamp>,v1=<signature>"+ });+ }++ const timestampMs = Number(timestamp) * 1000;+ if (Number.isNaN(timestampMs) || Math.abs(Date.now() - timestampMs) > SIGNATURE_TOLERANCE_MS) {+ throw new UnauthorizedError({ message: "Request timestamp is too old or invalid" });+ }++ const config = await honeyTokenConfigDAL.findOne({ orgId, type: HoneyTokenType.AWS });+ if (!config?.encryptedConfig) {+ throw new NotFoundError({ message: "No honey token configuration found for this organization" });+ }++ const { decryptor } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.Organization, orgId });+ const decrypted = decryptor({ cipherTextBlob: config.encryptedConfig });+ const storedConfig = AwsHoneyTokenConfigSchema.parse(JSON.parse(decrypted.toString()) as unknown);++ const bodyString = JSON.stringify(payload);+ const expectedSignature = crypto.nativeCrypto+ .createHmac("sha256", storedConfig.webhookSigningKey)+ .update(`${timestamp}.${bodyString}`)+ .digest("hex");+ const expectedBuf = Buffer.from(expectedSignature, "hex");+ const receivedBuf = Buffer.from(signatureHash, "hex");+ if (+ expectedBuf.byteLength !== receivedBuf.byteLength ||+ !crypto.nativeCrypto.timingSafeEqual(expectedBuf, receivedBuf)+ ) {+ throw new UnauthorizedError({ message: "Invalid webhook signature" });+ }++ const rawEvents = Array.isArray(payload) ? (payload as unknown[]) : [payload];+ /* eslint-disable no-await-in-loop, no-continue */+ for (const rawEvent of rawEvents) {+ const wrapped = rawEvent as { event?: unknown };+ const parsed = AwsHoneyTokenEventMetadataSchema.safeParse(wrapped.event ?? rawEvent);+ if (!parsed.success) {+ logger.warn(+ { orgId, event: rawEvent, error: parsed.error },+ `Failed to parse honey token event [orgId=${orgId}]`+ );+ continue;+ }+ const honeyToken = await honeyTokenDAL.findOneByTokenIdentifierAndOrgId(parsed.data.accessKeyId, orgId);+ if (!honeyToken) continue;+ if (honeyToken.status === HoneyTokenStatus.Revoked) continue;++ await honeyTokenEventDAL.create({+ honeyTokenId: honeyToken.id,+ eventType: HoneyTokenEventType.AWS,+ metadata: parsed.data+ });+ const updatedToken = await honeyTokenDAL.tryMarkTriggered(+ parsed.data.accessKeyId,+ TRIGGER_NOTIFICATION_COOLDOWN_MS+ );+ if (updatedToken) {+ void sendTriggerNotification({ orgId, honeyToken, eventMetadata: parsed.data });+ }+ }+ /* eslint-enable no-await-in-loop, no-continue */++ return { acknowledged: true };+ };+const getHoneyTokenById = async ({ honeyTokenId, projectId }: { honeyTokenId: string; projectId: string },actor: OrgServiceActor@@ -768,6 +918,7 @@ export const honeyTokenServiceFactory = ({getHoneyTokenEvents,getDashboardHoneyTokenCount,getOrgHoneyTokenLimit,- getDashboardHoneyTokens+ getDashboardHoneyTokens,+ handleTrigger};};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 1f617435b6..12b9c0cf43 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -960,15 +960,10 @@ export const registerRoutes = async (const honeyTokenConfigService = honeyTokenConfigServiceFactory({honeyTokenConfigDAL,- honeyTokenDAL,- honeyTokenEventDAL,permissionService,kmsService,licenseService,- appConnectionDAL,- orgDAL,- projectDAL,- smtpService+ appConnectionDAL});// ldapService is created after loginService (below) due to dependency on processProviderCallback@@ -1653,6 +1648,9 @@ export const registerRoutes = async (licenseService,kmsService,appConnectionDAL,+ orgDAL,+ projectDAL,+ smtpService,folderDAL,projectBotService,secretDAL: secretV2BridgeDAL,