Skip to content

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

feat(pki): manage imported certificates by attaching a certificate profile

Carlos Monastyrski6ac348b52732
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 5301ca3c1a..c059e6f4f2 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -3080,6 +3080,10 @@ interface ImportCert {
certId: string;
cn: string;
serialNumber: string;
+ certificateProfileId?: string;
+ profileName?: string;
+ caId?: string;
+ caName?: string;
};
}
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 0ed0a1350d..62af2185c2 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2232,6 +2232,8 @@ export const CERTIFICATES = {
id: "The ID of the certificate to get.",
serialNumber: "The serial number of the certificate to get.",
hasPrivateKey: "Whether Infisical holds the private key for this certificate.",
+ externalMetadata:
+ "Identifies this certificate at the provider that issued it, for certificates issued by or linked to an external certificate authority. Null for everything else.",
latestRenewalCertificateId:
"The ID of the newest certificate that has replaced this one through renewal, or null if no newer replacement is available. Revoked certificates are never named, so this is null when this certificate has never been renewed and also when every renewal of it has since been revoked. Use this to follow renewals without walking the chain one certificate at a time."
},
@@ -2271,6 +2273,10 @@ export const CERTIFICATES = {
chainPem: "Optional PEM-encoded chain of intermediate 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.",
+ 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 }.',
certificate: "The imported certificate.",
certificateChain:
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index e230d1efb5..7459200cc1 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3439,6 +3439,18 @@ export const registerRoutes = async (
telemetryService
});
+ const digicertCaFns = DigiCertCertificateAuthorityFns({
+ appConnectionDAL,
+ appConnectionService,
+ certificateAuthorityDAL,
+ externalCertificateAuthorityDAL,
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ kmsService,
+ projectDAL
+ });
+
const certificateService = certificateServiceFactory({
certificateDAL,
certificateBodyDAL,
@@ -3459,23 +3471,14 @@ export const registerRoutes = async (
resourceMetadataDAL,
pkiAlertV2Queue,
pkiApplicationDAL,
+ certificateProfileDAL,
+ pkiApplicationProfileDAL,
+ digicertFns: digicertCaFns,
licenseService,
usageMeteringService,
hsmConnectorService
});
- const digicertCaFns = DigiCertCertificateAuthorityFns({
- appConnectionDAL,
- appConnectionService,
- certificateAuthorityDAL,
- externalCertificateAuthorityDAL,
- certificateDAL,
- certificateBodyDAL,
- certificateSecretDAL,
- kmsService,
- projectDAL
- });
-
const godaddyCaFns = GoDaddyCertificateAuthorityFns({
appConnectionDAL,
appConnectionService,
diff --git a/backend/src/server/routes/v1/app-connection-routers/digicert-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/digicert-connection-router.ts
index ad9ee43aa1..ab78873314 100644
--- a/backend/src/server/routes/v1/app-connection-routers/digicert-connection-router.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/digicert-connection-router.ts
@@ -92,7 +92,7 @@ export const registerDigiCertConnectionRouter = async (server: FastifyZodProvide
organizationId: z.coerce.number().int().positive()
}),
querystring: z.object({
- productNameId: z.string().trim().min(1)
+ productNameId: z.string().trim().min(1).max(64)
}),
response: {
200: z.object({
@@ -126,7 +126,7 @@ export const registerDigiCertConnectionRouter = async (server: FastifyZodProvide
organizationId: z.coerce.number().int().positive()
}),
querystring: z.object({
- productNameId: z.string().trim().min(1)
+ productNameId: z.string().trim().min(1).max(64)
}),
response: {
200: z
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index 39a51bd018..b40de16995 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -25,6 +25,10 @@ import {
} from "@app/services/certificate-common/certificate-constants";
import { extractCertificateRequestFromCSR } from "@app/services/certificate-common/certificate-csr-utils";
import { mapEnumsForValidation } from "@app/services/certificate-common/certificate-utils";
+import {
+ ExternalMetadataSchema,
+ ImportExternalMetadataSchema
+} from "@app/services/certificate-common/external-metadata-schemas";
import { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types";
import { CertificateRequestStatus } from "@app/services/certificate-request/certificate-request-types";
import {
@@ -1375,6 +1379,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
.optional(),
caName: z.string().nullable().optional(),
caType: z.enum(["internal", "external"]).nullable().optional(),
+ externalMetadata: ExternalMetadataSchema.nullable().optional().describe(CERTIFICATES.GET.externalMetadata),
profileName: z.string().nullable().optional(),
applicationName: z.string().nullable().optional(),
hasPrivateKey: z.boolean().describe(CERTIFICATES.GET.hasPrivateKey),
@@ -1411,8 +1416,13 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
}
});
+ const parsedExternalMetadata = ExternalMetadataSchema.safeParse(cert.externalMetadata);
+
return {
- certificate: cert
+ certificate: {
+ ...cert,
+ externalMetadata: parsedExternalMetadata.success ? parsedExternalMetadata.data : null
+ }
};
}
});
@@ -1626,7 +1636,9 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
friendlyName: z.string().trim().max(255).optional().describe(CERTIFICATES.IMPORT.friendlyName),
pkiCollectionId: z.string().trim().optional().describe(CERTIFICATES.IMPORT.pkiCollectionId),
- applicationId: z.string().trim().uuid().optional()
+ applicationId: z.string().trim().uuid().optional(),
+ profileId: z.string().trim().uuid().optional().describe(CERTIFICATES.IMPORT.profileId),
+ externalMetadata: ImportExternalMetadataSchema.optional().describe(CERTIFICATES.IMPORT.externalMetadata)
}),
response: {
200: z.object({
@@ -1638,7 +1650,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
- const { certificate, certificateChain, privateKey, serialNumber, cert } =
+ const { certificate, certificateChain, privateKey, serialNumber, cert, profileName, caName } =
await server.services.certificate.importCert({
actor: req.permission.type,
actorId: req.permission.id,
@@ -1656,7 +1668,11 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
metadata: {
certId: cert.id,
cn: cert.commonName,
- serialNumber
+ serialNumber,
+ certificateProfileId: cert.profileId ?? undefined,
+ profileName: profileName ?? undefined,
+ caId: cert.caId ?? undefined,
+ caName: caName ?? undefined
}
}
});
diff --git a/backend/src/services/app-connection/digicert/digicert-connection-fns.ts b/backend/src/services/app-connection/digicert/digicert-connection-fns.ts
index 07f4e8e61a..a393e09cda 100644
--- a/backend/src/services/app-connection/digicert/digicert-connection-fns.ts
+++ b/backend/src/services/app-connection/digicert/digicert-connection-fns.ts
@@ -2,6 +2,7 @@ import { AxiosError } from "axios";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
@@ -149,6 +150,7 @@ export const getDigiCertOrgValidation = async (
};
type TDigiCertOrdersResponse = {
+ page?: { total?: number; limit?: number; offset?: number };
orders?: {
id: number;
status?: string;
@@ -165,6 +167,9 @@ export type TDigiCertOrder = {
validTill?: string;
};
+const DIGICERT_ORDERS_PAGE_SIZE = 1000;
+const DIGICERT_ORDERS_MAX_PAGES = 20;
+
export const listDigiCertOrders = async (
appConnection: TDigiCertConnection,
organizationId: number,
@@ -174,27 +179,48 @@ export const listDigiCertOrders = async (
const { apiKey } = appConnection.credentials;
const baseUrl = getDigiCertApiBaseUrl(appConnection.credentials);
+ const collected: TDigiCertOrder[] = [];
+
try {
- const { data } = await request.get<TDigiCertOrdersResponse>(`${baseUrl}/order/certificate`, {
- headers: {
- [DIGICERT_AUTH_HEADER]: apiKey,
- "Content-Type": "application/json"
- },
- params: {
- "filters[product_name_id]": productNameId,
- "filters[organization_id]": organizationId,
- "filters[status]": status,
- limit: 1000
+ for (let page = 0; page < DIGICERT_ORDERS_MAX_PAGES; page += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const { data } = await request.get<TDigiCertOrdersResponse>(`${baseUrl}/order/certificate`, {
+ headers: {
+ [DIGICERT_AUTH_HEADER]: apiKey,
+ "Content-Type": "application/json"
+ },
+ params: {
+ "filters[product_name_id]": productNameId,
+ "filters[organization_id]": organizationId,
+ "filters[status]": status,
+ limit: DIGICERT_ORDERS_PAGE_SIZE,
+ offset: page * DIGICERT_ORDERS_PAGE_SIZE
+ }
+ });
+
+ const orders = data.orders ?? [];
+ collected.push(
+ ...orders.map((order) => ({
+ orderId: order.id,
+ commonName: order.certificate?.common_name ?? "",
+ organizationName: order.organization?.name ?? "",
+ status: order.status ?? "",
+ validTill: order.certificate?.valid_till
+ }))
+ );
+
+ const total = data.page?.total;
+ const isComplete = total === undefined ? orders.length < DIGICERT_ORDERS_PAGE_SIZE : collected.length >= total;
+ if (isComplete) return collected;
+
+ if (page === DIGICERT_ORDERS_MAX_PAGES - 1) {
+ logger.warn(
+ `DigiCert order listing hit the page cap and is truncated [organizationId=${organizationId}] [productNameId=${productNameId}] [collected=${collected.length}] [total=${total ?? "unknown"}]`
+ );
}
- });
+ }
- return (data.orders ?? []).map((order) => ({
- orderId: order.id,
- commonName: order.certificate?.common_name ?? "",
- organizationName: order.organization?.name ?? "",
- status: order.status ?? "",
- validTill: order.certificate?.valid_till
- }));
+ return collected;
} catch (error: unknown) {
if (error instanceof AxiosError) {
throw new BadRequestError({
diff --git a/backend/src/services/app-connection/digicert/digicert-connection-service.ts b/backend/src/services/app-connection/digicert/digicert-connection-service.ts
index 37e6b7d8a1..e9289a6cb7 100644
--- a/backend/src/services/app-connection/digicert/digicert-connection-service.ts
+++ b/backend/src/services/app-connection/digicert/digicert-connection-service.ts
@@ -69,14 +69,8 @@ export const digicertConnectionService = (getAppConnection: TGetAppConnectionFun
productNameId: string,
actor: OrgServiceActor
) => {
- assertCodeSigningProduct(productNameId);
const appConnection = await getAppConnection(AppConnection.DigiCert, connectionId, actor);
- try {
- return await listDigiCertOrders(appConnection, organizationId, productNameId);
- } catch (error) {
- logger.error(error, `Failed to list DigiCert orders [connectionId=${connectionId}]`);
- return [];
- }
+ return listDigiCertOrders(appConnection, organizationId, productNameId);
};
return {
diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.ts
index 2eea7bf0e9..2cdca63d6d 100644
--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.ts
@@ -630,6 +630,57 @@ export const DigiCertCertificateAuthorityFns = ({
return { status: DigiCertPollOutcome.Pending, orderStatus };
};
+ const assertOrderMatchesCertificate = async ({
+ caId,
+ orderId,
+ serialNumber
+ }: {
+ caId: string;
+ orderId: number;
+ serialNumber: string;
+ }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca.externalCa || ca.externalCa.type !== CaType.DIGICERT) {
+ throw new BadRequestError({ message: `CA is not a DigiCert certificate authority [caId=${caId}]` });
+ }
+
+ const digicertCa = castDbEntryToDigiCertCertificateAuthority(ca);
+ const { apiKey, baseUrl } = await getDigiCertClientCredentials(
+ digicertCa.configuration.appConnectionId,
+ appConnectionDAL,
+ kmsService
+ );
+ const client = createDigiCertApiClient(apiKey, baseUrl);
+
+ const order = await client.getOrder(orderId);
+
+ if (
+ order.organization?.id !== digicertCa.configuration.organizationId ||
+ order.product?.name_id !== digicertCa.configuration.productNameId
+ ) {
+ throw new BadRequestError({
+ message: `DigiCert order ${orderId} belongs to a different DigiCert organization or product than this certificate authority.`
+ });
+ }
+
+ const digicertCertificateId = order.certificate?.id;
+ if (!digicertCertificateId) {
+ throw new BadRequestError({
+ message: `DigiCert order ${orderId} has no issued certificate yet, so it cannot be linked.`
+ });
+ }
+
+ const pem = await client.downloadCertificatePem(digicertCertificateId);
+ const { leaf } = extractLeafAndChain(pem);
+ const orderSerialNumber = new x509.X509Certificate(leaf).serialNumber;
+
+ if (orderSerialNumber.toLowerCase() !== serialNumber.toLowerCase()) {
+ throw new BadRequestError({
+ message: `DigiCert order ${orderId} was issued for a different certificate than the one being imported. Check the order number in DigiCert CertCentral.`
+ });
+ }
+ };
+
const revokeCertificate = async ({
caId,
serialNumber,
@@ -692,6 +743,7 @@ export const DigiCertCertificateAuthorityFns = ({
fetchAndAttachIssuedCertificate,
pollOrderForCertificate,
revokeCertificate,
+ assertOrderMatchesCertificate,
orderCodeSigningCertificate: codeSigningFns.orderCodeSigningCertificate,
reissueCodeSigningCertificate: codeSigningFns.reissueCodeSigningCertificate,
findCodeSigningOrderByReference: codeSigningFns.findCodeSigningOrderByReference,
diff --git a/backend/src/services/certificate-common/external-metadata-schemas.ts b/backend/src/services/certificate-common/external-metadata-schemas.ts
index e2df657ef0..10883b0c7c 100644
--- a/backend/src/services/certificate-common/external-metadata-schemas.ts
+++ b/backend/src/services/certificate-common/external-metadata-schemas.ts
@@ -34,3 +34,26 @@ 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>;
+
+export const CA_TYPE_LABEL: Record<CaType, string> = {
+ [CaType.INTERNAL]: "Internal CA",
+ [CaType.ACME]: "ACME",
+ [CaType.ADCS]: "Microsoft ADCS",
+ [CaType.AZURE_AD_CS]: "Azure ADCS",
+ [CaType.AWS_PCA]: "AWS Private CA",
+ [CaType.AWS_ACM_PUBLIC_CA]: "AWS ACM Public CA",
+ [CaType.DIGICERT]: "DigiCert CertCentral",
+ [CaType.VENAFI_TPP]: "Venafi TPP",
+ [CaType.GODADDY]: "GoDaddy"
+};
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.ts
index d51f32116c..958d38a1c3 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts
@@ -1526,11 +1526,9 @@ export const certificateProfileServiceFactory = ({
const certObj = new x509.X509Certificate(decryptedCert);
const certificate = certObj.toString("pem");
- const decryptedCertChain = await kmsDecryptor({
- cipherTextBlob: certBody.encryptedCertificateChain!
- });
-
- const certificateChain = decryptedCertChain.toString();
+ const certificateChain = certBody.encryptedCertificateChain
+ ? (await kmsDecryptor({ cipherTextBlob: certBody.encryptedCertificateChain })).toString()
+ : "";
let privateKey = null;
try {
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index 393be02e12..ce28ad2742 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -8,12 +8,14 @@ import { TLicenseServiceFactory } from "@app/ee/services/license/license-service
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ProjectPermissionCertificateActions,
+ ProjectPermissionCertificateProfileActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import {
ResourcePermissionCertificateActions,
ResourcePermissionSub
} from "@app/ee/services/permission/resource-permission";
+import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
@@ -25,6 +27,14 @@ import { CaCapability, CaType } from "@app/services/certificate-authority/certif
import { caSupportsCapability } from "@app/services/certificate-authority/certificate-authority-maps";
import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";
import { TCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service";
+import { DigiCertCertificateAuthorityFns } from "@app/services/certificate-authority/digicert/digicert-certificate-authority-fns";
+import {
+ CA_TYPE_LABEL,
+ CertificateImportLinkageMap,
+ TImportExternalMetadata
+} from "@app/services/certificate-common/external-metadata-schemas";
+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";
import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -33,6 +43,7 @@ import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage
import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
+import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
import { TPkiCollectionDALFactory } from "@app/services/pki-collection/pki-collection-dal";
import { TPkiCollectionItemDALFactory } from "@app/services/pki-collection/pki-collection-item-dal";
import { TPkiSyncDALFactory } from "@app/services/pki-sync/pki-sync-dal";
@@ -42,7 +53,12 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
-import { expandInternalCa, getCaCertChain, rebuildCaCrl } from "../certificate-authority/certificate-authority-fns";
+import {
+ expandInternalCa,
+ getCaCertChain,
+ getCaCertChains,
+ rebuildCaCrl
+} from "../certificate-authority/certificate-authority-fns";
import { validatePqcLicense } from "../certificate-common/certificate-utils";
import {
CertificateThumbprintAlgorithm,
@@ -91,10 +107,13 @@ type TCertificateServiceFactoryDep = {
| "updateById"
>;
pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
+ certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;
+ pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;
+ digicertFns: Pick<ReturnType<typeof DigiCertCertificateAuthorityFns>, "assertOrderMatchesCertificate">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne" | "create">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
- certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;
+ certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById" | "find">;
certificateAuthorityCrlDAL: Pick<TCertificateAuthorityCrlDALFactory, "update">;
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
pkiCollectionDAL: Pick<TPkiCollectionDALFactory, "findById">;
@@ -135,6 +154,9 @@ export const certificateServiceFactory = ({
resourceMetadataDAL,
pkiAlertV2Queue,
pkiApplicationDAL,
+ certificateProfileDAL,
+ pkiApplicationProfileDAL,
+ digicertFns,
licenseService,
usageMeteringService,
hsmConnectorService
@@ -474,6 +496,32 @@ export const certificateServiceFactory = ({
* 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,
+ certificateAuthorityDAL,
+ certificateAuthorityCertDAL,
+ projectDAL,
+ kmsService
+ });
+
+ const leaf = new x509.X509Certificate(certificatePem);
+ const verifications = await Promise.all(
+ caCerts.map((caCert) =>
+ leaf
+ .verify({ publicKey: new x509.X509Certificate(caCert.certificate).publicKey, signatureOnly: true })
+ .catch(() => false)
+ )
+ );
+
+ if (!verifications.some(Boolean)) {
+ throw new BadRequestError({
+ message:
+ "This certificate was not issued by the certificate authority behind its profile, so revoking it here would have no effect. Revocation only takes effect through the authority that issued the certificate. Revoke it with its original issuer instead."
+ });
+ }
+ };
+
const revokeCert = async ({
id,
serialNumber,
@@ -574,6 +622,19 @@ export const certificateServiceFactory = ({
if (cert.status === CertStatus.REVOKED) throw new Error("Certificate already revoked");
+ if (ca.internalCa && cert.profileId && cert.source === CertificateSource.Imported) {
+ const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
+ if (!certBody) {
+ throw new NotFoundError({ message: "Certificate body not found" });
+ }
+
+ const kmsDecryptor = await kmsService.decryptWithKmsKey({
+ kmsId: await getProjectKmsCertificateKeyId({ projectId: ca.projectId, projectDAL, kmsService })
+ });
+ const decryptedCert = await kmsDecryptor({ cipherTextBlob: certBody.encryptedCertificate });
+ await $assertInternalCaIssuedCertificate(ca.id, new x509.X509Certificate(decryptedCert).toString("pem"));
+ }
+
if (ca.internalCa) {
await validatePqcLicense({
keyAlgorithm: ca.internalCa.keyAlgorithm,
@@ -759,6 +820,122 @@ export const certificateServiceFactory = ({
/**
* Import certificate
*/
+ const $resolveImportLinkage = async ({
+ profileId,
+ projectId,
+ applicationId,
+ externalMetadata,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: {
+ profileId: string;
+ projectId: string;
+ applicationId?: string;
+ externalMetadata?: TImportExternalMetadata;
+ actor: TImportCertDTO["actor"];
+ actorId: string;
+ actorAuthMethod: TImportCertDTO["actorAuthMethod"];
+ actorOrgId: string;
+ }) => {
+ const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
+ if (!profile || profile.projectId !== projectId) {
+ throw new NotFoundError({ message: `Certificate profile with ID '${profileId}' not found` });
+ }
+
+ if (applicationId) {
+ const attachment = await pkiApplicationProfileDAL.findOneByApplicationAndProfile(applicationId, profileId);
+ if (!attachment) {
+ throw new BadRequestError({
+ message: `Certificate profile '${profile.slug}' is not attached to this Application.`
+ });
+ }
+
+ const { permission } = await permissionService.getResourcePermission({
+ actor,
+ actorId,
+ projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: applicationId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateProfileActions.IssueCert,
+ ProjectPermissionSub.CertificateProfiles
+ );
+ } else {
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateProfileActions.IssueCert,
+ subject(ProjectPermissionSub.CertificateProfiles, { slug: profile.slug })
+ );
+ }
+
+ if (!profile.caId) {
+ if (profile.issuerType !== IssuerType.SELF_SIGNED) {
+ throw new BadRequestError({
+ message: `Certificate profile '${profile.slug}' is not backed by a certificate authority, so it cannot manage an imported certificate.`
+ });
+ }
+
+ if (externalMetadata) {
+ throw new BadRequestError({
+ message: `Certificate profile '${profile.slug}' is self-signed, so it needs no identifier from an external provider. Remove 'externalMetadata' from the request.`
+ });
+ }
+
+ return { caId: null, caType: null, externalMetadata: undefined, profileName: profile.slug, caName: null };
+ }
+
+ const caType = (profile.certificateAuthority?.externalType as CaType) ?? CaType.INTERNAL;
+ const caName = profile.certificateAuthority?.name ?? null;
+ const linkage = CertificateImportLinkageMap[caType];
+ if (!linkage) {
+ throw new BadRequestError({
+ message: `Linking an imported certificate to a ${CA_TYPE_LABEL[caType] ?? caType} certificate authority is not supported yet.`
+ });
+ }
+
+ if (!linkage.externalMetadataSchema) {
+ if (externalMetadata) {
+ throw new BadRequestError({
+ message: `Certificate profile '${profile.slug}' issues from ${CA_TYPE_LABEL[caType] ?? caType}, which needs no identifier from an external provider. Remove 'externalMetadata' from the request.`
+ });
+ }
+ return { caId: profile.caId, caType, externalMetadata: undefined, profileName: profile.slug, caName };
+ }
+
+ if (!externalMetadata) {
+ throw new BadRequestError({
+ message: `Certificate profile '${profile.slug}' issues from ${CA_TYPE_LABEL[caType] ?? caType}. Supply this certificate's ${linkage.referenceLabel ?? "provider identifier"} in 'externalMetadata' so Infisical can renew and revoke it.`
+ });
+ }
+
+ const parsed = linkage.externalMetadataSchema.safeParse(externalMetadata);
+ if (!parsed.success) {
+ throw new BadRequestError({
+ message: `'externalMetadata' is not a valid ${linkage.referenceLabel ?? "provider identifier"}.`
+ });
+ }
+
+ return {
+ caId: profile.caId,
+ caType,
+ externalMetadata: parsed.data as TImportExternalMetadata,
+ profileName: profile.slug,
+ caName
+ };
+ };
+
const importCert = async ({
projectId: projectIdInput,
projectSlug,
@@ -771,7 +948,9 @@ export const certificateServiceFactory = ({
friendlyName,
certificatePem,
chainPem,
- privateKeyPem
+ privateKeyPem,
+ profileId,
+ externalMetadata
}: TImportCertDTO) => {
const collectionId = pkiCollectionId;
@@ -829,6 +1008,25 @@ export const certificateServiceFactory = ({
if (pkiCollection.projectId !== projectId) throw new BadRequestError({ message: "Invalid PKI collection" });
}
+ const linkage = profileId
+ ? await $resolveImportLinkage({
+ profileId,
+ projectId,
+ applicationId,
+ externalMetadata,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ })
+ : null;
+
+ if (!profileId && externalMetadata) {
+ throw new BadRequestError({
+ message: "'externalMetadata' can only be set when the certificate is imported into a certificate profile."
+ });
+ }
+
const leafCert = new x509.X509Certificate(certificatePem);
// Verify the certificate chain when one is provided
@@ -905,6 +1103,14 @@ 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
+ });
+ }
+
// Encrypt certificate for storage
const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
projectId,
@@ -962,6 +1168,10 @@ export const certificateServiceFactory = ({
notAfter,
projectId,
applicationId: applicationId ?? null,
+ profileId: profileId ?? null,
+ caId: linkage?.caId ?? null,
+ externalMetadata: linkage?.externalMetadata ?? null,
+ source: CertificateSource.Imported,
keyUsages,
extendedKeyUsages,
...parsedFields,
@@ -1019,7 +1229,9 @@ export const certificateServiceFactory = ({
certificateChain: chainPem,
privateKey: privateKeyPem,
serialNumber,
- cert
+ cert,
+ profileName: linkage?.profileName ?? null,
+ caName: linkage?.caName ?? null
};
};
diff --git a/backend/src/services/certificate/certificate-types.ts b/backend/src/services/certificate/certificate-types.ts
index 321ae1a8e1..a44aa7e983 100644
--- a/backend/src/services/certificate/certificate-types.ts
+++ b/backend/src/services/certificate/certificate-types.ts
@@ -6,6 +6,7 @@ import {
CertSubjectAlternativeNameType,
TAltNameType
} from "@app/services/certificate-common/certificate-constants";
+import { TImportExternalMetadata } from "@app/services/certificate-common/external-metadata-schemas";
import { TKmsServiceFactory } from "../kms/kms-service";
import { TProjectDALFactory } from "../project/project-dal";
@@ -151,6 +152,9 @@ export type TImportCertDTO = {
certificatePem: string;
privateKeyPem?: string;
chainPem?: string;
+
+ profileId?: string;
+ externalMetadata?: TImportExternalMetadata;
} & Omit<TProjectPermission, "projectId">;
export type TGetCertPrivateKeyDTO = {
diff --git a/docs/documentation/platform/pki/applications/certificates.mdx b/docs/documentation/platform/pki/applications/certificates.mdx
index 8bd42ab502..3969856136 100644
--- a/docs/documentation/platform/pki/applications/certificates.mdx
+++ b/docs/documentation/platform/pki/applications/certificates.mdx
@@ -56,10 +56,42 @@ For automated issuance, configure an [enrollment method](/documentation/platform
## Importing certificates
-Click **Import** on the Certificates tab to bring in a certificate you already hold, either as PEM files or as a `.p12` / `.pfx` keystore with its password.
+Select **Import** on the Certificates tab to bring in a certificate you already hold, either as PEM files or as a `.p12` / `.pfx` keystore with its password.
A keystore can hold several certificates. Infisical lists what is inside so you can pick which ones to import.
+### Managing an imported certificate
+
+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.
+
+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.
+</Note>
+
+### Which profile to attach
+
+Attaching a profile backed by the authority that issued the certificate keeps the whole lifecycle in Infisical.
+
+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.
+
+### What each external CA needs
+
+A profile backed by an external certificate authority needs the identifier the certificate already has at that provider, so Infisical can act on it there.
+
+<Tabs>
+ <Tab title="DigiCert">
+ The CertCentral **order ID**. Infisical lists the orders under the authority's DigiCert organization and product, so you can search for the right one instead of typing a number.
+
+ Renewal places a renewal order against it, and revocation revokes it in CertCentral. Infisical checks the order before saving it and rejects one that was issued for a different certificate.
+ </Tab>
+</Tabs>
+
## Renewal
| Type | How It Works |
diff --git a/docs/documentation/platform/pki/ca/digicert.mdx b/docs/documentation/platform/pki/ca/digicert.mdx
index e61282a5aa..4881594556 100644
--- a/docs/documentation/platform/pki/ca/digicert.mdx
+++ b/docs/documentation/platform/pki/ca/digicert.mdx
@@ -59,4 +59,7 @@ Now that your DigiCert CA is configured, set up the infrastructure to issue cert
<Card title="Quick Start" icon="rocket" href="/documentation/platform/pki/quick-starts/issue-first-certificate">
Issue your first certificate end-to-end.
</Card>
+ <Card title="Import existing certificates" icon="file-import" href="/documentation/platform/pki/applications/certificates#importing-certificates">
+ Bring certificates you already hold in CertCentral under Infisical management.
+ </Card>
</CardGroup>
diff --git a/frontend/src/components/v3/generic/ReactSelect/index.ts b/frontend/src/components/v3/generic/ReactSelect/index.ts
index 95a04676fe..9e7cf986ff 100644
--- a/frontend/src/components/v3/generic/ReactSelect/index.ts
+++ b/frontend/src/components/v3/generic/ReactSelect/index.ts
@@ -1,2 +1,3 @@
+export { Option as ReactSelectOption } from "./components";
export { CreatableSelect } from "./CreatableSelect";
export { FilterableSelect } from "./FilterableSelect";
diff --git a/frontend/src/hooks/api/certificates/mutations.tsx b/frontend/src/hooks/api/certificates/mutations.tsx
index 0487ebecf8..a130efb4d9 100644
--- a/frontend/src/hooks/api/certificates/mutations.tsx
+++ b/frontend/src/hooks/api/certificates/mutations.tsx
@@ -104,6 +104,9 @@ export const useImportCertificate = () => {
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 5b43b5e8b5..b0a046f56c 100644
--- a/frontend/src/hooks/api/certificates/types.ts
+++ b/frontend/src/hooks/api/certificates/types.ts
@@ -1,4 +1,5 @@
import type { TPkcs12Entry } from "@app/helpers/pkcs12";
+import { CaType } from "@app/hooks/api/ca/enums";
import {
CertExtendedKeyUsage,
@@ -60,6 +61,7 @@ export type TCertificate = {
profileName?: string | null;
enrollmentType?: string | null;
caType?: CertificateIssuerKind | null;
+ externalMetadata?: TCertificateExternalMetadata | null;
applicationId?: string | null;
applicationName?: string | null;
source?: TCertificateSource;
@@ -94,6 +96,11 @@ export type TImportPkcs12EntriesResult = {
error?: string;
};
+export type TCertificateExternalMetadata =
+ | { type: CaType.DIGICERT; orderId: number }
+ | { type: CaType.GODADDY; certificateId: string }
+ | { type: CaType.AWS_ACM_PUBLIC_CA; arn: string; region: string; validationMethod: string };
+
export type TImportCertificateDTO = {
certificatePem: string;
privateKeyPem?: string;
@@ -102,6 +109,8 @@ export type TImportCertificateDTO = {
pkiCollectionId?: string;
friendlyName?: string;
applicationId?: string;
+ profileId?: string;
+ externalMetadata?: TCertificateExternalMetadata;
};
export type TImportCertificateResponse = {
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
index deb529e852..7f356b6eff 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
@@ -202,7 +202,8 @@ const Page = () => {
// CA capability check for revocation
const caType = caData?.find((ca) => ca.id === certificate?.caId)?.type;
const supportsRevocation =
- !caType || caSupportsCapability(caType, CaCapability.REVOKE_CERTIFICATES);
+ Boolean(certificate?.caId) &&
+ (!caType || caSupportsCapability(caType, CaCapability.REVOKE_CERTIFICATES));
const handleDisableAutoRenewal = async () => {
if (!certificate) return;
@@ -451,7 +452,6 @@ const Page = () => {
)}
{supportsRevocation &&
!isRevoked &&
- certificate.source === CertSource.Issued &&
!(isInventoryView && certificate.applicationId) && (
<DropdownMenuItem
isDisabled={!canDeleteCertificate}
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx
index 7fb09e0c6c..a7547984ac 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx
@@ -19,6 +19,8 @@ import {
DetailValue
} from "@app/components/v3";
import { CertSource, CertStatus, useGetCertificateById } from "@app/hooks/api";
+import { CaType } from "@app/hooks/api/ca/enums";
+import { TCertificateExternalMetadata } from "@app/hooks/api/certificates/types";
import {
getCertificateDisplayStatus,
@@ -40,6 +42,25 @@ const formatDateLocal = (dateString: string) => {
return format(new Date(dateString), "EEE, dd MMM yyyy HH:mm:ss");
};
+const getProviderReference = (metadata?: TCertificateExternalMetadata | null) => {
+ if (!metadata) return null;
+
+ switch (metadata.type) {
+ case CaType.DIGICERT:
+ return {
+ provider: "DigiCert CertCentral",
+ label: "Order ID",
+ value: String(metadata.orderId)
+ };
+ case CaType.GODADDY:
+ return { provider: "GoDaddy", label: "Certificate ID", value: metadata.certificateId };
+ case CaType.AWS_ACM_PUBLIC_CA:
+ return { provider: "AWS ACM Public CA", label: "Certificate ARN", value: metadata.arn };
+ default:
+ return null;
+ }
+};
+
export const CertificateOverviewSection = ({ certificateId }: Props) => {
const { orgId, projectId } = useParams({
from: "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificates/$certificateId"
@@ -69,6 +90,7 @@ export const CertificateOverviewSection = ({ certificateId }: Props) => {
const displayStatus = getCertificateDisplayStatus(certificate);
const showCaLink = certificate.caId && certificate.caName && certificate.caType === "internal";
+ const providerReference = getProviderReference(certificate.externalMetadata);
return (
<div className="flex w-full flex-col gap-5 lg:max-w-[24rem]">
@@ -204,6 +226,18 @@ export const CertificateOverviewSection = ({ certificateId }: Props) => {
{certificate.profileName || <span className="text-muted">—</span>}
</DetailValue>
</Detail>
+ {providerReference && (
+ <>
+ <Detail>
+ <DetailLabel>Provider</DetailLabel>
+ <DetailValue>{providerReference.provider}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>{providerReference.label}</DetailLabel>
+ <DetailValue className="font-mono">{providerReference.value}</DetailValue>
+ </Detail>
+ </>
+ )}
<Detail>
<DetailLabel>Source</DetailLabel>
<DetailValue>
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
index bc3c861438..5e9688cf0a 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
@@ -2,7 +2,6 @@ import { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { CircleCheck, CircleX, TriangleAlert } from "lucide-react";
-import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import {
@@ -45,17 +44,14 @@ import type { TPkcs12Entry } from "@app/helpers/pkcs12";
import { useGetCert, useImportCertificate, useImportPkcs12Entries } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
+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 schema = z.object({
- certificatePem: z.string().trim().min(1, "Certificate PEM is required"),
- privateKeyPem: z.string().trim().optional(),
- chainPem: z.string().trim().optional()
-});
-
-export type FormData = z.infer<typeof schema>;
+export type FormData = CertificateImportFormData;
type Props = {
popUp: UsePopUpState<["certificateImport"]>;
@@ -103,12 +99,21 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
control,
handleSubmit,
reset,
+ setValue,
formState: { isSubmitting }
} = useForm<FormData>({
- resolver: zodResolver(schema)
+ resolver: zodResolver(certificateImportSchema)
});
- const clearFields = () => reset({ certificatePem: "", chainPem: "", privateKeyPem: "" });
+ const clearFields = () =>
+ reset({
+ certificatePem: "",
+ chainPem: "",
+ privateKeyPem: "",
+ profileId: undefined,
+ linkedCaType: undefined,
+ providerReference: ""
+ });
const resetAll = () => {
clearFields();
@@ -122,13 +127,26 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
setFormat("pem");
};
- const onFormSubmit = async ({ certificatePem, privateKeyPem, chainPem }: FormData) => {
+ 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
});
@@ -253,6 +271,13 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
</Field>
)}
/>
+ {applicationId && !pemFieldsDisabled && (
+ <CertificateImportProfileFields
+ control={control}
+ setValue={setValue}
+ applicationId={applicationId}
+ />
+ )}
</FieldGroup>
);
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportProfileFields.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportProfileFields.tsx
new file mode 100644
index 0000000000..43ed05db1f
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportProfileFields.tsx
@@ -0,0 +1,192 @@
+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 { getCertificateImportReference, isCaTypeLinkable } from "./certificate-import-linkage";
+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,
+ includeConfigs: true,
+ 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 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);
+
+ 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>
+ <FilterableSelect<ProfileOption>
+ isLoading={isProfilesLoading}
+ isClearable
+ 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."}
+ />
+ {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>
+ {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}
+ />
+ )}
+ <FieldDescription>{reference.description}</FieldDescription>
+ {error && <FieldError>{error.message}</FieldError>}
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-linkage.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-linkage.ts
new file mode 100644
index 0000000000..1c8f902551
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-linkage.ts
@@ -0,0 +1,38 @@
+import { CaType } from "@app/hooks/api/ca/enums";
+import { TCertificateExternalMetadata } from "@app/hooks/api/certificates/types";
+
+export type CertificateImportReference = {
+ label: string;
+ placeholder: string;
+ description: string;
+ invalidMessage: string;
+ hasLiveOptions?: boolean;
+ optionsPlaceholder?: string;
+ parse: (reference: string) => TCertificateExternalMetadata | null;
+};
+
+export const CERTIFICATE_IMPORT_LINKAGE: Partial<
+ Record<CaType, { reference: CertificateImportReference | null }>
+> = {
+ [CaType.INTERNAL]: { reference: null },
+ [CaType.DIGICERT]: {
+ reference: {
+ label: "Order ID",
+ placeholder: "e.g. 2081714",
+ description: "Found under Orders in DigiCert CertCentral.",
+ invalidMessage: "Enter the DigiCert order ID for this certificate, for example 2081714",
+ hasLiveOptions: true,
+ optionsPlaceholder: "Select an order...",
+ parse: (reference) => {
+ const orderId = Number(reference);
+ return Number.isInteger(orderId) && orderId > 0 ? { type: CaType.DIGICERT, orderId } : null;
+ }
+ }
+ }
+};
+
+export const isCaTypeLinkable = (caType?: CaType | null) =>
+ Boolean(caType && CERTIFICATE_IMPORT_LINKAGE[caType]);
+
+export const getCertificateImportReference = (caType?: CaType | null) =>
+ (caType && CERTIFICATE_IMPORT_LINKAGE[caType]?.reference) || null;
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/types.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/types.ts
new file mode 100644
index 0000000000..b606632c07
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/types.ts
@@ -0,0 +1,29 @@
+import { z } from "zod";
+
+import { CaType } from "@app/hooks/api/ca/enums";
+
+import { getCertificateImportReference } from "./certificate-import-linkage";
+
+export const certificateImportSchema = z
+ .object({
+ certificatePem: z.string().trim().min(1, "Certificate PEM is required"),
+ privateKeyPem: z.string().trim().optional(),
+ chainPem: z.string().trim().optional(),
+ profileId: z.string().uuid().optional(),
+ linkedCaType: z.nativeEnum(CaType).optional(),
+ providerReference: z.string().trim().optional()
+ })
+ .superRefine((data, ctx) => {
+ const reference = getCertificateImportReference(data.linkedCaType);
+ if (!reference) return;
+
+ if (!data.providerReference || !reference.parse(data.providerReference)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["providerReference"],
+ message: reference.invalidMessage
+ });
+ }
+ });
+
+export type CertificateImportFormData = z.infer<typeof certificateImportSchema>;