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
feature(pki): imperva certificate sync
bernie-g5cccb02dd9db
diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.tsindex f9bc641b10..d4b8f7e45f 100644--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts@@ -146,6 +146,10 @@ import {HumanitecConnectionListItemSchema,SanitizedHumanitecConnectionSchema} from "@app/services/app-connection/humanitec";+import {+ ImpervaConnectionListItemSchema,+ SanitizedImpervaConnectionSchema+} from "@app/services/app-connection/imperva";import { KeeperConnectionListItemSchema, SanitizedKeeperConnectionSchema } from "@app/services/app-connection/keeper";import {KempLoadMasterConnectionListItemSchema,@@ -358,6 +362,7 @@ const SanitizedAppConnectionSchema = z.union([...SanitizedNetScalerConnectionSchema.options,...SanitizedPaloAltoNetworksConnectionSchema.options,...SanitizedKempLoadMasterConnectionSchema.options,+ ...SanitizedImpervaConnectionSchema.options,...SanitizedDopplerConnectionSchema.options,...SanitizedOvhConnectionSchema.options,...SanitizedOnaConnectionSchema.options,@@ -452,6 +457,7 @@ const AppConnectionOptionsSchema = z.discriminatedUnion("app", [NetScalerConnectionListItemSchema,PaloAltoNetworksConnectionListItemSchema,KempLoadMasterConnectionListItemSchema,+ ImpervaConnectionListItemSchema,AnthropicConnectionListItemSchema,OvhConnectionListItemSchema,DevinConnectionListItemSchema,diff --git a/backend/src/server/routes/v1/app-connection-routers/imperva-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/imperva-connection-router.tsnew file mode 100644index 0000000000..072fb67514--- /dev/null+++ b/backend/src/server/routes/v1/app-connection-routers/imperva-connection-router.ts@@ -0,0 +1,18 @@+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import {+ CreateImpervaConnectionSchema,+ SanitizedImpervaConnectionSchema,+ UpdateImpervaConnectionSchema+} from "@app/services/app-connection/imperva";++import { registerAppConnectionEndpoints } from "./app-connection-endpoints";++export const registerImpervaConnectionRouter = async (server: FastifyZodProvider) => {+ registerAppConnectionEndpoints({+ app: AppConnection.Imperva,+ server,+ sanitizedResponseSchema: SanitizedImpervaConnectionSchema,+ createSchema: CreateImpervaConnectionSchema,+ updateSchema: UpdateImpervaConnectionSchema+ });+};diff --git a/backend/src/server/routes/v1/app-connection-routers/index.ts b/backend/src/server/routes/v1/app-connection-routers/index.tsindex 9fe44eb3a9..1a4c4d2c8c 100644--- a/backend/src/server/routes/v1/app-connection-routers/index.ts+++ b/backend/src/server/routes/v1/app-connection-routers/index.ts@@ -45,6 +45,7 @@ import { registerHCVaultConnectionRouter } from "./hc-vault-connection-router";import { registerHerokuConnectionRouter } from "./heroku-connection-router";import { registerHpeIloConnectionRouter } from "./hpe-ilo-connection-router";import { registerHumanitecConnectionRouter } from "./humanitec-connection-router";+import { registerImpervaConnectionRouter } from "./imperva-connection-router";import { registerKeeperConnectionRouter } from "./keeper-connection-router";import { registerKempLoadMasterConnectionRouter } from "./kemp-loadmaster-connection-router";import { registerLaravelForgeConnectionRouter } from "./laravel-forge-connection-router";@@ -164,6 +165,7 @@ export const APP_CONNECTION_REGISTER_ROUTER_MAP: Record<AppConnection, (server:[AppConnection.NetScaler]: registerNetScalerConnectionRouter,[AppConnection.PaloAltoNetworks]: registerPaloAltoNetworksConnectionRouter,[AppConnection.KempLoadMaster]: registerKempLoadMasterConnectionRouter,+ [AppConnection.Imperva]: registerImpervaConnectionRouter,[AppConnection.Anthropic]: registerAnthropicConnectionRouter,[AppConnection.OVH]: registerOvhConnectionRouter,[AppConnection.Devin]: registerDevinConnectionRouter,diff --git a/backend/src/server/routes/v1/pki-sync-routers/imperva-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/imperva-pki-sync-router.tsnew file mode 100644index 0000000000..4815ae74bc--- /dev/null+++ b/backend/src/server/routes/v1/pki-sync-routers/imperva-pki-sync-router.ts@@ -0,0 +1,65 @@+import { z } from "zod";++import { readLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";+import {+ CreateImpervaPkiSyncSchema,+ IMPERVA_PKI_SYNC_LIST_OPTION,+ ImpervaPkiSyncSchema,+ UpdateImpervaPkiSyncSchema+} from "@app/services/pki-sync/imperva";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";++import { registerSyncPkiEndpoints } from "./pki-sync-endpoints";++export const registerImpervaPkiSyncRouter = async (server: FastifyZodProvider, enableOperationId: boolean = true) => {+ registerSyncPkiEndpoints({+ destination: PkiSync.Imperva,+ server,+ responseSchema: ImpervaPkiSyncSchema,+ createSchema: CreateImpervaPkiSyncSchema,+ updateSchema: UpdateImpervaPkiSyncSchema,+ syncOptions: {+ canImportCertificates: IMPERVA_PKI_SYNC_LIST_OPTION.canImportCertificates,+ canRemoveCertificates: IMPERVA_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: IMPERVA_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand+ },+ enableOperationId+ });++ server.route({+ method: "GET",+ url: "/sites",+ config: {+ rateLimit: readLimit+ },+ schema: {+ hide: false,+ ...(enableOperationId ? { operationId: "listImpervaSites" } : {}),+ description: "List the websites available on Imperva for the specified connection.",+ querystring: z.object({+ connectionId: z.string().uuid()+ }),+ response: {+ 200: z.object({+ sites: z.array(+ z.object({+ id: z.string(),+ name: z.string(),+ status: z.string().optional()+ })+ )+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),+ handler: async (req) => {+ const { connectionId } = req.query;++ const sites = await server.services.appConnection.imperva.listSites(connectionId, req.permission);++ return { sites };+ }+ });+};diff --git a/backend/src/server/routes/v1/pki-sync-routers/index.ts b/backend/src/server/routes/v1/pki-sync-routers/index.tsindex ab6b85fbe4..aa85a9dfda 100644--- a/backend/src/server/routes/v1/pki-sync-routers/index.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/index.ts@@ -8,6 +8,7 @@ import { registerChefPkiSyncRouter } from "./chef-pki-sync-router";import { registerCloudflareCustomCertificatePkiSyncRouter } from "./cloudflare-custom-certificate-pki-sync-router";import { registerF5BigIpPkiSyncRouter } from "./f5-big-ip-pki-sync-router";import { registerGcpCertificateManagerPkiSyncRouter } from "./gcp-certificate-manager-pki-sync-router";+import { registerImpervaPkiSyncRouter } from "./imperva-pki-sync-router";import { registerKempLoadMasterPkiSyncRouter } from "./kemp-loadmaster-pki-sync-router";import { registerLinuxServerPkiSyncRouter } from "./linux-server-pki-sync-router";import { registerNetScalerPkiSyncRouter } from "./netscaler-pki-sync-router";@@ -36,6 +37,7 @@ export const PKI_SYNC_REGISTER_ROUTER_MAP: Record<[PkiSync.PaloAltoNetworksSslTlsProfile]: registerPaloAltoNetworksSslTlsProfilePkiSyncRouter,[PkiSync.F5BigIp]: registerF5BigIpPkiSyncRouter,[PkiSync.KempLoadMaster]: registerKempLoadMasterPkiSyncRouter,+ [PkiSync.Imperva]: registerImpervaPkiSyncRouter,[PkiSync.LinuxServer]: registerLinuxServerPkiSyncRouter,[PkiSync.WindowsServer]: registerWindowsServerPkiSyncRouter,[PkiSync.NutanixPrismCentral]: registerNutanixPrismCentralPkiSyncRouterdiff --git a/backend/src/services/app-connection/app-connection-enums.ts b/backend/src/services/app-connection/app-connection-enums.tsindex c82b36cb5d..2204e7d1a4 100644--- a/backend/src/services/app-connection/app-connection-enums.ts+++ b/backend/src/services/app-connection/app-connection-enums.ts@@ -82,6 +82,7 @@ export enum AppConnection {LiteLLM = "litellm",Fireworks = "fireworks",KempLoadMaster = "kemp-loadmaster",+ Imperva = "imperva",MicrosoftIntune = "microsoft-intune",NutanixPrismCentral = "nutanix-prism-central",PowerDns = "powerdns",diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.tsindex b478032815..682d0ff130 100644--- a/backend/src/services/app-connection/app-connection-fns.ts+++ b/backend/src/services/app-connection/app-connection-fns.ts@@ -189,6 +189,7 @@ import {HumanitecConnectionMethod,validateHumanitecConnectionCredentials} from "./humanitec";+import { getImpervaConnectionListItem, ImpervaConnectionMethod, validateImpervaConnectionCredentials } from "./imperva";import { getKeeperConnectionListItem, KeeperConnectionMethod, validateKeeperConnectionCredentials } from "./keeper";import {getKempLoadMasterConnectionListItem,@@ -364,6 +365,7 @@ const PKI_APP_CONNECTIONS = [AppConnection.NetScaler,AppConnection.PaloAltoNetworks,AppConnection.KempLoadMaster,+ AppConnection.Imperva,AppConnection.DigiCert,AppConnection.F5BigIp,AppConnection.GoDaddy,@@ -474,6 +476,7 @@ export const listAppConnectionOptions = (projectType?: ProjectType) => {getNetScalerConnectionListItem(),getPaloAltoNetworksConnectionListItem(),getKempLoadMasterConnectionListItem(),+ getImpervaConnectionListItem(),getOvhConnectionListItem(),getOnaConnectionListItem(),getDigiCertConnectionListItem(),@@ -710,6 +713,7 @@ export const validateAppConnectionCredentials = async ([AppConnection.PaloAltoNetworks]:validatePaloAltoNetworksConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.KempLoadMaster]: validateKempLoadMasterConnectionCredentials as TAppConnectionCredentialsValidator,+ [AppConnection.Imperva]: validateImpervaConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.Ona]: validateOnaConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.TravisCI]: validateTravisCIConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.ExternalInfisical]: ((config: TAppConnectionConfig) =>@@ -854,6 +858,7 @@ export const getAppConnectionMethodName = (method: TAppConnection["method"]) =>case NutanixPrismCentralConnectionMethod.ApiKey:case PowerDnsConnectionMethod.ApiKey:case DaytonaConnectionMethod.ApiKey:+ case ImpervaConnectionMethod.ApiKey:case KeeperConnectionMethod.ApiKey:return "API Key";case ChefConnectionMethod.UserKey:@@ -1004,6 +1009,7 @@ export const TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM: Record<[AppConnection.NetScaler]: platformManagedCredentialsNotSupported,[AppConnection.PaloAltoNetworks]: platformManagedCredentialsNotSupported,[AppConnection.KempLoadMaster]: platformManagedCredentialsNotSupported,+ [AppConnection.Imperva]: platformManagedCredentialsNotSupported,[AppConnection.Doppler]: platformManagedCredentialsNotSupported,[AppConnection.OVH]: platformManagedCredentialsNotSupported,[AppConnection.Ona]: platformManagedCredentialsNotSupported,diff --git a/backend/src/services/app-connection/app-connection-maps.ts b/backend/src/services/app-connection/app-connection-maps.tsindex 5a5711e181..96386172cb 100644--- a/backend/src/services/app-connection/app-connection-maps.ts+++ b/backend/src/services/app-connection/app-connection-maps.ts@@ -65,6 +65,7 @@ export const APP_CONNECTION_NAME_MAP: Record<AppConnection, string> = {[AppConnection.NetScaler]: "NetScaler",[AppConnection.PaloAltoNetworks]: "Palo Alto Networks",[AppConnection.KempLoadMaster]: "Kemp LoadMaster",+ [AppConnection.Imperva]: "Imperva",[AppConnection.Anthropic]: "Anthropic",[AppConnection.OVH]: "OVH",[AppConnection.Devin]: "Devin",@@ -160,6 +161,7 @@ export const APP_CONNECTION_PLAN_MAP: Record<AppConnection, AppConnectionPlanTyp[AppConnection.NetScaler]: AppConnectionPlanType.Regular,[AppConnection.PaloAltoNetworks]: AppConnectionPlanType.Regular,[AppConnection.KempLoadMaster]: AppConnectionPlanType.Regular,+ [AppConnection.Imperva]: AppConnectionPlanType.Regular,[AppConnection.Anthropic]: AppConnectionPlanType.Regular,[AppConnection.OVH]: AppConnectionPlanType.Regular,[AppConnection.Devin]: AppConnectionPlanType.Regular,diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex 6d4fcbd59f..8bbb4b4ba0 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -137,6 +137,8 @@ import { herokuConnectionService } from "./heroku/heroku-connection-service";import { ValidateHpeIloConnectionCredentialsSchema } from "./hpe-ilo";import { ValidateHumanitecConnectionCredentialsSchema } from "./humanitec";import { humanitecConnectionService } from "./humanitec/humanitec-connection-service";+import { ValidateImpervaConnectionCredentialsSchema } from "./imperva";+import { impervaConnectionService } from "./imperva/imperva-connection-service";import { ValidateKeeperConnectionCredentialsSchema } from "./keeper";import { keeperConnectionService } from "./keeper/keeper-connection-service";import { ValidateKempLoadMasterConnectionCredentialsSchema } from "./kemp-loadmaster";@@ -313,6 +315,7 @@ const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TValidateAp[AppConnection.NetScaler]: ValidateNetScalerConnectionCredentialsSchema,[AppConnection.PaloAltoNetworks]: ValidatePaloAltoNetworksConnectionCredentialsSchema,[AppConnection.KempLoadMaster]: ValidateKempLoadMasterConnectionCredentialsSchema,+ [AppConnection.Imperva]: ValidateImpervaConnectionCredentialsSchema,[AppConnection.Anthropic]: ValidateAnthropicConnectionCredentialsSchema,[AppConnection.OVH]: ValidateOvhConnectionCredentialsSchema,[AppConnection.Devin]: ValidateDevinConnectionCredentialsSchema,@@ -1462,6 +1465,7 @@ export const appConnectionServiceFactory = ({databricks: databricksConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),aws: awsConnectionService(connectAppConnectionById),kempLoadMaster: kempLoadMasterConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),+ imperva: impervaConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),humanitec: humanitecConnectionService(connectAppConnectionById),terraformCloud: terraformCloudConnectionService(connectAppConnectionById),camunda: camundaConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),diff --git a/backend/src/services/app-connection/app-connection-types.ts b/backend/src/services/app-connection/app-connection-types.tsindex 1cf2e45315..fb3d164677 100644--- a/backend/src/services/app-connection/app-connection-types.ts+++ b/backend/src/services/app-connection/app-connection-types.ts@@ -273,6 +273,12 @@ import {THumanitecConnectionInput,TValidateHumanitecConnectionCredentialsSchema} from "./humanitec";+import {+ TImpervaConnection,+ TImpervaConnectionConfig,+ TImpervaConnectionInput,+ TValidateImpervaConnectionCredentialsSchema+} from "./imperva";import {TKeeperConnection,TKeeperConnectionConfig,@@ -614,6 +620,7 @@ export type TAppConnection = { id: string; configuration?: TAppConnectionConfigu| TNetScalerConnection| TPaloAltoNetworksConnection| TKempLoadMasterConnection+ | TImpervaConnection| TAnthropicConnection| TOvhConnection| TDevinConnection@@ -717,6 +724,7 @@ export type TAppConnectionInput = { id: string } & (| TNetScalerConnectionInput| TPaloAltoNetworksConnectionInput| TKempLoadMasterConnectionInput+ | TImpervaConnectionInput| TAnthropicConnectionInput| TOvhConnectionInput| TDevinConnectionInput@@ -854,6 +862,7 @@ export type TAppConnectionConfig =| TNetScalerConnectionConfig| TPaloAltoNetworksConnectionConfig| TKempLoadMasterConnectionConfig+ | TImpervaConnectionConfig| TAnthropicConnectionConfig| TOvhConnectionConfig| TDevinConnectionConfig@@ -948,6 +957,7 @@ export type TValidateAppConnectionCredentialsSchema =| TValidateNetScalerConnectionCredentialsSchema| TValidatePaloAltoNetworksConnectionCredentialsSchema| TValidateKempLoadMasterConnectionCredentialsSchema+ | TValidateImpervaConnectionCredentialsSchema| TValidateAnthropicConnectionCredentialsSchema| TValidateOvhConnectionCredentialsSchema| TValidateDevinConnectionCredentialsSchemadiff --git a/backend/src/services/app-connection/imperva/imperva-connection-enums.ts b/backend/src/services/app-connection/imperva/imperva-connection-enums.tsnew file mode 100644index 0000000000..86324e951c--- /dev/null+++ b/backend/src/services/app-connection/imperva/imperva-connection-enums.ts@@ -0,0 +1,3 @@+export enum ImpervaConnectionMethod {+ ApiKey = "api-key"+}diff --git a/backend/src/services/app-connection/imperva/imperva-connection-fns.test.ts b/backend/src/services/app-connection/imperva/imperva-connection-fns.test.tsnew file mode 100644index 0000000000..406c3ae7ef--- /dev/null+++ b/backend/src/services/app-connection/imperva/imperva-connection-fns.test.ts@@ -0,0 +1,46 @@+import { AxiosError } from "axios";++import { extractImpervaErrorMessage } from "./imperva-connection-fns";++const axiosErrorWith = (status: number, data: unknown) => {+ const error = new AxiosError("Request failed");+ error.response = { status, data } as never;+ return error;+};++describe("Imperva error messages", () => {+ test("keeps the reason Imperva gives for rejecting a credential", () => {+ const message = extractImpervaErrorMessage(+ axiosErrorWith(401, { errCode: 1003, errMsg: "Unauthorized request for account: 9999999" }),+ "fallback"+ );++ expect(message).toContain("Unauthorized request for account: 9999999");+ expect(message).toContain("the account ID names an account the key can reach");+ });++ test("falls back to its own wording when Imperva sends no reason", () => {+ expect(extractImpervaErrorMessage(axiosErrorWith(403, {}), "fallback")).toContain(+ "Imperva rejected the API ID or API key"+ );+ });++ test("prefers the provisioning API's message over the status fallback", () => {+ expect(extractImpervaErrorMessage(axiosErrorWith(404, { res_message: "Unknown/unauthorized site_id" }), "x")).toBe(+ "Unknown/unauthorized site_id"+ );+ });++ test("explains a 404 that carries no message", () => {+ expect(extractImpervaErrorMessage(axiosErrorWith(404, {}), "x")).toContain("could not find the website");+ });++ test("reads the REST API's error list", () => {+ const message = extractImpervaErrorMessage(+ axiosErrorWith(400, { errors: [{ title: "Bad Request", detail: "size must be one of [10, 25, 50, 100]" }] }),+ "x"+ );++ expect(message).toBe("Bad Request: size must be one of [10, 25, 50, 100]");+ });+});diff --git a/backend/src/services/app-connection/imperva/imperva-connection-fns.ts b/backend/src/services/app-connection/imperva/imperva-connection-fns.tsnew file mode 100644index 0000000000..14b78de34f--- /dev/null+++ b/backend/src/services/app-connection/imperva/imperva-connection-fns.ts@@ -0,0 +1,250 @@+import { AxiosError, AxiosRequestConfig } from "axios";+import https from "https";++import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { getConfig } from "@app/lib/config/env";+import { request } from "@app/lib/config/request";+import { BadRequestError } from "@app/lib/errors";+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";+import { logger } from "@app/lib/logger";+import { safeRequest } from "@app/lib/validator";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";++import { ImpervaConnectionMethod } from "./imperva-connection-enums";+import { TImpervaConnectionConfig } from "./imperva-connection-types";++// Custom certificate writes live on the provisioning API (my.imperva.com/api/prov/v2) while site and+// certificate reads live on the newer REST API (api.imperva.com), so a connection talks to both hosts.+export const IMPERVA_PROV_HOST = "my.imperva.com";+export const IMPERVA_PROV_BASE_PATH = "/api/prov/v2";+export const IMPERVA_REST_HOST = "api.imperva.com";+export const IMPERVA_SITES_BASE_PATH = "/sites-mgmt/v3";+export const IMPERVA_CERTIFICATES_BASE_PATH = "/certificates-ui/v3";++const IMPERVA_HTTPS_PORT = 443;+const IMPERVA_REQUEST_TIMEOUT_MS = 30_000;+const IMPERVA_MAX_RESPONSE_BYTES = 10 * 1024 * 1024;+// Imperva only accepts these page sizes on the sites API+const IMPERVA_SITES_PAGE_SIZE = 100;+const IMPERVA_SITES_MIN_PAGE_SIZE = 10;+const IMPERVA_SITES_MAX_PAGES = 50;++type TImpervaCredentials = TImpervaConnectionConfig["credentials"];++export type TImpervaRequestArgs = Omit<AxiosRequestConfig, "url" | "baseURL" | "httpsAgent"> & {+ host: string;+ path: string;+};++export type TImpervaRequestFn = <R>(args: TImpervaRequestArgs) => Promise<R>;++export type TImpervaApiError = {+ status?: number;+ title?: string;+ detail?: string;+ code?: string;+};++export const getImpervaAuthHeaders = (credentials: TImpervaCredentials): Record<string, string> => ({+ "x-API-Id": credentials.apiId,+ "x-API-Key": credentials.apiKey+});++export const getImpervaAccountParams = (credentials: TImpervaCredentials): Record<string, string> =>+ credentials.accountId ? { caid: credentials.accountId } : {};++export const getImpervaConnectionListItem = () => {+ return {+ name: "Imperva" as const,+ app: AppConnection.Imperva as const,+ methods: Object.values(ImpervaConnectionMethod) as [ImpervaConnectionMethod.ApiKey]+ };+};++const IMPERVA_AUTH_GUIDANCE =+ "Check that the key is enabled under User Management > My Profile > API keys (Imperva creates keys disabled), that both the ID and the key were copied in full, that the key's role includes the Manage SSL Certificates permission, and that the account ID names an account the key can reach";++// Imperva reports errors three ways, and only errMsg says what a rejected credential got wrong.+export const extractImpervaErrorMessage = (error: unknown, fallback: string): string => {+ if (error instanceof AxiosError) {+ const data = error.response?.data as+ | { errors?: TImpervaApiError[]; message?: string; res_message?: string; errMsg?: string }+ | undefined;+ const apiError = data?.errors?.[0];+ const reported = apiError+ ? [apiError.title, apiError.detail].filter(Boolean).join(": ") || undefined+ : data?.res_message || data?.message || data?.errMsg;++ const status = error.response?.status;+ if (status === 401 || status === 403) {+ return `${reported ?? "Imperva rejected the API ID or API key"}. ${IMPERVA_AUTH_GUIDANCE}`;+ }+ if (reported) return reported;+ if (status === 404) {+ return "Imperva could not find the website. Check the website ID, and set the account ID on the connection if the website belongs to a sub-account";+ }+ if (status === 429) {+ return "Imperva rate limited the request, try again shortly";+ }+ return error.message;+ }+ if (error instanceof Error) return error.message;+ return fallback;+};++const executeImpervaRequestWithGateway = async <R>(+ args: TImpervaRequestArgs,+ config: { gatewayId?: string | null; credentials: TImpervaCredentials },+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId"> | undefined+): Promise<R> => {+ const { host, path, ...requestCfg } = args;+ const { gatewayId } = config;++ if (gatewayId && gatewayV2Service) {+ const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId,+ targetHost: host,+ targetPort: IMPERVA_HTTPS_PORT+ });++ if (!platformConnectionDetails) {+ throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });+ }++ return withGatewayV2Proxy(+ async (proxyPort) => {+ const resp = await request.request<R>({+ ...requestCfg,+ url: `https://localhost:${proxyPort}${path}`,+ headers: { ...requestCfg.headers, Host: host },+ httpsAgent: new https.Agent({ servername: host }),+ timeout: IMPERVA_REQUEST_TIMEOUT_MS,+ maxContentLength: IMPERVA_MAX_RESPONSE_BYTES,+ maxBodyLength: IMPERVA_MAX_RESPONSE_BYTES+ });+ return resp.data;+ },+ {+ protocol: GatewayProxyProtocol.Tcp,+ ...platformConnectionDetails+ }+ );+ }++ const resp = await safeRequest.request<R>({+ ...requestCfg,+ url: `https://${host}${path}`,+ servername: host,+ allowPrivateIps: getConfig().ALLOW_INTERNAL_IP_CONNECTIONS,+ timeout: IMPERVA_REQUEST_TIMEOUT_MS,+ maxContentLength: IMPERVA_MAX_RESPONSE_BYTES,+ maxBodyLength: IMPERVA_MAX_RESPONSE_BYTES+ });+ return resp.data;+};++export const buildImpervaRequestFn = (+ config: { gatewayId?: string | null; credentials: TImpervaCredentials },+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId"> | undefined+): TImpervaRequestFn => {+ return <R>(args: TImpervaRequestArgs) =>+ executeImpervaRequestWithGateway<R>(+ {+ ...args,+ headers: { ...getImpervaAuthHeaders(config.credentials), ...args.headers }+ },+ config,+ gatewayV2Service+ );+};++export type TImpervaSite = {+ id: string;+ name: string;+ status?: string;+};++type TImpervaSitesResponse = {+ data?: Array<{ id?: number; name?: string; siteStatus?: string }>;+ meta?: { page?: number; size?: number; totalPages?: number; totalElements?: number };+};++export const listImpervaSites = async (+ config: { gatewayId?: string | null; credentials: TImpervaCredentials },+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId"> | undefined+): Promise<TImpervaSite[]> => {+ const makeRequest = buildImpervaRequestFn(config, gatewayV2Service);+ const sites: TImpervaSite[] = [];++ let page = 0;+ let totalPages = 1;++ /* eslint-disable no-await-in-loop */+ while (page < totalPages && page < IMPERVA_SITES_MAX_PAGES) {+ const response = await makeRequest<TImpervaSitesResponse>({+ method: "GET",+ host: IMPERVA_REST_HOST,+ path: `${IMPERVA_SITES_BASE_PATH}/sites`,+ params: {+ page,+ size: IMPERVA_SITES_PAGE_SIZE,+ ...getImpervaAccountParams(config.credentials)+ }+ });++ for (const site of response.data ?? []) {+ if (site.id !== undefined && site.id !== null) {+ sites.push({ id: String(site.id), name: site.name ?? String(site.id), status: site.siteStatus });+ }+ }++ totalPages = response.meta?.totalPages ?? 1;+ page += 1;+ }+ /* eslint-enable no-await-in-loop */++ if (page < totalPages) {+ logger.warn(+ `Imperva site listing stopped at ${IMPERVA_SITES_MAX_PAGES} pages (${totalPages} pages reported), some websites are not listed`+ );+ }++ return sites;+};++export const validateImpervaConnectionCredentials = async (+ config: TImpervaConnectionConfig,+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+) => {+ const { credentials } = config;+ const makeRequest = buildImpervaRequestFn({ gatewayId: config.gatewayId, credentials }, gatewayV2Service);++ try {+ await makeRequest<TImpervaSitesResponse>({+ method: "GET",+ host: IMPERVA_REST_HOST,+ path: `${IMPERVA_SITES_BASE_PATH}/sites`,+ params: { page: 0, size: IMPERVA_SITES_MIN_PAGE_SIZE, ...getImpervaAccountParams(credentials) }+ });+ } catch (error: unknown) {+ if (error instanceof AxiosError) {+ const responseBody: unknown = error.response?.data;+ logger.warn(+ {+ status: error.response?.status,+ body: typeof responseBody === "string" ? responseBody.slice(0, 500) : responseBody+ },+ "Imperva rejected the connection validation request"+ );+ }+ throw new BadRequestError({+ message: `Unable to validate connection: ${extractImpervaErrorMessage(+ error,+ "verify the API ID, API key, and account ID"+ )}`+ });+ }++ return credentials;+};diff --git a/backend/src/services/app-connection/imperva/imperva-connection-schemas.ts b/backend/src/services/app-connection/imperva/imperva-connection-schemas.tsnew file mode 100644index 0000000000..df11ddb550--- /dev/null+++ b/backend/src/services/app-connection/imperva/imperva-connection-schemas.ts@@ -0,0 +1,80 @@+import RE2 from "re2";+import z from "zod";++import { AppConnections } from "@app/lib/api-docs";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import {+ BaseAppConnectionSchema,+ GenericCreateAppConnectionFieldsSchema,+ GenericUpdateAppConnectionFieldsSchema+} from "@app/services/app-connection/app-connection-schemas";++import { APP_CONNECTION_NAME_MAP } from "../app-connection-maps";+import { ImpervaConnectionMethod } from "./imperva-connection-enums";++const ACCOUNT_ID_PATTERN = new RE2("^[0-9]+$");++export const ImpervaConnectionApiKeyCredentialsSchema = z.object({+ apiId: z.string().trim().min(1, "API ID is required").max(256, "API ID cannot exceed 256 characters"),+ apiKey: z.string().trim().min(1, "API key is required").max(512, "API key cannot exceed 512 characters"),+ accountId: z+ .string()+ .trim()+ .max(32, "Account ID cannot exceed 32 characters")+ .refine((val) => ACCOUNT_ID_PATTERN.test(val), { message: "Account ID must be numeric" })+ .optional()+});++const BaseImpervaConnectionSchema = BaseAppConnectionSchema.extend({+ app: z.literal(AppConnection.Imperva)+});++export const ImpervaConnectionSchema = BaseImpervaConnectionSchema.extend({+ method: z.literal(ImpervaConnectionMethod.ApiKey),+ credentials: ImpervaConnectionApiKeyCredentialsSchema+});++export const SanitizedImpervaConnectionSchema = z.discriminatedUnion("method", [+ BaseImpervaConnectionSchema.extend({+ method: z.literal(ImpervaConnectionMethod.ApiKey),+ credentials: ImpervaConnectionApiKeyCredentialsSchema.pick({+ apiId: true,+ accountId: true+ })+ }).describe(JSON.stringify({ title: `${APP_CONNECTION_NAME_MAP[AppConnection.Imperva]} (API Key)` }))+]);++export const ValidateImpervaConnectionCredentialsSchema = z.discriminatedUnion("method", [+ z.object({+ method: z.literal(ImpervaConnectionMethod.ApiKey).describe(AppConnections.CREATE(AppConnection.Imperva).method),+ credentials: ImpervaConnectionApiKeyCredentialsSchema.describe(+ AppConnections.CREATE(AppConnection.Imperva).credentials+ )+ })+]);++export const CreateImpervaConnectionSchema = ValidateImpervaConnectionCredentialsSchema.and(+ GenericCreateAppConnectionFieldsSchema(AppConnection.Imperva, {+ supportsGateways: true+ })+);++export const UpdateImpervaConnectionSchema = z+ .object({+ credentials: ImpervaConnectionApiKeyCredentialsSchema.optional().describe(+ AppConnections.UPDATE(AppConnection.Imperva).credentials+ )+ })+ .and(+ GenericUpdateAppConnectionFieldsSchema(AppConnection.Imperva, {+ supportsGateways: true+ })+ );++export const ImpervaConnectionListItemSchema = z+ .object({+ name: z.literal("Imperva"),+ app: z.literal(AppConnection.Imperva),+ methods: z.nativeEnum(ImpervaConnectionMethod).array()+ })+ .describe(JSON.stringify({ title: APP_CONNECTION_NAME_MAP[AppConnection.Imperva] }));diff --git a/backend/src/services/app-connection/imperva/imperva-connection-service.ts b/backend/src/services/app-connection/imperva/imperva-connection-service.tsnew file mode 100644index 0000000000..887f72bc67--- /dev/null+++ b/backend/src/services/app-connection/imperva/imperva-connection-service.ts@@ -0,0 +1,34 @@+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { OrgServiceActor } from "@app/lib/types";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";++import { listImpervaSites } from "./imperva-connection-fns";+import { TImpervaConnection } from "./imperva-connection-types";++type TGetAppConnectionFunc = (+ app: AppConnection,+ connectionId: string,+ actor: OrgServiceActor+) => Promise<TImpervaConnection>;++export const impervaConnectionService = (+ getAppConnection: TGetAppConnectionFunc,+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">+) => {+ const listSites = async (connectionId: string, actor: OrgServiceActor) => {+ const appConnection = await getAppConnection(AppConnection.Imperva, connectionId, actor);++ const gatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: appConnection.gatewayId,+ gatewayPoolId: appConnection.gatewayPoolId+ });++ return listImpervaSites({ gatewayId, credentials: appConnection.credentials }, gatewayV2Service);+ };++ return {+ listSites+ };+};diff --git a/backend/src/services/app-connection/imperva/imperva-connection-types.ts b/backend/src/services/app-connection/imperva/imperva-connection-types.tsnew file mode 100644index 0000000000..ca67d31f71--- /dev/null+++ b/backend/src/services/app-connection/imperva/imperva-connection-types.ts@@ -0,0 +1,25 @@+import z from "zod";++import { DiscriminativePick } from "@app/lib/types";++import { AppConnection } from "../app-connection-enums";+import {+ CreateImpervaConnectionSchema,+ ImpervaConnectionSchema,+ ValidateImpervaConnectionCredentialsSchema+} from "./imperva-connection-schemas";++export type TImpervaConnection = z.infer<typeof ImpervaConnectionSchema>;++export type TImpervaConnectionInput = z.infer<typeof CreateImpervaConnectionSchema> & {+ app: AppConnection.Imperva;+};++export type TValidateImpervaConnectionCredentialsSchema = typeof ValidateImpervaConnectionCredentialsSchema;++export type TImpervaConnectionConfig = DiscriminativePick<+ TImpervaConnectionInput,+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId"+> & {+ orgId: string;+};diff --git a/backend/src/services/app-connection/imperva/index.ts b/backend/src/services/app-connection/imperva/index.tsnew file mode 100644index 0000000000..7d53c8135a--- /dev/null+++ b/backend/src/services/app-connection/imperva/index.ts@@ -0,0 +1,15 @@+export { ImpervaConnectionMethod } from "./imperva-connection-enums";+export { getImpervaConnectionListItem, validateImpervaConnectionCredentials } from "./imperva-connection-fns";+export {+ CreateImpervaConnectionSchema,+ ImpervaConnectionListItemSchema,+ SanitizedImpervaConnectionSchema,+ UpdateImpervaConnectionSchema,+ ValidateImpervaConnectionCredentialsSchema+} from "./imperva-connection-schemas";+export type {+ TImpervaConnection,+ TImpervaConnectionConfig,+ TImpervaConnectionInput,+ TValidateImpervaConnectionCredentialsSchema+} from "./imperva-connection-types";diff --git a/backend/src/services/pki-sync/imperva/imperva-pki-sync-constants.ts b/backend/src/services/pki-sync/imperva/imperva-pki-sync-constants.tsnew file mode 100644index 0000000000..ea1a8973f6--- /dev/null+++ b/backend/src/services/pki-sync/imperva/imperva-pki-sync-constants.ts@@ -0,0 +1,19 @@+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";++export enum ImpervaCertificateAuthType {+ Rsa = "RSA",+ Ecc = "ECC"+}++export const IMPERVA_PKI_SYNC_LIST_OPTION = {+ name: "Imperva" as const,+ connection: AppConnection.Imperva,+ destination: PkiSync.Imperva,+ canImportCertificates: false,+ canRemoveCertificates: true,+ canRunPostSyncCommand: false,+ canRunHealthCheckCommand: false,+ // Imperva holds a single custom certificate per site for each key type+ maxCertificates: 1+} as const;diff --git a/backend/src/services/pki-sync/imperva/imperva-pki-sync-fns.test.ts b/backend/src/services/pki-sync/imperva/imperva-pki-sync-fns.test.tsnew file mode 100644index 0000000000..66b5574aeb--- /dev/null+++ b/backend/src/services/pki-sync/imperva/imperva-pki-sync-fns.test.ts@@ -0,0 +1,188 @@+import { ImpervaCertificateAuthType } from "./imperva-pki-sync-constants";+import {+ buildImpervaCertificatePayload,+ buildImpervaExternalIdentifier,+ parseImpervaExternalIdentifier,+ resolveImpervaAuthType+} from "./imperva-pki-sync-fns";++const RSA_CERT_PEM = `-----BEGIN CERTIFICATE-----+MIICsDCCAZgCCQDcwqDsp/lnRDANBgkqhkiG9w0BAQsFADAaMRgwFgYDVQQDDA9y+c2EuZXhhbXBsZS5jb20wHhcNMjYwOTE1MTYyNjAzWhcNMjYwOTE3MTYyNjAzWjAa+MRgwFgYDVQQDDA9yc2EuZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IB+DwAwggEKAoIBAQCw7iX6PgIMsNtTC7tHxmCoXLISlaNII1SxFyLCLwSRjeYXR2oq+dw+TD3MDP4zlVZWAKkgdDdkywh74at7CiHN6LI5FkaJWj/J1FUjVu4EDXg/3DW4C+vcwdXBNnJNm9PN7gXlfqGSGJLgXVTlbfTEi4YteBE2xQVRKulSnExNLno7oF6XJ9+Oz0KuPlzeAGcYce8jzLBJdNaiOeULoPW8y4qBC1RxRJI9IaZLom5SGMM9vf/nlHz+GhCdxzeDYsxhnkJuOvRDZcJmIsz6GdnUXV2zTRDpDd9zn01wibUUhEcZrIFSITfL+OECM44zoFoPB/4rwInmNEdYjV1KtffEg+bsnAgMBAAEwDQYJKoZIhvcNAQELBQAD+ggEBABPaF5UrgC1bDLRy+QQAuuKVnBjaoBjoNoB95yG2bdjLV/vl68RlY4npaGqj+9W8xFI7SzLpTdZt6Qya3o89f4EfRhJwQe1wgkebCMd0iaOzoGPrN9KmhmtLZsaay+N4NzoUqUd+APyvnHA3B7x76kPk0P2MBl11T/BHqpw5MJ+roSVXkstMzaRIx8kMT4+LtXpfCzeM8GvnIfwFW9gsM3+ehOHXbepMUxYV2Gs9lMcZGVvwOxWg2gO/TUnm4sn+O5Lkz7irmjaEu5alF/pzp0wkkv+0vqdzsgcpGhcD2TxVVugD1f+OirRlgI4UC/89+QGHWcAH5c2RYOp2mDX/H9PT7VNo=+-----END CERTIFICATE-----`;++const EC_CERT_PEM = `-----BEGIN CERTIFICATE-----+MIICFTCCAbwCCQDGvfCuuhhlmTAKBggqhkjOPQQDAjAZMRcwFQYDVQQDDA5lYy5l+eGFtcGxlLmNvbTAeFw0yNjA5MTUxNjI2MDNaFw0yNjA5MTcxNjI2MDNaMBkxFzAV+BgNVBAMMDmVjLmV4YW1wbGUuY29tMIIBSzCCAQMGByqGSM49AgEwgfcCAQEwLAYH+KoZIzj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA////////////////MFsEIP//+//8AAAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57PrvVV2mIa8+ZR0GsMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEs+Qkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sx+Xs7LtkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8YyVRAgEB+A0IABG37u2Hh+02YvunRSH6Xbyt8w8lifANs1zfWyC908eFFgDCT4OkKwt/fbwaf+qIthgi09T5werzQ//3CGZsQQe8swCgYIKoZIzj0EAwIDRwAwRAIgR/AWesnHl/q7+sfCQq1nLT7j+3ympSNR1k1rsrp7E0PMCIEK0wzqY/0w/upq1GciYzEHAD+CyvDd2+eCYGkKKes90M+-----END CERTIFICATE-----`;++describe("Imperva auth type resolution", () => {+ test("reads RSA and ECC off the certificate public key", () => {+ expect(resolveImpervaAuthType(RSA_CERT_PEM)).toBe(ImpervaCertificateAuthType.Rsa);+ expect(resolveImpervaAuthType(EC_CERT_PEM)).toBe(ImpervaCertificateAuthType.Ecc);+ });++ test("falls back to RSA for an unparseable certificate", () => {+ expect(resolveImpervaAuthType("not a certificate")).toBe(ImpervaCertificateAuthType.Rsa);+ });+});++describe("Imperva external identifier", () => {+ test("round trips the site and key type", () => {+ const identifier = buildImpervaExternalIdentifier("12345", ImpervaCertificateAuthType.Ecc);++ expect(identifier).toBe("12345:ECC");+ expect(parseImpervaExternalIdentifier(identifier)).toEqual({+ siteId: "12345",+ authType: ImpervaCertificateAuthType.Ecc+ });+ });++ test("treats an identifier without a key type as RSA", () => {+ expect(parseImpervaExternalIdentifier("12345")).toEqual({+ siteId: "12345",+ authType: ImpervaCertificateAuthType.Rsa+ });+ });+});++describe("Imperva certificate payload", () => {+ test("base64 encodes the leaf followed by the chain", () => {+ const payload = buildImpervaCertificatePayload(RSA_CERT_PEM, EC_CERT_PEM);+ const decoded = Buffer.from(payload, "base64").toString();++ expect(decoded.indexOf(RSA_CERT_PEM)).toBe(0);+ expect(decoded).toContain(EC_CERT_PEM);+ });++ test("encodes the leaf alone when there is no chain", () => {+ const decoded = Buffer.from(buildImpervaCertificatePayload(RSA_CERT_PEM), "base64").toString();++ expect(decoded).toBe(RSA_CERT_PEM);+ });+});++const impervaRequest = vi.hoisted(() => vi.fn());++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }+}));++vi.mock("@app/services/app-connection/imperva/imperva-connection-fns", async (importActual) => {+ const actual = await importActual<typeof import("@app/services/app-connection/imperva/imperva-connection-fns")>();+ return { ...actual, buildImpervaRequestFn: () => impervaRequest };+});++describe("Imperva upload failures", () => {+ test("explains what Imperva rejects when it answers a bare 400", async () => {+ const { describeImpervaUploadFailure } = await import("./imperva-pki-sync-fns");+ const { AxiosError } = await import("axios");++ const rejected = new AxiosError("Request failed");+ rejected.response = { status: 400, data: { message: "Invalid input" } } as never;++ expect(describeImpervaUploadFailure(rejected)).toBe(+ "Invalid input. Imperva rejected the certificate. It has to cover every domain the website serves, and its chain has to be complete and ordered leaf first"+ );+ });++ test("leaves a message that is not a rejection alone", async () => {+ const { describeImpervaUploadFailure } = await import("./imperva-pki-sync-fns");+ const { AxiosError } = await import("axios");++ const rateLimited = new AxiosError("Request failed");+ rateLimited.response = { status: 429, data: {} } as never;++ expect(describeImpervaUploadFailure(rateLimited)).toBe("Imperva rate limited the request, try again shortly");+ });+});++type TRecordedRequest = { method: string; path: string; params?: Record<string, unknown> };++const firstImpervaRequest = (): TRecordedRequest => impervaRequest.mock.calls[0][0] as TRecordedRequest;++describe("Imperva slot removal", () => {+ const buildFactory = async (records: Array<{ certificateId: string; externalIdentifier: string | null }>) => {+ const { impervaPkiSyncFactory } = await import("./imperva-pki-sync-fns");+ const removeCertificatesFromDal = vi.fn();++ const factory = impervaPkiSyncFactory({+ certificateSyncDAL: {+ findByPkiSyncId: vi.fn().mockResolvedValue(records),+ removeCertificates: removeCertificatesFromDal,+ addCertificates: vi.fn(),+ findByPkiSyncAndCertificate: vi.fn().mockResolvedValue(undefined),+ updateById: vi.fn(),+ updateSyncStatus: vi.fn()+ } as never,+ certificateDAL: { findById: vi.fn().mockResolvedValue(undefined) } as never+ });++ return { factory, removeCertificatesFromDal };+ };++ const pkiSync = {+ id: "sync-1",+ destinationConfig: { siteId: "222", siteName: "current.example.com" },+ syncOptions: { canRemoveCertificates: true },+ connection: { credentials: { apiId: "id", apiKey: "key" }, gatewayId: null, gatewayPoolId: null }+ } as never;++ beforeEach(() => {+ impervaRequest.mockReset();+ impervaRequest.mockResolvedValue({});+ });++ test("deletes the slot on the site the certificate was uploaded to, not the sync's current site", async () => {+ const { factory } = await buildFactory([{ certificateId: "cert-1", externalIdentifier: "111:RSA" }]);++ await factory.removeCertificates(pkiSync, ["leaf"], {+ certificateMap: { leaf: { certificateId: "cert-1" } } as never+ });++ expect(impervaRequest).toHaveBeenCalledTimes(1);+ const request = firstImpervaRequest();+ expect(request.method).toBe("DELETE");+ expect(request.path).toBe("/api/prov/v2/sites/111/customCertificate");+ expect(request.params?.auth_type).toBe(ImpervaCertificateAuthType.Rsa);+ });++ test("cleans up an orphaned slot on its own site during a sync", async () => {+ const { factory, removeCertificatesFromDal } = await buildFactory([+ { certificateId: "cert-1", externalIdentifier: "111:ECC" }+ ]);++ const result = await factory.syncCertificates(pkiSync, {});++ expect(impervaRequest).toHaveBeenCalledTimes(1);+ const request = firstImpervaRequest();+ expect(request.method).toBe("DELETE");+ expect(request.path).toBe("/api/prov/v2/sites/111/customCertificate");+ expect(request.params?.auth_type).toBe(ImpervaCertificateAuthType.Ecc);+ expect(result.removed).toBe(1);+ expect(removeCertificatesFromDal).toHaveBeenCalledWith("sync-1", ["cert-1"]);+ });+});diff --git a/backend/src/services/pki-sync/imperva/imperva-pki-sync-fns.ts b/backend/src/services/pki-sync/imperva/imperva-pki-sync-fns.tsnew file mode 100644index 0000000000..3c87aed269--- /dev/null+++ b/backend/src/services/pki-sync/imperva/imperva-pki-sync-fns.ts@@ -0,0 +1,514 @@+/* eslint-disable no-await-in-loop */+import { AxiosError } from "axios";++import { TCertificateSyncs } from "@app/db/schemas";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { crypto } from "@app/lib/crypto/cryptography";+import { logger } from "@app/lib/logger";+import {+ buildImpervaRequestFn,+ extractImpervaErrorMessage,+ getImpervaAccountParams,+ IMPERVA_CERTIFICATES_BASE_PATH,+ IMPERVA_PROV_BASE_PATH,+ IMPERVA_PROV_HOST,+ IMPERVA_REST_HOST,+ TImpervaRequestFn+} from "@app/services/app-connection/imperva/imperva-connection-fns";+import { TImpervaConnection } from "@app/services/app-connection/imperva/imperva-connection-types";+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";+import { splitPemChain } from "@app/services/certificate/certificate-fns";+import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";+import { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums";+import { TCertificateMap } from "@app/services/pki-sync/pki-sync-types";++import { PkiSyncError } from "../pki-sync-errors";+import { TPkiSyncWithCredentials } from "../pki-sync-types";+import { ImpervaCertificateAuthType } from "./imperva-pki-sync-constants";+import { TImpervaPkiSyncConfig } from "./imperva-pki-sync-types";++type TImpervaCredentials = TImpervaConnection["credentials"];++type TImpervaPkiSyncFactoryDeps = {+ certificateSyncDAL: Pick<+ TCertificateSyncDALFactory,+ | "removeCertificates"+ | "addCertificates"+ | "findByPkiSyncAndCertificate"+ | "updateById"+ | "findByPkiSyncId"+ | "updateSyncStatus"+ >;+ certificateDAL: Pick<TCertificateDALFactory, "findById">;+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+};++type TImpervaSiteCertificate = {+ authType?: string;+ customCertificateDetails?: { hasMismatchSite?: boolean };+};++const IMPERVA_CUSTOM_CERT_TYPE = "CUSTOM_CERT";++// Imperva answers a rejected upload with a bare "Invalid input", which tells the user nothing about+// what to change, so the conditions it enforces are spelled out alongside its message.+const IMPERVA_UPLOAD_REJECTION_HINT =+ "Imperva rejected the certificate. It has to cover every domain the website serves, and its chain has to be complete and ordered leaf first";++export const describeImpervaUploadFailure = (error: unknown): string => {+ const message = extractImpervaErrorMessage(error, "Unknown error");+ const status = error instanceof AxiosError ? error.response?.status : undefined;+ return status === 400 ? `${message}. ${IMPERVA_UPLOAD_REJECTION_HINT}` : message;+};++const getImpervaCredentials = (pkiSync: TPkiSyncWithCredentials): TImpervaCredentials => {+ const credentials = pkiSync.connection.credentials as TImpervaCredentials;+ if (!credentials?.apiId || !credentials?.apiKey) {+ throw new PkiSyncError({+ message: "Imperva credentials (API ID, API key) not found in connection credentials"+ });+ }+ return credentials;+};++// Imperva keeps one custom certificate per site for each key type, so the key type is part of the+// slot a certificate occupies and is required to remove it again.+export const resolveImpervaAuthType = (certPem: string): ImpervaCertificateAuthType => {+ try {+ const keyType = crypto.nativeCrypto.createPublicKey(certPem).asymmetricKeyType;+ return keyType === "ec" ? ImpervaCertificateAuthType.Ecc : ImpervaCertificateAuthType.Rsa;+ } catch {+ return ImpervaCertificateAuthType.Rsa;+ }+};++export const buildImpervaExternalIdentifier = (siteId: string, authType: ImpervaCertificateAuthType): string =>+ `${siteId}:${authType}`;++export const parseImpervaExternalIdentifier = (+ externalIdentifier: string+): { siteId: string; authType: ImpervaCertificateAuthType } => {+ const [siteId, authType] = externalIdentifier.split(":");+ return {+ siteId,+ authType:+ authType === ImpervaCertificateAuthType.Ecc ? ImpervaCertificateAuthType.Ecc : ImpervaCertificateAuthType.Rsa+ };+};++export const buildImpervaCertificatePayload = (cert: string, certificateChain?: string): string => {+ const chain = splitPemChain(certificateChain ?? "");+ return Buffer.from([cert.trim(), ...chain].join("\n")).toString("base64");+};++export const impervaPkiSyncFactory = ({+ certificateSyncDAL,+ certificateDAL,+ gatewayV2Service,+ gatewayPoolService+}: TImpervaPkiSyncFactoryDeps) => {+ const resolveGateway = async (pkiSync: TPkiSyncWithCredentials) => {+ return gatewayPoolService+ ? gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: pkiSync.connection.gatewayId,+ gatewayPoolId: pkiSync.connection.gatewayPoolId+ })+ : (pkiSync.connection.gatewayId ?? null);+ };++ const uploadCustomCertificate = async (+ makeRequest: TImpervaRequestFn,+ credentials: TImpervaCredentials,+ siteId: string,+ payload: { certificate: string; privateKey: string; authType: ImpervaCertificateAuthType }+ ): Promise<void> => {+ await makeRequest({+ method: "PUT",+ host: IMPERVA_PROV_HOST,+ path: `${IMPERVA_PROV_BASE_PATH}/sites/${encodeURIComponent(siteId)}/customCertificate`,+ params: getImpervaAccountParams(credentials),+ headers: { "Content-Type": "application/json" },+ data: {+ certificate: payload.certificate,+ private_key: payload.privateKey,+ auth_type: payload.authType+ }+ });+ };++ const deleteCustomCertificate = async (+ makeRequest: TImpervaRequestFn,+ credentials: TImpervaCredentials,+ siteId: string,+ authType: ImpervaCertificateAuthType+ ): Promise<void> => {+ await makeRequest({+ method: "DELETE",+ host: IMPERVA_PROV_HOST,+ path: `${IMPERVA_PROV_BASE_PATH}/sites/${encodeURIComponent(siteId)}/customCertificate`,+ params: { auth_type: authType, ...getImpervaAccountParams(credentials) }+ });+ };++ const getSiteCustomCertificates = async (+ makeRequest: TImpervaRequestFn,+ credentials: TImpervaCredentials,+ siteId: string+ ): Promise<TImpervaSiteCertificate[]> => {+ const response = await makeRequest<{ data?: TImpervaSiteCertificate[] }>({+ method: "GET",+ host: IMPERVA_REST_HOST,+ path: `${IMPERVA_CERTIFICATES_BASE_PATH}/certificates`,+ params: {+ extSiteId: siteId,+ certType: IMPERVA_CUSTOM_CERT_TYPE,+ ...getImpervaAccountParams(credentials)+ }+ });++ return response.data ?? [];+ };++ // A certificate covering some but not all of the site's managed domains is deployed and flagged+ // rather than refused, and Imperva keeps serving the previous one, so the flag has to reach the sync.+ const buildDeploymentWarning = async (+ makeRequest: TImpervaRequestFn,+ credentials: TImpervaCredentials,+ siteId: string,+ authType: ImpervaCertificateAuthType+ ): Promise<string> => {+ try {+ const certificates = await getSiteCustomCertificates(makeRequest, credentials, siteId);+ const deployed = certificates.find((entry) => entry.authType === authType);++ if (!deployed) return "";+ if (deployed.customCertificateDetails?.hasMismatchSite) {+ return "Imperva reports the certificate does not cover every managed domain on the site, so it keeps serving the previous certificate";+ }+ return "";+ } catch (error: unknown) {+ logger.warn(+ { error },+ `Imperva PKI sync: unable to read certificate state for site ${siteId} after upload, continuing`+ );+ return "";+ }+ };++ type TPreparedCertificate = {+ certName: string;+ cert: string;+ privateKey: string;+ certificateChain?: string;+ certificateId?: string;+ renewedFromCertificateId?: string | null;+ };++ const prepareCertificate = async (+ certificateMap: TCertificateMap+ ): Promise<{+ certificate?: TPreparedCertificate;+ skippedCertificates: Array<{ name: string; reason: string }>;+ }> => {+ const skippedCertificates: Array<{ name: string; reason: string }> = [];+ let selected: TPreparedCertificate | undefined;++ const entries = Object.entries(certificateMap).sort(([a], [b]) => a.localeCompare(b));++ for (const [certName, certData] of entries) {+ const { cert, privateKey, certificateChain, certificateId } = certData;++ if (!cert || !privateKey) {+ skippedCertificates.push({ name: certName, reason: "Missing certificate or private key data" });+ // eslint-disable-next-line no-continue+ continue;+ }++ let renewedFromCertificateId: string | null | undefined;+ if (typeof certificateId === "string") {+ const certificate = await certificateDAL.findById(certificateId);+ if (certificate?.renewedByCertificateId) {+ skippedCertificates.push({+ name: certName,+ reason: "Certificate has been renewed and replaced by a newer certificate"+ });+ // eslint-disable-next-line no-continue+ continue;+ }+ renewedFromCertificateId = certificate?.renewedFromCertificateId;+ }++ if (selected) {+ skippedCertificates.push({+ name: certName,+ reason: "Imperva holds a single custom certificate per site"+ });+ // eslint-disable-next-line no-continue+ continue;+ }++ selected = { certName, cert, privateKey, certificateChain, certificateId, renewedFromCertificateId };+ }++ return { certificate: selected, skippedCertificates };+ };++ const syncCertificates = async (+ pkiSync: TPkiSyncWithCredentials,+ certificateMap: TCertificateMap+ ): Promise<{+ uploaded: number;+ removed?: number;+ failedRemovals?: number;+ skipped: number;+ partialFailureMessage?: string;+ details?: {+ failedUploads?: Array<{ name: string; error: string }>;+ failedRemovals?: Array<{ name: string; error: string }>;+ skippedCertificates?: Array<{ name: string; reason: string }>;+ };+ }> => {+ const credentials = getImpervaCredentials(pkiSync);+ const { siteId, siteName } = pkiSync.destinationConfig as TImpervaPkiSyncConfig;+ const syncOptions = pkiSync.syncOptions as { canRemoveCertificates?: boolean } | undefined;+ const canRemoveCertificates = syncOptions?.canRemoveCertificates ?? true;+ const siteLabel = siteName ? `${siteName} (${siteId})` : siteId;++ const effectiveGatewayId = await resolveGateway(pkiSync);+ const makeRequest = buildImpervaRequestFn({ gatewayId: effectiveGatewayId, credentials }, gatewayV2Service);++ const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);+ const { certificate, skippedCertificates } = await prepareCertificate(certificateMap);++ const failedUploads: Array<{ name: string; error: string }> = [];+ const failedRemovals: Array<{ name: string; error: string }> = [];+ const occupiedSlots = new Set<string>();+ let deploymentWarning = "";+ const activeCertificateIds = new Set<string>();+ let uploaded = 0;+ let removed = 0;++ if (certificate) {+ const authType = resolveImpervaAuthType(certificate.cert);+ const externalIdentifier = buildImpervaExternalIdentifier(siteId, authType);++ try {+ await uploadCustomCertificate(makeRequest, credentials, siteId, {+ certificate: buildImpervaCertificatePayload(certificate.cert, certificate.certificateChain),+ privateKey: Buffer.from(certificate.privateKey.trim()).toString("base64"),+ authType+ });++ occupiedSlots.add(externalIdentifier);+ uploaded += 1;++ deploymentWarning = await buildDeploymentWarning(makeRequest, credentials, siteId, authType);++ if (certificate.certificateId) {+ activeCertificateIds.add(certificate.certificateId);++ const existingCertSync = await certificateSyncDAL.findByPkiSyncAndCertificate(+ pkiSync.id,+ certificate.certificateId+ );++ if (existingCertSync) {+ await certificateSyncDAL.updateById(existingCertSync.id, {+ externalIdentifier,+ syncStatus: CertificateSyncStatus.Succeeded,+ lastSyncMessage: `Synced ${authType} custom certificate to Imperva site ${siteLabel}`,+ lastSyncedAt: new Date()+ });+ } else {+ await certificateSyncDAL.addCertificates(pkiSync.id, [+ { certificateId: certificate.certificateId, externalIdentifier }+ ]);+ }++ if (certificate.renewedFromCertificateId) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, [certificate.renewedFromCertificateId]);+ }+ }++ logger.info(+ `Imperva PKI sync [syncId=${pkiSync.id}]: uploaded ${authType} custom certificate to site ${siteLabel}`+ );+ } catch (error: unknown) {+ const errorMessage = describeImpervaUploadFailure(error);+ failedUploads.push({ name: certificate.certName, error: errorMessage });++ if (certificate.certificateId) {+ const syncRecord = await certificateSyncDAL.findByPkiSyncAndCertificate(+ pkiSync.id,+ certificate.certificateId+ );+ if (syncRecord) {+ await certificateSyncDAL.updateById(syncRecord.id, {+ syncStatus: CertificateSyncStatus.Failed,+ lastSyncMessage: `Failed to sync to Imperva: ${errorMessage}`.slice(0, 4096)+ });+ }+ }++ logger.error(+ { error },+ `Imperva PKI sync [syncId=${pkiSync.id}]: failed to upload certificate to site ${siteLabel}`+ );+ }+ }++ // A certificate this sync no longer manages leaves its slot behind on the site, so it is removed+ // unless this run wrote a new certificate into that same slot.+ if (canRemoveCertificates) {+ const orphanedRecords = existingSyncRecords.filter(+ (record: TCertificateSyncs) =>+ record.externalIdentifier &&+ !occupiedSlots.has(record.externalIdentifier) &&+ !(record.certificateId && activeCertificateIds.has(record.certificateId))+ );++ for (const record of orphanedRecords) {+ // The slot a record occupies belongs to the site it was uploaded to, which is not the sync's+ // current site once the destination has been repointed.+ const { siteId: recordSiteId, authType } = parseImpervaExternalIdentifier(record.externalIdentifier as string);+ const recordSiteLabel = recordSiteId === siteId ? siteLabel : recordSiteId;++ try {+ await deleteCustomCertificate(makeRequest, credentials, recordSiteId, authType);+ removed += 1;++ if (record.certificateId) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, [record.certificateId]);+ }++ logger.info(+ `Imperva PKI sync [syncId=${pkiSync.id}]: removed orphaned ${authType} custom certificate from site ${recordSiteLabel}`+ );+ } catch (error: unknown) {+ failedRemovals.push({+ name: record.externalIdentifier as string,+ error: extractImpervaErrorMessage(error, "Unknown error")+ });+ logger.error(+ { error },+ `Imperva PKI sync [syncId=${pkiSync.id}]: failed to remove ${authType} custom certificate from site ${recordSiteLabel}`+ );+ }+ }+ }++ if (failedUploads.length > 0) {+ throw new PkiSyncError({+ message: `Failed to sync certificate to Imperva site ${siteLabel}: ${failedUploads[0].error}`+ });+ }++ return {+ uploaded,+ removed: removed > 0 ? removed : undefined,+ failedRemovals: failedRemovals.length > 0 ? failedRemovals.length : undefined,+ skipped: skippedCertificates.length,+ partialFailureMessage: deploymentWarning || undefined,+ details: {+ failedRemovals: failedRemovals.length > 0 ? failedRemovals : undefined,+ skippedCertificates: skippedCertificates.length > 0 ? skippedCertificates : undefined+ }+ };+ };++ const removeCertificates = async (+ pkiSync: TPkiSyncWithCredentials,+ certificateNames: string[],+ deps?: {+ certificateSyncDAL?: Pick<TCertificateSyncDALFactory, "findByPkiSyncId">;+ certificateMap?: TCertificateMap;+ }+ ): Promise<void> => {+ if (certificateNames.length === 0) return;++ const credentials = getImpervaCredentials(pkiSync);+ const { siteId, siteName } = pkiSync.destinationConfig as TImpervaPkiSyncConfig;+ const siteLabel = siteName ? `${siteName} (${siteId})` : siteId;++ const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);+ // Keyed by external identifier so a record uploaded to a site the sync no longer points at is+ // still removed from the site that actually holds it.+ const slotsToRemove = new Map<string, string[]>();+ const certificateIdsToClean: string[] = [];++ for (const certName of certificateNames) {+ const certificateId = deps?.certificateMap?.[certName]?.certificateId;+ if (!certificateId) {+ // eslint-disable-next-line no-continue+ continue;+ }++ const syncRecord = existingSyncRecords.find(+ (record: TCertificateSyncs) => record.certificateId === certificateId+ );+ if (!syncRecord) {+ // eslint-disable-next-line no-continue+ continue;+ }++ // A certificate that never reached Imperva has no slot to delete, but its record still has to go+ if (!syncRecord.externalIdentifier) {+ certificateIdsToClean.push(certificateId);+ // eslint-disable-next-line no-continue+ continue;+ }++ slotsToRemove.set(syncRecord.externalIdentifier, [+ ...(slotsToRemove.get(syncRecord.externalIdentifier) ?? []),+ certificateId+ ]);+ }++ if (slotsToRemove.size === 0) {+ if (certificateIdsToClean.length > 0) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, certificateIdsToClean);+ }+ return;+ }++ const effectiveGatewayId = await resolveGateway(pkiSync);+ const makeRequest = buildImpervaRequestFn({ gatewayId: effectiveGatewayId, credentials }, gatewayV2Service);++ for (const [externalIdentifier, certificateIds] of slotsToRemove) {+ const { siteId: recordSiteId, authType } = parseImpervaExternalIdentifier(externalIdentifier);+ const recordSiteLabel = recordSiteId === siteId ? siteLabel : recordSiteId;++ try {+ await deleteCustomCertificate(makeRequest, credentials, recordSiteId, authType);+ certificateIdsToClean.push(...certificateIds);++ logger.info(+ `Imperva PKI sync [syncId=${pkiSync.id}]: removed ${authType} custom certificate from site ${recordSiteLabel}`+ );+ } catch (error: unknown) {+ const message = extractImpervaErrorMessage(error, "Unknown error");+ if (message.toLowerCase().includes("not found") || message.toLowerCase().includes("no custom certificate")) {+ certificateIdsToClean.push(...certificateIds);+ // eslint-disable-next-line no-continue+ continue;+ }++ throw new PkiSyncError({+ message: `Failed to remove ${authType} custom certificate from Imperva site ${recordSiteLabel}: ${message}`,+ shouldRetry: true+ });+ }+ }++ if (certificateIdsToClean.length > 0) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, certificateIdsToClean);+ }+ };++ return {+ syncCertificates,+ removeCertificates+ };+};diff --git a/backend/src/services/pki-sync/imperva/imperva-pki-sync-schemas.ts b/backend/src/services/pki-sync/imperva/imperva-pki-sync-schemas.tsnew file mode 100644index 0000000000..a642b8b316--- /dev/null+++ b/backend/src/services/pki-sync/imperva/imperva-pki-sync-schemas.ts@@ -0,0 +1,71 @@+import RE2 from "re2";+import { z } from "zod";++import { openApiHidden } from "@app/server/lib/schemas";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";+import {+ BasePkiSyncOptionsSchema,+ PkiSyncFiltersField,+ PkiSyncSchema,+ UpdatePkiSyncFiltersField+} from "@app/services/pki-sync/pki-sync-schemas";++const SITE_ID_PATTERN = new RE2("^[0-9]+$");++export const ImpervaPkiSyncConfigSchema = z.object({+ siteId: z+ .string()+ .trim()+ .min(1, "Site ID is required")+ .max(20, "Site ID cannot exceed 20 characters")+ .refine((val) => SITE_ID_PATTERN.test(val), {+ message: "Site ID must be the numeric Imperva website ID"+ }),+ siteName: z.string().trim().max(512, "Site name cannot exceed 512 characters").optional()+});++export const ImpervaPkiSyncOptionsSchema = BasePkiSyncOptionsSchema.pick({+ canRemoveCertificates: true,+ includeRootCa: true+});++export const ImpervaPkiSyncSchema = PkiSyncSchema.extend({+ destination: z.literal(PkiSync.Imperva),+ destinationConfig: ImpervaPkiSyncConfigSchema,+ syncOptions: ImpervaPkiSyncOptionsSchema+});++export const CreateImpervaPkiSyncSchema = z.object({+ name: z.string().trim().min(1).max(256),+ description: pkiDescriptionSchema.optional(),+ isAutoSyncEnabled: z.boolean().default(true),+ destinationConfig: ImpervaPkiSyncConfigSchema,+ syncOptions: ImpervaPkiSyncOptionsSchema,+ subscriberId: z.string().nullish(),+ connectionId: z.string(),+ projectId: z.string().trim().min(1).optional().describe(openApiHidden()),+ applicationId: z.string().uuid().optional(),+ certificateIds: z.array(z.string().uuid()).optional(),+ filters: PkiSyncFiltersField+});++export const UpdateImpervaPkiSyncSchema = z.object({+ name: z.string().trim().min(1).max(256).optional(),+ description: pkiDescriptionSchema.optional(),+ isAutoSyncEnabled: z.boolean().optional(),+ destinationConfig: ImpervaPkiSyncConfigSchema.optional(),+ syncOptions: ImpervaPkiSyncOptionsSchema.optional(),+ subscriberId: z.string().nullish(),+ connectionId: z.string().optional(),+ filters: UpdatePkiSyncFiltersField+});++export const ImpervaPkiSyncListItemSchema = z.object({+ name: z.literal("Imperva"),+ connection: z.literal(AppConnection.Imperva),+ destination: z.literal(PkiSync.Imperva),+ canImportCertificates: z.literal(false),+ canRemoveCertificates: z.literal(true)+});diff --git a/backend/src/services/pki-sync/imperva/imperva-pki-sync-types.ts b/backend/src/services/pki-sync/imperva/imperva-pki-sync-types.tsnew file mode 100644index 0000000000..96a55b6082--- /dev/null+++ b/backend/src/services/pki-sync/imperva/imperva-pki-sync-types.ts@@ -0,0 +1,22 @@+import { z } from "zod";++import { TImpervaConnection } from "@app/services/app-connection/imperva/imperva-connection-types";++import {+ CreateImpervaPkiSyncSchema,+ ImpervaPkiSyncConfigSchema,+ ImpervaPkiSyncSchema,+ UpdateImpervaPkiSyncSchema+} from "./imperva-pki-sync-schemas";++export type TImpervaPkiSyncConfig = z.infer<typeof ImpervaPkiSyncConfigSchema>;++export type TImpervaPkiSync = z.infer<typeof ImpervaPkiSyncSchema>;++export type TImpervaPkiSyncInput = z.infer<typeof CreateImpervaPkiSyncSchema>;++export type TImpervaPkiSyncUpdate = z.infer<typeof UpdateImpervaPkiSyncSchema>;++export type TImpervaPkiSyncWithCredentials = TImpervaPkiSync & {+ connection: TImpervaConnection;+};diff --git a/backend/src/services/pki-sync/imperva/index.ts b/backend/src/services/pki-sync/imperva/index.tsnew file mode 100644index 0000000000..205ac02863--- /dev/null+++ b/backend/src/services/pki-sync/imperva/index.ts@@ -0,0 +1,4 @@+export * from "./imperva-pki-sync-constants";+export * from "./imperva-pki-sync-fns";+export * from "./imperva-pki-sync-schemas";+export * from "./imperva-pki-sync-types";diff --git a/backend/src/services/pki-sync/pki-sync-enums.ts b/backend/src/services/pki-sync/pki-sync-enums.tsindex 673b91ee8d..c8e0440bd3 100644--- a/backend/src/services/pki-sync/pki-sync-enums.ts+++ b/backend/src/services/pki-sync/pki-sync-enums.ts@@ -11,6 +11,7 @@ export enum PkiSync {PaloAltoNetworksSslTlsProfile = "palo-alto-networks-ssl-tls-profile",F5BigIp = "f5-big-ip",KempLoadMaster = "kemp-loadmaster",+ Imperva = "imperva",LinuxServer = "linux-server",WindowsServer = "windows-server",NutanixPrismCentral = "nutanix-prism-central"diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.tsindex b73bce75a7..f006bdb331 100644--- a/backend/src/services/pki-sync/pki-sync-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.ts@@ -38,6 +38,8 @@ import {buildGcpTooManyCertificatesMessage,resolveGcpCertificateManagerConfigUpdate} from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-update-fns";+import { IMPERVA_PKI_SYNC_LIST_OPTION } from "./imperva/imperva-pki-sync-constants";+import { impervaPkiSyncFactory } from "./imperva/imperva-pki-sync-fns";import { KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION } from "./kemp-loadmaster/kemp-loadmaster-pki-sync-constants";import { kempLoadMasterPkiSyncFactory } from "./kemp-loadmaster/kemp-loadmaster-pki-sync-fns";import { LINUX_SERVER_PKI_SYNC_LIST_OPTION } from "./linux-server/linux-server-pki-sync-constants";@@ -98,6 +100,7 @@ const PKI_SYNC_LIST_OPTIONS = {[PkiSync.PaloAltoNetworksSslTlsProfile]: PALO_ALTO_NETWORKS_SSL_TLS_PROFILE_PKI_SYNC_LIST_OPTION,[PkiSync.F5BigIp]: F5_BIG_IP_PKI_SYNC_LIST_OPTION,[PkiSync.KempLoadMaster]: KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION,+ [PkiSync.Imperva]: IMPERVA_PKI_SYNC_LIST_OPTION,[PkiSync.LinuxServer]: LINUX_SERVER_PKI_SYNC_LIST_OPTION,[PkiSync.WindowsServer]: WINDOWS_SERVER_PKI_SYNC_LIST_OPTION,[PkiSync.NutanixPrismCentral]: NUTANIX_PRISM_CENTRAL_PKI_SYNC_LIST_OPTION@@ -287,6 +290,11 @@ export const PkiSyncFns = {"Kemp LoadMaster does not support importing certificates into Infisical (private keys cannot be extracted)");}+ case PkiSync.Imperva: {+ throw new Error(+ "Imperva does not support importing certificates into Infisical (private keys cannot be extracted)"+ );+ }case PkiSync.LinuxServer: {throw new Error("Linux Server does not support importing certificates into Infisical");}@@ -418,6 +426,16 @@ export const PkiSyncFns = {});return kempLoadMasterPkiSync.syncCertificates(pkiSync, certificateMap);}+ case PkiSync.Imperva: {+ checkPkiSyncDestination(pkiSync, PkiSync.Imperva as PkiSync);+ const impervaPkiSync = impervaPkiSyncFactory({+ certificateDAL: dependencies.certificateDAL,+ certificateSyncDAL: dependencies.certificateSyncDAL,+ gatewayV2Service: dependencies.gatewayV2Service,+ gatewayPoolService: dependencies.gatewayPoolService+ });+ return impervaPkiSync.syncCertificates(pkiSync, certificateMap);+ }case PkiSync.LinuxServer: {checkPkiSyncDestination(pkiSync, PkiSync.LinuxServer as PkiSync);const linuxServerPkiSync = linuxServerPkiSyncFactory({@@ -711,6 +729,20 @@ export const PkiSyncFns = {});break;}+ case PkiSync.Imperva: {+ checkPkiSyncDestination(pkiSync, PkiSync.Imperva as PkiSync);+ const impervaPkiSync = impervaPkiSyncFactory({+ certificateDAL: dependencies.certificateDAL,+ certificateSyncDAL: dependencies.certificateSyncDAL,+ gatewayV2Service: dependencies.gatewayV2Service,+ gatewayPoolService: dependencies.gatewayPoolService+ });+ await impervaPkiSync.removeCertificates(pkiSync, certificateNames, {+ certificateSyncDAL: dependencies.certificateSyncDAL,+ certificateMap: dependencies.certificateMap+ });+ break;+ }case PkiSync.LinuxServer: {checkPkiSyncDestination(pkiSync, PkiSync.LinuxServer as PkiSync);const linuxServerPkiSync = linuxServerPkiSyncFactory({diff --git a/backend/src/services/pki-sync/pki-sync-maps.ts b/backend/src/services/pki-sync/pki-sync-maps.tsindex 00583af5aa..d9247cd2e2 100644--- a/backend/src/services/pki-sync/pki-sync-maps.ts+++ b/backend/src/services/pki-sync/pki-sync-maps.ts@@ -15,6 +15,7 @@ export const PKI_SYNC_NAME_MAP: Record<PkiSync, string> = {[PkiSync.PaloAltoNetworksSslTlsProfile]: "Palo Alto Networks SSL/TLS Profile",[PkiSync.F5BigIp]: "F5 BIG-IP",[PkiSync.KempLoadMaster]: "Kemp LoadMaster",+ [PkiSync.Imperva]: "Imperva",[PkiSync.LinuxServer]: "Linux Server",[PkiSync.WindowsServer]: "Windows Server",[PkiSync.NutanixPrismCentral]: "Nutanix Prism Central"@@ -33,6 +34,7 @@ export const PKI_SYNC_CONNECTION_MAP: Record<PkiSync, AppConnection> = {[PkiSync.PaloAltoNetworksSslTlsProfile]: AppConnection.PaloAltoNetworks,[PkiSync.F5BigIp]: AppConnection.F5BigIp,[PkiSync.KempLoadMaster]: AppConnection.KempLoadMaster,+ [PkiSync.Imperva]: AppConnection.Imperva,[PkiSync.LinuxServer]: AppConnection.SSH,[PkiSync.WindowsServer]: AppConnection.WinRM,[PkiSync.NutanixPrismCentral]: AppConnection.NutanixPrismCentraldiff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex 07f773b3c2..d445692e9d 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -984,18 +984,31 @@ export const pkiSyncServiceFactory = ({});if (syncOptions || destinationConfig) {- const existingCount = (await certificateSyncDAL.findByPkiSyncId(id)).length;+ const effectiveFilters = filters === undefined ? (pkiSync.filters as TPkiSyncFilters | null) : filters;++ // Link rows also carry a certificate on its way out and whatever a failed removal left, and+ // counting those blocks the edit that fixes them.+ const heldCount =+ hasAnyPkiSyncFilter(effectiveFilters) && pkiSync.applicationId+ ? (+ await certificateDAL.findCertificatesMatchingSyncFilters(effectiveFilters, {+ projectId: pkiSync.projectId,+ applicationId: pkiSync.applicationId+ })+ ).length+ : (await certificateSyncDAL.findByPkiSyncId(id)).length;+assertPkiSyncCertificateCapsAllowCount(pkiSync.destination,effectiveSyncOptions,effectiveDestinationConfig,- existingCount+ heldCount);assertFiltersCannotExceedCertificateCap(pkiSync.destination,effectiveSyncOptions,effectiveDestinationConfig,- filters === undefined ? (pkiSync.filters as TPkiSyncFilters | null) : filters+ effectiveFilters);}@@ -1279,6 +1292,13 @@ export const pkiSyncServiceFactory = ({actor);+ // Removing a sync's certificates unlinks them, and without this only the next issuance relinks.+ if (pkiSync.applicationId && hasAnyPkiSyncFilter(pkiSync.filters as TPkiSyncFilters | null)) {+ await $withFilterLock(id, () =>+ $reconcileFilters(pkiSync as TPkiSyncReconcileTarget, pkiSync.filters as TPkiSyncFilters | null)+ );+ }+await pkiSyncDAL.updateById(id, { syncStatus: PkiSyncStatus.Pending, lastSyncMessage: null });await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: id });diff --git a/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt b/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txtindex 497a6738c2..b0ff89d512 100644--- a/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt+++ b/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt@@ -308,6 +308,7 @@ TomcatHAProxyJBossWildFly+ImpervaKempLoadMasterNetScaler@@ -551,6 +552,7 @@ VPC(?:s)?VPN(?:s)?vCPU(?:s)?+booleanswalkthroughwalkthroughsdiff --git a/docs/api-reference/endpoints/app-connections/imperva/create.mdx b/docs/api-reference/endpoints/app-connections/imperva/create.mdxnew file mode 100644index 0000000000..e36701483e--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/imperva/create.mdx@@ -0,0 +1,4 @@+---+title: "Create"+openapi: "POST /api/v1/app-connections/imperva"+---diff --git a/docs/api-reference/endpoints/pki/syncs/imperva/create.mdx b/docs/api-reference/endpoints/pki/syncs/imperva/create.mdxnew file mode 100644index 0000000000..78b6b186f9--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/imperva/create.mdx@@ -0,0 +1,4 @@+---+title: "Create"+openapi: "POST /api/v1/cert-manager/syncs/imperva"+---diff --git a/docs/api-reference/endpoints/pki/syncs/imperva/sync-certificates.mdx b/docs/api-reference/endpoints/pki/syncs/imperva/sync-certificates.mdxnew file mode 100644index 0000000000..374fbe409e--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/imperva/sync-certificates.mdx@@ -0,0 +1,4 @@+---+title: "Sync certificates to Imperva"+openapi: "POST /api/v1/cert-manager/syncs/imperva/{pkiSyncId}/sync"+---diff --git a/docs/docs.json b/docs/docs.jsonindex b614089eea..dc4bac220d 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -509,6 +509,7 @@"documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate","documentation/platform/pki/applications/certificate-syncs/f5-big-ip","documentation/platform/pki/applications/certificate-syncs/netscaler",+ "documentation/platform/pki/applications/certificate-syncs/imperva","documentation/platform/pki/applications/certificate-syncs/palo-alto-networks","documentation/platform/pki/applications/certificate-syncs/palo-alto-networks-ssl-tls-profile","documentation/platform/pki/applications/certificate-syncs/kemp-loadmaster",@@ -1077,6 +1078,7 @@"integrations/app-connections/heroku","integrations/app-connections/hpe-ilo","integrations/app-connections/humanitec",+ "integrations/app-connections/imperva","integrations/app-connections/keeper","integrations/app-connections/kemp-loadmaster","integrations/app-connections/external-infisical",@@ -2133,6 +2135,7 @@{"group": "Kemp LoadMaster","pages": [+ "api-reference/endpoints/app-connections/imperva/create","api-reference/endpoints/app-connections/kemp-loadmaster/create"]},@@ -4194,6 +4197,8 @@{"group": "Kemp LoadMaster","pages": [+ "api-reference/endpoints/pki/syncs/imperva/create",+ "api-reference/endpoints/pki/syncs/imperva/sync-certificates","api-reference/endpoints/pki/syncs/kemp-loadmaster/create","api-reference/endpoints/pki/syncs/kemp-loadmaster/sync-certificates"]diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/imperva.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/imperva.mdxnew file mode 100644index 0000000000..9ab761df3d--- /dev/null+++ b/docs/documentation/platform/pki/applications/certificate-syncs/imperva.mdx@@ -0,0 +1,167 @@+---+title: "Imperva"+sidebarTitle: "Imperva"+description: "Deploy certificates to websites protected by Imperva Cloud WAF."+---++Deploy certificates as custom certificates on Imperva Cloud WAF websites, so the WAF presents your own certificate to visitors instead of an Imperva-generated one.++<Info>+ Certificate Syncs are configured per Application. First select which certificates to sync, then configure the Imperva destination.+</Info>++Imperva stores one custom certificate per website for each key type, so a sync targets a single website and holds a single certificate. A renewal replaces the certificate already on that website.++## Prerequisites++- An [Imperva Connection](/integrations/app-connections/imperva) whose API key has the **Manage SSL Certificates** permission+- A website already protected by Imperva Cloud WAF+- A certificate whose subject alternative names cover every managed domain on that website+- An RSA 2048-bit or ECDSA P-256 certificate. Imperva blocks RSA 4096-bit uploads, and ECDSA P-384 needs prior approval from Imperva Support++## Create an Imperva sync++<Tabs>+ <Tab title="Infisical UI">+ 1. In your Application, go to the **Certificate Syncs** tab and select **Create Sync**.++ 2. Select the **Imperva** option.++ 3. Configure the **Destination**:+ - **Imperva Connection**: The connection to authenticate with.+ - **Website**: The website that receives the certificate, selected from the websites in the Imperva account.++ 4. Configure the **Sync Options**:+ - **Enable Removal of Expired/Revoked Certificates**: Remove the custom certificate from the website once the certificate is no longer active in Infisical. The website then falls back to whichever certificate Imperva would otherwise serve.+ - **Include Root CA in Certificate Chain**: Leave this off. Imperva recommends uploading trusted certificates without the root for a faster TLS handshake.+ - **Auto-Sync Enabled**: Automatically sync certificates when changes occur.++ 5. Configure the **Details**:+ - **Name**: The name of your sync (slug-friendly).+ - **Description**: Optional description.++ 6. Select the certificate to sync.++ 7. Review and click **Create Sync**.+ </Tab>+ <Tab title="API">+ To create an **Imperva Certificate Sync**, make an API request to the [Create Imperva PKI Sync](/api-reference/endpoints/pki/syncs/imperva/create) endpoint.++ ### Sample request++ <Note>+ You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.+ If not provided, you can add certificates later using the certificate management endpoints.+ </Note>++ ```bash Request+ curl --request POST \+ --url https://app.infisical.com/api/v1/cert-manager/syncs/imperva \+ --header 'Authorization: Bearer <access-token>' \+ --header 'Content-Type: application/json' \+ --data '{+ "name": "my-imperva-cert-sync",+ "applicationId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "description": "an example certificate sync",+ "connectionId": "550e8400-e29b-41d4-a716-446655440000",+ "destination": "imperva",+ "isAutoSyncEnabled": true,+ "certificateIds": [+ "550e8400-e29b-41d4-a716-446655440000"+ ],+ "syncOptions": {+ "canRemoveCertificates": true,+ "includeRootCa": false+ },+ "destinationConfig": {+ "siteId": "12345",+ "siteName": "app.example.com"+ }+ }'+ ```++ ### Sample response++ ```json Response+ {+ "pkiSync": {+ "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "name": "my-imperva-cert-sync",+ "description": "an example certificate sync",+ "destination": "imperva",+ "isAutoSyncEnabled": true,+ "destinationConfig": {+ "siteId": "12345",+ "siteName": "app.example.com"+ },+ "syncOptions": {+ "canRemoveCertificates": true,+ "includeRootCa": false+ },+ "applicationId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "connectionId": "550e8400-e29b-41d4-a716-446655440000",+ "createdAt": "2026-09-15T00:00:00.000Z",+ "updatedAt": "2026-09-15T00:00:00.000Z"+ }+ }+ ```+ </Tab>+</Tabs>++## How it works++Infisical uploads the certificate and its private key to the website as a custom certificate:++- The leaf certificate and its intermediate CA certificates are sent as one chain, so visitors receive a complete trust path.+- The key type is read from the certificate, and Imperva stores it in the matching RSA or ECDSA slot on the website.+- A renewal overwrites the certificate in that slot, so the website keeps serving without a binding step.+- Imperva serves a custom certificate to clients that support SNI. To cover clients that don't, add the domain to an Imperva SAN certificate as well.++## Removing certificates++When certificate removal is enabled and the certificate is no longer active in Infisical, Infisical deletes the custom certificate from the website. Imperva then serves whichever other certificate covers the requested domain, usually the Imperva-generated one.++## Manual certificate sync++You can manually trigger certificate synchronization to Imperva using the sync certificates functionality. This is useful for:++- Initial setup when you have an existing certificate to deploy+- Testing certificate sync configurations+- Force sync after making changes++To manually sync certificates, use the [Sync Certificates](/api-reference/endpoints/pki/syncs/imperva/sync-certificates) API endpoint or the manual sync option in the Infisical UI.++## FAQ++<Accordion title="Can I sync more than one certificate to a website?">+ No. Imperva holds one custom certificate per website for each key type, so a sync deploys a single certificate. Additional certificates in the sync are skipped and reported on the sync run. To cover several domains with one certificate, use a certificate whose subject alternative names include them.+</Accordion>++<Accordion title="Why was the certificate rejected, or reported as not covering every managed domain?">+ Imperva compares the certificate's subject alternative names against the domains configured on the website. A certificate that covers none of them is rejected outright. The sync then fails with Imperva's own message. A certificate that covers some but not all is accepted. Imperva reports a site mismatch, keeps serving the previous certificate, and Infisical surfaces the mismatch on the sync. Reissue the certificate with every managed domain, then sync again.+</Accordion>++<Accordion title="Can I import certificates from Imperva back into Infisical?">+ No. Private keys can't be read back out of Imperva, so the sync only pushes certificates.+</Accordion>++<Accordion title="Does uploading a certificate change any other website setting?">+ Yes. Each custom certificate upload resets the website's **Enable HTTP/2** setting to your account-level default. Check that default in Imperva before your first sync if the website relies on a per-website value.+</Accordion>++## What's next?++<CardGroup cols={2}>+ <Card title="NetScaler" icon="server" href="/documentation/platform/pki/applications/certificate-syncs/netscaler">+ Deploy certificates to Citrix NetScaler appliances.+ </Card>+ <Card title="Auto-Renewal" icon="arrows-spin" href="/documentation/platform/pki/applications/certificates#server-driven-renewal">+ Enable automatic certificate renewal and syncing.+ </Card>+ <Card title="Alerting" icon="bell" href="/documentation/platform/pki/applications/alerting/overview">+ Get notified about certificate lifecycle events.+ </Card>+ <Card title="Other Sync Destinations" icon="arrows-rotate" href="/documentation/platform/pki/applications/certificate-syncs/overview">+ View all supported sync destinations.+ </Card>+</CardGroup>diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdxindex 53ad4af644..5c309e5848 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx@@ -43,6 +43,9 @@ Push certificates from your Application to external services automatically. When<Card title="Palo Alto Networks SSL/TLS profile" icon="shield" href="/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks-ssl-tls-profile">Point a PAN-OS SSL/TLS service profile at a synced certificate.</Card>+ <Card title="Imperva" icon="shield-halved" href="/documentation/platform/pki/applications/certificate-syncs/imperva">+ Deploy certificates to Imperva Cloud WAF websites.+ </Card><Card title="Kemp LoadMaster" icon="scale" href="/documentation/platform/pki/applications/certificate-syncs/kemp-loadmaster">Deploy certificates to Progress Kemp LoadMaster.</Card>diff --git a/docs/integrations/app-connections/imperva.mdx b/docs/integrations/app-connections/imperva.mdxnew file mode 100644index 0000000000..126e8777ae--- /dev/null+++ b/docs/integrations/app-connections/imperva.mdx@@ -0,0 +1,91 @@+---+title: "Imperva connection"+sidebarTitle: "Imperva"+description: "Learn how to configure an Imperva Connection for Infisical."+---++Infisical connects to Imperva Cloud WAF with an account API key, which it uses to read the websites in your account and to manage their custom certificates.++## Setup++<Tabs>+ <Tab title="Infisical UI">+ <Steps>+ <Step title="Create an Imperva API key">+ In the Imperva Cloud Security Console, go to **Account Management > User Management > My Profile** and add an API key under **API keys**. Copy the **API ID** and **API key**; the key is shown only once.++ <Note>+ A new key is created disabled. Switch it on in the API keys list, or every call fails as an invalid API ID or key.+ </Note>++ <Note>+ The key needs the **Manage SSL Certificates** permission. Without it, Imperva rejects certificate uploads for every website in the account.+ </Note>+ </Step>+ <Step title="Note the account ID for a sub-account">+ An API key acts on the account it was created in. To manage websites that belong to a sub-account, copy that sub-account's numeric account ID from **Account > Account Management**.+ </Step>+ <Step title="Navigate to App Connections">+ In Certificate Manager, navigate to **Settings > App Connections** and click **Add Connection**.+ </Step>+ <Step title="Select Imperva">+ Select the **Imperva** option from the list of available connections.+ </Step>+ <Step title="Fill in Connection Details">+ - **API ID**: The API ID from the Imperva Cloud Security Console.+ - **API Key**: The API key paired with that ID.+ - **Account ID** (Optional): The numeric ID of the sub-account whose websites this connection manages. Leave it empty to use the account the key belongs to.++ Optionally select a **Gateway** to send the Imperva API calls through an Infisical Gateway, so outbound traffic leaves from a network you control.++ Click **Connect to Imperva** to validate and save your connection.+ </Step>+ <Step title="Connection Created">+ Your Imperva Connection is now available for use with certificate syncs.+ </Step>+ </Steps>+ </Tab>+ <Tab title="API">+ To create an Imperva Connection, make an API request to the [Create App Connection](/api-reference/endpoints/app-connections/imperva/create) endpoint.++ ### Sample request++ ```bash Request+ curl --request POST \+ --url https://app.infisical.com/api/v1/app-connections/imperva \+ --header 'Authorization: Bearer <access-token>' \+ --header 'Content-Type: application/json' \+ --data '{+ "name": "my-imperva-connection",+ "method": "api-key",+ "credentials": {+ "apiId": "12345",+ "apiKey": "<api-key>",+ "accountId": "678901"+ }+ }'+ ```++ ### Sample response++ ```json Response+ {+ "appConnection": {+ "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "name": "my-imperva-connection",+ "description": null,+ "version": 1,+ "orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "createdAt": "2026-09-15T00:00:00.000Z",+ "updatedAt": "2026-09-15T00:00:00.000Z",+ "app": "imperva",+ "method": "api-key",+ "credentials": {+ "apiId": "12345",+ "accountId": "678901"+ }+ }+ }+ ```+ </Tab>+</Tabs>diff --git a/frontend/public/images/integrations/Imperva.png b/frontend/public/images/integrations/Imperva.pngnew file mode 100644index 0000000000..c389016681Binary files /dev/null and b/frontend/public/images/integrations/Imperva.png differdiff --git a/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsx b/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsxnew file mode 100644index 0000000000..8e05f948c8--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsx@@ -0,0 +1,115 @@+import { Controller, useFormContext, useWatch } from "react-hook-form";+import { AxiosError } from "axios";+import { Info, Loader2Icon } from "lucide-react";++import {+ Field,+ FieldError,+ FieldLabel,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { PkiSync } from "@app/hooks/api/pkiSyncs";+import { useListImpervaSites } from "@app/hooks/api/pkiSyncs/queries";++import { TPkiSyncForm } from "./schemas/pki-sync-schema";+import { PkiSyncConnectionField } from "./PkiSyncConnectionField";++type TImpervaForm = TPkiSyncForm & { destination: PkiSync.Imperva };++export const ImpervaPkiSyncFields = () => {+ const { control, setValue } = useFormContext<TImpervaForm>();++ const connectionId = useWatch({ name: "connection.id", control });++ const {+ data: sites,+ isFetching: isLoadingSites,+ isError: isSitesError,+ error: sitesError+ } = useListImpervaSites(+ { connectionId },+ {+ enabled: Boolean(connectionId)+ }+ );++ return (+ <>+ <PkiSyncConnectionField+ onChange={() => {+ setValue("destinationConfig.siteId", "");+ setValue("destinationConfig.siteName", "");+ }}+ />+ <Controller+ name="destinationConfig.siteId"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => {+ const siteFetchErrorText =+ isSitesError && connectionId+ ? ((sitesError as AxiosError<{ message?: string }>)?.response?.data?.message ??+ "Failed to fetch websites. Check connection settings.")+ : undefined;++ const combinedError =+ error ??+ (siteFetchErrorText ? { type: "manual", message: siteFetchErrorText } : undefined);++ return (+ <Field className="mb-4">+ <FieldLabel>+ Website+ <Tooltip>+ <TooltipTrigger asChild>+ <Info />+ </TooltipTrigger>+ <TooltipContent className="max-w-sm">+ The Imperva website that will receive the custom certificate. Imperva holds one+ custom certificate per website for each key type.+ </TooltipContent>+ </Tooltip>+ </FieldLabel>+ {connectionId && isLoadingSites ? (+ <div className="flex items-center gap-2 py-2 text-sm text-muted">+ <Loader2Icon className="size-4 animate-spin" />+ Loading websites...+ </div>+ ) : (+ <Select+ value={value ?? ""}+ onValueChange={(newValue) => {+ const site = sites?.find((s) => s.id === newValue);+ onChange(newValue);+ setValue("destinationConfig.siteName", site?.name ?? "");+ }}+ disabled={!connectionId || isLoadingSites}+ >+ <SelectTrigger className="w-full" isError={Boolean(combinedError)}>+ <SelectValue+ placeholder={connectionId ? "Select a website" : "Select a connection first"}+ />+ </SelectTrigger>+ <SelectContent position="popper">+ {(sites ?? []).map((site) => (+ <SelectItem key={site.id} value={site.id}>+ {site.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ <FieldError errors={[combinedError]} />+ </Field>+ );+ }}+ />+ </>+ );+};diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsxindex 5ef33ac422..2dd5bfcee9 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx@@ -11,6 +11,7 @@ import { ChefPkiSyncFields } from "./ChefPkiSyncFields";import { CloudflareCustomCertificatePkiSyncFields } from "./CloudflareCustomCertificatePkiSyncFields";import { F5BigIpPkiSyncFields } from "./F5BigIpPkiSyncFields";import { GcpCertificateManagerPkiSyncFields } from "./GcpCertificateManagerPkiSyncFields";+import { ImpervaPkiSyncFields } from "./ImpervaPkiSyncFields";import { KempLoadMasterPkiSyncFields } from "./KempLoadMasterPkiSyncFields";import { LinuxServerPkiSyncFields } from "./LinuxServerPkiSyncFields";import { NetScalerPkiSyncFields } from "./NetScalerPkiSyncFields";@@ -52,6 +53,8 @@ export const PkiSyncDestinationFields = ({ isUpdate }: Props) => {return <F5BigIpPkiSyncFields />;case PkiSync.KempLoadMaster:return <KempLoadMasterPkiSyncFields />;+ case PkiSync.Imperva:+ return <ImpervaPkiSyncFields />;case PkiSync.LinuxServer:return <LinuxServerPkiSyncFields />;case PkiSync.WindowsServer:diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsxindex fd061d59f7..f8b03b2e93 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx@@ -93,90 +93,92 @@ export const PkiSyncOptionsFields = ({ destination, isUpdate }: Props) => {{renderDestinationOptions(currentDestination, isUpdate)}- {currentDestination !== PkiSync.NutanixPrismCentral && (- <Controller- control={control}- name="syncOptions.certificateNameSchema"- render={({ field: { value, onChange }, fieldState: { error } }) => (- <Field className="mb-4">- <FieldLabel>- Certificate name schema- {currentDestination === PkiSync.AwsElasticLoadBalancer && (- <span className="text-muted">(optional)</span>- )}- <NameSchemaHoverCard>- <span>- When a certificate is synced, the certificate name schema will be applied before- it reaches the destination.- </span>+ {currentDestination !== PkiSync.NutanixPrismCentral &&+ currentDestination !== PkiSync.Imperva && (+ <Controller+ control={control}+ name="syncOptions.certificateNameSchema"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>+ Certificate name schema+ {currentDestination === PkiSync.AwsElasticLoadBalancer && (+ <span className="text-muted">(optional)</span>+ )}+ <NameSchemaHoverCard>+ <span>+ When a certificate is synced, the certificate name schema will be applied+ before it reaches the destination.+ </span>- <div className="flex flex-col">- <span>Available placeholders:</span>- <ul className="list-disc pl-4 text-sm">- <li>- <code>{"{{certificateId}}"}</code> - The unique ID of the certificate- </li>- <li>- <code>{"{{shortCertificateId}}"}</code> - A shorter (22-character) form of- the certificate ID. Use it instead of <code>{"{{certificateId}}"}</code>{" "}- when the destination's name limit is tight (e.g. NetScaler's 63- characters).- </li>- <li>- <code>{"{{commonName}}"}</code> - The certificate's common name (FQDN)- </li>- <li>- <code>{"{{profileId}}"}</code> - The certificate profile ID (falls back to- the certificate ID when none is set)- </li>- <li>- <code>{"{{applicationId}}"}</code> - The ID of the application the sync- belongs to- </li>- <li>- <code>{"{{applicationName}}"}</code> - The name of the application the sync- belongs to- </li>- </ul>- {currentDestination === PkiSync.LinuxServer ||- currentDestination === PkiSync.WindowsServer ? (- <span className="mt-1 text-xs text-muted">- A placeholder is optional here. Include one (for example{" "}- <code>{"{{commonName}}"}</code>) so each certificate resolves to a distinct- file name. A schema with no placeholder resolves to a fixed name and can be- linked to only one certificate. When placeholders resolve, any characters- the destination doesn't support are replaced with hyphens.- </span>- ) : (- <span className="mt-1 text-xs text-muted">- The schema must include <code>{"{{certificateId}}"}</code> or{" "}- <code>{"{{shortCertificateId}}"}</code> so each certificate gets a unique- name. The template itself can only contain letters, numbers, and the- separators allowed by the destination. When placeholders resolve, any- characters the destination doesn't support are replaced with hyphens.- </span>- )}- </div>- </NameSchemaHoverCard>- </FieldLabel>- <Input- value={value || ""}- onChange={(e) => onChange(e.target.value)}- placeholder={- syncOption?.defaultCertificateNameSchema || "INFISICAL_{{certificateId}}"- }- isError={Boolean(error)}- />- <FieldDescription>- {currentDestination === PkiSync.AwsElasticLoadBalancer- ? "Set a Certificate Name Schema so Infisical only manages the specific certificates you intend to, keeping everything else untouched."- : "The Certificate Name Schema ensures Infisical only manages the specific certificates you intend to, keeping everything else untouched."}- </FieldDescription>- <FieldError errors={[error]} />- </Field>- )}- />- )}+ <div className="flex flex-col">+ <span>Available placeholders:</span>+ <ul className="list-disc pl-4 text-sm">+ <li>+ <code>{"{{certificateId}}"}</code> - The unique ID of the certificate+ </li>+ <li>+ <code>{"{{shortCertificateId}}"}</code> - A shorter (22-character) form of+ the certificate ID. Use it instead of <code>{"{{certificateId}}"}</code>{" "}+ when the destination's name limit is tight (e.g. NetScaler's 63+ characters).+ </li>+ <li>+ <code>{"{{commonName}}"}</code> - The certificate's common name+ (FQDN)+ </li>+ <li>+ <code>{"{{profileId}}"}</code> - The certificate profile ID (falls back to+ the certificate ID when none is set)+ </li>+ <li>+ <code>{"{{applicationId}}"}</code> - The ID of the application the sync+ belongs to+ </li>+ <li>+ <code>{"{{applicationName}}"}</code> - The name of the application the+ sync belongs to+ </li>+ </ul>+ {currentDestination === PkiSync.LinuxServer ||+ currentDestination === PkiSync.WindowsServer ? (+ <span className="mt-1 text-xs text-muted">+ A placeholder is optional here. Include one (for example{" "}+ <code>{"{{commonName}}"}</code>) so each certificate resolves to a+ distinct file name. A schema with no placeholder resolves to a fixed name+ and can be linked to only one certificate. When placeholders resolve, any+ characters the destination doesn't support are replaced with hyphens.+ </span>+ ) : (+ <span className="mt-1 text-xs text-muted">+ The schema must include <code>{"{{certificateId}}"}</code> or{" "}+ <code>{"{{shortCertificateId}}"}</code> so each certificate gets a unique+ name. The template itself can only contain letters, numbers, and the+ separators allowed by the destination. When placeholders resolve, any+ characters the destination doesn't support are replaced with hyphens.+ </span>+ )}+ </div>+ </NameSchemaHoverCard>+ </FieldLabel>+ <Input+ value={value || ""}+ onChange={(e) => onChange(e.target.value)}+ placeholder={+ syncOption?.defaultCertificateNameSchema || "INFISICAL_{{certificateId}}"+ }+ isError={Boolean(error)}+ />+ <FieldDescription>+ {currentDestination === PkiSync.AwsElasticLoadBalancer+ ? "Set a Certificate Name Schema so Infisical only manages the specific certificates you intend to, keeping everything else untouched."+ : "The Certificate Name Schema ensures Infisical only manages the specific certificates you intend to, keeping everything else untouched."}+ </FieldDescription>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ )}</>);};diff --git a/frontend/src/components/pki-syncs/forms/schemas/imperva-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/imperva-pki-sync-destination-schema.tsnew file mode 100644index 0000000000..f852cbd2b3--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/schemas/imperva-pki-sync-destination-schema.ts@@ -0,0 +1,46 @@+import { z } from "zod";++import { PkiSync } from "@app/hooks/api/pkiSyncs";++import { BasePkiSyncSchema } from "./base-pki-sync-schema";++const ImpervaSyncOptionsSchema = z.object({+ canRemoveCertificates: z.boolean().default(true),+ includeRootCa: z.boolean().default(false),+ // hidden in the UI; Imperva holds one custom certificate per site, so certificates are not named+ certificateNameSchema: z.string().optional()+});++export const ImpervaPkiSyncDestinationSchema = BasePkiSyncSchema(ImpervaSyncOptionsSchema).merge(+ z.object({+ destination: z.literal(PkiSync.Imperva),+ destinationConfig: z.object({+ siteId: z+ .string()+ .trim()+ .min(1, "Website is required")+ .regex(/^[0-9]+$/, "Website ID must be the numeric Imperva website ID")+ .max(20, "Website ID cannot exceed 20 characters"),+ siteName: z.string().trim().max(512).optional()+ })+ })+);++export const UpdateImpervaPkiSyncDestinationSchema =+ ImpervaPkiSyncDestinationSchema.partial().merge(+ z.object({+ name: z+ .string()+ .trim()+ .min(1, "Name is required")+ .max(255, "Name must be less than 255 characters"),+ destination: z.literal(PkiSync.Imperva),+ connection: z.object({+ id: z.string().uuid("Invalid connection ID format"),+ name: z+ .string()+ .min(1, "Connection name is required")+ .max(255, "Connection name must be less than 255 characters")+ })+ })+ );diff --git a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.tsindex f259a60be7..7137622572 100644--- a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts@@ -41,6 +41,10 @@ import {GcpCertificateManagerPkiSyncDestinationSchema,UpdateGcpCertificateManagerPkiSyncDestinationSchema} from "./gcp-certificate-manager-pki-sync-destination-schema";+import {+ ImpervaPkiSyncDestinationSchema,+ UpdateImpervaPkiSyncDestinationSchema+} from "./imperva-pki-sync-destination-schema";import {KempLoadMasterPkiSyncDestinationSchema,UpdateKempLoadMasterPkiSyncDestinationSchema@@ -79,6 +83,7 @@ const PkiSyncUnionSchema = z.discriminatedUnion("destination", [PaloAltoNetworksSslTlsProfileDestinationSchemas.createSchema,F5BigIpPkiSyncDestinationSchema,KempLoadMasterPkiSyncDestinationSchema,+ ImpervaPkiSyncDestinationSchema,LinuxServerPkiSyncDestinationSchema,WindowsServerPkiSyncDestinationSchema,NutanixPrismCentralPkiSyncDestinationSchema@@ -97,6 +102,7 @@ const UpdatePkiSyncUnionSchema = z.discriminatedUnion("destination", [PaloAltoNetworksSslTlsProfileDestinationSchemas.updateSchema,UpdateF5BigIpPkiSyncDestinationSchema,UpdateKempLoadMasterPkiSyncDestinationSchema,+ UpdateImpervaPkiSyncDestinationSchema,UpdateLinuxServerPkiSyncDestinationSchema,UpdateWindowsServerPkiSyncDestinationSchema,UpdateNutanixPrismCentralPkiSyncDestinationSchemadiff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.tsindex 567f20409f..0802c684bf 100644--- a/frontend/src/helpers/appConnections.ts+++ b/frontend/src/helpers/appConnections.ts@@ -74,6 +74,7 @@ import { GoDaddyConnectionMethod } from "@app/hooks/api/appConnections/types/godimport { HasuraCloudConnectionMethod } from "@app/hooks/api/appConnections/types/hasura-cloud-connection";import { HerokuConnectionMethod } from "@app/hooks/api/appConnections/types/heroku-connection";import { HpeIloConnectionMethod } from "@app/hooks/api/appConnections/types/hpe-ilo-connection";+import { ImpervaConnectionMethod } from "@app/hooks/api/appConnections/types/imperva-connection";import { KeeperConnectionMethod } from "@app/hooks/api/appConnections/types/keeper-connection";import { KempLoadMasterConnectionMethod } from "@app/hooks/api/appConnections/types/kemp-loadmaster-connection";import { LaravelForgeConnectionMethod } from "@app/hooks/api/appConnections/types/laravel-forge-connection";@@ -536,6 +537,12 @@ export const APP_CONNECTION_MAP: Record<category: "NETWORKING",description: "Connect to a Palo Alto Networks firewall or Panorama."},+ [AppConnection.Imperva]: {+ name: "Imperva",+ image: "Imperva.png",+ category: "NETWORKING",+ description: "Manage websites protected by Imperva Cloud WAF."+ },[AppConnection.KempLoadMaster]: {name: "Kemp LoadMaster",image: "Kemp LoadMaster.png",@@ -896,6 +903,7 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"])case HpeIloConnectionMethod.BasicAuth:return { name: "Basic Auth", icon: LockIcon };case NutanixPrismCentralConnectionMethod.ApiKey:+ case ImpervaConnectionMethod.ApiKey:return { name: "API Key", icon: KeyRoundIcon };case OVHConnectionMethod.Certificate:return { name: "Certificate", icon: FileBadgeIcon };diff --git a/frontend/src/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.tsindex 88c8ebac7b..d011744758 100644--- a/frontend/src/helpers/pkiSyncs.ts+++ b/frontend/src/helpers/pkiSyncs.ts@@ -82,6 +82,12 @@ export const PKI_SYNC_MAP: Record<category: "Networking",description: "Sync certificates to F5 BIG-IP."},+ [PkiSync.Imperva]: {+ name: "Imperva",+ image: "Imperva.png",+ category: "Networking",+ description: "Sync certificates to Imperva Cloud WAF websites."+ },[PkiSync.KempLoadMaster]: {name: "Kemp LoadMaster",image: "Kemp LoadMaster.png",@@ -148,6 +154,7 @@ export const PKI_SYNC_CONNECTION_MAP: Record<PkiSync, AppConnection> = {[PkiSync.PaloAltoNetworksSslTlsProfile]: AppConnection.PaloAltoNetworks,[PkiSync.F5BigIp]: AppConnection.F5BigIp,[PkiSync.KempLoadMaster]: AppConnection.KempLoadMaster,+ [PkiSync.Imperva]: AppConnection.Imperva,[PkiSync.LinuxServer]: AppConnection.SSH,[PkiSync.WindowsServer]: AppConnection.WinRM,[PkiSync.NutanixPrismCentral]: AppConnection.NutanixPrismCentraldiff --git a/frontend/src/hooks/api/appConnections/enums.ts b/frontend/src/hooks/api/appConnections/enums.tsindex f95ab21072..e1723f169a 100644--- a/frontend/src/hooks/api/appConnections/enums.ts+++ b/frontend/src/hooks/api/appConnections/enums.ts@@ -64,6 +64,7 @@ export enum AppConnection {NetScaler = "netscaler",PaloAltoNetworks = "palo-alto-networks",KempLoadMaster = "kemp-loadmaster",+ Imperva = "imperva",Anthropic = "anthropic",OVH = "ovh",Devin = "devin",diff --git a/frontend/src/hooks/api/appConnections/types/app-options.ts b/frontend/src/hooks/api/appConnections/types/app-options.tsindex b9a68945ca..ddc4e3c984 100644--- a/frontend/src/hooks/api/appConnections/types/app-options.ts+++ b/frontend/src/hooks/api/appConnections/types/app-options.ts@@ -293,6 +293,10 @@ export type TKempLoadMasterConnectionOption = TAppConnectionOptionBase & {app: AppConnection.KempLoadMaster;};+export type TImpervaConnectionOption = TAppConnectionOptionBase & {+ app: AppConnection.Imperva;+};+export type TAnthropicConnectionOption = TAppConnectionOptionBase & {app: AppConnection.Anthropic;};@@ -452,6 +456,7 @@ export type TAppConnectionOption =| TPaloAltoNetworksConnectionOption| TKeeperConnectionOption| TKempLoadMasterConnectionOption+ | TImpervaConnectionOption| TAnthropicConnectionOption| TOvhConnectionOption| TDevinConnectionOption@@ -546,6 +551,7 @@ export type TAppConnectionOptionMap = {[AppConnection.PaloAltoNetworks]: TPaloAltoNetworksConnectionOption;[AppConnection.Keeper]: TKeeperConnectionOption;[AppConnection.KempLoadMaster]: TKempLoadMasterConnectionOption;+ [AppConnection.Imperva]: TImpervaConnectionOption;[AppConnection.Anthropic]: TAnthropicConnectionOption;[AppConnection.OVH]: TOvhConnectionOption;[AppConnection.Devin]: TDevinConnectionOption;diff --git a/frontend/src/hooks/api/appConnections/types/imperva-connection.ts b/frontend/src/hooks/api/appConnections/types/imperva-connection.tsnew file mode 100644index 0000000000..8bbecf9954--- /dev/null+++ b/frontend/src/hooks/api/appConnections/types/imperva-connection.ts@@ -0,0 +1,17 @@+import { AppConnection } from "@app/hooks/api/appConnections/enums";+import { TRootAppConnection } from "@app/hooks/api/appConnections/types/root-connection";++export enum ImpervaConnectionMethod {+ ApiKey = "api-key"+}++export type TImpervaConnection = TRootAppConnection & {+ app: AppConnection.Imperva;+} & {+ method: ImpervaConnectionMethod.ApiKey;+ credentials: {+ apiId: string;+ apiKey: string;+ accountId?: string;+ };+};diff --git a/frontend/src/hooks/api/appConnections/types/index.ts b/frontend/src/hooks/api/appConnections/types/index.tsindex 1fa98b1254..e67f8b6c41 100644--- a/frontend/src/hooks/api/appConnections/types/index.ts+++ b/frontend/src/hooks/api/appConnections/types/index.ts@@ -43,6 +43,7 @@ import { THCVaultConnection } from "./hc-vault-connection";import { THerokuConnection } from "./heroku-connection";import { THpeIloConnection } from "./hpe-ilo-connection";import { THumanitecConnection } from "./humanitec-connection";+import { TImpervaConnection } from "./imperva-connection";import { TKeeperConnection } from "./keeper-connection";import { TKempLoadMasterConnection } from "./kemp-loadmaster-connection";import { TLaravelForgeConnection } from "./laravel-forge-connection";@@ -133,6 +134,7 @@ export * from "./hc-vault-connection";export * from "./heroku-connection";export * from "./hpe-ilo-connection";export * from "./humanitec-connection";+export * from "./imperva-connection";export * from "./keeper-connection";export * from "./kemp-loadmaster-connection";export * from "./laravel-forge-connection";@@ -249,6 +251,7 @@ export type TAppConnection =| TNetScalerConnection| TPaloAltoNetworksConnection| TKempLoadMasterConnection+ | TImpervaConnection| TDopplerConnection| TOvhConnection| TDevinConnectiondiff --git a/frontend/src/hooks/api/pkiSyncs/enums.ts b/frontend/src/hooks/api/pkiSyncs/enums.tsindex af6ccb6c30..9ddcc10066 100644--- a/frontend/src/hooks/api/pkiSyncs/enums.ts+++ b/frontend/src/hooks/api/pkiSyncs/enums.ts@@ -11,6 +11,7 @@ export enum PkiSync {PaloAltoNetworksSslTlsProfile = "palo-alto-networks-ssl-tls-profile",F5BigIp = "f5-big-ip",KempLoadMaster = "kemp-loadmaster",+ Imperva = "imperva",LinuxServer = "linux-server",WindowsServer = "windows-server",NutanixPrismCentral = "nutanix-prism-central"diff --git a/frontend/src/hooks/api/pkiSyncs/queries.tsx b/frontend/src/hooks/api/pkiSyncs/queries.tsxindex 5ea1655443..f344645d30 100644--- a/frontend/src/hooks/api/pkiSyncs/queries.tsx+++ b/frontend/src/hooks/api/pkiSyncs/queries.tsx@@ -6,6 +6,7 @@ import { PkiSync, TPkiSyncOption } from "@app/hooks/api/pkiSyncs";import {TAwsListener,TAwsLoadBalancer,+ TImpervaSite,TKempVirtualService,TListPkiSyncOptions,TListPkiSyncs,@@ -39,6 +40,8 @@ export const pkiSyncKeys = {[...pkiSyncKeys.all, "aws-listeners", connectionId, region, loadBalancerArn] as const,kempVirtualServices: (connectionId: string) =>[...pkiSyncKeys.all, "kemp-virtual-services", connectionId] as const,+ impervaSites: (connectionId: string) =>+ [...pkiSyncKeys.all, "imperva-sites", connectionId] as const,certificateOrders: (scopeId: string, certificateOrderIds: string[]) =>[...pkiSyncKeys.all, "certificate-orders", scopeId, certificateOrderIds] as const,matchingCertificateIds: (@@ -378,3 +381,31 @@ export const useListKempVirtualServices = (...options});};++export const useListImpervaSites = (+ { connectionId }: { connectionId: string },+ options?: Omit<+ UseQueryOptions<+ TImpervaSite[],+ unknown,+ TImpervaSite[],+ ReturnType<typeof pkiSyncKeys.impervaSites>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: pkiSyncKeys.impervaSites(connectionId),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ sites: TImpervaSite[] }>(+ "/api/v1/cert-manager/syncs/imperva/sites",+ {+ params: { connectionId }+ }+ );+ return data.sites;+ },+ enabled: !!connectionId,+ ...options+ });+};diff --git a/frontend/src/hooks/api/pkiSyncs/types/imperva-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/imperva-sync.tsnew file mode 100644index 0000000000..29226a8669--- /dev/null+++ b/frontend/src/hooks/api/pkiSyncs/types/imperva-sync.ts@@ -0,0 +1,23 @@+import { AppConnection } from "@app/hooks/api/appConnections/enums";++import { PkiSync } from "../enums";+import { TRootPkiSync } from "./common";++export type TImpervaSite = {+ id: string;+ name: string;+ status?: string;+};++export type TImpervaPkiSync = TRootPkiSync & {+ destination: PkiSync.Imperva;+ destinationConfig: {+ siteId: string;+ siteName?: string;+ };+ connection: {+ app: AppConnection.Imperva;+ name: string;+ id: string;+ };+};diff --git a/frontend/src/hooks/api/pkiSyncs/types/index.ts b/frontend/src/hooks/api/pkiSyncs/types/index.tsindex b1e7aaff27..a76adde8f8 100644--- a/frontend/src/hooks/api/pkiSyncs/types/index.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/index.ts@@ -13,6 +13,7 @@ import {TGcpCertificateManagerPkiSync,TGcpLabel} from "./gcp-certificate-manager-sync";+import { TImpervaPkiSync } from "./imperva-sync";import { TKempLoadMasterPkiSync } from "./kemp-loadmaster-sync";import { TLinuxServerPkiSync } from "./linux-server-sync";import { TNetScalerPkiSync } from "./netscaler-sync";@@ -53,6 +54,7 @@ export type TPkiSync =| TPaloAltoNetworksSslTlsProfilePkiSync| TF5BigIpPkiSync| TKempLoadMasterPkiSync+ | TImpervaPkiSync| TLinuxServerPkiSync| TWindowsServerPkiSync| TNutanixPrismCentralPkiSync;@@ -123,6 +125,8 @@ export type TCreatePkiSyncDTO = TCreatePkiSyncDTOBase & {parentProfile?: string;clusterId?: string;clusterName?: string;+ siteId?: string;+ siteName?: string;destinationPath?: string;gcpProjectId?: string;location?: string;@@ -176,6 +180,7 @@ export * from "./cloudflare-custom-certificate-sync";export * from "./common";export * from "./f5-big-ip-sync";export * from "./gcp-certificate-manager-sync";+export * from "./imperva-sync";export * from "./kemp-loadmaster-sync";export * from "./linux-server-sync";export * from "./netscaler-sync";diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsxindex 29cd46cbb4..b8fbbd9457 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx@@ -12,6 +12,7 @@ import {ChefPkiSyncDestinationSection,F5BigIpPkiSyncDestinationSection,GcpCertificateManagerPkiSyncDestinationSection,+ ImpervaPkiSyncDestinationSection,KempLoadMasterPkiSyncDestinationSection,LinuxServerPkiSyncDestinationSection,NetScalerPkiSyncDestinationSection,@@ -62,6 +63,9 @@ export const PkiSyncDestinationSection = ({ pkiSync }: Props) => {case PkiSync.KempLoadMaster:DestinationComponents = <KempLoadMasterPkiSyncDestinationSection pkiSync={pkiSync} />;break;+ case PkiSync.Imperva:+ DestinationComponents = <ImpervaPkiSyncDestinationSection pkiSync={pkiSync} />;+ break;case PkiSync.LinuxServer:DestinationComponents = <LinuxServerPkiSyncDestinationSection pkiSync={pkiSync} />;break;diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/ImpervaPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/ImpervaPkiSyncDestinationSection.tsxnew file mode 100644index 0000000000..de085fa045--- /dev/null+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/ImpervaPkiSyncDestinationSection.tsx@@ -0,0 +1,17 @@+import { Detail, DetailLabel, DetailValue } from "@app/components/v3";+import { TImpervaPkiSync } from "@app/hooks/api/pkiSyncs/types/imperva-sync";++type Props = {+ pkiSync: TImpervaPkiSync;+};++export const ImpervaPkiSyncDestinationSection = ({ pkiSync }: Props) => {+ const { siteId, siteName } = pkiSync.destinationConfig;++ return (+ <Detail>+ <DetailLabel>Website</DetailLabel>+ <DetailValue>{siteName ? `${siteName} (${siteId})` : siteId}</DetailValue>+ </Detail>+ );+};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.tsindex 992a44ead8..be5fc85f73 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts@@ -5,6 +5,7 @@ export { AzureKeyVaultPkiSyncDestinationSection } from "./AzureKeyVaultPkiSyncDeexport { ChefPkiSyncDestinationSection } from "./ChefPkiSyncDestinationSection";export { F5BigIpPkiSyncDestinationSection } from "./F5BigIpPkiSyncDestinationSection";export { GcpCertificateManagerPkiSyncDestinationSection } from "./GcpCertificateManagerPkiSyncDestinationSection";+export { ImpervaPkiSyncDestinationSection } from "./ImpervaPkiSyncDestinationSection";export { KempLoadMasterPkiSyncDestinationSection } from "./KempLoadMasterPkiSyncDestinationSection";export { LinuxServerPkiSyncDestinationSection } from "./LinuxServerPkiSyncDestinationSection";export { NetScalerPkiSyncDestinationSection } from "./NetScalerPkiSyncDestinationSection";diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsxindex 903951c669..95505e4396 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx@@ -58,6 +58,7 @@ import { HCVaultConnectionForm } from "./HCVaultConnectionForm";import { HerokuConnectionForm } from "./HerokuAppConnectionForm";import { HpeIloConnectionForm } from "./HpeIloConnectionForm";import { HumanitecConnectionForm } from "./HumanitecConnectionForm";+import { ImpervaConnectionForm } from "./ImpervaConnectionForm";import { KeeperConnectionForm } from "./KeeperConnectionForm";import { KempLoadMasterConnectionForm } from "./KempLoadMasterConnectionForm";import { LaravelForgeConnectionForm } from "./LaravelForgeConnectionForm";@@ -367,6 +368,8 @@ const CreateForm = ({ app, onComplete, projectId, projectType }: CreateFormPropsreturn <KeeperConnectionForm onSubmit={onSubmit} />;case AppConnection.KempLoadMaster:return <KempLoadMasterConnectionForm onSubmit={onSubmit} />;+ case AppConnection.Imperva:+ return <ImpervaConnectionForm onSubmit={onSubmit} />;case AppConnection.OVH:return <OVHConnectionForm onSubmit={onSubmit} />;case AppConnection.Ona:@@ -675,6 +678,8 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {return <KeeperConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;case AppConnection.KempLoadMaster:return <KempLoadMasterConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;+ case AppConnection.Imperva:+ return <ImpervaConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;case AppConnection.OVH:return <OVHConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;case AppConnection.Ona:diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ImpervaConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ImpervaConnectionForm.tsxnew file mode 100644index 0000000000..d08815957a--- /dev/null+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ImpervaConnectionForm.tsx@@ -0,0 +1,223 @@+import { Controller, FormProvider, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { Info } from "lucide-react";+import { z } from "zod";++import { OrgPermissionCan } from "@app/components/permissions";+import {+ Field,+ FieldDescription,+ FieldError,+ FieldLabel,+ Input,+ SecretInput,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";+import { OrgPermissionSubjects } from "@app/context";+import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";+import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";+import { ImpervaConnectionMethod, TImpervaConnection } from "@app/hooks/api/appConnections";+import { AppConnection } from "@app/hooks/api/appConnections/enums";++import { AppConnectionFormFooter } from "./AppConnectionFormFooter";+import {+ genericAppConnectionFieldsSchema,+ GenericAppConnectionsFields+} from "./GenericAppConnectionFields";++type Props = {+ appConnection?: TImpervaConnection;+ onSubmit: (formData: FormData) => Promise<void>;+};++const rootSchema = genericAppConnectionFieldsSchema.extend({+ app: z.literal(AppConnection.Imperva)+});++const formSchema = z.discriminatedUnion("method", [+ rootSchema.extend({+ method: z.literal(ImpervaConnectionMethod.ApiKey),+ credentials: z.object({+ apiId: z+ .string()+ .trim()+ .min(1, "API ID is required")+ .max(256, "API ID cannot exceed 256 characters"),+ apiKey: z+ .string()+ .trim()+ .min(1, "API key is required")+ .max(512, "API key cannot exceed 512 characters"),+ accountId: z+ .string()+ .trim()+ .max(32, "Account ID cannot exceed 32 characters")+ .regex(/^[0-9]*$/, "Account ID must be numeric")+ .optional()+ .transform((value) => value || undefined)+ })+ })+]);++type FormData = z.infer<typeof formSchema>;++export const ImpervaConnectionForm = ({ appConnection, onSubmit }: Props) => {+ const isUpdate = Boolean(appConnection);++ const form = useForm<FormData>({+ resolver: zodResolver(formSchema),+ defaultValues: appConnection ?? {+ app: AppConnection.Imperva,+ method: ImpervaConnectionMethod.ApiKey,+ gatewayId: null,+ gatewayPoolId: null+ }+ });++ const { handleSubmit, control, setValue, watch } = form;++ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");++ return (+ <FormProvider {...form}>+ <form onSubmit={handleSubmit(onSubmit)}>+ {!isUpdate && <GenericAppConnectionsFields />}+ <OrgPermissionCan+ I={OrgGatewayPermissionActions.AttachGateways}+ a={OrgPermissionSubjects.Gateway}+ >+ {(isAllowed) => (+ <Field className="mb-4">+ <FieldLabel>Gateway</FieldLabel>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ <FieldDescription>+ Optional. Route Imperva API calls through a gateway when outbound traffic must leave+ from a fixed network.+ </FieldDescription>+ </Field>+ )}+ </OrgPermissionCan>+ <Controller+ name="method"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>+ Method+ <Tooltip>+ <TooltipTrigger asChild>+ <Info />+ </TooltipTrigger>+ <TooltipContent className="max-w-sm">+ {`The method you would like to use to connect with ${+ APP_CONNECTION_MAP[AppConnection.Imperva].name+ }. This field cannot be changed after creation.`}+ </TooltipContent>+ </Tooltip>+ </FieldLabel>+ <Select disabled={isUpdate} value={value} onValueChange={(val) => onChange(val)}>+ <SelectTrigger className="w-full" isError={Boolean(error)}>+ <SelectValue placeholder="Select a method..." />+ </SelectTrigger>+ <SelectContent position="popper">+ {Object.values(ImpervaConnectionMethod).map((method) => {+ return (+ <SelectItem value={method} key={method}>+ {getAppConnectionMethodDetails(method).name}+ </SelectItem>+ );+ })}+ </SelectContent>+ </Select>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ <Controller+ name="credentials.apiId"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="credentials-api-id">API ID</FieldLabel>+ <Input+ id="credentials-api-id"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder="e.g. 12345"+ isError={Boolean(error?.message)}+ />+ <FieldDescription>+ Found in the Imperva Cloud Security Console under Account Management > User+ Management > My Profile.+ </FieldDescription>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ <Controller+ name="credentials.apiKey"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="credentials-api-key">API Key</FieldLabel>+ <SecretInput+ id="credentials-api-key"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ containerClassName="rounded-md border border-input bg-input px-2 py-1.5"+ isError={Boolean(error?.message)}+ />+ <FieldDescription>+ Enable the key after creating it, and give its role the Manage SSL Certificates+ permission. Imperva creates keys disabled.+ </FieldDescription>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ <Controller+ name="credentials.accountId"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="credentials-account-id">+ Account ID <span className="text-muted">(optional)</span>+ </FieldLabel>+ <Input+ id="credentials-account-id"+ value={value ?? ""}+ onChange={(e) => onChange(e.target.value)}+ placeholder="e.g. 678901"+ isError={Boolean(error?.message)}+ />+ <FieldDescription>+ Set this to manage websites that belong to a sub-account. Defaults to the account+ the API key belongs to.+ </FieldDescription>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ <AppConnectionFormFooter+ submitLabel={isUpdate ? "Update Credentials" : "Connect to Imperva"}+ />+ </form>+ </FormProvider>+ );+};