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
fix(pki): enforce domain component order in certificate policies
Carlos Monastyrskidd583203476f
diff --git a/backend/e2e-test/db/rewrite-json-column.spec.ts b/backend/e2e-test/db/rewrite-json-column.spec.tsnew file mode 100644index 0000000000..77d3f99327--- /dev/null+++ b/backend/e2e-test/db/rewrite-json-column.spec.ts@@ -0,0 +1,107 @@+import { Knex } from "knex";++import { rewriteJsonColumnInBatches } from "@app/db/migrations/utils/rewrite-json-column";++const getDb = () => (globalThis as unknown as { testDb: Knex }).testDb;++type TPayload = { flat?: string[]; nested?: string[][]; done?: boolean };++const seed = async (table: string, idColumnType: string, count: number, makeId?: (index: number) => string) => {+ const db = getDb();+ await db.raw(`drop table if exists ${table}`);+ await db.raw(`create table ${table} (id ${idColumnType}, payload jsonb)`);+ await db(table).insert(+ Array.from({ length: count }, (_, index) => ({+ ...(makeId ? { id: makeId(index) } : {}),+ payload: JSON.stringify(index % 2 === 0 ? { flat: ["corp", "example", "com"] } : { done: true })+ }))+ );+};++const rewriteFlatToNested = async (table: string, batchSize: number) => {+ const visited: string[] = [];+ const rewrittenCount = await rewriteJsonColumnInBatches<TPayload>({+ knex: getDb(),+ table,+ column: "payload",+ batchSize,+ // the filter stops matching a row once it is rewritten, so the cursor cannot rely on it+ narrow: (query) => void query.whereRaw(`payload::text like '%flat%'`),+ rewrite: (value, row) => {+ visited.push(row.id);+ return value.flat ? { nested: [value.flat] } : undefined;+ }+ });++ const rows = await getDb()(table).select("id", "payload");+ return {+ rewrittenCount,+ visited,+ nested: rows.filter((row) => (row.payload as TPayload).nested).length,+ stillFlat: rows.filter((row) => (row.payload as TPayload).flat).length,+ untouched: rows.filter((row) => (row.payload as TPayload).done).length,+ total: rows.length+ };+};++describe("rewriteJsonColumnInBatches", async () => {+ const tables = ["zz_rewrite_uuid", "zz_rewrite_text", "zz_rewrite_multiple", "zz_rewrite_none"];++ afterAll(async () => {+ for (const table of tables) {+ // eslint-disable-next-line no-await-in-loop+ await getDb().raw(`drop table if exists ${table}`);+ }+ });++ test("rewrites every matching row exactly once across batches", async () => {+ await seed("zz_rewrite_uuid", "uuid primary key default gen_random_uuid()", 25);++ const result = await rewriteFlatToNested("zz_rewrite_uuid", 4);++ expect(result.rewrittenCount).toBe(13);+ expect(result.nested).toBe(13);+ expect(result.stillFlat).toBe(0);+ expect(result.untouched).toBe(12);+ expect(result.total).toBe(25);+ expect(new Set(result.visited).size).toBe(result.visited.length);+ });++ test("paginates a varchar id column the same way", async () => {+ await seed("zz_rewrite_text", "varchar primary key", 25, (index) => `id-${String(index).padStart(3, "0")}`);++ const result = await rewriteFlatToNested("zz_rewrite_text", 4);++ expect(result.rewrittenCount).toBe(13);+ expect(result.stillFlat).toBe(0);+ expect(new Set(result.visited).size).toBe(result.visited.length);+ });++ test("terminates when the matching rows are an exact multiple of the batch size", async () => {+ await seed("zz_rewrite_multiple", "uuid primary key default gen_random_uuid()", 24);++ const result = await rewriteFlatToNested("zz_rewrite_multiple", 4);++ expect(result.rewrittenCount).toBe(12);+ expect(result.stillFlat).toBe(0);+ });++ test("does not call rewrite when the filter matches nothing", async () => {+ const db = getDb();+ await db.raw(`drop table if exists zz_rewrite_none`);+ await db.raw(`create table zz_rewrite_none (id uuid primary key default gen_random_uuid(), payload jsonb)`);+ await db("zz_rewrite_none").insert([{ payload: JSON.stringify({ done: true }) }]);++ const rewrittenCount = await rewriteJsonColumnInBatches<TPayload>({+ knex: db,+ table: "zz_rewrite_none",+ column: "payload",+ narrow: (query) => void query.whereRaw(`payload::text like '%flat%'`),+ rewrite: () => {+ throw new Error("rewrite must not be called");+ }+ });++ expect(rewrittenCount).toBe(0);+ });+});diff --git a/backend/e2e-test/routes/v1/certificate-policy-domain-components.spec.ts b/backend/e2e-test/routes/v1/certificate-policy-domain-components.spec.tsnew file mode 100644index 0000000000..1f7862a9ae--- /dev/null+++ b/backend/e2e-test/routes/v1/certificate-policy-domain-components.spec.ts@@ -0,0 +1,179 @@+import { ProjectType } from "@app/db/schemas";++const CERT_MANAGER_PROJECT_SLUG = "dc-order-policies";++type TSubjectRule = {+ type: string;+ allowed?: unknown;+ required?: unknown;+ denied?: unknown;+};++let projectId = "";++const createProject = async () => {+ const res = await testServer.inject({+ method: "POST",+ url: "/api/v1/projects",+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: {+ projectName: "DC order policies",+ slug: CERT_MANAGER_PROJECT_SLUG,+ type: ProjectType.CertificateManager+ }+ });++ expect(res.statusCode).toBe(200);+ return (JSON.parse(res.payload) as { project: { id: string } }).project.id;+};++const createPolicy = async (name: string, subject: TSubjectRule[]) =>+ testServer.inject({+ method: "POST",+ url: "/api/v1/cert-manager/certificate-policies",+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: { projectId, name, subject }+ });++const getPolicy = async (policyId: string) =>+ testServer.inject({+ method: "GET",+ url: `/api/v1/cert-manager/certificate-policies/${policyId}?projectId=${projectId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });++const subjectOf = (payload: string) =>+ (JSON.parse(payload) as { certificatePolicy: { subject: TSubjectRule[] } }).certificatePolicy.subject;++const domainComponentRule = (subject: TSubjectRule[]) => subject.find((rule) => rule.type === "domain_component");++describe("Certificate policy domain component rules", async () => {+ const createdPolicyIds: string[] = [];++ beforeAll(async () => {+ projectId = await createProject();+ });++ afterAll(async () => {+ for (const policyId of createdPolicyIds) {+ // eslint-disable-next-line no-await-in-loop+ await testServer.inject({+ method: "DELETE",+ url: `/api/v1/cert-manager/certificate-policies/${policyId}?projectId=${projectId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });+ }++ await testServer.inject({+ method: "DELETE",+ url: `/api/v1/projects/${projectId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });+ });++ const trackPolicy = (payload: string) => {+ const { certificatePolicy } = JSON.parse(payload) as { certificatePolicy: { id: string } };+ createdPolicyIds.push(certificatePolicy.id);+ return certificatePolicy.id;+ };++ test("stores ordered sequences as given", async () => {+ const res = await createPolicy("dc-sequences", [+ {+ type: "domain_component",+ allowed: [+ ["corp", "example", "com"],+ ["*", "internal", "example", "com"]+ ],+ denied: [["evil", "example", "com"]]+ }+ ]);++ expect(res.statusCode).toBe(200);+ const policyId = trackPolicy(res.payload);++ const read = await getPolicy(policyId);+ expect(read.statusCode).toBe(200);+ expect(domainComponentRule(subjectOf(read.payload))).toEqual({+ type: "domain_component",+ allowed: [+ ["corp", "example", "com"],+ ["*", "internal", "example", "com"]+ ],+ denied: [["evil", "example", "com"]]+ });+ });++ test("reads a flat label list as the single sequence it describes", async () => {+ const res = await createPolicy("dc-flat-list", [{ type: "domain_component", allowed: ["corp", "example", "com"] }]);++ expect(res.statusCode).toBe(200);+ const policyId = trackPolicy(res.payload);++ expect(domainComponentRule(subjectOf(res.payload))?.allowed).toEqual([["corp", "example", "com"]]);++ const read = await getPolicy(policyId);+ expect(domainComponentRule(subjectOf(read.payload))?.allowed).toEqual([["corp", "example", "com"]]);+ });++ test("leaves the rules of other subject attributes flat", async () => {+ const res = await createPolicy("dc-other-attributes", [+ { type: "common_name", allowed: ["*.example.com"], denied: ["admin.example.com"] },+ { type: "domain_component", required: [["corp", "example", "com"]] }+ ]);++ expect(res.statusCode).toBe(200);+ trackPolicy(res.payload);++ const subject = subjectOf(res.payload);+ expect(subject.find((rule) => rule.type === "common_name")).toEqual({+ type: "common_name",+ allowed: ["*.example.com"],+ denied: ["admin.example.com"]+ });+ expect(domainComponentRule(subject)?.required).toEqual([["corp", "example", "com"]]);+ });++ test("updates a rule from one sequence to several", async () => {+ const created = await createPolicy("dc-update", [+ { type: "domain_component", allowed: ["corp", "example", "com"] }+ ]);+ expect(created.statusCode).toBe(200);+ const policyId = trackPolicy(created.payload);++ const updated = await testServer.inject({+ method: "PATCH",+ url: `/api/v1/cert-manager/certificate-policies/${policyId}?projectId=${projectId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: {+ subject: [+ {+ type: "domain_component",+ allowed: [+ ["corp", "example", "com"],+ ["example", "com"]+ ]+ }+ ]+ }+ });++ expect(updated.statusCode).toBe(200);+ expect(domainComponentRule(subjectOf(updated.payload))?.allowed).toEqual([+ ["corp", "example", "com"],+ ["example", "com"]+ ]);+ });++ test.each([+ ["a value list mixing labels and sequences", ["corp", ["example", "com"]]],+ ["an empty component", [["corp", ""]]],+ ["a component holding the separator", [["corp,example", "com"]]]+ ])("rejects %s", async (_label, allowed) => {+ const res = await createPolicy(`dc-invalid-${_label.replace(/[^a-z]/g, "")}`, [+ { type: "domain_component", allowed }+ ]);++ expect(res.statusCode).toBe(422);+ });+});diff --git a/backend/src/db/migrations/20260805143012_certificate-policy-domain-component-sequences.ts b/backend/src/db/migrations/20260805143012_certificate-policy-domain-component-sequences.tsnew file mode 100644index 0000000000..dbbaf727ae--- /dev/null+++ b/backend/src/db/migrations/20260805143012_certificate-policy-domain-component-sequences.ts@@ -0,0 +1,79 @@+import { Knex } from "knex";++import { initLogger, logger } from "@app/lib/logger";++import { TableName } from "../schemas";+import { rewriteJsonColumnInBatches } from "./utils/rewrite-json-column";++const DOMAIN_COMPONENT_ATTRIBUTE_TYPE = "domain_component";+const RULE_FIELDS = ["allowed", "required", "denied"] as const;++type TStoredSubjectRule = {+ type?: string;+ allowed?: unknown;+ required?: unknown;+ denied?: unknown;+};++const isFlatLabelList = (values: unknown): values is string[] =>+ Array.isArray(values) && values.length > 0 && values.every((value) => typeof value === "string");++const isSingleSequence = (values: unknown): values is [string[]] =>+ Array.isArray(values) && values.length === 1 && isFlatLabelList(values[0]);++const rewriteDomainComponentRule =+ (rewriteField: (values: unknown) => string[] | string[][] | undefined) =>+ (subject: TStoredSubjectRule[]): TStoredSubjectRule[] | undefined => {+ if (!Array.isArray(subject)) return undefined;++ let changed = false;+ const rewrittenRules = subject.map((rule) => {+ if (rule?.type !== DOMAIN_COMPONENT_ATTRIBUTE_TYPE) return rule;++ const rewrittenRule = { ...rule };+ for (const field of RULE_FIELDS) {+ const rewritten = rewriteField(rewrittenRule[field]);+ if (rewritten !== undefined) {+ rewrittenRule[field] = rewritten;+ changed = true;+ }+ }+ return rewrittenRule;+ });++ return changed ? rewrittenRules : undefined;+ };++const narrowToDomainComponentPolicies = (query: Knex.QueryBuilder) => {+ void query.whereNotNull("subject").whereRaw(`subject::text LIKE ?`, [`%${DOMAIN_COMPONENT_ATTRIBUTE_TYPE}%`]);+};++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.PkiCertificatePolicy))) return;++ initLogger();++ const migratedCount = await rewriteJsonColumnInBatches<TStoredSubjectRule[]>({+ knex,+ table: TableName.PkiCertificatePolicy,+ column: "subject",+ narrow: narrowToDomainComponentPolicies,+ rewrite: rewriteDomainComponentRule((values) => (isFlatLabelList(values) ? [values] : undefined))+ });++ if (migratedCount) {+ logger.info(`Migrated certificate policy domain component rules to ordered sequences [count=${migratedCount}]`);+ }+}++export async function down(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.PkiCertificatePolicy))) return;++ await rewriteJsonColumnInBatches<TStoredSubjectRule[]>({+ knex,+ table: TableName.PkiCertificatePolicy,+ column: "subject",+ narrow: narrowToDomainComponentPolicies,+ rewrite: rewriteDomainComponentRule((values) => (isSingleSequence(values) ? values[0] : undefined))+ });+}diff --git a/backend/src/db/migrations/utils/rewrite-json-column.ts b/backend/src/db/migrations/utils/rewrite-json-column.tsnew file mode 100644index 0000000000..3374fc85b7--- /dev/null+++ b/backend/src/db/migrations/utils/rewrite-json-column.ts@@ -0,0 +1,60 @@+import { Knex } from "knex";++const DEFAULT_BATCH_SIZE = 500;++/**+ * Rewrites a JSON column in keyset-paginated batches. Prefer a set-based UPDATE when the transform can+ * be expressed in SQL. `rewrite` returns the new value for a row, or undefined to skip it. Requires a+ * unique, sortable `id` column.+ */+export const rewriteJsonColumnInBatches = async <TValue>({+ knex,+ table,+ column,+ rewrite,+ narrow,+ batchSize = DEFAULT_BATCH_SIZE+}: {+ knex: Knex;+ table: string;+ column: string;+ rewrite: (value: TValue, row: { id: string }) => TValue | undefined;+ narrow?: (query: Knex.QueryBuilder) => void;+ batchSize?: number;+}): Promise<number> => {+ let cursor: string | null = null;+ let rewrittenCount = 0;++ for (;;) {+ const query = knex(table).select("id", column).orderBy("id", "asc").limit(batchSize);+ if (narrow) narrow(query);+ if (cursor) void query.where("id", ">", cursor);++ // eslint-disable-next-line no-await-in-loop+ const rows = (await query) as ({ id: string } & Record<string, TValue>)[];+ if (rows.length === 0) break;+ cursor = rows[rows.length - 1].id;++ const updates: { id: string; value: TValue }[] = [];+ for (const row of rows) {+ const rewritten = rewrite(row[column], row);+ if (rewritten !== undefined) updates.push({ id: row.id, value: rewritten });+ }++ if (updates.length > 0) {+ // eslint-disable-next-line no-await-in-loop+ await Promise.all(+ updates.map((update) =>+ knex(table)+ .where({ id: update.id })+ .update({ [column]: JSON.stringify(update.value) })+ )+ );+ rewrittenCount += updates.length;+ }++ if (rows.length < batchSize) break;+ }++ return rewrittenCount;+};diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 33907cde81..e0d645f405 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -2124,6 +2124,17 @@ export const CERTIFICATES = {}};+const domainComponentRule = (rule: string) =>+ `Domain component sequences that are ${rule}, each ordered as the distinguished name reads it, most specific component first: [["*", "example", "com"]] matches DC=host,DC=example,DC=com. A request matches a sequence only when its components line up position by position, so the same labels in another order do not match. A flat list of labels is read as the single sequence it describes.`;++export const CERTIFICATE_POLICIES = {+ SUBJECT_DOMAIN_COMPONENT_RULE: {+ allowed: domainComponentRule("permitted"),+ required: domainComponentRule("required"),+ denied: domainComponentRule("rejected")+ }+};+export const CERTIFICATE_TEMPLATES = {CREATE: {caId: "The ID of the certificate authority to associate the template with.",diff --git a/backend/src/server/routes/v1/certificate-policy-router.ts b/backend/src/server/routes/v1/certificate-policy-router.tsindex 47b3f6053a..d499fa2cc6 100644--- a/backend/src/server/routes/v1/certificate-policy-router.ts+++ b/backend/src/server/routes/v1/certificate-policy-router.ts@@ -13,34 +13,16 @@ import {CertKeyUsageType,CertPolicyState,CertSubjectAlternativeNameType,- CertSubjectAttributeType,pkiDescriptionSchema} from "@app/services/certificate-common/certificate-constants";-import { certificatePolicyResponseSchema } from "@app/services/certificate-policy/certificate-policy-schemas";+import {+ certificatePolicyResponseSchema,+ policySubjectSchema+} from "@app/services/certificate-policy/certificate-policy-schemas";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";-const attributeTypeSchema = z.nativeEnum(CertSubjectAttributeType);const sanTypeSchema = z.nativeEnum(CertSubjectAlternativeNameType);-const policySubjectSchema = z- .object({- type: attributeTypeSchema,- allowed: z.array(z.string()).optional(),- required: z.array(z.string()).optional(),- denied: z.array(z.string()).optional()- })- .refine(- (data) => {- if (!data.allowed && !data.required && !data.denied) {- return false;- }- return true;- },- {- message: "Subject attribute must have at least one allowed, required, or denied value"- }- );-const policyKeyUsagesSchema = z.object({allowed: z.array(z.nativeEnum(CertKeyUsageType)).optional(),diff --git a/backend/src/services/certificate-authority/certificate-authority-fns.test.ts b/backend/src/services/certificate-authority/certificate-authority-fns.test.tsindex fa792763de..52602184f6 100644--- a/backend/src/services/certificate-authority/certificate-authority-fns.test.ts+++ b/backend/src/services/certificate-authority/certificate-authority-fns.test.ts@@ -1,3 +1,4 @@+import * as x509 from "@peculiar/x509";import { describe, expect, it } from "vitest";import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";@@ -5,6 +6,7 @@ import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";import {buildCrlDistributionPointUrls,createDistinguishedName,+ extractDnParts,signatureAlgorithmToAlgCfg} from "./certificate-authority-fns";@@ -248,12 +250,12 @@ describe("createDistinguishedName", () => {expect(dn).toBe("O=Acme, CN=example.com");});- it("should emit one DC RDN per domain component, in the given order, after the CN", () => {+ it("should encode the domain component chain root first, ahead of the other attributes", () => {const dn = createDistinguishedName({commonName: "auth-AD-MANAGER02-CA",domainComponents: ["app", "example", "auth"]});- expect(dn).toBe("CN=auth-AD-MANAGER02-CA, DC=app, DC=example, DC=auth");+ expect(dn).toBe("DC=auth, DC=example, DC=app, CN=auth-AD-MANAGER02-CA");});it("should skip empty domain component values", () => {@@ -261,7 +263,7 @@ describe("createDistinguishedName", () => {commonName: "host",domainComponents: ["app", "", "auth"]});- expect(dn).toBe("CN=host, DC=app, DC=auth");+ expect(dn).toBe("DC=auth, DC=app, CN=host");});it("should omit DC RDNs when no domain components are provided", () => {@@ -269,3 +271,47 @@ describe("createDistinguishedName", () => {expect(dn).toBe("CN=host");});});++describe("extractDnParts", () => {+ const parse = (dn: string) => extractDnParts(new x509.Name(dn));++ it("should read a root-first chain in display order", () => {+ expect(parse("DC=com, DC=example, DC=corp, CN=host").domainComponents).toEqual(["corp", "example", "com"]);+ });++ it("should read a forward-encoded chain in display order", () => {+ expect(parse("CN=host, DC=corp, DC=example, DC=com").domainComponents).toEqual(["corp", "example", "com"]);+ });++ it("should read a chain carrying no other attributes as root first", () => {+ expect(parse("DC=com, DC=example, DC=corp").domainComponents).toEqual(["corp", "example", "com"]);+ });++ it("should read a chain sitting before the organization attributes as root first", () => {+ expect(parse("DC=com, DC=corp, O=Acme, OU=Eng").domainComponents).toEqual(["corp", "com"]);+ });++ it("should read a single component the same either way", () => {+ expect(parse("DC=com, CN=host").domainComponents).toEqual(["com"]);+ expect(parse("CN=host, DC=com").domainComponents).toEqual(["com"]);+ });++ it("should round-trip a chain through createDistinguishedName", () => {+ const domainComponents = ["corp", "example", "com"];+ expect(parse(createDistinguishedName({ commonName: "host", domainComponents })).domainComponents).toEqual(+ domainComponents+ );+ });++ it("should leave domain components undefined when the DN carries none", () => {+ expect(parse("CN=host, O=Acme").domainComponents).toBeUndefined();+ });++ it("should read the remaining attributes alongside the chain", () => {+ const parts = parse("DC=com, DC=corp, O=Acme, OU=Eng, CN=host");+ expect(parts.commonName).toBe("host");+ expect(parts.organization).toBe("Acme");+ expect(parts.ou).toBe("Eng");+ expect(parts.domainComponents).toEqual(["corp", "com"]);+ });+});diff --git a/backend/src/services/certificate-authority/certificate-authority-fns.ts b/backend/src/services/certificate-authority/certificate-authority-fns.tsindex 47e2957045..3db82cd76a 100644--- a/backend/src/services/certificate-authority/certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/certificate-authority-fns.ts@@ -50,18 +50,18 @@ export const assertCaInProfileProject = (ca: { projectId: string }, profile: { pexport const createDistinguishedName = (parts: TDNParts) => {// Build JSON array for x509.Name - the library handles all RFC 4514 escapingconst jsonName: Array<{ [type: string]: string[] }> = [];++ if (parts.domainComponents) {+ for (const dc of [...parts.domainComponents].reverse()) {+ if (dc) jsonName.push({ DC: [dc] });+ }+ }if (parts.country) jsonName.push({ C: [parts.country] });if (parts.organization) jsonName.push({ O: [parts.organization] });if (parts.ou) jsonName.push({ OU: [parts.ou] });if (parts.province) jsonName.push({ ST: [parts.province] });if (parts.commonName) jsonName.push({ CN: [parts.commonName] });if (parts.locality) jsonName.push({ L: [parts.locality] });- // DC is multi-valued and ordered; emit one RDN per value in the given order (after CN, AD-style).- if (parts.domainComponents) {- for (const dc of parts.domainComponents) {- if (dc) jsonName.push({ DC: [dc] });- }- }// Create Name object from JSON and convert to properly escaped stringconst name = new x509.Name(jsonName);@@ -78,13 +78,38 @@ const getNameField = (name: x509.Name, field: string): string | undefined => {return values.length > 0 ? values[values.length - 1] : undefined;};+const DOMAIN_COMPONENT_RDN_KEYS = new Set(["DC", "0.9.2342.19200300.100.1.25"]);++/** Reads a DC chain in display order, whichever direction the DN encoded it in. */+const extractDomainComponentsInDisplayOrder = (name: x509.Name): string[] | undefined => {+ const rdns = name.toJSON();+ const domainComponents: string[] = [];+ let lastDomainComponentIndex = -1;+ let lastOtherAttributeIndex = -1;++ rdns.forEach((rdn, index) => {+ const isDomainComponent = Object.keys(rdn).some((key) => DOMAIN_COMPONENT_RDN_KEYS.has(key));+ if (isDomainComponent) {+ lastDomainComponentIndex = index;+ Object.entries(rdn).forEach(([key, values]) => {+ if (DOMAIN_COMPONENT_RDN_KEYS.has(key)) domainComponents.push(...values);+ });+ } else {+ lastOtherAttributeIndex = index;+ }+ });++ if (domainComponents.length === 0) return undefined;++ const isEncodedRootFirst = lastOtherAttributeIndex === -1 || lastDomainComponentIndex < lastOtherAttributeIndex;+ return isEncodedRootFirst ? domainComponents.reverse() : domainComponents;+};+/*** Extract DN parts directly from an x509 Name object.* This is the preferred method as it uses the library's built-in RFC 4514 parsing.*/export const extractDnParts = (name: x509.Name): TDNParts => {- // DC is multi-valued (ordered); keep all values rather than the last-wins single-value helper.- const domainComponents = name.getField("DC");return {country: getNameField(name, "C"),organization: getNameField(name, "O"),@@ -92,7 +117,7 @@ export const extractDnParts = (name: x509.Name): TDNParts => {province: getNameField(name, "ST"),commonName: getNameField(name, "CN"),locality: getNameField(name, "L"),- domainComponents: domainComponents.length > 0 ? domainComponents : undefined+ domainComponents: extractDomainComponentsInDisplayOrder(name)};};diff --git a/backend/src/services/certificate-common/certificate-constants.ts b/backend/src/services/certificate-common/certificate-constants.tsindex e98eeb794b..a7e777cb05 100644--- a/backend/src/services/certificate-common/certificate-constants.ts+++ b/backend/src/services/certificate-common/certificate-constants.ts@@ -31,6 +31,8 @@ export const domainComponentSchema = z.max(255).refine((value) => !value.includes(","), { message: "Domain component cannot contain a comma" });+export const MAX_DOMAIN_COMPONENTS = 50;+/*** Domain components are persisted comma-joined into a single `varchar(255)` column* (certificate_requests.domainComponents, certificates.subjectDomainComponents), so the combined@@ -38,7 +40,7 @@ export const domainComponentSchema = z*/export const domainComponentsSchema = z.array(domainComponentSchema)- .max(50)+ .max(MAX_DOMAIN_COMPONENTS).refine((components) => components.join(",").length <= PKI_TEXT_COLUMN_MAX_LENGTH,`Domain components cannot exceed ${PKI_TEXT_COLUMN_MAX_LENGTH} characters in total`diff --git a/backend/src/services/certificate-common/certificate-csr-utils.test.ts b/backend/src/services/certificate-common/certificate-csr-utils.test.tsnew file mode 100644index 0000000000..060bb77b10--- /dev/null+++ b/backend/src/services/certificate-common/certificate-csr-utils.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it } from "vitest";++import { extractCertificateRequestFromCSR } from "./certificate-csr-utils";++// the extraction every CSR-based enrollment shares; fixtures produced with openssl+const WINDOWS_ORDER_CSR = `-----BEGIN CERTIFICATE REQUEST-----+MIICmDCCAYACAQAwUzETMBEGCgmSJomT8ixkARkWA2NvbTEXMBUGCgmSJomT8ixk+ARkWB2V4YW1wbGUxFDASBgoJkiaJk/IsZAEZFgRjb3JwMQ0wCwYDVQQDDARob3N0+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA27qIeF4mNPLlFMpuJAMt+z2+MZHGo+w4NgYXnXcTVhJix+2s7qLZxVbBJfp/694VNJNQzfASRT0AnQQ1HpRev+0Ldr7XCTPnzbuiINTCWlq1RUfASpxd6gcAmss0EkkRy7hMlCa3dDaRDCtPuRFZ8n+wNl9f5iaXIDZcY9L6T1o59J5eWLL3dj2kfWfAFigOMRdPJmdAYQTJEP4bj8xPb6E+bZ1NWkh7wXRjVexF52IUPEHSyA1yMHFwSegrK+lOZiacNMtpe8AYptJssCsw8xan+nr95anhyTJLoZc8h8Pbw/Fzk1bN5JHww3T5uG62r+CtUlZiklE/Lru5GCuQyIu2Q+uwIDAQABoAAwDQYJKoZIhvcNAQELBQADggEBAAQxdSyqjq6xr53vy819C11+grDv+q2W66rzdbMm3rQSAKNW0M7S4ZncpSFOISc2P2SZnAjJVFFHHLJoV49/+Uzz01t7/+b86Ikjbp7jcfvMMvKT8aYyXH8CSbZP+tEJJ8o4W/bIzFT/4S32ynYNReXgYoGkVZ+4uQeAy6Z/ak6yPnas11I8w7F4pI3rxaJJ1DCKcMRhv4x35GCkQX7ub/mjV1ONYWa+bg47JC07W+V9iqHjq+38lmK4coo/ZM9DnorwfrvVPk/JrilL73LWuHn5lHg58OJy+Z3RtwGPNCCMhVa30GZ/UHa36gBQYbQCw9yBvegnkR/J/jlfPb9PswCIGTMw=+-----END CERTIFICATE REQUEST-----`;++const FORWARD_ORDER_CSR = `-----BEGIN CERTIFICATE REQUEST-----+MIICmDCCAYACAQAwUzENMAsGA1UEAwwEaG9zdDEUMBIGCgmSJomT8ixkARkWBGNv+cnAxFzAVBgoJkiaJk/IsZAEZFgdleGFtcGxlMRMwEQYKCZImiZPyLGQBGRYDY29t+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuqOmBclhKgEdXp0hP+CG+v5gm4ue/LiBV1E9y+0wiKjnJb9jDw82AtDJY/WB8RF6B5dbYgaWFgM7Num5bPAnd+LdDgDs9clkxGZItmQou0YhWBeT2/QXnyMMXGFvx1VJh4Ratdf1PgxWuMaLSEa3yG+OYBlUXRY2vPXSEf3N7+DOr5T8hr0vI3x4JCn/JFRyQ1o4XR88ZTsuGprH/b+N3R6+QnGmsrYFmIy6kOALTFgJm21YDJm3XdoZmuj9sWG3CakPAwzb7IwkoxVL4H3zLOAG+n7Vr038N8fME7sVscHJUAxDhOiEmUA8+nvrLWLj+9c0ArAAT/4DfzsT/Yf6hqoyu+ywIDAQABoAAwDQYJKoZIhvcNAQELBQADggEBAHL89trQCy2vIaqYEZ30v2SUfRD9+r/Z7MVcf3AKfHmi4/LBIk6aOlfYQRKDIBaxqyUPfY/AC1HAjYF5whB9FEt/EJUsX++GDEVw4EuJYqASR7Sdc2MQqTzCRoXn9vh1wyH16U6iO5Q6KZohynoedz+ynW9XR/+NXPr3XM2OUVOuVsa9s/hJEETMmfiI6TQ7vSeOy7ta+EOxSiOJL/NI+nHnycdBM38+FqRNLb9xTs/WFPr5y4Rgmfap+kEGQCGZPwsBqFPvPG1oaT86D17IyfmcfaZc9Buc+5S9pX4iGtS2KOsLImPU34nrHl4b6/l5rFWPiyq231xTDxCoH927Ix0OgR9k=+-----END CERTIFICATE REQUEST-----`;++const DOMAIN_COMPONENTS_ONLY_CSR = `-----BEGIN CERTIFICATE REQUEST-----+MIICiTCCAXECAQAwRDETMBEGCgmSJomT8ixkARkWA2NvbTEXMBUGCgmSJomT8ixk+ARkWB2V4YW1wbGUxFDASBgoJkiaJk/IsZAEZFgRjb3JwMIIBIjANBgkqhkiG9w0B+AQEFAAOCAQ8AMIIBCgKCAQEApJ2kp0kx4XB8+/5HJC1SYbldCqAe5M47Z2GHLKid+YPBxoPMYGCTmL7mTFEZ5b+dRfgNcJd336yyGzCB0EYRNunukXfJvNY8/s1as0DYf+TnZGfsbr5XkpovtN/EWTHsTc/Um8JNeMkJeymDJDW/uFviDZMne7YRPx/bj3EzxF+WMrA8QVeK3NrPYMjAtapJM6IXbBB5tIyP7liYtgMxMe9rM/uNQFzH1cvS8sqdhXD+wcmZe6jYadmQY+aMRVCuyaM8jItCkT8GpTuM+bvgh/E3NWOfyEXgbtD9VTXLuYiX+M86ZgeZ80ZHmht2sGjDy221fpmiK2e0hPfmmHS0PUaSUWQIDAQABoAAwDQYJKoZI+hvcNAQELBQADggEBAFrNHDBiTqAmZeTfWtF6gN0Yy6kpsIQIA++pLv3fBsxbECQJ+KAz605vQEKeqP7/f6wYiwFnbYnAlZS/E0r1rb+1s/5N3Lqs/WVOMBA9JTyEJT6xA+370d04fmGnpScG+Ro5MmEUa2TNE3BVv+1hmNCz574W1Ok9dMvZO9fn1uHiJFTrMC+d76KC3CN3UaoReeBMLNYaoe5CafeycPS3Z72FIQ8HxExAe+M08DV6HF4maCvZYvy+OvXfnX8nBFHhxGb0qJemsAa/3jYEJG1IVmOiciYpW7ar5KtmudG1UFO8c46htmNC+zxS2IdrWzTRnCoHr1BpBqkyCXx15lSj4Fx2tRdo=+-----END CERTIFICATE REQUEST-----`;++const NO_DOMAIN_COMPONENT_CSR = `-----BEGIN CERTIFICATE REQUEST-----+MIICYzCCAUsCAQAwHjENMAsGA1UEAwwEaG9zdDENMAsGA1UECgwEQWNtZTCCASIw+DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMI4drvs4ayH0WG78HIjZRu5J6dz+GEY7yp3yh90WqwQl3Nnfd9JEwh6tVjwqp4N2YR6VDlJbV4kMjzWXwgV3bBNEAP9X+GXdsZTMNz0ZwKd7i520VJAn1KMLj4m2jamVjQLz9hF/aQguhU+82dgQrpM++iAhd+j+/mjhZBwI9o8bcvxE7CKsYzwhGg8JVWLiNVtkFou2W/9aOL0eRW+riVFMUnYnwE+oda7x8kpnQtGr7d+zn0g+nQAUYrifFh1KoQMAbgfV3oktGuFPBS0u2iIvTDl0yi9+GertlttGZPVUKdcFOEHg1t+qqkhrFbl70x9MaCZbbjFkhOQMIM2RH4nx5DkCAwEA+AaAAMA0GCSqGSIb3DQEBCwUAA4IBAQAmMcVEk8nvN0m0eNB6RLLblednP44LYepA+/12bWYc7ydZEVD2WQNK7qy6iShrNA1O6SboGHooEV0F/0Zb+TXz8b0gsgRfP/xcp+J2rjExj38J9pd5nc10yvT8wGSHH/BAaOQ2AmHWF01dnUjCi/pmH5+VFaFZsapkrq+FKEYZ2X5isQ9x/hPWTivdEVzFHiUI0l/tzBpsQb2qE9CyRtCTB5Ir2FB+4dICwkr+dLRLy13y1JZ6RE0wCnUzoq/dJC/Rf8UgkiDFv9zHFD3RrH3GqaU0h53BKnjmqEqZ+T2d+vMwyzQKefaUBuj1xOtO2ffhc22BMmuuiqumz8hSojw5WU7Xn+-----END CERTIFICATE REQUEST-----`;++describe("extractCertificateRequestFromCSR domain components", () => {+ it("should read a chain encoded root first, as Windows, Active Directory and Intune send it", () => {+ expect(extractCertificateRequestFromCSR(WINDOWS_ORDER_CSR).domainComponents).toEqual(["corp", "example", "com"]);+ });++ it("should read a chain encoded after the common name, as older Infisical releases wrote it", () => {+ expect(extractCertificateRequestFromCSR(FORWARD_ORDER_CSR).domainComponents).toEqual(["corp", "example", "com"]);+ });++ it("should read a chain with no other subject attribute as encoded root first", () => {+ expect(extractCertificateRequestFromCSR(DOMAIN_COMPONENTS_ONLY_CSR).domainComponents).toEqual([+ "corp",+ "example",+ "com"+ ]);+ });++ it("should leave domain components unset when the CSR carries none", () => {+ const request = extractCertificateRequestFromCSR(NO_DOMAIN_COMPONENT_CSR);+ expect(request.domainComponents).toBeUndefined();+ expect(request.commonName).toBe("host");+ expect(request.organization).toBe("Acme");+ });+});diff --git a/backend/src/services/certificate-common/certificate-csr-utils.ts b/backend/src/services/certificate-common/certificate-csr-utils.tsindex fdfadc4418..d30b5d52d9 100644--- a/backend/src/services/certificate-common/certificate-csr-utils.ts+++ b/backend/src/services/certificate-common/certificate-csr-utils.ts@@ -43,8 +43,7 @@ export const extractCertificateRequestFromCSR = (csr: string): TCertificateReque// can distinguish "absent" (use default) from "explicitly set".const certificateRequest: TCertificateRequest = {};if (subject.commonName) certificateRequest.commonName = subject.commonName;- const domainComponents = csrObj.subjectName.getField("DC");- if (domainComponents.length > 0) certificateRequest.domainComponents = domainComponents;+ if (subject.domainComponents?.length) certificateRequest.domainComponents = subject.domainComponents;if (subject.organization) certificateRequest.organization = subject.organization;if (subject.ou) certificateRequest.organizationalUnit = subject.ou;if (subject.locality) certificateRequest.locality = subject.locality;diff --git a/backend/src/services/certificate-common/certificate-issuance-utils.ts b/backend/src/services/certificate-common/certificate-issuance-utils.tsindex 56ab540842..43f8572847 100644--- a/backend/src/services/certificate-common/certificate-issuance-utils.ts+++ b/backend/src/services/certificate-common/certificate-issuance-utils.ts@@ -19,6 +19,7 @@ import {keyAlgorithmToAlgCfg,signatureAlgorithmToAlgCfg} from "@app/services/certificate-authority/certificate-authority-fns";+import { TSubjectRule } from "@app/services/certificate-policy/certificate-policy-types";import {CERT_SUBJECT_ALTERNATIVE_NAMES,@@ -300,12 +301,7 @@ export type TSelfSignedCertificateRequest = {};export type TCertificatePolicy = {- subject?: Array<{- type: string;- allowed?: string[];- required?: string[];- denied?: string[];- }>;+ subject?: TSubjectRule[];sans?: Array<{type: string;allowed?: string[];diff --git a/backend/src/services/certificate-common/certificate-utils.ts b/backend/src/services/certificate-common/certificate-utils.tsindex 1aada18a84..59aa09ed02 100644--- a/backend/src/services/certificate-common/certificate-utils.ts+++ b/backend/src/services/certificate-common/certificate-utils.ts@@ -3,6 +3,7 @@ import RE2 from "re2";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { isPqcAlgorithm } from "@app/lib/crypto/pqc";import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { TSubjectRule } from "@app/services/certificate-policy/certificate-policy-types";import { TProjectDALFactory } from "@app/services/project/project-dal";import { CertExtendedKeyUsage, CertKeyUsage } from "../certificate/certificate-types";@@ -78,12 +79,7 @@ export const bufferToString = (data: Buffer | string): string => {export const buildCertificateSubjectFromTemplate = (request: Record<string, unknown>,- templateAttributes?: Array<{- type: string;- allowed?: string[];- required?: string[];- denied?: string[];- }>+ templateAttributes?: TSubjectRule[]): Record<string, string | undefined> => {const subject: Record<string, string> = {};const attributeMap: Record<string, string> = {diff --git a/backend/src/services/certificate-policy/certificate-policy-dal.ts b/backend/src/services/certificate-policy/certificate-policy-dal.tsindex 59f3d7b6ae..f9752a4af3 100644--- a/backend/src/services/certificate-policy/certificate-policy-dal.ts+++ b/backend/src/services/certificate-policy/certificate-policy-dal.ts@@ -10,6 +10,7 @@ import {type ProcessedPermissionRules} from "@app/lib/knex/permission-filter-utils";+import { normalizeSubjectRules } from "./certificate-policy-fns";import { TCertificatePolicy, TCertificatePolicyInsert, TCertificatePolicyUpdate } from "./certificate-policy-types";export type TCertificatePolicyDALFactory = ReturnType<typeof certificatePolicyDALFactory>;@@ -75,6 +76,10 @@ export const certificatePolicyDALFactory = (db: TDbClient) => {}});+ if (parsed.subject !== undefined) {+ parsed.subject = normalizeSubjectRules(parsed.subject);+ }+return parsed as TCertificatePolicy;};diff --git a/backend/src/services/certificate-policy/certificate-policy-fns.test.ts b/backend/src/services/certificate-policy/certificate-policy-fns.test.tsnew file mode 100644index 0000000000..c68f5145de--- /dev/null+++ b/backend/src/services/certificate-policy/certificate-policy-fns.test.ts@@ -0,0 +1,154 @@+import { describe, expect, it } from "vitest";++import { CertSubjectAttributeType } from "../certificate-common/certificate-constants";+import { normalizeSubjectRules, validateDomainComponentsAgainstRule } from "./certificate-policy-fns";+import { TDomainComponentSubjectRule } from "./certificate-policy-types";++const domainComponentRule = (rule: Omit<TDomainComponentSubjectRule, "type">): TDomainComponentSubjectRule => ({+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ ...rule+});++describe("normalizeSubjectRules", () => {+ it("should lift a legacy flat label list into one ordered sequence", () => {+ expect(normalizeSubjectRules([{ type: "domain_component", allowed: ["corp", "example", "com"] }])).toEqual([+ { type: "domain_component", allowed: [["corp", "example", "com"]], required: undefined, denied: undefined }+ ]);+ });++ it("should leave sequences that are already nested alone", () => {+ const sequences = [+ ["corp", "example", "com"],+ ["example", "com"]+ ];+ expect(normalizeSubjectRules([{ type: "domain_component", denied: sequences }])).toEqual([+ { type: "domain_component", allowed: undefined, required: undefined, denied: sequences }+ ]);+ });++ it("should leave the rules of other attribute types untouched", () => {+ const rules = [{ type: "common_name", allowed: ["*.example.com"] }];+ expect(normalizeSubjectRules(rules)).toEqual(rules);+ });++ it("should keep an empty list empty rather than reading it as a sequence", () => {+ expect(normalizeSubjectRules([{ type: "domain_component", allowed: [] }])).toEqual([+ { type: "domain_component", allowed: [], required: undefined, denied: undefined }+ ]);+ });++ it("should return a value it cannot read unchanged rather than dropping the constraint", () => {+ expect(normalizeSubjectRules(null)).toBeNull();+ expect(normalizeSubjectRules("domain_component")).toBe("domain_component");+ });+});++describe("validateDomainComponentsAgainstRule", () => {+ const validate = (requestDomainComponents: string[], rule: TDomainComponentSubjectRule, skipRequired = false) =>+ validateDomainComponentsAgainstRule({ requestDomainComponents, rule, skipRequired });++ it("should accept a request matching an allowed sequence", () => {+ expect(+ validate(["corp", "example", "com"], domainComponentRule({ allowed: [["corp", "example", "com"]] }))+ ).toEqual([]);+ });++ it("should reject the same labels in another order", () => {+ expect(+ validate(["com", "example", "corp"], domainComponentRule({ allowed: [["corp", "example", "com"]] }))+ ).toHaveLength(1);+ });++ it("should match a wildcard only at its own position", () => {+ const rule = domainComponentRule({ allowed: [["*", "example", "com"]] });+ expect(validate(["corp", "example", "com"], rule)).toEqual([]);+ expect(validate(["example", "com", "corp"], rule)).toHaveLength(1);+ });++ it("should reject a sequence of a different length", () => {+ expect(validate(["corp", "example", "com"], domainComponentRule({ allowed: [["example", "com"]] }))).toHaveLength(+ 1+ );+ });++ it("should compare components case-insensitively", () => {+ expect(+ validate(["Corp", "EXAMPLE", "com"], domainComponentRule({ allowed: [["corp", "example", "com"]] }))+ ).toEqual([]);+ });++ it("should report a request that has no domain components as missing when a sequence is required", () => {+ const errors = validate([], domainComponentRule({ required: [["corp", "example", "com"]] }));+ expect(errors).toEqual([+ "Missing required domain_component attribute. This policy requires one of: 'DC=corp,DC=example,DC=com'"+ ]);+ });++ it("should skip the required check when the caller asks for it", () => {+ expect(validate([], domainComponentRule({ required: [["corp", "example", "com"]] }), true)).toEqual([]);+ });++ it("should accept a required sequence without it also having to be in the allowed list", () => {+ const rule = domainComponentRule({ allowed: [["example", "com"]], required: [["corp", "example", "com"]] });+ expect(validate(["corp", "example", "com"], rule)).toEqual([]);+ });++ it("should reject a denied sequence and report it once", () => {+ const errors = validate(["evil", "example", "com"], domainComponentRule({ denied: [["evil", "example", "com"]] }));+ expect(errors).toEqual(["Domain components 'DC=evil,DC=example,DC=com' are denied by template policy"]);+ });++ it("should treat a rule with no populated list as no constraint", () => {+ expect(validate(["corp", "example", "com"], domainComponentRule({ allowed: [] }))).toEqual([]);+ });++ it("should point at the encoding order when the same components would match reversed", () => {+ const errors = validate(["com", "example", "corp"], domainComponentRule({ allowed: [["corp", "example", "com"]] }));+ expect(errors).toHaveLength(1);+ expect(errors[0]).toContain(+ "The same components in the opposite order would match, so check which end the client encoded first."+ );+ });++ it("should not mention the opposite order when reversing would not help either", () => {+ const errors = validate(["a", "b", "c"], domainComponentRule({ allowed: [["corp", "example", "com"]] }));+ expect(errors).toHaveLength(1);+ expect(errors[0]).not.toContain("opposite order");+ });++ it("should not mention the opposite order for a single component, which reads the same either way", () => {+ const errors = validate(["corp"], domainComponentRule({ allowed: [["example"]] }));+ expect(errors).toHaveLength(1);+ expect(errors[0]).not.toContain("opposite order");+ });++ it("should point at the encoding order on a required mismatch too", () => {+ const errors = validate(+ ["com", "example", "corp"],+ domainComponentRule({ required: [["corp", "example", "com"]] })+ );+ expect(errors).toHaveLength(1);+ expect(errors[0]).toContain("opposite order");+ });++ it("should refuse a rule whose value list cannot be read instead of treating it as no constraint", () => {+ const malformedRule = {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ allowed: "corp,example,com"+ } as unknown as TDomainComponentSubjectRule;++ expect(validate(["anything"], malformedRule)).toEqual([+ "The domain_component rule on this policy is malformed and cannot be evaluated. Edit the policy's domain component rule before issuing against it."+ ]);+ });++ it("should read a legacy flat label list as one ordered sequence", () => {+ const legacyRule = {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ allowed: ["corp", "example", "com"]+ } as unknown as TDomainComponentSubjectRule;++ expect(validate(["corp", "example", "com"], legacyRule)).toEqual([]);+ expect(validate(["com", "example", "corp"], legacyRule)).toHaveLength(1);+ });+});diff --git a/backend/src/services/certificate-policy/certificate-policy-fns.ts b/backend/src/services/certificate-policy/certificate-policy-fns.tsnew file mode 100644index 0000000000..5a3a3687e5--- /dev/null+++ b/backend/src/services/certificate-policy/certificate-policy-fns.ts@@ -0,0 +1,134 @@+import RE2 from "re2";++import { CertSubjectAttributeType } from "../certificate-common/certificate-constants";+import { TDomainComponentSubjectRule, TSubjectRule } from "./certificate-policy-types";++export const isWildcardPattern = (value: string): boolean => value.includes("*");++const createWildcardRegex = (pattern: string): RE2 => {+ const wildcardRegex = new RE2(/\*/g);+ const withPlaceholder = pattern.replace(wildcardRegex, "__WILDCARD__");+ const escapeRegex = new RE2(/[.+?^${}()|[\]\\]/g);+ const escaped = withPlaceholder.replace(escapeRegex, "\\$&");+ const placeholderRegex = new RE2(/__WILDCARD__/g);+ return new RE2(`^${escaped.replace(placeholderRegex, ".*")}$`);+};++// both sides must already be normalized by the caller (lower-cased, or URI-normalized for URI SANs)+export const matchesNormalizedPattern = (value: string, pattern: string): boolean => {+ if (!isWildcardPattern(pattern)) {+ return pattern === value;+ }++ try {+ return createWildcardRegex(pattern).test(value);+ } catch {+ return pattern === value;+ }+};++export const isDomainComponentRule = (rule: TSubjectRule): rule is TDomainComponentSubjectRule =>+ rule.type === CertSubjectAttributeType.DOMAIN_COMPONENT;++export const formatDomainComponentSequence = (sequence: string[]): string =>+ sequence.map((component) => `DC=${component}`).join(",");++const formatDomainComponentSequences = (sequences: string[][]): string =>+ sequences.map((sequence) => `'${formatDomainComponentSequence(sequence)}'`).join(", ");++const matchesDomainComponentSequence = (requestSequence: string[], policySequence: string[]): boolean =>+ requestSequence.length === policySequence.length &&+ requestSequence.every((component, index) =>+ matchesNormalizedPattern(component.toLowerCase(), policySequence[index].toLowerCase())+ );++const matchesAnySequence = (requestSequence: string[], policySequences: string[][]): boolean =>+ policySequences.some((policySequence) => matchesDomainComponentSequence(requestSequence, policySequence));++const isSequenceOfLabels = (value: unknown): value is string[] =>+ Array.isArray(value) && value.every((component) => typeof component === "string");++// a flat list of labels is read as the single sequence it describes+const normalizeDomainComponentSequences = (values: unknown): unknown => {+ if (!Array.isArray(values) || values.length === 0) return values;+ return isSequenceOfLabels(values) ? [values] : values;+};++const normalizeDomainComponentRule = (rule: TDomainComponentSubjectRule): TDomainComponentSubjectRule =>+ ({+ type: rule.type,+ allowed: normalizeDomainComponentSequences(rule.allowed),+ required: normalizeDomainComponentSequences(rule.required),+ denied: normalizeDomainComponentSequences(rule.denied)+ }) as TDomainComponentSubjectRule;++export const normalizeSubjectRules = (rules: unknown): unknown => {+ if (!Array.isArray(rules)) return rules;++ return (rules as TSubjectRule[]).map((rule) =>+ rule && isDomainComponentRule(rule) ? normalizeDomainComponentRule(rule) : rule+ );+};++const ORDER_NOTE =+ "Domain components are order-sensitive, so they must appear in the same order as the policy sequence.";++const reversalHint = (requestSequence: string[], policySequences: string[][]): string => {+ const reversed = [...requestSequence].reverse();+ if (requestSequence.length < 2 || !matchesAnySequence(reversed, policySequences)) {+ return "";+ }+ return " The same components in the opposite order would match, so check which end the client encoded first.";+};++const RULE_FIELDS = ["allowed", "required", "denied"] as const;++export const validateDomainComponentsAgainstRule = ({+ requestDomainComponents,+ rule,+ skipRequired = false+}: {+ requestDomainComponents: string[];+ rule: TDomainComponentSubjectRule;+ skipRequired?: boolean;+}): string[] => {+ const normalizedRule = normalizeDomainComponentRule(rule);++ // an unreadable rule is refused rather than treated as no constraint+ const isRuleReadable = RULE_FIELDS.every(+ (field) => normalizedRule[field] === undefined || Array.isArray(normalizedRule[field])+ );+ if (!isRuleReadable) {+ return [+ `The ${CertSubjectAttributeType.DOMAIN_COMPONENT} rule on this policy is malformed and cannot be evaluated. Edit the policy's domain component rule before issuing against it.`+ ];+ }++ const { allowed = [], required = [], denied = [] } = normalizedRule;+ const errors: string[] = [];+ const hasDomainComponents = requestDomainComponents.length > 0;+ const requestSequence = formatDomainComponentSequence(requestDomainComponents);++ const isDenied = hasDomainComponents && matchesAnySequence(requestDomainComponents, denied);+ if (isDenied) {+ errors.push(`Domain components '${requestSequence}' are denied by template policy`);+ }++ const satisfiesRequired = required.length > 0 && matchesAnySequence(requestDomainComponents, required);+ if (!skipRequired && required.length > 0 && !satisfiesRequired) {+ errors.push(+ hasDomainComponents+ ? `Domain components '${requestSequence}' do not match any required sequence: ${formatDomainComponentSequences(required)}. ${ORDER_NOTE}${reversalHint(requestDomainComponents, required)}`+ : `Missing required ${CertSubjectAttributeType.DOMAIN_COMPONENT} attribute. This policy requires one of: ${formatDomainComponentSequences(required)}`+ );+ }++ const needsAllowedCheck = !isDenied && !satisfiesRequired && hasDomainComponents && allowed.length > 0;+ if (needsAllowedCheck && !matchesAnySequence(requestDomainComponents, allowed)) {+ errors.push(+ `Domain components '${requestSequence}' are not allowed by template policy. Allowed sequences: ${formatDomainComponentSequences(allowed)}. ${ORDER_NOTE}${reversalHint(requestDomainComponents, allowed)}`+ );+ }++ return errors;+};diff --git a/backend/src/services/certificate-policy/certificate-policy-schemas.ts b/backend/src/services/certificate-policy/certificate-policy-schemas.tsindex 34f7289cd7..5c457213c6 100644--- a/backend/src/services/certificate-policy/certificate-policy-schemas.ts+++ b/backend/src/services/certificate-policy/certificate-policy-schemas.ts@@ -1,35 +1,91 @@import RE2 from "re2";import { z } from "zod";+import { CERTIFICATE_POLICIES } from "@app/lib/api-docs";import {CertExtendedKeyUsageType,CertKeyUsageType,CertPolicyState,CertSubjectAlternativeNameType,- CertSubjectAttributeType+ CertSubjectAttributeType,+ domainComponentSchema,+ MAX_DOMAIN_COMPONENTS,+ PKI_TEXT_COLUMN_MAX_LENGTH} from "@app/services/certificate-common/certificate-constants";-const attributeTypeSchema = z.nativeEnum(CertSubjectAttributeType);+import { TSingleValuedSubjectAttributeType } from "./certificate-policy-types";+const sanTypeSchema = z.nativeEnum(CertSubjectAlternativeNameType);-const policySubjectSchema = z- .object({- type: attributeTypeSchema,- allowed: z.array(z.string().trim().min(1, "Value cannot be empty")).optional(),- required: z.array(z.string().trim().min(1, "Value cannot be empty")).optional(),- denied: z.array(z.string().trim().min(1, "Value cannot be empty")).optional()- })- .refine(- (data) => {- if (!data.allowed && !data.required && !data.denied) {- return false;- }- return true;- },- {- message: "Subject attribute must have at least one allowed, required, or denied value"- }+const SINGLE_VALUED_SUBJECT_ATTRIBUTE_TYPES = Object.values(CertSubjectAttributeType).filter(+ (type): type is TSingleValuedSubjectAttributeType => type !== CertSubjectAttributeType.DOMAIN_COMPONENT+);++const singleValuedAttributeTypeSchema = z.enum(+ SINGLE_VALUED_SUBJECT_ATTRIBUTE_TYPES as [TSingleValuedSubjectAttributeType, ...TSingleValuedSubjectAttributeType[]]+);++const MAX_DOMAIN_COMPONENT_SEQUENCES = 25;++const requestSubjectValueSchema = z+ .string()+ .trim()+ .min(1, "Value cannot be empty")+ .max(PKI_TEXT_COLUMN_MAX_LENGTH, `Value cannot exceed ${PKI_TEXT_COLUMN_MAX_LENGTH} characters`);++const buildDomainComponentSequenceListSchema = (componentSchema: z.ZodType<string>, isRequest: boolean) => {+ const sequenceSchema = isRequest+ ? z+ .array(componentSchema)+ .min(1, "A domain component sequence must contain at least one component")+ .max(MAX_DOMAIN_COMPONENTS, `A domain component sequence cannot exceed ${MAX_DOMAIN_COMPONENTS} components`)+ : z.array(componentSchema);++ const listSchema = z.union([sequenceSchema, z.array(sequenceSchema)]).transform((value): string[][] => {+ const isFlatLabelList = value.length > 0 && value.every((entry) => typeof entry === "string");+ return isFlatLabelList ? [value as string[]] : (value as string[][]);+ });++ if (!isRequest) return listSchema;++ return listSchema.refine(+ (sequences) => sequences.length <= MAX_DOMAIN_COMPONENT_SEQUENCES,+ `A domain component rule cannot hold more than ${MAX_DOMAIN_COMPONENT_SEQUENCES} sequences`);+};++const buildPolicySubjectSchema = (valueSchema: z.ZodType<string>, isRequest: boolean) => {+ const domainComponentListSchema = buildDomainComponentSequenceListSchema(+ isRequest ? domainComponentSchema : z.string(),+ isRequest+ );++ const singleValuedSchema = z.object({+ type: singleValuedAttributeTypeSchema,+ allowed: z.array(valueSchema).optional(),+ required: z.array(valueSchema).optional(),+ denied: z.array(valueSchema).optional()+ });++ const domainComponentSubjectSchema = z.object({+ type: z.literal(CertSubjectAttributeType.DOMAIN_COMPONENT),+ allowed: domainComponentListSchema.optional().describe(CERTIFICATE_POLICIES.SUBJECT_DOMAIN_COMPONENT_RULE.allowed),+ required: domainComponentListSchema+ .optional()+ .describe(CERTIFICATE_POLICIES.SUBJECT_DOMAIN_COMPONENT_RULE.required),+ denied: domainComponentListSchema.optional().describe(CERTIFICATE_POLICIES.SUBJECT_DOMAIN_COMPONENT_RULE.denied)+ });++ const unionSchema = z.discriminatedUnion("type", [singleValuedSchema, domainComponentSubjectSchema]);+ if (!isRequest) return unionSchema;++ return unionSchema.refine((data) => Boolean(data.allowed || data.required || data.denied), {+ message: "Subject attribute must have at least one allowed, required, or denied value"+ });+};++export const policySubjectSchema = buildPolicySubjectSchema(requestSubjectValueSchema, true);+const storedPolicySubjectSchema = buildPolicySubjectSchema(z.string(), false);const policyKeyUsagesSchema = z.object({@@ -127,7 +183,7 @@ export const certificatePolicyResponseSchema = z.object({.max(255, "Policy name must be less than 255 characters").regex(new RE2("^[a-zA-Z0-9-_]+$"), "Policy name must contain only letters, numbers, hyphens, and underscores"),description: z.string().trim().max(1000, "Description must be less than 1000 characters").nullable().optional(),- subject: z.array(policySubjectSchema).optional(),+ subject: z.array(storedPolicySubjectSchema).optional(),sans: z.array(policySanSchema).optional(),keyUsages: policyKeyUsagesSchema.optional(),extendedKeyUsages: policyExtendedKeyUsagesSchema.optional(),diff --git a/backend/src/services/certificate-policy/certificate-policy-service.test.ts b/backend/src/services/certificate-policy/certificate-policy-service.test.tsindex 0d26d5b1be..343a3db82a 100644--- a/backend/src/services/certificate-policy/certificate-policy-service.test.ts+++ b/backend/src/services/certificate-policy/certificate-policy-service.test.ts@@ -772,11 +772,14 @@ describe("CertificatePolicyService", () => {updatedAt: new Date()}) as unknown as TCertificatePolicy;- it("should allow domain components that match the domain_component allowed patterns", async () => {+ it("should allow domain components that match an allowed sequence in order", async () => {mockCertificatePolicyDAL.findById.mockResolvedValue(buildSubjectPolicy([{ type: CertSubjectAttributeType.COMMON_NAME, allowed: ["*-CA"] },- { type: CertSubjectAttributeType.DOMAIN_COMPONENT, allowed: ["app", "example", "auth"] }+ {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ allowed: [["app", "example", "auth"]]+ }]));@@ -789,64 +792,169 @@ describe("CertificatePolicyService", () => {expect(result.isValid).toBe(true);});- it("should reject a domain component that does not match the domain_component allowed patterns", async () => {+ it("should reject the allowed domain components when they arrive in another order", async () => {mockCertificatePolicyDAL.findById.mockResolvedValue(buildSubjectPolicy([{ type: CertSubjectAttributeType.COMMON_NAME, allowed: ["*-CA"] },- { type: CertSubjectAttributeType.DOMAIN_COMPONENT, allowed: ["*.example"] }+ {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ allowed: [["app", "example", "auth"]]+ }]));const request: TCertificateRequest = {commonName: "auth-AD-MANAGER02-CA",- domainComponents: ["app", "example", "auth"]+ domainComponents: ["auth", "example", "app"]};const result = await service.validateCertificateRequest("template-123", request);expect(result.isValid).toBe(false);- expect(result.errors).toContain("domain_component value 'app' does not match allowed patterns: *.example");+ expect(result.errors).toContain(+ "Domain components 'DC=auth,DC=example,DC=app' are not allowed by template policy. Allowed sequences: 'DC=app,DC=example,DC=auth'. Domain components are order-sensitive, so they must appear in the same order as the policy sequence. The same components in the opposite order would match, so check which end the client encoded first."+ );+ });++ it("should match a wildcard component only at its own position in the sequence", async () => {+ mockCertificatePolicyDAL.findById.mockResolvedValue(+ buildSubjectPolicy([+ {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ allowed: [["*", "example", "com"]]+ }+ ])+ );++ const matching = await service.validateCertificateRequest("template-123", {+ domainComponents: ["corp", "example", "com"]+ });+ expect(matching.isValid).toBe(true);++ const reversed = await service.validateCertificateRequest("template-123", {+ domainComponents: ["com", "example", "corp"]+ });+ expect(reversed.isValid).toBe(false);+ });++ it("should reject a domain component sequence of a different length", async () => {+ mockCertificatePolicyDAL.findById.mockResolvedValue(+ buildSubjectPolicy([+ {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ allowed: [["example", "com"]]+ }+ ])+ );++ const result = await service.validateCertificateRequest("template-123", {+ domainComponents: ["corp", "example", "com"]+ });+ expect(result.isValid).toBe(false);});- it("should deny a domain component that matches a denied pattern", async () => {+ it("should deny a domain component sequence that matches a denied sequence", async () => {mockCertificatePolicyDAL.findById.mockResolvedValue(buildSubjectPolicy([{ type: CertSubjectAttributeType.COMMON_NAME, allowed: ["*-CA"] },- { type: CertSubjectAttributeType.DOMAIN_COMPONENT, denied: ["auth"] }+ {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ denied: [["app", "example", "auth"]]+ }]));- const request: TCertificateRequest = {+ const denied = await service.validateCertificateRequest("template-123", {commonName: "auth-AD-MANAGER02-CA",domainComponents: ["app", "example", "auth"]- };+ });+ expect(denied.isValid).toBe(false);+ expect(denied.errors).toContain("Domain components 'DC=app,DC=example,DC=auth' are denied by template policy");- const result = await service.validateCertificateRequest("template-123", request);- expect(result.isValid).toBe(false);- expect(result.errors).toContain("domain_component value 'auth' is denied by template policy");+ const reordered = await service.validateCertificateRequest("template-123", {+ commonName: "auth-AD-MANAGER02-CA",+ domainComponents: ["auth", "example", "app"]+ });+ expect(reordered.isValid).toBe(true);});- it("should enforce required domain_component patterns", async () => {+ it("should enforce required domain component sequences", async () => {mockCertificatePolicyDAL.findById.mockResolvedValue(buildSubjectPolicy([{ type: CertSubjectAttributeType.COMMON_NAME, allowed: ["*-CA"] },- { type: CertSubjectAttributeType.DOMAIN_COMPONENT, allowed: ["*"], required: ["auth"] }+ {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ required: [["app", "example", "auth"]]+ }]));- const missing: TCertificateRequest = {+ const missing = await service.validateCertificateRequest("template-123", {+ commonName: "auth-AD-MANAGER02-CA"+ });+ expect(missing.isValid).toBe(false);+ expect(missing.errors).toContain(+ "Missing required domain_component attribute. This policy requires one of: 'DC=app,DC=example,DC=auth'"+ );++ const outOfOrder = await service.validateCertificateRequest("template-123", {commonName: "auth-AD-MANAGER02-CA",- domainComponents: ["app", "example"]- };- const missingResult = await service.validateCertificateRequest("template-123", missing);- expect(missingResult.isValid).toBe(false);- expect(missingResult.errors).toContain("Required domain_component matching pattern 'auth' not found in request");+ domainComponents: ["auth", "example", "app"]+ });+ expect(outOfOrder.isValid).toBe(false);+ expect(outOfOrder.errors).toContain(+ "Domain components 'DC=auth,DC=example,DC=app' do not match any required sequence: 'DC=app,DC=example,DC=auth'. Domain components are order-sensitive, so they must appear in the same order as the policy sequence. The same components in the opposite order would match, so check which end the client encoded first."+ );- const present: TCertificateRequest = {+ const present = await service.validateCertificateRequest("template-123", {commonName: "auth-AD-MANAGER02-CA",domainComponents: ["app", "example", "auth"]- };- const presentResult = await service.validateCertificateRequest("template-123", present);- expect(presentResult.isValid).toBe(true);+ });+ expect(present.isValid).toBe(true);+ });++ it("should accept any of several allowed domain component sequences", async () => {+ mockCertificatePolicyDAL.findById.mockResolvedValue(+ buildSubjectPolicy([+ {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ allowed: [+ ["corp", "example", "com"],+ ["example", "com"]+ ]+ }+ ])+ );++ const firstSequence = await service.validateCertificateRequest("template-123", {+ domainComponents: ["corp", "example", "com"]+ });+ expect(firstSequence.isValid).toBe(true);++ const secondSequence = await service.validateCertificateRequest("template-123", {+ domainComponents: ["example", "com"]+ });+ expect(secondSequence.isValid).toBe(true);+ });++ it("should read a legacy flat domain component list as one ordered sequence", async () => {+ mockCertificatePolicyDAL.findById.mockResolvedValue(+ buildSubjectPolicy([+ {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,+ allowed: ["app", "example", "auth"]+ } as unknown as NonNullable<TTemplateV2Policy["subject"]>[number]+ ])+ );++ const inOrder = await service.validateCertificateRequest("template-123", {+ domainComponents: ["app", "example", "auth"]+ });+ expect(inOrder.isValid).toBe(true);++ const outOfOrder = await service.validateCertificateRequest("template-123", {+ domainComponents: ["auth", "example", "app"]+ });+ expect(outOfOrder.isValid).toBe(false);});it("should reject domain components when the policy defines subject rules but no domain_component rule", async () => {diff --git a/backend/src/services/certificate-policy/certificate-policy-service.ts b/backend/src/services/certificate-policy/certificate-policy-service.tsindex c21415b26c..6940885467 100644--- a/backend/src/services/certificate-policy/certificate-policy-service.ts+++ b/backend/src/services/certificate-policy/certificate-policy-service.ts@@ -23,12 +23,21 @@ import {CertSubjectAttributeType} from "../certificate-common/certificate-constants";import { TCertificatePolicyDALFactory } from "./certificate-policy-dal";+import {+ formatDomainComponentSequence,+ isDomainComponentRule,+ isWildcardPattern,+ matchesNormalizedPattern,+ validateDomainComponentsAgainstRule+} from "./certificate-policy-fns";import {TCertificatePolicy,TCertificatePolicyInsert,TCertificatePolicyUpdate,TCertificateRequest,- TPolicyValidationResult+ TPolicyValidationResult,+ TSingleValuedSubjectRule,+ TSubjectRule} from "./certificate-policy-types";type TCertificatePolicyServiceFactoryDep = {@@ -40,11 +49,7 @@ export const certificatePolicyServiceFactory = ({certificatePolicyDAL,permissionService}: TCertificatePolicyServiceFactoryDep) => {- const consolidateAttributeArray = <- T extends { type: string; allowed?: string[]; required?: string[]; denied?: string[] }- >(- attributes: T[]- ): T[] => {+ const consolidateAttributeArray = <T extends { type: string }>(attributes: T[]): T[] => {const consolidated = new Map<string, T>();attributes.forEach((attr) => {@@ -85,9 +90,7 @@ export const certificatePolicyServiceFactory = ({}};- const validateSubjectAttributePolicy = (- subjectAttributes: Array<{ type: string; allowed?: string[]; required?: string[]; denied?: string[] }>- ) => {+ const validateSubjectAttributePolicy = (subjectAttributes: TSubjectRule[]) => {if (!subjectAttributes || subjectAttributes.length === 0) return;// Validate each subject attribute policy@@ -99,12 +102,17 @@ export const certificatePolicyServiceFactory = ({});}- // Check for duplicate values within arrays- const arrays = [- { name: "allowed", values: attr.allowed },- { name: "required", values: attr.required },- { name: "denied", values: attr.denied }- ];+ const arrays = isDomainComponentRule(attr)+ ? [+ { name: "allowed", values: attr.allowed?.map(formatDomainComponentSequence) },+ { name: "required", values: attr.required?.map(formatDomainComponentSequence) },+ { name: "denied", values: attr.denied?.map(formatDomainComponentSequence) }+ ]+ : [+ { name: "allowed", values: attr.allowed },+ { name: "required", values: attr.required },+ { name: "denied", values: attr.denied }+ ];for (const { name, values } of arrays) {if (values && values.length > 0) {@@ -173,20 +181,6 @@ export const certificatePolicyServiceFactory = ({return randomSlug;};- const isWildcardPattern = (value: string): boolean => {- return value.includes("*");- };-- const createWildcardRegex = (pattern: string): RegExp => {- const wildcardRegex = new RE2(/\*/g);- const withPlaceholder = pattern.replace(wildcardRegex, "__WILDCARD__");- const escapeRegex = new RE2(/[.+?^${}()|[\]\\]/g);- const escaped = withPlaceholder.replace(escapeRegex, "\\$&");- const placeholderRegex = new RE2(/__WILDCARD__/g);- const regexPattern = escaped.replace(placeholderRegex, ".*");- return new RE2(`^${regexPattern}$`);- };-const mapTemplateSignatureAlgorithmToApi = (templateFormat: string): string => {const mapping: Record<string, string> = {"SHA256-RSA": "RSA-SHA256",@@ -292,19 +286,7 @@ export const certificatePolicyServiceFactory = ({const normalizedValue = normalize(value);for (const allowedValue of allowedValues) {- const normalizedAllowed = normalize(allowedValue);- if (isWildcardPattern(allowedValue)) {- try {- const regex = createWildcardRegex(normalizedAllowed);- if (regex.test(normalizedValue)) {- return { isValid: true };- }- } catch (error) {- if (normalizedAllowed === normalizedValue) {- return { isValid: true };- }- }- } else if (normalizedAllowed === normalizedValue) {+ if (matchesNormalizedPattern(normalizedValue, normalize(allowedValue))) {return { isValid: true };}}@@ -343,9 +325,8 @@ export const certificatePolicyServiceFactory = ({if (request.locality) requestAttributes.set(CertSubjectAttributeType.LOCALITY, request.locality);if (subjectPolicies) {- // Domain components are multi-valued and are validated separately below (like SANs).const singleValuedPolicies = subjectPolicies.filter(- (attrPolicy) => attrPolicy.type !== CertSubjectAttributeType.DOMAIN_COMPONENT+ (attrPolicy): attrPolicy is TSingleValuedSubjectRule => !isDomainComponentRule(attrPolicy));for (const attrPolicy of singleValuedPolicies) {const requestValue = requestAttributes.get(attrPolicy.type);@@ -408,52 +389,22 @@ export const certificatePolicyServiceFactory = ({}}- const domainComponentPolicy = subjectPolicies?.find(- (attrPolicy) => attrPolicy.type === CertSubjectAttributeType.DOMAIN_COMPONENT- );+ const domainComponentPolicy = subjectPolicies?.find(isDomainComponentRule);const requestDomainComponents = request.domainComponents ?? [];- const dcFieldName = CertSubjectAttributeType.DOMAIN_COMPONENT;if (domainComponentPolicy) {- if (!options?.skipRequired && domainComponentPolicy.required && domainComponentPolicy.required.length > 0) {- for (const requiredValue of domainComponentPolicy.required) {- const hasMatch = requestDomainComponents.some(- (dc) => validateValueAgainstConstraints(dc, [requiredValue], dcFieldName).isValid- );- if (!hasMatch) {- errors.push(`Required ${dcFieldName} matching pattern '${requiredValue}' not found in request`);- }- }- }-- if (domainComponentPolicy.denied && domainComponentPolicy.denied.length > 0) {- for (const dc of requestDomainComponents) {- if (validateValueAgainstConstraints(dc, domainComponentPolicy.denied, dcFieldName).isValid) {- errors.push(`${dcFieldName} value '${dc}' is denied by template policy`);- }- }- }-- if (domainComponentPolicy.allowed && domainComponentPolicy.allowed.length > 0 && requestDomainComponents.length) {- for (const dc of requestDomainComponents) {- const satisfiesRequired =- domainComponentPolicy.required && domainComponentPolicy.required.length > 0- ? domainComponentPolicy.required.some(- (requiredValue) => validateValueAgainstConstraints(dc, [requiredValue], dcFieldName).isValid- )- : false;-- if (!satisfiesRequired) {- const validation = validateValueAgainstConstraints(dc, domainComponentPolicy.allowed, dcFieldName);- if (!validation.isValid && validation.error) {- errors.push(validation.error);- }- }- }- }+ errors.push(+ ...validateDomainComponentsAgainstRule({+ requestDomainComponents,+ rule: domainComponentPolicy,+ skipRequired: options?.skipRequired+ })+ );} else if (subjectPolicies && requestDomainComponents.length > 0) {// A subject policy is defined but has no domain_component rule, so DCs aren't// permitted. When no subject policy is defined at all, every subject attribute is allowed.- errors.push(`${dcFieldName} is not allowed by template policy (not defined in template)`);+ errors.push(+ `${CertSubjectAttributeType.DOMAIN_COMPONENT} is not allowed by template policy (not defined in template)`+ );}// Validate Subject Alternative Names. An undefined SAN policy means no constraint (allow all);diff --git a/backend/src/services/certificate-policy/certificate-policy-types.ts b/backend/src/services/certificate-policy/certificate-policy-types.tsindex c08be192d7..11954206a0 100644--- a/backend/src/services/certificate-policy/certificate-policy-types.ts+++ b/backend/src/services/certificate-policy/certificate-policy-types.ts@@ -14,13 +14,30 @@ export interface TBasicConstraints {maxPathLength?: number; // -1 = unlimited, 0+ = specific limit, undefined = not constrained}+export type TSingleValuedSubjectAttributeType = Exclude<+ CertSubjectAttributeType,+ CertSubjectAttributeType.DOMAIN_COMPONENT+>;++export interface TSingleValuedSubjectRule {+ type: TSingleValuedSubjectAttributeType;+ allowed?: string[];+ required?: string[];+ denied?: string[];+}++/** Each entry is one ordered sequence of per-component patterns, matched position by position. */+export interface TDomainComponentSubjectRule {+ type: CertSubjectAttributeType.DOMAIN_COMPONENT;+ allowed?: string[][];+ required?: string[][];+ denied?: string[][];+}++export type TSubjectRule = TSingleValuedSubjectRule | TDomainComponentSubjectRule;+export interface TTemplateV2Policy {- subject?: Array<{- type: CertSubjectAttributeType;- allowed?: string[];- required?: string[];- denied?: string[];- }>;+ subject?: TSubjectRule[];sans?: Array<{type: CertSubjectAlternativeNameType;allowed?: string[];diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.tsindex 5fb9824a1f..0ca3a602fe 100644--- a/backend/src/services/certificate-profile/certificate-profile-service.ts+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts@@ -449,6 +449,7 @@ export const certificateProfileServiceFactory = ({country: data.defaults.country,state: data.defaults.state,locality: data.defaults.locality,+ domainComponents: data.defaults.domainComponents,keyUsages: data.defaults.keyUsages,extendedKeyUsages: data.defaults.extendedKeyUsages,signatureAlgorithm: data.defaults.signatureAlgorithm,@@ -759,6 +760,7 @@ export const certificateProfileServiceFactory = ({country: data.defaults.country,state: data.defaults.state,locality: data.defaults.locality,+ domainComponents: data.defaults.domainComponents,keyUsages: data.defaults.keyUsages,extendedKeyUsages: data.defaults.extendedKeyUsages,signatureAlgorithm: data.defaults.signatureAlgorithm,diff --git a/backend/src/services/certificate-v3/certificate-approval-fns.ts b/backend/src/services/certificate-v3/certificate-approval-fns.tsindex fab9b5fd5b..9ae33ccd20 100644--- a/backend/src/services/certificate-v3/certificate-approval-fns.ts+++ b/backend/src/services/certificate-v3/certificate-approval-fns.ts@@ -27,7 +27,7 @@ import {extractCertificateRequestFromCSR} from "@app/services/certificate-common/certificate-csr-utils";import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";-import { TCertificateRequest } from "@app/services/certificate-policy/certificate-policy-types";+import { TCertificateRequest, TSubjectRule } from "@app/services/certificate-policy/certificate-policy-types";import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";import { EnrollmentType, IssuerType } from "@app/services/certificate-profile/certificate-profile-types";import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";@@ -359,12 +359,7 @@ export const certificateApprovalServiceFactory = (notAfter?: Date;};policy?: {- subject?: Array<{- type: string;- allowed?: string[];- required?: string[];- denied?: string[];- }>;+ subject?: TSubjectRule[];sans?: Array<{type: string;allowed?: string[];diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.tsindex 2572bd26c4..3257325d7d 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts@@ -100,7 +100,7 @@ import {removeRootCaFromChain,validatePqcLicense} from "../certificate-common/certificate-utils";-import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";+import { TCertificateRequest, TSubjectRule } from "../certificate-policy/certificate-policy-types";import { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";import { TCertificateRequestServiceFactory } from "../certificate-request/certificate-request-service";import { CertificateRequestStatus } from "../certificate-request/certificate-request-types";@@ -599,12 +599,7 @@ const processSelfSignedCertificate = async ({notAfter?: Date;};policy?: {- subject?: Array<{- type: string;- allowed?: string[];- required?: string[];- denied?: string[];- }>;+ subject?: TSubjectRule[];sans?: Array<{type: string;allowed?: string[];diff --git a/backend/src/services/certificate/certificate-fns.ts b/backend/src/services/certificate/certificate-fns.tsindex dd6e59a66d..0b17e9278f 100644--- a/backend/src/services/certificate/certificate-fns.ts+++ b/backend/src/services/certificate/certificate-fns.ts@@ -250,8 +250,7 @@ export const parseCertificateBody = (decryptedCertificate: Buffer): TParsedCertistate: parsedDn.province,locality: parsedDn.locality};- const domainComponents = certObj.subjectName.getField("DC");- if (domainComponents.length > 0) subject.domainComponents = domainComponents;+ if (parsedDn.domainComponents?.length) subject.domainComponents = parsedDn.domainComponents;// Calculate fingerprints and format with colons (e.g., "1A:2F:73:...")const rawData = Buffer.from(certObj.rawData);diff --git a/docs/documentation/platform/pki/settings/policies.mdx b/docs/documentation/platform/pki/settings/policies.mdxindex bcfc8bc19e..505514a291 100644--- a/docs/documentation/platform/pki/settings/policies.mdx+++ b/docs/documentation/platform/pki/settings/policies.mdx@@ -73,7 +73,7 @@ Control what X.509 distinguished name attributes can appear in certificates:| Country | C | `US` || State/Province | ST | `California` || Locality | L | `San Francisco` |-| Domain Component | DC | `example` |+| Domain Component | DC | `corp,example,com` |For each attribute, configure enforcement:@@ -90,11 +90,19 @@ For each attribute, configure enforcement:</AccordionGroup><Note>- Domain Component (DC) support is for requests that use DC attributes explicitly. Each DC value is- matched independently against the Domain Component rule (like a Subject Alternative Name),- separately from the Common Name. A subject can carry more than one domain component (for example- `CN=host, DC=auth, DC=example, DC=app`), so allow the labels your requests use, such as `auth`,- `example`, and `app`, or a pattern like `*`.+ Domain Component (DC) support is for requests that use DC attributes explicitly, separately from the+ Common Name. Domain components form an ordered chain in the distinguished name, so a DC rule+ constrains whole sequences rather than individual labels:++ - Enter the full sequence in distinguished name order, separated by commas. `corp,example,com`+ matches `CN=host,DC=corp,DC=example,DC=com`.+ - A request matches a sequence only when its components line up position by position, so the same+ labels in another order are rejected. Requests are read in distinguished name order whichever way+ the client encoded the name, so a CSR from Windows, Active Directory or Intune matches the same+ rule as one from OpenSSL.+ - Wildcards apply within a single component. `*,example,com` matches any three-component sequence+ ending in `example`, `com`.+ - Add one rule per sequence you want to accept, deny, or require.</Note>Once you define subject attribute rules, only the attribute types you explicitly include are permitted — any other attribute in a request will be rejected. An empty configuration forbids all subject attributes; leave the section unconfigured to allow any attribute.diff --git a/frontend/src/hooks/api/certificatePolicies/index.tsx b/frontend/src/hooks/api/certificatePolicies/index.tsxindex f9ab2f719b..9195a3c612 100644--- a/frontend/src/hooks/api/certificatePolicies/index.tsx+++ b/frontend/src/hooks/api/certificatePolicies/index.tsx@@ -13,7 +13,9 @@ export type {TCertificatePolicyRule,TCreateCertificatePolicyDTO,TDeleteCertificatePolicyDTO,+ TDomainComponentSubjectRule,TGetCertificatePolicyByIdDTO,TListCertificatePoliciesDTO,+ TSubjectRule,TUpdateCertificatePolicyDTO} from "./types";diff --git a/frontend/src/hooks/api/certificatePolicies/types.ts b/frontend/src/hooks/api/certificatePolicies/types.tsindex 531c80cebc..521ea01053 100644--- a/frontend/src/hooks/api/certificatePolicies/types.ts+++ b/frontend/src/hooks/api/certificatePolicies/types.ts@@ -1,19 +1,24 @@import { CertPolicyState } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";+export type TSingleValuedSubjectRule = {+ type: "common_name" | "organization" | "country" | "state" | "locality" | "organizational_unit";+ allowed?: string[];+ required?: string[];+ denied?: string[];+};++/** Each entry is one ordered sequence of patterns, matched position by position. */+export type TDomainComponentSubjectRule = {+ type: "domain_component";+ allowed?: string[][];+ required?: string[][];+ denied?: string[][];+};++export type TSubjectRule = TSingleValuedSubjectRule | TDomainComponentSubjectRule;+export type TCertificatePolicyRule = {- subject?: Array<{- type:- | "common_name"- | "organization"- | "country"- | "state"- | "locality"- | "organizational_unit"- | "domain_component";- allowed?: string[];- required?: string[];- denied?: string[];- }>;+ subject?: TSubjectRule[];sans?: Array<{type: "dns_name" | "ip_address" | "email" | "uri" | "upn";allowed?: string[];diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicySubjectRulesSection.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicySubjectRulesSection.tsxindex ede3c2aae1..47fb2c9370 100644--- a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicySubjectRulesSection.tsx+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicySubjectRulesSection.tsx@@ -11,6 +11,7 @@ import {CertSubjectAttributeType,formatSubjectAttributeType} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";+import { formatDomainComponentSequence } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/utils";import { RuleList } from "./RuleList";@@ -18,6 +19,9 @@ type Props = {policy: TCertificatePolicy;};+const toRuleValues = (values?: Array<string | string[]>): string[] | undefined =>+ values?.map((value) => (Array.isArray(value) ? formatDomainComponentSequence(value) : value));+export const PolicySubjectRulesSection = ({ policy }: Props) => {if (!policy.subject) {return null;@@ -53,9 +57,9 @@ export const PolicySubjectRulesSection = ({ policy }: Props) => {<div className="text-sm font-medium text-foreground">{formatSubjectAttributeType(rule.type as CertSubjectAttributeType)}</div>- <RuleList label="Allowed" values={rule.allowed} />- <RuleList label="Required" values={rule.required} />- <RuleList label="Denied" values={rule.denied} />+ <RuleList label="Allowed" values={toRuleValues(rule.allowed)} />+ <RuleList label="Required" values={toRuleValues(rule.required)} />+ <RuleList label="Denied" values={toRuleValues(rule.denied)} /></div>))}</DetailGroup>diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsxindex 0401dff1f4..80676d83a3 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 { ReactNode, useEffect, useState } from "react";import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { Plus, ShieldCheck, Trash2 } from "lucide-react";+import { Info, Plus, ShieldCheck, Trash2 } from "lucide-react";import { createNotification } from "@app/components/notifications";import {@@ -16,6 +16,7 @@ import {FieldError,FieldGroup,FieldLabel,+ IconButton,Input,Select,SelectContent,@@ -30,7 +31,10 @@ import {StepperList,StepperStep,Switch,- TextArea+ TextArea,+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@app/components/v3";import { useProject, useSubscription } from "@app/context";import {@@ -63,11 +67,20 @@ import {SUBJECT_ATTRIBUTE_TYPE_OPTIONS} from "./shared/certificate-constants";import { CERTIFICATE_POLICY_PRESETS } from "./shared/policy-presets";-import { PolicyFormData, policySchema } from "./shared";+import {+ formatDomainComponentSequence,+ isValidDomainComponentSequence,+ parseDomainComponentSequence,+ PolicyFormData,+ policySchema+} from "./shared";export type FormData = PolicyFormData;+type AttributeRow = NonNullable<FormData["attributes"]>[number];type AttributeTransform = NonNullable<TCertificatePolicyRule["subject"]>[0];+type DomainComponentTransform = Extract<AttributeTransform, { type: "domain_component" }>;+type SingleValuedAttributeTransform = Exclude<AttributeTransform, DomainComponentTransform>;type SanTransform = NonNullable<TCertificatePolicyRule["sans"]>[0];type KeyUsagesTransform = TCertificatePolicyRule["keyUsages"];type ExtendedKeyUsagesTransform = TCertificatePolicyRule["extendedKeyUsages"];@@ -113,6 +126,15 @@ const SAN_INCLUDE_LABELS: Record<(typeof SAN_INCLUDE_OPTIONS)[number], string> =prohibit: "Deny"};+const SUBJECT_INCLUDE_RULE_KEYS: Record<+ CertSubjectAttributeInclude,+ "required" | "allowed" | "denied"+> = {+ [CertSubjectAttributeInclude.REQUIRED]: "required",+ [CertSubjectAttributeInclude.OPTIONAL]: "allowed",+ [CertSubjectAttributeInclude.PROHIBIT]: "denied"+};+const USAGE_POLICY_OPTIONS = [{ value: "deny", label: "Deny" },{ value: "allow", label: "Allow" },@@ -194,6 +216,34 @@ const STEPS = [}] as const;+const DomainComponentHelp = () => (+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton variant="ghost" size="xs" aria-label="Domain component format">+ <Info className="size-4" />+ </IconButton>+ </TooltipTrigger>+ <TooltipContent side="top" align="start" className="max-w-80 py-2">+ <p>+ Domain components form an ordered chain. Enter the components most specific first, separated+ by commas.+ </p>+ <dl className="mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5">+ <dt className="text-muted">Value</dt>+ <dd className="font-mono">corp,example,com</dd>+ <dt className="text-muted">Matches</dt>+ <dd className="font-mono">DC=corp,DC=example,DC=com</dd>+ <dt className="text-muted">Rejects</dt>+ <dd className="font-mono">DC=com,DC=example,DC=corp</dd>+ </dl>+ <p className="mt-2">+ A <span className="font-mono">*</span> matches a single component:{" "}+ <span className="font-mono">*,internal,example,com</span>.+ </p>+ </TooltipContent>+ </Tooltip>+);+const DurationInput = ({field,error,@@ -326,39 +376,30 @@ export const CreatePolicyModal = ({if (step > 0) setStep((s) => s - 1);};+ const toAttributeRows = (+ type: CertSubjectAttributeType,+ values: Array<string | string[]> | undefined,+ include: CertSubjectAttributeInclude+ ): AttributeRow[] =>+ Array.isArray(values)+ ? values.map((value) => ({+ type,+ include,+ value: [Array.isArray(value) ? formatDomainComponentSequence(value) : value]+ }))+ : [];+const convertApiToUiFormat = (policyData: TCertificatePolicy): FormData => {- const attributes: FormData["attributes"] = [];- if (policyData.subject && Array.isArray(policyData.subject)) {- policyData.subject.forEach((subj) => {- if (subj.required && Array.isArray(subj.required)) {- subj.required.forEach((requiredValue) => {- attributes.push({- type: subj.type as CertSubjectAttributeType,- include: CertSubjectAttributeInclude.REQUIRED,- value: [requiredValue]- });- });- }- if (subj.allowed && Array.isArray(subj.allowed)) {- subj.allowed.forEach((allowedValue) => {- attributes.push({- type: subj.type as CertSubjectAttributeType,- include: CertSubjectAttributeInclude.OPTIONAL,- value: [allowedValue]- });- });- }- if (subj.denied && Array.isArray(subj.denied)) {- subj.denied.forEach((deniedValue) => {- attributes.push({- type: subj.type as CertSubjectAttributeType,- include: CertSubjectAttributeInclude.PROHIBIT,- value: [deniedValue]- });- });- }- });- }+ const attributes: FormData["attributes"] = Array.isArray(policyData.subject)+ ? policyData.subject.flatMap((subj) => {+ const type = subj.type as CertSubjectAttributeType;+ return [+ ...toAttributeRows(type, subj.required, CertSubjectAttributeInclude.REQUIRED),+ ...toAttributeRows(type, subj.allowed, CertSubjectAttributeInclude.OPTIONAL),+ ...toAttributeRows(type, subj.denied, CertSubjectAttributeInclude.PROHIBIT)+ ];+ })+ : [];const subjectAlternativeNames: FormData["subjectAlternativeNames"] = [];if (policyData.sans && Array.isArray(policyData.sans)) {@@ -586,8 +627,24 @@ export const CreatePolicyModal = ({}};+ const mergeRuleValues = <TValue extends string | string[]>(+ existing: TValue[] | undefined,+ incoming: TValue[] | undefined+ ): TValue[] => {+ const merged = new Map<string, TValue>();+ [...(existing || []), ...(incoming || [])].forEach((value) => {+ merged.set(Array.isArray(value) ? formatDomainComponentSequence(value) : value, value);+ });+ return Array.from(merged.values());+ };+const consolidateByType = <- T extends { type: string; allowed?: string[]; required?: string[]; denied?: string[] }+ T extends {+ type: string;+ allowed?: Array<string | string[]>;+ required?: Array<string | string[]>;+ denied?: Array<string | string[]>;+ }>(items: T[]): T[] => {@@ -598,9 +655,9 @@ export const CreatePolicyModal = ({if (existing) {const mergedItem = {...item,- allowed: [...new Set([...(existing.allowed || []), ...(item.allowed || [])])],- required: [...new Set([...(existing.required || []), ...(item.required || [])])],- denied: [...new Set([...(existing.denied || []), ...(item.denied || [])])]+ allowed: mergeRuleValues(existing.allowed, item.allowed),+ required: mergeRuleValues(existing.required, item.required),+ denied: mergeRuleValues(existing.denied, item.denied)} as T;if (mergedItem.allowed?.length === 0) delete mergedItem.allowed;@@ -618,18 +675,25 @@ export const CreatePolicyModal = ({const transformToApiFormat = (data: FormData) => {const subjectRaw =- data.attributes?.map((attr) => {- const result: AttributeTransform = { type: attr.type };- if (attr.value && attr.value.length > 0) {- if (attr.include === CertSubjectAttributeInclude.REQUIRED) {- result.required = attr.value;- } else if (attr.include === CertSubjectAttributeInclude.OPTIONAL) {- result.allowed = attr.value;- } else if (attr.include === CertSubjectAttributeInclude.PROHIBIT) {- result.denied = attr.value;- }+ data.attributes?.map((attr): AttributeTransform => {+ const ruleKey = SUBJECT_INCLUDE_RULE_KEYS[attr.include];++ if (attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT) {+ const sequences = (attr.value || [])+ .map(parseDomainComponentSequence)+ .filter((sequence) => sequence.length > 0);++ return {+ type: attr.type,+ ...(sequences.length > 0 ? { [ruleKey]: sequences } : {})+ } as DomainComponentTransform;}- return result;++ const values = attr.value || [];+ return {+ type: attr.type,+ ...(values.length > 0 ? { [ruleKey]: values } : {})+ } as SingleValuedAttributeTransform;}) || [];const sansRaw =@@ -733,6 +797,22 @@ export const CreatePolicyModal = ({return;}+ const hasInvalidDomainComponentSequence =+ restrictSubject &&+ data.attributes?.some(+ (attr) =>+ attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT &&+ attr.value?.some((value) => !isValidDomainComponentSequence(value))+ );++ if (hasInvalidDomainComponentSequence) {+ createNotification({+ text: "Every domain component in a sequence must be non-empty, for example corp,example,com.",+ type: "error"+ });+ return;+ }+const transformedData = transformToApiFormat(data);if (isEdit) {@@ -1105,52 +1185,71 @@ export const CreatePolicyModal = ({)}{watchedAttributes.map((attr, index) => (// eslint-disable-next-line react/no-array-index-key- <div key={`attr-${index}`} className="flex items-start gap-2">- <Select- value={attr.type}- onValueChange={(value) => {- const next = [...watchedAttributes];- next[index] = { ...attr, type: value as CertSubjectAttributeType };- setValue("attributes", next);- markCustomPreset();- }}- >- <SelectTrigger className="w-52">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- {SUBJECT_ATTRIBUTE_TYPE_OPTIONS.map((type) => (- <SelectItem key={type} value={type}>- {ATTRIBUTE_TYPE_LABELS[type]}- </SelectItem>- ))}- </SelectContent>- </Select>- <Select- value={attr.include}- onValueChange={(value) => {- const next = [...watchedAttributes];- next[index] = {- ...attr,- include: value as (typeof SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS)[number]- };- setValue("attributes", next);- markCustomPreset();- }}- >- <SelectTrigger className="w-28">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- {SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS.map((type) => (- <SelectItem key={type} value={type}>- {SUBJECT_ATTRIBUTE_LABELS[type]}- </SelectItem>- ))}- </SelectContent>- </Select>+ <div key={`attr-${index}`} className="space-y-2">+ <div className="flex items-center gap-2">+ <Select+ value={attr.type}+ onValueChange={(value) => {+ const next = [...watchedAttributes];+ next[index] = { ...attr, type: value as CertSubjectAttributeType };+ setValue("attributes", next);+ markCustomPreset();+ }}+ >+ <SelectTrigger className="min-w-0 flex-1">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {SUBJECT_ATTRIBUTE_TYPE_OPTIONS.map((type) => (+ <SelectItem key={type} value={type}>+ {ATTRIBUTE_TYPE_LABELS[type]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select+ value={attr.include}+ onValueChange={(value) => {+ const next = [...watchedAttributes];+ next[index] = {+ ...attr,+ include:+ value as (typeof SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS)[number]+ };+ setValue("attributes", next);+ markCustomPreset();+ }}+ >+ <SelectTrigger className="w-32 shrink-0">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS.map((type) => (+ <SelectItem key={type} value={type}>+ {SUBJECT_ATTRIBUTE_LABELS[type]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT && (+ <DomainComponentHelp />+ )}+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="shrink-0"+ onClick={() => removeAttribute(index)}+ >+ <Trash2 className="size-4" />+ </Button>+ </div><Input- placeholder="Pattern/Value (use * for wildcards)"+ placeholder={+ attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT+ ? "corp,example,com"+ : "Pattern/Value (use * for wildcards)"+ }value={attr.value?.[0] || ""}onChange={(e) => {const next = [...watchedAttributes];@@ -1161,16 +1260,8 @@ export const CreatePolicyModal = ({setValue("attributes", next);markCustomPreset();}}- className="flex-1"+ className="w-full"/>- <Button- type="button"- variant="ghost"- size="sm"- onClick={() => removeAttribute(index)}- >- <Trash2 className="size-4" />- </Button></div>))}<Button type="button" variant="outline" size="sm" onClick={addAttribute}>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 969c2a2114..6ab3ec4aa0 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@@ -99,75 +99,3 @@ export const policySchema = z.object({});export type PolicyFormData = z.infer<typeof policySchema>;--export const apiSubjectSchema = z- .object({- type: z.nativeEnum(CertSubjectAttributeType),- allowed: z.array(z.string().min(1, "Value cannot be empty")).optional(),- required: z.array(z.string().min(1, "Value cannot be empty")).optional(),- denied: z.array(z.string().min(1, "Value cannot be empty")).optional()- })- .refine((data) => data.allowed || data.required || data.denied, {- message: "At least one allowed, required, or denied value must be provided"- });--export const apiSanSchema = z- .object({- type: z.nativeEnum(CertSubjectAlternativeNameType),- allowed: z.array(z.string().min(1, "Value cannot be empty")).optional(),- required: z.array(z.string().min(1, "Value cannot be empty")).optional(),- denied: z.array(z.string().min(1, "Value cannot be empty")).optional()- })- .refine((data) => data.allowed || data.required || data.denied, {- message: "At least one allowed, required, or denied value must be provided"- });--export const apiPolicySchema = z.object({- name: z- .string()- .trim()- .min(1, "Policy name is required")- .max(255, "Policy name must be less than 255 characters")- .regex(- /^[a-zA-Z0-9-_]+$/,- "Policy name must contain only letters, numbers, hyphens, and underscores"- ),- description: z- .string()- .trim()- .max(255, "Description must be less than 255 characters")- .optional(),- subject: z.array(apiSubjectSchema).optional(),- sans: z.array(apiSanSchema).optional(),- keyUsages: z- .object({- allowed: z.array(z.nativeEnum(CertKeyUsageType)).optional(),- required: z.array(z.nativeEnum(CertKeyUsageType)).optional(),- denied: z.array(z.nativeEnum(CertKeyUsageType)).optional()- })- .optional(),- extendedKeyUsages: z- .object({- allowed: z.array(z.nativeEnum(CertExtendedKeyUsageType)).optional(),- required: z.array(z.nativeEnum(CertExtendedKeyUsageType)).optional(),- denied: z.array(z.nativeEnum(CertExtendedKeyUsageType)).optional()- })- .optional(),- algorithms: z- .object({- signature: z.array(z.string().trim().min(1, "Algorithm cannot be empty")).optional(),- keyAlgorithm: z.array(z.string().trim().min(1, "Algorithm cannot be empty")).optional()- })- .optional(),- validity: z- .object({- max: z- .string()- .trim()- .regex(/^[1-9]\d*[dhmy]$/, "Must be in format like '365d', '12m', '1y', or '24h'")- .optional()- })- .optional()-});--export type ApiPolicyFormData = z.infer<typeof apiPolicySchema>;diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/utils.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/utils.tsindex 291d9d527d..9b609d73c7 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/utils.ts+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/utils.ts@@ -7,6 +7,20 @@ import {UsageState} from "./certificate-constants";+/** A sequence is edited as comma-separated text and sent as the ordered array the API takes. */+export const parseDomainComponentSequence = (value: string): string[] =>+ value+ .split(",")+ .map((component) => component.trim())+ .filter(Boolean);++export const formatDomainComponentSequence = (sequence: string[]): string => sequence.join(",");++export const isValidDomainComponentSequence = (value: string): boolean => {+ const components = value.split(",");+ return components.length > 0 && components.every((component) => component.trim().length > 0);+};+export const formatUsageName = (usage: string): string => {if (Object.values(CertKeyUsageType).includes(usage as CertKeyUsageType)) {return formatKeyUsage(usage as CertKeyUsageType);