Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
/* eslint-disable no-await-in-loop */
import { ForbiddenError, subject } from "@casl/ability";
import * as x509 from "@peculiar/x509";
import { ActionProjectType, ProjectMembershipRole, ResourceType } from "@app/db/schemas";
import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";
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 { TKeyStoreFactory } from "@app/keystore/keystore";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { Pkcs12PasswordSchema } from "@app/lib/validator/password-policy";
import { ActorType } from "@app/services/auth/auth-type";
import type { TCaKeySourceServiceFactory } from "@app/services/certificate-authority/ca-key-source/ca-key-source-service";
import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";
import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
import { CaCapability, CaType } from "@app/services/certificate-authority/certificate-authority-enums";
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 {
assertCertificateQuotaForProject,
recordNewCertificateQuotaKey
} from "@app/services/certificate-common/certificate-quota-fns";
import {
CA_TYPE_LABEL,
CertificateImportLinkageMap,
TDigiCertExternalMetadata,
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 { TCertificateRequestDALFactory } from "@app/services/certificate-request/certificate-request-dal";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
import {
CertificateApplicationAlertEvent,
TCertificateAlertEventEmitter
} from "@app/services/certificate/certificate-alert-events";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { ActiveCerts, WildcardCerts } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
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";
import { TPkiSyncQueueFactory } from "@app/services/pki-sync/pki-sync-queue";
import {
queueCertificateFilterReconcile,
triggerAutoSyncForCertificate,
triggerSyncsForDeletedCertificate
} from "@app/services/pki-sync/pki-sync-utils";
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 { TSignerDALFactory } from "@app/services/signer/signer-dal";
import { TUserDALFactory } from "@app/services/user/user-dal";
import {
expandInternalCa,
getCaCertChain,
getCaCertChains,
rebuildCaCrl
} from "../certificate-authority/certificate-authority-fns";
import { TInternalCertificateAuthorityDALFactory } from "../certificate-authority/internal/internal-certificate-authority-dal";
import { parseImportedCustomExtensions } from "../certificate-common/certificate-extension-fns";
import {
calculateFinalRenewBeforeDays,
detectSanType,
resolveEffectiveApiConfig
} from "../certificate-common/certificate-issuance-utils";
import { assertCanRevokeCertificate } from "../certificate-common/certificate-permission-fns";
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 {
assertCertificateMaterialAvailable,
assertCertificateNotDeleted,
CertificateThumbprintAlgorithm,
extractCertificateAlgorithms,
extractCertificateFields,
generatePkcs12FromCertificate,
getCertificateCredentials,
getCertificateDisplayName,
normalizePemText,
normalizeThumbprint,
parseCertificateBody,
parsePemCertificateChain,
resolveCertificateStatus,
revocationReasonToCrlCode,
softDeleteCertificates
} from "./certificate-fns";
import { TCertificateSecretDALFactory } from "./certificate-secret-dal";
import {
CertExtendedKeyUsage,
CertExtendedKeyUsageOIDToName,
CertKeyUsage,
CertStatus,
TAssignCertToApplicationDTO,
TCertificateBasicConstraints,
TCertificateFingerprints,
TCertificateSubject,
TDeleteCertDTO,
TGetCertBodyDTO,
TGetCertBundleDTO,
TGetCertDTO,
TGetCertPkcs12DTO,
TGetCertPrivateKeyDTO,
TImportCertDTO,
TRevokeCertDTO
} from "./certificate-types";
type TCertificateServiceFactoryDep = {
certificateDAL: Pick<
TCertificateDALFactory,
| "findOne"
| "update"
| "find"
| "findByThumbprintInOrg"
| "transaction"
| "create"
| "findById"
| "findWithFullDetails"
| "findLatestRenewalOf"
| "updateById"
| "findByIdForUpdate"
>;
pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;
pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;
apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;
digicertFns: Pick<ReturnType<typeof DigiCertCertificateAuthorityFns>, "assertOrderMatchesCertificate">;
certificatePolicyService: Pick<TCertificatePolicyServiceFactory, "validateCertificateRequest">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create" | "delete">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne" | "create" | "delete">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById" | "find">;
certificateAuthorityCrlDAL: Pick<TCertificateAuthorityCrlDALFactory, "update">;
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
pkiCollectionDAL: Pick<TPkiCollectionDALFactory, "findById">;
pkiCollectionItemDAL: Pick<TPkiCollectionItemDALFactory, "create" | "delete">;
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "findById" | "transaction" | "findProjectBySlug">;
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findPkiSyncIdsByCertificateId" | "find">;
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "update">;
signerDAL: Pick<TSignerDALFactory, "findOne">;
userDAL: Pick<TUserDALFactory, "findById">;
identityDAL: Pick<TIdentityDALFactory, "findById">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
certificateAuthorityService: Pick<TCertificateAuthorityServiceFactory, "revokeCertificate">;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find">;
pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;
licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;
usageCounterDAL: Pick<
TUsageCounterDALFactory,
"countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"
>;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
caKeySourceService: Pick<TCaKeySourceServiceFactory, "buildSigner">;
internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "update">;
};
export type TCertificateServiceFactory = ReturnType<typeof certificateServiceFactory>;
export const certificateServiceFactory = ({
certificateDAL,
certificateSecretDAL,
certificateBodyDAL,
certificateAuthorityDAL,
certificateAuthorityCertDAL,
certificateAuthorityCrlDAL,
certificateAuthoritySecretDAL,
pkiCollectionDAL,
pkiCollectionItemDAL,
projectDAL,
kmsService,
permissionService,
certificateSyncDAL,
certificateRequestDAL,
auditLogService,
pkiSyncDAL,
pkiSyncQueue,
certificateAuthorityService,
resourceMetadataDAL,
pkiAlertV2Queue,
certificateAlertEventEmitter,
pkiApplicationDAL,
certificateProfileDAL,
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL,
digicertFns,
certificatePolicyService,
licenseService,
usageCounterDAL,
keyStore,
usageMeteringService,
caKeySourceService,
internalCertificateAuthorityDAL,
signerDAL,
userDAL,
identityDAL
}: TCertificateServiceFactoryDep) => {
const $canActOnCertViaApplication = async (
cert: { applicationId?: string | null; projectId: string },
action: ResourcePermissionCertificateActions,
actor: {
type: Parameters<TPermissionServiceFactory["getResourcePermission"]>[0]["actor"];
id: string;
authMethod: Parameters<TPermissionServiceFactory["getResourcePermission"]>[0]["actorAuthMethod"];
orgId: string;
}
): Promise<boolean> => {
if (!cert.applicationId) return false;
const { permission } = await permissionService.getResourcePermission({
actor: actor.type,
actorId: actor.id,
projectId: cert.projectId,
resourceType: ResourceType.CertificateApplication,
resourceId: cert.applicationId,
actorAuthMethod: actor.authMethod,
actorOrgId: actor.orgId
});
return permission.can(action, ResourcePermissionSub.Certificates);
};
/**
* Return details for certificate with serial number [serialNumber]
*/
const $resolveApplicationName = async (applicationId?: string | null) => {
if (!applicationId) return null;
const application = await pkiApplicationDAL.findById(applicationId);
return application?.name ?? null;
};
const $resolveDeletedByActorName = async (cert: {
deletedByActorType?: string | null;
deletedByActorId?: string | null;
}) => {
if (!cert.deletedByActorId) return null;
if (cert.deletedByActorType === ActorType.USER) {
const user = await userDAL.findById(cert.deletedByActorId);
if (!user) return null;
return [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email || user.username;
}
if (cert.deletedByActorType === ActorType.IDENTITY) {
const identity = await identityDAL.findById(cert.deletedByActorId);
return identity?.name ?? null;
}
return null;
};
const $parseStoredCertificateBody = async (cert: { id: string; projectId: string }) => {
const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
if (!certBody?.encryptedCertificate) return undefined;
const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
projectId: cert.projectId,
projectDAL,
kmsService
});
const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: certificateManagerKeyId });
const decryptedCert = await kmsDecryptor({ cipherTextBlob: certBody.encryptedCertificate });
return parseCertificateBody(decryptedCert);
};
const getCert = async ({
id,
serialNumber,
includeDeleted = false,
actorId,
actorAuthMethod,
actor,
actorOrgId
}: TGetCertDTO) => {
// Validation: require either id or serialNumber
if (!id && !serialNumber) {
throw new BadRequestError({ message: "Either id or serialNumber must be provided" });
}
// Unified lookup - consistent response for both id and serialNumber
const certWithDetails = await certificateDAL.findWithFullDetails(id ? { id } : { serialNumber: serialNumber! });
if (!certWithDetails) {
throw new NotFoundError({ message: "Certificate not found" });
}
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
projectId: certWithDetails.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
});
const metadataRows = await resourceMetadataDAL.find({ certificateId: certWithDetails.id });
const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
const readSubject = subject(ProjectPermissionSub.Certificates, {
commonName: certWithDetails.commonName,
altNames: certWithDetails.altNames?.split(",").map((s) => s.trim()),
serialNumber: certWithDetails.serialNumber,
metadata: certMetadata
});
if (!permission.can(ProjectPermissionCertificateActions.Read, readSubject)) {
const allowedByApplication = await $canActOnCertViaApplication(
certWithDetails,
ResourcePermissionCertificateActions.Read,
{ type: actor, id: actorId, authMethod: actorAuthMethod, orgId: actorOrgId }
);
if (!allowedByApplication) {
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.Read, readSubject);
}
}
if (certWithDetails.deletedAt && !includeDeleted) {
throw new NotFoundError({
message: `Certificate '${getCertificateDisplayName(certWithDetails)}' was deleted on ${new Date(certWithDetails.deletedAt).toISOString()}.`
});
}
// Extract additional details from the joined result while creating clean cert object
const { caName, profileName, applicationName, ...cert } = certWithDetails;
// Extract subject, fingerprints, and basicConstraints
let certSubject: TCertificateSubject | undefined;
let fingerprints: TCertificateFingerprints | undefined;
let basicConstraints: TCertificateBasicConstraints | undefined;
// NEW: Try to read from database columns first (avoids KMS decryption)
// Check if any parsed field exists (indicates new certificate with stored data)
const hasParsedData = cert.fingerprintSha256 || cert.isCA !== null;
if (hasParsedData) {
// Build subject from individual columns
certSubject = {
commonName: cert.commonName,
organization: cert.subjectOrganization || undefined,
organizationalUnit: cert.subjectOrganizationalUnit || undefined,
country: cert.subjectCountry || undefined,
state: cert.subjectState || undefined,
locality: cert.subjectLocality || undefined,
domainComponents: cert.subjectDomainComponents ? cert.subjectDomainComponents.split(",") : undefined
};
// Build fingerprints from columns
if (cert.fingerprintSha256) {
fingerprints = {
sha256: cert.fingerprintSha256,
sha1: cert.fingerprintSha1 || undefined
};
}
// Build basic constraints
if (cert.isCA !== null && cert.isCA !== undefined) {
basicConstraints = {
isCA: cert.isCA,
pathLength: cert.pathLength !== null ? cert.pathLength : undefined
};
}
}
// BACKWARD COMPATIBILITY: Fallback to on-demand parsing for old certificates
if (!hasParsedData) {
const parsed = await $parseStoredCertificateBody(cert);
if (parsed) {
certSubject = parsed.subject;
fingerprints = parsed.fingerprints;
basicConstraints = parsed.basicConstraints;
}
}
const deletedByActorName = await $resolveDeletedByActorName(cert);
const resolvedRenewalId = await certificateDAL.findLatestRenewalOf(cert);
let latestRenewalCertificateId: string | null = null;
if (resolvedRenewalId) {
const renewal = await certificateDAL.findById(resolvedRenewalId);
if (renewal) {
const renewalMetadataRows = await resourceMetadataDAL.find({ certificateId: renewal.id });
const renewalReadSubject = subject(ProjectPermissionSub.Certificates, {
commonName: renewal.commonName,
altNames: renewal.altNames?.split(",").map((s) => s.trim()),
serialNumber: renewal.serialNumber,
metadata: renewalMetadataRows.map(({ key, value }) => ({ key, value: value || "" }))
});
const canReadRenewal =
permission.can(ProjectPermissionCertificateActions.Read, renewalReadSubject) ||
(await $canActOnCertViaApplication(renewal, ResourcePermissionCertificateActions.Read, {
type: actor,
id: actorId,
authMethod: actorAuthMethod,
orgId: actorOrgId
}));
if (canReadRenewal) latestRenewalCertificateId = renewal.id;
}
}
return {
cert: {
...cert,
subject: certSubject,
fingerprints,
basicConstraints,
caName,
profileName,
applicationName,
latestRenewalCertificateId,
deletedByActorType: cert.deletedByActorType as ActorType | null | undefined,
deletedByActorName,
metadata: certMetadata
}
};
};
/**
* Get certificate private key.
*/
const getCertPrivateKey = async ({
id,
serialNumber,
actorId,
actorAuthMethod,
actor,
actorOrgId
}: TGetCertPrivateKeyDTO) => {
const cert = id ? await certificateDAL.findById(id) : await certificateDAL.findOne({ serialNumber });
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
projectId: cert.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
});
const metadataRows = await resourceMetadataDAL.find({ certificateId: cert.id });
const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
const certSubject = subject(ProjectPermissionSub.Certificates, {
commonName: cert.commonName,
altNames: cert.altNames?.split(",").map((s) => s.trim()),
serialNumber: cert.serialNumber,
metadata: certMetadata
});
if (cert.applicationId) {
const allowedByApplication = await $canActOnCertViaApplication(
cert,
ResourcePermissionCertificateActions.ReadPrivateKey,
{ type: actor, id: actorId, authMethod: actorAuthMethod, orgId: actorOrgId }
);
if (!allowedByApplication) {
throw new ForbiddenRequestError({
message: "You don't have permission to read this certificate's private key"
});
}
} else {
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.ReadPrivateKey, certSubject);
}
assertCertificateMaterialAvailable(cert);
const { certPrivateKey } = await getCertificateCredentials({
certId: cert.id,
projectId: cert.projectId,
certificateSecretDAL,
projectDAL,
kmsService
});
return {
cert,
applicationName: await $resolveApplicationName(cert.applicationId),
certPrivateKey
};
};
/**
* Delete certificate with serial number [serialNumber]
*/
const deleteCert = async ({
id,
serialNumber,
actorId,
actorAuthMethod,
actor,
actorOrgId,
auditLogInfo
}: TDeleteCertDTO) => {
const cert = id ? await certificateDAL.findById(id) : await certificateDAL.findOne({ serialNumber });
if (!cert) {
throw new NotFoundError({
message: id
? `Certificate with id '${id}' not found`
: `Certificate with serial number '${serialNumber}' not found`
});
}
const metadataRows = await resourceMetadataDAL.find({ certificateId: cert.id });
const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
if (cert.applicationId) {
const { permission } = await permissionService.getResourcePermission({
actor,
actorId,
projectId: cert.projectId,
resourceType: ResourceType.CertificateApplication,
resourceId: cert.applicationId,
actorAuthMethod,
actorOrgId
});
ForbiddenError.from(permission).throwUnlessCan(
ResourcePermissionCertificateActions.Delete,
ResourcePermissionSub.Certificates
);
} else {
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
projectId: cert.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
});
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionCertificateActions.Delete,
subject(ProjectPermissionSub.Certificates, {
commonName: cert.commonName,
altNames: cert.altNames?.split(",").map((s) => s.trim()),
serialNumber: cert.serialNumber,
metadata: certMetadata
})
);
}
if (cert.deletedAt) {
throw new BadRequestError({
message: `Certificate '${getCertificateDisplayName(cert)}' was already deleted on ${cert.deletedAt.toISOString()}.`
});
}
const { deletedCert, pkiSyncIdsHoldingCertificate } = await certificateDAL.transaction(async (tx) => {
const lockedCert = await certificateDAL.findByIdForUpdate(cert.id, tx);
if (!lockedCert || lockedCert.deletedAt) {
throw new BadRequestError({
message: `Certificate '${getCertificateDisplayName(cert)}' was already deleted${lockedCert?.deletedAt ? ` on ${new Date(lockedCert.deletedAt).toISOString()}` : ""}.`
});
}
const signer = await signerDAL.findOne({ certificateId: cert.id }, tx);
if (signer) {
throw new BadRequestError({
message: "Cannot delete certificate because it is currently in use by a code signing signer"
});
}
const { deletedCertificates, pkiSyncIdsHoldingCertificates } = await softDeleteCertificates(
{ certificateIds: [cert.id], actorType: actor, actorId },
{
certificateDAL,
certificateBodyDAL,
certificateSecretDAL,
certificateRequestDAL,
pkiCollectionItemDAL,
certificateSyncDAL
},
tx
);
return { deletedCert: deletedCertificates[0], pkiSyncIdsHoldingCertificate: pkiSyncIdsHoldingCertificates };
});
await triggerSyncsForDeletedCertificate(
cert.id,
pkiSyncIdsHoldingCertificate,
{ pkiSyncDAL, pkiSyncQueue, auditLogService, pkiApplicationDAL },
{ commonName: cert.commonName, projectId: cert.projectId, applicationId: cert.applicationId },
auditLogInfo
);
usageMeteringService.emitForProject(cert.projectId, ActiveCerts.key);
usageMeteringService.emitForProject(cert.projectId, WildcardCerts.key);
return {
deletedCert,
statusAtDeletion: resolveCertificateStatus(deletedCert),
applicationName: await $resolveApplicationName(deletedCert.applicationId)
};
};
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,
thumbprint,
revocationReason,
actorId,
actorAuthMethod,
actor,
actorOrgId
}: TRevokeCertDTO) => {
let cert: Awaited<ReturnType<typeof certificateDAL.findById>> | undefined;
if (id) {
cert = await certificateDAL.findById(id);
} else if (serialNumber) {
cert = await certificateDAL.findOne({ serialNumber });
} else if (thumbprint) {
const { algorithm, fingerprint } = normalizeThumbprint(thumbprint);
const column = algorithm === CertificateThumbprintAlgorithm.SHA1 ? "fingerprintSha1" : "fingerprintSha256";
const matches = await certificateDAL.findByThumbprintInOrg({
orgId: actorOrgId,
column,
fingerprint,
limit: 2
});
if (matches.length > 1) {
throw new BadRequestError({
message:
"Multiple certificates match the provided thumbprint. Revoke by certificate ID or serial number instead"
});
}
[cert] = matches;
} else {
throw new BadRequestError({
message: "Must provide a certificate ID, serial number, or thumbprint to revoke"
});
}
if (!cert) {
throw new NotFoundError({ message: "Certificate not found" });
}
if (!cert.caId) {
throw new BadRequestError({
message: "Cannot revoke imported certificates"
});
}
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(cert.caId);
// Check if the CA type supports revocation
const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;
if (!caSupportsCapability(caType, CaCapability.REVOKE_CERTIFICATES)) {
throw new BadRequestError({
message: "Certificate revocation is not supported by this certificate authority type"
});
}
await assertCanRevokeCertificate({
certificate: { ...cert, projectId: ca.projectId },
actor,
actorId,
actorAuthMethod,
actorOrgId,
permissionService,
resourceMetadataDAL
});
if (cert.status === CertStatus.REVOKED) {
throw new BadRequestError({ message: `Certificate '${getCertificateDisplayName(cert)}' is already revoked.` });
}
if (ca.internalCa?.id && cert.profileId && cert.source === CertificateSource.Imported) {
if (cert.deletedAt) {
throw new BadRequestError({
message: `Certificate '${getCertificateDisplayName(cert)}' can't be revoked because it was imported and then deleted on ${cert.deletedAt.toISOString()}.`
});
}
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,
projectId: ca.projectId,
projectDAL,
licenseService
});
}
// Call the upstream CA first so we don't end up with a cert that's revoked locally but still
// active at the issuer (e.g., when the upstream rejects the chosen revocation reason).
if (
ca.externalCa?.type === CaType.AWS_PCA ||
ca.externalCa?.type === CaType.AWS_ACM_PUBLIC_CA ||
ca.externalCa?.type === CaType.DIGICERT ||
ca.externalCa?.type === CaType.GODADDY ||
ca.externalCa?.type === CaType.ADCS
) {
await certificateAuthorityService.revokeCertificate({
caId: ca.id,
serialNumber: cert.serialNumber,
reason: revocationReason
});
}
const revokedAt = new Date();
const revokedCertId = cert.id;
const revokedCertApplicationId = cert.applicationId ?? null;
await certificateDAL.transaction(async (tx) => {
await certificateDAL.update(
{
id: revokedCertId
},
{
status: CertStatus.REVOKED,
revokedAt,
revocationReason: revocationReasonToCrlCode(revocationReason)
},
tx
);
if (!ca.externalCa?.id) {
await internalCertificateAuthorityDAL.update({ caId: ca.id }, { $incr: { ocspGeneration: 1 } }, tx);
}
});
if (!cert.deletedAt) {
await certificateAlertEventEmitter.notify({
certificateId: revokedCertId,
projectId: ca.projectId,
orgId: actorOrgId,
eventType: CertificateApplicationAlertEvent.Revocation,
applicationId: revokedCertApplicationId
});
}
usageMeteringService.emitForProject(ca.projectId, ActiveCerts.key);
usageMeteringService.emitForProject(ca.projectId, WildcardCerts.key);
// Trigger auto sync for PKI syncs connected to this certificate
await triggerAutoSyncForCertificate(cert.id, {
certificateSyncDAL,
pkiSyncDAL,
pkiSyncQueue
});
if (cert.applicationId && !cert.deletedAt) {
await queueCertificateFilterReconcile(cert.id, cert.applicationId, pkiSyncQueue);
}
// rebuild CRL (TODO: move to interval-based cron job)
// Only rebuild CRL for internal CAs - external CAs manage their own CRLs
if (!ca.externalCa?.id) {
await rebuildCaCrl({
caId: ca.id,
certificateAuthorityDAL,
certificateAuthorityCrlDAL,
certificateAuthoritySecretDAL,
projectDAL,
certificateDAL,
kmsService,
caKeySourceService
});
}
if (!cert.deletedAt) {
try {
await pkiAlertV2Queue?.queueCertificateEvent({
certificateId: cert.id,
projectId: ca.projectId,
eventType: PkiAlertEventType.REVOCATION,
applicationId: cert.applicationId ?? null
});
} catch {
logger.debug("Failed to queue PKI revocation alert event");
}
}
// Return appropriate CA format based on CA type
const caResult = ca.externalCa?.id
? {
id: ca.id,
name: ca.name,
projectId: ca.projectId,
status: ca.status,
enableDirectIssuance: ca.enableDirectIssuance,
type: ca.externalCa.type,
externalCa: ca.externalCa
}
: expandInternalCa(ca);
return { revokedAt, cert, applicationName: await $resolveApplicationName(cert.applicationId), ca: caResult };
};
/**
* Return certificate body and certificate chain for certificate with
* serial number [serialNumber]
*/
const getCertBody = async ({ id, serialNumber, actorId, actorAuthMethod, actor, actorOrgId }: TGetCertBodyDTO) => {
const cert = id ? await certificateDAL.findById(id) : await certificateDAL.findOne({ serialNumber });
if (!cert) {
throw new NotFoundError({ message: "Certificate not found" });
}
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
projectId: cert.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
});
const metadataRows = await resourceMetadataDAL.find({ certificateId: cert.id });
const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
const readSubject = subject(ProjectPermissionSub.Certificates, {
commonName: cert.commonName,
altNames: cert.altNames?.split(",").map((s) => s.trim()),
serialNumber: cert.serialNumber,
metadata: certMetadata
});
if (!permission.can(ProjectPermissionCertificateActions.Read, readSubject)) {
const allowedByApplication = await $canActOnCertViaApplication(cert, ResourcePermissionCertificateActions.Read, {
type: actor,
id: actorId,
authMethod: actorAuthMethod,
orgId: actorOrgId
});
if (!allowedByApplication) {
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.Read, readSubject);
}
}
assertCertificateMaterialAvailable(cert);
const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
if (!certBody) {
throw new NotFoundError({ message: "Certificate body not found" });
}
if (!certBody.encryptedCertificate) {
throw new BadRequestError({ message: "Certificate data not available" });
}
const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
projectId: cert.projectId,
projectDAL,
kmsService
});
const kmsDecryptor = await kmsService.decryptWithKmsKey({
kmsId: certificateManagerKeyId
});
const decryptedCert = await kmsDecryptor({
cipherTextBlob: certBody.encryptedCertificate
});
const certObj = new x509.X509Certificate(decryptedCert);
let certificateChain = null;
// On newer certs the certBody.encryptedCertificateChain column will always exist.
// Older certs will have a caCertId which will be used as a fallback mechanism for structuring the chain.
if (certBody.encryptedCertificateChain) {
const decryptedCertChain = await kmsDecryptor({
cipherTextBlob: certBody.encryptedCertificateChain
});
certificateChain = decryptedCertChain.toString();
} else if (cert.caCertId) {
const { caCert, caCertChain } = await getCaCertChain({
caCertId: cert.caCertId,
certificateAuthorityDAL,
certificateAuthorityCertDAL,
projectDAL,
kmsService
});
certificateChain = `${caCert}\n${caCertChain}`.trim();
}
return {
certificate: certObj.toString("pem"),
certificateChain,
serialNumber: certObj.serialNumber,
cert,
applicationName: await $resolveApplicationName(cert.applicationId)
};
};
type TImportedCertificateFacts = {
serialNumber: string;
commonName: string;
altNames?: string;
keyUsages: CertKeyUsage[];
extendedKeyUsages: CertExtendedKeyUsage[];
certificatePem: string;
notBefore: Date;
notAfter: Date;
fields: ReturnType<typeof extractCertificateFields>;
algorithms: ReturnType<typeof extractCertificateAlgorithms>;
};
const $buildImportCertificateVerifier =
({
policyId,
profileName,
verifyWithProvider
}: {
policyId: string;
profileName: string;
verifyWithProvider?: (certificatePem: string) => Promise<Pick<TDigiCertExternalMetadata, "certificateId">>;
}) =>
async (cert: TImportedCertificateFacts) => {
const providerMetadata = verifyWithProvider ? await verifyWithProvider(cert.certificatePem) : {};
const validation = await certificatePolicyService.validateCertificateRequest(policyId, {
commonName: cert.commonName || undefined,
organization: cert.fields.subjectOrganization ?? undefined,
organizationalUnit: cert.fields.subjectOrganizationalUnit ?? undefined,
country: cert.fields.subjectCountry ?? undefined,
state: cert.fields.subjectState ?? undefined,
locality: cert.fields.subjectLocality ?? undefined,
domainComponents: cert.fields.subjectDomainComponents?.split(",") ?? undefined,
keyUsages: parseKeyUsages(cert.keyUsages),
extendedKeyUsages: parseExtendedKeyUsages(cert.extendedKeyUsages),
subjectAlternativeNames: cert.altNames ? cert.altNames.split(",").map((san) => detectSanType(san.trim())) : [],
validity: { ttl: certificateSpanToTtl(cert.notBefore, cert.notAfter) },
keyAlgorithm: cert.algorithms.keyAlgorithm,
signatureAlgorithm: cert.algorithms.signatureAlgorithm,
...(cert.fields.isCA && {
basicConstraints: { isCA: true, pathLength: cert.fields.pathLength ?? undefined }
})
});
if (!validation.isValid) {
const violations = validation.errors.map((error) => `- ${error}`).join("\n");
throw new BadRequestError({
message: `This certificate does not satisfy the policy of certificate profile '${profileName}':\n${violations}\nAttach a profile whose policy allows this certificate, or import it without one to track it for visibility and expiry alerts only.`
});
}
return providerMetadata;
};
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,
profileApiConfig: profile.apiConfig,
verifyCertificate: $buildImportCertificateVerifier({
policyId: profile.certificatePolicyId,
profileName: profile.slug
})
};
}
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,
profileApiConfig: profile.apiConfig,
verifyCertificate: $buildImportCertificateVerifier({
policyId: profile.certificatePolicyId,
profileName: profile.slug
})
};
}
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"}.`
});
}
const { caId } = profile;
const parsedMetadata = parsed.data as TImportExternalMetadata;
const { verifyCertificate } = linkage;
return {
caId,
caType,
externalMetadata: parsedMetadata,
profileName: profile.slug,
caName,
profileApiConfig: profile.apiConfig,
verifyCertificate: $buildImportCertificateVerifier({
policyId: profile.certificatePolicyId,
profileName: profile.slug,
verifyWithProvider: verifyCertificate
? (certificatePem: string) =>
verifyCertificate({ caId, externalMetadata: parsedMetadata, certificatePem }, { digicertFns })
: undefined
})
};
};
/**
* Import certificate
*/
const importCert = async ({
projectId: projectIdInput,
projectSlug,
applicationId,
pkiCollectionId,
actorId,
actorAuthMethod,
actor,
actorOrgId,
friendlyName,
certificatePem: rawCertificatePem,
chainPem: rawChainPem,
privateKeyPem: rawPrivateKeyPem,
profileId,
externalMetadata
}: TImportCertDTO) => {
const collectionId = pkiCollectionId;
const certificatePem = normalizePemText(rawCertificatePem);
const chainPem = rawChainPem ? normalizePemText(rawChainPem) : rawChainPem;
const privateKeyPem = rawPrivateKeyPem ? normalizePemText(rawPrivateKeyPem) : rawPrivateKeyPem;
const resolveProjectId = async (): Promise<string> => {
if (projectIdInput) return projectIdInput;
if (projectSlug) {
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
return project.id;
}
throw new BadRequestError({ message: "Either projectId or projectSlug is required" });
};
const projectId = await resolveProjectId();
if (applicationId) {
const application = await pkiApplicationDAL.findById(applicationId);
if (!application || application.projectId !== projectId) {
throw new NotFoundError({ message: `Application with id '${applicationId}' not found.` });
}
const { permission } = await permissionService.getResourcePermission({
actor,
actorId,
projectId,
resourceType: ResourceType.CertificateApplication,
resourceId: applicationId,
actorAuthMethod,
actorOrgId
});
ForbiddenError.from(permission).throwUnlessCan(
ResourcePermissionCertificateActions.Import,
ResourcePermissionSub.Certificates
);
} else {
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
});
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionCertificateActions.Import,
ProjectPermissionSub.Certificates
);
}
// Check PKI collection
if (collectionId) {
const pkiCollection = await pkiCollectionDAL.findById(collectionId);
if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" });
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
if (chainPem) {
const chainCerts = parsePemCertificateChain(chainPem);
if (!chainCerts) {
throw new BadRequestError({
message:
"The certificate chain contains a block that is not a valid certificate. Paste each certificate in full, including its BEGIN and END lines."
});
}
// Remove leaf cert from the chain if it's present
if (chainCerts[0]?.equal(leafCert)) {
chainCerts.splice(0, 1);
}
if (chainCerts.length === 0) {
throw new BadRequestError({
message: "Certificate chain must contain at least one issuer certificate"
});
}
// Verify leaf certificate is signed by the first certificate in the chain
const isLeafVerified = await leafCert.verify({ publicKey: chainCerts[0].publicKey }).catch(() => false);
if (!isLeafVerified) {
throw new BadRequestError({ message: "Leaf certificate verification against chain failed" });
}
// Verify the entire chain of trust
const verificationPromises = chainCerts.slice(0, -1).map(async (currentCert, index) => {
const issuerCert = chainCerts[index + 1];
return currentCert.verify({ publicKey: issuerCert.publicKey }).catch(() => false);
});
const verificationResults = await Promise.all(verificationPromises);
if (verificationResults.some((result) => !result)) {
throw new BadRequestError({
message: "Certificate chain verification failed: broken trust chain"
});
}
}
// Verify private key matches the certificate when one is provided
if (privateKeyPem) {
let privateKey;
try {
privateKey = crypto.nativeCrypto.createPrivateKey(privateKeyPem);
} catch (err) {
throw new BadRequestError({
message: "Invalid private key. Provide an unencrypted private key in PEM format."
});
}
try {
const message = Buffer.from(Buffer.alloc(32));
const publicKey = crypto.nativeCrypto.createPublicKey(certificatePem);
const signature = crypto.nativeCrypto.sign(null, message, privateKey);
const isValid = crypto.nativeCrypto.verify(null, message, publicKey, signature);
if (!isValid) {
throw new BadRequestError({ message: "Private key does not match certificate" });
}
} catch (err) {
if (err instanceof BadRequestError) {
throw err;
}
throw new BadRequestError({ message: "Error verifying private key against certificate" });
}
}
// Get certificate attributes
const commonName = Array.from(leafCert.subjectName.getField("CN")?.values() || [])[0] || "";
let altNames: undefined | string;
const sanExtension = leafCert.extensions.find((ext) => ext.type === "2.5.29.17");
if (sanExtension) {
const sanNames = new x509.GeneralNames(sanExtension.value);
altNames = sanNames.items.map((name) => name.value).join(", ");
}
const { serialNumber, notBefore, notAfter } = leafCert;
const existingCertWithSerial = await certificateDAL.findOne({ serialNumber, projectId });
if (existingCertWithSerial) {
assertCertificateNotDeleted(existingCertWithSerial, "A deleted certificate can't be imported again.");
}
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);
const importedCustomExtensions = parseImportedCustomExtensions(certificateBuffer);
const providerMetadata = await linkage?.verifyCertificate({
certificatePem,
serialNumber,
commonName,
altNames,
keyUsages,
extendedKeyUsages,
notBefore,
notAfter,
fields: certificateFields,
algorithms: certificateAlgorithms
});
// Encrypt certificate for storage
const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
projectId,
projectDAL,
kmsService
});
const kmsEncryptor = await kmsService.encryptWithKmsKey({
kmsId: certificateManagerKeyId
});
const { cipherTextBlob: encryptedCertificate } = await kmsEncryptor({
plainText: Buffer.from(certificatePem)
});
const encryptedPrivateKey = privateKeyPem
? (await kmsEncryptor({ plainText: Buffer.from(privateKeyPem) })).cipherTextBlob
: null;
const encryptedCertificateChain = chainPem
? (await kmsEncryptor({ plainText: Buffer.from(chainPem) })).cipherTextBlob
: null;
// Imported certificates count toward the quota, so import is gated like issuance. Before the
// transaction, since this reads the plan and may run a count.
const { quotaOrgId, isNewQuotaKey, isWildcard } = await assertCertificateQuotaForProject({
projectId,
commonName,
altNames,
deps: { projectDAL, licenseService, usageCounterDAL, keyStore }
});
let renewBeforeDays: number | undefined;
if (profileId && linkage) {
const effectiveApiConfig = await resolveEffectiveApiConfig({
applicationId,
profileId,
profileApiConfig: applicationId ? undefined : linkage.profileApiConfig,
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL
});
const validityDays = Math.max(1, Math.ceil((notAfter.getTime() - notBefore.getTime()) / (24 * 60 * 60 * 1000)));
renewBeforeDays = calculateFinalRenewBeforeDays({ apiConfig: effectiveApiConfig }, `${validityDays}d`, notAfter);
}
const cert = await certificateDAL.transaction(async (tx) => {
try {
const txCert = await certificateDAL.create(
{
status: CertStatus.ACTIVE,
friendlyName: friendlyName || commonName,
commonName,
altNames,
serialNumber,
notBefore,
notAfter,
projectId,
applicationId: applicationId ?? null,
profileId: profileId ?? null,
caId: linkage?.caId ?? null,
externalMetadata: linkage?.externalMetadata ? { ...linkage.externalMetadata, ...providerMetadata } : null,
source: CertificateSource.Imported,
renewBeforeDays,
keyUsages,
extendedKeyUsages,
...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.
...certificateAlgorithms,
customExtensions: importedCustomExtensions.length ? JSON.stringify(importedCustomExtensions) : null
},
tx
);
await certificateBodyDAL.create(
{
certId: txCert.id,
encryptedCertificate,
encryptedCertificateChain
},
tx
);
if (encryptedPrivateKey) {
await certificateSecretDAL.create(
{
certId: txCert.id,
encryptedPrivateKey
},
tx
);
}
if (collectionId) {
await pkiCollectionItemDAL.create(
{
pkiCollectionId: collectionId,
certId: txCert.id
},
tx
);
}
return txCert;
} catch (error) {
// @ts-expect-error We're expecting a database error
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (error?.error?.code === "23505") {
throw new BadRequestError({ message: "A certificate with this serial number already exists" });
}
throw error;
}
});
if (isNewQuotaKey) await recordNewCertificateQuotaKey(quotaOrgId, { keyStore }, isWildcard);
usageMeteringService.emitForProject(projectId, ActiveCerts.key);
usageMeteringService.emitForProject(projectId, WildcardCerts.key);
if (cert.id && cert.applicationId) {
await queueCertificateFilterReconcile(cert.id, cert.applicationId, pkiSyncQueue);
}
return {
certificate: certificatePem,
certificateChain: chainPem,
privateKey: privateKeyPem,
serialNumber,
cert,
applicationName: await $resolveApplicationName(cert.applicationId),
profileName: linkage?.profileName ?? null,
caName: linkage?.caName ?? null
};
};
/**
* Return certificate body and certificate chain for certificate with
* serial number [serialNumber]
*/
const getCertBundle = async ({
id,
serialNumber,
actorId,
actorAuthMethod,
actor,
actorOrgId
}: TGetCertBundleDTO) => {
const cert = id ? await certificateDAL.findById(id) : await certificateDAL.findOne({ serialNumber });
if (!cert) {
throw new NotFoundError({ message: "Certificate not found" });
}
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
projectId: cert.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
});
const metadataRows = await resourceMetadataDAL.find({ certificateId: cert.id });
const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
const certSubject = subject(ProjectPermissionSub.Certificates, {
commonName: cert.commonName,
altNames: cert.altNames?.split(",").map((s) => s.trim()),
serialNumber: cert.serialNumber,
friendlyName: cert.friendlyName,
status: cert.status,
metadata: certMetadata
});
if (!permission.can(ProjectPermissionCertificateActions.Read, certSubject)) {
const allowedByApplication = await $canActOnCertViaApplication(cert, ResourcePermissionCertificateActions.Read, {
type: actor,
id: actorId,
authMethod: actorAuthMethod,
orgId: actorOrgId
});
if (!allowedByApplication) {
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.Read, certSubject);
}
}
if (cert.applicationId) {
const allowedByApplication = await $canActOnCertViaApplication(
cert,
ResourcePermissionCertificateActions.ReadPrivateKey,
{ type: actor, id: actorId, authMethod: actorAuthMethod, orgId: actorOrgId }
);
if (!allowedByApplication) {
throw new ForbiddenRequestError({
message: "You don't have permission to read this certificate's private key"
});
}
} else {
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.ReadPrivateKey, certSubject);
}
assertCertificateMaterialAvailable(cert);
const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
if (!certBody) {
throw new NotFoundError({ message: "Certificate body not found" });
}
if (!certBody.encryptedCertificate) {
throw new BadRequestError({ message: "Certificate data not available" });
}
const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
projectId: cert.projectId,
projectDAL,
kmsService
});
const kmsDecryptor = await kmsService.decryptWithKmsKey({
kmsId: certificateManagerKeyId
});
const decryptedCert = await kmsDecryptor({
cipherTextBlob: certBody.encryptedCertificate
});
const certObj = new x509.X509Certificate(decryptedCert);
const certificate = certObj.toString("pem");
let certificateChain = null;
// On newer certs the certBody.encryptedCertificateChain column will always exist.
// Older certs will have a caCertId which will be used as a fallback mechanism for structuring the chain.
if (certBody.encryptedCertificateChain) {
const decryptedCertChain = await kmsDecryptor({
cipherTextBlob: certBody.encryptedCertificateChain
});
certificateChain = decryptedCertChain.toString();
} else if (cert.caCertId) {
const { caCert, caCertChain } = await getCaCertChain({
caCertId: cert.caCertId,
certificateAuthorityDAL,
certificateAuthorityCertDAL,
projectDAL,
kmsService
});
certificateChain = `${caCert}\n${caCertChain}`.trim();
}
let privateKey: string | null = null;
try {
const { certPrivateKey } = await getCertificateCredentials({
certId: cert.id,
projectId: cert.projectId,
certificateSecretDAL,
projectDAL,
kmsService
});
privateKey = certPrivateKey;
} catch (e) {
// Skip NotFound errors but throw all others
if (!(e instanceof NotFoundError)) {
throw e;
}
}
return {
certificate,
certificateChain,
privateKey,
serialNumber: cert.serialNumber,
cert,
applicationName: await $resolveApplicationName(cert.applicationId)
};
};
const getCertPkcs12 = async ({
id,
serialNumber,
password,
alias,
actorId,
actorAuthMethod,
actor,
actorOrgId
}: TGetCertPkcs12DTO) => {
const passwordCheck = Pkcs12PasswordSchema.safeParse(password);
if (!passwordCheck.success) {
throw new BadRequestError({
message: `Invalid keystore password: ${passwordCheck.error.issues.map((issue) => issue.message).join(", ")}`
});
}
if (!alias || alias.trim() === "") {
throw new BadRequestError({ message: "Alias is required for PKCS12 keystore generation" });
}
const cert = id ? await certificateDAL.findById(id) : await certificateDAL.findOne({ serialNumber });
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
projectId: cert.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
});
const metadataRows = await resourceMetadataDAL.find({ certificateId: cert.id });
const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
const certSubject = subject(ProjectPermissionSub.Certificates, {
commonName: cert.commonName,
altNames: cert.altNames?.split(",").map((s) => s.trim()),
serialNumber: cert.serialNumber,
friendlyName: cert.friendlyName,
status: cert.status,
metadata: certMetadata
});
if (cert.applicationId) {
const allowedByApplication = await $canActOnCertViaApplication(
cert,
ResourcePermissionCertificateActions.ReadPrivateKey,
{ type: actor, id: actorId, authMethod: actorAuthMethod, orgId: actorOrgId }
);
if (!allowedByApplication) {
throw new ForbiddenRequestError({
message: "You don't have permission to read this certificate's private key"
});
}
} else {
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.ReadPrivateKey, certSubject);
}
assertCertificateMaterialAvailable(cert);
// Get certificate bundle (certificate, chain, private key)
const { certificate, certificateChain, privateKey } = await getCertBundle({
id: cert.id,
actor,
actorId,
actorAuthMethod,
actorOrgId
});
if (!privateKey) {
throw new BadRequestError({ message: "Certificate private key is required for PKCS12 export" });
}
const pkcs12Data = await generatePkcs12FromCertificate({
certificate,
certificateChain: certificateChain || "",
privateKey,
password,
alias
});
return {
pkcs12Data,
cert,
applicationName: await $resolveApplicationName(cert.applicationId)
};
};
const assignCertificateToApplication = async ({
certificateId,
applicationId,
actor,
actorId,
actorAuthMethod,
actorOrgId
}: TAssignCertToApplicationDTO) => {
const cert = await certificateDAL.findById(certificateId);
if (!cert) {
throw new NotFoundError({ message: `Certificate with id '${certificateId}' not found.` });
}
if (cert.applicationId) {
throw new BadRequestError({
message: "This certificate is already assigned to an Application and cannot be moved."
});
}
const application = await pkiApplicationDAL.findById(applicationId);
if (!application || application.projectId !== cert.projectId) {
throw new NotFoundError({ message: `Application with id '${applicationId}' not found in this project.` });
}
const { hasRole } = await permissionService.getProjectPermission({
actor,
actorId,
projectId: cert.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
});
if (!hasRole(ProjectMembershipRole.Admin)) {
throw new ForbiddenRequestError({
message: "Only project admins can assign certificates to an Application."
});
}
const updatedCert = await certificateDAL.transaction(async (tx) => {
const lockedCert = await certificateDAL.findByIdForUpdate(cert.id, tx);
if (!lockedCert) {
throw new NotFoundError({ message: `Certificate with id '${certificateId}' not found.` });
}
assertCertificateNotDeleted(lockedCert);
if (lockedCert.applicationId) {
throw new BadRequestError({
message: "This certificate is already assigned to an Application and cannot be moved."
});
}
return certificateDAL.updateById(cert.id, { applicationId }, tx);
});
await queueCertificateFilterReconcile(cert.id, applicationId, pkiSyncQueue);
return { certificate: updatedCert, application };
};
return {
getCert,
getCertPrivateKey,
deleteCert,
revokeCert,
getCertBody,
importCert,
getCertBundle,
getCertPkcs12,
assignCertificateToApplication
};
};