Skip to content

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

29.6 KB
Raw Blame
import { ReactNode, useId, useMemo, useState } from "react";
import { subject } from "@casl/ability";
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useQuery } from "@tanstack/react-query";
import { Link, useParams } from "@tanstack/react-router";
import { formatDistance } from "date-fns";
import {
  CheckIcon,
  CopyIcon,
  MoreHorizontalIcon,
  PencilIcon,
  PlusIcon,
  Settings2Icon,
  Trash2Icon
} from "lucide-react";

import {
  CertificateApprovalPoliciesUpgradeIntent,
  useUpgradeGate
} from "@app/components/license/UpgradeGate";
import { createNotification } from "@app/components/notifications";
import {
  Badge,
  Button,
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Combobox,
  ConfirmationAlertDialog,
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DiscardChangesAlertDialog,
  DocumentationLinkBadge,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  Empty,
  EmptyDescription,
  EmptyHeader,
  EmptyTitle,
  Field,
  FieldLabel,
  IconButton,
  Skeleton,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from "@app/components/v3";
import { useProjectPermission, useSubscription } from "@app/context";
import {
  ProjectPermissionCertificateProfileActions,
  ProjectPermissionSub
} from "@app/context/ProjectPermissionContext/types";
import { usePopUp, useToggle } from "@app/hooks";
import {
  approvalPolicyQuery,
  ApprovalPolicyScope,
  ApprovalPolicyType,
  CertRequestPolicyConditions,
  TApprovalPolicy,
  useDeleteApprovalPolicy
} from "@app/hooks/api/approvalPolicies";
import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
import {
  PkiApplicationResourceActions,
  PkiApplicationResourceSub,
  TPkiApplication,
  TPkiApplicationProfile,
  useAttachPkiApplicationProfiles,
  useDetachPkiApplicationProfile,
  useGetPkiApplicationPermissions
} from "@app/hooks/api/pkiApplications";
import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";
import { PolicyModal } from "@app/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal";
import { CertificateAlertsCard } from "@app/pages/cert-manager/components/CertificateAlerts/CertificateAlertsCard";
import { CertificateAlertScopeKind } from "@app/pages/cert-manager/components/CertificateAlerts/types";
import { CreateProfileModal } from "@app/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal";
import { useProfileCreation } from "@app/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation";

import { PkiDocsUrls } from "../../pki-docs-urls";
import {
  ConfigureEnrollmentModal,
  EnrollmentMethod,
  METHOD_LABELS
} from "./ConfigureEnrollmentModal";
import { LegacyApplicationAlertsCard } from "./LegacyApplicationAlertsCard";

type Props = { application: TPkiApplication; profiles: TPkiApplicationProfile[] };

type TProfileOption = { value: string; label: string };

const methodBadges = (p: TPkiApplicationProfile) => {
  const methods: EnrollmentMethod[] = [];
  if (p.apiConfigId) methods.push("api");
  if (p.estConfigId) methods.push("est");
  if (p.acmeConfigId) methods.push("acme");
  if (p.scepConfigId) methods.push("scep");
  return methods;
};

const getPolicyProfileNames = (policy: TApprovalPolicy): string[] => {
  const conditions = policy.conditions.conditions as CertRequestPolicyConditions;
  return conditions.flatMap((c: { profileNames: string[] }) => c.profileNames);
};

type ApplicationPolicyActionsMenuProps = {
  policy: TApprovalPolicy;
  onEdit: (policy: TApprovalPolicy) => void;
  onDelete: (policy: TApprovalPolicy) => void;
  canEdit: boolean;
  canDelete: boolean;
};

const ApplicationPolicyActionsMenu = ({
  policy,
  onEdit,
  onDelete,
  canEdit,
  canDelete
}: ApplicationPolicyActionsMenuProps) => {
  const [isIdCopied, setIsIdCopied] = useToggle(false);

  const handleCopyId = async () => {
    try {
      await navigator.clipboard.writeText(policy.id);
      setIsIdCopied.on();
      createNotification({ type: "info", text: "Approval policy ID copied to clipboard" });
      setTimeout(() => setIsIdCopied.off(), 2000);
    } catch {
      createNotification({ type: "error", text: "Could not copy to clipboard" });
    }
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <IconButton variant="ghost" size="xs" aria-label="Policy actions">
          <MoreHorizontalIcon />
        </IconButton>
      </DropdownMenuTrigger>
      <DropdownMenuContent className="min-w-40" align="end" sideOffset={2}>
        <DropdownMenuItem onClick={handleCopyId}>
          {isIdCopied ? <CheckIcon /> : <CopyIcon />}
          Copy ID
        </DropdownMenuItem>
        <DropdownMenuItem isDisabled={!canEdit} onClick={() => onEdit(policy)}>
          <PencilIcon />
          Edit Policy
        </DropdownMenuItem>
        <DropdownMenuItem variant="danger" isDisabled={!canDelete} onClick={() => onDelete(policy)}>
          <Trash2Icon />
          Delete Policy
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};

type ApplicationPoliciesTableProps = {
  applicationId: string;
  onEdit: (policy: TApprovalPolicy) => void;
  onDelete: (policy: TApprovalPolicy) => void;
  canEdit: boolean;
  canDelete: boolean;
};

const ApplicationPoliciesTable = ({
  applicationId,
  onEdit,
  onDelete,
  canEdit,
  canDelete
}: ApplicationPoliciesTableProps) => {
  const { data: policies = [], isPending } = useQuery(
    approvalPolicyQuery.list({
      policyType: ApprovalPolicyType.CertRequest,
      scope: ApprovalPolicyScope.PkiApplication,
      scopeId: applicationId
    })
  );

  const sortedPolicies = useMemo(
    () =>
      [...policies].sort(
        (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      ),
    [policies]
  );

  if (!isPending && sortedPolicies.length === 0) {
    return (
      <Empty className="border">
        <EmptyHeader>
          <EmptyTitle>No approval policies</EmptyTitle>
          <EmptyDescription>
            Create one to require approval before certificates are issued for this application.
          </EmptyDescription>
        </EmptyHeader>
      </Empty>
    );
  }

  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Policy Name</TableHead>
          <TableHead>Profile Name</TableHead>
          <TableHead>Approval Steps</TableHead>
          <TableHead>Created</TableHead>
          <TableHead className="w-5" />
        </TableRow>
      </TableHeader>
      <TableBody>
        {isPending &&
          Array.from({ length: 3 }, (_, idx) => (
            <TableRow key={`policy-skeleton-${idx + 1}`}>
              {Array.from({ length: 5 }, (__, cellIdx) => (
                <TableCell key={`policy-skeleton-cell-${cellIdx + 1}`}>
                  <Skeleton className="h-4 w-24" />
                </TableCell>
              ))}
            </TableRow>
          ))}
        {!isPending &&
          sortedPolicies.map((policy) => {
            const profileNames = getPolicyProfileNames(policy);
            return (
              <TableRow key={policy.id}>
                <TableCell isTruncatable>
                  <div className="flex items-center gap-x-2">
                    <span className="font-medium text-foreground">{policy.name}</span>
                    {policy.scopeType !== ApprovalPolicyScope.PkiApplication ? (
                      <Badge variant="neutral" className="uppercase">
                        Legacy
                      </Badge>
                    ) : null}
                  </div>
                </TableCell>
                <TableCell>
                  <div className="flex flex-wrap items-center gap-1">
                    {profileNames.slice(0, 3).map((name) => (
                      <Badge key={name} variant="neutral">
                        {name}
                      </Badge>
                    ))}
                    {profileNames.length > 3 ? (
                      <span className="text-xs text-accent">+{profileNames.length - 3} more</span>
                    ) : null}
                  </div>
                </TableCell>
                <TableCell className="text-accent">
                  {policy.steps.length} step{policy.steps.length !== 1 ? "s" : ""}
                </TableCell>
                <TableCell className="text-accent">
                  {formatDistance(new Date(policy.createdAt), new Date(), { addSuffix: true })}
                </TableCell>
                <TableCell>
                  <ApplicationPolicyActionsMenu
                    policy={policy}
                    onEdit={onEdit}
                    onDelete={onDelete}
                    canEdit={canEdit}
                    canDelete={canDelete}
                  />
                </TableCell>
              </TableRow>
            );
          })}
      </TableBody>
    </Table>
  );
};

export const ApplicationSettingsTab = ({ application, profiles }: Props) => {
  const { orgId } = useParams({ strict: false }) as { orgId?: string };
  const { data: permissionData } = useGetPkiApplicationPermissions(application.id);
  const appAbility = permissionData?.permission;
  const canManageProfileAttachments = Boolean(
    appAbility?.can(
      PkiApplicationResourceActions.ManageProfiles,
      PkiApplicationResourceSub.Application
    )
  );
  const canConfigureEnrollment = Boolean(
    appAbility?.can(
      PkiApplicationResourceActions.Edit,
      PkiApplicationResourceSub.ApplicationEnrollment
    )
  );
  const canManagePolicies = Boolean(
    appAbility?.can(
      PkiApplicationResourceActions.Create,
      PkiApplicationResourceSub.ApprovalPolicies
    )
  );
  const canDeletePolicies = Boolean(
    appAbility?.can(
      PkiApplicationResourceActions.Delete,
      PkiApplicationResourceSub.ApprovalPolicies
    )
  );
  const canEditPolicies = Boolean(
    appAbility?.can(PkiApplicationResourceActions.Edit, PkiApplicationResourceSub.ApprovalPolicies)
  );
  const canCreateAlerts = Boolean(
    appAbility?.can(PkiApplicationResourceActions.Create, PkiApplicationResourceSub.PkiAlerts)
  );
  const canEditAlerts = Boolean(
    appAbility?.can(PkiApplicationResourceActions.Edit, PkiApplicationResourceSub.PkiAlerts)
  );
  const canDeleteAlerts = Boolean(
    appAbility?.can(PkiApplicationResourceActions.Delete, PkiApplicationResourceSub.PkiAlerts)
  );
  const [isAttachOpen, setIsAttachOpen] = useState(false);
  const [isCreateProfileOpen, setIsCreateProfileOpen] = useState(false);
  const [profilesToAttach, setProfilesToAttach] = useState<TProfileOption[]>([]);
  const profileInputId = useId();
  const closeAttach = () => {
    setIsAttachOpen(false);
    setProfilesToAttach([]);
  };
  const { requestDiscard, confirmDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen } =
    useDiscardChangesGuard({ isDirty: profilesToAttach.length > 0, onDiscard: closeAttach });
  const profileCreation = useProfileCreation((createdProfile) =>
    setProfilesToAttach((previous) => [
      ...previous,
      { value: createdProfile.id, label: createdProfile.slug }
    ])
  );
  const [profileToDetach, setProfileToDetach] = useState<TPkiApplicationProfile | null>(null);
  const [profileToConfigure, setProfileToConfigure] = useState<TPkiApplicationProfile | null>(null);
  const [enrollmentMethodToOpen, setEnrollmentMethodToOpen] = useState<EnrollmentMethod>();

  const openEnrollment = (profile: TPkiApplicationProfile, method?: EnrollmentMethod) => {
    setEnrollmentMethodToOpen(method);
    setProfileToConfigure(profile);
  };

  const { permission } = useProjectPermission();
  const canCreateAndAttachProfile =
    permission.can(
      ProjectPermissionCertificateProfileActions.Create,
      ProjectPermissionSub.CertificateProfiles
    ) &&
    permission.can(
      ProjectPermissionCertificateProfileActions.ManageApplicationAttachments,
      ProjectPermissionSub.CertificateProfiles
    );
  const validateCreatedProfileSlug = (slug: string) => {
    const profileSubject = subject(ProjectPermissionSub.CertificateProfiles, { slug });
    return canManageProfileAttachments &&
      permission.can(ProjectPermissionCertificateProfileActions.Create, profileSubject) &&
      permission.can(
        ProjectPermissionCertificateProfileActions.ManageApplicationAttachments,
        profileSubject
      )
      ? undefined
      : "You don't have permission to create and attach a profile with this name. Choose an allowed name.";
  };

  const { data: profileList } = useListCertificateProfiles({ limit: 100 });
  const attachMutation = useAttachPkiApplicationProfiles();
  const detachMutation = useDetachPkiApplicationProfile();

  const { subscription } = useSubscription();

  const { popUp, handlePopUpToggle, handlePopUpOpen, handlePopUpClose } = usePopUp([
    "policy",
    "deletePolicy"
  ] as const);
  const { openUpgradeGate, upgradeGate } = useUpgradeGate();

  // Creation only; existing policies keep enforcing and their requests can still be approved.
  const handleCreatePolicy = () => {
    if (!subscription.pkiApprovals) {
      openUpgradeGate({
        intent: CertificateApprovalPoliciesUpgradeIntent,
        paywallKey: "cert-manager.application-settings"
      });
      return;
    }
    handlePopUpOpen("policy");
  };
  const deletePolicy = useDeleteApprovalPolicy();

  const handleDeletePolicy = async () => {
    const p = popUp.deletePolicy.data as { policyId: string } | undefined;
    if (!p?.policyId) return;
    try {
      await deletePolicy.mutateAsync({
        policyType: ApprovalPolicyType.CertRequest,
        policyId: p.policyId
      });
      createNotification({ type: "success", text: "Policy deleted" });
      handlePopUpClose("deletePolicy");
    } catch (err) {
      createNotification({
        type: "error",
        text: err instanceof Error ? err.message : "Failed to delete policy"
      });
    }
  };

  const attachedIds = useMemo(() => new Set(profiles.map((p) => p.profileId)), [profiles]);
  const availableProfiles = useMemo(
    () =>
      (profileList?.certificateProfiles ?? [])
        .filter((p) => !attachedIds.has(p.id))
        .map((p) => ({ value: p.id, label: p.slug })),
    [profileList, attachedIds]
  );
  // Project-wide count, not the length of the fetched page. The list is paginated, so a page whose
  // profiles happen to all be attached says nothing about whether the project has others left.
  const totalProfileCount = profileList?.totalCount ?? 0;
  const hasAttachableProfiles = totalProfileCount > profiles.length;
  let attachDisabledReason: ReactNode | null = null;
  if (!hasAttachableProfiles && !canCreateAndAttachProfile) {
    attachDisabledReason =
      totalProfileCount === 0
        ? "No certificate profiles exist yet, and you do not have permission to create and attach one."
        : "All certificate profiles are already attached.";
  }

  const handleAttach = async () => {
    if (profilesToAttach.length === 0) return;
    try {
      await attachMutation.mutateAsync({
        applicationId: application.id,
        profileIds: profilesToAttach.map((p) => p.value)
      });
      createNotification({ type: "success", text: "Profile(s) attached" });
      setProfilesToAttach([]);
      setIsAttachOpen(false);
    } catch (err) {
      createNotification({
        type: "error",
        text: err instanceof Error ? err.message : "Failed to attach profile(s)"
      });
    }
  };

  const handleDetach = async () => {
    if (!profileToDetach) return;
    try {
      await detachMutation.mutateAsync({
        applicationId: application.id,
        profileId: profileToDetach.profileId
      });
      createNotification({ type: "success", text: "Profile detached" });
      setProfileToDetach(null);
    } catch (err) {
      createNotification({
        type: "error",
        text: err instanceof Error ? err.message : "Failed to detach profile"
      });
    }
  };

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle>
            Certificate Profiles
            <DocumentationLinkBadge href={PkiDocsUrls.applications.enrollment.overview} />
          </CardTitle>
          <CardDescription>
            For each profile, configure how this application will issue certificates via API, EST,
            ACME, or SCEP.
          </CardDescription>
          {canManageProfileAttachments ? (
            <CardAction>
              {attachDisabledReason ? (
                <Tooltip>
                  <TooltipTrigger asChild>
                    {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- focusable wrapper required so the tooltip surfaces on keyboard focus despite the inner button being disabled */}
                    <span tabIndex={0}>
                      <Button variant="outline" isDisabled>
                        <PlusIcon />
                        Attach Profile
                      </Button>
                    </span>
                  </TooltipTrigger>
                  <TooltipContent side="left" className="max-w-xs">
                    {attachDisabledReason}
                  </TooltipContent>
                </Tooltip>
              ) : (
                <Button
                  variant="outline"
                  onClick={() =>
                    hasAttachableProfiles ? setIsAttachOpen(true) : setIsCreateProfileOpen(true)
                  }
                >
                  <PlusIcon />
                  {hasAttachableProfiles ? "Attach Profile" : "Create Profile"}
                </Button>
              )}
            </CardAction>
          ) : null}
        </CardHeader>
        <CardContent>
          {profiles.length === 0 ? (
            <Empty className="border">
              <EmptyHeader>
                <EmptyTitle>No profiles attached</EmptyTitle>
                <EmptyDescription>
                  {totalProfileCount === 0
                    ? "Create a certificate profile, then configure how this application enrolls against it."
                    : "Attach a certificate profile, then configure how this application enrolls against it."}
                </EmptyDescription>
              </EmptyHeader>
            </Empty>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-1/2">Profile</TableHead>
                  <TableHead className="w-1/2">Enrollment Methods</TableHead>
                  <TableHead className="w-5" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {profiles.map((p) => {
                  const methods = methodBadges(p);
                  const hasMethods = methods.length > 0;
                  return (
                    <TableRow key={p.profileId}>
                      <TableCell className="font-mono">
                        <Link
                          to="/organizations/$orgId/cert-manager/certificate-profiles/$profileId"
                          params={{
                            orgId: orgId ?? "",
                            profileId: p.profileId
                          }}
                          search={{ from: "application", applicationName: application.name }}
                          className="hover:underline"
                        >
                          {p.profileSlug}
                        </Link>
                      </TableCell>
                      <TableCell>
                        {/* eslint-disable-next-line no-nested-ternary */}
                        {canConfigureEnrollment ? (
                          <div className="flex flex-wrap items-center gap-1.5">
                            {hasMethods ? (
                              methods.map((m) => (
                                <Badge key={m} variant="neutral" asChild>
                                  <button
                                    type="button"
                                    onClick={() => openEnrollment(p, m)}
                                    aria-label={`Edit ${METHOD_LABELS[m]} enrollment for ${p.profileSlug}`}
                                  >
                                    {METHOD_LABELS[m]}
                                  </button>
                                </Badge>
                              ))
                            ) : (
                              <button
                                type="button"
                                onClick={() => openEnrollment(p)}
                                aria-label={`Configure enrollment for ${p.profileSlug}`}
                                className="flex cursor-pointer items-center gap-1.5 text-sm text-muted transition-colors hover:text-foreground"
                              >
                                <Settings2Icon className="size-3.5" />
                                Configure
                              </button>
                            )}
                          </div>
                        ) : hasMethods ? (
                          <div className="flex flex-wrap gap-1.5">
                            {methods.map((m) => (
                              <Badge key={m} variant="neutral">
                                {METHOD_LABELS[m]}
                              </Badge>
                            ))}
                          </div>
                        ) : (
                          <span className="text-xs text-accent">—</span>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        {canConfigureEnrollment || canManageProfileAttachments ? (
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <IconButton variant="ghost" size="xs">
                                <MoreHorizontalIcon />
                              </IconButton>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent className="min-w-48" align="end" sideOffset={2}>
                              {canConfigureEnrollment ? (
                                <DropdownMenuItem onClick={() => openEnrollment(p)}>
                                  <PencilIcon />
                                  Configure Enrollment
                                </DropdownMenuItem>
                              ) : null}
                              {canManageProfileAttachments ? (
                                <DropdownMenuItem
                                  variant="danger"
                                  onClick={() => setProfileToDetach(p)}
                                >
                                  <Trash2Icon />
                                  Detach Profile
                                </DropdownMenuItem>
                              ) : null}
                            </DropdownMenuContent>
                          </DropdownMenu>
                        ) : null}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>
            Approval Policies
            <DocumentationLinkBadge href={PkiDocsUrls.applications.approvals} />
          </CardTitle>
          <CardDescription>
            Require approval before certificates are issued for this application.
          </CardDescription>
          <CardAction>
            <Tooltip>
              <TooltipTrigger asChild>
                {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- focusable wrapper required so the tooltip surfaces on keyboard focus despite the inner button being disabled */}
                <span tabIndex={0}>
                  <Button
                    variant="outline"
                    onClick={handleCreatePolicy}
                    isDisabled={!canManagePolicies}
                  >
                    <FontAwesomeIcon icon={faPlus} />
                    Create Policy
                  </Button>
                </span>
              </TooltipTrigger>
              {!canManagePolicies && (
                <TooltipContent side="left">
                  You don&apos;t have permission to create policies
                </TooltipContent>
              )}
            </Tooltip>
          </CardAction>
        </CardHeader>
        <CardContent>
          <ApplicationPoliciesTable
            applicationId={application.id}
            onEdit={(policy) => handlePopUpOpen("policy", { policyId: policy.id, policy })}
            onDelete={(policy) => handlePopUpOpen("deletePolicy", { policyId: policy.id })}
            canEdit={canEditPolicies}
            canDelete={canDeletePolicies}
          />
        </CardContent>
      </Card>

      <CertificateAlertsCard
        projectId={application.projectId}
        scope={{
          kind: CertificateAlertScopeKind.Application,
          applicationId: application.id,
          applicationName: application.name
        }}
        canCreate={canCreateAlerts}
        canEdit={canEditAlerts}
        canDelete={canDeleteAlerts}
      />
      <LegacyApplicationAlertsCard applicationId={application.id} canDelete={canDeleteAlerts} />

      <PolicyModal
        popUp={popUp}
        handlePopUpToggle={handlePopUpToggle}
        applicationId={application.id}
      />
      {upgradeGate}
      <ConfirmationAlertDialog
        isOpen={popUp.deletePolicy.isOpen}
        description="This action is irreversible."
        confirmKey="delete"
        title={`Delete approval policy ${(popUp.deletePolicy.data as TApprovalPolicy | undefined)?.name ?? ""}?`}
        onOpenChange={(isOpen) => handlePopUpToggle("deletePolicy", isOpen)}
        onConfirm={handleDeletePolicy}
      />

      <Dialog
        open={isAttachOpen}
        onOpenChange={(open) => {
          if (open) setIsAttachOpen(true);
          else requestDiscard();
        }}
      >
        <DialogContent isPending={attachMutation.isPending}>
          <DialogHeader>
            <DialogTitle>Attach Profiles</DialogTitle>
            <DialogDescription>
              Select one or more profiles to attach to this application.
            </DialogDescription>
          </DialogHeader>
          <form
            className="flex min-h-0 flex-1 flex-col gap-6"
            onSubmit={(event) => {
              event.preventDefault();
              if (profilesToAttach.length && !attachMutation.isPending) handleAttach();
            }}
          >
            <DialogBody>
              <fieldset disabled={attachMutation.isPending} className="min-w-0">
                <Field>
                  <FieldLabel htmlFor={profileInputId}>Certificate Profiles</FieldLabel>
                  <Combobox
                    id={profileInputId}
                    multiple
                    value={profilesToAttach}
                    onValueChange={setProfilesToAttach}
                    getOptionValue={(option) => option.value}
                    getOptionLabel={(option) => option.label}
                    options={availableProfiles}
                    creation={profileCreation}
                    placeholder="Select profiles..."
                  />
                </Field>
              </fieldset>
            </DialogBody>
            <DialogFooter>
              <Button
                variant="ghost"
                isDisabled={attachMutation.isPending}
                onClick={requestDiscard}
              >
                Cancel
              </Button>
              <Button
                variant="project"
                type="submit"
                isDisabled={profilesToAttach.length === 0 || attachMutation.isPending}
                isPending={attachMutation.isPending}
              >
                Attach
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
      <DiscardChangesAlertDialog
        open={isDiscardDialogOpen}
        onOpenChange={setIsDiscardDialogOpen}
        onDiscard={confirmDiscard}
        title="Discard Profile Selection?"
        description="Your pending profile attachments will be lost."
      />

      <ConfirmationAlertDialog
        isOpen={Boolean(profileToDetach)}
        title={`Detach profile ${profileToDetach?.profileSlug ?? ""}?`}
        description="This application will no longer be able to issue from this Profile. Existing certificates remain."
        confirmKey="confirm"
        onOpenChange={(open) => {
          if (!open) setProfileToDetach(null);
        }}
        onConfirm={handleDetach}
      />

      <CreateProfileModal
        isOpen={isCreateProfileOpen}
        onClose={() => setIsCreateProfileOpen(false)}
        validateSlug={validateCreatedProfileSlug}
        onComplete={async (createdProfile) => {
          if (
            !canManageProfileAttachments ||
            !permission.can(
              ProjectPermissionCertificateProfileActions.ManageApplicationAttachments,
              subject(ProjectPermissionSub.CertificateProfiles, { slug: createdProfile.slug })
            )
          ) {
            throw new Error(
              "The profile was created, but you no longer have permission to attach it to this application."
            );
          }
          await attachMutation.mutateAsync({
            applicationId: application.id,
            profileIds: [createdProfile.id]
          });
        }}
      />

      <ConfigureEnrollmentModal
        isOpen={Boolean(profileToConfigure)}
        onOpenChange={(open) => {
          if (!open) {
            setProfileToConfigure(null);
            setEnrollmentMethodToOpen(undefined);
          }
        }}
        applicationId={application.id}
        profile={profileToConfigure}
        initialMethod={enrollmentMethodToOpen}
      />
    </div>
  );
};