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
Merge remote-tracking branch 'origin/main' into PKI-336
Carlos Monastyrskie02e622ec9f5
diff --cc backend/src/lib/api-docs/constants.tsindex 554982f78c,1e61ab6c1d..77319d388e--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@@ -2085,17 -2086,7 +2086,17 @@@ export const CERTIFICATE_AUTHORITIES =export const CERTIFICATES = {GET: {id: "The ID of the certificate to get.",- serialNumber: "The serial number of the certificate to get."+ serialNumber: "The serial number of the certificate to get.",+ hasPrivateKey: "Whether Infisical holds the private key for this certificate."+ },+ RENEW: {+ id: "The ID of the certificate to renew.",+ renewalKeySource:- "How the renewed certificate's key pair is handled. 'new' generates a fresh pair, 'reuse' keeps the current one so the renewed certificate carries the same public key, and 'csr' takes the key from a supplied signing request. Omitting this generates a new key pair, and additionally declines to renew a certificate that was issued from a signing request, since that would change which key the certificate certifies without the caller saying so.",++ "How the renewed certificate's key pair is handled. 'new' generates a fresh pair, 'reuse' keeps the current one so the renewed certificate carries the same public key, and 'csr' takes the key from a supplied signing request. Defaults to 'new'.",+ csr: "A PEM-encoded certificate signing request to renew from. Its subject, key and extensions take precedence, so only TTL and basic constraints may be set alongside it.",+ attributes:+ "Certificate fields to change on renewal. Anything omitted is copied from the certificate being renewed. Profile defaults are not applied.",+ removeRootsFromChain: "Whether to remove the root certificate from the returned certificate chain."},REVOKE: {id: "The ID or SHA-1/SHA-256 thumbprint of the certificate to revoke. Thumbprint colons and casing are ignored.",diff --cc backend/src/services/certificate-v3/certificate-self-signed-fns.tsindex 472e36d60b,0000000000..a7b9c9f9d0mode 100644,000000..100644--- a/backend/src/services/certificate-v3/certificate-self-signed-fns.ts+++ b/backend/src/services/certificate-v3/certificate-self-signed-fns.ts@@@ -1,260 -1,0 +1,256 @@@+import { BadRequestError } from "@app/lib/errors";+import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";+import { extractCertificateFields } from "@app/services/certificate/certificate-fns";+import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";+import { CertKeyAlgorithm, CertSignatureAlgorithm, CertStatus } from "@app/services/certificate/certificate-types";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { TProjectDALFactory } from "@app/services/project/project-dal";+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";++import {+ CertExtendedKeyUsageType,+ CertKeyUsageType,+ CertSubjectAlternativeNameType+} from "../certificate-common/certificate-constants";+import { generateSelfSignedCertificate } from "../certificate-common/certificate-issuance-utils";+import {+ convertExtendedKeyUsageArrayToLegacy,+ convertKeyUsageArrayToLegacy+} from "../certificate-common/certificate-utils";++import { TSubjectRule } from "../certificate-policy/certificate-policy-types";++const createSelfSignedCertificateRecord = async ({+ selfSignedResult,+ certificateRequest,+ profile,+ originalCert,+ certificateDAL,+ tx,+ isRenewal = false+}: {+ selfSignedResult: Awaited<ReturnType<typeof generateSelfSignedCertificate>>;+ certificateRequest: {+ commonName?: string;+ keyUsages?: CertKeyUsageType[];+ extendedKeyUsages?: CertExtendedKeyUsageType[];+ };+ profile?: { id: string; projectId: string } | null;+ originalCert?: {+ id: string;+ friendlyName?: string | null;+ commonName?: string | null;+ projectId: string;+ };+ certificateDAL: Pick<TCertificateDALFactory, "create" | "updateById">;+ tx: Parameters<TCertificateDALFactory["create"]>[1];+ isRenewal?: boolean;+}) => {+ const subjectCommonName =+ (selfSignedResult.certificateSubject.common_name as string) ||+ certificateRequest.commonName ||+ originalCert?.commonName ||+ "";++ const altNamesList = selfSignedResult.subjectAlternativeNames.map((san) => san.value).join(",");++ const projectId = originalCert?.projectId || profile?.projectId;+ if (!projectId) {+ throw new BadRequestError({ message: "Project ID is required for certificate creation" });+ }++ const baseRecord = {+ serialNumber: selfSignedResult.serialNumber,+ friendlyName: originalCert?.friendlyName || subjectCommonName,+ commonName: subjectCommonName,+ altNames: altNamesList,+ status: CertStatus.ACTIVE,+ notBefore: selfSignedResult.notBefore,+ notAfter: selfSignedResult.notAfter,+ projectId,+ keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],+ profileId: profile?.id || null+ };++ const renewalRecord =+ isRenewal && originalCert+ ? {+ renewedFromCertificateId: originalCert.id+ }+ : {};++ const parsedFields = extractCertificateFields(selfSignedResult.certificate);++ return certificateDAL.create(+ {+ ...baseRecord,+ ...renewalRecord,+ ...parsedFields+ },+ tx+ );+};++const createEncryptedCertificateData = async ({+ certificateId,+ certificate,+ privateKey,+ projectId,+ certificateBodyDAL,+ certificateSecretDAL,+ kmsService,+ projectDAL,+ tx+}: {+ certificateId: string;+ certificate: Buffer;+ privateKey: Buffer;+ projectId: string;+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;+ kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;+ projectDAL: TProjectDALFactory;+ tx: Parameters<TCertificateBodyDALFactory["create"]>[1];+}) => {+ const certificateManagerKeyId = await getProjectKmsCertificateKeyId({+ projectId,+ projectDAL,+ kmsService+ });++ const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKeyId });++ const encryptedCertificate = await kmsEncryptor({+ plainText: certificate+ });++ await certificateBodyDAL.create(+ {+ certId: certificateId,+ encryptedCertificate: encryptedCertificate.cipherTextBlob+ },+ tx+ );++ const encryptedPrivateKey = await kmsEncryptor({+ plainText: privateKey+ });++ await certificateSecretDAL.create(+ {+ certId: certificateId,+ encryptedPrivateKey: encryptedPrivateKey.cipherTextBlob+ },+ tx+ );+};++export const processSelfSignedCertificate = async ({+ certificateRequest,+ policy,+ profile,+ originalCert,+ effectiveAlgorithms,+ certificateDAL,+ certificateBodyDAL,+ certificateSecretDAL,+ kmsService,+ projectDAL,+ tx,+ isRenewal = false,+ existingKeyPair+}: {+ certificateRequest: {+ commonName?: string;+ organization?: string;+ organizationalUnit?: string;+ country?: string;+ state?: string;+ locality?: string;+ domainComponents?: string[];+ keyUsages?: CertKeyUsageType[];+ extendedKeyUsages?: CertExtendedKeyUsageType[];+ altNames?: Array<{ type: CertSubjectAlternativeNameType; value: string }>;+ validity: { ttl: string };+ notBefore?: Date;+ notAfter?: Date;+ };+ policy?: {- subject?: Array<{- type: string;- allowed?: string[];- required?: string[];- denied?: string[];- }>;++ subject?: TSubjectRule[];+ sans?: Array<{+ type: string;+ allowed?: string[];+ required?: string[];+ denied?: string[];+ }>;+ } | null;+ profile?: { id: string; projectId: string } | null;+ originalCert?: {+ id: string;+ friendlyName?: string | null;+ commonName?: string | null;+ projectId: string;+ };+ effectiveAlgorithms: {+ signatureAlgorithm: CertSignatureAlgorithm;+ keyAlgorithm: CertKeyAlgorithm;+ };+ certificateDAL: Pick<TCertificateDALFactory, "create" | "updateById">;+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;+ kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;+ projectDAL: TProjectDALFactory;+ tx: Parameters<TCertificateDALFactory["create"]>[1];+ isRenewal?: boolean;+ existingKeyPair?: CryptoKeyPair;+}) => {+ const projectId = originalCert?.projectId || profile?.projectId;+ if (!projectId) {+ throw new BadRequestError({ message: "Project ID is required for certificate creation" });+ }++ const selfSignedResult = await generateSelfSignedCertificate({+ certificateRequest,+ policy,+ effectiveSignatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,+ effectiveKeyAlgorithm: effectiveAlgorithms.keyAlgorithm,+ existingKeyPair+ });++ const certificateData = await createSelfSignedCertificateRecord({+ selfSignedResult,+ certificateRequest,+ profile,+ originalCert,+ certificateDAL,+ tx,+ isRenewal+ });++ await certificateDAL.updateById(+ certificateData.id,+ {+ signatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,+ keyAlgorithm: effectiveAlgorithms.keyAlgorithm+ },+ tx+ );++ await createEncryptedCertificateData({+ certificateId: certificateData.id,+ certificate: selfSignedResult.certificate,+ privateKey: selfSignedResult.privateKey,+ projectId,+ certificateBodyDAL,+ certificateSecretDAL,+ kmsService,+ projectDAL,+ tx+ });++ return {+ selfSignedResult,+ certificateData+ };+};diff --cc frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsxindex 8f37e5b5a4,b11f67f7c9..80b6cb5135--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx@@@ -398,13 -418,13 +399,14 @@@ export const CertificateIssuanceModalreturn keys;}, [requestMethod, constraints.shouldShowSubjectSection, constraints.shouldShowSanSection]);- const currentStepKey = stepKeys[Math.min(step, stepKeys.length - 1)];- const currentStepMeta = STEP_META[currentStepKey];- const isLastStep = step === stepKeys.length - 1;+ const { step, setStep, currentStepKey, goBack, goNext, onFormInvalid } = useWizardSteps({+ stepKeys,+ stepFields: STEP_FIELDS,- invalidMessage: "Please fix the highlighted fields before requesting."++ invalidMessage: "Please fix the highlighted fields before requesting.",++ validateStep: (fields) => trigger(fields as (keyof FormData)[])+ });- useEffect(() => {- if (step > stepKeys.length - 1) setStep(stepKeys.length - 1);- }, [stepKeys.length, step]);+ const steps = useMemo(() => stepKeys.map((key) => STEP_META[key]), [stepKeys]);useEffect(() => {if (cert) {@@@ -550,11 -576,53 +552,18 @@@]);- const getModalTitle = () => {- if (cert) return "Certificate Details";- return "Request New Certificate";- };-- const getModalSubTitle = () => {- if (cert) return "View certificate information";- return "Request a new certificate using a certificate profile";- };-- const selectedProfileReady = Boolean(profileId || actualSelectedProfileId);-- const goBack = () => setStep((s) => Math.max(0, s - 1));- const goNext = async () => {- if (currentStepKey === "profile" && !selectedProfileReady) return;-- const isStepValid = await trigger(STEP_FIELDS[currentStepKey] as (keyof FormData)[]);- if (!isStepValid) {- createNotification({ text: "Fix the errors on this step to continue.", type: "error" });- return;- }-- setStep((s) => Math.min(stepKeys.length - 1, s + 1));- };-+ const rowErrorsOf = (fieldErrors: unknown): (string | undefined)[] | undefined =>+ Array.isArray(fieldErrors)+ ? (fieldErrors as ({ value?: { message?: string } } | undefined)[]).map(+ (rowError) => rowError?.value?.message+ )+ : undefined;+- const onFormInvalid = (errors: Record<string, unknown>) => {- const errorKeys = Object.keys(errors);- const idx = stepKeys.findIndex((key) =>- STEP_FIELDS[key].some((fieldName) => errorKeys.includes(fieldName))- );- if (idx >= 0) setStep(idx);- createNotification({- text: "Please fix the highlighted fields before requesting.",- type: "error"- });- };+ const selectedProfileReady = Boolean(profileId || actualSelectedProfileId);return (- <Sheet- open={popUp?.issueCertificate?.isOpen}+ <CertificateWizardSheet+ isOpen={Boolean(popUp?.issueCertificate?.isOpen)}onOpenChange={(isOpen) => {handlePopUpToggle("issueCertificate", isOpen);if (!isOpen) {@@@ -588,296 -653,479 +597,299 @@@<p className="text-sm text-muted">Common Name: {cert.commonName}</p><p className="text-sm text-muted">Status: {cert.status}</p></div>- ) : (- <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={step}- orientation="vertical"- onStepChange={(i) => {- if (isSubmitting) return;- if (i < step) setStep(i);- }}- >- <StepperList>- {stepKeys.map((key, i) => (- <StepperStep- key={key}- index={i}- title={STEP_META[key].name}- description={STEP_META[key].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-semibold text-foreground">{currentStepMeta.title}</h2>- <p className="mt-1 text-sm text-muted">{currentStepMeta.subtitle}</p>- </div>-- {currentStepKey === "profile" && (- <div className="space-y-5">- <Controller- control={control}- name="requestMethod"- render={({ field: { onChange, value } }) => (- <Field>- <FieldLabel>Request Method</FieldLabel>- <FieldContent>- <Select- value={value}- onValueChange={(val) => onChange(val as RequestMethod)}+ ) : undefined+ }+ >+ {currentStepKey === "profile" && (+ <div className="space-y-5">+ <Controller+ control={control}+ name="requestMethod"+ render={({ field: { onChange, value } }) => (+ <Field>+ <FieldLabel>Request Method</FieldLabel>+ <FieldContent>+ <Select value={value} onValueChange={(val) => onChange(val as RequestMethod)}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value={RequestMethod.MANAGED}>Managed</SelectItem>+ <SelectItem value={RequestMethod.CSR}>+ Certificate Signing Request (CSR)+ </SelectItem>+ </SelectContent>+ </Select>+ <FieldDescription>+ Managed generates and manages the private key for you. CSR lets you provide your+ own certificate signing request when you need to manage your own private key.+ </FieldDescription>+ </FieldContent>+ </Field>+ )}+ />++ {!profileId && (+ <Controller+ control={control}+ name="profileId"+ render={({ field: { onChange, value }, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Certificate Profile <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Select value={value || ""} onValueChange={(val) => onChange(val)}>+ <SelectTrigger className="w-full" isError={Boolean(error)}>+ <SelectValue placeholder="Select a certificate profile" />+ </SelectTrigger>+ <SelectContent position="popper">+ {profileOptions.length === 0 && applicationId ? (+ <div className="px-3 py-3 text-xs leading-snug whitespace-normal text-muted">+ No certificate profiles are attached to this Application. Add one under+ this Application's Settings tab.+ </div>+ ) : (+ profileOptions.map(({ profile, isApiEnabled }) => (+ <SelectItem+ key={profile.id}+ value={profile.id}+ disabled={!isApiEnabled}+ description={+ isApiEnabled ? undefined : "API enrollment not configured"+ }>- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={RequestMethod.MANAGED}>Managed</SelectItem>- <SelectItem value={RequestMethod.CSR}>- Certificate Signing Request (CSR)- </SelectItem>- </SelectContent>- </Select>- <FieldDescription>- Managed generates and manages the private key for you. CSR lets you- provide your own certificate signing request when you need to manage- your own private key.- </FieldDescription>- </FieldContent>- </Field>- )}- />-- {!profileId && (- <Controller- control={control}- name="profileId"- render={({ field: { onChange, value }, fieldState: { error } }) => (- <Field>- <FieldLabel>- Certificate Profile <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Select value={value || ""} onValueChange={(val) => onChange(val)}>- <SelectTrigger className="w-full" isError={Boolean(error)}>- <SelectValue placeholder="Select a certificate profile" />- </SelectTrigger>- <SelectContent position="popper">- {profileOptions.length === 0 && applicationId ? (- <div className="px-3 py-3 text-xs leading-snug whitespace-normal text-muted">- No certificate profiles are attached to this Application. Add- one under this Application's Settings tab.- </div>- ) : (- profileOptions.map(({ profile, isApiEnabled }) => (- <SelectItem- key={profile.id}- value={profile.id}- disabled={!isApiEnabled}- description={- isApiEnabled ? undefined : "API enrollment not configured"- }- >- {profile.slug}- </SelectItem>- ))- )}- </SelectContent>- </Select>- {hasDisabledProfiles && (- <FieldDescription>- Profiles without API enrollment configured can't be used- here. Configure API enrollment under this Application's- Settings tab.- </FieldDescription>- )}- {isAdcsProfile && (- <FieldDescription>{externalCaHint}</FieldDescription>- )}- <FieldError errors={[error]} />- </FieldContent>- </Field>+ {profile.slug}+ </SelectItem>+ )))}- />+ </SelectContent>+ </Select>+ {hasDisabledProfiles && (+ <FieldDescription>+ Profiles without API enrollment configured can't be used here.+ Configure API enrollment under this Application's Settings tab.+ </FieldDescription>)}- </div>- )}-- {currentStepKey !== "profile" && (actualSelectedProfile || profileId) && (- <div className="space-y-4">- {currentStepKey === "options" && profileId && isAdcsProfile && (- <p className="mb-4 text-xs text-mineshaft-400">{externalCaHint}</p>- )}-- {currentStepKey === "csr" && (+ {isAdcsProfile && <FieldDescription>{externalCaHint}</FieldDescription>}+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ )}+ </div>+ )}++ {currentStepKey !== "profile" && (actualSelectedProfile || profileId) && (+ <div className="space-y-4">+ {currentStepKey === "options" && profileId && isAdcsProfile && (+ <p className="mb-4 text-xs text-mineshaft-400">{externalCaHint}</p>+ )}++ {currentStepKey === "csr" && (+ <Controller+ control={control}+ name="csr"+ render={({ field: { value, ...field }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>+ Certificate Signing Request (CSR) <span className="text-danger">*</span>+ </FieldLabel>+ <TextArea+ {...field}+ value={value ?? ""}+ spellCheck={false}+ isError={Boolean(error)}+ placeholder={+ "-----BEGIN CERTIFICATE REQUEST-----\n" ++ "MIIByDCCAU4CAQAwfjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWEx\n" ++ "FjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xEjAQBgNVBAoMCURlbW8gQ29ycDEUMBIG\n" ++ "A1UECwwLRW5naW5lZXJpbmcxGDAWBgNVBAMMD2FwcC5leGFtcGxlLmNvbTB2MBAG\n" ++ "ByqGSM49AgEGBSuBBAAiA2IABDHV5yengUugeBcpjsw+iAaxSkCr16LMr3ITyvlM\n" ++ "lDv+AE0Ddc6FsFXJicBfTalM3AKl5F14OCBRfI2jugWJOGCLcKYqRDTDevxQmgCI\n" ++ "IfpRM6+jzPkqe0PsuLhYiRfbFKBRME8GCSqGSIb3DQEJDjFCMEAwPgYDVR0RBDcw\n" ++ "NYIPYXBwLmV4YW1wbGUuY29tghEqLmFwcC5leGFtcGxlLmNvbYIJbG9jYWxob3N0\n" ++ "hwR/AAABMAoGCCqGSM49BAMCA2gAMGUCMGQQYs4lTSc3r/5MlabDx4m+sWaAtDhO\n" ++ "17c3TaoDZOMG6r45mgUskPGTripXV9ItTQIxAJypXNlHnMvks7MO4LmicPqku4MF\n" ++ "IeFqqXMFzC9uAO3iQ8/ji6ukvT6a9A3DE9LLIg==\n" ++ "-----END CERTIFICATE REQUEST-----"+ }+ rows={13}+ className="w-full font-mono text-xs"+ />+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ )}++ {currentStepKey === "subject" && constraints.shouldShowSubjectSection && (+ <SubjectAttributesField+ control={control}+ allowedAttributeTypes={constraints.allowedSubjectAttributeTypes}+ error={+ (formState.errors as { subjectAttributes?: { message?: string } }).subjectAttributes+ ?.message+ }++ rowErrors={rowErrorsOf(++ (formState.errors as { subjectAttributes?: unknown }).subjectAttributes++ )}+ />+ )}++ {currentStepKey === "subject" && constraints.shouldShowSanSection && (+ <SubjectAltNamesField+ control={control}+ allowedSanTypes={constraints.allowedSanTypes}+ error={+ (formState.errors as { subjectAltNames?: { message?: string } }).subjectAltNames+ ?.message+ }+ />+ )}++ {(currentStepKey === "csr" || currentStepKey === "options") && !isAdcsProfile && (+ <Controller+ control={control}+ name="ttl"+ render={({ field, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>+ Time to Live (TTL) <span className="text-danger">*</span>+ </FieldLabel>+ <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(error)} />+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ )}++ {currentStepKey === "options" && (+ <>+ <AlgorithmSelectors+ control={control}+ availableSignatureAlgorithms={availableSignatureAlgorithms}+ availableKeyAlgorithms={availableKeyAlgorithms}+ hideSignatureAlgorithm={isAdcsProfile}+ signatureError={+ (formState.errors as { signatureAlgorithm?: { message?: string } })+ .signatureAlgorithm?.message+ }+ keyError={+ (formState.errors as { keyAlgorithm?: { message?: string } }).keyAlgorithm+ ?.message+ }+ />++ {!isAdcsProfile && (+ <div className="mt-4 space-y-6">+ <KeyUsageSection+ control={control}+ title="Key Usages"+ namePrefix="keyUsages"+ options={filteredKeyUsages}+ requiredUsages={constraints.requiredKeyUsages}+ />+ <KeyUsageSection+ control={control}+ title="Extended Key Usages"+ namePrefix="extendedKeyUsages"+ options={filteredExtendedKeyUsages}+ requiredUsages={constraints.requiredExtendedKeyUsages}+ />+ {constraints.templateAllowsCA && (+ <BasicConstraintsField+ control={control}+ setValue={setValue}+ isCA={watchedIsCA}+ templateRequiresCA={constraints.templateRequiresCA}+ maxPathLength={isAwsPcaProfile ? AWS_PCA_MAX_CA_PATH_LENGTH : undefined}+ isPathLengthRequired={+ isAwsPcaProfile ||+ (typeof constraints.maxPathLength === "number" &&+ constraints.maxPathLength !== -1)+ }+ idPrefix="issuance"+ />+ )}+ </div>+ )}+ </>+ )}++ {currentStepKey === "metadata" && (+ <div>+ <p className="text-sm font-medium text-foreground">Metadata</p>+ {metadataFields.length === 0 ? (+ <Empty className="mt-3 border py-8">+ <EmptyMedia variant="icon">+ <Tags />+ </EmptyMedia>+ <EmptyTitle>No metadata added</EmptyTitle>+ <EmptyContent>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => appendMetadata({ key: "", value: "" })}+ >+ <Plus className="size-4" /> Add entry+ </Button>+ </EmptyContent>+ </Empty>+ ) : (+ <div className="mt-3 space-y-2">+ {metadataFields.map((metaField, index) => (+ <div key={metaField.id} className="flex items-start gap-2"><Controllercontrol={control}- name="csr"- render={({ field: { value, ...field }, fieldState: { error } }) => (- <Field className="mb-4">- <FieldLabel>- Certificate Signing Request (CSR){" "}- <span className="text-danger">*</span>- </FieldLabel>- <TextArea- {...field}- value={value ?? ""}- spellCheck={false}- isError={Boolean(error)}- placeholder={- "-----BEGIN CERTIFICATE REQUEST-----\n" +- "MIIByDCCAU4CAQAwfjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWEx\n" +- "FjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xEjAQBgNVBAoMCURlbW8gQ29ycDEUMBIG\n" +- "A1UECwwLRW5naW5lZXJpbmcxGDAWBgNVBAMMD2FwcC5leGFtcGxlLmNvbTB2MBAG\n" +- "ByqGSM49AgEGBSuBBAAiA2IABDHV5yengUugeBcpjsw+iAaxSkCr16LMr3ITyvlM\n" +- "lDv+AE0Ddc6FsFXJicBfTalM3AKl5F14OCBRfI2jugWJOGCLcKYqRDTDevxQmgCI\n" +- "IfpRM6+jzPkqe0PsuLhYiRfbFKBRME8GCSqGSIb3DQEJDjFCMEAwPgYDVR0RBDcw\n" +- "NYIPYXBwLmV4YW1wbGUuY29tghEqLmFwcC5leGFtcGxlLmNvbYIJbG9jYWxob3N0\n" +- "hwR/AAABMAoGCCqGSM49BAMCA2gAMGUCMGQQYs4lTSc3r/5MlabDx4m+sWaAtDhO\n" +- "17c3TaoDZOMG6r45mgUskPGTripXV9ItTQIxAJypXNlHnMvks7MO4LmicPqku4MF\n" +- "IeFqqXMFzC9uAO3iQ8/ji6ukvT6a9A3DE9LLIg==\n" +- "-----END CERTIFICATE REQUEST-----"- }- rows={13}- className="w-full font-mono text-xs"- />- <FieldError errors={[error]} />- </Field>+ name={`metadata.${index}.key`}+ render={({ field, fieldState: { error } }) => (+ <Input+ {...field}+ placeholder="Key"+ className="flex-1"+ isError={Boolean(error)}+ />)}/>- )}-- {currentStepKey === "subject" && constraints.shouldShowSubjectSection && (- <SubjectAttributesField+ <Controllercontrol={control}- allowedAttributeTypes={constraints.allowedSubjectAttributeTypes}- error={- (formState.errors as { subjectAttributes?: { message?: string } })- .subjectAttributes?.message- }- rowErrors={rowErrorsOf(- (formState.errors as { subjectAttributes?: unknown }).subjectAttributes+ name={`metadata.${index}.value`}+ render={({ field }) => (+ <Input+ {...field}+ value={field.value ?? ""}+ placeholder="Value (optional)"+ className="flex-1"+ />)}/>- )}-- {currentStepKey === "subject" && constraints.shouldShowSanSection && (- <SubjectAltNamesField- control={control}- allowedSanTypes={constraints.allowedSanTypes}- error={- (formState.errors as { subjectAltNames?: { message?: string } })- .subjectAltNames?.message- }- />- )}-- {(currentStepKey === "csr" || currentStepKey === "options") &&- !isAdcsProfile && (- <Controller- control={control}- name="ttl"- render={({ field, fieldState: { error } }) => (- <Field className="mb-4">- <FieldLabel>- Time to Live (TTL) <span className="text-danger">*</span>- </FieldLabel>- <Input- {...field}- placeholder="30d, 1y, 8760h"- isError={Boolean(error)}- />- <FieldError errors={[error]} />- </Field>- )}- />- )}-- {currentStepKey === "options" && (- <>- <AlgorithmSelectors- control={control}- availableSignatureAlgorithms={availableSignatureAlgorithms}- availableKeyAlgorithms={availableKeyAlgorithms}- hideSignatureAlgorithm={isAdcsProfile}- signatureError={- (formState.errors as { signatureAlgorithm?: { message?: string } })- .signatureAlgorithm?.message- }- keyError={- (formState.errors as { keyAlgorithm?: { message?: string } })- .keyAlgorithm?.message- }- />-- {!isAdcsProfile && (- <div className="mt-4 space-y-6">- <KeyUsageSection- control={control}- title="Key Usages"- namePrefix="keyUsages"- options={filteredKeyUsages}- requiredUsages={constraints.requiredKeyUsages}- />- <KeyUsageSection- control={control}- title="Extended Key Usages"- namePrefix="extendedKeyUsages"- options={filteredExtendedKeyUsages}- requiredUsages={constraints.requiredExtendedKeyUsages}- />- {constraints.templateAllowsCA && (- <div>- <p className="text-sm font-medium text-foreground">- Basic Constraints- </p>- <div className="mt-4 space-y-4">- <Controller- control={control}- name="basicConstraints.isCA"- render={({ field: { value, onChange } }) => (- <div className="flex items-start gap-3">- <Checkbox- id="isCA"- variant="project"- isChecked={- constraints.templateRequiresCA || value || false- }- isDisabled={constraints.templateRequiresCA}- onCheckedChange={(checked) => {- if (!constraints.templateRequiresCA) {- onChange(checked);- if (!checked) {- setValue("basicConstraints.pathLength", null);- }- }- }}- />- <span className="text-sm text-foreground">- Issue as Certificate Authority- <span className="mt-1 block text-xs text-muted">- This certificate will be issued with the CA:TRUE- extension.- </span>- </span>- </div>- )}- />-- {watchedIsCA && (- <Controller- control={control}- name="basicConstraints.pathLength"- render={({ field, fieldState: { error } }) => {- const isPathLengthRequired =- isAwsPcaProfile ||- (typeof constraints.maxPathLength === "number" &&- constraints.maxPathLength !== -1);- return (- <Field>- <FieldLabel>- Path Length{" "}- {isPathLengthRequired && (- <span className="text-danger">*</span>- )}- </FieldLabel>- <Input- {...field}- type="number"- min={0}- max={- isAwsPcaProfile- ? AWS_PCA_MAX_CA_PATH_LENGTH- : undefined- }- isError={Boolean(error)}- placeholder={- isPathLengthRequired- ? "Enter path length (required)"- : "Leave empty for no constraint"- }- value={field.value ?? ""}- onChange={(e) => {- const val = e.target.value;- if (val === "") {- field.onChange(null);- } else {- const numVal = parseInt(val, 10);- field.onChange(- Number.isNaN(numVal) ? null : numVal- );- }- }}- />- <FieldDescription>- {isAwsPcaProfile- ? `Sets the pathLen for this CA certificate. Controls how many levels of sub-CAs can exist below. AWS Private CA supports 0 to ${AWS_PCA_MAX_CA_PATH_LENGTH}; 0 means it can only sign end-entity certificates.`- : "Sets the pathLen for this CA certificate. Controls how many levels of sub-CAs can exist below. Empty means unlimited; 0 means it can only sign end-entity certificates."}- </FieldDescription>- <FieldError errors={[error]} />- </Field>- );- }}- />- )}- </div>- </div>- )}- </div>- )}- </>- )}-- {currentStepKey === "metadata" && (- <div>- <p className="text-sm font-medium text-foreground">Metadata</p>- {metadataFields.length === 0 ? (- <Empty className="mt-3 border py-8">- <EmptyMedia variant="icon">- <Tags />- </EmptyMedia>- <EmptyTitle>No metadata added</EmptyTitle>- <EmptyContent>- <Button- type="button"- variant="outline"- size="sm"- onClick={() => appendMetadata({ key: "", value: "" })}- >- <Plus className="size-4" /> Add entry- </Button>- </EmptyContent>- </Empty>- ) : (- <div className="mt-3 space-y-2">- {metadataFields.map((metaField, index) => (- <div key={metaField.id} className="flex items-start gap-2">- <Controller- control={control}- name={`metadata.${index}.key`}- render={({ field, fieldState: { error } }) => (- <Input- {...field}- placeholder="Key"- className="flex-1"- isError={Boolean(error)}- />- )}- />- <Controller- control={control}- name={`metadata.${index}.value`}- render={({ field }) => (- <Input- {...field}- value={field.value ?? ""}- placeholder="Value (optional)"- className="flex-1"- />- )}- />- <IconButton- type="button"- variant="ghost"- aria-label="Remove metadata entry"- onClick={() => removeMetadata(index)}- >- <Trash2 />- </IconButton>- </div>- ))}- <Button- type="button"- variant="outline"- size="sm"- onClick={() => appendMetadata({ key: "", value: "" })}- >- <Plus className="size-4" /> Add entry- </Button>- </div>- )}- </div>- )}- </div>- )}- </div>-- <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">- <div className="mb-auto">- <div className="flex items-center justify-between gap-2">- <p className="text-[11px] font-medium tracking-wider text-muted uppercase">- Step {step + 1} · {currentStepMeta.rightLabel}- </p>- <DocumentationLinkBadge href={PkiDocsUrls.applications.certificates} />- </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">- {currentStepMeta.rightDescription}- </p>- </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">- Step {step + 1} of {stepKeys.length}- </span>- {step > 0 && (- <Button type="button" variant="outline" onClick={goBack}>- Back- </Button>- )}- {isLastStep ? (- <Button- type="button"- variant="project"- isPending={isSubmitting}- isDisabled={isSubmitting || (!actualSelectedProfile && !profileId)}- onClick={handleSubmit(onFormSubmit, onFormInvalid)}- >- Request Certificate- </Button>- ) : (+ <IconButton+ type="button"+ variant="ghost"+ aria-label="Remove metadata entry"+ onClick={() => removeMetadata(index)}+ >+ <Trash2 />+ </IconButton>+ </div>+ ))}<Buttontype="button"- variant="project"- isDisabled={!selectedProfileReady}- onClick={goNext}+ variant="outline"+ size="sm"+ onClick={() => appendMetadata({ key: "", value: "" })}>- Continue+ <Plus className="size-4" /> Add entry</Button>- )}- </div>+ </div>+ )}</div>- </form>- )}- </SheetContent>- </Sheet>+ )}+ </div>+ )}+ </CertificateWizardSheet>);};diff --cc frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsxindex 33741c0d8e,3459beed57..37bbd3cb6a--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx@@@ -1,142 -1,10 +1,150 @@@-import { faRedo } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { useEffect, useMemo, useRef } from "react";+import { Controller, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { useNavigate } from "@tanstack/react-router";+import { RefreshCw } from "lucide-react";+import { z } from "zod";import { createNotification } from "@app/components/notifications";-import { Button, Modal, ModalContent } from "@app/components/v2";+import {+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ Input,+ RadioGroup,+ RadioGroupItem,+ TextArea+} from "@app/components/v3";+import { useOrganization, useProject } from "@app/context";import { useRenewCertificate } from "@app/hooks/api";+import { useGetCertificatePolicyById } from "@app/hooks/api/certificatePolicies";+import { IssuerType, useGetCertificateProfileById } from "@app/hooks/api/certificateProfiles";++import {++ EXTENDED_KEY_USAGES_OPTIONS,++ KEY_USAGES_OPTIONS++} from "@app/hooks/api/certificates/constants";+import {+ CertificateIssuerKind,+ CertificateRenewalKeySource+} from "@app/hooks/api/certificates/enums";+import { useGetCertificateById } from "@app/hooks/api/certificates/queries";import { UsePopUpState } from "@app/hooks/usePopUp";+import { PkiDocsUrls } from "@app/pages/cert-manager/pki-docs-urls";+import {+ CertSubjectAlternativeNameType,+ CertSubjectAttributeType+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";++import { AlgorithmSelectors } from "./AlgorithmSelectors";+import { BasicConstraintsField } from "./BasicConstraintsField";- import { buildRenewalFormDefaults, buildRenewalRequestAttributes } from "./certificateRenewalUtils";++import {++ buildRenewalFormDefaults,++ buildRenewalRequestAttributes,++ unionUsageOptions++} from "./certificateRenewalUtils";+import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";+import { KeyUsageSection } from "./KeyUsageSection";+import { SubjectAltNamesField } from "./SubjectAltNamesField";+import { SubjectAttributesField } from "./SubjectAttributesField";+import {+ DEFAULT_TEMPLATE_CONSTRAINTS,+ deriveTemplateConstraints,+ useCertificatePolicyOptions+} from "./useCertificatePolicy";++const formSchema = z+ .object({+ keySource: z.nativeEnum(CertificateRenewalKeySource),+ csr: z.string().trim().optional(),+ ttl: z.string().trim().min(1, "TTL is required"),+ subjectAttributes: z+ .array(+ z.object({+ type: z.nativeEnum(CertSubjectAttributeType),+ value: z.string().trim().min(1, "Value is required")+ })+ )+ .default([]),+ subjectAltNames: z+ .array(+ z.object({+ type: z.nativeEnum(CertSubjectAlternativeNameType),+ value: z.string().trim().min(1, "Value is required")+ })+ )+ .default([]),+ basicConstraints: z+ .object({+ isCA: z.boolean().default(false),+ pathLength: z.number().min(0).nullable().optional()+ })+ .default({ isCA: false }),+ signatureAlgorithm: z.string().optional(),+ keyAlgorithm: z.string().optional(),+ keyUsages: z.record(z.boolean().optional()).default({}),+ extendedKeyUsages: z.record(z.boolean().optional()).default({})+ })+ .superRefine((data, ctx) => {+ if (data.keySource === CertificateRenewalKeySource.Csr && !data.csr) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["csr"],+ message: "A certificate signing request is required"+ });+ }+ });++export type RenewalFormData = z.infer<typeof formSchema>;++type RenewalStepKey = "setup" | "csr" | "subject" | "options";++const STEP_META: Record<RenewalStepKey, WizardStep> = {+ setup: {+ name: "Renewal Setup",+ shortDescription: "Key pair",+ subtitle: "Choose how this renewal handles the key pair.",+ rightDescription:+ "Decide whether the renewed certificate reuses the existing key pair or generates a new one. The key algorithm is fixed whenever the key is reused."+ },+ csr: {+ name: "Signing Request",+ shortDescription: "CSR and validity",+ subtitle: "Provide the CSR and set the validity for this renewal.",+ rightDescription:+ "The subject, key, and extensions are all taken from the CSR you provide, so there are no separate subject or key usage fields. Only validity is set here."+ },+ subject: {+ name: "Subject",+ shortDescription: "Names and SANs",+ subtitle: "These are copied from the current certificate. Change only what should differ.",+ rightDescription:+ "Subject attributes and alternative names identify the certificate. They start as a copy of the current certificate, and the profile's policy still constrains what they may contain."+ },+ options: {+ name: "Options",+ shortDescription: "Validity and key usage",+ title: "Certificate Options",+ subtitle: "Set validity, algorithms, and key usages within the profile's policy.",+ rightDescription:+ "Profile defaults are not applied on renewal. Every value here starts as a copy of the current certificate and is validated against the profile's policy at issuance."+ }+};++const STEP_FIELDS: Record<RenewalStepKey, string[]> = {+ setup: ["keySource"],+ csr: ["csr", "ttl"],+ subject: ["subjectAttributes", "subjectAltNames"],+ options: [+ "ttl",+ "signatureAlgorithm",+ "keyAlgorithm",+ "keyUsages",+ "extendedKeyUsages",+ "basicConstraints"+ ]+};type Props = {popUp: UsePopUpState<["renewCertificate"]>;@@@ -147,397 -15,66 +155,419 @@@};export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) => {- const { mutateAsync: renewCertificate, isPending: isRenewing } = useRenewCertificate();+ const { currentProject } = useProject();+ const { currentOrg } = useOrganization();+ const navigate = useNavigate();++ const isOpen = Boolean(popUp?.renewCertificate?.isOpen);+ const { certificateId } = (popUp?.renewCertificate?.data as { certificateId?: string }) ?? {};- const onRenewConfirm = async () => {- const { certificateId } = popUp.renewCertificate.data as { certificateId: string };+ const { data: certificateData } = useGetCertificateById(+ isOpen && certificateId ? certificateId : ""+ );+ const certificate = certificateData?.certificate;++ const { data: profile } = useGetCertificateProfileById({+ profileId: certificate?.profileId ?? ""+ });+ const { data: policyData } = useGetCertificatePolicyById({+ policyId: profile?.certificatePolicyId ?? "",+ applicationId: certificate?.applicationId ?? undefined+ });++ const constraints = useMemo(+ () => (policyData ? deriveTemplateConstraints(policyData) : DEFAULT_TEMPLATE_CONSTRAINTS),+ [policyData]+ );++ const isPolicyResolved =+ Boolean(policyData) || (Boolean(profile) && !profile?.certificatePolicyId);+ const {+ filteredKeyUsages,+ filteredExtendedKeyUsages,+ availableSignatureAlgorithms,+ availableKeyAlgorithms+ } = useCertificatePolicyOptions(constraints);++ const { mutateAsync: renewCertificate } = useRenewCertificate();++ const {+ control,+ handleSubmit,+ reset,+ watch,+ setValue,+ formState,+ formState: { isSubmitting }+ } = useForm<RenewalFormData>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ keySource: CertificateRenewalKeySource.New,+ ttl: "",+ subjectAttributes: [],+ subjectAltNames: [],+ basicConstraints: { isCA: false },+ keyUsages: {},+ extendedKeyUsages: {}+ }+ });++ const keySource = watch("keySource");+ const watchedIsCA = watch("basicConstraints.isCA") || false;+ const sanTypesInForm = (watch("subjectAltNames") ?? []).map((san) => san.type).join(",");++ const watchedKeyUsages = Object.keys(watch("keyUsages") ?? {})++ .sort()++ .join(",");++ const watchedExtendedKeyUsages = Object.keys(watch("extendedKeyUsages") ?? {})++ .sort()++ .join(",");+ const subjectTypesInForm = (watch("subjectAttributes") ?? []).map((attr) => attr.type).join(",");++ const selectableSanTypes = useMemo(+ () =>+ Array.from(+ new Set([+ ...constraints.allowedSanTypes,+ ...(sanTypesInForm ? (sanTypesInForm.split(",") as CertSubjectAlternativeNameType[]) : [])+ ])+ ),+ [constraints.allowedSanTypes, sanTypesInForm]+ );+++ // Same reason as the SAN types above: a certificate can carry a usage its policy no longer allows.++ // Rendering it keeps it visible and unsettable, instead of submitting a checkbox nobody can see.++ const selectableKeyUsages = useMemo(++ () => unionUsageOptions(filteredKeyUsages, KEY_USAGES_OPTIONS, watchedKeyUsages),++ [filteredKeyUsages, watchedKeyUsages]++ );++ const selectableExtendedKeyUsages = useMemo(++ () =>++ unionUsageOptions(++ filteredExtendedKeyUsages,++ EXTENDED_KEY_USAGES_OPTIONS,++ watchedExtendedKeyUsages++ ),++ [filteredExtendedKeyUsages, watchedExtendedKeyUsages]++ );+++ const selectableSubjectAttributeTypes = useMemo(+ () =>+ Array.from(+ new Set([+ ...constraints.allowedSubjectAttributeTypes,+ ...(subjectTypesInForm+ ? (subjectTypesInForm.split(",") as CertSubjectAttributeType[])+ : [])+ ])+ ),+ [constraints.allowedSubjectAttributeTypes, subjectTypesInForm]+ );++ const isSelfSigned = certificate+ ? (profile?.issuerType ?? (certificate.caId ? IssuerType.CA : IssuerType.SELF_SIGNED)) ===+ IssuerType.SELF_SIGNED+ : false;+ let reuseRefusalReason: string | undefined;+ if (isSelfSigned && certificate?.hasPrivateKey === false) {+ reuseRefusalReason =+ "Infisical does not hold this certificate's private key, which is what signs a self-signed certificate.";+ } else if (!isSelfSigned && certificate?.caType === CertificateIssuerKind.External) {+ reuseRefusalReason =+ "The issuing certificate authority does not support reusing an existing key pair.";+ }+ const csrRefusalReason = isSelfSigned+ ? "A self-signed certificate is signed by its own private key, which a signing request does not carry."+ : undefined;+ const isReuseAllowed = !reuseRefusalReason;+ const isCsrAllowed = !csrRefusalReason;++ useEffect(() => {+ const isRefused =+ (keySource === CertificateRenewalKeySource.Reuse && !isReuseAllowed) ||+ (keySource === CertificateRenewalKeySource.Csr && !isCsrAllowed);+ if (isRefused) setValue("keySource", CertificateRenewalKeySource.New);+ }, [keySource, isReuseAllowed, isCsrAllowed, setValue]);++ const stepKeys = useMemo<RenewalStepKey[]>(() => {+ if (keySource === CertificateRenewalKeySource.Csr) return ["setup", "csr"];+ const keys: RenewalStepKey[] = ["setup"];+ if (constraints.shouldShowSubjectSection || constraints.shouldShowSanSection)+ keys.push("subject");+ keys.push("options");+ return keys;+ }, [keySource, constraints.shouldShowSubjectSection, constraints.shouldShowSanSection]);++ const { step, setStep, currentStepKey, goBack, goNext, onFormInvalid } = useWizardSteps({+ stepKeys,+ stepFields: STEP_FIELDS,+ invalidMessage: "Please fix the highlighted fields before renewing."+ });++ const steps = useMemo(() => stepKeys.map((key) => STEP_META[key]), [stepKeys]);++ const seededCertificateIdRef = useRef<string | null>(null);+ useEffect(() => {+ if (!isOpen) {+ seededCertificateIdRef.current = null;+ return;+ }+ if (!certificate || !isPolicyResolved || seededCertificateIdRef.current === certificate.id)+ return;++ seededCertificateIdRef.current = certificate.id;+ reset(buildRenewalFormDefaults(certificate, constraints));+ setStep(0);+ }, [isOpen, certificate, isPolicyResolved, constraints, reset]);++ const closeWizard = () => {+ handlePopUpToggle("renewCertificate", false);+ reset();+ setStep(0);+ };++ const onFormSubmit = async (formData: RenewalFormData) => {+ if (!certificateId) return;const result = await renewCertificate({- certificateId+ certificateId,+ renewalKeySource: formData.keySource,+ ...(formData.keySource === CertificateRenewalKeySource.Csr && { csr: formData.csr }),+ attributes: buildRenewalRequestAttributes({ formData, constraints })});- const notificationText = result.certificateRequestId- ? `Certificate renewal initiated successfully. Certificate Request ID: ${result.certificateRequestId}`- : "Certificate renewed successfully";-createNotification({- text: result.certificateId- text: notificationText,++ text: result.certificate+ ? "Certificate renewed successfully"+ : `Certificate renewal submitted. This may take a few minutes to process. Certificate Request ID: ${result.certificateRequestId}`,type: "success"});- handlePopUpToggle("renewCertificate", false);- };+ closeWizard();- const certificateData = popUp.renewCertificate.data as {- certificateId: string;- commonName: string;- profileId: string;+ if (currentOrg?.id && currentProject?.id && result.certificateId && result.certificate) {+ navigate({+ to: "/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId",+ params: {+ orgId: currentOrg.id,+ projectId: currentProject.id,+ certificateId: result.certificateId+ }+ });+ }};+ const keySourceOptions = useMemo(+ () => [+ {+ value: CertificateRenewalKeySource.Reuse,+ label: "Reuse the existing key pair",+ description: certificate?.hasPrivateKey+ ? "Keep the same private and public key."+ : "Renew from the signing request this certificate was issued from, so the public key stays the same.",+ isDisabled: !isReuseAllowed,+ disabledReason: reuseRefusalReason+ },+ {+ value: CertificateRenewalKeySource.New,+ label: "Generate a new key pair",+ description: "Issue the certificate with a brand new key.",+ isDisabled: false+ },+ {+ value: CertificateRenewalKeySource.Csr,+ label: "Use a CSR",+ description: "Provide a certificate signing request with its own key.",+ isDisabled: !isCsrAllowed,+ disabledReason: csrRefusalReason+ }+ ],+ [certificate?.hasPrivateKey, isReuseAllowed, isCsrAllowed, reuseRefusalReason, csrRefusalReason]+ );+return (- <Modal- isOpen={popUp?.renewCertificate?.isOpen}- onOpenChange={(isOpen) => {- handlePopUpToggle("renewCertificate", isOpen);- }}+ <CertificateWizardSheet+ isOpen={isOpen}+ onOpenChange={(open) => (open ? handlePopUpToggle("renewCertificate", true) : closeWizard())}+ icon={<RefreshCw className="h-5 w-5" />}+ title="Renew certificate"+ description={certificate?.commonName || certificate?.friendlyName || "Certificate"}+ steps={steps}+ activeStep={step}+ onStepChange={setStep}+ docsHref={PkiDocsUrls.applications.certificateRenewal}+ submitLabel="Renew certificate"+ onSubmit={handleSubmit(onFormSubmit, onFormInvalid)}+ onBack={goBack}+ onContinue={goNext}+ isSubmitting={isSubmitting}+ isSubmitDisabled={!certificate}+ isContinueDisabled={!certificate}>- <ModalContent title={`Renew Certificate: ${certificateData?.commonName || ""}`}>- <div className="mb-6">- <p className="mb-4 text-sm text-mineshaft-300">- Are you sure you want to renew this certificate now?- </p>+ {currentStepKey === "setup" && (+ <Controller+ control={control}+ name="keySource"+ render={({ field: { onChange, value } }) => (+ <Field>+ <FieldLabel>Key pair</FieldLabel>+ <FieldContent>+ <RadioGroup value={value} onValueChange={onChange} className="gap-2">+ {keySourceOptions.map((option) => (+ <FieldLabel+ key={option.value}+ htmlFor={`key-source-${option.value}`}+ variant="project"+ >+ <Field orientation="horizontal" className="items-center gap-3">+ <div className="min-w-0 flex-1 text-left">+ <p className="text-sm font-medium text-foreground">{option.label}</p>+ <p className="text-xs text-muted">+ {option.isDisabled ? option.disabledReason : option.description}+ </p>+ </div>+ <RadioGroupItem+ id={`key-source-${option.value}`}+ value={option.value}+ disabled={option.isDisabled}+ className="sr-only"+ />+ </Field>+ </FieldLabel>+ ))}+ </RadioGroup>+ </FieldContent>+ </Field>+ )}+ />+ )}++ {currentStepKey === "csr" && (+ <div className="space-y-4">+ <Controller+ control={control}+ name="csr"+ render={({ field: { value, ...field }, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Certificate signing request <span className="text-danger">*</span>+ </FieldLabel>+ <TextArea+ {...field}+ value={value ?? ""}+ spellCheck={false}+ isError={Boolean(error)}+ placeholder="-----BEGIN CERTIFICATE REQUEST-----"+ rows={12}+ className="w-full font-mono text-xs"+ />+ <FieldDescription>+ The subject, key, and extensions are taken from this CSR.+ </FieldDescription>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ <Controller+ control={control}+ name="ttl"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Validity (TTL) <span className="text-danger">*</span>+ </FieldLabel>+ <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(error)} />+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ </div>+ )}++ {currentStepKey === "subject" && (+ <div className="space-y-4">+ {constraints.shouldShowSubjectSection && (+ <SubjectAttributesField+ control={control}+ allowedAttributeTypes={selectableSubjectAttributeTypes}+ error={+ (formState.errors as { subjectAttributes?: { message?: string } }).subjectAttributes+ ?.message+ }+ />+ )}+ {constraints.shouldShowSanSection && (+ <SubjectAltNamesField+ control={control}+ allowedSanTypes={selectableSanTypes}+ error={+ (formState.errors as { subjectAltNames?: { message?: string } }).subjectAltNames+ ?.message+ }+ />+ )}</div>+ )}++ {currentStepKey === "options" && (+ <div className="space-y-4">+ <Controller+ control={control}+ name="ttl"+ render={({ field, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>+ Validity (TTL) <span className="text-danger">*</span>+ </FieldLabel>+ <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(error)} />+ <FieldDescription>+ The renewed certificate is valid for this long, starting now.+ </FieldDescription>+ <FieldError errors={[error]} />+ </Field>+ )}+ />++ <AlgorithmSelectors+ control={control}+ availableSignatureAlgorithms={availableSignatureAlgorithms}+ availableKeyAlgorithms={availableKeyAlgorithms}+ keyAlgorithmDisabledReason={+ keySource === CertificateRenewalKeySource.Reuse+ ? "The key algorithm is fixed while the existing key pair is reused."+ : undefined+ }+ />- <div className="flex items-center gap-3">- <Button- onClick={onRenewConfirm}- colorSchema="primary"- isLoading={isRenewing}- isDisabled={isRenewing}- >- <FontAwesomeIcon icon={faRedo} className="mr-2" />- Renew Now- </Button>- <Button- colorSchema="secondary"- variant="plain"- onClick={() => handlePopUpToggle("renewCertificate", false)}- >- Cancel- </Button>+ <div className="mt-4 space-y-6">+ <KeyUsageSection+ control={control}+ title="Key Usages"+ namePrefix="keyUsages"- options={filteredKeyUsages}++ options={selectableKeyUsages}+ requiredUsages={constraints.requiredKeyUsages}+ />+ <KeyUsageSection+ control={control}+ title="Extended Key Usages"+ namePrefix="extendedKeyUsages"- options={filteredExtendedKeyUsages}++ options={selectableExtendedKeyUsages}+ requiredUsages={constraints.requiredExtendedKeyUsages}+ />+ {constraints.templateAllowsCA && (+ <BasicConstraintsField+ control={control}+ setValue={setValue}+ isCA={watchedIsCA}+ templateRequiresCA={constraints.templateRequiresCA}+ maxPathLength={+ constraints.maxPathLength === -1 ? undefined : constraints.maxPathLength+ }+ idPrefix="renewal"+ />+ )}+ </div></div>- </ModalContent>- </Modal>+ )}+ </CertificateWizardSheet>);};diff --cc frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsxindex b0b7dc3abe,0000000000..c1ec430a8fmode 100644,000000..100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx@@@ -1,213 -1,0 +1,219 @@@+import { ReactNode, useCallback, useMemo, useState } from "react";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ DocumentationLinkBadge,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ Stepper,+ StepperList,+ StepperStep+} from "@app/components/v3";++export type WizardStep = {+ name: string;+ shortDescription: string;+ title?: string;+ subtitle: string;+ rightLabel?: string;+ rightDescription: string;+};++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ icon: ReactNode;+ title: string;+ description?: string;+ steps: WizardStep[];+ activeStep: number;+ onStepChange: (index: number) => void;+ docsHref?: string;+ children: ReactNode;+ overrideContent?: ReactNode;+ submitLabel: string;+ onSubmit: () => void;+ onBack: () => void;+ onContinue: () => void;+ isSubmitting?: boolean;+ isSubmitDisabled?: boolean;+ isContinueDisabled?: boolean;+};++export const useWizardSteps = <TStepKey extends string>({+ stepKeys,+ stepFields,- invalidMessage++ invalidMessage,++ validateStep+}: {+ stepKeys: readonly TStepKey[];+ stepFields: Record<TStepKey, string[]>;+ invalidMessage: string;++ /** Gates Continue on the current step's fields, so errors surface where they can be fixed. */++ validateStep?: (fields: string[]) => Promise<boolean>;+}) => {+ const [step, setStep] = useState(0);+ const activeStep = Math.min(step, stepKeys.length - 1);+- const goBack = useCallback(() => setStep((s) => Math.max(0, s - 1)), []);- const goNext = useCallback(- () => setStep((s) => Math.min(stepKeys.length - 1, s + 1)),- [stepKeys.length]- );++ const goBack = useCallback(() => setStep(Math.max(0, activeStep - 1)), [activeStep]);++ const goNext = useCallback(async () => {++ if (validateStep && !(await validateStep(stepFields[stepKeys[activeStep]]))) {++ createNotification({ text: "Fix the errors on this step to continue.", type: "error" });++ return;++ }++ setStep(Math.min(stepKeys.length - 1, activeStep + 1));++ }, [stepKeys, stepFields, activeStep, validateStep]);++ const onFormInvalid = useCallback(+ (errors: Record<string, unknown>) => {+ const errorKeys = Object.keys(errors);+ const idx = stepKeys.findIndex((key) =>+ stepFields[key].some((name) => errorKeys.includes(name))+ );+ if (idx >= 0) setStep(idx);+ createNotification({ text: invalidMessage, type: "error" });+ },+ [stepKeys, stepFields, invalidMessage]+ );++ return {+ step: activeStep,+ setStep,+ currentStepKey: stepKeys[activeStep],+ isLastStep: activeStep === stepKeys.length - 1,+ goBack,+ goNext,+ onFormInvalid+ };+};++export const CertificateWizardSheet = ({+ isOpen,+ onOpenChange,+ icon,+ title,+ description,+ steps,+ activeStep,+ onStepChange,+ docsHref,+ children,+ overrideContent,+ submitLabel,+ onSubmit,+ onBack,+ onContinue,+ isSubmitting = false,+ isSubmitDisabled = false,+ isContinueDisabled = false+}: Props) => {+ const step = steps[Math.min(activeStep, steps.length - 1)];+ const isLastStep = activeStep === steps.length - 1;++ const stepperSteps = useMemo(+ () =>+ steps.map((s, i) => (+ <StepperStep key={s.name} index={i} title={s.name} description={s.shortDescription} />+ )),+ [steps]+ );++ return (+ <Sheet open={isOpen} onOpenChange={onOpenChange}>+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 p-0 sm:max-w-[1100px]">+ <SheetHeader className="border-b border-border">+ <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">+ {icon}+ </div>+ <div className="min-w-0">+ <SheetTitle>{title}</SheetTitle>+ {description && (+ <SheetDescription className="truncate text-muted">{description}</SheetDescription>+ )}+ </div>+ </div>+ </SheetHeader>++ {overrideContent ?? (+ <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-xs font-medium text-muted">Setup Steps</p>+ <Stepper+ activeStep={activeStep}+ orientation="vertical"+ onStepChange={(i) => {+ if (isSubmitting) return;+ if (i < activeStep) onStepChange(i);+ }}+ >+ <StepperList>{stepperSteps}</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-semibold text-foreground">+ {step.title ?? step.name}+ </h2>+ <p className="mt-1 text-sm text-muted">{step.subtitle}</p>+ </div>+ {children}+ </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-xs font-medium text-muted">+ Step {activeStep + 1} · {step.rightLabel ?? step.name}+ </p>+ {docsHref && <DocumentationLinkBadge href={docsHref} />}+ </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">{step.rightDescription}</p>+ </div>+ </aside>+ </div>++ <SheetFooter className="shrink-0 items-center justify-end border-t px-6">+ <span className="text-xs text-muted">+ Step {activeStep + 1} of {steps.length}+ </span>+ {activeStep > 0 && (+ <Button type="button" variant="outline" onClick={onBack}>+ Back+ </Button>+ )}+ {isLastStep ? (+ <Button+ type="button"+ variant="project"+ isPending={isSubmitting}+ isDisabled={isSubmitting || isSubmitDisabled}+ onClick={onSubmit}+ >+ {submitLabel}+ </Button>+ ) : (+ <Button+ type="button"+ variant="project"+ isDisabled={isContinueDisabled}+ onClick={onContinue}+ >+ Continue+ </Button>+ )}+ </SheetFooter>+ </form>+ )}+ </SheetContent>+ </Sheet>+ );+};diff --cc frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.tsindex cffd51354e,0000000000..7b6129493fmode 100644,000000..100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts@@@ -1,139 -1,0 +1,155 @@@+import { CertificateRenewalKeySource } from "@app/hooks/api/certificates/enums";+import { TCertificate, TRenewCertificateAttributes } from "@app/hooks/api/certificates/types";+import {+ CertSubjectAlternativeNameType,+ CertSubjectAttributeType+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";++import type { RenewalFormData } from "./CertificateRenewalModal";+import {+ filterUsages,+ formatSubjectAltNames,+ getAttributeValue,+ sanTypeCandidatesFromValue,+ SUBJECT_ATTR_MAP+} from "./certificateUtils";+import type { TemplateConstraints } from "./useCertificatePolicy";++const MS_PER_DAY = 24 * 60 * 60 * 1000;++const deriveTtlFromCertificate = (cert: TCertificate): string => {+ const spanMs = new Date(cert.notAfter).getTime() - new Date(cert.notBefore).getTime();+ if (!Number.isFinite(spanMs) || spanMs <= 0) return "";++ const days = Math.floor(spanMs / MS_PER_DAY);+ if (days > 0) return `${days}d`;++ const hours = Math.max(1, Math.floor(spanMs / (60 * 60 * 1000)));+ return `${hours}h`;+};++const resolveSanType = (+ value: string,+ allowedSanTypes: CertSubjectAlternativeNameType[]+): CertSubjectAlternativeNameType => {+ const candidates = sanTypeCandidatesFromValue(value);+ if (!allowedSanTypes.length) return candidates[0];+ return candidates.find((candidate) => allowedSanTypes.includes(candidate)) ?? candidates[0];+};++const parseCertificateSans = (+ cert: TCertificate,+ allowedSanTypes: CertSubjectAlternativeNameType[]+): { type: CertSubjectAlternativeNameType; value: string }[] => {+ const raw = cert.subjectAltNames || cert.altNames || "";+ return raw+ .split(",")+ .map((san) => san.trim())+ .filter(Boolean)+ .map((value) => ({ type: resolveSanType(value, allowedSanTypes), value }));+};++const buildSubjectAttributes = (cert: TCertificate) => {+ const attributes: { type: CertSubjectAttributeType; value: string }[] = [];++ SUBJECT_ATTR_MAP.forEach(({ attrType, requestKey }) => {+ const value = requestKey === "commonName" ? cert.commonName : cert.subject?.[requestKey];+ if (value) attributes.push({ type: attrType, value });+ });++ cert.subject?.domainComponents?.forEach((dc) => {+ if (dc) attributes.push({ type: CertSubjectAttributeType.DOMAIN_COMPONENT, value: dc });+ });++ return attributes;+};+++/**++ * Policy-allowed options plus any the certificate already carries, so a usage the policy has since++ * dropped stays visible and removable rather than being submitted from an unrendered checkbox.++ */++export const unionUsageOptions = <T extends { value: string }>(++ allowed: T[],++ all: readonly T[],++ presentCsv: string++): T[] => {++ const present = presentCsv ? presentCsv.split(",").filter(Boolean) : [];++ const missing = present.filter((v) => !allowed.some((o) => o.value === v));++ return [...allowed, ...all.filter((o) => missing.includes(o.value))];++};+++export const buildRenewalFormDefaults = (+ cert: TCertificate,+ constraints: TemplateConstraints+): RenewalFormData => ({+ keySource: CertificateRenewalKeySource.New,+ csr: "",+ ttl: deriveTtlFromCertificate(cert),+ subjectAttributes: buildSubjectAttributes(cert),+ subjectAltNames: parseCertificateSans(cert, constraints.allowedSanTypes),+ basicConstraints: {+ isCA: Boolean(cert.basicConstraints?.isCA),+ pathLength: cert.basicConstraints?.pathLength ?? null+ },+ signatureAlgorithm: cert.signatureAlgorithm ?? "",+ keyAlgorithm: cert.keyAlgorithm ?? "",+ keyUsages: Object.fromEntries((cert.keyUsages ?? []).map((usage) => [usage, true])),+ extendedKeyUsages: Object.fromEntries(+ (cert.extendedKeyUsages ?? []).map((usage) => [usage, true])+ )+});++const buildBasicConstraints = (+ formData: RenewalFormData,+ constraints: TemplateConstraints+): TRenewCertificateAttributes["basicConstraints"] => {+ if (!constraints.templateAllowsCA) return undefined;++ const isCA = constraints.templateRequiresCA || formData.basicConstraints.isCA;+ const { pathLength } = formData.basicConstraints;++ return { isCA, ...(isCA && pathLength !== null && pathLength !== undefined && { pathLength }) };+};++export const buildRenewalRequestAttributes = ({+ formData,+ constraints+}: {+ formData: RenewalFormData;+ constraints: TemplateConstraints;+}): TRenewCertificateAttributes => {- const basicConstraints = buildBasicConstraints(formData, constraints);-++ // The CSR carries its own basic constraints and the CSR step offers no control over them, so++ // sending the previous certificate's would silently override what the caller actually signed.+ if (formData.keySource === CertificateRenewalKeySource.Csr) {- return { ttl: formData.ttl, ...(basicConstraints && { basicConstraints }) };++ return { ttl: formData.ttl };+ }+++ const basicConstraints = buildBasicConstraints(formData, constraints);+++ const attributes: TRenewCertificateAttributes = {+ ttl: formData.ttl,+ keyUsages: filterUsages(formData.keyUsages as Record<string, boolean>),+ extendedKeyUsages: filterUsages(formData.extendedKeyUsages as Record<string, boolean>),+ ...(formData.signatureAlgorithm && { signatureAlgorithm: formData.signatureAlgorithm }),+ ...(formData.keySource !== CertificateRenewalKeySource.Reuse &&+ formData.keyAlgorithm && { keyAlgorithm: formData.keyAlgorithm }),+ ...(basicConstraints && { basicConstraints })+ };++ if (constraints.shouldShowSubjectSection) {+ SUBJECT_ATTR_MAP.forEach(({ attrType, requestKey }) => {+ attributes[requestKey] = getAttributeValue(formData.subjectAttributes, attrType) || null;+ });++ attributes.domainComponents = formData.subjectAttributes+ .filter((attr) => attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT)+ .map((attr) => attr.value.trim())+ .filter(Boolean);+ }++ if (constraints.shouldShowSanSection) {+ attributes.altNames = formatSubjectAltNames(formData.subjectAltNames);+ }++ return attributes;+};