Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(pki): keep imperva certificates on a failed sync

bernie-g1d098a904629
diff --git a/backend/src/services/app-connection/imperva/imperva-connection-fns.ts b/backend/src/services/app-connection/imperva/imperva-connection-fns.ts
index 14b78de34f..cbaf0ce875 100644
--- a/backend/src/services/app-connection/imperva/imperva-connection-fns.ts
+++ b/backend/src/services/app-connection/imperva/imperva-connection-fns.ts
@@ -228,16 +228,6 @@ export const validateImpervaConnectionCredentials = async (
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,
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.ts
index 66b5574aeb..de1dae8de4 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
@@ -186,3 +186,42 @@ describe("Imperva slot removal", () => {
expect(removeCertificatesFromDal).toHaveBeenCalledWith("sync-1", ["cert-1"]);
});
});
+
+describe("Imperva failed uploads", () => {
+ test("leaves the certificate already serving in place when the upload is rejected", async () => {
+ const { impervaPkiSyncFactory } = 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;
+ impervaRequest.mockReset();
+ impervaRequest.mockRejectedValue(rejected);
+
+ const removeCertificatesFromDal = vi.fn();
+ const factory = impervaPkiSyncFactory({
+ certificateSyncDAL: {
+ findByPkiSyncId: vi.fn().mockResolvedValue([{ certificateId: "old", externalIdentifier: "222:RSA" }]),
+ 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
+ });
+
+ const sync = {
+ 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;
+
+ await expect(
+ factory.syncCertificates(sync, { leaf: { cert: RSA_CERT_PEM, privateKey: "key" } } as never)
+ ).rejects.toThrow("Failed to sync certificate to Imperva");
+
+ expect(impervaRequest.mock.calls.every((call) => (call[0] as TRecordedRequest).method !== "DELETE")).toBe(true);
+ expect(removeCertificatesFromDal).not.toHaveBeenCalled();
+ });
+});
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.ts
index 3c87aed269..63c8490e94 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
@@ -360,8 +360,9 @@ export const impervaPkiSyncFactory = ({
}
// 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) {
+ // 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 &&
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index d445692e9d..ceadfa2794 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -19,6 +19,7 @@ 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";
@@ -1293,10 +1294,32 @@ export const pkiSyncServiceFactory = ({
);
// 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, () =>
- $reconcileFilters(pkiSync as TPkiSyncReconcileTarget, 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 });
diff --git a/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsx b/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsx
index 8e05f948c8..1c49a907c1 100644
--- a/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/ImpervaPkiSyncFields.tsx
@@ -1,16 +1,12 @@
import { Controller, useFormContext, useWatch } from "react-hook-form";
import { AxiosError } from "axios";
-import { Info, Loader2Icon } from "lucide-react";
+import { Info } from "lucide-react";
import {
+ Combobox,
Field,
FieldError,
FieldLabel,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
Tooltip,
TooltipContent,
TooltipTrigger
@@ -52,6 +48,7 @@ export const ImpervaPkiSyncFields = () => {
name="destinationConfig.siteId"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => {
+ const siteOptions = sites ?? [];
const siteFetchErrorText =
isSitesError && connectionId
? ((sitesError as AxiosError<{ message?: string }>)?.response?.data?.message ??
@@ -76,35 +73,22 @@ export const ImpervaPkiSyncFields = () => {
</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>
- )}
+ <Combobox
+ id="pki-sync-imperva-site"
+ isDisabled={!connectionId}
+ isLoading={Boolean(connectionId) && isLoadingSites}
+ options={siteOptions}
+ value={siteOptions.find((site) => site.id === value) ?? null}
+ onValueChange={(option) => {
+ onChange(option?.id ?? "");
+ setValue("destinationConfig.siteName", option?.name ?? "");
+ }}
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ getOptionKeywords={(option) => [option.id]}
+ placeholder={connectionId ? "Select a website" : "Select a connection first"}
+ isError={Boolean(combinedError)}
+ />
<FieldError errors={[combinedError]} />
</Field>
);