Skip to content

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

PKI policy optional fields

Carlos Monastyrski3a3b937e31b5
diff --git a/backend/src/server/routes/v1/certificate-profiles-router.ts b/backend/src/server/routes/v1/certificate-profiles-router.ts
index 8cf28fa689..2ea171ccbc 100644
--- a/backend/src/server/routes/v1/certificate-profiles-router.ts
+++ b/backend/src/server/routes/v1/certificate-profiles-router.ts
@@ -15,12 +15,22 @@ import {
CertExtendedKeyUsageType,
CertKeyAlgorithm,
CertKeyUsageType,
- CertSignatureAlgorithm
+ CertSignatureAlgorithm,
+ CertSubjectAlternativeNameType
} 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";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+const SubjectAltNameDefaultsSchema = z
+ .array(
+ z.object({
+ type: z.nativeEnum(CertSubjectAlternativeNameType),
+ value: z.string().trim().min(1)
+ })
+ )
+ .optional();
+
const CertificateProfileDefaultsResponseSchema = z
.object({
ttlDays: z.number().optional(),
@@ -39,7 +49,8 @@ const CertificateProfileDefaultsResponseSchema = z
organizationalUnit: z.string().optional(),
country: z.string().optional(),
state: z.string().optional(),
- locality: z.string().optional()
+ locality: z.string().optional(),
+ subjectAltNames: SubjectAltNameDefaultsSchema
})
.nullish();
@@ -122,7 +133,8 @@ export const registerCertificateProfilesRouter = async (
organizationalUnit: z.string().optional(),
country: z.string().optional(),
state: z.string().optional(),
- locality: z.string().optional()
+ locality: z.string().optional(),
+ subjectAltNames: SubjectAltNameDefaultsSchema
})
.nullish()
})
@@ -605,7 +617,8 @@ export const registerCertificateProfilesRouter = async (
organizationalUnit: z.string().optional(),
country: z.string().optional(),
state: z.string().optional(),
- locality: z.string().optional()
+ locality: z.string().optional(),
+ subjectAltNames: SubjectAltNameDefaultsSchema
})
.nullish()
})
diff --git a/backend/src/services/certificate-common/certificate-utils.ts b/backend/src/services/certificate-common/certificate-utils.ts
index 04fb185283..fd75720c7e 100644
--- a/backend/src/services/certificate-common/certificate-utils.ts
+++ b/backend/src/services/certificate-common/certificate-utils.ts
@@ -96,6 +96,12 @@ export const buildCertificateSubjectFromTemplate = (
};
if (!templateAttributes || templateAttributes.length === 0) {
+ Object.entries(attributeMap).forEach(([attrType, requestKey]) => {
+ const value = request[requestKey];
+ if (value && typeof value === "string") {
+ subject[attrType] = value;
+ }
+ });
return subject;
}
diff --git a/backend/src/services/certificate-policy/certificate-policy-service.test.ts b/backend/src/services/certificate-policy/certificate-policy-service.test.ts
index e687cc3cf0..262da7e56b 100644
--- a/backend/src/services/certificate-policy/certificate-policy-service.test.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-service.test.ts
@@ -1165,7 +1165,7 @@ describe("CertificatePolicyService", () => {
expect(result.errors).toContain("email SAN is not allowed by template policy (not defined in template)");
});
- it("should reject requests with unlisted key usages when template doesn't define any", async () => {
+ it("should allow any key usages when template does not define key-usage rules", async () => {
const templateWithoutKeyUsages = {
...sampleTemplate,
keyUsages: undefined
@@ -1174,16 +1174,15 @@ describe("CertificatePolicyService", () => {
const requestWithKeyUsages = {
commonName: "example.com",
- keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE], // This should be rejected
+ keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE], // undefined policy = allow all
validity: { ttl: "30d" }
};
const result = await service.validateCertificateRequest("template-123", requestWithKeyUsages);
- expect(result.isValid).toBe(false);
- expect(result.errors).toContain("Key usages are not allowed by template policy (not defined in template)");
+ expect(result.errors).not.toContain("Key usages are not allowed by template policy (not defined in template)");
});
- it("should reject requests with algorithms when template doesn't define any", async () => {
+ it("should allow any algorithms when template does not define algorithm rules", async () => {
const templateWithoutAlgorithms = {
...sampleTemplate,
algorithms: undefined
@@ -1194,17 +1193,16 @@ describe("CertificatePolicyService", () => {
commonName: "example.com",
keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE, CertKeyUsageType.KEY_ENCIPHERMENT],
extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH],
- signatureAlgorithm: "RSA-SHA256", // This should be rejected
- keyAlgorithm: "RSA-2048", // This should be rejected
+ signatureAlgorithm: "RSA-SHA256", // undefined policy = allow all
+ keyAlgorithm: "RSA-2048", // undefined policy = allow all
validity: { ttl: "30d" }
};
const result = await service.validateCertificateRequest("template-123", requestWithAlgorithms);
- expect(result.isValid).toBe(false);
- expect(result.errors).toContain(
+ expect(result.errors).not.toContain(
"Signature algorithm 'RSA-SHA256' is not allowed by template policy (not defined in template)"
);
- expect(result.errors).toContain(
+ expect(result.errors).not.toContain(
"Key algorithm 'RSA-2048' is not allowed by template policy (not defined in template)"
);
});
@@ -1436,7 +1434,7 @@ describe("CertificatePolicyService", () => {
expect(result.errors).toHaveLength(0);
});
- it("should reject algorithms when template has no algorithm constraints", async () => {
+ it("should allow any algorithms when template has no algorithm constraints", async () => {
const templateWithoutAlgorithms = {
...sampleTemplate,
algorithms: undefined
@@ -1454,11 +1452,10 @@ describe("CertificatePolicyService", () => {
};
const result = await service.validateCertificateRequest("template-123", requestWithAlgorithms);
- expect(result.isValid).toBe(false);
- expect(result.errors).toContain(
+ expect(result.errors).not.toContain(
"Signature algorithm 'RSA-SHA256' is not allowed by template policy (not defined in template)"
);
- expect(result.errors).toContain(
+ expect(result.errors).not.toContain(
"Key algorithm 'RSA_2048' is not allowed by template policy (not defined in template)"
);
});
diff --git a/backend/src/services/certificate-policy/certificate-policy-service.ts b/backend/src/services/certificate-policy/certificate-policy-service.ts
index 4a425fd684..ce08a13d66 100644
--- a/backend/src/services/certificate-policy/certificate-policy-service.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-service.ts
@@ -387,12 +387,8 @@ export const certificatePolicyServiceFactory = ({
errors.push(`${attrType} is not allowed by template policy (not defined in template)`);
}
}
- } else if (requestAttributes.size > 0) {
- // No subject policies defined but request has subject attributes - deny all
- for (const [attrType] of requestAttributes) {
- errors.push(`${attrType} is not allowed by template policy (no subject policies defined)`);
- }
}
+ // No subject policy defined means no subject constraint (allow all)
// Validate Subject Alternative Names
const sansPolicies = template.sans;
@@ -465,12 +461,8 @@ export const certificatePolicyServiceFactory = ({
errors.push(`${requestSanType} SAN is not allowed by template policy (not defined in template)`);
}
}
- } else if (request.subjectAlternativeNames && request.subjectAlternativeNames.length > 0) {
- // No SAN policies defined but request has SANs - deny all
- for (const san of request.subjectAlternativeNames) {
- errors.push(`${san.type} SAN is not allowed by template policy (no SAN policies defined)`);
- }
}
+ // No SAN policy defined means no SAN constraint (allow all)
// Validate key usages
const keyUsagePolicy = template.keyUsages;
@@ -504,9 +496,8 @@ export const certificatePolicyServiceFactory = ({
errors.push(`Invalid key usages: ${invalidUsages.join(", ")}`);
}
}
- } else if (request.keyUsages && request.keyUsages.length > 0) {
- errors.push(`Key usages are not allowed by template policy (not defined in template)`);
}
+ // No key usage policy defined means no key usage constraint (allow all)
// Validate extended key usages
const extendedKeyUsagePolicy = template.extendedKeyUsages;
@@ -549,34 +540,21 @@ export const certificatePolicyServiceFactory = ({
errors.push(`Invalid extended key usages: ${invalidExtendedUsages.join(", ")}`);
}
}
- } else if (request.extendedKeyUsages && request.extendedKeyUsages.length > 0) {
- errors.push(`Extended key usages are not allowed by template policy (not defined in template)`);
}
+ // No extended key usage policy defined means no EKU constraint (allow all)
- // Validate algorithms with new structure
- if (request.signatureAlgorithm) {
- if (template.algorithms?.signature && template.algorithms.signature.length > 0) {
- const mappedTemplateAlgorithms = template.algorithms.signature.map(mapTemplateSignatureAlgorithmToApi);
- if (!mappedTemplateAlgorithms.includes(request.signatureAlgorithm)) {
- errors.push(`Signature algorithm '${request.signatureAlgorithm}' is not allowed by template policy`);
- }
- } else if (!template.algorithms?.signature) {
- errors.push(
- `Signature algorithm '${request.signatureAlgorithm}' is not allowed by template policy (not defined in template)`
- );
+ // An undefined algorithm policy means no algorithm constraint (allow all).
+ if (request.signatureAlgorithm && template.algorithms?.signature && template.algorithms.signature.length > 0) {
+ const mappedTemplateAlgorithms = template.algorithms.signature.map(mapTemplateSignatureAlgorithmToApi);
+ if (!mappedTemplateAlgorithms.includes(request.signatureAlgorithm)) {
+ errors.push(`Signature algorithm '${request.signatureAlgorithm}' is not allowed by template policy`);
}
}
- if (request.keyAlgorithm) {
- if (template.algorithms?.keyAlgorithm && template.algorithms.keyAlgorithm.length > 0) {
- const mappedTemplateKeyTypes = template.algorithms.keyAlgorithm.map(mapTemplateKeyAlgorithmToApi);
- if (!mappedTemplateKeyTypes.includes(request.keyAlgorithm)) {
- errors.push(`Key algorithm '${request.keyAlgorithm}' is not allowed by template policy`);
- }
- } else if (!template.algorithms?.keyAlgorithm) {
- errors.push(
- `Key algorithm '${request.keyAlgorithm}' is not allowed by template policy (not defined in template)`
- );
+ if (request.keyAlgorithm && template.algorithms?.keyAlgorithm && template.algorithms.keyAlgorithm.length > 0) {
+ const mappedTemplateKeyTypes = template.algorithms.keyAlgorithm.map(mapTemplateKeyAlgorithmToApi);
+ if (!mappedTemplateKeyTypes.includes(request.keyAlgorithm)) {
+ errors.push(`Key algorithm '${request.keyAlgorithm}' is not allowed by template policy`);
}
}
diff --git a/backend/src/services/certificate-profile/certificate-profile-types.ts b/backend/src/services/certificate-profile/certificate-profile-types.ts
index 213750fc0f..4f3402db73 100644
--- a/backend/src/services/certificate-profile/certificate-profile-types.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-types.ts
@@ -8,7 +8,8 @@ import {
CertExtendedKeyUsageType,
CertKeyAlgorithm,
CertKeyUsageType,
- CertSignatureAlgorithm
+ CertSignatureAlgorithm,
+ CertSubjectAlternativeNameType
} from "../certificate-common/certificate-constants";
export enum EnrollmentType {
@@ -36,6 +37,7 @@ export type TCertificateProfileDefaults = {
country?: string;
state?: string;
locality?: string;
+ subjectAltNames?: { type: CertSubjectAlternativeNameType; value: string }[];
};
export type TCertificateProfile = Omit<
diff --git a/backend/src/services/certificate-v3/certificate-v3-fns.ts b/backend/src/services/certificate-v3/certificate-v3-fns.ts
index 770b3259fe..0a6daee7c4 100644
--- a/backend/src/services/certificate-v3/certificate-v3-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-fns.ts
@@ -121,6 +121,7 @@ export const applyProfileDefaults = <
keyUsages?: string[];
extendedKeyUsages?: string[];
basicConstraints?: { isCA: boolean; pathLength?: number };
+ altNames?: { type: string; value: string }[];
}
>(
request: T,
@@ -128,6 +129,8 @@ export const applyProfileDefaults = <
): T => {
if (!defaults) return request;
+ const altNames = request.altNames && request.altNames.length > 0 ? request.altNames : defaults.subjectAltNames;
+
// For scalar fields, key-presence distinguishes "omitted" (use default) from "explicitly set/cleared".
// CSR extraction (extractCertificateRequestFromCSR) omits keys for absent fields,
// while API routes include keys with undefined values for explicitly cleared fields.
@@ -143,6 +146,7 @@ export const applyProfileDefaults = <
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
+ basicConstraints: request.basicConstraints !== undefined ? request.basicConstraints : defaults.basicConstraints,
+ altNames
};
};
diff --git a/frontend/src/hooks/api/certificatePolicies/types.ts b/frontend/src/hooks/api/certificatePolicies/types.ts
index aed6932228..2ba673f38f 100644
--- a/frontend/src/hooks/api/certificatePolicies/types.ts
+++ b/frontend/src/hooks/api/certificatePolicies/types.ts
@@ -77,6 +77,7 @@ export type TCertificatePolicy = {
};
export type TCreateCertificatePolicyDTO = {
+ projectId?: string;
name: string;
description?: string;
subject?: TCertificatePolicyRule["subject"];
diff --git a/frontend/src/hooks/api/certificateProfiles/types.ts b/frontend/src/hooks/api/certificateProfiles/types.ts
index 8fa0ce0a73..a196c51ed9 100644
--- a/frontend/src/hooks/api/certificateProfiles/types.ts
+++ b/frontend/src/hooks/api/certificateProfiles/types.ts
@@ -28,6 +28,7 @@ export type TCertificateProfileDefaults = {
country?: string;
state?: string;
locality?: string;
+ subjectAltNames?: { type: string; value: string }[];
};
export type TCertificateProfile = {
diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/CertificatePolicyDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/CertificatePolicyDetailsByIDPage.tsx
index 1f1a8e065a..4e53c0cd87 100644
--- a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/CertificatePolicyDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/CertificatePolicyDetailsByIDPage.tsx
@@ -26,6 +26,7 @@ import {
PolicyAlgorithmsSection,
PolicyDetailsSection,
PolicyKeyUsagesSection,
+ PolicyNoRulesSection,
PolicySansRulesSection,
PolicySubjectRulesSection,
PolicyValiditySection
@@ -62,6 +63,21 @@ const Page = () => {
const projectId = currentProject?.id || "";
+ const hasAnyEnforcement = Boolean(
+ policy?.subject?.length ||
+ policy?.sans?.length ||
+ policy?.keyUsages?.required?.length ||
+ policy?.keyUsages?.allowed?.length ||
+ policy?.keyUsages?.denied?.length ||
+ policy?.extendedKeyUsages?.required?.length ||
+ policy?.extendedKeyUsages?.allowed?.length ||
+ policy?.extendedKeyUsages?.denied?.length ||
+ policy?.algorithms?.signature?.length ||
+ policy?.algorithms?.keyAlgorithm?.length ||
+ policy?.validity?.max ||
+ policy?.basicConstraints?.isCA
+ );
+
const handleDeleteConfirm = async () => {
if (!policy) return;
@@ -143,11 +159,17 @@ const Page = () => {
/>
</div>
<div className="flex flex-1 flex-col gap-y-5">
- <PolicyValiditySection policy={policy} />
- <PolicySubjectRulesSection policy={policy} />
- <PolicySansRulesSection policy={policy} />
- <PolicyKeyUsagesSection policy={policy} />
- <PolicyAlgorithmsSection policy={policy} />
+ {hasAnyEnforcement ? (
+ <>
+ <PolicyValiditySection policy={policy} />
+ <PolicySubjectRulesSection policy={policy} />
+ <PolicySansRulesSection policy={policy} />
+ <PolicyKeyUsagesSection policy={policy} />
+ <PolicyAlgorithmsSection policy={policy} />
+ </>
+ ) : (
+ <PolicyNoRulesSection />
+ )}
</div>
</div>
diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyNoRulesSection.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyNoRulesSection.tsx
new file mode 100644
index 0000000000..a862bb8081
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyNoRulesSection.tsx
@@ -0,0 +1,21 @@
+import { ShieldOff } from "lucide-react";
+
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@app/components/v3";
+
+export const PolicyNoRulesSection = () => (
+ <Card className="w-full">
+ <CardHeader className="border-b">
+ <CardTitle>No restrictions configured</CardTitle>
+ <CardDescription>This policy does not enforce any constraints</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex flex-col items-center justify-center gap-3 py-12 text-center">
+ <ShieldOff className="size-8 text-muted" />
+ <p className="max-w-md text-sm text-muted">
+ Certificates issued under this policy can use any subject attributes, subject alternative
+ names, algorithms, key usages, and validity period. Edit the policy to add restrictions.
+ </p>
+ </div>
+ </CardContent>
+ </Card>
+);
diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/index.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/index.tsx
index cc9dedfd0a..ea181230d2 100644
--- a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/index.tsx
+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/index.tsx
@@ -1,6 +1,7 @@
export { PolicyAlgorithmsSection } from "./PolicyAlgorithmsSection";
export { PolicyDetailsSection } from "./PolicyDetailsSection";
export { PolicyKeyUsagesSection } from "./PolicyKeyUsagesSection";
+export { PolicyNoRulesSection } from "./PolicyNoRulesSection";
export { PolicySansRulesSection } from "./PolicySansRulesSection";
export { PolicySubjectRulesSection } from "./PolicySubjectRulesSection";
export { PolicyValiditySection } from "./PolicyValiditySection";
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx
index 1cd0c34961..a3a88677ff 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx
@@ -12,20 +12,22 @@ type SubjectAltNamesFieldProps = {
allowedSanTypes: CertSubjectAlternativeNameType[];
error?: string;
shouldUnregister?: boolean;
+ namePrefix?: string;
};
export const SubjectAltNamesField = ({
control,
allowedSanTypes,
error,
- shouldUnregister
+ shouldUnregister,
+ namePrefix = "subjectAltNames"
}: SubjectAltNamesFieldProps) => {
const sanTypeLabels = getSanTypeLabels();
return (
<Controller
control={control}
- name="subjectAltNames"
+ name={namePrefix}
shouldUnregister={shouldUnregister}
render={({ field: { onChange, value } }) => {
const currentValues = value || [];
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
index 22f407cf51..0f3d25ecc0 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { UseFormSetValue, UseFormWatch } from "react-hook-form";
import {
@@ -99,16 +99,24 @@ export const useCertificatePolicy = (
});
const filteredKeyUsages = useMemo(() => {
+ if (constraints.allowedKeyUsages.length === 0) return [...KEY_USAGES_OPTIONS];
return KEY_USAGES_OPTIONS.filter(({ value }) => constraints.allowedKeyUsages.includes(value));
}, [constraints.allowedKeyUsages]);
const filteredExtendedKeyUsages = useMemo(() => {
+ if (constraints.allowedExtendedKeyUsages.length === 0) return [...EXTENDED_KEY_USAGES_OPTIONS];
return EXTENDED_KEY_USAGES_OPTIONS.filter(({ value }) =>
constraints.allowedExtendedKeyUsages.includes(value)
);
}, [constraints.allowedExtendedKeyUsages]);
const availableSignatureAlgorithms = useMemo(() => {
+ if (constraints.allowedSignatureAlgorithms.length === 0) {
+ return SIGNATURE_ALGORITHMS_OPTIONS.map((opt) => ({
+ value: opt.value as string,
+ label: opt.label
+ }));
+ }
const allowed = new Set(
constraints.allowedSignatureAlgorithms.map(mapPolicySignatureAlgorithmToApi)
);
@@ -119,6 +127,9 @@ export const useCertificatePolicy = (
}, [constraints.allowedSignatureAlgorithms]);
const availableKeyAlgorithms = useMemo(() => {
+ if (constraints.allowedKeyAlgorithms.length === 0) {
+ return certKeyAlgorithms.map((opt) => ({ value: opt.value as string, label: opt.label }));
+ }
const allowed = new Set(constraints.allowedKeyAlgorithms.map(mapPolicyKeyAlgorithmToApi));
return certKeyAlgorithms
.filter((opt) => allowed.has(opt.value))
@@ -148,8 +159,14 @@ export const useCertificatePolicy = (
});
};
+ const prevProfileIdRef = useRef<string | undefined>(undefined);
+
useEffect(() => {
if (templateData && selectedProfile && isModalOpen) {
+ const profileChanged = prevProfileIdRef.current !== selectedProfile.id;
+ prevProfileIdRef.current = selectedProfile.id;
+
+ // CA issuance is a privilege boundary: an undefined basicConstraints policy denies CA by default
const isCaPolicy =
(templateData.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED;
const templateAllowsCA =
@@ -204,7 +221,7 @@ export const useCertificatePolicy = (
}
}
- // Handle SAN types
+ // Handle SAN types. An undefined SAN policy allows every SAN type (allow all).
if (templateData.sans && templateData.sans.length > 0) {
const sanTypes: CertSubjectAlternativeNameType[] = [];
templateData.sans.forEach((sanPolicy: any) => {
@@ -215,13 +232,17 @@ export const useCertificatePolicy = (
newConstraints.allowedSanTypes = sanTypes;
newConstraints.shouldShowSanSection = true;
} else {
- newConstraints.allowedSanTypes = [];
- newConstraints.shouldShowSanSection = false;
- setValue("subjectAltNames", []);
+ newConstraints.allowedSanTypes = [
+ CertSubjectAlternativeNameType.DNS_NAME,
+ CertSubjectAlternativeNameType.IP_ADDRESS,
+ CertSubjectAlternativeNameType.EMAIL,
+ CertSubjectAlternativeNameType.URI
+ ];
+ newConstraints.shouldShowSanSection = true;
}
+ newConstraints.shouldShowSubjectSection = true;
if (templateData.subject && templateData.subject.length > 0) {
- newConstraints.shouldShowSubjectSection = true;
const subjectTypes: CertSubjectAttributeType[] = [];
templateData.subject.forEach((subjectPolicy: any) => {
if (!subjectTypes.includes(subjectPolicy.type)) {
@@ -230,67 +251,78 @@ export const useCertificatePolicy = (
});
newConstraints.allowedSubjectAttributeTypes =
subjectTypes.length > 0 ? subjectTypes : [CertSubjectAttributeType.COMMON_NAME];
+ } else {
+ // No subject policy allows every subject attribute type (allow all)
+ newConstraints.allowedSubjectAttributeTypes = [
+ CertSubjectAttributeType.COMMON_NAME,
+ CertSubjectAttributeType.ORGANIZATION,
+ CertSubjectAttributeType.ORGANIZATIONAL_UNIT,
+ CertSubjectAttributeType.COUNTRY,
+ CertSubjectAttributeType.STATE,
+ CertSubjectAttributeType.LOCALITY
+ ];
+ }
- // 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
- });
- }
+ // 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) {
- if (defaultSubjectAttrs.length > 0) {
- // Filter to only allowed attribute types
- const filteredDefaults = defaultSubjectAttrs.filter((attr) =>
- newConstraints.allowedSubjectAttributeTypes.includes(attr.type)
- );
- const subjectValue =
- filteredDefaults.length > 0
- ? filteredDefaults
- : [{ type: newConstraints.allowedSubjectAttributeTypes[0], value: "" }];
- setValue("subjectAttributes", subjectValue);
- } else {
- const defaultType = newConstraints.allowedSubjectAttributeTypes[0];
- setValue("subjectAttributes", [{ type: defaultType, value: "" }]);
- }
+ // Switching profiles resets SAN entries so a previous profile's values don't carry over.
+ if (profileChanged) {
+ setValue("subjectAltNames", []);
+ }
+
+ const currentSubjectAttrs = watch("subjectAttributes");
+ if (profileChanged || !currentSubjectAttrs || currentSubjectAttrs.length === 0) {
+ if (defaultSubjectAttrs.length > 0) {
+ // Filter to only allowed attribute types
+ const filteredDefaults = defaultSubjectAttrs.filter((attr) =>
+ newConstraints.allowedSubjectAttributeTypes.includes(attr.type)
+ );
+ const subjectValue =
+ filteredDefaults.length > 0
+ ? filteredDefaults
+ : [{ type: newConstraints.allowedSubjectAttributeTypes[0], value: "" }];
+ setValue("subjectAttributes", subjectValue);
+ } else {
+ const defaultType = newConstraints.allowedSubjectAttributeTypes[0];
+ setValue("subjectAttributes", [{ type: defaultType, value: "" }]);
}
- } else {
- newConstraints.shouldShowSubjectSection = false;
- newConstraints.allowedSubjectAttributeTypes = [];
- setValue("subjectAttributes", undefined);
}
// Set isCA if template requires it
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
index 67a41f9949..ab4f737e67 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
@@ -1,29 +1,37 @@
/* eslint-disable no-nested-ternary */
-import { useEffect } from "react";
+import { ReactNode, useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
-import { faPlus, faQuestionCircle, faTrash } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
+import { Plus, ShieldCheck, Trash2 } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import {
- Accordion,
- AccordionContent,
- AccordionItem,
- AccordionTrigger,
+ Badge,
Button,
Checkbox,
- FormControl,
- IconButton,
+ DocumentationLinkBadge,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
Input,
- Modal,
- ModalContent,
Select,
+ SelectContent,
SelectItem,
- TextArea,
- Tooltip
-} from "@app/components/v2";
-import { Badge } from "@app/components/v3";
+ SelectTrigger,
+ SelectValue,
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ Stepper,
+ StepperList,
+ StepperStep,
+ Switch,
+ TextArea
+} from "@app/components/v3";
import { useProject, useSubscription } from "@app/context";
import {
TCertificatePolicy,
@@ -33,6 +41,7 @@ import {
} from "@app/hooks/api/certificatePolicies";
import { isPqcAlgorithm } from "@app/hooks/api/certificates/constants";
+import { PkiDocsUrls } from "../../../pki-docs-urls";
import {
CertDurationUnit,
CertExtendedKeyUsageType,
@@ -42,6 +51,10 @@ import {
CertSubjectAlternativeNameType,
CertSubjectAttributeInclude,
CertSubjectAttributeType,
+ EXTENDED_KEY_USAGE_OPTIONS,
+ formatExtendedKeyUsage,
+ formatKeyUsage,
+ KEY_USAGE_OPTIONS,
POLICY_PRESET_IDS,
type PolicyPresetId,
SAN_INCLUDE_OPTIONS,
@@ -50,7 +63,7 @@ import {
SUBJECT_ATTRIBUTE_TYPE_OPTIONS
} from "./shared/certificate-constants";
import { CERTIFICATE_POLICY_PRESETS } from "./shared/policy-presets";
-import { KeyUsagesSection, PolicyFormData, policySchema } from "./shared";
+import { PolicyFormData, policySchema } from "./shared";
export type FormData = PolicyFormData;
@@ -97,6 +110,14 @@ const SAN_INCLUDE_LABELS: Record<(typeof SAN_INCLUDE_OPTIONS)[number], string> =
prohibit: "Deny"
};
+const USAGE_POLICY_OPTIONS = [
+ { value: "deny", label: "Deny" },
+ { value: "allow", label: "Allow" },
+ { value: "require", label: "Require" }
+] as const;
+
+type UsagePolicy = (typeof USAGE_POLICY_OPTIONS)[number]["value"];
+
const SIGNATURE_ALGORITHMS = [
"SHA256-RSA",
"SHA384-RSA",
@@ -121,6 +142,83 @@ const KEY_ALGORITHMS = [
"ML-DSA-87"
] as const;
+const STEPS = [
+ {
+ name: "Basics",
+ shortDescription: "Name and preset",
+ title: "Basics",
+ subtitle: "Name this policy and optionally start from a preset.",
+ rightLabel: "BASICS",
+ rightDescription:
+ "A clear name and description help your team identify what this policy enforces. Applying a preset fills the remaining steps with a recommended baseline that you can refine as you go."
+ },
+ {
+ name: "Subject",
+ shortDescription: "Attributes and SANs",
+ title: "Subject",
+ subtitle:
+ "Control the subject attributes and alternative names allowed on issued certificates.",
+ rightLabel: "SUBJECT",
+ rightDescription:
+ "By default, issued certificates may carry any subject attributes and subject alternative names. Enable a restriction to define exactly which values are allowed, required, or denied. Requests that fall outside those rules are rejected at issuance."
+ },
+ {
+ name: "Algorithms",
+ shortDescription: "Signature and key",
+ title: "Algorithms",
+ subtitle: "Restrict the signature and key algorithms certificates may use.",
+ rightLabel: "ALGORITHMS",
+ rightDescription:
+ "By default, any signature and key algorithm is accepted. Enable a restriction to limit issuance to the algorithms you approve. Requests using any other algorithm of that kind are rejected."
+ },
+ {
+ name: "Key Usages",
+ shortDescription: "Usages and EKUs",
+ title: "Key Usages",
+ subtitle: "Choose the key usages and extended key usages certificates may carry.",
+ rightLabel: "KEY USAGES",
+ rightDescription:
+ "By default, certificates may carry any key usages and extended key usages. Enable a restriction to mark each usage as required, allowed, or denied. Requests that fall outside those rules are rejected at issuance."
+ },
+ {
+ name: "Constraints",
+ shortDescription: "Validity and CA",
+ title: "Constraints",
+ subtitle: "Optionally cap validity and control CA behavior for issued certificates.",
+ rightLabel: "CONSTRAINTS",
+ rightDescription:
+ "By default, validity and CA capability are unrestricted. Enable a restriction to cap the maximum validity period or control whether certificates can act as a CA, including path length limits."
+ }
+] as const;
+
+const SectionToggle = ({
+ title,
+ description,
+ enabled,
+ onChange,
+ error,
+ children
+}: {
+ title: string;
+ description: string;
+ enabled: boolean;
+ onChange: (enabled: boolean) => void;
+ error?: string;
+ children?: ReactNode;
+}) => (
+ <div>
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <p className="text-sm font-medium text-foreground">{title}</p>
+ <p className="mt-0.5 text-xs text-muted">{description}</p>
+ </div>
+ <Switch checked={enabled} onCheckedChange={onChange} variant="project" />
+ </div>
+ {enabled && children && <div className="mt-4">{children}</div>}
+ {error && <p className="mt-2 text-xs text-danger">{error}</p>}
+ </div>
+);
+
export const CreatePolicyModal = ({
isOpen,
onClose,
@@ -135,6 +233,32 @@ export const CreatePolicyModal = ({
const isEdit = mode === "edit" && policy;
+ const [step, setStep] = useState(0);
+ const currentStep = STEPS[step];
+ const isLast = step === STEPS.length - 1;
+
+ const [restrictSubject, setRestrictSubject] = useState(false);
+ const [restrictSans, setRestrictSans] = useState(false);
+ const [restrictSignature, setRestrictSignature] = useState(false);
+ const [restrictKeyAlg, setRestrictKeyAlg] = useState(false);
+ const [restrictKeyUsages, setRestrictKeyUsages] = useState(false);
+ const [restrictExtendedKeyUsages, setRestrictExtendedKeyUsages] = useState(false);
+ const [restrictValidity, setRestrictValidity] = useState(false);
+ const [configureBasicConstraints, setConfigureBasicConstraints] = useState(false);
+
+ const [errors, setErrors] = useState<Record<string, string>>({});
+ const clearError = (key: string) =>
+ setErrors((prev) => {
+ if (!prev[key]) return prev;
+ const next = { ...prev };
+ delete next[key];
+ return next;
+ });
+
+ const goBack = () => {
+ if (step > 0) setStep((s) => s - 1);
+ };
+
const convertApiToUiFormat = (policyData: TCertificatePolicy): FormData => {
const attributes: FormData["attributes"] = [];
if (policyData.subject && Array.isArray(policyData.subject)) {
@@ -206,41 +330,38 @@ export const CreatePolicyModal = ({
const validity = policyData.validity?.max
? (() => {
const maxValue = policyData.validity.max;
- if (maxValue.length < 2) return undefined;
+ if (maxValue.length < 2)
+ return { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };
const lastChar = maxValue.slice(-1);
const numberPart = maxValue.slice(0, -1);
const value = parseInt(numberPart, 10);
if (Number.isNaN(value) || value <= 0 || numberPart !== value.toString()) {
- return undefined;
+ return { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };
}
let unit: CertDurationUnit = CertDurationUnit.DAYS;
- if (lastChar === "d") {
+ if (lastChar === "h") {
+ unit = CertDurationUnit.HOURS;
+ } else if (lastChar === "d") {
unit = CertDurationUnit.DAYS;
} else if (lastChar === "m") {
unit = CertDurationUnit.MONTHS;
} else if (lastChar === "y") {
unit = CertDurationUnit.YEARS;
- } else {
- return undefined;
}
- return {
- maxDuration: { value, unit }
- };
+ return { maxDuration: { value, unit } };
})()
: { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };
const signatureAlgorithm = {
- allowedAlgorithms: policyData.algorithms?.signature || [],
- defaultAlgorithm: ""
+ allowedAlgorithms: policyData.algorithms?.signature || []
};
const keyAlgorithm = {
- allowedKeyTypes: policyData.algorithms?.keyAlgorithm || [],
- defaultKeyType: ""
+ allowedKeyTypes: policyData.algorithms?.keyAlgorithm || []
};
const basicConstraints: FormData["basicConstraints"] = {
@@ -288,7 +409,7 @@ export const CreatePolicyModal = ({
};
};
- const { control, handleSubmit, reset, watch, setValue, formState, trigger } = useForm<
+ const { control, handleSubmit, reset, watch, setValue, trigger } = useForm<
FormData & { preset: PolicyPresetId }
>({
resolver: zodResolver(policySchema),
@@ -298,14 +419,36 @@ export const CreatePolicyModal = ({
criteriaMode: "all"
});
+ const resetToggles = (source?: TCertificatePolicy) => {
+ setRestrictSubject(Boolean(source?.subject?.length));
+ setRestrictSans(Boolean(source?.sans?.length));
+ setRestrictSignature(Boolean(source?.algorithms?.signature?.length));
+ setRestrictKeyAlg(Boolean(source?.algorithms?.keyAlgorithm?.length));
+ setRestrictKeyUsages(
+ Boolean(source?.keyUsages?.required?.length || source?.keyUsages?.allowed?.length)
+ );
+ setRestrictExtendedKeyUsages(
+ Boolean(
+ source?.extendedKeyUsages?.required?.length || source?.extendedKeyUsages?.allowed?.length
+ )
+ );
+ setRestrictValidity(Boolean(source?.validity?.max));
+ setConfigureBasicConstraints(Boolean(source?.basicConstraints?.isCA));
+ setErrors({});
+ };
+
useEffect(() => {
if (isEdit && policy) {
const convertedData = convertApiToUiFormat(policy);
reset({ ...convertedData, preset: POLICY_PRESET_IDS.CUSTOM });
+ resetToggles(policy);
} else if (!isEdit) {
reset(getDefaultValues());
+ resetToggles();
}
- }, [isEdit, policy, reset]);
+ setStep(0);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isEdit, policy, reset, isOpen]);
const watchedAttributes = watch("attributes") || [];
const watchedSans = watch("subjectAlternativeNames") || [];
@@ -315,8 +458,16 @@ export const CreatePolicyModal = ({
optionalUsages: []
};
const watchedPreset = watch("preset") || POLICY_PRESET_IDS.CUSTOM;
+ const watchedSignatureAlgs = watch("signatureAlgorithm")?.allowedAlgorithms || [];
+ const watchedKeyAlgs = watch("keyAlgorithm")?.allowedKeyTypes || [];
const watchedIsCAPolicy = watch("basicConstraints.isCA") || CertPolicyState.DENIED;
+ const markCustomPreset = () => {
+ if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
+ setValue("preset", POLICY_PRESET_IDS.CUSTOM);
+ }
+ };
+
const handlePresetChange = async (presetId: PolicyPresetId) => {
setValue("preset", presetId);
@@ -327,30 +478,39 @@ export const CreatePolicyModal = ({
const selectedPreset = CERTIFICATE_POLICY_PRESETS.find((p) => p.id === presetId);
if (selectedPreset) {
- if (selectedPreset.formData.keyUsages) {
- setValue("keyUsages", selectedPreset.formData.keyUsages);
- }
- if (selectedPreset.formData.extendedKeyUsages) {
- setValue("extendedKeyUsages", selectedPreset.formData.extendedKeyUsages);
- }
- if (selectedPreset.formData.attributes) {
- setValue("attributes", selectedPreset.formData.attributes);
- }
- if (selectedPreset.formData.subjectAlternativeNames) {
- setValue("subjectAlternativeNames", selectedPreset.formData.subjectAlternativeNames);
- }
- if (selectedPreset.formData.signatureAlgorithm) {
- setValue("signatureAlgorithm", selectedPreset.formData.signatureAlgorithm);
- }
- if (selectedPreset.formData.keyAlgorithm) {
- setValue("keyAlgorithm", selectedPreset.formData.keyAlgorithm);
- }
- if (selectedPreset.formData.basicConstraints) {
- setValue("basicConstraints", selectedPreset.formData.basicConstraints);
- }
- if (selectedPreset.formData.validity) {
- setValue("validity", selectedPreset.formData.validity);
- }
+ const { formData } = selectedPreset;
+ if (formData.keyUsages) setValue("keyUsages", formData.keyUsages);
+ if (formData.extendedKeyUsages) setValue("extendedKeyUsages", formData.extendedKeyUsages);
+ if (formData.attributes) setValue("attributes", formData.attributes);
+ if (formData.subjectAlternativeNames)
+ setValue("subjectAlternativeNames", formData.subjectAlternativeNames);
+ if (formData.signatureAlgorithm) setValue("signatureAlgorithm", formData.signatureAlgorithm);
+ if (formData.keyAlgorithm) setValue("keyAlgorithm", formData.keyAlgorithm);
+ if (formData.basicConstraints) setValue("basicConstraints", formData.basicConstraints);
+ if (formData.validity) setValue("validity", formData.validity);
+
+ setRestrictSubject(Boolean(formData.attributes?.length));
+ setRestrictSans(Boolean(formData.subjectAlternativeNames?.length));
+ setRestrictSignature(Boolean(formData.signatureAlgorithm?.allowedAlgorithms?.length));
+ setRestrictKeyAlg(Boolean(formData.keyAlgorithm?.allowedKeyTypes?.length));
+ setRestrictKeyUsages(
+ Boolean(
+ formData.keyUsages?.requiredUsages?.length || formData.keyUsages?.optionalUsages?.length
+ )
+ );
+ setRestrictExtendedKeyUsages(
+ Boolean(
+ formData.extendedKeyUsages?.requiredUsages?.length ||
+ formData.extendedKeyUsages?.optionalUsages?.length
+ )
+ );
+ setRestrictValidity(Boolean(formData.validity?.maxDuration));
+ setConfigureBasicConstraints(
+ Boolean(
+ formData.basicConstraints?.isCA &&
+ formData.basicConstraints.isCA !== CertPolicyState.DENIED
+ )
+ );
await trigger();
}
@@ -390,7 +550,6 @@ export const CreatePolicyModal = ({
const subjectRaw =
data.attributes?.map((attr) => {
const result: AttributeTransform = { type: attr.type };
-
if (
attr.include === CertSubjectAttributeInclude.OPTIONAL &&
attr.value &&
@@ -404,14 +563,12 @@ export const CreatePolicyModal = ({
) {
result.denied = attr.value;
}
-
return result;
}) || [];
const sansRaw =
data.subjectAlternativeNames?.map((san) => {
const result: SanTransform = { type: san.type };
-
if (san.include === CertSanInclude.MANDATORY && san.value && san.value.length > 0) {
result.required = san.value;
} else if (san.include === CertSanInclude.OPTIONAL && san.value && san.value.length > 0) {
@@ -419,76 +576,42 @@ export const CreatePolicyModal = ({
} else if (san.include === CertSanInclude.PROHIBIT && san.value && san.value.length > 0) {
result.denied = san.value;
}
-
return result;
}) || [];
- const subject = consolidateByType(subjectRaw);
- const sans = consolidateByType(sansRaw);
+ const subject = restrictSubject ? consolidateByType(subjectRaw) : undefined;
+ const sans = restrictSans ? consolidateByType(sansRaw) : undefined;
- const keyUsages: KeyUsagesTransform = {
- required: [],
- allowed: []
- };
- if (data.keyUsages?.requiredUsages && data.keyUsages.requiredUsages.length > 0) {
- keyUsages.required = data.keyUsages.requiredUsages;
- }
- if (data.keyUsages?.optionalUsages && data.keyUsages.optionalUsages.length > 0) {
- keyUsages.allowed = data.keyUsages.optionalUsages;
- }
+ const keyUsages: KeyUsagesTransform | undefined = restrictKeyUsages
+ ? {
+ required: data.keyUsages?.requiredUsages ?? [],
+ allowed: data.keyUsages?.optionalUsages ?? []
+ }
+ : undefined;
- const extendedKeyUsages: ExtendedKeyUsagesTransform = {
- required: [],
- allowed: []
- };
- if (
- data.extendedKeyUsages?.requiredUsages &&
- data.extendedKeyUsages.requiredUsages.length > 0
- ) {
- extendedKeyUsages.required = data.extendedKeyUsages.requiredUsages;
- }
- if (
- data.extendedKeyUsages?.optionalUsages &&
- data.extendedKeyUsages.optionalUsages.length > 0
- ) {
- extendedKeyUsages.allowed = data.extendedKeyUsages.optionalUsages;
- }
+ const extendedKeyUsages: ExtendedKeyUsagesTransform | undefined = restrictExtendedKeyUsages
+ ? {
+ required: data.extendedKeyUsages?.requiredUsages ?? [],
+ allowed: data.extendedKeyUsages?.optionalUsages ?? []
+ }
+ : undefined;
const algorithms: AlgorithmsTransform = {};
- if (
- data.signatureAlgorithm?.allowedAlgorithms &&
- data.signatureAlgorithm.allowedAlgorithms.length > 0
- ) {
- algorithms.signature = data.signatureAlgorithm.allowedAlgorithms as Array<
- | "SHA256-RSA"
- | "SHA384-RSA"
- | "SHA512-RSA"
- | "SHA256-ECDSA"
- | "SHA384-ECDSA"
- | "SHA512-ECDSA"
- | "ML-DSA-44"
- | "ML-DSA-65"
- | "ML-DSA-87"
- >;
+ if (restrictSignature && data.signatureAlgorithm?.allowedAlgorithms?.length) {
+ algorithms.signature = data.signatureAlgorithm
+ .allowedAlgorithms as NonNullable<AlgorithmsTransform>["signature"];
}
- if (data.keyAlgorithm?.allowedKeyTypes && data.keyAlgorithm.allowedKeyTypes.length > 0) {
- algorithms.keyAlgorithm = data.keyAlgorithm.allowedKeyTypes as Array<
- | "RSA-2048"
- | "RSA-3072"
- | "RSA-4096"
- | "ECDSA-P256"
- | "ECDSA-P384"
- | "ECDSA-P521"
- | "ML-DSA-44"
- | "ML-DSA-65"
- | "ML-DSA-87"
- >;
+ if (restrictKeyAlg && data.keyAlgorithm?.allowedKeyTypes?.length) {
+ algorithms.keyAlgorithm = data.keyAlgorithm
+ .allowedKeyTypes as NonNullable<AlgorithmsTransform>["keyAlgorithm"];
}
const validity: ValidityTransform = {};
- if (data.validity?.maxDuration) {
+ if (restrictValidity && data.validity?.maxDuration) {
let unit = "d";
- if (data.validity.maxDuration.unit === CertDurationUnit.DAYS) {
+ if (data.validity.maxDuration.unit === CertDurationUnit.HOURS) {
+ unit = "h";
+ } else if (data.validity.maxDuration.unit === CertDurationUnit.DAYS) {
unit = "d";
} else if (data.validity.maxDuration.unit === CertDurationUnit.MONTHS) {
unit = "m";
@@ -498,13 +621,15 @@ export const CreatePolicyModal = ({
validity.max = `${data.validity.maxDuration.value}${unit}`;
}
- const basicConstraints =
- data.basicConstraints?.isCA && data.basicConstraints.isCA !== CertPolicyState.DENIED
- ? {
- isCA: data.basicConstraints.isCA,
- maxPathLength: data.basicConstraints.maxPathLength ?? undefined
- }
- : null;
+ const basicConstraints = configureBasicConstraints
+ ? {
+ isCA: data.basicConstraints?.isCA ?? CertPolicyState.DENIED,
+ maxPathLength:
+ data.basicConstraints?.isCA && data.basicConstraints.isCA !== CertPolicyState.DENIED
+ ? (data.basicConstraints.maxPathLength ?? undefined)
+ : undefined
+ }
+ : null;
return {
name: data.name,
@@ -513,8 +638,8 @@ export const CreatePolicyModal = ({
sans,
keyUsages,
extendedKeyUsages,
- algorithms,
- validity,
+ algorithms: algorithms.signature || algorithms.keyAlgorithm ? algorithms : undefined,
+ validity: validity.max ? validity : undefined,
basicConstraints
};
};
@@ -522,17 +647,21 @@ export const CreatePolicyModal = ({
const onFormSubmit = async (data: FormData) => {
if (!currentProject?.id && !isEdit) return;
- const hasEmptyAttributeValues = data.attributes?.some(
- (attr) => !attr.value || attr.value.length === 0 || attr.value.some((v) => !v.trim())
- );
+ const hasEmptyAttributeValues =
+ restrictSubject &&
+ data.attributes?.some(
+ (attr) => !attr.value || attr.value.length === 0 || attr.value.some((v) => !v.trim())
+ );
- const hasEmptySanValues = data.subjectAlternativeNames?.some(
- (san) => !san.value || san.value.length === 0 || san.value.some((v) => !v.trim())
- );
+ const hasEmptySanValues =
+ restrictSans &&
+ data.subjectAlternativeNames?.some(
+ (san) => !san.value || san.value.length === 0 || san.value.some((v) => !v.trim())
+ );
if (hasEmptyAttributeValues || hasEmptySanValues) {
createNotification({
- text: "All values must be non-empty. Use wildcards (*) if needed.",
+ text: "All configured subject or SAN values must be non-empty. Use wildcards (*) if needed.",
type: "error"
});
return;
@@ -541,24 +670,16 @@ export const CreatePolicyModal = ({
const transformedData = transformToApiFormat(data);
if (isEdit) {
- const updateData = {
- policyId: policy.id,
- ...transformedData
- };
- await updatePolicy.mutateAsync(updateData);
+ await updatePolicy.mutateAsync({ policyId: policy.id, ...transformedData });
} else {
if (!currentProject?.id) {
throw new Error("Project ID is required for creating a policy");
}
-
- const createData = {
+ const createdPolicy = await createPolicy.mutateAsync({
projectId: currentProject.id,
...transformedData
- };
- const createdPolicy = await createPolicy.mutateAsync(createData);
- if (onComplete) {
- onComplete(createdPolicy);
- }
+ });
+ onComplete?.(createdPolicy);
}
createNotification({
@@ -571,692 +692,817 @@ export const CreatePolicyModal = ({
};
const addAttribute = () => {
- const newAttribute = {
- type: SUBJECT_ATTRIBUTE_TYPE_OPTIONS[0],
- include: SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS[0],
- value: ["*"]
- };
- setValue("attributes", [...watchedAttributes, newAttribute]);
-
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
+ setValue("attributes", [
+ ...watchedAttributes,
+ {
+ type: SUBJECT_ATTRIBUTE_TYPE_OPTIONS[0],
+ include: SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS[0],
+ value: ["*"]
+ }
+ ]);
+ clearError("subject");
+ markCustomPreset();
};
const removeAttribute = (index: number) => {
- const newAttributes = watchedAttributes.filter((_, i) => i !== index);
- setValue("attributes", newAttributes);
-
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
+ setValue(
+ "attributes",
+ watchedAttributes.filter((_, i) => i !== index)
+ );
+ markCustomPreset();
};
const addSan = () => {
- const newSan = {
- type: SAN_TYPE_OPTIONS[0],
- include: SAN_INCLUDE_OPTIONS[1],
- value: ["*"]
- };
- setValue("subjectAlternativeNames", [...watchedSans, newSan]);
-
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
+ setValue("subjectAlternativeNames", [
+ ...watchedSans,
+ { type: SAN_TYPE_OPTIONS[0], include: SAN_INCLUDE_OPTIONS[1], value: ["*"] }
+ ]);
+ clearError("sans");
+ markCustomPreset();
};
const removeSan = (index: number) => {
- const newSans = watchedSans.filter((_, i) => i !== index);
- setValue("subjectAlternativeNames", newSans);
+ setValue(
+ "subjectAlternativeNames",
+ watchedSans.filter((_, i) => i !== index)
+ );
+ markCustomPreset();
+ };
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
+ const keyUsagePolicyOf = (usage: CertKeyUsageType): UsagePolicy => {
+ if (watchedKeyUsages.requiredUsages.includes(usage)) return "require";
+ if (watchedKeyUsages.optionalUsages.includes(usage)) return "allow";
+ return "deny";
};
- const handleKeyUsagesChange = (usages: {
- requiredUsages: CertKeyUsageType[];
- optionalUsages: CertKeyUsageType[];
- }) => {
- setValue("keyUsages", {
- requiredUsages: usages.requiredUsages,
- optionalUsages: usages.optionalUsages
- });
+ const setKeyUsagePolicy = (usage: CertKeyUsageType, policyValue: UsagePolicy) => {
+ const required = watchedKeyUsages.requiredUsages.filter((u) => u !== usage);
+ const optional = watchedKeyUsages.optionalUsages.filter((u) => u !== usage);
+ if (policyValue === "require") required.push(usage);
+ else if (policyValue === "allow") optional.push(usage);
+ setValue("keyUsages", { requiredUsages: required, optionalUsages: optional });
+ clearError("keyUsages");
+ markCustomPreset();
+ };
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
+ const extendedKeyUsagePolicyOf = (usage: CertExtendedKeyUsageType): UsagePolicy => {
+ if (watchedExtendedKeyUsages.requiredUsages.includes(usage)) return "require";
+ if (watchedExtendedKeyUsages.optionalUsages.includes(usage)) return "allow";
+ return "deny";
};
- const handleExtendedKeyUsagesChange = (usages: {
- requiredUsages: CertExtendedKeyUsageType[];
- optionalUsages: CertExtendedKeyUsageType[];
- }) => {
- setValue("extendedKeyUsages", {
- requiredUsages: usages.requiredUsages,
- optionalUsages: usages.optionalUsages
- });
+ const setExtendedKeyUsagePolicy = (usage: CertExtendedKeyUsageType, policyValue: UsagePolicy) => {
+ const required = watchedExtendedKeyUsages.requiredUsages.filter((u) => u !== usage);
+ const optional = watchedExtendedKeyUsages.optionalUsages.filter((u) => u !== usage);
+ if (policyValue === "require") required.push(usage);
+ else if (policyValue === "allow") optional.push(usage);
+ setValue("extendedKeyUsages", { requiredUsages: required, optionalUsages: optional });
+ clearError("extendedKeyUsages");
+ markCustomPreset();
+ };
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
+ const toggleAlgorithm = (
+ fieldName: "signatureAlgorithm" | "keyAlgorithm",
+ key: "allowedAlgorithms" | "allowedKeyTypes",
+ current: string[],
+ value: string,
+ checked: boolean
+ ) => {
+ const next = checked ? [...current, value] : current.filter((v) => v !== value);
+ setValue(fieldName, { [key]: next } as never);
+ clearError(fieldName === "signatureAlgorithm" ? "signature" : "keyAlgorithm");
+ markCustomPreset();
+ };
+
+ const validateStep = (): boolean => {
+ const stepErrors: Record<string, string> = {};
+
+ if (step === 1) {
+ if (restrictSubject) {
+ if (!watchedAttributes.length) {
+ stepErrors.subject = "Add at least one subject attribute, or turn off the restriction.";
+ } else if (watchedAttributes.some((a) => !a.value?.[0]?.trim())) {
+ stepErrors.subject = "Every subject attribute needs a value (use * for any).";
+ }
+ }
+ if (restrictSans) {
+ if (!watchedSans.length) {
+ stepErrors.sans =
+ "Add at least one subject alternative name, or turn off the restriction.";
+ } else if (watchedSans.some((s) => !s.value?.[0]?.trim())) {
+ stepErrors.sans = "Every subject alternative name needs a value (use * for any).";
+ }
+ }
+ }
+
+ if (step === 2) {
+ if (restrictSignature && !watchedSignatureAlgs.length) {
+ stepErrors.signature =
+ "Select at least one signature algorithm, or turn off the restriction.";
+ }
+ if (restrictKeyAlg && !watchedKeyAlgs.length) {
+ stepErrors.keyAlgorithm = "Select at least one key algorithm, or turn off the restriction.";
+ }
}
+
+ if (step === 3) {
+ if (
+ restrictKeyUsages &&
+ watchedKeyUsages.requiredUsages.length === 0 &&
+ watchedKeyUsages.optionalUsages.length === 0
+ ) {
+ stepErrors.keyUsages =
+ "Set at least one key usage to Require or Allow, or turn off the restriction.";
+ }
+ if (
+ restrictExtendedKeyUsages &&
+ watchedExtendedKeyUsages.requiredUsages.length === 0 &&
+ watchedExtendedKeyUsages.optionalUsages.length === 0
+ ) {
+ stepErrors.extendedKeyUsages =
+ "Set at least one extended key usage to Require or Allow, or turn off the restriction.";
+ }
+ }
+
+ setErrors(stepErrors);
+ return Object.keys(stepErrors).length === 0;
};
+ const goNext = async () => {
+ if (step === 0) {
+ const ok = await trigger(["name"]);
+ if (!ok) return;
+ }
+ if (!validateStep()) return;
+ setStep((s) => Math.min(s + 1, STEPS.length - 1));
+ };
+
+ const isSubmitting = isEdit ? updatePolicy.isPending : createPolicy.isPending;
+
+ const renderUsageGrid = (
+ options: readonly string[],
+ policyOf: (u: never) => UsagePolicy,
+ onChange: (u: never, p: UsagePolicy) => void,
+ formatter: (u: never) => string
+ ) => (
+ <div className="grid grid-cols-2 gap-x-6 gap-y-3">
+ {options.map((usage) => (
+ <div key={usage} className="flex items-center justify-between gap-2">
+ <span className="text-sm text-foreground">{formatter(usage as never)}</span>
+ <Select
+ value={policyOf(usage as never)}
+ onValueChange={(value) => onChange(usage as never, value as UsagePolicy)}
+ >
+ <SelectTrigger className="w-28">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {USAGE_POLICY_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ ))}
+ </div>
+ );
+
+ const renderAlgorithmGrid = (
+ options: readonly string[],
+ selected: string[],
+ fieldName: "signatureAlgorithm" | "keyAlgorithm",
+ key: "allowedAlgorithms" | "allowedKeyTypes"
+ ) => (
+ <div className="grid grid-cols-2 gap-3">
+ {options.map((alg) => {
+ const isSelected = selected.includes(alg);
+ const isPqcGated = isPqcAlgorithm(alg) && !subscription?.pkiPqc;
+ return (
+ <div key={alg} className="flex items-center gap-3">
+ <Checkbox
+ id={`${fieldName}-${alg}`}
+ variant="project"
+ isChecked={isSelected}
+ isDisabled={isPqcGated}
+ onCheckedChange={(checked) =>
+ toggleAlgorithm(fieldName, key, selected, alg, Boolean(checked))
+ }
+ />
+ <label
+ htmlFor={`${fieldName}-${alg}`}
+ className="flex cursor-pointer items-center gap-2 text-sm text-foreground"
+ >
+ {alg}
+ {isPqcGated && <Badge variant="info">Enterprise</Badge>}
+ </label>
+ </div>
+ );
+ })}
+ </div>
+ );
+
return (
- <Modal
- isOpen={isOpen}
+ <Sheet
+ open={isOpen}
onOpenChange={(open) => {
if (!open) {
reset();
+ resetToggles();
+ setStep(0);
}
onClose();
}}
>
- <ModalContent
- className="max-w-4xl"
- title={isEdit ? "Edit Certificate Policy" : "Create Certificate Policy"}
- subTitle={
- isEdit
- ? `Update configuration for ${policy?.name}`
- : "Define comprehensive certificate policies, validation rules, and constraints"
- }
- >
- <form onSubmit={handleSubmit(onFormSubmit)} className="space-y-6">
- <Accordion type="multiple" defaultValue={["basic", "algorithms"]} className="w-full">
- <div className="space-y-4">
- <Controller
- control={control}
- name="name"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Policy Name"
- isRequired
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Input {...field} placeholder="Enter policy name" className="w-full" />
- </FormControl>
- )}
- />
-
- <Controller
- control={control}
- name="description"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Description"
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <TextArea {...field} placeholder="Enter policy description" rows={3} />
- </FormControl>
- )}
- />
-
- <Controller
- control={control}
- name="preset"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Policy Preset"
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Select
- value={field.value}
- onValueChange={handlePresetChange}
- className="w-full"
- position="popper"
- dropdownContainerClassName="max-w-none"
- >
- <SelectItem value={POLICY_PRESET_IDS.CUSTOM}>Custom</SelectItem>
- {CERTIFICATE_POLICY_PRESETS.map((preset) => (
- <SelectItem key={preset.id} value={preset.id}>
- {preset.name}
- </SelectItem>
- ))}
- </Select>
- </FormControl>
- )}
- />
+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 p-0 sm:max-w-[1100px]">
+ <SheetHeader className="border-b border-border">
+ <SheetTitle>
+ <div className="flex w-full items-start gap-2">
+ <div className="flex h-10 w-10 items-center justify-center rounded-md bg-project/10 text-project">
+ <ShieldCheck className="h-5 w-5" />
+ </div>
+ <div>
+ <div className="flex items-center gap-x-2 text-foreground">
+ {isEdit ? "Edit Certificate Policy" : "Create Certificate Policy"}
+ <DocumentationLinkBadge href={PkiDocsUrls.settings.policies} />
+ </div>
+ <p className="text-sm leading-4 text-muted">
+ {isEdit
+ ? `Update configuration for ${policy?.name}`
+ : "Define comprehensive certificate policies, validation rules, and constraints"}
+ </p>
+ </div>
</div>
-
- <AccordionItem value="attributes">
- <AccordionTrigger>Subject Attributes</AccordionTrigger>
- <AccordionContent>
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <Button
- type="button"
- onClick={addAttribute}
- size="sm"
- variant="outline_bg"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- >
- Add Attribute
- </Button>
- </div>
-
- <div className="space-y-2">
- {watchedAttributes.length === 0 ? (
- <div className="py-8 text-center text-bunker-300">
- No subject attributes configured yet. Click &quot;Add Attribute&quot; to get
- started.
- </div>
- ) : (
- watchedAttributes.map((attr, index) => {
- return (
- <div
- // eslint-disable-next-line react/no-array-index-key
- key={`attr-${attr.type}-${attr.include}-${index}`}
- className="flex items-start gap-2"
+ </SheetTitle>
+ </SheetHeader>
+
+ <form onSubmit={(e) => e.preventDefault()} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">
+ <p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">
+ Setup steps
+ </p>
+ <Stepper
+ activeStep={step}
+ orientation="vertical"
+ onStepChange={(i) => {
+ if (i < step) setStep(i);
+ }}
+ >
+ <StepperList>
+ {STEPS.map((s, i) => (
+ <StepperStep
+ key={s.name}
+ index={i}
+ title={s.name}
+ description={s.shortDescription}
+ />
+ ))}
+ </StepperList>
+ </Stepper>
+ </aside>
+
+ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">
+ <div className="mb-6">
+ <h2 className="text-lg font-semibold text-foreground">{currentStep.title}</h2>
+ <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>
+ </div>
+
+ {step === 0 && (
+ <FieldGroup>
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Policy Name <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ placeholder="e.g. tls-server"
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="description"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <FieldContent>
+ <TextArea
+ {...field}
+ value={field.value ?? ""}
+ placeholder="What this policy enforces."
+ rows={3}
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="preset"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Policy Preset</FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={handlePresetChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select a preset" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={POLICY_PRESET_IDS.CUSTOM}>Custom</SelectItem>
+ {CERTIFICATE_POLICY_PRESETS.map((preset) => (
+ <SelectItem key={preset.id} value={preset.id}>
+ {preset.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ Apply a preset to populate every step with a recommended baseline, then
+ review and tailor each one to your requirements. Select Custom to start
+ from scratch.
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </FieldGroup>
+ )}
+
+ {step === 1 && (
+ <div className="space-y-8">
+ <SectionToggle
+ title="Restrict subject attributes"
+ description="Only allow the subject attributes (CN, O, OU, ...) you configure here."
+ enabled={restrictSubject}
+ error={errors.subject}
+ onChange={(enabled) => {
+ setRestrictSubject(enabled);
+ if (!enabled) setValue("attributes", []);
+ clearError("subject");
+ markCustomPreset();
+ }}
+ >
+ <div className="space-y-3">
+ {watchedAttributes.map((attr, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <div key={`attr-${index}`} className="flex items-start gap-2">
+ <Select
+ value={attr.type}
+ onValueChange={(value) => {
+ const next = [...watchedAttributes];
+ next[index] = { ...attr, type: value as CertSubjectAttributeType };
+ setValue("attributes", next);
+ markCustomPreset();
+ }}
>
- <Select
- value={attr.type}
- onValueChange={(value) => {
- const newAttributes = [...watchedAttributes];
- newAttributes[index] = {
- ...attr,
- type: value as CertSubjectAttributeType
- };
- setValue("attributes", newAttributes);
-
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
- }}
- className="w-48"
- >
+ <SelectTrigger className="w-52">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
{SUBJECT_ATTRIBUTE_TYPE_OPTIONS.map((type) => (
<SelectItem key={type} value={type}>
{ATTRIBUTE_TYPE_LABELS[type]}
</SelectItem>
))}
- </Select>
-
- <Select
- value={attr.include}
- onValueChange={(value) => {
- const newAttributes = [...watchedAttributes];
- newAttributes[index] = {
- ...attr,
- include:
- value as (typeof SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS)[number]
- };
- setValue("attributes", newAttributes);
-
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
- }}
- className="w-32"
- >
+ </SelectContent>
+ </Select>
+ <Select
+ value={attr.include}
+ onValueChange={(value) => {
+ const next = [...watchedAttributes];
+ next[index] = {
+ ...attr,
+ include: value as (typeof SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS)[number]
+ };
+ setValue("attributes", next);
+ markCustomPreset();
+ }}
+ >
+ <SelectTrigger className="w-28">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
{SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS.map((type) => (
<SelectItem key={type} value={type}>
{SUBJECT_ATTRIBUTE_LABELS[type]}
</SelectItem>
))}
- </Select>
-
- <Input
- placeholder="Pattern/Value (required - use * for wildcards)"
- value={attr.value?.[0] || ""}
- onChange={(e) => {
- const newAttributes = [...watchedAttributes];
- newAttributes[index] = {
- ...attr,
- value: e.target.value.trim() ? [e.target.value.trim()] : []
- };
- setValue("attributes", newAttributes);
-
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
- }}
- className={`flex-1 ${
- attr.value && attr.value.length > 0 && attr.value[0] === ""
- ? "border-red-500 focus:border-red-500"
- : ""
- }`}
- required
- />
-
- {watchedAttributes.length > 0 && (
- <IconButton
- ariaLabel="Remove Attribute"
- variant="plain"
- size="sm"
- onClick={() => removeAttribute(index)}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- )}
- </div>
- );
- })
- )}
- </div>
- </div>
- </AccordionContent>
- </AccordionItem>
-
- <AccordionItem value="san" className="mt-4">
- <AccordionTrigger>Subject Alternative Names</AccordionTrigger>
- <AccordionContent>
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <Button
- type="button"
- onClick={addSan}
- size="sm"
- variant="outline_bg"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- >
- Add SAN
- </Button>
- </div>
-
- <div className="space-y-2">
- {watchedSans.length === 0 ? (
- <div className="py-8 text-center text-bunker-300">
- No subject alternative names configured yet. Click &quot;Add SAN&quot; to
- get started.
- </div>
- ) : (
- watchedSans.map((san, index) => (
- <div
- // eslint-disable-next-line react/no-array-index-key
- key={`san-${san.type}-${san.include}-${index}`}
- className="flex items-start gap-2"
- >
+ </SelectContent>
+ </Select>
+ <Input
+ placeholder="Pattern/Value (use * for wildcards)"
+ value={attr.value?.[0] || ""}
+ onChange={(e) => {
+ const next = [...watchedAttributes];
+ next[index] = {
+ ...attr,
+ value: e.target.value.trim() ? [e.target.value.trim()] : []
+ };
+ setValue("attributes", next);
+ markCustomPreset();
+ }}
+ className="flex-1"
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => removeAttribute(index)}
+ >
+ <Trash2 className="size-4" />
+ </Button>
+ </div>
+ ))}
+ <Button type="button" variant="outline" size="sm" onClick={addAttribute}>
+ <Plus className="size-4" /> Add attribute
+ </Button>
+ </div>
+ </SectionToggle>
+
+ <SectionToggle
+ title="Restrict subject alternative names"
+ description="Only allow the SAN types and values you configure here."
+ enabled={restrictSans}
+ error={errors.sans}
+ onChange={(enabled) => {
+ setRestrictSans(enabled);
+ if (!enabled) setValue("subjectAlternativeNames", []);
+ clearError("sans");
+ markCustomPreset();
+ }}
+ >
+ <div className="space-y-3">
+ {watchedSans.map((san, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <div key={`san-${index}`} className="flex items-start gap-2">
<Select
value={san.type}
onValueChange={(value) => {
- const newSans = [...watchedSans];
- newSans[index] = {
+ const next = [...watchedSans];
+ next[index] = {
...san,
type: value as CertSubjectAlternativeNameType
};
- setValue("subjectAlternativeNames", newSans);
-
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
+ setValue("subjectAlternativeNames", next);
+ markCustomPreset();
}}
- className="w-36"
>
- {SAN_TYPE_OPTIONS.map((type) => (
- <SelectItem key={type} value={type}>
- {SAN_TYPE_LABELS[type]}
- </SelectItem>
- ))}
+ <SelectTrigger className="w-40">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {SAN_TYPE_OPTIONS.map((type) => (
+ <SelectItem key={type} value={type}>
+ {SAN_TYPE_LABELS[type]}
+ </SelectItem>
+ ))}
+ </SelectContent>
</Select>
-
<Select
value={san.include}
onValueChange={(value) => {
- const newSans = [...watchedSans];
- newSans[index] = {
+ const next = [...watchedSans];
+ next[index] = {
...san,
include: value as (typeof SAN_INCLUDE_OPTIONS)[number]
};
- setValue("subjectAlternativeNames", newSans);
-
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
+ setValue("subjectAlternativeNames", next);
+ markCustomPreset();
}}
- className="w-32"
>
- {SAN_INCLUDE_OPTIONS.map((type) => (
- <SelectItem key={type} value={type}>
- {SAN_INCLUDE_LABELS[type]}
- </SelectItem>
- ))}
+ <SelectTrigger className="w-28">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {SAN_INCLUDE_OPTIONS.map((type) => (
+ <SelectItem key={type} value={type}>
+ {SAN_INCLUDE_LABELS[type]}
+ </SelectItem>
+ ))}
+ </SelectContent>
</Select>
-
<Input
- placeholder="Pattern/Value (required - use * for wildcards)"
+ placeholder="Pattern/Value (use * for wildcards)"
value={san.value?.[0] || ""}
onChange={(e) => {
- const newSans = [...watchedSans];
- newSans[index] = {
+ const next = [...watchedSans];
+ next[index] = {
...san,
value: e.target.value.trim() ? [e.target.value.trim()] : []
};
- setValue("subjectAlternativeNames", newSans);
-
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
+ setValue("subjectAlternativeNames", next);
+ markCustomPreset();
}}
- className={`flex-1 ${
- san.value && san.value.length > 0 && san.value[0] === ""
- ? "border-red-500 focus:border-red-500"
- : ""
- }`}
- required
+ className="flex-1"
/>
-
- {watchedSans.length > 0 && (
- <IconButton
- ariaLabel="Remove SAN"
- variant="plain"
- size="sm"
- onClick={() => removeSan(index)}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- )}
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => removeSan(index)}
+ >
+ <Trash2 className="size-4" />
+ </Button>
</div>
- ))
- )}
- </div>
- </div>
- </AccordionContent>
- </AccordionItem>
-
- <AccordionItem value="algorithms" className="mt-4">
- <AccordionTrigger>Algorithms</AccordionTrigger>
- <AccordionContent>
- <div className="space-y-6">
- <div>
- <h4 className="mb-3 text-sm font-medium text-mineshaft-200">
- Allowed Signature Algorithms
- <span className="ml-1 text-red-500">*</span>
- </h4>
- <Controller
- control={control}
- name="signatureAlgorithm.allowedAlgorithms"
- render={({ field, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div className="grid grid-cols-2 gap-2">
- {SIGNATURE_ALGORITHMS.map((alg) => {
- const isSelected = field.value?.includes(alg);
- const isPqcGated = isPqcAlgorithm(alg) && !subscription?.pkiPqc;
- return (
- <div key={alg} className="flex items-center space-x-3">
- <Checkbox
- id={`sig-alg-${alg}`}
- isChecked={isSelected}
- isDisabled={isPqcGated}
- onCheckedChange={(checked) => {
- const current = field.value || [];
- let newValue;
- if (checked && !isSelected) {
- newValue = [...current, alg];
- } else if (!checked && isSelected) {
- newValue = current.filter((a) => a !== alg);
- } else {
- return;
- }
- field.onChange(newValue);
- }}
- />
- <label
- htmlFor={`sig-alg-${alg}`}
- className="cursor-pointer text-sm font-medium text-mineshaft-200"
- >
- <span className="flex items-center gap-2">
- {alg}
- {isPqcGated && <Badge variant="info">Enterprise</Badge>}
- </span>
- </label>
- </div>
- );
- })}
- </div>
- </FormControl>
- )}
- />
- </div>
-
- <div>
- <h4 className="mb-3 text-sm font-medium text-mineshaft-200">
- Allowed Key Algorithms
- <span className="ml-1 text-red-500">*</span>
- </h4>
- <Controller
- control={control}
- name="keyAlgorithm.allowedKeyTypes"
- render={({ field, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div className="grid grid-cols-2 gap-2">
- {KEY_ALGORITHMS.map((alg) => {
- const isSelected = field.value?.includes(alg);
- const isPqcGated = isPqcAlgorithm(alg) && !subscription?.pkiPqc;
- return (
- <div key={alg} className="flex items-center space-x-3">
- <Checkbox
- id={`key-alg-${alg}`}
- isChecked={isSelected}
- isDisabled={isPqcGated}
- onCheckedChange={(checked) => {
- const current = field.value || [];
- let newValue;
- if (checked && !isSelected) {
- newValue = [...current, alg];
- } else if (!checked && isSelected) {
- newValue = current.filter((a) => a !== alg);
- } else {
- return;
- }
- field.onChange(newValue);
- }}
- />
- <label
- htmlFor={`key-alg-${alg}`}
- className="cursor-pointer text-sm font-medium text-mineshaft-200"
- >
- <span className="flex items-center gap-2">
- {alg}
- {isPqcGated && <Badge variant="info">Enterprise</Badge>}
- </span>
- </label>
- </div>
- );
- })}
- </div>
- </FormControl>
- )}
- />
- </div>
+ ))}
+ <Button type="button" variant="outline" size="sm" onClick={addSan}>
+ <Plus className="size-4" /> Add SAN
+ </Button>
+ </div>
+ </SectionToggle>
</div>
- </AccordionContent>
- </AccordionItem>
-
- <AccordionItem value="usages" className="mt-4">
- <AccordionTrigger>Key Usages</AccordionTrigger>
- <AccordionContent>
- <KeyUsagesSection
- watchedKeyUsages={watchedKeyUsages}
- watchedExtendedKeyUsages={watchedExtendedKeyUsages}
- onKeyUsagesChange={handleKeyUsagesChange}
- onExtendedKeyUsagesChange={handleExtendedKeyUsagesChange}
- />
- </AccordionContent>
- </AccordionItem>
-
- <AccordionItem value="validity" className="mt-4">
- <AccordionTrigger>Certificate Validity</AccordionTrigger>
- <AccordionContent>
- <div className="space-y-4">
- <div className="grid grid-cols-2 gap-4">
- <Controller
- control={control}
- name="validity.maxDuration.value"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Max Duration"
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Input
- {...field}
- type="number"
- placeholder="365"
- className="w-full"
- value={field.value ?? ""}
- onChange={(e) => {
- const val = e.target.value;
- field.onChange(val === "" ? "" : Number(val));
- }}
- />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="validity.maxDuration.unit"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Unit"
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Select
- {...field}
- onValueChange={field.onChange}
- className="w-full"
- position="popper"
- >
- <SelectItem value="days">Days</SelectItem>
- <SelectItem value="months">Months</SelectItem>
- <SelectItem value="years">Years</SelectItem>
- </Select>
- </FormControl>
- )}
- />
- </div>
+ )}
+
+ {step === 2 && (
+ <div className="space-y-8">
+ <SectionToggle
+ title="Restrict signature algorithms"
+ description="Only allow the signature algorithms you select."
+ enabled={restrictSignature}
+ error={errors.signature}
+ onChange={(enabled) => {
+ setRestrictSignature(enabled);
+ if (!enabled) setValue("signatureAlgorithm", { allowedAlgorithms: [] });
+ clearError("signature");
+ markCustomPreset();
+ }}
+ >
+ {renderAlgorithmGrid(
+ SIGNATURE_ALGORITHMS,
+ watchedSignatureAlgs,
+ "signatureAlgorithm",
+ "allowedAlgorithms"
+ )}
+ </SectionToggle>
+
+ <SectionToggle
+ title="Restrict key algorithms"
+ description="Only allow the key algorithms you select."
+ enabled={restrictKeyAlg}
+ error={errors.keyAlgorithm}
+ onChange={(enabled) => {
+ setRestrictKeyAlg(enabled);
+ if (!enabled) setValue("keyAlgorithm", { allowedKeyTypes: [] });
+ clearError("keyAlgorithm");
+ markCustomPreset();
+ }}
+ >
+ {renderAlgorithmGrid(
+ KEY_ALGORITHMS,
+ watchedKeyAlgs,
+ "keyAlgorithm",
+ "allowedKeyTypes"
+ )}
+ </SectionToggle>
</div>
- </AccordionContent>
- </AccordionItem>
-
- <AccordionItem value="basicConstraints" className="mt-4">
- <AccordionTrigger>Basic Constraints</AccordionTrigger>
- <AccordionContent>
- <div className="space-y-4">
- <Controller
- control={control}
- name="basicConstraints.isCA"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <span className="text-sm font-medium text-mineshaft-100">
- CA Certificate Property
- </span>
- <p className="text-xs text-bunker-300">
- Controls whether certificates issued under this policy can have the
- CA:TRUE property.
- </p>
- </div>
- <Select
- value={value || CertPolicyState.DENIED}
- onValueChange={(newValue) => {
- onChange(newValue);
- if (newValue === CertPolicyState.DENIED) {
- setValue("basicConstraints.maxPathLength", undefined);
- }
- }}
- className="w-32"
- >
- <SelectItem value={CertPolicyState.DENIED}>Deny</SelectItem>
- <SelectItem value={CertPolicyState.ALLOWED}>Allow</SelectItem>
- <SelectItem value={CertPolicyState.REQUIRED}>Require</SelectItem>
- </Select>
- </div>
- </FormControl>
+ )}
+
+ {step === 3 && (
+ <div className="space-y-8">
+ <SectionToggle
+ title="Restrict key usages"
+ description="Require, allow, or deny individual key usages."
+ enabled={restrictKeyUsages}
+ error={errors.keyUsages}
+ onChange={(enabled) => {
+ setRestrictKeyUsages(enabled);
+ if (!enabled)
+ setValue("keyUsages", { requiredUsages: [], optionalUsages: [] });
+ clearError("keyUsages");
+ markCustomPreset();
+ }}
+ >
+ {renderUsageGrid(
+ KEY_USAGE_OPTIONS,
+ keyUsagePolicyOf as (u: never) => UsagePolicy,
+ setKeyUsagePolicy as (u: never, p: UsagePolicy) => void,
+ formatKeyUsage as (u: never) => string
)}
- />
-
- {watchedIsCAPolicy !== CertPolicyState.DENIED && (
- <Controller
- control={control}
- name="basicConstraints.maxPathLength"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label={
- <div className="flex items-center gap-1">
- <span className="mb-1">Maximum allowed path length</span>
- <Tooltip
- content={
- <div className="max-w-xs">
- <p className="font-medium">Values:</p>
- <ul className="mt-1 list-disc pl-4 text-xs">
- <li>
- <strong>-1</strong> = Unlimited (no restriction)
- </li>
- <li>
- <strong>0</strong> = Can only sign end-entity certificates
- </li>
- <li>
- <strong>1+</strong> = Number of CA levels allowed beneath
- </li>
- </ul>
- </div>
- }
+ </SectionToggle>
+
+ <SectionToggle
+ title="Restrict extended key usages"
+ description="Require, allow, or deny individual extended key usages."
+ enabled={restrictExtendedKeyUsages}
+ error={errors.extendedKeyUsages}
+ onChange={(enabled) => {
+ setRestrictExtendedKeyUsages(enabled);
+ if (!enabled)
+ setValue("extendedKeyUsages", { requiredUsages: [], optionalUsages: [] });
+ clearError("extendedKeyUsages");
+ markCustomPreset();
+ }}
+ >
+ {renderUsageGrid(
+ EXTENDED_KEY_USAGE_OPTIONS,
+ extendedKeyUsagePolicyOf as (u: never) => UsagePolicy,
+ setExtendedKeyUsagePolicy as (u: never, p: UsagePolicy) => void,
+ formatExtendedKeyUsage as (u: never) => string
+ )}
+ </SectionToggle>
+ </div>
+ )}
+
+ {step === 4 && (
+ <div className="space-y-8">
+ <SectionToggle
+ title="Set maximum validity"
+ description="Cap how long issued certificates can remain valid."
+ enabled={restrictValidity}
+ onChange={(enabled) => {
+ setRestrictValidity(enabled);
+ markCustomPreset();
+ }}
+ >
+ <div className="flex items-end gap-3">
+ <Controller
+ control={control}
+ name="validity.maxDuration.value"
+ render={({ field, fieldState: { error } }) => (
+ <Field className="flex-1">
+ <FieldLabel>Duration</FieldLabel>
+ <FieldContent>
+ <Input
+ type="number"
+ min={1}
+ isError={Boolean(error)}
+ value={field.value ?? ""}
+ onChange={(e) => {
+ const parsed = parseInt(e.target.value, 10);
+ field.onChange(Number.isNaN(parsed) ? undefined : parsed);
+ markCustomPreset();
+ }}
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="validity.maxDuration.unit"
+ render={({ field }) => (
+ <Field className="flex-1">
+ <FieldLabel>Unit</FieldLabel>
+ <FieldContent>
+ <Select
+ value={field.value}
+ onValueChange={(value) => {
+ field.onChange(value);
+ markCustomPreset();
+ }}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={CertDurationUnit.HOURS}>Hours</SelectItem>
+ <SelectItem value={CertDurationUnit.DAYS}>Days</SelectItem>
+ <SelectItem value={CertDurationUnit.MONTHS}>Months</SelectItem>
+ <SelectItem value={CertDurationUnit.YEARS}>Years</SelectItem>
+ </SelectContent>
+ </Select>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </div>
+ </SectionToggle>
+
+ <SectionToggle
+ title="Configure basic constraints"
+ description="Control whether issued certificates can act as a CA. Off allows any."
+ enabled={configureBasicConstraints}
+ onChange={(enabled) => {
+ setConfigureBasicConstraints(enabled);
+ markCustomPreset();
+ }}
+ >
+ <div className="space-y-4">
+ <Controller
+ control={control}
+ name="basicConstraints.isCA"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>CA certificate (isCA)</FieldLabel>
+ <FieldContent>
+ <Select
+ value={field.value}
+ onValueChange={(value) => {
+ field.onChange(value);
+ if (value === CertPolicyState.DENIED) {
+ setValue("basicConstraints.maxPathLength", undefined);
+ }
+ markCustomPreset();
+ }}
>
- <FontAwesomeIcon
- icon={faQuestionCircle}
- size="sm"
- className="ml-1 text-mineshaft-400"
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={CertPolicyState.DENIED}>Deny</SelectItem>
+ <SelectItem value={CertPolicyState.ALLOWED}>Allow</SelectItem>
+ <SelectItem value={CertPolicyState.REQUIRED}>Require</SelectItem>
+ </SelectContent>
+ </Select>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ {watchedIsCAPolicy !== CertPolicyState.DENIED && (
+ <Controller
+ control={control}
+ name="basicConstraints.maxPathLength"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Maximum path length</FieldLabel>
+ <FieldContent>
+ <Input
+ type="number"
+ min={0}
+ placeholder="Leave empty for no limit"
+ value={field.value ?? ""}
+ onChange={(e) => {
+ field.onChange(
+ e.target.value === "" ? null : parseInt(e.target.value, 10)
+ );
+ markCustomPreset();
+ }}
/>
- </Tooltip>
- </div>
- }
- isError={Boolean(error)}
- errorText={error?.message}
- helperText="Defines the pathLen constraint applied to issued certificates. Path length limits how many intermediate CA certificates can exist downstream from the issued certificate in the certificate chain."
- >
- <Input
- {...field}
- type="number"
- placeholder="Leave empty to omit the constraint"
- className="w-full"
- min={-1}
- value={field.value ?? ""}
- onChange={(e) => {
- const { value } = e.target;
- if (!value || value === "") {
- field.onChange(null);
- } else if (!Number.isInteger(Number(value))) {
- field.onChange(value);
- } else {
- field.onChange(Number(value));
- }
- }}
- />
- </FormControl>
+ <FieldDescription>
+ How many sub-CA levels can exist below this certificate.
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+ />
)}
- />
- )}
+ </div>
+ </SectionToggle>
</div>
- </AccordionContent>
- </AccordionItem>
- </Accordion>
-
- <div className="flex gap-3">
- <Button
- type="submit"
- colorSchema="primary"
- isLoading={isEdit ? updatePolicy.isPending : createPolicy.isPending}
- isDisabled={
- !formState.isValid || (isEdit ? updatePolicy.isPending : createPolicy.isPending)
- }
- >
- {isEdit ? "Save Changes" : "Create"}
- </Button>
- <Button
- variant="outline_bg"
- onClick={onClose}
- disabled={isEdit ? updatePolicy.isPending : createPolicy.isPending}
- >
- Cancel
- </Button>
+ )}
+ </div>
+
+ <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">
+ <div className="mb-auto">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">
+ Step {step + 1} · {currentStep.rightLabel}
+ </p>
+ <DocumentationLinkBadge href={PkiDocsUrls.settings.policies} />
+ </div>
+ <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>
+ <p className="mt-2 text-sm leading-relaxed text-muted">
+ {currentStep.rightDescription}
+ </p>
+ </div>
+ </aside>
+ </div>
+
+ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-6 py-4">
+ <span className="text-xs text-muted" />
+ <div className="flex items-center gap-3">
+ <span className="text-xs text-muted">
+ Step {step + 1} of {STEPS.length}
+ </span>
+ {step > 0 && (
+ <Button type="button" variant="outline" onClick={goBack}>
+ Back
+ </Button>
+ )}
+ {isLast ? (
+ <Button
+ key="submit-cta"
+ type="button"
+ variant="project"
+ isPending={isSubmitting}
+ isDisabled={isSubmitting}
+ onClick={handleSubmit(onFormSubmit)}
+ >
+ {isEdit ? "Save Changes" : "Create Policy"}
+ </Button>
+ ) : (
+ <Button key="continue-cta" type="button" variant="project" onClick={goNext}>
+ Continue
+ </Button>
+ )}
+ </div>
</div>
</form>
- </ModalContent>
- </Modal>
+ </SheetContent>
+ </Sheet>
);
};
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts
index 8609bca9d6..11d3519ff3 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts
@@ -45,6 +45,7 @@ export enum CertPolicyState {
}
export enum CertDurationUnit {
+ HOURS = "hours",
DAYS = "days",
MONTHS = "months",
YEARS = "years"
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/components.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/components.tsx
deleted file mode 100644
index a578be3c07..0000000000
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/components.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-import React from "react";
-
-import { Select, SelectItem } from "@app/components/v2";
-
-import {
- CertExtendedKeyUsageType,
- CertKeyUsageType,
- EXTENDED_KEY_USAGE_OPTIONS,
- formatExtendedKeyUsage,
- formatKeyUsage,
- KEY_USAGE_OPTIONS
-} from "./certificate-constants";
-
-type KeyUsagePolicy = "allow" | "require" | "deny";
-
-interface KeyUsagesSectionProps {
- watchedKeyUsages: {
- requiredUsages: CertKeyUsageType[];
- optionalUsages: CertKeyUsageType[];
- };
- watchedExtendedKeyUsages: {
- requiredUsages: CertExtendedKeyUsageType[];
- optionalUsages: CertExtendedKeyUsageType[];
- };
- onKeyUsagesChange: (usages: {
- requiredUsages: CertKeyUsageType[];
- optionalUsages: CertKeyUsageType[];
- }) => void;
- onExtendedKeyUsagesChange: (usages: {
- requiredUsages: CertExtendedKeyUsageType[];
- optionalUsages: CertExtendedKeyUsageType[];
- }) => void;
-}
-
-export const KeyUsagesSection: React.FC<KeyUsagesSectionProps> = ({
- watchedKeyUsages,
- watchedExtendedKeyUsages,
- onKeyUsagesChange,
- onExtendedKeyUsagesChange
-}) => {
- const getKeyUsagePolicy = (usage: CertKeyUsageType): KeyUsagePolicy => {
- if (watchedKeyUsages.requiredUsages.includes(usage)) return "require";
- if (watchedKeyUsages.optionalUsages.includes(usage)) return "allow";
- return "deny";
- };
-
- const getExtendedKeyUsagePolicy = (usage: CertExtendedKeyUsageType): KeyUsagePolicy => {
- if (watchedExtendedKeyUsages.requiredUsages.includes(usage)) return "require";
- if (watchedExtendedKeyUsages.optionalUsages.includes(usage)) return "allow";
- return "deny";
- };
-
- const handleKeyUsagePolicyChange = (usage: CertKeyUsageType, policy: KeyUsagePolicy) => {
- const newRequired = watchedKeyUsages.requiredUsages.filter((u) => u !== usage);
- const newOptional = watchedKeyUsages.optionalUsages.filter((u) => u !== usage);
-
- if (policy === "require") {
- newRequired.push(usage);
- } else if (policy === "allow") {
- newOptional.push(usage);
- }
-
- onKeyUsagesChange({
- requiredUsages: newRequired,
- optionalUsages: newOptional
- });
- };
-
- const handleExtendedKeyUsagePolicyChange = (
- usage: CertExtendedKeyUsageType,
- policy: KeyUsagePolicy
- ) => {
- const newRequired = watchedExtendedKeyUsages.requiredUsages.filter((u) => u !== usage);
- const newOptional = watchedExtendedKeyUsages.optionalUsages.filter((u) => u !== usage);
-
- if (policy === "require") {
- newRequired.push(usage);
- } else if (policy === "allow") {
- newOptional.push(usage);
- }
-
- onExtendedKeyUsagesChange({
- requiredUsages: newRequired,
- optionalUsages: newOptional
- });
- };
-
- const policyOptions = [
- { value: "deny", label: "Deny" },
- { value: "allow", label: "Allow" },
- { value: "require", label: "Require" }
- ];
-
- return (
- <div className="space-y-8">
- {/* Key Usages */}
- <div className="space-y-4">
- <h4 className="text-sm font-medium text-bunker-200">Key Usages</h4>
-
- <div className="grid grid-cols-2 gap-4">
- {KEY_USAGE_OPTIONS.map((usage) => {
- const policy = getKeyUsagePolicy(usage);
- return (
- <div key={usage} className="flex items-center justify-between">
- <span className="text-sm text-bunker-200">{formatKeyUsage(usage)}</span>
- <Select
- value={policy}
- onValueChange={(value) =>
- handleKeyUsagePolicyChange(usage, value as KeyUsagePolicy)
- }
- className="w-32"
- >
- {policyOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </Select>
- </div>
- );
- })}
- </div>
- </div>
-
- {/* Extended Key Usages */}
- <div className="space-y-4">
- <h4 className="text-sm font-medium text-bunker-200">Extended Key Usages</h4>
-
- <div className="grid grid-cols-2 gap-4">
- {EXTENDED_KEY_USAGE_OPTIONS.map((usage) => {
- const policy = getExtendedKeyUsagePolicy(usage);
- return (
- <div key={usage} className="flex items-center justify-between">
- <span className="text-sm text-bunker-200">{formatExtendedKeyUsage(usage)}</span>
- <Select
- value={policy}
- onValueChange={(value) =>
- handleExtendedKeyUsagePolicyChange(usage, value as KeyUsagePolicy)
- }
- className="w-32"
- >
- {policyOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </Select>
- </div>
- );
- })}
- </div>
- </div>
- </div>
- );
-};
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/index.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/index.ts
index 6567de7247..a56d10de7d 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/index.ts
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/index.ts
@@ -1,3 +1,2 @@
-export * from "./components";
export * from "./schemas";
export * from "./utils";
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/schemas.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/schemas.ts
index ed385a21e4..9be7dc60dd 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/schemas.ts
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/schemas.ts
@@ -42,15 +42,11 @@ export const uiValiditySchema = z.object({
});
export const uiSignatureAlgorithmSchema = z.object({
- allowedAlgorithms: z
- .array(z.string().min(1, "Algorithm cannot be empty"))
- .min(1, "At least one algorithm must be selected")
+ allowedAlgorithms: z.array(z.string().min(1, "Algorithm cannot be empty"))
});
export const uiKeyAlgorithmSchema = z.object({
- allowedKeyTypes: z
- .array(z.string().min(1, "Key type cannot be empty"))
- .min(1, "At least one key type must be selected")
+ allowedKeyTypes: z.array(z.string().min(1, "Key type cannot be empty"))
});
export const uiBasicConstraintsSchema = z.object({
@@ -98,8 +94,8 @@ export const policySchema = z.object({
keyUsages: uiKeyUsagesSchema.optional(),
extendedKeyUsages: uiExtendedKeyUsagesSchema.optional(),
validity: uiValiditySchema.optional(),
- signatureAlgorithm: uiSignatureAlgorithmSchema,
- keyAlgorithm: uiKeyAlgorithmSchema
+ signatureAlgorithm: uiSignatureAlgorithmSchema.optional(),
+ keyAlgorithm: uiKeyAlgorithmSchema.optional()
});
export type PolicyFormData = z.infer<typeof policySchema>;
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 e9559e523d..8f3c82546b 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
@@ -56,15 +56,19 @@ import {
useUpdateCertificateProfile
} from "@app/hooks/api/certificateProfiles";
import {
+ certKeyAlgorithms,
EXTENDED_KEY_USAGES_OPTIONS,
- KEY_USAGES_OPTIONS
+ KEY_USAGES_OPTIONS,
+ SIGNATURE_ALGORITHMS_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 { SubjectAltNamesField } from "@app/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField";
import { SubjectAttributesField } from "@app/pages/cert-manager/CertificatesPage/components/SubjectAttributesField";
import {
CertPolicyState,
+ CertSubjectAlternativeNameType,
CertSubjectAttributeType,
mapPolicyKeyAlgorithmToApi,
mapPolicySignatureAlgorithmToApi
@@ -84,6 +88,14 @@ const certificateDefaultsSchema = z
})
)
.optional(),
+ subjectAltNames: z
+ .array(
+ z.object({
+ type: z.nativeEnum(CertSubjectAlternativeNameType),
+ 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(),
@@ -306,6 +318,10 @@ const convertDefaultsToForm = (
return {
ttlDays: defaults.ttlDays ?? null,
subjectAttributes: subjectAttributes.length > 0 ? subjectAttributes : undefined,
+ subjectAltNames:
+ defaults.subjectAltNames && defaults.subjectAltNames.length > 0
+ ? (defaults.subjectAltNames as { type: CertSubjectAlternativeNameType; value: string }[])
+ : undefined,
signatureAlgorithm: defaults.signatureAlgorithm ?? null,
keyAlgorithm: defaults.keyAlgorithm ?? null,
keyUsages: Object.keys(keyUsagesRecord).length > 0 ? keyUsagesRecord : undefined,
@@ -376,6 +392,11 @@ const convertFormToDefaults = (
});
}
+ if (formDefaults.subjectAltNames && formDefaults.subjectAltNames.length > 0) {
+ const sans = formDefaults.subjectAltNames.filter((san) => san.value?.trim());
+ if (sans.length > 0) result.subjectAltNames = sans;
+ }
+
if (formDefaults.basicConstraints) {
result.basicConstraints = {
isCA: formDefaults.basicConstraints.isCA,
@@ -518,6 +539,8 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
allowedKeyAlgorithms: [] as Array<{ value: string; label: string }>,
allowedSubjectAttributeTypes: [] as CertSubjectAttributeType[],
shouldShowSubjectSection: false,
+ allowedSanTypes: [] as CertSubjectAlternativeNameType[],
+ shouldShowSanSection: false,
templateAllowsCA: false,
maxPathLength: undefined as number | undefined
};
@@ -528,33 +551,43 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
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 hasKeyUsagePolicy = Boolean(
+ templateData.keyUsages?.required?.length || templateData.keyUsages?.allowed?.length
);
+ const allowedKeyUsages = hasKeyUsagePolicy
+ ? [...(templateData.keyUsages?.required || []), ...(templateData.keyUsages?.allowed || [])]
+ : KEY_USAGES_OPTIONS.map((option) => option.value);
- const allowedKeyAlgorithms = (templateData.algorithms?.keyAlgorithm || []).map(
- (templateAlgorithm: string) => {
- const apiAlgorithm = mapPolicyKeyAlgorithmToApi(templateAlgorithm);
- return { value: apiAlgorithm, label: apiAlgorithm };
- }
+ const hasExtendedKeyUsagePolicy = Boolean(
+ templateData.extendedKeyUsages?.required?.length ||
+ templateData.extendedKeyUsages?.allowed?.length
);
+ const allowedExtendedKeyUsages = hasExtendedKeyUsagePolicy
+ ? [
+ ...(templateData.extendedKeyUsages?.required || []),
+ ...(templateData.extendedKeyUsages?.allowed || [])
+ ]
+ : EXTENDED_KEY_USAGES_OPTIONS.map((option) => option.value);
+
+ const allowedSignatureAlgorithms = templateData.algorithms?.signature?.length
+ ? templateData.algorithms.signature.map((templateAlgorithm: string) => {
+ const apiAlgorithm = mapPolicySignatureAlgorithmToApi(templateAlgorithm);
+ return { value: apiAlgorithm, label: apiAlgorithm };
+ })
+ : SIGNATURE_ALGORITHMS_OPTIONS.map((option) => ({
+ value: option.value as string,
+ label: option.label
+ }));
+
+ const allowedKeyAlgorithms = templateData.algorithms?.keyAlgorithm?.length
+ ? templateData.algorithms.keyAlgorithm.map((templateAlgorithm: string) => {
+ const apiAlgorithm = mapPolicyKeyAlgorithmToApi(templateAlgorithm);
+ return { value: apiAlgorithm, label: apiAlgorithm };
+ })
+ : certKeyAlgorithms.map((option) => ({ value: option.value as string, label: option.label }));
- let allowedSubjectAttributeTypes: CertSubjectAttributeType[] = [];
- let shouldShowSubjectSection = false;
+ let allowedSubjectAttributeTypes: CertSubjectAttributeType[];
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)) {
@@ -563,7 +596,28 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
});
allowedSubjectAttributeTypes =
subjectTypes.length > 0 ? subjectTypes : [CertSubjectAttributeType.COMMON_NAME];
+ } else {
+ allowedSubjectAttributeTypes = Object.values(
+ CertSubjectAttributeType
+ ) as CertSubjectAttributeType[];
+ }
+ const shouldShowSubjectSection = true;
+
+ let allowedSanTypes: CertSubjectAlternativeNameType[];
+ if (templateData.sans && templateData.sans.length > 0) {
+ const sanTypes: CertSubjectAlternativeNameType[] = [];
+ templateData.sans.forEach((sanPolicy: { type: string }) => {
+ if (!sanTypes.includes(sanPolicy.type as CertSubjectAlternativeNameType)) {
+ sanTypes.push(sanPolicy.type as CertSubjectAlternativeNameType);
+ }
+ });
+ allowedSanTypes = sanTypes;
+ } else {
+ allowedSanTypes = Object.values(
+ CertSubjectAlternativeNameType
+ ) as CertSubjectAlternativeNameType[];
}
+ const shouldShowSanSection = true;
return {
allowedKeyUsages,
@@ -574,6 +628,8 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
allowedKeyAlgorithms,
allowedSubjectAttributeTypes,
shouldShowSubjectSection,
+ allowedSanTypes,
+ shouldShowSanSection,
templateAllowsCA,
maxPathLength: templateData.basicConstraints?.maxPathLength as number | undefined
};
@@ -1051,6 +1107,15 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
/>
)}
+ {/* Subject Alternative Names — only if policy allows SANs */}
+ {policyConstraints.shouldShowSanSection && (
+ <SubjectAltNamesField
+ control={control}
+ allowedSanTypes={policyConstraints.allowedSanTypes}
+ namePrefix="defaults.subjectAltNames"
+ />
+ )}
+
{/* Algorithms — filtered to policy-allowed values, with "None" option */}
{(policyConstraints.allowedSignatureAlgorithms.length > 0 ||
policyConstraints.allowedKeyAlgorithms.length > 0) && (