Skip to content

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

feat(pki): expand certificate profile defaults beyond TTL (#5493)

Saif Ur Rahman132782152189
diff --git a/backend/src/db/migrations/20260216110404_add-defaults-to-certificate-profiles.ts b/backend/src/db/migrations/20260216110404_add-defaults-to-certificate-profiles.ts
new file mode 100644
index 0000000000..4e30e3ece7
--- /dev/null
+++ b/backend/src/db/migrations/20260216110404_add-defaults-to-certificate-profiles.ts
@@ -0,0 +1,61 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasDefaultsCol = await knex.schema.hasColumn(TableName.PkiCertificateProfile, "defaults");
+ if (!hasDefaultsCol) {
+ await knex.schema.alterTable(TableName.PkiCertificateProfile, (t) => {
+ t.jsonb("defaults").nullable();
+ });
+ }
+
+ const hasDefaultTtlDaysCol = await knex.schema.hasColumn(TableName.PkiCertificateProfile, "defaultTtlDays");
+ if (hasDefaultTtlDaysCol) {
+ const profilesWithTtl = await knex(TableName.PkiCertificateProfile).whereNotNull("defaultTtlDays");
+ for await (const profile of profilesWithTtl) {
+ await knex(TableName.PkiCertificateProfile)
+ .where("id", profile.id)
+ .update({
+ defaults: JSON.stringify({ ttlDays: (profile as Record<string, unknown>).defaultTtlDays })
+ });
+ }
+
+ await knex.schema.alterTable(TableName.PkiCertificateProfile, (t) => {
+ t.dropColumn("defaultTtlDays");
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasDefaultTtlDaysCol = await knex.schema.hasColumn(TableName.PkiCertificateProfile, "defaultTtlDays");
+ if (!hasDefaultTtlDaysCol) {
+ await knex.schema.alterTable(TableName.PkiCertificateProfile, (t) => {
+ t.integer("defaultTtlDays").nullable();
+ });
+ }
+
+ // Extract ttlDays from defaults JSON back into defaultTtlDays
+ const hasDefaultsCol = await knex.schema.hasColumn(TableName.PkiCertificateProfile, "defaults");
+ if (hasDefaultsCol) {
+ const profilesWithDefaults = await knex(TableName.PkiCertificateProfile).whereNotNull("defaults");
+ for await (const profile of profilesWithDefaults) {
+ try {
+ const defaults = JSON.parse(profile.defaults as string);
+ if (defaults.ttlDays) {
+ await knex(TableName.PkiCertificateProfile)
+ .where("id", profile.id)
+ .update({
+ defaultTtlDays: defaults.ttlDays
+ } as Record<string, unknown>);
+ }
+ } catch {
+ // skip malformed JSON
+ }
+ }
+
+ await knex.schema.alterTable(TableName.PkiCertificateProfile, (t) => {
+ t.dropColumn("defaults");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/pki-certificate-profiles.ts b/backend/src/db/schemas/pki-certificate-profiles.ts
index a40d1e6043..7923b346ef 100644
--- a/backend/src/db/schemas/pki-certificate-profiles.ts
+++ b/backend/src/db/schemas/pki-certificate-profiles.ts
@@ -22,7 +22,7 @@ export const PkiCertificateProfilesSchema = z.object({
acmeConfigId: z.string().uuid().nullable().optional(),
issuerType: z.string().default("ca"),
externalConfigs: z.string().nullable().optional(),
- defaultTtlDays: z.number().nullable().optional()
+ defaults: z.unknown().nullable().optional()
});
export type TPkiCertificateProfiles = z.infer<typeof PkiCertificateProfilesSchema>;
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.ts
index 9ec1a2c498..b4ae75fce2 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts
@@ -850,7 +850,7 @@ export const pkiAcmeServiceFactory = ({
? {
ttl: resolveEffectiveTtl({
requestTtl: undefined,
- profileDefaultTtlDays: profile.defaultTtlDays,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
policyMaxValidity: internalPolicy?.validity?.max,
flowDefaultTtl: "47d"
})
@@ -890,7 +890,7 @@ export const pkiAcmeServiceFactory = ({
: {
ttl: resolveEffectiveTtl({
requestTtl: certificateRequest.validity?.ttl,
- profileDefaultTtlDays: profile.defaultTtlDays,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
policyMaxValidity: policy?.validity?.max,
flowDefaultTtl: "47d"
})
@@ -1061,7 +1061,7 @@ export const pkiAcmeServiceFactory = ({
})()
: resolveEffectiveTtl({
requestTtl: undefined,
- profileDefaultTtlDays: profile.defaultTtlDays,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
policyMaxValidity: policy?.validity?.max,
flowDefaultTtl: "47d"
});
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 777067d05f..6b83eead89 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1296,6 +1296,7 @@ export const registerRoutes = async (
const certificateProfileService = certificateProfileServiceFactory({
certificateProfileDAL,
certificatePolicyDAL,
+ certificatePolicyService,
apiEnrollmentConfigDAL,
estEnrollmentConfigDAL,
acmeEnrollmentConfigDAL,
diff --git a/backend/src/server/routes/v1/certificate-profiles-router.ts b/backend/src/server/routes/v1/certificate-profiles-router.ts
index aaa7ad49c2..c510f4aac9 100644
--- a/backend/src/server/routes/v1/certificate-profiles-router.ts
+++ b/backend/src/server/routes/v1/certificate-profiles-router.ts
@@ -8,9 +8,37 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
import { CertStatus } from "@app/services/certificate/certificate-types";
+import {
+ CertExtendedKeyUsageType,
+ CertKeyAlgorithm,
+ CertKeyUsageType,
+ CertSignatureAlgorithm
+} from "@app/services/certificate-common/certificate-constants";
import { ExternalConfigUnionSchema } from "@app/services/certificate-profile/certificate-profile-external-config-schemas";
import { EnrollmentType, IssuerType } from "@app/services/certificate-profile/certificate-profile-types";
+const CertificateProfileDefaultsResponseSchema = z
+ .object({
+ ttlDays: z.number().optional(),
+ commonName: z.string().optional(),
+ keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional(),
+ signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(),
+ keyUsages: z.array(z.nativeEnum(CertKeyUsageType)).optional(),
+ extendedKeyUsages: z.array(z.nativeEnum(CertExtendedKeyUsageType)).optional(),
+ basicConstraints: z
+ .object({
+ isCA: z.boolean(),
+ pathLength: z.number().optional()
+ })
+ .optional(),
+ organization: z.string().optional(),
+ organizationalUnit: z.string().optional(),
+ country: z.string().optional(),
+ state: z.string().optional(),
+ locality: z.string().optional()
+ })
+ .nullish();
+
export const registerCertificateProfilesRouter = async (
server: FastifyZodProvider,
enableOperationId: boolean = true
@@ -58,7 +86,27 @@ export const registerCertificateProfilesRouter = async (
})
.optional(),
externalConfigs: ExternalConfigUnionSchema,
- defaultTtlDays: z.number().int().positive().optional()
+ defaults: z
+ .object({
+ ttlDays: z.number().int().positive().optional(),
+ commonName: z.string().optional(),
+ keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional(),
+ signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(),
+ keyUsages: z.array(z.nativeEnum(CertKeyUsageType)).optional(),
+ extendedKeyUsages: z.array(z.nativeEnum(CertExtendedKeyUsageType)).optional(),
+ basicConstraints: z
+ .object({
+ isCA: z.boolean(),
+ pathLength: z.number().int().min(0).optional()
+ })
+ .optional(),
+ organization: z.string().optional(),
+ organizationalUnit: z.string().optional(),
+ country: z.string().optional(),
+ state: z.string().optional(),
+ locality: z.string().optional()
+ })
+ .nullish()
})
.refine(
(data) => {
@@ -173,7 +221,8 @@ export const registerCertificateProfilesRouter = async (
response: {
200: z.object({
certificateProfile: PkiCertificateProfilesSchema.extend({
- externalConfigs: ExternalConfigUnionSchema
+ externalConfigs: ExternalConfigUnionSchema,
+ defaults: CertificateProfileDefaultsResponseSchema
})
})
}
@@ -272,7 +321,8 @@ export const registerCertificateProfilesRouter = async (
skipEabBinding: z.boolean().optional()
})
.optional(),
- externalConfigs: ExternalConfigUnionSchema
+ externalConfigs: ExternalConfigUnionSchema,
+ defaults: CertificateProfileDefaultsResponseSchema
}).array(),
totalCount: z.number()
})
@@ -319,7 +369,8 @@ export const registerCertificateProfilesRouter = async (
response: {
200: z.object({
certificateProfile: PkiCertificateProfilesSchema.extend({
- externalConfigs: ExternalConfigUnionSchema
+ externalConfigs: ExternalConfigUnionSchema,
+ defaults: CertificateProfileDefaultsResponseSchema
}).extend({
certificateAuthority: z
.object({
@@ -412,7 +463,8 @@ export const registerCertificateProfilesRouter = async (
response: {
200: z.object({
certificateProfile: PkiCertificateProfilesSchema.extend({
- externalConfigs: ExternalConfigUnionSchema
+ externalConfigs: ExternalConfigUnionSchema,
+ defaults: CertificateProfileDefaultsResponseSchema
})
})
}
@@ -476,7 +528,27 @@ export const registerCertificateProfilesRouter = async (
})
.optional(),
externalConfigs: ExternalConfigUnionSchema,
- defaultTtlDays: z.number().int().positive().nullable().optional()
+ defaults: z
+ .object({
+ ttlDays: z.number().int().positive().optional(),
+ commonName: z.string().optional(),
+ keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional(),
+ signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(),
+ keyUsages: z.array(z.nativeEnum(CertKeyUsageType)).optional(),
+ extendedKeyUsages: z.array(z.nativeEnum(CertExtendedKeyUsageType)).optional(),
+ basicConstraints: z
+ .object({
+ isCA: z.boolean(),
+ pathLength: z.number().int().min(0).optional()
+ })
+ .optional(),
+ organization: z.string().optional(),
+ organizationalUnit: z.string().optional(),
+ country: z.string().optional(),
+ state: z.string().optional(),
+ locality: z.string().optional()
+ })
+ .nullish()
})
.refine(
(data) => {
@@ -510,7 +582,8 @@ export const registerCertificateProfilesRouter = async (
response: {
200: z.object({
certificateProfile: PkiCertificateProfilesSchema.extend({
- externalConfigs: ExternalConfigUnionSchema
+ externalConfigs: ExternalConfigUnionSchema,
+ defaults: CertificateProfileDefaultsResponseSchema
})
})
}
@@ -558,7 +631,8 @@ export const registerCertificateProfilesRouter = async (
response: {
200: z.object({
certificateProfile: PkiCertificateProfilesSchema.extend({
- externalConfigs: ExternalConfigUnionSchema
+ externalConfigs: ExternalConfigUnionSchema,
+ defaults: CertificateProfileDefaultsResponseSchema
})
})
}
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index f7f001d2aa..095eb0656d 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -131,12 +131,12 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
.optional(),
attributes: z
.object({
- commonName: validateTemplateRegexField.optional(),
- organization: validateTemplateRegexField.optional(),
- organizationalUnit: validateTemplateRegexField.optional(),
- country: validateTemplateRegexField.optional(),
- state: validateTemplateRegexField.optional(),
- locality: validateTemplateRegexField.optional(),
+ commonName: validateTemplateRegexField.nullish(),
+ organization: validateTemplateRegexField.nullish(),
+ organizationalUnit: validateTemplateRegexField.nullish(),
+ country: validateTemplateRegexField.nullish(),
+ state: validateTemplateRegexField.nullish(),
+ locality: validateTemplateRegexField.nullish(),
keyUsages: z.nativeEnum(CertKeyUsageType).array().optional(),
extendedKeyUsages: z.nativeEnum(CertExtendedKeyUsageType).array().optional(),
altNames: z
@@ -220,7 +220,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
const certificateOrderObject = {
altNames: attributes?.altNames || [],
validity: { ttl: attributes?.ttl || "" },
- commonName: attributes?.commonName,
+ ...(attributes?.commonName !== undefined && { commonName: attributes.commonName ?? undefined }),
keyUsages: attributes?.keyUsages,
extendedKeyUsages: attributes?.extendedKeyUsages,
notBefore: attributes?.notBefore ? new Date(attributes.notBefore) : undefined,
@@ -301,12 +301,6 @@ 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,
@@ -318,6 +312,23 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
basicConstraints: attributes?.basicConstraints
};
+ // Only include subject fields when explicitly provided (null or string).
+ // Omitting the key lets applyProfileDefaults use the profile default.
+ // Sending null (converted to undefined here) signals "clear the default".
+ const subjectFields = [
+ "commonName",
+ "organization",
+ "organizationalUnit",
+ "country",
+ "state",
+ "locality"
+ ] as const;
+ for (const field of subjectFields) {
+ if (attributes?.[field] !== undefined) {
+ certificateRequestForService[field] = attributes[field] ?? undefined;
+ }
+ }
+
const mappedCertificateRequest = mapEnumsForValidation(certificateRequestForService);
const data = await server.services.certificateV3.issueCertificateFromProfile({
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 c8b2b89a69..e4ea4826d9 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
@@ -1882,6 +1882,7 @@ export const internalCertificateAuthorityServiceFactory = ({
keyAlgorithm,
basicConstraints,
pathLength,
+ subjectOverride,
tx
} = dto;
@@ -2192,7 +2193,7 @@ export const internalCertificateAuthorityServiceFactory = ({
const serialNumber = createSerialNumber();
const leafCert = await x509.X509CertificateGenerator.create({
serialNumber,
- subject: csrObj.subject,
+ subject: subjectOverride || csrObj.subject,
issuer: caCertObj.subject,
notBefore: notBeforeDate,
notAfter: notAfterDate,
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 957812075f..5d345b8cc8 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
@@ -233,6 +233,7 @@ export type TSignCertFromCaDTO =
profileId?: string;
basicConstraints?: TBasicConstraints;
pathLength?: number | null;
+ subjectOverride?: string;
tx?: Knex;
}
| ({
@@ -255,6 +256,7 @@ export type TSignCertFromCaDTO =
profileId?: string;
basicConstraints?: TBasicConstraints;
pathLength?: number | null;
+ subjectOverride?: string;
tx?: Knex;
} & Omit<TProjectPermission, "projectId">);
diff --git a/backend/src/services/certificate-common/certificate-csr-utils.ts b/backend/src/services/certificate-common/certificate-csr-utils.ts
index b3286dc342..180a76cca1 100644
--- a/backend/src/services/certificate-common/certificate-csr-utils.ts
+++ b/backend/src/services/certificate-common/certificate-csr-utils.ts
@@ -40,7 +40,10 @@ export const extractCertificateRequestFromCSR = (csr: string): TCertificateReque
// eslint-disable-next-line no-bitwise
(keyUsage) => (x509.KeyUsageFlags[keyUsage] & csrKeyUsageExtension.usages) !== 0
);
- certificateRequest.keyUsages = csrKeyUsages.map(mapLegacyKeyUsageToStandard);
+ const mapped = csrKeyUsages.map(mapLegacyKeyUsageToStandard);
+ if (mapped.length > 0) {
+ certificateRequest.keyUsages = mapped;
+ }
}
const csrExtendedKeyUsageExtension = csrObj.getExtension("2.5.29.37") as x509.ExtendedKeyUsageExtension;
@@ -48,7 +51,10 @@ export const extractCertificateRequestFromCSR = (csr: string): TCertificateReque
const csrExtendedKeyUsages = csrExtendedKeyUsageExtension.usages.map(
(ekuOid) => CertExtendedKeyUsageOIDToName[ekuOid as string]
);
- certificateRequest.extendedKeyUsages = csrExtendedKeyUsages.map(mapLegacyExtendedKeyUsageToStandard);
+ const mapped = csrExtendedKeyUsages.map(mapLegacyExtendedKeyUsageToStandard);
+ if (mapped.length > 0) {
+ certificateRequest.extendedKeyUsages = mapped;
+ }
}
const sanExtension = csrObj.extensions.find((ext) => ext.type === "2.5.29.17");
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 2910647cc1..e3b6edae30 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
@@ -143,7 +143,7 @@ export const certificateEstV3ServiceFactory = ({
const policy = await certificatePolicyDAL.findById(profile.certificatePolicyId);
const ttl = resolveEffectiveTtl({
requestTtl: undefined, // EST doesn't accept TTL in request
- profileDefaultTtlDays: profile.defaultTtlDays,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
policyMaxValidity: policy?.validity?.max,
flowDefaultTtl: "90d"
});
@@ -279,7 +279,7 @@ export const certificateEstV3ServiceFactory = ({
const policy = await certificatePolicyDAL.findById(profile.certificatePolicyId);
const ttl = resolveEffectiveTtl({
requestTtl: undefined, // EST doesn't accept TTL in request
- profileDefaultTtlDays: profile.defaultTtlDays,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
policyMaxValidity: policy?.validity?.max,
flowDefaultTtl: "90d"
});
diff --git a/backend/src/services/certificate-policy/certificate-policy-service.ts b/backend/src/services/certificate-policy/certificate-policy-service.ts
index fed6db0242..fbb277ee3f 100644
--- a/backend/src/services/certificate-policy/certificate-policy-service.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-service.ts
@@ -303,7 +303,8 @@ export const certificatePolicyServiceFactory = ({
const validateRequestAgainstPolicy = (
template: TCertificatePolicy,
- request: TCertificateRequest
+ request: TCertificateRequest,
+ options?: { skipRequired?: boolean }
): TPolicyValidationResult => {
const errors: string[] = [];
const warnings: string[] = [];
@@ -315,13 +316,17 @@ export const certificatePolicyServiceFactory = ({
if (request.organization) {
requestAttributes.set(CertSubjectAttributeType.ORGANIZATION, request.organization);
}
+ if (request.organizationalUnit)
+ requestAttributes.set(CertSubjectAttributeType.ORGANIZATIONAL_UNIT, request.organizationalUnit);
if (request.country) requestAttributes.set(CertSubjectAttributeType.COUNTRY, request.country);
+ if (request.state) requestAttributes.set(CertSubjectAttributeType.STATE, request.state);
+ if (request.locality) requestAttributes.set(CertSubjectAttributeType.LOCALITY, request.locality);
if (subjectPolicies && subjectPolicies.length > 0) {
for (const attrPolicy of subjectPolicies) {
const requestValue = requestAttributes.get(attrPolicy.type);
- if (attrPolicy.required && attrPolicy.required.length > 0) {
+ if (!options?.skipRequired && attrPolicy.required && attrPolicy.required.length > 0) {
if (!requestValue) {
errors.push(`Missing required ${attrPolicy.type} attribute`);
} else {
@@ -405,7 +410,7 @@ export const certificatePolicyServiceFactory = ({
const requestSans = requestSansByType.get(sanPolicy.type) || [];
// Check REQUIRED values - at least one SAN must match each required pattern
- if (sanPolicy.required && sanPolicy.required.length > 0) {
+ if (!options?.skipRequired && sanPolicy.required && sanPolicy.required.length > 0) {
for (const requiredValue of sanPolicy.required) {
const hasMatchingRequiredSan = requestSans.some((sanValue) => {
const validation = validateValueAgainstConstraints(sanValue, [requiredValue], `${sanPolicy.type} SAN`);
@@ -467,7 +472,7 @@ export const certificatePolicyServiceFactory = ({
const keyUsagePolicy = template.keyUsages;
if (keyUsagePolicy) {
// Check REQUIRED key usages - must have all required usages
- if (keyUsagePolicy.required && keyUsagePolicy.required.length > 0) {
+ if (!options?.skipRequired && keyUsagePolicy.required && keyUsagePolicy.required.length > 0) {
const missingRequired = keyUsagePolicy.required.filter((usage) => !request.keyUsages?.includes(usage));
if (missingRequired.length > 0) {
errors.push(`Missing required key usages: ${missingRequired.join(", ")}`);
@@ -498,7 +503,7 @@ export const certificatePolicyServiceFactory = ({
const extendedKeyUsagePolicy = template.extendedKeyUsages;
if (extendedKeyUsagePolicy) {
// Check REQUIRED extended key usages - must have all required usages
- if (extendedKeyUsagePolicy.required && extendedKeyUsagePolicy.required.length > 0) {
+ if (!options?.skipRequired && extendedKeyUsagePolicy.required && extendedKeyUsagePolicy.required.length > 0) {
const missingRequired = extendedKeyUsagePolicy.required.filter(
(usage) => !request.extendedKeyUsages?.includes(usage)
);
@@ -611,7 +616,7 @@ export const certificatePolicyServiceFactory = ({
"CA certificate issuance is denied by this policy. The policy does not allow issuing CA certificates."
);
}
- } else if (isCaPolicy === CertPolicyState.REQUIRED) {
+ } else if (!options?.skipRequired && isCaPolicy === CertPolicyState.REQUIRED) {
if (!requestWantsCA) {
errors.push(
"CA certificate issuance is required by this policy. The request must include basicConstraints with isCA set to true."
@@ -1000,7 +1005,8 @@ export const certificatePolicyServiceFactory = ({
getPolicyBySlug,
listPolicies,
deletePolicy,
- validateCertificateRequest
+ validateCertificateRequest,
+ validateRequestAgainstPolicy
};
};
diff --git a/backend/src/services/certificate-profile/certificate-profile-dal.ts b/backend/src/services/certificate-profile/certificate-profile-dal.ts
index ef48a2c294..3e58a154c0 100644
--- a/backend/src/services/certificate-profile/certificate-profile-dal.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-dal.ts
@@ -14,6 +14,7 @@ import {
IssuerType,
TCertificateProfile,
TCertificateProfileCertificate,
+ TCertificateProfileDefaults,
TCertificateProfileInsert,
TCertificateProfileUpdate,
TCertificateProfileWithConfigs
@@ -28,7 +29,8 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
try {
const dataToInsert = {
...data,
- externalConfigs: data.externalConfigs ? JSON.stringify(data.externalConfigs) : null
+ externalConfigs: data.externalConfigs ? JSON.stringify(data.externalConfigs) : null,
+ defaults: data.defaults ? JSON.stringify(data.defaults) : null
};
const [insertedProfile] = await (tx || db)(TableName.PkiCertificateProfile).insert(dataToInsert).returning("*");
@@ -37,7 +39,8 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
...insertedProfile,
externalConfigs: insertedProfile.externalConfigs
? (JSON.parse(insertedProfile.externalConfigs) as Record<string, unknown>)
- : null
+ : null,
+ defaults: (insertedProfile.defaults as TCertificateProfileDefaults) ?? null
} as TCertificateProfile;
} catch (error) {
throw new DatabaseError({ error, name: "Create certificate profile" });
@@ -54,6 +57,10 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
dataToUpdate.externalConfigs = data.externalConfigs ? JSON.stringify(data.externalConfigs) : null;
}
+ if (data.defaults !== undefined) {
+ dataToUpdate.defaults = data.defaults ? JSON.stringify(data.defaults) : null;
+ }
+
const [updatedProfile] = await (tx || db)(TableName.PkiCertificateProfile)
.where({ id })
.update(dataToUpdate)
@@ -63,7 +70,8 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
...updatedProfile,
externalConfigs: updatedProfile.externalConfigs
? (JSON.parse(updatedProfile.externalConfigs) as Record<string, unknown>)
- : null
+ : null,
+ defaults: (updatedProfile.defaults as TCertificateProfileDefaults) ?? null
} as TCertificateProfile;
} catch (error) {
throw new DatabaseError({ error, name: "Update certificate profile" });
@@ -92,7 +100,8 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
...certificateProfile,
externalConfigs: certificateProfile.externalConfigs
? (JSON.parse(certificateProfile.externalConfigs) as Record<string, unknown>)
- : null
+ : null,
+ defaults: (certificateProfile.defaults as TCertificateProfileDefaults) ?? null
} as TCertificateProfile;
} catch (error) {
throw new DatabaseError({ error, name: "Find certificate profile by id" });
@@ -257,9 +266,9 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
externalConfigs: result.externalConfigs
? (JSON.parse(result.externalConfigs) as Record<string, unknown>)
: null,
+ defaults: (result.defaults as TCertificateProfileDefaults) ?? null,
createdAt: result.createdAt,
updatedAt: result.updatedAt,
- defaultTtlDays: result.defaultTtlDays,
estConfig,
apiConfig,
acmeConfig,
@@ -448,9 +457,9 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
externalConfigs: result.externalConfigs
? (JSON.parse(result.externalConfigs as string) as Record<string, unknown>)
: null,
+ defaults: (result.defaults as TCertificateProfileDefaults) ?? null,
createdAt: result.createdAt,
updatedAt: result.updatedAt,
- defaultTtlDays: result.defaultTtlDays as number | null,
estConfig,
apiConfig,
acmeConfig,
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.test.ts b/backend/src/services/certificate-profile/certificate-profile-service.test.ts
index f30b431d9d..9ded1881df 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.test.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.test.ts
@@ -100,6 +100,7 @@ describe("CertificateProfileService", () => {
apiConfigId: "api-config-123",
estConfigId: null,
externalConfigs: null,
+ defaults: null,
createdAt: new Date(),
updatedAt: new Date()
};
@@ -231,6 +232,10 @@ describe("CertificateProfileService", () => {
findOne: vi.fn()
} as unknown as Pick<TExternalCertificateAuthorityDALFactory, "findById" | "findOne">;
+ const mockCertificatePolicyService = {
+ validateRequestAgainstPolicy: vi.fn().mockReturnValue({ isValid: true, errors: [], warnings: [] })
+ };
+
beforeEach(() => {
vi.spyOn(ForbiddenError, "from").mockReturnValue({
throwUnlessCan: vi.fn()
@@ -245,6 +250,7 @@ describe("CertificateProfileService", () => {
service = certificateProfileServiceFactory({
certificateProfileDAL: mockCertificateProfileDAL,
certificatePolicyDAL: mockCertificatePolicyDAL,
+ certificatePolicyService: mockCertificatePolicyService,
apiEnrollmentConfigDAL: mockApiEnrollmentConfigDAL,
estEnrollmentConfigDAL: mockEstEnrollmentConfigDAL,
acmeEnrollmentConfigDAL: mockAcmeEnrollmentConfigDAL,
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.ts
index c865963e9b..a5d43a4a21 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts
@@ -14,7 +14,6 @@ import { extractX509CertFromChain } from "@app/lib/certificates/extract-certific
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
-import { ms } from "@app/lib/ms";
import { ActorAuthMethod, ActorType } from "../auth/auth-type";
import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
@@ -24,6 +23,8 @@ import { TCertificateAuthorityDALFactory } from "../certificate-authority/certif
import { CaType } from "../certificate-authority/certificate-authority-enums";
import { TExternalCertificateAuthorityDALFactory } from "../certificate-authority/external-certificate-authority-dal";
import { TCertificatePolicyDALFactory } from "../certificate-policy/certificate-policy-dal";
+import { TCertificatePolicyServiceFactory } from "../certificate-policy/certificate-policy-service";
+import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
import { TAcmeEnrollmentConfigDALFactory } from "../enrollment-config/acme-enrollment-config-dal";
import { TApiEnrollmentConfigDALFactory } from "../enrollment-config/api-enrollment-config-dal";
import { TAcmeConfigData, TApiConfigData, TEstConfigData } from "../enrollment-config/enrollment-config-types";
@@ -37,6 +38,7 @@ import {
IssuerType,
TCertificateProfile,
TCertificateProfileCertificate,
+ TCertificateProfileDefaults,
TCertificateProfileInsert,
TCertificateProfileUpdate,
TCertificateProfileWithConfigs
@@ -225,6 +227,7 @@ export type TCertificateProfileCreateData = Omit<
type TCertificateProfileServiceFactoryDep = {
certificateProfileDAL: TCertificateProfileDALFactory;
certificatePolicyDAL: TCertificatePolicyDALFactory;
+ certificatePolicyService: Pick<TCertificatePolicyServiceFactory, "validateRequestAgainstPolicy">;
apiEnrollmentConfigDAL: TApiEnrollmentConfigDALFactory;
estEnrollmentConfigDAL: TEstEnrollmentConfigDALFactory;
acmeEnrollmentConfigDAL: TAcmeEnrollmentConfigDALFactory;
@@ -251,17 +254,21 @@ const convertDalToService = (dalResult: Record<string, unknown>): TCertificatePr
parsedExternalConfigs = dalResult.externalConfigs as Record<string, unknown>;
}
+ const parsedDefaults = (dalResult.defaults as TCertificateProfileDefaults) ?? null;
+
return {
...dalResult,
enrollmentType: dalResult.enrollmentType as EnrollmentType,
issuerType: dalResult.issuerType as IssuerType,
- externalConfigs: parsedExternalConfigs
+ externalConfigs: parsedExternalConfigs,
+ defaults: parsedDefaults
} as TCertificateProfile;
};
export const certificateProfileServiceFactory = ({
certificateProfileDAL,
certificatePolicyDAL,
+ certificatePolicyService,
apiEnrollmentConfigDAL,
estEnrollmentConfigDAL,
acmeEnrollmentConfigDAL,
@@ -273,27 +280,6 @@ export const certificateProfileServiceFactory = ({
kmsService,
projectDAL
}: TCertificateProfileServiceFactoryDep) => {
- const validateDefaultTtlDaysAgainstPolicy = async (
- defaultTtlDays: number | undefined | null,
- certificatePolicyId: string
- ) => {
- if (!defaultTtlDays) return; // No defaultTtlDays to validate
-
- const policy = await certificatePolicyDAL.findById(certificatePolicyId);
- if (!policy) return; // Policy validation happens elsewhere
-
- if (!policy.validity?.max) return; // No max constraint
-
- const defaultTtlMs = defaultTtlDays * 24 * 60 * 60 * 1000;
- const maxTtlMs = ms(policy.validity.max);
-
- if (defaultTtlMs > maxTtlMs) {
- throw new BadRequestError({
- message: `Default TTL (${defaultTtlDays} days) exceeds the policy's maximum validity (${policy.validity.max})`
- });
- }
- };
-
const createProfile = async ({
actor,
actorId,
@@ -352,8 +338,30 @@ export const certificateProfileServiceFactory = ({
validateIssuerTypeConstraints(data.issuerType, data.enrollmentType, data.caId ?? null);
- // Validate defaultTtlDays against policy constraints
- await validateDefaultTtlDaysAgainstPolicy(data.defaultTtlDays, data.certificatePolicyId);
+ // Validate defaults against policy constraints
+ if (data.defaults && data.certificatePolicyId) {
+ const policy = await certificatePolicyDAL.findById(data.certificatePolicyId);
+ if (policy) {
+ const request: TCertificateRequest = {
+ commonName: data.defaults.commonName,
+ organization: data.defaults.organization,
+ organizationalUnit: data.defaults.organizationalUnit,
+ country: data.defaults.country,
+ state: data.defaults.state,
+ locality: data.defaults.locality,
+ keyUsages: data.defaults.keyUsages,
+ extendedKeyUsages: data.defaults.extendedKeyUsages,
+ signatureAlgorithm: data.defaults.signatureAlgorithm,
+ keyAlgorithm: data.defaults.keyAlgorithm,
+ validity: data.defaults.ttlDays ? { ttl: `${data.defaults.ttlDays}d` } : undefined,
+ basicConstraints: data.defaults.basicConstraints
+ };
+ const result = certificatePolicyService.validateRequestAgainstPolicy(policy, request, { skipRequired: true });
+ if (!result.isValid) {
+ throw new BadRequestError({ message: `Profile defaults violate policy: ${result.errors.join("; ")}` });
+ }
+ }
+ }
// Validate external configs
await validateExternalConfigs(
@@ -544,10 +552,30 @@ export const certificateProfileServiceFactory = ({
}
}
}
- // Validate defaultTtlDays against policy constraints if provided
- if (data.defaultTtlDays !== undefined) {
+ // Validate defaults against policy constraints if provided
+ if (data.defaults) {
const policyId = data.certificatePolicyId || existingProfile.certificatePolicyId;
- await validateDefaultTtlDaysAgainstPolicy(data.defaultTtlDays, policyId);
+ const policy = await certificatePolicyDAL.findById(policyId);
+ if (policy) {
+ const request: TCertificateRequest = {
+ commonName: data.defaults.commonName,
+ organization: data.defaults.organization,
+ organizationalUnit: data.defaults.organizationalUnit,
+ country: data.defaults.country,
+ state: data.defaults.state,
+ locality: data.defaults.locality,
+ keyUsages: data.defaults.keyUsages,
+ extendedKeyUsages: data.defaults.extendedKeyUsages,
+ signatureAlgorithm: data.defaults.signatureAlgorithm,
+ keyAlgorithm: data.defaults.keyAlgorithm,
+ validity: data.defaults.ttlDays ? { ttl: `${data.defaults.ttlDays}d` } : undefined,
+ basicConstraints: data.defaults.basicConstraints
+ };
+ const result = certificatePolicyService.validateRequestAgainstPolicy(policy, request, { skipRequired: true });
+ if (!result.isValid) {
+ throw new BadRequestError({ message: `Profile defaults violate policy: ${result.errors.join("; ")}` });
+ }
+ }
}
const updatedData =
diff --git a/backend/src/services/certificate-profile/certificate-profile-types.ts b/backend/src/services/certificate-profile/certificate-profile-types.ts
index 76b9971114..f591b0e655 100644
--- a/backend/src/services/certificate-profile/certificate-profile-types.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-types.ts
@@ -4,6 +4,13 @@ import {
TPkiCertificateProfilesUpdate
} from "@app/db/schemas/pki-certificate-profiles";
+import {
+ CertExtendedKeyUsageType,
+ CertKeyAlgorithm,
+ CertKeyUsageType,
+ CertSignatureAlgorithm
+} from "../certificate-common/certificate-constants";
+
export enum EnrollmentType {
API = "api",
EST = "est",
@@ -15,28 +22,49 @@ export enum IssuerType {
SELF_SIGNED = "self-signed"
}
-export type TCertificateProfile = Omit<TPkiCertificateProfiles, "enrollmentType" | "issuerType" | "externalConfigs"> & {
+export type TCertificateProfileDefaults = {
+ ttlDays?: number;
+ commonName?: string;
+ keyAlgorithm?: CertKeyAlgorithm;
+ signatureAlgorithm?: CertSignatureAlgorithm;
+ keyUsages?: CertKeyUsageType[];
+ extendedKeyUsages?: CertExtendedKeyUsageType[];
+ basicConstraints?: { isCA: boolean; pathLength?: number };
+ organization?: string;
+ organizationalUnit?: string;
+ country?: string;
+ state?: string;
+ locality?: string;
+};
+
+export type TCertificateProfile = Omit<
+ TPkiCertificateProfiles,
+ "enrollmentType" | "issuerType" | "externalConfigs" | "defaults"
+> & {
enrollmentType: EnrollmentType;
issuerType: IssuerType;
externalConfigs?: Record<string, unknown> | null;
+ defaults?: TCertificateProfileDefaults | null;
};
export type TCertificateProfileInsert = Omit<
TPkiCertificateProfilesInsert,
- "enrollmentType" | "issuerType" | "externalConfigs"
+ "enrollmentType" | "issuerType" | "externalConfigs" | "defaults"
> & {
enrollmentType: EnrollmentType;
issuerType: IssuerType;
externalConfigs?: Record<string, unknown> | null;
+ defaults?: TCertificateProfileDefaults | null;
};
export type TCertificateProfileUpdate = Omit<
TPkiCertificateProfilesUpdate,
- "enrollmentType" | "issuerType" | "externalConfigs"
+ "enrollmentType" | "issuerType" | "externalConfigs" | "defaults"
> & {
enrollmentType?: EnrollmentType;
issuerType?: IssuerType;
externalConfigs?: Record<string, unknown> | null;
+ defaults?: TCertificateProfileDefaults | null;
estConfig?: {
disableBootstrapCaValidation?: boolean;
passphrase?: string;
diff --git a/backend/src/services/certificate-v3/certificate-v3-fns.ts b/backend/src/services/certificate-v3/certificate-v3-fns.ts
index 9ebf188e89..4ca3191fed 100644
--- a/backend/src/services/certificate-v3/certificate-v3-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-fns.ts
@@ -3,6 +3,8 @@ import RE2 from "re2";
import { BadRequestError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
+import { TCertificateProfileDefaults } from "../certificate-profile/certificate-profile-types";
+
export const parseTtlToDays = (ttl: string): number => {
const match = ttl.match(new RE2("^(\\d+)([dhm])$"));
if (!match) {
@@ -45,7 +47,7 @@ export const calculateRenewalThreshold = (
*
* Priority order:
* 1. Request TTL (user explicitly passed)
- * 2. Profile's defaultTtlDays (validates against policy max)
+ * 2. Profile's defaults.ttlDays (validates against policy max)
* 3. Flow-specific default (for ACME, EST, etc.)
* 4. Error - throws if no TTL source is available
*
@@ -73,7 +75,7 @@ export const resolveEffectiveTtl = ({
return requestTtl;
}
- // Priority 2: Profile's defaultTtlDays
+ // Priority 2: Profile's defaults.ttlDays
if (profileDefaultTtlDays) {
// Validate against policy's maxValidity (catch config drift)
if (policyMaxValidity) {
@@ -99,3 +101,45 @@ export const resolveEffectiveTtl = ({
message: "Certificate issuance requires a valid TTL"
});
};
+
+/**
+ * Applies profile defaults to certificate request
+ * Request values always take precedence over defaults.
+ * For keyUsages/extendedKeyUsages/basicConstraints, replace strategy: request array wins entirely if present.
+ */
+export const applyProfileDefaults = <
+ T extends {
+ commonName?: string;
+ organization?: string;
+ organizationalUnit?: string;
+ country?: string;
+ state?: string;
+ locality?: string;
+ keyAlgorithm?: string;
+ signatureAlgorithm?: string;
+ keyUsages?: string[];
+ extendedKeyUsages?: string[];
+ basicConstraints?: { isCA: boolean; pathLength?: number };
+ }
+>(
+ request: T,
+ defaults: TCertificateProfileDefaults | null | undefined
+): T => {
+ if (!defaults) return request;
+
+ // For scalar fields, key-presence distinguishes "omitted" (use default) from "explicitly set/cleared".
+ return {
+ ...request,
+ commonName: "commonName" in request ? request.commonName : defaults.commonName,
+ organization: "organization" in request ? request.organization : defaults.organization,
+ organizationalUnit: "organizationalUnit" in request ? request.organizationalUnit : defaults.organizationalUnit,
+ country: "country" in request ? request.country : defaults.country,
+ state: "state" in request ? request.state : defaults.state,
+ locality: "locality" in request ? request.locality : defaults.locality,
+ keyAlgorithm: "keyAlgorithm" in request ? request.keyAlgorithm : defaults.keyAlgorithm,
+ signatureAlgorithm: "signatureAlgorithm" in request ? request.signatureAlgorithm : defaults.signatureAlgorithm,
+ keyUsages: request.keyUsages !== undefined ? request.keyUsages : defaults.keyUsages,
+ extendedKeyUsages: request.extendedKeyUsages !== undefined ? request.extendedKeyUsages : defaults.extendedKeyUsages,
+ basicConstraints: request.basicConstraints !== undefined ? request.basicConstraints : defaults.basicConstraints
+ };
+};
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 e1de50943a..12097f179e 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -27,6 +27,7 @@ import { TCertificateProfileDALFactory } from "@app/services/certificate-profile
import { EnrollmentType, IssuerType } from "@app/services/certificate-profile/certificate-profile-types";
import { ActorType, AuthMethod } from "../auth/auth-type";
+import { createDistinguishedName, parseDistinguishedName } from "../certificate-authority/certificate-authority-fns";
import {
extractAlgorithmsFromCSR,
extractCertificateRequestFromCSR
@@ -38,6 +39,23 @@ vi.mock("../certificate-common/certificate-csr-utils", () => ({
extractAlgorithmsFromCSR: vi.fn()
}));
+vi.mock("@peculiar/x509", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@peculiar/x509")>();
+ return {
+ ...actual,
+ Pkcs10CertificateRequest: vi.fn().mockImplementation(() => ({
+ subject: "CN=test.example.com"
+ }))
+ };
+});
+
+vi.mock("../certificate-authority/certificate-authority-fns", () => ({
+ parseDistinguishedName: vi.fn().mockReturnValue({
+ commonName: "test.example.com"
+ }),
+ createDistinguishedName: vi.fn().mockReturnValue("CN=test.example.com")
+}));
+
describe("CertificateV3Service", () => {
let service: TCertificateV3ServiceFactory;
@@ -161,6 +179,11 @@ describe("CertificateV3Service", () => {
signatureAlgorithm: "RSA-SHA256" as any
});
+ vi.mocked(parseDistinguishedName).mockReturnValue({
+ commonName: "test.example.com"
+ });
+ vi.mocked(createDistinguishedName).mockReturnValue("CN=test.example.com");
+
service = certificateV3ServiceFactory({
certificateDAL: mockCertificateDAL,
certificateSecretDAL: mockCertificateSecretDAL,
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index 17ffa3f5ff..07960e1acc 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -1,4 +1,5 @@
import { ForbiddenError, subject } from "@casl/ability";
+import * as x509 from "@peculiar/x509";
import { randomUUID } from "crypto";
import RE2 from "re2";
@@ -38,6 +39,10 @@ import {
TCertificateAuthorityWithAssociatedCa
} from "@app/services/certificate-authority/certificate-authority-dal";
import { CaStatus, CaType } from "@app/services/certificate-authority/certificate-authority-enums";
+import {
+ createDistinguishedName,
+ parseDistinguishedName
+} from "@app/services/certificate-authority/certificate-authority-fns";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
@@ -87,7 +92,7 @@ import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync
import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
import { addRenewedCertificateToSyncs, triggerAutoSyncForCertificate } from "../pki-sync/pki-sync-utils";
-import { resolveEffectiveTtl } from "./certificate-v3-fns";
+import { applyProfileDefaults, resolveEffectiveTtl } from "./certificate-v3-fns";
import {
TCertificateIssuanceResponse,
TDisableRenewalConfigDTO,
@@ -697,9 +702,10 @@ export const certificateV3ServiceFactory = ({
if (matchedApprovalPolicy && !shouldBypassApproval(actor, matchedApprovalPolicy)) {
const approvalPolicy = matchedApprovalPolicy;
+ const withDefaults = applyProfileDefaults(certificateRequest, profile.defaults);
const mappedCertificateRequestForValidation = mapEnumsForValidation({
- ...certificateRequest,
- subjectAlternativeNames: certificateRequest.altNames
+ ...withDefaults,
+ subjectAlternativeNames: withDefaults.altNames
});
const policy = await certificatePolicyService.getPolicyById({
@@ -730,7 +736,7 @@ export const certificateV3ServiceFactory = ({
const resolvedTtl = resolveEffectiveTtl({
requestTtl: certificateRequest.validity.ttl || undefined,
- profileDefaultTtlDays: profile.defaultTtlDays,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
policyMaxValidity: policy?.validity?.max,
flowDefaultTtl: ""
});
@@ -838,9 +844,10 @@ export const certificateV3ServiceFactory = ({
});
}
+ const certificateRequestWithDefaults = applyProfileDefaults(certificateRequest, profile.defaults);
const mappedCertificateRequest = mapEnumsForValidation({
- ...certificateRequest,
- subjectAlternativeNames: certificateRequest.altNames
+ ...certificateRequestWithDefaults,
+ subjectAlternativeNames: certificateRequestWithDefaults.altNames
});
const policy = await certificatePolicyService.getPolicyById({
@@ -866,8 +873,10 @@ export const certificateV3ServiceFactory = ({
});
}
- const effectiveSignatureAlgorithm = certificateRequest.signatureAlgorithm as CertSignatureAlgorithm | undefined;
- const effectiveKeyAlgorithm = certificateRequest.keyAlgorithm as CertKeyAlgorithm | undefined;
+ const effectiveSignatureAlgorithm = certificateRequestWithDefaults.signatureAlgorithm as
+ | CertSignatureAlgorithm
+ | undefined;
+ const effectiveKeyAlgorithm = certificateRequestWithDefaults.keyAlgorithm as CertKeyAlgorithm | undefined;
if (policy.algorithms?.keyAlgorithm && !effectiveKeyAlgorithm) {
throw new BadRequestError({
@@ -881,9 +890,9 @@ export const certificateV3ServiceFactory = ({
});
}
- const certificateSubject = buildCertificateSubjectFromTemplate(certificateRequest, policy?.subject);
+ const certificateSubject = buildCertificateSubjectFromTemplate(certificateRequestWithDefaults, policy?.subject);
const subjectAlternativeNames = buildSubjectAlternativeNamesFromTemplate(
- { subjectAlternativeNames: certificateRequest.altNames },
+ { subjectAlternativeNames: certificateRequestWithDefaults.altNames },
policy?.sans
);
@@ -892,7 +901,7 @@ export const certificateV3ServiceFactory = ({
if (issuerType === IssuerType.SELF_SIGNED) {
const resolvedTtl = resolveEffectiveTtl({
requestTtl: certificateRequest.validity.ttl || undefined,
- profileDefaultTtlDays: profile.defaultTtlDays,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
policyMaxValidity: policy?.validity?.max,
flowDefaultTtl: ""
});
@@ -1044,25 +1053,25 @@ export const certificateV3ServiceFactory = ({
commonName: certificateSubject.common_name || "",
altNames: subjectAlternativeNames,
basicConstraints: caBasicConstraints,
- pathLength: certificateRequest.basicConstraints?.pathLength,
+ pathLength: certificateRequestWithDefaults.basicConstraints?.pathLength,
ttl: resolveEffectiveTtl({
requestTtl: certificateRequest.validity.ttl,
- profileDefaultTtlDays: profile.defaultTtlDays,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
policyMaxValidity: policy?.validity?.max,
flowDefaultTtl: ""
}),
- keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
- extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
+ keyUsages: convertKeyUsageArrayToLegacy(certificateRequestWithDefaults.keyUsages) || [],
+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequestWithDefaults.extendedKeyUsages) || [],
notBefore: normalizeDateForApi(certificateRequest.notBefore),
notAfter: normalizeDateForApi(certificateRequest.notAfter),
signatureAlgorithm: effectiveSignatureAlgorithm,
keyAlgorithm: effectiveKeyAlgorithm,
isFromProfile: true,
- organization: certificateRequest.organization,
- organizationalUnit: certificateRequest.organizationalUnit,
- country: certificateRequest.country,
- state: certificateRequest.state,
- locality: certificateRequest.locality,
+ organization: certificateRequestWithDefaults.organization,
+ organizationalUnit: certificateRequestWithDefaults.organizationalUnit,
+ country: certificateRequestWithDefaults.country,
+ state: certificateRequestWithDefaults.state,
+ locality: certificateRequestWithDefaults.locality,
tx
};
@@ -1078,7 +1087,7 @@ export const certificateV3ServiceFactory = ({
}
const effectiveTtl = resolveEffectiveTtl({
requestTtl: certificateRequest.validity.ttl,
- profileDefaultTtlDays: profile.defaultTtlDays,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
policyMaxValidity: policy?.validity?.max,
flowDefaultTtl: ""
});
@@ -1217,7 +1226,8 @@ export const certificateV3ServiceFactory = ({
throw new NotFoundError({ message: "Certificate policy not found for this profile" });
}
- const certificateRequest = extractCertificateRequestFromCSR(csr);
+ const csrCertificateRequest = extractCertificateRequestFromCSR(csr);
+ const certificateRequest = applyProfileDefaults(csrCertificateRequest, profile.defaults);
const mappedCertificateRequest = mapEnumsForValidation(certificateRequest);
const { keyAlgorithm: extractedKeyAlgorithm, signatureAlgorithm: extractedSignatureAlgorithm } =
@@ -1391,23 +1401,42 @@ export const certificateV3ServiceFactory = ({
const effectiveTtl = resolveEffectiveTtl({
requestTtl: validity.ttl,
- profileDefaultTtlDays: profile.defaultTtlDays,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
policyMaxValidity: policy?.validity?.max,
flowDefaultTtl: ""
});
+ const csrSubjectParsed = parseDistinguishedName(new x509.Pkcs10CertificateRequest(csr).subject);
+ const mergedSubject = {
+ ...csrSubjectParsed,
+ commonName: csrSubjectParsed.commonName ?? certificateRequest.commonName,
+ organization: csrSubjectParsed.organization ?? certificateRequest.organization,
+ ou: csrSubjectParsed.ou ?? certificateRequest.organizationalUnit,
+ country: csrSubjectParsed.country ?? certificateRequest.country,
+ province: csrSubjectParsed.province ?? certificateRequest.state,
+ locality: csrSubjectParsed.locality ?? certificateRequest.locality
+ };
+ const subjectOverride = createDistinguishedName(mergedSubject);
+
const { certificate, certificateChain, issuingCaCertificate, serialNumber, cert, certificateRequestId } =
await certificateDAL.transaction(async (tx) => {
const certResult = await internalCaService.signCertFromCa({
isInternal: true,
caId: ca.id,
csr,
+ subjectOverride,
basicConstraints: caBasicConstraints,
pathLength: effectiveBasicConstraints?.pathLength,
ttl: effectiveTtl,
altNames: undefined,
notBefore: normalizeDateForApi(notBefore),
notAfter: normalizeDateForApi(notAfter),
+ keyUsages: certificateRequest.keyUsages
+ ? convertKeyUsageArrayToLegacy(certificateRequest.keyUsages)
+ : undefined,
+ extendedKeyUsages: certificateRequest.extendedKeyUsages
+ ? convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages)
+ : undefined,
signatureAlgorithm: effectiveSignatureAlgorithm,
keyAlgorithm: effectiveKeyAlgorithm,
isFromProfile: true,
@@ -1505,7 +1534,8 @@ export const certificateV3ServiceFactory = ({
let extractedSignatureAlgorithm: string | undefined;
if (certificateOrder.csr) {
- certificateRequest = extractCertificateRequestFromCSR(certificateOrder.csr);
+ const csrRequest = extractCertificateRequestFromCSR(certificateOrder.csr);
+ certificateRequest = applyProfileDefaults(csrRequest, profile.defaults);
const algorithms = extractAlgorithmsFromCSR(certificateOrder.csr);
extractedKeyAlgorithm = algorithms.keyAlgorithm;
extractedSignatureAlgorithm = algorithms.signatureAlgorithm;
@@ -1515,7 +1545,7 @@ export const certificateV3ServiceFactory = ({
certificateRequest.notAfter = certificateOrder.notAfter;
}
} else {
- certificateRequest = {
+ const rawRequest: TCertificateRequest = {
commonName: certificateOrder.commonName,
keyUsages: certificateOrder.keyUsages,
extendedKeyUsages: certificateOrder.extendedKeyUsages,
@@ -1526,6 +1556,7 @@ export const certificateV3ServiceFactory = ({
signatureAlgorithm: certificateOrder.signatureAlgorithm,
keyAlgorithm: certificateOrder.keyAlgorithm
};
+ certificateRequest = applyProfileDefaults(rawRequest, profile.defaults);
}
// Check if this is a CA certificate request (either explicit basicConstraints or keyCertSign in key usages)
diff --git a/docs/documentation/platform/pki/certificates/profiles.mdx b/docs/documentation/platform/pki/certificates/profiles.mdx
index 2b2a9210f2..31012f3808 100644
--- a/docs/documentation/platform/pki/certificates/profiles.mdx
+++ b/docs/documentation/platform/pki/certificates/profiles.mdx
@@ -24,7 +24,26 @@ Here's some guidance on each field:
- Issuer Type: The type of issuer that should be used to issue certificates for the profile; this can be either `Certificate Authority` or `Self-Signed`. If `Self-Signed` is selected, then the profile will only support the API enrollment method and be used to issue self-signed certificates over REST API.
- Issuing CA: The [issuing CA](/documentation/platform/pki/ca/overview) that should be used to issue certificates for the profile when the **Issuer Type** is set to `Certificate Authority`.
- Certificate Policy: The [certificate policy](/documentation/platform/pki/certificates/policies) that should be used to validate certificate requests for the profile.
-- Enrollment Method: The enrollment method that should be used to enroll certificates for the profile such as ACME, EST, API, etc.
-- Default Certificate TTL: An optional fallback validity period used when a TTL is not explicitly specified in the certificate request. The default TTL must not exceed the maximum validity defined in the associated [certificate policy](/documentation/platform/pki/certificates/policies).
+- Enrollment Method: The enrollment method that should be used to enroll certificates for the profile such as ACME, EST, API, etc. Depending on which enrollment method you choose, you may be presented with additional enrollment-specific configuration fields.
-Depending on which enrollment method you choose, you may be presented with additional enrollment-specific configuration fields.
+The profile form also has a separate **Certificate Details** tab where you can pre-configure certificate values that are applied when a requester does not specify them. See [Profile Defaults](#profile-defaults) below for more details.
+
+## Profile Defaults
+
+Requesting a certificate involves choosing a key algorithm, signature algorithm, key usages, subject attributes, and more. For users who are not familiar with these options, this can feel overwhelming. Profile defaults let administrators pre-configure sensible values so that requesters can issue certificates without needing to make every decision themselves. If a requester does not know what to pick, they can simply go with whatever the administrator has already set.
+
+Defaults are automatically applied to any certificate request that does not explicitly specify those values. If a requester does provide a value, it takes precedence over the default. In the UI, defaults are pre-selected in the certificate request form. For non-UI flows such as API, EST, or ACME, the requester does not need to pass those values in the request at all — the defaults are applied automatically.
+
+![pki certificate profile defaults](/images/platform/pki/certificate/cert-profile-modal-defaults.png)
+
+### Combining Defaults with Policies
+
+For the simplest possible requester experience, pair defaults with a tightly scoped [certificate policy](/documentation/platform/pki/certificates/policies). By narrowing the policy down so that only one option is allowed for each field and then setting that option as the default, the requester has nothing left to decide — the profile handles everything automatically.
+
+For example, if your policy only allows `RSA 4096` as the key algorithm and you set `RSA 4096` as the profile default, the requester never needs to think about key algorithms at all.
+
+Defaults can be configured for TTL, subject attributes (Common Name, Organization, OU, Country, State, Locality), key algorithm, signature algorithm, key usages, extended key usages, and basic constraints.
+
+<Warning>
+ If the certificate policy is updated after the profile is saved, the existing defaults may no longer comply with the new policy. When this drift occurs, certificate requests against the profile will fail at validation time. You will need to update the profile defaults to bring them back in line with the updated policy.
+</Warning>
diff --git a/docs/images/platform/pki/certificate/cert-profile-modal-defaults.png b/docs/images/platform/pki/certificate/cert-profile-modal-defaults.png
new file mode 100644
index 0000000000..01f1f74764
Binary files /dev/null and b/docs/images/platform/pki/certificate/cert-profile-modal-defaults.png differ
diff --git a/docs/images/platform/pki/certificate/cert-profile-modal.png b/docs/images/platform/pki/certificate/cert-profile-modal.png
index 033dd6f468..5a6413c300 100644
Binary files a/docs/images/platform/pki/certificate/cert-profile-modal.png and b/docs/images/platform/pki/certificate/cert-profile-modal.png differ
diff --git a/frontend/src/hooks/api/certificateProfiles/types.ts b/frontend/src/hooks/api/certificateProfiles/types.ts
index badaba6c99..f4739a1e03 100644
--- a/frontend/src/hooks/api/certificateProfiles/types.ts
+++ b/frontend/src/hooks/api/certificateProfiles/types.ts
@@ -9,6 +9,21 @@ export enum IssuerType {
SELF_SIGNED = "self-signed"
}
+export type TCertificateProfileDefaults = {
+ ttlDays?: number;
+ commonName?: string;
+ keyAlgorithm?: string;
+ signatureAlgorithm?: string;
+ keyUsages?: string[];
+ extendedKeyUsages?: string[];
+ basicConstraints?: { isCA: boolean; pathLength?: number };
+ organization?: string;
+ organizationalUnit?: string;
+ country?: string;
+ state?: string;
+ locality?: string;
+};
+
export type TCertificateProfile = {
id: string;
projectId: string;
@@ -23,7 +38,7 @@ export type TCertificateProfile = {
createdAt: string;
updatedAt: string;
externalConfigs?: Record<string, unknown> | null;
- defaultTtlDays?: number | null;
+ defaults?: TCertificateProfileDefaults | null;
certificateAuthority?: {
id: string;
projectId?: string;
@@ -90,7 +105,7 @@ export type TCreateCertificateProfileDTO = {
skipEabBinding?: boolean;
};
externalConfigs?: Record<string, unknown> | null;
- defaultTtlDays?: number;
+ defaults?: TCertificateProfileDefaults | null;
};
export type TUpdateCertificateProfileDTO = {
@@ -113,7 +128,7 @@ export type TUpdateCertificateProfileDTO = {
skipEabBinding?: boolean;
};
externalConfigs?: Record<string, unknown> | null;
- defaultTtlDays?: number | null;
+ defaults?: TCertificateProfileDefaults | null;
};
export type TDeleteCertificateProfileDTO = {
diff --git a/frontend/src/hooks/api/certificates/types.ts b/frontend/src/hooks/api/certificates/types.ts
index c47921cadb..35fb4fdcb3 100644
--- a/frontend/src/hooks/api/certificates/types.ts
+++ b/frontend/src/hooks/api/certificates/types.ts
@@ -124,7 +124,12 @@ export type TUnifiedCertificateIssuanceDTO = {
projectId: string;
csr?: string;
attributes?: {
- commonName?: string;
+ commonName?: string | null;
+ organization?: string | null;
+ organizationUnit?: string | null;
+ country?: string | null;
+ state?: string | null;
+ locality?: string | null;
keyUsages?: string[];
extendedKeyUsages?: string[];
altNames?: Array<{
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx
index e1d0342edd..28ccb26cf7 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx
@@ -14,34 +14,45 @@ type AlgorithmSelectorsProps = {
signatureError?: string;
keyError?: string;
shouldUnregister?: boolean;
+ signatureFieldName?: string;
+ keyFieldName?: string;
+ isRequired?: boolean;
+ nonePlaceholder?: string;
};
+const NONE_VALUE = "__none__";
+
export const AlgorithmSelectors = ({
control,
availableSignatureAlgorithms,
availableKeyAlgorithms,
signatureError,
keyError,
- shouldUnregister
+ shouldUnregister,
+ signatureFieldName = "signatureAlgorithm",
+ keyFieldName = "keyAlgorithm",
+ isRequired = true,
+ nonePlaceholder
}: AlgorithmSelectorsProps) => {
return (
<div className="grid grid-cols-2 gap-4">
<div>
<Controller
control={control}
- name="signatureAlgorithm"
+ name={signatureFieldName}
shouldUnregister={shouldUnregister}
- render={({ field: { onChange, ...field } }) => (
+ render={({ field: { onChange, value, ...field } }) => (
<FormControl
label="Signature Algorithm"
errorText={signatureError}
isError={Boolean(signatureError)}
- isRequired
+ isRequired={isRequired}
>
<Select
defaultValue=""
{...field}
- onValueChange={(e) => onChange(e)}
+ value={value ?? (nonePlaceholder ? NONE_VALUE : "")}
+ onValueChange={(e) => onChange(e === NONE_VALUE ? null : e)}
className="w-full"
placeholder={
availableSignatureAlgorithms.length > 0
@@ -50,6 +61,7 @@ export const AlgorithmSelectors = ({
}
position="popper"
>
+ {nonePlaceholder && <SelectItem value={NONE_VALUE}>{nonePlaceholder}</SelectItem>}
{availableSignatureAlgorithms.map((algorithm) => (
<SelectItem key={algorithm.value} value={algorithm.value}>
{algorithm.label}
@@ -64,19 +76,20 @@ export const AlgorithmSelectors = ({
<div>
<Controller
control={control}
- name="keyAlgorithm"
+ name={keyFieldName}
shouldUnregister={shouldUnregister}
- render={({ field: { onChange, ...field } }) => (
+ render={({ field: { onChange, value, ...field } }) => (
<FormControl
label="Key Algorithm"
errorText={keyError}
isError={Boolean(keyError)}
- isRequired
+ isRequired={isRequired}
>
<Select
defaultValue=""
{...field}
- onValueChange={(e) => onChange(e)}
+ value={value ?? (nonePlaceholder ? NONE_VALUE : "")}
+ onValueChange={(e) => onChange(e === NONE_VALUE ? null : e)}
className="w-full"
placeholder={
availableKeyAlgorithms.length > 0
@@ -85,6 +98,7 @@ export const AlgorithmSelectors = ({
}
position="popper"
>
+ {nonePlaceholder && <SelectItem value={NONE_VALUE}>{nonePlaceholder}</SelectItem>}
{availableKeyAlgorithms.map((algorithm) => (
<SelectItem key={algorithm.value} value={algorithm.value}>
{algorithm.label}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
index 9beeaedac5..862ab1583e 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
@@ -341,11 +341,15 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
subjectAttributes &&
subjectAttributes.length > 0
) {
+ const defaults = actualSelectedProfile?.defaults;
+
const cnAttr = subjectAttributes.find(
(attr) => attr.type === CertSubjectAttributeType.COMMON_NAME
);
if (cnAttr?.value) {
request.attributes.commonName = cnAttr.value;
+ } else if (defaults?.commonName) {
+ request.attributes.commonName = null;
}
const orgAttr = subjectAttributes.find(
@@ -353,6 +357,8 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
);
if (orgAttr?.value) {
request.attributes.organization = orgAttr.value;
+ } else if (defaults?.organization) {
+ request.attributes.organization = null;
}
const ouAttr = subjectAttributes.find(
@@ -360,6 +366,8 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
);
if (ouAttr?.value) {
request.attributes.organizationUnit = ouAttr.value;
+ } else if (defaults?.organizationalUnit) {
+ request.attributes.organizationUnit = null;
}
const countryAttr = subjectAttributes.find(
@@ -367,6 +375,8 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
);
if (countryAttr?.value) {
request.attributes.country = countryAttr.value;
+ } else if (defaults?.country) {
+ request.attributes.country = null;
}
const stateAttr = subjectAttributes.find(
@@ -374,6 +384,8 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
);
if (stateAttr?.value) {
request.attributes.state = stateAttr.value;
+ } else if (defaults?.state) {
+ request.attributes.state = null;
}
const localityAttr = subjectAttributes.find(
@@ -381,6 +393,8 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
);
if (localityAttr?.value) {
request.attributes.locality = localityAttr.value;
+ } else if (defaults?.locality) {
+ request.attributes.locality = null;
}
}
@@ -399,6 +413,8 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
isCA: true,
pathLength: basicConstraints?.pathLength ?? undefined
};
+ } else if (constraints.templateAllowsCA) {
+ request.attributes.basicConstraints = { isCA: false };
}
const response = await issueCertificate(request);
@@ -419,6 +435,7 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
constraints.shouldShowSanSection,
constraints.templateAllowsCA,
constraints.templateRequiresCA,
+ actualSelectedProfile?.defaults,
handlePopUpToggle,
navigate
]
@@ -670,7 +687,7 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
{constraints.templateAllowsCA && (
<AccordionItem value="basic-constraints">
<AccordionTrigger>Basic Constraints</AccordionTrigger>
- <AccordionContent>
+ <AccordionContent forceMount className="data-[state=closed]:hidden">
<div className="space-y-4 pl-2">
<Controller
control={control}
@@ -686,7 +703,7 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
if (!constraints.templateRequiresCA) {
onChange(checked);
if (!checked) {
- setValue("basicConstraints.pathLength", undefined);
+ setValue("basicConstraints.pathLength", null);
}
}
}}
@@ -769,12 +786,10 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
onChange={(e) => {
const val = e.target.value;
if (val === "") {
- field.onChange(undefined);
+ field.onChange(null);
} else {
const numVal = parseInt(val, 10);
- field.onChange(
- Number.isNaN(numVal) ? undefined : numVal
- );
+ field.onChange(Number.isNaN(numVal) ? null : numVal);
}
}}
/>
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/KeyUsageSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/KeyUsageSection.tsx
index 136cfe1c01..e177da92bd 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/KeyUsageSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/KeyUsageSection.tsx
@@ -17,7 +17,7 @@ type KeyUsageSectionProps = {
control: Control<any>;
title: string;
accordionValue: string;
- namePrefix: "keyUsages" | "extendedKeyUsages";
+ namePrefix: string;
options: KeyUsageOption[];
requiredUsages: string[];
shouldUnregister?: boolean;
@@ -37,7 +37,7 @@ export const KeyUsageSection = ({
return (
<AccordionItem value={accordionValue}>
<AccordionTrigger>{title}</AccordionTrigger>
- <AccordionContent>
+ <AccordionContent forceMount className="data-[state=closed]:hidden">
<div className="grid grid-cols-2 gap-2 pl-2">
{options.map(({ label, value }) => {
const isRequired = requiredUsages.includes(value);
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
index 1dfa8a4862..165ee1f50b 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
@@ -44,18 +44,20 @@ type SubjectAttributesFieldProps = {
allowedAttributeTypes: CertSubjectAttributeType[];
error?: string;
shouldUnregister?: boolean;
+ namePrefix?: string;
};
export const SubjectAttributesField = ({
control,
allowedAttributeTypes,
error,
- shouldUnregister
+ shouldUnregister,
+ namePrefix = "subjectAttributes"
}: SubjectAttributesFieldProps) => {
return (
<Controller
control={control}
- name="subjectAttributes"
+ name={namePrefix}
shouldUnregister={shouldUnregister}
render={({ field: { onChange, value } }) => {
const currentValues = value || [];
@@ -72,8 +74,7 @@ export const SubjectAttributesField = ({
);
return (
- // eslint-disable-next-line react/no-array-index-key
- <div key={`subject-attr-${index}`} className="flex items-center gap-2">
+ <div key={`subject-attr-${attr.type}`} className="flex items-center gap-2">
<Select
value={attr.type}
onValueChange={(newType) => {
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
index a6312264a2..3b3b40fd58 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
@@ -96,6 +96,13 @@ export const useCertificatePolicy = (
maxPathLength: undefined
});
+ const [pendingDefaults, setPendingDefaults] = useState<{
+ keyAlgorithm?: string;
+ signatureAlgorithm?: string;
+ basicConstraints?: { isCA: boolean; pathLength?: number };
+ subjectAttributes?: Array<{ type: CertSubjectAttributeType; value: string }>;
+ } | null>(null);
+
const filteredKeyUsages = useMemo(() => {
return KEY_USAGES_OPTIONS.filter(({ value }) => constraints.allowedKeyUsages.includes(value));
}, [constraints.allowedKeyUsages]);
@@ -127,6 +134,7 @@ export const useCertificatePolicy = (
}, [constraints.allowedKeyAlgorithms]);
const resetConstraints = () => {
+ setPendingDefaults(null);
setConstraints({
allowedKeyUsages: [],
allowedExtendedKeyUsages: [],
@@ -180,10 +188,12 @@ export const useCertificatePolicy = (
maxPathLength
};
- // Set TTL: use min(profile.defaultTtlDays, policy.maxValidity)
- const profileTtlDays = selectedProfile?.defaultTtlDays;
+ // Pre-populate from profile defaults
+ const defaults = selectedProfile?.defaults;
+ const profileTtlDays = defaults?.ttlDays;
const policyMaxValidity = templateData.validity?.max;
+ // Set TTL: use min(profile.defaults.ttlDays, policy.maxValidity)
if (profileTtlDays && policyMaxValidity) {
const profileTtlMs = profileTtlDays * 24 * 60 * 60 * 1000;
const policyMaxMs = parseTtlToMs(policyMaxValidity);
@@ -195,6 +205,27 @@ export const useCertificatePolicy = (
setValue("ttl", convertTemplateTtlToCertificateTtl(policyMaxValidity));
}
+ // Collect defaults that need to be applied after constraints update
+ const deferred: {
+ keyAlgorithm?: string;
+ signatureAlgorithm?: string;
+ basicConstraints?: { isCA: boolean; pathLength?: number };
+ subjectAttributes?: Array<{ type: CertSubjectAttributeType; value: string }>;
+ } = {};
+
+ // Defer algorithm defaults (Controllers use shouldUnregister)
+ if (defaults?.keyAlgorithm) {
+ deferred.keyAlgorithm = defaults.keyAlgorithm;
+ }
+ if (defaults?.signatureAlgorithm) {
+ deferred.signatureAlgorithm = defaults.signatureAlgorithm;
+ }
+
+ // Defer basic constraints defaults (Controller is behind templateAllowsCA gate)
+ if (defaults?.basicConstraints) {
+ deferred.basicConstraints = defaults.basicConstraints;
+ }
+
// Handle SAN types
if (templateData.sans && templateData.sans.length > 0) {
const sanTypes: CertSubjectAlternativeNameType[] = [];
@@ -222,10 +253,60 @@ export const useCertificatePolicy = (
newConstraints.allowedSubjectAttributeTypes =
subjectTypes.length > 0 ? subjectTypes : [CertSubjectAttributeType.COMMON_NAME];
+ // Pre-populate subject attributes from profile defaults
+ const defaultSubjectAttrs: Array<{ type: CertSubjectAttributeType; value: string }> = [];
+ if (defaults?.commonName) {
+ defaultSubjectAttrs.push({
+ type: CertSubjectAttributeType.COMMON_NAME,
+ value: defaults.commonName
+ });
+ }
+ if (defaults?.organization) {
+ defaultSubjectAttrs.push({
+ type: CertSubjectAttributeType.ORGANIZATION,
+ value: defaults.organization
+ });
+ }
+ if (defaults?.organizationalUnit) {
+ defaultSubjectAttrs.push({
+ type: CertSubjectAttributeType.ORGANIZATIONAL_UNIT,
+ value: defaults.organizationalUnit
+ });
+ }
+ if (defaults?.country) {
+ defaultSubjectAttrs.push({
+ type: CertSubjectAttributeType.COUNTRY,
+ value: defaults.country
+ });
+ }
+ if (defaults?.state) {
+ defaultSubjectAttrs.push({
+ type: CertSubjectAttributeType.STATE,
+ value: defaults.state
+ });
+ }
+ if (defaults?.locality) {
+ defaultSubjectAttrs.push({
+ type: CertSubjectAttributeType.LOCALITY,
+ value: defaults.locality
+ });
+ }
+
const currentSubjectAttrs = watch("subjectAttributes");
if (!currentSubjectAttrs || currentSubjectAttrs.length === 0) {
- const defaultType = newConstraints.allowedSubjectAttributeTypes[0];
- setValue("subjectAttributes", [{ type: defaultType, value: "" }]);
+ if (defaultSubjectAttrs.length > 0) {
+ // Filter to only allowed attribute types
+ const filteredDefaults = defaultSubjectAttrs.filter((attr) =>
+ newConstraints.allowedSubjectAttributeTypes.includes(attr.type)
+ );
+ deferred.subjectAttributes =
+ filteredDefaults.length > 0
+ ? filteredDefaults
+ : [{ type: newConstraints.allowedSubjectAttributeTypes[0], value: "" }];
+ } else {
+ const defaultType = newConstraints.allowedSubjectAttributeTypes[0];
+ deferred.subjectAttributes = [{ type: defaultType, value: "" }];
+ }
}
} else {
newConstraints.shouldShowSubjectSection = false;
@@ -233,29 +314,79 @@ export const useCertificatePolicy = (
setValue("subjectAttributes", undefined);
}
+ // Merge templateRequiresCA into deferred basicConstraints
+ if (templateRequiresCA) {
+ deferred.basicConstraints = {
+ isCA: true,
+ ...(deferred.basicConstraints?.pathLength !== undefined
+ ? { pathLength: deferred.basicConstraints.pathLength }
+ : {})
+ };
+ }
+
setConstraints(newConstraints);
- // Set initial required usages
+ if (Object.keys(deferred).length > 0) {
+ setPendingDefaults(deferred);
+ }
+
+ // Set initial usages: merge required usages with profile defaults
const initialKeyUsages: Record<string, boolean> = {};
const initialExtendedKeyUsages: Record<string, boolean> = {};
+ // Start with profile default key usages
+ if (defaults?.keyUsages) {
+ defaults.keyUsages.forEach((usage: string) => {
+ initialKeyUsages[usage] = true;
+ });
+ }
+
+ // Required usages always override (ensure they're checked)
(templateData.keyUsages?.required || []).forEach((usage: string) => {
initialKeyUsages[usage] = true;
});
+ // Start with profile default extended key usages
+ if (defaults?.extendedKeyUsages) {
+ defaults.extendedKeyUsages.forEach((usage: string) => {
+ initialExtendedKeyUsages[usage] = true;
+ });
+ }
+
+ // Required extended key usages always override
(templateData.extendedKeyUsages?.required || []).forEach((usage: string) => {
initialExtendedKeyUsages[usage] = true;
});
setValue("keyUsages", initialKeyUsages);
setValue("extendedKeyUsages", initialExtendedKeyUsages);
-
- if (templateRequiresCA) {
- setValue("basicConstraints.isCA", true);
- }
}
}, [templateData, selectedProfile, setValue, watch, isModalOpen]);
+ // Apply deferred defaults after constraints update has committed and Controllers have mounted
+ useEffect(() => {
+ if (!pendingDefaults) return undefined;
+ const timeoutId = setTimeout(() => {
+ if (pendingDefaults.keyAlgorithm) {
+ setValue("keyAlgorithm", pendingDefaults.keyAlgorithm);
+ }
+ if (pendingDefaults.signatureAlgorithm) {
+ setValue("signatureAlgorithm", pendingDefaults.signatureAlgorithm);
+ }
+ if (pendingDefaults.basicConstraints) {
+ setValue("basicConstraints.isCA", pendingDefaults.basicConstraints.isCA);
+ if (pendingDefaults.basicConstraints.pathLength !== undefined) {
+ setValue("basicConstraints.pathLength", pendingDefaults.basicConstraints.pathLength);
+ }
+ }
+ if (pendingDefaults.subjectAttributes) {
+ setValue("subjectAttributes", pendingDefaults.subjectAttributes);
+ }
+ setPendingDefaults(null);
+ }, 0);
+ return () => clearTimeout(timeoutId);
+ }, [pendingDefaults, setValue]);
+
return {
constraints,
filteredKeyUsages,
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
index 45826bbfcb..e12c174063 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
@@ -1,18 +1,25 @@
-import { useEffect } from "react";
+import { useEffect, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { SingleValue } from "react-select";
import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { Tab } from "@headlessui/react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
Button,
Checkbox,
+ EmptyState,
FilterableSelect,
FormControl,
+ FormLabel,
Input,
Modal,
ModalContent,
@@ -29,20 +36,90 @@ import {
import { usePopUp } from "@app/hooks";
import { CaType } from "@app/hooks/api/ca/enums";
import { useGetAzureAdcsTemplates, useListCasByProjectId } from "@app/hooks/api/ca/queries";
-import { TCertificatePolicy, useListCertificatePolicies } from "@app/hooks/api/certificatePolicies";
+import {
+ TCertificatePolicy,
+ useGetCertificatePolicyById,
+ useListCertificatePolicies
+} from "@app/hooks/api/certificatePolicies";
import {
EnrollmentType,
IssuerType,
+ TCertificateProfileDefaults,
TCertificateProfileWithDetails,
TCreateCertificateProfileDTO,
TUpdateCertificateProfileDTO,
useCreateCertificateProfile,
useUpdateCertificateProfile
} from "@app/hooks/api/certificateProfiles";
+import {
+ EXTENDED_KEY_USAGES_OPTIONS,
+ KEY_USAGES_OPTIONS
+} from "@app/hooks/api/certificates/constants";
+import { AlgorithmSelectors } from "@app/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors";
+import { filterUsages } from "@app/pages/cert-manager/CertificatesPage/components/certificateUtils";
+import { KeyUsageSection } from "@app/pages/cert-manager/CertificatesPage/components/KeyUsageSection";
+import { SubjectAttributesField } from "@app/pages/cert-manager/CertificatesPage/components/SubjectAttributesField";
+import {
+ CertPolicyState,
+ CertSubjectAttributeType,
+ mapPolicyKeyAlgorithmToApi,
+ mapPolicySignatureAlgorithmToApi
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
import { CreatePolicyModal } from "../CertificatePoliciesTab/CreatePolicyModal";
import { CertificatePolicyOption } from "./CertificatePolicyOption";
+const certificateDefaultsSchema = z
+ .object({
+ ttlDays: z.number().min(1).nullable().optional(),
+ subjectAttributes: z
+ .array(
+ z.object({
+ type: z.nativeEnum(CertSubjectAttributeType),
+ value: z.string().min(1, "Value is required")
+ })
+ )
+ .optional(),
+ signatureAlgorithm: z.string().nullable().optional(),
+ keyAlgorithm: z.string().nullable().optional(),
+ keyUsages: z.record(z.boolean().optional()).optional(),
+ extendedKeyUsages: z.record(z.boolean().optional()).optional(),
+ basicConstraints: z
+ .object({
+ isCA: z.boolean().default(false),
+ pathLength: z.number().min(0).nullable().optional()
+ })
+ .nullable()
+ .optional()
+ })
+ .optional();
+
+const configurationFields = [
+ "slug",
+ "description",
+ "enrollmentType",
+ "issuerType",
+ "certificateAuthorityId",
+ "certificatePolicyId",
+ "estConfig",
+ "apiConfig",
+ "acmeConfig",
+ "externalConfigs"
+] as const;
+
+const FORM_STEPS = [
+ {
+ name: "Configuration",
+ key: "configuration",
+ fields: configurationFields as unknown as string[]
+ },
+ {
+ name: "Certificate Defaults",
+ key: "certificate-defaults",
+ fields: ["defaults"] as string[]
+ }
+];
+
const createSchema = z
.object({
slug: z
@@ -99,23 +176,7 @@ const createSchema = z
template: z.string().min(1, "Azure ADCS template is required")
})
.optional(),
- defaultTtl: z
- .object({
- value: z.number().min(1, "Duration must be at least 1").nullable().optional(),
- unit: z.enum(["days", "months", "years"]).optional()
- })
- .nullable()
- .optional()
- .refine(
- (data) => {
- // If value is provided, unit must also be provided
- if (data?.value != null && !data?.unit) return false;
- // If unit is provided (checkbox checked), value must also be provided
- if (data?.unit && data?.value == null) return false;
- return true;
- },
- { message: "Please enter a valid TTL duration" }
- )
+ defaults: certificateDefaultsSchema
})
.refine(
(data) => {
@@ -272,23 +333,7 @@ const editSchema = z
template: z.string().optional()
})
.optional(),
- defaultTtl: z
- .object({
- value: z.number().min(1, "Duration must be at least 1").nullable().optional(),
- unit: z.enum(["days", "months", "years"]).optional()
- })
- .nullable()
- .optional()
- .refine(
- (data) => {
- // If value is provided, unit must also be provided
- if (data?.value != null && !data?.unit) return false;
- // If unit is provided (checkbox checked), value must also be provided
- if (data?.unit && data?.value == null) return false;
- return true;
- },
- { message: "Please enter a valid TTL duration" }
- )
+ defaults: certificateDefaultsSchema
})
.refine(
(data) => {
@@ -403,54 +448,133 @@ const editSchema = z
export type FormData = z.infer<typeof createSchema>;
-// Convert stored days (number) to form object for display
-const parseDaysToTtl = (
- days: number | null | undefined
-): { value: number; unit: "days" } | undefined => {
- if (!days) return undefined;
- return { value: days, unit: "days" };
-};
+// Convert profile defaults from API format to form format
+const convertDefaultsToForm = (
+ defaults: TCertificateProfileDefaults | null | undefined
+): FormData["defaults"] => {
+ if (!defaults) return undefined;
-// Convert form object to days (number) for storage
-const convertTtlToDays = (
- ttl: { value?: number | null; unit?: "days" | "months" | "years" } | null | undefined
-): number | undefined => {
- if (!ttl?.value || !ttl?.unit) return undefined;
- switch (ttl.unit) {
- case "days":
- return ttl.value;
- case "months":
- return ttl.value * 30;
- case "years":
- return ttl.value * 365;
- default:
- return undefined;
+ const keyUsagesRecord: Record<string, boolean> = {};
+ if (defaults.keyUsages) {
+ defaults.keyUsages.forEach((usage) => {
+ keyUsagesRecord[usage] = true;
+ });
}
-};
-// Convert days to ms for comparison with policy
-const daysToMs = (days: number | undefined): number | null => {
- if (!days) return null;
- return days * 24 * 60 * 60 * 1000;
+ const extKeyUsagesRecord: Record<string, boolean> = {};
+ if (defaults.extendedKeyUsages) {
+ defaults.extendedKeyUsages.forEach((usage) => {
+ extKeyUsagesRecord[usage] = true;
+ });
+ }
+
+ const subjectAttributes: Array<{ type: CertSubjectAttributeType; value: string }> = [];
+ if (defaults.commonName)
+ subjectAttributes.push({
+ type: CertSubjectAttributeType.COMMON_NAME,
+ value: defaults.commonName
+ });
+ if (defaults.organization)
+ subjectAttributes.push({
+ type: CertSubjectAttributeType.ORGANIZATION,
+ value: defaults.organization
+ });
+ if (defaults.organizationalUnit)
+ subjectAttributes.push({
+ type: CertSubjectAttributeType.ORGANIZATIONAL_UNIT,
+ value: defaults.organizationalUnit
+ });
+ if (defaults.country)
+ subjectAttributes.push({ type: CertSubjectAttributeType.COUNTRY, value: defaults.country });
+ if (defaults.state)
+ subjectAttributes.push({ type: CertSubjectAttributeType.STATE, value: defaults.state });
+ if (defaults.locality)
+ subjectAttributes.push({ type: CertSubjectAttributeType.LOCALITY, value: defaults.locality });
+
+ return {
+ ttlDays: defaults.ttlDays ?? null,
+ subjectAttributes: subjectAttributes.length > 0 ? subjectAttributes : undefined,
+ signatureAlgorithm: defaults.signatureAlgorithm ?? null,
+ keyAlgorithm: defaults.keyAlgorithm ?? null,
+ keyUsages: Object.keys(keyUsagesRecord).length > 0 ? keyUsagesRecord : undefined,
+ extendedKeyUsages: Object.keys(extKeyUsagesRecord).length > 0 ? extKeyUsagesRecord : undefined,
+ basicConstraints: defaults.basicConstraints ?? null
+ };
};
-// Parse policy max validity string (like "365d") to ms
-const parsePolicyValidityToMs = (validity: string | undefined | null): number | null => {
- if (!validity) return null;
- const match = validity.match(/^(\d+)([dmy])$/);
- if (!match) return null;
- const value = parseInt(match[1], 10);
- const msPerDay = 24 * 60 * 60 * 1000;
- switch (match[2]) {
- case "d":
- return value * msPerDay;
- case "m":
- return value * 30 * msPerDay;
- case "y":
- return value * 365 * msPerDay;
- default:
- return null;
+// Convert form defaults to API format
+const convertFormToDefaults = (
+ formDefaults: FormData["defaults"]
+): TCertificateProfileDefaults | null => {
+ if (!formDefaults) return null;
+
+ const result: TCertificateProfileDefaults = {};
+
+ if (formDefaults.ttlDays) {
+ result.ttlDays = formDefaults.ttlDays;
+ }
+
+ if (formDefaults.signatureAlgorithm) {
+ result.signatureAlgorithm = formDefaults.signatureAlgorithm;
+ }
+
+ if (formDefaults.keyAlgorithm) {
+ result.keyAlgorithm = formDefaults.keyAlgorithm;
+ }
+
+ // Key usages: convert Record<string, boolean> → string[]
+ // Empty array is meaningful (signals "no key usages")
+ if (formDefaults.keyUsages) {
+ result.keyUsages = filterUsages(formDefaults.keyUsages as Record<string, boolean>);
+ }
+
+ // Extended key usages: same pattern
+ if (formDefaults.extendedKeyUsages) {
+ result.extendedKeyUsages = filterUsages(
+ formDefaults.extendedKeyUsages as Record<string, boolean>
+ );
+ }
+
+ // Subject attributes → flat fields
+ if (formDefaults.subjectAttributes && formDefaults.subjectAttributes.length > 0) {
+ formDefaults.subjectAttributes.forEach((attr) => {
+ if (!attr.value) return;
+ switch (attr.type) {
+ case CertSubjectAttributeType.COMMON_NAME:
+ result.commonName = attr.value;
+ break;
+ case CertSubjectAttributeType.ORGANIZATION:
+ result.organization = attr.value;
+ break;
+ case CertSubjectAttributeType.ORGANIZATIONAL_UNIT:
+ result.organizationalUnit = attr.value;
+ break;
+ case CertSubjectAttributeType.COUNTRY:
+ result.country = attr.value;
+ break;
+ case CertSubjectAttributeType.STATE:
+ result.state = attr.value;
+ break;
+ case CertSubjectAttributeType.LOCALITY:
+ result.locality = attr.value;
+ break;
+ default:
+ break;
+ }
+ });
+ }
+
+ if (formDefaults.basicConstraints) {
+ result.basicConstraints = {
+ isCA: formDefaults.basicConstraints.isCA,
+ pathLength: formDefaults.basicConstraints.pathLength ?? undefined
+ };
}
+
+ // Return null if empty (no defaults set)
+ if (Object.keys(result).length === 0) return null;
+
+ return result;
};
interface Props {
@@ -466,6 +590,8 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["createPolicy"] as const);
const queryClient = useQueryClient();
+ const [selectedStepIndex, setSelectedStepIndex] = useState(0);
+
const canCreatePolicy = permission.can(
ProjectPermissionCertificatePolicyActions.Create,
ProjectPermissionSub.CertificatePolicies
@@ -482,6 +608,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
const updateProfile = useUpdateCertificateProfile();
const isEdit = mode === "edit" && profile;
+ const isFinalStep = selectedStepIndex === FORM_STEPS.length - 1;
const certificateAuthorities = (allCaData || []).map((ca) => ({
...ca,
@@ -509,7 +636,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
}
};
- const { control, handleSubmit, reset, watch, setValue, setError, formState } = useForm<FormData>({
+ const { control, handleSubmit, reset, watch, setValue, trigger, formState } = useForm<FormData>({
resolver: zodResolver(isEdit ? editSchema : createSchema),
defaultValues: isEdit
? {
@@ -553,7 +680,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
: ""
}
: undefined,
- defaultTtl: parseDaysToTtl(profile.defaultTtlDays)
+ defaults: convertDefaultsToForm(profile.defaults)
}
: {
slug: "",
@@ -571,10 +698,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
skipEabBinding: false
},
externalConfigs: undefined,
- defaultTtl: {
- value: 365,
- unit: "days"
- }
+ defaults: undefined
}
});
@@ -585,6 +709,99 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
const watchedAutoRenew = watch("apiConfig.autoRenew");
const watchedSkipDnsOwnershipVerification = watch("acmeConfig.skipDnsOwnershipVerification");
const watchedSkipEabBinding = watch("acmeConfig.skipEabBinding");
+ const watchedPolicyId = watch("certificatePolicyId");
+ const watchedDefaultsIsCA = watch("defaults.basicConstraints.isCA") || false;
+
+ // Fetch the policy for the defaults tab
+ const { data: selectedPolicyData } = useGetCertificatePolicyById({
+ policyId: watchedPolicyId || ""
+ });
+
+ // Compute constraints from the policy for the defaults tab
+ const policyConstraints = useMemo(() => {
+ const templateData = selectedPolicyData;
+ if (!templateData) {
+ return {
+ allowedKeyUsages: [] as string[],
+ allowedExtendedKeyUsages: [] as string[],
+ requiredKeyUsages: [] as string[],
+ requiredExtendedKeyUsages: [] as string[],
+ allowedSignatureAlgorithms: [] as Array<{ value: string; label: string }>,
+ allowedKeyAlgorithms: [] as Array<{ value: string; label: string }>,
+ allowedSubjectAttributeTypes: [] as CertSubjectAttributeType[],
+ shouldShowSubjectSection: false,
+ templateAllowsCA: false,
+ maxPathLength: undefined as number | undefined
+ };
+ }
+
+ const isCaPolicy =
+ (templateData.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED;
+ const templateAllowsCA =
+ isCaPolicy === CertPolicyState.ALLOWED || isCaPolicy === CertPolicyState.REQUIRED;
+
+ const allowedKeyUsages = [
+ ...(templateData.keyUsages?.required || []),
+ ...(templateData.keyUsages?.allowed || [])
+ ];
+ const allowedExtendedKeyUsages = [
+ ...(templateData.extendedKeyUsages?.required || []),
+ ...(templateData.extendedKeyUsages?.allowed || [])
+ ];
+
+ const allowedSignatureAlgorithms = (templateData.algorithms?.signature || []).map(
+ (templateAlgorithm: string) => {
+ const apiAlgorithm = mapPolicySignatureAlgorithmToApi(templateAlgorithm);
+ return { value: apiAlgorithm, label: apiAlgorithm };
+ }
+ );
+
+ const allowedKeyAlgorithms = (templateData.algorithms?.keyAlgorithm || []).map(
+ (templateAlgorithm: string) => {
+ const apiAlgorithm = mapPolicyKeyAlgorithmToApi(templateAlgorithm);
+ return { value: apiAlgorithm, label: apiAlgorithm };
+ }
+ );
+
+ let allowedSubjectAttributeTypes: CertSubjectAttributeType[] = [];
+ let shouldShowSubjectSection = false;
+ if (templateData.subject && templateData.subject.length > 0) {
+ shouldShowSubjectSection = true;
+ const subjectTypes: CertSubjectAttributeType[] = [];
+ templateData.subject.forEach((subjectPolicy: { type: string }) => {
+ if (!subjectTypes.includes(subjectPolicy.type as CertSubjectAttributeType)) {
+ subjectTypes.push(subjectPolicy.type as CertSubjectAttributeType);
+ }
+ });
+ allowedSubjectAttributeTypes =
+ subjectTypes.length > 0 ? subjectTypes : [CertSubjectAttributeType.COMMON_NAME];
+ }
+
+ return {
+ allowedKeyUsages,
+ allowedExtendedKeyUsages,
+ requiredKeyUsages: (templateData.keyUsages?.required || []) as string[],
+ requiredExtendedKeyUsages: (templateData.extendedKeyUsages?.required || []) as string[],
+ allowedSignatureAlgorithms,
+ allowedKeyAlgorithms,
+ allowedSubjectAttributeTypes,
+ shouldShowSubjectSection,
+ templateAllowsCA,
+ maxPathLength: templateData.basicConstraints?.maxPathLength as number | undefined
+ };
+ }, [selectedPolicyData]);
+
+ const filteredKeyUsages = useMemo(() => {
+ return KEY_USAGES_OPTIONS.filter(({ value }) =>
+ policyConstraints.allowedKeyUsages.includes(value)
+ );
+ }, [policyConstraints.allowedKeyUsages]);
+
+ const filteredExtendedKeyUsages = useMemo(() => {
+ return EXTENDED_KEY_USAGES_OPTIONS.filter(({ value }) =>
+ policyConstraints.allowedExtendedKeyUsages.includes(value)
+ );
+ }, [policyConstraints.allowedExtendedKeyUsages]);
// Get the selected CA to check if it's Azure ADCS
const selectedCa = certificateAuthorities.find((ca) => ca.id === watchedCertificateAuthorityId);
@@ -597,6 +814,13 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
isAzureAdcsCa
});
+ // Reset step to 0 when modal opens/closes
+ useEffect(() => {
+ if (isOpen) {
+ setSelectedStepIndex(0);
+ }
+ }, [isOpen]);
+
useEffect(() => {
if (isEdit && profile) {
reset({
@@ -640,7 +864,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
: ""
}
: undefined,
- defaultTtl: parseDaysToTtl(profile.defaultTtlDays)
+ defaults: convertDefaultsToForm(profile.defaults)
});
}
}, [isEdit, profile, reset, allCaData]);
@@ -657,8 +881,6 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
profile.externalConfigs !== null &&
typeof profile.externalConfigs.template === "string"
) {
- // Re-set the external configs to ensure the template value is properly set
- // after the Azure ADCS templates have been loaded
setValue("externalConfigs.template", profile.externalConfigs.template);
}
}, [isEdit, profile, isAzureAdcsCa, azureAdcsTemplatesData, setValue]);
@@ -678,23 +900,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
return;
}
- // Validate defaultTtl against policy's max validity
- if (data.defaultTtl?.value && data.defaultTtl?.unit) {
- const selectedPolicy = certificatePolicies.find((p) => p.id === data.certificatePolicyId);
- if (selectedPolicy?.validity?.max) {
- const defaultTtlDays = convertTtlToDays(data.defaultTtl);
- const defaultTtlMs = daysToMs(defaultTtlDays);
- const maxValidityMs = parsePolicyValidityToMs(selectedPolicy.validity.max);
-
- if (defaultTtlMs && maxValidityMs && defaultTtlMs > maxValidityMs) {
- setError("defaultTtl.value", {
- type: "manual",
- message: "Exceeds the selected policy's maximum validity"
- });
- return;
- }
- }
- }
+ const serializedDefaults = convertFormToDefaults(data.defaults);
if (isEdit) {
const updateData: TUpdateCertificateProfileDTO = {
@@ -712,15 +918,12 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
updateData.acmeConfig = data.acmeConfig;
}
- // Add external configs if present
if (data.externalConfigs) {
updateData.externalConfigs = data.externalConfigs;
}
- // Add defaultTtlDays if present (or null to clear it)
- if (data.defaultTtl !== undefined) {
- updateData.defaultTtlDays = convertTtlToDays(data.defaultTtl) || null;
- }
+ // Send defaults (or null to clear)
+ updateData.defaults = serializedDefaults;
await updateProfile.mutateAsync(updateData);
} else {
@@ -753,15 +956,12 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
createData.acmeConfig = data.acmeConfig;
}
- // Add external configs if present
if (data.externalConfigs) {
createData.externalConfigs = data.externalConfigs;
}
- // Add defaultTtlDays if present
- const ttlDays = convertTtlToDays(data.defaultTtl);
- if (ttlDays) {
- createData.defaultTtlDays = ttlDays;
+ if (serializedDefaults) {
+ createData.defaults = serializedDefaults;
}
await createProfile.mutateAsync(createData);
@@ -776,12 +976,49 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
onClose();
};
+ // Step validation and navigation (PolicyModal pattern)
+ const isStepValid = async (index: number) => {
+ const { fields } = FORM_STEPS[index];
+ if (fields.length === 0) return true;
+ return trigger(fields as any);
+ };
+
+ const handleNext = async () => {
+ if (isFinalStep) {
+ await handleSubmit(onFormSubmit)();
+ return;
+ }
+ const isValid = await isStepValid(selectedStepIndex);
+ if (!isValid) return;
+ setSelectedStepIndex((prev) => prev + 1);
+ };
+
+ const handlePrev = () => {
+ if (selectedStepIndex === 0) {
+ handlePopUpToggle("createPolicy", false);
+ reset();
+ onClose();
+ return;
+ }
+ setSelectedStepIndex((prev) => prev - 1);
+ };
+
+ const isTabEnabled = async (index: number) => {
+ let isEnabled = true;
+ for (let i = index - 1; i >= 0; i -= 1) {
+ // eslint-disable-next-line no-await-in-loop
+ isEnabled = isEnabled && (await isStepValid(i));
+ }
+ return isEnabled;
+ };
+
return (
<Modal
isOpen={isOpen}
onOpenChange={(open) => {
if (!open) {
reset();
+ setSelectedStepIndex(0);
}
onClose();
}}
@@ -794,579 +1031,712 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
: "Configure a new certificate profile for unified certificate issuance"
}
>
- <form onSubmit={handleSubmit(onFormSubmit)}>
- <Controller
- control={control}
- name="slug"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Name"
- isRequired
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Input {...field} placeholder="your-profile-name" />
- </FormControl>
- )}
- />
-
- <Controller
- control={control}
- name="description"
- render={({ field, fieldState: { error } }) => (
- <FormControl label="Description" isError={Boolean(error)} errorText={error?.message}>
- <TextArea {...field} placeholder="Enter profile description" rows={3} />
- </FormControl>
- )}
- />
-
- <Controller
- control={control}
- name="issuerType"
- render={({ field: { onChange, ...field }, fieldState: { error } }) => (
- <FormControl
- label="Issuer Type"
- isRequired
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Select
- {...field}
- onValueChange={(value) => {
- if (value === "self-signed") {
- setValue("certificateAuthorityId", "");
- setValue("enrollmentType", EnrollmentType.API);
- setValue("apiConfig", {
- autoRenew: false,
- renewBeforeDays: 30
- });
- setValue("estConfig", undefined);
- setValue("acmeConfig", {
- skipDnsOwnershipVerification: false,
- skipEabBinding: false
- });
- }
- onChange(value);
+ <form>
+ <Tab.Group selectedIndex={selectedStepIndex} onChange={setSelectedStepIndex}>
+ <Tab.List className="-pb-1 mb-6 w-full border-b-2 border-mineshaft-600">
+ {FORM_STEPS.map((step, index) => (
+ <Tab
+ onClick={async (e) => {
+ e.preventDefault();
+ const isEnabled = await isTabEnabled(index);
+ setSelectedStepIndex((prev) => (isEnabled ? index : prev));
}}
- className="w-full"
- position="popper"
- isDisabled={Boolean(isEdit)}
- >
- <SelectItem value="ca">Certificate Authority</SelectItem>
- <SelectItem value="self-signed">Self-Signed</SelectItem>
- </Select>
- </FormControl>
- )}
- />
-
- {watchedIssuerType === "ca" && (
- <Controller
- control={control}
- name="certificateAuthorityId"
- render={({ field: { onChange, value }, fieldState: { error } }) => (
- <FormControl
- label="Issuing CA"
- isRequired
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <FilterableSelect
- value={certificateAuthorities.find((ca) => ca.id === value) || null}
- onChange={(selectedCaValue) => {
- if (Array.isArray(selectedCaValue)) {
- onChange(selectedCaValue[0]?.id || "");
- } else if (
- selectedCaValue &&
- typeof selectedCaValue === "object" &&
- "id" in selectedCaValue
- ) {
- onChange(selectedCaValue.id || "");
- } else {
- onChange("");
- }
- }}
- getOptionLabel={(ca) =>
- ca.type === "internal" && ca.configuration.friendlyName
- ? ca.configuration.friendlyName
- : ca.name
- }
- getOptionValue={(ca) => ca.id}
- options={certificateAuthorities}
- groupBy="groupType"
- getGroupHeaderLabel={getGroupHeaderLabel}
- placeholder="Select a certificate authority"
- isDisabled={Boolean(isEdit)}
- className="w-full"
- />
- </FormControl>
- )}
- />
- )}
-
- {/* Azure ADCS Template Selection */}
- {isAzureAdcsCa && (
- <Controller
- control={control}
- name="externalConfigs.template"
- render={({ field: { onChange, value }, fieldState: { error } }) => (
- <FormControl
- label="Windows ADCS Template"
- isRequired
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <FilterableSelect
- value={
- azureAdcsTemplatesData?.templates.find((template) => template.id === value) ||
- null
- }
- onChange={(selectedTemplate) => {
- if (Array.isArray(selectedTemplate)) {
- onChange(selectedTemplate[0]?.id || "");
- } else if (
- selectedTemplate &&
- typeof selectedTemplate === "object" &&
- "id" in selectedTemplate
- ) {
- onChange(selectedTemplate.id || "");
- } else {
- onChange("");
- }
- }}
- getOptionLabel={(template) => template.name}
- getOptionValue={(template) => template.id}
- options={azureAdcsTemplatesData?.templates || []}
- placeholder="Select an Azure ADCS certificate template"
- className="w-full"
- />
- </FormControl>
- )}
- />
- )}
-
- <Controller
- control={control}
- name="certificatePolicyId"
- render={({ field: { onChange, value }, fieldState: { error } }) => (
- <FormControl
- label="Certificate Policy"
- isRequired
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <FilterableSelect
- value={certificatePolicies.find((p) => p.id === value) ?? null}
- onChange={(newValue) => {
- const selected = newValue as SingleValue<PolicyOption>;
- if (selected?.id === "_create") {
- handlePopUpOpen("createPolicy");
- return;
- }
- onChange(selected?.id || "");
-
- if (watchedEnrollmentType === "est") {
- setValue("apiConfig", undefined);
- setValue("estConfig", {
- disableBootstrapCaValidation: false,
- passphrase: ""
- });
- setValue("acmeConfig", undefined);
- } else if (watchedEnrollmentType === "api") {
- setValue("apiConfig", {
- autoRenew: false,
- renewBeforeDays: 30
- });
- setValue("estConfig", undefined);
- setValue("acmeConfig", undefined);
- } else if (watchedEnrollmentType === "acme") {
- setValue("estConfig", undefined);
- setValue("apiConfig", undefined);
- setValue("acmeConfig", {
- skipDnsOwnershipVerification: false,
- skipEabBinding: false
- });
- }
- }}
- options={policyOptions}
- getOptionLabel={(option) => option.name}
- getOptionValue={(option) => option.id}
- placeholder={
- certificatePolicies.length === 0 && !canCreatePolicy
- ? "No certificate policies available"
- : "Select a certificate policy"
+ className={({ selected }) =>
+ `-mb-[0.14rem] whitespace-nowrap ${index > selectedStepIndex ? "opacity-30" : ""} px-4 py-2 text-sm font-medium outline-hidden disabled:opacity-60 ${
+ selected
+ ? "border-b-2 border-mineshaft-300 text-mineshaft-200"
+ : "text-bunker-300"
+ }`
}
- isDisabled={Boolean(isEdit)}
- components={{ Option: CertificatePolicyOption }}
- />
- </FormControl>
- )}
- />
-
- <Controller
- control={control}
- name="enrollmentType"
- render={({ field: { onChange, ...field }, fieldState: { error } }) => (
- <FormControl
- label="Enrollment Method"
- isRequired
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Select
- {...field}
- onValueChange={(value) => {
- if (value === "est") {
- setValue("apiConfig", undefined);
- setValue("estConfig", {
- disableBootstrapCaValidation: false,
- passphrase: ""
- });
- setValue("acmeConfig", undefined);
- } else if (value === "api") {
- setValue("apiConfig", {
- autoRenew: false,
- renewBeforeDays: 30
- });
- setValue("estConfig", undefined);
- setValue("acmeConfig", undefined);
- } else if (value === "acme") {
- setValue("apiConfig", undefined);
- setValue("estConfig", undefined);
- setValue("acmeConfig", {
- skipDnsOwnershipVerification: false,
- skipEabBinding: false
- });
- }
- onChange(value);
- }}
- className="w-full"
- position="popper"
- isDisabled={Boolean(isEdit)}
+ key={step.key}
>
- <SelectItem value="api">API</SelectItem>
- {watchedIssuerType !== IssuerType.SELF_SIGNED && (
- <SelectItem value="est">EST</SelectItem>
+ {index + 1}. {step.name}
+ </Tab>
+ ))}
+ </Tab.List>
+ <Tab.Panels>
+ {/* Tab 1: Configuration */}
+ <Tab.Panel>
+ <Controller
+ control={control}
+ name="slug"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Name"
+ isRequired
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Input {...field} placeholder="your-profile-name" />
+ </FormControl>
)}
- {watchedIssuerType !== IssuerType.SELF_SIGNED && (
- <SelectItem value="acme">ACME</SelectItem>
+ />
+
+ <Controller
+ control={control}
+ name="description"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Description"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <TextArea {...field} placeholder="Enter profile description" rows={3} />
+ </FormControl>
)}
- </Select>
- </FormControl>
- )}
- />
-
- <div className="mb-4 space-y-4">
- <div className="flex items-center gap-2">
- <Checkbox
- id="enableDefaultTtl"
- isChecked={watch("defaultTtl")?.unit !== undefined}
- onCheckedChange={(checked) => {
- if (checked) {
- setValue("defaultTtl.value", 365);
- setValue("defaultTtl.unit", "days");
- } else {
- setValue("defaultTtl", null, { shouldValidate: true });
- }
- }}
- >
- Set default certificate TTL
- </Checkbox>
- <Tooltip content="Fallback validity period used when not explicitly specified in certificate request">
- <FontAwesomeIcon
- icon={faQuestionCircle}
- className="cursor-help text-mineshaft-400 hover:text-mineshaft-300"
- size="sm"
/>
- </Tooltip>
- </div>
- {watch("defaultTtl")?.unit !== undefined && (
- <div className="ml-3 border-l-2 border-mineshaft-500 pl-4">
- <div className="grid grid-cols-2 gap-4">
+ <Controller
+ control={control}
+ name="issuerType"
+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (
+ <FormControl
+ label="Issuer Type"
+ isRequired
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Select
+ {...field}
+ onValueChange={(value) => {
+ if (value === "self-signed") {
+ setValue("certificateAuthorityId", "");
+ setValue("enrollmentType", EnrollmentType.API);
+ setValue("apiConfig", {
+ autoRenew: false,
+ renewBeforeDays: 30
+ });
+ setValue("estConfig", undefined);
+ setValue("acmeConfig", {
+ skipDnsOwnershipVerification: false,
+ skipEabBinding: false
+ });
+ }
+ onChange(value);
+ }}
+ className="w-full"
+ position="popper"
+ isDisabled={Boolean(isEdit)}
+ >
+ <SelectItem value="ca">Certificate Authority</SelectItem>
+ <SelectItem value="self-signed">Self-Signed</SelectItem>
+ </Select>
+ </FormControl>
+ )}
+ />
+
+ {watchedIssuerType === "ca" && (
<Controller
control={control}
- name="defaultTtl.value"
- render={({ field, fieldState: { error } }) => (
+ name="certificateAuthorityId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
<FormControl
- label="Duration"
+ label="Issuing CA"
+ isRequired
isError={Boolean(error)}
errorText={error?.message}
>
- <Input
- {...field}
- type="number"
- placeholder="365"
- value={field.value == null ? "" : field.value}
- onChange={(e) => {
- const val = e.target.value;
- field.onChange(val === "" ? null : Number(val));
+ <FilterableSelect
+ value={certificateAuthorities.find((ca) => ca.id === value) || null}
+ onChange={(selectedCaValue) => {
+ if (Array.isArray(selectedCaValue)) {
+ onChange(selectedCaValue[0]?.id || "");
+ } else if (
+ selectedCaValue &&
+ typeof selectedCaValue === "object" &&
+ "id" in selectedCaValue
+ ) {
+ onChange(selectedCaValue.id || "");
+ } else {
+ onChange("");
+ }
}}
+ getOptionLabel={(ca) =>
+ ca.type === "internal" && ca.configuration.friendlyName
+ ? ca.configuration.friendlyName
+ : ca.name
+ }
+ getOptionValue={(ca) => ca.id}
+ options={certificateAuthorities}
+ groupBy="groupType"
+ getGroupHeaderLabel={getGroupHeaderLabel}
+ placeholder="Select a certificate authority"
+ isDisabled={Boolean(isEdit)}
+ className="w-full"
/>
</FormControl>
)}
/>
+ )}
+
+ {/* Azure ADCS Template Selection */}
+ {isAzureAdcsCa && (
<Controller
control={control}
- name="defaultTtl.unit"
- render={({ field, fieldState: { error } }) => (
- <FormControl label="Unit" isError={Boolean(error)} errorText={error?.message}>
- <Select
- {...field}
- value={field.value ?? "days"}
- onValueChange={field.onChange}
+ name="externalConfigs.template"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="Windows ADCS Template"
+ isRequired
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <FilterableSelect
+ value={
+ azureAdcsTemplatesData?.templates.find(
+ (template) => template.id === value
+ ) || null
+ }
+ onChange={(selectedTemplate) => {
+ if (Array.isArray(selectedTemplate)) {
+ onChange(selectedTemplate[0]?.id || "");
+ } else if (
+ selectedTemplate &&
+ typeof selectedTemplate === "object" &&
+ "id" in selectedTemplate
+ ) {
+ onChange(selectedTemplate.id || "");
+ } else {
+ onChange("");
+ }
+ }}
+ getOptionLabel={(template) => template.name}
+ getOptionValue={(template) => template.id}
+ options={azureAdcsTemplatesData?.templates || []}
+ placeholder="Select an Azure ADCS certificate template"
className="w-full"
- position="popper"
- >
- <SelectItem value="days">Days</SelectItem>
- <SelectItem value="months">Months</SelectItem>
- <SelectItem value="years">Years</SelectItem>
- </Select>
+ />
</FormControl>
)}
/>
- </div>
- </div>
- )}
- </div>
+ )}
- {/* EST Configuration */}
- {watchedEnrollmentType === "est" && (
- <div className="mb-4 space-y-4">
- <div className="space-y-4">
<Controller
control={control}
- name="estConfig.disableBootstrapCaValidation"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div className="flex items-center gap-3 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4">
- <Checkbox
- id="disableBootstrapCaValidation"
- isChecked={value}
- onCheckedChange={onChange}
- />
- <div className="space-y-1">
- <span className="text-sm font-medium text-mineshaft-100">
- Disable Bootstrap CA Validation
- </span>
- <p className="text-xs text-bunker-300">
- Skip CA certificate validation during EST bootstrap phase
- </p>
- </div>
- </div>
+ name="certificatePolicyId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="Certificate Policy"
+ isRequired
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <FilterableSelect
+ value={certificatePolicies.find((p) => p.id === value) ?? null}
+ onChange={(newValue) => {
+ const selected = newValue as SingleValue<PolicyOption>;
+ if (selected?.id === "_create") {
+ handlePopUpOpen("createPolicy");
+ return;
+ }
+ onChange(selected?.id || "");
+
+ // Reset defaults when policy changes
+ setValue("defaults", undefined);
+
+ if (watchedEnrollmentType === "est") {
+ setValue("apiConfig", undefined);
+ setValue("estConfig", {
+ disableBootstrapCaValidation: false,
+ passphrase: ""
+ });
+ setValue("acmeConfig", undefined);
+ } else if (watchedEnrollmentType === "api") {
+ setValue("apiConfig", {
+ autoRenew: false,
+ renewBeforeDays: 30
+ });
+ setValue("estConfig", undefined);
+ setValue("acmeConfig", undefined);
+ } else if (watchedEnrollmentType === "acme") {
+ setValue("estConfig", undefined);
+ setValue("apiConfig", undefined);
+ setValue("acmeConfig", {
+ skipDnsOwnershipVerification: false,
+ skipEabBinding: false
+ });
+ }
+ }}
+ options={policyOptions}
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ placeholder={
+ certificatePolicies.length === 0 && !canCreatePolicy
+ ? "No certificate policies available"
+ : "Select a certificate policy"
+ }
+ isDisabled={Boolean(isEdit)}
+ components={{ Option: CertificatePolicyOption }}
+ />
</FormControl>
)}
/>
<Controller
control={control}
- name="estConfig.passphrase"
- render={({ field, fieldState: { error } }) => (
+ name="enrollmentType"
+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
- label="EST Passphrase"
- isRequired={!isEdit}
+ label="Enrollment Method"
+ isRequired
isError={Boolean(error)}
errorText={error?.message}
>
- <Input
+ <Select
{...field}
- type="password"
- placeholder="Enter secure passphrase for EST authentication"
+ onValueChange={(value) => {
+ if (value === "est") {
+ setValue("apiConfig", undefined);
+ setValue("estConfig", {
+ disableBootstrapCaValidation: false,
+ passphrase: ""
+ });
+ setValue("acmeConfig", undefined);
+ } else if (value === "api") {
+ setValue("apiConfig", {
+ autoRenew: false,
+ renewBeforeDays: 30
+ });
+ setValue("estConfig", undefined);
+ setValue("acmeConfig", undefined);
+ } else if (value === "acme") {
+ setValue("apiConfig", undefined);
+ setValue("estConfig", undefined);
+ setValue("acmeConfig", {
+ skipDnsOwnershipVerification: false,
+ skipEabBinding: false
+ });
+ }
+ onChange(value);
+ }}
className="w-full"
- />
+ position="popper"
+ isDisabled={Boolean(isEdit)}
+ >
+ <SelectItem value="api">API</SelectItem>
+ {watchedIssuerType !== IssuerType.SELF_SIGNED && (
+ <SelectItem value="est">EST</SelectItem>
+ )}
+ {watchedIssuerType !== IssuerType.SELF_SIGNED && (
+ <SelectItem value="acme">ACME</SelectItem>
+ )}
+ </Select>
</FormControl>
)}
/>
- {!watchedDisableBootstrapValidation && (
- <Controller
- control={control}
- name="estConfig.caChain"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="CA Chain Certificate"
- isRequired={!isEdit}
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <div className="space-y-2">
- <TextArea
- {...field}
- placeholder="-----BEGIN CERTIFICATE-----&#10;MIIDXTCCAkWgAwIBAgIJAKoK/heBjcOuMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV&#10;BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX&#10;...&#10;-----END CERTIFICATE-----"
- rows={6}
- className="w-full font-mono text-xs"
- />
- <p className="text-xs text-bunker-400">
- Paste the complete CA certificate chain in PEM format
- </p>
- </div>
- </FormControl>
- )}
- />
- )}
- </div>
- </div>
- )}
-
- {/* API Configuration */}
- {watchedEnrollmentType === "api" && (
- <div className="mb-4 space-y-4">
- <Controller
- control={control}
- name="apiConfig.autoRenew"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div className="flex items-center gap-2">
- <Checkbox id="autoRenew" isChecked={value} onCheckedChange={onChange}>
- Enable Auto-Renewal By Default
- </Checkbox>
- <Tooltip content="If enabled, certificates issued against this profile will auto-renew at specified days before expiration.">
- <FontAwesomeIcon
- icon={faQuestionCircle}
- className="cursor-help text-mineshaft-400 hover:text-mineshaft-300"
- size="sm"
- />
- </Tooltip>
- </div>
- </FormControl>
- )}
- />
- </div>
- )}
-
- {/* ACME Configuration */}
- {watchedEnrollmentType === "acme" && (
- <div className="mb-4 space-y-4">
- <Controller
- control={control}
- name="acmeConfig.skipEabBinding"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div
- className={`flex items-center gap-3 rounded-md border bg-mineshaft-900 p-4 ${
- watchedSkipDnsOwnershipVerification
- ? "border-mineshaft-700 opacity-50"
- : "border-mineshaft-600"
- }`}
- >
- <Checkbox
- id="skipEabBinding"
- isChecked={value || false}
- onCheckedChange={onChange}
- isDisabled={watchedSkipDnsOwnershipVerification}
- />
- <div className="space-y-1">
- <span className="text-sm font-medium text-mineshaft-100">
- Skip External Account Binding (EAB)
- </span>
- <p className="text-xs text-bunker-300">
- Skip EAB authentication when clients create ACME accounts.
- </p>
- {watchedSkipDnsOwnershipVerification && (
- <p className="text-xs text-yellow-500">
- Cannot be enabled while DNS ownership validation is skipped.
- </p>
+ {/* EST Configuration */}
+ {watchedEnrollmentType === "est" && (
+ <div className="mb-4 space-y-4">
+ <div className="space-y-4">
+ <Controller
+ control={control}
+ name="estConfig.disableBootstrapCaValidation"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl isError={Boolean(error)} errorText={error?.message}>
+ <div className="flex items-center gap-3 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4">
+ <Checkbox
+ id="disableBootstrapCaValidation"
+ isChecked={value}
+ onCheckedChange={onChange}
+ />
+ <div className="space-y-1">
+ <span className="text-sm font-medium text-mineshaft-100">
+ Disable Bootstrap CA Validation
+ </span>
+ <p className="text-xs text-bunker-300">
+ Skip CA certificate validation during EST bootstrap phase
+ </p>
+ </div>
+ </div>
+ </FormControl>
)}
- </div>
- </div>
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="acmeConfig.skipDnsOwnershipVerification"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div
- className={`flex items-center gap-3 rounded-md border bg-mineshaft-900 p-4 ${
- watchedSkipEabBinding
- ? "border-mineshaft-700 opacity-50"
- : "border-mineshaft-600"
- }`}
- >
- <Checkbox
- id="skipDnsOwnershipVerification"
- isChecked={value || false}
- onCheckedChange={onChange}
- isDisabled={watchedSkipEabBinding}
/>
- <div className="space-y-1">
- <span className="text-sm font-medium text-mineshaft-100">
- Skip DNS Ownership Validation
- </span>
- <p className="text-xs text-bunker-300">
- Skip DNS ownership verification during ACME certificate issuance.
- </p>
- {watchedSkipEabBinding && (
- <p className="text-xs text-yellow-500">
- Cannot be enabled while EAB is skipped.
- </p>
+
+ <Controller
+ control={control}
+ name="estConfig.passphrase"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="EST Passphrase"
+ isRequired={!isEdit}
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Input
+ {...field}
+ type="password"
+ placeholder="Enter secure passphrase for EST authentication"
+ className="w-full"
+ />
+ </FormControl>
)}
- </div>
+ />
+
+ {!watchedDisableBootstrapValidation && (
+ <Controller
+ control={control}
+ name="estConfig.caChain"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="CA Chain Certificate"
+ isRequired={!isEdit}
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <div className="space-y-2">
+ <TextArea
+ {...field}
+ placeholder="-----BEGIN CERTIFICATE-----&#10;MIIDXTCCAkWgAwIBAgIJAKoK/heBjcOuMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV&#10;BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX&#10;...&#10;-----END CERTIFICATE-----"
+ rows={6}
+ className="w-full font-mono text-xs"
+ />
+ <p className="text-xs text-bunker-400">
+ Paste the complete CA certificate chain in PEM format
+ </p>
+ </div>
+ </FormControl>
+ )}
+ />
+ )}
</div>
- </FormControl>
+ </div>
+ )}
+
+ {/* API Configuration */}
+ {watchedEnrollmentType === "api" && (
+ <div className="mb-4 space-y-4">
+ <Controller
+ control={control}
+ name="apiConfig.autoRenew"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl isError={Boolean(error)} errorText={error?.message}>
+ <div className="flex items-center gap-2">
+ <Checkbox id="autoRenew" isChecked={value} onCheckedChange={onChange}>
+ Enable Auto-Renewal By Default
+ </Checkbox>
+ <Tooltip content="If enabled, certificates issued against this profile will auto-renew at specified days before expiration.">
+ <FontAwesomeIcon
+ icon={faQuestionCircle}
+ className="cursor-help text-mineshaft-400 hover:text-mineshaft-300"
+ size="sm"
+ />
+ </Tooltip>
+ </div>
+ </FormControl>
+ )}
+ />
+ </div>
+ )}
+
+ {/* ACME Configuration */}
+ {watchedEnrollmentType === "acme" && (
+ <div className="mb-4 space-y-4">
+ <Controller
+ control={control}
+ name="acmeConfig.skipEabBinding"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl isError={Boolean(error)} errorText={error?.message}>
+ <div
+ className={`flex items-center gap-3 rounded-md border bg-mineshaft-900 p-4 ${
+ watchedSkipDnsOwnershipVerification
+ ? "border-mineshaft-700 opacity-50"
+ : "border-mineshaft-600"
+ }`}
+ >
+ <Checkbox
+ id="skipEabBinding"
+ isChecked={value || false}
+ onCheckedChange={onChange}
+ isDisabled={watchedSkipDnsOwnershipVerification}
+ />
+ <div className="space-y-1">
+ <span className="text-sm font-medium text-mineshaft-100">
+ Skip External Account Binding (EAB)
+ </span>
+ <p className="text-xs text-bunker-300">
+ Skip EAB authentication when clients create ACME accounts.
+ </p>
+ {watchedSkipDnsOwnershipVerification && (
+ <p className="text-xs text-yellow-500">
+ Cannot be enabled while DNS ownership validation is skipped.
+ </p>
+ )}
+ </div>
+ </div>
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="acmeConfig.skipDnsOwnershipVerification"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl isError={Boolean(error)} errorText={error?.message}>
+ <div
+ className={`flex items-center gap-3 rounded-md border bg-mineshaft-900 p-4 ${
+ watchedSkipEabBinding
+ ? "border-mineshaft-700 opacity-50"
+ : "border-mineshaft-600"
+ }`}
+ >
+ <Checkbox
+ id="skipDnsOwnershipVerification"
+ isChecked={value || false}
+ onCheckedChange={onChange}
+ isDisabled={watchedSkipEabBinding}
+ />
+ <div className="space-y-1">
+ <span className="text-sm font-medium text-mineshaft-100">
+ Skip DNS Ownership Validation
+ </span>
+ <p className="text-xs text-bunker-300">
+ Skip DNS ownership verification during ACME certificate issuance.
+ </p>
+ {watchedSkipEabBinding && (
+ <p className="text-xs text-yellow-500">
+ Cannot be enabled while EAB is skipped.
+ </p>
+ )}
+ </div>
+ </div>
+ </FormControl>
+ )}
+ />
+ </div>
+ )}
+ {watchedAutoRenew && (
+ <div className="mb-4 space-y-4">
+ <Controller
+ control={control}
+ name="apiConfig.renewBeforeDays"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Auto-Renewal Days Before Expiration"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Input
+ {...field}
+ type="number"
+ placeholder="30"
+ min="1"
+ max="365"
+ className="w-full"
+ isDisabled={!watchedAutoRenew}
+ onChange={(e) => {
+ const { value } = e.target;
+ if (value === "") {
+ field.onChange("");
+ } else {
+ const parsed = parseInt(value, 10);
+ if (!Number.isNaN(parsed) && parsed >= 1 && parsed <= 365) {
+ field.onChange(parsed);
+ } else {
+ field.onChange(field.value || "");
+ }
+ }
+ }}
+ />
+ </FormControl>
+ )}
+ />
+ </div>
)}
- />
- </div>
- )}
- {watchedAutoRenew && (
- <div className="mb-4 space-y-4">
- <Controller
- control={control}
- name="apiConfig.renewBeforeDays"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Auto-Renewal Days Before Expiration"
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Input
- {...field}
- type="number"
- placeholder="30"
- min="1"
- max="365"
- className="w-full"
- isDisabled={!watchedAutoRenew}
- onChange={(e) => {
- const { value } = e.target;
- if (value === "") {
- field.onChange("");
- } else {
- const parsed = parseInt(value, 10);
- if (!Number.isNaN(parsed) && parsed >= 1 && parsed <= 365) {
- field.onChange(parsed);
- } else {
- field.onChange(field.value || "");
+ </Tab.Panel>
+
+ {/* Tab 2: Certificate Defaults */}
+ <Tab.Panel>
+ {!watchedPolicyId ? (
+ <EmptyState title="Select a certificate policy on the Configuration tab to configure defaults." />
+ ) : (
+ <div>
+ <p className="mb-4 text-sm text-bunker-300">
+ Set default values for certificates issued under this profile. These defaults
+ are used when a certificate request does not specify its own values.
+ </p>
+ {/* TTL — simple days number input */}
+ <Controller
+ name="defaults.ttlDays"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label={
+ <FormLabel
+ label="Time to Live (TTL) in Days"
+ icon={
+ <Tooltip content="Fallback validity period used when not explicitly specified in certificate request. Leave empty for no TTL default.">
+ <FontAwesomeIcon
+ icon={faQuestionCircle}
+ className="cursor-help text-mineshaft-400 hover:text-mineshaft-300"
+ size="sm"
+ />
+ </Tooltip>
+ }
+ />
}
- }
- }}
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Input
+ type="number"
+ placeholder="e.g. 365"
+ value={field.value == null ? "" : field.value}
+ onChange={(e) => {
+ const val = e.target.value;
+ field.onChange(val === "" ? null : Number(val));
+ }}
+ />
+ </FormControl>
+ )}
/>
- </FormControl>
+
+ {/* Subject Attributes — only if policy allows subject fields */}
+ {policyConstraints.shouldShowSubjectSection && (
+ <SubjectAttributesField
+ control={control}
+ allowedAttributeTypes={policyConstraints.allowedSubjectAttributeTypes}
+ namePrefix="defaults.subjectAttributes"
+ />
+ )}
+
+ {/* Algorithms — filtered to policy-allowed values, with "None" option */}
+ {(policyConstraints.allowedSignatureAlgorithms.length > 0 ||
+ policyConstraints.allowedKeyAlgorithms.length > 0) && (
+ <AlgorithmSelectors
+ control={control}
+ signatureFieldName="defaults.signatureAlgorithm"
+ keyFieldName="defaults.keyAlgorithm"
+ availableSignatureAlgorithms={policyConstraints.allowedSignatureAlgorithms}
+ availableKeyAlgorithms={policyConstraints.allowedKeyAlgorithms}
+ isRequired={false}
+ nonePlaceholder="No default"
+ />
+ )}
+
+ {/* Key Usages, Ext Key Usages, Basic Constraints — in Accordion */}
+ {(filteredKeyUsages.length > 0 ||
+ filteredExtendedKeyUsages.length > 0 ||
+ policyConstraints.templateAllowsCA) && (
+ <Accordion type="single" collapsible className="w-full">
+ {filteredKeyUsages.length > 0 && (
+ <KeyUsageSection
+ control={control}
+ title="Key Usages"
+ accordionValue="key-usages"
+ namePrefix="defaults.keyUsages"
+ options={filteredKeyUsages as Array<{ value: string; label: string }>}
+ requiredUsages={[]}
+ />
+ )}
+ {filteredExtendedKeyUsages.length > 0 && (
+ <KeyUsageSection
+ control={control}
+ title="Extended Key Usages"
+ accordionValue="extended-key-usages"
+ namePrefix="defaults.extendedKeyUsages"
+ options={
+ filteredExtendedKeyUsages as Array<{ value: string; label: string }>
+ }
+ requiredUsages={[]}
+ />
+ )}
+ {policyConstraints.templateAllowsCA && (
+ <AccordionItem value="basic-constraints">
+ <AccordionTrigger>Basic Constraints</AccordionTrigger>
+ <AccordionContent>
+ <div className="space-y-4 pl-2">
+ <Controller
+ control={control}
+ name="defaults.basicConstraints.isCA"
+ render={({ field: { value, onChange } }) => (
+ <div className="flex items-center gap-3">
+ <Checkbox
+ id="defaults-isCA"
+ isChecked={value || false}
+ onCheckedChange={(checked) => {
+ onChange(checked);
+ if (!checked) {
+ setValue(
+ "defaults.basicConstraints.pathLength",
+ undefined
+ );
+ }
+ }}
+ />
+ <div className="space-y-1">
+ <FormLabel
+ id="defaults-isCA"
+ className="cursor-pointer text-sm font-medium text-mineshaft-100"
+ label="Issue as Certificate Authority"
+ />
+ <p className="text-xs text-bunker-300">
+ Certificates will default to CA:TRUE extension
+ </p>
+ </div>
+ </div>
+ )}
+ />
+
+ {watchedDefaultsIsCA && (
+ <Controller
+ control={control}
+ name="defaults.basicConstraints.pathLength"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Path Length"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Input
+ {...field}
+ type="number"
+ min={0}
+ placeholder="Leave empty for no constraint"
+ className="w-full"
+ value={field.value ?? ""}
+ onChange={(e) => {
+ const val = e.target.value;
+ if (val === "") {
+ field.onChange(null);
+ } else {
+ const numVal = parseInt(val, 10);
+ field.onChange(Number.isNaN(numVal) ? null : numVal);
+ }
+ }}
+ />
+ </FormControl>
+ )}
+ />
+ )}
+ </div>
+ </AccordionContent>
+ </AccordionItem>
+ )}
+ </Accordion>
+ )}
+ </div>
)}
- />
- </div>
- )}
+ </Tab.Panel>
+ </Tab.Panels>
+ </Tab.Group>
- <div className="flex gap-3">
+ {/* Next/Back buttons OUTSIDE tabs — always visible */}
+ <div className="mt-6 flex justify-between border-t border-mineshaft-600 pt-4">
+ <Button type="button" variant="outline_bg" onClick={handlePrev}>
+ {selectedStepIndex === 0 ? "Cancel" : "Back"}
+ </Button>
<Button
- type="submit"
- colorSchema="primary"
- isLoading={isEdit ? updateProfile.isPending : createProfile.isPending}
+ type="button"
+ onClick={handleNext}
+ isLoading={createProfile.isPending || updateProfile.isPending}
isDisabled={
- !formState.isValid || (isEdit ? updateProfile.isPending : createProfile.isPending)
+ createProfile.isPending ||
+ updateProfile.isPending ||
+ (!formState.isValid && isFinalStep)
}
>
- {isEdit ? "Save Changes" : "Create"}
- </Button>
- <Button
- variant="outline_bg"
- onClick={() => {
- reset();
- onClose();
- }}
- disabled={isEdit ? updateProfile.isPending : createProfile.isPending}
- >
- Cancel
+ {isFinalStep && (isEdit ? "Update" : "Create")}
+ {!isFinalStep && "Next"}
</Button>
</div>
</form>