Skip to content

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

Merge remote-tracking branch 'origin/main' into PKI-390

Carlos Monastyrski20c2cc359d08
diff --cc backend/src/services/certificate/certificate-fns.test.ts
index cd5301f463,0e862998f3..e1b8e648ba
--- a/backend/src/services/certificate/certificate-fns.test.ts
+++ b/backend/src/services/certificate/certificate-fns.test.ts
@@@ -108,4 -108,14 +108,14 @@@ describe("parseCertificateBody usages"
expect(fields).not.toHaveProperty("extendedKeyUsages");
expect(fields.isCA).toBe(false);
});
+
+ test("drops extended key usage OIDs it cannot map rather than leaving holes in the array", async () => {
+ const pem = await buildCert([
+ new x509.ExtendedKeyUsageExtension(["1.3.6.1.5.5.7.3.1", "1.3.6.1.4.1.311.20.2.2", "1.3.6.1.5.5.7.3.17"], false)
+ ]);
+
+ const fields = extractCertificateFields(pem);
+
- expect(fields.extendedKeyUsages).toEqual(["serverAuth"]);
++ expect(fields.extendedKeyUsages).toEqual(["serverAuth", "smartCardLogon"]);
+ });
});
diff --cc frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
index a3c5110055,143aeccaaf..c7f6c3c18d
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
@@@ -437,719 -434,1220 +456,1362 @@@ const SectionToggle = (
</div>
);
- export const CreatePolicyModal = ({
- isOpen,
- onClose,
- policy,
- mode = "create",
- onComplete
- }: Props) => {
- const { currentProject } = useProject();
- const { subscription } = useSubscription();
- const createPolicy = useCreateCertificatePolicy();
- const updatePolicy = useUpdateCertificatePolicy();
-
- 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 [restrictCustomExtensions, setRestrictCustomExtensions] = useState(false);
- const [isCustomExtensionDialogOpen, setIsCustomExtensionDialogOpen] = 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);
- };
+ export const CertificatePolicyWizard = forwardRef<CertificatePolicyWizardHandle, WizardProps>(
+ (
+ {
+ policy,
+ mode = "create",
+ onComplete,
+ onFinish,
+ step,
+ onStepChange,
+ banner,
+ defaultName,
+ nameDescription
+ },
+ ref
+ ) => {
+ const { currentProject } = useProject();
+ const { subscription } = useSubscription();
+ const createPolicy = useCreateCertificatePolicy();
+ const updatePolicy = useUpdateCertificatePolicy();
+
+ const isEdit = mode === "edit" && policy;
+
+ const currentStep = STEPS[step];
+ const setStep = (next: number) => onStepChange(Math.min(Math.max(next, 0), 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 [restrictCustomExtensions, setRestrictCustomExtensions] = useState(false);
++ const [isCustomExtensionDialogOpen, setIsCustomExtensionDialogOpen] = 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 toAttributeRows = (
- type: CertSubjectAttributeType,
- values: string[] | undefined,
- include: CertSubjectAttributeInclude
- ): AttributeRow[] =>
- Array.isArray(values) ? values.map((value) => ({ type, include, value: [value] })) : [];
-
- const convertApiToUiFormat = (policyData: TCertificatePolicy): FormData => {
- const attributes: FormData["attributes"] = Array.isArray(policyData.subject)
- ? policyData.subject.flatMap((subj) => {
- const type = subj.type as CertSubjectAttributeType;
- return [
- ...toAttributeRows(type, subj.required, CertSubjectAttributeInclude.REQUIRED),
- ...toAttributeRows(type, subj.allowed, CertSubjectAttributeInclude.OPTIONAL),
- ...toAttributeRows(type, subj.denied, CertSubjectAttributeInclude.PROHIBIT)
- ];
- })
- : [];
-
- const subjectAlternativeNames: FormData["subjectAlternativeNames"] = [];
- if (policyData.sans && Array.isArray(policyData.sans)) {
- policyData.sans.forEach((san) => {
- if (san.required && Array.isArray(san.required)) {
- san.required.forEach((requiredValue) => {
- subjectAlternativeNames.push({
- type: san.type as CertSubjectAlternativeNameType,
- include: CertSanInclude.MANDATORY,
- value: [requiredValue]
+ const toAttributeRows = (
+ type: CertSubjectAttributeType,
+ values: string[] | undefined,
+ include: CertSubjectAttributeInclude
+ ): AttributeRow[] =>
+ Array.isArray(values) ? values.map((value) => ({ type, include, value: [value] })) : [];
+
+ const convertApiToUiFormat = (policyData: TCertificatePolicy): FormData => {
+ const attributes: FormData["attributes"] = Array.isArray(policyData.subject)
+ ? policyData.subject.flatMap((subj) => {
+ const type = subj.type as CertSubjectAttributeType;
+ return [
+ ...toAttributeRows(type, subj.required, CertSubjectAttributeInclude.REQUIRED),
+ ...toAttributeRows(type, subj.allowed, CertSubjectAttributeInclude.OPTIONAL),
+ ...toAttributeRows(type, subj.denied, CertSubjectAttributeInclude.PROHIBIT)
+ ];
+ })
+ : [];
+
+ const subjectAlternativeNames: FormData["subjectAlternativeNames"] = [];
+ if (policyData.sans && Array.isArray(policyData.sans)) {
+ policyData.sans.forEach((san) => {
+ if (san.required && Array.isArray(san.required)) {
+ san.required.forEach((requiredValue) => {
+ subjectAlternativeNames.push({
+ type: san.type as CertSubjectAlternativeNameType,
+ include: CertSanInclude.MANDATORY,
+ value: [requiredValue]
+ });
});
- });
- }
- if (san.allowed && Array.isArray(san.allowed)) {
- san.allowed.forEach((allowedValue) => {
- subjectAlternativeNames.push({
- type: san.type as CertSubjectAlternativeNameType,
- include: CertSanInclude.OPTIONAL,
- value: [allowedValue]
+ }
+ if (san.allowed && Array.isArray(san.allowed)) {
+ san.allowed.forEach((allowedValue) => {
+ subjectAlternativeNames.push({
+ type: san.type as CertSubjectAlternativeNameType,
+ include: CertSanInclude.OPTIONAL,
+ value: [allowedValue]
+ });
});
- });
- }
- if (san.denied && Array.isArray(san.denied)) {
- san.denied.forEach((deniedValue) => {
- subjectAlternativeNames.push({
- type: san.type as CertSubjectAlternativeNameType,
- include: CertSanInclude.PROHIBIT,
- value: [deniedValue]
+ }
+ if (san.denied && Array.isArray(san.denied)) {
+ san.denied.forEach((deniedValue) => {
+ subjectAlternativeNames.push({
+ type: san.type as CertSubjectAlternativeNameType,
+ include: CertSanInclude.PROHIBIT,
+ value: [deniedValue]
+ });
});
- });
- }
- });
- }
-
- const keyUsages = {
- requiredUsages: (policyData.keyUsages?.required || []) as CertKeyUsageType[],
- optionalUsages: (policyData.keyUsages?.allowed || []) as CertKeyUsageType[]
- };
-
- const extendedKeyUsages = {
- requiredUsages: (policyData.extendedKeyUsages?.required || []) as CertExtendedKeyUsageType[],
- optionalUsages: (policyData.extendedKeyUsages?.allowed || []) as CertExtendedKeyUsageType[]
- };
-
- const validity = policyData.validity?.max
- ? (() => {
- const maxValue = policyData.validity.max;
- 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 { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };
}
+ });
+ }
- let unit: CertDurationUnit = CertDurationUnit.DAYS;
- 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;
- }
+ const keyUsages = {
+ requiredUsages: (policyData.keyUsages?.required || []) as CertKeyUsageType[],
+ optionalUsages: (policyData.keyUsages?.allowed || []) as CertKeyUsageType[]
+ };
+
+ const extendedKeyUsages = {
+ requiredUsages: (policyData.extendedKeyUsages?.required ||
+ []) as CertExtendedKeyUsageType[],
+ optionalUsages: (policyData.extendedKeyUsages?.allowed || []) as CertExtendedKeyUsageType[]
+ };
+
+ const validity = policyData.validity?.max
+ ? (() => {
+ const maxValue = policyData.validity.max;
+ 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 { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };
+ }
- return { maxDuration: { value, unit } };
- })()
- : { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };
+ let unit: CertDurationUnit = CertDurationUnit.DAYS;
+ 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;
+ }
- const signatureAlgorithm = {
- allowedAlgorithms: policyData.algorithms?.signature || []
- };
+ return { maxDuration: { value, unit } };
+ })()
+ : { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };
- const keyAlgorithm = {
- allowedKeyTypes: policyData.algorithms?.keyAlgorithm || []
- };
+ const signatureAlgorithm = {
+ allowedAlgorithms: policyData.algorithms?.signature || []
+ };
- const basicConstraints: FormData["basicConstraints"] = {
- isCA: (policyData.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED,
- maxPathLength: policyData.basicConstraints?.maxPathLength ?? undefined
- };
+ const keyAlgorithm = {
+ allowedKeyTypes: policyData.algorithms?.keyAlgorithm || []
+ };
- const customExtensions: FormData["customExtensions"] = (policyData.customExtensions ?? []).map(
- (rule) => ({
+ const basicConstraints: FormData["basicConstraints"] = {
+ isCA: (policyData.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED,
+ maxPathLength: policyData.basicConstraints?.maxPathLength ?? undefined
+ };
+
++ const customExtensions: FormData["customExtensions"] = (
++ policyData.customExtensions ?? []
++ ).map((rule) => ({
+ oid: rule.oid,
+ label: rule.label ?? "",
+ critical: rule.critical ?? "",
+ rule: rule.rule,
+ value: rule.value
- })
- );
-
- return {
- preset: POLICY_PRESET_IDS.CUSTOM,
- name: policyData.name || "",
- description: policyData.description || "",
- attributes,
- subjectAlternativeNames,
- keyUsages,
- extendedKeyUsages,
- validity,
- signatureAlgorithm,
- keyAlgorithm,
- basicConstraints,
- customExtensions
++ }));
++
+ return {
+ preset: POLICY_PRESET_IDS.CUSTOM,
+ name: policyData.name || "",
+ description: policyData.description || "",
+ attributes,
+ subjectAlternativeNames,
+ keyUsages,
+ extendedKeyUsages,
+ validity,
+ signatureAlgorithm,
+ keyAlgorithm,
- basicConstraints
++ basicConstraints,
++ customExtensions
+ };
};
- };
- const getDefaultValues = (): FormData & { preset: PolicyPresetId } => {
- return {
- preset: POLICY_PRESET_IDS.CUSTOM,
- name: "",
- description: "",
- basicConstraints: {
- isCA: CertPolicyState.DENIED,
- maxPathLength: undefined
- },
- attributes: [],
- keyUsages: { requiredUsages: [], optionalUsages: [] },
- extendedKeyUsages: { requiredUsages: [], optionalUsages: [] },
- subjectAlternativeNames: [],
- validity: {
- maxDuration: { value: 365, unit: CertDurationUnit.DAYS }
- },
- signatureAlgorithm: {
- allowedAlgorithms: []
- },
- keyAlgorithm: {
- allowedKeyTypes: []
- }
+ const getDefaultValues = (): FormData & { preset: PolicyPresetId } => {
+ return {
+ preset: POLICY_PRESET_IDS.CUSTOM,
+ name: defaultName ?? "",
+ description: "",
+ basicConstraints: {
+ isCA: CertPolicyState.DENIED,
+ maxPathLength: undefined
+ },
+ attributes: [],
+ keyUsages: { requiredUsages: [], optionalUsages: [] },
+ extendedKeyUsages: { requiredUsages: [], optionalUsages: [] },
+ subjectAlternativeNames: [],
+ validity: {
+ maxDuration: { value: 365, unit: CertDurationUnit.DAYS }
+ },
+ signatureAlgorithm: {
+ allowedAlgorithms: []
+ },
+ keyAlgorithm: {
+ allowedKeyTypes: []
+ }
+ };
};
- };
-
- const { control, handleSubmit, reset, watch, setValue, trigger } = useForm<
- FormData & { preset: PolicyPresetId }
- >({
- resolver: zodResolver(policySchema),
- defaultValues: getDefaultValues(),
- mode: "onChange",
- reValidateMode: "onChange",
- criteriaMode: "all"
- });
-
- const resetToggles = (source?: TCertificatePolicy) => {
- setRestrictSubject(Boolean(source?.subject));
- setRestrictSans(Boolean(source?.sans));
- setRestrictSignature(Boolean(source?.algorithms?.signature?.length));
- setRestrictKeyAlg(Boolean(source?.algorithms?.keyAlgorithm?.length));
- setRestrictKeyUsages(Boolean(source?.keyUsages));
- setRestrictExtendedKeyUsages(Boolean(source?.extendedKeyUsages));
- setRestrictValidity(Boolean(source?.validity?.max));
- setConfigureBasicConstraints(Boolean(source?.basicConstraints?.isCA));
- setRestrictCustomExtensions(Boolean(source?.customExtensions));
- setErrors({});
- };
-
- useEffect(() => {
- if (isEdit && policy) {
- const convertedData = convertApiToUiFormat(policy);
- reset({ ...convertedData, preset: POLICY_PRESET_IDS.CUSTOM });
- resetToggles(policy);
- } else if (!isEdit) {
- reset(getDefaultValues());
- resetToggles();
- }
- setStep(0);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isEdit, policy, reset, isOpen]);
-
- const watchedAttributes = watch("attributes") || [];
- const watchedSans = watch("subjectAlternativeNames") || [];
- const watchedKeyUsages = watch("keyUsages") || { requiredUsages: [], optionalUsages: [] };
- const watchedExtendedKeyUsages = watch("extendedKeyUsages") || {
- requiredUsages: [],
- 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 watchedCustomExtensions = watch("customExtensions") || [];
-
- const markCustomPreset = () => {
- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
- setValue("preset", POLICY_PRESET_IDS.CUSTOM);
- }
- };
- const removeCustomExtension = (index: number) => {
- setValue(
- "customExtensions",
- watchedCustomExtensions.filter((_, i) => i !== index)
- );
- clearError("customExtensions");
- markCustomPreset();
- };
+ const { control, handleSubmit, reset, watch, setValue, trigger } = useForm<
+ FormData & { preset: PolicyPresetId }
+ >({
+ resolver: zodResolver(policySchema),
+ defaultValues: getDefaultValues(),
+ mode: "onChange",
+ reValidateMode: "onChange",
+ criteriaMode: "all"
+ });
- const handlePresetChange = async (presetId: PolicyPresetId) => {
- setValue("preset", presetId);
+ const resetToggles = (source?: TCertificatePolicy) => {
+ setRestrictSubject(Boolean(source?.subject));
+ setRestrictSans(Boolean(source?.sans));
+ setRestrictSignature(Boolean(source?.algorithms?.signature?.length));
+ setRestrictKeyAlg(Boolean(source?.algorithms?.keyAlgorithm?.length));
+ setRestrictKeyUsages(Boolean(source?.keyUsages));
+ setRestrictExtendedKeyUsages(Boolean(source?.extendedKeyUsages));
+ setRestrictValidity(Boolean(source?.validity?.max));
+ setConfigureBasicConstraints(Boolean(source?.basicConstraints?.isCA));
++ setRestrictCustomExtensions(Boolean(source?.customExtensions));
+ setErrors({});
+ };
- if (presetId === POLICY_PRESET_IDS.CUSTOM) {
- await trigger();
- return;
- }
+ useEffect(() => {
+ if (isEdit && policy) {
+ const convertedData = convertApiToUiFormat(policy);
+ reset({ ...convertedData, preset: POLICY_PRESET_IDS.CUSTOM });
+ resetToggles(policy);
+ } else if (!isEdit) {
+ reset(getDefaultValues());
+ resetToggles();
+ }
+ setStep(0);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isEdit, policy, reset]);
+
+ const watchedAttributes = watch("attributes") || [];
+ const watchedSans = watch("subjectAlternativeNames") || [];
+ const watchedKeyUsages = watch("keyUsages") || { requiredUsages: [], optionalUsages: [] };
+ const watchedExtendedKeyUsages = watch("extendedKeyUsages") || {
+ requiredUsages: [],
+ 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 watchedCustomExtensions = watch("customExtensions") || [];
+
+ const markCustomPreset = () => {
+ if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
+ setValue("preset", POLICY_PRESET_IDS.CUSTOM);
+ }
+ };
- const selectedPreset = CERTIFICATE_POLICY_PRESETS.find((p) => p.id === presetId);
- if (selectedPreset) {
- 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));
- setValue("customExtensions", []);
- setRestrictCustomExtensions(false);
- 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
- )
++ const removeCustomExtension = (index: number) => {
++ setValue(
++ "customExtensions",
++ watchedCustomExtensions.filter((_, i) => i !== index)
+ );
++ clearError("customExtensions");
++ markCustomPreset();
++ };
+
- await trigger();
- }
- };
+ const handlePresetChange = async (presetId: PolicyPresetId) => {
+ setValue("preset", presetId);
- const mergeRuleValues = (
- existing: string[] | undefined,
- incoming: string[] | undefined
- ): string[] => Array.from(new Set([...(existing || []), ...(incoming || [])]));
-
- const consolidateByType = <
- T extends {
- type: string;
- allowed?: string[];
- required?: string[];
- denied?: string[];
- }
- >(
- items: T[]
- ): T[] => {
- const consolidated = new Map<string, T>();
-
- items.forEach((item) => {
- const existing = consolidated.get(item.type);
- if (existing) {
- const mergedItem = {
- ...item,
- allowed: mergeRuleValues(existing.allowed, item.allowed),
- required: mergeRuleValues(existing.required, item.required),
- denied: mergeRuleValues(existing.denied, item.denied)
- } as T;
-
- if (mergedItem.allowed?.length === 0) delete mergedItem.allowed;
- if (mergedItem.required?.length === 0) delete mergedItem.required;
- if (mergedItem.denied?.length === 0) delete mergedItem.denied;
-
- consolidated.set(item.type, mergedItem);
- } else {
- consolidated.set(item.type, item);
+ if (presetId === POLICY_PRESET_IDS.CUSTOM) {
+ await trigger();
+ return;
}
- });
- return Array.from(consolidated.values());
- };
+ const selectedPreset = CERTIFICATE_POLICY_PRESETS.find((p) => p.id === presetId);
+ if (selectedPreset) {
+ 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));
++ setValue("customExtensions", []);
++ setRestrictCustomExtensions(false);
+ 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
+ )
+ );
- const transformToApiFormat = (data: FormData) => {
- const subjectRaw =
- data.attributes?.map((attr): AttributeTransform => {
- const ruleKey = SUBJECT_INCLUDE_RULE_KEYS[attr.include];
-
- const values = attr.value || [];
- return {
- type: attr.type,
- ...(values.length > 0 ? { [ruleKey]: values } : {})
- } as AttributeTransform;
- }) || [];
-
- 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) {
- result.allowed = san.value;
- } else if (san.include === CertSanInclude.PROHIBIT && san.value && san.value.length > 0) {
- result.denied = san.value;
+ await trigger();
+ }
+ };
+
+ const mergeRuleValues = (
+ existing: string[] | undefined,
+ incoming: string[] | undefined
+ ): string[] => Array.from(new Set([...(existing || []), ...(incoming || [])]));
+
+ const consolidateByType = <
+ T extends {
+ type: string;
+ allowed?: string[];
+ required?: string[];
+ denied?: string[];
+ }
+ >(
+ items: T[]
+ ): T[] => {
+ const consolidated = new Map<string, T>();
+
+ items.forEach((item) => {
+ const existing = consolidated.get(item.type);
+ if (existing) {
+ const mergedItem = {
+ ...item,
+ allowed: mergeRuleValues(existing.allowed, item.allowed),
+ required: mergeRuleValues(existing.required, item.required),
+ denied: mergeRuleValues(existing.denied, item.denied)
+ } as T;
+
+ if (mergedItem.allowed?.length === 0) delete mergedItem.allowed;
+ if (mergedItem.required?.length === 0) delete mergedItem.required;
+ if (mergedItem.denied?.length === 0) delete mergedItem.denied;
+
+ consolidated.set(item.type, mergedItem);
+ } else {
+ consolidated.set(item.type, item);
}
- return result;
- }) || [];
+ });
- const subject = restrictSubject ? consolidateByType(subjectRaw) : null;
- const sans = restrictSans ? consolidateByType(sansRaw) : null;
+ return Array.from(consolidated.values());
+ };
- const keyUsages: KeyUsagesTransform | null = restrictKeyUsages
- ? {
- required: data.keyUsages?.requiredUsages ?? [],
- allowed: data.keyUsages?.optionalUsages ?? []
- }
- : null;
+ const transformToApiFormat = (data: FormData) => {
+ const subjectRaw =
+ data.attributes?.map((attr): AttributeTransform => {
+ const ruleKey = SUBJECT_INCLUDE_RULE_KEYS[attr.include];
+
+ const values = attr.value || [];
+ return {
+ type: attr.type,
+ ...(values.length > 0 ? { [ruleKey]: values } : {})
+ } as AttributeTransform;
+ }) || [];
+
+ 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) {
+ result.allowed = san.value;
+ } else if (san.include === CertSanInclude.PROHIBIT && san.value && san.value.length > 0) {
+ result.denied = san.value;
+ }
+ return result;
+ }) || [];
- const extendedKeyUsages: ExtendedKeyUsagesTransform | null = restrictExtendedKeyUsages
- ? {
- required: data.extendedKeyUsages?.requiredUsages ?? [],
- allowed: data.extendedKeyUsages?.optionalUsages ?? []
- }
- : null;
+ const subject = restrictSubject ? consolidateByType(subjectRaw) : null;
+ const sans = restrictSans ? consolidateByType(sansRaw) : null;
- const algorithms: AlgorithmsTransform = {};
- if (restrictSignature && data.signatureAlgorithm?.allowedAlgorithms?.length) {
- algorithms.signature = data.signatureAlgorithm
- .allowedAlgorithms as NonNullable<AlgorithmsTransform>["signature"];
- }
- if (restrictKeyAlg && data.keyAlgorithm?.allowedKeyTypes?.length) {
- algorithms.keyAlgorithm = data.keyAlgorithm
- .allowedKeyTypes as NonNullable<AlgorithmsTransform>["keyAlgorithm"];
- }
+ const keyUsages: KeyUsagesTransform | null = restrictKeyUsages
+ ? {
+ required: data.keyUsages?.requiredUsages ?? [],
+ allowed: data.keyUsages?.optionalUsages ?? []
+ }
+ : null;
- const validity: ValidityTransform = {};
- if (restrictValidity && data.validity?.maxDuration) {
- let unit = "d";
- 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";
- } else {
- unit = "y";
+ const extendedKeyUsages: ExtendedKeyUsagesTransform | null = restrictExtendedKeyUsages
+ ? {
+ required: data.extendedKeyUsages?.requiredUsages ?? [],
+ allowed: data.extendedKeyUsages?.optionalUsages ?? []
+ }
+ : null;
+
+ const algorithms: AlgorithmsTransform = {};
+ if (restrictSignature && data.signatureAlgorithm?.allowedAlgorithms?.length) {
+ algorithms.signature = data.signatureAlgorithm
+ .allowedAlgorithms as NonNullable<AlgorithmsTransform>["signature"];
+ }
+ if (restrictKeyAlg && data.keyAlgorithm?.allowedKeyTypes?.length) {
+ algorithms.keyAlgorithm = data.keyAlgorithm
+ .allowedKeyTypes as NonNullable<AlgorithmsTransform>["keyAlgorithm"];
}
- validity.max = `${data.validity.maxDuration.value}${unit}`;
- }
- const basicConstraints = configureBasicConstraints
- ? {
- isCA: data.basicConstraints?.isCA ?? CertPolicyState.DENIED,
- maxPathLength:
- data.basicConstraints?.isCA && data.basicConstraints.isCA !== CertPolicyState.DENIED
- ? (data.basicConstraints.maxPathLength ?? undefined)
- : undefined
+ const validity: ValidityTransform = {};
+ if (restrictValidity && data.validity?.maxDuration) {
+ let unit = "d";
+ 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";
+ } else {
+ unit = "y";
}
- : null;
-
- const customExtensions = restrictCustomExtensions
- ? (data.customExtensions ?? [])
- .filter((extension) => extension.oid.trim())
- .map((extension) => ({
- oid: extension.oid.trim(),
- ...(extension.label?.trim() && { label: extension.label.trim() }),
- ...(extension.critical && {
- critical: extension.critical
- }),
- rule: extension.rule,
- value: extension.value.trim() || "*"
- }))
- : null;
-
- return {
- name: data.name,
- description: data.description,
- subject,
- sans,
- keyUsages,
- extendedKeyUsages,
- algorithms: algorithms.signature || algorithms.keyAlgorithm ? algorithms : null,
- validity: validity.max ? validity : null,
- basicConstraints,
- customExtensions
+ validity.max = `${data.validity.maxDuration.value}${unit}`;
+ }
+
+ const basicConstraints = configureBasicConstraints
+ ? {
+ isCA: data.basicConstraints?.isCA ?? CertPolicyState.DENIED,
+ maxPathLength:
+ data.basicConstraints?.isCA && data.basicConstraints.isCA !== CertPolicyState.DENIED
+ ? (data.basicConstraints.maxPathLength ?? undefined)
+ : undefined
+ }
+ : null;
+
++ const customExtensions = restrictCustomExtensions
++ ? (data.customExtensions ?? [])
++ .filter((extension) => extension.oid.trim())
++ .map((extension) => ({
++ oid: extension.oid.trim(),
++ ...(extension.label?.trim() && { label: extension.label.trim() }),
++ ...(extension.critical && {
++ critical: extension.critical
++ }),
++ rule: extension.rule,
++ value: extension.value.trim() || "*"
++ }))
++ : null;
++
+ return {
+ name: data.name,
+ description: data.description,
+ subject,
+ sans,
+ keyUsages,
+ extendedKeyUsages,
+ algorithms: algorithms.signature || algorithms.keyAlgorithm ? algorithms : null,
+ validity: validity.max ? validity : null,
- basicConstraints
++ basicConstraints,
++ customExtensions
+ };
};
- };
- const onFormSubmit = async (data: FormData) => {
- if (!currentProject?.id && !isEdit) return;
+ const onFormSubmit = async (data: FormData) => {
+ if (!currentProject?.id && !isEdit) return;
- const hasEmptyAttributeValues =
- restrictSubject &&
- 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 =
- restrictSans &&
- 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 configured subject or SAN values must be non-empty. Use wildcards (*) if needed.",
- type: "error"
- });
- return;
- }
+ if (hasEmptyAttributeValues || hasEmptySanValues) {
+ createNotification({
+ text: "All configured subject or SAN values must be non-empty. Use wildcards (*) if needed.",
+ type: "error"
+ });
+ return;
+ }
- const hasInvalidDomainComponentSequence =
- restrictSubject &&
- data.attributes?.some(
- (attr) =>
- attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT &&
- attr.value?.some((value) => !isValidDomainComponentSequence(value))
- );
+ const hasInvalidDomainComponentSequence =
+ restrictSubject &&
+ data.attributes?.some(
+ (attr) =>
+ attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT &&
+ attr.value?.some((value) => !isValidDomainComponentSequence(value))
+ );
- if (hasInvalidDomainComponentSequence) {
- createNotification({
- text: "Every domain component in a sequence must be non-empty, for example corp,example,com.",
- type: "error"
- });
- return;
- }
+ if (hasInvalidDomainComponentSequence) {
+ createNotification({
+ text: "Every domain component in a sequence must be non-empty, for example corp,example,com.",
+ type: "error"
+ });
+ return;
+ }
- const transformedData = transformToApiFormat(data);
+ const transformedData = transformToApiFormat(data);
- if (isEdit) {
- await updatePolicy.mutateAsync({ policyId: policy.id, ...transformedData });
- } else {
- if (!currentProject?.id) {
- throw new Error("Project ID is required for creating a policy");
+ if (isEdit) {
+ await updatePolicy.mutateAsync({ policyId: policy.id, ...transformedData });
+ } else {
+ if (!currentProject?.id) {
+ throw new Error("Project ID is required for creating a policy");
+ }
+ const createdPolicy = await createPolicy.mutateAsync({
+ projectId: currentProject.id,
+ ...transformedData
+ });
+ await onComplete?.(createdPolicy);
}
- const createdPolicy = await createPolicy.mutateAsync({
- projectId: currentProject.id,
- ...transformedData
- });
- onComplete?.(createdPolicy);
- }
- createNotification({
- text: `Certificate policy ${isEdit ? "updated" : "created"} successfully`,
- type: "success"
- });
+ createNotification({
+ text: `Certificate policy ${isEdit ? "updated" : "created"} successfully`,
+ type: "success"
+ });
- reset();
- onClose();
- };
+ reset();
+ onFinish?.();
+ };
- const addAttribute = () => {
- setValue("attributes", [
- ...watchedAttributes,
- {
- type: SUBJECT_ATTRIBUTE_TYPE_OPTIONS[0],
- include: SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS[1],
- value: []
- }
- ]);
- clearError("subject");
- markCustomPreset();
- };
+ const addAttribute = () => {
+ setValue("attributes", [
+ ...watchedAttributes,
+ {
+ type: SUBJECT_ATTRIBUTE_TYPE_OPTIONS[0],
+ include: SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS[1],
+ value: []
+ }
+ ]);
+ clearError("subject");
+ markCustomPreset();
+ };
- const removeAttribute = (index: number) => {
- setValue(
- "attributes",
- watchedAttributes.filter((_, i) => i !== index)
- );
- markCustomPreset();
- };
+ const removeAttribute = (index: number) => {
+ setValue(
+ "attributes",
+ watchedAttributes.filter((_, i) => i !== index)
+ );
+ markCustomPreset();
+ };
- const addSan = () => {
- setValue("subjectAlternativeNames", [
- ...watchedSans,
- { type: SAN_TYPE_OPTIONS[0], include: SAN_INCLUDE_OPTIONS[1], value: [] }
- ]);
- clearError("sans");
- markCustomPreset();
- };
+ const addSan = () => {
+ setValue("subjectAlternativeNames", [
+ ...watchedSans,
+ { type: SAN_TYPE_OPTIONS[0], include: SAN_INCLUDE_OPTIONS[1], value: [] }
+ ]);
+ clearError("sans");
+ markCustomPreset();
+ };
- const removeSan = (index: number) => {
- setValue(
- "subjectAlternativeNames",
- watchedSans.filter((_, i) => i !== index)
- );
- markCustomPreset();
- };
+ const removeSan = (index: number) => {
+ setValue(
+ "subjectAlternativeNames",
+ watchedSans.filter((_, i) => i !== index)
+ );
+ markCustomPreset();
+ };
- const keyUsagePolicyOf = (usage: CertKeyUsageType): UsagePolicy => {
- if (watchedKeyUsages.requiredUsages.includes(usage)) return "require";
- if (watchedKeyUsages.optionalUsages.includes(usage)) return "allow";
- return "deny";
- };
+ const keyUsagePolicyOf = (usage: CertKeyUsageType): UsagePolicy => {
+ if (watchedKeyUsages.requiredUsages.includes(usage)) return "require";
+ if (watchedKeyUsages.optionalUsages.includes(usage)) return "allow";
+ return "deny";
+ };
- 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();
- };
+ 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();
+ };
- const extendedKeyUsagePolicyOf = (usage: CertExtendedKeyUsageType): UsagePolicy => {
- if (watchedExtendedKeyUsages.requiredUsages.includes(usage)) return "require";
- if (watchedExtendedKeyUsages.optionalUsages.includes(usage)) return "allow";
- return "deny";
- };
+ const extendedKeyUsagePolicyOf = (usage: CertExtendedKeyUsageType): UsagePolicy => {
+ if (watchedExtendedKeyUsages.requiredUsages.includes(usage)) return "require";
+ if (watchedExtendedKeyUsages.optionalUsages.includes(usage)) return "allow";
+ return "deny";
+ };
- 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();
- };
+ 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();
+ };
- 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 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> = {};
+ const validateStep = (): boolean => {
+ const stepErrors: Record<string, string> = {};
- if (step === 1) {
- if (restrictSubject && watchedAttributes.some((a) => !a.value?.[0]?.trim())) {
- stepErrors.subject = "Every subject attribute needs a value (use * for any).";
- }
- if (restrictSans && watchedSans.some((s) => !s.value?.[0]?.trim())) {
- stepErrors.sans = "Every subject alternative name needs a value (use * for any).";
+ if (step === 1) {
+ if (restrictSubject && watchedAttributes.some((a) => !a.value?.[0]?.trim())) {
+ stepErrors.subject = "Every subject attribute needs a value (use * for any).";
+ }
+ if (restrictSans && watchedSans.some((s) => !s.value?.[0]?.trim())) {
+ stepErrors.sans = "Every subject alternative name needs a value (use * for any).";
+ }
}
- }
- if (step === 4 && restrictCustomExtensions) {
- if (watchedCustomExtensions.some((extension) => !extension.oid?.trim())) {
- stepErrors.customExtensions = "Every custom extension needs an OID.";
- } else if (watchedCustomExtensions.some((extension) => !extension.value?.trim())) {
- stepErrors.customExtensions =
- "Every custom extension needs a value pattern (use * for any).";
++ if (step === 4 && restrictCustomExtensions) {
++ if (watchedCustomExtensions.some((extension) => !extension.oid?.trim())) {
++ stepErrors.customExtensions = "Every custom extension needs an OID.";
++ } else if (watchedCustomExtensions.some((extension) => !extension.value?.trim())) {
++ stepErrors.customExtensions =
++ "Every custom extension needs a value pattern (use * for any).";
++ }
+ }
- }
+
- if (step === 2) {
- if (restrictSignature && !watchedSignatureAlgs.length) {
- stepErrors.signature =
- "Select at least one signature algorithm, or turn off the restriction.";
+ 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 (restrictKeyAlg && !watchedKeyAlgs.length) {
- stepErrors.keyAlgorithm = "Select at least one key algorithm, 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(step + 1);
+ };
- setErrors(stepErrors);
- return Object.keys(stepErrors).length === 0;
- };
+ 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 leading-tight text-balance 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-24 shrink-0">
+ <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 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 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>
+ );
- 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 leading-tight text-balance 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-24 shrink-0">
- <SelectValue />
- </SelectTrigger>
- <SelectContent position="popper">
- {USAGE_POLICY_OPTIONS.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ useImperativeHandle(ref, () => ({
+ goNext,
+ submit: () => handleSubmit(onFormSubmit)()
+ }));
+
+ return (
+ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">
+ {banner}
+ <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>
- ))}
- </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))
- }
+ {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)} />
+ {nameDescription ? (
+ <FieldDescription>{nameDescription}</FieldDescription>
+ ) : null}
+ <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>
+ )}
/>
- <label
- htmlFor={`${fieldName}-${alg}`}
- className="flex cursor-pointer items-center gap-2 text-sm text-foreground"
+ <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-4">
+ {watchedAttributes.length === 0 && (
+ <p className="text-xs text-muted">
+ No attributes configured. Certificates issued under this policy cannot include
+ any subject attributes. Turn this off to allow any subject attribute.
+ </p>
+ )}
+ {watchedAttributes.map((attr, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <div key={`attr-${index}`}>
+ <div className="flex items-center gap-2">
+ <Select
+ value={attr.type}
+ onValueChange={(value) => {
+ const next = [...watchedAttributes];
+ next[index] = { ...attr, type: value as CertSubjectAttributeType };
+ setValue("attributes", next);
+ markCustomPreset();
+ }}
+ >
+ <SelectTrigger className="w-18 shrink-0" aria-label="Attribute type">
+ {ATTRIBUTE_TYPE_ABBREVIATIONS[attr.type]}
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {SUBJECT_ATTRIBUTE_TYPE_OPTIONS.map((type) => (
+ <SelectItem key={type} value={type}>
+ {ATTRIBUTE_TYPE_LABELS[type]}
+ </SelectItem>
+ ))}
+ </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-24 shrink-0">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS.map((type) => (
+ <SelectItem key={type} value={type}>
+ {SUBJECT_ATTRIBUTE_LABELS[type]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <InputGroup className="min-w-0 flex-1">
+ <InputGroupInput
+ placeholder={ATTRIBUTE_TYPE_PLACEHOLDERS[attr.type]}
+ 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();
+ }}
+ />
+ {attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT && (
+ <InputGroupAddon align="inline-end">
+ <DomainComponentHelp
+ isDenyRule={attr.include === CertSubjectAttributeInclude.PROHIBIT}
+ />
+ </InputGroupAddon>
+ )}
+ </InputGroup>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="shrink-0"
+ onClick={() => removeAttribute(index)}
+ >
+ <Trash2 className="size-4" />
+ </Button>
+ </div>
+ <AttributeRulePreview
+ type={attr.type}
+ include={attr.include}
+ value={attr.value?.[0] || ""}
+ />
+ </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.length === 0 && (
+ <p className="text-xs text-muted">
+ No SANs configured. Certificates issued under this policy cannot include any
+ subject alternative names. Turn this off to allow any SAN.
+ </p>
+ )}
+ {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 next = [...watchedSans];
+ next[index] = {
+ ...san,
+ type: value as CertSubjectAlternativeNameType
+ };
+ setValue("subjectAlternativeNames", next);
+ markCustomPreset();
+ }}
+ >
+ <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 next = [...watchedSans];
+ next[index] = {
+ ...san,
+ include: value as (typeof SAN_INCLUDE_OPTIONS)[number]
+ };
+ setValue("subjectAlternativeNames", next);
+ markCustomPreset();
+ }}
+ >
+ <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={SAN_TYPE_PLACEHOLDERS[san.type]}
+ value={san.value?.[0] || ""}
+ onChange={(e) => {
+ const next = [...watchedSans];
+ next[index] = {
+ ...san,
+ value: e.target.value.trim() ? [e.target.value.trim()] : []
+ };
+ setValue("subjectAlternativeNames", next);
+ markCustomPreset();
+ }}
+ className="flex-1"
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => removeSan(index)}
+ >
+ <Trash2 className="size-4" />
+ </Button>
+ </div>
+ ))}
+ <Button type="button" variant="outline" size="sm" onClick={addSan}>
+ <Plus className="size-4" /> Add SAN
+ </Button>
+ </div>
+ </SectionToggle>
+ </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();
+ }}
>
- {alg}
- {isPqcGated && <Badge variant="info">Enterprise</Badge>}
- </label>
+ {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>
- );
- })}
- </div>
- );
+ )}
+
+ {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
+ )}
+ </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="Restrict custom extensions"
++ description="Only allow the custom extension OIDs you configure here."
++ enabled={restrictCustomExtensions}
++ error={errors.customExtensions}
++ onChange={(enabled) => {
++ setRestrictCustomExtensions(enabled);
++ if (!enabled) setValue("customExtensions", []);
++ clearError("customExtensions");
++ markCustomPreset();
++ }}
++ >
++ {watchedCustomExtensions.length === 0 ? (
++ <p className="mb-4 text-sm text-muted">
++ No custom extensions configured. Certificates issued under this policy cannot
++ include any custom extensions. Turn this off to allow any custom extension a
++ profile declares.
++ </p>
++ ) : (
++ <Table>
++ <TableHeader>
++ <TableRow>
++ <TableHead>
++ <TableHeadLabel>Extension</TableHeadLabel>
++ </TableHead>
++ <TableHead>
++ <TableHeadLabel>Rule</TableHeadLabel>
++ </TableHead>
++ <TableHead>
++ <TableHeadLabel>Criticality</TableHeadLabel>
++ </TableHead>
++ <TableHead>
++ <TableHeadLabel>Value pattern</TableHeadLabel>
++ </TableHead>
++ <TableHead className="w-12" />
++ </TableRow>
++ </TableHeader>
++ <TableBody>
++ {watchedCustomExtensions.map((extension, index) => (
++ <TableRow key={extension.oid}>
++ <TableCell>
++ <p>{customExtensionLabelFor(extension.oid, extension.label)}</p>
++ <p className="font-mono text-xs text-muted">{extension.oid}</p>
++ </TableCell>
++ <TableCell className="capitalize">{extension.rule}</TableCell>
++ <TableCell>
++ {CUSTOM_EXTENSION_CRITICALITY_LABELS[extension.critical || ""]}
++ </TableCell>
++ <TableCell className="font-mono text-xs">{extension.value}</TableCell>
++ <TableCell>
++ <IconButton
++ type="button"
++ variant="ghost"
++ aria-label={`Remove ${extension.oid}`}
++ onClick={() => removeCustomExtension(index)}
++ >
++ <Trash2 className="size-4" />
++ </IconButton>
++ </TableCell>
++ </TableRow>
++ ))}
++ </TableBody>
++ </Table>
++ )}
++
++ <Button
++ type="button"
++ className="mt-3"
++ variant="outline"
++ size="sm"
++ onClick={() => setIsCustomExtensionDialogOpen(true)}
++ >
++ <Plus className="mr-1 size-4" />
++ Add extension
++ </Button>
++
++ <CustomExtensionRuleDialog
++ isOpen={isCustomExtensionDialogOpen}
++ onOpenChange={setIsCustomExtensionDialogOpen}
++ usedOids={watchedCustomExtensions.map((extension) => extension.oid)}
++ onConfirm={(rule) => {
++ setValue("customExtensions", [...watchedCustomExtensions, rule]);
++ clearError("customExtensions");
++ markCustomPreset();
++ }}
++ />
++ </SectionToggle>
++ </div>
++ )}
++
++ {step === 5 && (
+ <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 } }) => (
+ <DurationInput field={field} error={error} onCustomPreset={markCustomPreset} />
+ )}
+ />
+ <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();
+ }}
+ >
+ <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();
+ }}
+ />
+ <FieldDescription>
+ How many sub-CA levels can exist below this certificate.
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+ </div>
+ </SectionToggle>
+ </div>
+ )}
+ </div>
+ );
+ }
+ );
+
+ CertificatePolicyWizard.displayName = "CertificatePolicyWizard";
+
+ export const CreatePolicyModal = ({
+ isOpen,
+ onClose,
+ policy,
+ mode = "create",
+ onComplete
+ }: Props) => {
+ const [step, setStep] = useState(0);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const wizardRef = useRef<CertificatePolicyWizardHandle>(null);
+
+ const isEdit = mode === "edit" && policy;
+ const currentStep = STEPS[step];
+ const isLast = step === STEPS.length - 1;
+
+ const goBack = () => {
+ if (step > 0) setStep(step - 1);
+ };
+
+ const goNext = () => wizardRef.current?.goNext();
+
+ const handleSubmit = async () => {
+ setIsSubmitting(true);
+ try {
+ await wizardRef.current?.submit();
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
return (
<Sheet
diff --cc frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
index 80b068d48e,9199a38205..7bcd2b70fb
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
@@@ -37,9 -38,7 +38,8 @@@ import
ProjectPermissionCertificatePolicyActions,
ProjectPermissionSub
} from "@app/context/ProjectPermissionContext/types";
- import { usePopUp } from "@app/hooks";
-import { CaType } from "@app/hooks/api/ca/enums";
+import { caSupportsCapability } from "@app/hooks/api/ca/constants";
+import { CaCapability, CaType } from "@app/hooks/api/ca/enums";
import {
useGetAdcsTemplates,
useGetAzureAdcsTemplates,
@@@ -958,235 -1018,255 +1058,256 @@@ export const CreateProfileModal = (
</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>
-
- {currentStep.key === "details" && (
- <div className="space-y-5">
- <Controller
- control={control}
- name="slug"
- render={({ field, fieldState: { error } }) => (
- <Field>
- <FieldLabel>
- Name <span className="text-danger">*</span>
- </FieldLabel>
- <FieldContent>
- <Input
- {...field}
- placeholder="your-profile-name"
- 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="Enter profile description"
- rows={3}
- isError={Boolean(error)}
- />
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
- )}
- />
+ {isPolicyWizardOpen ? (
+ <CertificatePolicyWizard
+ ref={policyWizardRef}
+ step={policyStepIndex}
+ onStepChange={setPolicyStepIndex}
+ onComplete={handlePolicyCreated}
+ defaultName={draftPolicyName}
+ nameDescription="Pre-filled from the profile name. Edit if this policy will be shared."
+ banner={
+ <div className="mb-4 flex items-center gap-2 text-xs text-muted">
+ <ShieldCheck className="size-3.5 shrink-0" />
+ <span>
+ Defining the policy for <span className="text-accent">{watchedSlug}</span>
+ </span>
+ </div>
+ }
+ />
+ ) : (
+ <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>
- )}
- {currentStep.key === "issuer" && (
- <div className="space-y-5">
- <Controller
- control={control}
- name="issuerType"
- render={({ field: { onChange, value }, fieldState: { error } }) => (
- <Field>
- <FieldLabel>
- Issuer Type <span className="text-danger">*</span>
- </FieldLabel>
- <FieldContent>
- <Select
- value={value}
- onValueChange={(next) => {
- if (next === IssuerType.SELF_SIGNED) {
- setValue("certificateAuthorityId", "");
- setValue("externalConfigs", undefined);
- }
- onChange(next);
- }}
- >
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent position="popper">
- <SelectItem value={IssuerType.CA}>Certificate Authority</SelectItem>
- <SelectItem value={IssuerType.SELF_SIGNED}>Self-Signed</SelectItem>
- </SelectContent>
- </Select>
- <FieldDescription>
- Certificate Authority issues from an existing CA in your organization,
- which is the standard path for production use. Self-Signed produces
- standalone certificates with no CA chain, suitable for testing or
- one-off identities only.
- </FieldDescription>
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
- )}
- />
+ {currentStep.key === "details" && (
+ <div className="space-y-5">
+ <Controller
+ control={control}
+ name="slug"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Name <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ placeholder="your-profile-name"
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
- {watchedIssuerType === IssuerType.CA && (
<Controller
control={control}
- name="certificateAuthorityId"
- render={({ field: { onChange, value }, fieldState: { error } }) => {
- const hasCas = certificateAuthorities.length > 0;
- return (
- <Field>
- <FieldLabel>
- Certificate Authority <span className="text-danger">*</span>
- </FieldLabel>
- <FieldContent>
- <FilterableSelect
- value={certificateAuthorities.find((ca) => ca.id === value) || null}
- onChange={(selectedCaValue) => {
- let nextCaId = "";
- if (Array.isArray(selectedCaValue)) {
- nextCaId = selectedCaValue[0]?.id || "";
- } else if (
- selectedCaValue &&
- typeof selectedCaValue === "object" &&
- "id" in selectedCaValue
- ) {
- nextCaId = selectedCaValue.id || "";
- }
- if (nextCaId !== value) {
- // Templates are per-CA; a stale hidden template would
- // fail step validation for non-ADCS issuers.
- setValue("externalConfigs", undefined);
- }
- onChange(nextCaId);
- }}
- getOptionLabel={(ca) => ca.name}
- getOptionValue={(ca) => ca.id}
- options={certificateAuthorities}
- groupBy={hasCas ? "groupType" : undefined}
- getGroupHeaderLabel={hasCas ? getGroupHeaderLabel : undefined}
- placeholder="Select a certificate authority"
- isError={Boolean(error)}
- className="w-full"
- />
- <FieldError errors={[error]} />
- {!hasCas && (
- <FieldDescription className="text-yellow-500">
- No certificate authorities available.{" "}
- <Link
- to="/organizations/$orgId/projects/cert-manager/$projectId/certificate-authorities"
- params={{ orgId: orgId ?? "", projectId: projectId ?? "" }}
- className="underline hover:text-yellow-400"
- >
- Create one in Certificate Authorities
- </Link>
- </FieldDescription>
- )}
- </FieldContent>
- </Field>
- );
- }}
+ name="description"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <FieldContent>
+ <TextArea
+ {...field}
+ value={field.value ?? ""}
+ placeholder="Enter profile description"
+ rows={3}
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
/>
- )}
+ </div>
+ )}
- {isAzureAdcsCa && (
- <ExternalCaTemplateSelect
+ {currentStep.key === "issuer" && (
+ <div className="space-y-5">
+ <Controller
control={control}
- templates={azureAdcsTemplatesData?.templates || []}
- valueKey="id"
- placeholder="Select an Azure ADCS certificate template"
+ name="issuerType"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Issuer Type <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Select
+ value={value}
+ onValueChange={(next) => {
+ if (next === IssuerType.SELF_SIGNED) {
+ setValue("certificateAuthorityId", "");
+ setValue("externalConfigs", undefined);
+ }
+ onChange(next);
+ }}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={IssuerType.CA}>Certificate Authority</SelectItem>
+ <SelectItem value={IssuerType.SELF_SIGNED}>Self-Signed</SelectItem>
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ Certificate Authority issues from an existing CA in your organization,
+ which is the standard path for production use. Self-Signed produces
+ standalone certificates with no CA chain, suitable for testing or
+ one-off identities only.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
/>
- )}
- {isAdcsCa && (
- <ExternalCaTemplateSelect
+ {watchedIssuerType === IssuerType.CA && (
+ <Controller
+ control={control}
+ name="certificateAuthorityId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => {
+ const hasCas = certificateAuthorities.length > 0;
+ return (
+ <Field>
+ <FieldLabel>
+ Certificate Authority <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ value={
+ certificateAuthorities.find((ca) => ca.id === value) || null
+ }
+ onChange={(selectedCaValue) => {
+ let nextCaId = "";
+ if (Array.isArray(selectedCaValue)) {
+ nextCaId = selectedCaValue[0]?.id || "";
+ } else if (
+ selectedCaValue &&
+ typeof selectedCaValue === "object" &&
+ "id" in selectedCaValue
+ ) {
+ nextCaId = selectedCaValue.id || "";
+ }
+ if (nextCaId !== value) {
+ // Templates are per-CA; a stale hidden template would
+ // fail step validation for non-ADCS issuers.
+ setValue("externalConfigs", undefined);
+ }
+ onChange(nextCaId);
+ }}
+ getOptionLabel={(ca) => ca.name}
+ getOptionValue={(ca) => ca.id}
+ options={certificateAuthorities}
+ groupBy={hasCas ? "groupType" : undefined}
+ getGroupHeaderLabel={hasCas ? getGroupHeaderLabel : undefined}
+ placeholder="Select a certificate authority"
+ isError={Boolean(error)}
+ className="w-full"
+ />
+ <FieldError errors={[error]} />
+ {!hasCas && (
+ <FieldDescription className="text-yellow-500">
+ No certificate authorities available.{" "}
+ <Link
+ to="/organizations/$orgId/projects/cert-manager/$projectId/certificate-authorities"
+ params={{ orgId: orgId ?? "", projectId: projectId ?? "" }}
+ className="underline hover:text-yellow-400"
+ >
+ Create one in Certificate Authorities
+ </Link>
+ </FieldDescription>
+ )}
+ </FieldContent>
+ </Field>
+ );
+ }}
+ />
+ )}
+
+ {isAzureAdcsCa && (
+ <ExternalCaTemplateSelect
+ control={control}
+ templates={azureAdcsTemplatesData?.templates || []}
+ valueKey="id"
+ placeholder="Select an Azure ADCS certificate template"
+ />
+ )}
+
+ {isAdcsCa && (
+ <ExternalCaTemplateSelect
+ control={control}
+ templates={adcsTemplatesData?.templates || []}
+ valueKey="name"
+ placeholder="Select an ADCS certificate template"
+ />
+ )}
+
+ <Controller
control={control}
- templates={adcsTemplatesData?.templates || []}
- valueKey="name"
- placeholder="Select an ADCS certificate template"
+ name="certificatePolicyId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Certificate Policy <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ value={certificatePolicies.find((p) => p.id === value) ?? null}
+ onChange={(newValue) => {
+ const selected = newValue as SingleValue<PolicyOption>;
+ if (selected?.id === "_create") {
+ setPolicyStepIndex(0);
+ return;
+ }
+ onChange(selected?.id || "");
+
+ setValue("defaults", undefined);
+ }}
+ options={policyOptions}
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ placeholder={
+ certificatePolicies.length === 0 && !canCreatePolicy
+ ? "No certificate policies available"
+ : "Select a certificate policy"
+ }
+ isError={Boolean(error)}
+ components={{ Option: CertificatePolicyOption }}
+ className="w-full"
+ />
+ <FieldDescription>
+ The rules that govern certificates issued from this profile: allowed
+ key/signature algorithms, key usages, TTL bounds, and subject
+ constraints.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
/>
- )}
+ </div>
+ )}
- <Controller
+ {currentStep.key === "certificate-defaults" && (
+ <ProfileDefaultsStep
control={control}
- name="certificatePolicyId"
- render={({ field: { onChange, value }, fieldState: { error } }) => (
- <Field>
- <FieldLabel>
- Certificate Policy <span className="text-danger">*</span>
- </FieldLabel>
- <FieldContent>
- <FilterableSelect
- value={certificatePolicies.find((p) => p.id === value) ?? null}
- onChange={(newValue) => {
- const selected = newValue as SingleValue<PolicyOption>;
- if (selected?.id === "_create") {
- handlePopUpOpen("createPolicy");
- return;
- }
- onChange(selected?.id || "");
-
- setValue("defaults", undefined);
- }}
- options={policyOptions}
- getOptionLabel={(option) => option.name}
- getOptionValue={(option) => option.id}
- placeholder={
- certificatePolicies.length === 0 && !canCreatePolicy
- ? "No certificate policies available"
- : "Select a certificate policy"
- }
- isError={Boolean(error)}
- components={{ Option: CertificatePolicyOption }}
- className="w-full"
- />
- <FieldDescription>
- The rules that govern certificates issued from this profile: allowed
- key/signature algorithms, key usages, TTL bounds, and subject
- constraints.
- </FieldDescription>
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
- )}
+ watch={watch}
+ setValue={setValue}
+ policyConstraints={policyConstraints}
+ isAwsAcmPublicCa={isAwsAcmPublicCa}
+ isExternalAdcsCa={isAzureAdcsCa || isAdcsCa}
++ caSupportsCustomExtensions={caSupportsCustomExtensions}
+ caKeyAlgorithm={caKeyAlgorithm}
/>
- </div>
- )}
-
- {currentStep.key === "certificate-defaults" && (
- <ProfileDefaultsStep
- control={control}
- watch={watch}
- setValue={setValue}
- policyConstraints={policyConstraints}
- isAwsAcmPublicCa={isAwsAcmPublicCa}
- isExternalAdcsCa={isAzureAdcsCa || isAdcsCa}
- caSupportsCustomExtensions={caSupportsCustomExtensions}
- caKeyAlgorithm={caKeyAlgorithm}
- />
- )}
- </div>
+ )}
+ </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">