Skip to content

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

feat(pki): move certificate import to a sheet wizard with per-certificate profiles

Carlos Monastyrski211ac3e666b4
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 0166da8d1b..92c5e6c275 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2282,6 +2282,7 @@ export const CERTIFICATES = {
externalMetadata:
'Identifies this certificate at the provider that issued it. Required when the chosen profile issues from an external certificate authority. For DigiCert, pass the CertCentral order ID as { type: "digicert", orderId: 2081714 }.',
+ certificateId: "The ID of the imported certificate.",
certificate: "The imported certificate.",
certificateChain:
"The certificate chain associated with the imported certificate. Returned only when a chain was supplied at import.",
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index 09868ef019..17464fce15 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -1642,6 +1642,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
+ certificateId: z.string().uuid().describe(CERTIFICATES.IMPORT.certificateId),
certificate: z.string().trim().describe(CERTIFICATES.IMPORT.certificate),
certificateChain: z.string().trim().optional().describe(CERTIFICATES.IMPORT.certificateChain),
privateKey: z.string().trim().optional().describe(CERTIFICATES.IMPORT.privateKey),
@@ -1689,6 +1690,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
});
return {
+ certificateId: cert.id,
certificate,
certificateChain,
privateKey,
diff --git a/frontend/src/helpers/certificatePem.ts b/frontend/src/helpers/certificatePem.ts
new file mode 100644
index 0000000000..761d5c56c6
--- /dev/null
+++ b/frontend/src/helpers/certificatePem.ts
@@ -0,0 +1,55 @@
+import * as x509 from "@peculiar/x509";
+
+const MAX_SUBJECT_LENGTH = 512;
+
+export type TCertificatePemSummary = {
+ subject: string;
+ commonName: string | null;
+ altNames: string | null;
+ keyAlgorithm: string;
+ serialNumber: string;
+ notBefore: string;
+ notAfter: string;
+};
+
+const describePublicKey = (cert: x509.X509Certificate) => {
+ const algorithm = cert.publicKey.algorithm as {
+ name: string;
+ modulusLength?: number;
+ namedCurve?: string;
+ };
+ if (algorithm.modulusLength) return `RSA ${algorithm.modulusLength}`;
+ if (algorithm.namedCurve) return `EC ${algorithm.namedCurve}`;
+ return algorithm.name;
+};
+
+const readAltNames = (cert: x509.X509Certificate) => {
+ const extension = cert.extensions.find((ext) => ext.type === "2.5.29.17");
+ if (!extension) return null;
+
+ try {
+ return new x509.GeneralNames(extension.value).items
+ .map((name) => name.value)
+ .join(", ")
+ .slice(0, MAX_SUBJECT_LENGTH);
+ } catch {
+ return null;
+ }
+};
+
+export const summarizeCertificatePem = (pem: string): TCertificatePemSummary | null => {
+ try {
+ const cert = new x509.X509Certificate(pem.trim());
+ return {
+ subject: cert.subject.slice(0, MAX_SUBJECT_LENGTH),
+ commonName: cert.subjectName.getField("CN")[0]?.slice(0, MAX_SUBJECT_LENGTH) ?? null,
+ altNames: readAltNames(cert),
+ keyAlgorithm: describePublicKey(cert),
+ serialNumber: cert.serialNumber,
+ notBefore: cert.notBefore.toISOString(),
+ notAfter: cert.notAfter.toISOString()
+ };
+ } catch {
+ return null;
+ }
+};
diff --git a/frontend/src/helpers/pkcs12.ts b/frontend/src/helpers/pkcs12.ts
index ffbb0019ff..2c22349b17 100644
--- a/frontend/src/helpers/pkcs12.ts
+++ b/frontend/src/helpers/pkcs12.ts
@@ -32,6 +32,7 @@ export type TPkcs12Entry = {
commonName: string | null;
altNames: string | null;
keyAlgorithm?: string;
+ serialNumber: string;
notAfter: string;
fingerprintSha256: string;
chainWarning: string | null;
@@ -433,6 +434,7 @@ const extractPkcs12Entries = async ({
subject: cert.cert.subject.slice(0, MAX_SUBJECT_LENGTH),
commonName: cert.cert.subjectName.getField("CN")[0]?.slice(0, MAX_SUBJECT_LENGTH) ?? null,
altNames: readAltNames(cert.cert),
+ serialNumber: cert.cert.serialNumber,
notAfter: cert.cert.notAfter.toISOString(),
fingerprintSha256: cert.fingerprint,
certificatePem: cert.pem
@@ -521,12 +523,18 @@ const pkcs12ErrorMessage = (code: TPkcs12ErrorCode, count?: number) => {
export const readKeystore = async (
file: ArrayBuffer,
password: string
-): Promise<{ entries: TPkcs12Entry[]; error?: never } | { entries?: never; error: string }> => {
+): Promise<
+ | { entries: TPkcs12Entry[]; error?: never; isPasswordError?: never }
+ | { entries?: never; error: string; isPasswordError: boolean }
+> => {
try {
return await extractPkcs12Entries({ pkcs12: new Uint8Array(file), password });
} catch (err) {
if (err instanceof Pkcs12ExtractionError)
- return { error: pkcs12ErrorMessage(err.code, err.count) };
- return { error: "Could not read this keystore." };
+ return {
+ error: pkcs12ErrorMessage(err.code, err.count),
+ isPasswordError: err.code === Pkcs12ErrorCode.BadPassword
+ };
+ return { error: "Could not read this keystore.", isPasswordError: false };
}
};
diff --git a/frontend/src/hooks/api/certificates/mutations.tsx b/frontend/src/hooks/api/certificates/mutations.tsx
index 754718014b..a9dc888c4e 100644
--- a/frontend/src/hooks/api/certificates/mutations.tsx
+++ b/frontend/src/hooks/api/certificates/mutations.tsx
@@ -119,7 +119,12 @@ export const useImportCertificate = () => {
export const useImportPkcs12Entries = () => {
const queryClient = useQueryClient();
return useMutation<TImportPkcs12EntriesResult[], object, TImportPkcs12EntriesDTO>({
- mutationFn: async ({ entries, applicationId, profileId, externalMetadataByFingerprint }) => {
+ mutationFn: async ({
+ entries,
+ applicationId,
+ profileIdByFingerprint,
+ externalMetadataByFingerprint
+ }) => {
const results: TImportPkcs12EntriesResult[] = [];
await entries.reduce<Promise<void>>(async (prev, entry) => {
@@ -131,7 +136,9 @@ export const useImportPkcs12Entries = () => {
certificatePem: entry.certificatePem,
...(entry.chainPem ? { chainPem: entry.chainPem } : {}),
...(entry.privateKeyPem ? { privateKeyPem: entry.privateKeyPem } : {}),
- ...(profileId ? { profileId } : {}),
+ ...(profileIdByFingerprint?.[entry.fingerprintSha256]
+ ? { profileId: profileIdByFingerprint[entry.fingerprintSha256] }
+ : {}),
...(externalMetadataByFingerprint?.[entry.fingerprintSha256]
? { externalMetadata: externalMetadataByFingerprint[entry.fingerprintSha256] }
: {}),
diff --git a/frontend/src/hooks/api/certificates/types.ts b/frontend/src/hooks/api/certificates/types.ts
index 52077be673..09b3a4f132 100644
--- a/frontend/src/hooks/api/certificates/types.ts
+++ b/frontend/src/hooks/api/certificates/types.ts
@@ -89,7 +89,7 @@ export type TRevokeCertDTO = {
export type TImportPkcs12EntriesDTO = {
entries: TPkcs12Entry[];
applicationId?: string;
- profileId?: string;
+ profileIdByFingerprint?: Record<string, string>;
externalMetadataByFingerprint?: Record<string, TCertificateExternalMetadata>;
};
@@ -116,6 +116,7 @@ export type TImportCertificateDTO = {
};
export type TImportCertificateResponse = {
+ certificateId: string;
certificate: string;
certificateChain?: string;
privateKey?: string;
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
deleted file mode 100644
index f734be556e..0000000000
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
+++ /dev/null
@@ -1,633 +0,0 @@
-import { useEffect, useState } from "react";
-import { Controller, useForm, useWatch } from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { CircleCheck, CircleX, TriangleAlert } from "lucide-react";
-
-import { createNotification } from "@app/components/notifications";
-import {
- Button,
- Checkbox,
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- Field,
- FieldContent,
- FieldDescription,
- FieldError,
- FieldGroup,
- FieldLabel,
- FileDropzone,
- Input,
- Item,
- ItemContent,
- ItemDescription,
- ItemGroup,
- ItemMedia,
- ItemTitle,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
- TextArea,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
-import type { TPkcs12Entry } from "@app/helpers/pkcs12";
-import { useGetCert, useImportCertificate, useImportPkcs12Entries } from "@app/hooks/api";
-import { UsePopUpState } from "@app/hooks/usePopUp";
-
-import {
- CertificateProfileSelect,
- CertificateReferenceField,
- useCertificateImportProfiles,
- useCertificateImportReference
-} from "./certificate-import-fields";
-import { getCertificateImportReference } from "./certificate-import-linkage";
-import { CertificateContent } from "./CertificateContent";
-import { CertificateImportProfileFields } from "./CertificateImportProfileFields";
-import { CertificateImportFormData, certificateImportSchema } from "./types";
-
-const MAX_KEYSTORE_BYTES = 1024 * 1024;
-
-const STICKY_HEAD = "sticky top-0 z-10 bg-popover";
-
-export type FormData = CertificateImportFormData;
-
-type Props = {
- popUp: UsePopUpState<["certificateImport"]>;
- handlePopUpToggle: (
- popUpName: keyof UsePopUpState<["certificateImport"]>,
- state?: boolean
- ) => void;
- applicationId?: string;
-};
-
-type TCertificateDetails = {
- serialNumber: string;
- certificate: string;
- certificateChain?: string;
- privateKey?: string;
-};
-
-type TImportOutcome = {
- subject: string;
- error?: string;
-};
-
-const entryLabel = (entry: TPkcs12Entry) =>
- entry.altNames || entry.commonName || entry.alias || entry.subject;
-
-export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId }: Props) => {
- const [certificateDetails, setCertificateDetails] = useState<TCertificateDetails | null>(null);
- const { data: cert } = useGetCert(
- (popUp?.certificateImport?.data as { serialNumber: string })?.serialNumber || ""
- );
-
- const { mutateAsync: importCertificate } = useImportCertificate();
- const [isExtracting, setIsExtracting] = useState(false);
- const { mutateAsync: importEntries, isPending: isImportingEntries } = useImportPkcs12Entries();
-
- const [keystoreFiles, setKeystoreFiles] = useState<File[]>([]);
- const [keystorePassword, setKeystorePassword] = useState("");
- const [keystoreError, setKeystoreError] = useState<string | null>(null);
- const [entries, setEntries] = useState<TPkcs12Entry[] | null>(null);
- const [selected, setSelected] = useState<Set<string>>(new Set());
- const [outcomes, setOutcomes] = useState<TImportOutcome[] | null>(null);
- const [format, setFormat] = useState<"pem" | "pkcs12">("pem");
- const [keystoreReferences, setKeystoreReferences] = useState<Record<string, string>>({});
-
- const {
- control,
- handleSubmit,
- reset,
- setValue,
- formState: { isSubmitting }
- } = useForm<FormData>({
- resolver: zodResolver(certificateImportSchema)
- });
-
- const { profileOptions, isProfilesLoading } = useCertificateImportProfiles(applicationId);
- const selectedProfileId = useWatch({ control, name: "profileId" });
- const keystoreProfile = profileOptions.find((option) => option.id === selectedProfileId) ?? null;
- const keystoreReferenceSource = useCertificateImportReference(keystoreProfile);
- const keystoreReference = keystoreReferenceSource.reference;
-
- const clearFields = () =>
- reset({
- certificatePem: "",
- chainPem: "",
- privateKeyPem: "",
- profileId: undefined,
- linkedCaType: undefined,
- providerReference: ""
- });
-
- const resetAll = () => {
- clearFields();
- setCertificateDetails(null);
- setKeystoreFiles([]);
- setKeystorePassword("");
- setKeystoreError(null);
- setEntries(null);
- setSelected(new Set());
- setOutcomes(null);
- setFormat("pem");
- setKeystoreReferences({});
- };
-
- const onFormSubmit = async ({
- certificatePem,
- privateKeyPem,
- chainPem,
- profileId,
- linkedCaType,
- providerReference
- }: FormData) => {
- const trimmedPrivateKey = privateKeyPem?.trim();
- const trimmedChain = chainPem?.trim();
- const reference = getCertificateImportReference(linkedCaType);
- const externalMetadata =
- reference && providerReference ? reference.parse(providerReference) : undefined;
-
- const { serialNumber, certificate, certificateChain, privateKey } = await importCertificate({
- certificatePem,
- ...(trimmedPrivateKey ? { privateKeyPem: trimmedPrivateKey } : {}),
- ...(trimmedChain ? { chainPem: trimmedChain } : {}),
- ...(profileId ? { profileId } : {}),
- ...(externalMetadata ? { externalMetadata } : {}),
- applicationId
- });
-
- clearFields();
-
- setCertificateDetails({
- serialNumber,
- certificate,
- certificateChain,
- privateKey
- });
-
- createNotification({
- text: "Successfully imported certificate",
- type: "success"
- });
- };
-
- const handleExtract = async () => {
- const file = keystoreFiles[0];
- if (!file) return;
-
- setKeystoreError(null);
-
- if (file.size > MAX_KEYSTORE_BYTES) {
- setKeystoreError("This file is larger than 1 MB. Upload a keystore under 1 MB.");
- return;
- }
-
- setIsExtracting(true);
- try {
- // Loaded on demand so node-forge stays out of the main bundle.
- const { readKeystore } = await import("@app/helpers/pkcs12");
- const result = await readKeystore(await file.arrayBuffer(), keystorePassword);
-
- if (!result.entries) {
- setKeystoreError(result.error);
- return;
- }
-
- const found = result.entries;
- setEntries(found);
- setSelected(new Set(found.map((entry) => entry.fingerprintSha256)));
- } finally {
- setIsExtracting(false);
- }
- };
-
- const handleImportSelected = async () => {
- if (!entries) return;
-
- const selectedEntries = entries.filter((entry) => selected.has(entry.fingerprintSha256));
- const externalMetadataByFingerprint = keystoreReference
- ? Object.fromEntries(
- selectedEntries.flatMap((entry) => {
- const parsed = keystoreReference.parse(
- keystoreReferences[entry.fingerprintSha256] ?? ""
- );
- return parsed ? [[entry.fingerprintSha256, parsed] as const] : [];
- })
- )
- : undefined;
-
- const results = await importEntries({
- entries: selectedEntries,
- applicationId,
- profileId: selectedProfileId,
- externalMetadataByFingerprint
- });
-
- setOutcomes(
- results.map((result) => ({ subject: entryLabel(result.entry), error: result.error }))
- );
-
- const imported = results.filter((result) => !result.error).length;
- if (imported) {
- createNotification({
- text: `Imported ${imported} of ${results.length} certificate${results.length === 1 ? "" : "s"}`,
- type: "success"
- });
- }
- };
-
- const toggleEntry = (fingerprint: string) => {
- setSelected((prev) => {
- const next = new Set(prev);
- if (next.has(fingerprint)) next.delete(fingerprint);
- else next.add(fingerprint);
- return next;
- });
- };
-
- const isOpen = Boolean(popUp?.certificateImport?.isOpen);
- useEffect(() => {
- // Radix fires onOpenChange only for its own interactions, so our footer buttons never reach it.
- if (isOpen) resetAll();
- }, [isOpen]);
-
- const pemFieldsDisabled = Boolean(cert);
-
- const renderPemFields = () => (
- <FieldGroup>
- <Controller
- control={control}
- defaultValue=""
- name="certificatePem"
- render={({ field, fieldState: { error } }) => (
- <Field data-invalid={Boolean(error)}>
- <FieldLabel>Leaf Certificate PEM</FieldLabel>
- <TextArea {...field} disabled={pemFieldsDisabled} />
- {error && <FieldError>{error.message}</FieldError>}
- </Field>
- )}
- />
- <Controller
- control={control}
- defaultValue=""
- name="chainPem"
- render={({ field, fieldState: { error } }) => (
- <Field data-invalid={Boolean(error)}>
- <FieldLabel>Certificate Chain PEM (optional)</FieldLabel>
- <TextArea {...field} disabled={pemFieldsDisabled} />
- {error && <FieldError>{error.message}</FieldError>}
- </Field>
- )}
- />
- <Controller
- control={control}
- defaultValue=""
- name="privateKeyPem"
- render={({ field, fieldState: { error } }) => (
- <Field data-invalid={Boolean(error)}>
- <FieldLabel>Private Key PEM (optional)</FieldLabel>
- <TextArea {...field} disabled={pemFieldsDisabled} />
- {error && <FieldError>{error.message}</FieldError>}
- </Field>
- )}
- />
- {applicationId && !pemFieldsDisabled && (
- <CertificateImportProfileFields
- control={control}
- setValue={setValue}
- applicationId={applicationId}
- />
- )}
- </FieldGroup>
- );
-
- const isMissingKeystoreReference = Boolean(
- keystoreReference &&
- entries?.some(
- (entry) =>
- selected.has(entry.fingerprintSha256) &&
- !keystoreReference.parse(keystoreReferences[entry.fingerprintSha256] ?? "")
- )
- );
-
- const failures = outcomes?.filter((outcome) => outcome.error) ?? [];
-
- const renderOutcomes = () => (
- <ItemGroup className="max-h-96 thin-scrollbar gap-2 overflow-y-auto">
- {outcomes?.map((outcome, index) => (
- // eslint-disable-next-line react/no-array-index-key
- <Item key={index} variant="outline" size="xs" role="listitem">
- <ItemMedia variant="icon">
- {outcome.error ? (
- <CircleX className="text-danger" />
- ) : (
- <CircleCheck className="text-success" />
- )}
- </ItemMedia>
- <ItemContent className="min-w-0">
- <ItemTitle className="truncate">{outcome.subject}</ItemTitle>
- <ItemDescription className="mt-1 line-clamp-none whitespace-pre-line">
- {outcome.error ?? "Imported"}
- </ItemDescription>
- </ItemContent>
- </Item>
- ))}
- </ItemGroup>
- );
-
- const renderEntriesTable = () => (
- <>
- {applicationId && (
- <FieldGroup className="mb-4">
- <Field>
- <FieldLabel>Certificate Profile (optional)</FieldLabel>
- <FieldContent>
- <CertificateProfileSelect
- options={profileOptions}
- isLoading={isProfilesLoading}
- value={selectedProfileId}
- onChange={(profileId) => {
- setValue("profileId", profileId);
- setKeystoreReferences({});
- }}
- />
- <FieldDescription>
- Applied to every certificate you import from this keystore.
- </FieldDescription>
- </FieldContent>
- </Field>
- </FieldGroup>
- )}
- <Table containerClassName="max-h-96 thin-scrollbar overflow-y-auto">
- <TableHeader>
- <TableRow>
- <TableHead className={`w-12 ${STICKY_HEAD}`}>
- <Checkbox
- id="select-all-entries"
- variant="project"
- isChecked={Boolean(entries?.length) && selected.size === entries?.length}
- onCheckedChange={() =>
- setSelected((prev) =>
- prev.size === entries?.length
- ? new Set()
- : new Set(entries?.map((entry) => entry.fingerprintSha256))
- )
- }
- />
- </TableHead>
- <TableHead className={STICKY_HEAD}>SAN / CN</TableHead>
- <TableHead className={`w-28 ${STICKY_HEAD}`}>Private Key</TableHead>
- <TableHead className={`w-20 ${STICKY_HEAD}`}>Chain</TableHead>
- <TableHead className={`w-32 ${STICKY_HEAD}`}>Expires</TableHead>
- {keystoreReference && (
- <TableHead className={`w-80 ${STICKY_HEAD}`}>{keystoreReference.label}</TableHead>
- )}
- </TableRow>
- </TableHeader>
- <TableBody>
- {entries?.map((entry) => (
- <TableRow
- key={entry.fingerprintSha256}
- className="cursor-pointer"
- onClick={() => toggleEntry(entry.fingerprintSha256)}
- >
- <TableCell onClick={(e) => e.stopPropagation()}>
- <Checkbox
- id={entry.fingerprintSha256}
- variant="project"
- isChecked={selected.has(entry.fingerprintSha256)}
- onCheckedChange={() => toggleEntry(entry.fingerprintSha256)}
- />
- </TableCell>
- <TableCell className="max-w-0">
- <div className="truncate">{entryLabel(entry)}</div>
- </TableCell>
- <TableCell>{entry.keyAlgorithm || "—"}</TableCell>
- <TableCell>
- {entry.chainWarning ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="flex items-center gap-1 text-warning">
- <TriangleAlert className="size-3.5" />0
- </span>
- </TooltipTrigger>
- <TooltipContent>{entry.chainWarning}</TooltipContent>
- </Tooltip>
- ) : (
- (entry.chainPem?.split("BEGIN CERTIFICATE").length ?? 1) - 1
- )}
- </TableCell>
- <TableCell>{new Date(entry.notAfter).toLocaleDateString()}</TableCell>
- {keystoreReference && (
- <TableCell onClick={(e) => e.stopPropagation()}>
- {selected.has(entry.fingerprintSha256) ? (
- <CertificateReferenceField
- source={keystoreReferenceSource}
- value={keystoreReferences[entry.fingerprintSha256]}
- onChange={(value) =>
- setKeystoreReferences((prev) => ({
- ...prev,
- [entry.fingerprintSha256]: value
- }))
- }
- />
- ) : (
- <span className="text-mineshaft-400">&mdash;</span>
- )}
- </TableCell>
- )}
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </>
- );
-
- const renderKeystorePicker = () => (
- <FieldGroup>
- <Field data-invalid={Boolean(keystoreError)}>
- <FieldLabel>Keystore file</FieldLabel>
- <FileDropzone
- accept=".p12,.pfx"
- description=".p12 or .pfx keystore, up to 1 MB"
- files={keystoreFiles}
- onFilesSelect={(files) => {
- setKeystoreFiles(files.slice(0, 1));
- setKeystoreError(null);
- }}
- onFileRemove={() => {
- setKeystoreFiles([]);
- setKeystoreError(null);
- }}
- />
- </Field>
- <Field>
- <FieldLabel>Password</FieldLabel>
- <Input
- type="password"
- autoComplete="off"
- value={keystorePassword}
- onChange={(e) => setKeystorePassword(e.target.value)}
- placeholder="Leave blank if the keystore has no password"
- />
- </Field>
- {keystoreError && (
- <Field data-invalid>
- <FieldError>{keystoreError}</FieldError>
- </Field>
- )}
- <div>
- <Button
- variant="project"
- isDisabled={!keystoreFiles.length || isExtracting}
- isPending={isExtracting}
- onClick={handleExtract}
- >
- Read keystore
- </Button>
- </div>
- </FieldGroup>
- );
-
- const renderBody = () => {
- if (certificateDetails) {
- return (
- <CertificateContent
- serialNumber={certificateDetails.serialNumber}
- certificate={certificateDetails.certificate}
- certificateChain={certificateDetails.certificateChain}
- privateKey={certificateDetails.privateKey}
- />
- );
- }
-
- if (outcomes) return renderOutcomes();
-
- if (cert) return renderPemFields();
-
- return (
- <Tabs value={format} onValueChange={(value) => setFormat(value as "pem" | "pkcs12")}>
- <TabsList className="mb-2">
- <TabsTrigger value="pem">PEM</TabsTrigger>
- <TabsTrigger value="pkcs12">PKCS#12</TabsTrigger>
- </TabsList>
- <TabsContent value="pem">
- <form id="import-pem-form" onSubmit={handleSubmit(onFormSubmit)}>
- {renderPemFields()}
- </form>
- </TabsContent>
- <TabsContent value="pkcs12">
- {entries ? renderEntriesTable() : renderKeystorePicker()}
- </TabsContent>
- </Tabs>
- );
- };
-
- const headerContent = () => {
- if (cert) return { title: "View Certificate", description: null };
- if (certificateDetails)
- return { title: "Certificate Imported", description: "Copy or download it before closing." };
- if (outcomes) {
- const imported = outcomes.length - failures.length;
- return {
- title: "Import Results",
- description: `${imported} of ${outcomes.length} certificate${outcomes.length === 1 ? "" : "s"} imported.`
- };
- }
- if (entries && format === "pkcs12")
- return {
- title: "Review & Import",
- description: `${entries.length} certificate${entries.length === 1 ? "" : "s"} found in this keystore. Choose which to import.`
- };
- return {
- title: "Import Certificate",
- description: "Import an existing certificate from PEM files or a PKCS#12 keystore."
- };
- };
-
- const renderFooter = () => {
- if (certificateDetails || cert) return null;
-
- if (format === "pkcs12" && !entries) return null;
-
- if (outcomes) {
- return (
- <DialogFooter>
- <Button variant="project" onClick={() => handlePopUpToggle("certificateImport", false)}>
- Done
- </Button>
- </DialogFooter>
- );
- }
-
- if (entries && format === "pkcs12") {
- return (
- <DialogFooter>
- {isMissingKeystoreReference && keystoreReference && (
- <span className="self-center text-sm text-mineshaft-300">
- {`Enter the ${keystoreReference.label} for every selected certificate.`}
- </span>
- )}
- <Button variant="outline" onClick={() => handlePopUpToggle("certificateImport", false)}>
- Cancel
- </Button>
- <Button
- variant="project"
- isDisabled={!selected.size || isImportingEntries || isMissingKeystoreReference}
- isPending={isImportingEntries}
- onClick={handleImportSelected}
- >
- {`Import ${selected.size} selected`}
- </Button>
- </DialogFooter>
- );
- }
-
- return (
- <DialogFooter>
- <Button variant="outline" onClick={() => handlePopUpToggle("certificateImport", false)}>
- Cancel
- </Button>
- <Button
- type="submit"
- form="import-pem-form"
- variant="project"
- isPending={isSubmitting}
- isDisabled={isSubmitting}
- >
- Import
- </Button>
- </DialogFooter>
- );
- };
-
- const header = headerContent();
-
- return (
- <Dialog
- open={isOpen}
- onOpenChange={(nextOpen) => handlePopUpToggle("certificateImport", nextOpen)}
- >
- <DialogContent className="max-w-3xl">
- <DialogHeader>
- <DialogTitle>{header.title}</DialogTitle>
- {header.description && <DialogDescription>{header.description}</DialogDescription>}
- </DialogHeader>
- {renderBody()}
- {renderFooter()}
- </DialogContent>
- </Dialog>
- );
-};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportProfileFields.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportProfileFields.tsx
deleted file mode 100644
index 5ee4f82d2d..0000000000
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportProfileFields.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { useEffect } from "react";
-import { Control, Controller, UseFormSetValue, useWatch } from "react-hook-form";
-
-import { Field, FieldContent, FieldDescription, FieldError, FieldLabel } from "@app/components/v3";
-
-import {
- CertificateProfileSelect,
- CertificateReferenceField,
- useCertificateImportProfiles,
- useCertificateImportReference
-} from "./certificate-import-fields";
-import { CertificateImportFormData } from "./types";
-
-type Props = {
- control: Control<CertificateImportFormData>;
- setValue: UseFormSetValue<CertificateImportFormData>;
- applicationId: string;
-};
-
-export const CertificateImportProfileFields = ({ control, setValue, applicationId }: Props) => {
- const { profileOptions, isProfilesLoading } = useCertificateImportProfiles(applicationId);
-
- const selectedProfileId = useWatch({ control, name: "profileId" });
- const selectedProfile = profileOptions.find((option) => option.id === selectedProfileId) ?? null;
- const referenceSource = useCertificateImportReference(selectedProfile);
- const { reference } = referenceSource;
-
- useEffect(() => {
- setValue("linkedCaType", selectedProfile?.caType ?? undefined);
- setValue("providerReference", "");
- }, [selectedProfileId, selectedProfile?.caType, setValue]);
-
- return (
- <>
- <Controller
- control={control}
- name="profileId"
- render={({ field, fieldState: { error } }) => (
- <Field data-invalid={Boolean(error)}>
- <FieldLabel>Certificate Profile (optional)</FieldLabel>
- <FieldContent>
- <CertificateProfileSelect
- options={profileOptions}
- isLoading={isProfilesLoading}
- value={field.value}
- onChange={field.onChange}
- />
- {error && <FieldError>{error.message}</FieldError>}
- </FieldContent>
- </Field>
- )}
- />
-
- {reference && (
- <Controller
- control={control}
- name="providerReference"
- render={({ field, fieldState: { error } }) => (
- <Field data-invalid={Boolean(error)}>
- <FieldLabel>{reference.label}</FieldLabel>
- <FieldContent>
- <CertificateReferenceField
- source={referenceSource}
- value={field.value}
- onChange={field.onChange}
- />
- <FieldDescription>{reference.description}</FieldDescription>
- {error && <FieldError>{error.message}</FieldError>}
- </FieldContent>
- </Field>
- )}
- />
- )}
- </>
- );
-};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsx
new file mode 100644
index 0000000000..7b0b7df664
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportSheet.tsx
@@ -0,0 +1,1009 @@
+import { ReactNode, useEffect, useMemo, useState } from "react";
+import { Controller, useForm, useWatch } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useNavigate } from "@tanstack/react-router";
+import { CircleCheck, CircleX, TriangleAlert, Upload } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Badge,
+ Checkbox,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ FileDropzone,
+ Input,
+ Item,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemTitle,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ TextArea,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { useOrganization, useProject } from "@app/context";
+import type { TCertificatePemSummary } from "@app/helpers/certificatePem";
+import type { TPkcs12Entry } from "@app/helpers/pkcs12";
+import { useImportCertificate, useImportPkcs12Entries } from "@app/hooks/api";
+import { UsePopUpState } from "@app/hooks/usePopUp";
+
+import {
+ CertificateProfileSelect,
+ CertificateReferenceField,
+ ProfileOption,
+ useCertificateImportProfiles,
+ useCertificateImportReference
+} from "./certificate-import-fields";
+import { getCertificateImportReference } from "./certificate-import-linkage";
+import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";
+import { CertificateImportFormData, certificateImportSchema } from "./types";
+
+const MAX_KEYSTORE_BYTES = 1024 * 1024;
+const STICKY_HEAD = "sticky top-0 z-10 bg-popover";
+const ENTRY_BASE_WIDTH = 368;
+const ENTRY_PROFILE_WIDTH = 224;
+const ENTRY_REF_WIDTH = 224;
+const REVIEW_BASE_WIDTH = 496;
+const REVIEW_PROFILE_WIDTH = 176;
+const REVIEW_REF_WIDTH = 160;
+
+export type FormData = CertificateImportFormData;
+
+enum ImportFormat {
+ Pem = "pem",
+ Keystore = "pkcs12"
+}
+
+const STEP_KEYS = ["source", "profile", "review"] as const;
+type ImportStepKey = (typeof STEP_KEYS)[number];
+
+const STEP_FIELDS: Record<ImportStepKey, string[]> = {
+ source: ["certificatePem", "chainPem", "privateKeyPem"],
+ profile: ["profileId", "providerReference"],
+ review: []
+};
+
+const buildSteps = (hasApplication: boolean): Record<ImportStepKey, WizardStep> => ({
+ source: {
+ name: "Source",
+ shortDescription: "PEM or keystore",
+ title: "Certificate Source",
+ subtitle: "Paste the PEM files you hold, or upload a PKCS#12 keystore.",
+ rightLabel: "Source",
+ rightDescription: hasApplication
+ ? "Nothing is issued here. Infisical stores the certificate you already hold so it can be tracked, and renewed later if you attach a profile."
+ : "Nothing is issued here. Infisical stores the certificate you already hold so it can be tracked for visibility and expiry alerts."
+ },
+ profile: hasApplication
+ ? {
+ name: "Profile",
+ shortDescription: "Lifecycle owner",
+ title: "Certificate Profile",
+ subtitle: "Choose the profile that will manage renewal and revocation.",
+ rightLabel: "Profile",
+ rightDescription:
+ "The profile decides which authority signs the replacement at renewal, and the certificate has to satisfy its policy. Leave it empty to track the certificate for visibility and expiry alerts only."
+ }
+ : {
+ name: "Certificates",
+ shortDescription: "What to import",
+ title: "Keystore Contents",
+ subtitle: "Choose which certificates to import from this keystore.",
+ rightLabel: "Certificates",
+ rightDescription:
+ "A keystore can hold more than one certificate. Only the ones you select are imported."
+ },
+ review: {
+ name: "Review",
+ shortDescription: "Confirm and import",
+ title: "Review & Import",
+ subtitle: "Check what will be imported before it is stored.",
+ rightLabel: "Review",
+ rightDescription: hasApplication
+ ? "Anything rejected stays here so you can change the profile or the details and try again. Certificates already imported are locked and cannot be imported twice."
+ : "Anything rejected stays here so you can change the details and try again. Certificates already imported are locked and cannot be imported twice."
+ }
+});
+
+type Props = {
+ popUp: UsePopUpState<["certificateImport"]>;
+ handlePopUpToggle: (
+ popUpName: keyof UsePopUpState<["certificateImport"]>,
+ state?: boolean
+ ) => void;
+ applicationId?: string;
+};
+
+const ReviewSection = ({ title, children }: { title: string; children: ReactNode }) => (
+ <div className="flex flex-col gap-3">
+ <div className="w-full border-b border-border">
+ <span className="text-sm text-muted">{title}</span>
+ </div>
+ {children}
+ </div>
+);
+
+const entryLabel = (entry: TPkcs12Entry) =>
+ entry.altNames || entry.commonName || entry.alias || entry.subject;
+
+type EntryRowProps = {
+ entry: TPkcs12Entry;
+ isImported: boolean;
+ isSelected: boolean;
+ onToggle: () => void;
+ showProfile: boolean;
+ hasReferenceColumn: boolean;
+ profileOptions: ProfileOption[];
+ isProfilesLoading: boolean;
+ profileId?: string;
+ onProfileChange: (profileId?: string) => void;
+ referenceValue?: string;
+ onReferenceChange: (value: string) => void;
+ lastError?: string;
+};
+
+const KeystoreEntryRow = ({
+ entry,
+ isImported,
+ isSelected,
+ onToggle,
+ showProfile,
+ hasReferenceColumn,
+ profileOptions,
+ isProfilesLoading,
+ profileId,
+ onProfileChange,
+ referenceValue,
+ onReferenceChange,
+ lastError
+}: EntryRowProps) => {
+ const profile = profileOptions.find((option) => option.id === profileId) ?? null;
+ const referenceSource = useCertificateImportReference(profile);
+ const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
+
+ return (
+ <TableRow
+ className={isImported ? "opacity-60" : "cursor-pointer"}
+ onClick={isImported ? undefined : onToggle}
+ >
+ <TableCell onClick={stopRowToggle}>
+ <Checkbox
+ id={entry.fingerprintSha256}
+ variant="project"
+ isDisabled={isImported}
+ isChecked={isImported || isSelected}
+ onCheckedChange={onToggle}
+ />
+ </TableCell>
+ <TableCell className="max-w-0">
+ <div className="flex items-center gap-2">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="truncate">{entryLabel(entry)}</span>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-lg break-words">{entryLabel(entry)}</TooltipContent>
+ </Tooltip>
+ {isImported && <Badge variant="success">Imported</Badge>}
+ {!isImported && lastError && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="danger">Rejected</Badge>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-lg whitespace-pre-line">{lastError}</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ </TableCell>
+ <TableCell>
+ <Badge variant={entry.privateKeyPem ? "success" : "neutral"}>
+ {entry.privateKeyPem ? "Yes" : "No"}
+ </Badge>
+ </TableCell>
+ <TableCell>
+ {entry.chainWarning ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="flex items-center gap-1 text-warning">
+ <TriangleAlert className="size-3.5" />
+ No
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{entry.chainWarning}</TooltipContent>
+ </Tooltip>
+ ) : (
+ <Badge variant={entry.chainPem ? "success" : "neutral"}>
+ {entry.chainPem ? "Yes" : "No"}
+ </Badge>
+ )}
+ </TableCell>
+ {showProfile && (
+ <TableCell onClick={stopRowToggle}>
+ {isSelected ? (
+ <CertificateProfileSelect
+ options={profileOptions}
+ isLoading={isProfilesLoading}
+ value={profileId}
+ onChange={onProfileChange}
+ />
+ ) : (
+ <span className="text-muted">&mdash;</span>
+ )}
+ </TableCell>
+ )}
+ {hasReferenceColumn && (
+ <TableCell onClick={stopRowToggle}>
+ {isSelected && referenceSource.reference ? (
+ <CertificateReferenceField
+ source={referenceSource}
+ value={referenceValue}
+ onChange={onReferenceChange}
+ />
+ ) : (
+ <span className="text-muted">&mdash;</span>
+ )}
+ </TableCell>
+ )}
+ </TableRow>
+ );
+};
+
+export const CertificateImportSheet = ({ popUp, handlePopUpToggle, applicationId }: Props) => {
+ const navigate = useNavigate();
+ const { currentOrg } = useOrganization();
+ const { currentProject } = useProject();
+ const { mutateAsync: importCertificate, isPending: isImportingPem } = useImportCertificate();
+ const { mutateAsync: importEntries, isPending: isImportingEntries } = useImportPkcs12Entries();
+
+ const [format, setFormat] = useState<ImportFormat>(ImportFormat.Pem);
+ const [keystoreFiles, setKeystoreFiles] = useState<File[]>([]);
+ const [keystorePassword, setKeystorePassword] = useState("");
+ const [fileError, setFileError] = useState<string | null>(null);
+ const [passwordError, setPasswordError] = useState<string | null>(null);
+ const [isExtracting, setIsExtracting] = useState(false);
+ const [entries, setEntries] = useState<TPkcs12Entry[] | null>(null);
+ const [selected, setSelected] = useState<Set<string>>(new Set());
+ const [references, setReferences] = useState<Record<string, string>>({});
+ const [profileByFingerprint, setProfileByFingerprint] = useState<Record<string, string>>({});
+ const [importedFingerprints, setImportedFingerprints] = useState<Set<string>>(new Set());
+ const [failureByFingerprint, setFailureByFingerprint] = useState<Record<string, string>>({});
+ const [hasRun, setHasRun] = useState(false);
+ const [pemError, setPemError] = useState<string | null>(null);
+ const [pemSummary, setPemSummary] = useState<TCertificatePemSummary | null>(null);
+
+ const hasApplication = Boolean(applicationId);
+ const stepKeys = useMemo(
+ () =>
+ hasApplication || format === ImportFormat.Keystore
+ ? STEP_KEYS
+ : STEP_KEYS.filter((key) => key !== "profile"),
+ [hasApplication, format]
+ );
+ const steps = useMemo(() => {
+ const built = buildSteps(hasApplication);
+ return stepKeys.map((key) => built[key]);
+ }, [hasApplication, stepKeys]);
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ setValue,
+ setError,
+ getValues,
+ trigger,
+ formState: { isSubmitting }
+ } = useForm<FormData>({
+ resolver: zodResolver(certificateImportSchema),
+ defaultValues: { certificatePem: "", chainPem: "", privateKeyPem: "", providerReference: "" }
+ });
+
+ const { profileOptions, isProfilesLoading } = useCertificateImportProfiles(applicationId);
+ const selectedProfileId = useWatch({ control, name: "profileId" });
+ const selectedProfile = profileOptions.find((option) => option.id === selectedProfileId) ?? null;
+ const referenceSource = useCertificateImportReference(selectedProfile);
+ const { reference } = referenceSource;
+
+ const isKeystore = format === ImportFormat.Keystore;
+
+ const selectableEntries = useMemo(
+ () => (entries ?? []).filter((entry) => !importedFingerprints.has(entry.fingerprintSha256)),
+ [entries, importedFingerprints]
+ );
+
+ const selectedEntries = useMemo(
+ () => selectableEntries.filter((entry) => selected.has(entry.fingerprintSha256)),
+ [selectableEntries, selected]
+ );
+
+ const profileFor = (fingerprint: string) =>
+ profileOptions.find((option) => option.id === profileByFingerprint[fingerprint]) ?? null;
+
+ const entryReferences = selectedEntries.map((entry) => ({
+ entry,
+ reference: getCertificateImportReference(profileFor(entry.fingerprintSha256)?.caType)
+ }));
+
+ const referenceColumnLabel = (() => {
+ const labels = [
+ ...new Set(entryReferences.flatMap(({ reference: r }) => (r ? [r.label] : [])))
+ ];
+ if (!labels.length) return null;
+ return labels.length === 1 ? labels[0] : "Provider Reference";
+ })();
+
+ const isMissingReference = isKeystore
+ ? entryReferences.some(
+ ({ entry, reference: r }) => r && !r.parse(references[entry.fingerprintSha256] ?? "")
+ )
+ : false;
+
+ const discardKeystoreRead = () => {
+ setFileError(null);
+ setPasswordError(null);
+ setEntries(null);
+ setSelected(new Set());
+ setReferences({});
+ setProfileByFingerprint({});
+ };
+
+ const readKeystoreFile = async () => {
+ const file = keystoreFiles[0];
+ if (!file) return false;
+
+ setFileError(null);
+ setPasswordError(null);
+ if (file.size > MAX_KEYSTORE_BYTES) {
+ setFileError("This file is larger than 1 MB. Upload a keystore under 1 MB.");
+ return false;
+ }
+
+ setIsExtracting(true);
+ try {
+ const { readKeystore } = await import("@app/helpers/pkcs12");
+ const result = await readKeystore(await file.arrayBuffer(), keystorePassword);
+ if (!result.entries) {
+ if (result.isPasswordError) setPasswordError(result.error);
+ else setFileError(result.error);
+ return false;
+ }
+ setEntries(result.entries);
+ setSelected(
+ new Set(
+ result.entries
+ .filter((entry) => !importedFingerprints.has(entry.fingerprintSha256))
+ .map((entry) => entry.fingerprintSha256)
+ )
+ );
+ return true;
+ } finally {
+ setIsExtracting(false);
+ }
+ };
+
+ const readCertificatePem = async () => {
+ if (!(await trigger(STEP_FIELDS.source as (keyof FormData)[]))) return false;
+
+ const { summarizeCertificatePem } = await import("@app/helpers/certificatePem");
+ const summary = summarizeCertificatePem(getValues("certificatePem"));
+ if (!summary) {
+ setError("certificatePem", {
+ message:
+ "This is not a valid certificate. Paste the PEM block, including the BEGIN and END lines."
+ });
+ return false;
+ }
+ setPemSummary(summary);
+ return true;
+ };
+
+ const { step, setStep, currentStepKey, goBack, goNext, onFormInvalid } = useWizardSteps({
+ stepKeys,
+ stepFields: STEP_FIELDS,
+ invalidMessage: "Fix the highlighted fields before importing.",
+ validateStep: async (fields) => {
+ if (fields === STEP_FIELDS.source) {
+ if (isKeystore) return entries ? true : readKeystoreFile();
+ return readCertificatePem();
+ }
+ if (isKeystore) return true;
+ return trigger(fields as (keyof FormData)[]);
+ }
+ });
+
+ const resetAll = () => {
+ reset({
+ certificatePem: "",
+ chainPem: "",
+ privateKeyPem: "",
+ profileId: undefined,
+ linkedCaType: undefined,
+ providerReference: ""
+ });
+ setFormat(ImportFormat.Pem);
+ setKeystoreFiles([]);
+ setKeystorePassword("");
+ setFileError(null);
+ setPasswordError(null);
+ setEntries(null);
+ setSelected(new Set());
+ setReferences({});
+ setProfileByFingerprint({});
+ setImportedFingerprints(new Set());
+ setFailureByFingerprint({});
+ setHasRun(false);
+ setPemError(null);
+ setPemSummary(null);
+ setStep(0);
+ };
+
+ const isOpen = Boolean(popUp?.certificateImport?.isOpen);
+ useEffect(() => {
+ if (isOpen) resetAll();
+ }, [isOpen]);
+
+ useEffect(() => {
+ setValue("linkedCaType", selectedProfile?.caType ?? undefined);
+ }, [selectedProfileId, selectedProfile?.caType, setValue]);
+
+ const toggleEntry = (fingerprint: string) => {
+ if (importedFingerprints.has(fingerprint)) return;
+ setSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(fingerprint)) next.delete(fingerprint);
+ else next.add(fingerprint);
+ return next;
+ });
+ };
+
+ const importPem = async (values: FormData) => {
+ setPemError(null);
+ const trimmedPrivateKey = values.privateKeyPem?.trim();
+ const trimmedChain = values.chainPem?.trim();
+ const linkage = getCertificateImportReference(values.linkedCaType);
+ const externalMetadata =
+ linkage && values.providerReference ? linkage.parse(values.providerReference) : undefined;
+
+ try {
+ const { certificateId } = await importCertificate({
+ certificatePem: values.certificatePem,
+ ...(trimmedPrivateKey ? { privateKeyPem: trimmedPrivateKey } : {}),
+ ...(trimmedChain ? { chainPem: trimmedChain } : {}),
+ ...(values.profileId ? { profileId: values.profileId } : {}),
+ ...(externalMetadata ? { externalMetadata } : {}),
+ applicationId
+ });
+
+ handlePopUpToggle("certificateImport", false);
+ createNotification({ text: "Successfully imported certificate", type: "success" });
+
+ if (currentOrg && currentProject) {
+ await navigate({
+ to: "/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId",
+ params: { orgId: currentOrg.id, projectId: currentProject.id, certificateId }
+ });
+ }
+ } catch (error) {
+ setHasRun(true);
+ setPemError(
+ (error as { response?: { data?: { message?: string } } })?.response?.data?.message ??
+ "Could not import this certificate."
+ );
+ }
+ };
+
+ const importKeystore = async () => {
+ const externalMetadataByFingerprint = Object.fromEntries(
+ entryReferences.flatMap(({ entry, reference: r }) => {
+ const parsed = r?.parse(references[entry.fingerprintSha256] ?? "");
+ return parsed ? [[entry.fingerprintSha256, parsed] as const] : [];
+ })
+ );
+
+ const results = await importEntries({
+ entries: selectedEntries,
+ applicationId,
+ profileIdByFingerprint: profileByFingerprint,
+ externalMetadataByFingerprint
+ });
+
+ const succeeded = results.filter((result) => !result.error);
+ const failed = results.filter((result) => result.error);
+
+ setImportedFingerprints((prev) => {
+ const next = new Set(prev);
+ succeeded.forEach((result) => next.add(result.entry.fingerprintSha256));
+ return next;
+ });
+ setFailureByFingerprint(
+ Object.fromEntries(failed.map((result) => [result.entry.fingerprintSha256, result.error!]))
+ );
+ setSelected(new Set(failed.map((result) => result.entry.fingerprintSha256)));
+ setHasRun(true);
+
+ if (succeeded.length) {
+ createNotification({
+ text: `Imported ${succeeded.length} of ${results.length} certificate${results.length === 1 ? "" : "s"}`,
+ type: "success"
+ });
+ }
+ };
+
+ const renderSourceStep = () => (
+ <FieldGroup>
+ <Field>
+ <FieldLabel>Source Format</FieldLabel>
+ <FieldContent>
+ <Select
+ value={format}
+ onValueChange={(value) => {
+ setFormat(value as ImportFormat);
+ setPemError(null);
+ }}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={ImportFormat.Pem}>PEM</SelectItem>
+ <SelectItem value={ImportFormat.Keystore}>PKCS#12 Keystore</SelectItem>
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ PEM takes the certificate, its chain and its private key as text. A PKCS#12 keystore is
+ a single .p12 or .pfx file, and can hold more than one certificate.
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+
+ {isKeystore ? (
+ <>
+ <Field data-invalid={Boolean(fileError)}>
+ <FieldLabel>Keystore File</FieldLabel>
+ <FieldContent>
+ <FileDropzone
+ accept=".p12,.pfx"
+ description=".p12 or .pfx keystore, up to 1 MB"
+ files={keystoreFiles}
+ onFilesSelect={(files) => {
+ setKeystoreFiles(files.slice(0, 1));
+ discardKeystoreRead();
+ }}
+ onFileRemove={() => {
+ setKeystoreFiles([]);
+ discardKeystoreRead();
+ }}
+ />
+ {fileError && <FieldError>{fileError}</FieldError>}
+ </FieldContent>
+ </Field>
+ <Field data-invalid={Boolean(passwordError)}>
+ <FieldLabel>Password</FieldLabel>
+ <FieldContent>
+ <Input
+ type="password"
+ autoComplete="off"
+ value={keystorePassword}
+ onChange={(e) => {
+ setKeystorePassword(e.target.value);
+ discardKeystoreRead();
+ }}
+ placeholder="Leave blank if the keystore has no password"
+ />
+ {passwordError ? (
+ <FieldError>{passwordError}</FieldError>
+ ) : (
+ <FieldDescription>
+ Infisical opens the keystore in your browser to list what is inside.
+ </FieldDescription>
+ )}
+ </FieldContent>
+ </Field>
+ </>
+ ) : (
+ <>
+ <Controller
+ control={control}
+ name="certificatePem"
+ render={({ field, fieldState: { error } }) => (
+ <Field data-invalid={Boolean(error)}>
+ <FieldLabel>Leaf Certificate PEM</FieldLabel>
+ <TextArea {...field} />
+ {error && <FieldError>{error.message}</FieldError>}
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="chainPem"
+ render={({ field, fieldState: { error } }) => (
+ <Field data-invalid={Boolean(error)}>
+ <FieldLabel>Certificate Chain PEM (optional)</FieldLabel>
+ <TextArea {...field} />
+ {error && <FieldError>{error.message}</FieldError>}
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="privateKeyPem"
+ render={({ field, fieldState: { error } }) => (
+ <Field data-invalid={Boolean(error)}>
+ <FieldLabel>Private Key PEM (optional)</FieldLabel>
+ <TextArea {...field} />
+ {error && <FieldError>{error.message}</FieldError>}
+ </Field>
+ )}
+ />
+ </>
+ )}
+ </FieldGroup>
+ );
+
+ const renderEntriesTable = () => (
+ <Table
+ containerClassName="max-h-80 thin-scrollbar overflow-auto"
+ style={{
+ minWidth:
+ ENTRY_BASE_WIDTH +
+ (hasApplication ? ENTRY_PROFILE_WIDTH : 0) +
+ (referenceColumnLabel ? ENTRY_REF_WIDTH : 0)
+ }}
+ >
+ <TableHeader>
+ <TableRow>
+ <TableHead className={`w-12 ${STICKY_HEAD}`}>
+ <Checkbox
+ id="select-all-entries"
+ variant="project"
+ isChecked={
+ Boolean(selectableEntries.length) && selected.size === selectableEntries.length
+ }
+ onCheckedChange={() =>
+ setSelected((prev) =>
+ prev.size === selectableEntries.length
+ ? new Set()
+ : new Set(selectableEntries.map((entry) => entry.fingerprintSha256))
+ )
+ }
+ />
+ </TableHead>
+ <TableHead className={`min-w-44 ${STICKY_HEAD}`}>SAN / CN</TableHead>
+ <TableHead className={`w-20 ${STICKY_HEAD}`}>Private Key</TableHead>
+ <TableHead className={`w-16 ${STICKY_HEAD}`}>Chain</TableHead>
+ {hasApplication && (
+ <TableHead className={`w-56 ${STICKY_HEAD}`}>Certificate Profile</TableHead>
+ )}
+ {referenceColumnLabel && (
+ <TableHead className={`w-56 ${STICKY_HEAD}`}>{referenceColumnLabel}</TableHead>
+ )}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {selectableEntries.map((entry) => (
+ <KeystoreEntryRow
+ key={entry.fingerprintSha256}
+ entry={entry}
+ isImported={importedFingerprints.has(entry.fingerprintSha256)}
+ isSelected={selected.has(entry.fingerprintSha256)}
+ onToggle={() => toggleEntry(entry.fingerprintSha256)}
+ showProfile={hasApplication}
+ hasReferenceColumn={Boolean(referenceColumnLabel)}
+ profileOptions={profileOptions}
+ isProfilesLoading={isProfilesLoading}
+ profileId={profileByFingerprint[entry.fingerprintSha256]}
+ onProfileChange={(profileId) => {
+ setProfileByFingerprint((prev) => {
+ const next = { ...prev };
+ if (profileId) next[entry.fingerprintSha256] = profileId;
+ else delete next[entry.fingerprintSha256];
+ return next;
+ });
+ setReferences((prev) => ({ ...prev, [entry.fingerprintSha256]: "" }));
+ }}
+ lastError={failureByFingerprint[entry.fingerprintSha256]}
+ referenceValue={references[entry.fingerprintSha256]}
+ onReferenceChange={(value) =>
+ setReferences((prev) => ({ ...prev, [entry.fingerprintSha256]: value }))
+ }
+ />
+ ))}
+ </TableBody>
+ </Table>
+ );
+
+ const renderProfileStep = () => (
+ <FieldGroup>
+ {hasApplication && !isKeystore && (
+ <Field>
+ <FieldLabel>Certificate Profile (optional)</FieldLabel>
+ <FieldContent>
+ <CertificateProfileSelect
+ options={profileOptions}
+ isLoading={isProfilesLoading}
+ value={selectedProfileId}
+ onChange={(profileId) => {
+ setValue("profileId", profileId);
+ setValue("providerReference", "");
+ }}
+ />
+ <FieldDescription>
+ Leave empty to track this certificate without renewal, reissue or revocation.
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+
+ {reference && !isKeystore && (
+ <Controller
+ control={control}
+ name="providerReference"
+ render={({ field, fieldState: { error } }) => (
+ <Field data-invalid={Boolean(error)}>
+ <FieldLabel>{reference.label}</FieldLabel>
+ <FieldContent>
+ <CertificateReferenceField
+ source={referenceSource}
+ value={field.value}
+ onChange={field.onChange}
+ />
+ <FieldDescription>{reference.description}</FieldDescription>
+ {error && <FieldError>{error.message}</FieldError>}
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+
+ {isKeystore && selectableEntries.length > 0 && (
+ <Field>
+ <FieldLabel>{`${selectedEntries.length} certificate${selectedEntries.length === 1 ? "" : "s"} to import`}</FieldLabel>
+ <FieldContent>{renderEntriesTable()}</FieldContent>
+ </Field>
+ )}
+ </FieldGroup>
+ );
+
+ const renderResults = () => {
+ const attempted = (entries ?? []).filter(
+ (entry) =>
+ importedFingerprints.has(entry.fingerprintSha256) ||
+ failureByFingerprint[entry.fingerprintSha256]
+ );
+ return (
+ <ItemGroup className="max-h-[28rem] thin-scrollbar gap-2 overflow-y-auto">
+ {attempted.map((entry) => {
+ const error = failureByFingerprint[entry.fingerprintSha256];
+ return (
+ <Item key={entry.fingerprintSha256} variant="outline" size="xs" role="listitem">
+ <ItemMedia variant="icon">
+ {error ? (
+ <CircleX className="text-danger" />
+ ) : (
+ <CircleCheck className="text-success" />
+ )}
+ </ItemMedia>
+ <ItemContent className="min-w-0">
+ <ItemTitle className="truncate">{entryLabel(entry)}</ItemTitle>
+ <ItemDescription className="mt-1 line-clamp-none whitespace-pre-line">
+ {error ?? "Imported"}
+ </ItemDescription>
+ </ItemContent>
+ </Item>
+ );
+ })}
+ </ItemGroup>
+ );
+ };
+
+ const renderReviewTable = () => {
+ const rows = isKeystore
+ ? selectedEntries.map((entry) => ({
+ key: entry.fingerprintSha256,
+ name: entryLabel(entry),
+ serialNumber: entry.serialNumber,
+ hasChain: Boolean(entry.chainPem),
+ hasPrivateKey: Boolean(entry.privateKeyPem),
+ profileName: profileFor(entry.fingerprintSha256)?.slug,
+ referenceValue: references[entry.fingerprintSha256]
+ }))
+ : [
+ {
+ key: "pem",
+ name: pemSummary?.altNames || pemSummary?.commonName || pemSummary?.subject || "—",
+ serialNumber: pemSummary?.serialNumber ?? "",
+ hasChain: Boolean(getValues("chainPem")?.trim()),
+ hasPrivateKey: Boolean(getValues("privateKeyPem")?.trim()),
+ profileName: selectedProfile?.slug,
+ referenceValue: getValues("providerReference")
+ }
+ ];
+
+ const reviewReferenceLabel = isKeystore ? referenceColumnLabel : (reference?.label ?? null);
+
+ return (
+ <Table
+ containerClassName="max-h-96 thin-scrollbar overflow-auto"
+ style={{
+ minWidth:
+ REVIEW_BASE_WIDTH +
+ (hasApplication ? REVIEW_PROFILE_WIDTH : 0) +
+ (reviewReferenceLabel ? REVIEW_REF_WIDTH : 0)
+ }}
+ >
+ <TableHeader>
+ <TableRow>
+ <TableHead className={`min-w-44 ${STICKY_HEAD}`}>SAN / CN</TableHead>
+ <TableHead className={`w-44 ${STICKY_HEAD}`}>Serial Number</TableHead>
+ <TableHead className={`w-16 ${STICKY_HEAD}`}>Chain</TableHead>
+ <TableHead className={`w-20 ${STICKY_HEAD}`}>Private Key</TableHead>
+ {hasApplication && (
+ <TableHead className={`w-44 ${STICKY_HEAD}`}>Certificate Profile</TableHead>
+ )}
+ {reviewReferenceLabel && (
+ <TableHead className={`w-40 ${STICKY_HEAD}`}>{reviewReferenceLabel}</TableHead>
+ )}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row) => (
+ <TableRow key={row.key}>
+ <TableCell className="max-w-0">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="block truncate">{row.name}</span>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-lg break-words">{row.name}</TooltipContent>
+ </Tooltip>
+ </TableCell>
+ <TableCell className="max-w-0">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="block truncate font-mono text-xs">{row.serialNumber}</span>
+ </TooltipTrigger>
+ <TooltipContent className="font-mono text-xs">{row.serialNumber}</TooltipContent>
+ </Tooltip>
+ </TableCell>
+ <TableCell>
+ <Badge variant={row.hasChain ? "success" : "neutral"}>
+ {row.hasChain ? "Yes" : "No"}
+ </Badge>
+ </TableCell>
+ <TableCell>
+ <Badge variant={row.hasPrivateKey ? "success" : "neutral"}>
+ {row.hasPrivateKey ? "Yes" : "No"}
+ </Badge>
+ </TableCell>
+ {hasApplication && (
+ <TableCell className="max-w-0">
+ {row.profileName ? (
+ <span className="block truncate">{row.profileName}</span>
+ ) : (
+ <span className="text-muted/50 italic">None</span>
+ )}
+ </TableCell>
+ )}
+ {reviewReferenceLabel && (
+ <TableCell className="max-w-0">
+ <span className="block truncate font-mono text-xs">
+ {row.referenceValue || "—"}
+ </span>
+ </TableCell>
+ )}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ );
+ };
+
+ const renderReviewStep = () => {
+ if (isKeystore && hasRun) {
+ return <ReviewSection title="Results">{renderResults()}</ReviewSection>;
+ }
+
+ if (!isKeystore && pemError) {
+ return (
+ <ReviewSection title="Import Failed">
+ <Item variant="outline" size="xs" role="listitem">
+ <ItemMedia variant="icon">
+ <CircleX className="text-danger" />
+ </ItemMedia>
+ <ItemContent className="min-w-0">
+ <ItemDescription className="line-clamp-none whitespace-pre-line">
+ {pemError}
+ </ItemDescription>
+ </ItemContent>
+ </Item>
+ </ReviewSection>
+ );
+ }
+
+ return (
+ <ReviewSection title={isKeystore ? "Certificates" : "Certificate"}>
+ {renderReviewTable()}
+ </ReviewSection>
+ );
+ };
+
+ const isSourceIncomplete = isKeystore && !keystoreFiles.length;
+ const hasNothingToImport = isKeystore && selectedEntries.length === 0;
+
+ const isImporting = isImportingPem || isImportingEntries || isSubmitting;
+
+ const submitLabel = (() => {
+ if (!isKeystore) return "Import";
+ if (hasRun && selectedEntries.length) return `Retry ${selectedEntries.length}`;
+ return `Import ${selectedEntries.length}`;
+ })();
+
+ const allKeystoreDone = isKeystore && hasRun && selectableEntries.length === 0;
+
+ const clearLastRun = () => {
+ if (isKeystore && !selectableEntries.length) return;
+ setPemError(null);
+ setHasRun(false);
+ };
+
+ const onSubmit = async () => {
+ if (allKeystoreDone) {
+ handlePopUpToggle("certificateImport", false);
+ return;
+ }
+ if (isKeystore) {
+ await importKeystore();
+ return;
+ }
+ await handleSubmit(importPem, onFormInvalid)();
+ };
+
+ return (
+ <CertificateWizardSheet
+ isOpen={isOpen}
+ onOpenChange={(open) => handlePopUpToggle("certificateImport", open)}
+ icon={<Upload className="size-5" />}
+ title="Import Certificate"
+ description="Bring a certificate you already hold under Infisical management."
+ steps={steps}
+ activeStep={step}
+ onStepChange={(index) => {
+ clearLastRun();
+ setStep(index);
+ }}
+ submitLabel={allKeystoreDone ? "Done" : submitLabel}
+ onSubmit={onSubmit}
+ onBack={() => {
+ clearLastRun();
+ goBack();
+ }}
+ onContinue={goNext}
+ isSubmitting={isImporting}
+ isSubmitDisabled={!allKeystoreDone && (hasNothingToImport || isMissingReference)}
+ isContinuePending={isExtracting}
+ isContinueDisabled={
+ (currentStepKey === "source" && (isSourceIncomplete || isExtracting)) ||
+ (currentStepKey === "profile" && (hasNothingToImport || isMissingReference))
+ }
+ >
+ {currentStepKey === "source" && renderSourceStep()}
+ {currentStepKey === "profile" && renderProfileStep()}
+ {currentStepKey === "review" && renderReviewStep()}
+ </CertificateWizardSheet>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx
index c1ec430a8f..a391d3e1ef 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx
@@ -43,6 +43,7 @@ type Props = {
isSubmitting?: boolean;
isSubmitDisabled?: boolean;
isContinueDisabled?: boolean;
+ isContinuePending?: boolean;
};
export const useWizardSteps = <TStepKey extends string>({
@@ -110,7 +111,8 @@ export const CertificateWizardSheet = ({
onContinue,
isSubmitting = false,
isSubmitDisabled = false,
- isContinueDisabled = false
+ isContinueDisabled = false,
+ isContinuePending = false
}: Props) => {
const step = steps[Math.min(activeStep, steps.length - 1)];
const isLastStep = activeStep === steps.length - 1;
@@ -204,6 +206,7 @@ export const CertificateWizardSheet = ({
<Button
type="button"
variant="project"
+ isPending={isContinuePending}
isDisabled={isContinueDisabled}
onClick={onContinue}
>
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
index a12963f240..25a1431a5f 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
@@ -29,7 +29,7 @@ import { usePopUp } from "@app/hooks/usePopUp";
import { PkiDocsUrls } from "../../pki-docs-urls";
import { CertificateCertModal } from "./CertificateCertModal";
import { CertificateExportModal, ExportOptions } from "./CertificateExportModal";
-import { CertificateImportModal } from "./CertificateImportModal";
+import { CertificateImportSheet } from "./CertificateImportSheet";
import { CertificateManagePkiSyncsModal } from "./CertificateManagePkiSyncsModal";
import { CertificateManageRenewalModal } from "./CertificateManageRenewalModal";
import { CertificateRenewalModal } from "./CertificateRenewalModal";
@@ -185,7 +185,7 @@ export const CertificatesSection = ({
applicationId={applicationId}
applicationName={applicationName}
/>
- <CertificateImportModal
+ <CertificateImportSheet
popUp={popUp}
handlePopUpToggle={handlePopUpToggle}
applicationId={applicationId}
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.tsx
index 76bba85655..cce847148b 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
@@ -134,7 +134,7 @@ export const useCertificateImportReference = (profile: ProfileOption | null) =>
return { reference, referenceOptions, isOptionsLoading: isResolvingOptions, useFreeText };
};
-export type TCertificateReferenceSource = ReturnType<typeof useCertificateImportReference>;
+type TCertificateReferenceSource = ReturnType<typeof useCertificateImportReference>;
export const CertificateReferenceField = ({
source,