Skip to content

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

misc: addressed feedback

Sheen Capadngan51d27229ee98
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
index 8314b2d7e7..a1559dfad3 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
@@ -45,7 +45,6 @@ import {
import { AlgorithmSelectors } from "./AlgorithmSelectors";
import { BasicConstraintsField } from "./BasicConstraintsField";
import { buildManagedRequest } from "./buildManagedRequest";
-import { mergeRowErrors } from "./certificatePolicyGuidance";
import {
detectSanTypeFromValue,
EXTERNAL_CA_TEMPLATE_HINT,
@@ -54,11 +53,11 @@ import {
} from "./certificateUtils";
import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";
import { KeyUsageSection } from "./KeyUsageSection";
-import { PolicyRequirementsAlert } from "./PolicyRequirementsAlert";
import { SubjectAltNamesField } from "./SubjectAltNamesField";
import { SubjectAttributesField } from "./SubjectAttributesField";
import { useCertificatePolicy } from "./useCertificatePolicy";
-import { useSubjectPolicyGuidance } from "./useSubjectPolicyGuidance";
+import { usePolicyGuidance } from "./usePolicyGuidance";
+import { ValidityField } from "./ValidityField";
enum RequestMethod {
MANAGED = "managed",
@@ -317,6 +316,7 @@ export const CertificateIssuanceModal = ({
watch,
setValue,
trigger,
+ clearErrors,
formState,
formState: { isSubmitting }
} = useForm<FormData>({
@@ -385,18 +385,17 @@ export const CertificateIssuanceModal = ({
watch
);
- const policyGuidance = useSubjectPolicyGuidance({
+ const policy = usePolicyGuidance({
policy: policyData,
watch,
- setValue,
+ clearErrors,
isSubjectSectionShown: constraints.shouldShowSubjectSection,
isSanSectionShown: constraints.shouldShowSanSection,
- isEnabled: requestMethod === RequestMethod.MANAGED
+ isSubjectEvaluated: requestMethod === RequestMethod.MANAGED,
+ isValidityEvaluated: !isAdcsProfile,
+ resetKey: actualSelectedProfileId
});
- const hasPolicyIssuesRef = useRef(false);
- hasPolicyIssuesRef.current = policyGuidance.hasBlockingIssues;
-
const resetAllState = useCallback(() => {
resetConstraints();
reset();
@@ -421,10 +420,10 @@ export const CertificateIssuanceModal = ({
stepFields: STEP_FIELDS,
invalidMessage: "Please fix the highlighted fields before requesting.",
validateStep: async (fields) => {
- const isValid = await trigger(fields as (keyof FormData)[]);
- if (!isValid) return false;
- // The subject step is where policy violations can be fixed, so don't let them reach issuance.
- return !fields.includes("subjectAttributes") || !hasPolicyIssuesRef.current;
+ // Leaving a step reveals the findings on its own fields; entering it must stay quiet.
+ policy.reveal(fields);
+ if (!(await trigger(fields as (keyof FormData)[]))) return false;
+ return policy.findBlockedFields(fields).length === 0;
}
});
@@ -467,7 +466,9 @@ export const CertificateIssuanceModal = ({
}, [popUp?.issueCertificate?.isOpen, profileId, cert, setValue]);
useEffect(() => {
- if (popUp?.issueCertificate?.isOpen) setStep(0);
+ if (popUp?.issueCertificate?.isOpen) {
+ setStep(0);
+ }
}, [popUp?.issueCertificate?.isOpen]);
const onFormSubmit = useCallback(
@@ -490,11 +491,15 @@ export const CertificateIssuanceModal = ({
return;
}
- if (formData.requestMethod === RequestMethod.MANAGED && hasPolicyIssuesRef.current) {
- const subjectStepIndex = stepKeys.indexOf("subject");
- if (subjectStepIndex >= 0) setStep(subjectStepIndex);
+ // Reachable when a step was skipped or its values changed after it was cleared. Reveal the
+ // whole offending step, so the finding is visible wherever in it the requester lands.
+ const [blockedField] = policy.findBlockedFields(stepKeys.flatMap((key) => STEP_FIELDS[key]));
+ if (blockedField) {
+ const blockedStep = stepKeys.findIndex((key) => STEP_FIELDS[key].includes(blockedField));
+ policy.reveal(blockedStep >= 0 ? STEP_FIELDS[stepKeys[blockedStep]] : [blockedField]);
+ if (blockedStep >= 0) setStep(blockedStep);
createNotification({
- text: "Resolve the policy violations on the Subject step before requesting.",
+ text: "Resolve the policy violations before requesting this certificate.",
type: "error"
});
return;
@@ -753,13 +758,6 @@ export const CertificateIssuanceModal = ({
/>
)}
- {currentStepKey === "subject" && (
- <PolicyRequirementsAlert
- requirements={policyGuidance.requirements}
- onAddMissing={policyGuidance.addMissingFields}
- />
- )}
-
{currentStepKey === "subject" && constraints.shouldShowSubjectSection && (
<SubjectAttributesField
control={control}
@@ -768,14 +766,12 @@ export const CertificateIssuanceModal = ({
(formState.errors as { subjectAttributes?: { message?: string } }).subjectAttributes
?.message
}
- rowErrors={mergeRowErrors(
- rowErrorsOf(
- (formState.errors as { subjectAttributes?: unknown }).subjectAttributes
- ),
- policyGuidance.subjectRowErrors
+ rowErrors={rowErrorsOf(
+ (formState.errors as { subjectAttributes?: unknown }).subjectAttributes
)}
- rowHints={policyGuidance.subjectRowHints}
- notices={policyGuidance.subjectNotices}
+ policyRows={policy.subject.rows}
+ policyNotices={policy.subject.notices}
+ revealPolicyErrors={policy.isRevealed("subjectAttributes")}
/>
)}
@@ -787,27 +783,23 @@ export const CertificateIssuanceModal = ({
(formState.errors as { subjectAltNames?: { message?: string } }).subjectAltNames
?.message
}
- rowErrors={mergeRowErrors(
- rowErrorsOf((formState.errors as { subjectAltNames?: unknown }).subjectAltNames),
- policyGuidance.sanRowErrors
+ rowErrors={rowErrorsOf(
+ (formState.errors as { subjectAltNames?: unknown }).subjectAltNames
)}
- rowHints={policyGuidance.sanRowHints}
+ policyRows={policy.sans.rows}
+ policyNotices={policy.sans.notices}
+ revealPolicyErrors={policy.isRevealed("subjectAltNames")}
/>
)}
{(currentStepKey === "csr" || currentStepKey === "options") && !isAdcsProfile && (
- <Controller
+ <ValidityField
control={control}
- name="ttl"
- render={({ field, fieldState: { error } }) => (
- <Field className="mb-4">
- <FieldLabel>
- Time to Live (TTL) <span className="text-danger">*</span>
- </FieldLabel>
- <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(error)} />
- <FieldError errors={[error]} />
- </Field>
- )}
+ className="mb-4"
+ label="Time to Live (TTL)"
+ hint={policy.ttlHint}
+ policyError={policy.ttlError}
+ revealPolicyError={policy.isRevealed("ttl")}
/>
)}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
index 4a228402ee..79d17f2942 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
@@ -12,7 +12,6 @@ import {
FieldDescription,
FieldError,
FieldLabel,
- Input,
RadioGroup,
RadioGroupItem,
TextArea
@@ -42,7 +41,7 @@ import {
import { AlgorithmSelectors } from "./AlgorithmSelectors";
import { BasicConstraintsField } from "./BasicConstraintsField";
-import { mergeRowErrors } from "./certificatePolicyGuidance";
+import { buildPolicyRules, withRequiredRows } from "./certificatePolicyGuidance";
import {
buildRenewalFormDefaults,
buildRenewalRequestAttributes,
@@ -51,7 +50,6 @@ import {
import { isExternalTemplateCa, rowErrorsOf } from "./certificateUtils";
import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";
import { KeyUsageSection } from "./KeyUsageSection";
-import { PolicyRequirementsAlert } from "./PolicyRequirementsAlert";
import { SubjectAltNamesField } from "./SubjectAltNamesField";
import { SubjectAttributesField } from "./SubjectAttributesField";
import {
@@ -59,7 +57,8 @@ import {
deriveTemplateConstraints,
useCertificatePolicyOptions
} from "./useCertificatePolicy";
-import { useSubjectPolicyGuidance } from "./useSubjectPolicyGuidance";
+import { usePolicyGuidance } from "./usePolicyGuidance";
+import { ValidityField } from "./ValidityField";
const formSchema = z
.object({
@@ -240,6 +239,7 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
watch,
setValue,
trigger,
+ clearErrors,
formState,
formState: { isSubmitting }
} = useForm<RenewalFormData>({
@@ -373,27 +373,26 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
return keys;
}, [keySource, constraints.shouldShowSubjectSection, constraints.shouldShowSanSection]);
- const policyGuidance = useSubjectPolicyGuidance({
+ const policy = usePolicyGuidance({
policy: policyData,
watch,
- setValue,
+ clearErrors,
isSubjectSectionShown: constraints.shouldShowSubjectSection,
isSanSectionShown: constraints.shouldShowSanSection,
- isEnabled: keySource !== CertificateRenewalKeySource.Csr
+ isSubjectEvaluated: keySource !== CertificateRenewalKeySource.Csr,
+ isValidityEvaluated: !isExternalTemplateProfile,
+ resetKey: certificate?.id
});
- const hasPolicyIssuesRef = useRef(false);
- hasPolicyIssuesRef.current = policyGuidance.hasBlockingIssues;
-
const { step, setStep, currentStepKey, goBack, goNext, onFormInvalid } = useWizardSteps({
stepKeys,
stepFields: STEP_FIELDS,
invalidMessage: "Please fix the highlighted fields before renewing.",
validateStep: async (fields) => {
- const isValid = await trigger(fields as (keyof RenewalFormData)[]);
- if (!isValid) return false;
- // The subject step is where policy violations can be fixed, so don't let them reach renewal.
- return !fields.includes("subjectAttributes") || !hasPolicyIssuesRef.current;
+ // Leaving a step reveals the findings on its own fields; entering it must stay quiet.
+ policy.reveal(fields);
+ if (!(await trigger(fields as (keyof RenewalFormData)[]))) return false;
+ return policy.findBlockedFields(fields).length === 0;
}
});
@@ -417,9 +416,20 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
return;
seededCertificateIdRef.current = certificate.id;
- reset(buildRenewalFormDefaults(certificate, constraints));
+ const renewalDefaults = buildRenewalFormDefaults(certificate, constraints);
+ // Seed the rows the policy requires so they are visible as fields from the start.
+ const seeded = withRequiredRows(
+ buildPolicyRules(policyData),
+ renewalDefaults.subjectAttributes ?? [],
+ renewalDefaults.subjectAltNames ?? []
+ );
+ reset({
+ ...renewalDefaults,
+ subjectAttributes: seeded.subjectAttributes,
+ subjectAltNames: seeded.subjectAltNames
+ });
setStep(0);
- }, [isOpen, certificate, isPolicyResolved, constraints, reset]);
+ }, [isOpen, certificate, isPolicyResolved, constraints, policyData, reset]);
const closeWizard = () => {
handlePopUpToggle("renewCertificate", false);
@@ -430,11 +440,15 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
const onFormSubmit = async (formData: RenewalFormData) => {
if (!certificateId) return;
- if (keySource !== CertificateRenewalKeySource.Csr && hasPolicyIssuesRef.current) {
- const subjectStepIndex = stepKeys.indexOf("subject");
- if (subjectStepIndex >= 0) setStep(subjectStepIndex);
+ // Reachable when a step was skipped or its values changed after it was cleared. Reveal the
+ // whole offending step, so the finding is visible wherever in it the requester lands.
+ const [blockedField] = policy.findBlockedFields(stepKeys.flatMap((key) => STEP_FIELDS[key]));
+ if (blockedField) {
+ const blockedStep = stepKeys.findIndex((key) => STEP_FIELDS[key].includes(blockedField));
+ policy.reveal(blockedStep >= 0 ? STEP_FIELDS[stepKeys[blockedStep]] : [blockedField]);
+ if (blockedStep >= 0) setStep(blockedStep);
createNotification({
- text: "Resolve the policy violations on the Subject step before renewing.",
+ text: "Resolve the policy violations before renewing this certificate.",
type: "error"
});
return;
@@ -584,28 +598,18 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
</Field>
)}
/>
- <Controller
+ <ValidityField
control={control}
- name="ttl"
- render={({ field, fieldState: { error } }) => (
- <Field>
- <FieldLabel>
- Validity (TTL) <span className="text-danger">*</span>
- </FieldLabel>
- <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(error)} />
- <FieldError errors={[error]} />
- </Field>
- )}
+ label="Validity (TTL)"
+ hint={policy.ttlHint}
+ policyError={policy.ttlError}
+ revealPolicyError={policy.isRevealed("ttl")}
/>
</div>
)}
{currentStepKey === "subject" && (
<div className="space-y-4">
- <PolicyRequirementsAlert
- requirements={policyGuidance.requirements}
- onAddMissing={policyGuidance.addMissingFields}
- />
{constraints.shouldShowSubjectSection && (
<SubjectAttributesField
control={control}
@@ -614,14 +618,12 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
(formState.errors as { subjectAttributes?: { message?: string } }).subjectAttributes
?.message
}
- rowErrors={mergeRowErrors(
- rowErrorsOf(
- (formState.errors as { subjectAttributes?: unknown }).subjectAttributes
- ),
- policyGuidance.subjectRowErrors
+ rowErrors={rowErrorsOf(
+ (formState.errors as { subjectAttributes?: unknown }).subjectAttributes
)}
- rowHints={policyGuidance.subjectRowHints}
- notices={policyGuidance.subjectNotices}
+ policyRows={policy.subject.rows}
+ policyNotices={policy.subject.notices}
+ revealPolicyErrors={policy.isRevealed("subjectAttributes")}
/>
)}
{constraints.shouldShowSanSection && (
@@ -632,11 +634,12 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
(formState.errors as { subjectAltNames?: { message?: string } }).subjectAltNames
?.message
}
- rowErrors={mergeRowErrors(
- rowErrorsOf((formState.errors as { subjectAltNames?: unknown }).subjectAltNames),
- policyGuidance.sanRowErrors
+ rowErrors={rowErrorsOf(
+ (formState.errors as { subjectAltNames?: unknown }).subjectAltNames
)}
- rowHints={policyGuidance.sanRowHints}
+ policyRows={policy.sans.rows}
+ policyNotices={policy.sans.notices}
+ revealPolicyErrors={policy.isRevealed("subjectAltNames")}
/>
)}
</div>
@@ -645,21 +648,14 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
{currentStepKey === "options" && (
<div className="space-y-4">
{!isExternalTemplateProfile && (
- <Controller
+ <ValidityField
control={control}
- name="ttl"
- render={({ field, fieldState: { error } }) => (
- <Field className="mb-4">
- <FieldLabel>
- Validity (TTL) <span className="text-danger">*</span>
- </FieldLabel>
- <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(error)} />
- <FieldDescription>
- The renewed certificate is valid for this long, starting now.
- </FieldDescription>
- <FieldError errors={[error]} />
- </Field>
- )}
+ className="mb-4"
+ label="Validity (TTL)"
+ description="The renewed certificate is valid for this long, starting now."
+ hint={policy.ttlHint}
+ policyError={policy.ttlError}
+ revealPolicyError={policy.isRevealed("ttl")}
/>
)}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/PolicyRequirementsAlert.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/PolicyRequirementsAlert.tsx
deleted file mode 100644
index 4d1b5ccbbf..0000000000
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/PolicyRequirementsAlert.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { ListChecks, Plus } from "lucide-react";
-
-import { Alert, AlertDescription, AlertTitle, Button } from "@app/components/v3";
-
-import { PolicyRequirement } from "./certificatePolicyGuidance";
-
-type Props = {
- requirements: PolicyRequirement[];
- onAddMissing?: () => void;
-};
-
-export const PolicyRequirementsAlert = ({ requirements, onAddMissing }: Props) => {
- if (requirements.length === 0) return null;
-
- const canAddMissing = Boolean(onAddMissing) && requirements.some(({ addRows }) => addRows);
-
- return (
- <Alert variant="warning" className="mb-4">
- <ListChecks />
- <AlertTitle>Still required by this profile&apos;s policy</AlertTitle>
- <AlertDescription>
- <ul className="list-disc space-y-0.5 pl-4">
- {requirements.map(({ id, message }) => (
- <li key={id}>{message}</li>
- ))}
- </ul>
- {canAddMissing && (
- <Button type="button" variant="outline" size="xs" className="mt-2" onClick={onAddMissing}>
- <Plus /> Add Missing Fields
- </Button>
- )}
- </AlertDescription>
- </Alert>
- );
-};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/PolicyRowMessage.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/PolicyRowMessage.tsx
new file mode 100644
index 0000000000..b9c38bdbb5
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/PolicyRowMessage.tsx
@@ -0,0 +1,40 @@
+import {
+ FieldDescription,
+ FieldError,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+
+type Props = {
+ lines: string[];
+ isError?: boolean;
+};
+
+/**
+ * A policy constraint can list many patterns, and a single pattern can be long, so the message is
+ * kept to one line under the input and the full text is read from the tooltip, where each
+ * constraint gets its own paragraph.
+ */
+export const PolicyRowMessage = ({ lines, isError }: Props) => {
+ if (lines.length === 0) return null;
+
+ const message = (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="block truncate">{lines.join("; ")}</span>
+ </TooltipTrigger>
+ <TooltipContent className="flex max-w-sm flex-col gap-1.5 break-words">
+ {lines.map((line) => (
+ <span key={line}>{line}</span>
+ ))}
+ </TooltipContent>
+ </Tooltip>
+ );
+
+ return isError ? (
+ <FieldError className="mt-1.5">{message}</FieldError>
+ ) : (
+ <FieldDescription className="mt-1.5">{message}</FieldDescription>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx
index 7ec46524fa..8c98bb2320 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx
@@ -4,7 +4,6 @@ import { Plus, Trash2 } from "lucide-react";
import {
Button,
Field,
- FieldDescription,
FieldError,
FieldLabel,
IconButton,
@@ -17,14 +16,21 @@ import {
} from "@app/components/v3";
import { CertSubjectAlternativeNameType } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+import { PolicyNotice, PolicyRowGuidance } from "./certificatePolicyGuidance";
import { getSanPlaceholder, getSanTypeLabels, SubjectAltName } from "./certificateUtils";
+import { PolicyRowMessage } from "./PolicyRowMessage";
type SubjectAltNamesFieldProps = {
control: Control<any>;
allowedSanTypes: CertSubjectAlternativeNameType[];
error?: string;
rowErrors?: (string | undefined)[];
- rowHints?: (string | undefined)[];
+ /** Per-row policy findings: the constraint, how the value breaks it, and whether it is fixed. */
+ policyRows?: PolicyRowGuidance[];
+ /** Policy findings spanning several rows, such as a required SAN pattern. */
+ policyNotices?: PolicyNotice[];
+ /** Policy findings stay hidden until the requester tries to leave the step. */
+ revealPolicyErrors?: boolean;
shouldUnregister?: boolean;
namePrefix?: string;
};
@@ -34,7 +40,9 @@ export const SubjectAltNamesField = ({
allowedSanTypes,
error,
rowErrors,
- rowHints,
+ policyRows,
+ policyNotices,
+ revealPolicyErrors,
shouldUnregister,
namePrefix = "subjectAltNames"
}: SubjectAltNamesFieldProps) => {
@@ -51,60 +59,66 @@ export const SubjectAltNamesField = ({
<Field className="mb-4">
<FieldLabel>Subject Alternative Names (SANs)</FieldLabel>
<div className="space-y-3">
- {currentValues.map((san, index) => (
- // eslint-disable-next-line react/no-array-index-key
- <div key={`subject-alt-name-${index}`} className="flex items-start gap-2">
- <Select
- value={san.type}
- onValueChange={(newType) => {
- const newValue = [...currentValues];
- newValue[index] = {
- ...san,
- type: newType as CertSubjectAlternativeNameType
- };
- onChange(newValue);
- }}
- >
- <SelectTrigger className="w-32">
- <SelectValue />
- </SelectTrigger>
- <SelectContent position="popper">
- {allowedSanTypes.map((sanType) => (
- <SelectItem key={sanType} value={sanType}>
- {sanTypeLabels[sanType]}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <div className="flex-1">
- <Input
- value={san.value}
- onChange={(e) => {
+ {currentValues.map((san, index) => {
+ const policy = policyRows?.[index];
+ const rowError =
+ rowErrors?.[index] ?? (revealPolicyErrors ? policy?.error : undefined);
+
+ return (
+ // eslint-disable-next-line react/no-array-index-key
+ <div key={`subject-alt-name-${index}`} className="flex items-start gap-2">
+ <Select
+ value={san.type}
+ onValueChange={(newType) => {
const newValue = [...currentValues];
- newValue[index] = { ...san, value: e.target.value };
+ newValue[index] = {
+ ...san,
+ type: newType as CertSubjectAlternativeNameType
+ };
onChange(newValue);
}}
- placeholder={getSanPlaceholder(san.type)}
- isError={Boolean(rowErrors?.[index])}
- className="w-full"
- />
- {rowErrors?.[index] ? (
- <FieldError className="mt-1.5">{rowErrors[index]}</FieldError>
- ) : null}
- {!rowErrors?.[index] && rowHints?.[index] && (
- <FieldDescription className="mt-1.5">{rowHints[index]}</FieldDescription>
+ >
+ <SelectTrigger className="w-32" disabled={policy?.isLocked}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {allowedSanTypes.map((sanType) => (
+ <SelectItem key={sanType} value={sanType}>
+ {sanTypeLabels[sanType]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <div className="min-w-0 flex-1">
+ <Input
+ value={san.value}
+ onChange={(e) => {
+ const newValue = [...currentValues];
+ newValue[index] = { ...san, value: e.target.value };
+ onChange(newValue);
+ }}
+ placeholder={getSanPlaceholder(san.type)}
+ isError={Boolean(rowError)}
+ className="w-full"
+ />
+ {rowError && <PolicyRowMessage isError lines={[rowError]} />}
+ {!rowError && policy?.hint && <PolicyRowMessage lines={policy.hint} />}
+ </div>
+ {policy?.isLocked ? (
+ <span className="w-9 shrink-0" />
+ ) : (
+ <IconButton
+ type="button"
+ variant="ghost"
+ aria-label="Remove entry"
+ onClick={() => onChange(currentValues.filter((_, i) => i !== index))}
+ >
+ <Trash2 />
+ </IconButton>
)}
</div>
- <IconButton
- type="button"
- variant="ghost"
- aria-label="Remove entry"
- onClick={() => onChange(currentValues.filter((_, i) => i !== index))}
- >
- <Trash2 />
- </IconButton>
- </div>
- ))}
+ );
+ })}
<Button
type="button"
variant="outline"
@@ -121,6 +135,23 @@ export const SubjectAltNamesField = ({
</Button>
</div>
<FieldError>{error}</FieldError>
+ {revealPolicyErrors && Boolean(policyNotices?.length) && (
+ <div className="mb-2 space-y-2">
+ {policyNotices?.map((notice) => (
+ <FieldError key={notice.message}>
+ <span className="block">
+ {notice.message}
+ {notice.label ? ` ${notice.label}:` : null}
+ </span>
+ {notice.items?.map((item) => (
+ <span key={item} className="block pl-3">
+ {item}
+ </span>
+ ))}
+ </FieldError>
+ ))}
+ </div>
+ )}
</Field>
);
}}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
index 2dae8457a4..90b08e15c7 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
@@ -4,7 +4,6 @@ import { Plus, Trash2 } from "lucide-react";
import {
Button,
Field,
- FieldDescription,
FieldError,
FieldLabel,
IconButton,
@@ -17,7 +16,9 @@ import {
} from "@app/components/v3";
import { CertSubjectAttributeType } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+import { PolicyNotice, PolicyRowGuidance } from "./certificatePolicyGuidance";
import { SUBJECT_ATTRIBUTE_LABELS, SubjectAttribute } from "./certificateUtils";
+import { PolicyRowMessage } from "./PolicyRowMessage";
const getSubjectAttributePlaceholder = (type: CertSubjectAttributeType): string => {
switch (type) {
@@ -46,8 +47,12 @@ type SubjectAttributesFieldProps = {
allowedAttributeTypes: CertSubjectAttributeType[];
error?: string;
rowErrors?: (string | undefined)[];
- rowHints?: (string | undefined)[];
- notices?: string[];
+ /** Per-row policy findings: the constraint, how the value breaks it, and whether it is fixed. */
+ policyRows?: PolicyRowGuidance[];
+ /** Policy findings spanning several rows, such as an ordered sequence. */
+ policyNotices?: PolicyNotice[];
+ /** Policy findings stay hidden until the requester tries to leave the step. */
+ revealPolicyErrors?: boolean;
shouldUnregister?: boolean;
namePrefix?: string;
};
@@ -57,8 +62,9 @@ export const SubjectAttributesField = ({
allowedAttributeTypes,
error,
rowErrors,
- rowHints,
- notices,
+ policyRows,
+ policyNotices,
+ revealPolicyErrors,
shouldUnregister,
namePrefix = "subjectAttributes"
}: SubjectAttributesFieldProps) => {
@@ -86,6 +92,9 @@ export const SubjectAttributesField = ({
const selectableTypes = allowedAttributeTypes.filter(
(type) => type === attr.type || isMultiValued(type) || !usedTypes.includes(type)
);
+ const policy = policyRows?.[index];
+ const rowError =
+ rowErrors?.[index] ?? (revealPolicyErrors ? policy?.error : undefined);
return (
<div
@@ -101,7 +110,7 @@ export const SubjectAttributesField = ({
onChange(newValue);
}}
>
- <SelectTrigger className="w-52">
+ <SelectTrigger className="w-52" disabled={policy?.isLocked}>
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
@@ -112,7 +121,7 @@ export const SubjectAttributesField = ({
))}
</SelectContent>
</Select>
- <div className="flex-1">
+ <div className="min-w-0 flex-1">
<Input
value={attr.value}
onChange={(e) => {
@@ -121,22 +130,24 @@ export const SubjectAttributesField = ({
onChange(newValue);
}}
placeholder={getSubjectAttributePlaceholder(attr.type)}
- isError={Boolean(rowErrors?.[index])}
+ isError={Boolean(rowError)}
className="w-full"
/>
- <FieldError className="mt-1.5">{rowErrors?.[index]}</FieldError>
- {!rowErrors?.[index] && rowHints?.[index] && (
- <FieldDescription className="mt-1.5">{rowHints[index]}</FieldDescription>
- )}
+ {rowError && <PolicyRowMessage isError lines={[rowError]} />}
+ {!rowError && policy?.hint && <PolicyRowMessage lines={policy.hint} />}
</div>
- <IconButton
- type="button"
- variant="ghost"
- aria-label="Remove entry"
- onClick={() => onChange(currentValues.filter((_, i) => i !== index))}
- >
- <Trash2 />
- </IconButton>
+ {policy?.isLocked ? (
+ <span className="w-9 shrink-0" />
+ ) : (
+ <IconButton
+ type="button"
+ variant="ghost"
+ aria-label="Remove entry"
+ onClick={() => onChange(currentValues.filter((_, i) => i !== index))}
+ >
+ <Trash2 />
+ </IconButton>
+ )}
</div>
);
})}
@@ -154,7 +165,23 @@ export const SubjectAttributesField = ({
)}
</div>
<FieldError>{error}</FieldError>
- {notices?.map((notice) => <FieldError key={notice}>{notice}</FieldError>)}
+ {revealPolicyErrors && Boolean(policyNotices?.length) && (
+ <div className="mb-2 space-y-2">
+ {policyNotices?.map((notice) => (
+ <FieldError key={notice.message}>
+ <span className="block">
+ {notice.message}
+ {notice.label ? ` ${notice.label}:` : null}
+ </span>
+ {notice.items?.map((item) => (
+ <span key={item} className="block pl-3">
+ {item}
+ </span>
+ ))}
+ </FieldError>
+ ))}
+ </div>
+ )}
</Field>
);
}}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/ValidityField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/ValidityField.tsx
new file mode 100644
index 0000000000..080f43724f
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/ValidityField.tsx
@@ -0,0 +1,54 @@
+import { ReactNode } from "react";
+import { Control, Controller } from "react-hook-form";
+
+import { Field, FieldDescription, FieldLabel, Input } from "@app/components/v3";
+
+import { PolicyRowMessage } from "./PolicyRowMessage";
+
+type Props = {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ control: Control<any>;
+ label: string;
+ description?: ReactNode;
+ className?: string;
+ /** The policy's ceiling on validity, shown until something has to be corrected. */
+ hint?: string[];
+ /** How the entered duration breaks the policy. */
+ policyError?: string;
+ /** Policy findings stay hidden until the requester tries to leave the step. */
+ revealPolicyError?: boolean;
+};
+
+/**
+ * The validity field and the policy's ceiling on it. The schema's own error takes precedence, so a
+ * missing value reads as missing rather than as a policy violation.
+ */
+export const ValidityField = ({
+ control,
+ label,
+ description,
+ className,
+ hint,
+ policyError,
+ revealPolicyError
+}: Props) => (
+ <Controller
+ control={control}
+ name="ttl"
+ render={({ field, fieldState: { error } }) => {
+ const shownError = error?.message ?? (revealPolicyError ? policyError : undefined);
+
+ return (
+ <Field className={className}>
+ <FieldLabel>
+ {label} <span className="text-danger">*</span>
+ </FieldLabel>
+ <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(shownError)} />
+ {description && <FieldDescription>{description}</FieldDescription>}
+ {shownError && <PolicyRowMessage isError lines={[shownError]} />}
+ {!shownError && hint && <PolicyRowMessage lines={hint} />}
+ </Field>
+ );
+ }}
+ />
+);
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts
index 371ccdf8a7..0aeb876031 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts
@@ -11,7 +11,7 @@ import {
import { SUBJECT_ATTRIBUTE_LABELS, SubjectAltName, SubjectAttribute } from "./certificateUtils";
-export type SanRule = NonNullable<TCertificatePolicyRule["sans"]>[number];
+type SanRule = NonNullable<TCertificatePolicyRule["sans"]>[number];
type ValueRule = {
allowed?: string[];
@@ -27,13 +27,14 @@ const formatPatterns = (patterns: string[]): string => {
return remaining > 0 ? `${shown.join(", ")} (+${remaining} more)` : shown.join(", ");
};
-// Messages end on the pattern list rather than a period, because a trailing period reads as part of
-// a domain name ("dawg.com." is a valid FQDN).
-const asSentence = (clauses: string[]): string | undefined => {
- if (clauses.length === 0) return undefined;
- const joined = clauses.join("; ");
- return `${joined.charAt(0).toUpperCase()}${joined.slice(1)}`;
-};
+/**
+ * Hints carry the policy editor's own words (Require / Allow / Deny) so a requester can line the
+ * constraint up against the rule that produced it. Each constraint gets its own line, and a line
+ * ends on the pattern list rather than a period, because a trailing period reads as part of a
+ * domain name ("dawg.com." is a valid FQDN).
+ */
+const labelledLine = (label: "Required" | "Allowed" | "Denied", patterns: string[]): string =>
+ `${label}: ${formatPatterns(patterns)}`;
const patternClause = (verb: string, connector: string, patterns: string[]): string =>
patterns.length === 1
@@ -80,11 +81,18 @@ const parseSequence = (value: string): string[] =>
const formatSequence = (sequence: string[]): string =>
sequence.map((component) => `DC=${component}`).join(",");
-const formatSequences = (sequences: string[][]): string =>
- formatPatterns(sequences.map(formatSequence));
+/**
+ * The same values as `formatPatterns`, but one per entry. A domain component sequence contains
+ * commas of its own, so comma-joining a list of them reads as one long undifferentiated run.
+ */
+const listPatterns = (patterns: string[]): string[] => {
+ const shown = patterns.slice(0, MAX_LISTED_PATTERNS);
+ const remaining = patterns.length - shown.length;
+ return remaining > 0 ? [...shown, `+${remaining} more`] : shown;
+};
-const sequenceClause = (verb: string, connector: string, sequences: string[][]): string =>
- patternClause(verb, connector, sequences.map(formatSequence));
+const listSequences = (sequences: string[][]): string[] =>
+ listPatterns(sequences.map(formatSequence));
const matchesSequence = (request: string[], policy: string[]): boolean =>
request.length === policy.length &&
@@ -120,7 +128,7 @@ const mergeRules = <T extends ValueRule>(existing: T | undefined, incoming: T):
}
: incoming;
-export type CertificatePolicyRules = {
+type CertificatePolicyRules = {
subject: Partial<Record<CertSubjectAttributeType, TSubjectRule>>;
sans: Partial<Record<CertSubjectAlternativeNameType, SanRule>>;
/** An absent subject/SAN policy means no constraint at all, which is different from an empty one. */
@@ -128,7 +136,7 @@ export type CertificatePolicyRules = {
hasSanPolicy: boolean;
};
-export const EMPTY_POLICY_RULES: CertificatePolicyRules = {
+const EMPTY_POLICY_RULES: CertificatePolicyRules = {
subject: {},
sans: {},
hasSubjectPolicy: false,
@@ -158,54 +166,107 @@ export const buildPolicyRules = (policy?: TCertificatePolicy | null): Certificat
};
};
+const getSubjectAttributeHint = (rule?: TSubjectRule): string[] | undefined => {
+ if (!rule) return undefined;
+
+ const lines: string[] = [];
+ // `allowed` cannot widen a rule that already carries `required`, so only one of the two is real.
+ if (rule.required?.length) lines.push(labelledLine("Required", rule.required));
+ else if (rule.allowed?.length) lines.push(labelledLine("Allowed", rule.allowed));
+ if (rule.denied?.length) lines.push(labelledLine("Denied", rule.denied));
+ return lines.length > 0 ? lines : undefined;
+};
+
+const formatComponentCounts = (lengths: number[]): string => {
+ const unique = Array.from(new Set(lengths)).sort((a, b) => a - b);
+ return `${unique.join(" or ")} component${unique.length === 1 && unique[0] === 1 ? "" : "s"}`;
+};
+
+/** The sequence a domain component rule accepts, preferring `required` the way the backend does. */
+const acceptedSequences = (rule: TSubjectRule): string[][] | undefined => {
+ const patterns = rule.required?.length ? rule.required : rule.allowed;
+ return patterns?.length ? patterns.map(parseSequence) : undefined;
+};
+
/**
- * The values a rule accepts. When a rule carries `required` patterns the backend demands a match
- * against those specifically, so `allowed` no longer widens the set for subject attributes.
+ * Domain components are an ordered sequence, so each row is constrained by its own position rather
+ * than by the sequence as a whole.
*/
-const acceptedSubjectPatterns = (rule: TSubjectRule): string[] | undefined =>
- rule.required?.length ? rule.required : rule.allowed;
+const getDomainComponentHint = (
+ rule: TSubjectRule | undefined,
+ position: number
+): string[] | undefined => {
+ const sequences = rule && acceptedSequences(rule);
+ if (!sequences) return undefined;
-export const getSubjectAttributeHint = (
- type: CertSubjectAttributeType,
- rule?: TSubjectRule
-): string | undefined => {
- if (!rule) return undefined;
+ const options = Array.from(
+ new Set(sequences.filter((sequence) => position < sequence.length).map((s) => s[position]))
+ );
- if (type === CertSubjectAttributeType.DOMAIN_COMPONENT) {
- const sequences = (rule.required?.length ? rule.required : rule.allowed)?.map(parseSequence);
- const clauses: string[] = [];
- if (sequences?.length) {
- clauses.push(sequenceClause("the ordered sequence must match", "one of", sequences));
- }
- if (rule.denied?.length) {
- clauses.push(sequenceClause("cannot contain", "any of", rule.denied.map(parseSequence)));
- }
- return asSentence(clauses);
+ if (options.length === 0) {
+ return [
+ `The sequence takes ${formatComponentCounts(sequences.map((s) => s.length))}, so this row is past its end`
+ ];
}
- const clauses: string[] = [];
- const accepted = acceptedSubjectPatterns(rule);
- if (accepted?.length) clauses.push(patternClause("must match", "one of", accepted));
- if (rule.denied?.length) clauses.push(patternClause("cannot match", "any of", rule.denied));
- return asSentence(clauses);
+ // A bare "*" accepts anything at this position, so there is nothing to tell the requester.
+ if (options.includes("*")) return undefined;
+
+ return [labelledLine(rule?.required?.length ? "Required" : "Allowed", options)];
+};
+
+// Mirrors parseTTL in backend/src/services/certificate-policy/certificate-policy-service.ts.
+const parseTtlToMs = (ttl: string): number | undefined => {
+ const match = /^(\d+)([dmyh])$/.exec(ttl.trim());
+ if (!match) return undefined;
+
+ const value = Number(match[1]);
+ const hour = 60 * 60 * 1000;
+ const day = 24 * hour;
+ switch (match[2]) {
+ case "h":
+ return value * hour;
+ case "d":
+ return value * day;
+ case "m":
+ return value * 30 * day;
+ case "y":
+ return value * 365 * day;
+ default:
+ return undefined;
+ }
};
-export const getSanHint = (rule?: SanRule): string | undefined => {
+export const getValidityHint = (maxTtl?: string): string[] | undefined =>
+ maxTtl ? [`Maximum: ${maxTtl}`] : undefined;
+
+export const validateTtlAgainstPolicy = (ttl: string, maxTtl?: string): string | undefined => {
+ const trimmed = ttl?.trim() ?? "";
+ // An empty value is the schema's business, not the policy's.
+ if (!trimmed) return undefined;
+
+ // The backend throws on an unparseable TTL, so catching the format here keeps that off the wire.
+ const requested = parseTtlToMs(trimmed);
+ if (requested === undefined) return "Enter a duration such as 30d, 12h, 6m, or 1y";
+
+ const max = maxTtl ? parseTtlToMs(maxTtl) : undefined;
+ if (max === undefined || requested <= max) return undefined;
+ return `Exceeds the maximum validity of ${maxTtl} allowed by this policy`;
+};
+
+const getSanHint = (rule?: SanRule): string[] | undefined => {
if (!rule) return undefined;
- const clauses: string[] = [];
- if (rule.allowed?.length) {
- clauses.push(
- patternClause("must match", "one of", [...(rule.required ?? []), ...rule.allowed])
- );
- } else if (rule.required?.length) {
- clauses.push(patternClause("this policy requires one matching", "any of", rule.required));
- }
- if (rule.denied?.length) clauses.push(patternClause("cannot match", "any of", rule.denied));
- return asSentence(clauses);
+ // Unlike a subject attribute, a required SAN pattern does not narrow what any one row may hold:
+ // it demands that some SAN of this type match it, and `allowed` still widens the set.
+ const lines: string[] = [];
+ if (rule.required?.length) lines.push(labelledLine("Required", rule.required));
+ if (rule.allowed?.length) lines.push(labelledLine("Allowed", rule.allowed));
+ if (rule.denied?.length) lines.push(labelledLine("Denied", rule.denied));
+ return lines.length > 0 ? lines : undefined;
};
-export const validateSubjectAttributeValue = (
+const validateSubjectAttributeValue = (
type: CertSubjectAttributeType,
value: string,
rule: TSubjectRule | undefined,
@@ -232,7 +293,7 @@ export const validateSubjectAttributeValue = (
return undefined;
};
-export const validateSanValue = (
+const validateSanValue = (
type: CertSubjectAlternativeNameType,
value: string,
rule: SanRule | undefined,
@@ -258,17 +319,55 @@ export const validateSanValue = (
const DOMAIN_COMPONENT_ORDER_NOTE =
"Rows are order-sensitive, so they must follow the policy's order.";
-const reversalHint = (request: string[], policies: string[][]): string => {
- const reversed = [...request].reverse();
- if (request.length < 2 || !matchesAnySequence(reversed, policies)) return "";
- return " The same components in the opposite order would match, so check the row order.";
+const DOMAIN_COMPONENT_REVERSAL_NOTE =
+ "The same components in the opposite order would match, so check the row order.";
+
+const isReversalOf = (request: string[], candidates: string[][]): boolean =>
+ request.length > 1 && matchesAnySequence([...request].reverse(), candidates);
+
+/**
+ * The sequences a rule accepts that are as long as the request. Only these can say anything about
+ * an individual row, since a position means nothing across sequences of a different length.
+ */
+const comparableSequences = (components: string[], rule?: TSubjectRule): string[][] => {
+ const sequences = rule && acceptedSequences(rule);
+ return (sequences ?? []).filter((sequence) => sequence.length === components.length);
+};
+
+/**
+ * Per-row domain component errors, so a wrong component is marked where it was typed rather than
+ * only in a summary underneath. Empty rows are left to the schema's own required-value error.
+ */
+const validateDomainComponentRows = (
+ components: string[],
+ rule?: TSubjectRule
+): (string | undefined)[] => {
+ const candidates = comparableSequences(components, rule);
+ if (candidates.length === 0) return [];
+
+ const label = SUBJECT_ATTRIBUTE_LABELS[CertSubjectAttributeType.DOMAIN_COMPONENT];
+
+ return components.map((component, position) => {
+ if (!component) return undefined;
+
+ const options = Array.from(new Set(candidates.map((sequence) => sequence[position])));
+ const isAccepted = options.some((option) =>
+ matchesNormalizedPattern(component.toLowerCase(), option.toLowerCase())
+ );
+
+ return isAccepted ? undefined : `${label} ${patternClause("must match", "one of", options)}`;
+ });
};
-/** Sequence-level domain component errors. An absent sequence is reported as a requirement instead. */
-export const validateDomainComponents = (components: string[], rule?: TSubjectRule): string[] => {
+/** Domain component faults no single row can own: the wrong count, a denied run, a reversed order. */
+const validateDomainComponents = (
+ components: string[],
+ rule: TSubjectRule | undefined,
+ isReportedPerRow: boolean
+): PolicyNotice[] => {
if (!rule || components.length === 0) return [];
- const errors: string[] = [];
+ const notices: PolicyNotice[] = [];
const allowed = (rule.allowed ?? []).map(parseSequence);
const required = (rule.required ?? []).map(parseSequence);
const denied = (rule.denied ?? []).map(parseSequence);
@@ -276,60 +375,146 @@ export const validateDomainComponents = (components: string[], rule?: TSubjectRu
const isDenied = containsAnySequence(components, denied);
if (isDenied) {
- errors.push(
- `Domain components "${formatted}" are denied by this policy. Denied: ${formatSequences(denied)}`
- );
+ notices.push({
+ message: `Domain components "${formatted}" are denied by this policy.`,
+ label: "Denied",
+ items: listSequences(denied)
+ });
}
- const satisfiesRequired = required.length > 0 && matchesAnySequence(components, required);
- if (required.length > 0 && !satisfiesRequired) {
- errors.push(
- `Domain components "${formatted}" do not match a required sequence. ${DOMAIN_COMPONENT_ORDER_NOTE}${reversalHint(components, required)} Required: ${formatSequences(required)}`
- );
- }
+ const describeMismatch = (candidates: string[][], label: string) => {
+ if (candidates.length === 0 || matchesAnySequence(components, candidates)) return;
+
+ const items = listSequences(candidates);
+ const lengths = candidates.map((sequence) => sequence.length);
+ if (!lengths.includes(components.length)) {
+ // A count mismatch is the most common way a sequence fails, and naming it beats "do not match".
+ notices.push({
+ message: `Domain components must form a sequence of ${formatComponentCounts(lengths)}, but this request has ${components.length}.`,
+ label,
+ items
+ });
+ } else if (!isReportedPerRow) {
+ // Otherwise the rows carry the fault themselves, on the exact component that is wrong.
+ notices.push({
+ message: `Domain components "${formatted}" do not match. ${DOMAIN_COMPONENT_ORDER_NOTE}`,
+ label,
+ items
+ });
+ }
- if (!isDenied && !satisfiesRequired && allowed.length > 0) {
- if (!matchesAnySequence(components, allowed)) {
- errors.push(
- `Domain components "${formatted}" are not allowed by this policy. ${DOMAIN_COMPONENT_ORDER_NOTE}${reversalHint(components, allowed)} Allowed: ${formatSequences(allowed)}`
- );
+ if (isReversalOf(components, candidates)) {
+ notices.push({ message: DOMAIN_COMPONENT_REVERSAL_NOTE });
}
- }
+ };
- return errors;
-};
+ const satisfiesRequired = required.length > 0 && matchesAnySequence(components, required);
+ describeMismatch(required, "Required");
+ if (!isDenied && !satisfiesRequired) describeMismatch(allowed, "Allowed");
-export type PolicyRequirement = {
- id: string;
- message: string;
- /** Rows to append when the request is missing this attribute or SAN entirely. */
- addRows?:
- | { kind: "subject"; type: CertSubjectAttributeType; values: string[] }
- | { kind: "san"; type: CertSubjectAlternativeNameType; values: string[] };
+ return notices;
};
/** A single literal pattern can be filled in for the user; wildcards cannot. */
const literalSuggestion = (patterns: string[]): string =>
patterns.length === 1 && !isWildcardPattern(patterns[0]) ? patterns[0] : "";
-export type SubjectPolicyGuidance = {
- subjectRowHints: (string | undefined)[];
- subjectRowErrors: (string | undefined)[];
- subjectNotices: string[];
- sanRowHints: (string | undefined)[];
- sanRowErrors: (string | undefined)[];
- requirements: PolicyRequirement[];
- hasBlockingIssues: boolean;
+const requiredSequenceRows = (rule: TSubjectRule): string[] => {
+ const sequences = (rule.required ?? []).map(parseSequence);
+ const onlySequence = sequences.length === 1 ? sequences[0] : undefined;
+ const isFillable = Boolean(onlySequence?.every((part) => !isWildcardPattern(part)));
+ return isFillable && onlySequence ? onlySequence : [""];
};
-export const EMPTY_SUBJECT_POLICY_GUIDANCE: SubjectPolicyGuidance = {
- subjectRowHints: [],
- subjectRowErrors: [],
- subjectNotices: [],
- sanRowHints: [],
- sanRowErrors: [],
- requirements: [],
- hasBlockingIssues: false
+/**
+ * Seeds the rows the policy demands so the requirement is visible as a field the moment a profile
+ * is chosen, rather than as a banner the requester has to act on. Literal patterns are filled in;
+ * wildcard ones leave a blank row for the requester.
+ */
+export const withRequiredRows = (
+ rules: CertificatePolicyRules,
+ subjectAttributes: SubjectAttribute[],
+ subjectAltNames: SubjectAltName[]
+): { subjectAttributes: SubjectAttribute[]; subjectAltNames: SubjectAltName[] } => {
+ const subject = subjectAttributes.map((attr) => ({ ...attr }));
+
+ Object.entries(rules.subject).forEach(([rawType, rule]) => {
+ const type = rawType as CertSubjectAttributeType;
+ if (!rule?.required?.length) return;
+
+ if (type === CertSubjectAttributeType.DOMAIN_COMPONENT) {
+ if (subject.some((attr) => attr.type === type)) return;
+ requiredSequenceRows(rule).forEach((value) => subject.push({ type, value }));
+ return;
+ }
+
+ const suggestion = literalSuggestion(rule.required);
+ const existing = subject.find((attr) => attr.type === type);
+ if (!existing) {
+ subject.push({ type, value: suggestion });
+ } else if (!existing.value && suggestion) {
+ existing.value = suggestion;
+ }
+ });
+
+ const sans = subjectAltNames.map((san) => ({ ...san }));
+
+ Object.entries(rules.sans).forEach(([rawType, rule]) => {
+ const type = rawType as CertSubjectAlternativeNameType;
+ if (!rule?.required?.length) return;
+
+ const isUri = type === CertSubjectAlternativeNameType.URI;
+ let unclaimedBlankRows = sans.filter((san) => san.type === type && !san.value.trim()).length;
+
+ rule.required.forEach((pattern) => {
+ const isSatisfied = sans.some(
+ (san) =>
+ san.type === type && san.value.trim() && matchesAny(san.value.trim(), [pattern], isUri)
+ );
+ if (isSatisfied) return;
+
+ if (!isWildcardPattern(pattern)) {
+ sans.push({ type, value: pattern });
+ } else if (unclaimedBlankRows > 0) {
+ unclaimedBlankRows -= 1;
+ } else {
+ sans.push({ type, value: "" });
+ }
+ });
+ });
+
+ return { subjectAttributes: subject, subjectAltNames: sans };
+};
+
+/** What the policy has to say about one subject attribute or SAN row. */
+export type PolicyRowGuidance = {
+ /** The constraint in the policy editor's own words, one line per clause. */
+ hint?: string[];
+ /** How this row's current value breaks the policy. */
+ error?: string;
+ /** Seeded to satisfy a `required` rule: neither removable nor retypeable. */
+ isLocked: boolean;
+};
+
+/** A finding no single row can own, such as an ordered sequence or a set-level requirement. */
+export type PolicyNotice = {
+ message: string;
+ /** Names what `items` are, in the policy editor's words. */
+ label?: string;
+ /** Rendered one per line, because an entry may contain commas of its own. */
+ items?: string[];
+};
+
+export type PolicySectionGuidance = {
+ rows: PolicyRowGuidance[];
+ notices: PolicyNotice[];
+ /** Whether this section holds something the request cannot be submitted with. */
+ isBlocking: boolean;
+};
+
+export type SubjectPolicyGuidance = {
+ subject: PolicySectionGuidance;
+ sans: PolicySectionGuidance;
};
export const evaluateSubjectStep = ({
@@ -345,146 +530,155 @@ export const evaluateSubjectStep = ({
isSubjectSectionShown: boolean;
isSanSectionShown: boolean;
}): SubjectPolicyGuidance => {
- const requirements: PolicyRequirement[] = [];
-
- const subjectRowHints = subjectAttributes.map((attr, index) => {
- const isFirstOfType =
- subjectAttributes.findIndex((other) => other.type === attr.type) === index;
- // A domain component rule spans every DC row, so only the first row carries the hint.
- if (attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT && !isFirstOfType) return undefined;
- return getSubjectAttributeHint(attr.type, rules.subject[attr.type]);
- });
+ const domainComponentRule = rules.subject[CertSubjectAttributeType.DOMAIN_COMPONENT];
- const subjectRowErrors = subjectAttributes.map((attr) =>
- validateSubjectAttributeValue(
- attr.type,
- attr.value,
- rules.subject[attr.type],
- rules.hasSubjectPolicy
- )
+ // Domain components are one ordered sequence spread across rows, so they are judged in row order
+ // rather than individually like every other attribute type.
+ const domainComponentValues = subjectAttributes
+ .filter((attr) => attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT)
+ .map((attr) => attr.value.trim());
+ const domainComponentErrors = validateDomainComponentRows(
+ domainComponentValues,
+ domainComponentRule
);
- const domainComponents = subjectAttributes
- .filter((attr) => attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT)
- .map((attr) => attr.value.trim())
- .filter(Boolean);
+ let domainComponentPosition = 0;
+ let lockableDomainComponents = domainComponentRule?.required?.length
+ ? requiredSequenceRows(domainComponentRule).length
+ : 0;
- const domainComponentRule = rules.subject[CertSubjectAttributeType.DOMAIN_COMPONENT];
- const subjectNotices = validateDomainComponents(domainComponents, domainComponentRule);
+ const subjectRows: PolicyRowGuidance[] = subjectAttributes.map((attr) => {
+ const rule = rules.subject[attr.type];
+
+ if (attr.type !== CertSubjectAttributeType.DOMAIN_COMPONENT) {
+ return {
+ hint: getSubjectAttributeHint(rule),
+ error: validateSubjectAttributeValue(attr.type, attr.value, rule, rules.hasSubjectPolicy),
+ isLocked: Boolean(rule?.required?.length)
+ };
+ }
+ const position = domainComponentPosition;
+ domainComponentPosition += 1;
+
+ // A required sequence has a fixed length, so removing any row within it breaks the request.
+ // Rows beyond that length are the requester's own and stay removable.
+ const isLocked = lockableDomainComponents > 0;
+ if (isLocked) lockableDomainComponents -= 1;
+
+ return {
+ hint: getDomainComponentHint(domainComponentRule, position),
+ error: domainComponentErrors[position],
+ isLocked
+ };
+ });
+
+ const subjectNotices = validateDomainComponents(
+ domainComponentValues.filter(Boolean),
+ domainComponentRule,
+ domainComponentErrors.some(Boolean)
+ );
+
+ // A required attribute normally has a seeded row, and an empty or wrong value on that row reports
+ // itself. This only speaks up when the row is missing entirely.
if (isSubjectSectionShown) {
Object.entries(rules.subject).forEach(([rawType, rule]) => {
const type = rawType as CertSubjectAttributeType;
if (!rule?.required?.length) return;
+ if (subjectAttributes.some((attr) => attr.type === type)) return;
const label = SUBJECT_ATTRIBUTE_LABELS[type];
if (type === CertSubjectAttributeType.DOMAIN_COMPONENT) {
const sequences = rule.required.map(parseSequence);
- // A populated sequence that does not match already produces its own notice.
- if (domainComponents.length > 0) return;
-
- const onlySequence = sequences.length === 1 ? sequences[0] : undefined;
- const isFillable = Boolean(onlySequence?.every((part) => !isWildcardPattern(part)));
- requirements.push({
- id: `subject-${type}`,
- message:
- sequences.length === 1
- ? `${label} rows must form the sequence ${formatSequence(sequences[0])}`
- : `${label} rows must form one of: ${formatSequences(sequences)}`,
- ...(subjectAttributes.every((attr) => attr.type !== type) && {
- addRows: {
- kind: "subject" as const,
- type,
- values: isFillable && onlySequence ? onlySequence : [""]
- }
- })
+ subjectNotices.push({
+ message: `${label} rows are required.`,
+ label: "Required",
+ items: listSequences(sequences)
});
return;
}
- const current = subjectAttributes.find((attr) => attr.type === type);
- const value = current?.value.trim() ?? "";
- if (value && matchesAny(value, rule.required)) return;
-
- requirements.push({
- id: `subject-${type}`,
- message: `${label} is required and ${patternClause("must match", "one of", rule.required)}`,
- ...(!current && {
- addRows: {
- kind: "subject" as const,
- type,
- values: [literalSuggestion(rule.required)]
- }
- })
+ subjectNotices.push({
+ message: `${label} is required and ${patternClause("must match", "one of", rule.required)}`
});
});
}
- const sanRowHints = subjectAltNames.map((san) => getSanHint(rules.sans[san.type]));
- const sanRowErrors = subjectAltNames.map((san) =>
- validateSanValue(san.type, san.value, rules.sans[san.type], rules.hasSanPolicy)
- );
+ // A SAN row is fixed when it is the one holding a required pattern up: either it satisfies the
+ // pattern or it is the blank row standing in for it. Claiming rows the same way withRequiredRows
+ // seeds them keeps the lock on the row that matters, wherever it sits in the list.
+ const lockedSanRows = new Set<number>();
+ Object.entries(rules.sans).forEach(([rawType, rule]) => {
+ const type = rawType as CertSubjectAlternativeNameType;
+ if (!rule?.required?.length) return;
+
+ const isUri = type === CertSubjectAlternativeNameType.URI;
+ const claim = (predicate: (san: SubjectAltName) => boolean) => {
+ const index = subjectAltNames.findIndex(
+ (san, position) => !lockedSanRows.has(position) && san.type === type && predicate(san)
+ );
+ if (index >= 0) lockedSanRows.add(index);
+ return index >= 0;
+ };
+
+ rule.required.forEach((pattern) => {
+ const isSatisfiedBy = (san: SubjectAltName) =>
+ Boolean(san.value.trim()) && matchesAny(san.value.trim(), [pattern], isUri);
+ if (!claim(isSatisfiedBy)) claim((san) => !san.value.trim());
+ });
+ });
+
+ const sanRows: PolicyRowGuidance[] = subjectAltNames.map((san, index) => {
+ const rule = rules.sans[san.type];
+ return {
+ hint: getSanHint(rule),
+ error: validateSanValue(san.type, san.value, rule, rules.hasSanPolicy),
+ isLocked: lockedSanRows.has(index)
+ };
+ });
+
+ // A required SAN pattern is set-level: the backend only asks that some SAN of that type match it,
+ // so it cannot be reported on any one row.
+ const sanNotices: PolicyNotice[] = [];
if (isSanSectionShown) {
Object.entries(rules.sans).forEach(([rawType, rule]) => {
const type = rawType as CertSubjectAlternativeNameType;
if (!rule?.required?.length) return;
const isUri = type === CertSubjectAlternativeNameType.URI;
- const presentValues = subjectAltNames
- .filter((san) => san.type === type)
- .map((san) => san.value.trim())
- .filter(Boolean);
-
- // A wildcard pattern cannot be filled in for the user, so each unmet one needs its own blank
- // row. Blank rows already on the form are claimed first, one per requirement.
- let unclaimedEmptyRows = subjectAltNames.filter(
- (san) => san.type === type && !san.value.trim()
- ).length;
+ const rows = subjectAltNames.filter((san) => san.type === type);
+ const presentValues = rows.map((san) => san.value.trim()).filter(Boolean);
+ // A blank row of the right type is a requirement the requester is still filling in, and the
+ // empty-value error on that row already blocks. Only speak up once no blank row is left.
+ let unclaimedBlankRows = rows.length - presentValues.length;
rule.required.forEach((pattern) => {
if (presentValues.some((value) => matchesAny(value, [pattern], isUri))) return;
-
- const requirement: PolicyRequirement = {
- id: `san-${type}-${pattern}`,
- message: `A ${formatSANType(type)} SAN matching ${pattern} is required`
- };
-
- if (!isWildcardPattern(pattern)) {
- requirement.addRows = { kind: "san", type, values: [pattern] };
- } else if (unclaimedEmptyRows > 0) {
- unclaimedEmptyRows -= 1;
- } else {
- requirement.addRows = { kind: "san", type, values: [""] };
+ if (unclaimedBlankRows > 0) {
+ unclaimedBlankRows -= 1;
+ return;
}
-
- requirements.push(requirement);
+ sanNotices.push({
+ message: `A ${formatSANType(type)} SAN matching ${pattern} is required`
+ });
});
});
}
- // Only issues on a rendered section can block, otherwise there is nowhere to go and fix them.
- const hasBlockingIssues =
- (isSubjectSectionShown && (subjectRowErrors.some(Boolean) || subjectNotices.length > 0)) ||
- (isSanSectionShown && sanRowErrors.some(Boolean)) ||
- requirements.length > 0;
+ // Only findings on a rendered section can block, otherwise there is nowhere to go and fix them.
+ const toSection = (
+ rows: PolicyRowGuidance[],
+ notices: PolicyNotice[],
+ isShown: boolean
+ ): PolicySectionGuidance => ({
+ rows,
+ notices,
+ isBlocking: isShown && (rows.some((row) => row.error) || notices.length > 0)
+ });
return {
- subjectRowHints,
- subjectRowErrors,
- subjectNotices,
- sanRowHints,
- sanRowErrors,
- requirements,
- hasBlockingIssues
+ subject: toSection(subjectRows, subjectNotices, isSubjectSectionShown),
+ sans: toSection(sanRows, sanNotices, isSanSectionShown)
};
};
-
-export const mergeRowErrors = (
- formErrors: (string | undefined)[] | undefined,
- policyErrors: (string | undefined)[]
-): (string | undefined)[] =>
- Array.from(
- { length: Math.max(formErrors?.length ?? 0, policyErrors.length) },
- (_, index) => formErrors?.[index] ?? policyErrors[index]
- );
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
index 59eff2c12b..6266d8e0ea 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
@@ -16,6 +16,9 @@ import {
mapPolicySignatureAlgorithmToApi
} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+import { buildPolicyRules, withRequiredRows } from "./certificatePolicyGuidance";
+import { SubjectAltName, SubjectAttribute } from "./certificateUtils";
+
const convertTemplateTtlToCertificateTtl = (templateTtl: string): string => {
const match = templateTtl.match(/^(\d+)([dmyh])$/);
if (!match) return templateTtl;
@@ -307,6 +310,7 @@ export const useCertificatePolicy = (
}
// Pre-populate SANs from profile defaults or reset when profile changes
+ let nextSans: SubjectAltName[] = watch("subjectAltNames") ?? [];
if (profileChanged) {
if (
defaults?.subjectAltNames &&
@@ -314,36 +318,38 @@ export const useCertificatePolicy = (
defaults.subjectAltNames.length > 0
) {
// Filter to only allowed SAN types
- const filteredSans = defaults.subjectAltNames.filter(
- (san: { type: CertSubjectAlternativeNameType; value: string }) =>
- newConstraints.allowedSanTypes.includes(san.type)
+ nextSans = defaults.subjectAltNames.filter((san: SubjectAltName) =>
+ newConstraints.allowedSanTypes.includes(san.type)
);
- setValue("subjectAltNames", filteredSans.length > 0 ? filteredSans : []);
} else {
- setValue("subjectAltNames", []);
+ nextSans = [];
}
}
const currentSubjectAttrs = watch("subjectAttributes");
+ let nextSubjectAttrs: SubjectAttribute[] = currentSubjectAttrs ?? [];
if (profileChanged || !currentSubjectAttrs || currentSubjectAttrs.length === 0) {
if (newConstraints.allowedSubjectAttributeTypes.length === 0) {
- setValue("subjectAttributes", []);
+ nextSubjectAttrs = [];
} else if (defaultSubjectAttrs.length > 0) {
// Filter to only allowed attribute types
const filteredDefaults = defaultSubjectAttrs.filter((attr) =>
newConstraints.allowedSubjectAttributeTypes.includes(attr.type)
);
- const subjectValue =
+ nextSubjectAttrs =
filteredDefaults.length > 0
? filteredDefaults
: [{ type: newConstraints.allowedSubjectAttributeTypes[0], value: "" }];
- setValue("subjectAttributes", subjectValue);
} else {
- const defaultType = newConstraints.allowedSubjectAttributeTypes[0];
- setValue("subjectAttributes", [{ type: defaultType, value: "" }]);
+ nextSubjectAttrs = [{ type: newConstraints.allowedSubjectAttributeTypes[0], value: "" }];
}
}
+ // Seed the rows the policy requires so they are visible as fields from the start.
+ const seeded = withRequiredRows(buildPolicyRules(templateData), nextSubjectAttrs, nextSans);
+ setValue("subjectAltNames", seeded.subjectAltNames);
+ setValue("subjectAttributes", seeded.subjectAttributes);
+
// Set isCA if template requires it
if (templateRequiresCA) {
setValue("basicConstraints.isCA", true);
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/usePolicyGuidance.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/usePolicyGuidance.ts
new file mode 100644
index 0000000000..c804897995
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/usePolicyGuidance.ts
@@ -0,0 +1,154 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { UseFormClearErrors, UseFormWatch } from "react-hook-form";
+
+import { TCertificatePolicy } from "@app/hooks/api/certificatePolicies";
+
+import {
+ buildPolicyRules,
+ evaluateSubjectStep,
+ getValidityHint,
+ PolicySectionGuidance,
+ validateTtlAgainstPolicy
+} from "./certificatePolicyGuidance";
+import { SubjectAltName, SubjectAttribute } from "./certificateUtils";
+
+/** The form fields this hook evaluates. Each wizard step declares the ones it owns. */
+export const POLICY_FIELDS = ["subjectAttributes", "subjectAltNames", "ttl"] as const;
+
+export type PolicyField = (typeof POLICY_FIELDS)[number];
+
+const SUBJECT_FIELDS: PolicyField[] = ["subjectAttributes", "subjectAltNames"];
+
+const EMPTY_SUBJECT_ATTRIBUTES: SubjectAttribute[] = [];
+const EMPTY_SUBJECT_ALT_NAMES: SubjectAltName[] = [];
+
+type UsePolicyGuidanceParams = {
+ policy?: TCertificatePolicy | null;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ watch: UseFormWatch<any>;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ clearErrors: UseFormClearErrors<any>;
+ isSubjectSectionShown: boolean;
+ isSanSectionShown: boolean;
+ /** False for request methods that take the subject from a CSR instead of these fields. */
+ isSubjectEvaluated?: boolean;
+ /** False when an external CA's template owns validity, so the TTL field is not shown. */
+ isValidityEvaluated?: boolean;
+ /** Identity of the current policy source; a change here starts every violation hidden again. */
+ resetKey?: string;
+};
+
+export type PolicyGuidance = {
+ subject: PolicySectionGuidance;
+ sans: PolicySectionGuidance;
+ ttlHint?: string[];
+ ttlError?: string;
+ /** True once the requester has tried to leave the step that owns this field. */
+ isRevealed: (field: PolicyField) => boolean;
+ /** Called when leaving a step, so its own violations surface where they can be fixed. */
+ reveal: (fields: readonly string[]) => void;
+ /** Which of `fields` must be fixed before the request can go any further. */
+ findBlockedFields: (fields: readonly string[]) => PolicyField[];
+};
+
+/**
+ * Evaluates the profile's policy against the form on every keystroke, and owns when those findings
+ * are allowed to surface: a field stays quiet until the requester tries to leave the step that owns
+ * it, and goes quiet again the moment they edit it. Violations therefore never interrupt typing,
+ * and the request can still never reach issuance carrying one.
+ */
+export const usePolicyGuidance = ({
+ policy,
+ watch,
+ clearErrors,
+ isSubjectSectionShown,
+ isSanSectionShown,
+ isSubjectEvaluated = true,
+ isValidityEvaluated = true,
+ resetKey
+}: UsePolicyGuidanceParams): PolicyGuidance => {
+ const subjectAttributes: SubjectAttribute[] =
+ watch("subjectAttributes") ?? EMPTY_SUBJECT_ATTRIBUTES;
+ const subjectAltNames: SubjectAltName[] = watch("subjectAltNames") ?? EMPTY_SUBJECT_ALT_NAMES;
+ const ttl: string = watch("ttl") ?? "";
+
+ const rules = useMemo(
+ () => buildPolicyRules(isSubjectEvaluated ? policy : undefined),
+ [policy, isSubjectEvaluated]
+ );
+
+ const { subject, sans } = useMemo(
+ () =>
+ evaluateSubjectStep({
+ rules,
+ subjectAttributes,
+ subjectAltNames,
+ isSubjectSectionShown,
+ isSanSectionShown
+ }),
+ [rules, subjectAttributes, subjectAltNames, isSubjectSectionShown, isSanSectionShown]
+ );
+
+ const maxTtl = policy?.validity?.max;
+ const ttlHint = useMemo(
+ () => (isValidityEvaluated ? getValidityHint(maxTtl) : undefined),
+ [maxTtl, isValidityEvaluated]
+ );
+ const ttlError = useMemo(
+ () => (isValidityEvaluated ? validateTtlAgainstPolicy(ttl, maxTtl) : undefined),
+ [ttl, maxTtl, isValidityEvaluated]
+ );
+
+ const [revealedFields, setRevealedFields] = useState<ReadonlySet<PolicyField>>(new Set());
+
+ const hide = useCallback((fields: readonly PolicyField[]) => {
+ setRevealedFields((previous) => {
+ if (!fields.some((field) => previous.has(field))) return previous;
+ const next = new Set(previous);
+ fields.forEach((field) => next.delete(field));
+ return next;
+ });
+ }, []);
+
+ const reveal = useCallback((fields: readonly string[]) => {
+ const revealable = POLICY_FIELDS.filter((field) => fields.includes(field));
+ if (revealable.length === 0) return;
+ setRevealedFields((previous) => new Set([...previous, ...revealable]));
+ }, []);
+
+ // A different policy makes every finding from the previous one meaningless.
+ useEffect(() => setRevealedFields(new Set()), [resetKey]);
+
+ // Editing a field puts its findings away until the next attempt to leave the step. React Hook
+ // Form's own errors are cleared alongside them, so both sources surface on the same terms.
+ useEffect(() => {
+ hide(SUBJECT_FIELDS);
+ clearErrors(SUBJECT_FIELDS);
+ }, [subjectAttributes, subjectAltNames, clearErrors, hide]);
+
+ useEffect(() => {
+ hide(["ttl"]);
+ clearErrors("ttl");
+ }, [ttl, clearErrors, hide]);
+
+ // Read through a ref so the wizard's validateStep callback does not have to be rebuilt per render.
+ const blockedFields = useRef<ReadonlySet<PolicyField>>(new Set());
+ blockedFields.current = new Set<PolicyField>([
+ ...(subject.isBlocking ? (["subjectAttributes"] as const) : []),
+ ...(sans.isBlocking ? (["subjectAltNames"] as const) : []),
+ ...(ttlError ? (["ttl"] as const) : [])
+ ]);
+
+ const findBlockedFields = useCallback(
+ (fields: readonly string[]) =>
+ POLICY_FIELDS.filter((field) => fields.includes(field) && blockedFields.current.has(field)),
+ []
+ );
+
+ const isRevealed = useCallback(
+ (field: PolicyField) => revealedFields.has(field),
+ [revealedFields]
+ );
+
+ return { subject, sans, ttlHint, ttlError, isRevealed, reveal, findBlockedFields };
+};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/useSubjectPolicyGuidance.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/useSubjectPolicyGuidance.ts
deleted file mode 100644
index f1a7f0d599..0000000000
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/useSubjectPolicyGuidance.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { useCallback, useMemo, useRef } from "react";
-import { UseFormSetValue, UseFormWatch } from "react-hook-form";
-
-import { TCertificatePolicy } from "@app/hooks/api/certificatePolicies";
-
-import {
- buildPolicyRules,
- evaluateSubjectStep,
- SubjectPolicyGuidance
-} from "./certificatePolicyGuidance";
-import { SubjectAltName, SubjectAttribute } from "./certificateUtils";
-
-const EMPTY_SUBJECT_ATTRIBUTES: SubjectAttribute[] = [];
-const EMPTY_SUBJECT_ALT_NAMES: SubjectAltName[] = [];
-
-type UseSubjectPolicyGuidanceParams = {
- policy?: TCertificatePolicy | null;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- watch: UseFormWatch<any>;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- setValue: UseFormSetValue<any>;
- isSubjectSectionShown: boolean;
- isSanSectionShown: boolean;
- isEnabled?: boolean;
-};
-
-/**
- * Evaluates the subject step against the profile's policy on every keystroke so the constraints and
- * their violations surface where they can be fixed, rather than as a rejection at issuance.
- */
-export const useSubjectPolicyGuidance = ({
- policy,
- watch,
- setValue,
- isSubjectSectionShown,
- isSanSectionShown,
- isEnabled = true
-}: UseSubjectPolicyGuidanceParams): SubjectPolicyGuidance & { addMissingFields: () => void } => {
- const subjectAttributes: SubjectAttribute[] =
- watch("subjectAttributes") ?? EMPTY_SUBJECT_ATTRIBUTES;
- const subjectAltNames: SubjectAltName[] = watch("subjectAltNames") ?? EMPTY_SUBJECT_ALT_NAMES;
-
- const rules = useMemo(
- () => buildPolicyRules(isEnabled ? policy : undefined),
- [policy, isEnabled]
- );
-
- const guidance = useMemo(
- () =>
- evaluateSubjectStep({
- rules,
- subjectAttributes,
- subjectAltNames,
- isSubjectSectionShown,
- isSanSectionShown
- }),
- [rules, subjectAttributes, subjectAltNames, isSubjectSectionShown, isSanSectionShown]
- );
-
- const requirementsRef = useRef(guidance.requirements);
- requirementsRef.current = guidance.requirements;
-
- const addMissingFields = useCallback(() => {
- const additions = requirementsRef.current
- .map(({ addRows }) => addRows)
- .filter((addRows): addRows is NonNullable<typeof addRows> => Boolean(addRows));
-
- const subjectRows = additions.flatMap((addition) =>
- addition.kind === "subject"
- ? addition.values.map((value) => ({ type: addition.type, value }))
- : []
- );
- const sanRows = additions.flatMap((addition) =>
- addition.kind === "san"
- ? addition.values.map((value) => ({ type: addition.type, value }))
- : []
- );
-
- if (subjectRows.length > 0) {
- setValue("subjectAttributes", [...subjectAttributes, ...subjectRows], { shouldDirty: true });
- }
- if (sanRows.length > 0) {
- setValue("subjectAltNames", [...subjectAltNames, ...sanRows], { shouldDirty: true });
- }
- }, [setValue, subjectAttributes, subjectAltNames]);
-
- return { ...guidance, addMissingFields };
-};