Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Address PR comments
Carlos Monastyrskif8e30f06533f
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex ad41f07c0f..c60a7825e6 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -2294,8 +2294,12 @@ export const CERTIFICATE_POLICIES = {CUSTOM_EXTENSION_RULES:"Rules for custom X.509 extensions, one per OID. Omit the field to leave custom extensions unconstrained; send an empty array to forbid them entirely.",CUSTOM_EXTENSION_RULE: {- rule: "Whether the value pattern allows, requires, or denies this extension. Require also makes the extension mandatory.",- value: "The value pattern this rule matches against, with * as a wildcard. Use * on its own to match any value."+ allowed:+ "Value patterns this extension may take, with * as a wildcard. Use * on its own to accept any value. Omit to place no allow-list constraint on the value.",+ required:+ "Value patterns this extension must match, with * as a wildcard. Setting any required pattern also makes the extension mandatory on every request.",+ denied:+ "Value patterns this extension must not take, with * as a wildcard. A denied match is rejected even when an allowed pattern also matches."},SUBJECT_DOMAIN_COMPONENT_RULE: {allowed: domainComponentRule("permitted"),diff --git a/backend/src/services/certificate-common/certificate-constants.ts b/backend/src/services/certificate-common/certificate-constants.tsindex 1f72340288..c8097f677d 100644--- a/backend/src/services/certificate-common/certificate-constants.ts+++ b/backend/src/services/certificate-common/certificate-constants.ts@@ -366,12 +366,6 @@ export enum CertExtensionCriticality {NOT_CRITICAL = "not_critical"}-export enum CertExtensionRuleKind {- ALLOW = "allow",- REQUIRE = "require",- DENY = "deny"-}-export const CUSTOM_EXTENSION_PRESET_OIDS = {NTDS_SID: "1.3.6.1.4.1.311.25.2",MS_CERTIFICATE_TEMPLATE_NAME: "1.3.6.1.4.1.311.20.2",diff --git a/backend/src/services/certificate-common/certificate-extension-fns.test.ts b/backend/src/services/certificate-common/certificate-extension-fns.test.tsindex f229167162..401f98555e 100644--- a/backend/src/services/certificate-common/certificate-extension-fns.test.ts+++ b/backend/src/services/certificate-common/certificate-extension-fns.test.ts@@ -2,11 +2,7 @@ import * as x509 from "@peculiar/x509";import * as asn1js from "asn1js";import { describe, expect, it } from "vitest";-import {- CertExtensionCriticality,- CertExtensionRuleKind,- certificateExtensionOidSchema-} from "./certificate-constants";+import { CertExtensionCriticality, certificateExtensionOidSchema } from "./certificate-constants";import {appendCustomExtensions,CUSTOM_EXTENSION_PRESETS_BY_OID,@@ -133,7 +129,7 @@ describe("resolveCustomExtensions", () => {it("refuses a request extension whose value could not be decoded when the policy restricts OIDs", () => {const { errors } = resolveCustomExtensions({declarations: [],- rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],+ rules: [{ oid: SID_OID, allowed: ["*"] }],requestExtensions: [{ oid: OPAQUE_OID, critical: false }]});@@ -181,7 +177,7 @@ describe("resolveCustomExtensions", () => {it("denies an OID that no rule mentions", () => {const { errors } = resolveCustomExtensions({declarations: [declareSid],- rules: [{ oid: TEMPLATE_NAME_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }]+ rules: [{ oid: TEMPLATE_NAME_OID, allowed: ["*"] }]});expect(errors).toEqual([`Custom extension '${SID_OID}' is not allowed by this policy.`]);@@ -191,7 +187,7 @@ describe("resolveCustomExtensions", () => {const override = "S-1-5-21-1004336348-1177238915-682003330-9999";const { extensions, errors } = resolveCustomExtensions({declarations: [declareSid],- rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],+ rules: [{ oid: SID_OID, allowed: ["*"] }],requestExtensions: [{ oid: SID_OID, value: override }]});@@ -202,7 +198,7 @@ describe("resolveCustomExtensions", () => {it("emits nothing when neither the profile nor the request supplies a value", () => {const { extensions, errors } = resolveCustomExtensions({declarations: [{ oid: SID_OID }],- rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }]+ rules: [{ oid: SID_OID, allowed: ["*"] }]});expect(extensions).toEqual([]);@@ -212,21 +208,70 @@ describe("resolveCustomExtensions", () => {it("rejects a request SID from a different AD domain, which is the case this model exists for", () => {const { errors } = resolveCustomExtensions({declarations: [{ oid: SID_OID }],- rules: [- { oid: SID_OID, rule: CertExtensionRuleKind.REQUIRE, value: "S-1-5-21-1004336348-1177238915-682003330-*" }- ],+ rules: [{ oid: SID_OID, required: ["S-1-5-21-1004336348-1177238915-682003330-*"] }],requestExtensions: [{ oid: SID_OID, value: "S-1-5-21-999-888-777-1103" }]});- expect(errors[0]).toContain("does not match the value required by this policy");+ expect(errors[0]).toContain("does not match any value required by this policy");});it("accepts a request SID inside the allowed AD domain", () => {const { extensions, errors } = resolveCustomExtensions({declarations: [{ oid: SID_OID }],- rules: [- { oid: SID_OID, rule: CertExtensionRuleKind.REQUIRE, value: "S-1-5-21-1004336348-1177238915-682003330-*" }- ],+ rules: [{ oid: SID_OID, required: ["S-1-5-21-1004336348-1177238915-682003330-*"] }],+ requestExtensions: [{ oid: SID_OID, value: SID }]+ });++ expect(errors).toEqual([]);+ expect(extensions).toHaveLength(1);+ });++ it("accepts a SID from either of two AD domains, which one pattern per OID could not express", () => {+ const rules = [+ {+ oid: SID_OID,+ allowed: ["S-1-5-21-1004336348-1177238915-682003330-*", "S-1-5-21-9-8-7-*"]+ }+ ];++ const first = resolveCustomExtensions({+ declarations: [{ oid: SID_OID }],+ rules,+ requestExtensions: [{ oid: SID_OID, value: SID }]+ });+ expect(first.errors).toEqual([]);+ expect(first.extensions).toHaveLength(1);++ const second = resolveCustomExtensions({+ declarations: [{ oid: SID_OID }],+ rules,+ requestExtensions: [{ oid: SID_OID, value: "S-1-5-21-9-8-7-1103" }]+ });+ expect(second.errors).toEqual([]);+ expect(second.extensions).toHaveLength(1);++ const outside = resolveCustomExtensions({+ declarations: [{ oid: SID_OID }],+ rules,+ requestExtensions: [{ oid: SID_OID, value: "S-1-5-21-111-222-333-1103" }]+ });+ expect(outside.errors[0]).toContain("is not allowed by this policy");+ });++ it("rejects a denied value even when an allowed pattern also matches it", () => {+ const { errors } = resolveCustomExtensions({+ declarations: [{ oid: SID_OID }],+ rules: [{ oid: SID_OID, allowed: ["S-1-5-21-*"], denied: ["S-1-5-21-*-500"] }],+ requestExtensions: [{ oid: SID_OID, value: "S-1-5-21-1-2-3-500" }]+ });++ expect(errors[0]).toContain("is denied by this policy");+ });++ it("exempts a value that satisfies a required pattern from the allow list, as SAN rules do", () => {+ const { errors, extensions } = resolveCustomExtensions({+ declarations: [{ oid: SID_OID }],+ rules: [{ oid: SID_OID, allowed: ["S-1-5-21-9-*"], required: ["S-1-5-21-1004336348-*"] }],requestExtensions: [{ oid: SID_OID, value: SID }]});@@ -237,7 +282,7 @@ describe("resolveCustomExtensions", () => {it("honours denied patterns", () => {const { errors } = resolveCustomExtensions({declarations: [{ oid: SID_OID }],- rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.DENY, value: "S-1-5-21-*-500" }],+ rules: [{ oid: SID_OID, denied: ["S-1-5-21-*-500"] }],requestExtensions: [{ oid: SID_OID, value: "S-1-5-21-1004336348-1177238915-682003330-500" }]});@@ -245,7 +290,7 @@ describe("resolveCustomExtensions", () => {});it("reports a required rule that nothing satisfies, and respects skipRequired", () => {- const rules = [{ oid: SID_OID, rule: CertExtensionRuleKind.REQUIRE, value: "S-1-5-21-*" }];+ const rules = [{ oid: SID_OID, required: ["S-1-5-21-*"] }];expect(resolveCustomExtensions({ declarations: [], rules }).errors).toHaveLength(1);expect(resolveCustomExtensions({ declarations: [], rules, skipRequired: true }).errors).toEqual([]);@@ -272,7 +317,7 @@ describe("resolveCustomExtensions", () => {it("refuses a request extension the policy does not list, declared or not", () => {const { extensions, errors } = resolveCustomExtensions({declarations: [],- rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],+ rules: [{ oid: SID_OID, allowed: ["*"] }],requestExtensions: [{ oid: CUSTOM_OID, value: "BQA=" }]});@@ -295,7 +340,7 @@ describe("resolveCustomExtensions", () => {const value = Buffer.from("0500", "hex").toString("base64");const { extensions } = resolveCustomExtensions({declarations: [{ oid: CUSTOM_OID, value, critical: false }],- rules: [{ oid: CUSTOM_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],+ rules: [{ oid: CUSTOM_OID, allowed: ["*"] }],requestExtensions: [{ oid: CUSTOM_OID, critical: true }]});@@ -306,9 +351,7 @@ describe("resolveCustomExtensions", () => {const value = Buffer.from("0500", "hex").toString("base64");const { errors } = resolveCustomExtensions({declarations: [{ oid: CUSTOM_OID, value }],- rules: [- { oid: CUSTOM_OID, rule: CertExtensionRuleKind.ALLOW, value: "*", critical: CertExtensionCriticality.CRITICAL }- ],+ rules: [{ oid: CUSTOM_OID, allowed: ["*"], critical: CertExtensionCriticality.CRITICAL }],requestExtensions: [{ oid: CUSTOM_OID, critical: false }]});@@ -320,7 +363,7 @@ describe("resolveCustomExtensions", () => {it("keeps a preset's criticality when the request does not contest it", () => {const { extensions } = resolveCustomExtensions({declarations: [declareSid],- rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],+ rules: [{ oid: SID_OID, allowed: ["*"] }],requestExtensions: [{ oid: SID_OID }]});@@ -330,7 +373,7 @@ describe("resolveCustomExtensions", () => {it("rejects a request that contests a preset's criticality", () => {const { extensions, errors } = resolveCustomExtensions({declarations: [declareSid],- rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],+ rules: [{ oid: SID_OID, allowed: ["*"] }],requestExtensions: [{ oid: SID_OID, critical: true }]});@@ -341,7 +384,7 @@ describe("resolveCustomExtensions", () => {it("denies a value the policy denies", () => {const { extensions, errors } = resolveCustomExtensions({declarations: [{ oid: CUSTOM_OID, value: "ops-prod" }],- rules: [{ oid: CUSTOM_OID, rule: CertExtensionRuleKind.DENY, value: "ops-prod" }]+ rules: [{ oid: CUSTOM_OID, denied: ["ops-prod"] }]});expect(extensions).toHaveLength(0);@@ -354,7 +397,7 @@ describe("resolveCustomExtensions", () => {])("matching %s against an allowed pattern of Machine", (requested, emitted, failures) => {const { extensions, errors } = resolveCustomExtensions({declarations: [{ oid: TEMPLATE_NAME_OID }],- rules: [{ oid: TEMPLATE_NAME_OID, rule: CertExtensionRuleKind.ALLOW, value: "Machine" }],+ rules: [{ oid: TEMPLATE_NAME_OID, allowed: ["Machine"] }],requestExtensions: [{ oid: TEMPLATE_NAME_OID, value: requested }]});@@ -364,7 +407,7 @@ describe("resolveCustomExtensions", () => {it("rejects a template name that is empty or outside the basic multilingual plane", () => {expect(resolveCustomExtensions({ declarations: [{ oid: TEMPLATE_NAME_OID, value: "" }] }).errors[0]).toContain(- "Enter a certificate template name"+ "Value must be a certificate template name");expect(resolveCustomExtensions({ declarations: [{ oid: TEMPLATE_NAME_OID, value: "Ma\u{1F600}ne" }] }).errors[0]@@ -419,7 +462,7 @@ describe("resolveCustomExtensions on the profile-save path", () => {it("rejects a declared value the policy forbids", () => {const errors = save([{ oid: TEMPLATE_NAME_OID, value: "User" }],- [{ oid: TEMPLATE_NAME_OID, rule: CertExtensionRuleKind.ALLOW, value: "Machine" }]+ [{ oid: TEMPLATE_NAME_OID, allowed: ["Machine"] }]);expect(errors[0]).toContain("is not allowed by this policy");@@ -432,14 +475,14 @@ describe("resolveCustomExtensions on the profile-save path", () => {it("rejects a criticality that disagrees with the policy even with no value", () => {const errors = save([{ oid: CUSTOM_OID, critical: false }],- [{ oid: CUSTOM_OID, rule: CertExtensionRuleKind.ALLOW, value: "*", critical: CertExtensionCriticality.CRITICAL }]+ [{ oid: CUSTOM_OID, allowed: ["*"], critical: CertExtensionCriticality.CRITICAL }]);expect(errors[0]).toContain("must be emitted as critical");});it("does not ask the profile to satisfy a required rule", () => {- expect(save([], [{ oid: CUSTOM_OID, rule: CertExtensionRuleKind.REQUIRE, value: "BQA=" }])).toHaveLength(0);+ expect(save([], [{ oid: CUSTOM_OID, required: ["BQA="] }])).toHaveLength(0);});});diff --git a/backend/src/services/certificate-common/certificate-extension-fns.ts b/backend/src/services/certificate-common/certificate-extension-fns.tsindex 70ed170d7e..d995a40b6c 100644--- a/backend/src/services/certificate-common/certificate-extension-fns.ts+++ b/backend/src/services/certificate-common/certificate-extension-fns.ts@@ -8,7 +8,6 @@ import { matchesNormalizedPattern } from "../certificate-policy/certificate-poliimport {CERT_EXTENSION_OID_PATTERN_SOURCE,CertExtensionCriticality,- CertExtensionRuleKind,CUSTOM_EXTENSION_PRESET_OIDS,MAX_CUSTOM_EXTENSION_VALUE_BYTES,MAX_CUSTOM_EXTENSIONS_PER_AWS_PCA_PROFILE,@@ -29,8 +28,9 @@ export type TCustomExtensionRule = {oid: string;label?: string;critical?: CertExtensionCriticality;- rule: CertExtensionRuleKind;- value: string;+ allowed?: string[];+ required?: string[];+ denied?: string[];};export type TProfileCustomExtension = {@@ -146,14 +146,14 @@ export const CUSTOM_EXTENSION_PRESETS_BY_OID: Record<string, TCustomExtensionPrevalidateInput: (value) =>SID_PATTERN.test(value)? null- : "Enter a security identifier, for example S-1-5-21-1004336348-1177238915-682003330-1103",+ : "Value must be a security identifier, for example S-1-5-21-1004336348-1177238915-682003330-1103",encode: encodeNtdsSid,describe: describeNtdsSid},[CUSTOM_EXTENSION_PRESET_OIDS.MS_CERTIFICATE_TEMPLATE_NAME]: asn1StringPreset({Type: asn1js.BmpString,validateInput: (value) => {- if (!value.length) return "Enter a certificate template name";+ if (!value.length) return "Value must be a certificate template name";if (value.length > 64) return "Template name cannot exceed 64 characters";if (Array.from(value).some((character) => (character.codePointAt(0) ?? 0) > 0xffff)) {return "Template name cannot contain characters outside the basic multilingual plane";@@ -166,7 +166,7 @@ export const CUSTOM_EXTENSION_PRESETS_BY_OID: Record<string, TCustomExtensionPrevalidateInput: (value) =>TEMPLATE_INFORMATION_PATTERN.test(value)? null- : "Enter the template OID, a colon, then the version, for example 1.3.6.1.4.1.311.21.8.1.2:100.3",+ : "Value must be the template OID, a colon, then the version, for example 1.3.6.1.4.1.311.21.8.1.2:100.3",encode: (value) => {const match = TEMPLATE_INFORMATION_PATTERN.exec(value);if (!match) throw new BadRequestError({ message: "Certificate template information value is malformed" });@@ -200,7 +200,7 @@ const getCustomExtensionPreset = (oid: string): TCustomExtensionPreset | undefinexport const validateCustomExtensionValue = (oid: string, value: string): string | null => {const preset = getCustomExtensionPreset(oid);if (preset) return preset.validateInput(value);- if (!value.length) return "Enter a value";+ if (!value.length) return "Value cannot be empty";if (Buffer.byteLength(value, "utf8") > MAX_CUSTOM_EXTENSION_VALUE_BYTES) {return `Value cannot exceed ${MAX_CUSTOM_EXTENSION_VALUE_BYTES} bytes`;}@@ -255,6 +255,12 @@ export const parseCustomExtensionsFromCertificate = (.sort((a, b) => a.oid.localeCompare(b.oid));};+const withDisplayValue = (extensions: TIssuedCustomExtension[]): TIssuedCustomExtension[] =>+ extensions.map((extension) => ({+ ...extension,+ displayValue: describeCustomExtensionValue(extension.oid, extension.value) ?? undefined+ }));+export const parseIssuedCustomExtensions = (certificateDer: Buffer,resolved?: TResolvedCustomExtension[]@@ -262,14 +268,14 @@ export const parseIssuedCustomExtensions = (if (!resolved?.length) return [];const resolvedOids = new Set(resolved.map((extension) => extension.oid));- return parseCustomExtensionsFromCertificate(certificateDer)- .filter((extension) => resolvedOids.has(extension.oid))- .map((extension) => ({- ...extension,- displayValue: describeCustomExtensionValue(extension.oid, extension.value) ?? undefined- }));+ return withDisplayValue(+ parseCustomExtensionsFromCertificate(certificateDer).filter((extension) => resolvedOids.has(extension.oid))+ );};+export const parseImportedCustomExtensions = (certificateDer: Buffer): TIssuedCustomExtension[] =>+ withDisplayValue(parseCustomExtensionsFromCertificate(certificateDer));+export type TCsrCustomExtensionMismatch = { oid: string; reason: "missing" | "value" | "criticality" };export const findCsrCustomExtensionMismatch = (@@ -347,7 +353,10 @@ export const appendCustomExtensions = (extensions: x509.Extension[], resolved: T}};-const ALLOW_ANY_RULE: TCustomExtensionRule = { oid: "", rule: CertExtensionRuleKind.ALLOW, value: "*" };+const ALLOW_ANY_RULE: TCustomExtensionRule = { oid: "", allowed: ["*"] };++const matchesAnyPattern = (value: string, patterns: string[]) =>+ patterns.some((pattern) => matchesNormalizedPattern(value, pattern));const buildRuleLookup = (rules?: TCustomExtensionRule[] | null) => {if (rules === undefined || rules === null) return null;@@ -457,22 +466,30 @@ export const resolveCustomExtensions = ({continue;}- const matchesRule = matchesNormalizedPattern(displayValue, rule.value);- if (rule.rule === CertExtensionRuleKind.DENY && matchesRule) {- errors.push(`Custom extension '${oid}' value '${displayValue}' is denied by this policy.`);+ const denied = rule.denied ?? [];+ const required = rule.required ?? [];+ const allowed = rule.allowed ?? [];++ if (matchesAnyPattern(displayValue, denied)) {+ errors.push(+ `Custom extension '${oid}' value '${displayValue}' is denied by this policy. Denied values: ${denied.join(", ")}`+ );// eslint-disable-next-line no-continuecontinue;}- if (rule.rule === CertExtensionRuleKind.REQUIRE && !matchesRule) {++ const satisfiesRequired = required.length > 0 && matchesAnyPattern(displayValue, required);+ if (required.length > 0 && !satisfiesRequired) {errors.push(- `Custom extension '${oid}' value '${displayValue}' does not match the value required by this policy: ${rule.value}`+ `Custom extension '${oid}' value '${displayValue}' does not match any value required by this policy: ${required.join(", ")}`);// eslint-disable-next-line no-continuecontinue;}- if (rule.rule === CertExtensionRuleKind.ALLOW && !matchesRule) {++ if (!satisfiesRequired && allowed.length > 0 && !matchesAnyPattern(displayValue, allowed)) {errors.push(- `Custom extension '${oid}' value '${displayValue}' is not allowed by this policy. Allowed values: ${rule.value}`+ `Custom extension '${oid}' value '${displayValue}' is not allowed by this policy. Allowed values: ${allowed.join(", ")}`);// eslint-disable-next-line no-continuecontinue;@@ -489,13 +506,13 @@ export const resolveCustomExtensions = ({if (!skipRequired && rulesByOid !== null) {for (const rule of rulesByOid.values()) {- if (rule.rule !== CertExtensionRuleKind.REQUIRE) {+ if (!rule.required?.length) {// eslint-disable-next-line no-continuecontinue;}if (!resolvedOids.has(rule.oid)) {errors.push(- `This policy requires custom extension '${rule.oid}' matching '${rule.value}'. Supply it on the request, or set it as a default on the certificate profile.`+ `This policy requires custom extension '${rule.oid}' matching one of: ${rule.required.join(", ")}. Supply it on the request, or set it as a default on the certificate profile.`);}}diff --git a/backend/src/services/certificate-policy/certificate-policy-schemas.ts b/backend/src/services/certificate-policy/certificate-policy-schemas.tsindex 5c33cda74a..fcbc302e1d 100644--- a/backend/src/services/certificate-policy/certificate-policy-schemas.ts+++ b/backend/src/services/certificate-policy/certificate-policy-schemas.ts@@ -5,7 +5,6 @@ import { CERTIFICATE_POLICIES } from "@app/lib/api-docs";import {CertExtendedKeyUsageType,CertExtensionCriticality,- CertExtensionRuleKind,certificateExtensionOidSchema,CertKeyUsageType,CertPolicyState,@@ -121,13 +120,24 @@ const policyExtendedKeyUsagesSchema = z});-export const policyCustomExtensionSchema = z.object({- oid: certificateExtensionOidSchema,- label: customExtensionLabelSchema.optional(),- critical: z.nativeEnum(CertExtensionCriticality).optional(),- rule: z.nativeEnum(CertExtensionRuleKind).describe(CERTIFICATE_POLICIES.CUSTOM_EXTENSION_RULE.rule),- value: customExtensionValueSchema.describe(CERTIFICATE_POLICIES.CUSTOM_EXTENSION_RULE.value)-});+export const policyCustomExtensionSchema = z+ .object({+ oid: certificateExtensionOidSchema,+ label: customExtensionLabelSchema.optional(),+ critical: z.nativeEnum(CertExtensionCriticality).optional(),+ allowed: z+ .array(customExtensionValueSchema)+ .optional()+ .describe(CERTIFICATE_POLICIES.CUSTOM_EXTENSION_RULE.allowed),+ required: z+ .array(customExtensionValueSchema)+ .optional()+ .describe(CERTIFICATE_POLICIES.CUSTOM_EXTENSION_RULE.required),+ denied: z.array(customExtensionValueSchema).optional().describe(CERTIFICATE_POLICIES.CUSTOM_EXTENSION_RULE.denied)+ })+ .refine((data) => Boolean(data.allowed?.length || data.required?.length || data.denied?.length), {+ message: "Custom extension rule must have at least one allowed, required, or denied value"+ });const policySanSchema = z.object({diff --git a/backend/src/services/certificate-policy/certificate-policy-service.test.ts b/backend/src/services/certificate-policy/certificate-policy-service.test.tsindex 45d6b35796..96560ffa73 100644--- a/backend/src/services/certificate-policy/certificate-policy-service.test.ts+++ b/backend/src/services/certificate-policy/certificate-policy-service.test.ts@@ -208,17 +208,17 @@ describe("CertificatePolicyService", () => {});it("accepts a rule for an unmanaged OID", async () => {- await expect(createWith([{ oid: CUSTOM_OID, rule: "allow", value: "*" }])).resolves.toBeDefined();+ await expect(createWith([{ oid: CUSTOM_OID, allowed: ["*"] }])).resolves.toBeDefined();});it("rejects a reserved OID", async () => {- await expect(createWith([{ oid: "2.5.29.17", rule: "allow", value: "*" }])).rejects.toThrow(+ await expect(createWith([{ oid: "2.5.29.17", allowed: ["*"] }])).rejects.toThrow("standard X.509 extension that Infisical manages");});it("rejects the UPN otherName OID with a pointer to SANs", async () => {- await expect(createWith([{ oid: "1.3.6.1.4.1.311.20.2.3", rule: "allow", value: "*" }])).rejects.toThrow(+ await expect(createWith([{ oid: "1.3.6.1.4.1.311.20.2.3", allowed: ["*"] }])).rejects.toThrow("Use a UPN subject alternative name");});@@ -226,14 +226,14 @@ describe("CertificatePolicyService", () => {it("rejects duplicate OIDs", async () => {await expect(createWith([- { oid: CUSTOM_OID, rule: "allow", value: "*" },- { oid: CUSTOM_OID, rule: "deny", value: "x" }+ { oid: CUSTOM_OID, allowed: ["*"] },+ { oid: CUSTOM_OID, denied: ["x"] }])).rejects.toThrow("Duplicate custom extension rule");});it("rejects constraining criticality on a preset OID, whose spec fixes it", async () => {- await expect(createWith([{ oid: SID_OID, rule: "allow", value: "*", critical: "critical" }])).rejects.toThrow(+ await expect(createWith([{ oid: SID_OID, allowed: ["*"], critical: "critical" }])).rejects.toThrow("always emitted as non-critical");});@@ -243,7 +243,7 @@ describe("CertificatePolicyService", () => {id: "p",projectId: "project-123",name: "p",- customExtensions: [{ oid: SID_OID, rule: "allow", value }]+ customExtensions: [{ oid: SID_OID, allowed: [value] }]}) as never;it("resolves declarations through validateRequestAgainstPolicy", () => {diff --git a/backend/src/services/certificate-policy/certificate-policy-service.ts b/backend/src/services/certificate-policy/certificate-policy-service.tsindex 080201e5ec..53592688f6 100644--- a/backend/src/services/certificate-policy/certificate-policy-service.ts+++ b/backend/src/services/certificate-policy/certificate-policy-service.ts@@ -181,15 +181,27 @@ export const certificatePolicyServiceFactory = ({throw new BadRequestError({ message: describeReservedExtensionOid(rule.oid) });}- if (!isWildcardPattern(rule.value)) {- const invalid = validateCustomExtensionValue(rule.oid, rule.value);+ const patterns = [...(rule.allowed ?? []), ...(rule.required ?? []), ...(rule.denied ?? [])];+ for (const pattern of patterns) {+ if (isWildcardPattern(pattern)) {+ // eslint-disable-next-line no-continue+ continue;+ }+ const invalid = validateCustomExtensionValue(rule.oid, pattern);if (invalid) {throw new BadRequestError({- message: `Custom extension rule for OID '${rule.oid}' has a value this extension can never take, so the rule would never apply. ${invalid}`+ message: `Custom extension rule for OID '${rule.oid}' lists '${pattern}', which this extension can never take, so the rule would never apply. ${invalid}. Patterns may use * as a wildcard to cover a range of values.`});}}+ const conflicting = (rule.required ?? []).filter((pattern) => (rule.denied ?? []).includes(pattern));+ if (conflicting.length > 0) {+ throw new BadRequestError({+ message: `Custom extension rule for OID '${rule.oid}' both requires and denies ${conflicting.join(", ")}, so no value could ever satisfy it.`+ });+ }+const preset = CUSTOM_EXTENSION_PRESETS_BY_OID[rule.oid];if (preset && rule.critical) {throw new BadRequestError({diff --git a/backend/src/services/certificate-profile/certificate-profile-service.test.ts b/backend/src/services/certificate-profile/certificate-profile-service.test.tsindex 70b1ce1f2c..a797b732a9 100644--- a/backend/src/services/certificate-profile/certificate-profile-service.test.ts+++ b/backend/src/services/certificate-profile/certificate-profile-service.test.ts@@ -355,7 +355,7 @@ describe("CertificateProfileService", () => {it("accepts a declaration the policy permits", async () => {(mockCertificatePolicyDAL.findById as any).mockResolvedValue({...samplePolicy,- customExtensions: [{ oid: SID_OID, rule: "allow", value: "*" }]+ customExtensions: [{ oid: SID_OID, allowed: ["*"] }]});await expect(createWithExtensions([{ oid: SID_OID, value: "S-1-5-21-1-2-3-1103" }])).resolves.toBeDefined();@@ -382,7 +382,7 @@ describe("CertificateProfileService", () => {it("rejects an OID the policy does not mention", async () => {(mockCertificatePolicyDAL.findById as any).mockResolvedValue({...samplePolicy,- customExtensions: [{ oid: SID_OID, rule: "allow", value: "*" }]+ customExtensions: [{ oid: SID_OID, allowed: ["*"] }]});await expect(createWithExtensions([{ oid: CUSTOM_OID }])).rejects.toThrow("is not allowed by this policy");@@ -391,7 +391,7 @@ describe("CertificateProfileService", () => {it("rejects a declared value the policy forbids", async () => {(mockCertificatePolicyDAL.findById as any).mockResolvedValue({...samplePolicy,- customExtensions: [{ oid: SID_OID, rule: "allow", value: "S-1-5-21-1-2-3-*" }]+ customExtensions: [{ oid: SID_OID, allowed: ["S-1-5-21-1-2-3-*"] }]});await expect(createWithExtensions([{ oid: SID_OID, value: "S-1-5-21-9-9-9-1103" }])).rejects.toThrow(@@ -406,7 +406,7 @@ describe("CertificateProfileService", () => {});(mockCertificatePolicyDAL.findById as any).mockResolvedValue({...samplePolicy,- customExtensions: [{ oid: SID_OID, rule: "allow", value: "*" }]+ customExtensions: [{ oid: SID_OID, allowed: ["*"] }]});await expect(createWithExtensions([{ oid: SID_OID, value: "S-1-5-21-1-2-3-1103" }])).rejects.toThrow(@@ -417,7 +417,7 @@ describe("CertificateProfileService", () => {it("rejects setting criticality on a preset OID", async () => {(mockCertificatePolicyDAL.findById as any).mockResolvedValue({...samplePolicy,- customExtensions: [{ oid: SID_OID, rule: "allow", value: "*" }]+ customExtensions: [{ oid: SID_OID, allowed: ["*"] }]});await expect(diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex 639d657a77..0862852039 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -49,6 +49,7 @@ import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fnsimport { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";import { expandInternalCa, getCaCertChain, rebuildCaCrl } from "../certificate-authority/certificate-authority-fns";+import { parseImportedCustomExtensions } from "../certificate-common/certificate-extension-fns";import { validatePqcLicense } from "../certificate-common/certificate-utils";import {CertificateThumbprintAlgorithm,@@ -974,6 +975,7 @@ export const certificateServiceFactory = ({// Extract certificate fields for storageconst certificateBuffer = Buffer.from(certificatePem);const parsedFields = extractCertificateFields(certificateBuffer);+ const importedCustomExtensions = parseImportedCustomExtensions(certificateBuffer);const txCert = await certificateDAL.create({@@ -991,7 +993,8 @@ export const certificateServiceFactory = ({...parsedFields,// Issuance records these from what it was asked to produce. An imported certificate has// no such request, so they come from the certificate itself.- ...extractCertificateAlgorithms(certificateBuffer)+ ...extractCertificateAlgorithms(certificateBuffer),+ customExtensions: importedCustomExtensions.length ? JSON.stringify(importedCustomExtensions) : null},tx);diff --git a/docs/documentation/platform/pki/settings/policies.mdx b/docs/documentation/platform/pki/settings/policies.mdxindex 85bdfa8f79..6e75ec2f00 100644--- a/docs/documentation/platform/pki/settings/policies.mdx+++ b/docs/documentation/platform/pki/settings/policies.mdx@@ -195,17 +195,19 @@ Control whether certificates can act as CAs:### Custom extensions-Control which custom X.509 extensions certificates may carry, with one rule per object identifier (OID):+Control which custom X.509 extensions certificates may carry. Each rule is one value pattern for one object identifier (OID), classified the same way subject alternative name rules are:| Rule | Meaning ||------|---------|-| Allow | The extension is permitted, and its value must match the pattern |-| Require | The extension must be present, and its value must match the pattern |-| Deny | The extension is permitted, but not with a value matching the pattern |+| Allowed | The value may match this pattern |+| Required | The extension must be present, and its value must match one of the required patterns |+| Denied | The value must not match this pattern, even when an allowed pattern also matches it |-Each rule takes one value pattern, matched against the value you enter rather than its encoded form. Use `*` for any value, or a wildcard such as `S-1-5-21-1004336348-1177238915-682003330-*` to accept only identifiers from your own Active Directory domain. A rule can also pin criticality, except where an extension's specification already fixes it.+Add several rules for the same OID to accept more than one value. An Active Directory estate with two domains, for example, takes two Allowed rules on the security identifier extension, one wildcard per domain.-If you configure Custom Extensions, only the OIDs you list are permitted, each subject to its rule. Any other OID in a request is rejected, including one carried in a signing request, so a value pattern is what limits what an enrolling client can assert. An empty configuration forbids all custom extensions, and leaving the section unconfigured allows any OID with any value.+Patterns are matched against the value you enter rather than its encoded form, and matching is case sensitive. Use `*` for any value, or a wildcard such as `S-1-5-21-1004336348-1177238915-682003330-*` to accept only identifiers from one domain. A rule can also pin criticality, except where an extension's specification already fixes it.++If you configure Custom Extensions, only the OIDs you list are permitted. Any other OID in a request is rejected, including one carried in a signing request, so the patterns are what limit what an enrolling client can assert. An empty configuration forbids all custom extensions, and leaving the section unconfigured allows any OID with any value.Infisical manages some extensions itself, so you can't set any OID under `2.5.29.` or authority information access here.diff --git a/frontend/src/hooks/api/certificatePolicies/types.ts b/frontend/src/hooks/api/certificatePolicies/types.tsindex bc80b6ec68..ec0df401dd 100644--- a/frontend/src/hooks/api/certificatePolicies/types.ts+++ b/frontend/src/hooks/api/certificatePolicies/types.ts@@ -1,6 +1,5 @@import {CertExtensionCriticality,- CertExtensionRuleKind,CertPolicyState} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";@@ -26,8 +25,9 @@ export type TCustomExtensionRule = {oid: string;label?: string;critical?: CertExtensionCriticality;- rule: CertExtensionRuleKind;- value: string;+ allowed?: string[];+ required?: string[];+ denied?: string[];};export type TCertificatePolicyRule = {diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsxindex 25e3794fb3..3e4c9fca3e 100644--- a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsx+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsx@@ -10,7 +10,6 @@ import {import { TCertificatePolicy } from "@app/hooks/api/certificatePolicies";import {CertExtensionCriticality,- CertExtensionRuleKind,customExtensionLabelFor} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";@@ -20,12 +19,6 @@ type Props = {policy: TCertificatePolicy;};-const RULE_KIND_LABEL: Record<CertExtensionRuleKind, string> = {- [CertExtensionRuleKind.ALLOW]: "Allowed",- [CertExtensionRuleKind.REQUIRE]: "Required",- [CertExtensionRuleKind.DENY]: "Denied"-};-const CRITICALITY_LABEL: Record<CertExtensionCriticality, string> = {[CertExtensionCriticality.CRITICAL]: "Always critical",[CertExtensionCriticality.NOT_CRITICAL]: "Never critical"@@ -66,7 +59,15 @@ export const PolicyCustomExtensionsSection = ({ policy }: Props) => {)}</div><p className="font-mono text-xs text-mineshaft-400">{rule.oid}</p>- <RuleList label={RULE_KIND_LABEL[rule.rule]} values={[rule.value]} />+ {Boolean(rule.required?.length) && (+ <RuleList label="Required" values={rule.required ?? []} />+ )}+ {Boolean(rule.allowed?.length) && (+ <RuleList label="Allowed" values={rule.allowed ?? []} />+ )}+ {Boolean(rule.denied?.length) && (+ <RuleList label="Denied" values={rule.denied ?? []} />+ )}</div>))}</DetailGroup>diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsxindex e21f30ba37..c991c8e83d 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx@@ -150,7 +150,9 @@ const buildFormSchema = (variant: CaFormVariant) => {keyAlgorithm: z.string().min(1, "Key algorithm is required"),keyUsages: keyUsagesField,extendedKeyUsages: extendedKeyUsagesField,- customExtensions: z.array(z.object({ oid: z.string(), value: z.string() })).optional()+ customExtensions: z+ .array(z.object({ oid: z.string(), value: z.string(), critical: z.boolean().optional() }))+ .optional()});return zdiff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsxindex d761a715f9..bf83b5bb2d 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx@@ -96,7 +96,11 @@ const formSchema = zkeyAlgorithm: z.string().optional(),keyUsages: z.record(z.boolean().optional()).default({}),extendedKeyUsages: z.record(z.boolean().optional()).default({}),- customExtensions: z.array(z.object({ oid: z.string().trim(), value: z.string() })).default([])+ customExtensions: z+ .array(+ z.object({ oid: z.string().trim(), value: z.string(), critical: z.boolean().optional() })+ )+ .default([])}).superRefine((data, ctx) => {if (data.keySource === CertificateRenewalKeySource.Csr && !data.csr) {diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/RequestCustomExtensionsField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/RequestCustomExtensionsField.tsxindex 416c60a6bc..acc56dbdc4 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/RequestCustomExtensionsField.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/RequestCustomExtensionsField.tsx@@ -3,6 +3,7 @@ import { Plus, Trash2 } from "lucide-react";import {Button,+ Checkbox,Field,FieldLabel,IconButton,@@ -11,15 +12,18 @@ import {SelectContent,SelectItem,SelectTrigger,- SelectValue+ SelectValue,+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@app/components/v3";import { TCustomExtensionRule } from "@app/hooks/api/certificatePolicies";import { TProfileCustomExtension } from "@app/hooks/api/certificateProfiles/types";import { CustomExtensionOidSelect } from "@app/pages/cert-manager/components/CustomExtensionOidSelect";import {- CertExtensionRuleKind,customExtensionLabelFor,- getCustomExtensionValuePlaceholder+ getCustomExtensionValuePlaceholder,+ isPresetExtensionOid} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";import { PolicyRowMessage } from "./PolicyRowMessage";@@ -27,6 +31,7 @@ import { PolicyRowMessage } from "./PolicyRowMessage";export type TRequestCustomExtension = {oid: string;value: string;+ critical?: boolean;};type Props = {@@ -49,16 +54,14 @@ export const RequestCustomExtensionsField = ({const isPinned = (declaration: TProfileCustomExtension) =>Boolean(declaration.value?.trim()) ||- policyRules?.find((rule) => rule.oid === declaration.oid)?.rule ===- CertExtensionRuleKind.REQUIRE;+ Boolean(policyRules?.find((rule) => rule.oid === declaration.oid)?.required?.length);const effectiveDeclarations: TProfileCustomExtension[] = [...declarations,...(policyRules ?? []).filter((rule) =>- rule.rule === CertExtensionRuleKind.REQUIRE &&- !declarations.some((declaration) => declaration.oid === rule.oid)+ rule.required?.length && !declarations.some((declaration) => declaration.oid === rule.oid)).map((rule) => ({ oid: rule.oid, label: rule.label ?? undefined }))];@@ -89,19 +92,68 @@ export const RequestCustomExtensionsField = ({declarationByOid.get(oid)?.label ?? policyRules?.find((rule) => rule.oid === oid)?.label);- const upsert = (oid: string, next: string) => {+ const upsert = (oid: string, patch: Partial<TRequestCustomExtension>) => {const index = rows.findIndex((row) => row.oid === oid);if (index === -1) {- onChange([...rows, { oid, value: next }]);+ onChange([...rows, { oid, value: "", ...patch }]);return;}const updated = [...rows];- updated[index] = { oid, value: next };+ updated[index] = { ...updated[index], oid, ...patch };onChange(updated);};const rowError = (oid: string) => (revealPolicyErrors ? errorsByOid?.[oid] : undefined);+ const criticalityLock = (oid: string): string | null => {+ if (!oid) return null;+ if (isPresetExtensionOid(oid)) {+ return "Criticality is fixed for this extension because Active Directory rejects certificates that mark it differently.";+ }+ const pinned = policyRules?.find((rule) => rule.oid === oid)?.critical;+ return pinned+ ? "The certificate policy pins the criticality for this object identifier."+ : null;+ };++ const renderCriticality = (+ oid: string,+ isCritical: boolean,+ onToggle: (next: boolean) => void+ ) => {+ const lock = criticalityLock(oid);+ const box = (+ <Checkbox+ variant="project"+ isChecked={isCritical}+ isDisabled={Boolean(lock)}+ aria-label="Critical"+ onCheckedChange={(checked) => onToggle(checked === true)}+ />+ );++ return (+ <div className="flex h-9 shrink-0 items-center gap-2">+ {lock ? (+ <Tooltip>+ <TooltipTrigger asChild>+ {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}+ <span tabIndex={0} className="flex items-center">+ {box}+ </span>+ </TooltipTrigger>+ <TooltipContent side="top" className="max-w-64">+ {lock}+ </TooltipContent>+ </Tooltip>+ ) : (+ box+ )}+ <span className="text-sm whitespace-nowrap text-muted">Critical</span>+ </div>+ );+ };+return (<Field><FieldLabel>Custom Extensions</FieldLabel>@@ -122,12 +174,15 @@ export const RequestCustomExtensionsField = ({<InputclassName="w-full"value={current?.value ?? declaration.value ?? ""}- onChange={(e) => upsert(declaration.oid, e.target.value)}+ onChange={(e) => upsert(declaration.oid, { value: e.target.value })}placeholder={placeholder}isError={Boolean(error)}/>{error && <PolicyRowMessage isError lines={[error]} />}</div>+ {renderCriticality(declaration.oid, Boolean(current?.critical), (next) =>+ upsert(declaration.oid, { critical: next })+ )}<span className="w-9 shrink-0" /></div>);@@ -186,6 +241,9 @@ export const RequestCustomExtensionsField = ({/>{error && <PolicyRowMessage isError lines={[error]} />}</div>+ {renderCriticality(row.oid, Boolean(row.critical), (next) =>+ replaceRow({ ...row, critical: next })+ )}<IconButtontype="button"variant="ghost"diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.tsindex 54028fc786..10fdb437b1 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts@@ -12,7 +12,7 @@ type ManagedFormData = Extract<FormData, { requestMethod: "managed" }>;type ManagedIssuanceRequest = Omit<TUnifiedCertificateIssuanceDTO, "attributes"> & {attributes: NonNullable<TUnifiedCertificateIssuanceDTO["attributes"]> & {basicConstraints?: { isCA: boolean; pathLength?: number };- customExtensions?: { oid: string; value: string }[];+ customExtensions?: { oid: string; value: string; critical?: boolean }[];};};@@ -117,7 +117,11 @@ export const buildManagedRequest = ({const suppliedExtensions = (customExtensions ?? []).filter((entry) => entry.oid?.trim() && entry.value?.trim())- .map((entry) => ({ oid: entry.oid.trim(), value: entry.value.trim() }));+ .map((entry) => ({+ oid: entry.oid.trim(),+ value: entry.value.trim(),+ ...(entry.critical !== undefined && { critical: entry.critical })+ }));if (suppliedExtensions.length) {request.attributes.customExtensions = suppliedExtensions;}diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.tsindex 6a8c3f4018..1f0f869522 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts@@ -4,7 +4,6 @@ import {TSubjectRule} from "@app/hooks/api/certificatePolicies";import {- CertExtensionRuleKind,CertSubjectAlternativeNameType,CertSubjectAttributeType,formatSANType,@@ -651,8 +650,9 @@ export type SubjectPolicyGuidance = {export type TCustomExtensionPolicyRule = {oid: string;- rule: CertExtensionRuleKind;- value: string;+ allowed?: string[];+ required?: string[];+ denied?: string[];};export type TCustomExtensionDeclaration = {@@ -685,7 +685,7 @@ export const evaluateCustomExtensions = ({const isUnrestricted = rules === undefined || rules === null;const requiredOids = (rules ?? [])- .filter((rule) => rule.rule === CertExtensionRuleKind.REQUIRE)+ .filter((rule) => rule.required?.length).map((rule) => rule.oid);const oids = [...new Set([...declarationByOid.keys(), ...valueByOid.keys(), ...requiredOids])];@@ -701,7 +701,7 @@ export const evaluateCustomExtensions = ({}if (!value) {- if (rule?.rule === CertExtensionRuleKind.REQUIRE) {+ if (rule?.required?.length) {errorsByOid[oid] = "A value is required by this policy";}return;@@ -715,15 +715,24 @@ export const evaluateCustomExtensions = ({if (!rule) return;- const matches = matchesNormalizedPattern(value, rule.value);- if (rule.rule === CertExtensionRuleKind.DENY) {- if (matches) {- errorsByOid[oid] = "This value is denied by this policy";- }+ const matchesAnyExtensionPattern = (patterns: string[]) =>+ patterns.some((pattern) => matchesNormalizedPattern(value, pattern));++ if (matchesAnyExtensionPattern(rule.denied ?? [])) {+ errorsByOid[oid] = "This value is denied by this policy";return;}- if (!matches) {- errorsByOid[oid] = `Value must match ${rule.value}`;++ const required = rule.required ?? [];+ const satisfiesRequired = required.length > 0 && matchesAnyExtensionPattern(required);+ if (required.length > 0 && !satisfiesRequired) {+ errorsByOid[oid] = `Value must match one of: ${required.join(", ")}`;+ return;+ }++ const allowed = rule.allowed ?? [];+ if (!satisfiesRequired && allowed.length > 0 && !matchesAnyExtensionPattern(allowed)) {+ errorsByOid[oid] = `Value must match one of: ${allowed.join(", ")}`;}});diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.tsindex 160b912fd5..57d8bbada1 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts@@ -152,15 +152,17 @@ export const buildRenewalRequestAttributes = ({constraints: TemplateConstraints;isExternalTemplateProfile?: boolean;}): TRenewCertificateAttributes => {- // The CSR carries its own basic constraints and the CSR step offers no control over them, so- // sending the previous certificate's would silently override what the caller actually signed.- if (formData.keySource === CertificateRenewalKeySource.Csr) {- return { ttl: formData.ttl };- }-const customExtensions = (formData.customExtensions ?? []).filter((extension) => extension.oid.trim())- .map((extension) => ({ oid: extension.oid.trim(), value: extension.value }));+ .map((extension) => ({+ oid: extension.oid.trim(),+ value: extension.value,+ ...(extension.critical !== undefined && { critical: extension.critical })+ }));++ if (formData.keySource === CertificateRenewalKeySource.Csr) {+ return { ttl: formData.ttl, customExtensions };+ }const basicConstraints = buildBasicConstraints(formData, constraints);diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsxindex 7f85d27fb8..c20b0a62f4 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx@@ -2,7 +2,7 @@import { forwardRef, ReactNode, useEffect, useImperativeHandle, useRef, useState } from "react";import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { Info, Plus, ShieldCheck, Trash2 } from "lucide-react";+import { Info, PencilIcon, Plus, ShieldCheck, Trash2 } from "lucide-react";import { createNotification } from "@app/components/notifications";import {@@ -60,16 +60,20 @@ import { PkiDocsUrls } from "../../../pki-docs-urls";import {CertDurationUnit,CertExtendedKeyUsageType,+ CertExtensionCriticality,+ CertExtensionInclude,CertKeyUsageType,CertPolicyState,CertSanInclude,CertSubjectAlternativeNameType,CertSubjectAttributeInclude,CertSubjectAttributeType,+ CUSTOM_EXTENSION_INCLUDE_LABELS,customExtensionLabelFor,EXTENDED_KEY_USAGE_OPTIONS,formatExtendedKeyUsage,formatKeyUsage,+ groupCustomExtensionRows,KEY_USAGE_OPTIONS,POLICY_PRESET_IDS,type PolicyPresetId,@@ -491,6 +495,9 @@ export const CertificatePolicyWizard = forwardRef<CertificatePolicyWizardHandle,const [configureBasicConstraints, setConfigureBasicConstraints] = useState(false);const [restrictCustomExtensions, setRestrictCustomExtensions] = useState(false);const [isCustomExtensionDialogOpen, setIsCustomExtensionDialogOpen] = useState(false);+ const [editingCustomExtensionIndex, setEditingCustomExtensionIndex] = useState<number | null>(+ null+ );const [errors, setErrors] = useState<Record<string, string>>({});const clearError = (key: string) =>@@ -606,15 +613,23 @@ export const CertificatePolicyWizard = forwardRef<CertificatePolicyWizardHandle,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- }));+ const customExtensions: FormData["customExtensions"] = [];+ (policyData.customExtensions ?? []).forEach((rule) => {+ const base = {+ oid: rule.oid,+ label: rule.label ?? "",+ critical: (rule.critical ?? "") as CertExtensionCriticality | ""+ };+ (+ [+ [CertExtensionInclude.REQUIRED, rule.required],+ [CertExtensionInclude.ALLOWED, rule.allowed],+ [CertExtensionInclude.DENIED, rule.denied]+ ] as const+ ).forEach(([include, values]) => {+ (values ?? []).forEach((value) => customExtensions.push({ ...base, include, value }));+ });+ });return {preset: POLICY_PRESET_IDS.CUSTOM,@@ -890,17 +905,7 @@ export const CertificatePolicyWizard = forwardRef<CertificatePolicyWizardHandle,: 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() || "*"- }))+ ? groupCustomExtensionRows(data.customExtensions): null;return {@@ -1083,7 +1088,7 @@ export const CertificatePolicyWizard = forwardRef<CertificatePolicyWizardHandle,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).";+ "Every custom extension rule needs a value pattern (use * for any).";}}@@ -1566,7 +1571,7 @@ export const CertificatePolicyWizard = forwardRef<CertificatePolicyWizardHandle,<div className="space-y-8"><SectionToggletitle="Restrict custom extensions"- description="Only allow the custom extension OIDs you configure here."+ description="Certificates may carry only the OIDs listed here, each subject to its rule."enabled={restrictCustomExtensions}error={errors.customExtensions}onChange={(enabled) => {@@ -1603,25 +1608,39 @@ export const CertificatePolicyWizard = forwardRef<CertificatePolicyWizardHandle,</TableHeader><TableBody>{watchedCustomExtensions.map((extension, index) => (- <TableRow key={extension.oid}>+ // eslint-disable-next-line react/no-array-index-key+ <TableRow key={`${extension.oid}-${extension.include}-${index}`}><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_INCLUDE_LABELS[extension.include]}</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>+ <div className="flex items-center gap-1">+ <IconButton+ type="button"+ variant="ghost"+ aria-label={`Edit ${extension.oid}`}+ onClick={() => {+ setEditingCustomExtensionIndex(index);+ setIsCustomExtensionDialogOpen(true);+ }}+ >+ <PencilIcon className="size-4" />+ </IconButton>+ <IconButton+ type="button"+ variant="ghost"+ aria-label={`Remove ${extension.oid}`}+ onClick={() => removeCustomExtension(index)}+ >+ <Trash2 className="size-4" />+ </IconButton>+ </div></TableCell></TableRow>))}@@ -1634,18 +1653,44 @@ export const CertificatePolicyWizard = forwardRef<CertificatePolicyWizardHandle,className="mt-3"variant="outline"size="sm"- onClick={() => setIsCustomExtensionDialogOpen(true)}+ onClick={() => {+ setEditingCustomExtensionIndex(null);+ setIsCustomExtensionDialogOpen(true);+ }}><Plus className="mr-1 size-4" />- Add extension+ Add extension rule</Button><CustomExtensionRuleDialogisOpen={isCustomExtensionDialogOpen}- onOpenChange={setIsCustomExtensionDialogOpen}- usedOids={watchedCustomExtensions.map((extension) => extension.oid)}+ onOpenChange={(open) => {+ setIsCustomExtensionDialogOpen(open);+ if (!open) setEditingCustomExtensionIndex(null);+ }}+ initialRule={+ editingCustomExtensionIndex === null+ ? null+ : (() => {+ const row = watchedCustomExtensions[editingCustomExtensionIndex];+ return {+ oid: row.oid,+ label: row.label ?? "",+ include: row.include,+ critical: row.critical ?? "",+ value: row.value+ };+ })()+ }onConfirm={(rule) => {- setValue("customExtensions", [...watchedCustomExtensions, rule]);+ if (editingCustomExtensionIndex === null) {+ setValue("customExtensions", [...watchedCustomExtensions, rule]);+ } else {+ const next = [...watchedCustomExtensions];+ next[editingCustomExtensionIndex] = rule;+ setValue("customExtensions", next);+ }+ setEditingCustomExtensionIndex(null);clearError("customExtensions");markCustomPreset();}}diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CustomExtensionRuleDialog.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CustomExtensionRuleDialog.tsxindex 4cd6b042fd..cb71154616 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CustomExtensionRuleDialog.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CustomExtensionRuleDialog.tsx@@ -24,8 +24,9 @@ import {import { CustomExtensionOidSelect } from "@app/pages/cert-manager/components/CustomExtensionOidSelect";import {CertExtensionCriticality,- CertExtensionRuleKind,+ CertExtensionInclude,customExtensionLabelFor,+ getPresetExtensionCriticality,isPresetExtensionOid} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";@@ -34,15 +35,15 @@ export const ANY_CRITICALITY = "any";export type TCustomExtensionRuleDraft = {oid: string;label: string;- rule: CertExtensionRuleKind;+ include: CertExtensionInclude;critical: CertExtensionCriticality | "";value: string;};-const RULE_OPTIONS = [- { value: CertExtensionRuleKind.ALLOW, label: "Allow" },- { value: CertExtensionRuleKind.REQUIRE, label: "Require" },- { value: CertExtensionRuleKind.DENY, label: "Deny" }+const INCLUDE_OPTIONS = [+ { value: CertExtensionInclude.ALLOWED, label: "Allowed" },+ { value: CertExtensionInclude.REQUIRED, label: "Required" },+ { value: CertExtensionInclude.DENIED, label: "Denied" }] as const;export const CUSTOM_EXTENSION_CRITICALITY_LABELS: Record<string, string> = {@@ -68,7 +69,7 @@ const OID_PATTERN = /^[0-2](\.(0|[1-9][0-9]{0,14})){1,20}$/;const EMPTY_DRAFT: TCustomExtensionRuleDraft = {oid: "",label: "",- rule: CertExtensionRuleKind.ALLOW,+ include: CertExtensionInclude.ALLOWED,critical: "",value: "*"};@@ -76,20 +77,26 @@ const EMPTY_DRAFT: TCustomExtensionRuleDraft = {type Props = {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;- usedOids: string[];onConfirm: (rule: TCustomExtensionRuleDraft) => void;+ initialRule?: TCustomExtensionRuleDraft | null;};-export const CustomExtensionRuleDialog = ({ isOpen, onOpenChange, usedOids, onConfirm }: Props) => {+export const CustomExtensionRuleDialog = ({+ isOpen,+ onOpenChange,+ onConfirm,+ initialRule+}: Props) => {+ const isEdit = Boolean(initialRule);const [draft, setDraft] = useState<TCustomExtensionRuleDraft>(EMPTY_DRAFT);const [error, setError] = useState<string | null>(null);useEffect(() => {if (isOpen) {- setDraft(EMPTY_DRAFT);+ setDraft(initialRule ?? EMPTY_DRAFT);setError(null);}- }, [isOpen]);+ }, [isOpen, initialRule]);const isPreset = isPresetExtensionOid(draft.oid);@@ -99,10 +106,6 @@ export const CustomExtensionRuleDialog = ({ isOpen, onOpenChange, usedOids, onCosetError("Enter a valid object identifier, for example 1.3.6.1.4.1.311.25.2");return;}- if (usedOids.includes(oid)) {- setError("This policy already has a rule for that object identifier.");- return;- }onConfirm({...draft,oid,@@ -117,9 +120,12 @@ export const CustomExtensionRuleDialog = ({ isOpen, onOpenChange, usedOids, onCo<Dialog open={isOpen} onOpenChange={onOpenChange}><DialogContent className="max-w-lg"><DialogHeader>- <DialogTitle>Add custom extension rule</DialogTitle>+ <DialogTitle>+ {isEdit ? "Edit custom extension rule" : "Add custom extension rule"}+ </DialogTitle><DialogDescription>- Constrain the values certificates may carry for one object identifier.+ Add one value pattern for an object identifier. Add several rules for the same OID to+ accept more than one value.</DialogDescription></DialogHeader><DialogBody className="space-y-4">@@ -160,16 +166,16 @@ export const CustomExtensionRuleDialog = ({ isOpen, onOpenChange, usedOids, onCo<FieldLabel>Rule</FieldLabel><FieldContent><Select- value={draft.rule}+ value={draft.include}onValueChange={(value) =>- setDraft((current) => ({ ...current, rule: value as CertExtensionRuleKind }))+ setDraft((current) => ({ ...current, include: value as CertExtensionInclude }))}><SelectTrigger className="w-full" aria-label="Rule"><SelectValue /></SelectTrigger><SelectContent position="popper">- {RULE_OPTIONS.map((option) => (+ {INCLUDE_OPTIONS.map((option) => (<SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>@@ -183,7 +189,10 @@ export const CustomExtensionRuleDialog = ({ isOpen, onOpenChange, usedOids, onCo<FieldLabel>Criticality</FieldLabel><FieldContent><Select- value={draft.critical || ANY_CRITICALITY}+ value={+ (isPreset ? getPresetExtensionCriticality(draft.oid) : draft.critical) ||+ ANY_CRITICALITY+ }disabled={isPreset}onValueChange={(value) =>setDraft((current) => ({@@ -218,7 +227,7 @@ export const CustomExtensionRuleDialog = ({ isOpen, onOpenChange, usedOids, onCoonChange={(e) => setDraft((current) => ({ ...current, value: e.target.value }))}/><FieldDescription>- Values this rule matches, with * as a wildcard. Use * alone for any value.+ One value this rule matches, with * as a wildcard. Use * alone for any value.</FieldDescription></FieldContent></Field>@@ -228,7 +237,7 @@ export const CustomExtensionRuleDialog = ({ isOpen, onOpenChange, usedOids, onCoCancel</Button><Button type="button" onClick={handleConfirm}>- Add extension+ {isEdit ? "Save rule" : "Add extension"}</Button></DialogFooter></DialogContent>diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.tsindex 40418f31d6..92b6241a13 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts@@ -331,12 +331,18 @@ export const ALGORITHM_FAMILIES = {}} as const;-export enum CertExtensionRuleKind {- ALLOW = "allow",- REQUIRE = "require",- DENY = "deny"+export enum CertExtensionInclude {+ ALLOWED = "allowed",+ REQUIRED = "required",+ DENIED = "denied"}+export const CUSTOM_EXTENSION_INCLUDE_LABELS: Record<CertExtensionInclude, string> = {+ [CertExtensionInclude.ALLOWED]: "Allowed",+ [CertExtensionInclude.REQUIRED]: "Required",+ [CertExtensionInclude.DENIED]: "Denied"+};+export enum CertExtensionCriticality {CRITICAL = "critical",NOT_CRITICAL = "not_critical"@@ -351,17 +357,24 @@ const TEMPLATE_INFORMATION_PATTERN = new RegExp(export const CUSTOM_EXTENSION_PRESETS: Record<string,- { label: string; placeholder: string; validate: (value: string) => string | null }+ {+ label: string;+ placeholder: string;+ critical: boolean;+ validate: (value: string) => string | null;+ }> = {"1.3.6.1.4.1.311.25.2": {+ critical: false,label: "AD SID security extension",placeholder: "S-1-5-21-...",validate: (value) =>SID_PATTERN.test(value)? null- : "Enter a security identifier, for example S-1-5-21-1004336348-1177238915-682003330-1103"+ : "Value must be a security identifier, for example S-1-5-21-1004336348-1177238915-682003330-1103"},"1.3.6.1.4.1.311.20.2": {+ critical: false,label: "Certificate template name",placeholder: "Machine",validate: (value) => {@@ -372,12 +385,13 @@ export const CUSTOM_EXTENSION_PRESETS: Record<}},"1.3.6.1.4.1.311.21.7": {+ critical: false,label: "Certificate template information",placeholder: "1.3.6.1.4.1.311.21.8.1.2:100.3",validate: (value) =>TEMPLATE_INFORMATION_PATTERN.test(value)? null- : "Enter the template OID, a colon, then the version, for example 1.3.6.1.4.1.311.21.8.1.2:100.3"+ : "Value must be the template OID, a colon, then the version, for example 1.3.6.1.4.1.311.21.8.1.2:100.3"}};@@ -386,6 +400,14 @@ const getCustomExtensionPreset = (oid: string) =>? CUSTOM_EXTENSION_PRESETS[oid]: undefined;+export const getPresetExtensionCriticality = (oid: string): CertExtensionCriticality | null => {+ const preset = getCustomExtensionPreset(oid);+ if (!preset) return null;+ return preset.critical+ ? CertExtensionCriticality.CRITICAL+ : CertExtensionCriticality.NOT_CRITICAL;+};+export const isPresetExtensionOid = (oid: string) => Boolean(getCustomExtensionPreset(oid));export const customExtensionLabelFor = (oid: string, label?: string | null) =>@@ -401,3 +423,44 @@ export const validateCustomExtensionValue = (oid: string, value: string): stringexport const getCustomExtensionValuePlaceholder = (oid: string) =>getCustomExtensionPreset(oid)?.placeholder ?? "Value";++export type TCustomExtensionRow = {+ oid: string;+ label?: string;+ critical?: CertExtensionCriticality | "";+ include: CertExtensionInclude;+ value: string;+};++export const groupCustomExtensionRows = (rows?: TCustomExtensionRow[] | null) => {+ const byOid = new Map<+ string,+ {+ oid: string;+ label?: string;+ critical?: CertExtensionCriticality;+ allowed: string[];+ required: string[];+ denied: string[];+ }+ >();++ (rows ?? [])+ .filter((row) => row.oid.trim())+ .forEach((row) => {+ const oid = row.oid.trim();+ const existing = byOid.get(oid) ?? { oid, allowed: [], required: [], denied: [] };+ const label = row.label?.trim();+ if (label) existing.label = label;+ if (row.critical) existing.critical = row.critical;+ existing[row.include].push(row.value.trim() || "*");+ byOid.set(oid, existing);+ });++ return [...byOid.values()].map(({ allowed, required, denied, ...rest }) => ({+ ...rest,+ ...(allowed.length && { allowed }),+ ...(required.length && { required }),+ ...(denied.length && { denied })+ }));+};diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/schemas.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/schemas.tsindex aa91340c7e..5c7e77fde5 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/schemas.ts+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/schemas.ts@@ -4,7 +4,7 @@ import {CertDurationUnit,CertExtendedKeyUsageType,CertExtensionCriticality,- CertExtensionRuleKind,+ CertExtensionInclude,CertKeyUsageType,CertPolicyState,CertSanInclude,@@ -78,7 +78,7 @@ export const uiCustomExtensionSchema = z.object({oid: z.string().trim(),label: z.string().trim().max(64).optional(),critical: z.union([z.literal(""), z.nativeEnum(CertExtensionCriticality)]).optional(),- rule: z.nativeEnum(CertExtensionRuleKind),+ include: z.nativeEnum(CertExtensionInclude),value: z.string().trim()});diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/CustomExtensionDefaults.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/CustomExtensionDefaults.tsxindex 4155efc2ad..e1dc2c763d 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/CustomExtensionDefaults.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/CustomExtensionDefaults.tsx@@ -2,13 +2,17 @@ import { Plus, Trash2 } from "lucide-react";import {Button,+ Checkbox,IconButton,Input,Select,SelectContent,SelectItem,SelectTrigger,- SelectValue+ SelectValue,+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@app/components/v3";import { TProfileCustomExtension } from "@app/hooks/api/certificateProfiles/types";import { CustomExtensionOidSelect } from "@app/pages/cert-manager/components/CustomExtensionOidSelect";@@ -17,7 +21,8 @@ import {CertExtensionCriticality,customExtensionLabelFor,getCustomExtensionValuePlaceholder,- isPresetExtensionOid+ isPresetExtensionOid,+ validateCustomExtensionValue} from "../../CertificatePoliciesTab/shared/certificate-constants";import { SectionHeading } from "./SectionHeading";@@ -54,6 +59,19 @@ export const CustomExtensionDefaults = ({const criticalityPinnedFor = (oid: string) =>allowedCustomExtensions?.find((rule) => rule.oid === oid)?.critical;+ const allSelectableOidsUsed = Boolean(+ selectableOids?.length &&+ selectableOids.every((oid) => extensions.some((extension) => extension.oid === oid))+ );++ const takenOidsExcept = (index: number) =>+ new Set(+ extensions+ .filter((_, i) => i !== index)+ .map((extension) => extension.oid)+ .filter(Boolean)+ );+const declarationFor = (oid: string): TProfileCustomExtension => {const pinned = criticalityPinnedFor(oid);return { oid, critical: pinned ? pinned === CertExtensionCriticality.CRITICAL : false };@@ -63,7 +81,7 @@ export const CustomExtensionDefaults = ({<div><SectionHeadingtitle="Custom Extensions"- description="Declare the custom X.509 extensions certificates from this profile may carry. Leave a value empty to have the request supply it."+ description="Declare the custom X.509 extensions certificates from this profile may carry."/><div className="mt-4 space-y-3">{isDisabled && (@@ -82,70 +100,93 @@ export const CustomExtensionDefaults = ({const isPreset = isPresetExtensionOid(extension.oid);const placeholder = getCustomExtensionValuePlaceholder(extension.oid);const criticalityPinned = criticalityPinnedFor(extension.oid);+ const criticalityLocked = isPreset || Boolean(criticalityPinned);+ const isCritical = criticalityPinned+ ? criticalityPinned === CertExtensionCriticality.CRITICAL+ : Boolean(extension.critical);+ const valueError =+ extension.oid && extension.value+ ? validateCustomExtensionValue(extension.oid, extension.value)+ : null;++ const criticalityCheckbox = (+ <Checkbox+ variant="project"+ isChecked={isCritical}+ isDisabled={criticalityLocked}+ aria-label="Critical"+ onCheckedChange={(checked) => update(index, { critical: checked === true })}+ />+ );return (<div// eslint-disable-next-line react/no-array-index-keykey={`profile-extension-${index}`}- className="flex items-start gap-2"+ className="flex items-start gap-3">{selectableOids ? (<Selectvalue={extension.oid || undefined}onValueChange={(oid) => replace(index, declarationFor(oid))}>- <SelectTrigger className="min-w-0 flex-[2]">+ <SelectTrigger className="min-w-0 flex-[3]" aria-label="Extension"><SelectValue placeholder="Select an extension" /></SelectTrigger><SelectContent position="popper">- {selectableOids.map((oid) => (- <SelectItem key={oid} value={oid}>- {customExtensionLabelFor(- oid,- allowedCustomExtensions?.find((rule) => rule.oid === oid)?.label- )}- </SelectItem>- ))}+ {selectableOids+ .filter((oid) => !takenOidsExcept(index).has(oid))+ .map((oid) => (+ <SelectItem key={oid} value={oid}>+ {customExtensionLabelFor(+ oid,+ allowedCustomExtensions?.find((rule) => rule.oid === oid)?.label+ )}+ </SelectItem>+ ))}</SelectContent></Select>) : (<CustomExtensionOidSelect- className="min-w-0 flex-[2]"+ className="min-w-0 flex-[3]"placeholder="Select OID"value={extension.oid}+ excludeOids={[...takenOidsExcept(index)]}onChange={(oid) => replace(index, declarationFor(oid))}/>)}- <Select- value={- (criticalityPinned ??- (extension.critical- ? CertExtensionCriticality.CRITICAL- : CertExtensionCriticality.NOT_CRITICAL)) as CertExtensionCriticality- }- disabled={isPreset || Boolean(criticalityPinned)}- onValueChange={(value) =>- update(index, { critical: value === CertExtensionCriticality.CRITICAL })- }- >- <SelectTrigger className="w-28 shrink-0" aria-label="Criticality">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={CertExtensionCriticality.NOT_CRITICAL}>- Not critical- </SelectItem>- <SelectItem value={CertExtensionCriticality.CRITICAL}>Critical</SelectItem>- </SelectContent>- </Select>-- <Input- className="min-w-0 flex-1"- placeholder={placeholder}- value={extension.value ?? ""}- onChange={(e) => update(index, { value: e.target.value })}- />+ <div className="min-w-0 flex-[4]">+ <Input+ className="w-full"+ placeholder={placeholder}+ value={extension.value ?? ""}+ isError={Boolean(valueError)}+ onChange={(e) => update(index, { value: e.target.value })}+ />+ {valueError && <p className="mt-1 text-xs text-danger">{valueError}</p>}+ </div>++ <div className="flex h-9 shrink-0 items-center gap-2">+ {criticalityLocked ? (+ <Tooltip>+ <TooltipTrigger asChild>+ {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}+ <span tabIndex={0} className="flex items-center">+ {criticalityCheckbox}+ </span>+ </TooltipTrigger>+ <TooltipContent side="top" className="max-w-64">+ {isPreset+ ? "Criticality is fixed for this extension because Active Directory rejects certificates that mark it differently."+ : "The certificate policy pins the criticality for this object identifier."}+ </TooltipContent>+ </Tooltip>+ ) : (+ criticalityCheckbox+ )}+ <span className="text-sm whitespace-nowrap text-muted">Critical</span>+ </div><IconButtontype="button"@@ -163,14 +204,20 @@ export const CustomExtensionDefaults = ({type="button"variant="outline"size="sm"+ isDisabled={allSelectableOidsUsed}onClick={() => {const taken = new Set(extensions.map((extension) => extension.oid));const nextOid = selectableOids?.find((oid) => !taken.has(oid)) ?? "";onChange([...extensions, declarationFor(nextOid)]);}}>- <Plus className="size-4" /> Declare extension+ <Plus className="size-4" /> Add extension</Button>+ {allSelectableOidsUsed && (+ <p className="text-xs text-muted">+ Every extension this policy allows is already declared.+ </p>+ )}</>)}</div>diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/ProfileDefaultsStep.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/ProfileDefaultsStep.tsxindex b72c20798b..a593ed655b 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/ProfileDefaultsStep.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/ProfileDefaultsStep.tsx@@ -376,14 +376,6 @@ export const ProfileDefaultsStep = ({/>)}- {caSupportsCustomExtensions && (- <CustomExtensionDefaults- allowedCustomExtensions={policyConstraints.allowedCustomExtensions}- extensions={watchedCustomExtensions}- onChange={(next) => setValue("defaults.customExtensions", next)}- />- )}-{policyConstraints.shouldShowSanSection && (<AttributeListEditor<CertSubjectAlternativeNameType>title="Subject Alternative Names"@@ -595,6 +587,13 @@ export const ProfileDefaultsStep = ({</div></div>)}+ {caSupportsCustomExtensions && (+ <CustomExtensionDefaults+ allowedCustomExtensions={policyConstraints.allowedCustomExtensions}+ extensions={watchedCustomExtensions}+ onChange={(next) => setValue("defaults.customExtensions", next)}+ />+ )}</div>);};diff --git a/frontend/src/pages/cert-manager/components/CustomExtensionList.tsx b/frontend/src/pages/cert-manager/components/CustomExtensionList.tsxindex 47e5a94de8..2594e5e84e 100644--- a/frontend/src/pages/cert-manager/components/CustomExtensionList.tsx+++ b/frontend/src/pages/cert-manager/components/CustomExtensionList.tsx@@ -30,11 +30,23 @@ export const CustomExtensionList = ({ extensions }: Props) => {<Badge variant="outline" isTruncatable><span>{value}</span></Badge>+ {extension.critical && (+ <Badge variant="warning" className="shrink-0">+ <span>Critical</span>+ </Badge>+ )}</ButtonGroup>) : (- <Badge key={extension.oid} isTruncatable>- <span>{label}</span>- </Badge>+ <ButtonGroup className="max-w-full min-w-0" key={extension.oid}>+ <Badge isTruncatable>+ <span>{label}</span>+ </Badge>+ {extension.critical && (+ <Badge variant="warning" className="shrink-0">+ <span>Critical</span>+ </Badge>+ )}+ </ButtonGroup>);})}</div>diff --git a/frontend/src/pages/cert-manager/components/CustomExtensionOidSelect.tsx b/frontend/src/pages/cert-manager/components/CustomExtensionOidSelect.tsxindex 65d31bd2f4..25a17fee24 100644--- a/frontend/src/pages/cert-manager/components/CustomExtensionOidSelect.tsx+++ b/frontend/src/pages/cert-manager/components/CustomExtensionOidSelect.tsx@@ -17,6 +17,7 @@ type Props = {className?: string;placeholder?: string;extraOptions?: TOidOption[];+ excludeOids?: string[];};export const CustomExtensionOidSelect = ({@@ -25,7 +26,8 @@ export const CustomExtensionOidSelect = ({isError,className,placeholder = "Select or enter an OID",- extraOptions+ extraOptions,+ excludeOids}: Props) => {const [typed, setTyped] = useState("");@@ -39,10 +41,18 @@ export const CustomExtensionOidSelect = ({}, [extraOptions]);const options = useMemo(() => {+ const excluded = new Set((excludeOids ?? []).filter((oid) => oid !== value));+ const selectable = knownOptions.filter((option) => !excluded.has(option.oid));const candidate = typed.trim();- if (!candidate || knownOptions.some((option) => option.oid === candidate)) return knownOptions;- return [{ oid: candidate, isCustom: true }, ...knownOptions];- }, [knownOptions, typed]);+ if (+ !candidate ||+ excluded.has(candidate) ||+ selectable.some((option) => option.oid === candidate)+ ) {+ return selectable;+ }+ return [{ oid: candidate, isCustom: true }, ...selectable];+ }, [knownOptions, typed, excludeOids, value]);const selected = useMemo(() => {if (!value) return null;@@ -58,9 +68,22 @@ export const CustomExtensionOidSelect = ({emptyMessage="Enter an OID"options={options}value={selected}- onValueChange={(option) => onChange(option.oid)}- onClear={() => onChange("")}+ onValueChange={(option) => {+ setTyped("");+ onChange(option.oid);+ }}+ onClear={() => {+ setTyped("");+ onChange("");+ }}onInput={(event) => setTyped(event.currentTarget.value)}+ onBlur={() => {+ const candidate = typed.trim();+ setTyped("");+ if (!candidate || candidate === value) return;+ if ((excludeOids ?? []).includes(candidate)) return;+ onChange(candidate);+ }}getOptionValue={(option) => option.oid}getOptionLabel={(option) => option.oid}getOptionKeywords={(option) => (option.name ? [option.name] : [])}