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
refactor: backend to be more generic and extensible
Matheus Nogueirae2bc774cad30
diff --git a/backend/src/ee/routes/v1/honey-token-router.ts b/backend/src/ee/routes/v1/honey-token-router.tsindex 57e803cb12..6cf2b67b8b 100644--- a/backend/src/ee/routes/v1/honey-token-router.ts+++ b/backend/src/ee/routes/v1/honey-token-router.ts@@ -2,22 +2,14 @@ import { z } from "zod";import { HoneyTokenConfigsSchema, HoneyTokensSchema } from "@app/db/schemas";import { HoneyTokenType } from "@app/ee/services/honey-token/honey-token-enums";-import { AwsHoneyTokenConfigSchema } from "@app/ee/services/honey-token/honey-token-types";-import { logger } from "@app/lib/logger";+import {+ HONEY_TOKEN_CREDENTIALS_RESPONSE_SCHEMA_MAP,+ HONEY_TOKEN_REGISTER_ROUTER_MAP+} from "@app/ee/services/honey-token/honey-token-provider-registry";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { slugSchema } from "@app/server/lib/schemas";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";-import { AwsHoneyTokenCredentialsSchema } from "@app/ee/services/honey-token/honey-token-aws-types";--const SanitizedHoneyTokenConfigSchema = HoneyTokenConfigsSchema.pick({- id: true,- orgId: true,- type: true,- connectionId: true,- createdAt: true,- updatedAt: true-});const HoneyTokenResponseSchema = HoneyTokensSchema.pick({id: true,@@ -65,14 +57,15 @@ const HoneyTokenResetResponseSchema = HoneyTokensSchema.pick({lastResetAt: z.date().nullable()});-const HoneyTokenCredentialsResponseSchema = z.discriminatedUnion("type", [- z.object({- type: z.literal(HoneyTokenType.AWS),- credentials: AwsHoneyTokenCredentialsSchema- })-]);+const HoneyTokenCredentialsResponseSchema = z.discriminatedUnion(+ "type",+ Object.values(HONEY_TOKEN_CREDENTIALS_RESPONSE_SCHEMA_MAP) as unknown as [+ z.ZodDiscriminatedUnionOption<"type">,+ ...z.ZodDiscriminatedUnionOption<"type">[]+ ]+);-export const registerHoneyTokenRouter = async (server: FastifyZodProvider) => {+export const registerHoneyTokenGenericRouter = async (server: FastifyZodProvider) => {server.route({url: "/limits",method: "GET",@@ -116,10 +109,12 @@ export const registerHoneyTokenRouter = async (server: FastifyZodProvider) => {response: {200: z.object({honeyToken: HoneyTokenResponseSchema,- stackDeployment: z.object({- deployed: z.boolean(),- status: z.string().nullable()- })+ stackDeployment: z+ .object({+ deployed: z.boolean(),+ status: z.string().nullable()+ })+ .optional()})}},@@ -289,7 +284,7 @@ export const registerHoneyTokenRouter = async (server: FastifyZodProvider) => {}},handler: async (req) => {- const { credentials } = await server.services.honeyToken.getCredentials(+ const { type, credentials } = await server.services.honeyToken.getCredentials({honeyTokenId: req.params.id,projectId: req.query.projectId@@ -297,7 +292,7 @@ export const registerHoneyTokenRouter = async (server: FastifyZodProvider) => {req.permission);return {- type: HoneyTokenType.AWS,+ type,credentials};}@@ -349,129 +344,12 @@ export const registerHoneyTokenRouter = async (server: FastifyZodProvider) => {}});- server.route({- url: "/configs",- method: "PUT",- config: {- rateLimit: writeLimit- },- onRequest: verifyAuth([AuthMode.JWT]),- schema: {- body: z.object({- type: z.nativeEnum(HoneyTokenType),- connectionId: z.string().uuid(),- config: AwsHoneyTokenConfigSchema- }),- response: {- 200: z.object({- config: SanitizedHoneyTokenConfigSchema- })- }- },- handler: async (req) => {- const config = await server.services.honeyTokenConfig.upsertConfig({- orgPermission: req.permission,- type: req.body.type,- connectionId: req.body.connectionId,- config: req.body.config- });-- return { config };- }- });-- server.route({- url: "/configs/:type/test-connection",- method: "POST",- config: {- rateLimit: writeLimit- },- onRequest: verifyAuth([AuthMode.JWT]),- schema: {- params: z.object({- type: z.nativeEnum(HoneyTokenType)- }),- response: {- 200: z.object({- isConnected: z.boolean(),- status: z.string().nullable(),- stackName: z.string()- })- }- },- handler: async (req) => {- return server.services.honeyTokenConfig.testConnection({- orgPermission: req.permission,- type: req.params.type- });- }- });-- server.route({- url: "/configs/:type",- method: "GET",- config: {- rateLimit: readLimit- },- onRequest: verifyAuth([AuthMode.JWT]),- schema: {- params: z.object({- type: z.nativeEnum(HoneyTokenType)- }),- response: {- 200: z.object({- config: SanitizedHoneyTokenConfigSchema.extend({- id: z.string().nullable(),- connectionId: z.string().nullable(),- createdAt: z.date().nullable(),- updatedAt: z.date().nullable(),- decryptedConfig: z- .object({ webhookSigningKey: z.string(), stackName: z.string(), awsRegion: z.string() })- .nullable()- })- })- }- },- handler: async (req) => {- const config = await server.services.honeyTokenConfig.getConfig({- orgPermission: req.permission,- type: req.params.type- });-- return { config };- }- });-- server.route({- url: "/:orgId/trigger",- method: "POST",- config: {- rateLimit: writeLimit- },- schema: {- params: z.object({- orgId: z.string().trim()- }),- body: z.unknown(),- response: {- 200: z.object({- acknowledged: z.boolean()- })- }- },- handler: async (req) => {- logger.info(- { orgId: req.params.orgId, payload: req.body, headers: req.headers },- `Honey token trigger received [orgId=${req.params.orgId}]`- );+};- const { acknowledged } = await server.services.honeyTokenConfig.handleTrigger({- orgId: req.params.orgId,- signature: req.headers["x-infisical-signature"] as string | undefined,- payload: req.body- });+export const registerHoneyTokenRouter = async (server: FastifyZodProvider) => {+ await registerHoneyTokenGenericRouter(server);- return { acknowledged };- }- });+ for await (const [type, router] of Object.entries(HONEY_TOKEN_REGISTER_ROUTER_MAP)) {+ await server.register(router, { prefix: `/${type}` });+ }};diff --git a/backend/src/ee/routes/v1/honey-token-routers/aws-honey-token-router.ts b/backend/src/ee/routes/v1/honey-token-routers/aws-honey-token-router.tsnew file mode 100644index 0000000000..3c0fffcd85--- /dev/null+++ b/backend/src/ee/routes/v1/honey-token-routers/aws-honey-token-router.ts@@ -0,0 +1,21 @@+import { z } from "zod";++import { AwsHoneyTokenConfigSchema } from "@app/ee/services/honey-token/honey-token-types";+import { HoneyTokenType } from "@app/ee/services/honey-token/honey-token-enums";++import { registerHoneyTokenEndpoints } from "./honey-token-endpoints";++export const registerAwsHoneyTokenRouter = async (server: FastifyZodProvider) =>+ registerHoneyTokenEndpoints({+ server,+ type: HoneyTokenType.AWS,+ configSchema: AwsHoneyTokenConfigSchema,+ decryptedConfigSchema: AwsHoneyTokenConfigSchema,+ testConnectionResponseSchema: z+ .object({+ isConnected: z.boolean(),+ status: z.string().nullable(),+ stackName: z.string()+ })+ .passthrough()+ });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.tsnew file mode 100644index 0000000000..eb7237e13e--- /dev/null+++ b/backend/src/ee/routes/v1/honey-token-routers/honey-token-endpoints.ts@@ -0,0 +1,149 @@+import { z } from "zod";++import { HoneyTokenConfigsSchema } from "@app/db/schemas";+import { HoneyTokenType } from "@app/ee/services/honey-token/honey-token-enums";+import { logger } from "@app/lib/logger";+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";++const SanitizedHoneyTokenConfigSchema = HoneyTokenConfigsSchema.pick({+ id: true,+ orgId: true,+ type: true,+ connectionId: true,+ createdAt: true,+ updatedAt: true+});++export const registerHoneyTokenEndpoints = <TConfig extends z.ZodTypeAny>({+ server,+ type,+ configSchema,+ testConnectionResponseSchema,+ decryptedConfigSchema+}: {+ server: FastifyZodProvider;+ type: HoneyTokenType;+ configSchema: TConfig;+ testConnectionResponseSchema: z.ZodTypeAny;+ decryptedConfigSchema: z.ZodTypeAny;+}) => {+ const upsertBodySchema = z.object({+ connectionId: z.string().uuid(),+ config: configSchema+ });++ server.route({+ url: "/configs",+ method: "PUT",+ config: {+ rateLimit: writeLimit+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ schema: {+ body: upsertBodySchema,+ response: {+ 200: z.object({+ config: SanitizedHoneyTokenConfigSchema+ })+ }+ },+ handler: async (req) => {+ const { connectionId, config } = req.body as { connectionId: string; config: unknown };+ const parsedConfig = configSchema.parse(config);+ const savedConfig = await server.services.honeyTokenConfig.upsertConfig({+ orgPermission: req.permission,+ type,+ connectionId,+ config: parsedConfig+ });++ return { config: savedConfig };+ }+ });++ server.route({+ url: "/configs/test-connection",+ method: "POST",+ config: {+ rateLimit: writeLimit+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ schema: {+ response: {+ 200: testConnectionResponseSchema+ }+ },+ handler: async (req) => {+ return server.services.honeyTokenConfig.testConnection({+ orgPermission: req.permission,+ type+ });+ }+ });++ server.route({+ url: "/configs",+ method: "GET",+ config: {+ rateLimit: readLimit+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ schema: {+ response: {+ 200: z.object({+ config: SanitizedHoneyTokenConfigSchema.extend({+ id: z.string().nullable(),+ connectionId: z.string().nullable(),+ createdAt: z.date().nullable(),+ updatedAt: z.date().nullable(),+ decryptedConfig: decryptedConfigSchema.nullable()+ })+ })+ }+ },+ handler: async (req) => {+ const config = await server.services.honeyTokenConfig.getConfig({+ orgPermission: req.permission,+ type+ });++ return { config };+ }+ });++ server.route({+ url: "/:orgId/trigger",+ method: "POST",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ params: z.object({+ orgId: z.string().trim()+ }),+ body: z.unknown(),+ response: {+ 200: z.object({+ acknowledged: z.boolean()+ })+ }+ },+ handler: async (req) => {+ logger.info(+ { orgId: req.params.orgId, payload: req.body, headers: req.headers, type },+ `Honey token trigger received [orgId=${req.params.orgId}] [type=${type}]`+ );++ const { acknowledged } = await server.services.honeyTokenConfig.handleTrigger({+ type,+ orgId: req.params.orgId,+ signature: req.headers["x-infisical-signature"] as string | undefined,+ payload: req.body+ });++ return { acknowledged };+ }+ });+};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.tsnew file mode 100644index 0000000000..ae42eb0131--- /dev/null+++ b/backend/src/ee/services/honey-token/honey-token-aws-config-provider.ts@@ -0,0 +1,402 @@+import crypto from "node:crypto";++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 { logger } from "@app/lib/logger";+import { OrgServiceActor } from "@app/lib/types";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";+import { getAwsConnectionConfig } from "@app/services/app-connection/aws";+import { AwsConnectionSchema } from "@app/services/app-connection/aws/aws-connection-schemas";+import { 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";++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;+ orgId: string;+ type: string;+ connectionId: string;+ createdAt: Date;+ updatedAt: Date;+ encryptedConfig?: Buffer | null;+}++export interface THoneyTokenConfigWithDecrypted {+ id: string | null;+ orgId: string;+ type: string;+ connectionId: string | null;+ createdAt: Date | null;+ updatedAt: Date | null;+ decryptedConfig: { webhookSigningKey: string; stackName: string; awsRegion: string } | null;+}++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 => {+ const parsedConnection = AwsConnectionSchema.safeParse(decryptedConnection);+ if (!parsedConnection.success) {+ throw new BadRequestError({+ message: "Invalid AWS App Connection configuration"+ });+ }++ return parsedConnection.data as TAwsConnectionConfig;+};++export const honeyTokenAwsConfigProviderFactory = ({+ honeyTokenConfigDAL,+ honeyTokenDAL,+ honeyTokenEventDAL,+ permissionService,+ kmsService,+ licenseService,+ appConnectionDAL,+ orgDAL,+ projectDAL,+ smtpService+}: TProviderDep) => {+ const verifyStackDeployment = async ({+ connectionId: connId,+ stackName,+ awsRegion+ }: {+ connectionId: string;+ stackName: string;+ awsRegion: string;+ }): Promise<{ deployed: boolean; status: string | null }> => {+ try {+ const appConnection = await appConnectionDAL.findById(connId);+ if (!appConnection) {+ return { deployed: false, status: null };+ }++ const decryptedConnection = await decryptAppConnection(appConnection, kmsService);+ const awsConfig = parseAwsConnectionConfig(decryptedConnection);+ const { credentials: awsCredentials } = await getAwsConnectionConfig(awsConfig);++ const cfn = new CloudFormationClient({ credentials: awsCredentials, region: awsRegion });+ const res = await cfn.send(new DescribeStacksCommand({ StackName: stackName }));+ const stack = res.Stacks?.[0];+ if (!stack) {+ return { deployed: false, status: null };+ }++ return {+ deployed: CF_COMPLETE_STATUSES.has(stack.StackStatus ?? ""),+ status: stack.StackStatus ?? null+ };+ } catch (err) {+ const awsCode = (err as { code?: string }).code;+ if (awsCode === "AccessDenied" || awsCode === "ExpiredToken" || awsCode === "InvalidClientTokenId") {+ throw new BadRequestError({+ message:+ "The AWS App Connection does not have permission to describe CloudFormation stacks. Ensure the connection's IAM role or credentials include the cloudformation:DescribeStacks permission."+ });+ }+ if (awsCode === "ValidationError") return { deployed: false, status: null };+ logger.warn(+ { err, connectionId: connId, stackName, awsRegion },+ `Failed to verify CloudFormation stack [stackName=${stackName}] [awsRegion=${awsRegion}]`+ );+ return { deployed: false, status: null };+ }+ };++ const upsertConfig = async ({+ orgPermission,+ connectionId,+ config+ }: {+ orgPermission: OrgServiceActor;+ connectionId: string;+ config: { webhookSigningKey: string; stackName?: string; awsRegion?: string };+ }): Promise<THoneyTokenConfigRecord> => {+ const { permission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor: orgPermission.type,+ actorId: orgPermission.id,+ orgId: orgPermission.orgId,+ actorAuthMethod: orgPermission.authMethod,+ actorOrgId: orgPermission.orgId+ });+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);++ const plan = await licenseService.getPlan(orgPermission.orgId);+ if (!plan.honeyTokens) {+ throw new BadRequestError({+ message: "Failed to save honey token configuration due to plan restriction. Upgrade plan to use honey tokens."+ });+ }++ const validatedConfig = AwsHoneyTokenConfigSchema.parse(config);+ const { encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.Organization,+ orgId: orgPermission.orgId+ });+ const encryptedConfig = encryptor({+ plainText: Buffer.from(JSON.stringify(validatedConfig))+ }).cipherTextBlob;++ const existing = await honeyTokenConfigDAL.findOne({+ orgId: orgPermission.orgId,+ type: HoneyTokenType.AWS+ });+ if (existing) {+ return honeyTokenConfigDAL.updateById(existing.id, { connectionId, encryptedConfig });+ }+ return honeyTokenConfigDAL.create({+ orgId: orgPermission.orgId,+ type: HoneyTokenType.AWS,+ connectionId,+ encryptedConfig+ });+ };++ const testConnection = async ({ orgPermission }: { orgPermission: OrgServiceActor }) => {+ const { permission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor: orgPermission.type,+ actorId: orgPermission.id,+ orgId: orgPermission.orgId,+ actorAuthMethod: orgPermission.authMethod,+ actorOrgId: orgPermission.orgId+ });+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);++ const config = await honeyTokenConfigDAL.findOne({+ orgId: orgPermission.orgId,+ type: HoneyTokenType.AWS+ });+ if (!config?.encryptedConfig || !config.connectionId) {+ throw new BadRequestError({ message: "Honey token configuration not found. Save the configuration first." });+ }++ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.Organization,+ orgId: orgPermission.orgId+ });+ const decrypted = decryptor({ cipherTextBlob: config.encryptedConfig });+ const storedConfig = AwsHoneyTokenConfigSchema.parse(JSON.parse(decrypted.toString()) as unknown);++ const stackDeployment = await verifyStackDeployment({+ connectionId: config.connectionId,+ stackName: storedConfig.stackName,+ awsRegion: storedConfig.awsRegion+ });+ return {+ isConnected: stackDeployment.deployed,+ status: stackDeployment.status,+ stackName: storedConfig.stackName+ };+ };++ const getConfig = async ({+ orgPermission+ }: {+ orgPermission: OrgServiceActor;+ }): Promise<THoneyTokenConfigWithDecrypted> => {+ const { permission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor: orgPermission.type,+ actorId: orgPermission.id,+ orgId: orgPermission.orgId,+ actorAuthMethod: orgPermission.authMethod,+ actorOrgId: orgPermission.orgId+ });+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);++ const config = await honeyTokenConfigDAL.findOne({+ orgId: orgPermission.orgId,+ type: HoneyTokenType.AWS+ });+ if (!config) {+ return {+ id: null,+ orgId: orgPermission.orgId,+ type: HoneyTokenType.AWS,+ connectionId: null,+ createdAt: null,+ updatedAt: null,+ decryptedConfig: {+ webhookSigningKey: `htk_live_${crypto.randomBytes(24).toString("hex")}`,+ stackName: "infisical-honey-tokens",+ awsRegion: "us-east-1"+ }+ };+ }++ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.Organization,+ orgId: orgPermission.orgId+ });+ let decryptedConfig: { webhookSigningKey: string; stackName: string; awsRegion: string } | null = null;+ if (config.encryptedConfig) {+ const decrypted = decryptor({ cipherTextBlob: config.encryptedConfig });+ decryptedConfig = AwsHoneyTokenConfigSchema.parse(JSON.parse(decrypted.toString()) as unknown);+ }+ 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 };+};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.tsnew file mode 100644index 0000000000..4c98982d77--- /dev/null+++ b/backend/src/ee/services/honey-token/honey-token-aws-service-helpers.ts@@ -0,0 +1,137 @@+import crypto from "node:crypto";++import { CloudFormationClient, DescribeStacksCommand } from "@aws-sdk/client-cloudformation";+import {+ CreateAccessKeyCommand,+ CreateUserCommand,+ DeleteAccessKeyCommand,+ DeleteUserCommand,+ IAMClient+} from "@aws-sdk/client-iam";++import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";+import { getAwsConnectionConfig } from "@app/services/app-connection/aws";+import { AwsConnectionSchema } from "@app/services/app-connection/aws/aws-connection-schemas";+import { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";++type TEncryptedAppConnection = Parameters<typeof decryptAppConnection>[0];++const HONEY_TOKEN_IAM_USER_PREFIX = "inf_ht_";+const CF_COMPLETE_STATUSES = new Set(["CREATE_COMPLETE", "UPDATE_COMPLETE", "IMPORT_COMPLETE"]);++const parseAwsConnectionConfig = (decryptedConnection: unknown): TAwsConnectionConfig => {+ const parsedConnection = AwsConnectionSchema.safeParse(decryptedConnection);+ if (!parsedConnection.success) {+ throw new BadRequestError({+ message: "Invalid AWS App Connection configuration"+ });+ }++ return parsedConnection.data as TAwsConnectionConfig;+};++export const verifyAwsStackDeployment = async ({+ connectionId,+ stackName,+ appConnectionDAL,+ kmsService+}: {+ connectionId: string;+ stackName: string;+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+}): Promise<{ deployed: boolean; status: string | null }> => {+ try {+ const appConnection = await appConnectionDAL.findById(connectionId);+ if (!appConnection) return { deployed: false, status: null };++ const decryptedConnection = await decryptAppConnection(appConnection, kmsService);+ const awsConfig = parseAwsConnectionConfig(decryptedConnection);+ const { credentials: awsCredentials } = await getAwsConnectionConfig(awsConfig);++ const cfn = new CloudFormationClient({ credentials: awsCredentials, region: "us-east-1" });+ const res = await cfn.send(new DescribeStacksCommand({ StackName: stackName }));+ const stack = res.Stacks?.[0];++ if (!stack) return { deployed: false, status: null };++ return {+ deployed: CF_COMPLETE_STATUSES.has(stack.StackStatus ?? ""),+ status: stack.StackStatus ?? null+ };+ } catch (err) {+ const awsCode = (err as { code?: string }).code;++ if (awsCode === "ValidationError") {+ return { deployed: false, status: null };+ }++ logger.warn({ err, connectionId, stackName }, "Failed to verify honey token CloudFormation stack deployment");+ return { deployed: false, status: null };+ }+};++export const createAwsIamHoneyTokenCredentials = async ({+ appConnection,+ kmsService+}: {+ appConnection: TEncryptedAppConnection;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+}) => {+ const decryptedConnection = await decryptAppConnection(appConnection, kmsService);+ const awsConfig = parseAwsConnectionConfig(decryptedConnection);+ const { credentials: awsCredentials, region } = await getAwsConnectionConfig(awsConfig);+ const iam = new IAMClient({ credentials: awsCredentials, region });++ const iamUserName = `${HONEY_TOKEN_IAM_USER_PREFIX}${crypto.randomBytes(8).toString("hex")}`;+ await iam.send(new CreateUserCommand({ UserName: iamUserName }));++ const createKeyRes = await iam.send(new CreateAccessKeyCommand({ UserName: iamUserName }));+ if (!createKeyRes.AccessKey?.AccessKeyId || !createKeyRes.AccessKey?.SecretAccessKey) {+ throw new BadRequestError({ message: "Failed to create AWS access key for honey token" });+ }++ return {+ accessKeyId: createKeyRes.AccessKey.AccessKeyId,+ secretAccessKey: createKeyRes.AccessKey.SecretAccessKey,+ iamUserName+ };+};++export const revokeAwsIamHoneyTokenCredentials = async ({+ appConnection,+ kmsService,+ iamUserName,+ accessKeyId+}: {+ appConnection: TEncryptedAppConnection;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ iamUserName: string;+ accessKeyId: string;+}) => {+ const decryptedConnection = await decryptAppConnection(appConnection, kmsService);+ const awsConfig = parseAwsConnectionConfig(decryptedConnection);+ const { credentials: awsCredentials, region } = await getAwsConnectionConfig(awsConfig);+ const iam = new IAMClient({ credentials: awsCredentials, region });++ try {+ await iam.send(+ new DeleteAccessKeyCommand({+ UserName: iamUserName,+ AccessKeyId: accessKeyId+ })+ );+ } catch {+ // Access key may already be deleted+ }++ try {+ await iam.send(new DeleteUserCommand({ UserName: iamUserName }));+ } catch {+ // IAM user may already be deleted+ }+};diff --git a/backend/src/ee/services/honey-token/honey-token-aws-service.ts b/backend/src/ee/services/honey-token/honey-token-aws-service.tsnew file mode 100644index 0000000000..c8876c6de8--- /dev/null+++ b/backend/src/ee/services/honey-token/honey-token-aws-service.ts@@ -0,0 +1,64 @@+import {+ createAwsIamHoneyTokenCredentials,+ revokeAwsIamHoneyTokenCredentials,+ verifyAwsStackDeployment+} from "./honey-token-aws-service-helpers";+import { parseAwsHoneyTokenDecryptedCredentials } from "./honey-token-aws-types";+import { THoneyTokenProviderHooks } from "./honey-token-provider-hook-types";+import { THoneyTokenServiceFactoryDep } from "./honey-token-service-types";+import { KmsDataKey } from "@app/services/kms/kms-types";++type THoneyTokenAwsProviderHookFactoryDep = Pick<+ THoneyTokenServiceFactoryDep,+ "kmsService" | "appConnectionDAL"+>;++export const honeyTokenAwsProviderHooksFactory = ({+ kmsService,+ appConnectionDAL+}: THoneyTokenAwsProviderHookFactoryDep): THoneyTokenProviderHooks => ({+ createCredentials: (appConnection) =>+ createAwsIamHoneyTokenCredentials({+ appConnection,+ kmsService+ }).then((credentials) => ({+ credentials,+ tokenIdentifier: credentials.accessKeyId+ })),+ revokeCredentials: ({ appConnection, credentials }) =>+ revokeAwsIamHoneyTokenCredentials({+ appConnection,+ kmsService,+ iamUserName: credentials.iamUserName,+ accessKeyId: credentials.accessKeyId+ }),+ verifyDeployment: async ({ connectionId, orgId, encryptedConfig }) => {+ const { decryptor: configDecryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.Organization,+ orgId+ });+ const stackName = encryptedConfig+ ? JSON.parse(configDecryptor({ cipherTextBlob: encryptedConfig }).toString()).stackName+ : "infisical-honey-tokens";++ return verifyAwsStackDeployment({+ connectionId,+ stackName,+ appConnectionDAL,+ kmsService+ });+ },+ getCredentialsForDisplay: async ({ encryptedCredentials, orgId }) => {+ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.Organization,+ orgId+ });+ const decryptedCredentials = parseAwsHoneyTokenDecryptedCredentials(+ JSON.parse(decryptor({ cipherTextBlob: encryptedCredentials }).toString()) as unknown+ );+ return {+ accessKeyId: decryptedCredentials.accessKeyId,+ secretAccessKey: decryptedCredentials.secretAccessKey+ };+ }+});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 8afec5a46b..c2c99b9dab 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@@ -1,40 +1,29 @@-import crypto from "node:crypto";--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 { logger } from "@app/lib/logger";+import { BadRequestError, NotFoundError } from "@app/lib/errors";import { OrgServiceActor } from "@app/lib/types";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";-import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";-import { getAwsConnectionConfig } from "@app/services/app-connection/aws";-import { 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 { 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 {+ THoneyTokenConfigRecord,+ THoneyTokenConfigWithDecrypted+} from "./honey-token-aws-config-provider";import { THoneyTokenConfigDALFactory } from "./honey-token-config-dal";import { THoneyTokenDALFactory } from "./honey-token-dal";-import { HoneyTokenEventType, HoneyTokenStatus, HoneyTokenType } from "./honey-token-enums";+import { HoneyTokenType } from "./honey-token-enums";import { THoneyTokenEventDALFactory } from "./honey-token-event-dal";+import { THoneyTokenConfigByType, THoneyTokenTestConnectionResponseByType } from "./honey-token-provider-types";import {- AwsHoneyTokenConfigSchema,- AwsHoneyTokenEventMetadataSchema,- TAwsHoneyTokenEventMetadata-} from "./honey-token-types";--const TRIGGER_NOTIFICATION_COOLDOWN_MS = 24 * 60 * 60 * 1000;+ getHoneyTokenConfigProvidersByType,+ getHoneyTokenProviderDefinition,+ HONEY_TOKEN_PROVIDER_MAP+} from "./honey-token-provider-registry";-type THoneyTokenConfigServiceFactoryDep = {+export type THoneyTokenConfigServiceFactoryDep = {honeyTokenConfigDAL: THoneyTokenConfigDALFactory;honeyTokenDAL: Pick<THoneyTokenDALFactory,@@ -51,74 +40,39 @@ type THoneyTokenConfigServiceFactoryDep = {};export type THoneyTokenConfigServiceFactory = ReturnType<typeof honeyTokenConfigServiceFactory>;--const CF_COMPLETE_STATUSES = new Set(["CREATE_COMPLETE", "UPDATE_COMPLETE", "IMPORT_COMPLETE"]);--export const honeyTokenConfigServiceFactory = ({- honeyTokenConfigDAL,- honeyTokenDAL,- honeyTokenEventDAL,- permissionService,- kmsService,- licenseService,- appConnectionDAL,- orgDAL,- projectDAL,- smtpService-}: THoneyTokenConfigServiceFactoryDep) => {- const verifyStackDeployment = async ({- connectionId: connId,- stackName,- awsRegion- }: {+export type THoneyTokenConfigProvider<T extends HoneyTokenType = HoneyTokenType> = {+ upsertConfig: (input: {+ orgPermission: OrgServiceActor;connectionId: string;- stackName: string;- awsRegion: string;- }): Promise<{ deployed: boolean; status: string | null }> => {- try {- const appConnection = await appConnectionDAL.findById(connId);- if (!appConnection) {- return { deployed: false, status: null };- }-- const decryptedConnection = await decryptAppConnection(appConnection, kmsService);- const awsConfig = decryptedConnection as unknown as TAwsConnectionConfig;- const { credentials: awsCredentials } = await getAwsConnectionConfig(awsConfig);-- const cfn = new CloudFormationClient({ credentials: awsCredentials, region: awsRegion });- const res = await cfn.send(new DescribeStacksCommand({ StackName: stackName }));-- const stack = res.Stacks?.[0];- if (!stack) {- return { deployed: false, status: null };- }-- return {- deployed: CF_COMPLETE_STATUSES.has(stack.StackStatus ?? ""),- status: stack.StackStatus ?? null- };- } catch (err) {- const awsCode = (err as { code?: string }).code;+ config: THoneyTokenConfigByType[T];+ }) => 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 }>;+};- if (awsCode === "AccessDenied" || awsCode === "ExpiredToken" || awsCode === "InvalidClientTokenId") {- throw new BadRequestError({- message:- "The AWS App Connection does not have permission to describe CloudFormation stacks. " +- "Ensure the connection's IAM role or credentials include the cloudformation:DescribeStacks permission."- });- }+const assertSupportedHoneyTokenType = (type: string): HoneyTokenType => {+ if (Object.prototype.hasOwnProperty.call(HONEY_TOKEN_PROVIDER_MAP, type)) {+ return type as HoneyTokenType;+ }+ throw new BadRequestError({ message: "Unsupported honey token type" });+};- if (awsCode === "ValidationError") {- return { deployed: false, status: null };- }+const assertHoneyTokenConnectionType = (type: HoneyTokenType, app: string) => {+ const provider = getHoneyTokenProviderDefinition(type);+ if (app !== provider.connectionApp) {+ throw new BadRequestError({+ message: `Honey Token is not configured for ${provider.name}`+ });+ }+};- logger.warn(- { err, connectionId: connId, stackName, awsRegion },- `Failed to verify CloudFormation stack [stackName=${stackName}] [awsRegion=${awsRegion}]`- );- return { deployed: false, status: null };- }- };+export const honeyTokenConfigServiceFactory = (deps: THoneyTokenConfigServiceFactoryDep) => {+ const honeyTokenConfigProviderByType = getHoneyTokenConfigProvidersByType(deps);const upsertConfig = async ({orgPermission,@@ -129,322 +83,63 @@ export const honeyTokenConfigServiceFactory = ({orgPermission: OrgServiceActor;type: HoneyTokenType;connectionId: string;- config: { webhookSigningKey: string; stackName?: string; awsRegion?: string };+ config: THoneyTokenConfigByType[HoneyTokenType];}) => {- const { permission } = await permissionService.getOrgPermission({- scope: OrganizationActionScope.Any,- actor: orgPermission.type,- actorId: orgPermission.id,- orgId: orgPermission.orgId,- actorAuthMethod: orgPermission.authMethod,- actorOrgId: orgPermission.orgId- });-- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);-- const plan = await licenseService.getPlan(orgPermission.orgId);- if (!plan.honeyTokens) {- throw new BadRequestError({- message: "Failed to save honey token configuration due to plan restriction. Upgrade plan to use honey tokens."- });+ const providerType = assertSupportedHoneyTokenType(type);+ const provider = honeyTokenConfigProviderByType[providerType];+ if (!provider) {+ throw new BadRequestError({ message: "Unsupported honey token type" });}-- const validatedConfig = AwsHoneyTokenConfigSchema.parse(config);-- const { encryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: orgPermission.orgId- });-- const encryptedConfig = encryptor({- plainText: Buffer.from(JSON.stringify(validatedConfig))- }).cipherTextBlob;-- const existing = await honeyTokenConfigDAL.findOne({- orgId: orgPermission.orgId,- type- });-- if (existing) {- return honeyTokenConfigDAL.updateById(existing.id, {- connectionId,- encryptedConfig- });+ const appConnection = await deps.appConnectionDAL.findById(connectionId);+ if (!appConnection) {+ throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });}- return honeyTokenConfigDAL.create({- orgId: orgPermission.orgId,- type,- connectionId,- encryptedConfig- });+ assertHoneyTokenConnectionType(providerType, appConnection.app);+ return provider.upsertConfig({ orgPermission, connectionId, config });};- const testConnection = async ({ orgPermission, type }: { orgPermission: OrgServiceActor; type: HoneyTokenType }) => {- const { permission } = await permissionService.getOrgPermission({- scope: OrganizationActionScope.Any,- actor: orgPermission.type,- actorId: orgPermission.id,- orgId: orgPermission.orgId,- actorAuthMethod: orgPermission.authMethod,- actorOrgId: orgPermission.orgId- });-- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);-- const config = await honeyTokenConfigDAL.findOne({- orgId: orgPermission.orgId,- type- });-- if (!config?.encryptedConfig || !config.connectionId) {- throw new BadRequestError({- message: "Honey token configuration not found. Save the configuration first."- });+ const testConnection = async <T extends HoneyTokenType>({+ orgPermission,+ type+ }: {+ orgPermission: OrgServiceActor;+ type: T;+ }): Promise<THoneyTokenTestConnectionResponseByType[T]> => {+ const providerType = assertSupportedHoneyTokenType(type);+ const provider = honeyTokenConfigProviderByType[providerType];+ if (!provider) {+ throw new BadRequestError({ message: "Unsupported honey token type" });}-- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: orgPermission.orgId- });-- const decrypted = decryptor({ cipherTextBlob: config.encryptedConfig });- const storedConfig = AwsHoneyTokenConfigSchema.parse(JSON.parse(decrypted.toString()) as unknown);-- const stackDeployment = await verifyStackDeployment({- connectionId: config.connectionId,- stackName: storedConfig.stackName,- awsRegion: storedConfig.awsRegion- });-- return {- isConnected: stackDeployment.deployed,- status: stackDeployment.status,- stackName: storedConfig.stackName- };+ return provider.testConnection({ orgPermission });};const getConfig = async ({ orgPermission, type }: { orgPermission: OrgServiceActor; type: HoneyTokenType }) => {- const { permission } = await permissionService.getOrgPermission({- scope: OrganizationActionScope.Any,- actor: orgPermission.type,- actorId: orgPermission.id,- orgId: orgPermission.orgId,- actorAuthMethod: orgPermission.authMethod,- actorOrgId: orgPermission.orgId- });-- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);-- const config = await honeyTokenConfigDAL.findOne({- orgId: orgPermission.orgId,- type- });-- if (!config) {- const generatedKey = `htk_live_${crypto.randomBytes(24).toString("hex")}`;- return {- id: null,- orgId: orgPermission.orgId,- type,- connectionId: null,- createdAt: null,- updatedAt: null,- decryptedConfig: {- webhookSigningKey: generatedKey,- stackName: "infisical-honey-tokens",- awsRegion: "us-east-1"- }- };- }-- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: orgPermission.orgId- });-- let decryptedConfig: { webhookSigningKey: string; stackName: string; awsRegion: string } | null = null;- if (config.encryptedConfig) {- const decrypted = decryptor({- cipherTextBlob: config.encryptedConfig- });- decryptedConfig = AwsHoneyTokenConfigSchema.parse(JSON.parse(decrypted.toString()) as unknown);- }-- 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 providerType = assertSupportedHoneyTokenType(type);+ const provider = honeyTokenConfigProviderByType[providerType];+ if (!provider) {+ throw new BadRequestError({ message: "Unsupported honey token type" });}+ return provider.getConfig({ orgPermission });};- const SIGNATURE_TOLERANCE_MS = 5 * 60 * 1000;-const handleTrigger = async ({+ type,orgId,signature,payload}: {+ type: HoneyTokenType;orgId: string;signature: string | undefined;payload: unknown;}) => {- if (!signature) {- throw new UnauthorizedError({ message: "Missing X-Infisical-Signature header" });- }-- // Header format: t=<unix-seconds>,v1=<hmac-sha256-hex>- 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 providerType = assertSupportedHoneyTokenType(type);+ const provider = honeyTokenConfigProviderByType[providerType];+ if (!provider) {+ throw new BadRequestError({ message: "Unsupported honey token type" });}-- 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 signedPayload = `${timestamp}.${bodyString}`;- const expectedSignature = crypto- .createHmac("sha256", storedConfig.webhookSigningKey)- .update(signedPayload)- .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 { type?: string; event?: unknown };- const eventData = wrapped.event ?? rawEvent;-- const parsed = AwsHoneyTokenEventMetadataSchema.safeParse(eventData);- 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) {- logger.warn(- { orgId, accessKeyId: parsed.data.accessKeyId },- `No honey token found for accessKeyId in organization [orgId=${orgId}] [accessKeyId=${parsed.data.accessKeyId}]`- );- continue;- }-- if (honeyToken.status === HoneyTokenStatus.Revoked) {- logger.info(- { orgId, honeyTokenId: honeyToken.id, accessKeyId: parsed.data.accessKeyId },- `Ignoring trigger event for revoked honey token [orgId=${orgId}] [honeyTokenId=${honeyToken.id}]`- );- 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) {- logger.info(- { orgId, honeyTokenId: honeyToken.id, eventName: parsed.data.eventName },- `Honey token triggered [orgId=${orgId}] [honeyTokenId=${honeyToken.id}]`- );-- void sendTriggerNotification({- orgId,- honeyToken,- eventMetadata: parsed.data- });- }- }- /* eslint-enable no-await-in-loop, no-continue */-- return { acknowledged: true };+ return provider.handleTrigger({ orgId, signature, payload });};return {diff --git a/backend/src/ee/services/honey-token/honey-token-dal.ts b/backend/src/ee/services/honey-token/honey-token-dal.tsindex 66357ad078..86eace57d9 100644--- a/backend/src/ee/services/honey-token/honey-token-dal.ts+++ b/backend/src/ee/services/honey-token/honey-token-dal.ts@@ -63,8 +63,10 @@ export const honeyTokenDALFactory = (db: TDbClient) => {void query.where(`${TableName.HoneyToken}.name`, "ilike", `%${search}%`);}- const [result] = await query.countDistinct(`${TableName.HoneyToken}.name`);- return Number((result as unknown as { count: number }).count || 0);+ const [result] = await query.countDistinct<{ count: string | number }>({+ count: `${TableName.HoneyToken}.name`+ });+ return Number(result?.count ?? 0);};const findOneByTokenIdentifierAndOrgId = async (@@ -87,9 +89,11 @@ export const honeyTokenDALFactory = (db: TDbClient) => {.join(TableName.Project, `${TableName.HoneyToken}.projectId`, `${TableName.Project}.id`).where(`${TableName.Project}.orgId`, orgId).whereNot(`${TableName.HoneyToken}.status`, "revoked")- .count(`${TableName.HoneyToken}.id`);+ .count<{ count: string | number }>({+ count: `${TableName.HoneyToken}.id`+ });- return Number((result as unknown as { count: number }).count || 0);+ return Number(result?.count ?? 0);};const tryMarkTriggered = async (diff --git a/backend/src/ee/services/honey-token/honey-token-provider-definitions.ts b/backend/src/ee/services/honey-token/honey-token-provider-definitions.tsnew file mode 100644index 0000000000..44d31daa68--- /dev/null+++ b/backend/src/ee/services/honey-token/honey-token-provider-definitions.ts@@ -0,0 +1,45 @@+import { z } from "zod";++import { AppConnection } from "@app/services/app-connection/app-connection-enums";++import { honeyTokenAwsConfigProviderFactory } from "./honey-token-aws-config-provider";+import { honeyTokenAwsProviderHooksFactory } from "./honey-token-aws-service";+import { AwsHoneyTokenCredentialsSchema } from "./honey-token-aws-types";+import { HoneyTokenType } from "./honey-token-enums";+import { THoneyTokenProviderHooks } from "./honey-token-provider-hook-types";+import { THoneyTokenConfigByType, THoneyTokenDisplayCredentialsByType } from "./honey-token-provider-types";+import { AwsHoneyTokenConfigSchema } from "./honey-token-types";+import type { THoneyTokenConfigProvider, THoneyTokenConfigServiceFactoryDep } from "./honey-token-config-service";+import type { THoneyTokenServiceFactoryDep } from "./honey-token-service-types";+import { registerAwsHoneyTokenRouter } from "@app/ee/routes/v1/honey-token-routers/aws-honey-token-router";++export type THoneyTokenProviderDefinition<T extends HoneyTokenType = HoneyTokenType> = {+ type: T;+ name: string;+ connectionApp: AppConnection;+ configSchema: z.ZodType<THoneyTokenConfigByType[T], z.ZodTypeDef, unknown>;+ credentialsResponseSchema: z.ZodType<{+ type: T;+ credentials: THoneyTokenDisplayCredentialsByType[T];+ }>;+ serviceHooksFactory: (deps: THoneyTokenServiceFactoryDep) => THoneyTokenProviderHooks;+ configProviderFactory: (deps: THoneyTokenConfigServiceFactoryDep) => THoneyTokenConfigProvider<T>;+ registerRouter?: (server: FastifyZodProvider) => Promise<void>;+};++export const HONEY_TOKEN_PROVIDER_DEFINITIONS: THoneyTokenProviderDefinition[] = [+ {+ type: HoneyTokenType.AWS,+ name: "AWS",+ connectionApp: AppConnection.AWS,+ configSchema: AwsHoneyTokenConfigSchema,+ credentialsResponseSchema: z.object({+ type: z.literal(HoneyTokenType.AWS),+ credentials: AwsHoneyTokenCredentialsSchema+ }),+ serviceHooksFactory: ({ kmsService, appConnectionDAL }) =>+ honeyTokenAwsProviderHooksFactory({ kmsService, appConnectionDAL }),+ configProviderFactory: (deps) => honeyTokenAwsConfigProviderFactory(deps),+ registerRouter: registerAwsHoneyTokenRouter+ }+];diff --git a/backend/src/ee/services/honey-token/honey-token-provider-hook-types.ts b/backend/src/ee/services/honey-token/honey-token-provider-hook-types.tsnew file mode 100644index 0000000000..2b3436b493--- /dev/null+++ b/backend/src/ee/services/honey-token/honey-token-provider-hook-types.ts@@ -0,0 +1,28 @@+import { THoneyTokenServiceFactoryDep } from "./honey-token-service-types";++export type THoneyTokenAppConnection = NonNullable<+ Awaited<ReturnType<THoneyTokenServiceFactoryDep["appConnectionDAL"]["findById"]>>+>;++export type THoneyTokenDeploymentStatus = { deployed: boolean; status: string | null };++export type THoneyTokenProviderHooks = {+ createCredentials: (appConnection: THoneyTokenAppConnection) => Promise<{+ credentials: Record<string, string>;+ tokenIdentifier: string;+ }>;+ revokeCredentials: (input: {+ appConnection: THoneyTokenAppConnection;+ credentials: Record<string, string>;+ }) => Promise<void>;+ verifyDeployment?: (input: {+ appConnection: THoneyTokenAppConnection;+ orgId: string;+ encryptedConfig?: Buffer | null;+ connectionId: string;+ }) => Promise<THoneyTokenDeploymentStatus>;+ getCredentialsForDisplay: (input: {+ encryptedCredentials: Buffer;+ orgId: string;+ }) => Promise<Record<string, string>>;+};diff --git a/backend/src/ee/services/honey-token/honey-token-provider-registry.ts b/backend/src/ee/services/honey-token/honey-token-provider-registry.tsnew file mode 100644index 0000000000..579c489cdb--- /dev/null+++ b/backend/src/ee/services/honey-token/honey-token-provider-registry.ts@@ -0,0 +1,67 @@+import { BadRequestError } from "@app/lib/errors";++import { HoneyTokenType } from "./honey-token-enums";+import { THoneyTokenProviderHooks } from "./honey-token-provider-hook-types";+import { HONEY_TOKEN_PROVIDER_DEFINITIONS, THoneyTokenProviderDefinition } from "./honey-token-provider-definitions";+import type { THoneyTokenConfigProvider, THoneyTokenConfigServiceFactoryDep } from "./honey-token-config-service";+import type { THoneyTokenServiceFactoryDep } from "./honey-token-service-types";++export const HONEY_TOKEN_PROVIDER_MAP: Record<HoneyTokenType, THoneyTokenProviderDefinition> =+ HONEY_TOKEN_PROVIDER_DEFINITIONS.reduce((acc, provider) => {+ acc[provider.type] = provider;+ return acc;+ }, {} as Record<HoneyTokenType, THoneyTokenProviderDefinition>);++export const HONEY_TOKEN_NAME_MAP: Record<HoneyTokenType, string> = HONEY_TOKEN_PROVIDER_DEFINITIONS.reduce(+ (acc, provider) => {+ acc[provider.type] = provider.name;+ return acc;+ },+ {} as Record<HoneyTokenType, string>+);++export const HONEY_TOKEN_CONNECTION_MAP = HONEY_TOKEN_PROVIDER_DEFINITIONS.reduce((acc, provider) => {+ acc[provider.type] = provider.connectionApp;+ return acc;+}, {} as Record<HoneyTokenType, THoneyTokenProviderDefinition["connectionApp"]>);++export const HONEY_TOKEN_CONFIG_SCHEMA_MAP = HONEY_TOKEN_PROVIDER_DEFINITIONS.reduce((acc, provider) => {+ acc[provider.type] = provider.configSchema;+ return acc;+}, {} as Record<HoneyTokenType, THoneyTokenProviderDefinition["configSchema"]>);++export const HONEY_TOKEN_CREDENTIALS_RESPONSE_SCHEMA_MAP = HONEY_TOKEN_PROVIDER_DEFINITIONS.reduce((acc, provider) => {+ acc[provider.type] = provider.credentialsResponseSchema;+ return acc;+}, {} as Record<HoneyTokenType, THoneyTokenProviderDefinition["credentialsResponseSchema"]>);++export const HONEY_TOKEN_REGISTER_ROUTER_MAP = HONEY_TOKEN_PROVIDER_DEFINITIONS.reduce((acc, provider) => {+ if (provider.registerRouter) {+ acc[provider.type] = provider.registerRouter;+ }+ return acc;+}, {} as Partial<Record<HoneyTokenType, (server: FastifyZodProvider) => Promise<void>>>);++export const getHoneyTokenProviderDefinition = (type: string) => {+ const provider = HONEY_TOKEN_PROVIDER_MAP[type as HoneyTokenType];+ if (!provider) {+ throw new BadRequestError({ message: "Unsupported honey token type" });+ }+ return provider;+};++export const getHoneyTokenServiceHooksByType = (+ deps: THoneyTokenServiceFactoryDep+): Record<HoneyTokenType, THoneyTokenProviderHooks> =>+ HONEY_TOKEN_PROVIDER_DEFINITIONS.reduce((acc, provider) => {+ acc[provider.type] = provider.serviceHooksFactory(deps);+ return acc;+ }, {} as Record<HoneyTokenType, THoneyTokenProviderHooks>);++export const getHoneyTokenConfigProvidersByType = (+ deps: THoneyTokenConfigServiceFactoryDep+): { [K in HoneyTokenType]: THoneyTokenConfigProvider<K> } =>+ HONEY_TOKEN_PROVIDER_DEFINITIONS.reduce((acc, provider) => {+ acc[provider.type] = provider.configProviderFactory(deps);+ return acc;+ }, {} as { [K in HoneyTokenType]: THoneyTokenConfigProvider<K> });diff --git a/backend/src/ee/services/honey-token/honey-token-provider-types.ts b/backend/src/ee/services/honey-token/honey-token-provider-types.tsnew file mode 100644index 0000000000..47ea3fe2b3--- /dev/null+++ b/backend/src/ee/services/honey-token/honey-token-provider-types.ts@@ -0,0 +1,52 @@+import { OrderByDirection } from "@app/lib/types";++import { TAwsHoneyTokenCredentials } from "./honey-token-aws-types";+import { HoneyTokenType } from "./honey-token-enums";+import { TAwsHoneyTokenConfig } from "./honey-token-types";++export type THoneyTokenCreateInput = {+ projectId: string;+ type: HoneyTokenType;+ name: string;+ description?: string | null;+ secretsMapping: Record<string, string>;+ environment: string;+ secretPath: string;+};++export type THoneyTokenUpdateInput = {+ honeyTokenId: string;+ projectId: string;+ name?: string;+ description?: string | null;+ secretsMapping?: Record<string, string>;+};++export type THoneyTokenByIdInput = { honeyTokenId: string; projectId: string };++export type THoneyTokenListInput = {+ projectId: string;+ environments: string[];+ secretPath: string;+ search?: string;+ orderBy?: string;+ orderDirection?: OrderByDirection;+ limit?: number;+ offset?: number;+};++export type THoneyTokenConfigByType = {+ [HoneyTokenType.AWS]: TAwsHoneyTokenConfig;+};++export type THoneyTokenDisplayCredentialsByType = {+ [HoneyTokenType.AWS]: TAwsHoneyTokenCredentials;+};++export type THoneyTokenTestConnectionResponseByType = {+ [HoneyTokenType.AWS]: {+ isConnected: boolean;+ status: string | null;+ stackName: string;+ };+};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.tsnew file mode 100644index 0000000000..d6facc32d6--- /dev/null+++ b/backend/src/ee/services/honey-token/honey-token-service-types.ts@@ -0,0 +1,44 @@+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { 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 { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";+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";+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 { TSecretSnapshotServiceFactory } from "../secret-snapshot/secret-snapshot-service";+import { THoneyTokenConfigDALFactory } from "./honey-token-config-dal";+import { THoneyTokenDALFactory } from "./honey-token-dal";+import { THoneyTokenEventDALFactory } from "./honey-token-event-dal";++export type THoneyTokenServiceFactoryDep = {+ honeyTokenDAL: THoneyTokenDALFactory;+ honeyTokenConfigDAL: THoneyTokenConfigDALFactory;+ honeyTokenEventDAL: Pick<THoneyTokenEventDALFactory, "find" | "countByHoneyTokenId" | "findByHoneyTokenId">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;+ folderDAL: Pick<+ TSecretFolderDALFactory,+ "findBySecretPath" | "findBySecretPathMultiEnv" | "findSecretPathByFolderIds"+ >;+ projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;+ secretDAL: Pick<+ TSecretV2BridgeDALFactory,+ "insertMany" | "upsertSecretReferences" | "find" | "deleteMany" | "invalidateSecretCacheByProjectId"+ >;+ secretVersionDAL: Pick<TSecretVersionV2DALFactory, "insertMany" | "findLatestVersionMany">;+ secretVersionTagDAL: Pick<TSecretVersionV2TagDALFactory, "insertMany">;+ secretTagDAL: TSecretTagDALFactory;+ folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;+ resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany">;+ snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">;+ secretQueueService: Pick<TSecretQueueFactory, "syncSecrets" | "removeSecretReminder">;+};diff --git a/backend/src/ee/services/honey-token/honey-token-service.ts b/backend/src/ee/services/honey-token/honey-token-service.tsindex b5f0994cf3..9c16ee3ed9 100644--- a/backend/src/ee/services/honey-token/honey-token-service.ts+++ b/backend/src/ee/services/honey-token/honey-token-service.ts@@ -1,81 +1,58 @@-import crypto from "node:crypto";--import { CloudFormationClient, DescribeStacksCommand } from "@aws-sdk/client-cloudformation";-import {- CreateAccessKeyCommand,- CreateUserCommand,- DeleteAccessKeyCommand,- DeleteUserCommand,- IAMClient-} from "@aws-sdk/client-iam";import { ForbiddenError } from "@casl/ability";import { ActionProjectType, SecretType, TableName } from "@app/db/schemas";-import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";-import { ProjectPermissionHoneyTokenActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";+import {+ ProjectPermissionActions,+ ProjectPermissionHoneyTokenActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";import { BadRequestError, NotFoundError } from "@app/lib/errors";-import { logger } from "@app/lib/logger";import { OrderByDirection, OrgServiceActor } from "@app/lib/types";-import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";-import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";-import { getAwsConnectionConfig } from "@app/services/app-connection/aws";-import { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types";import { ActorType } from "@app/services/auth/auth-type";-import { TFolderCommitServiceFactory } from "@app/services/folder-commit/folder-commit-service";-import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";-import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";-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";-import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";-import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";import { fnSecretBulkDelete, fnSecretBulkInsert } from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";-import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";-import { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";-import { TSecretSnapshotServiceFactory } from "../secret-snapshot/secret-snapshot-service";-import { THoneyTokenConfigDALFactory } from "./honey-token-config-dal";-import { THoneyTokenDALFactory } from "./honey-token-dal";import { HoneyTokenStatus, HoneyTokenType } from "./honey-token-enums";-import { THoneyTokenEventDALFactory } from "./honey-token-event-dal";-import { AwsHoneyTokenConfigSchema } from "./honey-token-types";+import { THoneyTokenDeploymentStatus, THoneyTokenProviderHooks } from "./honey-token-provider-hook-types";+import { THoneyTokenByIdInput, THoneyTokenCreateInput } from "./honey-token-provider-types";import {- parseAwsHoneyTokenDecryptedCredentials,- TAwsHoneyTokenCredentials-} from "./honey-token-aws-types";--const HONEY_TOKEN_IAM_USER_PREFIX = "inf_ht_";-const CF_COMPLETE_STATUSES = new Set(["CREATE_COMPLETE", "UPDATE_COMPLETE", "IMPORT_COMPLETE"]);--type THoneyTokenServiceFactoryDep = {- honeyTokenDAL: THoneyTokenDALFactory;- honeyTokenConfigDAL: THoneyTokenConfigDALFactory;- honeyTokenEventDAL: Pick<THoneyTokenEventDALFactory, "find" | "countByHoneyTokenId" | "findByHoneyTokenId">;- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;- licenseService: Pick<TLicenseServiceFactory, "getPlan">;- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;- folderDAL: Pick<- TSecretFolderDALFactory,- "findBySecretPath" | "findBySecretPathMultiEnv" | "findSecretPathByFolderIds"- >;- projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;- secretDAL: Pick<- TSecretV2BridgeDALFactory,- "insertMany" | "upsertSecretReferences" | "find" | "deleteMany" | "invalidateSecretCacheByProjectId"- >;- secretVersionDAL: Pick<TSecretVersionV2DALFactory, "insertMany" | "findLatestVersionMany">;- secretVersionTagDAL: Pick<TSecretVersionV2TagDALFactory, "insertMany">;- secretTagDAL: Pick<TSecretTagDALFactory, "saveTagsToSecretV2" | "find">;- folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;- resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany">;- snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">;- secretQueueService: Pick<TSecretQueueFactory, "syncSecrets" | "removeSecretReminder">;+ getHoneyTokenProviderDefinition,+ getHoneyTokenServiceHooksByType,+ HONEY_TOKEN_PROVIDER_MAP+} from "./honey-token-provider-registry";+import { THoneyTokenServiceFactoryDep } from "./honey-token-service-types";++const assertSupportedHoneyTokenType = (type: string): HoneyTokenType => {+ if (Object.prototype.hasOwnProperty.call(HONEY_TOKEN_PROVIDER_MAP, type)) {+ return type as HoneyTokenType;+ }+ throw new BadRequestError({ message: "Unsupported honey token type" });+};++const assertHoneyTokenConnectionType = (type: HoneyTokenType, app: string) => {+ const provider = getHoneyTokenProviderDefinition(type);+ if (app !== provider.connectionApp) {+ throw new BadRequestError({+ message: `Honey Token is not configured for ${provider.name}`+ });+ }};export type THoneyTokenServiceFactory = ReturnType<typeof honeyTokenServiceFactory>;+interface THoneyTokenCreateResult {+ honeyToken: {+ id: string;+ name: string;+ description?: string | null;+ type: string;+ status: string;+ projectId: string;+ secretsMapping: unknown;+ createdAt: Date;+ updatedAt: Date;+ };+ stackDeployment?: THoneyTokenDeploymentStatus;+}export const honeyTokenServiceFactory = ({honeyTokenDAL,@@ -96,71 +73,87 @@ export const honeyTokenServiceFactory = ({snapshotService,secretQueueService}: THoneyTokenServiceFactoryDep) => {- const verifyStackDeployment = async ({- connectionId,- stackName+ const honeyTokenProviderHooksByType: Record<HoneyTokenType, THoneyTokenProviderHooks> =+ getHoneyTokenServiceHooksByType({+ honeyTokenDAL,+ honeyTokenConfigDAL,+ honeyTokenEventDAL,+ permissionService,+ licenseService,+ kmsService,+ appConnectionDAL,+ folderDAL,+ projectBotService,+ secretDAL,+ secretVersionDAL,+ secretVersionTagDAL,+ secretTagDAL,+ folderCommitService,+ resourceMetadataDAL,+ snapshotService,+ secretQueueService+ });++ const ensurePlanSupportsHoneyTokens = async (orgId: string, action: string) => {+ const plan = await licenseService.getPlan(orgId);+ if (!plan.honeyTokens) {+ throw new BadRequestError({+ message: `Failed to ${action} due to plan restriction. Upgrade plan to use honey tokens.`+ });+ }+ return plan;+ };++ const getProjectPermission = async (projectId: string, actor: OrgServiceActor) =>+ permissionService.getProjectPermission({+ actor: actor.type,+ actorId: actor.id,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ actionProjectType: ActionProjectType.SecretManager,+ projectId+ });++ const assertProjectPermission = async ({+ projectId,+ actor,+ action}: {- connectionId: string;- stackName: string;- }): Promise<{ deployed: boolean; status: string | null }> => {- try {- const appConnection = await appConnectionDAL.findById(connectionId);- if (!appConnection) return { deployed: false, status: null };-- const decryptedConnection = await decryptAppConnection(appConnection, kmsService);- const awsConfig = decryptedConnection as unknown as TAwsConnectionConfig;- const { credentials: awsCredentials } = await getAwsConnectionConfig(awsConfig);-- const cfn = new CloudFormationClient({ credentials: awsCredentials, region: "us-east-1" });- const res = await cfn.send(new DescribeStacksCommand({ StackName: stackName }));- const stack = res.Stacks?.[0];-- if (!stack) return { deployed: false, status: null };-- return {- deployed: CF_COMPLETE_STATUSES.has(stack.StackStatus ?? ""),- status: stack.StackStatus ?? null- };- } catch (err) {- const awsCode = (err as { code?: string }).code;-- if (awsCode === "ValidationError") {- return { deployed: false, status: null };- }+ projectId: string;+ actor: OrgServiceActor;+ action: ProjectPermissionHoneyTokenActions;+ }) => {+ const { permission } = await getProjectPermission(projectId, actor);+ if (permission.can(action, ProjectPermissionSub.HoneyTokens)) {+ return permission;+ }- logger.warn({ err, connectionId, stackName }, "Failed to verify honey token CloudFormation stack deployment");- return { deployed: false, status: null };+ // Backwards compatibility: older roles may not yet include the new honey-token subject.+ // Fall back to the equivalent secret/folder permission actions.+ const legacyAction = action as ProjectPermissionActions;+ if (+ permission.can(legacyAction, ProjectPermissionSub.Secrets) ||+ permission.can(legacyAction, ProjectPermissionSub.SecretFolders)+ ) {+ return permission;}++ ForbiddenError.from(permission).throwUnlessCan(action, ProjectPermissionSub.HoneyTokens);+ return permission;};const create = async (- {- projectId,- type,- name,- description,- secretsMapping,- environment,- secretPath- }: {- projectId: string;- type: HoneyTokenType;- name: string;- description?: string | null;- secretsMapping: Record<string, string>;- environment: string;- secretPath: string;- },+ { projectId, type, name, description, secretsMapping, environment, secretPath }: THoneyTokenCreateInput,actor: OrgServiceActor) => {- const plan = await licenseService.getPlan(actor.orgId);-- if (!plan.honeyTokens) {- throw new BadRequestError({- message: "Failed to create honey token due to plan restriction. Upgrade plan to use honey tokens."- });+ const providerType = assertSupportedHoneyTokenType(type);+ const providerHooks = honeyTokenProviderHooksByType[providerType];+ if (!providerHooks) {+ throw new BadRequestError({ message: "Unsupported honey token type" });}+ const plan = await ensurePlanSupportsHoneyTokens(actor.orgId, "create honey token");+if (plan.honeyTokenLimit !== null) {const honeyTokensCreated = await honeyTokenDAL.countByOrgId(actor.orgId);if (honeyTokensCreated >= plan.honeyTokenLimit) {@@ -170,19 +163,7 @@ export const honeyTokenServiceFactory = ({}}- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager,- projectId- });-- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionHoneyTokenActions.Create,- ProjectPermissionSub.HoneyTokens- );+ await assertProjectPermission({ projectId, actor, action: ProjectPermissionHoneyTokenActions.Create });const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId);@@ -194,7 +175,7 @@ export const honeyTokenServiceFactory = ({const orgConfig = await honeyTokenConfigDAL.findOne({orgId: actor.orgId,- type+ type: providerType});if (!orgConfig?.connectionId) {@@ -204,16 +185,6 @@ export const honeyTokenServiceFactory = ({});}- const { decryptor: configDecryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: actor.orgId- });- const stackName = orgConfig.encryptedConfig- ? AwsHoneyTokenConfigSchema.parse(- JSON.parse(configDecryptor({ cipherTextBlob: orgConfig.encryptedConfig }).toString()) as unknown- ).stackName- : "infisical-honey-tokens";-const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);if (!folder) {@@ -261,28 +232,8 @@ export const honeyTokenServiceFactory = ({message: `Could not find App Connection with ID ${orgConfig.connectionId}`});}-- const decryptedConnection = await decryptAppConnection(appConnection, kmsService);- const awsConfig = decryptedConnection as unknown as TAwsConnectionConfig;-- const iamUserName = `${HONEY_TOKEN_IAM_USER_PREFIX}${crypto.randomBytes(8).toString("hex")}`;-- const { credentials: awsCredentials, region } = await getAwsConnectionConfig(awsConfig);- const iam = new IAMClient({ credentials: awsCredentials, region });-- await iam.send(new CreateUserCommand({ UserName: iamUserName }));-- const createKeyRes = await iam.send(new CreateAccessKeyCommand({ UserName: iamUserName }));-- if (!createKeyRes.AccessKey?.AccessKeyId || !createKeyRes.AccessKey?.SecretAccessKey) {- throw new BadRequestError({ message: "Failed to create AWS access key for honey token" });- }-- const honeyTokenCredentials = {- accessKeyId: createKeyRes.AccessKey.AccessKeyId,- secretAccessKey: createKeyRes.AccessKey.SecretAccessKey,- iamUserName- };+ assertHoneyTokenConnectionType(providerType, appConnection.app);+ const { credentials: honeyTokenCredentials, tokenIdentifier } = await providerHooks.createCredentials(appConnection);const { encryptor: credentialEncryptor } = await kmsService.createCipherPairWithDataKey({type: KmsDataKey.Organization,@@ -296,14 +247,14 @@ export const honeyTokenServiceFactory = ({const honeyToken = await honeyTokenDAL.create({name,description,- type,+ type: providerType,status: HoneyTokenStatus.Active,projectId,folderId: folder.id,connectionId: orgConfig.connectionId,encryptedCredentials,secretsMapping,- tokenIdentifier: createKeyRes.AccessKey.AccessKeyId,+ tokenIdentifier,createdByUserId: actor.id});@@ -312,10 +263,16 @@ export const honeyTokenServiceFactory = ({projectId});- const secretEntries = [- { key: secretsMapping.accessKeyId, value: createKeyRes.AccessKey.AccessKeyId },- { key: secretsMapping.secretAccessKey, value: createKeyRes.AccessKey.SecretAccessKey }- ];+ const secretEntries = Object.entries(secretsMapping).map(([credentialField, secretKey]) => {+ const credentialValue = honeyTokenCredentials[credentialField];+ if (credentialValue === undefined) {+ throw new BadRequestError({+ message: `Secrets mapping key "${credentialField}" does not exist in generated credentials for this honey token type`+ });+ }++ return { key: secretKey, value: credentialValue };+ });await fnSecretBulkInsert({folderId: folder.id,@@ -350,10 +307,14 @@ export const honeyTokenServiceFactory = ({excludeReplication: true});- const stackDeployment = await verifyStackDeployment({- connectionId: orgConfig.connectionId,- stackName- });+ const stackDeployment = providerHooks.verifyDeployment+ ? await providerHooks.verifyDeployment({+ appConnection,+ connectionId: orgConfig.connectionId,+ orgId: actor.orgId,+ encryptedConfig: orgConfig.encryptedConfig+ })+ : undefined;return {honeyToken: {@@ -367,7 +328,7 @@ export const honeyTokenServiceFactory = ({createdAt: honeyToken.createdAt,updatedAt: honeyToken.updatedAt},- stackDeployment+ ...(stackDeployment ? { stackDeployment } : {})};};@@ -387,24 +348,8 @@ export const honeyTokenServiceFactory = ({},actor: OrgServiceActor) => {- const plan = await licenseService.getPlan(actor.orgId);-- if (!plan.honeyTokens) {- throw new BadRequestError({- message: "Failed to update honey token due to plan restriction. Upgrade plan to use honey tokens."- });- }-- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager,- projectId- });-- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionHoneyTokenActions.Edit, ProjectPermissionSub.HoneyTokens);+ await ensurePlanSupportsHoneyTokens(actor.orgId, "update honey token");+ await assertProjectPermission({ projectId, actor, action: ProjectPermissionHoneyTokenActions.Edit });const honeyToken = await honeyTokenDAL.findById(honeyTokenId);@@ -471,17 +416,23 @@ export const honeyTokenServiceFactory = ({const decryptedCredentials = JSON.parse(decryptor({ cipherTextBlob: honeyToken.encryptedCredentials }).toString()- ) as { accessKeyId: string; secretAccessKey: string; iamUserName: string };+ ) as Record<string, string>;const { encryptor: secretEncryptor } = await kmsService.createCipherPairWithDataKey({type: KmsDataKey.SecretManager,projectId});- const secretEntries = [- { key: secretsMapping.accessKeyId, value: decryptedCredentials.accessKeyId },- { key: secretsMapping.secretAccessKey, value: decryptedCredentials.secretAccessKey }- ];+ const secretEntries = Object.entries(secretsMapping).map(([credentialField, secretKey]) => {+ const credentialValue = decryptedCredentials[credentialField];+ if (credentialValue === undefined) {+ throw new BadRequestError({+ message: `Secrets mapping key "${credentialField}" does not exist in stored credentials for this honey token type`+ });+ }++ return { key: secretKey, value: credentialValue };+ });await fnSecretBulkInsert({folderId: honeyToken.folderId,@@ -546,27 +497,8 @@ export const honeyTokenServiceFactory = ({{ honeyTokenId, projectId }: { honeyTokenId: string; projectId: string },actor: OrgServiceActor) => {- const plan = await licenseService.getPlan(actor.orgId);-- if (!plan.honeyTokens) {- throw new BadRequestError({- message: "Failed to revoke honey token due to plan restriction. Upgrade plan to use honey tokens."- });- }-- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager,- projectId- });-- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionHoneyTokenActions.Delete,- ProjectPermissionSub.HoneyTokens- );+ await ensurePlanSupportsHoneyTokens(actor.orgId, "revoke honey token");+ await assertProjectPermission({ projectId, actor, action: ProjectPermissionHoneyTokenActions.Delete });const honeyToken = await honeyTokenDAL.findById(honeyTokenId);@@ -577,6 +509,7 @@ export const honeyTokenServiceFactory = ({if (honeyToken.status === HoneyTokenStatus.Revoked) {throw new BadRequestError({ message: "Honey token is already revoked" });}+ const type = assertSupportedHoneyTokenType(honeyToken.type);const { decryptor } = await kmsService.createCipherPairWithDataKey({type: KmsDataKey.Organization,@@ -585,32 +518,18 @@ export const honeyTokenServiceFactory = ({const decryptedCredentials = JSON.parse(decryptor({ cipherTextBlob: honeyToken.encryptedCredentials }).toString()- ) as { accessKeyId: string; secretAccessKey: string; iamUserName: string };+ ) as Record<string, string>;const appConnection = await appConnectionDAL.findById(honeyToken.connectionId);if (appConnection) {- const decryptedConnection = await decryptAppConnection(appConnection, kmsService);- const awsConfig = decryptedConnection as unknown as TAwsConnectionConfig;- const { credentials: awsCredentials, region } = await getAwsConnectionConfig(awsConfig);- const iam = new IAMClient({ credentials: awsCredentials, region });-- try {- await iam.send(- new DeleteAccessKeyCommand({- UserName: decryptedCredentials.iamUserName,- AccessKeyId: decryptedCredentials.accessKeyId- })- );- } catch {- // Access key may already be deleted- }-- try {- await iam.send(new DeleteUserCommand({ UserName: decryptedCredentials.iamUserName }));- } catch {- // IAM user may already be deleted- }+ assertHoneyTokenConnectionType(type, appConnection.app);+ const providerHooks = honeyTokenProviderHooksByType[type];+ if (!providerHooks) throw new BadRequestError({ message: "Unsupported honey token type" });+ await providerHooks.revokeCredentials({+ appConnection,+ credentials: decryptedCredentials+ });}const secretKeys = Object.values(honeyToken.secretsMapping as Record<string, string>);@@ -653,22 +572,14 @@ export const honeyTokenServiceFactory = ({{ honeyTokenId, projectId }: { honeyTokenId: string; projectId: string },actor: OrgServiceActor) => {- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager,- projectId- });-- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionHoneyTokenActions.Edit, ProjectPermissionSub.HoneyTokens);+ await assertProjectPermission({ projectId, actor, action: ProjectPermissionHoneyTokenActions.Edit });const honeyToken = await honeyTokenDAL.findById(honeyTokenId);if (!honeyToken || honeyToken.projectId !== projectId) {throw new NotFoundError({ message: `Honey token with ID "${honeyTokenId}" not found` });}+ assertSupportedHoneyTokenType(honeyToken.type);if (honeyToken.status !== HoneyTokenStatus.Triggered) {throw new BadRequestError({ message: "Only triggered honey tokens can be reset" });@@ -698,14 +609,7 @@ export const honeyTokenServiceFactory = ({},actor: OrgServiceActor) => {- await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager,- projectId- });+ await getProjectPermission(projectId, actor);const folders = await folderDAL.findBySecretPathMultiEnv(projectId, environments, secretPath);if (!folders.length) return 0;@@ -715,21 +619,9 @@ export const honeyTokenServiceFactory = ({};const getOrgHoneyTokenLimit = async ({ projectId }: { projectId: string }, actor: OrgServiceActor) => {- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager,- projectId- });-- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionHoneyTokenActions.Create,- ProjectPermissionSub.HoneyTokens- );+ await assertProjectPermission({ projectId, actor, action: ProjectPermissionHoneyTokenActions.Create });- const plan = await licenseService.getPlan(actor.orgId);+ const plan = await ensurePlanSupportsHoneyTokens(actor.orgId, "access honey token limits");const used = await honeyTokenDAL.countByOrgId(actor.orgId);return {@@ -760,14 +652,7 @@ export const honeyTokenServiceFactory = ({},actor: OrgServiceActor) => {- await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager,- projectId- });+ await getProjectPermission(projectId, actor);const folders = await folderDAL.findBySecretPathMultiEnv(projectId, environments, secretPath);if (!folders.length) return [];@@ -793,20 +678,8 @@ export const honeyTokenServiceFactory = ({return honeyTokens;};- const getCredentials = async (- { honeyTokenId, projectId }: { honeyTokenId: string; projectId: string },- actor: OrgServiceActor- ): Promise<{ credentials: TAwsHoneyTokenCredentials }> => {- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager,- projectId- });-- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionHoneyTokenActions.Read, ProjectPermissionSub.HoneyTokens);+ const getCredentials = async ({ honeyTokenId, projectId }: THoneyTokenByIdInput, actor: OrgServiceActor) => {+ await assertProjectPermission({ projectId, actor, action: ProjectPermissionHoneyTokenActions.Read });const honeyToken = await honeyTokenDAL.findById(honeyTokenId);@@ -814,20 +687,16 @@ export const honeyTokenServiceFactory = ({throw new NotFoundError({ message: `Honey token with ID "${honeyTokenId}" not found` });}- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: actor.orgId- });-- const decryptedCredentials = parseAwsHoneyTokenDecryptedCredentials(- JSON.parse(decryptor({ cipherTextBlob: honeyToken.encryptedCredentials }).toString()) as unknown- );+ const type = assertSupportedHoneyTokenType(honeyToken.type);+ const providerHooks = honeyTokenProviderHooksByType[type];+ if (!providerHooks) throw new BadRequestError({ message: "Unsupported honey token type" });return {- credentials: {- accessKeyId: decryptedCredentials.accessKeyId,- secretAccessKey: decryptedCredentials.secretAccessKey- }+ type,+ credentials: await providerHooks.getCredentialsForDisplay({+ encryptedCredentials: honeyToken.encryptedCredentials,+ orgId: actor.orgId+ })};};@@ -835,16 +704,7 @@ export const honeyTokenServiceFactory = ({{ honeyTokenId, projectId }: { honeyTokenId: string; projectId: string },actor: OrgServiceActor) => {- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager,- projectId- });-- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionHoneyTokenActions.Read, ProjectPermissionSub.HoneyTokens);+ await assertProjectPermission({ projectId, actor, action: ProjectPermissionHoneyTokenActions.Read });const honeyToken = await honeyTokenDAL.findById(honeyTokenId);@@ -891,16 +751,7 @@ export const honeyTokenServiceFactory = ({}: { honeyTokenId: string; projectId: string; offset?: number; limit?: number },actor: OrgServiceActor) => {- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager,- projectId- });-- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionHoneyTokenActions.Read, ProjectPermissionSub.HoneyTokens);+ await assertProjectPermission({ projectId, actor, action: ProjectPermissionHoneyTokenActions.Read });const honeyToken = await honeyTokenDAL.findById(honeyTokenId);diff --git a/frontend/src/components/honey-tokens/HoneyTokenDetailsDrawer.tsx b/frontend/src/components/honey-tokens/HoneyTokenDetailsDrawer.tsxindex 14a05295c7..b0118adc07 100644--- a/frontend/src/components/honey-tokens/HoneyTokenDetailsDrawer.tsx+++ b/frontend/src/components/honey-tokens/HoneyTokenDetailsDrawer.tsx@@ -235,7 +235,7 @@ const DrawerContent = ({({ key, label }) => {const mapping = honeyToken.secretsMapping as Record<string, string>;const secretName = mapping[key];- const value = secretName ? credentials[secretName] : undefined;+ const value = (secretName ? credentials[secretName] : undefined) ?? credentials[key];return <CredentialField key={key} label={label} value={value} />;})}diff --git a/frontend/src/components/honey-tokens/ViewHoneyTokenCredentials/AwsHoneyTokenCredentials.tsx b/frontend/src/components/honey-tokens/ViewHoneyTokenCredentials/AwsHoneyTokenCredentials.tsxindex 56ed94256b..5c5c7b865c 100644--- a/frontend/src/components/honey-tokens/ViewHoneyTokenCredentials/AwsHoneyTokenCredentials.tsx+++ b/frontend/src/components/honey-tokens/ViewHoneyTokenCredentials/AwsHoneyTokenCredentials.tsx@@ -17,7 +17,7 @@ export const AwsHoneyTokenCredentials = ({ secretsMapping, credentials }: Props)<div className="flex flex-col gap-4">{CREDENTIAL_FIELDS.map(({ key, label }) => {const secretName = secretsMapping[key];- const value = secretName ? credentials[secretName] : undefined;+ const value = (secretName ? credentials[secretName] : undefined) ?? credentials[key];return <CredentialField key={key} label={label} value={value} />;})}diff --git a/frontend/src/components/honey-tokens/forms/HoneyTokenForm.tsx b/frontend/src/components/honey-tokens/forms/HoneyTokenForm.tsxindex fda810a18e..a340ca4f6d 100644--- a/frontend/src/components/honey-tokens/forms/HoneyTokenForm.tsx+++ b/frontend/src/components/honey-tokens/forms/HoneyTokenForm.tsx@@ -100,7 +100,7 @@ export const HoneyTokenForm = ({projectId: currentProject.id});- if (!stackDeployment.deployed) {+ if (stackDeployment && !stackDeployment.deployed) {const isDeploying = stackDeployment.status?.endsWith("_IN_PROGRESS");createNotification({text: isDeployingdiff --git a/frontend/src/hooks/api/honeyToken/mutations.ts b/frontend/src/hooks/api/honeyToken/mutations.tsindex 9e08c035c7..58a2539a5c 100644--- a/frontend/src/hooks/api/honeyToken/mutations.ts+++ b/frontend/src/hooks/api/honeyToken/mutations.ts@@ -10,7 +10,10 @@ export const useUpsertHoneyTokenConfig = () => {return useMutation({mutationFn: async (dto: TUpsertHoneyTokenConfigDTO) => {- const { data } = await apiRequest.put("/api/v1/honey-tokens/configs", dto);+ const { data } = await apiRequest.put(`/api/v1/honey-tokens/${dto.type}/configs`, {+ connectionId: dto.connectionId,+ config: dto.config+ });return data.config;},onSuccess: (_, dto) => {@@ -26,7 +29,7 @@ export const useTestHoneyTokenConnection = () => {isConnected: boolean;status: string | null;stackName: string;- }>(`/api/v1/honey-tokens/configs/${type}/test-connection`);+ }>(`/api/v1/honey-tokens/${type}/configs/test-connection`);return data;}});diff --git a/frontend/src/hooks/api/honeyToken/queries.ts b/frontend/src/hooks/api/honeyToken/queries.tsindex d17f7deeb0..1ea8d3d730 100644--- a/frontend/src/hooks/api/honeyToken/queries.ts+++ b/frontend/src/hooks/api/honeyToken/queries.ts@@ -24,7 +24,7 @@ export const useGetHoneyTokenConfig = (queryKey: honeyTokenKeys.config(type),queryFn: async () => {const { data } = await apiRequest.get<{ config: THoneyTokenConfig }>(- `/api/v1/honey-tokens/configs/${type}`+ `/api/v1/honey-tokens/${type}/configs`);return data.config;},diff --git a/frontend/src/hooks/api/honeyTokens/types/index.ts b/frontend/src/hooks/api/honeyTokens/types/index.tsindex 0898ffe318..2f7d431be9 100644--- a/frontend/src/hooks/api/honeyTokens/types/index.ts+++ b/frontend/src/hooks/api/honeyTokens/types/index.ts@@ -35,7 +35,7 @@ export type TCreateHoneyTokenDTO = {export type TCreateHoneyTokenResponse = {honeyToken: THoneyToken;- stackDeployment: {+ stackDeployment?: {deployed: boolean;status: string | null;};diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgProductSettingsTab/HoneyTokenModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgProductSettingsTab/HoneyTokenModal.tsxindex 56def8d114..2800cd47cc 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgProductSettingsTab/HoneyTokenModal.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgProductSettingsTab/HoneyTokenModal.tsx@@ -74,7 +74,7 @@ export const HoneyTokenModal = ({ isOpen, onOpenChange }: Props) => {const webhookUrl = useMemo(() => {const { protocol, host } = window.location;- return `${protocol}//${host}/api/v1/honey-tokens/${currentOrg?.id}/trigger`;+ return `${protocol}//${host}/api/v1/honey-tokens/${HoneyTokenType.AWS}/${currentOrg?.id}/trigger`;}, [currentOrg?.id]);const { control, handleSubmit, watch, reset } = useForm<FormData>({