Skip to content

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

Address PR comments

Carlos Monastyrskia7b6442f7bb8
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 62af2185c2..985a5ddf6e 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2274,7 +2274,7 @@ export const CERTIFICATES = {
friendlyName: "A friendly name for the certificate.",
pkiCollectionId: "The ID of the PKI collection to add the certificate to.",
profileId:
- "The certificate profile that will manage this certificate's lifecycle. Omit to track the certificate without renewal, reissue or revocation.",
+ "The certificate profile that will manage this certificate's lifecycle. The certificate must satisfy the profile's certificate policy, or the request is rejected with a 400 naming the attributes that failed. Omit to track the certificate without renewal, reissue or revocation.",
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 }.',
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 84ada38c0d..88ca47cda2 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3475,6 +3475,7 @@ export const registerRoutes = async (
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL,
digicertFns: digicertCaFns,
+ certificatePolicyService,
licenseService,
usageMeteringService,
hsmConnectorService
diff --git a/backend/src/services/certificate-common/external-metadata-schemas.ts b/backend/src/services/certificate-common/external-metadata-schemas.ts
index 91e57d649f..787ad93c72 100644
--- a/backend/src/services/certificate-common/external-metadata-schemas.ts
+++ b/backend/src/services/certificate-common/external-metadata-schemas.ts
@@ -35,17 +35,35 @@ export const ExternalMetadataSchema = z.discriminatedUnion("type", [
export type TExternalMetadata = z.infer<typeof ExternalMetadataSchema>;
-export const CertificateImportLinkageMap: Partial<
- Record<CaType, { externalMetadataSchema: z.ZodTypeAny | null; referenceLabel?: string }>
-> = {
- [CaType.INTERNAL]: { externalMetadataSchema: null },
- [CaType.DIGICERT]: { externalMetadataSchema: DigiCertExternalMetadataSchema, referenceLabel: "DigiCert order ID" }
-};
-
export const ImportExternalMetadataSchema = z.discriminatedUnion("type", [DigiCertExternalMetadataSchema]);
export type TImportExternalMetadata = z.infer<typeof ImportExternalMetadataSchema>;
+type TCertificateImportVerifierDeps = {
+ digicertFns: {
+ assertOrderMatchesCertificate: (args: { caId: string; orderId: number; serialNumber: string }) => Promise<void>;
+ };
+};
+
+type TCertificateImportLinkage = {
+ externalMetadataSchema: z.ZodTypeAny | null;
+ referenceLabel?: string;
+ verifyCertificate?: (
+ args: { caId: string; externalMetadata: TImportExternalMetadata; serialNumber: string },
+ deps: TCertificateImportVerifierDeps
+ ) => Promise<void>;
+};
+
+export const CertificateImportLinkageMap: Partial<Record<CaType, TCertificateImportLinkage>> = {
+ [CaType.INTERNAL]: { externalMetadataSchema: null },
+ [CaType.DIGICERT]: {
+ externalMetadataSchema: DigiCertExternalMetadataSchema,
+ referenceLabel: "DigiCert order ID",
+ verifyCertificate: ({ caId, externalMetadata, serialNumber }, { digicertFns }) =>
+ digicertFns.assertOrderMatchesCertificate({ caId, orderId: externalMetadata.orderId, serialNumber })
+ }
+};
+
export const CA_TYPE_LABEL: Record<CaType, string> = {
[CaType.INTERNAL]: "Internal CA",
[CaType.ACME]: "ACME",
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index b737c8541f..0fd811c341 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -33,6 +33,7 @@ import {
CertificateImportLinkageMap,
TImportExternalMetadata
} from "@app/services/certificate-common/external-metadata-schemas";
+import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
import { IssuerType } from "@app/services/certificate-profile/certificate-profile-types";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
@@ -62,9 +63,12 @@ import {
} from "../certificate-authority/certificate-authority-fns";
import {
calculateFinalRenewBeforeDays,
+ detectSanType,
resolveEffectiveApiConfig
} from "../certificate-common/certificate-issuance-utils";
import { validatePqcLicense } from "../certificate-common/certificate-utils";
+import { certificateSpanToTtl } from "../certificate-v3/certificate-renewal-fns";
+import { parseExtendedKeyUsages, parseKeyUsages } from "../certificate-v3/certificate-v3-fns";
import {
CertificateThumbprintAlgorithm,
extractCertificateAlgorithms,
@@ -80,7 +84,9 @@ import { TCertificateSecretDALFactory } from "./certificate-secret-dal";
import {
CertExtendedKeyUsage,
CertExtendedKeyUsageOIDToName,
+ CertKeyAlgorithm,
CertKeyUsage,
+ CertSignatureAlgorithm,
CertStatus,
TAssignCertToApplicationDTO,
TCertificateBasicConstraints,
@@ -116,6 +122,7 @@ type TCertificateServiceFactoryDep = {
pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;
apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;
digicertFns: Pick<ReturnType<typeof DigiCertCertificateAuthorityFns>, "assertOrderMatchesCertificate">;
+ certificatePolicyService: Pick<TCertificatePolicyServiceFactory, "validateCertificateRequest">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne" | "create">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
@@ -164,6 +171,7 @@ export const certificateServiceFactory = ({
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL,
digicertFns,
+ certificatePolicyService,
licenseService,
usageMeteringService,
hsmConnectorService
@@ -498,11 +506,6 @@ export const certificateServiceFactory = ({
};
};
- /**
- * Revoke certificate with serial number [serialNumber].
- * Note: Revoking a certificate adds it to the certificate revocation list (CRL)
- * of its issuing CA
- */
const $assertInternalCaIssuedCertificate = async (caId: string, certificatePem: string) => {
const caCerts = await getCaCertChains({
caId,
@@ -529,6 +532,11 @@ export const certificateServiceFactory = ({
}
};
+ /**
+ * Revoke certificate with serial number [serialNumber].
+ * Note: Revoking a certificate adds it to the certificate revocation list (CRL)
+ * of its issuing CA
+ */
const revokeCert = async ({
id,
serialNumber,
@@ -906,7 +914,9 @@ export const certificateServiceFactory = ({
externalMetadata: undefined,
profileName: profile.slug,
caName: null,
- profileApiConfig: profile.apiConfig
+ profileApiConfig: profile.apiConfig,
+ policyId: profile.certificatePolicyId,
+ verifyCertificate: undefined
};
}
@@ -931,7 +941,9 @@ export const certificateServiceFactory = ({
externalMetadata: undefined,
profileName: profile.slug,
caName,
- profileApiConfig: profile.apiConfig
+ profileApiConfig: profile.apiConfig,
+ policyId: profile.certificatePolicyId,
+ verifyCertificate: undefined
};
}
@@ -948,13 +960,22 @@ export const certificateServiceFactory = ({
});
}
+ const caId = profile.caId;
+ const parsedMetadata = parsed.data as TImportExternalMetadata;
+ const { verifyCertificate } = linkage;
+
return {
- caId: profile.caId,
+ caId,
caType,
- externalMetadata: parsed.data as TImportExternalMetadata,
+ externalMetadata: parsedMetadata,
profileName: profile.slug,
caName,
- profileApiConfig: profile.apiConfig
+ profileApiConfig: profile.apiConfig,
+ policyId: profile.certificatePolicyId,
+ verifyCertificate: verifyCertificate
+ ? (serialNumber: string) =>
+ verifyCertificate({ caId, externalMetadata: parsedMetadata, serialNumber }, { digicertFns })
+ : undefined
};
};
@@ -1125,12 +1146,59 @@ export const certificateServiceFactory = ({
const { serialNumber, notBefore, notAfter } = leafCert;
- if (linkage?.caType === CaType.DIGICERT && linkage.externalMetadata?.type === CaType.DIGICERT) {
- await digicertFns.assertOrderMatchesCertificate({
- caId: linkage.caId,
- orderId: linkage.externalMetadata.orderId,
- serialNumber
+ await linkage?.verifyCertificate?.(serialNumber);
+
+ const keyUsagesExt = leafCert.getExtension("2.5.29.15") as x509.KeyUsagesExtension;
+
+ let keyUsages: CertKeyUsage[] = [];
+ if (keyUsagesExt) {
+ keyUsages = Object.values(CertKeyUsage).filter(
+ // eslint-disable-next-line no-bitwise
+ (keyUsage) => (x509.KeyUsageFlags[keyUsage] & keyUsagesExt.usages) !== 0
+ );
+ }
+
+ const extKeyUsageExt = leafCert.getExtension("2.5.29.37") as x509.ExtendedKeyUsageExtension;
+ let extendedKeyUsages: CertExtendedKeyUsage[] = [];
+ if (extKeyUsageExt) {
+ extendedKeyUsages = extKeyUsageExt.usages.map((ekuOid) => CertExtendedKeyUsageOIDToName[ekuOid as string]);
+ }
+
+ const certificateBuffer = Buffer.from(certificatePem);
+ const certificateFields = extractCertificateFields(certificateBuffer);
+ const certificateAlgorithms = extractCertificateAlgorithms(certificateBuffer);
+
+ if (linkage) {
+ const { keyAlgorithm, signatureAlgorithm } = certificateAlgorithms;
+
+ const validation = await certificatePolicyService.validateCertificateRequest(linkage.policyId, {
+ commonName: commonName || undefined,
+ organization: certificateFields.subjectOrganization ?? undefined,
+ organizationalUnit: certificateFields.subjectOrganizationalUnit ?? undefined,
+ country: certificateFields.subjectCountry ?? undefined,
+ state: certificateFields.subjectState ?? undefined,
+ locality: certificateFields.subjectLocality ?? undefined,
+ domainComponents: certificateFields.subjectDomainComponents?.split(",") ?? undefined,
+ keyUsages: parseKeyUsages(keyUsages),
+ extendedKeyUsages: parseExtendedKeyUsages(extendedKeyUsages),
+ subjectAlternativeNames: altNames ? altNames.split(",").map((san) => detectSanType(san.trim())) : [],
+ validity: { ttl: certificateSpanToTtl(notBefore, notAfter) },
+ keyAlgorithm: Object.values(CertKeyAlgorithm).includes(keyAlgorithm as CertKeyAlgorithm)
+ ? keyAlgorithm
+ : undefined,
+ signatureAlgorithm: Object.values(CertSignatureAlgorithm).includes(signatureAlgorithm as CertSignatureAlgorithm)
+ ? signatureAlgorithm
+ : undefined,
+ ...(certificateFields.isCA && {
+ basicConstraints: { isCA: true, pathLength: certificateFields.pathLength ?? undefined }
+ })
});
+
+ if (!validation.isValid) {
+ throw new BadRequestError({
+ message: `This certificate does not satisfy the policy of certificate profile '${linkage.profileName}', so that profile could not renew it: ${validation.errors.join(", ")}. Attach a profile whose policy allows this certificate, or import it without one to track it for visibility and expiry alerts only.`
+ });
+ }
}
// Encrypt certificate for storage
@@ -1151,24 +1219,6 @@ export const certificateServiceFactory = ({
? (await kmsEncryptor({ plainText: Buffer.from(privateKeyPem) })).cipherTextBlob
: null;
- // Extract Key Usage
- const keyUsagesExt = leafCert.getExtension("2.5.29.15") as x509.KeyUsagesExtension;
-
- let keyUsages: CertKeyUsage[] = [];
- if (keyUsagesExt) {
- keyUsages = Object.values(CertKeyUsage).filter(
- // eslint-disable-next-line no-bitwise
- (keyUsage) => (x509.KeyUsageFlags[keyUsage] & keyUsagesExt.usages) !== 0
- );
- }
-
- // Extract Extended Key Usage
- const extKeyUsageExt = leafCert.getExtension("2.5.29.37") as x509.ExtendedKeyUsageExtension;
- let extendedKeyUsages: CertExtendedKeyUsage[] = [];
- if (extKeyUsageExt) {
- extendedKeyUsages = extKeyUsageExt.usages.map((ekuOid) => CertExtendedKeyUsageOIDToName[ekuOid as string]);
- }
-
const encryptedCertificateChain = chainPem
? (await kmsEncryptor({ plainText: Buffer.from(chainPem) })).cipherTextBlob
: null;
@@ -1188,10 +1238,6 @@ export const certificateServiceFactory = ({
const cert = await certificateDAL.transaction(async (tx) => {
try {
- // Extract certificate fields for storage
- const certificateBuffer = Buffer.from(certificatePem);
- const parsedFields = extractCertificateFields(certificateBuffer);
-
const txCert = await certificateDAL.create(
{
status: CertStatus.ACTIVE,
@@ -1210,10 +1256,10 @@ export const certificateServiceFactory = ({
renewBeforeDays,
keyUsages,
extendedKeyUsages,
- ...parsedFields,
+ ...certificateFields,
// Issuance records these from what it was asked to produce. An imported certificate has
// no such request, so they come from the certificate itself.
- ...extractCertificateAlgorithms(certificateBuffer)
+ ...certificateAlgorithms
},
tx
);
diff --git a/docs/documentation/platform/pki/applications/certificates.mdx b/docs/documentation/platform/pki/applications/certificates.mdx
index 3969856136..bdc1ee7b4c 100644
--- a/docs/documentation/platform/pki/applications/certificates.mdx
+++ b/docs/documentation/platform/pki/applications/certificates.mdx
@@ -64,21 +64,23 @@ A keystore can hold several certificates. Infisical lists what is inside so you
An imported certificate is tracked for visibility and expiry alerts. Renewal, reissue and revocation stay wherever it was issued.
-To hand the rest of its lifecycle to Infisical, pick a **Certificate Profile** during import. The profile determines which authority signs the replacement when the certificate is renewed. Nothing is reissued at import time and your key pair is untouched.
+To hand the rest of its lifecycle to Infisical, pick a **Certificate Profile** during import. The profile determines which authority signs the replacement when the certificate is renewed.
Renewal also needs [API enrollment](/documentation/platform/pki/applications/enrollment-methods/api) turned on for that profile in this Application.
<Note>
- You can pick a profile when you import PEM files into an Application. Importing a keystore, or importing from the organization-wide Inventory, tracks the certificate without one.
+ You can pick a profile when you import into an Application, from either PEM files or a keystore. Importing from the organization-wide Inventory tracks the certificate without one.
</Note>
### Which profile to attach
Attaching a profile backed by the authority that issued the certificate keeps the whole lifecycle in Infisical.
+The certificate has to satisfy the profile's certificate policy, because that policy is what constrains the replacement issued at renewal. Infisical checks it during import and refuses a profile the certificate doesn't meet, naming the attributes that failed, so the problem surfaces then rather than at renewal. Import without a profile if you only need visibility and expiry alerts.
+
You can also attach one backed by a different authority, including a self-signed profile. The certificate you already hold stays in service, and its replacement is issued by the authority you're moving to. Renewal works in both cases, because a renewal is a new certificate signed by the profile's authority.
-Revocation behaves differently. It only takes effect through the issuing authority, because that authority publishes the revocation list clients check. Infisical therefore refuses to revoke an imported certificate whose profile is backed by a different authority, rather than record a revocation no client would see. Revoke those certificates with their original issuer instead.
+Revocation behaves differently. It only takes effect through the issuing authority, because that authority publishes the revocation list clients check. Infisical therefore refuses to revoke an imported certificate whose profile is backed by a different authority. Revoke those certificates with their original issuer instead.
### What each external CA needs
diff --git a/frontend/src/hooks/api/certificateProfiles/queries.tsx b/frontend/src/hooks/api/certificateProfiles/queries.tsx
index 2df27de645..117cc4194f 100644
--- a/frontend/src/hooks/api/certificateProfiles/queries.tsx
+++ b/frontend/src/hooks/api/certificateProfiles/queries.tsx
@@ -53,7 +53,8 @@ export const useListCertificateProfiles = ({
search,
includeConfigs = false,
enrollmentType,
- applicationId
+ applicationId,
+ enabled = true
}: TListCertificateProfilesDTO) => {
return useQuery({
queryKey: certificateProfileKeys.list({
@@ -79,7 +80,8 @@ export const useListCertificateProfiles = ({
}
});
return data;
- }
+ },
+ enabled
});
};
diff --git a/frontend/src/hooks/api/certificateProfiles/types.ts b/frontend/src/hooks/api/certificateProfiles/types.ts
index ee1f64e799..e3904ad45f 100644
--- a/frontend/src/hooks/api/certificateProfiles/types.ts
+++ b/frontend/src/hooks/api/certificateProfiles/types.ts
@@ -140,6 +140,7 @@ export type TListCertificateProfilesDTO = {
issuerType?: IssuerType;
caId?: string;
applicationId?: string;
+ enabled?: boolean;
};
export type TGetCertificateProfileByIdDTO = {
diff --git a/frontend/src/hooks/api/certificates/mutations.tsx b/frontend/src/hooks/api/certificates/mutations.tsx
index a130efb4d9..754718014b 100644
--- a/frontend/src/hooks/api/certificates/mutations.tsx
+++ b/frontend/src/hooks/api/certificates/mutations.tsx
@@ -119,7 +119,7 @@ export const useImportCertificate = () => {
export const useImportPkcs12Entries = () => {
const queryClient = useQueryClient();
return useMutation<TImportPkcs12EntriesResult[], object, TImportPkcs12EntriesDTO>({
- mutationFn: async ({ entries, applicationId }) => {
+ mutationFn: async ({ entries, applicationId, profileId, externalMetadataByFingerprint }) => {
const results: TImportPkcs12EntriesResult[] = [];
await entries.reduce<Promise<void>>(async (prev, entry) => {
@@ -131,6 +131,10 @@ export const useImportPkcs12Entries = () => {
certificatePem: entry.certificatePem,
...(entry.chainPem ? { chainPem: entry.chainPem } : {}),
...(entry.privateKeyPem ? { privateKeyPem: entry.privateKeyPem } : {}),
+ ...(profileId ? { profileId } : {}),
+ ...(externalMetadataByFingerprint?.[entry.fingerprintSha256]
+ ? { externalMetadata: externalMetadataByFingerprint[entry.fingerprintSha256] }
+ : {}),
applicationId
}
);
@@ -150,6 +154,7 @@ export const useImportPkcs12Entries = () => {
onSuccess: (results) => {
if (results.some((result) => !result.error)) {
queryClient.invalidateQueries({ queryKey: projectKeys.allProjectCertificates() });
+ queryClient.invalidateQueries({ queryKey: certificateProfileKeys.lists() });
queryClient.invalidateQueries({ queryKey: ["cert-dashboard-stats"] });
}
}
diff --git a/frontend/src/hooks/api/certificates/types.ts b/frontend/src/hooks/api/certificates/types.ts
index b0a046f56c..52077be673 100644
--- a/frontend/src/hooks/api/certificates/types.ts
+++ b/frontend/src/hooks/api/certificates/types.ts
@@ -89,6 +89,8 @@ export type TRevokeCertDTO = {
export type TImportPkcs12EntriesDTO = {
entries: TPkcs12Entry[];
applicationId?: string;
+ profileId?: string;
+ externalMetadataByFingerprint?: Record<string, TCertificateExternalMetadata>;
};
export type TImportPkcs12EntriesResult = {
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
index 5e9688cf0a..a52138f8ed 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
-import { Controller, useForm } from "react-hook-form";
+import { Controller, useForm, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { CircleCheck, CircleX, TriangleAlert } from "lucide-react";
@@ -14,6 +14,8 @@ import {
DialogHeader,
DialogTitle,
Field,
+ FieldContent,
+ FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
@@ -44,6 +46,12 @@ 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";
@@ -51,6 +59,8 @@ 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 = {
@@ -94,6 +104,7 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
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,
@@ -105,6 +116,12 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
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: "",
@@ -125,6 +142,7 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
setSelected(new Set());
setOutcomes(null);
setFormat("pem");
+ setKeystoreReferences({});
};
const onFormSubmit = async ({
@@ -198,9 +216,23 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
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: entries.filter((entry) => selected.has(entry.fingerprintSha256)),
- applicationId
+ entries: selectedEntries,
+ applicationId,
+ profileId: selectedProfileId,
+ externalMetadataByFingerprint
});
setOutcomes(
@@ -281,10 +313,19 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, 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="gap-2">
+ <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">
@@ -297,7 +338,9 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
</ItemMedia>
<ItemContent className="min-w-0">
<ItemTitle className="truncate">{outcome.subject}</ItemTitle>
- <ItemDescription>{outcome.error ?? "Imported"}</ItemDescription>
+ <ItemDescription className="line-clamp-none">
+ {outcome.error ?? "Imported"}
+ </ItemDescription>
</ItemContent>
</Item>
))}
@@ -305,67 +348,111 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
);
const renderEntriesTable = () => (
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-12">
- <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>SAN / CN</TableHead>
- <TableHead className="w-40">Private Key</TableHead>
- <TableHead className="w-24">Chain</TableHead>
- <TableHead className="w-44">Expires</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {entries?.map((entry) => (
- <TableRow
- key={entry.fingerprintSha256}
- className="cursor-pointer"
- onClick={() => toggleEntry(entry.fingerprintSha256)}
- >
- <TableCell onClick={(e) => e.stopPropagation()}>
+ <>
+ {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={entry.fingerprintSha256}
+ id="select-all-entries"
variant="project"
- isChecked={selected.has(entry.fingerprintSha256)}
- onCheckedChange={() => toggleEntry(entry.fingerprintSha256)}
+ isChecked={Boolean(entries?.length) && selected.size === entries?.length}
+ onCheckedChange={() =>
+ setSelected((prev) =>
+ prev.size === entries?.length
+ ? new Set()
+ : new Set(entries?.map((entry) => 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>
+ </TableHead>
+ <TableHead className={STICKY_HEAD}>SAN / CN</TableHead>
+ <TableHead className={`w-40 ${STICKY_HEAD}`}>Private Key</TableHead>
+ <TableHead className={`w-24 ${STICKY_HEAD}`}>Chain</TableHead>
+ <TableHead className={`w-44 ${STICKY_HEAD}`}>Expires</TableHead>
+ {keystoreReference && (
+ <TableHead className={`w-64 ${STICKY_HEAD}`}>{keystoreReference.label}</TableHead>
+ )}
</TableRow>
- ))}
- </TableBody>
- </Table>
+ </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 = () => (
@@ -491,9 +578,14 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
<Button variant="outline" onClick={() => handlePopUpToggle("certificateImport", false)}>
Cancel
</Button>
+ {isMissingKeystoreReference && keystoreReference && (
+ <span className="text-sm text-mineshaft-300">
+ {`Enter the ${keystoreReference.label} for every selected certificate.`}
+ </span>
+ )}
<Button
variant="project"
- isDisabled={!selected.size || isImportingEntries}
+ isDisabled={!selected.size || isImportingEntries || isMissingKeystoreReference}
isPending={isImportingEntries}
onClick={handleImportSelected}
>
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportProfileFields.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportProfileFields.tsx
index 093e7be2c7..5ee4f82d2d 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportProfileFields.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportProfileFields.tsx
@@ -1,120 +1,29 @@
import { useEffect } from "react";
import { Control, Controller, UseFormSetValue, useWatch } from "react-hook-form";
-import { OptionProps } from "react-select";
-import {
- Field,
- FieldContent,
- FieldDescription,
- FieldError,
- FieldLabel,
- FilterableSelect,
- Input,
- ReactSelectOption,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
-import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";
-import { useListCasByProjectId } from "@app/hooks/api/ca";
-import { CaStatus, CaType } from "@app/hooks/api/ca/enums";
-import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles/queries";
+import { Field, FieldContent, FieldDescription, FieldError, FieldLabel } from "@app/components/v3";
-import { getCertificateImportReference, isCaTypeLinkable } from "./certificate-import-linkage";
+import {
+ CertificateProfileSelect,
+ CertificateReferenceField,
+ useCertificateImportProfiles,
+ useCertificateImportReference
+} from "./certificate-import-fields";
import { CertificateImportFormData } from "./types";
-type ProfileOption = {
- id: string;
- slug: string;
- caId: string | null;
- caType: CaType | null;
- isLinkable: boolean;
-};
-
-type ReferenceOption = { value: string; label: string };
-
type Props = {
control: Control<CertificateImportFormData>;
setValue: UseFormSetValue<CertificateImportFormData>;
applicationId: string;
};
-const ProfileOptionRow = (props: OptionProps<ProfileOption>) => {
- const { data, children } = props;
-
- if (data.isLinkable) return <ReactSelectOption {...props}>{children}</ReactSelectOption>;
-
- return (
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <ReactSelectOption {...props}>
- <span className="cursor-not-allowed opacity-40">{children}</span>
- </ReactSelectOption>
- </div>
- </TooltipTrigger>
- <TooltipContent side="right" className="max-w-72">
- Infisical can&apos;t manage the lifecycle of a certificate issued by this authority yet.
- </TooltipContent>
- </Tooltip>
- );
-};
-
export const CertificateImportProfileFields = ({ control, setValue, applicationId }: Props) => {
- const { data: profileData, isPending: isProfilesLoading } = useListCertificateProfiles({
- applicationId,
- limit: 100
- });
-
- const profileOptions: ProfileOption[] = (profileData?.certificateProfiles ?? [])
- .map((profile) => {
- const caType = profile.caId
- ? ((profile.certificateAuthority?.externalType as CaType) ?? CaType.INTERNAL)
- : null;
- return {
- id: profile.id,
- slug: profile.slug,
- caId: profile.caId,
- caType,
- isLinkable: profile.caId ? isCaTypeLinkable(caType) : true
- };
- })
- .sort((a, b) => Number(b.isLinkable) - Number(a.isLinkable));
+ const { profileOptions, isProfilesLoading } = useCertificateImportProfiles(applicationId);
const selectedProfileId = useWatch({ control, name: "profileId" });
const selectedProfile = profileOptions.find((option) => option.id === selectedProfileId) ?? null;
- const reference = getCertificateImportReference(selectedProfile?.caType);
-
- const { data: cas = [] } = useListCasByProjectId();
- const selectedCa = cas.find(
- (ca) => ca.id === selectedProfile?.caId && ca.status === CaStatus.ACTIVE
- );
- const digicertConfig =
- selectedCa?.type === CaType.DIGICERT && reference?.hasLiveOptions
- ? selectedCa.configuration
- : undefined;
-
- const {
- data: orders = [],
- isPending: isOptionsLoading,
- isError: isOptionsError
- } = useDigiCertConnectionListOrders(
- digicertConfig?.appConnectionId ?? "",
- digicertConfig?.organizationId ?? 0,
- digicertConfig?.productNameId ?? "",
- { enabled: Boolean(digicertConfig) }
- );
-
- const referenceOptions: ReferenceOption[] = orders.map((order) => ({
- value: String(order.orderId),
- label: `${order.commonName || "Certificate"} (#${order.orderId})`
- }));
-
- const useFreeTextReference =
- !reference?.hasLiveOptions ||
- !digicertConfig ||
- isOptionsError ||
- (!isOptionsLoading && !referenceOptions.length);
+ const referenceSource = useCertificateImportReference(selectedProfile);
+ const { reference } = referenceSource;
useEffect(() => {
setValue("linkedCaType", selectedProfile?.caType ?? undefined);
@@ -130,20 +39,11 @@ export const CertificateImportProfileFields = ({ control, setValue, applicationI
<Field data-invalid={Boolean(error)}>
<FieldLabel>Certificate Profile (optional)</FieldLabel>
<FieldContent>
- <FilterableSelect<ProfileOption>
- isLoading={isProfilesLoading}
- isClearable
+ <CertificateProfileSelect
options={profileOptions}
- components={{ Option: ProfileOptionRow }}
- isOptionDisabled={(option) => !option.isLinkable}
- value={profileOptions.find((option) => option.id === field.value) ?? null}
- onChange={(selected) =>
- field.onChange((selected as ProfileOption | null)?.id ?? undefined)
- }
- getOptionLabel={(option) => option.slug}
- getOptionValue={(option) => option.id}
- placeholder="Select a profile..."
- noOptionsMessage={() => "This application has no certificate profiles."}
+ isLoading={isProfilesLoading}
+ value={field.value}
+ onChange={field.onChange}
/>
{error && <FieldError>{error.message}</FieldError>}
</FieldContent>
@@ -159,26 +59,11 @@ export const CertificateImportProfileFields = ({ control, setValue, applicationI
<Field data-invalid={Boolean(error)}>
<FieldLabel>{reference.label}</FieldLabel>
<FieldContent>
- {useFreeTextReference ? (
- <Input
- value={field.value ?? ""}
- onChange={(e) => field.onChange(e.target.value)}
- placeholder={reference.placeholder}
- />
- ) : (
- <FilterableSelect<ReferenceOption>
- isLoading={isOptionsLoading}
- isClearable
- options={referenceOptions}
- value={referenceOptions.find((option) => option.value === field.value) ?? null}
- onChange={(selected) =>
- field.onChange((selected as ReferenceOption | null)?.value ?? "")
- }
- getOptionLabel={(option) => option.label}
- getOptionValue={(option) => option.value}
- placeholder={reference.optionsPlaceholder}
- />
- )}
+ <CertificateReferenceField
+ source={referenceSource}
+ value={field.value}
+ onChange={field.onChange}
+ />
<FieldDescription>{reference.description}</FieldDescription>
{error && <FieldError>{error.message}</FieldError>}
</FieldContent>
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
new file mode 100644
index 0000000000..4f44c7fa97
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-fields.tsx
@@ -0,0 +1,171 @@
+import { OptionProps } from "react-select";
+
+import {
+ FilterableSelect,
+ Input,
+ ReactSelectOption,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";
+import { useListCasByProjectId } from "@app/hooks/api/ca";
+import { CaStatus, CaType } from "@app/hooks/api/ca/enums";
+import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles/queries";
+
+import { getCertificateImportReference, isCaTypeLinkable } from "./certificate-import-linkage";
+
+export type ProfileOption = {
+ id: string;
+ slug: string;
+ caId: string | null;
+ caType: CaType | null;
+ isLinkable: boolean;
+};
+
+type ReferenceOption = { value: string; label: string };
+
+const ProfileOptionRow = (props: OptionProps<ProfileOption>) => {
+ const { data, children } = props;
+
+ if (data.isLinkable) return <ReactSelectOption {...props}>{children}</ReactSelectOption>;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <ReactSelectOption {...props}>
+ <span className="cursor-not-allowed opacity-40">{children}</span>
+ </ReactSelectOption>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="right" className="max-w-72">
+ Infisical can&apos;t manage the lifecycle of a certificate issued by this authority yet.
+ </TooltipContent>
+ </Tooltip>
+ );
+};
+
+export const useCertificateImportProfiles = (applicationId?: string) => {
+ const { data, isPending } = useListCertificateProfiles({
+ applicationId,
+ limit: 100,
+ enabled: Boolean(applicationId)
+ });
+
+ const profileOptions: ProfileOption[] = (data?.certificateProfiles ?? [])
+ .map((profile) => {
+ const caType = profile.caId
+ ? ((profile.certificateAuthority?.externalType as CaType) ?? CaType.INTERNAL)
+ : null;
+ return {
+ id: profile.id,
+ slug: profile.slug,
+ caId: profile.caId,
+ caType,
+ isLinkable: profile.caId ? isCaTypeLinkable(caType) : true
+ };
+ })
+ .sort((a, b) => Number(b.isLinkable) - Number(a.isLinkable));
+
+ return { profileOptions, isProfilesLoading: isPending };
+};
+
+export const CertificateProfileSelect = ({
+ options,
+ isLoading,
+ value,
+ onChange
+}: {
+ options: ProfileOption[];
+ isLoading: boolean;
+ value?: string;
+ onChange: (profileId?: string) => void;
+}) => (
+ <FilterableSelect<ProfileOption>
+ isLoading={isLoading}
+ isClearable
+ options={options}
+ components={{ Option: ProfileOptionRow }}
+ isOptionDisabled={(option) => !option.isLinkable}
+ value={options.find((option) => option.id === value) ?? null}
+ onChange={(selected) => onChange((selected as ProfileOption | null)?.id ?? undefined)}
+ getOptionLabel={(option) => option.slug}
+ getOptionValue={(option) => option.id}
+ placeholder="Select a profile..."
+ noOptionsMessage={() => "This application has no certificate profiles."}
+ />
+);
+
+export const useCertificateImportReference = (profile: ProfileOption | null) => {
+ const reference = getCertificateImportReference(profile?.caType);
+
+ const { data: cas = [] } = useListCasByProjectId();
+ const selectedCa = cas.find((ca) => ca.id === profile?.caId && ca.status === CaStatus.ACTIVE);
+ const digicertConfig =
+ selectedCa?.type === CaType.DIGICERT && reference?.hasLiveOptions
+ ? selectedCa.configuration
+ : undefined;
+
+ const {
+ data: orders = [],
+ isPending: isOptionsLoading,
+ isError: isOptionsError
+ } = useDigiCertConnectionListOrders(
+ digicertConfig?.appConnectionId ?? "",
+ digicertConfig?.organizationId ?? 0,
+ digicertConfig?.productNameId ?? "",
+ { enabled: Boolean(digicertConfig) }
+ );
+
+ const referenceOptions: ReferenceOption[] = orders.map((order) => ({
+ value: String(order.orderId),
+ label: `${order.commonName || "Certificate"} (#${order.orderId})`
+ }));
+
+ const useFreeText =
+ !reference?.hasLiveOptions ||
+ !digicertConfig ||
+ isOptionsError ||
+ (!isOptionsLoading && !referenceOptions.length);
+
+ return { reference, referenceOptions, isOptionsLoading, useFreeText };
+};
+
+export type TCertificateReferenceSource = ReturnType<typeof useCertificateImportReference>;
+
+export const CertificateReferenceField = ({
+ source,
+ value,
+ onChange
+}: {
+ source: TCertificateReferenceSource;
+ value?: string;
+ onChange: (value: string) => void;
+}) => {
+ const { reference, referenceOptions, isOptionsLoading, useFreeText } = source;
+ if (!reference) return null;
+
+ if (useFreeText) {
+ return (
+ <Input
+ value={value ?? ""}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={reference.placeholder}
+ />
+ );
+ }
+
+ return (
+ <FilterableSelect<ReferenceOption>
+ isLoading={isOptionsLoading}
+ isClearable
+ options={referenceOptions}
+ value={referenceOptions.find((option) => option.value === value) ?? null}
+ onChange={(selected) => onChange((selected as ReferenceOption | null)?.value ?? "")}
+ getOptionLabel={(option) => option.label}
+ getOptionValue={(option) => option.value}
+ placeholder={reference.optionsPlaceholder}
+ />
+ );
+};