Skip to content

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

feat(pki): support custom X.509 extensions on certificate policies and profiles

Carlos Monastyrskia63497691fc2
diff --git a/backend/src/db/migrations/20260831164512_add-custom-extensions-to-pki-policies-and-certificates.ts b/backend/src/db/migrations/20260831164512_add-custom-extensions-to-pki-policies-and-certificates.ts
new file mode 100644
index 0000000000..3289ec09ea
--- /dev/null
+++ b/backend/src/db/migrations/20260831164512_add-custom-extensions-to-pki-policies-and-certificates.ts
@@ -0,0 +1,33 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const TABLES_WITH_CUSTOM_EXTENSIONS = [
+ TableName.PkiCertificatePolicy,
+ TableName.CertificateRequests,
+ TableName.Certificate
+] as const;
+
+export async function up(knex: Knex): Promise<void> {
+ for await (const tableName of TABLES_WITH_CUSTOM_EXTENSIONS) {
+ if (await knex.schema.hasTable(tableName)) {
+ if (!(await knex.schema.hasColumn(tableName, "customExtensions"))) {
+ await knex.schema.alterTable(tableName, (t) => {
+ t.jsonb("customExtensions");
+ });
+ }
+ }
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ for await (const tableName of TABLES_WITH_CUSTOM_EXTENSIONS) {
+ if (await knex.schema.hasTable(tableName)) {
+ if (await knex.schema.hasColumn(tableName, "customExtensions")) {
+ await knex.schema.alterTable(tableName, (t) => {
+ t.dropColumn("customExtensions");
+ });
+ }
+ }
+ }
+}
diff --git a/backend/src/db/schemas/certificate-requests.ts b/backend/src/db/schemas/certificate-requests.ts
index 22ea43c03d..be7999b080 100644
--- a/backend/src/db/schemas/certificate-requests.ts
+++ b/backend/src/db/schemas/certificate-requests.ts
@@ -42,7 +42,8 @@ export const CertificateRequestsSchema = z.object({
encryptedPrivateKey: zodBuffer.nullable().optional(),
pendingMessage: z.string().nullable().optional(),
applicationId: z.string().uuid().nullable().optional(),
- domainComponents: z.string().nullable().optional()
+ domainComponents: z.string().nullable().optional(),
+ customExtensions: z.unknown().nullable().optional()
});
export type TCertificateRequests = z.infer<typeof CertificateRequestsSchema>;
diff --git a/backend/src/db/schemas/certificates.ts b/backend/src/db/schemas/certificates.ts
index bdf4c9ec4e..4473f0f04c 100644
--- a/backend/src/db/schemas/certificates.ts
+++ b/backend/src/db/schemas/certificates.ts
@@ -54,7 +54,8 @@ export const CertificatesSchema = z.object({
hsmKeyLabel: z.string().nullable().optional(),
hsmPublicKeySpki: zodBuffer.nullable().optional(),
subjectDomainComponents: z.string().nullable().optional(),
- orderId: z.string().uuid().default("00000000-0000-0000-0000-000000000000")
+ orderId: z.string().uuid().default("00000000-0000-0000-0000-000000000000"),
+ customExtensions: z.unknown().nullable().optional()
});
export type TCertificates = z.infer<typeof CertificatesSchema>;
diff --git a/backend/src/db/schemas/pki-certificate-policies.ts b/backend/src/db/schemas/pki-certificate-policies.ts
index 0269007fef..9564a3f562 100644
--- a/backend/src/db/schemas/pki-certificate-policies.ts
+++ b/backend/src/db/schemas/pki-certificate-policies.ts
@@ -20,7 +20,8 @@ export const PkiCertificatePoliciesSchema = z.object({
validity: z.unknown().nullable().optional(),
createdAt: z.date(),
updatedAt: z.date(),
- basicConstraints: z.unknown().nullable().optional()
+ basicConstraints: z.unknown().nullable().optional(),
+ customExtensions: z.unknown().nullable().optional()
});
export type TPkiCertificatePolicies = z.infer<typeof PkiCertificatePoliciesSchema>;
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 5301ca3c1a..b91d5f5bd5 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -3555,6 +3555,7 @@ interface CreateCertificatePolicy {
certificatePolicyId: string;
name: string;
projectId: string;
+ customExtensionOids?: string[];
}
| {
certificatePolicyId: string;
@@ -3574,6 +3575,7 @@ interface UpdateCertificatePolicy {
| {
certificatePolicyId: string;
name: string;
+ customExtensionOids?: string[];
}
| {
certificatePolicyId: string;
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.ts
index 176b3190e0..1744e7979f 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts
@@ -1080,7 +1080,8 @@ export const pkiAcmeServiceFactory = ({
// so forwarding a defaulted one would replace the identifier the client just validated.
const validationResult = await certificatePolicyService.validateCertificateRequest(
policy.id,
- applyProfileDefaults(updatedCertificateRequest, profile.defaults)
+ applyProfileDefaults(updatedCertificateRequest, profile.defaults),
+ { profileCustomExtensions: profile.defaults?.customExtensions }
);
if (!validationResult.isValid) {
throw new AcmeBadCSRError({ message: `Invalid CSR: ${validationResult.errors.join(", ")}` });
@@ -1106,6 +1107,7 @@ export const pkiAcmeServiceFactory = ({
status: CertificateRequestStatus.PENDING,
acmeOrderId: orderId,
csr,
+ customExtensions: validationResult.resolvedCustomExtensions,
ttl: updatedCertificateRequest.validity?.ttl,
enrollmentType: EnrollmentType.ACME,
organization: updatedCertificateRequest.organization || undefined,
@@ -1123,6 +1125,7 @@ export const pkiAcmeServiceFactory = ({
certificateId: orderId,
profileId: profile.id,
caId: profile.caId || "",
+ customExtensions: validationResult.resolvedCustomExtensions,
ttl: updatedCertificateRequest.validity?.ttl || "47d",
signatureAlgorithm: updatedCertificateRequest.signatureAlgorithm || "",
keyAlgorithm: updatedCertificateRequest.keyAlgorithm || "",
@@ -1264,7 +1267,8 @@ export const pkiAcmeServiceFactory = ({
// key actually is, which would fail a policy the CSR itself satisfies.
const validationResult = await certificatePolicyService.validateCertificateRequest(
policy.id,
- applyProfileDefaults({ ...certificateRequest, ...extractAlgorithmsFromCSR(csr) }, profile.defaults)
+ applyProfileDefaults({ ...certificateRequest, ...extractAlgorithmsFromCSR(csr) }, profile.defaults),
+ { profileCustomExtensions: profile.defaults?.customExtensions }
);
if (!validationResult.isValid) {
throw new AcmeBadCSRError({ message: `Invalid CSR: ${validationResult.errors.join(", ")}` });
@@ -1273,6 +1277,7 @@ export const pkiAcmeServiceFactory = ({
return {
approvalPolicy: matchedApprovalPolicy,
policy,
+ resolvedCustomExtensions: validationResult.resolvedCustomExtensions,
policySteps: await approvalPolicyDAL.findStepsByPolicyId(matchedApprovalPolicy.id)
};
})()
@@ -1342,6 +1347,9 @@ export const pkiAcmeServiceFactory = ({
ttl,
enrollmentType: EnrollmentType.ACME,
status: CertificateRequestStatus.PENDING_APPROVAL,
+ customExtensions: approvalContext?.resolvedCustomExtensions
+ ? JSON.stringify(approvalContext.resolvedCustomExtensions)
+ : null,
organization: certificateRequest.organization || null,
organizationalUnit: certificateRequest.organizationalUnit || null,
country: certificateRequest.country || null,
diff --git a/backend/src/ee/services/pki-scep/pki-scep-service.ts b/backend/src/ee/services/pki-scep/pki-scep-service.ts
index 12fa66b830..7557f7f28a 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-service.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-service.ts
@@ -911,7 +911,8 @@ export const pkiScepServiceFactory = ({
validity: { ttl }
},
profile.defaults
- )
+ ),
+ { profileCustomExtensions: profile.defaults?.customExtensions }
);
if (!validationResult.isValid) {
throw new BadRequestError({
@@ -937,6 +938,7 @@ export const pkiScepServiceFactory = ({
csr: csrPem,
ttl,
status: CertificateRequestStatus.PENDING,
+ customExtensions: validationResult.resolvedCustomExtensions,
enrollmentType: EnrollmentType.SCEP,
organization: certRequest.organization,
organizationalUnit: certRequest.organizationalUnit,
@@ -950,6 +952,7 @@ export const pkiScepServiceFactory = ({
certificateId: newCertRequest.id,
profileId: profile.id,
caId: profile.caId!,
+ customExtensions: validationResult.resolvedCustomExtensions,
ttl,
signatureAlgorithm: signatureAlgorithm || "",
keyAlgorithm: keyAlgorithm || "",
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 22cf146060..764fc11afb 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2285,6 +2285,12 @@ const domainComponentRule = (rule: string) =>
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 = {
+ CUSTOM_EXTENSION_RULES:
+ "Rules for custom X.509 extensions, one per OID. Omit the field to leave custom extensions unconstrained; send an empty array to forbid them entirely.",
+ CUSTOM_EXTENSION_RULE: {
+ rule: "Whether the value pattern allows, requires, or denies this extension. Require also makes the extension mandatory.",
+ value: "The value pattern this rule matches against, with * as a wildcard. Use * on its own to match any value."
+ },
SUBJECT_DOMAIN_COMPONENT_RULE: {
allowed: domainComponentRule("permitted"),
required: domainComponentRule("required"),
diff --git a/backend/src/server/routes/v1/certificate-policy-router.ts b/backend/src/server/routes/v1/certificate-policy-router.ts
index 2d40f88fed..113e0b4459 100644
--- a/backend/src/server/routes/v1/certificate-policy-router.ts
+++ b/backend/src/server/routes/v1/certificate-policy-router.ts
@@ -2,7 +2,7 @@ import RE2 from "re2";
import { z } from "zod";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { ApiDocsTags } from "@app/lib/api-docs";
+import { ApiDocsTags, CERTIFICATE_POLICIES } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { openApiHidden, slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
@@ -17,6 +17,7 @@ import {
} from "@app/services/certificate-common/certificate-constants";
import {
certificatePolicyResponseSchema,
+ policyCustomExtensionSchema,
policySubjectSchema
} from "@app/services/certificate-policy/certificate-policy-schemas";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
@@ -169,7 +170,8 @@ const createCertificatePolicySchema = z.object({
extendedKeyUsages: policyExtendedKeyUsagesSchema.nullish(),
algorithms: policyAlgorithmsSchema.nullish(),
validity: policyValiditySchema.nullish(),
- basicConstraints: policyBasicConstraintsSchema.optional()
+ basicConstraints: policyBasicConstraintsSchema.optional(),
+ customExtensions: z.array(policyCustomExtensionSchema).nullish().describe(CERTIFICATE_POLICIES.CUSTOM_EXTENSION_RULES)
});
const updateCertificatePolicySchema = z.object({
@@ -181,7 +183,8 @@ const updateCertificatePolicySchema = z.object({
extendedKeyUsages: policyExtendedKeyUsagesSchema.nullish(),
algorithms: policyAlgorithmsSchema.nullish(),
validity: policyValiditySchema.nullish(),
- basicConstraints: policyBasicConstraintsSchema.optional()
+ basicConstraints: policyBasicConstraintsSchema.optional(),
+ customExtensions: z.array(policyCustomExtensionSchema).nullish().describe(CERTIFICATE_POLICIES.CUSTOM_EXTENSION_RULES)
});
export const registerCertificatePolicyRouter = async (server: FastifyZodProvider) => {
@@ -221,7 +224,10 @@ export const registerCertificatePolicyRouter = async (server: FastifyZodProvider
metadata: {
certificatePolicyId: certificatePolicy.id,
name: certificatePolicy.name,
- projectId: certificatePolicy.projectId
+ projectId: certificatePolicy.projectId,
+ ...(certificatePolicy.customExtensions && {
+ customExtensionOids: certificatePolicy.customExtensions.map((rule) => rule.oid)
+ })
}
}
});
@@ -377,7 +383,10 @@ export const registerCertificatePolicyRouter = async (server: FastifyZodProvider
type: EventType.UPDATE_CERTIFICATE_POLICY,
metadata: {
certificatePolicyId: certificatePolicy.id,
- name: certificatePolicy.name
+ name: certificatePolicy.name,
+ ...(certificatePolicy.customExtensions && {
+ customExtensionOids: certificatePolicy.customExtensions.map((rule) => rule.oid)
+ })
}
}
});
diff --git a/backend/src/server/routes/v1/certificate-profiles-router.ts b/backend/src/server/routes/v1/certificate-profiles-router.ts
index f35672978c..60efc7a55c 100644
--- a/backend/src/server/routes/v1/certificate-profiles-router.ts
+++ b/backend/src/server/routes/v1/certificate-profiles-router.ts
@@ -13,11 +13,15 @@ import { AuthMode } from "@app/services/auth/auth-type";
import { CertStatus } from "@app/services/certificate/certificate-types";
import {
CertExtendedKeyUsageType,
+ certificateExtensionOidSchema,
CertKeyAlgorithm,
CertKeyUsageType,
CertSignatureAlgorithm,
CertSubjectAlternativeNameType,
+ customExtensionLabelSchema,
+ customExtensionValueSchema,
domainComponentsSchema,
+ MAX_CUSTOM_EXTENSIONS_PER_PROFILE,
pkiDescriptionSchema,
subjectAttributeSchema
} from "@app/services/certificate-common/certificate-constants";
@@ -34,6 +38,18 @@ const SubjectAltNameDefaultsSchema = z
)
.optional();
+const CustomExtensionDefaultsSchema = z
+ .array(
+ z.object({
+ oid: certificateExtensionOidSchema,
+ label: customExtensionLabelSchema.optional(),
+ critical: z.boolean().optional(),
+ value: customExtensionValueSchema.optional()
+ })
+ )
+ .max(MAX_CUSTOM_EXTENSIONS_PER_PROFILE)
+ .optional();
+
// Subject defaults are stored as jsonb on the profile but are copied verbatim onto the certificate
// request at issuance time, where each attribute lands in a varchar(255) column — so they carry the
// same bound as an explicitly supplied subject attribute.
@@ -57,7 +73,8 @@ const CertificateProfileDefaultsSchema = z
state: subjectAttributeSchema.optional(),
locality: subjectAttributeSchema.optional(),
subjectAltNames: SubjectAltNameDefaultsSchema,
- domainComponents: domainComponentsSchema.optional()
+ domainComponents: domainComponentsSchema.optional(),
+ customExtensions: CustomExtensionDefaultsSchema
})
.nullish();
@@ -81,7 +98,8 @@ const CertificateProfileDefaultsResponseSchema = z
state: z.string().optional(),
locality: z.string().optional(),
subjectAltNames: SubjectAltNameDefaultsSchema,
- domainComponents: z.array(z.string()).optional()
+ domainComponents: z.array(z.string()).optional(),
+ customExtensions: CustomExtensionDefaultsSchema
})
.nullish();
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index 39a51bd018..e22247c986 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -5,6 +5,7 @@ import { z } from "zod";
import { CertificatesSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, CERTIFICATES } from "@app/lib/api-docs";
+import { BadRequestError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
import { isUuidV4 } from "@app/lib/validator";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -21,6 +22,8 @@ import {
certificateAttributesSchema,
CertKeyUsageType,
CertSubjectAlternativeNameType,
+ CUSTOM_EXTENSIONS_WITH_CSR_ERROR_MESSAGE,
+ resolvedCustomExtensionSchema,
subjectAttributeSchema
} from "@app/services/certificate-common/certificate-constants";
import { extractCertificateRequestFromCSR } from "@app/services/certificate-common/certificate-csr-utils";
@@ -89,6 +92,7 @@ interface CertificateRequestForService {
isCA: boolean;
pathLength?: number;
};
+ customExtensions?: Array<{ oid: string; value?: string; critical?: boolean }>;
}
const validateTtlAndDateFields = (data: {
@@ -178,6 +182,11 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const { csr, attributes, metadata, ...requestBody } = req.body;
+
+ if (csr && attributes?.customExtensions?.length) {
+ throw new BadRequestError({ message: CUSTOM_EXTENSIONS_WITH_CSR_ERROR_MESSAGE });
+ }
+
const profile = await server.services.certificateProfile.getProfileById({
actor: req.permission.type,
actorId: req.permission.id,
@@ -217,7 +226,8 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
organizationalUnit: attributes?.organizationalUnit ?? undefined,
country: attributes?.country ?? undefined,
state: attributes?.state ?? undefined,
- locality: attributes?.locality ?? undefined
+ locality: attributes?.locality ?? undefined,
+ customExtensions: attributes?.customExtensions
};
const data = await server.services.certificateV3.orderCertificate({
@@ -328,7 +338,8 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
notAfter: attributes?.notAfter ? new Date(attributes.notAfter) : undefined,
signatureAlgorithm: attributes?.signatureAlgorithm,
keyAlgorithm: attributes?.keyAlgorithm,
- basicConstraints: attributes?.basicConstraints
+ basicConstraints: attributes?.basicConstraints,
+ customExtensions: attributes?.customExtensions
};
// Only include subject fields when explicitly provided (null or string).
@@ -437,6 +448,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
.nullable()
.optional(),
metadata: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
+ customExtensions: z.array(resolvedCustomExtensionSchema).nullable().optional(),
createdAt: z.date(),
updatedAt: z.date()
})
diff --git a/backend/src/services/approval-policy/cert-request/cert-request-policy-schemas.ts b/backend/src/services/approval-policy/cert-request/cert-request-policy-schemas.ts
index d8e31d38d9..6a3cef4446 100644
--- a/backend/src/services/approval-policy/cert-request/cert-request-policy-schemas.ts
+++ b/backend/src/services/approval-policy/cert-request/cert-request-policy-schemas.ts
@@ -1,6 +1,9 @@
import { z } from "zod";
-import { domainComponentSchema } from "@app/services/certificate-common/certificate-constants";
+import {
+ domainComponentSchema,
+ resolvedCustomExtensionSchema
+} from "@app/services/certificate-common/certificate-constants";
import {
BaseApprovalPolicySchema,
@@ -57,7 +60,8 @@ export const CertRequestPolicyRequestDataSchema = z.object({
isCA: z.boolean(),
pathLength: z.number().optional()
})
- .optional()
+ .optional(),
+ customExtensions: z.array(resolvedCustomExtensionSchema).optional()
}),
certificateRequestId: z.string().uuid()
});
diff --git a/backend/src/services/cert-manager-export/cert-manager-export-service.ts b/backend/src/services/cert-manager-export/cert-manager-export-service.ts
index c9b5fb6c9a..f29b3c77af 100644
--- a/backend/src/services/cert-manager-export/cert-manager-export-service.ts
+++ b/backend/src/services/cert-manager-export/cert-manager-export-service.ts
@@ -337,6 +337,7 @@ export const certManagerExportServiceFactory = ({
sans: toJsonbValue(sourcePolicy.sans),
keyUsages: toJsonbValue(sourcePolicy.keyUsages),
extendedKeyUsages: toJsonbValue(sourcePolicy.extendedKeyUsages),
+ customExtensions: toJsonbValue(sourcePolicy.customExtensions),
algorithms: toJsonbValue(sourcePolicy.algorithms),
validity: toJsonbValue(sourcePolicy.validity),
basicConstraints: toJsonbValue(sourcePolicy.basicConstraints)
diff --git a/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts
index effb70f45b..f5a93449e2 100644
--- a/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts
@@ -32,6 +32,11 @@ import {
CrlReason
} from "@app/services/certificate/certificate-types";
import { generateLeafKeypairAndCsr } from "@app/services/certificate-common/certificate-csr-utils";
+import {
+ findDroppedCustomExtensionOids,
+ parseIssuedCustomExtensions,
+ TResolvedCustomExtension
+} from "@app/services/certificate-common/certificate-extension-fns";
import { calculateFinalRenewBeforeDays } from "@app/services/certificate-common/certificate-issuance-utils";
import { CertificateRequestCancelledError } from "@app/services/certificate-common/certificate-request-errors";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
@@ -408,7 +413,8 @@ export const ADCSCertificateAuthorityFns = ({
csr,
isRenewal,
originalCertificateId,
- isCancelled
+ isCancelled,
+ customExtensions
}: {
caId: string;
profileId?: string;
@@ -424,6 +430,7 @@ export const ADCSCertificateAuthorityFns = ({
isRenewal?: boolean;
originalCertificateId?: string;
isCancelled?: () => Promise<boolean>;
+ customExtensions?: TResolvedCustomExtension[];
}) => {
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
if (!ca.externalCa || ca.externalCa.type !== CaType.ADCS) {
@@ -497,12 +504,29 @@ export const ADCSCertificateAuthorityFns = ({
let skLeaf: string | undefined;
let csrDerBase64: string;
if (csr) {
+ const csrExtensionValues = new Map(
+ new x509.Pkcs10CertificateRequest(csr).extensions.map((entry) => [
+ entry.type,
+ Buffer.from(new Uint8Array(entry.value)).toString("base64")
+ ])
+ );
+ const mismatched = (customExtensions ?? []).find(
+ (extension) => csrExtensionValues.get(extension.oid) !== extension.value
+ );
+ if (mismatched) {
+ throw new BadRequestError({
+ message: csrExtensionValues.has(mismatched.oid)
+ ? `Custom extension '${mismatched.oid}' in the certificate signing request does not carry the value this policy resolved, and Active Directory Certificate Services is given that request unchanged. Correct the request, or let Infisical generate the key.`
+ : `Custom extension '${mismatched.oid}' must be present in the certificate signing request you supply, because Active Directory Certificate Services is given that request unchanged. Include it, or let Infisical generate the key.`
+ });
+ }
csrDerBase64 = Buffer.from(new Uint8Array(new x509.Pkcs10CertificateRequest(csr).rawData)).toString("base64");
} else {
const generated = await generateLeafKeypairAndCsr({
subjectName: buildSubjectDN(commonName),
algorithm: alg,
- altNames
+ altNames,
+ customExtensions
});
skLeaf = generated.privateKeyPem;
csrDerBase64 = generated.csrDerBase64;
@@ -561,6 +585,8 @@ export const ADCSCertificateAuthorityFns = ({
let certificateId: string;
+ const droppedOids = findDroppedCustomExtensionOids(Buffer.from(cleanedCertificatePem), customExtensions);
+
await certificateDAL.transaction(async (tx) => {
const cert = await certificateDAL.create(
{
@@ -578,6 +604,9 @@ export const ADCSCertificateAuthorityFns = ({
keyAlgorithm,
signatureAlgorithm: extractIssuedSignatureAlgorithm(certObj) ?? signatureAlgorithm,
projectId: ca.projectId,
+ customExtensions: JSON.stringify(
+ parseIssuedCustomExtensions(Buffer.from(cleanedCertificatePem), customExtensions)
+ ),
renewedFromCertificateId: isRenewal && originalCertificateId ? originalCertificateId : null
},
tx
@@ -626,6 +655,15 @@ export const ADCSCertificateAuthorityFns = ({
}
});
+ if (droppedOids.length) {
+ logger.warn(
+ `Active Directory Certificate Services dropped custom extensions this profile declared [caId=${ca.id}] [profileId=${profileId}] [certificateId=${certificateId!}] [oids=${droppedOids.join(",")}]`
+ );
+ throw new BadRequestError({
+ message: `Active Directory Certificate Services issued a certificate without ${droppedOids.join(", ")}, so it does not carry what this profile declared. The certificate is recorded so you can revoke it. Add each object identifier to the certificate authority's EnableRequestExtensionList and restart certsvc, then request again.`
+ });
+ }
+
return {
certificate: cleanedCertificatePem,
certificateChain: certificateChainPem,
diff --git a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts
index 69efbe1f15..14ab17c5be 100644
--- a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts
@@ -42,6 +42,11 @@ import {
getSanOtherNameOid,
mapSanTypeToX509Type
} from "@app/services/certificate/certificate-types";
+import {
+ appendCustomExtensions,
+ assertAwsPcaCustomExtensionLimit,
+ TResolvedCustomExtension
+} from "@app/services/certificate-common/certificate-extension-fns";
import { buildIdempotencyToken } from "@app/services/certificate-common/certificate-issuance-utils";
import { CertificateRequestCancelledError } from "@app/services/certificate-common/certificate-request-errors";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
@@ -574,6 +579,7 @@ export const AwsPcaCertificateAuthorityFns = ({
state,
locality,
basicConstraints,
+ customExtensions,
isCancelled
}: {
caId: string;
@@ -598,6 +604,7 @@ export const AwsPcaCertificateAuthorityFns = ({
state?: string;
locality?: string;
basicConstraints?: { isCA: boolean; pathLength?: number | null } | null;
+ customExtensions?: TResolvedCustomExtension[];
isCancelled?: () => Promise<boolean>;
}) => {
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
@@ -676,6 +683,8 @@ export const AwsPcaCertificateAuthorityFns = ({
);
}
+ appendCustomExtensions(extensions, customExtensions);
+
// Build the DN via x509.Name (RFC 4514 escaping) rather than raw string concat so that
// special characters in the attributes cannot inject additional RDNs.
const subjectDn =
@@ -752,6 +761,18 @@ export const AwsPcaCertificateAuthorityFns = ({
SubjectAlternativeNames: altNames.map(sanToGeneralName)
};
}
+ if (customExtensions?.length) {
+ assertAwsPcaCustomExtensionLimit(customExtensions.length);
+
+ apiPassthrough.Extensions = {
+ ...apiPassthrough.Extensions,
+ CustomExtensions: customExtensions.map((extension) => ({
+ ObjectIdentifier: extension.oid,
+ Value: extension.value,
+ Critical: extension.critical
+ }))
+ };
+ }
const issueResult = await pcaClient.send(
new IssueCertificateCommand({
@@ -802,7 +823,7 @@ export const AwsPcaCertificateAuthorityFns = ({
let certificateId: string;
- const parsedFields = extractCertificateFields(Buffer.from(certificatePem));
+ const parsedFields = extractCertificateFields(Buffer.from(certificatePem), customExtensions);
await certificateDAL.transaction(async (tx) => {
const cert = await certificateDAL.create(
diff --git a/backend/src/services/certificate-authority/certificate-authority-enums.ts b/backend/src/services/certificate-authority/certificate-authority-enums.ts
index cd5a8f0e11..335bbe1365 100644
--- a/backend/src/services/certificate-authority/certificate-authority-enums.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-enums.ts
@@ -34,5 +34,6 @@ export enum CaRenewalStatus {
export enum CaCapability {
ISSUE_CERTIFICATES = "issue-certificates",
REVOKE_CERTIFICATES = "revoke-certificates",
- RENEW_CERTIFICATES = "renew-certificates"
+ RENEW_CERTIFICATES = "renew-certificates",
+ CUSTOM_EXTENSIONS = "custom-extensions"
}
diff --git a/backend/src/services/certificate-authority/certificate-authority-maps.ts b/backend/src/services/certificate-authority/certificate-authority-maps.ts
index 0ed36285ab..b1ebacb86a 100644
--- a/backend/src/services/certificate-authority/certificate-authority-maps.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-maps.ts
@@ -1,3 +1,5 @@
+import { BadRequestError } from "@app/lib/errors";
+
import { CaCapability, CaType } from "./certificate-authority-enums";
export const CERTIFICATE_AUTHORITIES_TYPE_MAP: Record<CaType, string> = {
@@ -16,7 +18,8 @@ export const CERTIFICATE_AUTHORITIES_CAPABILITIES_MAP: Record<CaType, CaCapabili
[CaType.INTERNAL]: [
CaCapability.ISSUE_CERTIFICATES,
CaCapability.REVOKE_CERTIFICATES,
- CaCapability.RENEW_CERTIFICATES
+ CaCapability.RENEW_CERTIFICATES,
+ CaCapability.CUSTOM_EXTENSIONS
],
[CaType.ACME]: [CaCapability.ISSUE_CERTIFICATES, CaCapability.REVOKE_CERTIFICATES, CaCapability.RENEW_CERTIFICATES],
[CaType.AZURE_AD_CS]: [
@@ -24,11 +27,17 @@ export const CERTIFICATE_AUTHORITIES_CAPABILITIES_MAP: Record<CaType, CaCapabili
CaCapability.RENEW_CERTIFICATES
// Note: REVOKE_CERTIFICATES intentionally omitted - not supported by ADCS connector
],
- [CaType.ADCS]: [CaCapability.ISSUE_CERTIFICATES, CaCapability.REVOKE_CERTIFICATES, CaCapability.RENEW_CERTIFICATES],
+ [CaType.ADCS]: [
+ CaCapability.ISSUE_CERTIFICATES,
+ CaCapability.REVOKE_CERTIFICATES,
+ CaCapability.RENEW_CERTIFICATES,
+ CaCapability.CUSTOM_EXTENSIONS
+ ],
[CaType.AWS_PCA]: [
CaCapability.ISSUE_CERTIFICATES,
CaCapability.REVOKE_CERTIFICATES,
- CaCapability.RENEW_CERTIFICATES
+ CaCapability.RENEW_CERTIFICATES,
+ CaCapability.CUSTOM_EXTENSIONS
],
[CaType.DIGICERT]: [
CaCapability.ISSUE_CERTIFICATES,
@@ -72,3 +81,11 @@ export const CERTIFICATE_AUTHORITIES_EXTERNAL_ISSUANCE_MAP: Record<CaType, boole
export const caUsesExternalIssuanceQueue = (caType: CaType): boolean =>
CERTIFICATE_AUTHORITIES_EXTERNAL_ISSUANCE_MAP[caType] ?? false;
+
+export const assertCaSupportsCustomExtensions = (caType: CaType, count: number): void => {
+ if (!count || caSupportsCapability(caType, CaCapability.CUSTOM_EXTENSIONS)) return;
+
+ throw new BadRequestError({
+ message: `${CERTIFICATE_AUTHORITIES_TYPE_MAP[caType] ?? caType} certificate authorities cannot carry custom extensions, but this request resolved ${count} of them. Update the certificate profile.`
+ });
+};
diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
index 0d3cdd36ba..4dfa9c0cd7 100644
--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts
+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
@@ -13,6 +13,7 @@ import {
CertKeyUsage,
CertSubjectAlternativeNameType
} from "@app/services/certificate/certificate-types";
+import { TResolvedCustomExtension } from "@app/services/certificate-common/certificate-extension-fns";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
import { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -66,6 +67,7 @@ import { AzureAdCsCertificateAuthorityFns } from "./azure-ad-cs/azure-ad-cs-cert
import { TCertificateAuthorityDALFactory } from "./certificate-authority-dal";
import { CaType } from "./certificate-authority-enums";
import { keyAlgorithmToAlgCfg } from "./certificate-authority-fns";
+import { assertCaSupportsCustomExtensions } from "./certificate-authority-maps";
import { DigiCertCertificateAuthorityFns } from "./digicert/digicert-certificate-authority-fns";
import { TExternalCertificateAuthorityDALFactory } from "./external-certificate-authority-dal";
import { GoDaddyCertificateAuthorityFns } from "./godaddy/godaddy-certificate-authority-fns";
@@ -142,6 +144,7 @@ export type TIssueCertificateFromProfileJobData = {
locality?: string;
applicationId?: string;
basicConstraints?: { isCA: boolean; pathLength?: number | null } | null;
+ customExtensions?: TResolvedCustomExtension[];
};
type TCertificateIssuanceQueueFactoryDep = {
@@ -326,54 +329,8 @@ export const certificateIssuanceQueueFactory = ({
/**
* Queue a certificate issuance job.
*/
- const queueCertificateIssuance = async ({
- certificateId,
- profileId,
- caId,
- caType,
- commonName,
- altNames,
- ttl,
- signatureAlgorithm,
- keyAlgorithm,
- keyUsages,
- extendedKeyUsages,
- isRenewal,
- originalCertificateId,
- certificateRequestId,
- csr,
- organization,
- organizationalUnit,
- country,
- state,
- locality,
- applicationId,
- basicConstraints
- }: TIssueCertificateFromProfileJobData) => {
- const jobData: TIssueCertificateFromProfileJobData = {
- certificateId,
- profileId,
- caId,
- caType,
- commonName,
- altNames,
- ttl,
- signatureAlgorithm,
- keyAlgorithm,
- keyUsages,
- extendedKeyUsages,
- isRenewal,
- originalCertificateId,
- certificateRequestId,
- csr,
- organization,
- organizationalUnit,
- country,
- state,
- locality,
- applicationId,
- basicConstraints
- };
+ const queueCertificateIssuance = async (jobData: TIssueCertificateFromProfileJobData) => {
+ const { caType, certificateId, certificateRequestId } = jobData;
// ACM DNS validation can take 5–30 minutes; the function is fully idempotent via
// IdempotencyToken, so we poll longer with a fixed backoff instead of exponential.
@@ -423,7 +380,8 @@ export const certificateIssuanceQueueFactory = ({
country,
state,
locality,
- basicConstraints
+ basicConstraints,
+ customExtensions
} = data;
const setPending = async (message: string) => {
@@ -467,6 +425,10 @@ export const certificateIssuanceQueueFactory = ({
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (customExtensions?.length) {
+ assertCaSupportsCustomExtensions((ca.externalCa?.type ?? CaType.INTERNAL) as CaType, customExtensions.length);
+ }
+
await setPending("Starting certificate issuance");
if (ca.externalCa?.type === CaType.ACME) {
@@ -646,6 +608,7 @@ export const certificateIssuanceQueueFactory = ({
const template = await extractProfileTemplate(certificateProfileDAL, profileId);
const adcsParams = {
+ customExtensions,
caId,
profileId,
commonName: commonName || "",
@@ -800,6 +763,7 @@ export const certificateIssuanceQueueFactory = ({
state,
locality,
basicConstraints,
+ customExtensions,
isCancelled
};
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
index f813a0f74f..08eddbfcb9 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
@@ -32,6 +32,7 @@ import { alphaNumericNanoId } from "@app/lib/nanoid";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
+import { CERT_SUBJECT_ALTERNATIVE_NAMES } from "@app/services/certificate-common/certificate-constants";
import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { ActiveCerts } from "@app/services/license-client";
@@ -61,6 +62,7 @@ import {
PKI_TEXT_COLUMN_MAX_LENGTH,
SUPPORTED_GENERAL_NAME_TYPES
} from "../../certificate-common/certificate-constants";
+import { appendCustomExtensions } from "../../certificate-common/certificate-extension-fns";
import { validatePqcLicense } from "../../certificate-common/certificate-utils";
import { TCertificateTemplateDALFactory } from "../../certificate-template/certificate-template-dal";
import { validateCertificateDetailsAgainstTemplate } from "../../certificate-template/certificate-template-fns";
@@ -1812,6 +1814,7 @@ export const internalCertificateAuthorityServiceFactory = ({
friendlyName,
commonName,
altNames,
+ altNameEntries,
ttl,
notBefore,
notAfter,
@@ -1826,6 +1829,7 @@ export const internalCertificateAuthorityServiceFactory = ({
isFromProfile,
internal = false,
basicConstraints,
+ customExtensions,
pathLength,
organization,
country,
@@ -2100,7 +2104,12 @@ export const internalCertificateAuthorityServiceFactory = ({
let altNamesArray: TAltNameMapping[] = [];
- if (altNames) {
+ if (altNameEntries?.length) {
+ altNamesArray = altNameEntries.map(({ type, value }) => ({
+ type: CERT_SUBJECT_ALTERNATIVE_NAMES[type].generalNameType,
+ value
+ }));
+ } else if (altNames) {
altNamesArray = altNames
.split(",")
.map((name) => name.trim())
@@ -2111,12 +2120,16 @@ export const internalCertificateAuthorityServiceFactory = ({
}
return altNameType;
});
+ }
+ if (altNamesArray.length) {
// RFC 5280 4.1.2.6: subjectAltName must be marked critical when the subject is an empty sequence
const altNamesExtension = new x509.SubjectAlternativeNameExtension(altNamesArray, leafDn.trim().length === 0);
extensions.push(altNamesExtension);
}
+ appendCustomExtensions(extensions, customExtensions);
+
if (certificateTemplate) {
validateCertificateDetailsAgainstTemplate(
{
@@ -2175,7 +2188,7 @@ export const internalCertificateAuthorityServiceFactory = ({
const executeIssueCertOperations = async (transaction: Knex) => {
// Extract certificate fields for storage
const certificatePem = leafCert.toString("pem");
- const parsedFields = extractCertificateFields(Buffer.from(certificatePem));
+ const parsedFields = extractCertificateFields(Buffer.from(certificatePem), customExtensions);
const cert = await certificateDAL.create(
{
@@ -2281,6 +2294,7 @@ export const internalCertificateAuthorityServiceFactory = ({
basicConstraints,
pathLength,
subjectOverride,
+ customExtensions,
tx
} = dto;
@@ -2605,6 +2619,8 @@ export const internalCertificateAuthorityServiceFactory = ({
extensions.push(altNamesExtension);
}
+ appendCustomExtensions(extensions, customExtensions);
+
if (certificateTemplate) {
validateCertificateDetailsAgainstTemplate(
{
@@ -2652,7 +2668,7 @@ export const internalCertificateAuthorityServiceFactory = ({
const createSignedCert = async (transaction: Knex) => {
// Extract certificate fields for storage
const certificatePem = leafCert.toString("pem");
- const parsedFields = extractCertificateFields(Buffer.from(certificatePem));
+ const parsedFields = extractCertificateFields(Buffer.from(certificatePem), customExtensions);
const newCert = await certificateDAL.create(
{
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
index 441bf8ed86..eda4274685 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
@@ -12,6 +12,8 @@ import {
CertKeyUsage,
CertSignatureAlgorithm
} from "@app/services/certificate/certificate-types";
+import { CertSubjectAlternativeNameType } from "@app/services/certificate-common/certificate-constants";
+import { TResolvedCustomExtension } from "@app/services/certificate-common/certificate-extension-fns";
import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -223,6 +225,7 @@ type TIssueCertFromCaBaseDTO = {
friendlyName?: string;
commonName: string;
altNames: string;
+ altNameEntries?: { type: CertSubjectAlternativeNameType; value: string }[];
ttl: string;
notBefore?: string;
notAfter?: string;
@@ -240,6 +243,7 @@ type TIssueCertFromCaBaseDTO = {
locality?: string;
ou?: string;
domainComponents?: string[];
+ customExtensions?: TResolvedCustomExtension[];
tx?: Knex;
onPersisted?: (cert: TCertificates, tx: Knex) => Promise<void>;
};
@@ -278,6 +282,7 @@ export type TSignCertFromCaDTO =
basicConstraints?: TBasicConstraints;
pathLength?: number | null;
subjectOverride?: string;
+ customExtensions?: TResolvedCustomExtension[];
tx?: Knex;
/**
* Runs inside the same transaction that writes the certificate rows, after they are created
@@ -309,6 +314,7 @@ export type TSignCertFromCaDTO =
basicConstraints?: TBasicConstraints;
pathLength?: number | null;
subjectOverride?: string;
+ customExtensions?: TResolvedCustomExtension[];
tx?: Knex;
/** See the `onPersisted` note on the internal variant above. */
onPersisted?: (cert: TCertificates, tx: Knex) => Promise<void>;
diff --git a/backend/src/services/certificate-common/certificate-constants.ts b/backend/src/services/certificate-common/certificate-constants.ts
index 65275a0567..1f72340288 100644
--- a/backend/src/services/certificate-common/certificate-constants.ts
+++ b/backend/src/services/certificate-common/certificate-constants.ts
@@ -1,3 +1,4 @@
+import RE2 from "re2";
import { z } from "zod";
import { ms } from "@app/lib/ms";
@@ -122,6 +123,7 @@ export enum CertExtendedKeyUsageType {
CODE_SIGNING = "code_signing",
EMAIL_PROTECTION = "email_protection",
OCSP_SIGNING = "ocsp_signing",
+ SMART_CARD_LOGON = "smart_card_logon",
TIME_STAMPING = "time_stamping",
ANY_PURPOSE = "any_purpose"
}
@@ -133,6 +135,7 @@ export enum CertExtendedKeyUsage {
EMAIL_PROTECTION = "emailProtection",
TIMESTAMPING = "timeStamping",
OCSP_SIGNING = "ocspSigning",
+ SMART_CARD_LOGON = "smartCardLogon",
ANY_PURPOSE = "anyExtendedKeyUsage"
}
@@ -227,6 +230,10 @@ export const CERT_EXTENDED_KEY_USAGES: Record<
legacyName: CertExtendedKeyUsage.EMAIL_PROTECTION
},
[CertExtendedKeyUsageType.OCSP_SIGNING]: { oid: "1.3.6.1.5.5.7.3.9", legacyName: CertExtendedKeyUsage.OCSP_SIGNING },
+ [CertExtendedKeyUsageType.SMART_CARD_LOGON]: {
+ oid: "1.3.6.1.4.1.311.20.2.2",
+ legacyName: CertExtendedKeyUsage.SMART_CARD_LOGON
+ },
[CertExtendedKeyUsageType.TIME_STAMPING]: { oid: "1.3.6.1.5.5.7.3.8", legacyName: CertExtendedKeyUsage.TIMESTAMPING },
[CertExtendedKeyUsageType.ANY_PURPOSE]: { oid: "2.5.29.37.0", legacyName: CertExtendedKeyUsage.ANY_PURPOSE }
};
@@ -354,6 +361,95 @@ export const POLICY_STATE_OPTIONS = Object.values(CertPolicyState);
export const KEY_ALGORITHM_OPTIONS = Object.values(CertKeyAlgorithm);
export const SIGNATURE_ALGORITHM_OPTIONS = Object.values(CertSignatureAlgorithm);
+export enum CertExtensionCriticality {
+ CRITICAL = "critical",
+ NOT_CRITICAL = "not_critical"
+}
+
+export enum CertExtensionRuleKind {
+ ALLOW = "allow",
+ REQUIRE = "require",
+ DENY = "deny"
+}
+
+export const CUSTOM_EXTENSION_PRESET_OIDS = {
+ NTDS_SID: "1.3.6.1.4.1.311.25.2",
+ MS_CERTIFICATE_TEMPLATE_NAME: "1.3.6.1.4.1.311.20.2",
+ MS_CERTIFICATE_TEMPLATE_INFORMATION: "1.3.6.1.4.1.311.21.7"
+} as const;
+
+export const MAX_CUSTOM_EXTENSIONS_PER_PROFILE = 10;
+
+/**
+ * AWS Private CA accepts at most 3 entries in ApiPassthrough.Extensions.CustomExtensions and rejects the
+ * request with an unexplained ValidationException past that, so the limit is enforced before we call them.
+ */
+export const MAX_CUSTOM_EXTENSIONS_PER_AWS_PCA_PROFILE = 3;
+export const MAX_CUSTOM_EXTENSION_RULES_PER_POLICY = 20;
+export const CUSTOM_EXTENSIONS_WITH_CSR_ERROR_MESSAGE =
+ "Custom extensions cannot be supplied alongside a certificate signing request. Include them in the request itself, or let Infisical generate the key.";
+export const MAX_CUSTOM_EXTENSION_VALUE_BYTES = 2048;
+
+/**
+ * AWS Private CA caps ObjectIdentifier at 64 characters and it is the strictest CA we integrate with,
+ * so bounding here turns a too-long OID into a 422 from us rather than an opaque error from them.
+ */
+export const MAX_CERT_EXTENSION_OID_LENGTH = 64;
+
+export const RESERVED_CERT_EXTENSION_OID_PREFIXES = ["2.5.29."] as const;
+
+export const RESERVED_CERT_EXTENSION_OID_MESSAGES: Record<string, string> = {
+ "1.3.6.1.5.5.7.1.1":
+ "OID 1.3.6.1.5.5.7.1.1 is the authority information access extension, which Infisical manages, so it cannot be used as a custom extension.",
+ "1.3.6.1.4.1.311.20.2.3":
+ "Use a UPN subject alternative name instead of declaring OID 1.3.6.1.4.1.311.20.2.3 as a custom extension."
+};
+
+export const CERT_EXTENSION_OID_PATTERN_SOURCE = "[0-2](\\.(0|[1-9][0-9]{0,14})){1,20}";
+
+const CERT_EXTENSION_OID_PATTERN = new RE2(`^${CERT_EXTENSION_OID_PATTERN_SOURCE}$`);
+
+export const certificateExtensionOidSchema = z
+ .string()
+ .trim()
+ .max(MAX_CERT_EXTENSION_OID_LENGTH, `OID cannot exceed ${MAX_CERT_EXTENSION_OID_LENGTH} characters`)
+ .superRefine((oid, ctx) => {
+ if (!CERT_EXTENSION_OID_PATTERN.test(oid)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "OID must be dot-separated integers, for example 1.3.6.1.4.1.311.25.2"
+ });
+ return;
+ }
+
+ const [first, second] = oid.split(".");
+ if (first !== "2" && Number(second) > 39) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "When an OID starts with 0 or 1, its second arc must be 39 or lower"
+ });
+ }
+ });
+
+export const customExtensionLabelSchema = z
+ .string()
+ .trim()
+ .min(1, "Name cannot be empty")
+ .max(64, "Name cannot exceed 64 characters");
+
+export const customExtensionValueSchema = z
+ .string()
+ .trim()
+ .min(1, "Value cannot be empty")
+ .max(PKI_ALT_NAMES_COLUMN_MAX_LENGTH, "Value is too large");
+
+export const resolvedCustomExtensionSchema = z.object({
+ oid: z.string().max(MAX_CERT_EXTENSION_OID_LENGTH),
+ critical: z.boolean(),
+ value: z.string().max(PKI_ALT_NAMES_COLUMN_MAX_LENGTH),
+ displayValue: z.string().max(PKI_ALT_NAMES_COLUMN_MAX_LENGTH).optional()
+});
+
export const subjectAlternativeNameSchema = z.object({
type: z.nativeEnum(CertSubjectAlternativeNameType),
value: z
@@ -398,5 +494,28 @@ export const certificateAttributesSchema = z.object({
isCA: z.boolean(),
pathLength: z.number().int().min(0).max(255).optional()
})
+ .optional(),
+ customExtensions: z
+ .array(
+ z.object({
+ oid: certificateExtensionOidSchema,
+ value: customExtensionValueSchema.optional(),
+ critical: z.boolean().optional()
+ })
+ )
+ .max(MAX_CUSTOM_EXTENSIONS_PER_PROFILE)
+ .superRefine((extensions, ctx) => {
+ const seen = new Set<string>();
+ extensions.forEach((extension, index) => {
+ if (seen.has(extension.oid)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: [index, "oid"],
+ message: `Duplicate custom extension for OID '${extension.oid}'. Each OID must appear only once.`
+ });
+ }
+ seen.add(extension.oid);
+ });
+ })
.optional()
});
diff --git a/backend/src/services/certificate-common/certificate-csr-utils.ts b/backend/src/services/certificate-common/certificate-csr-utils.ts
index 26609f263f..19b9ea3e01 100644
--- a/backend/src/services/certificate-common/certificate-csr-utils.ts
+++ b/backend/src/services/certificate-common/certificate-csr-utils.ts
@@ -25,6 +25,12 @@ import {
mapLegacyKeyUsageToStandard,
SUPPORTED_GENERAL_NAME_TYPES
} from "./certificate-constants";
+import {
+ appendCustomExtensions,
+ describeCustomExtensionValue,
+ isReservedExtensionOid,
+ TIssuedCustomExtension
+} from "./certificate-extension-fns";
/**
* Extracts certificate request data from a CSR string
@@ -118,6 +124,20 @@ export const extractCertificateRequestFromCSR = (csr: string): TCertificateReque
};
}
+ const csrCustomExtensions = csrObj.extensions
+ .filter((extension) => !isReservedExtensionOid(extension.type))
+ .flatMap((extension) => {
+ const value = describeCustomExtensionValue(
+ extension.type,
+ Buffer.from(new Uint8Array(extension.value)).toString("base64")
+ );
+ return value === null ? [] : [{ oid: extension.type, value, critical: extension.critical }];
+ });
+
+ if (csrCustomExtensions.length) {
+ certificateRequest.customExtensions = csrCustomExtensions;
+ }
+
return certificateRequest;
};
@@ -370,28 +390,34 @@ export const extractAlgorithmsFromCSR = (csr: string) => {
export const generateLeafKeypairAndCsr = async ({
subjectName,
algorithm,
- altNames = []
+ altNames = [],
+ customExtensions = []
}: {
subjectName: string;
algorithm: ReturnType<typeof keyAlgorithmToAlgCfg>;
altNames?: string[];
+ customExtensions?: TIssuedCustomExtension[];
}): Promise<{ privateKeyPem: string; csrPem: string; csrDerBase64: string }> => {
const leafKeys = await crypto.nativeCrypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);
const skLeafObj = crypto.nativeCrypto.KeyObject.from(leafKeys.privateKey);
const privateKeyPem = skLeafObj.export({ format: "pem", type: "pkcs8" }) as string;
+ const csrExtensions: x509.Extension[] = [];
+ if (altNames.length > 0) {
+ csrExtensions.push(
+ new x509.SubjectAlternativeNameExtension(
+ altNames.map((value) => ({ type: "dns" as TAltNameType, value })),
+ false
+ )
+ );
+ }
+ appendCustomExtensions(csrExtensions, customExtensions);
+
const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
name: subjectName,
keys: leafKeys,
signingAlgorithm: algorithm,
- ...(altNames.length > 0 && {
- extensions: [
- new x509.SubjectAlternativeNameExtension(
- altNames.map((value) => ({ type: "dns" as TAltNameType, value })),
- false
- )
- ]
- })
+ ...(csrExtensions.length > 0 && { extensions: csrExtensions })
});
return {
diff --git a/backend/src/services/certificate-common/certificate-extension-fns.test.ts b/backend/src/services/certificate-common/certificate-extension-fns.test.ts
new file mode 100644
index 0000000000..7c4f9c7f7f
--- /dev/null
+++ b/backend/src/services/certificate-common/certificate-extension-fns.test.ts
@@ -0,0 +1,496 @@
+import * as x509 from "@peculiar/x509";
+import { describe, expect, it } from "vitest";
+
+import {
+ CertExtensionCriticality,
+ CertExtensionRuleKind,
+ certificateExtensionOidSchema
+} from "./certificate-constants";
+import {
+ appendCustomExtensions,
+ CUSTOM_EXTENSION_PRESETS_BY_OID,
+ describeCustomExtensionValue,
+ encodeCustomExtensionValue,
+ findDroppedCustomExtensionOids,
+ isReservedExtensionOid,
+ parseCustomExtensionsFromCertificate,
+ resolveCustomExtensions,
+ TCustomExtensionRule,
+ toRequestCustomExtensions,
+ TProfileCustomExtension,
+ validateCustomExtensionValue
+} from "./certificate-extension-fns";
+
+const SID_OID = "1.3.6.1.4.1.311.25.2";
+const TEMPLATE_NAME_OID = "1.3.6.1.4.1.311.20.2";
+const TEMPLATE_INFO_OID = "1.3.6.1.4.1.311.21.7";
+const CUSTOM_OID = "1.3.6.1.4.1.99999.7.1";
+
+const SID = "S-1-5-21-1004336348-1177238915-682003330-1103";
+
+describe("certificateExtensionOidSchema", () => {
+ it.each(["1.3.6.1.4.1.311.25.2", "2.999.1", "0.9.2342"])("accepts %s", (oid) => {
+ expect(certificateExtensionOidSchema.safeParse(oid).success).toBe(true);
+ });
+
+ it.each([
+ ["3.1.1", "first arc above 2"],
+ ["1.", "trailing dot"],
+ ["1.02.3", "leading zero"],
+ ["1.40.2", "second arc above 39 under a first arc of 1"],
+ ["", "empty"],
+ [`1.3.${"9".repeat(70)}`, "over 64 characters"]
+ ])("rejects %s (%s)", (oid) => {
+ expect(certificateExtensionOidSchema.safeParse(oid).success).toBe(false);
+ });
+});
+
+describe("isReservedExtensionOid", () => {
+ it.each(["2.5.29.17", "2.5.29.15", "2.5.29.30", "1.3.6.1.5.5.7.1.1", "1.3.6.1.4.1.311.20.2.3"])(
+ "reserves %s",
+ (oid) => {
+ expect(isReservedExtensionOid(oid)).toBe(true);
+ }
+ );
+
+ it.each([SID_OID, TEMPLATE_NAME_OID, TEMPLATE_INFO_OID, CUSTOM_OID])("does not reserve %s", (oid) => {
+ expect(isReservedExtensionOid(oid)).toBe(false);
+ });
+});
+
+describe("preset encoders", () => {
+ it("encodes the AD SID extension to the [MS-WCCE] byte layout", () => {
+ const der = Buffer.from(encodeCustomExtensionValue(SID_OID, SID), "base64");
+
+ expect(der.toString("hex")).toBe(
+ "303fa03d060a2b060104018237190201a02f042d532d312d352d32312d313030343333363334382d313137373233383931352d3638323030333333302d31313033"
+ );
+ });
+
+ it("encodes a certificate template name as a BMPString", () => {
+ const der = Buffer.from(encodeCustomExtensionValue(TEMPLATE_NAME_OID, "Machine"), "base64");
+
+ expect(der.toString("hex")).toBe("1e0e004d0061006300680069006e0065");
+ });
+
+ it("encodes certificate template information as a sequence", () => {
+ const der = Buffer.from(encodeCustomExtensionValue(TEMPLATE_INFO_OID, "1.3.6.1.4.1.311.21.8.1.2:100.3"), "base64");
+
+ expect(der.toString("hex")).toBe("3013060b2b06010401823715080102020164020103");
+ });
+
+ it.each([
+ [SID_OID, SID],
+ [TEMPLATE_NAME_OID, "Machine"],
+ [TEMPLATE_INFO_OID, "1.3.6.1.4.1.311.21.8.1.2:100.3"],
+ [TEMPLATE_INFO_OID, "1.3.6.1.4.1.311.21.8.1.2:100"]
+ ])("round-trips %s", (oid, value) => {
+ expect(describeCustomExtensionValue(oid, encodeCustomExtensionValue(oid, value))).toBe(value);
+ });
+
+ it("every preset declares a spec-correct criticality", () => {
+ expect(Object.values(CUSTOM_EXTENSION_PRESETS_BY_OID).map((preset) => preset.critical)).toEqual([
+ false,
+ false,
+ false
+ ]);
+ });
+});
+
+describe("describeCustomExtensionValue", () => {
+ it("returns null rather than throwing on undecodable bytes", () => {
+ expect(describeCustomExtensionValue(SID_OID, Buffer.from("not der at all").toString("base64"))).toBeNull();
+ });
+
+ it("returns null when the bytes decode but do not re-encode identically", () => {
+ expect(describeCustomExtensionValue(SID_OID, Buffer.from("30030201ff", "hex").toString("base64"))).toBeNull();
+ });
+
+ it("round-trips the text an unknown OID was given", () => {
+ expect(describeCustomExtensionValue(CUSTOM_OID, encodeCustomExtensionValue(CUSTOM_OID, "ops-prod"))).toBe(
+ "ops-prod"
+ );
+ });
+});
+
+describe("resolveCustomExtensions", () => {
+ const declareSid = { oid: SID_OID, value: SID };
+
+ it("emits a declared value when the policy is unconstrained", () => {
+ const { extensions, errors } = resolveCustomExtensions({ declarations: [declareSid], rules: undefined });
+
+ expect(errors).toEqual([]);
+ expect(extensions).toHaveLength(1);
+ expect(extensions[0]).toMatchObject({
+ oid: SID_OID,
+ critical: false
+ });
+ });
+
+ it("treats a null rule list as unconstrained, matching an unset jsonb column", () => {
+ const { errors } = resolveCustomExtensions({ declarations: [declareSid], rules: null });
+
+ expect(errors).toEqual([]);
+ });
+
+ it.each([
+ ["a profile default", { declarations: [declareSid] }],
+ ["a request", { declarations: [], requestExtensions: [{ oid: SID_OID, value: SID }] }]
+ ])("denies %s when the rule list is empty", (_label, input) => {
+ const { extensions, errors } = resolveCustomExtensions({ ...input, rules: [] });
+
+ expect(extensions).toEqual([]);
+ expect(errors).toEqual([`Custom extension '${SID_OID}' is not allowed by this policy.`]);
+ });
+
+ it("denies an OID that no rule mentions", () => {
+ const { errors } = resolveCustomExtensions({
+ declarations: [declareSid],
+ rules: [{ oid: TEMPLATE_NAME_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }]
+ });
+
+ expect(errors).toEqual([`Custom extension '${SID_OID}' is not allowed by this policy.`]);
+ });
+
+ it("lets a request value override the declared default", () => {
+ const override = "S-1-5-21-1004336348-1177238915-682003330-9999";
+ const { extensions, errors } = resolveCustomExtensions({
+ declarations: [declareSid],
+ rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],
+ requestExtensions: [{ oid: SID_OID, value: override }]
+ });
+
+ expect(errors).toEqual([]);
+ expect(describeCustomExtensionValue(SID_OID, extensions[0].value)).toBe(override);
+ });
+
+ it("emits nothing when neither the profile nor the request supplies a value", () => {
+ const { extensions, errors } = resolveCustomExtensions({
+ declarations: [{ oid: SID_OID }],
+ rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }]
+ });
+
+ expect(extensions).toEqual([]);
+ expect(errors).toEqual([]);
+ });
+
+ it("rejects a request SID from a different AD domain, which is the case this model exists for", () => {
+ const { errors } = resolveCustomExtensions({
+ declarations: [{ oid: SID_OID }],
+ rules: [
+ { oid: SID_OID, rule: CertExtensionRuleKind.REQUIRE, value: "S-1-5-21-1004336348-1177238915-682003330-*" }
+ ],
+ requestExtensions: [{ oid: SID_OID, value: "S-1-5-21-999-888-777-1103" }]
+ });
+
+ expect(errors[0]).toContain("does not match the value required by this policy");
+ });
+
+ it("accepts a request SID inside the allowed AD domain", () => {
+ const { extensions, errors } = resolveCustomExtensions({
+ declarations: [{ oid: SID_OID }],
+ rules: [
+ { oid: SID_OID, rule: CertExtensionRuleKind.REQUIRE, value: "S-1-5-21-1004336348-1177238915-682003330-*" }
+ ],
+ requestExtensions: [{ oid: SID_OID, value: SID }]
+ });
+
+ expect(errors).toEqual([]);
+ expect(extensions).toHaveLength(1);
+ });
+
+ it("honours denied patterns", () => {
+ const { errors } = resolveCustomExtensions({
+ declarations: [{ oid: SID_OID }],
+ rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.DENY, value: "S-1-5-21-*-500" }],
+ requestExtensions: [{ oid: SID_OID, value: "S-1-5-21-1004336348-1177238915-682003330-500" }]
+ });
+
+ expect(errors[0]).toContain("is denied by this policy");
+ });
+
+ it("reports a required rule that nothing satisfies, and respects skipRequired", () => {
+ const rules = [{ oid: SID_OID, rule: CertExtensionRuleKind.REQUIRE, value: "S-1-5-21-*" }];
+
+ expect(resolveCustomExtensions({ declarations: [], rules }).errors).toHaveLength(1);
+ expect(resolveCustomExtensions({ declarations: [], rules, skipRequired: true }).errors).toEqual([]);
+ });
+
+ it("emits a request extension the profile never declared when the policy is unrestricted", () => {
+ const { extensions, errors } = resolveCustomExtensions({
+ declarations: [],
+ rules: undefined,
+ requestExtensions: [{ oid: CUSTOM_OID, value: "ops-prod" }]
+ });
+
+ expect(errors).toEqual([]);
+ expect(extensions).toEqual([
+ {
+ oid: CUSTOM_OID,
+ critical: false,
+ value: encodeCustomExtensionValue(CUSTOM_OID, "ops-prod"),
+ displayValue: "ops-prod"
+ }
+ ]);
+ });
+
+ it("refuses a request extension the policy does not list, declared or not", () => {
+ const { extensions, errors } = resolveCustomExtensions({
+ declarations: [],
+ rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],
+ requestExtensions: [{ oid: CUSTOM_OID, value: "BQA=" }]
+ });
+
+ expect(extensions).toEqual([]);
+ expect(errors[0]).toContain("is not allowed by this policy");
+ });
+
+ it("refuses a reserved OID a request tries to smuggle past an unrestricted policy", () => {
+ const { errors } = resolveCustomExtensions({
+ declarations: [],
+ rules: undefined,
+ requestExtensions: [{ oid: "2.5.29.17", value: "BQA=" }]
+ });
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain("2.5.29.17");
+ });
+
+ it("lets the request set criticality when the policy leaves it undefined", () => {
+ const value = Buffer.from("0500", "hex").toString("base64");
+ const { extensions } = resolveCustomExtensions({
+ declarations: [{ oid: CUSTOM_OID, value, critical: false }],
+ rules: [{ oid: CUSTOM_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],
+ requestExtensions: [{ oid: CUSTOM_OID, critical: true }]
+ });
+
+ expect(extensions[0]).toMatchObject({ critical: true });
+ });
+
+ it("rejects a request criticality that contradicts a pinned policy", () => {
+ const value = Buffer.from("0500", "hex").toString("base64");
+ const { errors } = resolveCustomExtensions({
+ declarations: [{ oid: CUSTOM_OID, value }],
+ rules: [
+ { oid: CUSTOM_OID, rule: CertExtensionRuleKind.ALLOW, value: "*", critical: CertExtensionCriticality.CRITICAL }
+ ],
+ requestExtensions: [{ oid: CUSTOM_OID, critical: false }]
+ });
+
+ expect(errors).toEqual([
+ `Custom extension '${CUSTOM_OID}' must be emitted as critical by this policy, so its criticality cannot be set.`
+ ]);
+ });
+
+ it("keeps a preset's criticality when the request does not contest it", () => {
+ const { extensions } = resolveCustomExtensions({
+ declarations: [declareSid],
+ rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],
+ requestExtensions: [{ oid: SID_OID }]
+ });
+
+ expect(extensions[0]).toMatchObject({ critical: false });
+ });
+
+ it("rejects a request that contests a preset's criticality", () => {
+ const { extensions, errors } = resolveCustomExtensions({
+ declarations: [declareSid],
+ rules: [{ oid: SID_OID, rule: CertExtensionRuleKind.ALLOW, value: "*" }],
+ requestExtensions: [{ oid: SID_OID, critical: true }]
+ });
+
+ expect(extensions).toHaveLength(0);
+ expect(errors[0]).toContain("always emitted as non-critical");
+ });
+
+ it("denies a value the policy denies", () => {
+ const { extensions, errors } = resolveCustomExtensions({
+ declarations: [{ oid: CUSTOM_OID, value: "ops-prod" }],
+ rules: [{ oid: CUSTOM_OID, rule: CertExtensionRuleKind.DENY, value: "ops-prod" }]
+ });
+
+ expect(extensions).toHaveLength(0);
+ expect(errors[0]).toContain("is denied by this policy");
+ });
+
+ it.each([
+ ["Machine", 1, 0],
+ ["MACHINE", 0, 1]
+ ])("matching %s against an allowed pattern of Machine", (requested, emitted, failures) => {
+ const { extensions, errors } = resolveCustomExtensions({
+ declarations: [{ oid: TEMPLATE_NAME_OID }],
+ rules: [{ oid: TEMPLATE_NAME_OID, rule: CertExtensionRuleKind.ALLOW, value: "Machine" }],
+ requestExtensions: [{ oid: TEMPLATE_NAME_OID, value: requested }]
+ });
+
+ expect(extensions).toHaveLength(emitted);
+ expect(errors).toHaveLength(failures);
+ });
+
+ it("rejects a template name that is empty or outside the basic multilingual plane", () => {
+ expect(resolveCustomExtensions({ declarations: [{ oid: TEMPLATE_NAME_OID, value: "" }] }).errors[0]).toContain(
+ "Enter a certificate template name"
+ );
+ expect(
+ resolveCustomExtensions({ declarations: [{ oid: TEMPLATE_NAME_OID, value: "Ma\u{1F600}ne" }] }).errors[0]
+ ).toContain("basic multilingual plane");
+ });
+
+ it("carries every stored extension forward for a renewal, as the subject alternative names are", () => {
+ const stored = [
+ { oid: CUSTOM_OID, critical: false, value: encodeCustomExtensionValue(CUSTOM_OID, "ops-prod") },
+ { oid: SID_OID, critical: false, value: encodeCustomExtensionValue(SID_OID, SID) }
+ ];
+
+ expect(toRequestCustomExtensions(stored).map((entry) => entry.oid)).toEqual([CUSTOM_OID, SID_OID]);
+ });
+
+ it("refuses to reissue an extension whose stored value cannot be read back", () => {
+ const stored = [{ oid: SID_OID, critical: false, value: Buffer.from([0x05, 0x00]).toString("base64") }];
+
+ expect(() => toRequestCustomExtensions(stored)).toThrow(/cannot be read back into a value/);
+ });
+
+ it("keeps the profile default and the request's own OID side by side", () => {
+ const { extensions, errors } = resolveCustomExtensions({
+ declarations: [declareSid],
+ rules: null,
+ requestExtensions: [{ oid: CUSTOM_OID, value: "BQA=" }]
+ });
+
+ expect(errors).toEqual([]);
+ expect(extensions.map((entry) => entry.oid)).toEqual([SID_OID, CUSTOM_OID]);
+ });
+
+ it("orders output by OID so identical requests produce identical certificates", () => {
+ const value = Buffer.from("0500", "hex").toString("base64");
+ const { extensions } = resolveCustomExtensions({
+ declarations: [
+ { oid: TEMPLATE_NAME_OID, value: "Machine" },
+ { oid: CUSTOM_OID, value },
+ { oid: SID_OID, value: SID }
+ ],
+ rules: undefined
+ });
+
+ expect(extensions.map((extension) => extension.oid)).toEqual([TEMPLATE_NAME_OID, SID_OID, CUSTOM_OID]);
+ });
+});
+
+describe("resolveCustomExtensions on the profile-save path", () => {
+ const save = (declarations: TProfileCustomExtension[], rules?: TCustomExtensionRule[]) =>
+ resolveCustomExtensions({ declarations, rules, skipRequired: true }).errors;
+
+ it("rejects a declared value the policy forbids", () => {
+ const errors = save(
+ [{ oid: TEMPLATE_NAME_OID, value: "User" }],
+ [{ oid: TEMPLATE_NAME_OID, rule: CertExtensionRuleKind.ALLOW, value: "Machine" }]
+ );
+
+ expect(errors[0]).toContain("is not allowed by this policy");
+ });
+
+ it("rejects a criticality that disagrees with a preset", () => {
+ expect(save([{ oid: SID_OID, value: SID, critical: true }])[0]).toContain("always emitted as non-critical");
+ });
+
+ it("rejects a criticality that disagrees with the policy even with no value", () => {
+ const errors = save(
+ [{ oid: CUSTOM_OID, critical: false }],
+ [{ oid: CUSTOM_OID, rule: CertExtensionRuleKind.ALLOW, value: "*", critical: CertExtensionCriticality.CRITICAL }]
+ );
+
+ expect(errors[0]).toContain("must be emitted as critical");
+ });
+
+ it("does not ask the profile to satisfy a required rule", () => {
+ expect(save([], [{ oid: CUSTOM_OID, rule: CertExtensionRuleKind.REQUIRE, value: "BQA=" }])).toHaveLength(0);
+ });
+});
+
+describe("appendCustomExtensions", () => {
+ it("appends resolved extensions", () => {
+ const extensions: x509.Extension[] = [];
+ appendCustomExtensions(extensions, [
+ { oid: SID_OID, critical: false, value: encodeCustomExtensionValue(SID_OID, SID) }
+ ]);
+
+ expect(extensions).toHaveLength(1);
+ expect(extensions[0].type).toBe(SID_OID);
+ });
+
+ it("throws when the OID collides with an extension already on the certificate", () => {
+ const extensions: x509.Extension[] = [new x509.BasicConstraintsExtension(false)];
+
+ expect(() => appendCustomExtensions(extensions, [{ oid: "2.5.29.19", critical: false, value: "MAA=" }])).toThrow(
+ /collides with an extension this certificate authority manages/
+ );
+ });
+});
+
+describe("parseCustomExtensionsFromCertificate", () => {
+ it("returns an empty list for bytes that are not a certificate", () => {
+ expect(parseCustomExtensionsFromCertificate(Buffer.from("not a certificate"))).toEqual([]);
+ });
+});
+
+describe("findDroppedCustomExtensionOids", () => {
+ const certificateWith = async (oids: string[]) => {
+ const keys = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);
+ const cert = await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "01",
+ name: "CN=drop-test",
+ notBefore: new Date("2026-01-01"),
+ notAfter: new Date("2027-01-01"),
+ keys,
+ signingAlgorithm: { name: "ECDSA", hash: "SHA-256" },
+ extensions: oids.map((oid) => new x509.Extension(oid, false, Buffer.from("BQA=", "base64")))
+ });
+ return Buffer.from(cert.rawData);
+ };
+
+ const resolved = (oids: string[]) =>
+ oids.map((oid) => ({
+ oid,
+ value: "BQA=",
+ critical: false
+ }));
+
+ it("names the declared OIDs the issuer left off the certificate", async () => {
+ const der = await certificateWith([CUSTOM_OID]);
+ expect(findDroppedCustomExtensionOids(der, resolved([CUSTOM_OID, SID_OID]))).toEqual([SID_OID]);
+ });
+
+ it("returns nothing when every declared OID is present", async () => {
+ const der = await certificateWith([CUSTOM_OID, SID_OID]);
+ expect(findDroppedCustomExtensionOids(der, resolved([CUSTOM_OID, SID_OID]))).toEqual([]);
+ });
+
+ it("returns nothing when the profile declared none, even for an unreadable certificate", () => {
+ expect(findDroppedCustomExtensionOids(Buffer.from("not a certificate"), [])).toEqual([]);
+ expect(findDroppedCustomExtensionOids(Buffer.from("not a certificate"), undefined)).toEqual([]);
+ });
+
+ it("reports every declared OID when the certificate cannot be parsed at all", async () => {
+ expect(findDroppedCustomExtensionOids(Buffer.from("not a certificate"), resolved([CUSTOM_OID]))).toEqual([
+ CUSTOM_OID
+ ]);
+ });
+});
+
+describe("preset registry", () => {
+ it("round-trips every preset through encode and describe", () => {
+ const samples: Record<string, string> = {
+ [SID_OID]: SID,
+ [TEMPLATE_NAME_OID]: "Machine",
+ [TEMPLATE_INFO_OID]: "1.3.6.1.4.1.311.21.8.1.2:100.3"
+ };
+
+ Object.keys(CUSTOM_EXTENSION_PRESETS_BY_OID).forEach((oid) => {
+ const sample = samples[oid];
+ expect(sample, `add a sample value for ${oid}`).toBeDefined();
+ expect(validateCustomExtensionValue(oid, sample)).toBeNull();
+ expect(describeCustomExtensionValue(oid, encodeCustomExtensionValue(oid, sample))).toBe(sample);
+ });
+ });
+});
diff --git a/backend/src/services/certificate-common/certificate-extension-fns.ts b/backend/src/services/certificate-common/certificate-extension-fns.ts
new file mode 100644
index 0000000000..df6fec453b
--- /dev/null
+++ b/backend/src/services/certificate-common/certificate-extension-fns.ts
@@ -0,0 +1,475 @@
+import * as x509 from "@peculiar/x509";
+import * as asn1js from "asn1js";
+import RE2 from "re2";
+
+import { BadRequestError } from "@app/lib/errors";
+
+import { matchesNormalizedPattern } from "../certificate-policy/certificate-policy-fns";
+import {
+ CERT_EXTENSION_OID_PATTERN_SOURCE,
+ CertExtensionCriticality,
+ CertExtensionRuleKind,
+ CUSTOM_EXTENSION_PRESET_OIDS,
+ MAX_CUSTOM_EXTENSION_VALUE_BYTES,
+ MAX_CUSTOM_EXTENSIONS_PER_AWS_PCA_PROFILE,
+ RESERVED_CERT_EXTENSION_OID_MESSAGES,
+ RESERVED_CERT_EXTENSION_OID_PREFIXES
+} from "./certificate-constants";
+
+export type TIssuedCustomExtension = {
+ oid: string;
+ critical: boolean;
+ value: string;
+ displayValue?: string;
+};
+
+export type TResolvedCustomExtension = TIssuedCustomExtension;
+
+export type TCustomExtensionRule = {
+ oid: string;
+ label?: string;
+ critical?: CertExtensionCriticality;
+ rule: CertExtensionRuleKind;
+ value: string;
+};
+
+export type TProfileCustomExtension = {
+ oid: string;
+ label?: string;
+ critical?: boolean;
+ value?: string;
+};
+
+export type TRequestCustomExtension = {
+ oid: string;
+ value?: string;
+ critical?: boolean;
+};
+
+type TCustomExtensionPreset = {
+ critical: boolean;
+ validateInput: (value: string) => string | null;
+ encode: (value: string) => Buffer;
+ describe: (der: Buffer) => string | null;
+};
+
+const SID_PATTERN = new RE2("^S-1-[0-9]{1,10}(-[0-9]{1,10}){1,14}$");
+const TEMPLATE_INFORMATION_PATTERN = new RE2(
+ `^(${CERT_EXTENSION_OID_PATTERN_SOURCE}):(0|[1-9][0-9]{0,4})(\\.(0|[1-9][0-9]{0,4}))?$`
+);
+
+const toDerBuffer = (schema: { toBER: (sizeOnly?: boolean) => ArrayBuffer }): Buffer =>
+ Buffer.from(new Uint8Array(schema.toBER(false)));
+
+const parseSingleDerValue = (der: Buffer): asn1js.AsnType | null => {
+ try {
+ const { offset, result } = asn1js.fromBER(der);
+ if (offset === -1 || offset !== der.length) return null;
+ return result;
+ } catch {
+ return null;
+ }
+};
+
+const encodeNtdsSid = (sid: string): Buffer => {
+ const otherName = new asn1js.Sequence({
+ value: [
+ new asn1js.ObjectIdentifier({ value: `${CUSTOM_EXTENSION_PRESET_OIDS.NTDS_SID}.1` }),
+ new asn1js.Constructed({
+ idBlock: { tagClass: 3, tagNumber: 0 },
+ value: [new asn1js.OctetString({ valueHex: new TextEncoder().encode(sid).buffer as ArrayBuffer })]
+ })
+ ]
+ });
+
+ return toDerBuffer(
+ new asn1js.Sequence({
+ value: [new asn1js.Constructed({ idBlock: { tagClass: 3, tagNumber: 0 }, value: otherName.valueBlock.value })]
+ })
+ );
+};
+
+const describeNtdsSid = (der: Buffer): string | null => {
+ const parsed = parseSingleDerValue(der);
+ if (!(parsed instanceof asn1js.Sequence)) return null;
+
+ const generalName = parsed.valueBlock.value[0];
+ if (!(generalName instanceof asn1js.Constructed)) return null;
+
+ const [typeId, tagged] = generalName.valueBlock.value;
+ if (!(typeId instanceof asn1js.ObjectIdentifier)) return null;
+ if (typeId.valueBlock.toString() !== `${CUSTOM_EXTENSION_PRESET_OIDS.NTDS_SID}.1`) return null;
+ if (!(tagged instanceof asn1js.Constructed)) return null;
+
+ const octets = tagged.valueBlock.value[0];
+ if (!(octets instanceof asn1js.OctetString)) return null;
+
+ const sid = Buffer.from(octets.valueBlock.valueHexView).toString("utf8");
+ return SID_PATTERN.test(sid) ? sid : null;
+};
+
+const describeTemplateInformation = (der: Buffer): string | null => {
+ const parsed = parseSingleDerValue(der);
+ if (!(parsed instanceof asn1js.Sequence)) return null;
+
+ const [templateOid, major, minor] = parsed.valueBlock.value;
+ if (!(templateOid instanceof asn1js.ObjectIdentifier)) return null;
+ if (!(major instanceof asn1js.Integer)) return null;
+
+ const base = `${templateOid.valueBlock.toString()}:${major.valueBlock.valueDec}`;
+ return minor instanceof asn1js.Integer ? `${base}.${minor.valueBlock.valueDec}` : base;
+};
+
+type TAsn1StringType = new (params: { value: string }) => asn1js.AsnType;
+
+const asn1StringPreset = ({
+ Type,
+ validateInput,
+ critical = false
+}: {
+ Type: TAsn1StringType;
+ validateInput: (value: string) => string | null;
+ critical?: boolean;
+}): TCustomExtensionPreset => ({
+ critical,
+ validateInput,
+ encode: (value) => toDerBuffer(new Type({ value })),
+ describe: (der) => {
+ const parsed = parseSingleDerValue(der);
+ return parsed instanceof Type ? (parsed as unknown as { valueBlock: { value: string } }).valueBlock.value : null;
+ }
+});
+
+export const CUSTOM_EXTENSION_PRESETS_BY_OID: Record<string, TCustomExtensionPreset> = {
+ [CUSTOM_EXTENSION_PRESET_OIDS.NTDS_SID]: {
+ critical: false,
+ validateInput: (value) =>
+ SID_PATTERN.test(value)
+ ? null
+ : "Enter a security identifier, for example S-1-5-21-1004336348-1177238915-682003330-1103",
+ encode: encodeNtdsSid,
+ describe: describeNtdsSid
+ },
+ [CUSTOM_EXTENSION_PRESET_OIDS.MS_CERTIFICATE_TEMPLATE_NAME]: asn1StringPreset({
+ Type: asn1js.BmpString,
+ validateInput: (value) => {
+ if (!value.length) return "Enter a certificate template name";
+ if (value.length > 64) return "Template name cannot exceed 64 characters";
+ if (Array.from(value).some((character) => (character.codePointAt(0) ?? 0) > 0xffff)) {
+ return "Template name cannot contain characters outside the basic multilingual plane";
+ }
+ return null;
+ }
+ }),
+ [CUSTOM_EXTENSION_PRESET_OIDS.MS_CERTIFICATE_TEMPLATE_INFORMATION]: {
+ critical: false,
+ validateInput: (value) =>
+ TEMPLATE_INFORMATION_PATTERN.test(value)
+ ? null
+ : "Enter the template OID, a colon, then the version, for example 1.3.6.1.4.1.311.21.8.1.2:100.3",
+ encode: (value) => {
+ const match = TEMPLATE_INFORMATION_PATTERN.exec(value);
+ if (!match) throw new BadRequestError({ message: "Certificate template information value is malformed" });
+
+ const [, templateOid, , , major, , minor] = match;
+ return toDerBuffer(
+ new asn1js.Sequence({
+ value: [
+ new asn1js.ObjectIdentifier({ value: templateOid }),
+ new asn1js.Integer({ value: Number(major) }),
+ ...(minor === undefined ? [] : [new asn1js.Integer({ value: Number(minor) })])
+ ]
+ })
+ );
+ },
+ describe: describeTemplateInformation
+ }
+};
+
+export const isReservedExtensionOid = (oid: string): boolean =>
+ RESERVED_CERT_EXTENSION_OID_PREFIXES.some((prefix) => oid.startsWith(prefix)) ||
+ Object.hasOwn(RESERVED_CERT_EXTENSION_OID_MESSAGES, oid);
+
+export const describeReservedExtensionOid = (oid: string): string =>
+ RESERVED_CERT_EXTENSION_OID_MESSAGES[oid] ??
+ `OID ${oid} is a standard X.509 extension that Infisical manages, so it cannot be used as a custom extension.`;
+
+const getCustomExtensionPreset = (oid: string): TCustomExtensionPreset | undefined =>
+ Object.hasOwn(CUSTOM_EXTENSION_PRESETS_BY_OID, oid) ? CUSTOM_EXTENSION_PRESETS_BY_OID[oid] : undefined;
+
+export const validateCustomExtensionValue = (oid: string, value: string): string | null => {
+ const preset = getCustomExtensionPreset(oid);
+ if (preset) return preset.validateInput(value);
+ if (!value.length) return "Enter a value";
+ if (Buffer.byteLength(value, "utf8") > MAX_CUSTOM_EXTENSION_VALUE_BYTES) {
+ return `Value cannot exceed ${MAX_CUSTOM_EXTENSION_VALUE_BYTES} bytes`;
+ }
+ return null;
+};
+
+export const encodeCustomExtensionValue = (oid: string, value: string): string => {
+ const preset = getCustomExtensionPreset(oid);
+ if (preset) return preset.encode(value).toString("base64");
+ return toDerBuffer(new asn1js.Utf8String({ value })).toString("base64");
+};
+
+export const describeCustomExtensionValue = (oid: string, base64Value: string): string | null => {
+ const preset = getCustomExtensionPreset(oid);
+ const der = Buffer.from(base64Value, "base64");
+
+ if (!preset) {
+ const parsed = parseSingleDerValue(der);
+ return parsed instanceof asn1js.Utf8String ? parsed.valueBlock.value : null;
+ }
+
+ try {
+ const described = preset.describe(der);
+ if (described === null) return null;
+ return preset.encode(described).equals(der) ? described : null;
+ } catch {
+ return null;
+ }
+};
+
+export const parseCustomExtensionsFromCertificate = (
+ source: Buffer | x509.X509Certificate
+): TIssuedCustomExtension[] => {
+ let certificate: x509.X509Certificate;
+ if (source instanceof x509.X509Certificate) {
+ certificate = source;
+ } else {
+ try {
+ certificate = new x509.X509Certificate(source);
+ } catch {
+ return [];
+ }
+ }
+
+ return certificate.extensions
+ .filter((extension) => !isReservedExtensionOid(extension.type))
+ .map((extension) => ({
+ oid: extension.type,
+ critical: extension.critical,
+ value: Buffer.from(new Uint8Array(extension.value)).toString("base64")
+ }))
+ .sort((a, b) => a.oid.localeCompare(b.oid));
+};
+
+export const parseIssuedCustomExtensions = (
+ certificateDer: Buffer,
+ resolved?: TResolvedCustomExtension[]
+): TIssuedCustomExtension[] => {
+ if (!resolved?.length) return [];
+ const resolvedOids = new Set(resolved.map((extension) => extension.oid));
+
+ return parseCustomExtensionsFromCertificate(certificateDer)
+ .filter((extension) => resolvedOids.has(extension.oid))
+ .map((extension) => ({
+ ...extension,
+ displayValue: describeCustomExtensionValue(extension.oid, extension.value) ?? undefined
+ }));
+};
+
+export const findDroppedCustomExtensionOids = (
+ certificateDer: Buffer,
+ resolved?: TResolvedCustomExtension[]
+): string[] => {
+ if (!resolved?.length) return [];
+ const issuedOids = new Set(parseCustomExtensionsFromCertificate(certificateDer).map((extension) => extension.oid));
+ return resolved.filter((extension) => !issuedOids.has(extension.oid)).map((extension) => extension.oid);
+};
+
+export const toRequestCustomExtensions = (stored: unknown): TRequestCustomExtension[] =>
+ ((stored as TResolvedCustomExtension[] | null) ?? []).flatMap((extension) => {
+ const value = describeCustomExtensionValue(extension.oid, extension.value);
+ if (value === null) {
+ throw new BadRequestError({
+ message: `Custom extension '${extension.oid}' on this certificate cannot be read back into a value a new request can carry, so it cannot be reissued. Issue a new certificate, or renew from a certificate signing request that carries the extension.`
+ });
+ }
+ return [
+ {
+ oid: extension.oid,
+ value,
+ critical: extension.critical
+ }
+ ];
+ });
+
+export const assertAwsPcaCustomExtensionLimit = (count: number): void => {
+ if (count > MAX_CUSTOM_EXTENSIONS_PER_AWS_PCA_PROFILE) {
+ throw new BadRequestError({
+ message: `AWS Private CA accepts at most ${MAX_CUSTOM_EXTENSIONS_PER_AWS_PCA_PROFILE} custom extensions on a certificate, and this request resolved to ${count}.`
+ });
+ }
+};
+
+export const appendCustomExtensions = (extensions: x509.Extension[], resolved: TIssuedCustomExtension[] = []): void => {
+ for (const extension of resolved) {
+ if (extensions.some((existing) => existing.type === extension.oid)) {
+ throw new BadRequestError({
+ message: `Custom extension '${extension.oid}' collides with an extension this certificate authority manages. Remove it from the certificate profile.`
+ });
+ }
+ extensions.push(new x509.Extension(extension.oid, extension.critical, Buffer.from(extension.value, "base64")));
+ }
+};
+
+const ALLOW_ANY_RULE: TCustomExtensionRule = { oid: "", rule: CertExtensionRuleKind.ALLOW, value: "*" };
+
+const buildRuleLookup = (rules?: TCustomExtensionRule[] | null) => {
+ if (rules === undefined || rules === null) return null;
+ return new Map(rules.map((rule) => [rule.oid, rule]));
+};
+
+const resolveCriticality = ({
+ oid,
+ rule,
+ declaration,
+ requested
+}: {
+ oid: string;
+ rule: TCustomExtensionRule;
+ declaration: TProfileCustomExtension;
+ requested?: TRequestCustomExtension;
+}): { critical: boolean; errors: string[] } => {
+ const preset = getCustomExtensionPreset(oid);
+
+ const fixed = (critical: boolean, reason: string) => {
+ const contested = [declaration.critical, requested?.critical].some(
+ (asked) => asked !== undefined && asked !== critical
+ );
+ return {
+ critical,
+ errors: contested ? [`Custom extension '${oid}' ${reason}, so its criticality cannot be set.`] : []
+ };
+ };
+
+ if (preset) {
+ return fixed(preset.critical, `is always emitted as ${preset.critical ? "critical" : "non-critical"}`);
+ }
+
+ if (rule.critical) {
+ const critical = rule.critical === CertExtensionCriticality.CRITICAL;
+ return fixed(critical, `must be emitted as ${critical ? "critical" : "non-critical"} by this policy`);
+ }
+
+ if (requested?.critical !== undefined) {
+ return { critical: requested.critical, errors: [] };
+ }
+
+ return {
+ critical: declaration.critical ?? false,
+ errors: []
+ };
+};
+
+export const resolveCustomExtensions = ({
+ declarations,
+ rules,
+ requestExtensions,
+ skipRequired = false
+}: {
+ declarations?: TProfileCustomExtension[] | null;
+ rules?: TCustomExtensionRule[] | null;
+ requestExtensions?: TRequestCustomExtension[];
+ skipRequired?: boolean;
+}): { extensions: TResolvedCustomExtension[]; errors: string[] } => {
+ const rulesByOid = buildRuleLookup(rules);
+ const errors: string[] = [];
+ const extensions: TResolvedCustomExtension[] = [];
+ const resolvedOids = new Set<string>();
+
+ const declarationByOid = new Map((declarations ?? []).map((declaration) => [declaration.oid, declaration]));
+ const requestedByOid = new Map((requestExtensions ?? []).map((requested) => [requested.oid, requested]));
+ const resolvableOids = [...new Set([...declarationByOid.keys(), ...requestedByOid.keys()])];
+
+ for (const oid of resolvableOids) {
+ if (isReservedExtensionOid(oid)) {
+ errors.push(describeReservedExtensionOid(oid));
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ const declaration = declarationByOid.get(oid) ?? { oid };
+ const rule = rulesByOid === null ? ALLOW_ANY_RULE : rulesByOid.get(oid);
+ if (!rule) {
+ errors.push(`Custom extension '${oid}' is not allowed by this policy.`);
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ const requested = requestedByOid.get(oid);
+ const criticality = resolveCriticality({ oid, rule, declaration, requested });
+ errors.push(...criticality.errors);
+ if (criticality.errors.length) {
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ const displayValue = requested?.value ?? declaration.value;
+ if (displayValue === undefined) {
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ const isFromRequest = requested?.value !== undefined;
+ const invalid = validateCustomExtensionValue(oid, displayValue);
+ if (invalid) {
+ errors.push(
+ isFromRequest
+ ? `Custom extension '${oid}' in the request is invalid. ${invalid}`
+ : `Custom extension '${oid}' value is invalid. ${invalid}`
+ );
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ const matchesRule = matchesNormalizedPattern(displayValue, rule.value);
+ if (rule.rule === CertExtensionRuleKind.DENY && matchesRule) {
+ errors.push(`Custom extension '${oid}' value '${displayValue}' is denied by this policy.`);
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+ if (rule.rule === CertExtensionRuleKind.REQUIRE && !matchesRule) {
+ errors.push(
+ `Custom extension '${oid}' value '${displayValue}' does not match the value required by this policy: ${rule.value}`
+ );
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+ if (rule.rule === CertExtensionRuleKind.ALLOW && !matchesRule) {
+ errors.push(
+ `Custom extension '${oid}' value '${displayValue}' is not allowed by this policy. Allowed values: ${rule.value}`
+ );
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ resolvedOids.add(oid);
+ extensions.push({
+ oid,
+ critical: criticality.critical,
+ value: encodeCustomExtensionValue(oid, displayValue),
+ displayValue
+ });
+ }
+
+ if (!skipRequired && rulesByOid !== null) {
+ for (const rule of rulesByOid.values()) {
+ if (rule.rule !== CertExtensionRuleKind.REQUIRE) {
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+ if (!resolvedOids.has(rule.oid)) {
+ errors.push(
+ `This policy requires custom extension '${rule.oid}' matching '${rule.value}'. Supply it on the request, or set it as a default on the certificate profile.`
+ );
+ }
+ }
+ }
+
+ extensions.sort((a, b) => a.oid.localeCompare(b.oid));
+
+ return { extensions, errors };
+};
diff --git a/backend/src/services/certificate-common/certificate-issuance-utils.ts b/backend/src/services/certificate-common/certificate-issuance-utils.ts
index 5cb3a26bdd..1f06606d8d 100644
--- a/backend/src/services/certificate-common/certificate-issuance-utils.ts
+++ b/backend/src/services/certificate-common/certificate-issuance-utils.ts
@@ -27,6 +27,7 @@ import {
CertKeyUsageType,
CertSubjectAlternativeNameType
} from "./certificate-constants";
+import { appendCustomExtensions, TResolvedCustomExtension } from "./certificate-extension-fns";
import {
bufferToString,
buildCertificateSubjectFromTemplate,
@@ -351,13 +352,15 @@ export const generateSelfSignedCertificate = async ({
policy,
effectiveSignatureAlgorithm,
effectiveKeyAlgorithm,
- existingKeyPair
+ existingKeyPair,
+ customExtensions
}: {
certificateRequest: TSelfSignedCertificateRequest;
policy?: TCertificatePolicy | null;
effectiveSignatureAlgorithm: CertSignatureAlgorithm;
effectiveKeyAlgorithm: CertKeyAlgorithm;
existingKeyPair?: CryptoKeyPair;
+ customExtensions?: TResolvedCustomExtension[];
}): Promise<TSelfSignedCertificateResult> => {
const certificateSubject = buildCertificateSubjectFromTemplate(certificateRequest, policy?.subject);
const subjectAlternativeNames = buildSubjectAlternativeNamesFromTemplate(
@@ -411,6 +414,46 @@ export const generateSelfSignedCertificate = async ({
domainComponents: certificateRequest.domainComponents
});
+ const selfSignedExtensions: x509.Extension[] = [
+ new x509.BasicConstraintsExtension(false, undefined, false),
+ ...(certificateRequest.keyUsages?.length
+ ? [
+ new x509.KeyUsagesExtension(
+ combineKeyUsageFlags(convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || []),
+ false
+ )
+ ]
+ : []),
+ ...(certificateRequest.extendedKeyUsages?.length
+ ? [
+ new x509.ExtendedKeyUsageExtension(
+ (convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || []).map(
+ (eku) => CertExtendedKeyUsageNameToOID[eku]
+ ),
+ false
+ )
+ ]
+ : []),
+ ...(subjectAlternativeNames
+ ? [
+ new x509.SubjectAlternativeNameExtension(
+ certificateRequest.altNames?.map((san) => {
+ const generalNameType = CERT_SUBJECT_ALTERNATIVE_NAMES[san.type]?.generalNameType;
+ if (!generalNameType) {
+ throw new BadRequestError({
+ message: `Unsupported Subject Alternative Name type: ${san.type as string}`
+ });
+ }
+ return { type: generalNameType, value: san.value };
+ }) || [],
+ false
+ )
+ ]
+ : [])
+ ];
+
+ appendCustomExtensions(selfSignedExtensions, customExtensions);
+
const cert = await x509.X509CertificateGenerator.createSelfSigned({
name: dn,
serialNumber,
@@ -418,43 +461,7 @@ export const generateSelfSignedCertificate = async ({
notAfter: notAfterDate,
signingAlgorithm: signatureAlgorithmConfig,
keys: keyPair,
- extensions: [
- new x509.BasicConstraintsExtension(false, undefined, false),
- ...(certificateRequest.keyUsages?.length
- ? [
- new x509.KeyUsagesExtension(
- combineKeyUsageFlags(convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || []),
- false
- )
- ]
- : []),
- ...(certificateRequest.extendedKeyUsages?.length
- ? [
- new x509.ExtendedKeyUsageExtension(
- (convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || []).map(
- (eku) => CertExtendedKeyUsageNameToOID[eku]
- ),
- false
- )
- ]
- : []),
- ...(subjectAlternativeNames
- ? [
- new x509.SubjectAlternativeNameExtension(
- certificateRequest.altNames?.map((san) => {
- const generalNameType = CERT_SUBJECT_ALTERNATIVE_NAMES[san.type]?.generalNameType;
- if (!generalNameType) {
- throw new BadRequestError({
- message: `Unsupported Subject Alternative Name type: ${san.type as string}`
- });
- }
- return { type: generalNameType, value: san.value };
- }) || [],
- false
- )
- ]
- : [])
- ]
+ extensions: selfSignedExtensions
});
const certificatePem = cert.toString("pem");
diff --git a/backend/src/services/certificate-policy/certificate-policy-dal.ts b/backend/src/services/certificate-policy/certificate-policy-dal.ts
index 59f3d7b6ae..1fd1b2107e 100644
--- a/backend/src/services/certificate-policy/certificate-policy-dal.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-dal.ts
@@ -9,6 +9,7 @@ import {
applyProcessedPermissionRulesToQuery,
type ProcessedPermissionRules
} from "@app/lib/knex/permission-filter-utils";
+import { TProfileCustomExtension } from "@app/services/certificate-common/certificate-extension-fns";
import { TCertificatePolicy, TCertificatePolicyInsert, TCertificatePolicyUpdate } from "./certificate-policy-types";
@@ -31,7 +32,8 @@ export const certificatePolicyDALFactory = (db: TDbClient) => {
"extendedKeyUsages",
"algorithms",
"validity",
- "basicConstraints"
+ "basicConstraints",
+ "customExtensions"
];
jsonFields.forEach((field) => {
@@ -52,7 +54,8 @@ export const certificatePolicyDALFactory = (db: TDbClient) => {
"extendedKeyUsages",
"algorithms",
"validity",
- "basicConstraints"
+ "basicConstraints",
+ "customExtensions"
];
const parsed = { ...raw } as Record<string, unknown>;
@@ -262,10 +265,15 @@ export const certificatePolicyDALFactory = (db: TDbClient) => {
const getProfilesUsingPolicy = async (policyId: string, tx?: Knex) => {
try {
const profiles = await (tx || db)(TableName.PkiCertificateProfile)
- .select("id", "slug", "description")
+ .select("id", "slug", "description", "defaults")
.where({ certificatePolicyId: policyId });
- return profiles as Array<{ id: string; slug: string; description?: string }>;
+ return profiles as Array<{
+ id: string;
+ slug: string;
+ description?: string;
+ defaults?: { customExtensions?: TProfileCustomExtension[] } | null;
+ }>;
} catch (error) {
throw new DatabaseError({ error, name: "Get profiles using certificate policy" });
}
diff --git a/backend/src/services/certificate-policy/certificate-policy-schemas.ts b/backend/src/services/certificate-policy/certificate-policy-schemas.ts
index 81265698c3..5c33cda74a 100644
--- a/backend/src/services/certificate-policy/certificate-policy-schemas.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-schemas.ts
@@ -4,10 +4,15 @@ import { z } from "zod";
import { CERTIFICATE_POLICIES } from "@app/lib/api-docs";
import {
CertExtendedKeyUsageType,
+ CertExtensionCriticality,
+ CertExtensionRuleKind,
+ certificateExtensionOidSchema,
CertKeyUsageType,
CertPolicyState,
CertSubjectAlternativeNameType,
CertSubjectAttributeType,
+ customExtensionLabelSchema,
+ customExtensionValueSchema,
domainComponentSchema,
MAX_DOMAIN_COMPONENTS,
PKI_TEXT_COLUMN_MAX_LENGTH
@@ -116,6 +121,14 @@ const policyExtendedKeyUsagesSchema = z
}
);
+export const policyCustomExtensionSchema = z.object({
+ oid: certificateExtensionOidSchema,
+ label: customExtensionLabelSchema.optional(),
+ critical: z.nativeEnum(CertExtensionCriticality).optional(),
+ rule: z.nativeEnum(CertExtensionRuleKind).describe(CERTIFICATE_POLICIES.CUSTOM_EXTENSION_RULE.rule),
+ value: customExtensionValueSchema.describe(CERTIFICATE_POLICIES.CUSTOM_EXTENSION_RULE.value)
+});
+
const policySanSchema = z
.object({
type: sanTypeSchema,
@@ -183,6 +196,7 @@ export const certificatePolicyResponseSchema = z.object({
algorithms: policyAlgorithmsSchema.optional(),
validity: policyValiditySchema.optional(),
basicConstraints: policyBasicConstraintsSchema.optional(),
+ customExtensions: z.array(policyCustomExtensionSchema).optional(),
createdAt: z.date(),
updatedAt: z.date()
});
@@ -234,5 +248,14 @@ export const certificateRequestSchema = z.object({
})
.optional(),
signatureAlgorithm: z.string().trim().min(1, "Signature algorithm cannot be empty").optional(),
- keyAlgorithm: z.string().trim().min(1, "Key algorithm cannot be empty").optional()
+ keyAlgorithm: z.string().trim().min(1, "Key algorithm cannot be empty").optional(),
+ customExtensions: z
+ .array(
+ z.object({
+ oid: certificateExtensionOidSchema,
+ value: customExtensionValueSchema.optional(),
+ critical: z.boolean().optional()
+ })
+ )
+ .optional()
});
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 7a0b6d87ce..45d6b35796 100644
--- a/backend/src/services/certificate-policy/certificate-policy-service.test.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-service.test.ts
@@ -192,6 +192,84 @@ describe("CertificatePolicyService", () => {
// - Default key algorithm not in allowed list (now schema-level validation)
});
+ describe("custom extension rules", () => {
+ const SID_OID = "1.3.6.1.4.1.311.25.2";
+ const CUSTOM_OID = "1.3.6.1.4.1.99999.7.1";
+
+ const createWith = (customExtensions: unknown) =>
+ service.createPolicy({
+ ...mockActor,
+ projectId: "project-123",
+ data: { name: "ext-policy", customExtensions } as never
+ });
+
+ beforeEach(() => {
+ mockCertificatePolicyDAL.create.mockResolvedValue(sampleTemplate);
+ });
+
+ it("accepts a rule for an unmanaged OID", async () => {
+ await expect(createWith([{ oid: CUSTOM_OID, rule: "allow", value: "*" }])).resolves.toBeDefined();
+ });
+
+ it("rejects a reserved OID", async () => {
+ await expect(createWith([{ oid: "2.5.29.17", rule: "allow", value: "*" }])).rejects.toThrow(
+ "standard X.509 extension that Infisical manages"
+ );
+ });
+
+ it("rejects the UPN otherName OID with a pointer to SANs", async () => {
+ await expect(createWith([{ oid: "1.3.6.1.4.1.311.20.2.3", rule: "allow", value: "*" }])).rejects.toThrow(
+ "Use a UPN subject alternative name"
+ );
+ });
+
+ it("rejects duplicate OIDs", async () => {
+ await expect(
+ createWith([
+ { oid: CUSTOM_OID, rule: "allow", value: "*" },
+ { oid: CUSTOM_OID, rule: "deny", value: "x" }
+ ])
+ ).rejects.toThrow("Duplicate custom extension rule");
+ });
+
+ it("rejects constraining criticality on a preset OID, whose spec fixes it", async () => {
+ await expect(createWith([{ oid: SID_OID, rule: "allow", value: "*", critical: "critical" }])).rejects.toThrow(
+ "always emitted as non-critical"
+ );
+ });
+
+ const extensionOnlyPolicy = (value: string) =>
+ ({
+ id: "p",
+ projectId: "project-123",
+ name: "p",
+ customExtensions: [{ oid: SID_OID, rule: "allow", value }]
+ }) as never;
+
+ it("resolves declarations through validateRequestAgainstPolicy", () => {
+ const result = service.validateRequestAgainstPolicy(
+ extensionOnlyPolicy("S-1-5-21-1-2-3-*"),
+ {},
+ { profileCustomExtensions: [{ oid: SID_OID, value: "S-1-5-21-1-2-3-1103" }] }
+ );
+
+ expect(result.isValid).toBe(true);
+ expect(result.resolvedCustomExtensions).toHaveLength(1);
+ expect(result.resolvedCustomExtensions?.[0].oid).toBe(SID_OID);
+ });
+
+ it("rejects a declared value the policy forbids", () => {
+ const result = service.validateRequestAgainstPolicy(
+ extensionOnlyPolicy("S-1-5-21-1-2-3-*"),
+ {},
+ { profileCustomExtensions: [{ oid: SID_OID, value: "S-1-5-21-9-9-9-1103" }] }
+ );
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors.join(" ")).toContain("is not allowed by this policy");
+ });
+ });
+
describe("updatePolicy", () => {
it("should update policy with valid data", async () => {
const updateData = { name: "updated-template-name" };
diff --git a/backend/src/services/certificate-policy/certificate-policy-service.ts b/backend/src/services/certificate-policy/certificate-policy-service.ts
index cab9079075..080201e5ec 100644
--- a/backend/src/services/certificate-policy/certificate-policy-service.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-service.ts
@@ -20,8 +20,17 @@ import { ActorAuthMethod, ActorType } from "../auth/auth-type";
import {
CertPolicyState,
CertSubjectAlternativeNameType,
- CertSubjectAttributeType
+ CertSubjectAttributeType,
+ MAX_CUSTOM_EXTENSION_RULES_PER_POLICY
} from "../certificate-common/certificate-constants";
+import {
+ CUSTOM_EXTENSION_PRESETS_BY_OID,
+ describeReservedExtensionOid,
+ isReservedExtensionOid,
+ resolveCustomExtensions,
+ TCustomExtensionRule,
+ validateCustomExtensionValue
+} from "../certificate-common/certificate-extension-fns";
import { TCertificatePolicyDALFactory } from "./certificate-policy-dal";
import {
isDomainComponentRule,
@@ -34,6 +43,7 @@ import {
TCertificatePolicyInsert,
TCertificatePolicyUpdate,
TCertificateRequest,
+ TPolicyValidationOptions,
TPolicyValidationResult,
TSubjectRule
} from "./certificate-policy-types";
@@ -151,6 +161,44 @@ export const certificatePolicyServiceFactory = ({
}
};
+ const validateCustomExtensionPolicy = (customExtensions: TCustomExtensionRule[]) => {
+ if (customExtensions.length > MAX_CUSTOM_EXTENSION_RULES_PER_POLICY) {
+ throw new BadRequestError({
+ message: `A policy cannot have more than ${MAX_CUSTOM_EXTENSION_RULES_PER_POLICY} custom extension rules`
+ });
+ }
+
+ const seenOids = new Set<string>();
+ for (const rule of customExtensions) {
+ if (seenOids.has(rule.oid)) {
+ throw new BadRequestError({
+ message: `Duplicate custom extension rule for OID '${rule.oid}'. Each OID must appear only once.`
+ });
+ }
+ seenOids.add(rule.oid);
+
+ if (isReservedExtensionOid(rule.oid)) {
+ throw new BadRequestError({ message: describeReservedExtensionOid(rule.oid) });
+ }
+
+ if (!isWildcardPattern(rule.value)) {
+ const invalid = validateCustomExtensionValue(rule.oid, rule.value);
+ if (invalid) {
+ throw new BadRequestError({
+ message: `Custom extension rule for OID '${rule.oid}' has a value this extension can never take, so the rule would never apply. ${invalid}`
+ });
+ }
+ }
+
+ const preset = CUSTOM_EXTENSION_PRESETS_BY_OID[rule.oid];
+ if (preset && rule.critical) {
+ throw new BadRequestError({
+ message: `Custom extension '${rule.oid}' is always emitted as ${preset.critical ? "critical" : "non-critical"}, so its criticality cannot be constrained.`
+ });
+ }
+ }
+ };
+
const generateTemplateSlug = (baseName?: string): string => {
if (baseName) {
return slugify(baseName);
@@ -201,7 +249,7 @@ export const certificatePolicyServiceFactory = ({
if (!keyUsages) return;
if (!keyUsages.allowed && !keyUsages.required && !keyUsages.denied) {
- throw new ForbiddenRequestError({
+ throw new BadRequestError({
message: "Key usages must have at least one allowed, required, or denied value"
});
}
@@ -216,7 +264,7 @@ export const certificatePolicyServiceFactory = ({
if (values && values.length > 0) {
const uniqueValues = new Set(values);
if (uniqueValues.size !== values.length) {
- throw new ForbiddenRequestError({
+ throw new BadRequestError({
message: `Duplicate values found in ${name} key usages list`
});
}
@@ -232,7 +280,7 @@ export const certificatePolicyServiceFactory = ({
if (!extendedKeyUsages) return;
if (!extendedKeyUsages.allowed && !extendedKeyUsages.required && !extendedKeyUsages.denied) {
- throw new ForbiddenRequestError({
+ throw new BadRequestError({
message: "Extended key usages must have at least one allowed, required, or denied value"
});
}
@@ -247,7 +295,7 @@ export const certificatePolicyServiceFactory = ({
if (values && values.length > 0) {
const uniqueValues = new Set(values);
if (uniqueValues.size !== values.length) {
- throw new ForbiddenRequestError({
+ throw new BadRequestError({
message: `Duplicate values found in ${name} extended key usages list`
});
}
@@ -298,7 +346,7 @@ export const certificatePolicyServiceFactory = ({
const validateRequestAgainstPolicy = (
template: TCertificatePolicy,
request: TCertificateRequest,
- options?: { skipRequired?: boolean }
+ options?: TPolicyValidationOptions
): TPolicyValidationResult => {
const errors: string[] = [];
const warnings: string[] = [];
@@ -650,10 +698,19 @@ export const certificatePolicyServiceFactory = ({
}
}
+ const { extensions: resolvedCustomExtensions, errors: customExtensionErrors } = resolveCustomExtensions({
+ declarations: options?.profileCustomExtensions,
+ rules: template.customExtensions,
+ requestExtensions: request.customExtensions,
+ skipRequired: options?.skipRequired
+ });
+ errors.push(...customExtensionErrors);
+
return {
isValid: errors.length === 0,
errors,
- warnings
+ warnings,
+ resolvedCustomExtensions
};
};
@@ -715,8 +772,12 @@ export const certificatePolicyServiceFactory = ({
}
// Generate slug from name and ensure it's unique within project
+ if (consolidatedData.customExtensions) {
+ validateCustomExtensionPolicy(consolidatedData.customExtensions);
+ }
+
if (!data.name) {
- throw new ForbiddenRequestError({ message: "Template name is required" });
+ throw new BadRequestError({ message: "Template name is required" });
}
const slug = generateTemplateSlug(data.name);
@@ -789,6 +850,27 @@ export const certificatePolicyServiceFactory = ({
validateExtendedKeyUsagePolicy(consolidatedData.extendedKeyUsages);
}
+ if (consolidatedData.customExtensions) {
+ validateCustomExtensionPolicy(consolidatedData.customExtensions);
+
+ const boundProfiles = await certificatePolicyDAL.getProfilesUsingPolicy(policyId);
+ for (const boundProfile of boundProfiles) {
+ const declarations = boundProfile.defaults?.customExtensions;
+ if (declarations?.length) {
+ const { errors } = resolveCustomExtensions({
+ declarations,
+ rules: consolidatedData.customExtensions,
+ skipRequired: true
+ });
+ if (errors.length) {
+ throw new BadRequestError({
+ message: `Certificate profile '${boundProfile.slug}' uses this policy and would no longer be valid. ${errors.join(" ")}`
+ });
+ }
+ }
+ }
+ }
+
const updateData = { ...consolidatedData };
if (data.name && typeof data.name === "string") {
const newSlug = generateTemplateSlug(data.name);
@@ -1017,14 +1099,15 @@ export const certificatePolicyServiceFactory = ({
const validateCertificateRequest = async (
policyId: string,
- request: TCertificateRequest
+ request: TCertificateRequest,
+ options?: TPolicyValidationOptions
): Promise<TPolicyValidationResult> => {
const policy = await certificatePolicyDAL.findById(policyId);
if (!policy) {
throw new NotFoundError({ message: "Certificate policy not found" });
}
- return validateRequestAgainstPolicy(policy, request);
+ return validateRequestAgainstPolicy(policy, request, options);
};
return {
diff --git a/backend/src/services/certificate-policy/certificate-policy-types.ts b/backend/src/services/certificate-policy/certificate-policy-types.ts
index cd71069a99..92221fb07c 100644
--- a/backend/src/services/certificate-policy/certificate-policy-types.ts
+++ b/backend/src/services/certificate-policy/certificate-policy-types.ts
@@ -6,6 +6,12 @@ import {
CertSubjectAlternativeNameType,
CertSubjectAttributeType
} from "@app/services/certificate-common/certificate-constants";
+import {
+ TCustomExtensionRule,
+ TProfileCustomExtension,
+ TRequestCustomExtension,
+ TResolvedCustomExtension
+} from "@app/services/certificate-common/certificate-extension-fns";
export type TBasicConstraintsIsCAPolicy = CertPolicyState;
@@ -55,6 +61,7 @@ export interface TTemplateV2Policy {
validity?: {
max?: string;
};
+ customExtensions?: TCustomExtensionRule[];
}
export type TCertificatePolicy = TPkiCertificatePolicies & {
@@ -65,6 +72,7 @@ export type TCertificatePolicy = TPkiCertificatePolicies & {
algorithms?: TTemplateV2Policy["algorithms"];
validity?: TTemplateV2Policy["validity"];
basicConstraints?: TBasicConstraints | null;
+ customExtensions?: TCustomExtensionRule[];
};
export type TCertificatePolicyInsert = TPkiCertificatePoliciesInsert & {
@@ -75,6 +83,7 @@ export type TCertificatePolicyInsert = TPkiCertificatePoliciesInsert & {
algorithms?: TTemplateV2Policy["algorithms"] | null;
validity?: TTemplateV2Policy["validity"] | null;
basicConstraints?: TBasicConstraints | null;
+ customExtensions?: TCustomExtensionRule[] | null;
};
export type TCertificatePolicyUpdate = Partial<Pick<TCertificatePolicy, "name" | "description">> & {
@@ -85,6 +94,7 @@ export type TCertificatePolicyUpdate = Partial<Pick<TCertificatePolicy, "name" |
algorithms?: TTemplateV2Policy["algorithms"] | null;
validity?: TTemplateV2Policy["validity"] | null;
basicConstraints?: TBasicConstraints | null;
+ customExtensions?: TCustomExtensionRule[] | null;
};
export interface TCertificateRequest {
@@ -115,10 +125,17 @@ export interface TCertificateRequest {
isCA: boolean;
pathLength?: number;
};
+ customExtensions?: TRequestCustomExtension[];
+}
+
+export interface TPolicyValidationOptions {
+ skipRequired?: boolean;
+ profileCustomExtensions?: TProfileCustomExtension[] | null;
}
export interface TPolicyValidationResult {
isValid: boolean;
errors: string[];
warnings: string[];
+ resolvedCustomExtensions?: TResolvedCustomExtension[];
}
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.test.ts b/backend/src/services/certificate-profile/certificate-profile-service.test.ts
index ff26ecefff..70b1ce1f2c 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.test.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.test.ts
@@ -13,6 +13,7 @@ import type { TCertificateBodyDALFactory } from "../certificate/certificate-body
import type { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";
import { CertStatus } from "../certificate/certificate-types";
import type { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";
+import { CaType } from "../certificate-authority/certificate-authority-enums";
import type { TExternalCertificateAuthorityDALFactory } from "../certificate-authority/external-certificate-authority-dal";
import type { TCertificatePolicyDALFactory } from "../certificate-policy/certificate-policy-dal";
import { TAcmeEnrollmentConfigDALFactory } from "../enrollment-config/acme-enrollment-config-dal";
@@ -239,6 +240,7 @@ describe("CertificateProfileService", () => {
const mockCertificateAuthorityDAL = {
create: vi.fn(),
findById: vi.fn(),
+ findByIdWithAssociatedCa: vi.fn(),
updateById: vi.fn(),
deleteById: vi.fn(),
transaction: vi.fn(),
@@ -332,6 +334,98 @@ describe("CertificateProfileService", () => {
});
});
+ describe("custom extension declarations", () => {
+ const SID_OID = "1.3.6.1.4.1.311.25.2";
+ const CUSTOM_OID = "1.3.6.1.4.1.99999.7.1";
+
+ const createWithExtensions = (customExtensions: unknown) =>
+ service.createProfile({
+ ...mockActor,
+ projectId: "project-123",
+ data: { ...validProfileData, defaults: { customExtensions } } as never
+ });
+
+ beforeEach(() => {
+ (mockCertificateAuthorityDAL.findByIdWithAssociatedCa as any).mockResolvedValue({
+ id: "ca-123",
+ externalCa: null
+ });
+ });
+
+ it("accepts a declaration the policy permits", async () => {
+ (mockCertificatePolicyDAL.findById as any).mockResolvedValue({
+ ...samplePolicy,
+ customExtensions: [{ oid: SID_OID, rule: "allow", value: "*" }]
+ });
+
+ await expect(createWithExtensions([{ oid: SID_OID, value: "S-1-5-21-1-2-3-1103" }])).resolves.toBeDefined();
+ });
+
+ it("rejects a reserved OID", async () => {
+ await expect(createWithExtensions([{ oid: "2.5.29.17" }])).rejects.toThrow(
+ "standard X.509 extension that Infisical manages"
+ );
+ });
+
+ it("rejects duplicate OIDs", async () => {
+ await expect(createWithExtensions([{ oid: CUSTOM_OID }, { oid: CUSTOM_OID }])).rejects.toThrow(
+ "Duplicate custom extension"
+ );
+ });
+
+ it("rejects more declarations than a profile may hold", async () => {
+ const tooMany = Array.from({ length: 11 }, (_, i) => ({ oid: `1.3.6.1.4.1.99999.7.${i + 1}` }));
+
+ await expect(createWithExtensions(tooMany)).rejects.toThrow("cannot declare more than");
+ });
+
+ it("rejects an OID the policy does not mention", async () => {
+ (mockCertificatePolicyDAL.findById as any).mockResolvedValue({
+ ...samplePolicy,
+ customExtensions: [{ oid: SID_OID, rule: "allow", value: "*" }]
+ });
+
+ await expect(createWithExtensions([{ oid: CUSTOM_OID }])).rejects.toThrow("is not allowed by this policy");
+ });
+
+ it("rejects a declared value the policy forbids", async () => {
+ (mockCertificatePolicyDAL.findById as any).mockResolvedValue({
+ ...samplePolicy,
+ customExtensions: [{ oid: SID_OID, rule: "allow", value: "S-1-5-21-1-2-3-*" }]
+ });
+
+ await expect(createWithExtensions([{ oid: SID_OID, value: "S-1-5-21-9-9-9-1103" }])).rejects.toThrow(
+ "is not allowed by this policy"
+ );
+ });
+
+ it("rejects a certificate authority that cannot carry custom extensions", async () => {
+ (mockCertificateAuthorityDAL.findByIdWithAssociatedCa as any).mockResolvedValue({
+ id: "ca-123",
+ externalCa: { type: CaType.DIGICERT }
+ });
+ (mockCertificatePolicyDAL.findById as any).mockResolvedValue({
+ ...samplePolicy,
+ customExtensions: [{ oid: SID_OID, rule: "allow", value: "*" }]
+ });
+
+ await expect(createWithExtensions([{ oid: SID_OID, value: "S-1-5-21-1-2-3-1103" }])).rejects.toThrow(
+ "cannot carry custom extensions"
+ );
+ });
+
+ it("rejects setting criticality on a preset OID", async () => {
+ (mockCertificatePolicyDAL.findById as any).mockResolvedValue({
+ ...samplePolicy,
+ customExtensions: [{ oid: SID_OID, rule: "allow", value: "*" }]
+ });
+
+ await expect(
+ createWithExtensions([{ oid: SID_OID, value: "S-1-5-21-1-2-3-1103", critical: true }])
+ ).rejects.toThrow("always emitted as non-critical");
+ });
+ });
+
it("should create profile successfully", async () => {
const result = await service.createProfile({
...mockActor,
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.ts
index d51f32116c..e0638f2ef6 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts
@@ -30,9 +30,23 @@ import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-
import { CertStatus } from "../certificate/certificate-types";
import { TCertificateAuthorityCertDALFactory } from "../certificate-authority/certificate-authority-cert-dal";
import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";
-import { CaType } from "../certificate-authority/certificate-authority-enums";
+import { CaCapability, CaType } from "../certificate-authority/certificate-authority-enums";
+import {
+ caSupportsCapability,
+ CERTIFICATE_AUTHORITIES_TYPE_MAP
+} from "../certificate-authority/certificate-authority-maps";
import { TCertificateAuthoritySecretDALFactory } from "../certificate-authority/certificate-authority-secret-dal";
import { TExternalCertificateAuthorityDALFactory } from "../certificate-authority/external-certificate-authority-dal";
+import {
+ MAX_CUSTOM_EXTENSIONS_PER_AWS_PCA_PROFILE,
+ MAX_CUSTOM_EXTENSIONS_PER_PROFILE
+} from "../certificate-common/certificate-constants";
+import {
+ describeReservedExtensionOid,
+ isReservedExtensionOid,
+ resolveCustomExtensions,
+ TCustomExtensionRule
+} from "../certificate-common/certificate-extension-fns";
import { isSignatureAlgorithmCompatibleWithCaKey } from "../certificate-common/certificate-issuance-utils";
import { TCertificatePolicyDALFactory } from "../certificate-policy/certificate-policy-dal";
import { TCertificatePolicyServiceFactory } from "../certificate-policy/certificate-policy-service";
@@ -395,6 +409,65 @@ export const certificateProfileServiceFactory = ({
resourceMetadataDAL,
pkiApplicationProfileDAL
}: TCertificateProfileServiceFactoryDep) => {
+ const validateProfileCustomExtensions = async ({
+ certificatePolicyId,
+ caId,
+ defaults
+ }: {
+ certificatePolicyId?: string | null;
+ caId?: string | null;
+ defaults?: TCertificateProfileDefaults | null;
+ }) => {
+ const declarations = defaults?.customExtensions;
+ if (!declarations?.length) return;
+
+ if (declarations.length > MAX_CUSTOM_EXTENSIONS_PER_PROFILE) {
+ throw new BadRequestError({
+ message: `A profile cannot declare more than ${MAX_CUSTOM_EXTENSIONS_PER_PROFILE} custom extensions`
+ });
+ }
+
+ const seenOids = new Set<string>();
+ for (const declaration of declarations) {
+ if (seenOids.has(declaration.oid)) {
+ throw new BadRequestError({
+ message: `Duplicate custom extension for OID '${declaration.oid}'. Each OID must appear only once.`
+ });
+ }
+ seenOids.add(declaration.oid);
+
+ if (isReservedExtensionOid(declaration.oid)) {
+ throw new BadRequestError({ message: describeReservedExtensionOid(declaration.oid) });
+ }
+ }
+
+ const policy = certificatePolicyId ? await certificatePolicyDAL.findById(certificatePolicyId) : null;
+ const { errors } = resolveCustomExtensions({
+ declarations,
+ rules: policy?.customExtensions as TCustomExtensionRule[] | null | undefined,
+ skipRequired: true
+ });
+ if (errors.length) {
+ throw new BadRequestError({ message: errors.join(" ") });
+ }
+
+ if (caId) {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ const caType = (ca?.externalCa?.type ?? CaType.INTERNAL) as CaType;
+ if (!caSupportsCapability(caType, CaCapability.CUSTOM_EXTENSIONS)) {
+ throw new BadRequestError({
+ message: `${CERTIFICATE_AUTHORITIES_TYPE_MAP[caType] ?? caType} certificate authorities cannot carry custom extensions, so this profile cannot declare any. Use an internal certificate authority, ${CERTIFICATE_AUTHORITIES_TYPE_MAP[CaType.ADCS]}, or ${CERTIFICATE_AUTHORITIES_TYPE_MAP[CaType.AWS_PCA]} instead.`
+ });
+ }
+
+ if (caType === CaType.AWS_PCA && declarations.length > MAX_CUSTOM_EXTENSIONS_PER_AWS_PCA_PROFILE) {
+ throw new BadRequestError({
+ message: `AWS Private CA accepts at most ${MAX_CUSTOM_EXTENSIONS_PER_AWS_PCA_PROFILE} custom extensions on a certificate, so this profile cannot declare ${declarations.length}.`
+ });
+ }
+ }
+ };
+
const createProfile = async ({
actor,
actorId,
@@ -489,6 +562,12 @@ export const certificateProfileServiceFactory = ({
}
}
+ await validateProfileCustomExtensions({
+ certificatePolicyId: data.certificatePolicyId,
+ caId: data.caId,
+ defaults: data.defaults
+ });
+
await validateDefaultSignatureAlgorithmAgainstCa(
data.defaults?.signatureAlgorithm,
data.caId,
@@ -806,6 +885,14 @@ export const certificateProfileServiceFactory = ({
}
}
+ await validateProfileCustomExtensions({
+ certificatePolicyId:
+ data.certificatePolicyId !== undefined ? data.certificatePolicyId : existingProfile.certificatePolicyId,
+ caId: data.caId !== undefined ? data.caId : existingProfile.caId,
+ defaults:
+ data.defaults !== undefined ? data.defaults : (existingProfile.defaults as TCertificateProfileDefaults | null)
+ });
+
await validateDefaultSignatureAlgorithmAgainstCa(
data.defaults?.signatureAlgorithm,
finalCaId,
diff --git a/backend/src/services/certificate-profile/certificate-profile-types.ts b/backend/src/services/certificate-profile/certificate-profile-types.ts
index a65ca4847a..d68b9fc2f6 100644
--- a/backend/src/services/certificate-profile/certificate-profile-types.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-types.ts
@@ -11,6 +11,7 @@ import {
CertSignatureAlgorithm,
CertSubjectAlternativeNameType
} from "../certificate-common/certificate-constants";
+import { TProfileCustomExtension } from "../certificate-common/certificate-extension-fns";
export enum EnrollmentType {
API = "api",
@@ -39,6 +40,7 @@ export type TCertificateProfileDefaults = {
locality?: string;
subjectAltNames?: { type: CertSubjectAlternativeNameType; value: string }[];
domainComponents?: string[];
+ customExtensions?: TProfileCustomExtension[];
};
export type TCertificateProfile = Omit<
diff --git a/backend/src/services/certificate-request/certificate-request-service.test.ts b/backend/src/services/certificate-request/certificate-request-service.test.ts
index 0fa749efc6..499a1251e7 100644
--- a/backend/src/services/certificate-request/certificate-request-service.test.ts
+++ b/backend/src/services/certificate-request/certificate-request-service.test.ts
@@ -312,6 +312,7 @@ describe("CertificateRequestService", () => {
locality: null,
domainComponents: null,
basicConstraints: undefined,
+ customExtensions: null,
metadata: [],
createdAt: mockRequestWithCert.createdAt,
updatedAt: mockRequestWithCert.updatedAt
@@ -359,6 +360,7 @@ describe("CertificateRequestService", () => {
locality: null,
domainComponents: null,
basicConstraints: undefined,
+ customExtensions: null,
metadata: [],
createdAt: mockRequestWithoutCert.createdAt,
updatedAt: mockRequestWithoutCert.updatedAt
@@ -426,6 +428,7 @@ describe("CertificateRequestService", () => {
locality: null,
domainComponents: null,
basicConstraints: undefined,
+ customExtensions: null,
metadata: [],
createdAt: mockRequestWithCert.createdAt,
updatedAt: mockRequestWithCert.updatedAt
@@ -504,6 +507,7 @@ describe("CertificateRequestService", () => {
locality: null,
domainComponents: null,
basicConstraints: undefined,
+ customExtensions: null,
metadata: [],
createdAt: mockRequestWithCert.createdAt,
updatedAt: mockRequestWithCert.updatedAt
@@ -551,6 +555,7 @@ describe("CertificateRequestService", () => {
locality: null,
domainComponents: null,
basicConstraints: undefined,
+ customExtensions: null,
metadata: [],
createdAt: mockFailedRequest.createdAt,
updatedAt: mockFailedRequest.updatedAt
diff --git a/backend/src/services/certificate-request/certificate-request-service.ts b/backend/src/services/certificate-request/certificate-request-service.ts
index bba5591ba4..221247ff31 100644
--- a/backend/src/services/certificate-request/certificate-request-service.ts
+++ b/backend/src/services/certificate-request/certificate-request-service.ts
@@ -19,7 +19,14 @@ import { logger } from "@app/lib/logger";
import { QueueName, TQueueServiceFactory } from "@app/queue";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TCertificateServiceFactory } from "@app/services/certificate/certificate-service";
-import { domainComponentsSchema } from "@app/services/certificate-common/certificate-constants";
+import {
+ domainComponentsSchema,
+ resolvedCustomExtensionSchema
+} from "@app/services/certificate-common/certificate-constants";
+import {
+ describeCustomExtensionValue,
+ TResolvedCustomExtension
+} from "@app/services/certificate-common/certificate-extension-fns";
import { ActorAuthMethod, ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -76,6 +83,7 @@ const certificateRequestDataSchema = z
pathLength: z.number().int().min(-1).optional()
})
.optional(),
+ customExtensions: z.array(resolvedCustomExtensionSchema).optional(),
ttl: z.string().max(50).optional(),
enrollmentType: z.string().max(50).optional(),
organization: z.string().max(255).optional(),
@@ -179,7 +187,12 @@ export const certificateRequestServiceFactory = ({
// Validate input data before creating the request
const validatedData = validateCertificateRequestData(requestData);
- const { altNames: altNamesInput, domainComponents: domainComponentsInput, ...restValidatedData } = validatedData;
+ const {
+ altNames: altNamesInput,
+ domainComponents: domainComponentsInput,
+ customExtensions: customExtensionsInput,
+ ...restValidatedData
+ } = validatedData;
// Explicitly set createdAt to ensure millisecond precision matches when used in FK references.
// PostgreSQL's DEFAULT now() has microsecond precision, but JavaScript Date only has millisecond precision.
@@ -192,6 +205,7 @@ export const certificateRequestServiceFactory = ({
acmeOrderId,
...restValidatedData,
altNames: altNamesInput ? JSON.stringify(altNamesInput) : null,
+ customExtensions: customExtensionsInput?.length ? JSON.stringify(customExtensionsInput) : null,
domainComponents:
domainComponentsInput && domainComponentsInput.length > 0 ? domainComponentsInput.join(",") : null,
createdAt: new Date()
@@ -321,6 +335,11 @@ export const certificateRequestServiceFactory = ({
}
}
+ const parsedCustomExtensions =
+ (certificateRequest.customExtensions as TResolvedCustomExtension[] | null)?.map((extension) => ({
+ ...extension,
+ displayValue: describeCustomExtensionValue(extension.oid, extension.value) ?? undefined
+ })) ?? null;
const parsedBasicConstraints = certificateRequest.basicConstraints as {
isCA: boolean;
pathLength?: number;
@@ -345,6 +364,7 @@ export const certificateRequestServiceFactory = ({
locality: certificateRequest.locality || null,
domainComponents: certificateRequest.domainComponents ? certificateRequest.domainComponents.split(",") : null,
basicConstraints: parsedBasicConstraints,
+ customExtensions: parsedCustomExtensions,
metadata: requestMetadata,
createdAt: certificateRequest.createdAt,
updatedAt: certificateRequest.updatedAt
@@ -423,6 +443,7 @@ export const certificateRequestServiceFactory = ({
locality: certificateRequest.locality || null,
domainComponents: certificateRequest.domainComponents ? certificateRequest.domainComponents.split(",") : null,
basicConstraints: parsedBasicConstraints,
+ customExtensions: parsedCustomExtensions,
metadata: requestMetadata,
createdAt: certificateRequest.createdAt,
updatedAt: certificateRequest.updatedAt
diff --git a/backend/src/services/certificate-request/certificate-request-types.ts b/backend/src/services/certificate-request/certificate-request-types.ts
index dde4b0d93c..85c65f8611 100644
--- a/backend/src/services/certificate-request/certificate-request-types.ts
+++ b/backend/src/services/certificate-request/certificate-request-types.ts
@@ -1,4 +1,5 @@
import { TProjectPermission } from "@app/lib/types";
+import { TResolvedCustomExtension } from "@app/services/certificate-common/certificate-extension-fns";
import { CertificateRequestStatus } from "../certificate-common/certificate-constants";
import { EnrollmentType } from "../certificate-profile/certificate-profile-types";
@@ -28,6 +29,7 @@ export type TCreateCertificateRequestDTO = TProjectPermission & {
status: CertificateRequestStatus;
certificateId?: string;
acmeOrderId?: string;
+ customExtensions?: TResolvedCustomExtension[];
basicConstraints?: {
isCA: boolean;
pathLength?: number;
diff --git a/backend/src/services/certificate-v3/certificate-approval-fns.ts b/backend/src/services/certificate-v3/certificate-approval-fns.ts
index 5bb2f5f677..12ae633aeb 100644
--- a/backend/src/services/certificate-v3/certificate-approval-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-approval-fns.ts
@@ -28,6 +28,12 @@ import {
extractAlgorithmsFromCSR,
extractCertificateRequestFromCSR
} from "@app/services/certificate-common/certificate-csr-utils";
+import {
+ parseIssuedCustomExtensions,
+ toRequestCustomExtensions,
+ TRequestCustomExtension,
+ TResolvedCustomExtension
+} from "@app/services/certificate-common/certificate-extension-fns";
import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
import { TCertificateRequest, TSubjectRule } from "@app/services/certificate-policy/certificate-policy-types";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
@@ -107,6 +113,7 @@ const buildRevalidationRequest = ({
notAfter,
altNames,
basicConstraints,
+ customExtensions,
profileDefaults,
ttl
}: {
@@ -125,6 +132,7 @@ const buildRevalidationRequest = ({
notAfter?: Date | null;
altNames?: TAltNameEntry[] | null;
basicConstraints?: { isCA: boolean; pathLength?: number | null } | null;
+ customExtensions?: TRequestCustomExtension[];
profileDefaults: Parameters<typeof applyProfileDefaults>[1];
ttl?: string;
}): TCertificateRequest => {
@@ -154,6 +162,10 @@ const buildRevalidationRequest = ({
mappedRequest.signatureAlgorithm = csrSigAlg;
}
// The stored value wins over anything reconstructed from the CSR or profile defaults.
+ if (customExtensions?.length) {
+ mappedRequest.customExtensions = customExtensions;
+ }
+
if (basicConstraints) {
mappedRequest.basicConstraints = {
isCA: basicConstraints.isCA,
@@ -263,9 +275,11 @@ export const certificateApprovalServiceFactory = (
selfSignedResult,
certificateRequest,
profile,
+ customExtensions,
tx
}: {
selfSignedResult: Awaited<ReturnType<typeof generateSelfSignedCertificate>>;
+ customExtensions?: TResolvedCustomExtension[];
certificateRequest: {
commonName?: string;
keyUsages?: CertKeyUsageType[];
@@ -296,6 +310,7 @@ export const certificateApprovalServiceFactory = (
projectId,
keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
+ customExtensions: JSON.stringify(parseIssuedCustomExtensions(selfSignedResult.certificate, customExtensions)),
profileId: profile?.id || null
},
tx
@@ -353,6 +368,7 @@ export const certificateApprovalServiceFactory = (
policy,
profile,
effectiveAlgorithms,
+ customExtensions,
tx
}: {
certificateRequest: {
@@ -383,6 +399,7 @@ export const certificateApprovalServiceFactory = (
signatureAlgorithm: CertSignatureAlgorithm;
keyAlgorithm: CertKeyAlgorithm;
};
+ customExtensions?: TResolvedCustomExtension[];
tx: Parameters<TCertificateDALFactory["create"]>[1];
}) => {
const projectId = profile?.projectId;
@@ -394,13 +411,15 @@ export const certificateApprovalServiceFactory = (
certificateRequest,
policy,
effectiveSignatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,
- effectiveKeyAlgorithm: effectiveAlgorithms.keyAlgorithm
+ effectiveKeyAlgorithm: effectiveAlgorithms.keyAlgorithm,
+ customExtensions
});
const certificateData = await $createSelfSignedCertificateRecord({
selfSignedResult,
certificateRequest,
profile,
+ customExtensions,
tx
});
@@ -521,7 +540,8 @@ export const certificateApprovalServiceFactory = (
const revalidationResult = await certificatePolicyService.validateCertificateRequest(
profile.certificatePolicyId,
- mappedReconstructedRequest
+ mappedReconstructedRequest,
+ { profileCustomExtensions: profile.defaults?.customExtensions }
);
if (!revalidationResult.isValid) {
throw new BadRequestError({
@@ -568,6 +588,7 @@ export const certificateApprovalServiceFactory = (
notAfter: normalizeDateForApi(certRequest.notAfter || undefined),
signatureAlgorithm: certRequest.signatureAlgorithm || undefined,
keyAlgorithm: certRequest.keyAlgorithm || undefined,
+ customExtensions: revalidationResult.resolvedCustomExtensions,
isFromProfile: true,
basicConstraints: effectiveBasicConstraints,
pathLength: effectivePathLength,
@@ -701,13 +722,15 @@ export const certificateApprovalServiceFactory = (
notAfter: certRequest.notAfter,
altNames,
basicConstraints: certRequest.basicConstraints as { isCA: boolean; pathLength?: number | null } | null,
+ customExtensions: toRequestCustomExtensions(certRequest.customExtensions),
profileDefaults: profile.defaults,
ttl: effectiveTtl
});
const revalidationResult = await certificatePolicyService.validateCertificateRequest(
profile.certificatePolicyId,
- mappedReconstructedRequest
+ mappedReconstructedRequest,
+ { profileCustomExtensions: profile.defaults?.customExtensions }
);
if (!revalidationResult.isValid) {
throw new BadRequestError({
@@ -737,6 +760,7 @@ export const certificateApprovalServiceFactory = (
state: certRequest.state || undefined,
locality: certRequest.locality || undefined,
basicConstraints: certRequest.basicConstraints as { isCA: boolean; pathLength?: number | null } | null,
+ customExtensions: revalidationResult.resolvedCustomExtensions,
...(certRequest.applicationId && { applicationId: certRequest.applicationId })
});
@@ -775,7 +799,8 @@ export const certificateApprovalServiceFactory = (
certificateRequestId: string,
profile: NonNullable<Awaited<ReturnType<TCertificateProfileDALFactory["findByIdWithConfigs"]>>>,
certPolicy: NonNullable<Awaited<ReturnType<TCertificatePolicyServiceFactory["getPolicyById"]>>>,
- applicationId?: string | null
+ applicationId?: string | null,
+ customExtensions?: TResolvedCustomExtension[]
): Promise<TCertificateIssuanceResponse> => {
const effectiveSignatureAlgorithm = certificateRequestInput.signatureAlgorithm as
| CertSignatureAlgorithm
@@ -790,6 +815,7 @@ export const certificateApprovalServiceFactory = (
policy: certPolicy,
profile,
effectiveAlgorithms,
+ customExtensions,
tx
});
@@ -883,7 +909,8 @@ export const certificateApprovalServiceFactory = (
certificateRequestId: string,
profile: NonNullable<Awaited<ReturnType<TCertificateProfileDALFactory["findByIdWithConfigs"]>>>,
certPolicy: NonNullable<Awaited<ReturnType<TCertificatePolicyServiceFactory["getPolicyById"]>>>,
- applicationId?: string | null
+ applicationId?: string | null,
+ customExtensions?: TResolvedCustomExtension[]
): Promise<TCertificateIssuanceResponse> => {
if (!profile.caId) {
throw new NotFoundError({ message: "Certificate Authority ID not found" });
@@ -917,6 +944,7 @@ export const certificateApprovalServiceFactory = (
friendlyName: certificateSubject.common_name || "Certificate",
commonName: certificateSubject.common_name || "",
altNames: subjectAlternativeNames,
+ altNameEntries: certificateRequestInput.altNames,
ttl: certificateRequestInput.validity.ttl,
keyUsages: convertKeyUsageArrayToLegacy(certificateRequestInput.keyUsages) || [],
extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequestInput.extendedKeyUsages) || [],
@@ -924,6 +952,7 @@ export const certificateApprovalServiceFactory = (
notAfter: normalizeDateForApi(certificateRequestInput.notAfter),
signatureAlgorithm: effectiveSignatureAlgorithm,
keyAlgorithm: effectiveKeyAlgorithm,
+ customExtensions,
actor: undefined,
actorId: undefined,
actorAuthMethod: undefined,
@@ -1072,7 +1101,8 @@ export const certificateApprovalServiceFactory = (
country: certRequest.country || undefined,
state: certRequest.state || undefined,
locality: certRequest.locality || undefined,
- basicConstraints: basicConstraints || undefined
+ basicConstraints: basicConstraints || undefined,
+ customExtensions: toRequestCustomExtensions(certRequest.customExtensions)
};
// Validate against certificate policy
@@ -1096,7 +1126,8 @@ export const certificateApprovalServiceFactory = (
const validationResult = await certificatePolicyService.validateCertificateRequest(
targetProfile.certificatePolicyId,
- mappedCertificateRequest
+ mappedCertificateRequest,
+ { profileCustomExtensions: targetProfile.defaults?.customExtensions }
);
if (!validationResult.isValid) {
@@ -1113,7 +1144,8 @@ export const certificateApprovalServiceFactory = (
certificateRequestId,
targetProfile,
certPolicy,
- certRequest.applicationId
+ certRequest.applicationId,
+ validationResult.resolvedCustomExtensions
);
}
@@ -1122,7 +1154,8 @@ export const certificateApprovalServiceFactory = (
certificateRequestId,
targetProfile,
certPolicy,
- certRequest.applicationId
+ certRequest.applicationId,
+ validationResult.resolvedCustomExtensions
);
} catch (error) {
await certificateRequestDAL.updateById(certificateRequestId, {
diff --git a/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts b/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts
index a54f801386..df495e0e61 100644
--- a/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts
+++ b/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts
@@ -9,6 +9,7 @@ import {
CertSignatureAlgorithm,
CertSubjectAlternativeNameType
} from "../certificate-common/certificate-constants";
+import { encodeCustomExtensionValue } from "../certificate-common/certificate-extension-fns";
import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
import {
assertCsrRenewalAttributes,
@@ -72,6 +73,12 @@ describe("assertCsrRenewalAttributes", () => {
expect(() => assertCsrRenewalAttributes({ ttl: "30d", basicConstraints: { isCA: false } })).not.toThrow();
});
+ it("allows custom extensions, which a CSR never supplies on its own", () => {
+ expect(() =>
+ assertCsrRenewalAttributes({ customExtensions: [{ oid: "1.3.6.1.4.1.99001.1", value: "ops-prod" }] })
+ ).not.toThrow();
+ });
+
it("rejects anything the CSR already carries, naming the fields", () => {
expect(() => assertCsrRenewalAttributes({ commonName: "other.example.com", ttl: "30d" })).toThrow(/common name/);
expect(() =>
@@ -259,6 +266,48 @@ describe("buildRenewalAuditChanges", () => {
expect(buildRenewalAuditChanges(cert, unchangedRequest)).toEqual([]);
});
+ it("records a custom extension change with the readable values, not their DER", () => {
+ const withExtension = {
+ ...cert,
+ customExtensions: [
+ {
+ oid: "1.3.6.1.4.1.99001.1",
+ critical: false,
+ value: encodeCustomExtensionValue("1.3.6.1.4.1.99001.1", "before")
+ }
+ ]
+ };
+
+ const changes = buildRenewalAuditChanges(withExtension, {
+ ...unchangedRequest,
+ customExtensions: [{ oid: "1.3.6.1.4.1.99001.1", value: "after" }]
+ });
+
+ expect(changes).toEqual([
+ { field: "customExtensions", from: "1.3.6.1.4.1.99001.1=before", to: "1.3.6.1.4.1.99001.1=after" }
+ ]);
+ });
+
+ it("records nothing when the custom extensions are unchanged", () => {
+ const withExtension = {
+ ...cert,
+ customExtensions: [
+ {
+ oid: "1.3.6.1.4.1.99001.1",
+ critical: false,
+ value: encodeCustomExtensionValue("1.3.6.1.4.1.99001.1", "same")
+ }
+ ]
+ };
+
+ expect(
+ buildRenewalAuditChanges(withExtension, {
+ ...unchangedRequest,
+ customExtensions: [{ oid: "1.3.6.1.4.1.99001.1", value: "same" }]
+ })
+ ).toEqual([]);
+ });
+
it("does not report a change when stored legacy usage names resolve to the same usages", () => {
expect(
buildRenewalAuditChanges(cert, { ...unchangedRequest, keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE] })
diff --git a/backend/src/services/certificate-v3/certificate-renewal-fns.ts b/backend/src/services/certificate-v3/certificate-renewal-fns.ts
index 94bc614ff6..735c19d501 100644
--- a/backend/src/services/certificate-v3/certificate-renewal-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-renewal-fns.ts
@@ -22,6 +22,7 @@ import {
extractAlgorithmsFromCSR,
extractCertificateRequestFromCSR
} from "../certificate-common/certificate-csr-utils";
+import { toRequestCustomExtensions, TRequestCustomExtension } from "../certificate-common/certificate-extension-fns";
import { mapEnumsForValidation } from "../certificate-common/certificate-utils";
import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
import { parseExtendedKeyUsages, parseKeyUsages } from "./certificate-v3-fns";
@@ -67,6 +68,7 @@ type TRenewalAuditSubject = Pick<
| "pathLength"
| "notBefore"
| "notAfter"
+ | "customExtensions"
>;
const formatBasicConstraints = (isCA: boolean | null | undefined, pathLength: number | null | undefined) =>
@@ -81,6 +83,19 @@ type TRenewalAttributeDescriptor<K extends keyof TRenewalAttributes> = {
};
const text = (value: string | null | undefined) => value ?? "";
+
+const describeStoredCustomExtensions = (stored: unknown): TRequestCustomExtension[] => {
+ try {
+ return toRequestCustomExtensions(stored);
+ } catch {
+ return ((stored as { oid: string }[] | null) ?? []).map(({ oid }) => ({ oid, value: "" }));
+ }
+};
+
+const customExtensionList = (extensions: TRequestCustomExtension[] | null | undefined) =>
+ (extensions ?? [])
+ .map((extension) => `${extension.oid}=${extension.value ?? ""}${extension.critical ? " (critical)" : ""}`)
+ .join(",");
const list = (values: readonly string[] | null | undefined) => (values ?? []).join(",");
const RENEWAL_ATTRIBUTES: { [K in keyof TRenewalAttributes]-?: TRenewalAttributeDescriptor<K> } = {
@@ -169,6 +184,13 @@ const RENEWAL_ATTRIBUTES: { [K in keyof TRenewalAttributes]-?: TRenewalAttribute
apply: (value) => ({ basicConstraints: value }),
current: (original) => formatBasicConstraints(original.isCA, original.pathLength),
issued: (request) => formatBasicConstraints(request.basicConstraints?.isCA, request.basicConstraints?.pathLength)
+ },
+ customExtensions: {
+ label: "custom extensions",
+ csrEditable: true,
+ apply: (value) => ({ customExtensions: value }),
+ current: (original) => customExtensionList(describeStoredCustomExtensions(original.customExtensions)),
+ issued: (request) => customExtensionList(request.customExtensions)
}
};
@@ -222,8 +244,11 @@ export const assertCsrRenewalAttributes = (attributes?: TRenewalAttributes) => {
.map((key) => RENEWAL_ATTRIBUTES[key].label);
if (rejected.length > 0) {
+ const settable = RENEWAL_ATTRIBUTE_KEYS.filter((key) => RENEWAL_ATTRIBUTES[key].csrEditable).map(
+ (key) => RENEWAL_ATTRIBUTES[key].label
+ );
throw new BadRequestError({
- message: `The CSR is the source of truth for ${rejected.join(", ")}. Update the CSR instead, or renew without one. Only TTL and basic constraints can be set alongside a CSR.`
+ message: `The CSR is the source of truth for ${rejected.join(", ")}. Update the CSR instead, or renew without one. Only ${settable.join(", ")} can be set alongside a CSR.`
});
}
};
diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.ts
index 77f488ce76..24e5bbf5ab 100644
--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts
+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts
@@ -26,6 +26,11 @@ import { CaCapability, CaType } from "@app/services/certificate-authority/certif
import { assertCaInProfileProject } from "@app/services/certificate-authority/certificate-authority-fns";
import { caSupportsCapability } from "@app/services/certificate-authority/certificate-authority-maps";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
+import {
+ toRequestCustomExtensions,
+ TProfileCustomExtension,
+ TResolvedCustomExtension
+} from "@app/services/certificate-common/certificate-extension-fns";
import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
import {
@@ -365,7 +370,8 @@ export const certificateRenewalServiceFactory = ({
actorId,
actorAuthMethod,
actorOrgId,
- removeRootsFromChain
+ removeRootsFromChain,
+ resolvedCustomExtensions
}: {
keySource: CertificateRenewalKeySource;
csr?: string;
@@ -387,6 +393,7 @@ export const certificateRenewalServiceFactory = ({
actorAuthMethod: ActorAuthMethod;
actorOrgId: string;
removeRootsFromChain?: boolean;
+ resolvedCustomExtensions?: TResolvedCustomExtension[];
}): Promise<TCertificateIssuanceResponse> => {
const isCsrAuthoritative = keySource === CertificateRenewalKeySource.Csr;
const requestedAltNames = certificateRequest.subjectAlternativeNames ?? [];
@@ -440,6 +447,7 @@ export const certificateRenewalServiceFactory = ({
keyAlgorithm: effectiveKeyAlgorithm,
signatureAlgorithm: effectiveSignatureAlgorithm,
metadata: `Renewed from certificate ID: ${originalCert.id}`,
+ customExtensions: resolvedCustomExtensions,
status: CertificateRequestStatus.PENDING,
ttl,
enrollmentType: EnrollmentType.API,
@@ -459,6 +467,7 @@ export const certificateRenewalServiceFactory = ({
caId: ca.id,
csr: renewalCsr,
subjectOverride,
+ customExtensions: resolvedCustomExtensions,
commonName: certificateRequest.commonName,
altNames: isCsrAuthoritative ? undefined : requestedAltNames.map((san) => san.value).join(","),
basicConstraints: caBasicConstraints,
@@ -692,7 +701,8 @@ export const certificateRenewalServiceFactory = ({
attributes,
keySource,
originalSignatureAlgorithm,
- originalKeyAlgorithm
+ originalKeyAlgorithm,
+ profileCustomExtensions
}: {
originalCert: TCertificates;
policy: Parameters<TCertificatePolicyServiceFactory["validateRequestAgainstPolicy"]>[0];
@@ -701,9 +711,12 @@ export const certificateRenewalServiceFactory = ({
keySource: CertificateRenewalKeySource;
originalSignatureAlgorithm?: CertSignatureAlgorithm;
originalKeyAlgorithm?: CertKeyAlgorithm;
+ profileCustomExtensions?: TProfileCustomExtension[] | null;
}) => {
const originalTtl = certificateSpanToTtl(originalCert.notBefore, originalCert.notAfter);
+ const carriedCustomExtensions = toRequestCustomExtensions(originalCert.customExtensions);
+
const originalRequest: TCertificateRequest = {
commonName: originalCert.commonName || undefined,
organization: originalCert.subjectOrganization || undefined,
@@ -722,13 +735,19 @@ export const certificateRenewalServiceFactory = ({
validity: { ttl: originalTtl },
signatureAlgorithm: originalSignatureAlgorithm,
keyAlgorithm: originalKeyAlgorithm,
+ customExtensions: carriedCustomExtensions,
...(originalCert.isCA && {
basicConstraints: { isCA: true, pathLength: originalCert.pathLength ?? undefined }
})
};
- const mergedRequest =
- csrRenewalRequest ?? buildRenewalCertificateRequest({ original: originalRequest, attributes });
+ const mergedRequest = csrRenewalRequest
+ ? {
+ ...csrRenewalRequest,
+ customExtensions:
+ attributes?.customExtensions ?? csrRenewalRequest.customExtensions ?? carriedCustomExtensions
+ }
+ : buildRenewalCertificateRequest({ original: originalRequest, attributes });
if (
keySource === CertificateRenewalKeySource.Reuse &&
@@ -743,12 +762,14 @@ export const certificateRenewalServiceFactory = ({
const ttl = mergedRequest.validity?.ttl || originalTtl;
const certificateRequest = { ...mergedRequest, validity: { ttl } };
- const validationResult = certificatePolicyService.validateRequestAgainstPolicy(policy, certificateRequest);
+ const validationResult = certificatePolicyService.validateRequestAgainstPolicy(policy, certificateRequest, {
+ profileCustomExtensions
+ });
if (!validationResult.isValid) {
throw new RenewalBlockedError(`Certificate renewal failed. Errors: ${validationResult.errors.join(", ")}`);
}
- return { certificateRequest, ttl };
+ return { certificateRequest, ttl, resolvedCustomExtensions: validationResult.resolvedCustomExtensions };
};
const $assertKeySourceSupported = ({
@@ -802,7 +823,8 @@ export const certificateRenewalServiceFactory = ({
effectiveSignatureAlgorithm,
effectiveKeyAlgorithm,
actorCtx,
- removeRootsFromChain
+ removeRootsFromChain,
+ resolvedCustomExtensions
}: {
ca: TCertificateAuthorityWithAssociatedCa;
profile: TCertificateProfileWithConfigs;
@@ -819,6 +841,7 @@ export const certificateRenewalServiceFactory = ({
effectiveKeyAlgorithm: CertKeyAlgorithm;
actorCtx: TRenewalActor;
removeRootsFromChain?: boolean;
+ resolvedCustomExtensions?: TResolvedCustomExtension[];
}): Promise<TCertificateIssuanceResponse> => {
const pendingRequest = await certificateRequestService.createCertificateRequest({
internal: true,
@@ -836,6 +859,7 @@ export const certificateRenewalServiceFactory = ({
keyAlgorithm: effectiveKeyAlgorithm,
signatureAlgorithm: effectiveSignatureAlgorithm,
metadata: `Renewed from certificate ID: ${originalCert.id}`,
+ customExtensions: resolvedCustomExtensions,
status: CertificateRequestStatus.PENDING,
ttl,
enrollmentType: EnrollmentType.API,
@@ -852,9 +876,11 @@ export const certificateRenewalServiceFactory = ({
try {
caResult = await internalCaService.issueCertFromCa({
caId: ca.id,
+ customExtensions: resolvedCustomExtensions,
friendlyName: originalCert.friendlyName || certificateRequest.commonName || "Renewed Certificate",
commonName: certificateRequest.commonName || "",
altNames: renewalAltNames.map((san) => san.value).join(","),
+ altNameEntries: renewalAltNames,
...(renewalBasicConstraints && {
basicConstraints: { isCA: true, pathLength: policy?.basicConstraints?.maxPathLength },
pathLength: renewalBasicConstraints.pathLength
@@ -1008,14 +1034,15 @@ export const certificateRenewalServiceFactory = ({
tx
);
- const { certificateRequest, ttl } = $buildValidatedRenewalRequest({
+ const { certificateRequest, ttl, resolvedCustomExtensions } = $buildValidatedRenewalRequest({
originalCert,
policy,
csrRenewalRequest,
attributes,
keySource,
originalSignatureAlgorithm,
- originalKeyAlgorithm
+ originalKeyAlgorithm,
+ profileCustomExtensions: profile?.defaults?.customExtensions
});
changedAttributes = buildRenewalAuditChanges(originalCert, { ...certificateRequest, validity: { ttl } });
@@ -1069,6 +1096,7 @@ export const certificateRenewalServiceFactory = ({
return {
renewalMode: CertificateRenewalMode.KeyPreserving as const,
+ resolvedCustomExtensions,
keySource,
csr,
ca,
@@ -1099,6 +1127,7 @@ export const certificateRenewalServiceFactory = ({
return {
renewalMode: CertificateRenewalMode.InternalCa as const,
+ resolvedCustomExtensions,
ca,
profile,
policy,
@@ -1123,6 +1152,7 @@ export const certificateRenewalServiceFactory = ({
certificateRequest,
renewalAltNames,
renewalBasicConstraints,
+ resolvedCustomExtensions,
effectiveSignatureAlgorithm,
effectiveKeyAlgorithm,
ttl
@@ -1149,6 +1179,7 @@ export const certificateRenewalServiceFactory = ({
policy,
profile,
originalCert,
+ customExtensions: resolvedCustomExtensions,
effectiveAlgorithms: {
signatureAlgorithm: effectiveSignatureAlgorithm,
keyAlgorithm: effectiveKeyAlgorithm
@@ -1169,6 +1200,7 @@ export const certificateRenewalServiceFactory = ({
const certRequestResult = await certificateRequestService.createCertificateRequest({
internal: true,
+ customExtensions: resolvedCustomExtensions,
actor,
actorId,
actorAuthMethod,
@@ -1259,6 +1291,7 @@ export const certificateRenewalServiceFactory = ({
certificateRequest: renewalRequest,
renewalAltNames: structuredAltNames,
renewalBasicConstraints,
+ resolvedCustomExtensions,
effectiveSignatureAlgorithm,
effectiveKeyAlgorithm,
ttl
@@ -1268,6 +1301,7 @@ export const certificateRenewalServiceFactory = ({
const certificateRequest = await certificateRequestService.createCertificateRequest({
internal: true,
+ customExtensions: resolvedCustomExtensions,
actor,
actorId,
actorAuthMethod,
@@ -1324,6 +1358,7 @@ export const certificateRenewalServiceFactory = ({
originalCertificateId: certificateId,
certificateRequestId: certificateRequest.id,
basicConstraints: renewalBasicConstraints,
+ customExtensions: resolvedCustomExtensions,
...(csr && { csr }),
...(originalCert.applicationId && { applicationId: originalCert.applicationId })
});
diff --git a/backend/src/services/certificate-v3/certificate-self-signed-fns.ts b/backend/src/services/certificate-v3/certificate-self-signed-fns.ts
index a7b9c9f9d0..57caad9b42 100644
--- a/backend/src/services/certificate-v3/certificate-self-signed-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-self-signed-fns.ts
@@ -13,6 +13,7 @@ import {
CertKeyUsageType,
CertSubjectAlternativeNameType
} from "../certificate-common/certificate-constants";
+import { TResolvedCustomExtension } from "../certificate-common/certificate-extension-fns";
import { generateSelfSignedCertificate } from "../certificate-common/certificate-issuance-utils";
import {
convertExtendedKeyUsageArrayToLegacy,
@@ -25,11 +26,13 @@ const createSelfSignedCertificateRecord = async ({
certificateRequest,
profile,
originalCert,
+ customExtensions,
certificateDAL,
tx,
isRenewal = false
}: {
selfSignedResult: Awaited<ReturnType<typeof generateSelfSignedCertificate>>;
+ customExtensions?: TResolvedCustomExtension[];
certificateRequest: {
commonName?: string;
keyUsages?: CertKeyUsageType[];
@@ -80,7 +83,7 @@ const createSelfSignedCertificateRecord = async ({
}
: {};
- const parsedFields = extractCertificateFields(selfSignedResult.certificate);
+ const parsedFields = extractCertificateFields(selfSignedResult.certificate, customExtensions);
return certificateDAL.create(
{
@@ -159,7 +162,8 @@ export const processSelfSignedCertificate = async ({
projectDAL,
tx,
isRenewal = false,
- existingKeyPair
+ existingKeyPair,
+ customExtensions
}: {
certificateRequest: {
commonName?: string;
@@ -204,6 +208,7 @@ export const processSelfSignedCertificate = async ({
tx: Parameters<TCertificateDALFactory["create"]>[1];
isRenewal?: boolean;
existingKeyPair?: CryptoKeyPair;
+ customExtensions?: TResolvedCustomExtension[];
}) => {
const projectId = originalCert?.projectId || profile?.projectId;
if (!projectId) {
@@ -215,7 +220,8 @@ export const processSelfSignedCertificate = async ({
policy,
effectiveSignatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,
effectiveKeyAlgorithm: effectiveAlgorithms.keyAlgorithm,
- existingKeyPair
+ existingKeyPair,
+ customExtensions
});
const certificateData = await createSelfSignedCertificateRecord({
@@ -223,6 +229,7 @@ export const processSelfSignedCertificate = async ({
certificateRequest,
profile,
originalCert,
+ customExtensions,
certificateDAL,
tx,
isRenewal
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
index d9a9be4191..30fddff64a 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -1092,7 +1092,8 @@ describe("CertificateV3Service", () => {
CertExtendedKeyUsageType.OCSP_SIGNING,
CertExtendedKeyUsageType.SERVER_AUTH
]
- })
+ }),
+ expect.anything()
);
});
@@ -2499,7 +2500,8 @@ describe("CertificateV3Service", () => {
expect(mockCertificatePolicyService.validateRequestAgainstPolicy).toHaveBeenCalledWith(
mockPolicy,
- expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 3 } })
+ expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 3 } }),
+ expect.anything()
);
expect(mockInternalCaService.issueCertFromCa).not.toHaveBeenCalled();
});
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index c283f09a6e..4c0a2babc4 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -37,7 +37,10 @@ import { validateAwsPcaCaIssuanceInputs } from "@app/services/certificate-author
import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";
import { assertCaInProfileProject } from "@app/services/certificate-authority/certificate-authority-fns";
-import { caUsesExternalIssuanceQueue } from "@app/services/certificate-authority/certificate-authority-maps";
+import {
+ assertCaSupportsCustomExtensions,
+ caUsesExternalIssuanceQueue
+} from "@app/services/certificate-authority/certificate-authority-maps";
import { validateGoDaddyIssuanceInputs } from "@app/services/certificate-authority/godaddy/godaddy-certificate-authority-validators";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
@@ -55,13 +58,15 @@ import { TUserDALFactory } from "@app/services/user/user-dal";
import {
CertificateIssuanceOperation,
CertKeyUsageType,
- CertPolicyState
+ CertPolicyState,
+ CUSTOM_EXTENSIONS_WITH_CSR_ERROR_MESSAGE
} from "../certificate-common/certificate-constants";
import {
buildSubjectOverrideForCsr,
extractAlgorithmsFromCSR,
extractCertificateRequestFromCSR
} from "../certificate-common/certificate-csr-utils";
+import { assertAwsPcaCustomExtensionLimit } from "../certificate-common/certificate-extension-fns";
import {
calculateFinalRenewBeforeDays,
extractCertificateFromBuffer,
@@ -589,7 +594,8 @@ export const certificateV3ServiceFactory = ({
const validationResult = await certificatePolicyService.validateCertificateRequest(
profile.certificatePolicyId,
- mappedCertificateRequestForValidation
+ mappedCertificateRequestForValidation,
+ { profileCustomExtensions: profile.defaults?.customExtensions }
);
if (!validationResult.isValid) {
@@ -632,6 +638,9 @@ export const certificateV3ServiceFactory = ({
ttl: resolvedTtl,
enrollmentType: EnrollmentType.API,
status: CertificateRequestStatus.PENDING_APPROVAL,
+ customExtensions: validationResult.resolvedCustomExtensions
+ ? JSON.stringify(validationResult.resolvedCustomExtensions)
+ : null,
organization: certificateRequestWithDefaults.organization || null,
organizationalUnit: certificateRequestWithDefaults.organizationalUnit || null,
country: certificateRequestWithDefaults.country || null,
@@ -677,7 +686,8 @@ export const certificateV3ServiceFactory = ({
notAfter: certificateRequestWithDefaults.notAfter?.toISOString(),
signatureAlgorithm: certificateRequestWithDefaults.signatureAlgorithm,
keyAlgorithm: certificateRequestWithDefaults.keyAlgorithm,
- basicConstraints: certificateRequestWithDefaults.basicConstraints
+ basicConstraints: certificateRequestWithDefaults.basicConstraints,
+ customExtensions: validationResult.resolvedCustomExtensions
},
certificateRequestId: certRequest.id
};
@@ -754,7 +764,8 @@ export const certificateV3ServiceFactory = ({
const validationResult = await certificatePolicyService.validateCertificateRequest(
profile.certificatePolicyId,
- mappedCertificateRequest
+ mappedCertificateRequest,
+ { profileCustomExtensions: profile.defaults?.customExtensions }
);
if (!validationResult.isValid) {
@@ -763,6 +774,8 @@ export const certificateV3ServiceFactory = ({
});
}
+ const { resolvedCustomExtensions } = validationResult;
+
const effectiveSignatureAlgorithm = certificateRequestWithDefaults.signatureAlgorithm as
| CertSignatureAlgorithm
| undefined;
@@ -806,6 +819,7 @@ export const certificateV3ServiceFactory = ({
},
policy,
profile,
+ customExtensions: resolvedCustomExtensions,
effectiveAlgorithms,
certificateDAL,
certificateBodyDAL,
@@ -835,6 +849,7 @@ export const certificateV3ServiceFactory = ({
signatureAlgorithm: effectiveSignatureAlgorithm,
status: CertificateRequestStatus.ISSUED,
certificateId: processResult.certificateData.id,
+ customExtensions: resolvedCustomExtensions,
ttl: resolvedTtl,
enrollmentType: EnrollmentType.API,
organization: certificateRequest.organization,
@@ -1011,6 +1026,7 @@ export const certificateV3ServiceFactory = ({
friendlyName: certificateSubject.common_name || "Certificate",
commonName: certificateSubject.common_name || "",
altNames: subjectAlternativeNames,
+ altNameEntries: certificateRequestWithDefaults.altNames,
basicConstraints: caBasicConstraints,
pathLength: certificateRequestWithDefaults.basicConstraints?.pathLength,
ttl: resolveEffectiveTtl({
@@ -1032,6 +1048,7 @@ export const certificateV3ServiceFactory = ({
state: certificateRequestWithDefaults.state,
locality: certificateRequestWithDefaults.locality,
domainComponents: certificateRequestWithDefaults.domainComponents,
+ customExtensions: resolvedCustomExtensions,
tx
};
@@ -1096,6 +1113,7 @@ export const certificateV3ServiceFactory = ({
signatureAlgorithm: effectiveSignatureAlgorithm,
status: CertificateRequestStatus.ISSUED,
certificateId: certResult.certificateId,
+ customExtensions: resolvedCustomExtensions,
basicConstraints: certificateRequest.basicConstraints,
ttl: certificateRequest.validity.ttl,
enrollmentType: EnrollmentType.API,
@@ -1304,7 +1322,8 @@ export const certificateV3ServiceFactory = ({
const validationResult = await certificatePolicyService.validateCertificateRequest(
profile.certificatePolicyId,
- mappedCertificateRequest
+ mappedCertificateRequest,
+ { profileCustomExtensions: profile.defaults?.customExtensions }
);
if (!validationResult.isValid) {
@@ -1313,6 +1332,8 @@ export const certificateV3ServiceFactory = ({
});
}
+ const { resolvedCustomExtensions } = validationResult;
+
validateAlgorithmCompatibility(ca, policy);
const policyIsCAState: CertPolicyState =
@@ -1370,6 +1391,7 @@ export const certificateV3ServiceFactory = ({
enrollmentType,
status: CertificateRequestStatus.PENDING_APPROVAL,
basicConstraints: resolvedBasicConstraints ? JSON.stringify(resolvedBasicConstraints) : null,
+ customExtensions: resolvedCustomExtensions ? JSON.stringify(resolvedCustomExtensions) : null,
createdAt: certRequestCreatedAt
} as Parameters<typeof certificateRequestDAL.create>[0] & { createdAt: Date },
tx
@@ -1404,7 +1426,8 @@ export const certificateV3ServiceFactory = ({
notAfter: notAfter?.toISOString(),
signatureAlgorithm: extractedSignatureAlgorithm,
keyAlgorithm: extractedKeyAlgorithm,
- basicConstraints: resolvedBasicConstraints
+ basicConstraints: resolvedBasicConstraints,
+ customExtensions: resolvedCustomExtensions
},
certificateRequestId: certRequest.id
};
@@ -1509,6 +1532,7 @@ export const certificateV3ServiceFactory = ({
signatureAlgorithm: effectiveSignatureAlgorithm,
status: CertificateRequestStatus.PENDING,
basicConstraints,
+ customExtensions: resolvedCustomExtensions,
ttl: validity.ttl,
enrollmentType
});
@@ -1545,6 +1569,7 @@ export const certificateV3ServiceFactory = ({
: undefined,
signatureAlgorithm: effectiveSignatureAlgorithm,
keyAlgorithm: effectiveKeyAlgorithm,
+ customExtensions: resolvedCustomExtensions,
isFromProfile: true,
onPersisted: async (newCert, tx) => {
const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
@@ -1687,6 +1712,10 @@ export const certificateV3ServiceFactory = ({
let extractedSignatureAlgorithm: string | undefined;
if (certificateOrder.csr) {
+ if (certificateOrder.customExtensions?.length) {
+ throw new BadRequestError({ message: CUSTOM_EXTENSIONS_WITH_CSR_ERROR_MESSAGE });
+ }
+
const csrRequest = extractCertificateRequestFromCSR(certificateOrder.csr);
certificateRequest = applyProfileDefaults(csrRequest, profile.defaults);
const algorithms = extractAlgorithmsFromCSR(certificateOrder.csr);
@@ -1713,7 +1742,8 @@ export const certificateV3ServiceFactory = ({
organizationalUnit: certificateOrder.organizationalUnit,
country: certificateOrder.country,
state: certificateOrder.state,
- locality: certificateOrder.locality
+ locality: certificateOrder.locality,
+ customExtensions: certificateOrder.customExtensions
};
certificateRequest = applyProfileDefaults(rawRequest, profile.defaults);
}
@@ -1749,7 +1779,8 @@ export const certificateV3ServiceFactory = ({
const validationResult = await certificatePolicyService.validateCertificateRequest(
profile.certificatePolicyId,
- mappedCertificateRequest
+ mappedCertificateRequest,
+ { profileCustomExtensions: profile.defaults?.customExtensions }
);
if (!validationResult.isValid) {
@@ -1761,6 +1792,17 @@ export const certificateV3ServiceFactory = ({
// ACM pre-flight validation runs before the approval branch so bad inputs (e.g., a TTL that
// isn't ACM's fixed 198 days) are rejected at submit time rather than after the approver has
// already approved a request that's guaranteed to fail downstream.
+ const orderCustomExtensions = validationResult.resolvedCustomExtensions;
+
+ if (orderCustomExtensions?.length && preflightCa) {
+ const preflightCaType = (preflightCa.externalCa?.type ?? CaType.INTERNAL) as CaType;
+ assertCaSupportsCustomExtensions(preflightCaType, orderCustomExtensions.length);
+
+ if (preflightCaType === CaType.AWS_PCA) {
+ assertAwsPcaCustomExtensionLimit(orderCustomExtensions.length);
+ }
+ }
+
if (preflightCa?.externalCa?.type === CaType.AWS_ACM_PUBLIC_CA) {
validateAcmIssuanceInputs({
csr: certificateOrder.csr,
@@ -1837,6 +1879,7 @@ export const certificateV3ServiceFactory = ({
basicConstraints: certificateRequest.basicConstraints
? JSON.stringify(certificateRequest.basicConstraints)
: null,
+ customExtensions: orderCustomExtensions ? JSON.stringify(orderCustomExtensions) : null,
createdAt: certRequestCreatedAt
} as Parameters<typeof certificateRequestDAL.create>[0] & { createdAt: Date },
tx
@@ -2000,6 +2043,7 @@ export const certificateV3ServiceFactory = ({
notBefore: certificateOrder.notBefore,
notAfter: certificateOrder.notAfter,
status: CertificateRequestStatus.PENDING,
+ customExtensions: orderCustomExtensions,
ttl: certificateOrder.validity?.ttl,
enrollmentType: EnrollmentType.API,
organization: certificateRequest.organization,
@@ -2041,6 +2085,7 @@ export const certificateV3ServiceFactory = ({
state: certificateRequest.state,
locality: certificateRequest.locality,
basicConstraints: certificateRequest.basicConstraints,
+ customExtensions: orderCustomExtensions,
...(applicationId && { applicationId })
});
diff --git a/backend/src/services/certificate-v3/certificate-v3-types.ts b/backend/src/services/certificate-v3/certificate-v3-types.ts
index 72a79bb3fc..013eb58749 100644
--- a/backend/src/services/certificate-v3/certificate-v3-types.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-types.ts
@@ -8,6 +8,7 @@ import {
CertSignatureAlgorithm,
CertSubjectAlternativeNameType
} from "../certificate-common/certificate-constants";
+import { TRequestCustomExtension } from "../certificate-common/certificate-extension-fns";
import { EnrollmentType } from "../certificate-profile/certificate-profile-types";
export type TIssueCertificateFromProfileDTO = {
@@ -37,6 +38,7 @@ export type TIssueCertificateFromProfileDTO = {
isCA: boolean;
pathLength?: number;
};
+ customExtensions?: TRequestCustomExtension[];
};
metadata?: Array<{ key: string; value: string }>;
removeRootsFromChain?: boolean;
@@ -90,6 +92,7 @@ export type TOrderCertificateFromProfileDTO = {
country?: string;
state?: string;
locality?: string;
+ customExtensions?: TRequestCustomExtension[];
};
metadata?: Array<{ key: string; value: string }>;
removeRootsFromChain?: boolean;
@@ -158,6 +161,11 @@ export type TRenewalAttributes = {
isCA: boolean;
pathLength?: number;
};
+ customExtensions?: Array<{
+ oid: string;
+ value?: string;
+ critical?: boolean;
+ }>;
};
export type TRenewCertificateDTO = {
diff --git a/backend/src/services/certificate/certificate-fns.ts b/backend/src/services/certificate/certificate-fns.ts
index 1d285bec25..cb211811c0 100644
--- a/backend/src/services/certificate/certificate-fns.ts
+++ b/backend/src/services/certificate/certificate-fns.ts
@@ -5,6 +5,10 @@ import RE2 from "re2";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import {
+ parseIssuedCustomExtensions,
+ TResolvedCustomExtension
+} from "@app/services/certificate-common/certificate-extension-fns";
import { extractDnParts } from "../certificate-authority/certificate-authority-fns";
import { getProjectKmsCertificateKeyId } from "../project/project-fns";
@@ -374,9 +378,11 @@ export const extractCertificateAlgorithms = (decryptedCertificate: Buffer) => {
* Extract certificate fields including subject attributes, fingerprints, and basic constraints.
* Returns all parsed fields as separate properties.
*/
-export const extractCertificateFields = (decryptedCertificate: Buffer) => {
+export const extractCertificateFields = (decryptedCertificate: Buffer, resolved?: TResolvedCustomExtension[]) => {
const parsed = parseCertificateBody(decryptedCertificate);
+ const issuedCustomExtensions = parseIssuedCustomExtensions(decryptedCertificate, resolved);
+
return {
// Subject attributes
subjectOrganization: parsed.subject?.organization ?? null,
@@ -399,6 +405,7 @@ export const extractCertificateFields = (decryptedCertificate: Buffer) => {
// Callers spread these last so the issued usages win over the requested ones. Absent when the
// certificate carries no such extension, leaving the requested values in place.
+ customExtensions: issuedCustomExtensions.length ? JSON.stringify(issuedCustomExtensions) : null,
...(parsed.keyUsages && { keyUsages: parsed.keyUsages }),
...(parsed.extendedKeyUsages && { extendedKeyUsages: parsed.extendedKeyUsages })
};
diff --git a/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt b/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt
index 057ac7ede5..a91984959b 100644
--- a/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt
+++ b/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt
@@ -437,6 +437,7 @@ NTLM
OAuth
OCI
OCID
+OIDs
OIDC
OKMS
OTLP
diff --git a/docs/documentation/platform/pki/applications/certificate-renewal.mdx b/docs/documentation/platform/pki/applications/certificate-renewal.mdx
index d719fed975..5b5d657b17 100644
--- a/docs/documentation/platform/pki/applications/certificate-renewal.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-renewal.mdx
@@ -67,6 +67,7 @@ Reuse is available for certificates issued with an Infisical-managed key pair. A
| Key and signature algorithm | Locked to the current key algorithm while reusing the key pair, because the key already exists |
| Key usages and extended key usages | Constrained to what the certificate policy allows |
| Basic constraints | Whether the certificate is a CA, and its path length |
+| Custom extensions | Object identifiers and values, constrained to what the certificate policy allows |
<Warning>
Changing the common name can affect [certificate syncs](/documentation/platform/pki/applications/certificate-syncs/overview) that select certificates by name. Check any sync attached to the certificate before renaming it.
@@ -78,7 +79,7 @@ Renewing a certificate as it stands needs only permission to issue from its cert
### Renewing from a signing request
-When you supply a CSR, that request is the source of truth. The subject, the key, and the extensions all come from the CSR, so there are no separate fields for them. Only the validity and the basic constraints are set alongside it.
+When you supply a CSR, that request is the source of truth for the subject and the key, so there are no separate fields for them. The validity, the basic constraints and the custom extensions are set alongside it, and custom extensions keep their current values unless you change them.
Sending a property the CSR already carries is rejected rather than quietly ignored, so a renewal never silently discards something you asked for.
@@ -100,7 +101,10 @@ Sending a property the CSR already carries is rejected rather than quietly ignor
The subject attributes and alternative names are filled in from the current certificate. Change only what should differ.
</Step>
<Step title="Set validity and extensions">
- Adjust the validity, algorithms, key usages, and basic constraints, then select **Renew certificate**.
+ Adjust the validity, algorithms, key usages, and basic constraints.
+ </Step>
+ <Step title="Review the custom extensions">
+ The custom extensions are filled in from the current certificate. Change only what should differ, then select **Renew certificate**.
</Step>
</Steps>
diff --git a/docs/documentation/platform/pki/ca/adcs.mdx b/docs/documentation/platform/pki/ca/adcs.mdx
index c0a889c326..7819d83062 100644
--- a/docs/documentation/platform/pki/ca/adcs.mdx
+++ b/docs/documentation/platform/pki/ca/adcs.mdx
@@ -197,6 +197,16 @@ You can use AD CS in a few ways: as an **External CA** that issues certificates
<Accordion title="Could not reach certificate authority through the gateway">
When you create or update the CA, Infisical validates the certificate authority name against the CA over the Gateway. This error means the name does not match a CA on the host, or the Gateway cannot reach the AD CS server. Confirm the name with `certutil -getreg CA\CommonName` on the AD CS server and that the Gateway can connect to the host over DCOM (MS-WCCE).
</Accordion>
+ <Accordion title="The certificate was issued without a custom extension">
+ AD CS copies a custom extension out of a request only when its OID is listed in the CA's `EnableRequestExtensionList`, which lists none by default. Add the OID and restart the service:
+
+ ```powershell
+ certutil -setreg policy\EnableRequestExtensionList +1.3.6.1.4.1.311.25.2
+ net stop certsvc && net start certsvc
+ ```
+
+ Leaving an OID off that list is also how you stop requests from introducing it.
+ </Accordion>
<Accordion title="Signer rejected: missing Code Signing extended key usage">
The template used for a code signing signer does not produce a code-signing certificate. Point the signer at a template that carries the Code Signing extended key usage.
</Accordion>
diff --git a/docs/documentation/platform/pki/concepts/certificate-components.mdx b/docs/documentation/platform/pki/concepts/certificate-components.mdx
index 94f29f4dbe..4c87b63ec9 100644
--- a/docs/documentation/platform/pki/concepts/certificate-components.mdx
+++ b/docs/documentation/platform/pki/concepts/certificate-components.mdx
@@ -10,7 +10,7 @@ The following resources define how certificates are issued, shaped, and governed
- [Certificate Authority (CA)](/documentation/platform/pki/ca/overview): The trusted entity that issues X.509 certificates. This can be an [Internal CA](/documentation/platform/pki/ca/private-ca) or an [External CA](/documentation/platform/pki/ca/external-ca) in Infisical.
The former represents a fully managed CA hierarchy within Infisical, while the latter represents an external CA (e.g. [DigiCert](/documentation/platform/pki/ca/digicert), [Let's Encrypt](/documentation/platform/pki/ca/lets-encrypt), [Microsoft AD CS](/documentation/platform/pki/ca/adcs), etc.) that can be integrated with Infisical.
-- [Certificate Policy](/documentation/platform/pki/settings/policies): A policy structure specifying permitted attributes for requested certificates. This includes constraints around subject naming conventions, SAN fields, key usages, and extended key usages.
+- [Certificate Policy](/documentation/platform/pki/settings/policies): A policy structure specifying permitted attributes for requested certificates. This includes constraints around subject naming conventions, SAN fields, key usages, extended key usages, and custom X.509 extensions.
- [Certificate Profile](/documentation/platform/pki/settings/profiles): A reusable template that combines a CA with a certificate policy and sensible defaults. Profiles define what certificates look like — the issuing CA, validation rules, and default values for fields like TTL and key algorithm.
diff --git a/docs/documentation/platform/pki/reference/infisical-agent.mdx b/docs/documentation/platform/pki/reference/infisical-agent.mdx
index afe5bbb699..94c50f7d1f 100644
--- a/docs/documentation/platform/pki/reference/infisical-agent.mdx
+++ b/docs/documentation/platform/pki/reference/infisical-agent.mdx
@@ -163,7 +163,7 @@ Each entry in the `certificates` list accepts the following parameters:
| `attributes.key-algorithm` | Optional | The algorithm for the certificate key pair. One of: `RSA_2048`, `RSA_3072`, `RSA_4096`, `EC_prime256v1`, `EC_secp384r1`, `EC_secp521r1` |
| `attributes.signature-algorithm` | Optional | The algorithm used to sign the certificate. One of: `RSA-SHA256`, `RSA-SHA384`, `RSA-SHA512`, `ECDSA-SHA256`, `ECDSA-SHA384`, `ECDSA-SHA512` |
| `attributes.key-usages` | Optional | The list of key usage values. One or more of: `digital_signature`, `key_encipherment`, `non_repudiation`, `data_encipherment`, `key_agreement`, `key_cert_sign`, `crl_sign`, `encipher_only`, `decipher_only` |
-| `attributes.extended-key-usages` | Optional | The list of extended key usage values. One or more of: `server_auth`, `client_auth`, `code_signing`, `email_protection`, `timestamping`, `ocsp_signing` |
+| `attributes.extended-key-usages` | Optional | The list of extended key usage values. One or more of: `server_auth`, `client_auth`, `code_signing`, `email_protection`, `timestamping`, `ocsp_signing`, `smart_card_logon` |
| `csr-path` | Conditional | The path to a pre-generated certificate signing request (CSR) file (e.g. `/etc/ssl/csr.pem`). See [Using a pre-generated CSR](#one-time-issuance-from-a-pre-generated-csr) |
| `csr` | Conditional | The CSR content inline, as an alternative to `csr-path` |
| `file-output.private-key.path` | Required unless using `csr-path`/`csr` | The path to store the private key |
diff --git a/docs/documentation/platform/pki/settings/policies.mdx b/docs/documentation/platform/pki/settings/policies.mdx
index 8ae19166d1..09b23effbf 100644
--- a/docs/documentation/platform/pki/settings/policies.mdx
+++ b/docs/documentation/platform/pki/settings/policies.mdx
@@ -176,6 +176,7 @@ Define higher-level intended uses:
| Email Protection | S/MIME |
| OCSP Signing | OCSP responders |
| Time Stamping | Trusted timestamps |
+| Smart Card Logon | Active Directory logon, Windows Hello and other PKINIT authentication |
| Any Extended Key Usage | Any purpose |
If you configure Extended Key Usages, only the usages listed in **Required** or **Allowed** are permitted. Leave Extended Key Usages unconfigured to allow any extended key usage.
@@ -192,6 +193,23 @@ Control whether certificates can act as CAs:
**Maximum Path Length**: Limits how many intermediate CAs can exist below this certificate. `0` means the CA can only sign end-entity certificates.
+### Custom extensions
+
+Control which custom X.509 extensions certificates may carry, with one rule per object identifier (OID):
+
+| Rule | Meaning |
+|------|---------|
+| Allow | The extension is permitted, and its value must match the pattern |
+| Require | The extension must be present, and its value must match the pattern |
+| Deny | The extension is permitted, but not with a value matching the pattern |
+
+Each rule takes one value pattern, matched against the value you enter rather than its encoded form. Use `*` for any value, or a wildcard such as `S-1-5-21-1004336348-1177238915-682003330-*` to accept only identifiers from your own Active Directory domain. A rule can also pin criticality, except where an extension's specification already fixes it.
+
+If you configure Custom Extensions, only the OIDs you list are permitted, each subject to its rule. Any other OID in a request is rejected, including one carried in a signing request, so a value pattern is what limits what an enrolling client can assert. An empty configuration forbids all custom extensions, and leaving the section unconfigured allows any OID with any value.
+
+Infisical manages some extensions itself, so you can't set any OID under `2.5.29.` or authority information access here.
+
+
## Next steps
Once you've created a policy, combine it with a CA in a [Certificate Profile](/documentation/platform/pki/settings/profiles) that teams can consume.
diff --git a/docs/documentation/platform/pki/settings/profiles.mdx b/docs/documentation/platform/pki/settings/profiles.mdx
index 1a6f0c51a7..e240288e03 100644
--- a/docs/documentation/platform/pki/settings/profiles.mdx
+++ b/docs/documentation/platform/pki/settings/profiles.mdx
@@ -62,6 +62,23 @@ Defaults can be configured for:
If the certificate policy is updated after the profile is saved, existing defaults may no longer comply. Certificate requests will fail at validation until you update the profile defaults to match the new policy.
</Warning>
+### Custom extensions
+
+Set default values for custom X.509 extensions. The [certificate policy](/documentation/platform/pki/settings/policies) decides which object identifiers (OIDs) may be emitted, so a request can carry any extension the policy permits, whether or not the profile declares it. A request that supplies a signing request can carry them in the CSR, which is how an MDM enrolling over SCEP sets a per-device value.
+
+Set a value and Infisical uses it whenever the request doesn't supply one. Leave the value empty and the request supplies it, which suits a per-principal value such as an Active Directory security identifier. Either way, Infisical checks the value against the policy's rule for that OID.
+
+Enter the value as you want it read and Infisical encodes it. A few well-known extensions have a shape their specification fixes, so Infisical checks those as you type:
+
+| Extension | Value to enter |
+|-----------|----------------|
+| AD SID security extension | A security identifier, such as `S-1-5-21-1004336348-1177238915-682003330-1103` |
+| Certificate template name | The template name, such as `Machine` |
+| Certificate template information | The template OID, a colon, then the version, such as `1.3.6.1.4.1.311.21.8.1.2:100.3` |
+
+Any other OID takes whatever text you enter.
+
+
## How profiles are used
Profiles are consumed through [Applications](/documentation/platform/pki/applications/overview). The workflow separates responsibilities between product and application administrators:
diff --git a/frontend/src/hooks/api/ca/constants.tsx b/frontend/src/hooks/api/ca/constants.tsx
index b485648570..ca1fa7a641 100644
--- a/frontend/src/hooks/api/ca/constants.tsx
+++ b/frontend/src/hooks/api/ca/constants.tsx
@@ -30,7 +30,8 @@ export const CA_TYPE_CAPABILITIES_MAP: Record<CaType, CaCapability[]> = {
[CaType.INTERNAL]: [
CaCapability.ISSUE_CERTIFICATES,
CaCapability.REVOKE_CERTIFICATES,
- CaCapability.RENEW_CERTIFICATES
+ CaCapability.RENEW_CERTIFICATES,
+ CaCapability.CUSTOM_EXTENSIONS
],
[CaType.ACME]: [
CaCapability.ISSUE_CERTIFICATES,
@@ -41,12 +42,14 @@ export const CA_TYPE_CAPABILITIES_MAP: Record<CaType, CaCapability[]> = {
[CaType.ADCS]: [
CaCapability.ISSUE_CERTIFICATES,
CaCapability.REVOKE_CERTIFICATES,
- CaCapability.RENEW_CERTIFICATES
+ CaCapability.RENEW_CERTIFICATES,
+ CaCapability.CUSTOM_EXTENSIONS
],
[CaType.AWS_PCA]: [
CaCapability.ISSUE_CERTIFICATES,
CaCapability.REVOKE_CERTIFICATES,
- CaCapability.RENEW_CERTIFICATES
+ CaCapability.RENEW_CERTIFICATES,
+ CaCapability.CUSTOM_EXTENSIONS
],
[CaType.DIGICERT]: [
CaCapability.ISSUE_CERTIFICATES,
diff --git a/frontend/src/hooks/api/ca/enums.tsx b/frontend/src/hooks/api/ca/enums.tsx
index ad699f3846..3f069d106d 100644
--- a/frontend/src/hooks/api/ca/enums.tsx
+++ b/frontend/src/hooks/api/ca/enums.tsx
@@ -41,7 +41,8 @@ export enum CaRenewalStatus {
export enum CaCapability {
ISSUE_CERTIFICATES = "issue-certificates",
REVOKE_CERTIFICATES = "revoke-certificates",
- RENEW_CERTIFICATES = "renew-certificates"
+ RENEW_CERTIFICATES = "renew-certificates",
+ CUSTOM_EXTENSIONS = "custom-extensions"
}
export enum CaSigningConfigType {
diff --git a/frontend/src/hooks/api/certificatePolicies/index.tsx b/frontend/src/hooks/api/certificatePolicies/index.tsx
index f1d24c4c7a..a3ccfbd86f 100644
--- a/frontend/src/hooks/api/certificatePolicies/index.tsx
+++ b/frontend/src/hooks/api/certificatePolicies/index.tsx
@@ -12,6 +12,7 @@ export type {
TCertificatePolicy,
TCertificatePolicyRule,
TCreateCertificatePolicyDTO,
+ TCustomExtensionRule,
TDeleteCertificatePolicyDTO,
TGetCertificatePolicyByIdDTO,
TListCertificatePoliciesDTO,
diff --git a/frontend/src/hooks/api/certificatePolicies/types.ts b/frontend/src/hooks/api/certificatePolicies/types.ts
index 437149a8f5..bc80b6ec68 100644
--- a/frontend/src/hooks/api/certificatePolicies/types.ts
+++ b/frontend/src/hooks/api/certificatePolicies/types.ts
@@ -1,4 +1,8 @@
-import { CertPolicyState } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+import {
+ CertExtensionCriticality,
+ CertExtensionRuleKind,
+ CertPolicyState
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
/**
* A domain_component rule's values are comma-joined ordered sequences ("corp,example,com"), one per
@@ -18,6 +22,14 @@ export type TSubjectRule = {
denied?: string[];
};
+export type TCustomExtensionRule = {
+ oid: string;
+ label?: string;
+ critical?: CertExtensionCriticality;
+ rule: CertExtensionRuleKind;
+ value: string;
+};
+
export type TCertificatePolicyRule = {
subject?: TSubjectRule[];
sans?: Array<{
@@ -64,6 +76,7 @@ export type TCertificatePolicyRule = {
max?: string;
};
basicConstraints?: TBasicConstraints;
+ customExtensions?: TCustomExtensionRule[];
};
export type TBasicConstraintsIsCAPolicy = CertPolicyState;
@@ -87,6 +100,7 @@ export type TCertificatePolicy = {
createdAt: string;
updatedAt: string;
basicConstraints?: TBasicConstraints | null;
+ customExtensions?: TCustomExtensionRule[] | null;
};
export type TCreateCertificatePolicyDTO = {
@@ -100,6 +114,7 @@ export type TCreateCertificatePolicyDTO = {
algorithms?: TCertificatePolicyRule["algorithms"] | null;
validity?: TCertificatePolicyRule["validity"] | null;
basicConstraints?: TBasicConstraints | null;
+ customExtensions?: TCustomExtensionRule[] | null;
};
export type TUpdateCertificatePolicyDTO = {
@@ -113,6 +128,7 @@ export type TUpdateCertificatePolicyDTO = {
algorithms?: TCertificatePolicyRule["algorithms"] | null;
validity?: TCertificatePolicyRule["validity"] | null;
basicConstraints?: TBasicConstraints | null;
+ customExtensions?: TCustomExtensionRule[] | null;
};
export type TDeleteCertificatePolicyDTO = {
diff --git a/frontend/src/hooks/api/certificateProfiles/types.ts b/frontend/src/hooks/api/certificateProfiles/types.ts
index b0bb7275e7..7e9ff132f1 100644
--- a/frontend/src/hooks/api/certificateProfiles/types.ts
+++ b/frontend/src/hooks/api/certificateProfiles/types.ts
@@ -1,3 +1,10 @@
+export type TProfileCustomExtension = {
+ oid: string;
+ label?: string;
+ critical?: boolean;
+ value?: string;
+};
+
export enum EnrollmentType {
API = "api",
EST = "est",
@@ -31,6 +38,7 @@ export type TCertificateProfileDefaults = {
locality?: string;
subjectAltNames?: { type: string; value: string }[];
domainComponents?: string[];
+ customExtensions?: TProfileCustomExtension[];
};
export type TCertificateProfile = {
diff --git a/frontend/src/hooks/api/certificates/constants.tsx b/frontend/src/hooks/api/certificates/constants.tsx
index 674e5bc65e..91d46830b3 100644
--- a/frontend/src/hooks/api/certificates/constants.tsx
+++ b/frontend/src/hooks/api/certificates/constants.tsx
@@ -105,6 +105,7 @@ export const EXTENDED_KEY_USAGE_LABELS: Record<CertExtendedKeyUsage, string> = {
[CertExtendedKeyUsage.SERVER_AUTH]: "Server Auth",
[CertExtendedKeyUsage.EMAIL_PROTECTION]: "Email Protection",
[CertExtendedKeyUsage.OCSP_SIGNING]: "OCSP Signing",
+ [CertExtendedKeyUsage.SMART_CARD_LOGON]: "Smart Card Logon",
[CertExtendedKeyUsage.CODE_SIGNING]: "Code Signing",
[CertExtendedKeyUsage.TIMESTAMPING]: "Timestamping",
[CertExtendedKeyUsage.ANY_PURPOSE]: "Any Extended Key Usage"
diff --git a/frontend/src/hooks/api/certificates/enums.tsx b/frontend/src/hooks/api/certificates/enums.tsx
index 42a3ed9674..e3074128b5 100644
--- a/frontend/src/hooks/api/certificates/enums.tsx
+++ b/frontend/src/hooks/api/certificates/enums.tsx
@@ -49,6 +49,7 @@ export enum CertExtendedKeyUsage {
EMAIL_PROTECTION = "email_protection",
TIMESTAMPING = "time_stamping",
OCSP_SIGNING = "ocsp_signing",
+ SMART_CARD_LOGON = "smart_card_logon",
ANY_PURPOSE = "any_purpose"
}
diff --git a/frontend/src/hooks/api/certificates/types.ts b/frontend/src/hooks/api/certificates/types.ts
index 5b43b5e8b5..0d25c16671 100644
--- a/frontend/src/hooks/api/certificates/types.ts
+++ b/frontend/src/hooks/api/certificates/types.ts
@@ -27,7 +27,15 @@ export type TCertificateFingerprints = {
export type TCertificateSource = CertSource | null;
+export type TCertificateCustomExtension = {
+ oid: string;
+ critical: boolean;
+ value: string;
+ displayValue?: string;
+};
+
export type TCertificate = {
+ customExtensions?: TCertificateCustomExtension[] | null;
id: string;
caId: string;
certificateTemplateId?: string;
@@ -132,6 +140,11 @@ export type TRenewCertificateAttributes = {
isCA: boolean;
pathLength?: number;
};
+ customExtensions?: Array<{
+ oid: string;
+ value?: string;
+ critical?: boolean;
+ }>;
};
export type TRenewCertificateDTO = {
@@ -237,6 +250,7 @@ export type TCertificateRequestDetails = {
isCA: boolean;
pathLength?: number;
} | null;
+ customExtensions?: TCertificateCustomExtension[] | null;
createdAt: string;
updatedAt: string;
metadata?: Array<{ key: string; value: string }>;
diff --git a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx
index d7ddf747da..b63e89a76d 100644
--- a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx
@@ -1,4 +1,11 @@
-import { faGlobe, faKey, faLock, faShieldHalved, faTags } from "@fortawesome/free-solid-svg-icons";
+import {
+ faGlobe,
+ faKey,
+ faLock,
+ faPuzzlePiece,
+ faShieldHalved,
+ faTags
+} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Link } from "@tanstack/react-router";
import { ExternalLinkIcon } from "lucide-react";
@@ -15,6 +22,7 @@ import {
} from "@app/hooks/api/certificates/constants";
import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";
import { useGetCertificateRequest } from "@app/hooks/api/certificates/queries";
+import { CustomExtensionList } from "@app/pages/cert-manager/components/CustomExtensionList";
type Props = {
request: TApprovalRequest;
@@ -88,6 +96,7 @@ export const CertificateDetailsSection = ({ request }: Props) => {
const hasDomainComponents = Boolean(domainComponents && domainComponents.length > 0);
const basicConstraints = certRequestDetails?.basicConstraints || certRequest?.basicConstraints;
const metadata = certRequestDetails?.metadata || [];
+ const customExtensions = certRequestDetails?.customExtensions || [];
return (
<div className="flex flex-col gap-4">
@@ -263,6 +272,16 @@ export const CertificateDetailsSection = ({ request }: Props) => {
)}
</div>
+ {customExtensions.length > 0 && (
+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
+ <h3 className="mb-4 flex items-center gap-2 text-base font-medium text-mineshaft-100">
+ <FontAwesomeIcon icon={faPuzzlePiece} className="text-sm text-mineshaft-400" />
+ Custom Extensions
+ </h3>
+ <CustomExtensionList extensions={customExtensions} />
+ </div>
+ )}
+
{basicConstraints?.isCA && (
<div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
<h3 className="mb-4 flex items-center gap-2 text-base font-medium text-mineshaft-100">
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateDetailsSection.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateDetailsSection.tsx
index eeb3229fda..2178087964 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateDetailsSection.tsx
@@ -18,6 +18,7 @@ import {
certSignatureAlgorithmToNameMap
} from "@app/hooks/api/certificates";
import { camelCaseToSpaces, toTitleCase } from "@app/lib/fn/string";
+import { CustomExtensionList } from "@app/pages/cert-manager/components/CustomExtensionList";
type Props = {
certificateId: string;
@@ -220,6 +221,14 @@ export const CertificateDetailsSection = ({ certificateId }: Props) => {
)}
</DetailValue>
</Detail>
+ {Boolean(certificate.customExtensions?.length) && (
+ <Detail>
+ <DetailLabel>Custom Extensions</DetailLabel>
+ <DetailValue>
+ <CustomExtensionList extensions={certificate.customExtensions ?? []} />
+ </DetailValue>
+ </Detail>
+ )}
</DetailGroup>
</CardContent>
</Card>
diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/CertificatePolicyDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/CertificatePolicyDetailsByIDPage.tsx
index b7b24ebcf9..f92b206ba9 100644
--- a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/CertificatePolicyDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/CertificatePolicyDetailsByIDPage.tsx
@@ -24,6 +24,7 @@ import { ProjectType } from "@app/hooks/api/projects/types";
import { CreatePolicyModal } from "../PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal";
import {
PolicyAlgorithmsSection,
+ PolicyCustomExtensionsSection,
PolicyDetailsSection,
PolicyKeyUsagesSection,
PolicyNoRulesSection,
@@ -71,7 +72,8 @@ const Page = () => {
policy?.algorithms?.signature?.length ||
policy?.algorithms?.keyAlgorithm?.length ||
policy?.validity?.max ||
- policy?.basicConstraints?.isCA
+ policy?.basicConstraints?.isCA ||
+ policy?.customExtensions
);
const handleDeleteConfirm = async () => {
@@ -163,6 +165,7 @@ const Page = () => {
<PolicySansRulesSection policy={policy} />
<PolicyKeyUsagesSection policy={policy} />
<PolicyAlgorithmsSection policy={policy} />
+ <PolicyCustomExtensionsSection policy={policy} />
</>
) : (
<PolicyNoRulesSection />
diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsx
new file mode 100644
index 0000000000..25e3794fb3
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsx
@@ -0,0 +1,77 @@
+import {
+ Badge,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DetailGroup
+} from "@app/components/v3";
+import { TCertificatePolicy } from "@app/hooks/api/certificatePolicies";
+import {
+ CertExtensionCriticality,
+ CertExtensionRuleKind,
+ customExtensionLabelFor
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+
+import { RuleList } from "./RuleList";
+
+type Props = {
+ policy: TCertificatePolicy;
+};
+
+const RULE_KIND_LABEL: Record<CertExtensionRuleKind, string> = {
+ [CertExtensionRuleKind.ALLOW]: "Allowed",
+ [CertExtensionRuleKind.REQUIRE]: "Required",
+ [CertExtensionRuleKind.DENY]: "Denied"
+};
+
+const CRITICALITY_LABEL: Record<CertExtensionCriticality, string> = {
+ [CertExtensionCriticality.CRITICAL]: "Always critical",
+ [CertExtensionCriticality.NOT_CRITICAL]: "Never critical"
+};
+
+export const PolicyCustomExtensionsSection = ({ policy }: Props) => {
+ if (!policy.customExtensions) {
+ return null;
+ }
+
+ return (
+ <Card className="w-full">
+ <CardHeader className="border-b">
+ <CardTitle>Custom Extensions</CardTitle>
+ <CardDescription>
+ Constraints on custom X.509 extensions in issued certificates
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {policy.customExtensions.length === 0 ? (
+ <p className="text-sm text-muted">
+ No custom extensions are allowed. Certificates issued under this policy cannot include
+ any custom extensions.
+ </p>
+ ) : (
+ <DetailGroup>
+ {policy.customExtensions.map((rule) => (
+ <div
+ key={rule.oid}
+ className="flex flex-col gap-y-3 border-b border-mineshaft-700 pb-3 last:border-b-0 last:pb-0"
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-sm font-medium text-foreground">
+ {customExtensionLabelFor(rule.oid, rule.label)}
+ </span>
+ {rule.critical && (
+ <Badge variant="neutral">{CRITICALITY_LABEL[rule.critical]}</Badge>
+ )}
+ </div>
+ <p className="font-mono text-xs text-mineshaft-400">{rule.oid}</p>
+ <RuleList label={RULE_KIND_LABEL[rule.rule]} values={[rule.value]} />
+ </div>
+ ))}
+ </DetailGroup>
+ )}
+ </CardContent>
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/index.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/index.tsx
index ea181230d2..e131c3162b 100644
--- a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/index.tsx
+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/index.tsx
@@ -1,4 +1,5 @@
export { PolicyAlgorithmsSection } from "./PolicyAlgorithmsSection";
+export { PolicyCustomExtensionsSection } from "./PolicyCustomExtensionsSection";
export { PolicyDetailsSection } from "./PolicyDetailsSection";
export { PolicyKeyUsagesSection } from "./PolicyKeyUsagesSection";
export { PolicyNoRulesSection } from "./PolicyNoRulesSection";
diff --git a/frontend/src/pages/cert-manager/CertificateProfileDetailsByIDPage/components/ProfileDefaultsSection.tsx b/frontend/src/pages/cert-manager/CertificateProfileDetailsByIDPage/components/ProfileDefaultsSection.tsx
index a214e82f84..9d486fed0a 100644
--- a/frontend/src/pages/cert-manager/CertificateProfileDetailsByIDPage/components/ProfileDefaultsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateProfileDetailsByIDPage/components/ProfileDefaultsSection.tsx
@@ -16,6 +16,7 @@ import {
EmptyTitle
} from "@app/components/v3";
import { TCertificateProfileWithDetails } from "@app/hooks/api/certificateProfiles";
+import { CustomExtensionList } from "@app/pages/cert-manager/components/CustomExtensionList";
import {
CertExtendedKeyUsageType,
CertKeyUsageType,
@@ -246,6 +247,25 @@ export const ProfileDefaultsSection = ({ profile }: Props) => {
});
}
+ if (defaults.customExtensions?.length) {
+ sections.push({
+ id: "customExtensions",
+ node: (
+ <>
+ <p className="mb-3 text-sm font-medium text-foreground">Custom extensions</p>
+ <CustomExtensionList
+ extensions={defaults.customExtensions.map((extension) => ({
+ oid: extension.oid,
+ label: extension.label,
+ critical: extension.critical,
+ displayValue: extension.value ?? "Supplied by the request"
+ }))}
+ />
+ </>
+ )
+ });
+ }
+
return (
<Card className="w-full">
<CardHeader className="border-b">
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
index a1559dfad3..e4cb04cc85 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
@@ -29,6 +29,8 @@ import {
import { useOrganization, useProject } from "@app/context";
import { useGetCert } from "@app/hooks/api";
import { CaType } from "@app/hooks/api/ca";
+import { caSupportsCapability } from "@app/hooks/api/ca/constants";
+import { CaCapability } from "@app/hooks/api/ca/enums";
import { useGetCertificatePolicyById } from "@app/hooks/api/certificatePolicies";
import { EnrollmentType, useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
import { buildExtendedKeyUsageToggleSchema } from "@app/hooks/api/certificates/constants";
@@ -53,6 +55,7 @@ import {
} from "./certificateUtils";
import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";
import { KeyUsageSection } from "./KeyUsageSection";
+import { RequestCustomExtensionsField } from "./RequestCustomExtensionsField";
import { SubjectAltNamesField } from "./SubjectAltNamesField";
import { SubjectAttributesField } from "./SubjectAttributesField";
import { useCertificatePolicy } from "./useCertificatePolicy";
@@ -144,7 +147,8 @@ const buildFormSchema = (variant: CaFormVariant) => {
: z.string().min(1, "Signature algorithm is required"),
keyAlgorithm: z.string().min(1, "Key algorithm is required"),
keyUsages: keyUsagesField,
- extendedKeyUsages: extendedKeyUsagesField
+ extendedKeyUsages: extendedKeyUsagesField,
+ customExtensions: z.array(z.object({ oid: z.string(), value: z.string() })).optional()
});
return z
@@ -189,7 +193,7 @@ type Props = {
applicationName?: string;
};
-type IssuanceStepKey = "profile" | "csr" | "subject" | "options" | "metadata";
+type IssuanceStepKey = "profile" | "csr" | "subject" | "options" | "extensions" | "metadata";
const STEP_META: Record<IssuanceStepKey, WizardStep> = {
profile: {
@@ -228,6 +232,15 @@ const STEP_META: Record<IssuanceStepKey, WizardStep> = {
rightDescription:
"These values are validated against the profile's policy at issuance. Fields that the profile or an external CA fully controls are hidden or read-only."
},
+ extensions: {
+ name: "Custom Extensions",
+ shortDescription: "Extension values",
+ title: "Custom Extensions",
+ subtitle: "Set the custom extensions this certificate carries.",
+ rightLabel: "Custom Extensions",
+ rightDescription:
+ "Custom extensions carry object identifiers beyond the standard ones. The profile's policy constrains which are permitted and what values they may take."
+ },
metadata: {
name: "Metadata",
shortDescription: "Optional key-values",
@@ -251,6 +264,7 @@ const STEP_FIELDS: Record<IssuanceStepKey, string[]> = {
"extendedKeyUsages",
"basicConstraints"
],
+ extensions: ["customExtensions"],
metadata: ["metadata"]
};
@@ -331,6 +345,7 @@ export const CertificateIssuanceModal = ({
profileId: profileId || "",
subjectAttributes: [],
subjectAltNames: [],
+ customExtensions: [],
basicConstraints: {
isCA: false,
pathLength: undefined
@@ -357,9 +372,21 @@ export const CertificateIssuanceModal = ({
() => availableProfiles.find((p) => p.id === actualSelectedProfileId),
[availableProfiles, actualSelectedProfileId]
);
+ const requestableCustomExtensions = useMemo(
+ () => actualSelectedProfile?.defaults?.customExtensions ?? [],
+ [actualSelectedProfile]
+ );
+
+ useEffect(() => {
+ setValue("customExtensions", []);
+ }, [actualSelectedProfileId, setValue]);
const externalCaType = actualSelectedProfile?.certificateAuthority?.externalType;
const isAdcsProfile = isExternalTemplateCa(externalCaType);
+ const caSupportsCustomExtensions = caSupportsCapability(
+ (externalCaType as CaType | undefined) ?? CaType.INTERNAL,
+ CaCapability.CUSTOM_EXTENSIONS
+ );
isAdcsProfileRef.current = isAdcsProfile;
const isAwsPcaProfile = externalCaType === CaType.AWS_PCA;
@@ -391,6 +418,7 @@ export const CertificateIssuanceModal = ({
clearErrors,
isSubjectSectionShown: constraints.shouldShowSubjectSection,
isSanSectionShown: constraints.shouldShowSanSection,
+ customExtensionDeclarations: requestableCustomExtensions,
isSubjectEvaluated: requestMethod === RequestMethod.MANAGED,
isValidityEvaluated: !isAdcsProfile,
resetKey: actualSelectedProfileId
@@ -410,10 +438,19 @@ export const CertificateIssuanceModal = ({
keys.push("subject");
}
keys.push("options");
+ if (policyData?.customExtensions?.length !== 0 && caSupportsCustomExtensions) {
+ keys.push("extensions");
+ }
}
keys.push("metadata");
return keys;
- }, [requestMethod, constraints.shouldShowSubjectSection, constraints.shouldShowSanSection]);
+ }, [
+ requestMethod,
+ constraints.shouldShowSubjectSection,
+ constraints.shouldShowSanSection,
+ policyData?.customExtensions?.length,
+ caSupportsCustomExtensions
+ ]);
const { step, setStep, currentStepKey, goBack, goNext, onFormInvalid } = useWizardSteps({
stepKeys,
@@ -857,6 +894,16 @@ export const CertificateIssuanceModal = ({
</>
)}
+ {currentStepKey === "extensions" && (
+ <RequestCustomExtensionsField
+ control={control}
+ declarations={requestableCustomExtensions}
+ policyRules={policyData?.customExtensions}
+ errorsByOid={policy.customExtensions.errorsByOid}
+ revealPolicyErrors={policy.isRevealed("customExtensions")}
+ />
+ )}
+
{currentStepKey === "metadata" && (
<div>
<p className="text-sm font-medium text-foreground">Metadata</p>
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
index 79d17f2942..d761a715f9 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
@@ -18,8 +18,12 @@ import {
} from "@app/components/v3";
import { useOrganization, useProject } from "@app/context";
import { useRenewCertificate } from "@app/hooks/api";
+import { CaType } from "@app/hooks/api/ca";
+import { caSupportsCapability } from "@app/hooks/api/ca/constants";
+import { CaCapability } from "@app/hooks/api/ca/enums";
import { useGetCertificatePolicyById } from "@app/hooks/api/certificatePolicies";
import { IssuerType, useGetCertificateProfileById } from "@app/hooks/api/certificateProfiles";
+import { TProfileCustomExtension } from "@app/hooks/api/certificateProfiles/types";
import {
certKeyAlgorithms,
EXTENDED_KEY_USAGES_OPTIONS,
@@ -50,6 +54,7 @@ import {
import { isExternalTemplateCa, rowErrorsOf } from "./certificateUtils";
import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";
import { KeyUsageSection } from "./KeyUsageSection";
+import { RequestCustomExtensionsField } from "./RequestCustomExtensionsField";
import { SubjectAltNamesField } from "./SubjectAltNamesField";
import { SubjectAttributesField } from "./SubjectAttributesField";
import {
@@ -90,7 +95,8 @@ const formSchema = z
signatureAlgorithm: z.string().optional(),
keyAlgorithm: z.string().optional(),
keyUsages: z.record(z.boolean().optional()).default({}),
- extendedKeyUsages: z.record(z.boolean().optional()).default({})
+ extendedKeyUsages: z.record(z.boolean().optional()).default({}),
+ customExtensions: z.array(z.object({ oid: z.string().trim(), value: z.string() })).default([])
})
.superRefine((data, ctx) => {
if (data.keySource === CertificateRenewalKeySource.Csr && !data.csr) {
@@ -124,7 +130,9 @@ const externalTemplateFormSchema = formSchema.innerType().omit({ ttl: true }).ex
export type RenewalFormData = z.infer<typeof formSchema>;
-type RenewalStepKey = "setup" | "csr" | "subject" | "options";
+type RenewalStepKey = "setup" | "csr" | "subject" | "options" | "extensions";
+
+const NO_RENEWAL_DECLARATIONS: TProfileCustomExtension[] = [];
const STEP_META: Record<RenewalStepKey, WizardStep> = {
setup: {
@@ -139,7 +147,7 @@ const STEP_META: Record<RenewalStepKey, WizardStep> = {
shortDescription: "CSR and validity",
subtitle: "Provide the CSR and set the validity for this renewal.",
rightDescription:
- "The subject, key, and extensions are all taken from the CSR you provide, so there are no separate subject or key usage fields. Only validity is set here."
+ "The subject and key are taken from the CSR you provide, so there are no separate subject or key usage fields. Validity is set here, and custom extensions on the next step."
},
subject: {
name: "Subject",
@@ -155,6 +163,13 @@ const STEP_META: Record<RenewalStepKey, WizardStep> = {
subtitle: "Set validity, algorithms, and key usages within the profile's policy.",
rightDescription:
"Profile defaults are not applied on renewal. Every value here starts as a copy of the current certificate and is validated against the profile's policy at issuance."
+ },
+ extensions: {
+ name: "Custom Extensions",
+ shortDescription: "Extension values",
+ subtitle: "These are copied from the current certificate. Change only what should differ.",
+ rightDescription:
+ "Custom extensions start as a copy of the current certificate, and the profile's policy still constrains which object identifiers are permitted and what values they may take."
}
};
@@ -177,7 +192,8 @@ const STEP_FIELDS: Record<RenewalStepKey, string[]> = {
"keyUsages",
"extendedKeyUsages",
"basicConstraints"
- ]
+ ],
+ extensions: ["customExtensions"]
};
type Props = {
@@ -213,6 +229,10 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
const isExternalTemplateProfile = isExternalTemplateCa(
profile?.certificateAuthority?.externalType
);
+ const caSupportsCustomExtensions = caSupportsCapability(
+ (profile?.certificateAuthority?.externalType as CaType | undefined) ?? CaType.INTERNAL,
+ CaCapability.CUSTOM_EXTENSIONS
+ );
const isExternalTemplateProfileRef = useRef(false);
isExternalTemplateProfileRef.current = isExternalTemplateProfile;
@@ -256,7 +276,8 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
subjectAltNames: [],
basicConstraints: { isCA: false },
keyUsages: {},
- extendedKeyUsages: {}
+ extendedKeyUsages: {},
+ customExtensions: []
}
});
@@ -364,14 +385,27 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
if (isRefused) setValue("keySource", CertificateRenewalKeySource.New);
}, [keySource, isReuseAllowed, isCsrAllowed, setValue]);
+ const showCustomExtensions =
+ policyData?.customExtensions?.length !== 0 && caSupportsCustomExtensions;
+
const stepKeys = useMemo<RenewalStepKey[]>(() => {
- if (keySource === CertificateRenewalKeySource.Csr) return ["setup", "csr"];
+ if (keySource === CertificateRenewalKeySource.Csr) {
+ return showCustomExtensions ? ["setup", "csr", "extensions"] : ["setup", "csr"];
+ }
const keys: RenewalStepKey[] = ["setup"];
if (constraints.shouldShowSubjectSection || constraints.shouldShowSanSection)
keys.push("subject");
keys.push("options");
+ if (showCustomExtensions) {
+ keys.push("extensions");
+ }
return keys;
- }, [keySource, constraints.shouldShowSubjectSection, constraints.shouldShowSanSection]);
+ }, [
+ keySource,
+ constraints.shouldShowSubjectSection,
+ constraints.shouldShowSanSection,
+ showCustomExtensions
+ ]);
const policy = usePolicyGuidance({
policy: policyData,
@@ -645,6 +679,16 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
</div>
)}
+ {currentStepKey === "extensions" && (
+ <RequestCustomExtensionsField
+ control={control}
+ declarations={NO_RENEWAL_DECLARATIONS}
+ policyRules={policyData?.customExtensions}
+ errorsByOid={policy.customExtensions.errorsByOid}
+ revealPolicyErrors={policy.isRevealed("customExtensions")}
+ />
+ )}
+
{currentStepKey === "options" && (
<div className="space-y-4">
{!isExternalTemplateProfile && (
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/RequestCustomExtensionsField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/RequestCustomExtensionsField.tsx
new file mode 100644
index 0000000000..c634a3aae4
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/RequestCustomExtensionsField.tsx
@@ -0,0 +1,204 @@
+import { Control, Controller } from "react-hook-form";
+import { Plus, Trash2 } from "lucide-react";
+
+import {
+ Button,
+ Field,
+ FieldLabel,
+ IconButton,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { TCustomExtensionRule } from "@app/hooks/api/certificatePolicies";
+import { TProfileCustomExtension } from "@app/hooks/api/certificateProfiles/types";
+import { CustomExtensionOidSelect } from "@app/pages/cert-manager/components/CustomExtensionOidSelect";
+import {
+ CertExtensionRuleKind,
+ customExtensionLabelFor,
+ getCustomExtensionValuePlaceholder
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+
+import { PolicyRowMessage } from "./PolicyRowMessage";
+
+export type TRequestCustomExtension = {
+ oid: string;
+ value: string;
+};
+
+type Props = {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ control: Control<any>;
+ declarations: TProfileCustomExtension[];
+ policyRules?: TCustomExtensionRule[] | null;
+ errorsByOid?: Record<string, string>;
+ revealPolicyErrors?: boolean;
+};
+
+export const RequestCustomExtensionsField = ({
+ control,
+ declarations,
+ policyRules,
+ errorsByOid,
+ revealPolicyErrors
+}: Props) => {
+ const isUnrestricted = policyRules === undefined || policyRules === null;
+
+ const isPinned = (declaration: TProfileCustomExtension) =>
+ Boolean(declaration.value?.trim()) ||
+ policyRules?.find((rule) => rule.oid === declaration.oid)?.rule ===
+ CertExtensionRuleKind.REQUIRE;
+
+ const pinnedDeclarations = declarations.filter(isPinned);
+ const pinnedOids = pinnedDeclarations.map((declaration) => declaration.oid);
+ const declarationByOid = new Map(
+ declarations.map((declaration) => [declaration.oid, declaration] as const)
+ );
+
+ return (
+ <Controller
+ control={control}
+ name="customExtensions"
+ defaultValue={[]}
+ render={({ field: { onChange, value } }) => {
+ const rows: TRequestCustomExtension[] = value || [];
+ const addedRows = rows.filter((row) => !pinnedOids.includes(row.oid));
+ const usedOids = [...pinnedOids, ...addedRows.map((row) => row.oid)];
+
+ const offerableOids = (
+ policyRules?.map((rule) => rule.oid) ?? [...declarationByOid.keys()]
+ ).filter((oid) => !usedOids.includes(oid));
+
+ const labelOf = (oid: string) =>
+ customExtensionLabelFor(
+ oid,
+ declarationByOid.get(oid)?.label ?? policyRules?.find((rule) => rule.oid === oid)?.label
+ );
+
+ const upsert = (oid: string, next: string) => {
+ const index = rows.findIndex((row) => row.oid === oid);
+ if (index === -1) {
+ onChange([...rows, { oid, value: next }]);
+ return;
+ }
+ const updated = [...rows];
+ updated[index] = { oid, value: next };
+ onChange(updated);
+ };
+
+ const rowError = (oid: string) => (revealPolicyErrors ? errorsByOid?.[oid] : undefined);
+
+ return (
+ <Field>
+ <FieldLabel>Custom Extensions</FieldLabel>
+ <div className="space-y-3">
+ {pinnedDeclarations.map((declaration) => {
+ const placeholder = getCustomExtensionValuePlaceholder(declaration.oid);
+ const error = rowError(declaration.oid);
+ const current = rows.find((row) => row.oid === declaration.oid);
+
+ return (
+ <div key={`declared-${declaration.oid}`} className="flex items-start gap-2">
+ <Input
+ className="w-44 shrink-0 font-mono text-xs"
+ value={labelOf(declaration.oid)}
+ disabled
+ />
+ <div className="min-w-0 flex-1">
+ <Input
+ className="w-full"
+ value={current?.value ?? declaration.value ?? ""}
+ onChange={(e) => upsert(declaration.oid, e.target.value)}
+ placeholder={placeholder}
+ isError={Boolean(error)}
+ />
+ {error && <PolicyRowMessage isError lines={[error]} />}
+ </div>
+ <span className="w-9 shrink-0" />
+ </div>
+ );
+ })}
+
+ {rows.map((row, index) => {
+ if (pinnedOids.includes(row.oid)) return null;
+ const placeholder = getCustomExtensionValuePlaceholder(row.oid);
+ const error = rowError(row.oid);
+ const selectableOids = row.oid ? [row.oid, ...offerableOids] : offerableOids;
+
+ const replaceRow = (next: TRequestCustomExtension) => {
+ const updated = [...rows];
+ updated[index] = next;
+ onChange(updated);
+ };
+
+ const selectOid = (oid: string) =>
+ replaceRow({ oid, value: row.value || (declarationByOid.get(oid)?.value ?? "") });
+
+ return (
+ // eslint-disable-next-line react/no-array-index-key
+ <div key={`custom-extension-${index}`} className="flex items-start gap-2">
+ {isUnrestricted ? (
+ <CustomExtensionOidSelect
+ className="w-44 shrink-0"
+ value={row.oid}
+ onChange={selectOid}
+ extraOptions={offerableOids.map((oid) => ({
+ oid,
+ name: declarationByOid.get(oid)?.label
+ }))}
+ isError={Boolean(error)}
+ />
+ ) : (
+ <Select value={row.oid || undefined} onValueChange={selectOid}>
+ <SelectTrigger className="w-44 shrink-0" aria-label="Extension">
+ <SelectValue placeholder="Select an extension" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {selectableOids.map((oid) => (
+ <SelectItem key={oid} value={oid}>
+ {labelOf(oid)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ <div className="min-w-0 flex-1">
+ <Input
+ className="w-full"
+ value={row.value}
+ onChange={(e) => replaceRow({ ...row, value: e.target.value })}
+ placeholder={placeholder}
+ isError={Boolean(error)}
+ />
+ {error && <PolicyRowMessage isError lines={[error]} />}
+ </div>
+ <IconButton
+ type="button"
+ variant="ghost"
+ aria-label="Remove entry"
+ onClick={() => onChange(rows.filter((_, i) => i !== index))}
+ >
+ <Trash2 />
+ </IconButton>
+ </div>
+ );
+ })}
+
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onChange([...rows, { oid: "", value: "" }])}
+ >
+ <Plus className="size-4" /> Add extension
+ </Button>
+ </div>
+ </Field>
+ );
+ }}
+ />
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts
index 8d83f4bf49..54028fc786 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts
@@ -12,6 +12,7 @@ type ManagedFormData = Extract<FormData, { requestMethod: "managed" }>;
type ManagedIssuanceRequest = Omit<TUnifiedCertificateIssuanceDTO, "attributes"> & {
attributes: NonNullable<TUnifiedCertificateIssuanceDTO["attributes"]> & {
basicConstraints?: { isCA: boolean; pathLength?: number };
+ customExtensions?: { oid: string; value: string }[];
};
};
@@ -40,6 +41,7 @@ export const buildManagedRequest = ({
keyAlgorithm,
keyUsages,
extendedKeyUsages,
+ customExtensions,
metadata
} = formData;
@@ -113,5 +115,12 @@ export const buildManagedRequest = ({
}
}
+ const suppliedExtensions = (customExtensions ?? [])
+ .filter((entry) => entry.oid?.trim() && entry.value?.trim())
+ .map((entry) => ({ oid: entry.oid.trim(), value: entry.value.trim() }));
+ if (suppliedExtensions.length) {
+ request.attributes.customExtensions = suppliedExtensions;
+ }
+
return request;
};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts
index 8d000abee0..8789a41c1f 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificatePolicyGuidance.ts
@@ -4,9 +4,11 @@ import {
TSubjectRule
} from "@app/hooks/api/certificatePolicies";
import {
+ CertExtensionRuleKind,
CertSubjectAlternativeNameType,
CertSubjectAttributeType,
- formatSANType
+ formatSANType,
+ validateCustomExtensionValue
} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
import { SUBJECT_ATTRIBUTE_LABELS, SubjectAltName, SubjectAttribute } from "./certificateUtils";
@@ -647,6 +649,83 @@ export type SubjectPolicyGuidance = {
sans: PolicySectionGuidance;
};
+export type TCustomExtensionPolicyRule = {
+ oid: string;
+ rule: CertExtensionRuleKind;
+ value: string;
+};
+
+export type TCustomExtensionDeclaration = {
+ oid: string;
+ label?: string | null;
+ value?: string | null;
+};
+
+export type CustomExtensionsGuidance = {
+ errorsByOid: Record<string, string>;
+ isBlocking: boolean;
+};
+
+export const evaluateCustomExtensions = ({
+ declarations,
+ rows,
+ rules
+}: {
+ declarations: TCustomExtensionDeclaration[];
+ rows: { oid: string; value: string }[];
+ rules?: TCustomExtensionPolicyRule[] | null;
+}): CustomExtensionsGuidance => {
+ const errorsByOid: Record<string, string> = {};
+ const declarationByOid = new Map(
+ declarations.map((declaration) => [declaration.oid, declaration])
+ );
+ const valueByOid = new Map(
+ rows.filter((row) => row.oid.trim()).map((row) => [row.oid, row.value])
+ );
+ const isUnrestricted = rules === undefined || rules === null;
+
+ const oids = [...new Set([...declarationByOid.keys(), ...valueByOid.keys()])];
+
+ oids.forEach((oid) => {
+ const declaration = declarationByOid.get(oid);
+ const rule = rules?.find((entry) => entry.oid === oid);
+ const value = (valueByOid.get(oid) ?? declaration?.value ?? "").trim();
+
+ if (!isUnrestricted && !rule) {
+ errorsByOid[oid] = "This extension is not allowed by this policy";
+ return;
+ }
+
+ if (!value) {
+ if (rule?.rule === CertExtensionRuleKind.REQUIRE) {
+ errorsByOid[oid] = "A value is required by this policy";
+ }
+ return;
+ }
+
+ const malformed = validateCustomExtensionValue(oid, value);
+ if (malformed) {
+ errorsByOid[oid] = malformed;
+ return;
+ }
+
+ if (!rule) return;
+
+ const matches = matchesNormalizedPattern(value, rule.value);
+ if (rule.rule === CertExtensionRuleKind.DENY) {
+ if (matches) {
+ errorsByOid[oid] = "This value is denied by this policy";
+ }
+ return;
+ }
+ if (!matches) {
+ errorsByOid[oid] = `Value must match ${rule.value}`;
+ }
+ });
+
+ return { errorsByOid, isBlocking: Object.keys(errorsByOid).length > 0 };
+};
+
export const evaluateSubjectStep = ({
rules,
subjectAttributes,
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
index d72411735d..160b912fd5 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
@@ -125,7 +125,10 @@ export const buildRenewalFormDefaults = (
? (cert.keyAlgorithm as string)
: "",
keyUsages: toUsageFormKeys(cert.keyUsages, KEY_USAGE_BY_NAME),
- extendedKeyUsages: toUsageFormKeys(cert.extendedKeyUsages, EXTENDED_KEY_USAGE_BY_NAME)
+ extendedKeyUsages: toUsageFormKeys(cert.extendedKeyUsages, EXTENDED_KEY_USAGE_BY_NAME),
+ customExtensions: (cert.customExtensions ?? [])
+ .filter((extension) => extension.displayValue !== undefined)
+ .map((extension) => ({ oid: extension.oid, value: extension.displayValue as string }))
});
const buildBasicConstraints = (
@@ -155,6 +158,10 @@ export const buildRenewalRequestAttributes = ({
return { ttl: formData.ttl };
}
+ const customExtensions = (formData.customExtensions ?? [])
+ .filter((extension) => extension.oid.trim())
+ .map((extension) => ({ oid: extension.oid.trim(), value: extension.value }));
+
const basicConstraints = buildBasicConstraints(formData, constraints);
const attributes: TRenewCertificateAttributes = isExternalTemplateProfile
@@ -172,6 +179,8 @@ export const buildRenewalRequestAttributes = ({
...(basicConstraints && { basicConstraints })
};
+ attributes.customExtensions = customExtensions;
+
if (constraints.shouldShowSubjectSection) {
SUBJECT_ATTR_MAP.forEach(({ attrType, requestKey }) => {
attributes[requestKey] = getAttributeValue(formData.subjectAttributes, attrType) || null;
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/usePolicyGuidance.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/usePolicyGuidance.ts
index c804897995..e7ffc91e30 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/usePolicyGuidance.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/usePolicyGuidance.ts
@@ -5,15 +5,23 @@ import { TCertificatePolicy } from "@app/hooks/api/certificatePolicies";
import {
buildPolicyRules,
+ CustomExtensionsGuidance,
+ evaluateCustomExtensions,
evaluateSubjectStep,
getValidityHint,
PolicySectionGuidance,
+ TCustomExtensionDeclaration,
validateTtlAgainstPolicy
} from "./certificatePolicyGuidance";
import { SubjectAltName, SubjectAttribute } from "./certificateUtils";
/** The form fields this hook evaluates. Each wizard step declares the ones it owns. */
-export const POLICY_FIELDS = ["subjectAttributes", "subjectAltNames", "ttl"] as const;
+export const POLICY_FIELDS = [
+ "subjectAttributes",
+ "subjectAltNames",
+ "ttl",
+ "customExtensions"
+] as const;
export type PolicyField = (typeof POLICY_FIELDS)[number];
@@ -21,6 +29,8 @@ const SUBJECT_FIELDS: PolicyField[] = ["subjectAttributes", "subjectAltNames"];
const EMPTY_SUBJECT_ATTRIBUTES: SubjectAttribute[] = [];
const EMPTY_SUBJECT_ALT_NAMES: SubjectAltName[] = [];
+const EMPTY_CUSTOM_EXTENSION_DECLARATIONS: TCustomExtensionDeclaration[] = [];
+const EMPTY_CUSTOM_EXTENSION_ROWS: { oid: string; value: string }[] = [];
type UsePolicyGuidanceParams = {
policy?: TCertificatePolicy | null;
@@ -30,6 +40,8 @@ type UsePolicyGuidanceParams = {
clearErrors: UseFormClearErrors<any>;
isSubjectSectionShown: boolean;
isSanSectionShown: boolean;
+ /** The profile's default values, so a declared row is checked even when the request leaves it alone. */
+ customExtensionDeclarations?: TCustomExtensionDeclaration[];
/** False for request methods that take the subject from a CSR instead of these fields. */
isSubjectEvaluated?: boolean;
/** False when an external CA's template owns validity, so the TTL field is not shown. */
@@ -41,6 +53,7 @@ type UsePolicyGuidanceParams = {
export type PolicyGuidance = {
subject: PolicySectionGuidance;
sans: PolicySectionGuidance;
+ customExtensions: CustomExtensionsGuidance;
ttlHint?: string[];
ttlError?: string;
/** True once the requester has tried to leave the step that owns this field. */
@@ -63,6 +76,7 @@ export const usePolicyGuidance = ({
clearErrors,
isSubjectSectionShown,
isSanSectionShown,
+ customExtensionDeclarations = EMPTY_CUSTOM_EXTENSION_DECLARATIONS,
isSubjectEvaluated = true,
isValidityEvaluated = true,
resetKey
@@ -71,6 +85,8 @@ export const usePolicyGuidance = ({
watch("subjectAttributes") ?? EMPTY_SUBJECT_ATTRIBUTES;
const subjectAltNames: SubjectAltName[] = watch("subjectAltNames") ?? EMPTY_SUBJECT_ALT_NAMES;
const ttl: string = watch("ttl") ?? "";
+ const customExtensionRows: { oid: string; value: string }[] =
+ watch("customExtensions") ?? EMPTY_CUSTOM_EXTENSION_ROWS;
const rules = useMemo(
() => buildPolicyRules(isSubjectEvaluated ? policy : undefined),
@@ -89,6 +105,16 @@ export const usePolicyGuidance = ({
[rules, subjectAttributes, subjectAltNames, isSubjectSectionShown, isSanSectionShown]
);
+ const customExtensions = useMemo(
+ () =>
+ evaluateCustomExtensions({
+ declarations: customExtensionDeclarations,
+ rows: customExtensionRows,
+ rules: policy?.customExtensions
+ }),
+ [customExtensionDeclarations, customExtensionRows, policy?.customExtensions]
+ );
+
const maxTtl = policy?.validity?.max;
const ttlHint = useMemo(
() => (isValidityEvaluated ? getValidityHint(maxTtl) : undefined),
@@ -131,12 +157,18 @@ export const usePolicyGuidance = ({
clearErrors("ttl");
}, [ttl, clearErrors, hide]);
+ useEffect(() => {
+ hide(["customExtensions"]);
+ clearErrors("customExtensions");
+ }, [customExtensionRows, clearErrors, hide]);
+
// Read through a ref so the wizard's validateStep callback does not have to be rebuilt per render.
const blockedFields = useRef<ReadonlySet<PolicyField>>(new Set());
blockedFields.current = new Set<PolicyField>([
...(subject.isBlocking ? (["subjectAttributes"] as const) : []),
...(sans.isBlocking ? (["subjectAltNames"] as const) : []),
- ...(ttlError ? (["ttl"] as const) : [])
+ ...(ttlError ? (["ttl"] as const) : []),
+ ...(customExtensions.isBlocking ? (["customExtensions"] as const) : [])
]);
const findBlockedFields = useCallback(
@@ -150,5 +182,14 @@ export const usePolicyGuidance = ({
[revealedFields]
);
- return { subject, sans, ttlHint, ttlError, isRevealed, reveal, findBlockedFields };
+ return {
+ subject,
+ sans,
+ customExtensions,
+ ttlHint,
+ ttlError,
+ isRevealed,
+ reveal,
+ findBlockedFields
+ };
};
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 d390485e19..a3c5110055 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx
@@ -19,6 +19,7 @@ import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
+ IconButton,
Input,
InputGroup,
InputGroupAddon,
@@ -37,6 +38,13 @@ import {
StepperList,
StepperStep,
Switch,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableHeadLabel,
+ TableRow,
TextArea
} from "@app/components/v3";
import { useProject, useSubscription } from "@app/context";
@@ -58,6 +66,7 @@ import {
CertSubjectAlternativeNameType,
CertSubjectAttributeInclude,
CertSubjectAttributeType,
+ customExtensionLabelFor,
EXTENDED_KEY_USAGE_OPTIONS,
formatExtendedKeyUsage,
formatKeyUsage,
@@ -70,6 +79,10 @@ import {
SUBJECT_ATTRIBUTE_TYPE_OPTIONS
} from "./shared/certificate-constants";
import { CERTIFICATE_POLICY_PRESETS } from "./shared/policy-presets";
+import {
+ CUSTOM_EXTENSION_CRITICALITY_LABELS,
+ CustomExtensionRuleDialog
+} from "./CustomExtensionRuleDialog";
import { isValidDomainComponentSequence, PolicyFormData, policySchema } from "./shared";
export type FormData = PolicyFormData;
@@ -232,6 +245,15 @@ const STEPS = [
rightDescription:
"By default, certificates may carry any key usages and extended key usages. Enable a restriction to mark each usage as required, allowed, or denied. Requests that fall outside those rules are rejected at issuance."
},
+ {
+ name: "Custom Extensions",
+ shortDescription: "Arbitrary OIDs",
+ title: "Custom Extensions",
+ subtitle: "Control which custom X.509 extensions certificates may carry.",
+ rightLabel: "CUSTOM EXTENSIONS",
+ rightDescription:
+ "By default, certificates may carry any custom extension with any value. Enable a restriction to limit issuance to the OIDs you approve and the values they may take. Requests that fall outside those rules are rejected at issuance."
+ },
{
name: "Constraints",
shortDescription: "Validity and CA",
@@ -441,6 +463,8 @@ export const CreatePolicyModal = ({
const [restrictExtendedKeyUsages, setRestrictExtendedKeyUsages] = useState(false);
const [restrictValidity, setRestrictValidity] = useState(false);
const [configureBasicConstraints, setConfigureBasicConstraints] = useState(false);
+ const [restrictCustomExtensions, setRestrictCustomExtensions] = useState(false);
+ const [isCustomExtensionDialogOpen, setIsCustomExtensionDialogOpen] = useState(false);
const [errors, setErrors] = useState<Record<string, string>>({});
const clearError = (key: string) =>
@@ -559,6 +583,16 @@ export const CreatePolicyModal = ({
maxPathLength: policyData.basicConstraints?.maxPathLength ?? undefined
};
+ const customExtensions: FormData["customExtensions"] = (policyData.customExtensions ?? []).map(
+ (rule) => ({
+ oid: rule.oid,
+ label: rule.label ?? "",
+ critical: rule.critical ?? "",
+ rule: rule.rule,
+ value: rule.value
+ })
+ );
+
return {
preset: POLICY_PRESET_IDS.CUSTOM,
name: policyData.name || "",
@@ -570,7 +604,8 @@ export const CreatePolicyModal = ({
validity,
signatureAlgorithm,
keyAlgorithm,
- basicConstraints
+ basicConstraints,
+ customExtensions
};
};
@@ -618,6 +653,7 @@ export const CreatePolicyModal = ({
setRestrictExtendedKeyUsages(Boolean(source?.extendedKeyUsages));
setRestrictValidity(Boolean(source?.validity?.max));
setConfigureBasicConstraints(Boolean(source?.basicConstraints?.isCA));
+ setRestrictCustomExtensions(Boolean(source?.customExtensions));
setErrors({});
};
@@ -645,6 +681,7 @@ export const CreatePolicyModal = ({
const watchedSignatureAlgs = watch("signatureAlgorithm")?.allowedAlgorithms || [];
const watchedKeyAlgs = watch("keyAlgorithm")?.allowedKeyTypes || [];
const watchedIsCAPolicy = watch("basicConstraints.isCA") || CertPolicyState.DENIED;
+ const watchedCustomExtensions = watch("customExtensions") || [];
const markCustomPreset = () => {
if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {
@@ -652,6 +689,15 @@ export const CreatePolicyModal = ({
}
};
+ const removeCustomExtension = (index: number) => {
+ setValue(
+ "customExtensions",
+ watchedCustomExtensions.filter((_, i) => i !== index)
+ );
+ clearError("customExtensions");
+ markCustomPreset();
+ };
+
const handlePresetChange = async (presetId: PolicyPresetId) => {
setValue("preset", presetId);
@@ -675,6 +721,8 @@ export const CreatePolicyModal = ({
setRestrictSubject(Boolean(formData.attributes?.length));
setRestrictSans(Boolean(formData.subjectAlternativeNames?.length));
+ setValue("customExtensions", []);
+ setRestrictCustomExtensions(false);
setRestrictSignature(Boolean(formData.signatureAlgorithm?.allowedAlgorithms?.length));
setRestrictKeyAlg(Boolean(formData.keyAlgorithm?.allowedKeyTypes?.length));
setRestrictKeyUsages(
@@ -817,6 +865,20 @@ export const CreatePolicyModal = ({
}
: null;
+ const customExtensions = restrictCustomExtensions
+ ? (data.customExtensions ?? [])
+ .filter((extension) => extension.oid.trim())
+ .map((extension) => ({
+ oid: extension.oid.trim(),
+ ...(extension.label?.trim() && { label: extension.label.trim() }),
+ ...(extension.critical && {
+ critical: extension.critical
+ }),
+ rule: extension.rule,
+ value: extension.value.trim() || "*"
+ }))
+ : null;
+
return {
name: data.name,
description: data.description,
@@ -826,7 +888,8 @@ export const CreatePolicyModal = ({
extendedKeyUsages,
algorithms: algorithms.signature || algorithms.keyAlgorithm ? algorithms : null,
validity: validity.max ? validity : null,
- basicConstraints
+ basicConstraints,
+ customExtensions
};
};
@@ -988,6 +1051,15 @@ export const CreatePolicyModal = ({
}
}
+ if (step === 4 && restrictCustomExtensions) {
+ if (watchedCustomExtensions.some((extension) => !extension.oid?.trim())) {
+ stepErrors.customExtensions = "Every custom extension needs an OID.";
+ } else if (watchedCustomExtensions.some((extension) => !extension.value?.trim())) {
+ stepErrors.customExtensions =
+ "Every custom extension needs a value pattern (use * for any).";
+ }
+ }
+
if (step === 2) {
if (restrictSignature && !watchedSignatureAlgs.length) {
stepErrors.signature =
@@ -1525,6 +1597,98 @@ export const CreatePolicyModal = ({
)}
{step === 4 && (
+ <div className="space-y-8">
+ <SectionToggle
+ title="Restrict custom extensions"
+ description="Only allow the custom extension OIDs you configure here."
+ enabled={restrictCustomExtensions}
+ error={errors.customExtensions}
+ onChange={(enabled) => {
+ setRestrictCustomExtensions(enabled);
+ if (!enabled) setValue("customExtensions", []);
+ clearError("customExtensions");
+ markCustomPreset();
+ }}
+ >
+ {watchedCustomExtensions.length === 0 ? (
+ <p className="mb-4 text-sm text-muted">
+ No custom extensions configured. Certificates issued under this policy
+ cannot include any custom extensions. Turn this off to allow any custom
+ extension a profile declares.
+ </p>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>
+ <TableHeadLabel>Extension</TableHeadLabel>
+ </TableHead>
+ <TableHead>
+ <TableHeadLabel>Rule</TableHeadLabel>
+ </TableHead>
+ <TableHead>
+ <TableHeadLabel>Criticality</TableHeadLabel>
+ </TableHead>
+ <TableHead>
+ <TableHeadLabel>Value pattern</TableHeadLabel>
+ </TableHead>
+ <TableHead className="w-12" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {watchedCustomExtensions.map((extension, index) => (
+ <TableRow key={extension.oid}>
+ <TableCell>
+ <p>{customExtensionLabelFor(extension.oid, extension.label)}</p>
+ <p className="font-mono text-xs text-muted">{extension.oid}</p>
+ </TableCell>
+ <TableCell className="capitalize">{extension.rule}</TableCell>
+ <TableCell>
+ {CUSTOM_EXTENSION_CRITICALITY_LABELS[extension.critical || ""]}
+ </TableCell>
+ <TableCell className="font-mono text-xs">{extension.value}</TableCell>
+ <TableCell>
+ <IconButton
+ type="button"
+ variant="ghost"
+ aria-label={`Remove ${extension.oid}`}
+ onClick={() => removeCustomExtension(index)}
+ >
+ <Trash2 className="size-4" />
+ </IconButton>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+
+ <Button
+ type="button"
+ className="mt-3"
+ variant="outline"
+ size="sm"
+ onClick={() => setIsCustomExtensionDialogOpen(true)}
+ >
+ <Plus className="mr-1 size-4" />
+ Add extension
+ </Button>
+
+ <CustomExtensionRuleDialog
+ isOpen={isCustomExtensionDialogOpen}
+ onOpenChange={setIsCustomExtensionDialogOpen}
+ usedOids={watchedCustomExtensions.map((extension) => extension.oid)}
+ onConfirm={(rule) => {
+ setValue("customExtensions", [...watchedCustomExtensions, rule]);
+ clearError("customExtensions");
+ markCustomPreset();
+ }}
+ />
+ </SectionToggle>
+ </div>
+ )}
+
+ {step === 5 && (
<div className="space-y-8">
<SectionToggle
title="Set maximum validity"
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CustomExtensionRuleDialog.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CustomExtensionRuleDialog.tsx
new file mode 100644
index 0000000000..4cd6b042fd
--- /dev/null
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CustomExtensionRuleDialog.tsx
@@ -0,0 +1,237 @@
+import { useEffect, useState } from "react";
+
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { CustomExtensionOidSelect } from "@app/pages/cert-manager/components/CustomExtensionOidSelect";
+import {
+ CertExtensionCriticality,
+ CertExtensionRuleKind,
+ customExtensionLabelFor,
+ isPresetExtensionOid
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+
+export const ANY_CRITICALITY = "any";
+
+export type TCustomExtensionRuleDraft = {
+ oid: string;
+ label: string;
+ rule: CertExtensionRuleKind;
+ critical: CertExtensionCriticality | "";
+ value: string;
+};
+
+const RULE_OPTIONS = [
+ { value: CertExtensionRuleKind.ALLOW, label: "Allow" },
+ { value: CertExtensionRuleKind.REQUIRE, label: "Require" },
+ { value: CertExtensionRuleKind.DENY, label: "Deny" }
+] as const;
+
+export const CUSTOM_EXTENSION_CRITICALITY_LABELS: Record<string, string> = {
+ "": "Critical and non-critical allowed",
+ [CertExtensionCriticality.CRITICAL]: "Always critical",
+ [CertExtensionCriticality.NOT_CRITICAL]: "Never critical"
+};
+
+const CRITICALITY_OPTIONS = [
+ { value: ANY_CRITICALITY, label: CUSTOM_EXTENSION_CRITICALITY_LABELS[""] },
+ {
+ value: CertExtensionCriticality.CRITICAL,
+ label: CUSTOM_EXTENSION_CRITICALITY_LABELS[CertExtensionCriticality.CRITICAL]
+ },
+ {
+ value: CertExtensionCriticality.NOT_CRITICAL,
+ label: CUSTOM_EXTENSION_CRITICALITY_LABELS[CertExtensionCriticality.NOT_CRITICAL]
+ }
+] as const;
+
+const OID_PATTERN = /^[0-2](\.(0|[1-9][0-9]{0,14})){1,20}$/;
+
+const EMPTY_DRAFT: TCustomExtensionRuleDraft = {
+ oid: "",
+ label: "",
+ rule: CertExtensionRuleKind.ALLOW,
+ critical: "",
+ value: "*"
+};
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ usedOids: string[];
+ onConfirm: (rule: TCustomExtensionRuleDraft) => void;
+};
+
+export const CustomExtensionRuleDialog = ({ isOpen, onOpenChange, usedOids, onConfirm }: Props) => {
+ const [draft, setDraft] = useState<TCustomExtensionRuleDraft>(EMPTY_DRAFT);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (isOpen) {
+ setDraft(EMPTY_DRAFT);
+ setError(null);
+ }
+ }, [isOpen]);
+
+ const isPreset = isPresetExtensionOid(draft.oid);
+
+ const handleConfirm = () => {
+ const oid = draft.oid.trim();
+ if (!OID_PATTERN.test(oid)) {
+ setError("Enter a valid object identifier, for example 1.3.6.1.4.1.311.25.2");
+ return;
+ }
+ if (usedOids.includes(oid)) {
+ setError("This policy already has a rule for that object identifier.");
+ return;
+ }
+ onConfirm({
+ ...draft,
+ oid,
+ label: isPreset ? "" : draft.label.trim(),
+ critical: isPreset ? "" : draft.critical,
+ value: draft.value.trim() || "*"
+ });
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Add custom extension rule</DialogTitle>
+ <DialogDescription>
+ Constrain the values certificates may carry for one object identifier.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="space-y-4">
+ <Field>
+ <FieldLabel>Object identifier</FieldLabel>
+ <FieldContent>
+ <CustomExtensionOidSelect
+ placeholder="Select or enter an OID"
+ value={draft.oid}
+ onChange={(oid) => {
+ setDraft((current) => ({ ...current, oid }));
+ setError(null);
+ }}
+ isError={Boolean(error)}
+ />
+ {error && <FieldError>{error}</FieldError>}
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Name</FieldLabel>
+ <FieldContent>
+ <Input
+ placeholder="e.g. Device compliance marker"
+ value={isPreset ? customExtensionLabelFor(draft.oid) : draft.label}
+ disabled={isPreset}
+ onChange={(e) => setDraft((current) => ({ ...current, label: e.target.value }))}
+ />
+ <FieldDescription>
+ {isPreset
+ ? "Infisical names this extension."
+ : "Optional label, shown wherever this extension appears."}
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Rule</FieldLabel>
+ <FieldContent>
+ <Select
+ value={draft.rule}
+ onValueChange={(value) =>
+ setDraft((current) => ({ ...current, rule: value as CertExtensionRuleKind }))
+ }
+ >
+ <SelectTrigger className="w-full" aria-label="Rule">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {RULE_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Criticality</FieldLabel>
+ <FieldContent>
+ <Select
+ value={draft.critical || ANY_CRITICALITY}
+ disabled={isPreset}
+ onValueChange={(value) =>
+ setDraft((current) => ({
+ ...current,
+ critical: value === ANY_CRITICALITY ? "" : (value as CertExtensionCriticality)
+ }))
+ }
+ >
+ <SelectTrigger className="w-full" aria-label="Criticality">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {CRITICALITY_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {isPreset && (
+ <FieldDescription>Fixed by this extension&apos;s specification.</FieldDescription>
+ )}
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Value pattern</FieldLabel>
+ <FieldContent>
+ <Input
+ placeholder="*"
+ value={draft.value}
+ onChange={(e) => setDraft((current) => ({ ...current, value: e.target.value }))}
+ />
+ <FieldDescription>
+ Values this rule matches, with * as a wildcard. Use * alone for any value.
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="button" onClick={handleConfirm}>
+ Add extension
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts
index ab1b3623af..40418f31d6 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants.ts
@@ -24,6 +24,7 @@ export enum CertExtendedKeyUsageType {
CODE_SIGNING = "code_signing",
EMAIL_PROTECTION = "email_protection",
OCSP_SIGNING = "ocsp_signing",
+ SMART_CARD_LOGON = "smart_card_logon",
TIME_STAMPING = "time_stamping",
ANY_PURPOSE = "any_purpose"
}
@@ -111,6 +112,7 @@ export const EXTENDED_KEY_USAGE_LABELS: Record<CertExtendedKeyUsageType, string>
[CertExtendedKeyUsageType.CODE_SIGNING]: "Code Signing",
[CertExtendedKeyUsageType.EMAIL_PROTECTION]: "Email Protection",
[CertExtendedKeyUsageType.OCSP_SIGNING]: "OCSP Signing",
+ [CertExtendedKeyUsageType.SMART_CARD_LOGON]: "Smart Card Logon",
[CertExtendedKeyUsageType.TIME_STAMPING]: "Time Stamping",
[CertExtendedKeyUsageType.ANY_PURPOSE]: "Any Extended Key Usage"
};
@@ -328,3 +330,74 @@ export const ALGORITHM_FAMILIES = {
key: ["ML-DSA-44", "ML-DSA-65", "ML-DSA-87"] as const
}
} as const;
+
+export enum CertExtensionRuleKind {
+ ALLOW = "allow",
+ REQUIRE = "require",
+ DENY = "deny"
+}
+
+export enum CertExtensionCriticality {
+ CRITICAL = "critical",
+ NOT_CRITICAL = "not_critical"
+}
+
+const MAX_CUSTOM_EXTENSION_VALUE_BYTES = 2048;
+const OID_PATTERN_SOURCE = "[0-2](\\.(0|[1-9][0-9]{0,14})){1,20}";
+const SID_PATTERN = /^S-1-[0-9]{1,10}(-[0-9]{1,10}){1,14}$/;
+const TEMPLATE_INFORMATION_PATTERN = new RegExp(
+ `^(${OID_PATTERN_SOURCE}):(0|[1-9][0-9]{0,4})(\\.(0|[1-9][0-9]{0,4}))?$`
+);
+
+export const CUSTOM_EXTENSION_PRESETS: Record<
+ string,
+ { label: string; placeholder: string; validate: (value: string) => string | null }
+> = {
+ "1.3.6.1.4.1.311.25.2": {
+ label: "AD SID security extension",
+ placeholder: "S-1-5-21-...",
+ validate: (value) =>
+ SID_PATTERN.test(value)
+ ? null
+ : "Enter a security identifier, for example S-1-5-21-1004336348-1177238915-682003330-1103"
+ },
+ "1.3.6.1.4.1.311.20.2": {
+ label: "Certificate template name",
+ placeholder: "Machine",
+ validate: (value) => {
+ if (value.length > 64) return "Template name cannot exceed 64 characters";
+ return Array.from(value).some((character) => (character.codePointAt(0) ?? 0) > 0xffff)
+ ? "Template name cannot contain characters outside the basic multilingual plane"
+ : null;
+ }
+ },
+ "1.3.6.1.4.1.311.21.7": {
+ label: "Certificate template information",
+ placeholder: "1.3.6.1.4.1.311.21.8.1.2:100.3",
+ validate: (value) =>
+ TEMPLATE_INFORMATION_PATTERN.test(value)
+ ? null
+ : "Enter the template OID, a colon, then the version, for example 1.3.6.1.4.1.311.21.8.1.2:100.3"
+ }
+};
+
+const getCustomExtensionPreset = (oid: string) =>
+ Object.prototype.hasOwnProperty.call(CUSTOM_EXTENSION_PRESETS, oid)
+ ? CUSTOM_EXTENSION_PRESETS[oid]
+ : undefined;
+
+export const isPresetExtensionOid = (oid: string) => Boolean(getCustomExtensionPreset(oid));
+
+export const customExtensionLabelFor = (oid: string, label?: string | null) =>
+ label?.trim() || getCustomExtensionPreset(oid)?.label || oid;
+
+export const validateCustomExtensionValue = (oid: string, value: string): string | null => {
+ const preset = getCustomExtensionPreset(oid);
+ if (preset) return preset.validate(value);
+ return new TextEncoder().encode(value).length > MAX_CUSTOM_EXTENSION_VALUE_BYTES
+ ? `Value cannot exceed ${MAX_CUSTOM_EXTENSION_VALUE_BYTES} bytes`
+ : null;
+};
+
+export const getCustomExtensionValuePlaceholder = (oid: string) =>
+ getCustomExtensionPreset(oid)?.placeholder ?? "Value";
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.ts
index 6ab3ec4aa0..aa91340c7e 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
@@ -3,6 +3,8 @@ import { z } from "zod";
import {
CertDurationUnit,
CertExtendedKeyUsageType,
+ CertExtensionCriticality,
+ CertExtensionRuleKind,
CertKeyUsageType,
CertPolicyState,
CertSanInclude,
@@ -72,6 +74,14 @@ export const uiPresetSchema = z
])
.default(POLICY_PRESET_IDS.CUSTOM);
+export const uiCustomExtensionSchema = z.object({
+ oid: z.string().trim(),
+ label: z.string().trim().max(64).optional(),
+ critical: z.union([z.literal(""), z.nativeEnum(CertExtensionCriticality)]).optional(),
+ rule: z.nativeEnum(CertExtensionRuleKind),
+ value: z.string().trim()
+});
+
export const policySchema = z.object({
preset: uiPresetSchema,
name: z
@@ -95,7 +105,8 @@ export const policySchema = z.object({
extendedKeyUsages: uiExtendedKeyUsagesSchema.optional(),
validity: uiValiditySchema.optional(),
signatureAlgorithm: uiSignatureAlgorithmSchema.optional(),
- keyAlgorithm: uiKeyAlgorithmSchema.optional()
+ keyAlgorithm: uiKeyAlgorithmSchema.optional(),
+ customExtensions: z.array(uiCustomExtensionSchema).optional()
});
export type PolicyFormData = z.infer<typeof policySchema>;
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
index 651fc76d27..80b068d48e 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
@@ -38,7 +38,8 @@ import {
ProjectPermissionSub
} from "@app/context/ProjectPermissionContext/types";
import { usePopUp } from "@app/hooks";
-import { CaType } from "@app/hooks/api/ca/enums";
+import { caSupportsCapability } from "@app/hooks/api/ca/constants";
+import { CaCapability, CaType } from "@app/hooks/api/ca/enums";
import {
useGetAdcsTemplates,
useGetAzureAdcsTemplates,
@@ -59,6 +60,7 @@ import {
useCreateCertificateProfile,
useUpdateCertificateProfile
} from "@app/hooks/api/certificateProfiles";
+import { TProfileCustomExtension } from "@app/hooks/api/certificateProfiles/types";
import {
certKeyAlgorithms,
EXTENDED_KEY_USAGES_OPTIONS,
@@ -98,6 +100,16 @@ const certificateDefaultsSchema = z
})
)
.optional(),
+ customExtensions: z
+ .array(
+ z.object({
+ oid: z.string(),
+ label: z.string().optional(),
+ critical: z.boolean().optional(),
+ value: z.string().optional()
+ })
+ )
+ .optional(),
signatureAlgorithm: z.string().nullable().optional(),
keyAlgorithm: z.string().nullable().optional(),
keyUsages: z.record(z.boolean().optional()).optional(),
@@ -337,6 +349,10 @@ const convertDefaultsToForm = (
keyAlgorithm: defaults.keyAlgorithm ?? null,
keyUsages: Object.keys(keyUsagesRecord).length > 0 ? keyUsagesRecord : undefined,
extendedKeyUsages: Object.keys(extKeyUsagesRecord).length > 0 ? extKeyUsagesRecord : undefined,
+ customExtensions:
+ defaults.customExtensions && defaults.customExtensions.length > 0
+ ? defaults.customExtensions
+ : undefined,
basicConstraints: defaults.basicConstraints ?? null
};
};
@@ -419,6 +435,18 @@ const convertFormToDefaults = (
if (sans.length > 0) result.subjectAltNames = sans;
}
+ if (formDefaults.customExtensions) {
+ const declared = formDefaults.customExtensions
+ .filter((extension: TProfileCustomExtension) => extension.oid?.trim())
+ .map((extension: TProfileCustomExtension) => ({
+ oid: extension.oid.trim(),
+ ...(extension.label?.trim() && { label: extension.label.trim() }),
+ ...(extension.critical !== undefined && { critical: extension.critical }),
+ ...(extension.value?.trim() && { value: extension.value.trim() })
+ }));
+ if (declared.length > 0) result.customExtensions = declared;
+ }
+
if (formDefaults.basicConstraints) {
result.basicConstraints = {
isCA: formDefaults.basicConstraints.isCA,
@@ -567,6 +595,7 @@ export const CreateProfileModal = ({
allowedSubjectAttributeTypes: [],
shouldShowSubjectSection: false,
allowedSanTypes: [],
+ allowedCustomExtensions: null,
shouldShowSanSection: false,
policyAllowsCA: false,
maxPathLength: undefined
@@ -654,6 +683,9 @@ export const CreateProfileModal = ({
shouldShowSubjectSection,
allowedSanTypes,
shouldShowSanSection,
+ allowedCustomExtensions: selectedPolicyData.customExtensions
+ ? selectedPolicyData.customExtensions.filter((rule) => rule.oid)
+ : null,
policyAllowsCA,
maxPathLength: selectedPolicyData.basicConstraints?.maxPathLength as number | undefined
};
@@ -667,6 +699,9 @@ export const CreateProfileModal = ({
const isAdcsCa = selectedCa?.type === CaType.ADCS;
// ACM Public CA issues certificates with a fixed 198-day validity, so pin the TTL default.
const isAwsAcmPublicCa = selectedCa?.type === CaType.AWS_ACM_PUBLIC_CA;
+ const caSupportsCustomExtensions = selectedCa
+ ? caSupportsCapability(selectedCa.type, CaCapability.CUSTOM_EXTENSIONS)
+ : false;
const { data: azureAdcsTemplatesData } = useGetAzureAdcsTemplates({
caId: watchedCertificateAuthorityId || "",
@@ -748,6 +783,11 @@ export const CreateProfileModal = ({
delete adcsSafeDefaults.basicConstraints;
effectiveDefaults = adcsSafeDefaults;
}
+ if (effectiveDefaults && !caSupportsCustomExtensions) {
+ const withoutCustomExtensions = { ...effectiveDefaults };
+ delete withoutCustomExtensions.customExtensions;
+ effectiveDefaults = withoutCustomExtensions;
+ }
if (effectiveDefaults && !(isAzureAdcsCa || isAdcsCa)) {
const nextDefaults = { ...effectiveDefaults };
if (policyConstraints.requiredKeyUsages.length) {
@@ -1142,6 +1182,7 @@ export const CreateProfileModal = ({
policyConstraints={policyConstraints}
isAwsAcmPublicCa={isAwsAcmPublicCa}
isExternalAdcsCa={isAzureAdcsCa || isAdcsCa}
+ caSupportsCustomExtensions={caSupportsCustomExtensions}
caKeyAlgorithm={caKeyAlgorithm}
/>
)}
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/CustomExtensionDefaults.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/CustomExtensionDefaults.tsx
new file mode 100644
index 0000000000..4155efc2ad
--- /dev/null
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/CustomExtensionDefaults.tsx
@@ -0,0 +1,179 @@
+import { Plus, Trash2 } from "lucide-react";
+
+import {
+ Button,
+ IconButton,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { TProfileCustomExtension } from "@app/hooks/api/certificateProfiles/types";
+import { CustomExtensionOidSelect } from "@app/pages/cert-manager/components/CustomExtensionOidSelect";
+
+import {
+ CertExtensionCriticality,
+ customExtensionLabelFor,
+ getCustomExtensionValuePlaceholder,
+ isPresetExtensionOid
+} from "../../CertificatePoliciesTab/shared/certificate-constants";
+import { SectionHeading } from "./SectionHeading";
+
+type Props = {
+ allowedCustomExtensions: Array<{
+ oid: string;
+ label?: string;
+ critical?: CertExtensionCriticality;
+ }> | null;
+ extensions: TProfileCustomExtension[];
+ onChange: (next: TProfileCustomExtension[]) => void;
+};
+
+export const CustomExtensionDefaults = ({
+ allowedCustomExtensions,
+ extensions,
+ onChange
+}: Props) => {
+ const isDisabled = allowedCustomExtensions !== null && allowedCustomExtensions.length === 0;
+ const selectableOids = allowedCustomExtensions?.map((rule) => rule.oid) ?? null;
+
+ const replace = (index: number, next: TProfileCustomExtension) => {
+ const updated = [...extensions];
+ updated[index] = next;
+ onChange(updated);
+ };
+
+ const update = (index: number, patch: Partial<TProfileCustomExtension>) => {
+ const next = [...extensions];
+ next[index] = { ...next[index], ...patch };
+ onChange(next);
+ };
+
+ const criticalityPinnedFor = (oid: string) =>
+ allowedCustomExtensions?.find((rule) => rule.oid === oid)?.critical;
+
+ const declarationFor = (oid: string): TProfileCustomExtension => {
+ const pinned = criticalityPinnedFor(oid);
+ return { oid, critical: pinned ? pinned === CertExtensionCriticality.CRITICAL : false };
+ };
+
+ return (
+ <div>
+ <SectionHeading
+ title="Custom Extensions"
+ description="Declare the custom X.509 extensions certificates from this profile may carry. Leave a value empty to have the request supply it."
+ />
+ <div className="mt-4 space-y-3">
+ {isDisabled && (
+ <p className="text-xs text-muted">
+ The selected policy does not allow any custom extensions.
+ </p>
+ )}
+
+ {!isDisabled && (
+ <>
+ {extensions.length === 0 && (
+ <p className="text-xs text-muted">No custom extensions declared.</p>
+ )}
+
+ {extensions.map((extension, index) => {
+ const isPreset = isPresetExtensionOid(extension.oid);
+ const placeholder = getCustomExtensionValuePlaceholder(extension.oid);
+ const criticalityPinned = criticalityPinnedFor(extension.oid);
+
+ return (
+ <div
+ // eslint-disable-next-line react/no-array-index-key
+ key={`profile-extension-${index}`}
+ className="flex items-start gap-2"
+ >
+ {selectableOids ? (
+ <Select
+ value={extension.oid || undefined}
+ onValueChange={(oid) => replace(index, declarationFor(oid))}
+ >
+ <SelectTrigger className="min-w-0 flex-[2]">
+ <SelectValue placeholder="Select an extension" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {selectableOids.map((oid) => (
+ <SelectItem key={oid} value={oid}>
+ {customExtensionLabelFor(
+ oid,
+ allowedCustomExtensions?.find((rule) => rule.oid === oid)?.label
+ )}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <CustomExtensionOidSelect
+ className="min-w-0 flex-[2]"
+ placeholder="Select OID"
+ value={extension.oid}
+ onChange={(oid) => replace(index, declarationFor(oid))}
+ />
+ )}
+
+ <Select
+ value={
+ (criticalityPinned ??
+ (extension.critical
+ ? CertExtensionCriticality.CRITICAL
+ : CertExtensionCriticality.NOT_CRITICAL)) as CertExtensionCriticality
+ }
+ disabled={isPreset || Boolean(criticalityPinned)}
+ onValueChange={(value) =>
+ update(index, { critical: value === CertExtensionCriticality.CRITICAL })
+ }
+ >
+ <SelectTrigger className="w-28 shrink-0" aria-label="Criticality">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={CertExtensionCriticality.NOT_CRITICAL}>
+ Not critical
+ </SelectItem>
+ <SelectItem value={CertExtensionCriticality.CRITICAL}>Critical</SelectItem>
+ </SelectContent>
+ </Select>
+
+ <Input
+ className="min-w-0 flex-1"
+ placeholder={placeholder}
+ value={extension.value ?? ""}
+ onChange={(e) => update(index, { value: e.target.value })}
+ />
+
+ <IconButton
+ type="button"
+ variant="ghost"
+ aria-label="Remove custom extension"
+ onClick={() => onChange(extensions.filter((_, i) => i !== index))}
+ >
+ <Trash2 />
+ </IconButton>
+ </div>
+ );
+ })}
+
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ const taken = new Set(extensions.map((extension) => extension.oid));
+ const nextOid = selectableOids?.find((oid) => !taken.has(oid)) ?? "";
+ onChange([...extensions, declarationFor(nextOid)]);
+ }}
+ >
+ <Plus className="size-4" /> Declare extension
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/ProfileDefaultsStep.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/ProfileDefaultsStep.tsx
index 9ef318adc2..b72c20798b 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/ProfileDefaultsStep.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/ProfileDefaultsStep.tsx
@@ -31,6 +31,7 @@ import {
KEY_USAGES_OPTIONS
} from "@app/hooks/api/certificates/constants";
import {
+ CertExtensionCriticality,
CertSubjectAlternativeNameType,
CertSubjectAttributeType,
formatSANType,
@@ -38,6 +39,8 @@ import {
} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
import type { FormData } from "../CreateProfileModal";
+import { CustomExtensionDefaults } from "./CustomExtensionDefaults";
+import { SectionHeading } from "./SectionHeading";
export type PolicyConstraints = {
allowedKeyUsages: string[];
@@ -50,6 +53,11 @@ export type PolicyConstraints = {
shouldShowSubjectSection: boolean;
allowedSanTypes: CertSubjectAlternativeNameType[];
shouldShowSanSection: boolean;
+ allowedCustomExtensions: Array<{
+ oid: string;
+ label?: string;
+ critical?: CertExtensionCriticality;
+ }> | null;
policyAllowsCA: boolean;
maxPathLength: number | undefined;
};
@@ -80,13 +88,6 @@ const subjectAttrPlaceholder = (type: CertSubjectAttributeType): string => {
}
};
-const SectionHeading = ({ title, description }: { title: string; description: string }) => (
- <div>
- <p className="text-sm font-medium text-foreground">{title}</p>
- <p className="mt-0.5 text-xs text-muted">{description}</p>
- </div>
-);
-
type EditableEntry<T extends string> = { type: T; value: string };
type AttributeListEditorProps<T extends string> = {
@@ -238,6 +239,7 @@ type Props = {
policyConstraints: PolicyConstraints;
isAwsAcmPublicCa: boolean;
isExternalAdcsCa: boolean;
+ caSupportsCustomExtensions: boolean;
caKeyAlgorithm?: string | null;
};
@@ -251,12 +253,14 @@ export const ProfileDefaultsStep = ({
policyConstraints,
isAwsAcmPublicCa,
isExternalAdcsCa,
+ caSupportsCustomExtensions,
caKeyAlgorithm
}: Props) => {
const watchedPolicyId = watch("certificatePolicyId");
const watchedDefaultsIsCA = watch("defaults.basicConstraints.isCA") || false;
const watchedDefaultSubjectAttrs = watch("defaults.subjectAttributes") || [];
const watchedDefaultSans = watch("defaults.subjectAltNames") || [];
+ const watchedCustomExtensions = watch("defaults.customExtensions") || [];
const watchedDefaultSigAlg = watch("defaults.signatureAlgorithm") ?? null;
const watchedDefaultKeyAlg = watch("defaults.keyAlgorithm") ?? null;
const watchedDefaultKeyUsages = watch("defaults.keyUsages") || {};
@@ -372,6 +376,14 @@ export const ProfileDefaultsStep = ({
/>
)}
+ {caSupportsCustomExtensions && (
+ <CustomExtensionDefaults
+ allowedCustomExtensions={policyConstraints.allowedCustomExtensions}
+ extensions={watchedCustomExtensions}
+ onChange={(next) => setValue("defaults.customExtensions", next)}
+ />
+ )}
+
{policyConstraints.shouldShowSanSection && (
<AttributeListEditor<CertSubjectAlternativeNameType>
title="Subject Alternative Names"
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/SectionHeading.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/SectionHeading.tsx
new file mode 100644
index 0000000000..65e339297b
--- /dev/null
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal/SectionHeading.tsx
@@ -0,0 +1,6 @@
+export const SectionHeading = ({ title, description }: { title: string; description: string }) => (
+ <div>
+ <p className="text-sm font-medium text-foreground">{title}</p>
+ <p className="mt-0.5 text-xs text-muted">{description}</p>
+ </div>
+);
diff --git a/frontend/src/pages/cert-manager/components/CustomExtensionList.tsx b/frontend/src/pages/cert-manager/components/CustomExtensionList.tsx
new file mode 100644
index 0000000000..47e5a94de8
--- /dev/null
+++ b/frontend/src/pages/cert-manager/components/CustomExtensionList.tsx
@@ -0,0 +1,42 @@
+import { Badge, ButtonGroup } from "@app/components/v3";
+import { customExtensionLabelFor } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+
+export type TCustomExtensionListEntry = {
+ oid: string;
+ critical?: boolean;
+ value?: string;
+ displayValue?: string | null;
+ label?: string | null;
+};
+
+type Props = {
+ extensions: TCustomExtensionListEntry[];
+};
+
+export const CustomExtensionList = ({ extensions }: Props) => {
+ if (!extensions.length) return null;
+
+ return (
+ <div className="flex flex-wrap gap-2">
+ {extensions.map((extension) => {
+ const label = customExtensionLabelFor(extension.oid, extension.label);
+ const value = extension.displayValue ?? extension.value;
+
+ return value ? (
+ <ButtonGroup className="max-w-full min-w-0" key={extension.oid}>
+ <Badge isTruncatable className="max-w-[12rem] shrink-0">
+ <span>{label}</span>
+ </Badge>
+ <Badge variant="outline" isTruncatable>
+ <span>{value}</span>
+ </Badge>
+ </ButtonGroup>
+ ) : (
+ <Badge key={extension.oid} isTruncatable>
+ <span>{label}</span>
+ </Badge>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/components/CustomExtensionOidSelect.tsx b/frontend/src/pages/cert-manager/components/CustomExtensionOidSelect.tsx
new file mode 100644
index 0000000000..65d31bd2f4
--- /dev/null
+++ b/frontend/src/pages/cert-manager/components/CustomExtensionOidSelect.tsx
@@ -0,0 +1,78 @@
+import { useMemo, useState } from "react";
+
+import { Combobox } from "@app/components/v3";
+import { CUSTOM_EXTENSION_PRESETS } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+
+type TOidOption = { oid: string; name?: string; isCustom?: boolean };
+
+const OID_OPTIONS: TOidOption[] = Object.entries(CUSTOM_EXTENSION_PRESETS).map(([oid, preset]) => ({
+ oid,
+ name: preset.label
+}));
+
+type Props = {
+ value: string;
+ onChange: (oid: string) => void;
+ isError?: boolean;
+ className?: string;
+ placeholder?: string;
+ extraOptions?: TOidOption[];
+};
+
+export const CustomExtensionOidSelect = ({
+ value,
+ onChange,
+ isError,
+ className,
+ placeholder = "Select or enter an OID",
+ extraOptions
+}: Props) => {
+ const [typed, setTyped] = useState("");
+
+ const knownOptions = useMemo(() => {
+ if (!extraOptions?.length) return OID_OPTIONS;
+ const byOid = new Map(OID_OPTIONS.map((option) => [option.oid, option]));
+ extraOptions.forEach((option) => {
+ byOid.set(option.oid, { ...byOid.get(option.oid), ...option });
+ });
+ return [...byOid.values()];
+ }, [extraOptions]);
+
+ const options = useMemo(() => {
+ const candidate = typed.trim();
+ if (!candidate || knownOptions.some((option) => option.oid === candidate)) return knownOptions;
+ return [{ oid: candidate, isCustom: true }, ...knownOptions];
+ }, [knownOptions, typed]);
+
+ const selected = useMemo(() => {
+ if (!value) return null;
+ return knownOptions.find((option) => option.oid === value) ?? { oid: value };
+ }, [knownOptions, value]);
+
+ return (
+ <div className={className}>
+ <Combobox<TOidOption>
+ aria-label="Object identifier"
+ placeholder={placeholder}
+ searchPlaceholder="Select or enter an OID"
+ emptyMessage="Enter an OID"
+ options={options}
+ value={selected}
+ onValueChange={(option) => onChange(option.oid)}
+ onClear={() => onChange("")}
+ onInput={(event) => setTyped(event.currentTarget.value)}
+ getOptionValue={(option) => option.oid}
+ getOptionLabel={(option) => option.oid}
+ getOptionKeywords={(option) => (option.name ? [option.name] : [])}
+ renderValue={(option) => <span className="font-mono text-xs">{option.oid}</span>}
+ renderOption={(option) => (
+ <div>
+ <p className="font-mono text-xs">{option.oid}</p>
+ <p className="text-xs text-muted">{option.isCustom ? "Use this OID" : option.name}</p>
+ </div>
+ )}
+ isError={isError}
+ />
+ </div>
+ );
+};