Skip to content

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

20.1 KB
Raw Blame
import { useState } from "react";
import { Controller, FieldErrors, 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 { useProject } from "@app/context";
import {
  isPaloAltoNetworksPkiSync,
  PALO_ALTO_NETWORKS_PRIVATE_KEY_NOTE,
  PKI_SYNC_MAP,
  PRESERVE_ARN_DESTINATIONS,
  PRESERVE_ITEM_ON_RENEWAL_DESTINATIONS
} from "@app/helpers/pkiSyncs";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { usePaloAltoNetworksConnectionListTemplates } from "@app/hooks/api/appConnections/palo-alto-networks";
import {
  PkiSync,
  PkiSyncExportFormat,
  TPkiSync,
  useCanSetHealthCheckCommand,
  useCanSetPostSyncCommand,
  useCreatePkiSync,
  usePkiSyncOption
} from "@app/hooks/api/pkiSyncs";

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 { PkiSyncReviewFields } from "./PkiSyncReviewFields";
import { PkiSyncTargetHostField } from "./PkiSyncTargetHostField";
import { KEMP_DEFAULT_CA_NAME_SCHEMA } from "./schemas/kemp-loadmaster-pki-sync-destination-schema";
import {
  isPaloAltoNetworksTemplateMissing,
  PALO_ALTO_NETWORKS_TEMPLATE_REQUIRED_MESSAGE
} from "./schemas/palo-alto-networks-pki-sync-destination-schema";
import {
  getKeystoreFieldIssues,
  PkiSyncFormSchema,
  removeUnusedKeystoreOptions,
  TPkiSyncForm
} from "./schemas/pki-sync-schema";

type Props = {
  onComplete: (pkiSync: TPkiSync) => void;
  destination: PkiSync;
  onCancel: () => void;
  initialData?: Partial<TPkiSyncForm>;
  applicationId?: string;
};

const STEP_META: Record<
  string,
  { short: string; subtitle: string; rightLabel: string; rightDescription: string }
> = {
  destination: {
    short: "Where to sync",
    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."
  },
  targetHost: {
    short: "Which machine to reach",
    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."
  },
  options: {
    short: "Sync behavior",
    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."
  },
  mappings: {
    short: "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."
  },
  hostCommands: {
    short: "Commands on the host",
    subtitle: "Check the host before the sync, and run a command after it.",
    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."
  },
  details: {
    short: "Name and description",
    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."
  },
  certificates: {
    short: "Certificates to sync",
    subtitle: "Link the certificates this sync pushes.",
    rightLabel: "CERTIFICATES",
    rightDescription:
      "Anything in the application matching these filters is synced as it is issued. A sync with no filters syncs nothing."
  },
  review: {
    short: "Confirm and create",
    subtitle: "Double-check everything before creating the sync.",
    rightLabel: "REVIEW",
    rightDescription:
      "Review the configuration and create the sync. Every setting can be edited afterward from the sync's details."
  }
};

const getFormTabs = (
  destination: PkiSync,
  canRunHostCommands: boolean,
  needsTargetHost: boolean
): { name: string; key: string; fields: FieldPath<TPkiSyncForm>[] }[] => {
  const baseTabs = [
    {
      name: "Destination",
      key: "destination",
      fields: ["connection", "destinationConfig"] as FieldPath<TPkiSyncForm>[]
    }
  ];

  if (needsTargetHost) {
    baseTabs.push({
      name: "Target Host",
      key: "targetHost",
      fields: ["destinationConfig"] as FieldPath<TPkiSyncForm>[]
    });
  }

  baseTabs.push({
    name: "Sync Options",
    key: "options",
    fields: ["syncOptions", "credentials"] as FieldPath<TPkiSyncForm>[]
  });

  if (destination === PkiSync.Chef || destination === PkiSync.AwsSecretsManager) {
    baseTabs.push({
      name: "Mappings",
      key: "mappings",
      fields: ["syncOptions"] as FieldPath<TPkiSyncForm>[]
    });
  }

  baseTabs.push(
    {
      name: "Details",
      key: "details",
      fields: ["name", "description"] as FieldPath<TPkiSyncForm>[]
    },
    {
      name: "Certificates",
      key: "certificates",
      fields: ["filters"] as FieldPath<TPkiSyncForm>[]
    }
  );

  if (canRunHostCommands) {
    baseTabs.push({
      name: "Commands",
      key: "hostCommands",
      fields: [
        "syncOptions.healthCheckCommand",
        "syncOptions.postSyncCommand"
      ] as FieldPath<TPkiSyncForm>[]
    });
  }

  baseTabs.push({ name: "Review", key: "review", fields: [] as FieldPath<TPkiSyncForm>[] });

  return baseTabs;
};

export const CreatePkiSyncForm = ({
  destination,
  onComplete,
  onCancel,
  initialData,
  applicationId
}: Props) => {
  const createPkiSync = useCreatePkiSync();
  const { currentProject } = useProject();
  const { name: destinationName } = PKI_SYNC_MAP[destination];

  const [selectedTabIndex, setSelectedTabIndex] = useState(0);
  const [showConfirmation, setShowConfirmation] = useState(false);

  const { syncOption } = usePkiSyncOption(destination);
  const canSetPostSyncCommand = useCanSetPostSyncCommand(applicationId);
  const canSetHealthCheckCommand = useCanSetHealthCheckCommand(applicationId);
  const formMethods = useForm<TPkiSyncForm>({
    resolver: zodResolver(PkiSyncFormSchema),
    defaultValues: {
      destination,
      isAutoSyncEnabled: false,
      filters: null,
      syncOptions: {
        canImportCertificates: false,
        canRemoveCertificates: false,
        certificateNameSchema: syncOption?.defaultCertificateNameSchema,
        ...(PRESERVE_ARN_DESTINATIONS.includes(destination) && { preserveArn: true }),
        ...(PRESERVE_ITEM_ON_RENEWAL_DESTINATIONS.includes(destination) && {
          preserveItemOnRenewal: true
        }),
        ...((destination === PkiSync.LinuxServer || destination === PkiSync.WindowsServer) && {
          exportFormat:
            destination === PkiSync.WindowsServer
              ? PkiSyncExportFormat.Pkcs12
              : PkiSyncExportFormat.Pem,
          includePrivateKey: true
        }),
        ...(destination === PkiSync.KempLoadMaster && {
          caCertificateNameSchema: KEMP_DEFAULT_CA_NAME_SCHEMA
        }),
        ...((destination === PkiSync.Chef || destination === PkiSync.AwsSecretsManager) && {
          fieldMappings: {
            certificate: "certificate",
            privateKey: "private_key",
            certificateChain: "certificate_chain",
            caCertificate: "ca_certificate"
          }
        }),
        ...(destination === PkiSync.AwsSecretsManager && {
          preserveSecretOnRenewal: true,
          updateExistingCertificates: true
        })
      },
      ...initialData
    } as Partial<TPkiSyncForm>,
    reValidateMode: "onChange"
  });

  const selectedConnectionApp = formMethods.watch("connection")?.app;
  const FORM_TABS = getFormTabs(
    destination,
    (Boolean(syncOption?.canRunHealthCheckCommand) && canSetHealthCheckCommand) ||
      (Boolean(syncOption?.canRunPostSyncCommand) && canSetPostSyncCommand),
    selectedConnectionApp === AppConnection.LDAP
  );

  const onSubmit = async ({ connection, destinationConfig, ...formData }: TPkiSyncForm) => {
    try {
      const pkiSync = await createPkiSync.mutateAsync({
        ...removeUnusedKeystoreOptions(formData),
        connectionId: connection.id,
        projectId: currentProject.id,
        applicationId,
        destinationConfig
      });

      createNotification({
        text: `Successfully created ${destinationName} Certificate Sync`,
        type: "success"
      });
      setShowConfirmation(false);
      onComplete(pkiSync);
    } catch {
      setShowConfirmation(false);
    }
  };

  const { handleSubmit, trigger, control, getValues, setError, watch } = formMethods;
  const canRemoveCertificates = watch("syncOptions.canRemoveCertificates");
  const { data: paloAltoNetworksDevice, isLoading: isDetectingPaloAltoNetworksDevice } =
    usePaloAltoNetworksConnectionListTemplates(watch("connection.id"), {
      enabled: isPaloAltoNetworksPkiSync(destination)
    });

  const isStepValid = async (index: number) => {
    const isValid = await trigger(FORM_TABS[index].fields);
    if (!isValid) return false;

    // The union member is still incomplete at this point (name is unset), so the schema's cross-field
    // rule does not surface here. Same reason the PKCS#12 rule below is checked by hand.
    if (FORM_TABS[index].key === "targetHost") {
      const { destinationConfig } = getValues() as { destinationConfig?: { host?: string } };
      if (!destinationConfig?.host) {
        setError("destinationConfig.host" as FieldPath<TPkiSyncForm>, {
          type: "manual",
          message: "A target host is required when using an LDAP connection"
        });
        return false;
      }
    }

    if (
      FORM_TABS[index].key === "destination" &&
      isPaloAltoNetworksPkiSync(destination) &&
      isPaloAltoNetworksTemplateMissing(
        paloAltoNetworksDevice?.isPanorama,
        getValues("destinationConfig")
      )
    ) {
      setError("destinationConfig.template" as FieldPath<TPkiSyncForm>, {
        type: "manual",
        message: PALO_ALTO_NETWORKS_TEMPLATE_REQUIRED_MESSAGE
      });
      return false;
    }

    if (FORM_TABS[index].key === "options") {
      const issues = getKeystoreFieldIssues(getValues(), { requirePassword: true });
      issues.forEach(({ path, message }) =>
        setError(path.join(".") as FieldPath<TPkiSyncForm>, { type: "manual", message })
      );
      if (issues.length > 0) return false;
    }

    return true;
  };

  // A field from an earlier step can fail only when the whole form is checked, so show that step.
  const onInvalid = (errors: FieldErrors<TPkiSyncForm>) => {
    const errorKeys = Object.keys(errors);
    const stepIndex = FORM_TABS.findIndex((tab) =>
      tab.fields.some((field) => errorKeys.includes(String(field).split(".")[0]))
    );
    setShowConfirmation(false);
    if (stepIndex >= 0) setSelectedTabIndex(stepIndex);
  };

  const isFinalStep = selectedTabIndex === FORM_TABS.length - 1;
  const isNextBusy = (isFinalStep && createPkiSync.isPending) || isDetectingPaloAltoNetworksDevice;

  const handleNext = async () => {
    if (isFinalStep) {
      setShowConfirmation(true);
      return;
    }

    const isValid = await isStepValid(selectedTabIndex);
    if (!isValid) return;

    setSelectedTabIndex((prev) => prev + 1);
  };

  const handleBack = () => {
    if (selectedTabIndex === 0) {
      onCancel();
      return;
    }
    setSelectedTabIndex((prev) => prev - 1);
  };

  const handleStepChange = (index: number) => {
    if (index < selectedTabIndex) setSelectedTabIndex(index);
  };

  const currentKey = FORM_TABS[selectedTabIndex].key;
  const currentName = FORM_TABS[selectedTabIndex].name;
  const currentDetail = STEP_META[currentKey];
  const rightDescription =
    currentKey === "certificates" && isPaloAltoNetworksPkiSync(destination)
      ? `${currentDetail.rightDescription}\n\n${PALO_ALTO_NETWORKS_PRIVATE_KEY_NOTE}`
      : currentDetail.rightDescription;

  return (
    <form
      onSubmit={(e) => e.preventDefault()}
      className="flex min-h-0 flex-1 flex-col overflow-hidden"
    >
      <FormProvider {...formMethods}>
        <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">
              Setup steps
            </p>
            <Stepper
              activeStep={selectedTabIndex}
              orientation="vertical"
              onStepChange={handleStepChange}
            >
              <StepperList>
                {FORM_TABS.map((tab, index) => (
                  <StepperStep
                    key={tab.key}
                    index={index}
                    title={tab.name}
                    description={STEP_META[tab.key].short}
                  />
                ))}
              </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">{currentName}</h2>
              <p className="mt-1 text-sm text-muted">{currentDetail.subtitle}</p>
            </div>
            {currentKey === "destination" && <PkiSyncDestinationFields />}
            {currentKey === "targetHost" && (
              <PkiSyncTargetHostField applicationId={applicationId} />
            )}
            {currentKey === "options" && (
              <>
                <PkiSyncOptionsFields destination={destination} />
                <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>
                  )}
                />
              </>
            )}
            {currentKey === "mappings" && <PkiSyncFieldMappingsFields destination={destination} />}
            {currentKey === "hostCommands" && (
              <div className="flex flex-col gap-8">
                <PkiSyncHealthCheckCommandFields
                  destination={destination}
                  applicationId={applicationId}
                  canEditCommand={canSetHealthCheckCommand}
                />
                <PkiSyncPostSyncCommandFields
                  destination={destination}
                  canEditCommand={canSetPostSyncCommand}
                />
              </div>
            )}
            {currentKey === "details" && <PkiSyncDetailsFields />}
            {currentKey === "certificates" && (
              <PkiSyncCertificatesFields applicationId={applicationId} />
            )}
            {currentKey === "review" && <PkiSyncReviewFields applicationId={applicationId} />}
          </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 {selectedTabIndex + 1} · {currentDetail.rightLabel}
                </p>
                <DocumentationLinkBadge
                  href={`https://infisical.com/docs/documentation/platform/pki/applications/certificate-syncs/${destination}`}
                />
              </div>
              <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>
              {rightDescription.split("\n\n").map((paragraph) => (
                <p key={paragraph} className="mt-2 text-sm leading-relaxed text-muted">
                  {paragraph}
                </p>
              ))}
            </div>
          </aside>
        </div>
      </FormProvider>

      <SheetFooter className="shrink-0 items-center justify-between border-t">
        <span className="text-xs text-muted">
          Step {selectedTabIndex + 1} of {FORM_TABS.length}
        </span>
        <div className="flex items-center gap-3">
          <Button type="button" variant="outline" onClick={handleBack}>
            {selectedTabIndex === 0 ? "Cancel" : "Back"}
          </Button>
          <Button
            type="button"
            variant="project"
            onClick={handleNext}
            isPending={isFinalStep && createPkiSync.isPending}
            isDisabled={isNextBusy}
          >
            {isFinalStep ? "Create Sync" : "Continue"}
          </Button>
        </div>
      </SheetFooter>

      <AlertDialog
        open={showConfirmation}
        onOpenChange={(open) => {
          if (!createPkiSync.isPending) setShowConfirmation(open);
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogMedia>
              <AlertTriangleIcon className="text-warning" />
            </AlertDialogMedia>
            <AlertDialogTitle>Certificate Sync Behavior</AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div className="flex flex-col gap-2">
                <p>Infisical is the source of truth for synced destinations.</p>
                <p>
                  Certificates in the destination will be overwritten, and any direct edits there
                  may be overwritten by future syncs.
                </p>
                {syncOption?.canRemoveCertificates && canRemoveCertificates && (
                  <p>
                    Certificates that leave this sync will be deleted from {destinationName},
                    whether they stopped being active, were deleted, or stopped matching the
                    sync&apos;s filters.
                  </p>
                )}
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel isDisabled={createPkiSync.isPending}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              variant="project"
              isDisabled={createPkiSync.isPending}
              onClick={handleSubmit(onSubmit, onInvalid)}
            >
              I Understand
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </form>
  );
};