Skip to content

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

9.6 KB
Raw Blame
import { useEffect, useId, useMemo } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate, useParams } from "@tanstack/react-router";
import { z } from "zod";

import { createNotification } from "@app/components/notifications";
import {
  Button,
  Combobox,
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DiscardChangesAlertDialog,
  Field,
  FieldContent,
  FieldDescription,
  FieldError,
  FieldLabel,
  Input,
  TextArea
} from "@app/components/v3";
import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
import {
  TPkiApplication,
  useCreatePkiApplication,
  useUpdatePkiApplication
} from "@app/hooks/api/pkiApplications";
import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { ApplicationTab } from "@app/pages/cert-manager/ApplicationDetailsByIDPage/application-tabs";
import { useProfileCreation } from "@app/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation";

const SLUG_REGEX = /^[a-z0-9-]+$/;

const schema = z.object({
  name: z
    .string()
    .trim()
    .min(1, "Name is required")
    .max(64)
    .regex(SLUG_REGEX, "Name must contain only lowercase letters, numbers, and hyphens"),
  description: z.string().trim().max(256).optional(),
  profileIds: z.array(z.object({ value: z.string(), label: z.string() })).optional()
});

type FormData = z.infer<typeof schema>;

type Props = {
  popUp: UsePopUpState<["application"]>;
  handlePopUpToggle: (popUpName: keyof UsePopUpState<["application"]>, state?: boolean) => void;
};

export const PkiApplicationModal = ({ popUp, handlePopUpToggle }: Props) => {
  const { orgId } = useParams({ strict: false });
  const navigate = useNavigate();
  const editing = (popUp?.application?.data as TPkiApplication | undefined) ?? null;
  const create = useCreatePkiApplication();
  const update = useUpdatePkiApplication();
  const inputId = useId();

  const { data: profilesData } = useListCertificateProfiles({ limit: 100 });

  const profileOptions = useMemo(
    () =>
      (profilesData?.certificateProfiles ?? []).map((p) => ({
        value: p.id,
        label: p.slug
      })),
    [profilesData]
  );

  const {
    control,
    handleSubmit,
    reset,
    getValues,
    setValue,
    formState: { isSubmitting, isDirty }
  } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: { name: "", description: "", profileIds: [] }
  });
  const profileCreation = useProfileCreation((profile) =>
    setValue(
      "profileIds",
      [...(getValues("profileIds") ?? []), { value: profile.id, label: profile.slug }],
      { shouldDirty: true }
    )
  );
  const { requestDiscard, confirmDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen } =
    useDiscardChangesGuard({ isDirty, onDiscard: () => handlePopUpToggle("application", false) });

  useEffect(() => {
    if (!popUp.application.isOpen) return;
    if (editing) {
      reset({
        name: editing.name,
        description: editing.description ?? "",
        profileIds: []
      });
    } else {
      reset({ name: "", description: "", profileIds: [] });
    }
  }, [editing, reset, popUp.application.isOpen]);

  const onSubmit = async (data: FormData) => {
    try {
      if (editing) {
        await update.mutateAsync({
          applicationId: editing.id,
          name: data.name,
          description: data.description?.length ? data.description : null
        });
        createNotification({ type: "success", text: "Application updated" });
      } else {
        const selectedIds = (data.profileIds ?? []).map((p) => p.value);
        const created = await create.mutateAsync({
          name: data.name,
          description: data.description,
          profileIds: selectedIds
        });
        createNotification({ type: "success", text: "Application created" });
        handlePopUpToggle("application", false);
        // Land on Settings rather than the empty inventory: attaching a profile is the next step
        // before the application can issue anything.
        navigate({
          to: "/organizations/$orgId/cert-manager/applications/$applicationName",
          params: {
            orgId: orgId ?? "",
            applicationName: created.name
          },
          search: { selectedTab: ApplicationTab.Settings }
        });
        return;
      }
      handlePopUpToggle("application", false);
    } catch (err) {
      const detail = err instanceof Error ? err.message : "Failed to save application.";
      createNotification({ type: "error", text: detail });
    }
  };

  return (
    <>
      <Dialog
        open={popUp?.application?.isOpen}
        onOpenChange={(isOpen) => {
          if (isOpen) handlePopUpToggle("application", true);
          else requestDiscard();
        }}
      >
        <DialogContent isPending={isSubmitting}>
          <DialogHeader>
            <DialogTitle>{editing ? "Edit Application" : "Create Application"}</DialogTitle>
            <DialogDescription>
              {editing
                ? "Update this Application's name and description."
                : "A logical grouping for a service or workload that needs certificates."}
            </DialogDescription>
          </DialogHeader>

          <form onSubmit={handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col gap-6">
            <DialogBody>
              <fieldset disabled={isSubmitting} className="flex min-w-0 flex-col gap-4">
                <Controller
                  control={control}
                  name="name"
                  render={({ field, fieldState: { error } }) => (
                    <Field>
                      <FieldLabel htmlFor={`${inputId}-name`}>Name</FieldLabel>
                      <FieldContent>
                        <Input
                          {...field}
                          id={`${inputId}-name`}
                          isError={Boolean(error)}
                          placeholder="my-service"
                          autoComplete="off"
                          name="pki-application-name"
                        />
                      </FieldContent>
                      {error ? <FieldError>{error.message}</FieldError> : null}
                    </Field>
                  )}
                />
                <Controller
                  control={control}
                  name="description"
                  render={({ field, fieldState: { error } }) => (
                    <Field>
                      <FieldLabel htmlFor={`${inputId}-description`}>Description</FieldLabel>
                      <FieldContent>
                        <TextArea
                          {...field}
                          id={`${inputId}-description`}
                          isError={Boolean(error)}
                          placeholder="Issues and rotates certificates for my application stack."
                        />
                      </FieldContent>
                      {error ? <FieldError>{error.message}</FieldError> : null}
                    </Field>
                  )}
                />
                {!editing ? (
                  <Controller
                    control={control}
                    name="profileIds"
                    render={({ field, fieldState: { error } }) => (
                      <Field>
                        <FieldLabel htmlFor={`${inputId}-profiles`}>
                          Certificate Profiles
                        </FieldLabel>
                        <FieldContent>
                          <Combobox
                            ref={field.ref}
                            id={`${inputId}-profiles`}
                            multiple
                            onBlur={field.onBlur}
                            isError={Boolean(error)}
                            value={field.value ?? []}
                            onValueChange={field.onChange}
                            getOptionValue={(option) => option.value}
                            getOptionLabel={(option) => option.label}
                            options={profileOptions}
                            creation={profileCreation}
                            placeholder="Select profiles to attach..."
                          />
                        </FieldContent>
                        <FieldDescription>
                          Select the profiles this application can issue certificates from. You can
                          also attach them later from the application&apos;s settings.
                        </FieldDescription>
                        {error ? <FieldError>{error.message}</FieldError> : null}
                      </Field>
                    )}
                  />
                ) : null}
              </fieldset>
            </DialogBody>
            <DialogFooter>
              <Button
                type="button"
                variant="ghost"
                isDisabled={isSubmitting}
                onClick={requestDiscard}
              >
                Cancel
              </Button>
              <Button type="submit" variant="project" isPending={isSubmitting}>
                {editing ? "Save Changes" : "Create Application"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
      <DiscardChangesAlertDialog
        open={isDiscardDialogOpen}
        onOpenChange={setIsDiscardDialogOpen}
        onDiscard={confirmDiscard}
        title="Discard Application Changes?"
        description="Your unsaved application settings will be lost."
      />
    </>
  );
};