Skip to content

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

merge: resolve conflicts with origin/main after certificate-v3 module split

Saif5c43844ec75a
diff --cc backend/src/services/certificate-v3/certificate-v3-service.test.ts
index a7141c9b9e,bb3bc9d0ea..177a79ab45
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@@ -9,7 -9,7 +9,8 @@@ import { afterEach, beforeEach, describ
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ProjectPermissionCertificateActions,
+ ProjectPermissionCertificateProfileActions,
+ ProjectPermissionSet,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import { TPkiAcmeAccountDALFactory } from "@app/ee/services/pki-acme/pki-acme-account-dal";
diff --cc backend/src/services/certificate-v3/certificate-v3-service.ts
index f924028c0f,29414d4eaa..d80ac6a158
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@@ -288,420 -282,6 +282,28 @@@ const validateProfileAndPermissions = a
return profile;
};
- const validateRenewalEligibility = (
- certificate: {
- id: string;
- status: string;
- notBefore: Date;
- notAfter: Date;
- revokedAt?: Date | null;
- renewedByCertificateId?: string | null;
- profileId?: string | null;
- caId?: string | null;
- pkiSubscriberId?: string | null;
- },
- ca: TCertificateAuthorityWithAssociatedCa
- ) => {
- const errors: string[] = [];
-
- if (certificate.status !== CertStatus.ACTIVE) {
- errors.push(`Certificate status is ${certificate.status}, must be ${CertStatus.ACTIVE}`);
- }
-
- const now = new Date();
- if (certificate.notAfter <= now) {
- errors.push("Certificate is already expired");
- }
-
- if (certificate.revokedAt) {
- errors.push("Certificate is revoked and cannot be renewed");
- }
-
- const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;
- const isInternalCa = caType === CaType.INTERNAL;
- const isConnectedExternalCa =
- caType === CaType.ACME ||
- caType === CaType.AZURE_AD_CS ||
- caType === CaType.ADCS ||
- caType === CaType.AWS_PCA ||
- caType === CaType.AWS_ACM_PUBLIC_CA ||
- caType === CaType.DIGICERT ||
- caType === CaType.VENAFI_TPP ||
- caType === CaType.GODADDY;
- const isImportedCertificate = certificate.pkiSubscriberId != null && !certificate.profileId;
-
- if (!isInternalCa && !isConnectedExternalCa) {
- errors.push(`CA type ${String(caType)} does not support renewal`);
- }
-
- if (isImportedCertificate) {
- errors.push("Externally imported certificates cannot be renewed");
- }
-
- if (ca.status !== CaStatus.ACTIVE) {
- errors.push(`Certificate Authority is ${ca.status}, must be ${CaStatus.ACTIVE}`);
- }
-
- if (certificate.renewedByCertificateId) {
- errors.push("Certificate has already been renewed");
- }
-
- const certificateTtlInDays = Math.ceil(
- (certificate.notAfter.getTime() - certificate.notBefore.getTime()) / (24 * 60 * 60 * 1000)
- );
-
- if (ca.internalCa?.notAfter) {
- const caExpiryDate = new Date(ca.internalCa.notAfter);
- const proposedCertExpiryDate = new Date(now.getTime() + certificateTtlInDays * 24 * 60 * 60 * 1000);
-
- if (proposedCertExpiryDate > caExpiryDate) {
- errors.push(
- `New certificate would expire (${proposedCertExpiryDate.toISOString()}) after its issuing CA (${caExpiryDate.toISOString()})`
- );
- }
- }
-
- return {
- isEligible: errors.length === 0,
- errors
- };
- };
-
- const parseKeyUsages = (keyUsages: unknown): CertKeyUsageType[] => {
- if (!keyUsages) return [];
-
- const validKeyUsages = [...Object.values(CertKeyUsageType), ...Object.values(CertKeyUsage)] as string[];
-
- const normalize = (usage: string): CertKeyUsageType | null => {
- if (validKeyUsages.includes(usage)) {
- return mapLegacyKeyUsageToStandard(usage as CertKeyUsageType);
- }
- return null;
- };
-
- let raw: string[];
-
- if (Array.isArray(keyUsages)) {
- raw = keyUsages.filter((u): u is string => typeof u === "string");
- } else if (typeof keyUsages === "string") {
- raw = keyUsages.split(",").map((u) => u.trim());
- } else {
- return [];
- }
-
- return raw.map((u) => normalize(u)).filter((u): u is CertKeyUsageType => u !== null);
- };
-
- const parseExtendedKeyUsages = (extendedKeyUsages: unknown): CertExtendedKeyUsageType[] => {
- if (!extendedKeyUsages) return [];
-
- const validExtendedKeyUsages = [
- ...Object.values(CertExtendedKeyUsageType),
- ...Object.values(CertExtendedKeyUsage)
- ] as string[];
-
- const normalize = (usage: string): CertExtendedKeyUsageType | null => {
- if (validExtendedKeyUsages.includes(usage)) {
- return mapLegacyExtendedKeyUsageToStandard(usage as CertExtendedKeyUsageType);
- }
- return null;
- };
-
- let raw: string[];
-
- if (Array.isArray(extendedKeyUsages)) {
- raw = extendedKeyUsages.filter((u): u is string => typeof u === "string");
- } else if (typeof extendedKeyUsages === "string") {
- raw = extendedKeyUsages.split(",").map((u) => u.trim());
- } else {
- return [];
- }
-
- return raw.map((u) => normalize(u)).filter((u): u is CertExtendedKeyUsageType => u !== null);
- };
-
- const createSelfSignedCertificateRecord = async ({
- selfSignedResult,
- certificateRequest,
- profile,
- originalCert,
- certificateDAL,
- tx,
- isRenewal = false
- }: {
- selfSignedResult: Awaited<ReturnType<typeof generateSelfSignedCertificate>>;
- certificateRequest: {
- commonName?: string;
- keyUsages?: CertKeyUsageType[];
- extendedKeyUsages?: CertExtendedKeyUsageType[];
- };
- profile?: { id: string; projectId: string } | null;
- originalCert?: {
- id: string;
- friendlyName?: string | null;
- commonName?: string | null;
- projectId: string;
- };
- certificateDAL: Pick<TCertificateDALFactory, "create" | "updateById">;
- tx: Parameters<TCertificateDALFactory["create"]>[1];
- isRenewal?: boolean;
- }) => {
- const subjectCommonName =
- (selfSignedResult.certificateSubject.common_name as string) ||
- certificateRequest.commonName ||
- originalCert?.commonName ||
- "";
-
- const altNamesList = selfSignedResult.subjectAlternativeNames.map((san) => san.value).join(",");
-
- const projectId = originalCert?.projectId || profile?.projectId;
- if (!projectId) {
- throw new BadRequestError({ message: "Project ID is required for certificate creation" });
- }
-
- const baseRecord = {
- serialNumber: selfSignedResult.serialNumber,
- friendlyName: originalCert?.friendlyName || subjectCommonName,
- commonName: subjectCommonName,
- altNames: altNamesList,
- status: CertStatus.ACTIVE,
- notBefore: selfSignedResult.notBefore,
- notAfter: selfSignedResult.notAfter,
- projectId,
- keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
- extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
- profileId: profile?.id || null
- };
-
- const renewalRecord =
- isRenewal && originalCert
- ? {
- renewedFromCertificateId: originalCert.id
- }
- : {};
-
- // Extract certificate fields for storage
- const parsedFields = extractCertificateFields(selfSignedResult.certificate);
-
- return certificateDAL.create(
- {
- ...baseRecord,
- ...renewalRecord,
- ...parsedFields
- },
- tx
- );
- };
-
- const createEncryptedCertificateData = async ({
- certificateId,
- certificate,
- privateKey,
- projectId,
- certificateBodyDAL,
- certificateSecretDAL,
- kmsService,
- projectDAL,
- tx
- }: {
- certificateId: string;
- certificate: Buffer;
- privateKey: Buffer;
- projectId: string;
- certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
- certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
- kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;
- projectDAL: TProjectDALFactory;
- tx: Parameters<TCertificateBodyDALFactory["create"]>[1];
- }) => {
- const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
- projectId,
- projectDAL,
- kmsService
- });
-
- const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKeyId });
-
- const encryptedCertificate = await kmsEncryptor({
- plainText: certificate
- });
-
- await certificateBodyDAL.create(
- {
- certId: certificateId,
- encryptedCertificate: encryptedCertificate.cipherTextBlob
- },
- tx
- );
-
- const encryptedPrivateKey = await kmsEncryptor({
- plainText: privateKey
- });
-
- await certificateSecretDAL.create(
- {
- certId: certificateId,
- encryptedPrivateKey: encryptedPrivateKey.cipherTextBlob
- },
- tx
- );
- };
-
- const parseTtlToMs = (ttl: string): number => {
- const regex = new RE2("^(\\d+)(s|m|h|d)$");
- const match = regex.exec(ttl);
-
- if (!match) throw new Error(`Invalid TTL format: ${ttl}`);
-
- const value = parseInt(match[1], 10);
- const unit = match[2];
-
- switch (unit) {
- case "s":
- return value * 1000;
- case "m":
- return value * 60 * 1000;
- case "h":
- return value * 60 * 60 * 1000;
- case "d":
- return value * 24 * 60 * 60 * 1000;
- default:
- throw new Error(`Unknown TTL unit: ${unit}`);
- }
- };
-
- const processSelfSignedCertificate = async ({
- certificateRequest,
- policy,
- profile,
- originalCert,
- effectiveAlgorithms,
- certificateDAL,
- certificateBodyDAL,
- certificateSecretDAL,
- kmsService,
- projectDAL,
- tx,
- isRenewal = false
- }: {
- certificateRequest: {
- commonName?: string;
- organization?: string;
- organizationalUnit?: string;
- country?: string;
- state?: string;
- locality?: string;
- domainComponents?: string[];
- keyUsages?: CertKeyUsageType[];
- extendedKeyUsages?: CertExtendedKeyUsageType[];
- validity: { ttl: string };
- notBefore?: Date;
- notAfter?: Date;
- };
- policy?: {
- subject?: Array<{
- type: string;
- allowed?: string[];
- required?: string[];
- denied?: string[];
- }>;
- sans?: Array<{
- type: string;
- allowed?: string[];
- required?: string[];
- denied?: string[];
- }>;
- } | null;
- profile?: { id: string; projectId: string } | null;
- originalCert?: {
- id: string;
- friendlyName?: string | null;
- commonName?: string | null;
- projectId: string;
- };
- effectiveAlgorithms: {
- signatureAlgorithm: CertSignatureAlgorithm;
- keyAlgorithm: CertKeyAlgorithm;
- };
- certificateDAL: Pick<TCertificateDALFactory, "create" | "updateById">;
- certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
- certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
- kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;
- projectDAL: TProjectDALFactory;
- tx: Parameters<TCertificateDALFactory["create"]>[1];
- isRenewal?: boolean;
- }) => {
- const projectId = originalCert?.projectId || profile?.projectId;
- if (!projectId) {
- throw new BadRequestError({ message: "Project ID is required for certificate creation" });
- }
-
- const selfSignedResult = await generateSelfSignedCertificate({
- certificateRequest,
- policy,
- effectiveSignatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,
- effectiveKeyAlgorithm: effectiveAlgorithms.keyAlgorithm
- });
-
- const certificateData = await createSelfSignedCertificateRecord({
- selfSignedResult,
- certificateRequest,
- profile,
- originalCert,
- certificateDAL,
- tx,
- isRenewal
- });
-
- await certificateDAL.updateById(
- certificateData.id,
- {
- signatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,
- keyAlgorithm: effectiveAlgorithms.keyAlgorithm
- },
- tx
- );
-
- await createEncryptedCertificateData({
- certificateId: certificateData.id,
- certificate: selfSignedResult.certificate,
- privateKey: selfSignedResult.privateKey,
- projectId,
- certificateBodyDAL,
- certificateSecretDAL,
- kmsService,
- projectDAL,
- tx
- });
-
- return {
- selfSignedResult,
- certificateData
- };
- };
-
+// Builds the certificate permission subject from a persisted certificate record so the private-key
+// read permission is evaluated against the same fields the certificate read paths use. Includes every
+// field the certificate permission conditions support, so attribute-scoped grants match consistently.
+const buildCertificateReadPrivateKeySubject = (
+ certRecord: {
+ commonName?: string | null;
+ altNames?: string | null;
+ serialNumber?: string | null;
+ friendlyName?: string | null;
+ status?: string | null;
+ },
+ metadata?: { key: string; value: string }[]
+) =>
+ subject(ProjectPermissionSub.Certificates, {
+ commonName: certRecord.commonName ?? undefined,
+ altNames: certRecord.altNames ? certRecord.altNames.split(",").map((san) => san.trim()) : undefined,
+ serialNumber: certRecord.serialNumber ?? undefined,
+ friendlyName: certRecord.friendlyName ?? undefined,
+ status: certRecord.status ?? undefined,
+ metadata
+ });
+
export const certificateV3ServiceFactory = ({
certificateDAL,
certificateBodyDAL,