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
fix(pki): imperva slot ownership and error handling
bernie-ga72733d73257
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex a755bd412f..925928fe5d 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -2934,6 +2934,12 @@ export const AppConnections = {}},CREDENTIALS: {+ IMPERVA: {+ apiId: "The API ID of an Imperva API key, shown beside the key in the Cloud Security Console.",+ apiKey: "The Imperva API key. It has to be enabled, and its role needs the Manage SSL Certificates permission.",+ accountId:+ "The numeric Imperva account ID to act on. Set it to manage websites in a sub-account. Defaults to the account the API key belongs to."+ },PALO_ALTO_NETWORKS: {hostname: "The IP address or hostname of the management interface of the firewall or Panorama.",port: "The HTTPS port of the management interface. Defaults to 443.",diff --git a/backend/src/services/app-connection/imperva/imperva-connection-fns.ts b/backend/src/services/app-connection/imperva/imperva-connection-fns.tsindex cbaf0ce875..175d3e8169 100644--- a/backend/src/services/app-connection/imperva/imperva-connection-fns.ts+++ b/backend/src/services/app-connection/imperva/imperva-connection-fns.ts@@ -1,14 +1,15 @@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 { BadRequestError, NotFoundError } from "@app/lib/errors";+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-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 { getSharedHttpsAgent } from "@app/lib/validator/safe-request";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { ImpervaConnectionMethod } from "./imperva-connection-enums";@@ -39,6 +40,18 @@ export type TImpervaRequestArgs = Omit<AxiosRequestConfig, "url" | "baseURL" | "export type TImpervaRequestFn = <R>(args: TImpervaRequestArgs) => Promise<R>;+// The gateway proxy rewrites whatever a request throws, so Imperva's own status and message are+// carried out on this instead of on the AxiosError.+export class ImpervaRequestError extends Error {+ public readonly status?: number;++ constructor({ message, status }: { message: string; status?: number }) {+ super(message);+ this.name = "ImpervaRequestError";+ this.status = status;+ }+}+export type TImpervaApiError = {status?: number;title?: string;@@ -93,70 +106,103 @@ export const extractImpervaErrorMessage = (error: unknown, fallback: string): streturn fallback;};-const executeImpervaRequestWithGateway = async <R>(- args: TImpervaRequestArgs,+const toImpervaRequestError = (error: unknown): Error => {+ if (error instanceof AxiosError) {+ return new ImpervaRequestError({+ message: extractImpervaErrorMessage(error, "Imperva rejected the request"),+ status: error.response?.status+ });+ }+ return error instanceof Error ? error : new Error(String(error));+};++const buildDirectRequestFn =+ (credentials: TImpervaCredentials): TImpervaRequestFn =>+ async <R>({ host, path, ...requestCfg }: TImpervaRequestArgs) => {+ try {+ const resp = await safeRequest.request<R>({+ ...requestCfg,+ headers: { ...getImpervaAuthHeaders(credentials), ...requestCfg.headers },+ 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;+ } catch (error) {+ throw toImpervaRequestError(error);+ }+ };++// One tunnel per host per operation, not per request: each proxy costs a relay connection.+export const withImpervaOperation = async <T>(config: { gatewayId?: string | null; credentials: TImpervaCredentials },- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId"> | undefined-): Promise<R> => {- const { host, path, ...requestCfg } = args;- const { gatewayId } = config;+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId"> | undefined,+ operation: (makeRequest: TImpervaRequestFn) => Promise<T>+): Promise<T> => {+ const { gatewayId, credentials } = config;++ if (!gatewayId) return operation(buildDirectRequestFn(credentials));- if (gatewayId && gatewayV2Service) {- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ if (!gatewayV2Service) {+ throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });+ }++ const resolveTarget = async (targetHost: string) => {+ const details = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({gatewayId,- targetHost: host,+ targetHost,targetPort: IMPERVA_HTTPS_PORT});- if (!platformConnectionDetails) {- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });- }+ if (!details) throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });+ return details;+ };- 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 [provTarget, restTarget] = await Promise.all([+ resolveTarget(IMPERVA_PROV_HOST),+ resolveTarget(IMPERVA_REST_HOST)+ ]);- 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;-};+ // withGatewayV2Proxy replaces the thrown error with one of its own, so Imperva's status and+ // message are kept here and rethrown once the proxies have been torn down.+ let impervaError: Error | undefined;-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+ try {+ return await withGatewayV2Proxy(+ async (provPort) =>+ withGatewayV2Proxy(+ async (restPort) => {+ const makeRequest: TImpervaRequestFn = async <R>({ host, path, ...requestCfg }: TImpervaRequestArgs) => {+ try {+ const resp = await request.request<R>({+ ...requestCfg,+ headers: { ...getImpervaAuthHeaders(credentials), ...requestCfg.headers, Host: host },+ url: `https://localhost:${host === IMPERVA_PROV_HOST ? provPort : restPort}${path}`,+ httpsAgent: getSharedHttpsAgent({ servername: host, rejectUnauthorized: true }),+ timeout: IMPERVA_REQUEST_TIMEOUT_MS,+ maxContentLength: IMPERVA_MAX_RESPONSE_BYTES,+ maxBodyLength: IMPERVA_MAX_RESPONSE_BYTES+ });+ return resp.data;+ } catch (error) {+ impervaError = toImpervaRequestError(error);+ throw impervaError;+ }+ };++ return operation(makeRequest);+ },+ { protocol: GatewayProxyProtocol.Tcp, ...restTarget }+ ),+ { protocol: GatewayProxyProtocol.Tcp, ...provTarget });+ } catch (error) {+ if (impervaError) throw impervaError;+ throw error;+ }};export type TImpervaSite = {@@ -174,43 +220,53 @@ 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)- }- });+ try {+ return await withImpervaOperation(config, gatewayV2Service, async (makeRequest) => {+ const sites: TImpervaSite[] = [];++ let page = 0;+ let hasMore = true;++ /* eslint-disable no-await-in-loop */+ while (hasMore && 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 });+ const pageSites = response.data ?? [];+ for (const site of pageSites) {+ if (site.id !== undefined && site.id !== null) {+ sites.push({ id: String(site.id), name: site.name ?? String(site.id), status: site.siteStatus });+ }+ }++ page += 1;+ // Imperva's totalPages is the signal to follow, but a full page with no pagination metadata+ // means there is more to read rather than nothing.+ const totalPages = response.meta?.totalPages;+ hasMore = totalPages === undefined ? pageSites.length === IMPERVA_SITES_PAGE_SIZE : page < totalPages;}- }+ /* eslint-enable no-await-in-loop */- totalPages = response.meta?.totalPages ?? 1;- page += 1;- }- /* eslint-enable no-await-in-loop */+ if (hasMore) {+ logger.warn(`Imperva site listing stopped at ${IMPERVA_SITES_MAX_PAGES} pages, some websites are not listed`);+ }- 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;+ });+ } catch (error) {+ if (error instanceof ImpervaRequestError) {+ throw new BadRequestError({ message: `Unable to list Imperva websites: ${error.message}` });+ }+ throw error;}-- return sites;};export const validateImpervaConnectionCredentials = async (@@ -218,22 +274,23 @@ export const validateImpervaConnectionCredentials = async (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) {- throw new BadRequestError({- message: `Unable to validate connection: ${extractImpervaErrorMessage(- error,- "verify the API ID, API key, and account ID"- )}`- });+ await withImpervaOperation({ gatewayId: config.gatewayId, credentials }, gatewayV2Service, (makeRequest) =>+ 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) {+ // Only a refusal from Imperva becomes a validation error; a database or gateway failure keeps+ // its own class rather than being rendered as a 400 carrying a raw driver message.+ if (error instanceof ImpervaRequestError) {+ throw new BadRequestError({ message: `Unable to validate connection: ${error.message}` });+ }+ throw error;}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.tsindex df11ddb550..d1f92e6c25 100644--- a/backend/src/services/app-connection/imperva/imperva-connection-schemas.ts+++ b/backend/src/services/app-connection/imperva/imperva-connection-schemas.ts@@ -13,16 +13,33 @@ import { APP_CONNECTION_NAME_MAP } from "../app-connection-maps";import { ImpervaConnectionMethod } from "./imperva-connection-enums";const ACCOUNT_ID_PATTERN = new RE2("^[0-9]+$");+// Both credentials go straight into request headers, where a stray newline throws deep in Node+// rather than failing here with the field named.+const HEADER_SAFE_PATTERN = new RE2("^[\\x21-\\x7e]+$");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"),+ apiId: z+ .string()+ .trim()+ .min(1, "API ID is required")+ .max(256, "API ID cannot exceed 256 characters")+ .refine((val) => HEADER_SAFE_PATTERN.test(val), { message: "API ID cannot contain spaces or line breaks" })+ .describe(AppConnections.CREDENTIALS.IMPERVA.apiId),+ apiKey: z+ .string()+ .trim()+ .min(1, "API key is required")+ .max(512, "API key cannot exceed 512 characters")+ .refine((val) => HEADER_SAFE_PATTERN.test(val), { message: "API key cannot contain spaces or line breaks" })+ .describe(AppConnections.CREDENTIALS.IMPERVA.apiKey),accountId: z.string().trim()+ .min(1, "Account ID cannot be empty").max(32, "Account ID cannot exceed 32 characters").refine((val) => ACCOUNT_ID_PATTERN.test(val), { message: "Account ID must be numeric" }).optional()+ .describe(AppConnections.CREDENTIALS.IMPERVA.accountId)});const BaseImpervaConnectionSchema = BaseAppConnectionSchema.extend({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.tsindex de1dae8de4..8d1c086796 100644--- 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.ts@@ -45,8 +45,8 @@ describe("Imperva auth type resolution", () => {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);+ test("refuses a certificate whose key type Imperva cannot hold", () => {+ expect(resolveImpervaAuthType("not a certificate")).toBeUndefined();});});@@ -93,7 +93,14 @@ vi.mock("@app/lib/logger", () => ({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 };+ return {+ ...actual,+ withImpervaOperation: (+ _config: unknown,+ _gatewayV2Service: unknown,+ operation: (makeRequest: unknown) => unknown+ ) => operation(impervaRequest)+ };});describe("Imperva upload failures", () => {@@ -136,7 +143,9 @@ describe("Imperva slot removal", () => {addCertificates: vi.fn(),findByPkiSyncAndCertificate: vi.fn().mockResolvedValue(undefined),updateById: vi.fn(),- updateSyncStatus: vi.fn()+ updateSyncStatus: vi.fn(),+ findExternalIdentifiersInUse: vi.fn().mockResolvedValue(new Set<string>()),+ claimExternalIdentifier: vi.fn()} as never,certificateDAL: { findById: vi.fn().mockResolvedValue(undefined) } as never});@@ -205,7 +214,9 @@ describe("Imperva failed uploads", () => {addCertificates: vi.fn(),findByPkiSyncAndCertificate: vi.fn().mockResolvedValue(undefined),updateById: vi.fn(),- updateSyncStatus: vi.fn()+ updateSyncStatus: vi.fn(),+ findExternalIdentifiersInUse: vi.fn().mockResolvedValue(new Set<string>()),+ claimExternalIdentifier: vi.fn()} as never,certificateDAL: { findById: vi.fn().mockResolvedValue(undefined) } as never});@@ -225,3 +236,77 @@ describe("Imperva failed uploads", () => {expect(removeCertificatesFromDal).not.toHaveBeenCalled();});});++describe("Imperva slot ownership", () => {+ const buildSync = (siteId: string) =>+ ({+ id: "sync-1",+ destination: "imperva",+ destinationConfig: { siteId, siteName: "current.example.com" },+ syncOptions: { canRemoveCertificates: true },+ connection: { credentials: { apiId: "id", apiKey: "key" }, gatewayId: null, gatewayPoolId: null }+ }) as never;++ const buildDeps = (records: Array<{ certificateId: string; externalIdentifier: string }>, inUse: string[] = []) => {+ const removeCertificatesFromDal = vi.fn();+ const certificateSyncDAL = {+ findByPkiSyncId: vi.fn().mockResolvedValue(records),+ removeCertificates: removeCertificatesFromDal,+ addCertificates: vi.fn(),+ findByPkiSyncAndCertificate: vi.fn().mockResolvedValue({ id: "row-1" }),+ updateById: vi.fn(),+ updateSyncStatus: vi.fn(),+ findExternalIdentifiersInUse: vi.fn().mockResolvedValue(new Set(inUse)),+ claimExternalIdentifier: vi.fn()+ };+ return { certificateSyncDAL, removeCertificatesFromDal };+ };++ beforeEach(() => {+ impervaRequest.mockReset();+ impervaRequest.mockResolvedValue({});+ });++ test("clears the slot on the website a repointed sync left behind, and keeps the link row", async () => {+ const { impervaPkiSyncFactory } = await import("./imperva-pki-sync-fns");+ const { certificateSyncDAL, removeCertificatesFromDal } = buildDeps([+ { certificateId: "cert-1", externalIdentifier: "111:RSA" }+ ]);++ const factory = impervaPkiSyncFactory({+ certificateSyncDAL: certificateSyncDAL as never,+ certificateDAL: { findById: vi.fn().mockResolvedValue(undefined) } as never+ });++ await factory.syncCertificates(buildSync("222"), {+ leaf: { cert: RSA_CERT_PEM, privateKey: "key", certificateId: "cert-1" }+ } as never);++ const deletes = impervaRequest.mock.calls+ .map((call) => call[0] as TRecordedRequest)+ .filter((req) => req.method === "DELETE");++ expect(deletes).toHaveLength(1);+ expect(deletes[0].path).toBe("/api/prov/v2/sites/111/customCertificate");+ expect(removeCertificatesFromDal).not.toHaveBeenCalled();+ });++ test("leaves a slot another sync owns alone", async () => {+ const { impervaPkiSyncFactory } = await import("./imperva-pki-sync-fns");+ const { certificateSyncDAL, removeCertificatesFromDal } = buildDeps(+ [{ certificateId: "cert-old", externalIdentifier: "222:ECC" }],+ ["222:ECC"]+ );++ const factory = impervaPkiSyncFactory({+ certificateSyncDAL: certificateSyncDAL as never,+ certificateDAL: { findById: vi.fn().mockResolvedValue(undefined) } as never+ });++ const result = await factory.syncCertificates(buildSync("222"), {});++ expect(impervaRequest).not.toHaveBeenCalled();+ expect(result.removed).toBeUndefined();+ expect(removeCertificatesFromDal).toHaveBeenCalledWith("sync-1", ["cert-old"]);+ });+});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.tsindex 63c8490e94..760c492aa2 100644--- a/backend/src/services/pki-sync/imperva/imperva-pki-sync-fns.ts+++ b/backend/src/services/pki-sync/imperva/imperva-pki-sync-fns.ts@@ -7,14 +7,15 @@ import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2import { 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+ ImpervaRequestError,+ TImpervaRequestFn,+ withImpervaOperation} 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";@@ -39,6 +40,8 @@ type TImpervaPkiSyncFactoryDeps = {| "updateById"| "findByPkiSyncId"| "updateSyncStatus"+ | "findExternalIdentifiersInUse"+ | "claimExternalIdentifier">;certificateDAL: Pick<TCertificateDALFactory, "findById">;gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;@@ -75,12 +78,22 @@ const getImpervaCredentials = (pkiSync: TPkiSyncWithCredentials): TImpervaCreden// 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 => {+export const resolveImpervaAuthType = (certPem: string): ImpervaCertificateAuthType | undefined => {try {const keyType = crypto.nativeCrypto.createPublicKey(certPem).asymmetricKeyType;- return keyType === "ec" ? ImpervaCertificateAuthType.Ecc : ImpervaCertificateAuthType.Rsa;+ if (keyType === "ec") return ImpervaCertificateAuthType.Ecc;+ if (keyType === "rsa" || keyType === "rsa-pss") return ImpervaCertificateAuthType.Rsa;+ return undefined;} catch {- return ImpervaCertificateAuthType.Rsa;+ return undefined;+ }+};++export const describeImpervaKeyType = (certPem: string): string => {+ try {+ return crypto.nativeCrypto.createPublicKey(certPem).asymmetricKeyType ?? "an unrecognized key type";+ } catch {+ return "an unreadable public key";}};@@ -226,6 +239,15 @@ export const impervaPkiSyncFactory = ({continue;}+ if (selected) {+ skippedCertificates.push({+ name: certName,+ reason: "Imperva holds a single custom certificate per site"+ });+ // eslint-disable-next-line no-continue+ continue;+ }+let renewedFromCertificateId: string | null | undefined;if (typeof certificateId === "string") {const certificate = await certificateDAL.findById(certificateId);@@ -240,15 +262,6 @@ export const impervaPkiSyncFactory = ({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 };}@@ -277,146 +290,193 @@ export const impervaPkiSyncFactory = ({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()+ return withImpervaOperation(+ { gatewayId: effectiveGatewayId, credentials },+ gatewayV2Service,+ async (makeRequest) => {+ 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;++ const renewedFromCertificateIds: string[] = [];++ if (certificate) {+ const authType = resolveImpervaAuthType(certificate.cert);++ if (!authType) {+ throw new PkiSyncError({+ message: `Imperva accepts only RSA and ECDSA certificates, and '${+ certificate.certName+ }' uses ${describeImpervaKeyType(certificate.cert)}`});- } 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)+ const externalIdentifier = buildImpervaExternalIdentifier(siteId, authType);++ try {+ // Claimed before the upload so a second sync pointed at the same slot cannot take it over+ // while this one is writing to it.+ if (certificate.certificateId) {+ await certificateSyncDAL.claimExternalIdentifier(+ pkiSync.id,+ certificate.certificateId,+ externalIdentifier+ );+ }++ 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 }+ ]);+ }++ // Dropped after the cleanup below, which still needs the record to find the old slot.+ if (certificate.renewedFromCertificateId) {+ renewedFromCertificateIds.push(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}`+ );}}- 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. A failed upload leaves the- // previous certificate serving, and clearing its slot here would take the site off TLS.- if (canRemoveCertificates && failedUploads.length === 0) {- 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;+ // A failed upload leaves the previous certificate serving, and clearing its slot would+ // take the website off TLS.+ if (canRemoveCertificates && failedUploads.length === 0) {+ // Keyed on the slot rather than the certificate, so repointing the sync to another website+ // still clears the slot the certificate used to occupy on the old one.+ const orphanedRecords = existingSyncRecords.filter(+ (record: TCertificateSyncs) => record.externalIdentifier && !occupiedSlots.has(record.externalIdentifier)+ );- try {- await deleteCustomCertificate(makeRequest, credentials, recordSiteId, authType);- removed += 1;+ const ownedByOtherSync = await certificateSyncDAL.findExternalIdentifiersInUse(+ orphanedRecords.map((record: TCertificateSyncs) => record.externalIdentifier as string),+ { excludePkiSyncId: pkiSync.id, destination: pkiSync.destination }+ );- if (record.certificateId) {- await certificateSyncDAL.removeCertificates(pkiSync.id, [record.certificateId]);+ for (const record of orphanedRecords) {+ if (ownedByOtherSync.has(record.externalIdentifier as string)) {+ if (record.certificateId && !activeCertificateIds.has(record.certificateId)) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, [record.certificateId]);+ }+ // eslint-disable-next-line no-continue+ continue;+ }++ // 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;++ // The row survives when the same certificate was just written to a different slot, since+ // it now points at that new slot.+ if (record.certificateId && !activeCertificateIds.has(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}`+ );+ }}+ }- 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}`- );+ // Only once the cleanup above has had its look at the old slot.+ if (renewedFromCertificateIds.length > 0 && failedRemovals.length === 0) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, renewedFromCertificateIds);}- }- }- if (failedUploads.length > 0) {- throw new PkiSyncError({- message: `Failed to sync certificate to Imperva site ${siteLabel}: ${failedUploads[0].error}`- });- }+ 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+ 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 (@@ -474,37 +534,63 @@ export const impervaPkiSyncFactory = ({return;}- const effectiveGatewayId = await resolveGateway(pkiSync);- const makeRequest = buildImpervaRequestFn({ gatewayId: effectiveGatewayId, credentials }, gatewayV2Service);+ const ownedByOtherSync = await certificateSyncDAL.findExternalIdentifiersInUse([...slotsToRemove.keys()], {+ excludePkiSyncId: pkiSync.id,+ destination: pkiSync.destination+ });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);+ if (ownedByOtherSync.has(externalIdentifier)) {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- });+ slotsToRemove.delete(externalIdentifier);}}- if (certificateIdsToClean.length > 0) {- await certificateSyncDAL.removeCertificates(pkiSync.id, certificateIdsToClean);+ const effectiveGatewayId = await resolveGateway(pkiSync);++ try {+ await withImpervaOperation(+ { gatewayId: effectiveGatewayId, credentials },+ gatewayV2Service,+ async (makeRequest) => {+ for (const [externalIdentifier, certificateIds] of slotsToRemove) {+ const { siteId: recordSiteId, authType } = parseImpervaExternalIdentifier(externalIdentifier);+ const recordSiteLabel = recordSiteId === siteId ? siteLabel : recordSiteId;++ try {+ // eslint-disable-next-line no-await-in-loop+ 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) {+ // A slot Imperva no longer has is already in the state the caller asked for. Decided on+ // the status, since the message is Imperva's own prose.+ if (error instanceof ImpervaRequestError && error.status === 404) {+ certificateIdsToClean.push(...certificateIds);+ // eslint-disable-next-line no-continue+ continue;+ }++ throw new PkiSyncError({+ message: `Failed to remove ${authType} custom certificate from Imperva site ${recordSiteLabel}: ${extractImpervaErrorMessage(+ error,+ "Unknown error"+ )}`,+ shouldRetry: true+ });+ }+ }+ }+ );+ } finally {+ // Whatever was cleared before the failure still has to lose its link row, or the sync keeps+ // reporting certificates it has already removed.+ if (certificateIdsToClean.length > 0) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, certificateIdsToClean);+ }}};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.tsindex a642b8b316..91f9f63836 100644--- a/backend/src/services/pki-sync/imperva/imperva-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/imperva/imperva-pki-sync-schemas.ts@@ -22,8 +22,14 @@ export const ImpervaPkiSyncConfigSchema = z.object({.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()+ })+ .describe("The numeric ID of the Imperva website that receives the certificate."),+ siteName: z+ .string()+ .trim()+ .max(512, "Site name cannot exceed 512 characters")+ .optional()+ .describe("The website's name, kept for display. Imperva's website ID is what the sync acts on.")});export const ImpervaPkiSyncOptionsSchema = BasePkiSyncOptionsSchema.pick({@@ -43,8 +49,8 @@ export const CreateImpervaPkiSyncSchema = z.object({isAutoSyncEnabled: z.boolean().default(true),destinationConfig: ImpervaPkiSyncConfigSchema,syncOptions: ImpervaPkiSyncOptionsSchema,- subscriberId: z.string().nullish(),- connectionId: z.string(),+ subscriberId: z.string().uuid().nullish(),+ connectionId: z.string().uuid(),projectId: z.string().trim().min(1).optional().describe(openApiHidden()),applicationId: z.string().uuid().optional(),certificateIds: z.array(z.string().uuid()).optional(),@@ -57,8 +63,8 @@ export const UpdateImpervaPkiSyncSchema = z.object({isAutoSyncEnabled: z.boolean().optional(),destinationConfig: ImpervaPkiSyncConfigSchema.optional(),syncOptions: ImpervaPkiSyncOptionsSchema.optional(),- subscriberId: z.string().nullish(),- connectionId: z.string().optional(),+ subscriberId: z.string().uuid().nullish(),+ connectionId: z.string().uuid().optional(),filters: UpdatePkiSyncFiltersField});diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex ceadfa2794..d26301b20e 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -19,7 +19,6 @@ import { TKeyStoreFactory } from "@app/keystore/keystore";import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-utils";import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { deepEqual } from "@app/lib/fn/object";-import { logger } from "@app/lib/logger";import { OrgServiceActor } from "@app/lib/types";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";@@ -991,12 +990,10 @@ export const pkiSyncServiceFactory = ({// 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 certificateDAL.countCertificatesMatchingSyncFilters(effectiveFilters, {+ projectId: pkiSync.projectId,+ applicationId: pkiSync.applicationId+ }): (await certificateSyncDAL.findByPkiSyncId(id)).length;assertPkiSyncCertificateCapsAllowCount(@@ -1293,35 +1290,6 @@ export const pkiSyncServiceFactory = ({actor);- // Removing a sync's certificates unlinks them, and without this only the next issuance relinks.- // Links only: dropping a certificate is the filter editor's job, and a sync must not delete.- if (pkiSync.applicationId && hasAnyPkiSyncFilter(pkiSync.filters as TPkiSyncFilters | null)) {- await $withFilterLock(id, async () => {- const target = pkiSync as TPkiSyncReconcileTarget;- const diff = await computePkiSyncCertificateDiff(target, pkiSync.filters as TPkiSyncFilters | null, {- certificateDAL,- certificateSyncDAL- });- if (diff.toLink.length === 0) return;-- try {- assertPkiSyncCanHoldMatchedCertificates(target, diff.matched.length);- } catch (capError) {- logger.warn(- capError,- `A filtered PKI sync matches more certificates than it can hold, so none were linked [pkiSyncId=${id}]`- );- return;- }-- await applyPkiSyncCertificateDiff(- target,- { ...diff, toUnlink: [] },- { certificateDAL, certificateSyncDAL, pkiSyncQueue, auditLogService, pkiApplicationDAL }- );- });- }-await pkiSyncDAL.updateById(id, { syncStatus: PkiSyncStatus.Pending, lastSyncMessage: null });await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: id });diff --git a/docs/docs.json b/docs/docs.jsonindex dc4bac220d..9ef12ec293 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -2132,12 +2132,13 @@"api-reference/endpoints/app-connections/keeper/delete"]},+ {+ "group": "Imperva",+ "pages": ["api-reference/endpoints/app-connections/imperva/create"]+ },{"group": "Kemp LoadMaster",- "pages": [- "api-reference/endpoints/app-connections/imperva/create",- "api-reference/endpoints/app-connections/kemp-loadmaster/create"- ]+ "pages": ["api-reference/endpoints/app-connections/kemp-loadmaster/create"]},{"group": "Laravel Forge",@@ -4195,10 +4196,15 @@]},{- "group": "Kemp LoadMaster",+ "group": "Imperva","pages": ["api-reference/endpoints/pki/syncs/imperva/create",- "api-reference/endpoints/pki/syncs/imperva/sync-certificates",+ "api-reference/endpoints/pki/syncs/imperva/sync-certificates"+ ]+ },+ {+ "group": "Kemp LoadMaster",+ "pages": ["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.mdxindex 9ab761df3d..b1d8d904c1 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/imperva.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/imperva.mdx@@ -1,5 +1,5 @@----title: "Imperva"+title: "Sync certificates to Imperva"sidebarTitle: "Imperva"description: "Deploy certificates to websites protected by Imperva Cloud WAF."---@@ -7,11 +7,15 @@ 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.+ Certificate Syncs are configured per Application. Configure the Imperva destination first, then select which certificates to sync.</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.+<Warning>+ An Imperva sync accepts a certificate order filter naming one order. A certificate profile filter, a metadata filter, or an order filter naming more than one order is rejected when you save the sync.+</Warning>+## Prerequisites- An [Imperva Connection](/integrations/app-connections/imperva) whose API key has the **Manage SSL Certificates** permission@@ -23,7 +27,7 @@ Imperva stores one custom certificate per website for each key type, so a sync t<Tabs><Tab title="Infisical UI">- 1. In your Application, go to the **Certificate Syncs** tab and select **Create Sync**.+ 1. In your Application, go to the **Certificate Syncs** tab and select **Add Sync**.2. Select the **Imperva** option.@@ -32,9 +36,9 @@ Imperva stores one custom certificate per website for each key type, so a sync t- **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.+ - **Remove certificates from destination**: Remove the custom certificate from the website once this sync stops holding it. 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 on change**: Automatically sync certificates when changes occur.5. Configure the **Details**:- **Name**: The name of your sync (slug-friendly).@@ -42,7 +46,7 @@ Imperva stores one custom certificate per website for each key type, so a sync t6. Select the certificate to sync.- 7. Review and click **Create Sync**.+ 7. Review and select **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.@@ -50,8 +54,9 @@ Imperva stores one custom certificate per website for each key type, so a sync t### 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.+ Pass `filters` to describe the certificate this sync holds. The matching certificate in the Application is+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).</Note>```bash Request@@ -66,9 +71,9 @@ Imperva stores one custom certificate per website for each key type, so a sync t"connectionId": "550e8400-e29b-41d4-a716-446655440000","destination": "imperva","isAutoSyncEnabled": true,- "certificateIds": [- "550e8400-e29b-41d4-a716-446655440000"- ],+ "filters": {+ "certificateOrderIds": ["550e8400-e29b-41d4-a716-446655440000"]+ },"syncOptions": {"canRemoveCertificates": true,"includeRootCa": false@@ -84,25 +89,23 @@ Imperva stores one custom certificate per website for each key type, so a sync t```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"- }+ "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>@@ -133,8 +136,9 @@ To manually sync certificates, use the [Sync Certificates](/api-reference/endpoi## FAQ+<AccordionGroup><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.+ No. Imperva holds one custom certificate per website for each key type, so a sync deploys a single certificate. A filter naming more than one certificate order is rejected when you save the sync. 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?">@@ -148,6 +152,7 @@ To manually sync certificates, use the [Sync Certificates](/api-reference/endpoi<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>+</AccordionGroup>## What's next?@@ -155,13 +160,13 @@ To manually sync certificates, use the [Sync Certificates](/api-reference/endpoi<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">+ <Card title="Auto-Renewal" icon="rotate-cw" 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">+ <Card title="Other Sync Destinations" icon="refresh-cw" 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 5c309e5848..06bbe9b892 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx@@ -43,7 +43,7 @@ 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">+ <Card title="Imperva" icon="shield-half" 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">diff --git a/docs/integrations/app-connections/imperva.mdx b/docs/integrations/app-connections/imperva.mdxindex 126e8777ae..c00a30056c 100644--- a/docs/integrations/app-connections/imperva.mdx+++ b/docs/integrations/app-connections/imperva.mdx@@ -23,10 +23,10 @@ Infisical connects to Imperva Cloud WAF with an account API key, which it uses t</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**.+ 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 the Cloud Security Console under **Account Management > User Management > My Profile**.</Step><Step title="Navigate to App Connections">- In Certificate Manager, navigate to **Settings > App Connections** and click **Add Connection**.+ In Certificate Manager, go to **Settings > App Connections** and select **Add Connection**.</Step><Step title="Select Imperva">Select the **Imperva** option from the list of available connections.@@ -38,7 +38,7 @@ Infisical connects to Imperva Cloud WAF with an account API key, which it uses tOptionally 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.+ Select **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.diff --git a/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsx b/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsxindex 1c49a907c1..416534a6f4 100644--- a/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsx+++ b/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsx@@ -23,10 +23,11 @@ export const ImpervaPkiSyncFields = () => {const { control, setValue } = useFormContext<TImpervaForm>();const connectionId = useWatch({ name: "connection.id", control });+ const siteName = useWatch({ name: "destinationConfig.siteName", control });const {data: sites,- isFetching: isLoadingSites,+ isLoading: isLoadingSites,isError: isSitesError,error: sitesError} = useListImpervaSites(@@ -61,7 +62,7 @@ export const ImpervaPkiSyncFields = () => {return (<Field className="mb-4">- <FieldLabel>+ <FieldLabel htmlFor="pki-sync-imperva-site">Website<Tooltip><TooltipTrigger asChild>@@ -69,7 +70,7 @@ export const ImpervaPkiSyncFields = () => {</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.+ custom certificate per website, so this sync carries a single certificate.</TooltipContent></Tooltip></FieldLabel>@@ -78,7 +79,10 @@ export const ImpervaPkiSyncFields = () => {isDisabled={!connectionId}isLoading={Boolean(connectionId) && isLoadingSites}options={siteOptions}- value={siteOptions.find((site) => site.id === value) ?? null}+ value={+ siteOptions.find((site) => site.id === value) ??+ (value ? { id: value, name: siteName || value } : null)+ }onValueChange={(option) => {onChange(option?.id ?? "");setValue("destinationConfig.siteName", option?.name ?? "");diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsxindex f8b03b2e93..d5f53da389 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx@@ -1,7 +1,10 @@import { Controller, useFormContext } from "react-hook-form";import { Field, FieldDescription, FieldError, FieldLabel, Input } from "@app/components/v3";-import { INCLUDE_ROOT_CA_UNSUPPORTED_DESTINATIONS } from "@app/helpers/pkiSyncs";+import {+ CERTIFICATE_NAME_SCHEMA_UNSUPPORTED_DESTINATIONS,+ INCLUDE_ROOT_CA_UNSUPPORTED_DESTINATIONS+} from "@app/helpers/pkiSyncs";import { PkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";import { TPkiSyncForm } from "../schemas/pki-sync-schema";@@ -93,92 +96,90 @@ export const PkiSyncOptionsFields = ({ destination, isUpdate }: Props) => {{renderDestinationOptions(currentDestination, isUpdate)}- {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>+ {!CERTIFICATE_NAME_SCHEMA_UNSUPPORTED_DESTINATIONS.includes(currentDestination) && (+ <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/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.tsindex d011744758..167baf3e43 100644--- a/frontend/src/helpers/pkiSyncs.ts+++ b/frontend/src/helpers/pkiSyncs.ts@@ -201,6 +201,12 @@ export const PRESERVE_ITEM_ON_RENEWAL_DESTINATIONS: PkiSync[] = [PkiSync.PaloAltoNetworksSslTlsProfile];+// Destinations that name a certificate themselves, so a name schema has nothing to drive.+export const CERTIFICATE_NAME_SCHEMA_UNSUPPORTED_DESTINATIONS: PkiSync[] = [+ PkiSync.NutanixPrismCentral,+ PkiSync.Imperva+];+export const INCLUDE_ROOT_CA_UNSUPPORTED_DESTINATIONS: PkiSync[] = [PkiSync.CloudflareCustomCertificate,PkiSync.NutanixPrismCentral,diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ImpervaConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ImpervaConnectionForm.tsxindex d08815957a..ca5ce0937e 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ImpervaConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ImpervaConnectionForm.tsx@@ -98,14 +98,38 @@ export const ImpervaConnectionForm = ({ appConnection, onSubmit }: Props) => {{(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 });- }}- />+ {isAllowed ? (+ <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 });+ }}+ />+ ) : (+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <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 });+ }}+ />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ Restricted access. You don't have permission to attach gateways to+ resources.+ </TooltipContent>+ </Tooltip>+ )}<FieldDescription>Optional. Route Imperva API calls through a gateway when outbound traffic must leavefrom a fixed network.@@ -180,12 +204,11 @@ export const ImpervaConnectionForm = ({ appConnection, onSubmit }: Props) => {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.+ Imperva creates keys disabled, so switch the key on after creating it. Its role also+ needs the Manage SSL Certificates permission.</FieldDescription><FieldError errors={[error]} /></Field>