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
improvement(cert-manager): migrate CA and profile creation to v3 (#8846)
Andrew Huangeee37767f98a
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsxindex 7904083d7f..a6977e44c6 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsx@@ -2,14 +2,15 @@ import { useMemo, useState } from "react";import { useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { format } from "date-fns";-import { ShieldIcon } from "lucide-react";import { createNotification } from "@app/components/notifications";import {Button,+ DiscardChangesAlertDialog,DocumentationLinkBadge,Sheet,SheetContent,+ SheetDescription,SheetFooter,SheetHeader,SheetTitle,@@ -22,9 +23,11 @@ import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { useCreateCa } from "@app/hooks/api/ca";import { CaStatus, CaType, InternalCaType } from "@app/hooks/api/ca/enums";+import { TUnifiedCertificateAuthority } from "@app/hooks/api/ca/types";import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";import { useListHsmConnectors } from "@app/hooks/api/hsmConnectors";import { CertKeySource } from "@app/hooks/api/signers";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";import { PkiDocsUrls } from "../../../pki-docs-urls";import { BasicsStep } from "./BasicsStep";@@ -37,6 +40,7 @@ import { STEPS } from "./types";type Props = {isOpen: boolean;onOpenChange: (open: boolean) => void;+ onComplete?: (createdCA: TUnifiedCertificateAuthority) => void | Promise<void>;};const getDateTenYearsFromToday = () => {@@ -81,10 +85,12 @@ const STEP_FIELDS: (keyof CaWizardForm)[][] = [["crlDistributionPointUrls"]];-export const CreateCaWizard = ({ isOpen, onOpenChange }: Props) => {+export const CreateCaWizard = ({ isOpen, onOpenChange, onComplete }: Props) => {const [step, setStep] = useState(0);+ const [isCompleting, setIsCompleting] = useState(false);const { subscription } = useSubscription();const createCa = useCreateCa();+ const isPending = createCa.isPending || isCompleting;const { data: hsmConnectors = [], isPending: isHsmConnectorsLoading } = useListHsmConnectors({enabled: Boolean(subscription?.hsm)@@ -116,16 +122,25 @@ export const CreateCaWizard = ({ isOpen, onOpenChange }: Props) => {form.reset(buildDefaultValues());};+ const { isDiscardDialogOpen, setIsDiscardDialogOpen, requestDiscard, confirmDiscard } =+ useDiscardChangesGuard({+ isDirty: form.formState.isDirty || step > 0,+ onDiscard: () => {+ reset();+ onOpenChange(false);+ }+ });const handleClose = (open: boolean) => {- if (!open) reset();- onOpenChange(open);+ if (isPending) return;+ if (open) onOpenChange(true);+ else requestDiscard();};const onCreate = async () => {const values = form.getValues();const isRoot = values.type === InternalCaType.ROOT;try {- await createCa.mutateAsync({+ const createdCA = await createCa.mutateAsync({name: values.name,type: CaType.INTERNAL,status: CaStatus.ACTIVE,@@ -156,18 +171,24 @@ export const CreateCaWizard = ({ isOpen, onOpenChange }: Props) => {});createNotification({ text: "Successfully created CA", type: "success" });- handleClose(false);+ setIsCompleting(true);+ await onComplete?.(createdCA);+ reset();+ onOpenChange(false);} catch (err) {createNotification({type: "error",text: err instanceof Error ? err.message : "Failed to create CA"});+ } finally {+ setIsCompleting(false);}};const isLast = step === STEPS.length - 1;const goNext = async () => {+ if (isPending) return;const ok = await form.trigger(STEP_FIELDS[step]);if (!ok) return;if (isLast) {@@ -178,115 +199,123 @@ export const CreateCaWizard = ({ isOpen, onOpenChange }: Props) => {};const goBack = () => {- if (step > 0) setStep((s) => s - 1);+ if (step > 0 && !isPending) setStep((s) => s - 1);};const currentStep = STEPS[step];const ctaLabel = isLast ? "Create CA" : "Continue";return (- <Sheet open={isOpen} onOpenChange={handleClose}>- <SheetContent size="workspace" className="flex h-full max-h-full flex-col gap-y-0">- <SheetHeader className="border-b">- <SheetTitle>- <div className="flex w-full items-start gap-2">- <div className="flex h-10 w-10 items-center justify-center rounded-md bg-project/10 text-project">- <ShieldIcon className="h-5 w-5" />- </div>- <div>- <div className="flex items-center gap-x-2 text-label">- Create Internal CA- <DocumentationLinkBadge href={PkiDocsUrls.ca.internal} />- </div>- <p className="text-sm leading-4 text-muted">- A private Certificate Authority hosted by Infisical, with its signing key managed- by Infisical, kept in your HSM, or kept in AWS KMS.+ <>+ <Sheet open={isOpen} onOpenChange={handleClose}>+ <SheetContent size="workspace" isPending={isPending}>+ <SheetHeader>+ <SheetTitle className="flex items-center gap-2">+ Create Internal CA+ <DocumentationLinkBadge href={PkiDocsUrls.ca.internal} />+ </SheetTitle>+ <SheetDescription>+ A private Certificate Authority hosted by Infisical, with its signing key managed by+ Infisical, kept in your HSM, or kept in AWS KMS.+ </SheetDescription>+ </SheetHeader>++ <div className="flex min-h-0 flex-1 flex-col">+ <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>- </div>- </div>- </SheetTitle>- </SheetHeader>+ <Stepper+ activeStep={step}+ orientation="vertical"+ onStepChange={(i) => {+ if (i < step && !isPending) setStep(i);+ }}+ >+ <StepperList>+ {STEPS.map((s, i) => (+ <StepperStep+ key={s.name}+ index={i}+ title={s.name}+ description={s.shortDescription}+ />+ ))}+ </StepperList>+ </Stepper>+ </aside>- <div className="flex min-h-0 flex-1 flex-col">- <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={step}- orientation="vertical"- onStepChange={(i) => {- if (i < step) setStep(i);- }}+ <fieldset+ disabled={isPending}+ className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">- <StepperList>- {STEPS.map((s, i) => (- <StepperStep- key={s.name}- index={i}- title={s.name}- description={s.shortDescription}- />- ))}- </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>+ <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>- {step === 0 && <BasicsStep form={form} />}- {step === 1 && <SubjectStep form={form} />}- {step === 2 && (- <KeyValidityStep- form={form}- hsmConnectorOptions={hsmConnectorOptions}- isHsmConnectorsLoading={isHsmConnectorsLoading}- awsConnectionOptions={awsConnections}- isAwsConnectionsLoading={isAwsConnectionsLoading}- />- )}- {step === 3 && <DistributionStep form={form} />}- </div>+ {step === 0 && <BasicsStep form={form} />}+ {step === 1 && <SubjectStep form={form} />}+ {step === 2 && (+ <KeyValidityStep+ form={form}+ hsmConnectorOptions={hsmConnectorOptions}+ isHsmConnectorsLoading={isHsmConnectorsLoading}+ awsConnectionOptions={awsConnections}+ isAwsConnectionsLoading={isAwsConnectionsLoading}+ />+ )}+ {step === 3 && <DistributionStep form={form} />}+ </fieldset>- <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 {step + 1} · {currentStep.rightLabel}+ <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 {step + 1} · {currentStep.rightLabel}+ </p>+ <DocumentationLinkBadge href={currentStep.docsUrl} />+ </div>+ <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>+ <p className="mt-2 text-sm leading-relaxed text-muted">+ {currentStep.rightDescription}</p>- <DocumentationLinkBadge href={currentStep.docsUrl} /></div>- <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>- <p className="mt-2 text-sm leading-relaxed text-muted">- {currentStep.rightDescription}- </p>- </div>- </aside>- </div>+ </aside>+ </div>- <SheetFooter className="shrink-0 items-center justify-between border-t">- <span className="text-xs text-muted" />- <div className="flex items-center gap-3">- <span className="text-xs text-muted">- Step {step + 1} of {STEPS.length}- </span>+ <SheetFooter className="items-center justify-end border-t">{step > 0 && (- <Button variant="outline" onClick={goBack}>+ <Button+ variant="outline"+ className="mr-auto"+ onClick={goBack}+ isDisabled={isPending}+ >Back</Button>)}- <Button variant="project" onClick={goNext} isPending={createCa.isPending}>+ <span className="text-xs text-muted">+ Step {step + 1} of {STEPS.length}+ </span>+ <Button variant="ghost" onClick={() => handleClose(false)} isDisabled={isPending}>+ Cancel+ </Button>+ <Button variant="project" onClick={goNext} isPending={isPending}>{ctaLabel}</Button>- </div>- </SheetFooter>- </div>- </SheetContent>- </Sheet>+ </SheetFooter>+ </div>+ </SheetContent>+ </Sheet>+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Changes?"+ description="Your certificate authority setup changes will be lost."+ />+ </>);};diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsxindex 40e8cb3ef9..bdc7115531 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx@@ -1,8 +1,7 @@import { useState } from "react";import { Controller, UseFormReturn } from "react-hook-form";-import { SingleValue } from "react-select";-import { AppConnectionOption } from "@app/components/app-connections";+import { AppConnectionOptionContent } from "@app/components/app-connections";import {PostQuantumCertificatesUpgradeIntent,useUpgradeGate@@ -10,13 +9,13 @@ import {import { AwsRegionSelect } from "@app/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect";import {Badge,+ Combobox,Field,FieldContent,FieldDescription,FieldError,FieldGroup,FieldLabel,- FilterableSelect,Input,Select,SelectContent,@@ -24,29 +23,23 @@ import {SelectTrigger,SelectValue} from "@app/components/v3";-import { useProject, useProjectPermission, useSubscription } from "@app/context";+import { useProjectPermission, useSubscription } from "@app/context";import {- ProjectPermissionAppConnectionActions,ProjectPermissionHsmConnectorActions,ProjectPermissionSub} from "@app/context/ProjectPermissionContext/types";-import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";import { TAvailableAppConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { InternalCaType } from "@app/hooks/api/ca/enums";import { certKeyAlgorithms, isPqcAlgorithm } from "@app/hooks/api/certificates/constants";import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";import { CertKeySource } from "@app/hooks/api/signers";-import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";+import { CreateHsmConnectorWizard } from "@app/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard";+import { useConnectionCreation } from "../CaInstallCertModal/useConnectionCreation";import { CaWizardForm } from "./schemas";import { HsmConnectorOption, isKeyAlgorithmSupportedByKeySource } from "./types";-const CREATE_AWS_CONNECTION_OPTION = {- id: `_create:${AppConnection.AWS}`,- name: `Create ${APP_CONNECTION_MAP[AppConnection.AWS].name} Connection`-};-const KEY_SOURCE_DESCRIPTIONS: Record<CertKeySource, string> = {[CertKeySource.Infisical]: "Infisical generates and manages the CA keypair for you.",[CertKeySource.Hsm]:@@ -74,20 +67,24 @@ export const KeyValidityStep = ({const { openUpgradeGate, upgradeGate } = useUpgradeGate();const isHsmLicensed = Boolean(subscription?.hsm);const isAwsKmsLicensed = Boolean(subscription?.pkiAwsKmsSigning);- const { currentProject } = useProject();const { permission } = useProjectPermission();- const [isCreateAwsConnectionOpen, setIsCreateAwsConnectionOpen] = useState(false);const [createdAwsConnection, setCreatedAwsConnection] = useState<TAvailableAppConnection | null>(null);- const canCreateAppConnection = permission.can(- ProjectPermissionAppConnectionActions.Create,- ProjectPermissionSub.AppConnections- );+ const [isCreateHsmConnectorOpen, setIsCreateHsmConnectorOpen] = useState(false);+ const [createdHsmConnector, setCreatedHsmConnector] = useState<HsmConnectorOption | null>(null);+ const connectionCreation = useConnectionCreation(AppConnection.AWS, (connection) => {+ setCreatedAwsConnection(connection);+ form.setValue("appConnectionId", connection.id, { shouldValidate: true });+ });const canAttachHsm = permission.can(ProjectPermissionHsmConnectorActions.Attach,ProjectPermissionSub.HsmConnectors);+ const canCreateHsm = permission.can(+ ProjectPermissionHsmConnectorActions.Create,+ ProjectPermissionSub.HsmConnectors+ );const keySource = form.watch("keySource");const caType = form.watch("type");@@ -160,18 +157,35 @@ export const KeyValidityStep = ({HSM Connector <span className="text-danger">*</span></FieldLabel><FieldContent>- <FilterableSelect<HsmConnectorOption>+ <Combobox<HsmConnectorOption>+ isClearable={false}+ name={field.name}+ onBlur={field.onBlur}+ ref={field.ref}isLoading={isHsmConnectorsLoading}options={hsmConnectorOptions}- value={hsmConnectorOptions.find((o) => o.id === field.value) ?? null}- onChange={(selected) => {- const opt = selected as HsmConnectorOption | null;- field.onChange(opt?.id ?? null);+ value={+ [...hsmConnectorOptions, createdHsmConnector].find(+ (option) => option?.id === field.value+ ) ?? null+ }+ onValueChange={(selected) => {+ field.onChange(selected.id);}}getOptionLabel={(opt) => `${opt.name} (${opt.slotLabel})`}getOptionValue={(opt) => opt.id}placeholder="Select an HSM Connector..."- noOptionsMessage={() =>+ creation={+ isHsmLicensed && canAttachHsm && canCreateHsm+ ? {+ mode: "action",+ emptyLabel: "Create HSM Connector",+ formatLabel: () => "Create HSM Connector",+ onAction: () => setIsCreateHsmConnectorOpen(true)+ }+ : undefined+ }+ emptyMessage={() =>hsmConnectorOptions.length === 0? "No HSM Connectors configured. Add one in Cert Manager Settings → HSM Connectors.": "No match."@@ -199,30 +213,28 @@ export const KeyValidityStep = ({AWS Connection <span className="text-danger">*</span></FieldLabel><FieldContent>- <FilterableSelect+ <Combobox+ isClearable={false}+ includeMissingSelectedOptions={false}+ name={field.name}+ onBlur={field.onBlur}+ ref={field.ref}isLoading={isAwsConnectionsLoading}- options={[- ...(canCreateAppConnection ? [CREATE_AWS_CONNECTION_OPTION] : []),- ...awsConnectionOptions- ]}+ options={awsConnectionOptions}value={[...awsConnectionOptions, createdAwsConnection].find((option) => option?.id === field.value) ?? null}- onChange={(newValue) => {- const selected = newValue as SingleValue<{ id: string }>;- if (selected?.id === CREATE_AWS_CONNECTION_OPTION.id) {- setIsCreateAwsConnectionOpen(true);- return;- }- field.onChange(selected?.id ?? null);+ onValueChange={(selected) => {+ field.onChange(selected.id);}}getOptionLabel={(option) => option.name}getOptionValue={(option) => option.id}- components={{ Option: AppConnectionOption }}+ renderOption={(option) => <AppConnectionOptionContent data={option} />}+ creation={connectionCreation}placeholder="Select an AWS connection..."- noOptionsMessage={() =>+ emptyMessage={() =>"No AWS connections available. Contact an admin to create one."}isError={Boolean(error)}@@ -364,20 +376,22 @@ export const KeyValidityStep = ({/></>)}- {isAwsKms && (- <AddAppConnectionModal- isOpen={isCreateAwsConnectionOpen}- onOpenChange={setIsCreateAwsConnectionOpen}- projectType={currentProject.type}- projectId={currentProject.id}- app={AppConnection.AWS}- onComplete={(connection) => {- setCreatedAwsConnection(connection);- form.setValue("appConnectionId", connection.id, { shouldValidate: true });- }}- />- )}{upgradeGate}+ <CreateHsmConnectorWizard+ isOpen={isCreateHsmConnectorOpen}+ onOpenChange={setIsCreateHsmConnectorOpen}+ onCreated={(connector) => {+ setCreatedHsmConnector({+ id: connector.id,+ name: connector.name,+ slotLabel: connector.slotLabel+ });+ form.setValue("hsmConnectorId", connector.id, {+ shouldDirty: true,+ shouldValidate: true+ });+ }}+ /></FieldGroup>);};diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AcmeFields.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AcmeFields.tsxindex 3fbf3696a9..539ccfeb2a 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AcmeFields.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AcmeFields.tsx@@ -1,12 +1,11 @@import { Control, Controller, UseFormSetValue } from "react-hook-form";-import { SingleValue } from "react-select";import { Info } from "lucide-react";import {+ Combobox,Field,FieldError,FieldLabel,- FilterableSelect,Input,Select,SelectContent,@@ -127,7 +126,7 @@ export const AcmeFields = ({<Controllername="configuration.dnsProviderConfig.hostedZoneId"control={control}- render={({ field: { value, onChange }, fieldState: { error } }) => (+ render={({ field: { value, onChange, ref }, fieldState: { error } }) => (<Field className="mb-4"><FieldLabel>Zone <span className="text-danger">*</span>@@ -141,15 +140,18 @@ export const AcmeFields = ({</TooltipContent></Tooltip></FieldLabel>- <FilterableSelect+ <Combobox+ isClearable={false}+ includeMissingSelectedOptions={false}+ ref={ref}isLoading={isZonesPending && !!dnsAppConnection.id}isDisabled={!dnsAppConnection.id}value={zones.find((zone) => zone.id === value) ||(value ? { id: value, name: value } : null)}- onChange={(option) => {- onChange((option as SingleValue<TAcmeDnsZone>)?.id ?? null);+ onValueChange={(option) => {+ onChange(option.id);}}options={zones}placeholder="Select a zone..."diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AdcsFields.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AdcsFields.tsxindex e2ed35e671..2c54ce6851 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AdcsFields.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AdcsFields.tsx@@ -28,7 +28,6 @@ export const AdcsFields = ({ control, availableConnections, isPending }: Props)name="configuration.adcsConnection"label="ADCS Connection"required- menuPlacement="top"options={availableConnections}isLoading={isPending}tooltip="ADCS App Connection contains the Windows domain credentials and Gateway used to reach the AD CS server."diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AppConnectionSelectField.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AppConnectionSelectField.tsxindex e2ff9296db..4758284c97 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AppConnectionSelectField.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AppConnectionSelectField.tsx@@ -1,30 +1,34 @@-import { ReactNode, useState } from "react";+import { ReactNode, useId } from "react";import { Control, FieldPath, useController } from "react-hook-form";-import { SingleValue } from "react-select";import { Info } from "lucide-react";-import { AppConnectionOption } from "@app/components/app-connections";+import { AppConnectionOptionContent } from "@app/components/app-connections";import {+ Combobox,Field,FieldError,FieldLabel,- FilterableSelect,Tooltip,TooltipContent,TooltipTrigger} from "@app/components/v3";-import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";-import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";-import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";import { TAvailableAppConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";-import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";+import { useConnectionCreation } from "../CaInstallCertModal/useConnectionCreation";import { FormData } from "./schema";type AppConnectionValue = { id: string; name: string };-const CREATE_CONNECTION_OPTION_PREFIX = "_create:";+const CONNECTION_APPS: Partial<Record<FieldPath<FormData>, AppConnection>> = {+ "configuration.adcsConnection": AppConnection.ADCS,+ "configuration.azureAdcsConnection": AppConnection.AzureADCS,+ "configuration.awsConnection": AppConnection.AWS,+ "configuration.dnsConnection": AppConnection.AWS,+ "configuration.digicertConnection": AppConnection.DigiCert,+ "configuration.godaddyConnection": AppConnection.GoDaddy,+ "configuration.venafiTppConnection": AppConnection.VenafiTpp+};type Props = {control: Control<FormData>;@@ -34,7 +38,6 @@ type Props = {options: TAvailableAppConnection[];isLoading: boolean;required?: boolean;- menuPlacement?: "top" | "bottom" | "auto";onAfterChange?: () => void;createApp?: AppConnection;};@@ -47,92 +50,59 @@ export const AppConnectionSelectField = ({options,isLoading,required,- menuPlacement,onAfterChange,createApp}: Props) => {- const { currentProject } = useProject();- const { permission } = useProjectPermission();- const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);-+ const inputId = useId();const {- field: { value, onChange },+ field: { value, onChange, onBlur, ref },fieldState: { error }} = useController({ control, name });- const canCreateConnection =- Boolean(createApp) &&- permission.can(- ProjectPermissionAppConnectionActions.Create,- ProjectPermissionSub.AppConnections- );-- const selectOptions: AppConnectionValue[] = [- ...(canCreateConnection && createApp- ? [- {- id: `${CREATE_CONNECTION_OPTION_PREFIX}${createApp}`,- name: `Create ${APP_CONNECTION_MAP[createApp].name} Connection`- }- ]- : []),- ...options- ];+ const connectionCreation = useConnectionCreation(+ createApp ?? CONNECTION_APPS[name],+ (connection) => {+ onChange({ id: connection.id, name: connection.name });+ onAfterChange?.();+ }+ );return (- <>- <Field className="mb-4">- <FieldLabel>- {label} {required && <span className="text-danger">*</span>}- <Tooltip>- <TooltipTrigger asChild>- <Info />- </TooltipTrigger>- <TooltipContent className="max-w-sm">{tooltip}</TooltipContent>- </Tooltip>- </FieldLabel>- <FilterableSelect- {...(menuPlacement ? { menuPlacement } : {})}- value={(value as AppConnectionValue)?.id ? (value as AppConnectionValue) : null}- onChange={(newValue) => {- if (- (newValue as SingleValue<AppConnectionValue>)?.id?.startsWith(- CREATE_CONNECTION_OPTION_PREFIX- )- ) {- setIsCreateModalOpen(true);- return;- }- onChange(newValue);- onAfterChange?.();- }}- isLoading={isLoading}- options={selectOptions}- placeholder="Select connection..."- getOptionLabel={(option) => option.name}- getOptionValue={(option) => option.id}- components={{ Option: AppConnectionOption }}- isError={Boolean(error)}- />- <FieldError errors={[error]} />- </Field>- {createApp && (- // the modal portals out of the DOM but React still bubbles its submit to the CA form- <div className="contents" onSubmit={(e) => e.stopPropagation()}>- <AddAppConnectionModal- isOpen={isCreateModalOpen}- onOpenChange={setIsCreateModalOpen}- projectType={currentProject.type}- projectId={currentProject.id}- app={createApp}- onComplete={(connection) => {- if (!connection) return;- onChange({ id: connection.id, name: connection.name });- onAfterChange?.();- }}- />- </div>- )}- </>+ <Field className="mb-4">+ <FieldLabel htmlFor={inputId}>+ {label} {required && <span className="text-danger">*</span>}+ <Tooltip>+ <TooltipTrigger asChild>+ <Info />+ </TooltipTrigger>+ <TooltipContent className="max-w-sm">{tooltip}</TooltipContent>+ </Tooltip>+ </FieldLabel>+ <Combobox<AppConnectionValue & { projectId?: string | null }>+ id={inputId}+ isClearable={false}+ includeMissingSelectedOptions={false}+ name={name}+ onBlur={onBlur}+ ref={ref}+ value={+ options.find((option) => option.id === (value as AppConnectionValue)?.id) ??+ ((value as AppConnectionValue)?.id ? (value as AppConnectionValue) : null)+ }+ onValueChange={(newValue) => {+ onChange(newValue);+ onAfterChange?.();+ }}+ isLoading={isLoading}+ options={options}+ placeholder="Select connection..."+ getOptionLabel={(option) => option.name}+ getOptionValue={(option) => option.id}+ renderOption={(option) => <AppConnectionOptionContent data={option} />}+ creation={connectionCreation}+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </Field>);};diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AzureAdCsFields.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AzureAdCsFields.tsxindex 83a0f03082..a1c5a78c1f 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AzureAdCsFields.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AzureAdCsFields.tsx@@ -16,7 +16,6 @@ export const AzureAdCsFields = ({ control, availableConnections, isPending }: Prcontrol={control}name="configuration.azureAdcsConnection"label="Azure ADCS Connection"- menuPlacement="top"options={availableConnections}isLoading={isPending}tooltip="Azure ADCS App Connection contains the Windows domain credentials and ADCS server URL for certificate requests."diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/DigiCertFields.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/DigiCertFields.tsxindex a1327d23bf..ae4d649749 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/DigiCertFields.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/DigiCertFields.tsx@@ -1,12 +1,11 @@import { Control, Controller, UseFormSetValue } from "react-hook-form";-import { SingleValue } from "react-select";import { Info } from "lucide-react";import {+ Combobox,Field,FieldError,FieldLabel,- FilterableSelect,Input,Tooltip,TooltipContent,@@ -65,7 +64,7 @@ export const DigiCertFields = ({<Controllercontrol={control}name="configuration.organizationId"- render={({ field: { value }, fieldState: { error } }) => (+ render={({ field: { value, onChange, onBlur, ref }, fieldState: { error } }) => (<Field className="mb-4"><FieldLabel>Organization <span className="text-danger">*</span>@@ -78,16 +77,16 @@ export const DigiCertFields = ({</TooltipContent></Tooltip></FieldLabel>- <FilterableSelect+ <Combobox+ isClearable={false}isLoading={isDigiCertOrgsPending && !!digicertConnectionId}isDisabled={!digicertConnectionId}value={digicertOrganizations.find((org) => org.id === value) ?? null}- onChange={(option) => {- setValue(- "configuration.organizationId",- (option as SingleValue<TDigiCertOrganization>)?.id ?? 0- );+ onValueChange={(option) => {+ onChange(option.id);}}+ onBlur={onBlur}+ ref={ref}options={digicertOrganizations}placeholder="Select an organization..."getOptionLabel={(option) => option.displayName || option.name}@@ -101,7 +100,7 @@ export const DigiCertFields = ({<Controllercontrol={control}name="configuration.purpose"- render={({ field: { value, onChange }, fieldState: { error } }) => (+ render={({ field: { value, onChange, ref }, fieldState: { error } }) => (<Field className="mb-4"><FieldLabel>Purpose <span className="text-danger">*</span>@@ -115,19 +114,20 @@ export const DigiCertFields = ({</TooltipContent></Tooltip></FieldLabel>- <FilterableSelect+ <Combobox+ isClearable={false}value={PURPOSE_OPTIONS.find((o) => o.value === (value ?? DigiCertCaPurpose.Ssl)) ??PURPOSE_OPTIONS[0]}- onChange={(option) => {- const next = (option as SingleValue<{ value: DigiCertCaPurpose; label: string }>)- ?.value;+ onValueChange={(option) => {+ const next = option.value;if (next) {onChange(next);setValue("configuration.productNameId", "");}}}+ ref={ref}options={PURPOSE_OPTIONS}getOptionLabel={(option) => option.label}getOptionValue={(option) => option.value}@@ -140,7 +140,7 @@ export const DigiCertFields = ({<Controllercontrol={control}name="configuration.productNameId"- render={({ field: { value, onChange }, fieldState: { error } }) => {+ render={({ field: { value, onChange, ref }, fieldState: { error } }) => {const purpose =configuration && "purpose" in configuration? (configuration.purpose ?? DigiCertCaPurpose.Ssl)@@ -164,13 +164,15 @@ export const DigiCertFields = ({</TooltipContent></Tooltip></FieldLabel>- <FilterableSelect+ <Combobox+ isClearable={false}isLoading={isDigiCertProductsPending && !!digicertConnectionId}isDisabled={!digicertConnectionId}value={filteredProducts.find((product) => product.nameId === value) ?? null}- onChange={(option) => {- onChange((option as SingleValue<TDigiCertProduct>)?.nameId ?? "");+ onValueChange={(option) => {+ onChange(option.nameId);}}+ ref={ref}options={filteredProducts}placeholder="Select a product..."getOptionLabel={(option) => `${option.name} (${option.nameId})`}diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/ExternalCaHeader.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/ExternalCaHeader.tsxindex 8c721579f7..2a109b209f 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/ExternalCaHeader.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/ExternalCaHeader.tsx@@ -1,6 +1,6 @@import { type LucideIcon } from "lucide-react";-import { ProviderIcon } from "@app/components/v3";+import { ProviderIcon, SheetDescription, SheetTitle } from "@app/components/v3";type Props = {name: string;@@ -20,8 +20,8 @@ export const ExternalCaHeader = ({ name, subtitle, image, icon: Icon }: Props) =)}</div><div>- <div className="flex items-center gap-x-2 text-label">{name}</div>- <p className="text-sm leading-4 font-normal text-muted">{subtitle}</p>+ <SheetTitle>{name}</SheetTitle>+ <SheetDescription>{subtitle}</SheetDescription></div></div>);diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/GcpCloudDnsZoneFields.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/GcpCloudDnsZoneFields.tsxindex a2b8af73bf..6240e9345f 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/GcpCloudDnsZoneFields.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/GcpCloudDnsZoneFields.tsx@@ -1,14 +1,13 @@import { useState } from "react";-import { Control, Controller } from "react-hook-form";-import { SingleValue } from "react-select";+import { Control, Controller, ControllerRenderProps } from "react-hook-form";import { AxiosError } from "axios";import { Info } from "lucide-react";import {+ Combobox,Field,FieldError,FieldLabel,- FilterableSelect,Tooltip,TooltipContent,TooltipTrigger@@ -17,7 +16,6 @@ import {useGcpConnectionListCloudDnsProjects,useGcpConnectionListCloudDnsZones} from "@app/hooks/api/appConnections/gcp/queries";-import { TGcpCloudDnsZone, TGcpProject } from "@app/hooks/api/appConnections/gcp/types";import { FormData } from "./schema";@@ -37,12 +35,14 @@ const GcpCloudDnsZoneSelect = ({gcpProjectId,value,onChange,+ inputRef,error}: {connectionId: string;gcpProjectId: string;value?: string | null;onChange: (value: string) => void;+ inputRef: ControllerRenderProps<FormData, "configuration.dnsProviderConfig.hostedZoneId">["ref"];error?: { message?: string };}) => {const {@@ -75,19 +75,22 @@ const GcpCloudDnsZoneSelect = ({</TooltipContent></Tooltip></FieldLabel>- <FilterableSelect+ <Combobox+ isClearable={false}+ includeMissingSelectedOptions={false}+ ref={inputRef}isLoading={isZonesPending && Boolean(connectionId) && Boolean(gcpProjectId)}isDisabled={!connectionId || !gcpProjectId}value={zones.find((zone) => zone.id === value) ||(value ? { id: value, name: value.split("/").pop() ?? value, dnsName: "" } : null)}- onChange={(option) => {- onChange((option as SingleValue<TGcpCloudDnsZone>)?.id ?? "");+ onValueChange={(option) => {+ onChange(option.id);}}options={zones}placeholder="Select a zone..."- noOptionsMessage={() => "No public managed zones found in this project."}+ emptyMessage="No public managed zones found in this project."getOptionLabel={(option) =>option.dnsName ? `${option.dnsName} (${option.name})` : option.name}@@ -117,7 +120,7 @@ export const GcpCloudDnsZoneFields = ({ control, connectionId }: Props) => {<Controllername="configuration.dnsProviderConfig.hostedZoneId"control={control}- render={({ field: { value, onChange }, fieldState: { error } }) => {+ render={({ field: { value, onChange, ref }, fieldState: { error } }) => {const gcpProjectId = getProjectIdFromZone(value) || selectedProjectId || "";return (@@ -136,20 +139,22 @@ export const GcpCloudDnsZoneFields = ({ control, connectionId }: Props) => {</TooltipContent></Tooltip></FieldLabel>- <FilterableSelect+ <Combobox+ isClearable={false}+ includeMissingSelectedOptions={false}isLoading={isProjectsPending && Boolean(connectionId)}isDisabled={!connectionId}value={projects.find((project) => project.id === gcpProjectId) ||(gcpProjectId ? { id: gcpProjectId, name: gcpProjectId } : null)}- onChange={(option) => {- setSelectedProjectId((option as SingleValue<TGcpProject>)?.id ?? "");+ onValueChange={(option) => {+ setSelectedProjectId(option.id);onChange("");}}options={projects}placeholder="Select a project..."- noOptionsMessage={({ inputValue }) =>+ emptyMessage={(inputValue) =>inputValue? "No matching projects": "No projects found. Grant the connection's service account the DNS Administrator and Service Usage Viewer roles on your project and enable the Cloud DNS API there."@@ -167,6 +172,7 @@ export const GcpCloudDnsZoneFields = ({ control, connectionId }: Props) => {gcpProjectId={gcpProjectId}value={value}onChange={onChange}+ inputRef={ref}error={error}/></>diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsxindex 0e00084f92..461ce6610c 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx@@ -12,6 +12,7 @@ import { createNotification } from "@app/components/notifications";import {Badge,Button,+ DiscardChangesAlertDialog,Field,FieldDescription,FieldError,@@ -56,8 +57,10 @@ import {import {DigiCertCaPurpose,TCreateCertificateAuthorityDTO,+ TUnifiedCertificateAuthority,TUpdateCertificateAuthorityDTO} from "@app/hooks/api/ca/types";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";import { UsePopUpState } from "@app/hooks/usePopUp";import { AcmeFields, TAcmeDnsZone } from "./ExternalCaFields/AcmeFields";@@ -106,6 +109,7 @@ type ExternalCaConfigurationPayload =type Props = {popUp: UsePopUpState<["ca"]>;handlePopUpToggle: (popUpName: keyof UsePopUpState<["ca"]>, state?: boolean) => void;+ onComplete?: (createdCA: TUnifiedCertificateAuthority) => void | Promise<void>;};type ExternalCaOption = {@@ -229,7 +233,7 @@ const CaTypeCard = ({);};-export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {+export const ExternalCaModal = ({ popUp, handlePopUpToggle, onComplete }: Props) => {const { currentProject } = useProject();const { subscription } = useSubscription();const { openUpgradeGate, upgradeGate } = useUpgradeGate();@@ -246,7 +250,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {control,handleSubmit,reset,- formState: { isSubmitting },+ formState: { isSubmitting, isDirty },watch,setValue} = useForm<FormData>({@@ -934,6 +938,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {throw new Error("Invalid certificate authority configuration");}+ let createdCA: TUnifiedCertificateAuthority | undefined;if (ca) {await updateMutateAsync({id: ca.id,@@ -943,7 +948,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {configuration: configPayload} as TUpdateCertificateAuthorityDTO);} else {- await createMutateAsync({+ createdCA = await createMutateAsync({name,type,status,@@ -951,6 +956,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {} as TCreateCertificateAuthorityDTO);}+ if (createdCA) await onComplete?.(createdCA);reset();handlePopUpToggle("ca", false);@@ -978,21 +984,31 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {);});+ const discardActionRef = useRef<VoidFunction>(() => {});+ const { isDiscardDialogOpen, setIsDiscardDialogOpen, requestDiscard, confirmDiscard } =+ useDiscardChangesGuard({ isDirty, onDiscard: () => discardActionRef.current() });+ const isPendingSave = isSubmitting || isCheckingCsValidation;+ const requestClose = () => {+ if (isPendingSave) return;+ discardActionRef.current = () => {+ reset();+ setSelectedType(null);+ setSearch("");+ handlePopUpToggle("ca", false);+ };+ requestDiscard();+ };+return (<><Sheetopen={popUp?.ca?.isOpen}onOpenChange={(isOpen) => {- if (!isOpen) {- reset();- setSelectedType(null);- setSearch("");- }- handlePopUpToggle("ca", isOpen);+ if (!isOpen) requestClose();}}>- <SheetContent className="flex h-full max-h-full flex-col gap-y-0 p-0 sm:max-w-2xl">- <SheetHeader className="border-b border-border">+ <SheetContent size="form" isPending={isPendingSave}>+ <SheetHeader>{showGrid ? (<><SheetTitle>Connect External CA</SheetTitle>@@ -1006,21 +1022,26 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {{!isEditMode && (<buttontype="button"- onClick={() => setSelectedType(null)}+ disabled={isPendingSave}+ onClick={() => {+ discardActionRef.current = () => {+ reset();+ setSelectedType(null);+ };+ requestDiscard();+ }}className="mb-1 flex w-fit cursor-pointer items-center gap-1 text-xs text-muted transition-colors hover:text-foreground hover:underline"><ArrowLeftIcon className="size-3" />Select Another CA</button>)}- <SheetTitle>- <ExternalCaHeader- name={headerTitle}- subtitle="Define the connection and credentials used to issue certificates from this CA."- image={activeTypeMedia?.image}- icon={activeTypeMedia?.icon}- />- </SheetTitle>+ <ExternalCaHeader+ name={headerTitle}+ subtitle="Define the connection and credentials used to issue certificates from this CA."+ image={activeTypeMedia?.image}+ icon={activeTypeMedia?.icon}+ /></>)}</SheetHeader>@@ -1055,7 +1076,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {</div>) : (<form onSubmit={handleSubmit(onFormSubmit)} className="flex min-h-0 flex-1 flex-col">- <div className="min-h-0 flex-1 overflow-y-auto px-6 py-6">+ <fieldset disabled={isPendingSave} className="min-h-0 flex-1 overflow-y-auto p-4">{ca && (<Field className="mb-4"><FieldLabel>CA ID</FieldLabel>@@ -1165,12 +1186,13 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {isPending={isPending}/>)}- </div>- <SheetFooter className="shrink-0 items-center justify-end border-t">+ </fieldset>+ <SheetFooter className="justify-end border-t"><Buttontype="button"- variant="outline"- onClick={() => handlePopUpToggle("ca", false)}+ variant="ghost"+ isDisabled={isPendingSave}+ onClick={requestClose}>Cancel</Button>@@ -1187,6 +1209,13 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {)}</SheetContent></Sheet>+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Changes?"+ description="Your certificate authority configuration changes will be lost."+ />{upgradeGate}</>);diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsxindex 81139eae93..6dd11e3068 100644--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx@@ -4,8 +4,6 @@ import { format } from "date-fns";import { ExternalLinkIcon } from "lucide-react";import { getCertificateDisplayName } from "@app/components/utilities/certificateDisplayUtils";-import { Tooltip } from "@app/components/v2";-import { CopyButton } from "@app/components/v2/CopyButton";import {Badge,Card,@@ -13,10 +11,14 @@ import {CardDescription,CardHeader,CardTitle,+ CopyButton,Detail,DetailGroup,DetailLabel,- DetailValue+ DetailValue,+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@app/components/v3";import { CertSource, CertStatus, useGetCertificateById } from "@app/hooks/api";import { CaType } from "@app/hooks/api/ca/enums";@@ -111,7 +113,7 @@ export const CertificateOverviewSection = ({ certificateId }: Props) => {<DetailLabel>Certificate ID</DetailLabel><DetailValue className="flex items-center gap-2 font-mono text-xs">{certificate.id}- <CopyButton value={certificate.id} size="xs" variant="plain" />+ <CopyButton value={certificate.id} ariaLabel="Copy certificate ID" /></DetailValue></Detail><Detail>@@ -120,7 +122,7 @@ export const CertificateOverviewSection = ({ certificateId }: Props) => {{certificate.orderId ? (<>{certificate.orderId}- <CopyButton value={certificate.orderId} size="xs" variant="plain" />+ <CopyButton value={certificate.orderId} ariaLabel="Copy order ID" /></>) : (<span className="text-muted">—</span>@@ -143,8 +145,7 @@ export const CertificateOverviewSection = ({ certificateId }: Props) => {{certificate.serialNumber.toUpperCase()}<CopyButtonvalue={certificate.serialNumber.toUpperCase()}- size="xs"- variant="plain"+ ariaLabel="Copy serial number"/></DetailValue></Detail>@@ -152,11 +153,13 @@ export const CertificateOverviewSection = ({ certificateId }: Props) => {<DetailLabel>Not Before</DetailLabel><DetailValue>{certificate.notBefore ? (- <Tooltip- content={`${formatDateLocal(certificate.notBefore)} (Local)`}- position="right"- >- <span className="cursor-default">{formatDateUTC(certificate.notBefore)}</span>+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" className="cursor-default">+ {formatDateUTC(certificate.notBefore)}+ </button>+ </TooltipTrigger>+ <TooltipContent side="right">{`${formatDateLocal(certificate.notBefore)} (Local)`}</TooltipContent></Tooltip>) : (<span className="text-muted">—</span>@@ -167,11 +170,13 @@ export const CertificateOverviewSection = ({ certificateId }: Props) => {<DetailLabel>Not After</DetailLabel><DetailValue>{certificate.notAfter ? (- <Tooltip- content={`${formatDateLocal(certificate.notAfter)} (Local)`}- position="right"- >- <span className="cursor-default">{formatDateUTC(certificate.notAfter)}</span>+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" className="cursor-default">+ {formatDateUTC(certificate.notAfter)}+ </button>+ </TooltipTrigger>+ <TooltipContent side="right">{`${formatDateLocal(certificate.notAfter)} (Local)`}</TooltipContent></Tooltip>) : (<span className="text-muted">—</span>diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsxindex 6893220777..57eb961b9f 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsx@@ -131,6 +131,7 @@ const entryLabel = (entry: TPkcs12Entry) =>entry.altNames || entry.commonName || entry.alias || entry.subject;type EntryRowProps = {+ applicationId?: string;entry: TPkcs12Entry;isImported: boolean;isSelected: boolean;@@ -147,6 +148,7 @@ type EntryRowProps = {};const KeystoreEntryRow = ({+ applicationId,entry,isImported,isSelected,@@ -224,6 +226,7 @@ const KeystoreEntryRow = ({<TableCell onClick={stopRowToggle}>{isSelected ? (<CertificateProfileSelect+ applicationId={applicationId}options={profileOptions}isLoading={isProfilesLoading}value={profileId}@@ -685,6 +688,7 @@ export const CertificateImportSheet = ({ popUp, handlePopUpToggle, applicationId<TableBody>{selectableEntries.map((entry) => (<KeystoreEntryRow+ applicationId={applicationId}key={entry.fingerprintSha256}entry={entry}isImported={importedFingerprints.has(entry.fingerprintSha256)}@@ -722,6 +726,7 @@ export const CertificateImportSheet = ({ popUp, handlePopUpToggle, applicationId<FieldLabel>Certificate Profile (optional)</FieldLabel><FieldContent><CertificateProfileSelect+ applicationId={applicationId}options={profileOptions}isLoading={isProfilesLoading}value={selectedProfileId}diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-fields.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-fields.tsxindex cce847148b..dcd6ed989a 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-fields.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-fields.tsx@@ -1,17 +1,21 @@-import { OptionProps } from "react-select";+import { useState } from "react";+import { useQueryClient } from "@tanstack/react-query";-import {- FilterableSelect,- Input,- ReactSelectOption,- Tooltip,- TooltipContent,- TooltipTrigger-} from "@app/components/v3";+import { Combobox, Input } from "@app/components/v3";import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";import { useListCasByProjectId } from "@app/hooks/api/ca";import { CaStatus, CaType } from "@app/hooks/api/ca/enums";+import { caKeys } from "@app/hooks/api/ca/queries";+import { TUnifiedCertificateAuthority } from "@app/hooks/api/ca/types";+import { TCertificateProfile } from "@app/hooks/api/certificateProfiles";import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles/queries";+import {+ PkiApplicationResourceActions,+ PkiApplicationResourceSub,+ useAttachPkiApplicationProfiles,+ useGetPkiApplicationPermissions+} from "@app/hooks/api/pkiApplications";+import { useProfileCreation } from "@app/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation";import { getCertificateImportReference, isCaTypeLinkable } from "./certificate-import-linkage";@@ -25,25 +29,17 @@ export type ProfileOption = {type ReferenceOption = { value: string; label: string };-const ProfileOptionRow = (props: OptionProps<ProfileOption>) => {- const { data, children } = props;-- if (data.isLinkable) return <ReactSelectOption {...props}>{children}</ReactSelectOption>;-- return (- <Tooltip>- <TooltipTrigger asChild>- <div>- <ReactSelectOption {...props}>- <span className="cursor-not-allowed opacity-40">{children}</span>- </ReactSelectOption>- </div>- </TooltipTrigger>- <TooltipContent side="right" className="max-w-72">- Infisical can't manage the lifecycle of a certificate issued by this authority yet.- </TooltipContent>- </Tooltip>- );+const toProfileOption = (profile: TCertificateProfile): ProfileOption => {+ const caType = profile.caId+ ? ((profile.certificateAuthority?.externalType as CaType) ?? CaType.INTERNAL)+ : null;+ return {+ id: profile.id,+ slug: profile.slug,+ caId: profile.caId,+ caType,+ isLinkable: profile.caId ? isCaTypeLinkable(caType) : true+ };};export const useCertificateImportProfiles = (applicationId?: string) => {@@ -54,48 +50,110 @@ export const useCertificateImportProfiles = (applicationId?: string) => {});const profileOptions: ProfileOption[] = (data?.certificateProfiles ?? [])- .map((profile) => {- const caType = profile.caId- ? ((profile.certificateAuthority?.externalType as CaType) ?? CaType.INTERNAL)- : null;- return {- id: profile.id,- slug: profile.slug,- caId: profile.caId,- caType,- isLinkable: profile.caId ? isCaTypeLinkable(caType) : true- };- })+ .map(toProfileOption).sort((a, b) => Number(b.isLinkable) - Number(a.isLinkable));return { profileOptions, isProfilesLoading: isPending };};export const CertificateProfileSelect = ({+ applicationId,options,isLoading,value,onChange}: {+ applicationId?: string;options: ProfileOption[];isLoading: boolean;value?: string;onChange: (profileId?: string) => void;-}) => (- <FilterableSelect<ProfileOption>- isLoading={isLoading}- isClearable- options={options}- components={{ Option: ProfileOptionRow }}- isOptionDisabled={(option) => !option.isLinkable}- value={options.find((option) => option.id === value) ?? null}- onChange={(selected) => onChange((selected as ProfileOption | null)?.id ?? undefined)}- getOptionLabel={(option) => option.slug}- getOptionValue={(option) => option.id}- placeholder="Select a profile..."- noOptionsMessage={() => "This application has no certificate profiles."}- />-);+}) => {+ const queryClient = useQueryClient();+ const { data: permissionData } = useGetPkiApplicationPermissions(applicationId ?? "");+ const attach = useAttachPkiApplicationProfiles();+ const [attachedProfileId, setAttachedProfileId] = useState<string>();+ const { refetch } = useListCertificateProfiles({+ applicationId,+ limit: 100,+ enabled: Boolean(applicationId)+ });+ const canAttach = permissionData?.permission.can(+ PkiApplicationResourceActions.ManageProfiles,+ PkiApplicationResourceSub.Application+ );+ const profileCreation = useProfileCreation<ProfileOption>(async (profile) => {+ if (!applicationId || !canAttach) {+ throw new Error(+ "The profile was created, but you no longer have permission to attach it to this application."+ );+ }+ const ca = queryClient+ .getQueryData<TUnifiedCertificateAuthority[]>(caKeys.listCasByProjectId())+ ?.find((option) => option.id === profile.caId);+ if (profile.caId && (!ca || !isCaTypeLinkable(ca.type))) {+ throw new Error(+ "The profile was created, but its certificate authority cannot manage imported certificates. Cancel setup and choose a supported profile."+ );+ }+ if (attachedProfileId !== profile.id) {+ try {+ await attach.mutateAsync({ applicationId, profileIds: [profile.id] });+ } catch {+ throw new Error(+ "The profile was created, but attachment failed. Retry to attach it to this application."+ );+ }+ setAttachedProfileId(profile.id);+ }+ const result = await refetch();+ const listedProfile = result.data?.certificateProfiles.find(+ (option) => option.id === profile.id+ );+ if (result.isError || !listedProfile || !toProfileOption(listedProfile).isLinkable) {+ throw new Error(+ "The profile was attached, but the available profiles could not be refreshed. Retry to load and select it."+ );+ }+ onChange(listedProfile.id);+ });++ return (+ <Combobox<ProfileOption>+ aria-label="Certificate profile"+ isLoading={isLoading}+ isClearable+ options={options}+ renderOption={(option) => (+ <div className="min-w-0">+ <p>{option.slug}</p>+ {!option.isLinkable && (+ <p className="text-xs whitespace-normal text-muted">+ Infisical can't manage the lifecycle of a certificate issued by this authority+ yet.+ </p>+ )}+ </div>+ )}+ isOptionDisabled={(option) => !option.isLinkable}+ value={options.find((option) => option.id === value) ?? null}+ onValueChange={(selected) => onChange(selected?.id ?? undefined)}+ getOptionLabel={(option) => option.slug}+ getOptionValue={(option) => option.id}+ placeholder="Select a profile..."+ emptyMessage="This application has no certificate profiles."+ creation={+ canAttach && profileCreation+ ? {+ ...profileCreation,+ emptyLabel: "Create and Attach Profile",+ formatLabel: () => "Create and Attach Profile"+ }+ : undefined+ }+ />+ );+};export const useCertificateImportReference = (profile: ProfileOption | null) => {const reference = getCertificateImportReference(profile?.caType);@@ -159,35 +217,16 @@ export const CertificateReferenceField = ({}return (- <FilterableSelect<ReferenceOption>+ <Combobox<ReferenceOption>+ aria-label={reference.optionsPlaceholder}isLoading={isOptionsLoading}isClearableoptions={referenceOptions}value={referenceOptions.find((option) => option.value === value) ?? null}- onChange={(selected) => onChange((selected as ReferenceOption | null)?.value ?? "")}+ onValueChange={(selected) => onChange(selected?.value ?? "")}getOptionLabel={(option) => option.label}getOptionValue={(option) => option.value}placeholder={reference.optionsPlaceholder}- styles={{- control: (base) => ({ ...base, minHeight: "unset" }),- input: (base) => ({ ...base, "input:focus": { boxShadow: "none" } }),- menuPortal: (base) => ({ ...base, zIndex: 60, pointerEvents: "auto" }),- menu: (base) => ({- ...base,- width: "max-content",- minWidth: "100%",- maxWidth: "24rem",- overflowX: "auto"- }),- menuList: (base) => ({ ...base, width: "max-content", minWidth: "100%" }),- option: (base) => ({- ...base,- minWidth: "100%",- overflow: "visible",- textOverflow: "clip",- whiteSpace: "nowrap"- })- }}/>);};diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsxindex 9cd7c380ac..18e652bca9 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx@@ -1,16 +1,17 @@import { useEffect, useMemo, useRef, useState } from "react";import { Control, Controller, useForm } from "react-hook-form";-import { SingleValue } from "react-select";import { zodResolver } from "@hookform/resolvers/zod";import { useQueryClient } from "@tanstack/react-query";import { Link, useParams } from "@tanstack/react-router";import axios from "axios";-import { Check, ChevronRight, FileBadge, ShieldCheck } from "lucide-react";+import { Check, ShieldCheck } from "lucide-react";import { z } from "zod";import { createNotification } from "@app/components/notifications";import {Button,+ Combobox,+ DiscardChangesAlertDialog,DocumentationLinkBadge,Field,FieldContent,@@ -18,7 +19,6 @@ import {FieldError,FieldFeedback,FieldLabel,- FilterableSelect,Input,Select,SelectContent,@@ -27,6 +27,8 @@ import {SelectValue,Sheet,SheetContent,+ SheetDescription,+ SheetFooter,SheetHeader,SheetTitle,Stepper,@@ -70,8 +72,10 @@ import {SIGNATURE_ALGORITHMS_OPTIONS} from "@app/hooks/api/certificates/constants";import { ApiErrorTypes } from "@app/hooks/api/types";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";import { normalizeSlugInput } from "@app/lib/schemas";import { filterUsages } from "@app/pages/cert-manager/CertificatesPage/components/certificateUtils";+import { useCaCreation } from "@app/pages/cert-manager/components/useCaCreation";import {CertPolicyState,CertSubjectAlternativeNameType,@@ -87,7 +91,6 @@ import {CertificatePolicyWizardHandle} from "../CertificatePoliciesTab/CreatePolicyModal";import { PolicyConstraints, ProfileDefaultsStep } from "./CreateProfileModal/ProfileDefaultsStep";-import { CertificatePolicyOption } from "./CertificatePolicyOption";const certificateDefaultsSchema = z.object({@@ -259,31 +262,28 @@ const ExternalCaTemplateSelect = ({<Controllercontrol={control}name="externalConfigs.template"- render={({ field: { onChange, value }, fieldState: { error } }) => (+ render={({ field: { onChange, value, ref, onBlur, name }, fieldState: { error } }) => (<Field><FieldLabel>Windows ADCS Template <span className="text-danger">*</span></FieldLabel><FieldContent>- <FilterableSelect+ <Combobox+ ref={ref}+ name={name}+ onBlur={onBlur}value={templates.find((template) => template[valueKey] === value) ||(value ? { id: value, name: value } : null)}- onChange={(selected) => {- const option = Array.isArray(selected) ? selected[0] : selected;- onChange(- option && typeof option === "object" && valueKey in option- ? option[valueKey] || ""- : ""- );+ onValueChange={(selected) => {+ onChange(selected?.[valueKey] || "");}}getOptionLabel={(template) => template.name}getOptionValue={(template) => template[valueKey]}options={templates}placeholder={placeholder}isError={Boolean(error)}- className="w-full"/><FieldError errors={[error]} /></FieldContent>@@ -509,7 +509,7 @@ const PolicySubSteps = ({ activeStep, onCancel }: { activeStep: number; onCancel"flex size-5 shrink-0 items-center justify-center rounded-full border text-[10px] font-medium",status === "complete" && "border-success bg-success/10 text-success",status === "current" && "border-warning bg-warning/10 text-warning",- status === "pending" && "border-border bg-mineshaft-800 text-muted"+ status === "pending" && "border-border bg-container text-muted")}>{status === "complete" ? <Check className="size-2.5" strokeWidth={3} /> : i + 1}@@ -538,21 +538,37 @@ interface Props {onClose: () => void;profile?: TCertificateProfileWithDetails;mode?: "create" | "edit" | "clone";- onComplete?: (profile: TCertificateProfile) => void;+ onComplete?: (profile: TCertificateProfile) => void | Promise<void>;+ validateSlug?: (slug: string) => string | undefined;}-export const CreateProfileModal = ({+type ProfileFormProps = Props & {+ initialSlug?: string;+ onCancel: () => void;+ onDirtyChange?: (dirty: boolean) => void;+ onPendingChange?: (pending: boolean) => void;+};++export const CreateProfileForm = ({isOpen,onClose,profile,mode = "create",- onComplete-}: Props) => {+ onComplete,+ initialSlug = "",+ validateSlug,+ onCancel,+ onDirtyChange,+ onPendingChange+}: ProfileFormProps) => {const { currentProject } = useProject();const { permission } = useProjectPermission();const { orgId } = useParams({ strict: false }) as { orgId?: string };const [policyStepIndex, setPolicyStepIndex] = useState<number | null>(null);const [isPolicySubmitting, setIsPolicySubmitting] = useState(false);+ const [savedProfile, setSavedProfile] = useState<TCertificateProfile | null>(null);+ const [completionError, setCompletionError] = useState<string>();+ const [isCompleting, setIsCompleting] = useState(false);const policyWizardRef = useRef<CertificatePolicyWizardHandle>(null);const queryClient = useQueryClient();@@ -585,15 +601,6 @@ export const CreateProfileModal = ({}));const certificatePolicies = policyData?.certificatePolicies || [];- type PolicyOption = TCertificatePolicy | { id: "_create"; name: string };-- const policyOptions: PolicyOption[] = [- ...(canCreatePolicy && !isEdit- ? [{ id: "_create" as const, name: "Add Certificate Policy" }]- : []),- ...certificatePolicies- ];-const getGroupHeaderLabel = (groupType: "internal" | "external") => {switch (groupType) {case "internal":@@ -605,14 +612,23 @@ export const CreateProfileModal = ({}};- const { control, handleSubmit, reset, watch, setValue, setError, trigger } = useForm<FormData>({+ const {+ control,+ handleSubmit,+ reset,+ watch,+ setValue,+ setError,+ trigger,+ formState: { isDirty, isSubmitting: isFormSubmitting }+ } = useForm<FormData>({mode: "onTouched",resolver: zodResolver(isEdit ? editSchema : createSchema),defaultValues:(isEdit || isClone) && profile? buildFormValuesFromProfile(profile, Boolean(isClone)): {- slug: "",+ slug: normalizeSlugInput(initialSlug),description: "",issuerType: IssuerType.CA,certificateAuthorityId: "",@@ -625,6 +641,12 @@ export const CreateProfileModal = ({const watchedSlug = watch("slug");const watchedIssuerType = watch("issuerType");const watchedCertificateAuthorityId = watch("certificateAuthorityId");+ const { creation: caCreation, caCreationModals } = useCaCreation<+ (typeof certificateAuthorities)[number]+ >((ca) => {+ if (ca.id !== watchedCertificateAuthorityId) setValue("externalConfigs", undefined);+ setValue("certificateAuthorityId", ca.id, { shouldDirty: true, shouldValidate: true });+ });const watchedPolicyId = watch("certificatePolicyId");const { data: selectedPolicyData } = useGetCertificatePolicyById({policyId: watchedPolicyId || ""@@ -764,6 +786,8 @@ export const CreateProfileModal = ({useEffect(() => {if (isOpen) {setSelectedStepIndex(0);+ setSavedProfile(null);+ setCompletionError(undefined);}}, [isOpen]);@@ -897,8 +921,25 @@ export const CreateProfileModal = ({createData.defaults = serializedDefaults;}- const createdProfile = await createProfile.mutateAsync(createData);- onComplete?.(createdProfile);+ const createdProfile = savedProfile ?? (await createProfile.mutateAsync(createData));+ setIsCompleting(true);+ if (!savedProfile) {+ setSavedProfile(createdProfile);+ reset(data);+ }+ setCompletionError(undefined);+ try {+ await onComplete?.(createdProfile);+ } catch (error) {+ setCompletionError(+ error instanceof Error+ ? error.message+ : "The profile was created, but setup could not finish. Retry to continue."+ );+ return;+ } finally {+ setIsCompleting(false);+ }}createNotification({@@ -911,6 +952,12 @@ export const CreateProfileModal = ({};const onFormSubmit = async (data: FormData) => {+ const slugError = savedProfile ? undefined : validateSlug?.(data.slug);+ if (slugError) {+ setSelectedStepIndex(0);+ setError("slug", { type: "permission", message: slugError });+ return;+ }try {await saveProfile(data);} catch (error) {@@ -924,7 +971,7 @@ export const CreateProfileModal = ({const isStepValid = async (index: number) => {const { fields } = steps[index];if (fields.length === 0) return true;- return trigger(fields as any);+ return trigger(fields as any, { shouldFocus: true });};const goNext = async () => {@@ -944,13 +991,13 @@ export const CreateProfileModal = ({};const handleClose = () => {- setPolicyStepIndex(null);- reset();- setSelectedStepIndex(0);- onClose();+ onCancel();};- const isSubmitting = createProfile.isPending || updateProfile.isPending;+ const isSubmitting =+ isCompleting || isFormSubmitting || createProfile.isPending || updateProfile.isPending;+ let submitLabel = isEdit ? "Save Changes" : "Create Profile";+ if (savedProfile) submitLabel = completionError ? "Retry Setup" : "Complete Setup";const isPolicyWizardOpen = policyStepIndex !== null;const isFinalPolicyStep = policyStepIndex === CERTIFICATE_POLICY_STEPS.length - 1;@@ -977,440 +1024,498 @@ export const CreateProfileModal = ({await queryClient.refetchQueries({queryKey: ["list-certificate-policies", currentProject?.id]});- setValue("certificatePolicyId", createdPolicy.id, { shouldValidate: true });+ setValue("certificatePolicyId", createdPolicy.id, { shouldValidate: true, shouldDirty: true });setPolicyStepIndex(null);};- return (- <Sheet- open={isOpen}- onOpenChange={(open) => {- if (!open) {- handleClose();- }- }}- >- <SheetContent className="flex h-full max-h-full flex-col gap-y-0 p-0 sm:max-w-[1260px]">- <SheetHeader className="border-b border-border">- <SheetTitle>- <div className="flex w-full items-start gap-2">- <div className="flex h-10 w-10 items-center justify-center rounded-md bg-project/10 text-project">- <FileBadge className="h-5 w-5" />- </div>- <div>- <div className="flex items-center gap-x-2 text-foreground">- {/* eslint-disable-next-line no-nested-ternary */}- {isEdit- ? "Edit Certificate Profile"- : isClone- ? "Clone Certificate Profile"- : "Create Certificate Profile"}- <DocumentationLinkBadge href={PkiDocsUrls.settings.profiles} />- </div>- {isPolicyWizardOpen ? (- <p className="flex items-center gap-1 text-sm leading-4 font-normal text-muted">- <span>{currentStep.name}</span>- <ChevronRight className="h-3 w-3 shrink-0" />- <span>New certificate policy</span>- </p>- ) : (- <p className="text-sm leading-4 text-muted">- {/* eslint-disable-next-line no-nested-ternary */}- {isEdit- ? `Update configuration for ${profile?.slug}`- : isClone- ? `Create a new profile based on ${profile?.slug}`- : "Define the CA and policy used to issue certificates from this profile"}- </p>- )}- </div>- </div>- </SheetTitle>- </SheetHeader>-- <form onSubmit={(e) => e.preventDefault()} className="flex min-h-0 flex-1 flex-col">- <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={selectedStepIndex}- orientation="vertical"- onStepChange={(i) => {- if (!isPolicyWizardOpen && i < selectedStepIndex) setSelectedStepIndex(i);- }}- >- <StepperList>- {steps.flatMap((s, i) => {- const stepNode = (- <StepperStep- key={s.key}- index={i}- title={s.name}- description={s.shortDescription}- />- );-- if (!isPolicyWizardOpen || s.key !== "issuer") return [stepNode];-- return [- stepNode,- <PolicySubSteps- key="policy-sub-steps"- activeStep={policyStepIndex}- onCancel={() => setPolicyStepIndex(null)}- />- ];- })}- </StepperList>- </Stepper>- </aside>+ useEffect(() => {+ onDirtyChange?.(isDirty || isPolicyWizardOpen);+ }, [isDirty, isPolicyWizardOpen, onDirtyChange]);- {isPolicyWizardOpen ? (- <CertificatePolicyWizard- ref={policyWizardRef}- step={policyStepIndex}- onStepChange={setPolicyStepIndex}- onComplete={handlePolicyCreated}- defaultName={draftPolicyName}- nameDescription="Pre-filled from the profile name. Edit if this policy will be shared."- banner={- <div className="mb-4 flex items-center gap-2 text-xs text-muted">- <ShieldCheck className="size-3.5 shrink-0" />- <span>- Defining the policy for <span className="text-accent">{watchedSlug}</span>- </span>- </div>- }- />- ) : (- <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>+ useEffect(() => {+ onPendingChange?.(isSubmitting || isPolicySubmitting);+ return () => onPendingChange?.(false);+ }, [isSubmitting, isPolicySubmitting, onPendingChange]);- {currentStep.key === "details" && (- <div className="space-y-5">- <Controller- control={control}- name="slug"- render={({ field, fieldState: { error } }) => (- <Field data-invalid={Boolean(error)}>- <FieldLabel>- Name <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Input- {...field}- onChange={(event) =>- field.onChange(normalizeSlugInput(event.target.value))- }- aria-describedby="certificate-profile-name-feedback"- placeholder="your-profile-name"- isError={Boolean(error)}- />- <FieldFeedback- id="certificate-profile-name-feedback"- description="Use lowercase letters, numbers, and hyphens. Spaces become hyphens."- error={error?.message}- />- </FieldContent>- </Field>- )}+ return (+ <>+ <SheetHeader>+ <SheetTitle className="flex items-center gap-2">+ {isEdit && "Edit Certificate Profile"}+ {!isEdit && isClone && "Clone Certificate Profile"}+ {!isEdit && !isClone && "Create Certificate Profile"}+ <DocumentationLinkBadge href={PkiDocsUrls.settings.profiles} />+ </SheetTitle>+ <SheetDescription>+ {isPolicyWizardOpen && `${currentStep.name}: new certificate policy`}+ {!isPolicyWizardOpen && isEdit && `Update configuration for ${profile?.slug}`}+ {!isPolicyWizardOpen &&+ !isEdit &&+ isClone &&+ `Create a new profile based on ${profile?.slug}`}+ {!isPolicyWizardOpen &&+ !isEdit &&+ !isClone &&+ "Define the CA and policy used to issue certificates from this profile"}+ </SheetDescription>+ </SheetHeader>++ <form+ onSubmit={(event) => {+ event.preventDefault();+ if (isSubmitting || isPolicySubmitting) return;+ if (isPolicyWizardOpen) {+ goNextInPolicy();+ return;+ }+ if (!isFinalStep) {+ goNext();+ return;+ }+ handleSubmit(onFormSubmit, (errors) => {+ const errorKeys = Object.keys(errors);+ const stepIndex = steps.findIndex((s) =>+ s.fields.some((fld) => errorKeys.includes(fld))+ );+ if (stepIndex >= 0) setSelectedStepIndex(stepIndex);+ createNotification({+ text: "Please fix the highlighted errors before saving.",+ type: "error"+ });+ })();+ }}+ className="flex min-h-0 flex-1 flex-col"+ >+ <fieldset+ disabled={isSubmitting || isPolicySubmitting || Boolean(savedProfile)}+ className="flex min-h-0 min-w-0 flex-1 overflow-hidden"+ >+ <aside className="flex w-60 shrink-0 flex-col border-r border-border p-4">+ <p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">+ Setup steps+ </p>+ <Stepper+ activeStep={selectedStepIndex}+ orientation="vertical"+ onStepChange={(i) => {+ if (+ !isSubmitting &&+ !isPolicySubmitting &&+ !isPolicyWizardOpen &&+ !savedProfile &&+ i < selectedStepIndex+ )+ setSelectedStepIndex(i);+ }}+ >+ <StepperList>+ {steps.flatMap((s, i) => {+ const stepNode = (+ <StepperStep+ key={s.key}+ index={i}+ title={s.name}+ description={s.shortDescription}/>+ );- <Controller- control={control}- name="description"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>Description</FieldLabel>- <FieldContent>- <TextArea- {...field}- value={field.value ?? ""}- placeholder="Enter profile description"- rows={3}- isError={Boolean(error)}- />- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />- </div>- )}+ if (!isPolicyWizardOpen || s.key !== "issuer") return [stepNode];- {currentStep.key === "issuer" && (- <div className="space-y-5">- <Controller- control={control}- name="issuerType"- render={({ field: { onChange, value }, fieldState: { error } }) => (- <Field>- <FieldLabel>- Issuer Type <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Select- value={value}- onValueChange={(next) => {- if (next === IssuerType.SELF_SIGNED) {- setValue("certificateAuthorityId", "");- setValue("externalConfigs", undefined);- }- onChange(next);- }}- >- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={IssuerType.CA}>Certificate Authority</SelectItem>- <SelectItem value={IssuerType.SELF_SIGNED}>Self-Signed</SelectItem>- </SelectContent>- </Select>- <FieldDescription>- Certificate Authority issues from an existing CA in your organization,- which is the standard path for production use. Self-Signed produces- standalone certificates with no CA chain, suitable for testing or- one-off identities only.- </FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}+ return [+ stepNode,+ <PolicySubSteps+ key="policy-sub-steps"+ activeStep={policyStepIndex}+ onCancel={() => setPolicyStepIndex(null)}/>+ ];+ })}+ </StepperList>+ </Stepper>+ </aside>++ {isPolicyWizardOpen ? (+ <CertificatePolicyWizard+ ref={policyWizardRef}+ step={policyStepIndex}+ onStepChange={setPolicyStepIndex}+ onComplete={handlePolicyCreated}+ defaultName={draftPolicyName}+ nameDescription="Pre-filled from the profile name. Edit if this policy will be shared."+ banner={+ <div className="mb-4 flex items-center gap-2 text-xs text-muted">+ <ShieldCheck className="size-3.5 shrink-0" />+ <span>+ Defining the policy for <span className="text-accent">{watchedSlug}</span>+ </span>+ </div>+ }+ />+ ) : (+ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto p-4">+ <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>- {watchedIssuerType === IssuerType.CA && (- <Controller- control={control}- name="certificateAuthorityId"- render={({ field: { onChange, value }, fieldState: { error } }) => {- const hasCas = certificateAuthorities.length > 0;- return (- <Field>- <FieldLabel>- Certificate Authority <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <FilterableSelect- value={- certificateAuthorities.find((ca) => ca.id === value) || null- }- onChange={(selectedCaValue) => {- let nextCaId = "";- if (Array.isArray(selectedCaValue)) {- nextCaId = selectedCaValue[0]?.id || "";- } else if (- selectedCaValue &&- typeof selectedCaValue === "object" &&- "id" in selectedCaValue- ) {- nextCaId = selectedCaValue.id || "";- }- if (nextCaId !== value) {- // Templates are per-CA; a stale hidden template would- // fail step validation for non-ADCS issuers.- setValue("externalConfigs", undefined);- }- onChange(nextCaId);- }}- getOptionLabel={(ca) => ca.name}- getOptionValue={(ca) => ca.id}- options={certificateAuthorities}- groupBy={hasCas ? "groupType" : undefined}- getGroupHeaderLabel={hasCas ? getGroupHeaderLabel : undefined}- placeholder="Select a certificate authority"- isError={Boolean(error)}- className="w-full"- />- <FieldError errors={[error]} />- {!hasCas && (- <FieldDescription className="text-warning">- No certificate authorities available.{" "}- <Link- to="/organizations/$orgId/cert-manager/certificate-authorities"- params={{ orgId: orgId ?? "" }}- className="underline hover:text-warning"- >- Create one in Certificate Authorities- </Link>- </FieldDescription>- )}- </FieldContent>- </Field>- );- }}- />+ {currentStep.key === "details" && (+ <div className="space-y-5">+ <Controller+ control={control}+ name="slug"+ render={({ field, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel>+ Name <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input+ {...field}+ onChange={(event) =>+ field.onChange(normalizeSlugInput(event.target.value))+ }+ aria-describedby="certificate-profile-name-feedback"+ placeholder="your-profile-name"+ isError={Boolean(error)}+ />+ <FieldFeedback+ id="certificate-profile-name-feedback"+ description="Use lowercase letters, numbers, and hyphens. Spaces become hyphens."+ error={error?.message}+ />+ </FieldContent>+ </Field>)}+ />- {isAzureAdcsCa && (- <ExternalCaTemplateSelect- control={control}- templates={azureAdcsTemplatesData?.templates || []}- valueKey="id"- placeholder="Select an Azure ADCS certificate template"- />+ <Controller+ control={control}+ name="description"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Description</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ value={field.value ?? ""}+ placeholder="Enter profile description"+ rows={3}+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>)}+ />+ </div>+ )}- {isAdcsCa && (- <ExternalCaTemplateSelect- control={control}- templates={adcsTemplatesData?.templates || []}- valueKey="name"- placeholder="Select an ADCS certificate template"- />+ {currentStep.key === "issuer" && (+ <div className="space-y-5">+ <Controller+ control={control}+ name="issuerType"+ render={({ field: { onChange, value }, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Issuer Type <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Select+ value={value}+ onValueChange={(next) => {+ if (next === IssuerType.SELF_SIGNED) {+ setValue("certificateAuthorityId", "");+ setValue("externalConfigs", undefined);+ }+ onChange(next);+ }}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value={IssuerType.CA}>Certificate Authority</SelectItem>+ <SelectItem value={IssuerType.SELF_SIGNED}>Self-Signed</SelectItem>+ </SelectContent>+ </Select>+ <FieldDescription>+ Certificate Authority issues from an existing CA in your organization,+ which is the standard path for production use. Self-Signed produces+ standalone certificates with no CA chain, suitable for testing or+ one-off identities only.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>)}+ />+ {watchedIssuerType === IssuerType.CA && (<Controllercontrol={control}- name="certificatePolicyId"- render={({ field: { onChange, value }, fieldState: { error } }) => (- <Field>- <FieldLabel>- Certificate Policy <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <FilterableSelect- value={certificatePolicies.find((p) => p.id === value) ?? null}- onChange={(newValue) => {- const selected = newValue as SingleValue<PolicyOption>;- if (selected?.id === "_create") {- setPolicyStepIndex(0);- return;+ name="certificateAuthorityId"+ render={({+ field: { onChange, value, ref, onBlur, name },+ fieldState: { error }+ }) => {+ const hasCas = certificateAuthorities.length > 0;+ return (+ <Field>+ <FieldLabel>+ Certificate Authority <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Combobox+ ref={ref}+ name={name}+ onBlur={onBlur}+ value={certificateAuthorities.find((ca) => ca.id === value) || null}+ onValueChange={(selectedCaValue) => {+ const nextCaId = selectedCaValue?.id || "";+ if (nextCaId !== value) {+ // Templates are per-CA; a stale hidden template would+ // fail step validation for non-ADCS issuers.+ setValue("externalConfigs", undefined);+ }+ onChange(nextCaId);+ }}+ getOptionLabel={(ca) => ca.name}+ getOptionValue={(ca) => ca.id}+ options={certificateAuthorities}+ getOptionGroup={(ca) =>+ getGroupHeaderLabel(ca.groupType as "internal" | "external")}- onChange(selected?.id || "");-- setValue("defaults", undefined);- }}- options={policyOptions}- getOptionLabel={(option) => option.name}- getOptionValue={(option) => option.id}- placeholder={- certificatePolicies.length === 0 && !canCreatePolicy- ? "No certificate policies available"- : "Select a certificate policy"- }- isError={Boolean(error)}- components={{ Option: CertificatePolicyOption }}- className="w-full"- />- <FieldDescription>- The rules that govern certificates issued from this profile: allowed- key/signature algorithms, key usages, TTL bounds, and subject- constraints.- </FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}+ placeholder="Select a certificate authority"+ isError={Boolean(error)}+ creation={!isEdit ? caCreation : undefined}+ />+ <FieldError errors={[error]} />+ {!hasCas && (+ <FieldDescription className="text-warning">+ No certificate authorities available.{" "}+ <Link+ to="/organizations/$orgId/cert-manager/certificate-authorities"+ params={{ orgId: orgId ?? "" }}+ className="underline hover:text-warning"+ >+ Create one in Certificate Authorities+ </Link>+ </FieldDescription>+ )}+ </FieldContent>+ </Field>+ );+ }}/>- </div>- )}+ )}- {currentStep.key === "certificate-defaults" && (- <ProfileDefaultsStep- control={control}- watch={watch}- setValue={setValue}- policyConstraints={policyConstraints}- isAwsAcmPublicCa={isAwsAcmPublicCa}- isExternalAdcsCa={isAzureAdcsCa || isAdcsCa}- caSupportsCustomExtensions={caSupportsCustomExtensions}- caKeyAlgorithm={caKeyAlgorithm}- />- )}- </div>- )}+ {isAzureAdcsCa && (+ <ExternalCaTemplateSelect+ control={control}+ templates={azureAdcsTemplatesData?.templates || []}+ valueKey="id"+ placeholder="Select an Azure ADCS certificate template"+ />+ )}++ {isAdcsCa && (+ <ExternalCaTemplateSelect+ control={control}+ templates={adcsTemplatesData?.templates || []}+ valueKey="name"+ placeholder="Select an ADCS certificate template"+ />+ )}- <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">- {activePolicyStep- ? `Step ${selectedStepIndex + 1}.${(policyStepIndex ?? 0) + 1} · ${activePolicyStep.rightLabel}`- : `Step ${selectedStepIndex + 1} · ${currentStep.rightLabel}`}- </p>- <DocumentationLinkBadge- href={- activePolicyStep- ? PkiDocsUrls.settings.policies- : PkiDocsUrls.settings.profiles- }+ <Controller+ control={control}+ name="certificatePolicyId"+ render={({+ field: { onChange, value, ref, onBlur, name },+ fieldState: { error }+ }) => (+ <Field>+ <FieldLabel>+ Certificate Policy <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Combobox+ ref={ref}+ name={name}+ onBlur={onBlur}+ value={certificatePolicies.find((p) => p.id === value) ?? null}+ onValueChange={(selected) => {+ onChange(selected?.id || "");++ setValue("defaults", undefined);+ }}+ options={certificatePolicies}+ getOptionLabel={(option) => option.name}+ getOptionValue={(option) => option.id}+ placeholder={+ certificatePolicies.length === 0 && !canCreatePolicy+ ? "No certificate policies available"+ : "Select a certificate policy"+ }+ isError={Boolean(error)}+ creation={+ canCreatePolicy && !isEdit+ ? {+ mode: "action",+ emptyLabel: "Add Certificate Policy",+ formatLabel: () => "Add Certificate Policy",+ onAction: () => setPolicyStepIndex(0)+ }+ : undefined+ }+ />+ <FieldDescription>+ The rules that govern certificates issued from this profile: allowed+ key/signature algorithms, key usages, TTL bounds, and subject+ constraints.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}/></div>- <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>- <p className="mt-2 text-sm leading-relaxed text-muted">+ )}++ {currentStep.key === "certificate-defaults" && (+ <ProfileDefaultsStep+ control={control}+ watch={watch}+ setValue={setValue}+ policyConstraints={policyConstraints}+ isAwsAcmPublicCa={isAwsAcmPublicCa}+ isExternalAdcsCa={isAzureAdcsCa || isAdcsCa}+ caSupportsCustomExtensions={caSupportsCustomExtensions}+ caKeyAlgorithm={caKeyAlgorithm}+ />+ )}+ </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">{activePolicyStep- ? activePolicyStep.rightDescription- : currentStep.rightDescription}+ ? `Step ${selectedStepIndex + 1}.${(policyStepIndex ?? 0) + 1} · ${activePolicyStep.rightLabel}`+ : `Step ${selectedStepIndex + 1} · ${currentStep.rightLabel}`}</p>+ <DocumentationLinkBadge+ href={+ activePolicyStep ? PkiDocsUrls.settings.policies : PkiDocsUrls.settings.profiles+ }+ /></div>- </aside>- </div>-- <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-6 py-4">- <span className="text-xs text-muted" />- <div className="flex items-center gap-3">- <span className="text-xs text-muted">- {isPolicyWizardOpen- ? `Profile step ${selectedStepIndex + 1} of ${steps.length} · Policy step ${(policyStepIndex ?? 0) + 1} of ${CERTIFICATE_POLICY_STEPS.length}`- : `Step ${selectedStepIndex + 1} of ${steps.length}`}- </span>- {(selectedStepIndex > 0 || isPolicyWizardOpen) && (- <Button- type="button"- variant="outline"- onClick={isPolicyWizardOpen ? goBackInPolicy : goBack}- >- Back- </Button>- )}- {/* eslint-disable-next-line no-nested-ternary */}- {isPolicyWizardOpen ? (- <Button- key="policy-cta"- type="button"- variant="project"- isPending={isPolicySubmitting}- isDisabled={isPolicySubmitting}- onClick={goNextInPolicy}- >- {isFinalPolicyStep ? "Create Policy" : "Continue"}- </Button>- ) : isFinalStep ? (- <Button- key="submit-cta"- type="button"- variant="project"- isPending={isSubmitting}- isDisabled={isSubmitting}- onClick={handleSubmit(onFormSubmit, (errors) => {- const errorKeys = Object.keys(errors);- const stepIndex = steps.findIndex((s) =>- s.fields.some((fld) => errorKeys.includes(fld))- );- if (stepIndex >= 0) setSelectedStepIndex(stepIndex);- createNotification({- text: "Please fix the highlighted errors before saving.",- type: "error"- });- })}- >- {isEdit ? "Save Changes" : "Create Profile"}- </Button>- ) : (- <Button key="continue-cta" type="button" variant="project" onClick={goNext}>- Continue- </Button>- )}+ <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>+ <p className="mt-2 text-sm leading-relaxed text-muted">+ {activePolicyStep+ ? activePolicyStep.rightDescription+ : currentStep.rightDescription}+ </p></div>+ </aside>+ </fieldset>+ {completionError && <FieldError className="px-4">{completionError}</FieldError>}++ <SheetFooter className="justify-between border-t">+ <div className="flex items-center gap-3">+ {(selectedStepIndex > 0 || isPolicyWizardOpen) && (+ <Button+ type="button"+ variant="outline"+ isDisabled={isSubmitting || isPolicySubmitting || Boolean(savedProfile)}+ onClick={isPolicyWizardOpen ? goBackInPolicy : goBack}+ >+ Back+ </Button>+ )}+ <span className="text-xs text-muted">+ {isPolicyWizardOpen+ ? `Profile step ${selectedStepIndex + 1} of ${steps.length} · Policy step ${(policyStepIndex ?? 0) + 1} of ${CERTIFICATE_POLICY_STEPS.length}`+ : `Step ${selectedStepIndex + 1} of ${steps.length}`}+ </span></div>- </form>- </SheetContent>- </Sheet>+ <div className="flex items-center gap-2">+ <Button+ type="button"+ variant="ghost"+ isDisabled={isSubmitting || isPolicySubmitting}+ onClick={handleClose}+ >+ Cancel+ </Button>+ {/* eslint-disable-next-line no-nested-ternary */}+ {isPolicyWizardOpen ? (+ <Button+ key="policy-cta"+ type="submit"+ variant="project"+ isPending={isPolicySubmitting}+ isDisabled={isPolicySubmitting}+ >+ {isFinalPolicyStep ? "Create Policy" : "Continue"}+ </Button>+ ) : isFinalStep ? (+ <Button+ key="submit-cta"+ type="submit"+ variant="project"+ isPending={isSubmitting}+ isDisabled={isSubmitting}+ >+ {submitLabel}+ </Button>+ ) : (+ <Button key="continue-cta" type="submit" variant="project" isDisabled={isSubmitting}>+ Continue+ </Button>+ )}+ </div>+ </SheetFooter>+ </form>+ {caCreationModals}+ </>+ );+};++export const CreateProfileModal = ({ isOpen, onClose, ...props }: Props) => {+ const [isDirty, setIsDirty] = useState(false);+ const [isPending, setIsPending] = useState(false);+ const { requestDiscard, confirmDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen } =+ useDiscardChangesGuard({ isDirty, onDiscard: onClose });++ return (+ <>+ <Sheet+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) requestDiscard();+ }}+ >+ <SheetContent size="workspace" isPending={isPending}>+ <CreateProfileForm+ {...props}+ isOpen={isOpen}+ onClose={onClose}+ onCancel={requestDiscard}+ onDirtyChange={setIsDirty}+ onPendingChange={setIsPending}+ />+ </SheetContent>+ </Sheet>+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Profile Changes?"+ description="Your unsaved profile configuration will be lost."+ />+ </>);};diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation.tsxnew file mode 100644index 0000000000..b1b4826c1e--- /dev/null+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation.tsx@@ -0,0 +1,97 @@+import { useRef, useState } from "react";+import { subject } from "@casl/ability";++import { ComboboxSheetCreationConfig, DiscardChangesAlertDialog } from "@app/components/v3";+import {+ ProjectPermissionCertificateProfileActions,+ ProjectPermissionSub,+ useProjectPermission+} from "@app/context";+import { TCertificateProfile } from "@app/hooks/api/certificateProfiles";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";++import { CreateProfileForm } from "./CreateProfileModal";++type ProfileOption = { value: string; label: string };++export const useProfileCreation = <TOption = ProfileOption,>(+ onCreated: (profile: TCertificateProfile) => void | Promise<void>+): ComboboxSheetCreationConfig<TOption> | undefined => {+ const { permission } = useProjectPermission();+ const [isDirty, setIsDirty] = useState(false);+ const [isPending, setIsPending] = useState(false);+ const cancelRef = useRef(() => {});+ const { requestDiscard, confirmDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen } =+ useDiscardChangesGuard({+ isDirty,+ onDiscard: () => {+ setIsDirty(false);+ cancelRef.current();+ }+ });+ const requestCancel = (cancel: () => void) => {+ cancelRef.current = cancel;+ requestDiscard();+ };+ const canAttachProfile = (slug: string) =>+ permission.can(+ ProjectPermissionCertificateProfileActions.ManageApplicationAttachments,+ subject(ProjectPermissionSub.CertificateProfiles, { slug })+ );++ if (+ !permission.can(+ ProjectPermissionCertificateProfileActions.Create,+ ProjectPermissionSub.CertificateProfiles+ ) ||+ !permission.can(+ ProjectPermissionCertificateProfileActions.ManageApplicationAttachments,+ ProjectPermissionSub.CertificateProfiles+ )+ )+ return undefined;++ return {+ mode: "sheet",+ size: "workspace",+ showHeader: false,+ emptyLabel: "Create New Profile",+ isPending,+ onDismiss: requestCancel,+ renderForm: ({ initialInput, complete, cancel }) => (+ <>+ <CreateProfileForm+ isOpen+ onClose={complete}+ onCancel={() => requestCancel(cancel)}+ onComplete={(profile) => {+ if (!canAttachProfile(profile.slug)) {+ throw new Error(+ "The profile was created, but you no longer have permission to attach it to an application."+ );+ }+ return onCreated(profile);+ }}+ initialSlug={initialInput}+ validateSlug={(slug) =>+ permission.can(+ ProjectPermissionCertificateProfileActions.Create,+ subject(ProjectPermissionSub.CertificateProfiles, { slug })+ ) && canAttachProfile(slug)+ ? undefined+ : "You don't have permission to create and attach a profile with this name. Choose an allowed name."+ }+ onDirtyChange={setIsDirty}+ onPendingChange={setIsPending}+ />+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Profile Changes?"+ description="Your unsaved profile configuration will be lost."+ />+ </>+ )+ };+};diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsxindex 80d4dd85a7..e292b372ea 100644--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx@@ -1,13 +1,14 @@import { useState } from "react";import { useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { ShieldCheckIcon } from "lucide-react";import { createNotification } from "@app/components/notifications";import {Button,+ DiscardChangesAlertDialog,Sheet,SheetContent,+ SheetDescription,SheetFooter,SheetHeader,SheetTitle,@@ -16,6 +17,7 @@ import {StepperStep} from "@app/components/v3";import { THsmConnector, useCreateHsmConnector } from "@app/hooks/api/hsmConnectors";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";import { AccessStep } from "./AccessStep";import { BasicsStep } from "./BasicsStep";@@ -68,13 +70,28 @@ export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange, onCreated }: PraccessForm.reset({ slotLabel: "", pin: "", keyNamePrefix: "infisical-" });};+ const dirty =+ step > 0 ||+ basicsForm.formState.isDirty ||+ hostForm.formState.isDirty ||+ accessForm.formState.isDirty ||+ JSON.stringify(state) !== JSON.stringify(INITIAL_WIZARD_STATE);+ const { isDiscardDialogOpen, setIsDiscardDialogOpen, requestDiscard, confirmDiscard } =+ useDiscardChangesGuard({+ isDirty: dirty,+ onDiscard: () => {+ reset();+ onOpenChange(false);+ }+ });const handleClose = (open: boolean) => {- if (!open && submitting) return;- if (!open) reset();- onOpenChange(open);+ if (submitting) return;+ if (open) onOpenChange(true);+ else requestDiscard();};const onCreate = async (finalState: WizardState) => {+ if (submitting) return;setSubmitting(true);try {const [kind, id] = finalState.reachedFrom.split(":");@@ -93,7 +110,8 @@ export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange, onCreated }: Prtype: "success",text: `HSM Connector "${finalState.name}" created and verified.`});- handleClose(false);+ reset();+ onOpenChange(false);onCreated?.(connector);// eslint-disable-next-line no-empty} catch {@@ -103,6 +121,7 @@ export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange, onCreated }: Pr};const goNext = async () => {+ if (submitting) return;if (step === 0) {const ok = await basicsForm.trigger();if (!ok) return;@@ -139,111 +158,117 @@ export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange, onCreated }: Pr};const goBack = () => {- if (step > 0) setStep((s) => s - 1);+ if (step > 0 && !submitting) setStep((s) => s - 1);};- const dirty = step > 0 || state.name !== "";const currentStep = STEPS[step];const isLast = step === STEPS.length - 1;const ctaLabel = isLast ? "Add HSM Connector" : "Continue";return (- <Sheet open={isOpen} onOpenChange={handleClose}>- <SheetContent size="workspace" className="flex h-full max-h-full flex-col gap-y-0">- <SheetHeader className="border-b">- <SheetTitle>- <div className="flex w-full items-start gap-2">- <div className="flex h-10 w-10 items-center justify-center rounded-md bg-project/10 text-project">- <ShieldCheckIcon className="h-5 w-5" />- </div>- <div>- <div className="flex items-center gap-x-2 text-label">Add HSM Connector</div>- <p className="text-sm leading-4 text-muted">- Register a hardware security module so Infisical can route key operations through- it.+ <>+ <Sheet open={isOpen} onOpenChange={handleClose}>+ <SheetContent size="workspace" isPending={submitting}>+ <SheetHeader>+ <SheetTitle>Add HSM Connector</SheetTitle>+ <SheetDescription>+ Register a hardware security module so Infisical can route key operations through it.+ </SheetDescription>+ </SheetHeader>++ <div className="flex min-h-0 flex-1 flex-col">+ <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>- </div>- </div>- </SheetTitle>- </SheetHeader>-- <div className="flex min-h-0 flex-1 flex-col">- <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={step}- orientation="vertical"- onStepChange={(i) => {- if (i < step) setStep(i);- }}+ <Stepper+ activeStep={step}+ orientation="vertical"+ onStepChange={(i) => {+ if (i < step && !submitting) setStep(i);+ }}+ >+ <StepperList>+ {STEPS.map((s, i) => (+ <StepperStep+ key={s.name}+ index={i}+ title={s.name}+ description={s.shortDescription}+ />+ ))}+ </StepperList>+ </Stepper>+ </aside>++ <fieldset+ disabled={submitting}+ className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">- <StepperList>- {STEPS.map((s, i) => (- <StepperStep- key={s.name}- index={i}- title={s.name}- description={s.shortDescription}- />- ))}- </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>-- {step === 0 && <BasicsStep form={basicsForm} />}- {step === 1 && <HostStep form={hostForm} />}- {step === 2 && <AccessStep form={accessForm} />}- </div>+ <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>- <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>- <p className="text-[11px] font-medium tracking-wider text-muted uppercase">- Step {step + 1} · {currentStep.rightLabel}- </p>- <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>- <p className="mt-2 text-sm leading-relaxed text-muted">- {currentStep.rightDescription}- </p>- </div>+ {step === 0 && <BasicsStep form={basicsForm} />}+ {step === 1 && <HostStep form={hostForm} />}+ {step === 2 && <AccessStep form={accessForm} />}+ </fieldset>- <div className="mt-auto space-y-3">- {isLast && (- <p className="text-xs leading-relaxed text-muted">- Infisical runs a Verify against your HSM before saving. A wrong PIN, slot, or- unreachable Gateway will surface here.+ <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>+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">+ Step {step + 1} · {currentStep.rightLabel}</p>- )}- </div>- </aside>- </div>+ <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>+ <p className="mt-2 text-sm leading-relaxed text-muted">+ {currentStep.rightDescription}+ </p>+ </div>- <SheetFooter className="shrink-0 items-center justify-between border-t">- <span className="text-xs text-muted">{dirty ? "Unsaved changes" : ""}</span>- <div className="flex items-center gap-3">- <span className="text-xs text-muted">- Step {step + 1} of {STEPS.length}- </span>+ <div className="mt-auto space-y-3">+ {isLast && (+ <p className="text-xs leading-relaxed text-muted">+ Infisical runs a Verify against your HSM before saving. A wrong PIN, slot, or+ unreachable Gateway will surface here.+ </p>+ )}+ </div>+ </aside>+ </div>++ <SheetFooter className="items-center justify-end border-t">{step > 0 && (- <Button variant="outline" onClick={goBack}>+ <Button+ variant="outline"+ className="mr-auto"+ onClick={goBack}+ isDisabled={submitting}+ >Back</Button>)}+ <span className="text-xs text-muted">+ Step {step + 1} of {STEPS.length}+ </span>+ <Button variant="ghost" onClick={() => handleClose(false)} isDisabled={submitting}>+ Cancel+ </Button><Button variant="project" onClick={goNext} isPending={submitting}>{ctaLabel}</Button>- </div>- </SheetFooter>- </div>- </SheetContent>- </Sheet>+ </SheetFooter>+ </div>+ </SheetContent>+ </Sheet>+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Changes?"+ description="Your HSM connector setup changes will be lost."+ />+ </>);};diff --git a/frontend/src/pages/cert-manager/components/AdcsTemplateField.tsx b/frontend/src/pages/cert-manager/components/AdcsTemplateField.tsxindex 91708180c1..c2235132aa 100644--- a/frontend/src/pages/cert-manager/components/AdcsTemplateField.tsx+++ b/frontend/src/pages/cert-manager/components/AdcsTemplateField.tsx@@ -1,14 +1,14 @@-import type { JSX } from "react";+import { type JSX, useId } from "react";import { Control, Controller, FieldValues, Path } from "react-hook-form";import { InfoIcon } from "lucide-react";import {+ Combobox,Field,FieldContent,FieldDescription,FieldError,FieldLabel,- FilterableSelect,Input,Tooltip,TooltipContent,@@ -29,6 +29,7 @@ export const AdcsTemplateField = <T extends FieldValues>({connectionId,description}: Props<T>) => {+ const inputId = useId();const { data: templates = [], isLoading } = useAdcsConnectionListCertificateTemplates(connectionId ?? "",{@@ -46,22 +47,29 @@ export const AdcsTemplateField = <T extends FieldValues>({let templateControl: JSX.Element;if (isLoading && connectionId) {templateControl = (- <FilterableSelect+ <Combobox<Option>+ id={inputId}isLoadingisDisabledoptions={[]}value={null}- onChange={() => {}}+ onValueChange={() => {}}+ getOptionLabel={(option) => option.label}+ getOptionValue={(option) => option.value}placeholder="Loading templates..."/>);} else if (options.length > 0) {templateControl = (- <FilterableSelect<Option>+ <Combobox<Option>+ id={inputId}isClearableoptions={options}value={options.find((o) => o.value === field.value) ?? null}- onChange={(selected) => field.onChange((selected as Option | null)?.value ?? "")}+ onValueChange={(selected) => field.onChange(selected?.value ?? "")}+ name={field.name}+ onBlur={field.onBlur}+ ref={field.ref}getOptionLabel={(o) => o.label}getOptionValue={(o) => o.value}placeholder="Select a template..."@@ -71,6 +79,10 @@ export const AdcsTemplateField = <T extends FieldValues>({} else {templateControl = (<Input+ id={inputId}+ name={field.name}+ ref={field.ref}+ onBlur={field.onBlur}value={typeof field.value === "string" ? field.value : ""}onChange={field.onChange}placeholder="e.g. CodeSigning"@@ -81,7 +93,7 @@ export const AdcsTemplateField = <T extends FieldValues>({return (<Field>- <FieldLabel>+ <FieldLabel htmlFor={inputId}><span className="inline-flex items-center gap-1.5">Certificate Template <span className="text-danger">*</span><Tooltip>diff --git a/frontend/src/pages/cert-manager/components/useCaCreation.tsx b/frontend/src/pages/cert-manager/components/useCaCreation.tsxnew file mode 100644index 0000000000..bdb4dda707--- /dev/null+++ b/frontend/src/pages/cert-manager/components/useCaCreation.tsx@@ -0,0 +1,161 @@+import { useId, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";++import {+ CertificateAuthoritiesUpgradeIntent,+ useUpgradeGate+} from "@app/components/license/UpgradeGate";+import { createNotification } from "@app/components/notifications";+import {+ Button,+ ComboboxActionCreationConfig,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldLabel,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3";+import {+ ProjectPermissionCertificateAuthorityActions,+ ProjectPermissionSub,+ useProjectPermission+} from "@app/context";+import { caKeys, useGetCaQuota } from "@app/hooks/api/ca/queries";+import { TUnifiedCertificateAuthority } from "@app/hooks/api/ca/types";+import { usePopUp } from "@app/hooks/usePopUp";++import { CreateCaWizard } from "../CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard";+import { ExternalCaModal } from "../CertificateAuthoritiesPage/components/ExternalCaModal";++export const useCaCreation = <TOption,>(+ onCreated: (ca: TUnifiedCertificateAuthority) => void | Promise<void>+) => {+ const { permission } = useProjectPermission();+ const canCreate = permission.can(+ ProjectPermissionCertificateAuthorityActions.Create,+ ProjectPermissionSub.CertificateAuthorities+ );+ const inputId = useId();+ const queryClient = useQueryClient();+ const { data: quota } = useGetCaQuota({ enabled: canCreate });+ const { openUpgradeGate, upgradeGate } = useUpgradeGate();+ const [isChooserOpen, setIsChooserOpen] = useState(false);+ const [isInternalOpen, setIsInternalOpen] = useState(false);+ const [kind, setKind] = useState("internal");+ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["ca"] as const);++ const acceptCreated = async (ca: TUnifiedCertificateAuthority) => {+ await queryClient.refetchQueries({ queryKey: caKeys.listCasByProjectId() });+ const listedCa = queryClient+ .getQueryData<TUnifiedCertificateAuthority[]>(caKeys.listCasByProjectId())+ ?.find((option) => option.id === ca.id);+ if (!listedCa) {+ createNotification({+ type: "error",+ text: "The certificate authority was created, but the list could not be refreshed. Refresh the list to select it."+ });+ return;+ }+ await onCreated(listedCa);+ };++ const startCreation = () => {+ setIsChooserOpen(false);+ const limits =+ kind === "internal"+ ? [quota?.certificateAuthorities, quota?.internalCertificateAuthorities]+ : [quota?.certificateAuthorities];+ if (limits.some((limit) => typeof limit?.limit === "number" && limit.used >= limit.limit)) {+ openUpgradeGate({+ intent: CertificateAuthoritiesUpgradeIntent,+ paywallKey: kind === "internal" ? "cert-manager.ca" : "cert-manager.external-ca"+ });+ return;+ }+ if (kind === "internal") {+ setIsInternalOpen(true);+ return;+ }+ handlePopUpOpen("ca");+ };++ const creation: ComboboxActionCreationConfig<TOption> | undefined = canCreate+ ? {+ mode: "action",+ emptyLabel: "Create Certificate Authority",+ formatLabel: () => "Create Certificate Authority",+ onAction: () => {+ setKind("internal");+ setIsChooserOpen(true);+ }+ }+ : undefined;++ return {+ creation,+ caCreationModals: (+ <>+ <Dialog open={isChooserOpen} onOpenChange={setIsChooserOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Create Certificate Authority</DialogTitle>+ <DialogDescription>+ Choose where the certificate authority is hosted.+ </DialogDescription>+ </DialogHeader>+ <form+ className="flex min-h-0 flex-1 flex-col"+ onSubmit={(event) => {+ event.preventDefault();+ startCreation();+ }}+ >+ <DialogBody>+ <Field>+ <FieldLabel htmlFor={inputId}>Certificate Authority Type</FieldLabel>+ <Select value={kind} onValueChange={setKind}>+ <SelectTrigger id={inputId}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="internal">Internal</SelectItem>+ <SelectItem value="external">External</SelectItem>+ </SelectContent>+ </Select>+ </Field>+ </DialogBody>+ <DialogFooter>+ <Button variant="ghost" onClick={() => setIsChooserOpen(false)}>+ Cancel+ </Button>+ <Button type="submit" variant="project">+ Continue+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ {isInternalOpen && (+ <CreateCaWizard isOpen onOpenChange={setIsInternalOpen} onComplete={acceptCreated} />+ )}+ {popUp.ca.isOpen && (+ <ExternalCaModal+ popUp={popUp}+ handlePopUpToggle={handlePopUpToggle}+ onComplete={acceptCreated}+ />+ )}+ {upgradeGate}+ </>+ )+ };+};