Skip to content

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

Support issuing intermediate CAs via certificate profiles

Carlos Monastyrski80b7da76c859
diff --git a/backend/src/db/migrations/20260113145337_add-ca-settings-to-certificate-templates-v2.ts b/backend/src/db/migrations/20260113145337_add-ca-settings-to-certificate-templates-v2.ts
new file mode 100644
index 0000000000..b91154f58b
--- /dev/null
+++ b/backend/src/db/migrations/20260113145337_add-ca-settings-to-certificate-templates-v2.ts
@@ -0,0 +1,35 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasTemplateCaSettingsColumn = await knex.schema.hasColumn(TableName.PkiCertificateTemplateV2, "caSettings");
+ if (!hasTemplateCaSettingsColumn) {
+ await knex.schema.alterTable(TableName.PkiCertificateTemplateV2, (t) => {
+ t.jsonb("caSettings");
+ });
+ }
+
+ const hasRequestCaSettingsColumn = await knex.schema.hasColumn(TableName.CertificateRequests, "caSettings");
+ if (!hasRequestCaSettingsColumn) {
+ await knex.schema.alterTable(TableName.CertificateRequests, (t) => {
+ t.jsonb("caSettings");
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasTemplateCaSettingsColumn = await knex.schema.hasColumn(TableName.PkiCertificateTemplateV2, "caSettings");
+ if (hasTemplateCaSettingsColumn) {
+ await knex.schema.alterTable(TableName.PkiCertificateTemplateV2, (t) => {
+ t.dropColumn("caSettings");
+ });
+ }
+
+ const hasRequestCaSettingsColumn = await knex.schema.hasColumn(TableName.CertificateRequests, "caSettings");
+ if (hasRequestCaSettingsColumn) {
+ await knex.schema.alterTable(TableName.CertificateRequests, (t) => {
+ t.dropColumn("caSettings");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/pki-certificate-templates-v2.ts b/backend/src/db/schemas/pki-certificate-templates-v2.ts
index de4603887a..580c2565b6 100644
--- a/backend/src/db/schemas/pki-certificate-templates-v2.ts
+++ b/backend/src/db/schemas/pki-certificate-templates-v2.ts
@@ -19,7 +19,8 @@ export const PkiCertificateTemplatesV2Schema = z.object({
algorithms: z.unknown().nullable().optional(),
validity: z.unknown().nullable().optional(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ caSettings: z.unknown().nullable().optional()
});
export type TPkiCertificateTemplatesV2 = z.infer<typeof PkiCertificateTemplatesV2Schema>;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 9e9527e5ba..3f10b2a631 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2319,6 +2319,7 @@ export const registerRoutes = async (
const certificateEstV3Service = certificateEstV3ServiceFactory({
internalCertificateAuthorityService,
certificateTemplateV2Service,
+ certificateTemplateV2DAL,
certificateAuthorityDAL,
certificateAuthorityCertDAL,
projectDAL,
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index d598bd9aa6..0f21ca77c5 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -42,6 +42,11 @@ const extractCertificateData = (data: CertificateServiceResponse) => ({
interface CertificateRequestForService {
commonName?: string;
+ organization?: string;
+ organizationalUnit?: string;
+ country?: string;
+ state?: string;
+ locality?: string;
keyUsages?: CertKeyUsageType[];
extendedKeyUsages?: CertExtendedKeyUsageType[];
altNames?: Array<{
@@ -55,6 +60,10 @@ interface CertificateRequestForService {
notAfter?: Date;
signatureAlgorithm?: string;
keyAlgorithm?: string;
+ basicConstraints?: {
+ isCA: boolean;
+ pathLength?: number;
+ };
}
const validateTtlAndDateFields = (data: {
@@ -113,6 +122,11 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
attributes: z
.object({
commonName: validateTemplateRegexField.optional(),
+ organization: validateTemplateRegexField.optional(),
+ organizationalUnit: validateTemplateRegexField.optional(),
+ country: validateTemplateRegexField.optional(),
+ state: validateTemplateRegexField.optional(),
+ locality: validateTemplateRegexField.optional(),
keyUsages: z.nativeEnum(CertKeyUsageType).array().optional(),
extendedKeyUsages: z.nativeEnum(CertExtendedKeyUsageType).array().optional(),
altNames: z
@@ -131,7 +145,13 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
.min(1, "TTL cannot be empty")
.refine((val) => ms(val) > 0, "TTL must be a positive number"),
notBefore: validateCaDateField.optional(),
- notAfter: validateCaDateField.optional()
+ notAfter: validateCaDateField.optional(),
+ basicConstraints: z
+ .object({
+ isCA: z.boolean(),
+ pathLength: z.number().int().min(-1).optional()
+ })
+ .optional()
})
.optional(),
removeRootsFromChain: booleanSchema.default(false).optional()
@@ -195,7 +215,8 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
notAfter: attributes?.notAfter ? new Date(attributes.notAfter) : undefined,
signatureAlgorithm: attributes?.signatureAlgorithm,
keyAlgorithm: attributes?.keyAlgorithm,
- csr
+ csr,
+ basicConstraints: attributes?.basicConstraints
};
const data = await server.services.certificateV3.orderCertificateFromProfile({
@@ -240,7 +261,8 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
notBefore: attributes?.notBefore ? new Date(attributes.notBefore) : undefined,
notAfter: attributes?.notAfter ? new Date(attributes.notAfter) : undefined,
enrollmentType: EnrollmentType.API,
- removeRootsFromChain: requestBody.removeRootsFromChain
+ removeRootsFromChain: requestBody.removeRootsFromChain,
+ basicConstraints: attributes?.basicConstraints
});
await server.services.auditLog.createAuditLog({
@@ -264,6 +286,11 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
const certificateRequestForService: CertificateRequestForService = {
commonName: attributes?.commonName,
+ organization: attributes?.organization,
+ organizationalUnit: attributes?.organizationalUnit,
+ country: attributes?.country,
+ state: attributes?.state,
+ locality: attributes?.locality,
keyUsages: attributes?.keyUsages,
extendedKeyUsages: attributes?.extendedKeyUsages,
altNames: attributes?.altNames,
@@ -271,7 +298,8 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
notBefore: attributes?.notBefore ? new Date(attributes.notBefore) : undefined,
notAfter: attributes?.notAfter ? new Date(attributes.notAfter) : undefined,
signatureAlgorithm: attributes?.signatureAlgorithm,
- keyAlgorithm: attributes?.keyAlgorithm
+ keyAlgorithm: attributes?.keyAlgorithm,
+ basicConstraints: attributes?.basicConstraints
};
const mappedCertificateRequest = mapEnumsForValidation(certificateRequestForService);
@@ -486,6 +514,11 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
.object({
profileId: z.string().uuid(),
commonName: validateTemplateRegexField.optional(),
+ organization: validateTemplateRegexField.optional(),
+ organizationalUnit: validateTemplateRegexField.optional(),
+ country: validateTemplateRegexField.optional(),
+ state: validateTemplateRegexField.optional(),
+ locality: validateTemplateRegexField.optional(),
ttl: z
.string()
.trim()
@@ -530,6 +563,11 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
handler: async (req) => {
const certificateRequestForService: CertificateRequestForService = {
commonName: req.body.commonName,
+ organization: req.body.organization,
+ organizationalUnit: req.body.organizationalUnit,
+ country: req.body.country,
+ state: req.body.state,
+ locality: req.body.locality,
keyUsages: req.body.keyUsages,
extendedKeyUsages: req.body.extendedKeyUsages,
altNames: req.body.altNames,
diff --git a/backend/src/server/routes/v1/certificate-template-router.ts b/backend/src/server/routes/v1/certificate-template-router.ts
index 499d0b98ef..8f3a21ed4c 100644
--- a/backend/src/server/routes/v1/certificate-template-router.ts
+++ b/backend/src/server/routes/v1/certificate-template-router.ts
@@ -115,6 +115,16 @@ const templateV2AlgorithmsSchema = z.object({
keyAlgorithm: z.array(z.string()).min(1, "At least one key algorithm must be provided").optional()
});
+const templateV2CaSettingsSchema = z
+ .object({
+ maxPathLength: z
+ .number()
+ .int("Path length must be an integer")
+ .min(-1, "Path length must be -1 (unlimited) or a non-negative integer")
+ .optional()
+ })
+ .nullable();
+
const createCertificateTemplateV2Schema = z.object({
projectId: z.string().min(1),
name: z.string().min(1).max(255, "Name must be between 1 and 255 characters"),
@@ -124,7 +134,8 @@ const createCertificateTemplateV2Schema = z.object({
keyUsages: templateV2KeyUsagesSchema.optional(),
extendedKeyUsages: templateV2ExtendedKeyUsagesSchema.optional(),
algorithms: templateV2AlgorithmsSchema.optional(),
- validity: templateV2ValiditySchema.optional()
+ validity: templateV2ValiditySchema.optional(),
+ caSettings: templateV2CaSettingsSchema.optional()
});
const updateCertificateTemplateV2Schema = z.object({
@@ -135,7 +146,8 @@ const updateCertificateTemplateV2Schema = z.object({
keyUsages: templateV2KeyUsagesSchema.optional(),
extendedKeyUsages: templateV2ExtendedKeyUsagesSchema.optional(),
algorithms: templateV2AlgorithmsSchema.optional(),
- validity: templateV2ValiditySchema.optional()
+ validity: templateV2ValiditySchema.optional(),
+ caSettings: templateV2CaSettingsSchema.optional()
});
export const registerCertificateTemplateRouter = async (server: FastifyZodProvider) => {
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
index 86e3b233c9..31e339c104 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
@@ -1,3 +1,4 @@
+/* eslint-disable no-nested-ternary */
/* eslint-disable no-bitwise */
import { ForbiddenError, subject } from "@casl/ability";
import * as x509 from "@peculiar/x509";
@@ -1203,6 +1204,13 @@ export const internalCertificateAuthorityServiceFactory = ({
keyAlgorithm,
isFromProfile,
internal = false,
+ caSettings,
+ pathLength,
+ organization,
+ country,
+ state,
+ locality,
+ ou,
tx
}: TIssueCertFromCaDTO): Promise<TIssueCertFromCaResponse> => {
let ca: TCertificateAuthorityWithAssociatedCa | undefined;
@@ -1329,8 +1337,17 @@ export const internalCertificateAuthorityServiceFactory = ({
? signatureAlgorithmToAlgCfg(signatureAlgorithm, ca.internalCa.keyAlgorithm as CertKeyAlgorithm)
: keyAlgorithmToAlgCfg(ca.internalCa.keyAlgorithm as CertKeyAlgorithm);
+ const leafDn = createDistinguishedName({
+ commonName,
+ organization,
+ ou,
+ country,
+ province: state,
+ locality
+ });
+
const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
- name: `CN=${commonName}`,
+ name: leafDn,
keys: leafKeys,
signingAlgorithm: keyGenAlg,
extensions: [
@@ -1355,8 +1372,63 @@ export const internalCertificateAuthorityServiceFactory = ({
const distributionPointUrl = `${appCfg.SITE_URL}/api/v1/cert-manager/crl/${caCrl.id}/der`;
const caIssuerUrl = `${appCfg.SITE_URL}/api/v1/cert-manager/ca/internal/${ca.id}/certificates/${caCert.id}/der`;
+ const shouldIssueCaCertificate = caSettings !== undefined && caSettings !== null;
+
+ let basicConstraintsExtension: x509.BasicConstraintsExtension;
+ if (shouldIssueCaCertificate) {
+ const templateMaxPathLength = caSettings.maxPathLength;
+ if (templateMaxPathLength !== undefined && templateMaxPathLength !== null && templateMaxPathLength !== -1) {
+ // When template has a maxPathLength set (not unlimited), pathLength is required
+ if (pathLength === undefined || pathLength === null) {
+ throw new BadRequestError({
+ message: `Path length is required when issuing CA certificates. Template allows maximum path length of ${templateMaxPathLength}.`
+ });
+ }
+ if (pathLength > templateMaxPathLength) {
+ throw new BadRequestError({
+ message: `Path length (${pathLength}) exceeds template's maximum allowed path length (${templateMaxPathLength})`
+ });
+ }
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ const issuingCaBasicConstraints = caCertObj.getExtension("2.5.29.19") as x509.BasicConstraintsExtension | null;
+
+ if (issuingCaBasicConstraints) {
+ const issuingCaPathLength = issuingCaBasicConstraints.pathLength;
+
+ if (issuingCaPathLength === 0) {
+ throw new BadRequestError({
+ message: "Issuing CA cannot issue subordinate CA certificates (path length is 0)"
+ });
+ }
+
+ if (issuingCaPathLength !== undefined && pathLength !== undefined && pathLength !== null) {
+ if (pathLength >= issuingCaPathLength) {
+ throw new BadRequestError({
+ message: `Path length (${pathLength}) must be less than issuing CA's path length (${issuingCaPathLength})`
+ });
+ }
+ }
+
+ const effectivePathLength =
+ pathLength !== undefined && pathLength !== null
+ ? pathLength
+ : issuingCaPathLength !== undefined
+ ? issuingCaPathLength - 1
+ : undefined;
+
+ basicConstraintsExtension = new x509.BasicConstraintsExtension(true, effectivePathLength, true);
+ } else {
+ const effectivePathLength = pathLength !== undefined && pathLength !== null ? pathLength : undefined;
+ basicConstraintsExtension = new x509.BasicConstraintsExtension(true, effectivePathLength, true);
+ }
+ } else {
+ basicConstraintsExtension = new x509.BasicConstraintsExtension(false);
+ }
+
const extensions: x509.Extension[] = [
- new x509.BasicConstraintsExtension(false),
+ basicConstraintsExtension,
new x509.CRLDistributionPointsExtension([distributionPointUrl]),
await x509.AuthorityKeyIdentifierExtension.create(caCertObj, false),
await x509.SubjectKeyIdentifierExtension.create(csrObj.publicKey),
@@ -1581,6 +1653,8 @@ export const internalCertificateAuthorityServiceFactory = ({
extendedKeyUsages,
signatureAlgorithm,
keyAlgorithm,
+ caSettings,
+ pathLength,
tx
} = dto;
@@ -1720,8 +1794,64 @@ export const internalCertificateAuthorityServiceFactory = ({
const distributionPointUrl = `${appCfg.SITE_URL}/api/v1/cert-manager/crl/${caCrl.id}/der`;
const caIssuerUrl = `${appCfg.SITE_URL}/api/v1/cert-manager/ca/internal/${ca.id}/certificates/${caCert.id}/der`;
+
+ const shouldIssueCaCertificate = caSettings !== undefined && caSettings !== null;
+
+ let basicConstraintsExtension: x509.BasicConstraintsExtension;
+ if (shouldIssueCaCertificate) {
+ const templateMaxPathLength = caSettings.maxPathLength;
+ if (templateMaxPathLength !== undefined && templateMaxPathLength !== null && templateMaxPathLength !== -1) {
+ // When template has a maxPathLength set (not unlimited), pathLength is required
+ if (pathLength === undefined || pathLength === null) {
+ throw new BadRequestError({
+ message: `Path length is required when issuing CA certificates. Template allows maximum path length of ${templateMaxPathLength}.`
+ });
+ }
+ if (pathLength > templateMaxPathLength) {
+ throw new BadRequestError({
+ message: `Path length (${pathLength}) exceeds template's maximum allowed path length (${templateMaxPathLength})`
+ });
+ }
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ const issuingCaBasicConstraints = caCertObj.getExtension("2.5.29.19") as x509.BasicConstraintsExtension | null;
+
+ if (issuingCaBasicConstraints) {
+ const issuingCaPathLength = issuingCaBasicConstraints.pathLength;
+
+ if (issuingCaPathLength === 0) {
+ throw new BadRequestError({
+ message: "Issuing CA cannot issue subordinate CA certificates (path length is 0)"
+ });
+ }
+
+ if (issuingCaPathLength !== undefined && pathLength !== undefined && pathLength !== null) {
+ if (pathLength >= issuingCaPathLength) {
+ throw new BadRequestError({
+ message: `Path length (${pathLength}) must be less than issuing CA's path length (${issuingCaPathLength})`
+ });
+ }
+ }
+
+ const effectivePathLength =
+ pathLength !== undefined && pathLength !== null
+ ? pathLength
+ : issuingCaPathLength !== undefined
+ ? issuingCaPathLength - 1
+ : undefined;
+
+ basicConstraintsExtension = new x509.BasicConstraintsExtension(true, effectivePathLength, true);
+ } else {
+ const effectivePathLength = pathLength !== undefined && pathLength !== null ? pathLength : undefined;
+ basicConstraintsExtension = new x509.BasicConstraintsExtension(true, effectivePathLength, true);
+ }
+ } else {
+ basicConstraintsExtension = new x509.BasicConstraintsExtension(false);
+ }
+
const extensions: x509.Extension[] = [
- new x509.BasicConstraintsExtension(false),
+ basicConstraintsExtension,
await x509.AuthorityKeyIdentifierExtension.create(caCertObj, false),
await x509.SubjectKeyIdentifierExtension.create(csrObj.publicKey),
new x509.CRLDistributionPointsExtension([distributionPointUrl]),
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
index c13f85aa5f..4ef5e07537 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
@@ -121,6 +121,10 @@ export type TImportCertToCaDTO = {
certificateChain: string;
} & Omit<TProjectPermission, "projectId">;
+export type TCaSettings = {
+ maxPathLength?: number;
+} | null;
+
export type TIssueCertFromCaDTO = {
caId?: string;
certificateTemplateId?: string;
@@ -138,6 +142,13 @@ export type TIssueCertFromCaDTO = {
isFromProfile?: boolean;
profileId?: string;
internal?: boolean;
+ caSettings?: TCaSettings;
+ pathLength?: number | null;
+ organization?: string;
+ country?: string;
+ state?: string;
+ locality?: string;
+ ou?: string;
tx?: Knex;
} & Omit<TProjectPermission, "projectId">;
@@ -160,6 +171,8 @@ export type TSignCertFromCaDTO =
keyAlgorithm?: string;
isFromProfile?: boolean;
profileId?: string;
+ caSettings?: TCaSettings;
+ pathLength?: number | null;
tx?: Knex;
}
| ({
@@ -180,6 +193,8 @@ export type TSignCertFromCaDTO =
keyAlgorithm?: string;
isFromProfile?: boolean;
profileId?: string;
+ caSettings?: TCaSettings;
+ pathLength?: number | null;
tx?: Knex;
} & Omit<TProjectPermission, "projectId">);
diff --git a/backend/src/services/certificate-common/certificate-constants.ts b/backend/src/services/certificate-common/certificate-constants.ts
index ab1be0cc92..329617bf00 100644
--- a/backend/src/services/certificate-common/certificate-constants.ts
+++ b/backend/src/services/certificate-common/certificate-constants.ts
@@ -52,7 +52,10 @@ export enum CertDurationUnit {
export enum CertSubjectAttributeType {
COMMON_NAME = "common_name",
ORGANIZATION = "organization",
- COUNTRY = "country"
+ COUNTRY = "country",
+ STATE = "state",
+ LOCALITY = "locality",
+ ORGANIZATIONAL_UNIT = "organizational_unit"
}
export const mapKeyUsageToLegacy = (usage: CertKeyUsageType): string => {
diff --git a/backend/src/services/certificate-common/certificate-utils.ts b/backend/src/services/certificate-common/certificate-utils.ts
index 51754955f8..194febdb3a 100644
--- a/backend/src/services/certificate-common/certificate-utils.ts
+++ b/backend/src/services/certificate-common/certificate-utils.ts
@@ -61,7 +61,10 @@ export const buildCertificateSubjectFromTemplate = (
const attributeMap: Record<string, string> = {
common_name: "commonName",
organization: "organization",
- country: "country"
+ country: "country",
+ state: "state",
+ locality: "locality",
+ organizational_unit: "organizationalUnit"
};
if (!templateAttributes || templateAttributes.length === 0) {
diff --git a/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts b/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts
index b6408a986f..d725a05182 100644
--- a/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts
+++ b/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts
@@ -171,6 +171,15 @@ describe("CertificateEstV3Service Security Fix", () => {
validateCertificateRequest: vi.fn()
};
+ const mockCertificateTemplateV2DAL = {
+ findById: vi.fn().mockResolvedValue({
+ id: "template-v2-123",
+ caSettings: null,
+ subject: [],
+ sans: []
+ })
+ };
+
const mockCertificateAuthorityDAL = {
findById: vi.fn(),
findByIdWithAssociatedCa: vi.fn()
@@ -233,6 +242,7 @@ describe("CertificateEstV3Service Security Fix", () => {
service = certificateEstV3ServiceFactory({
internalCertificateAuthorityService: mockInternalCertificateAuthorityService,
certificateTemplateV2Service: mockCertificateTemplateV2Service,
+ certificateTemplateV2DAL: mockCertificateTemplateV2DAL,
certificateAuthorityDAL: mockCertificateAuthorityDAL,
certificateAuthorityCertDAL: mockCertificateAuthorityCertDAL,
projectDAL: mockProjectDAL,
@@ -525,7 +535,9 @@ describe("CertificateEstV3Service Security Fix", () => {
isInternal: true,
caId: "ca-123",
csr: basicCSR,
- isFromProfile: true
+ isFromProfile: true,
+ caSettings: null,
+ pathLength: undefined
});
});
@@ -704,7 +716,9 @@ describe("CertificateEstV3Service Security Fix", () => {
isInternal: true,
caId: "ca-123",
isFromProfile: true,
- csr: basicCSR
+ csr: basicCSR,
+ caSettings: null,
+ pathLength: undefined
});
});
diff --git a/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts b/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts
index 2499a18d20..b162d839a5 100644
--- a/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts
+++ b/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts
@@ -11,6 +11,7 @@ import { extractCertificateRequestFromCSR } from "@app/services/certificate-comm
import { mapEnumsForValidation } from "@app/services/certificate-common/certificate-utils";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
import { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types";
+import { TCertificateTemplateV2DALFactory } from "@app/services/certificate-template-v2/certificate-template-v2-dal";
import { TCertificateTemplateV2ServiceFactory } from "@app/services/certificate-template-v2/certificate-template-v2-service";
import { TEstEnrollmentConfigDALFactory } from "@app/services/enrollment-config/est-enrollment-config-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -23,6 +24,7 @@ import { TLicenseServiceFactory } from "../../ee/services/license/license-servic
type TCertificateEstV3ServiceFactoryDep = {
internalCertificateAuthorityService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa">;
certificateTemplateV2Service: Pick<TCertificateTemplateV2ServiceFactory, "validateCertificateRequest">;
+ certificateTemplateV2DAL: Pick<TCertificateTemplateV2DALFactory, "findById">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find" | "findById">;
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
@@ -37,6 +39,7 @@ export type TCertificateEstV3ServiceFactory = ReturnType<typeof certificateEstV3
export const certificateEstV3ServiceFactory = ({
internalCertificateAuthorityService,
certificateTemplateV2Service,
+ certificateTemplateV2DAL,
certificateAuthorityCertDAL,
certificateAuthorityDAL,
projectDAL,
@@ -143,11 +146,18 @@ export const certificateEstV3ServiceFactory = ({
});
}
+ // Fetch the template to get caSettings for CA certificate support
+ const template = await certificateTemplateV2DAL.findById(profile.certificateTemplateId);
+
const { certificate } = await internalCertificateAuthorityService.signCertFromCa({
isInternal: true,
caId: profile.caId,
csr,
- isFromProfile: true
+ isFromProfile: true,
+ // Pass CA settings from template (null for leaf certificates, object for CA certificates)
+ caSettings: template?.caSettings,
+ // Pass path length from profile (only applicable for CA certificates)
+ pathLength: profile.pathLength
});
return convertRawCertsToPkcs7([certificate.rawData]);
@@ -269,11 +279,18 @@ export const certificateEstV3ServiceFactory = ({
});
}
+ // Fetch the template to get caSettings for CA certificate support
+ const template = await certificateTemplateV2DAL.findById(profile.certificateTemplateId);
+
const { certificate } = await internalCertificateAuthorityService.signCertFromCa({
isInternal: true,
caId: profile.caId,
csr,
- isFromProfile: true
+ isFromProfile: true,
+ // Pass CA settings from template (null for leaf certificates, object for CA certificates)
+ caSettings: template?.caSettings,
+ // Pass path length from profile (only applicable for CA certificates)
+ pathLength: profile.pathLength
});
return convertRawCertsToPkcs7([certificate.rawData]);
diff --git a/backend/src/services/certificate-request/certificate-request-service.ts b/backend/src/services/certificate-request/certificate-request-service.ts
index b3e28028f6..1b5fcb9346 100644
--- a/backend/src/services/certificate-request/certificate-request-service.ts
+++ b/backend/src/services/certificate-request/certificate-request-service.ts
@@ -49,7 +49,13 @@ const certificateRequestDataSchema = z
keyAlgorithm: z.string().max(100).optional(),
signatureAlgorithm: z.string().max(100).optional(),
metadata: z.string().max(2000).optional(),
- certificateId: z.string().optional()
+ certificateId: z.string().optional(),
+ caSettings: z
+ .object({
+ isCA: z.boolean(),
+ pathLength: z.number().int().min(-1).optional()
+ })
+ .optional()
})
.refine(
(data) => {
diff --git a/backend/src/services/certificate-request/certificate-request-types.ts b/backend/src/services/certificate-request/certificate-request-types.ts
index 9b96515974..5ad685834b 100644
--- a/backend/src/services/certificate-request/certificate-request-types.ts
+++ b/backend/src/services/certificate-request/certificate-request-types.ts
@@ -22,6 +22,10 @@ export type TCreateCertificateRequestDTO = TProjectPermission & {
status: CertificateRequestStatus;
certificateId?: string;
acmeOrderId?: string;
+ caSettings?: {
+ isCA: boolean;
+ pathLength?: number;
+ };
};
export type TGetCertificateRequestDTO = TProjectPermission & {
diff --git a/backend/src/services/certificate-template-v2/certificate-template-v2-dal.ts b/backend/src/services/certificate-template-v2/certificate-template-v2-dal.ts
index 4951986b19..9e7fef563b 100644
--- a/backend/src/services/certificate-template-v2/certificate-template-v2-dal.ts
+++ b/backend/src/services/certificate-template-v2/certificate-template-v2-dal.ts
@@ -28,7 +28,7 @@ export const certificateTemplateV2DALFactory = (db: TDbClient) => {
const serializeJsonFields = (data: TCertificateTemplateV2Insert | TCertificateTemplateV2Update) => {
const serialized = { ...data } as Record<string, unknown>;
- const jsonFields = ["subject", "sans", "keyUsages", "extendedKeyUsages", "algorithms", "validity"];
+ const jsonFields = ["subject", "sans", "keyUsages", "extendedKeyUsages", "algorithms", "validity", "caSettings"];
jsonFields.forEach((field) => {
const value = serialized[field];
@@ -41,7 +41,7 @@ export const certificateTemplateV2DALFactory = (db: TDbClient) => {
};
const parseJsonFields = (raw: Record<string, unknown>): TCertificateTemplateV2 => {
- const jsonFields = ["subject", "sans", "keyUsages", "extendedKeyUsages", "algorithms", "validity"];
+ const jsonFields = ["subject", "sans", "keyUsages", "extendedKeyUsages", "algorithms", "validity", "caSettings"];
const parsed = { ...raw } as Record<string, unknown>;
jsonFields.forEach((field) => {
diff --git a/backend/src/services/certificate-template-v2/certificate-template-v2-schemas.ts b/backend/src/services/certificate-template-v2/certificate-template-v2-schemas.ts
index 9fcc51a574..1b8fe918bb 100644
--- a/backend/src/services/certificate-template-v2/certificate-template-v2-schemas.ts
+++ b/backend/src/services/certificate-template-v2/certificate-template-v2-schemas.ts
@@ -105,6 +105,16 @@ const templateV2AlgorithmsSchema = z.object({
.optional()
});
+export const templateV2CaSettingsSchema = z
+ .object({
+ maxPathLength: z
+ .number()
+ .int("Path length must be an integer")
+ .min(-1, "Path length must be -1 (unlimited) or a non-negative integer")
+ .optional()
+ })
+ .nullable();
+
export const certificateTemplateV2ResponseSchema = z.object({
id: z.string().uuid(),
projectId: z.string().uuid("Project ID must be valid"),
@@ -121,6 +131,7 @@ export const certificateTemplateV2ResponseSchema = z.object({
extendedKeyUsages: templateV2ExtendedKeyUsagesSchema.optional(),
algorithms: templateV2AlgorithmsSchema.optional(),
validity: templateV2ValiditySchema.optional(),
+ caSettings: templateV2CaSettingsSchema.optional(),
createdAt: z.date(),
updatedAt: z.date()
});
diff --git a/backend/src/services/certificate-template-v2/certificate-template-v2-types.ts b/backend/src/services/certificate-template-v2/certificate-template-v2-types.ts
index de2691d9a0..a20508f673 100644
--- a/backend/src/services/certificate-template-v2/certificate-template-v2-types.ts
+++ b/backend/src/services/certificate-template-v2/certificate-template-v2-types.ts
@@ -9,6 +9,10 @@ import {
CertSubjectAttributeType
} from "@app/services/certificate-common/certificate-constants";
+export interface TCaSettings {
+ maxPathLength?: number; // -1 = unlimited, 0+ = specific limit, undefined = not constrained
+}
+
export interface TTemplateV2Policy {
subject?: Array<{
type: CertSubjectAttributeType;
@@ -48,6 +52,7 @@ export type TCertificateTemplateV2 = TPkiCertificateTemplatesV2 & {
extendedKeyUsages?: TTemplateV2Policy["extendedKeyUsages"];
algorithms?: TTemplateV2Policy["algorithms"];
validity?: TTemplateV2Policy["validity"];
+ caSettings?: TCaSettings | null;
};
export type TCertificateTemplateV2Insert = TPkiCertificateTemplatesV2Insert & {
@@ -57,12 +62,21 @@ export type TCertificateTemplateV2Insert = TPkiCertificateTemplatesV2Insert & {
extendedKeyUsages?: TTemplateV2Policy["extendedKeyUsages"];
algorithms?: TTemplateV2Policy["algorithms"];
validity?: TTemplateV2Policy["validity"];
+ caSettings?: TCaSettings | null;
};
export type TCertificateTemplateV2Update = Partial<
Pick<
TCertificateTemplateV2,
- "name" | "description" | "subject" | "sans" | "keyUsages" | "extendedKeyUsages" | "algorithms" | "validity"
+ | "name"
+ | "description"
+ | "subject"
+ | "sans"
+ | "keyUsages"
+ | "extendedKeyUsages"
+ | "algorithms"
+ | "validity"
+ | "caSettings"
>
>;
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index fd46f2c5fd..d4fcd7e6d1 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -987,7 +987,8 @@ export const certificateV3ServiceFactory = ({
keyAlgorithm: effectiveKeyAlgorithm,
signatureAlgorithm: effectiveSignatureAlgorithm,
status: CertificateRequestStatus.ISSUED,
- certificateId: selfSignedResult.certificateData.id
+ certificateId: selfSignedResult.certificateData.id,
+ caSettings: certificateRequest.basicConstraints
});
return { ...selfSignedResult, certificateRequestId: certRequestResult.id };
@@ -1080,6 +1081,13 @@ export const certificateV3ServiceFactory = ({
actorAuthMethod,
actorOrgId,
isFromProfile: true,
+ caSettings: template.caSettings,
+ pathLength: profile.pathLength,
+ organization: certificateSubject.organization,
+ country: certificateSubject.country,
+ state: certificateSubject.state,
+ locality: certificateSubject.locality,
+ ou: certificateSubject.organizational_unit,
tx
});
@@ -1118,7 +1126,8 @@ export const certificateV3ServiceFactory = ({
keyAlgorithm: effectiveKeyAlgorithm,
signatureAlgorithm: effectiveSignatureAlgorithm,
status: CertificateRequestStatus.ISSUED,
- certificateId: certResult.certificateId
+ certificateId: certResult.certificateId,
+ caSettings: certificateRequest.basicConstraints
});
return { ...certResult, cert: certificateRecord, certificateRequestId: certRequestResult.id };
@@ -1171,7 +1180,8 @@ export const certificateV3ServiceFactory = ({
actorAuthMethod,
actorOrgId,
enrollmentType,
- removeRootsFromChain
+ removeRootsFromChain,
+ basicConstraints
}: TSignCertificateFromProfileDTO): Promise<Omit<TCertificateFromProfileResponse, "privateKey">> => {
const profile = await validateProfileAndPermissions(
profileId,
@@ -1250,6 +1260,8 @@ export const certificateV3ServiceFactory = ({
signatureAlgorithm: effectiveSignatureAlgorithm,
keyAlgorithm: effectiveKeyAlgorithm,
isFromProfile: true,
+ caSettings: template.caSettings,
+ pathLength: profile.pathLength,
tx
});
@@ -1289,7 +1301,8 @@ export const certificateV3ServiceFactory = ({
keyAlgorithm: effectiveKeyAlgorithm,
signatureAlgorithm: effectiveSignatureAlgorithm,
status: CertificateRequestStatus.ISSUED,
- certificateId: certResult.certificateId
+ certificateId: certResult.certificateId,
+ caSettings: basicConstraints
});
return { ...certResult, cert: signedCertRecord, certificateRequestId: certRequestResult.id };
@@ -1420,7 +1433,8 @@ export const certificateV3ServiceFactory = ({
altNames: certificateOrder.altNames?.map((san) => san.value).join(",") || "",
notBefore: certificateOrder.notBefore,
notAfter: certificateOrder.notAfter,
- status: CertificateRequestStatus.PENDING
+ status: CertificateRequestStatus.PENDING,
+ caSettings: certificateOrder.basicConstraints
});
await certificateIssuanceQueue.queueCertificateIssuance({
@@ -1674,6 +1688,8 @@ export const certificateV3ServiceFactory = ({
actorAuthMethod,
actorOrgId,
internal: true,
+ caSettings: template?.caSettings,
+ pathLength: profile?.pathLength,
tx
});
diff --git a/backend/src/services/certificate-v3/certificate-v3-types.ts b/backend/src/services/certificate-v3/certificate-v3-types.ts
index 50d7104067..87a209c1fa 100644
--- a/backend/src/services/certificate-v3/certificate-v3-types.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-types.ts
@@ -11,6 +11,11 @@ export type TIssueCertificateFromProfileDTO = {
profileId: string;
certificateRequest: {
commonName?: string;
+ organization?: string;
+ organizationalUnit?: string;
+ country?: string;
+ state?: string;
+ locality?: string;
keyUsages?: CertKeyUsageType[];
extendedKeyUsages?: CertExtendedKeyUsageType[];
altNames?: Array<{
@@ -24,6 +29,10 @@ export type TIssueCertificateFromProfileDTO = {
notAfter?: Date;
signatureAlgorithm?: string;
keyAlgorithm?: string;
+ basicConstraints?: {
+ isCA: boolean;
+ pathLength?: number;
+ };
};
removeRootsFromChain?: boolean;
} & Omit<TProjectPermission, "projectId">;
@@ -38,6 +47,10 @@ export type TSignCertificateFromProfileDTO = {
notAfter?: Date;
enrollmentType: EnrollmentType;
removeRootsFromChain?: boolean;
+ basicConstraints?: {
+ isCA: boolean;
+ pathLength?: number;
+ };
} & Omit<TProjectPermission, "projectId">;
export type TOrderCertificateFromProfileDTO = {
@@ -59,6 +72,10 @@ export type TOrderCertificateFromProfileDTO = {
keyAlgorithm?: string;
template?: string;
csr?: string;
+ basicConstraints?: {
+ isCA: boolean;
+ pathLength?: number;
+ };
};
removeRootsFromChain?: boolean;
} & Omit<TProjectPermission, "projectId">;
diff --git a/frontend/src/hooks/api/certificateTemplates/types.ts b/frontend/src/hooks/api/certificateTemplates/types.ts
index a6653cbec3..ec284576e3 100644
--- a/frontend/src/hooks/api/certificateTemplates/types.ts
+++ b/frontend/src/hooks/api/certificateTemplates/types.ts
@@ -122,9 +122,13 @@ export type TListCertificateTemplatesDTO = {
projectId: string;
};
+export type TCaSettings = {
+ maxPathLength?: number;
+} | null;
+
export type TCertificateTemplateV2Policy = {
subject?: Array<{
- type: "common_name" | "organization" | "country";
+ type: "common_name" | "organization" | "country" | "state" | "locality" | "organizational_unit";
allowed?: string[];
required?: string[];
denied?: string[];
@@ -154,6 +158,7 @@ export type TCertificateTemplateV2Policy = {
validity?: {
max?: string;
};
+ caSettings?: TCaSettings;
};
export type TCertificateTemplateV2WithPolicies = {
@@ -167,6 +172,7 @@ export type TCertificateTemplateV2WithPolicies = {
extendedKeyUsages?: TCertificateTemplateV2Policy["extendedKeyUsages"];
algorithms?: TCertificateTemplateV2Policy["algorithms"];
validity?: TCertificateTemplateV2Policy["validity"];
+ caSettings?: TCaSettings;
createdAt: string;
updatedAt: string;
};
@@ -181,6 +187,7 @@ export type TCreateCertificateTemplateV2WithPoliciesDTO = {
extendedKeyUsages?: TCertificateTemplateV2Policy["extendedKeyUsages"];
algorithms?: TCertificateTemplateV2Policy["algorithms"];
validity?: TCertificateTemplateV2Policy["validity"];
+ caSettings?: TCaSettings;
};
export type TUpdateCertificateTemplateV2WithPoliciesDTO = {
@@ -193,6 +200,7 @@ export type TUpdateCertificateTemplateV2WithPoliciesDTO = {
extendedKeyUsages?: TCertificateTemplateV2Policy["extendedKeyUsages"];
algorithms?: TCertificateTemplateV2Policy["algorithms"];
validity?: TCertificateTemplateV2Policy["validity"];
+ caSettings?: TCaSettings;
};
export type TDeleteCertificateTemplateV2WithPoliciesDTO = {
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
index fff9416817..fc99b57f52 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
@@ -8,7 +8,11 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import {
Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
Button,
+ Checkbox,
FormControl,
FormLabel,
Input,
@@ -25,13 +29,17 @@ import { CertExtendedKeyUsage, CertKeyUsage } from "@app/hooks/api/certificates/
import { useUnifiedCertificateIssuance } from "@app/hooks/api/certificates/mutations";
import { useGetCertificateTemplateV2ById } from "@app/hooks/api/certificateTemplates/queries";
import { UsePopUpState } from "@app/hooks/usePopUp";
-import { CertSubjectAlternativeNameType } from "@app/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/certificate-constants";
+import {
+ CertSubjectAlternativeNameType,
+ CertSubjectAttributeType
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/certificate-constants";
import { AlgorithmSelectors } from "./AlgorithmSelectors";
import { CertificateContent } from "./CertificateContent";
-import { filterUsages, formatSubjectAltNames, getAttributeValue } from "./certificateUtils";
+import { filterUsages, formatSubjectAltNames } from "./certificateUtils";
import { KeyUsageSection } from "./KeyUsageSection";
import { SubjectAltNamesField } from "./SubjectAltNamesField";
+import { SubjectAttributesField } from "./SubjectAttributesField";
import { useCertificateTemplate } from "./useCertificateTemplate";
const createSchema = (shouldShowSubjectSection: boolean) => {
@@ -41,7 +49,7 @@ const createSchema = (shouldShowSubjectSection: boolean) => {
? z
.array(
z.object({
- type: z.enum(["common_name"]),
+ type: z.nativeEnum(CertSubjectAttributeType),
value: z.string().min(1, "Value is required")
})
)
@@ -49,7 +57,7 @@ const createSchema = (shouldShowSubjectSection: boolean) => {
: z
.array(
z.object({
- type: z.enum(["common_name"]),
+ type: z.nativeEnum(CertSubjectAttributeType),
value: z.string().min(1, "Value is required")
})
)
@@ -62,6 +70,12 @@ const createSchema = (shouldShowSubjectSection: boolean) => {
})
)
.default([]),
+ basicConstraints: z
+ .object({
+ isCA: z.boolean().default(false),
+ pathLength: z.number().min(-1).nullable().optional()
+ })
+ .optional(),
ttl: z.string().trim().min(1, "TTL is required"),
signatureAlgorithm: z.string().min(1, "Signature algorithm is required"),
keyAlgorithm: z.string().min(1, "Key algorithm is required"),
@@ -147,6 +161,10 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
profileId: profileId || "",
subjectAttributes: [],
subjectAltNames: [],
+ basicConstraints: {
+ isCA: false,
+ pathLength: undefined
+ },
ttl: "30d",
signatureAlgorithm: "",
keyAlgorithm: "",
@@ -195,14 +213,16 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
useEffect(() => {
if (cert) {
- const subjectAttrs: Array<{ type: "common_name"; value: string }> = [];
+ const subjectAttrs: Array<{ type: CertSubjectAttributeType; value: string }> = [];
if (cert.commonName)
- subjectAttrs.push({ type: "common_name" as const, value: cert.commonName });
+ subjectAttrs.push({ type: CertSubjectAttributeType.COMMON_NAME, value: cert.commonName });
reset({
profileId: "",
subjectAttributes:
- subjectAttrs.length > 0 ? subjectAttrs : [{ type: "common_name" as const, value: "" }],
+ subjectAttrs.length > 0
+ ? subjectAttrs
+ : [{ type: CertSubjectAttributeType.COMMON_NAME, value: "" }],
subjectAltNames: cert.subjectAltNames
? cert.subjectAltNames.split(",").map((name) => {
const trimmed = name.trim();
@@ -237,6 +257,7 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
profileId: formProfileId,
subjectAttributes,
subjectAltNames,
+ basicConstraints,
ttl,
signatureAlgorithm,
keyAlgorithm,
@@ -259,22 +280,6 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
return;
}
- let commonName = "";
- if (
- constraints.shouldShowSubjectSection &&
- subjectAttributes &&
- subjectAttributes.length > 0
- ) {
- commonName = getAttributeValue(subjectAttributes, "common_name");
- if (!commonName.trim()) {
- createNotification({
- text: "Common name is required.",
- type: "error"
- });
- return;
- }
- }
-
try {
// Prepare unified request
const request: any = {
@@ -290,8 +295,52 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
}
};
- if (constraints.shouldShowSubjectSection && commonName) {
- request.attributes.commonName = commonName;
+ if (
+ constraints.shouldShowSubjectSection &&
+ subjectAttributes &&
+ subjectAttributes.length > 0
+ ) {
+ const cnAttr = subjectAttributes.find(
+ (attr) => attr.type === CertSubjectAttributeType.COMMON_NAME
+ );
+ if (cnAttr?.value) {
+ request.attributes.commonName = cnAttr.value;
+ }
+
+ const orgAttr = subjectAttributes.find(
+ (attr) => attr.type === CertSubjectAttributeType.ORGANIZATION
+ );
+ if (orgAttr?.value) {
+ request.attributes.organization = orgAttr.value;
+ }
+
+ const ouAttr = subjectAttributes.find(
+ (attr) => attr.type === CertSubjectAttributeType.ORGANIZATIONAL_UNIT
+ );
+ if (ouAttr?.value) {
+ request.attributes.organizationalUnit = ouAttr.value;
+ }
+
+ const countryAttr = subjectAttributes.find(
+ (attr) => attr.type === CertSubjectAttributeType.COUNTRY
+ );
+ if (countryAttr?.value) {
+ request.attributes.country = countryAttr.value;
+ }
+
+ const stateAttr = subjectAttributes.find(
+ (attr) => attr.type === CertSubjectAttributeType.STATE
+ );
+ if (stateAttr?.value) {
+ request.attributes.state = stateAttr.value;
+ }
+
+ const localityAttr = subjectAttributes.find(
+ (attr) => attr.type === CertSubjectAttributeType.LOCALITY
+ );
+ if (localityAttr?.value) {
+ request.attributes.locality = localityAttr.value;
+ }
}
if (constraints.shouldShowSanSection && subjectAltNames && subjectAltNames.length > 0) {
@@ -301,6 +350,13 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
}
}
+ if (constraints.templateAllowsCA && basicConstraints?.isCA) {
+ request.attributes.basicConstraints = {
+ isCA: true,
+ pathLength: basicConstraints.pathLength ?? undefined
+ };
+ }
+
const response = await issueCertificate(request);
// Handle certificate issuance response
@@ -338,9 +394,12 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
},
[
currentProject?.slug,
+ currentProject?.id,
issueCertificate,
constraints.shouldShowSubjectSection,
- constraints.shouldShowSanSection
+ constraints.shouldShowSanSection,
+ constraints.templateAllowsCA,
+ handlePopUpToggle
]
);
@@ -442,25 +501,10 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
{(actualSelectedProfile || profileId) && (
<>
{constraints.shouldShowSubjectSection && (
- <Controller
+ <SubjectAttributesField
control={control}
- name="subjectAttributes"
- render={({ field: { onChange, value }, fieldState: { error } }) => (
- <FormControl
- label="Common Name"
- isRequired
- errorText={error?.message}
- isError={Boolean(error)}
- >
- <Input
- value={value?.[0]?.value || ""}
- onChange={(e) => {
- onChange([{ type: "common_name", value: e.target.value }]);
- }}
- placeholder="example.com"
- />
- </FormControl>
- )}
+ allowedAttributeTypes={constraints.allowedSubjectAttributeTypes}
+ error={formState.errors.subjectAttributes?.message}
/>
)}
@@ -512,6 +556,105 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
options={filteredExtendedKeyUsages}
requiredUsages={constraints.requiredExtendedKeyUsages}
/>
+ {constraints.templateAllowsCA && (
+ <AccordionItem value="basic-constraints">
+ <AccordionTrigger>Basic Constraints</AccordionTrigger>
+ <AccordionContent>
+ <div className="space-y-4 pl-2">
+ <Controller
+ control={control}
+ name="basicConstraints.isCA"
+ render={({ field: { value, onChange } }) => (
+ <div className="flex items-center gap-3">
+ <Checkbox
+ id="isCA"
+ isChecked={value || false}
+ onCheckedChange={onChange}
+ />
+ <div className="space-y-1">
+ <FormLabel
+ id="isCA"
+ className="cursor-pointer text-sm font-medium text-mineshaft-100"
+ label="Request as Certificate Authority"
+ />
+ <p className="text-xs text-bunker-300">
+ This certificate will be created as a certificate authority.
+ </p>
+ </div>
+ </div>
+ )}
+ />
+
+ {watch("basicConstraints.isCA") && (
+ <Controller
+ control={control}
+ name="basicConstraints.pathLength"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label={
+ <div className="flex items-center gap-1">
+ <span className="mb-1">Path Length</span>
+ <Tooltip
+ content={
+ <div className="max-w-xs">
+ <p className="font-medium">Values:</p>
+ <ul className="mt-1 list-disc pl-4 text-xs">
+ <li>
+ <strong>-1</strong> = Unlimited depth
+ </li>
+ <li>
+ <strong>0</strong> = Can only sign end-entity certs
+ </li>
+ <li>
+ <strong>1+</strong> = CA levels allowed beneath
+ </li>
+ </ul>
+ </div>
+ }
+ >
+ <FontAwesomeIcon
+ icon={faQuestionCircle}
+ size="sm"
+ className="ml-1 text-mineshaft-400"
+ />
+ </Tooltip>
+ </div>
+ }
+ isError={Boolean(error)}
+ errorText={error?.message}
+ helperText={
+ constraints.maxPathLength !== undefined &&
+ constraints.maxPathLength !== null &&
+ constraints.maxPathLength !== -1
+ ? `Required. Template maximum: ${constraints.maxPathLength}`
+ : "Controls how many CA levels can exist below this certificate."
+ }
+ >
+ <Input
+ {...field}
+ type="number"
+ placeholder={
+ constraints.maxPathLength !== undefined &&
+ constraints.maxPathLength !== null &&
+ constraints.maxPathLength !== -1
+ ? "Enter path length (required)"
+ : "Leave empty for no constraint"
+ }
+ className="w-full"
+ value={field.value ?? ""}
+ onChange={(e) => {
+ const val = e.target.value;
+ field.onChange(val === "" ? undefined : Number(val));
+ }}
+ />
+ </FormControl>
+ )}
+ />
+ )}
+ </div>
+ </AccordionContent>
+ </AccordionItem>
+ )}
</Accordion>
</>
)}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
new file mode 100644
index 0000000000..4aaae72bea
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
@@ -0,0 +1,136 @@
+import { Control, Controller } from "react-hook-form";
+import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+
+import { Button, FormControl, IconButton, Input, Select, SelectItem } from "@app/components/v2";
+import { CertSubjectAttributeType } from "@app/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/certificate-constants";
+
+export type SubjectAttribute = {
+ type: CertSubjectAttributeType;
+ value: string;
+};
+
+const SUBJECT_ATTRIBUTE_LABELS: Record<CertSubjectAttributeType, string> = {
+ [CertSubjectAttributeType.COMMON_NAME]: "Common Name",
+ [CertSubjectAttributeType.ORGANIZATION]: "Organization",
+ [CertSubjectAttributeType.ORGANIZATIONAL_UNIT]: "Organizational Unit",
+ [CertSubjectAttributeType.COUNTRY]: "Country",
+ [CertSubjectAttributeType.STATE]: "State/Province",
+ [CertSubjectAttributeType.LOCALITY]: "Locality"
+};
+
+const getSubjectAttributePlaceholder = (type: CertSubjectAttributeType): string => {
+ switch (type) {
+ case CertSubjectAttributeType.COMMON_NAME:
+ return "example.com";
+ case CertSubjectAttributeType.ORGANIZATION:
+ return "Acme Inc.";
+ case CertSubjectAttributeType.ORGANIZATIONAL_UNIT:
+ return "Engineering";
+ case CertSubjectAttributeType.COUNTRY:
+ return "US";
+ case CertSubjectAttributeType.STATE:
+ return "California";
+ case CertSubjectAttributeType.LOCALITY:
+ return "San Francisco";
+ default:
+ return "";
+ }
+};
+
+type SubjectAttributesFieldProps = {
+ control: Control<any>;
+ allowedAttributeTypes: CertSubjectAttributeType[];
+ error?: string;
+};
+
+export const SubjectAttributesField = ({
+ control,
+ allowedAttributeTypes,
+ error
+}: SubjectAttributesFieldProps) => {
+ return (
+ <Controller
+ control={control}
+ name="subjectAttributes"
+ render={({ field: { onChange, value } }) => {
+ const currentValues = value || [];
+ const usedTypes = currentValues.map((attr: SubjectAttribute) => attr.type);
+ const availableTypes = allowedAttributeTypes.filter((type) => !usedTypes.includes(type));
+ const canAddMore = availableTypes.length > 0;
+
+ return (
+ <FormControl label="Subject Attributes" errorText={error} isError={Boolean(error)}>
+ <div className="space-y-2">
+ {currentValues.map((attr: SubjectAttribute, index: number) => {
+ const selectableTypes = allowedAttributeTypes.filter(
+ (type) => type === attr.type || !usedTypes.includes(type)
+ );
+
+ return (
+ // eslint-disable-next-line react/no-array-index-key
+ <div key={`subject-attr-${index}`} className="flex items-center gap-2">
+ <Select
+ value={attr.type}
+ onValueChange={(newType) => {
+ const newValue = [...currentValues];
+ newValue[index] = {
+ ...attr,
+ type: newType as CertSubjectAttributeType
+ };
+ onChange(newValue);
+ }}
+ className="w-44"
+ >
+ {selectableTypes.map((attrType) => (
+ <SelectItem key={attrType} value={attrType}>
+ {SUBJECT_ATTRIBUTE_LABELS[attrType]}
+ </SelectItem>
+ ))}
+ </Select>
+ <Input
+ value={attr.value}
+ onChange={(e) => {
+ const newValue = [...currentValues];
+ newValue[index] = { ...attr, value: e.target.value };
+ onChange(newValue);
+ }}
+ placeholder={getSubjectAttributePlaceholder(attr.type)}
+ className="flex-1"
+ />
+ <IconButton
+ ariaLabel="Remove attribute"
+ variant="plain"
+ size="sm"
+ onClick={() => {
+ const newValue = currentValues.filter((_: any, i: number) => i !== index);
+ onChange(newValue);
+ }}
+ >
+ <FontAwesomeIcon icon={faTrash} />
+ </IconButton>
+ </div>
+ );
+ })}
+ {canAddMore && (
+ <Button
+ type="button"
+ variant="outline_bg"
+ size="xs"
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={() => {
+ const nextType = availableTypes[0];
+ onChange([...currentValues, { type: nextType, value: "" }]);
+ }}
+ className="w-full"
+ >
+ Add Subject Attribute
+ </Button>
+ )}
+ </div>
+ </FormControl>
+ );
+ }}
+ />
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateTemplate.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateTemplate.ts
index 5499a2762c..61967af3be 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateTemplate.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateTemplate.ts
@@ -7,6 +7,7 @@ import {
} from "@app/hooks/api/certificates/constants";
import {
CertSubjectAlternativeNameType,
+ CertSubjectAttributeType,
mapTemplateKeyAlgorithmToApi,
mapTemplateSignatureAlgorithmToApi
} from "@app/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/certificate-constants";
@@ -39,8 +40,11 @@ export type TemplateConstraints = {
allowedSignatureAlgorithms: string[];
allowedKeyAlgorithms: string[];
allowedSanTypes: CertSubjectAlternativeNameType[];
+ allowedSubjectAttributeTypes: CertSubjectAttributeType[];
shouldShowSanSection: boolean;
shouldShowSubjectSection: boolean;
+ templateAllowsCA: boolean;
+ maxPathLength?: number;
};
export const useCertificateTemplate = (
@@ -63,8 +67,11 @@ export const useCertificateTemplate = (
CertSubjectAlternativeNameType.EMAIL,
CertSubjectAlternativeNameType.URI
],
+ allowedSubjectAttributeTypes: [CertSubjectAttributeType.COMMON_NAME],
shouldShowSanSection: true,
- shouldShowSubjectSection: true
+ shouldShowSubjectSection: true,
+ templateAllowsCA: false,
+ maxPathLength: undefined
});
const filteredKeyUsages = useMemo(() => {
@@ -111,13 +118,20 @@ export const useCertificateTemplate = (
CertSubjectAlternativeNameType.EMAIL,
CertSubjectAlternativeNameType.URI
],
+ allowedSubjectAttributeTypes: [CertSubjectAttributeType.COMMON_NAME],
shouldShowSanSection: true,
- shouldShowSubjectSection: true
+ shouldShowSubjectSection: true,
+ templateAllowsCA: false,
+ maxPathLength: undefined
});
};
useEffect(() => {
if (templateData && selectedProfile && isModalOpen) {
+ const templateAllowsCA =
+ templateData.caSettings !== undefined && templateData.caSettings !== null;
+ const maxPathLength = templateData.caSettings?.maxPathLength;
+
const newConstraints: TemplateConstraints = {
allowedSignatureAlgorithms: templateData.algorithms?.signature || [],
allowedKeyAlgorithms: templateData.algorithms?.keyAlgorithm || [],
@@ -132,8 +146,11 @@ export const useCertificateTemplate = (
requiredKeyUsages: templateData.keyUsages?.required || [],
requiredExtendedKeyUsages: templateData.extendedKeyUsages?.required || [],
allowedSanTypes: [],
+ allowedSubjectAttributeTypes: [],
shouldShowSanSection: true,
- shouldShowSubjectSection: true
+ shouldShowSubjectSection: true,
+ templateAllowsCA,
+ maxPathLength
};
// Set TTL if available
@@ -157,15 +174,25 @@ export const useCertificateTemplate = (
setValue("subjectAltNames", []);
}
- // Handle subject section
if (templateData.subject && templateData.subject.length > 0) {
newConstraints.shouldShowSubjectSection = true;
+ const subjectTypes: CertSubjectAttributeType[] = [];
+ templateData.subject.forEach((subjectPolicy: any) => {
+ if (!subjectTypes.includes(subjectPolicy.type)) {
+ subjectTypes.push(subjectPolicy.type as CertSubjectAttributeType);
+ }
+ });
+ newConstraints.allowedSubjectAttributeTypes =
+ subjectTypes.length > 0 ? subjectTypes : [CertSubjectAttributeType.COMMON_NAME];
+
const currentSubjectAttrs = watch("subjectAttributes");
if (!currentSubjectAttrs || currentSubjectAttrs.length === 0) {
- setValue("subjectAttributes", [{ type: "common_name", value: "" }]);
+ const defaultType = newConstraints.allowedSubjectAttributeTypes[0];
+ setValue("subjectAttributes", [{ type: defaultType, value: "" }]);
}
} else {
newConstraints.shouldShowSubjectSection = false;
+ newConstraints.allowedSubjectAttributeTypes = [];
setValue("subjectAttributes", undefined);
}
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CreateTemplateModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CreateTemplateModal.tsx
index 1da9e8ebe2..1fbf75cf63 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CreateTemplateModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/CreateTemplateModal.tsx
@@ -1,7 +1,7 @@
/* eslint-disable no-nested-ternary */
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
-import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons";
+import { faPlus, faQuestionCircle, faTrash } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -20,7 +20,8 @@ import {
ModalContent,
Select,
SelectItem,
- TextArea
+ TextArea,
+ Tooltip
} from "@app/components/v2";
import { useProject } from "@app/context";
import {
@@ -67,7 +68,12 @@ interface Props {
}
const ATTRIBUTE_TYPE_LABELS: Record<(typeof SUBJECT_ATTRIBUTE_TYPE_OPTIONS)[number], string> = {
- common_name: "Common Name (CN)"
+ common_name: "Common Name (CN)",
+ organization: "Organization (O)",
+ organizational_unit: "Organizational Unit (OU)",
+ country: "Country (C)",
+ state: "State/Province (ST)",
+ locality: "Locality (L)"
};
const SAN_TYPE_LABELS: Record<(typeof SAN_TYPE_OPTIONS)[number], string> = {
@@ -223,10 +229,16 @@ export const CreateTemplateModal = ({ isOpen, onClose, template, mode = "create"
defaultKeyType: ""
};
+ const basicConstraints = {
+ isCA: templateData.caSettings !== undefined && templateData.caSettings !== null,
+ maxPathLength: templateData.caSettings?.maxPathLength ?? undefined
+ };
+
return {
preset: TEMPLATE_PRESET_IDS.CUSTOM,
name: templateData.name || "",
description: templateData.description || "",
+ basicConstraints,
attributes,
subjectAlternativeNames,
keyUsages,
@@ -242,6 +254,10 @@ export const CreateTemplateModal = ({ isOpen, onClose, template, mode = "create"
preset: TEMPLATE_PRESET_IDS.CUSTOM,
name: "",
description: "",
+ basicConstraints: {
+ isCA: false,
+ maxPathLength: undefined
+ },
attributes: [],
keyUsages: { requiredUsages: [], optionalUsages: [] },
extendedKeyUsages: { requiredUsages: [], optionalUsages: [] },
@@ -450,6 +466,12 @@ export const CreateTemplateModal = ({ isOpen, onClose, template, mode = "create"
validity.max = `${data.validity.maxDuration.value}${unit}`;
}
+ const caSettings = data.basicConstraints?.isCA
+ ? {
+ maxPathLength: data.basicConstraints.maxPathLength ?? undefined
+ }
+ : null;
+
return {
name: data.name,
description: data.description,
@@ -458,7 +480,8 @@ export const CreateTemplateModal = ({ isOpen, onClose, template, mode = "create"
keyUsages,
extendedKeyUsages,
algorithms,
- validity
+ validity,
+ caSettings
};
};
@@ -660,6 +683,7 @@ export const CreateTemplateModal = ({ isOpen, onClose, template, mode = "create"
)}
/>
</div>
+
<AccordionItem value="attributes">
<AccordionTrigger>Subject Attributes</AccordionTrigger>
<AccordionContent>
@@ -1056,6 +1080,92 @@ export const CreateTemplateModal = ({ isOpen, onClose, template, mode = "create"
</div>
</AccordionContent>
</AccordionItem>
+
+ <AccordionItem value="basicConstraints" className="mt-4">
+ <AccordionTrigger>CA Settings</AccordionTrigger>
+ <AccordionContent>
+ <div className="space-y-4">
+ <Controller
+ control={control}
+ name="basicConstraints.isCA"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl isError={Boolean(error)} errorText={error?.message}>
+ <div className="flex items-center gap-3">
+ <Checkbox
+ id="isCA"
+ isChecked={value || false}
+ onCheckedChange={onChange}
+ />
+ <div className="space-y-1">
+ <span className="text-sm font-medium text-mineshaft-100">
+ Allow Certificate Authority Issuance
+ </span>
+ <p className="text-xs text-bunker-300">
+ Enable this to allow issuing intermediate CA certificates.
+ </p>
+ </div>
+ </div>
+ </FormControl>
+ )}
+ />
+
+ {watch("basicConstraints.isCA") && (
+ <Controller
+ control={control}
+ name="basicConstraints.maxPathLength"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label={
+ <div className="flex items-center gap-1">
+ <span className="mb-1">Max Path Length</span>
+ <Tooltip
+ content={
+ <div className="max-w-xs">
+ <p className="font-medium">Values:</p>
+ <ul className="mt-1 list-disc pl-4 text-xs">
+ <li>
+ <strong>-1</strong> = Unlimited (no restriction)
+ </li>
+ <li>
+ <strong>0</strong> = Can only sign end-entity certificates
+ </li>
+ <li>
+ <strong>1+</strong> = Number of CA levels allowed beneath
+ </li>
+ </ul>
+ </div>
+ }
+ >
+ <FontAwesomeIcon
+ icon={faQuestionCircle}
+ size="sm"
+ className="ml-1 text-mineshaft-400"
+ />
+ </Tooltip>
+ </div>
+ }
+ isError={Boolean(error)}
+ errorText={error?.message}
+ helperText="Controls how many levels of CA certificates can be created below certificates issued from this template."
+ >
+ <Input
+ {...field}
+ type="number"
+ placeholder="Leave empty for no constraint"
+ className="w-full"
+ value={field.value ?? ""}
+ onChange={(e) => {
+ const val = e.target.value;
+ field.onChange(val === "" ? undefined : Number(val));
+ }}
+ />
+ </FormControl>
+ )}
+ />
+ )}
+ </div>
+ </AccordionContent>
+ </AccordionItem>
</Accordion>
<div className="flex gap-3">
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/certificate-constants.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/certificate-constants.ts
index 47fdcd5a2a..649bddb120 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/certificate-constants.ts
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/certificate-constants.ts
@@ -45,7 +45,12 @@ export enum CertDurationUnit {
}
export enum CertSubjectAttributeType {
- COMMON_NAME = "common_name"
+ COMMON_NAME = "common_name",
+ ORGANIZATION = "organization",
+ ORGANIZATIONAL_UNIT = "organizational_unit",
+ COUNTRY = "country",
+ STATE = "state",
+ LOCALITY = "locality"
}
export const formatSANType = (type: CertSubjectAlternativeNameType): string => {
@@ -111,6 +116,16 @@ export const formatSubjectAttributeType = (type: CertSubjectAttributeType): stri
switch (type) {
case CertSubjectAttributeType.COMMON_NAME:
return "Common Name (CN)";
+ case CertSubjectAttributeType.ORGANIZATION:
+ return "Organization (O)";
+ case CertSubjectAttributeType.ORGANIZATIONAL_UNIT:
+ return "Organizational Unit (OU)";
+ case CertSubjectAttributeType.COUNTRY:
+ return "Country (C)";
+ case CertSubjectAttributeType.STATE:
+ return "State/Province (ST)";
+ case CertSubjectAttributeType.LOCALITY:
+ return "Locality (L)";
default:
return type;
}
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/schemas.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/schemas.ts
index 137ca262c6..f5df667645 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/schemas.ts
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/schemas.ts
@@ -52,6 +52,15 @@ export const uiKeyAlgorithmSchema = z.object({
.min(1, "At least one key type must be selected")
});
+export const uiBasicConstraintsSchema = z.object({
+ isCA: z.boolean().default(false),
+ maxPathLength: z
+ .number()
+ .min(-1, "Path length must be -1 (unlimited) or greater")
+ .nullable()
+ .optional()
+});
+
export const uiPresetSchema = z
.enum([
TEMPLATE_PRESET_IDS.CUSTOM,
@@ -81,6 +90,7 @@ export const templateSchema = z.object({
.trim()
.max(1000, "Description must be less than 1000 characters")
.optional(),
+ basicConstraints: uiBasicConstraintsSchema.optional(),
attributes: z.array(uiAttributeSchema).optional(),
subjectAlternativeNames: z.array(uiSanSchema).optional(),
keyUsages: uiKeyUsagesSchema.optional(),