Skip to content

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

fix(certificate): scope private-key read permission to certificate subject on v3 issuance

Vlad Ligai2dbb2c550d47
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
index 08d661cd21..d9bbdc5e4d 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -3,10 +3,15 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
-import { ForbiddenError } from "@casl/ability";
+import { createMongoAbility, ForbiddenError } from "@casl/ability";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionCertificateActions,
+ ProjectPermissionSet,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
import { TPkiAcmeAccountDALFactory } from "@app/ee/services/pki-acme/pki-acme-account-dal";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
@@ -476,6 +481,221 @@ describe("CertificateV3Service", () => {
);
});
+ describe("read-private-key permission scoping", () => {
+ const profileId = "profile-123";
+
+ const mockProfile = {
+ id: profileId,
+ projectId: "project-123",
+ enrollmentType: EnrollmentType.API,
+ issuerType: IssuerType.CA,
+ caId: "ca-123",
+ certificatePolicyId: "policy-123",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ slug: "test-profile",
+ description: "Test profile",
+ apiConfigId: "api-config-legacy"
+ };
+
+ const mockCA = {
+ id: "ca-123",
+ projectId: "project-123",
+ externalCa: undefined,
+ internalCa: {
+ id: "internal-ca-123",
+ parentCaId: null,
+ type: "ROOT",
+ friendlyName: "Test CA",
+ organization: "Test Org",
+ ou: "Test OU",
+ country: "US",
+ province: "CA",
+ locality: "SF",
+ commonName: "Test CA",
+ dn: "CN=Test CA",
+ serialNumber: "123",
+ maxPathLength: null,
+ keyAlgorithm: "RSA_2048",
+ notBefore: undefined,
+ notAfter: undefined,
+ activeCaCertId: "cert-123",
+ caId: "ca-123",
+ crlDistributionPointUrls: [],
+ disableManagedCrlDistributionPointUrl: false
+ },
+ name: "Test CA",
+ status: "ACTIVE",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ enableDirectIssuance: true
+ };
+
+ const mockPolicy = {
+ id: "policy-123",
+ name: "Test Policy",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ projectId: "project-123",
+ description: "Test policy",
+ signatureAlgorithm: { defaultAlgorithm: "RSA-SHA256" },
+ keyAlgorithm: { defaultKeyType: "RSA_2048" },
+ attributes: [
+ {
+ type: CertSubjectAttributeType.COMMON_NAME,
+ include: CertIncludeType.OPTIONAL,
+ value: ["example.com"]
+ }
+ ]
+ };
+
+ const mockCertificateResult = {
+ certificate: "cert",
+ certificateChain: "chain",
+ issuingCaCertificate: "issuing-ca",
+ privateKey: "key",
+ serialNumber: "123456",
+ certificateId: "cert-1",
+ commonName: "test.example.com"
+ };
+
+ const mockCertRecord = {
+ id: "cert-123",
+ serialNumber: "123456",
+ status: "ACTIVE",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ projectId: "project-123",
+ commonName: "test.example.com",
+ friendlyName: "Test Cert",
+ notBefore: new Date(),
+ notAfter: new Date(),
+ caId: "ca-123",
+ certificatePolicyId: "policy-123",
+ revokedAt: null,
+ revokedBy: null,
+ source: "issued",
+ keySource: "infisical"
+ };
+
+ // Return a real ability so the read-private-key check is evaluated against the certificate subject
+ // rather than a mocked boolean.
+ const grantPermission = (rules: any) => {
+ (mockPermissionService.getProjectPermission as any).mockResolvedValue({
+ permission: createMongoAbility<ProjectPermissionSet>(rules)
+ });
+ };
+
+ beforeEach(() => {
+ vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);
+ vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
+ isValid: true,
+ errors: [],
+ warnings: []
+ });
+ vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA as any);
+ vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy as any);
+ vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue(mockCertificateResult as any);
+ vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(mockCertRecord as any);
+ vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCertRecord as any);
+ vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCertRecord as any);
+ vi.mocked(mockCertificateDAL.transaction).mockImplementation(
+ async (callback: (tx: any) => Promise<unknown>) => callback(undefined as any)
+ );
+ });
+
+ it("returns the private key when read-private-key is granted unconditionally", async () => {
+ grantPermission([
+ { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
+ { action: ProjectPermissionCertificateActions.ReadPrivateKey, subject: ProjectPermissionSub.Certificates }
+ ]);
+
+ const result = await service.issueCertificateFromProfile({
+ profileId,
+ certificateRequest: mockCertificateRequest,
+ ...mockActor
+ });
+
+ expect(result.privateKey).toBeDefined();
+ });
+
+ it("omits the private key when read-private-key is granted only for a non-matching certificate subject", async () => {
+ grantPermission([
+ { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
+ {
+ action: ProjectPermissionCertificateActions.ReadPrivateKey,
+ subject: ProjectPermissionSub.Certificates,
+ conditions: { commonName: "not-the-issued-name.invalid" }
+ }
+ ]);
+
+ const result = await service.issueCertificateFromProfile({
+ profileId,
+ certificateRequest: mockCertificateRequest,
+ ...mockActor
+ });
+
+ expect(result.privateKey).toBeUndefined();
+ });
+
+ it("returns the private key when the read-private-key condition matches the issued certificate subject", async () => {
+ grantPermission([
+ { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
+ {
+ action: ProjectPermissionCertificateActions.ReadPrivateKey,
+ subject: ProjectPermissionSub.Certificates,
+ conditions: { commonName: "test.example.com" }
+ }
+ ]);
+
+ const result = await service.issueCertificateFromProfile({
+ profileId,
+ certificateRequest: mockCertificateRequest,
+ ...mockActor
+ });
+
+ expect(result.privateKey).toBeDefined();
+ });
+
+ it("returns the private key when a read-private-key condition on a non-common-name field matches", async () => {
+ grantPermission([
+ { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
+ {
+ action: ProjectPermissionCertificateActions.ReadPrivateKey,
+ subject: ProjectPermissionSub.Certificates,
+ conditions: { status: "ACTIVE" }
+ }
+ ]);
+
+ const result = await service.issueCertificateFromProfile({
+ profileId,
+ certificateRequest: mockCertificateRequest,
+ ...mockActor
+ });
+
+ expect(result.privateKey).toBeDefined();
+ });
+
+ it("omits the private key when a read-private-key condition on a non-common-name field excludes the certificate", async () => {
+ grantPermission([
+ { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
+ {
+ action: ProjectPermissionCertificateActions.ReadPrivateKey,
+ subject: ProjectPermissionSub.Certificates,
+ conditions: { status: { $ne: "ACTIVE" } }
+ }
+ ]);
+
+ const result = await service.issueCertificateFromProfile({
+ profileId,
+ certificateRequest: mockCertificateRequest,
+ ...mockActor
+ });
+
+ expect(result.privateKey).toBeUndefined();
+ });
+ });
+
it("should correctly map camelCase key usages to snake_case before validation", async () => {
const profileId = "profile-123";
const mockProfile = {
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index 2572bd26c4..f924028c0f 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -680,6 +680,28 @@ const processSelfSignedCertificate = async ({
};
};
+// 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,
@@ -1300,7 +1322,7 @@ export const certificateV3ServiceFactory = ({
} else {
canReadPrivateKey = permission.can(
ProjectPermissionCertificateActions.ReadPrivateKey,
- ProjectPermissionSub.Certificates
+ buildCertificateReadPrivateKeySubject(certificateData, metadata)
);
}
@@ -1534,7 +1556,7 @@ export const certificateV3ServiceFactory = ({
} else {
canReadPrivateKey = permission.can(
ProjectPermissionCertificateActions.ReadPrivateKey,
- ProjectPermissionSub.Certificates
+ buildCertificateReadPrivateKeySubject(cert, metadata)
);
}