Skip to content

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

fix(cert-manager): validate certificate profile name inline and keep wizard on the failing step (#8664)

Andrew Huangbd5e4debe566
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.test.ts b/backend/src/services/certificate-profile/certificate-profile-service.test.ts
index 3961c17721..2f425b5c27 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.test.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.test.ts
@@ -6,7 +6,7 @@ import { ForbiddenError } from "@casl/ability";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { ConflictError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ActorType, AuthMethod } from "../auth/auth-type";
import type { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
@@ -481,7 +481,7 @@ describe("CertificateProfileService", () => {
).rejects.toThrow(ForbiddenRequestError);
});
- it("should throw ForbiddenRequestError when profile slug already exists", async () => {
+ it("should throw ConflictError when profile slug already exists", async () => {
(mockCertificateProfileDAL.findBySlugAndProjectId as any).mockResolvedValue(sampleProfile);
await expect(
@@ -490,7 +490,7 @@ describe("CertificateProfileService", () => {
projectId: "project-123",
data: validProfileData
})
- ).rejects.toThrow(ForbiddenRequestError);
+ ).rejects.toThrow(ConflictError);
});
it("should create profile with EST enrollment type but no EST config (config attached to Application junction)", async () => {
@@ -911,7 +911,7 @@ describe("CertificateProfileService", () => {
projectId: "project-123",
data: duplicateSlugData
})
- ).rejects.toThrow(ForbiddenRequestError);
+ ).rejects.toThrow(ConflictError);
});
it("should validate auto-renewal configuration", async () => {
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.ts
index 7c56c1c92d..aaead1b621 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts
@@ -21,7 +21,7 @@ import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-uti
import { extractX509CertFromChain } from "@app/lib/certificates/extract-certificate";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, ConflictError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ActorAuthMethod, ActorType } from "../auth/auth-type";
import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
@@ -527,8 +527,8 @@ export const certificateProfileServiceFactory = ({
// Check for slug uniqueness within project
const existingSlugProfile = await certificateProfileDAL.findBySlugAndProjectId(data.slug, projectId);
if (existingSlugProfile) {
- throw new ForbiddenRequestError({
- message: "Certificate profile with this name already exists in project"
+ throw new ConflictError({
+ message: `A certificate profile named '${data.slug}' already exists. Choose a different name.`
});
}
@@ -816,8 +816,8 @@ export const certificateProfileServiceFactory = ({
existingProfile.projectId
);
if (conflictingProfile && conflictingProfile.id !== profileId) {
- throw new ForbiddenRequestError({
- message: "Certificate profile with this name already exists in project"
+ throw new ConflictError({
+ message: `A certificate profile named '${data.slug}' already exists. Choose a different name.`
});
}
}
diff --git a/frontend/src/hooks/api/certificateProfiles/mutations.tsx b/frontend/src/hooks/api/certificateProfiles/mutations.tsx
index 3e1ae8bdb6..a0c78eb772 100644
--- a/frontend/src/hooks/api/certificateProfiles/mutations.tsx
+++ b/frontend/src/hooks/api/certificateProfiles/mutations.tsx
@@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { pkiApplicationKeys } from "@app/hooks/api/pkiApplications/queries";
+import { ApiErrorTypes } from "@app/hooks/api/types";
import { certificateProfileKeys } from "./queries";
import {
@@ -15,6 +16,7 @@ export const useCreateCertificateProfile = () => {
const queryClient = useQueryClient();
return useMutation<TCertificateProfile, object, TCreateCertificateProfileDTO>({
+ meta: { handledErrorCodes: [ApiErrorTypes.ConflictError] },
mutationFn: async (data) => {
const { data: response } = await apiRequest.post<{
certificateProfile: TCertificateProfile;
@@ -34,6 +36,7 @@ export const useUpdateCertificateProfile = () => {
const queryClient = useQueryClient();
return useMutation<TCertificateProfile, object, TUpdateCertificateProfileDTO>({
+ meta: { handledErrorCodes: [ApiErrorTypes.ConflictError] },
mutationFn: async ({ profileId, ...data }) => {
const { data: response } = await apiRequest.patch<{
certificateProfile: TCertificateProfile;
diff --git a/frontend/src/hooks/api/types.ts b/frontend/src/hooks/api/types.ts
index 52b98cfde8..f82520cb65 100644
--- a/frontend/src/hooks/api/types.ts
+++ b/frontend/src/hooks/api/types.ts
@@ -40,6 +40,7 @@ export enum ApiErrorTypes {
ValidationError = "ValidationFailure",
PermissionBoundaryError = "PermissionBoundaryError",
BadRequestError = "BadRequest",
+ ConflictError = "Conflict",
UnauthorizedError = "UnauthorizedError",
ForbiddenError = "PermissionDenied",
CustomForbiddenError = "ForbiddenError",
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
index b5dc6c5dbd..9cd7c380ac 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
@@ -4,6 +4,7 @@ import { SingleValue } from "react-select";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQueryClient } from "@tanstack/react-query";
import { Link, useParams } from "@tanstack/react-router";
+import axios from "axios";
import { Check, ChevronRight, FileBadge, ShieldCheck } from "lucide-react";
import { z } from "zod";
@@ -15,6 +16,7 @@ import {
FieldContent,
FieldDescription,
FieldError,
+ FieldFeedback,
FieldLabel,
FilterableSelect,
Input,
@@ -67,6 +69,8 @@ import {
KEY_USAGES_OPTIONS,
SIGNATURE_ALGORITHMS_OPTIONS
} from "@app/hooks/api/certificates/constants";
+import { ApiErrorTypes } from "@app/hooks/api/types";
+import { normalizeSlugInput } from "@app/lib/schemas";
import { filterUsages } from "@app/pages/cert-manager/CertificatesPage/components/certificateUtils";
import {
CertPolicyState,
@@ -172,16 +176,6 @@ const STEPS = [
}
] as const;
-const slugSchema = z
- .string()
- .trim()
- .min(1, "Profile slug is required")
- .max(255, "Profile slug must be less than 255 characters")
- .regex(
- /^[a-zA-Z0-9-_]+$/,
- "Profile slug must contain only letters, numbers, hyphens, and underscores"
- );
-
const descriptionSchema = z
.string()
.trim()
@@ -189,7 +183,12 @@ const descriptionSchema = z
.optional();
const baseProfileSchema = z.object({
- slug: slugSchema,
+ slug: z
+ .string()
+ .trim()
+ .min(1, "Name is required")
+ .max(255, "Name must be 255 characters or fewer")
+ .regex(/^[a-z0-9-]+$/, "Name can only contain lowercase letters, numbers, and hyphens"),
description: descriptionSchema,
issuerType: z.nativeEnum(IssuerType),
certificateAuthorityId: z.string().nullable().optional(),
@@ -606,7 +605,8 @@ export const CreateProfileModal = ({
}
};
- const { control, handleSubmit, reset, watch, setValue, trigger } = useForm<FormData>({
+ const { control, handleSubmit, reset, watch, setValue, setError, trigger } = useForm<FormData>({
+ mode: "onTouched",
resolver: zodResolver(isEdit ? editSchema : createSchema),
defaultValues:
(isEdit || isClone) && profile
@@ -809,7 +809,7 @@ export const CreateProfileModal = ({
}
}, [isAwsAcmPublicCa, watchedPolicyId, setValue]);
- const onFormSubmit = async (data: FormData) => {
+ const saveProfile = async (data: FormData) => {
if (!currentProject?.id && !isEdit) return;
// Both AD CS variants require a template on the profile's external config.
@@ -910,6 +910,17 @@ export const CreateProfileModal = ({
onClose();
};
+ const onFormSubmit = async (data: FormData) => {
+ try {
+ await saveProfile(data);
+ } catch (error) {
+ if (!axios.isAxiosError(error) || error.response?.data?.error !== ApiErrorTypes.ConflictError)
+ throw error;
+ setSelectedStepIndex(0);
+ setError("slug", { type: "server", message: error.response.data?.message });
+ }
+ };
+
const isStepValid = async (index: number) => {
const { fields } = steps[index];
if (fields.length === 0) return true;
@@ -1086,17 +1097,25 @@ export const CreateProfileModal = ({
control={control}
name="slug"
render={({ field, fieldState: { error } }) => (
- <Field>
+ <Field data-invalid={Boolean(error)}>
<FieldLabel>
Name <span className="text-danger">*</span>
</FieldLabel>
<FieldContent>
<Input
{...field}
+ onChange={(event) =>
+ field.onChange(normalizeSlugInput(event.target.value))
+ }
+ aria-describedby="certificate-profile-name-feedback"
placeholder="your-profile-name"
isError={Boolean(error)}
/>
- <FieldError errors={[error]} />
+ <FieldFeedback
+ id="certificate-profile-name-feedback"
+ description="Use lowercase letters, numbers, and hyphens. Spaces become hyphens."
+ error={error?.message}
+ />
</FieldContent>
</Field>
)}