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
import { useEffect, useState } from "react";
import { Controller, FieldPath, FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { AlertTriangleIcon } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogTitle,
Button,
DocumentationLinkBadge,
Field,
FieldContent,
FieldDescription,
Label,
SheetFooter,
Stepper,
StepperList,
StepperStep,
Toggle
} from "@app/components/v3";
import {
getCertificateDisplayName,
isPaloAltoNetworksPkiSync,
PALO_ALTO_NETWORKS_PRIVATE_KEY_NOTE,
PKI_SYNC_MAP
} from "@app/helpers/pkiSyncs";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { usePaloAltoNetworksConnectionListTemplates } from "@app/hooks/api/appConnections/palo-alto-networks";
import {
PkiSync,
TPkiSync,
TPkiSyncRemovalOptions,
useCanSetHealthCheckCommand,
useCanSetPostSyncCommand,
usePkiSyncOption,
usePreviewPkiSyncFilters,
useUpdatePkiSync
} from "@app/hooks/api/pkiSyncs";
import { TPkiSyncFilterPreview } from "@app/hooks/api/pkiSyncs/types";
import {
arePkiSyncRemovalOptionsComplete,
hasPkiSyncRemovalOptions,
PkiSyncRemovalOptionsFields
} from "../PkiSyncRemovalOptionsFields";
import { PkiSyncCertificatesFields } from "./PkiSyncCertificatesFields";
import { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";
import { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";
import { PkiSyncFieldMappingsFields } from "./PkiSyncFieldMappingsFields";
import { PkiSyncHealthCheckCommandFields } from "./PkiSyncHealthCheckCommandFields";
import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields";
import { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";
import { PkiSyncTargetHostField } from "./PkiSyncTargetHostField";
import {
isPaloAltoNetworksTemplateMissing,
PALO_ALTO_NETWORKS_TEMPLATE_REQUIRED_MESSAGE
} from "./schemas/palo-alto-networks-pki-sync-destination-schema";
import {
removeUnusedKeystoreOptions,
TUpdatePkiSyncForm,
UpdatePkiSyncFormSchema
} from "./schemas/pki-sync-schema";
type Props = {
onComplete: (pkiSync: TPkiSync) => void;
pkiSync: TPkiSync;
onDirtyChange?: (isDirty: boolean) => void;
onCancel?: () => void;
initialStepKey?: TPkiSyncEditStepKey;
};
export type TPkiSyncEditStepKey =
| "destination"
| "targetHost"
| "options"
| "mappings"
| "hostCommands"
| "certificates"
| "details";
type FormStep = {
key: TPkiSyncEditStepKey;
name: string;
description: string;
title: string;
subtitle: string;
rightLabel: string;
rightDescription: string;
};
const getFormSteps = (
destination: PkiSync,
canRunHostCommands: boolean,
needsTargetHost: boolean
): FormStep[] => {
const steps: FormStep[] = [
{
key: "destination",
name: "Destination",
description: "Where to sync",
title: "Destination",
subtitle: "Choose a connection and configure the target location.",
rightLabel: "DESTINATION",
rightDescription:
"Choose the connection and the destination where certificates will be pushed. The available fields depend on the selected service."
},
...(needsTargetHost
? ([
{
key: "targetHost",
name: "Target Host",
description: "Which machine to reach",
title: "Target Host",
subtitle: "Name the machine this sync delivers to and how to reach it.",
rightLabel: "TARGET HOST",
rightDescription:
"An LDAP Connection supplies the credential for a whole domain rather than one machine, so each sync names its own host.\n\nMachines found in the directory are offered as suggestions, and you can enter one that is not listed."
}
] as FormStep[])
: []),
{
key: "options",
name: "Sync Options",
description: "Sync behavior",
title: "Sync Options",
subtitle: "Control how certificates are written and whether they sync automatically.",
rightLabel: "SYNC OPTIONS",
rightDescription:
"Control how certificates are synced, such as whether stale certificates are removed and whether the root CA is included. Auto-Sync pushes changes automatically as they occur."
}
];
if (destination === PkiSync.Chef || destination === PkiSync.AwsSecretsManager) {
steps.push({
key: "mappings",
name: "Mappings",
description: "Field mappings",
title: "Field Mappings",
subtitle: "Map each certificate component to the field names used at the destination.",
rightLabel: "MAPPINGS",
rightDescription:
"Map each certificate component (certificate, private key, and chain) to the field names used at the destination."
});
}
if (canRunHostCommands) {
steps.push({
key: "hostCommands",
name: "Commands",
description: "Commands on the host",
title: "Commands",
subtitle: "Optionally check the host before the sync, and act on it afterward.",
rightLabel: "COMMANDS",
rightDescription:
"The health check runs first. If the host is not ready, the sync stops and no certificate is delivered.\n\nThe post-sync command runs after the certificates are written, so a service can reload and pick up the new one. It only runs when the sync delivers a file. If either command fails, the sync is marked failed."
});
}
steps.push({
key: "certificates",
name: "Certificates",
description: "Filters and certificates",
title: "Certificates",
subtitle: "Describe the certificates this sync holds.",
rightLabel: "CERTIFICATES",
rightDescription: `Anything in the application matching these filters is synced as it is issued, and anything that stops matching is no longer synced. Nothing changes until you save.${
isPaloAltoNetworksPkiSync(destination) ? `\n\n${PALO_ALTO_NETWORKS_PRIVATE_KEY_NOTE}` : ""
}`
});
steps.push({
key: "details",
name: "Details",
description: "Name and description",
title: "Details",
subtitle: "Give this sync a name and an optional description.",
rightLabel: "DETAILS",
rightDescription:
"Give this sync a name and an optional description so your team can identify it later."
});
return steps;
};
const LDAP_TARGET_DEFAULTS = {
host: undefined,
port: undefined,
sslEnabled: undefined,
sslRejectUnauthorized: undefined,
sslCertificate: undefined
};
export const EditPkiSyncForm = ({
pkiSync,
onComplete,
onDirtyChange,
onCancel,
initialStepKey
}: Props) => {
const updatePkiSync = useUpdatePkiSync();
const { name: destinationName } = PKI_SYNC_MAP[pkiSync.destination];
const { syncOption } = usePkiSyncOption(pkiSync.destination);
const canSetPostSyncCommand = useCanSetPostSyncCommand(pkiSync.applicationId);
const canSetHealthCheckCommand = useCanSetHealthCheckCommand(pkiSync.applicationId);
const [selectedStepIndex, setSelectedStepIndex] = useState(() => {
const initialSteps = getFormSteps(
pkiSync.destination,
Boolean(syncOption?.canRunHealthCheckCommand || syncOption?.canRunPostSyncCommand),
pkiSync.connection.app === AppConnection.LDAP
);
const initialIndex = initialSteps.findIndex((step) => step.key === initialStepKey);
return initialIndex === -1 ? 0 : initialIndex;
});
const formMethods = useForm<TUpdatePkiSyncForm>({
resolver: zodResolver(UpdatePkiSyncFormSchema),
defaultValues: {
name: pkiSync.name,
destination: pkiSync.destination,
description: pkiSync.description ?? "",
connection: {
id: pkiSync.connectionId,
name: pkiSync.appConnectionName,
app: pkiSync.connection.app
},
syncOptions: pkiSync.syncOptions,
destinationConfig: { ...LDAP_TARGET_DEFAULTS, ...pkiSync.destinationConfig },
isAutoSyncEnabled: pkiSync.isAutoSyncEnabled,
filters: pkiSync.filters ?? null
} as Partial<TUpdatePkiSyncForm>,
reValidateMode: "onChange"
});
const selectedConnectionApp = (
formMethods.watch("connection") as { app?: AppConnection } | undefined
)?.app;
const steps = getFormSteps(
pkiSync.destination,
Boolean(syncOption?.canRunHealthCheckCommand || syncOption?.canRunPostSyncCommand),
selectedConnectionApp === AppConnection.LDAP
);
const {
handleSubmit,
control,
setError,
formState: { isSubmitting, isDirty }
} = formMethods;
const { data: paloAltoNetworksDevice, isLoading: isDetectingPaloAltoNetworksDevice } =
usePaloAltoNetworksConnectionListTemplates(formMethods.watch("connection.id"), {
enabled: isPaloAltoNetworksPkiSync(pkiSync.destination)
});
const previewFilters = usePreviewPkiSyncFilters();
const [unlinkRemovalOptions, setUnlinkRemovalOptions] = useState<TPkiSyncRemovalOptions>({});
const [pendingUnlink, setPendingUnlink] = useState<{
preview: TPkiSyncFilterPreview;
formData: TUpdatePkiSyncForm;
} | null>(null);
useEffect(() => {
onDirtyChange?.(isDirty);
}, [isDirty, onDirtyChange]);
const applyUpdate = async (
{ connection, ...formData }: TUpdatePkiSyncForm,
removalOptions?: TPkiSyncRemovalOptions
) => {
const hasNewExportPassword = Boolean(
(formData as { credentials?: { exportPassword?: string } }).credentials?.exportPassword
);
try {
const updatedPkiSync = await updatePkiSync.mutateAsync({
syncId: pkiSync.id,
...removeUnusedKeystoreOptions(formData),
...(hasNewExportPassword ? {} : { credentials: undefined }),
connectionId: connection.id,
projectId: pkiSync.projectId,
destination: pkiSync.destination,
...(removalOptions ? { removalOptions } : {})
});
createNotification({
text: `Successfully updated ${destinationName} Certificate Sync`,
type: "success"
});
onComplete(updatedPkiSync);
} catch {
/* empty */
}
};
const onSubmit = async (formData: TUpdatePkiSyncForm) => {
if (
isPaloAltoNetworksPkiSync(pkiSync.destination) &&
isPaloAltoNetworksTemplateMissing(
paloAltoNetworksDevice?.isPanorama,
formData.destinationConfig
)
) {
setError("destinationConfig.template" as FieldPath<TUpdatePkiSyncForm>, {
type: "manual",
message: PALO_ALTO_NETWORKS_TEMPLATE_REQUIRED_MESSAGE
});
setSelectedStepIndex(steps.findIndex((step) => step.key === "destination"));
return;
}
const haveFiltersChanged =
JSON.stringify(formData.filters ?? null) !== JSON.stringify(pkiSync.filters ?? null);
if (haveFiltersChanged) {
try {
const preview = await previewFilters.mutateAsync({
pkiSyncId: pkiSync.id,
filters: formData.filters
});
if (preview.toUnlink.length > 0) {
setUnlinkRemovalOptions({});
setPendingUnlink({ preview, formData });
return;
}
} catch {
return;
}
}
await applyUpdate(formData);
};
const needsUnlinkRemovalOptions = Boolean(
pendingUnlink &&
hasPkiSyncRemovalOptions(pkiSync.destination) &&
(pendingUnlink.formData.syncOptions as { canRemoveCertificates?: boolean } | undefined)
?.canRemoveCertificates &&
pendingUnlink.preview.toUnlinkAtDestinationCount > 0
);
const areUnlinkRemovalOptionsComplete =
!pendingUnlink ||
!needsUnlinkRemovalOptions ||
arePkiSyncRemovalOptionsComplete(
pkiSync.destination,
{ remainingCertificateCount: pendingUnlink.preview.matchedCount },
unlinkRemovalOptions
);
const currentStep = steps[selectedStepIndex];
const renderStep = () => {
switch (currentStep.key) {
case "destination":
return <PkiSyncDestinationFields isUpdate />;
case "targetHost":
return <PkiSyncTargetHostField applicationId={pkiSync.applicationId} />;
case "options":
return (
<>
<PkiSyncOptionsFields destination={pkiSync.destination} isUpdate />
<Controller
control={control}
name="isAutoSyncEnabled"
render={({ field: { value, onChange } }) => (
<Field className="mt-2">
<Field orientation="horizontal">
<FieldContent>
<Label htmlFor="auto-sync-enabled">Auto-sync on change</Label>
<FieldDescription>
When certificates in the selected list change, sync automatically. Turn off
to only sync manually.
</FieldDescription>
</FieldContent>
<Toggle
id="auto-sync-enabled"
variant="project"
checked={value}
onCheckedChange={onChange}
/>
</Field>
</Field>
)}
/>
</>
);
case "mappings":
return <PkiSyncFieldMappingsFields destination={pkiSync.destination} />;
case "hostCommands":
return (
<div className="flex flex-col gap-8">
<PkiSyncHealthCheckCommandFields
destination={pkiSync.destination}
applicationId={pkiSync.applicationId}
syncId={pkiSync.id}
canEditCommand={canSetHealthCheckCommand}
/>
<PkiSyncPostSyncCommandFields
destination={pkiSync.destination}
canEditCommand={canSetPostSyncCommand}
/>
</div>
);
case "certificates":
return (
<PkiSyncCertificatesFields
applicationId={pkiSync.applicationId ?? undefined}
pkiSyncId={pkiSync.id}
/>
);
case "details":
return <PkiSyncDetailsFields />;
default:
return null;
}
};
return (
<FormProvider {...formMethods}>
<form className="flex h-full min-h-0 flex-col" onSubmit={handleSubmit(onSubmit)}>
<div className="flex min-h-0 flex-1 overflow-hidden">
<aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">
<p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">
Sections
</p>
<Stepper
activeStep={selectedStepIndex}
orientation="vertical"
onStepChange={setSelectedStepIndex}
nonLinear
>
<StepperList>
{steps.map((step, i) => (
<StepperStep
key={step.key}
index={i}
title={step.name}
description={step.description}
/>
))}
</StepperList>
</Stepper>
</aside>
<div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">
<div className="mb-6">
<h2 className="text-lg font-normal text-foreground">{currentStep.title}</h2>
<p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>
</div>
{renderStep()}
</div>
<aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">
<div className="mb-auto">
<div className="flex items-center justify-between gap-2">
<p className="text-[11px] font-medium tracking-wider text-muted uppercase">
Step {selectedStepIndex + 1} · {currentStep.rightLabel}
</p>
<DocumentationLinkBadge
href={`https://infisical.com/docs/documentation/platform/pki/applications/certificate-syncs/${pkiSync.destination}`}
/>
</div>
<p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>
{currentStep.rightDescription.split("\n\n").map((paragraph) => (
<p key={paragraph} className="mt-2 text-sm leading-relaxed text-muted">
{paragraph}
</p>
))}
</div>
</aside>
</div>
<SheetFooter className="shrink-0 items-center justify-between border-t">
<div className="flex items-center gap-3">
<Button
variant="outline"
type="button"
onClick={onCancel ?? (() => onComplete(pkiSync))}
>
Cancel
</Button>
<span className="text-xs text-muted">{isDirty ? "Unsaved changes" : ""}</span>
</div>
<div className="flex items-center gap-3">
<span className="text-xs text-muted">
Step {selectedStepIndex + 1} of {steps.length}
</span>
<Button
variant="outline"
type="button"
onClick={() => setSelectedStepIndex((i) => Math.max(0, i - 1))}
isDisabled={selectedStepIndex === 0}
>
Back
</Button>
<Button
variant="outline"
type="button"
onClick={() => setSelectedStepIndex((i) => Math.min(steps.length - 1, i + 1))}
isDisabled={selectedStepIndex === steps.length - 1}
>
Next
</Button>
<Button
variant="project"
type="submit"
isPending={isSubmitting}
isDisabled={!isDirty || isSubmitting || isDetectingPaloAltoNetworksDevice}
>
Save
</Button>
</div>
</SheetFooter>
</form>
<AlertDialog
open={Boolean(pendingUnlink)}
onOpenChange={(open) => {
if (!open && !isSubmitting) setPendingUnlink(null);
}}
>
<AlertDialogContent>
<AlertDialogHeader className="sm:grid-rows-[auto]!">
<AlertDialogMedia className="mb-0 sm:row-span-1!">
<AlertTriangleIcon className="text-warning" />
</AlertDialogMedia>
<AlertDialogTitle>
{pendingUnlink?.preview.toUnlink.length} certificate
{pendingUnlink?.preview.toUnlink.length === 1 ? "" : "s"} will no longer be synced
</AlertDialogTitle>
<AlertDialogDescription asChild className="sm:col-span-2">
<div className="flex flex-col gap-2">
<p>
These certificates no longer match the filters, so this sync will stop holding
them:
</p>
<ul className="max-h-40 overflow-y-auto font-mono text-xs">
{pendingUnlink?.preview.toUnlink.map((certificate) => (
<li key={certificate.id}>
{getCertificateDisplayName(certificate).originalDisplayName}
</li>
))}
</ul>
{pendingUnlink?.preview.willRemoveFromDestination && (
<p>
Removal is enabled on this sync, so they will also be deleted from{" "}
{destinationName}.
</p>
)}
</div>
</AlertDialogDescription>
{needsUnlinkRemovalOptions && (
<div className="mt-2 w-full text-wrap sm:col-span-2">
<PkiSyncRemovalOptionsFields
pkiSync={pkiSync}
value={unlinkRemovalOptions}
onChange={setUnlinkRemovalOptions}
/>
</div>
)}
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel isDisabled={isSubmitting}>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="danger"
isPending={isSubmitting}
isDisabled={!areUnlinkRemovalOptionsComplete}
onClick={(event) => {
event.preventDefault();
const pending = pendingUnlink;
setPendingUnlink(null);
if (pending) {
applyUpdate(
pending.formData,
needsUnlinkRemovalOptions ? unlinkRemovalOptions : undefined
).catch(() => {});
}
}}
>
Save changes
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</FormProvider>
);
};