Skip to content

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

Address PR comments

Carlos Monastyrski6af4b5d52028
diff --git a/backend/e2e-test/db/rewrite-json-column.spec.ts b/backend/e2e-test/db/rewrite-json-column.spec.ts
deleted file mode 100644
index 77d3f99327..0000000000
--- a/backend/e2e-test/db/rewrite-json-column.spec.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-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.ts
index 83d6ecfa63..bc1e3c39f3 100644
--- a/backend/e2e-test/routes/v1/certificate-policy-domain-components.spec.ts
+++ b/backend/e2e-test/routes/v1/certificate-policy-domain-components.spec.ts
@@ -81,11 +81,8 @@ describe("Certificate policy domain component rules", async () => {
const res = await createPolicy("dc-sequences", [
{
type: "domain_component",
- allowed: [
- ["corp", "example", "com"],
- ["*", "internal", "example", "com"]
- ],
- denied: [["evil", "example", "com"]]
+ allowed: ["corp,example,com", "*,internal,example,com"],
+ denied: ["evil,example,com"]
}
]);
@@ -96,42 +93,35 @@ describe("Certificate policy domain component rules", async () => {
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"]]
+ 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"] }]);
+ test("stores a deny list of single labels as the single-component sequences they are", async () => {
+ const res = await createPolicy("dc-single-label-deny", [{ type: "domain_component", denied: ["evil", "bad"] }]);
expect(res.statusCode).toBe(200);
const policyId = trackPolicy(res.payload);
- expect(domainComponentRule(subjectOf(res.payload))?.allowed).toEqual([["corp", "example", "com"]]);
+ expect(domainComponentRule(subjectOf(res.payload))?.denied).toEqual(["evil", "bad"]);
const read = await getPolicy(policyId);
- expect(domainComponentRule(subjectOf(read.payload))?.allowed).toEqual([["corp", "example", "com"]]);
+ expect(domainComponentRule(subjectOf(read.payload))?.denied).toEqual(["evil", "bad"]);
});
- test("reads a flat deny list as one sequence per label", async () => {
- const res = await createPolicy("dc-flat-deny", [{ type: "domain_component", denied: ["evil", "bad"] }]);
-
- expect(res.statusCode).toBe(200);
- const policyId = trackPolicy(res.payload);
-
- expect(domainComponentRule(subjectOf(res.payload))?.denied).toEqual([["evil"], ["bad"]]);
+ test("rejects a sequence with an empty component", async () => {
+ const res = await createPolicy("dc-empty-component", [
+ { type: "domain_component", allowed: ["corp,,com"] }
+ ]);
- const read = await getPolicy(policyId);
- expect(domainComponentRule(subjectOf(read.payload))?.denied).toEqual([["evil"], ["bad"]]);
+ expect(res.statusCode).toBe(422);
});
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"]] }
+ { type: "domain_component", required: ["corp,example,com"] }
]);
expect(res.statusCode).toBe(200);
@@ -143,12 +133,12 @@ describe("Certificate policy domain component rules", async () => {
allowed: ["*.example.com"],
denied: ["admin.example.com"]
});
- expect(domainComponentRule(subject)?.required).toEqual([["corp", "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"] }
+ { type: "domain_component", allowed: ["corp,example,com"] }
]);
expect(created.statusCode).toBe(200);
const policyId = trackPolicy(created.payload);
@@ -161,28 +151,22 @@ describe("Certificate policy domain component rules", async () => {
subject: [
{
type: "domain_component",
- allowed: [
- ["corp", "example", "com"],
- ["example", "com"]
- ]
+ allowed: ["corp,example,com", "example,com"]
}
]
}
});
expect(updated.statusCode).toBe(200);
- expect(domainComponentRule(subjectOf(updated.payload))?.allowed).toEqual([
- ["corp", "example", "com"],
- ["example", "com"]
- ]);
+ 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, "")}`, [
+ ["a nested value list", [["corp", "example", "com"]]],
+ ["a trailing separator", ["corp,example,com,"]],
+ ["a blank sequence", [" "]]
+ ])("rejects %s", async (label, allowed) => {
+ const res = await createPolicy(`dc-invalid-${label.replace(/[^a-z]/g, "")}`, [
{ type: "domain_component", allowed }
]);
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.ts
deleted file mode 100644
index 8d68db3f5c..0000000000
--- a/backend/src/db/migrations/20260805143012_certificate-policy-domain-component-sequences.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-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 ORDERED_RULE_FIELDS = ["allowed", "required"] as const;
-const DENIED_RULE_FIELD = "denied";
-
-type TRewriteField = (values: unknown) => string[] | string[][] | undefined;
-
-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 isSingleLabelSequenceList = (values: unknown): values is string[][] =>
- Array.isArray(values) &&
- values.length > 0 &&
- values.every((value) => Array.isArray(value) && value.length === 1 && typeof value[0] === "string");
-
-const rewriteDomainComponentRule =
- (rewriteOrderedField: TRewriteField, rewriteDeniedField: TRewriteField) =>
- (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 };
- const fields = [
- ...ORDERED_RULE_FIELDS.map((field) => [field, rewriteOrderedField] as const),
- [DENIED_RULE_FIELD, rewriteDeniedField] as const
- ];
- for (const [field, rewriteField] of 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),
- (values) => (isFlatLabelList(values) ? values.map((label) => [label]) : 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),
- (values) => (isSingleLabelSequenceList(values) ? values.map(([label]) => label) : undefined)
- )
- });
-}
diff --git a/backend/src/db/migrations/20260806134218_certificate-policy-domain-component-sequences.ts b/backend/src/db/migrations/20260806134218_certificate-policy-domain-component-sequences.ts
new file mode 100644
index 0000000000..1768996cda
--- /dev/null
+++ b/backend/src/db/migrations/20260806134218_certificate-policy-domain-component-sequences.ts
@@ -0,0 +1,65 @@
+import { Knex } from "knex";
+
+import { initLogger, logger } from "@app/lib/logger";
+
+import { TableName } from "../schemas";
+
+const SUBJECT_RULES = `jsonb_array_elements(CASE WHEN jsonb_typeof(subject) = 'array' THEN subject ELSE '[]'::jsonb END)`;
+
+const isLabelList = (field: string) => `
+ jsonb_array_length(COALESCE(rule->'${field}', '[]'::jsonb)) > 1
+ AND NOT EXISTS (
+ SELECT 1 FROM jsonb_array_elements_text(rule->'${field}') AS label WHERE label LIKE '%,%'
+ )
+`;
+
+const joinDomainComponentLabels = (field: string) => `
+ UPDATE ${TableName.PkiCertificatePolicy}
+ SET subject = (
+ SELECT jsonb_agg(
+ CASE
+ WHEN rule->>'type' = 'domain_component' AND ${isLabelList(field)}
+ THEN jsonb_set(
+ rule,
+ '{${field}}',
+ jsonb_build_array(
+ (
+ SELECT string_agg(label, ',' ORDER BY ordinality)
+ FROM jsonb_array_elements_text(rule->'${field}') WITH ORDINALITY AS labels(label, ordinality)
+ )
+ )
+ )
+ ELSE rule
+ END
+ ORDER BY position
+ )
+ FROM ${SUBJECT_RULES} WITH ORDINALITY AS rules(rule, position)
+ )
+ WHERE jsonb_typeof(subject) = 'array'
+ AND EXISTS (
+ SELECT 1
+ FROM ${SUBJECT_RULES} AS rule
+ WHERE rule->>'type' = 'domain_component'
+ AND ${isLabelList(field)}
+ )
+`;
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.PkiCertificatePolicy))) return;
+
+ initLogger();
+
+ for (const field of ["allowed", "required"]) {
+ // eslint-disable-next-line no-await-in-loop
+ const { rowCount } = await knex.raw<{ rowCount: number }>(joinDomainComponentLabels(field));
+ if (rowCount) {
+ logger.info(
+ `Joined certificate policy domain component labels into sequences [field=${field}] [policies=${rowCount}]`
+ );
+ }
+ }
+}
+
+export async function down(): Promise<void> {
+ // a joined sequence holds the same characters as the labels it was built from, so there is nothing to undo
+}
diff --git a/backend/src/db/migrations/utils/rewrite-json-column.ts b/backend/src/db/migrations/utils/rewrite-json-column.ts
deleted file mode 100644
index 3374fc85b7..0000000000
--- a/backend/src/db/migrations/utils/rewrite-json-column.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-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.ts
index f3e4154576..e4e362fc07 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2125,9 +2125,9 @@ 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.`;
+ `Domain component sequences that are ${rule}. Each entry is one sequence, its components comma-joined most specific first: "corp,example,com" matches 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 do not match.`;
-const DOMAIN_COMPONENT_DENIED_RULE = `Domain component sequences that are rejected, each ordered as the distinguished name reads it, most specific component first. A sequence is rejected wherever it appears in the chain, so [["example", "com"]] rejects DC=example,DC=com and DC=host,DC=example,DC=com alike. A flat list of labels rejects each label on its own, wherever it appears.`;
+const DOMAIN_COMPONENT_DENIED_RULE = `Domain component sequences that are rejected, each comma-joined most specific first. A sequence is rejected wherever it appears in the chain, so "example,com" rejects DC=example,DC=com and DC=host,DC=example,DC=com alike.`;
export const CERTIFICATE_POLICIES = {
SUBJECT_DOMAIN_COMPONENT_RULE: {
diff --git a/backend/src/services/certificate-policy/certificate-policy-dal.ts b/backend/src/services/certificate-policy/certificate-policy-dal.ts
index f9752a4af3..59f3d7b6ae 100644
--- a/backend/src/services/certificate-policy/certificate-policy-dal.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-dal.ts
@@ -10,7 +10,6 @@ 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>;
@@ -76,10 +75,6 @@ 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.ts
index 5c123ba565..0b01416aa6 100644
--- a/backend/src/services/certificate-policy/certificate-policy-fns.test.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-fns.test.ts
@@ -1,120 +1,74 @@
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";
+import { validateDomainComponentsAgainstRule } from "./certificate-policy-fns";
+import { TSubjectRule } from "./certificate-policy-types";
-const domainComponentRule = (rule: Omit<TDomainComponentSubjectRule, "type">): TDomainComponentSubjectRule => ({
+const domainComponentRule = (rule: Omit<TSubjectRule, "type">): TSubjectRule => ({
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 lift a legacy flat deny list into one sequence per label", () => {
- expect(normalizeSubjectRules([{ type: "domain_component", denied: ["evil", "bad"] }])).toEqual([
- { type: "domain_component", allowed: undefined, required: undefined, denied: [["evil"], ["bad"]] }
- ]);
- });
-
- 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) =>
+ const validate = (requestDomainComponents: string[], rule: TSubjectRule, 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([]);
+ 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);
+ 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"]] });
+ 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
- );
+ 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([]);
+ 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"]] }));
+ 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([]);
+ 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"]] });
+ 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"]] }));
+ 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. Denied sequences: 'DC=evil,DC=example,DC=com'"
+ "Domain components 'DC=evil,DC=example,DC=com' are denied by this policy. Denied sequences: 'DC=evil,DC=example,DC=com'"
]);
});
it("should deny everything under a denied sequence", () => {
- const rule = domainComponentRule({ denied: [["corp", "example", "com"]] });
+ const rule = domainComponentRule({ denied: ["corp,example,com"] });
expect(validate(["dev", "corp", "example", "com"], rule)).toHaveLength(1);
expect(validate(["other", "example", "com"], rule)).toEqual([]);
expect(validate(["example", "com"], rule)).toEqual([]);
});
it("should deny a label wherever it appears in the chain", () => {
- const rule = domainComponentRule({ denied: [["evil"]] });
+ const rule = domainComponentRule({ denied: ["evil"] });
expect(validate(["evil"], rule)).toHaveLength(1);
expect(validate(["evil", "example"], rule)).toHaveLength(1);
expect(validate(["a", "evil", "b"], rule)).toHaveLength(1);
@@ -125,7 +79,7 @@ describe("validateDomainComponentsAgainstRule", () => {
const legacyRule = {
type: CertSubjectAttributeType.DOMAIN_COMPONENT,
denied: ["evil", "bad"]
- } as unknown as TDomainComponentSubjectRule;
+ } as unknown as TSubjectRule;
expect(validate(["evil"], legacyRule)).toHaveLength(1);
expect(validate(["bad", "example"], legacyRule)).toHaveLength(1);
@@ -134,15 +88,15 @@ describe("validateDomainComponentsAgainstRule", () => {
it("should deny one subtree while still allowing its siblings", () => {
const rule = domainComponentRule({
- allowed: [["*", "example", "com"]],
- denied: [["dev", "example", "com"]]
+ allowed: ["*,example,com"],
+ denied: ["dev,example,com"]
});
expect(validate(["prod", "example", "com"], rule)).toEqual([]);
expect(validate(["dev", "example", "com"], rule)).toHaveLength(1);
});
it("should honour a wildcard inside a denied sequence", () => {
- const rule = domainComponentRule({ denied: [["*", "internal", "com"]] });
+ const rule = domainComponentRule({ denied: ["*,internal,com"] });
expect(validate(["a", "internal", "com"], rule)).toHaveLength(1);
expect(validate(["internal", "com"], rule)).toEqual([]);
});
@@ -152,7 +106,7 @@ describe("validateDomainComponentsAgainstRule", () => {
});
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"]] }));
+ 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."
@@ -160,44 +114,58 @@ describe("validateDomainComponentsAgainstRule", () => {
});
it("should not mention the opposite order when reversing would not help either", () => {
- const errors = validate(["a", "b", "c"], domainComponentRule({ allowed: [["corp", "example", "com"]] }));
+ 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"]] }));
+ 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"]] })
- );
+ 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 sequence holding an empty component instead of reading it as a shorter chain", () => {
+ const malformedRule = {
+ type: CertSubjectAttributeType.DOMAIN_COMPONENT,
+ allowed: ["corp,,com"]
+ } as unknown as TSubjectRule;
+
+ expect(validate(["corp", "com"], malformedRule)).toHaveLength(1);
+ });
+
+ it("should refuse a rule whose values are all blank instead of allowing everything", () => {
+ expect(validate(["anything"], domainComponentRule({ allowed: [" "] }))).toHaveLength(1);
+ });
+
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;
+ } as unknown as TSubjectRule;
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;
+ it("should read each entry as its own sequence", () => {
+ const rule = domainComponentRule({ allowed: ["corp,example,com", "example,com"] });
- expect(validate(["corp", "example", "com"], legacyRule)).toEqual([]);
- expect(validate(["com", "example", "corp"], legacyRule)).toHaveLength(1);
+ expect(validate(["corp", "example", "com"], rule)).toEqual([]);
+ expect(validate(["example", "com"], rule)).toEqual([]);
+ expect(validate(["com"], rule)).toHaveLength(1);
+ });
+
+ it("should tolerate spacing around the components of a stored sequence", () => {
+ expect(validate(["corp", "example", "com"], domainComponentRule({ allowed: [" corp , example , com "] }))).toEqual(
+ []
+ );
});
});
diff --git a/backend/src/services/certificate-policy/certificate-policy-fns.ts b/backend/src/services/certificate-policy/certificate-policy-fns.ts
index ec572ad60c..c904127b6b 100644
--- a/backend/src/services/certificate-policy/certificate-policy-fns.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-fns.ts
@@ -1,7 +1,7 @@
import RE2 from "re2";
import { CertSubjectAttributeType } from "../certificate-common/certificate-constants";
-import { TDomainComponentSubjectRule, TSubjectRule } from "./certificate-policy-types";
+import { TSubjectRule } from "./certificate-policy-types";
export const isWildcardPattern = (value: string): boolean => value.includes("*");
@@ -24,12 +24,18 @@ export const matchesNormalizedPattern = (value: string, pattern: string): boolea
}
};
-export const isDomainComponentRule = (rule: TSubjectRule): rule is TDomainComponentSubjectRule =>
+export const isDomainComponentRule = (rule: TSubjectRule): boolean =>
rule.type === CertSubjectAttributeType.DOMAIN_COMPONENT;
-export const formatDomainComponentSequence = (sequence: string[]): string =>
+const formatDomainComponentSequence = (sequence: string[]): string =>
sequence.map((component) => `DC=${component}`).join(",");
+const parseDomainComponentSequence = (value: string): string[] =>
+ value
+ .split(",")
+ .map((component) => component.trim())
+ .filter((component) => component.length > 0);
+
const formatDomainComponentSequences = (sequences: string[][]): string =>
sequences.map((sequence) => `'${formatDomainComponentSequence(sequence)}'`).join(", ");
@@ -55,36 +61,6 @@ const containsSequence = (requestSequence: string[], policySequence: string[]):
const containsAnySequence = (requestSequence: string[], policySequences: string[][]): boolean =>
policySequences.some((policySequence) => containsSequence(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 normalizeDeniedDomainComponentSequences = (values: unknown): unknown => {
- if (!Array.isArray(values) || values.length === 0) return values;
- return isSequenceOfLabels(values) ? values.map((label) => [label]) : values;
-};
-
-const normalizeDomainComponentRule = (rule: TDomainComponentSubjectRule): TDomainComponentSubjectRule =>
- ({
- type: rule.type,
- allowed: normalizeDomainComponentSequences(rule.allowed),
- required: normalizeDomainComponentSequences(rule.required),
- denied: normalizeDeniedDomainComponentSequences(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.";
@@ -98,28 +74,35 @@ const reversalHint = (requestSequence: string[], policySequences: string[][]): s
const RULE_FIELDS = ["allowed", "required", "denied"] as const;
+const isReadableValueList = (values: unknown): values is string[] =>
+ values === undefined ||
+ (Array.isArray(values) &&
+ values.every(
+ (value) => typeof value === "string" && value.split(",").every((component) => component.trim().length > 0)
+ ));
+
export const validateDomainComponentsAgainstRule = ({
requestDomainComponents,
rule,
skipRequired = false
}: {
requestDomainComponents: string[];
- rule: TDomainComponentSubjectRule;
+ rule: TSubjectRule;
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) {
+ if (!RULE_FIELDS.every((field) => isReadableValueList(rule[field]))) {
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 sequencesOf = (values: string[] = []) => values.map(parseDomainComponentSequence);
+
+ const allowed = sequencesOf(rule.allowed);
+ const required = sequencesOf(rule.required);
+ const denied = sequencesOf(rule.denied);
+
const errors: string[] = [];
const hasDomainComponents = requestDomainComponents.length > 0;
const requestSequence = formatDomainComponentSequence(requestDomainComponents);
@@ -127,7 +110,7 @@ export const validateDomainComponentsAgainstRule = ({
const isDenied = hasDomainComponents && containsAnySequence(requestDomainComponents, denied);
if (isDenied) {
errors.push(
- `Domain components '${requestSequence}' are denied by template policy. Denied sequences: ${formatDomainComponentSequences(denied)}`
+ `Domain components '${requestSequence}' are denied by this policy. Denied sequences: ${formatDomainComponentSequences(denied)}`
);
}
@@ -143,7 +126,7 @@ export const validateDomainComponentsAgainstRule = ({
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)}`
+ `Domain components '${requestSequence}' are not allowed by this policy. Allowed sequences: ${formatDomainComponentSequences(allowed)}. ${ORDER_NOTE}${reversalHint(requestDomainComponents, allowed)}`
);
}
diff --git a/backend/src/services/certificate-policy/certificate-policy-schemas.ts b/backend/src/services/certificate-policy/certificate-policy-schemas.ts
index f2d86dc4fd..81265698c3 100644
--- a/backend/src/services/certificate-policy/certificate-policy-schemas.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-schemas.ts
@@ -33,39 +33,23 @@ const requestSubjectValueSchema = z
.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,
- liftFlatList: (labels: string[]) => string[][]
-) => {
- 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 ? liftFlatList(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 requestDomainComponentSequenceSchema = requestSubjectValueSchema
+ .refine(
+ (value) => value.split(",").every((component) => domainComponentSchema.safeParse(component).success),
+ "A domain component sequence must be comma-separated components, most specific first"
+ )
+ .refine(
+ (value) => value.split(",").length <= MAX_DOMAIN_COMPONENTS,
+ `A domain component sequence cannot exceed ${MAX_DOMAIN_COMPONENTS} components`
);
-};
-const buildPolicySubjectSchema = (valueSchema: z.ZodType<string>, isRequest: boolean) => {
- const componentSchema = isRequest ? domainComponentSchema : z.string();
- const domainComponentListSchema = buildDomainComponentSequenceListSchema(componentSchema, isRequest, (labels) => [
- labels
- ]);
- const deniedDomainComponentListSchema = buildDomainComponentSequenceListSchema(componentSchema, isRequest, (labels) =>
- labels.map((label) => [label])
- );
+const buildPolicySubjectSchema = (
+ valueSchema: z.ZodType<string>,
+ domainComponentValueSchema: z.ZodType<string>,
+ maxSequences?: number
+) => {
+ const sequenceList = z.array(domainComponentValueSchema);
+ const domainComponentListSchema = maxSequences ? sequenceList.max(maxSequences) : sequenceList;
const singleValuedSchema = z.object({
type: singleValuedAttributeTypeSchema,
@@ -74,27 +58,27 @@ const buildPolicySubjectSchema = (valueSchema: z.ZodType<string>, isRequest: boo
denied: z.array(valueSchema).optional()
});
- const domainComponentSubjectSchema = z.object({
+ const domainComponentSchemaShape = 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: deniedDomainComponentListSchema
- .optional()
- .describe(CERTIFICATE_POLICIES.SUBJECT_DOMAIN_COMPONENT_RULE.denied)
+ 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"
- });
+ return z.discriminatedUnion("type", [singleValuedSchema, domainComponentSchemaShape]);
};
-export const policySubjectSchema = buildPolicySubjectSchema(requestSubjectValueSchema, true);
-const storedPolicySubjectSchema = buildPolicySubjectSchema(z.string(), false);
+export const policySubjectSchema = buildPolicySubjectSchema(
+ requestSubjectValueSchema,
+ requestDomainComponentSequenceSchema,
+ MAX_DOMAIN_COMPONENT_SEQUENCES
+).refine((data) => Boolean(data.allowed || data.required || data.denied), {
+ message: "Subject attribute must have at least one allowed, required, or denied value"
+});
+
+const storedPolicySubjectSchema = buildPolicySubjectSchema(z.string(), z.string());
const policyKeyUsagesSchema = z
.object({
diff --git a/backend/src/services/certificate-policy/certificate-policy-service.test.ts b/backend/src/services/certificate-policy/certificate-policy-service.test.ts
index 7eff159b93..7a0b6d87ce 100644
--- a/backend/src/services/certificate-policy/certificate-policy-service.test.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-service.test.ts
@@ -440,7 +440,7 @@ describe("CertificatePolicyService", () => {
const result = await service.validateCertificateRequest("template-123", invalidRequest);
expect(result.isValid).toBe(false);
- expect(result.errors).toContain("organization value 'Forbidden Corp' is denied by template policy");
+ expect(result.errors).toContain("organization value 'Forbidden Corp' is denied by this policy");
});
it("should treat an empty subject policy as nothing allowed (reject request subject attributes)", async () => {
@@ -449,7 +449,7 @@ describe("CertificatePolicyService", () => {
const result = await service.validateCertificateRequest("template-123", validRequest);
expect(result.isValid).toBe(false);
- expect(result.errors).toContain("common_name is not allowed by template policy (not defined in template)");
+ expect(result.errors).toContain("common_name is not allowed by this policy");
});
it("should treat an undefined subject policy as allow all (no subject constraint)", async () => {
@@ -466,7 +466,7 @@ describe("CertificatePolicyService", () => {
const result = await service.validateCertificateRequest("template-123", validRequest);
expect(result.isValid).toBe(false);
- expect(result.errors).toContain("dns_name SAN is not allowed by template policy (not defined in template)");
+ expect(result.errors).toContain("dns_name SAN is not allowed by this policy");
});
it("should treat an undefined SAN policy as allow all (no SAN constraint)", async () => {
@@ -486,7 +486,7 @@ describe("CertificatePolicyService", () => {
});
expect(result.isValid).toBe(false);
- expect(result.errors).toContain("domain_component is not allowed by template policy (not defined in template)");
+ expect(result.errors).toContain("domain_component is not allowed by this policy");
});
it("should detect missing required key usages", async () => {
@@ -594,7 +594,7 @@ describe("CertificatePolicyService", () => {
const result = await service.validateCertificateRequest("template-123", invalidRequest);
expect(result.isValid).toBe(false);
- expect(result.errors).toContain("Signature algorithm 'MD5-RSA' is not allowed by template policy");
+ expect(result.errors).toContain("Signature algorithm 'MD5-RSA' is not allowed by this policy");
});
it("should detect invalid key algorithm", async () => {
@@ -603,7 +603,7 @@ describe("CertificatePolicyService", () => {
const result = await service.validateCertificateRequest("template-123", invalidRequest);
expect(result.isValid).toBe(false);
- expect(result.errors).toContain("Key algorithm 'RSA-1024' is not allowed by template policy");
+ expect(result.errors).toContain("Key algorithm 'RSA-1024' is not allowed by this policy");
});
it("should detect TTL exceeding maximum duration", async () => {
@@ -778,7 +778,7 @@ describe("CertificatePolicyService", () => {
{ type: CertSubjectAttributeType.COMMON_NAME, allowed: ["*-CA"] },
{
type: CertSubjectAttributeType.DOMAIN_COMPONENT,
- allowed: [["app", "example", "auth"]]
+ allowed: ["app,example,auth"]
}
])
);
@@ -798,7 +798,7 @@ describe("CertificatePolicyService", () => {
{ type: CertSubjectAttributeType.COMMON_NAME, allowed: ["*-CA"] },
{
type: CertSubjectAttributeType.DOMAIN_COMPONENT,
- allowed: [["app", "example", "auth"]]
+ allowed: ["app,example,auth"]
}
])
);
@@ -811,7 +811,7 @@ describe("CertificatePolicyService", () => {
const result = await service.validateCertificateRequest("template-123", request);
expect(result.isValid).toBe(false);
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."
+ "Domain components 'DC=auth,DC=example,DC=app' are not allowed by this 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."
);
});
@@ -820,7 +820,7 @@ describe("CertificatePolicyService", () => {
buildSubjectPolicy([
{
type: CertSubjectAttributeType.DOMAIN_COMPONENT,
- allowed: [["*", "example", "com"]]
+ allowed: ["*,example,com"]
}
])
);
@@ -841,7 +841,7 @@ describe("CertificatePolicyService", () => {
buildSubjectPolicy([
{
type: CertSubjectAttributeType.DOMAIN_COMPONENT,
- allowed: [["example", "com"]]
+ allowed: ["example,com"]
}
])
);
@@ -858,7 +858,7 @@ describe("CertificatePolicyService", () => {
{ type: CertSubjectAttributeType.COMMON_NAME, allowed: ["*-CA"] },
{
type: CertSubjectAttributeType.DOMAIN_COMPONENT,
- denied: [["app", "example", "auth"]]
+ denied: ["app,example,auth"]
}
])
);
@@ -869,7 +869,7 @@ describe("CertificatePolicyService", () => {
});
expect(denied.isValid).toBe(false);
expect(denied.errors).toContain(
- "Domain components 'DC=app,DC=example,DC=auth' are denied by template policy. Denied sequences: 'DC=app,DC=example,DC=auth'"
+ "Domain components 'DC=app,DC=example,DC=auth' are denied by this policy. Denied sequences: 'DC=app,DC=example,DC=auth'"
);
const reordered = await service.validateCertificateRequest("template-123", {
@@ -885,7 +885,7 @@ describe("CertificatePolicyService", () => {
{ type: CertSubjectAttributeType.COMMON_NAME, allowed: ["*-CA"] },
{
type: CertSubjectAttributeType.DOMAIN_COMPONENT,
- required: [["app", "example", "auth"]]
+ required: ["app,example,auth"]
}
])
);
@@ -919,10 +919,7 @@ describe("CertificatePolicyService", () => {
buildSubjectPolicy([
{
type: CertSubjectAttributeType.DOMAIN_COMPONENT,
- allowed: [
- ["corp", "example", "com"],
- ["example", "com"]
- ]
+ allowed: ["corp,example,com", "example,com"]
}
])
);
@@ -938,27 +935,6 @@ describe("CertificatePolicyService", () => {
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 () => {
mockCertificatePolicyDAL.findById.mockResolvedValue(
buildSubjectPolicy([{ type: CertSubjectAttributeType.COMMON_NAME, allowed: ["*-CA"] }])
@@ -971,7 +947,7 @@ describe("CertificatePolicyService", () => {
const result = await service.validateCertificateRequest("template-123", request);
expect(result.isValid).toBe(false);
- expect(result.errors).toContain("domain_component is not allowed by template policy (not defined in template)");
+ expect(result.errors).toContain("domain_component is not allowed by this policy");
});
it("should prevent certificates from including denied SANs", async () => {
@@ -1308,9 +1284,7 @@ describe("CertificatePolicyService", () => {
const invalidSigResult = await service.validateCertificateRequest("template-123", invalidSigRequest);
expect(invalidSigResult.isValid).toBe(false);
- expect(invalidSigResult.errors).toContain(
- "Signature algorithm 'ECDSA-SHA256' is not allowed by template policy"
- );
+ expect(invalidSigResult.errors).toContain("Signature algorithm 'ECDSA-SHA256' is not allowed by this policy");
const invalidKeyRequest = {
commonName: "example.com",
@@ -1323,7 +1297,7 @@ describe("CertificatePolicyService", () => {
const invalidKeyResult = await service.validateCertificateRequest("template-123", invalidKeyRequest);
expect(invalidKeyResult.isValid).toBe(false);
- expect(invalidKeyResult.errors).toContain("Key algorithm 'EC_prime256v1' is not allowed by template policy");
+ expect(invalidKeyResult.errors).toContain("Key algorithm 'EC_prime256v1' is not allowed by this policy");
});
it("should validate validity period edge cases", async () => {
@@ -1421,7 +1395,7 @@ describe("CertificatePolicyService", () => {
const result = await service.validateCertificateRequest("template-123", requestWithUnlistedSan);
expect(result.isValid).toBe(false);
- expect(result.errors).toContain("email SAN is not allowed by template policy (not defined in template)");
+ expect(result.errors).toContain("email SAN is not allowed by this policy");
});
it("should allow any key usages when template does not define key-usage rules", async () => {
@@ -1438,7 +1412,7 @@ describe("CertificatePolicyService", () => {
};
const result = await service.validateCertificateRequest("template-123", requestWithKeyUsages);
- expect(result.errors).not.toContain("Key usages are not allowed by template policy (not defined in template)");
+ expect(result.errors).not.toContain("Key usages are not allowed by this policy (not defined in template)");
});
it("should allow any algorithms when template does not define algorithm rules", async () => {
@@ -1458,12 +1432,8 @@ describe("CertificatePolicyService", () => {
};
const result = await service.validateCertificateRequest("template-123", requestWithAlgorithms);
- expect(result.errors).not.toContain(
- "Signature algorithm 'RSA-SHA256' is not allowed by template policy (not defined in template)"
- );
- expect(result.errors).not.toContain(
- "Key algorithm 'RSA-2048' is not allowed by template policy (not defined in template)"
- );
+ expect(result.errors).not.toContain("Signature algorithm 'RSA-SHA256' is not allowed by this policy");
+ expect(result.errors).not.toContain("Key algorithm 'RSA-2048' is not allowed by this policy");
});
});
@@ -1711,12 +1681,8 @@ describe("CertificatePolicyService", () => {
};
const result = await service.validateCertificateRequest("template-123", requestWithAlgorithms);
- expect(result.errors).not.toContain(
- "Signature algorithm 'RSA-SHA256' is not allowed by template policy (not defined in template)"
- );
- expect(result.errors).not.toContain(
- "Key algorithm 'RSA_2048' is not allowed by template policy (not defined in template)"
- );
+ expect(result.errors).not.toContain("Signature algorithm 'RSA-SHA256' is not allowed by this policy");
+ expect(result.errors).not.toContain("Key algorithm 'RSA_2048' is not allowed by this policy");
});
it("should allow requests that match any of multiple attribute policies of same type", async () => {
@@ -1822,7 +1788,7 @@ describe("CertificatePolicyService", () => {
const invalidCountryRequest = { ...validComplexRequest, country: "XX" };
const result2 = await service.validateCertificateRequest("template-123", invalidCountryRequest);
expect(result2.isValid).toBe(false);
- expect(result2.errors).toContain("country value 'XX' is denied by template policy");
+ expect(result2.errors).toContain("country value 'XX' is denied by this policy");
const invalidOrgRequest = { ...validComplexRequest, organization: "Different Corp" };
const result3 = await service.validateCertificateRequest("template-123", invalidOrgRequest);
expect(result3.isValid).toBe(false);
diff --git a/backend/src/services/certificate-policy/certificate-policy-service.ts b/backend/src/services/certificate-policy/certificate-policy-service.ts
index 6940885467..cab9079075 100644
--- a/backend/src/services/certificate-policy/certificate-policy-service.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-service.ts
@@ -24,7 +24,6 @@ import {
} from "../certificate-common/certificate-constants";
import { TCertificatePolicyDALFactory } from "./certificate-policy-dal";
import {
- formatDomainComponentSequence,
isDomainComponentRule,
isWildcardPattern,
matchesNormalizedPattern,
@@ -36,7 +35,6 @@ import {
TCertificatePolicyUpdate,
TCertificateRequest,
TPolicyValidationResult,
- TSingleValuedSubjectRule,
TSubjectRule
} from "./certificate-policy-types";
@@ -102,17 +100,11 @@ export const certificatePolicyServiceFactory = ({
});
}
- 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 }
- ];
+ const arrays = [
+ { 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) {
@@ -325,9 +317,7 @@ export const certificatePolicyServiceFactory = ({
if (request.locality) requestAttributes.set(CertSubjectAttributeType.LOCALITY, request.locality);
if (subjectPolicies) {
- const singleValuedPolicies = subjectPolicies.filter(
- (attrPolicy): attrPolicy is TSingleValuedSubjectRule => !isDomainComponentRule(attrPolicy)
- );
+ const singleValuedPolicies = subjectPolicies.filter((attrPolicy) => !isDomainComponentRule(attrPolicy));
for (const attrPolicy of singleValuedPolicies) {
const requestValue = requestAttributes.get(attrPolicy.type);
@@ -352,7 +342,7 @@ export const certificatePolicyServiceFactory = ({
if (attrPolicy.denied && attrPolicy.denied.length > 0) {
const validation = validateValueAgainstConstraints(requestValue, attrPolicy.denied, attrPolicy.type);
if (validation.isValid) {
- errors.push(`${attrPolicy.type} value '${requestValue}' is denied by template policy`);
+ errors.push(`${attrPolicy.type} value '${requestValue}' is denied by this policy`);
isValueDenied = true;
}
}
@@ -384,7 +374,7 @@ export const certificatePolicyServiceFactory = ({
for (const [attrType] of requestAttributes) {
const hasPolicy = subjectPolicies.some((policy) => policy.type === attrType);
if (!hasPolicy) {
- errors.push(`${attrType} is not allowed by template policy (not defined in template)`);
+ errors.push(`${attrType} is not allowed by this policy`);
}
}
}
@@ -402,9 +392,7 @@ export const certificatePolicyServiceFactory = ({
} 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(
- `${CertSubjectAttributeType.DOMAIN_COMPONENT} is not allowed by template policy (not defined in template)`
- );
+ errors.push(`${CertSubjectAttributeType.DOMAIN_COMPONENT} is not allowed by this policy`);
}
// Validate Subject Alternative Names. An undefined SAN policy means no constraint (allow all);
@@ -498,7 +486,7 @@ export const certificatePolicyServiceFactory = ({
for (const [requestSanType] of requestSansByType) {
const hasPolicy = sansPolicies.some((policy) => policy.type === requestSanType);
if (!hasPolicy) {
- errors.push(`${requestSanType} SAN is not allowed by template policy (not defined in template)`);
+ errors.push(`${requestSanType} SAN is not allowed by this policy`);
}
}
}
@@ -576,14 +564,14 @@ export const certificatePolicyServiceFactory = ({
if (request.signatureAlgorithm && template.algorithms?.signature && template.algorithms.signature.length > 0) {
const mappedTemplateAlgorithms = template.algorithms.signature.map(mapTemplateSignatureAlgorithmToApi);
if (!mappedTemplateAlgorithms.includes(request.signatureAlgorithm)) {
- errors.push(`Signature algorithm '${request.signatureAlgorithm}' is not allowed by template policy`);
+ errors.push(`Signature algorithm '${request.signatureAlgorithm}' is not allowed by this policy`);
}
}
if (request.keyAlgorithm && template.algorithms?.keyAlgorithm && template.algorithms.keyAlgorithm.length > 0) {
const mappedTemplateKeyTypes = template.algorithms.keyAlgorithm.map(mapTemplateKeyAlgorithmToApi);
if (!mappedTemplateKeyTypes.includes(request.keyAlgorithm)) {
- errors.push(`Key algorithm '${request.keyAlgorithm}' is not allowed by template policy`);
+ errors.push(`Key algorithm '${request.keyAlgorithm}' is not allowed by this policy`);
}
}
diff --git a/backend/src/services/certificate-policy/certificate-policy-types.ts b/backend/src/services/certificate-policy/certificate-policy-types.ts
index 11954206a0..cd71069a99 100644
--- a/backend/src/services/certificate-policy/certificate-policy-types.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-types.ts
@@ -19,23 +19,17 @@ export type TSingleValuedSubjectAttributeType = Exclude<
CertSubjectAttributeType.DOMAIN_COMPONENT
>;
-export interface TSingleValuedSubjectRule {
- type: TSingleValuedSubjectAttributeType;
+/**
+ * A domain component rule's values are comma-joined ordered sequences ("corp,example,com"), one per
+ * entry, matched position by position. Every other attribute type takes plain patterns.
+ */
+export interface TSubjectRule {
+ type: CertSubjectAttributeType;
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?: TSubjectRule[];
sans?: Array<{
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index 3257325d7d..1e3cc497a1 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -1140,13 +1140,13 @@ export const certificateV3ServiceFactory = ({
if (policy.algorithms?.keyAlgorithm && !effectiveKeyAlgorithm) {
throw new BadRequestError({
- message: "Key algorithm is required by template policy but not provided in request"
+ message: "Key algorithm is required by this policy but not provided in request"
});
}
if (policy.algorithms?.signature && !effectiveSignatureAlgorithm) {
throw new BadRequestError({
- message: "Signature algorithm is required by template policy but not provided in request"
+ message: "Signature algorithm is required by this policy but not provided in request"
});
}
diff --git a/frontend/src/hooks/api/certificatePolicies/index.tsx b/frontend/src/hooks/api/certificatePolicies/index.tsx
index 9195a3c612..f1d24c4c7a 100644
--- a/frontend/src/hooks/api/certificatePolicies/index.tsx
+++ b/frontend/src/hooks/api/certificatePolicies/index.tsx
@@ -13,7 +13,6 @@ export type {
TCertificatePolicyRule,
TCreateCertificatePolicyDTO,
TDeleteCertificatePolicyDTO,
- TDomainComponentSubjectRule,
TGetCertificatePolicyByIdDTO,
TListCertificatePoliciesDTO,
TSubjectRule,
diff --git a/frontend/src/hooks/api/certificatePolicies/types.ts b/frontend/src/hooks/api/certificatePolicies/types.ts
index 521ea01053..437149a8f5 100644
--- a/frontend/src/hooks/api/certificatePolicies/types.ts
+++ b/frontend/src/hooks/api/certificatePolicies/types.ts
@@ -1,22 +1,23 @@
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";
+/**
+ * A domain_component rule's values are comma-joined ordered sequences ("corp,example,com"), one per
+ * entry. Every other attribute type takes plain patterns.
+ */
+export type TSubjectRule = {
+ type:
+ | "common_name"
+ | "organization"
+ | "country"
+ | "state"
+ | "locality"
+ | "organizational_unit"
+ | "domain_component";
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?: TSubjectRule[];
sans?: Array<{
diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicySubjectRulesSection.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicySubjectRulesSection.tsx
index 47fb2c9370..1a1938ff6a 100644
--- a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicySubjectRulesSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicySubjectRulesSection.tsx
@@ -11,17 +11,19 @@ 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";
+const formatDomainComponentChain = (value: string) =>
+ value
+ .split(",")
+ .map((component) => `DC=${component.trim()}`)
+ .join(" ");
+
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;
@@ -48,20 +50,40 @@ export const PolicySubjectRulesSection = ({ policy }: Props) => {
</p>
) : (
<DetailGroup>
- {entries.map((rule, idx) => (
- <div
- // eslint-disable-next-line react/no-array-index-key
- key={`${rule.type}-${idx}`}
- className="flex flex-col gap-y-3 border-b border-mineshaft-700 pb-3 last:border-b-0 last:pb-0"
- >
- <div className="text-sm font-medium text-foreground">
- {formatSubjectAttributeType(rule.type as CertSubjectAttributeType)}
+ {entries.map((rule, idx) => {
+ const isDomainComponent = rule.type === CertSubjectAttributeType.DOMAIN_COMPONENT;
+ const formatter = isDomainComponent ? formatDomainComponentChain : undefined;
+
+ return (
+ <div
+ // eslint-disable-next-line react/no-array-index-key
+ key={`${rule.type}-${idx}`}
+ className="flex flex-col gap-y-3 border-b border-mineshaft-700 pb-3 last:border-b-0 last:pb-0"
+ >
+ <div className="text-sm font-medium text-foreground">
+ {formatSubjectAttributeType(rule.type as CertSubjectAttributeType)}
+ </div>
+ <RuleList
+ label="Allowed"
+ values={rule.allowed}
+ formatter={formatter}
+ isMonospace={isDomainComponent}
+ />
+ <RuleList
+ label="Required"
+ values={rule.required}
+ formatter={formatter}
+ isMonospace={isDomainComponent}
+ />
+ <RuleList
+ label="Denied"
+ values={rule.denied}
+ formatter={formatter}
+ isMonospace={isDomainComponent}
+ />
</div>
- <RuleList label="Allowed" values={toRuleValues(rule.allowed)} />
- <RuleList label="Required" values={toRuleValues(rule.required)} />
- <RuleList label="Denied" values={toRuleValues(rule.denied)} />
- </div>
- ))}
+ );
+ })}
</DetailGroup>
)}
</CardContent>
diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/RuleList.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/RuleList.tsx
index 59023b93e0..bcc11bb294 100644
--- a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/RuleList.tsx
+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/RuleList.tsx
@@ -4,9 +4,10 @@ type Props = {
label: string;
values?: string[];
formatter?: (value: string) => string;
+ isMonospace?: boolean;
};
-export const RuleList = ({ label, values, formatter }: Props) => {
+export const RuleList = ({ label, values, formatter, isMonospace }: Props) => {
if (!values || values.length === 0) return null;
return (
@@ -14,7 +15,11 @@ export const RuleList = ({ label, values, formatter }: Props) => {
<DetailLabel>{label}</DetailLabel>
<DetailValue className="flex flex-wrap gap-1">
{values.map((value) => (
- <Badge key={`${label}-${value}`} variant="neutral">
+ <Badge
+ key={`${label}-${value}`}
+ variant="neutral"
+ className={isMonospace ? "font-mono" : ""}
+ >
{formatter ? formatter(value) : value}
</Badge>
))}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
index 5ae8cbd1f5..cf63be065e 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
@@ -281,6 +281,7 @@ export const CertificateIssuanceModal = ({
reset,
watch,
setValue,
+ trigger,
formState,
formState: { isSubmitting }
} = useForm<FormData>({
@@ -539,11 +540,25 @@ export const CertificateIssuanceModal = ({
const selectedProfileReady = Boolean(profileId || actualSelectedProfileId);
const goBack = () => setStep((s) => Math.max(0, s - 1));
- const goNext = () => {
+ const goNext = async () => {
if (currentStepKey === "profile" && !selectedProfileReady) return;
+
+ const isStepValid = await trigger(STEP_FIELDS[currentStepKey] as (keyof FormData)[]);
+ if (!isStepValid) {
+ createNotification({ text: "Fix the errors on this step to continue.", type: "error" });
+ return;
+ }
+
setStep((s) => Math.min(stepKeys.length - 1, s + 1));
};
+ const rowErrorsOf = (fieldErrors: unknown): (string | undefined)[] | undefined =>
+ Array.isArray(fieldErrors)
+ ? (fieldErrors as ({ value?: { message?: string } } | undefined)[]).map(
+ (rowError) => rowError?.value?.message
+ )
+ : undefined;
+
const onFormInvalid = (errors: Record<string, unknown>) => {
const errorKeys = Object.keys(errors);
const idx = stepKeys.findIndex((key) =>
@@ -750,6 +765,9 @@ export const CertificateIssuanceModal = ({
(formState.errors as { subjectAttributes?: { message?: string } })
.subjectAttributes?.message
}
+ rowErrors={rowErrorsOf(
+ (formState.errors as { subjectAttributes?: unknown }).subjectAttributes
+ )}
/>
)}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
index 591a455a1a..0755b2b7ce 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAttributesField.tsx
@@ -57,6 +57,7 @@ type SubjectAttributesFieldProps = {
control: Control<any>;
allowedAttributeTypes: CertSubjectAttributeType[];
error?: string;
+ rowErrors?: (string | undefined)[];
shouldUnregister?: boolean;
namePrefix?: string;
};
@@ -65,6 +66,7 @@ export const SubjectAttributesField = ({
control,
allowedAttributeTypes,
error,
+ rowErrors,
shouldUnregister,
namePrefix = "subjectAttributes"
}: SubjectAttributesFieldProps) => {
@@ -118,16 +120,20 @@ export const SubjectAttributesField = ({
))}
</SelectContent>
</Select>
- <Input
- value={attr.value}
- onChange={(e) => {
- const newValue = [...currentValues];
- newValue[index] = { ...attr, value: e.target.value };
- onChange(newValue);
- }}
- placeholder={getSubjectAttributePlaceholder(attr.type)}
- className="flex-1"
- />
+ <div className="flex-1">
+ <Input
+ value={attr.value}
+ onChange={(e) => {
+ const newValue = [...currentValues];
+ newValue[index] = { ...attr, value: e.target.value };
+ onChange(newValue);
+ }}
+ placeholder={getSubjectAttributePlaceholder(attr.type)}
+ isError={Boolean(rowErrors?.[index])}
+ className="w-full"
+ />
+ <FieldError>{rowErrors?.[index]}</FieldError>
+ </div>
<IconButton
type="button"
variant="ghost"
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
index abe65929cc..d390485e19 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
@@ -16,8 +16,14 @@ import {
FieldError,
FieldGroup,
FieldLabel,
- IconButton,
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
Input,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupInput,
Select,
SelectContent,
SelectItem,
@@ -31,10 +37,7 @@ import {
StepperList,
StepperStep,
Switch,
- TextArea,
- Tooltip,
- TooltipContent,
- TooltipTrigger
+ TextArea
} from "@app/components/v3";
import { useProject, useSubscription } from "@app/context";
import {
@@ -67,20 +70,12 @@ import {
SUBJECT_ATTRIBUTE_TYPE_OPTIONS
} from "./shared/certificate-constants";
import { CERTIFICATE_POLICY_PRESETS } from "./shared/policy-presets";
-import {
- formatDomainComponentSequence,
- isValidDomainComponentSequence,
- parseDomainComponentSequence,
- PolicyFormData,
- policySchema
-} from "./shared";
+import { isValidDomainComponentSequence, 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"];
@@ -105,6 +100,38 @@ const ATTRIBUTE_TYPE_LABELS: Record<(typeof SUBJECT_ATTRIBUTE_TYPE_OPTIONS)[numb
domain_component: "Domain Component (DC)"
};
+const ATTRIBUTE_TYPE_ABBREVIATIONS: Record<
+ (typeof SUBJECT_ATTRIBUTE_TYPE_OPTIONS)[number],
+ string
+> = {
+ common_name: "CN",
+ organization: "O",
+ organizational_unit: "OU",
+ country: "C",
+ state: "ST",
+ locality: "L",
+ domain_component: "DC"
+};
+
+const ATTRIBUTE_TYPE_PLACEHOLDERS: Record<(typeof SUBJECT_ATTRIBUTE_TYPE_OPTIONS)[number], string> =
+ {
+ common_name: "*.example.com",
+ organization: "Acme Inc.",
+ organizational_unit: "Engineering",
+ country: "US",
+ state: "California",
+ locality: "San Francisco",
+ domain_component: "corp,example,com"
+ };
+
+const SAN_TYPE_PLACEHOLDERS: Record<(typeof SAN_TYPE_OPTIONS)[number], string> = {
+ dns_name: "*.example.com",
+ ip_address: "10.0.0.1",
+ email: "[email protected]",
+ uri: "spiffe://example.com/service",
+};
+
const SAN_TYPE_LABELS: Record<(typeof SAN_TYPE_OPTIONS)[number], string> = {
dns_name: "DNS Name",
ip_address: "IP Address",
@@ -216,39 +243,84 @@ const STEPS = [
}
] as const;
+const SUBJECT_INCLUDE_VERBS: Record<CertSubjectAttributeInclude, string> = {
+ [CertSubjectAttributeInclude.REQUIRED]: "Requires",
+ [CertSubjectAttributeInclude.OPTIONAL]: "Allows",
+ [CertSubjectAttributeInclude.PROHIBIT]: "Denies"
+};
+
+const AttributeRulePreview = ({
+ type,
+ include,
+ value
+}: {
+ type: CertSubjectAttributeType;
+ include: CertSubjectAttributeInclude;
+ value: string;
+}) => {
+ const trimmed = value.trim();
+ const verb = SUBJECT_INCLUDE_VERBS[include];
+ const isDenyRule = include === CertSubjectAttributeInclude.PROHIBIT;
+
+ if (type !== CertSubjectAttributeType.DOMAIN_COMPONENT || !trimmed) return null;
+
+ if (!isValidDomainComponentSequence(trimmed)) {
+ return (
+ <p className="mt-2 pl-1 text-2xs text-danger">
+ Every component must be non-empty, for example corp,example,com.
+ </p>
+ );
+ }
+
+ const chain = trimmed.split(",").map((component) => component.trim());
+ return (
+ <div className="mt-2 flex flex-wrap items-center gap-1.5 pl-1 text-2xs text-muted">
+ <span>{verb}</span>
+ <span className="font-mono text-label">
+ {chain.map((component) => `DC=${component}`).join(",")}
+ </span>
+ <span>
+ {isDenyRule ? "wherever they appear in the chain" : chain.length > 1 ? "in this order" : ""}
+ </span>
+ </div>
+ );
+};
+
const DomainComponentHelp = ({ isDenyRule }: { isDenyRule: boolean }) => (
- <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">
+ <HoverCard openDelay={150} closeDelay={150}>
+ <HoverCardTrigger asChild>
+ <InputGroupButton aria-label="Domain component format">
+ <Info />
+ </InputGroupButton>
+ </HoverCardTrigger>
+ <HoverCardContent side="bottom" align="end" className="w-96">
<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>
+ <dl className="mt-2.5 grid grid-cols-[auto_1fr] items-baseline gap-x-3 gap-y-1">
+ <dt className="whitespace-nowrap text-muted">Value</dt>
<dd className="font-mono">corp,example,com</dd>
- <dt className="text-muted">{isDenyRule ? "Rejects" : "Matches"}</dt>
+ <dt className={`whitespace-nowrap ${isDenyRule ? "text-danger" : "text-success"}`}>
+ {isDenyRule ? "Rejects" : "Matches"}
+ </dt>
<dd className="font-mono">DC=corp,DC=example,DC=com</dd>
- <dt className="text-muted">{isDenyRule ? "Also rejects" : "Rejects"}</dt>
+ <dt className="whitespace-nowrap text-danger">{isDenyRule ? "Also rejects" : "Rejects"}</dt>
<dd className="font-mono">
{isDenyRule ? "DC=host,DC=corp,DC=example,DC=com" : "DC=com,DC=example,DC=corp"}
</dd>
</dl>
- <p className="mt-2">
+ <p className="mt-2.5">
{isDenyRule
? "A denied chain is rejected wherever it appears, so denying a domain denies everything under it."
: "A request matches only when its components line up position by position."}
</p>
<p className="mt-2">
- A <span className="font-mono">*</span> matches a single component:{" "}
+ A <span className="font-mono text-accent">*</span> matches a single component:{" "}
<span className="font-mono">*,internal,example,com</span>.
</p>
- </TooltipContent>
- </Tooltip>
+ </HoverCardContent>
+ </HoverCard>
);
const DurationInput = ({
@@ -385,16 +457,10 @@ export const CreatePolicyModal = ({
const toAttributeRows = (
type: CertSubjectAttributeType,
- values: Array<string | string[]> | undefined,
+ values: string[] | undefined,
include: CertSubjectAttributeInclude
): AttributeRow[] =>
- Array.isArray(values)
- ? values.map((value) => ({
- type,
- include,
- value: [Array.isArray(value) ? formatDomainComponentSequence(value) : value]
- }))
- : [];
+ Array.isArray(values) ? values.map((value) => ({ type, include, value: [value] })) : [];
const convertApiToUiFormat = (policyData: TCertificatePolicy): FormData => {
const attributes: FormData["attributes"] = Array.isArray(policyData.subject)
@@ -634,23 +700,17 @@ 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 mergeRuleValues = (
+ existing: string[] | undefined,
+ incoming: string[] | undefined
+ ): string[] => Array.from(new Set([...(existing || []), ...(incoming || [])]));
const consolidateByType = <
T extends {
type: string;
- allowed?: Array<string | string[]>;
- required?: Array<string | string[]>;
- denied?: Array<string | string[]>;
+ allowed?: string[];
+ required?: string[];
+ denied?: string[];
}
>(
items: T[]
@@ -685,22 +745,11 @@ export const CreatePolicyModal = ({
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;
- }
-
const values = attr.value || [];
return {
type: attr.type,
...(values.length > 0 ? { [ruleKey]: values } : {})
- } as SingleValuedAttributeTransform;
+ } as AttributeTransform;
}) || [];
const sansRaw =
@@ -850,7 +899,7 @@ export const CreatePolicyModal = ({
{
type: SUBJECT_ATTRIBUTE_TYPE_OPTIONS[0],
include: SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS[1],
- value: ["*"]
+ value: []
}
]);
clearError("subject");
@@ -868,7 +917,7 @@ export const CreatePolicyModal = ({
const addSan = () => {
setValue("subjectAlternativeNames", [
...watchedSans,
- { type: SAN_TYPE_OPTIONS[0], include: SAN_INCLUDE_OPTIONS[1], value: ["*"] }
+ { type: SAN_TYPE_OPTIONS[0], include: SAN_INCLUDE_OPTIONS[1], value: [] }
]);
clearError("sans");
markCustomPreset();
@@ -1042,7 +1091,7 @@ export const CreatePolicyModal = ({
onClose();
}}
>
- <SheetContent className="flex h-full max-h-full flex-col gap-y-0 p-0 sm:max-w-[1100px]">
+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 p-0 sm:max-w-[1260px]">
<SheetHeader className="border-b border-border">
<SheetTitle>
<div className="flex w-full items-start gap-2">
@@ -1182,7 +1231,7 @@ export const CreatePolicyModal = ({
markCustomPreset();
}}
>
- <div className="space-y-3">
+ <div className="space-y-4">
{watchedAttributes.length === 0 && (
<p className="text-xs text-muted">
No attributes configured. Certificates issued under this policy cannot
@@ -1192,7 +1241,7 @@ export const CreatePolicyModal = ({
)}
{watchedAttributes.map((attr, index) => (
// eslint-disable-next-line react/no-array-index-key
- <div key={`attr-${index}`} className="space-y-2">
+ <div key={`attr-${index}`}>
<div className="flex items-center gap-2">
<Select
value={attr.type}
@@ -1203,8 +1252,8 @@ export const CreatePolicyModal = ({
markCustomPreset();
}}
>
- <SelectTrigger className="min-w-0 flex-1">
- <SelectValue />
+ <SelectTrigger className="w-18 shrink-0" aria-label="Attribute type">
+ {ATTRIBUTE_TYPE_ABBREVIATIONS[attr.type]}
</SelectTrigger>
<SelectContent position="popper">
{SUBJECT_ATTRIBUTE_TYPE_OPTIONS.map((type) => (
@@ -1227,7 +1276,7 @@ export const CreatePolicyModal = ({
markCustomPreset();
}}
>
- <SelectTrigger className="w-32 shrink-0">
+ <SelectTrigger className="w-24 shrink-0">
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
@@ -1238,11 +1287,30 @@ export const CreatePolicyModal = ({
))}
</SelectContent>
</Select>
- {attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT && (
- <DomainComponentHelp
- isDenyRule={attr.include === CertSubjectAttributeInclude.PROHIBIT}
+ <InputGroup className="min-w-0 flex-1">
+ <InputGroupInput
+ placeholder={ATTRIBUTE_TYPE_PLACEHOLDERS[attr.type]}
+ value={attr.value?.[0] || ""}
+ onChange={(e) => {
+ const next = [...watchedAttributes];
+ next[index] = {
+ ...attr,
+ value: e.target.value.trim() ? [e.target.value.trim()] : []
+ };
+ setValue("attributes", next);
+ markCustomPreset();
+ }}
/>
- )}
+ {attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT && (
+ <InputGroupAddon align="inline-end">
+ <DomainComponentHelp
+ isDenyRule={
+ attr.include === CertSubjectAttributeInclude.PROHIBIT
+ }
+ />
+ </InputGroupAddon>
+ )}
+ </InputGroup>
<Button
type="button"
variant="ghost"
@@ -1253,23 +1321,10 @@ export const CreatePolicyModal = ({
<Trash2 className="size-4" />
</Button>
</div>
- <Input
- placeholder={
- attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT
- ? "corp,example,com"
- : "Pattern/Value (use * for wildcards)"
- }
+ <AttributeRulePreview
+ type={attr.type}
+ include={attr.include}
value={attr.value?.[0] || ""}
- onChange={(e) => {
- const next = [...watchedAttributes];
- next[index] = {
- ...attr,
- value: e.target.value.trim() ? [e.target.value.trim()] : []
- };
- setValue("attributes", next);
- markCustomPreset();
- }}
- className="w-full"
/>
</div>
))}
@@ -1348,7 +1403,7 @@ export const CreatePolicyModal = ({
</SelectContent>
</Select>
<Input
- placeholder="Pattern/Value (use * for wildcards)"
+ placeholder={SAN_TYPE_PLACEHOLDERS[san.type]}
value={san.value?.[0] || ""}
onChange={(e) => {
const next = [...watchedSans];
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.ts
index 9b609d73c7..025595d6ed 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,15 +7,6 @@ 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);