Skip to content

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

feat: allow to edit cert details on manual renewals

Carlos Monastyrskief482cd9b19d
diff --git a/.infisicalignore b/.infisicalignore
index b1e9c0dcc7..63decac3da 100644
--- a/.infisicalignore
+++ b/.infisicalignore
@@ -66,3 +66,4 @@ backend/src/ee/services/honey-token/honey-token-service.ts:generic-api-key:49
docs/integrations/app-connections/ovh.mdx:private-key:84
docs/integrations/app-connections/datadog.mdx:generic-api-key:161
docs/integrations/app-connections/qovery.mdx:generic-api-key:96
+backend/src/services/certificate-v3/certificate-renewal-fns.test.ts:private-key:163
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 33907cde81..554982f78c 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2085,7 +2085,17 @@ export const CERTIFICATE_AUTHORITIES = {
export const CERTIFICATES = {
GET: {
id: "The ID of the certificate to get.",
- serialNumber: "The serial number of the certificate to get."
+ serialNumber: "The serial number of the certificate to get.",
+ hasPrivateKey: "Whether Infisical holds the private key for this certificate."
+ },
+ RENEW: {
+ id: "The ID of the certificate to renew.",
+ renewalKeySource:
+ "How the renewed certificate's key pair is handled. 'new' generates a fresh pair, 'reuse' keeps the current one so the renewed certificate carries the same public key, and 'csr' takes the key from a supplied signing request. Omitting this generates a new key pair, and additionally declines to renew a certificate that was issued from a signing request, since that would change which key the certificate certifies without the caller saying so.",
+ csr: "A PEM-encoded certificate signing request to renew from. Its subject, key and extensions take precedence, so only TTL and basic constraints may be set alongside it.",
+ attributes:
+ "Certificate fields to change on renewal. Anything omitted is copied from the certificate being renewed. Profile defaults are not applied.",
+ removeRootsFromChain: "Whether to remove the root certificate from the returned certificate chain."
},
REVOKE: {
id: "The ID or SHA-1/SHA-256 thumbprint of the certificate to revoke. Thumbprint colons and casing are ignored.",
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index 7611415e2c..75fc217af8 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -19,16 +19,19 @@ import { CaType } from "@app/services/certificate-authority/certificate-authorit
import { validateCaDateField } from "@app/services/certificate-authority/certificate-authority-validators";
import {
CertExtendedKeyUsageType,
+ certificateAttributesSchema,
CertKeyUsageType,
CertSubjectAlternativeNameType,
- domainComponentsSchema,
subjectAttributeSchema
} from "@app/services/certificate-common/certificate-constants";
import { extractCertificateRequestFromCSR } from "@app/services/certificate-common/certificate-csr-utils";
import { mapEnumsForValidation } from "@app/services/certificate-common/certificate-utils";
import { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types";
import { CertificateRequestStatus } from "@app/services/certificate-request/certificate-request-types";
-import { TCertificateIssuanceResponse } from "@app/services/certificate-v3/certificate-v3-types";
+import {
+ CertificateRenewalKeySource,
+ TCertificateIssuanceResponse
+} from "@app/services/certificate-v3/certificate-v3-types";
import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
@@ -42,6 +45,8 @@ type CertificateServiceResponse = TCertificateIssuanceResponse | Omit<TCertifica
// subjectAttributeSchema does against the varchar(255) columns they are persisted in.
const subjectAttributeField = subjectAttributeSchema;
+const csrSchema = z.string().trim().min(1, "CSR cannot be empty").max(4096, "CSR cannot exceed 4096 characters");
+
const extractCertificateData = (
data: CertificateServiceResponse
): {
@@ -136,46 +141,11 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
.object({
profileId: z.string().uuid(),
applicationId: z.string().uuid().optional(),
- csr: z
- .string()
- .trim()
- .min(1, "CSR cannot be empty")
- .max(4096, "CSR cannot exceed 4096 characters")
- .optional(),
- attributes: z
- .object({
- commonName: subjectAttributeField.nullish(),
- organization: subjectAttributeField.nullish(),
- organizationalUnit: subjectAttributeField.nullish(),
- country: subjectAttributeField.nullish(),
- state: subjectAttributeField.nullish(),
- locality: subjectAttributeField.nullish(),
- domainComponents: domainComponentsSchema.nullish(),
- keyUsages: z.nativeEnum(CertKeyUsageType).array().optional(),
- extendedKeyUsages: z.nativeEnum(CertExtendedKeyUsageType).array().optional(),
- altNames: z
- .array(
- z.object({
- type: z.nativeEnum(CertSubjectAlternativeNameType),
- value: z.string().min(1, "SAN value cannot be empty")
- })
- )
- .optional(),
- signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(),
- keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional(),
- ttl: z
- .string()
- .trim()
- .refine((val) => !val || ms(val) > 0, "TTL must be a positive number")
- .optional(),
+ csr: csrSchema.optional(),
+ attributes: certificateAttributesSchema
+ .extend({
notBefore: validateCaDateField.optional(),
- notAfter: validateCaDateField.optional(),
- basicConstraints: z
- .object({
- isCA: z.boolean(),
- pathLength: z.number().int().min(0).optional()
- })
- .optional()
+ notAfter: validateCaDateField.optional()
})
.optional(),
removeRootsFromChain: booleanSchema.default(false).optional(),
@@ -1161,14 +1131,25 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
hide: false,
operationId: "renewCertificate",
tags: [ApiDocsTags.PkiCertificates],
+ description:
+ "Renew a certificate. The renewed certificate copies the one being renewed, then applies only the changes supplied here. Profile defaults are not applied.",
params: z.object({
- id: z.string().uuid()
+ id: z.string().uuid().describe(CERTIFICATES.RENEW.id)
}),
body: z
.object({
- removeRootsFromChain: booleanSchema.default(false).optional()
+ removeRootsFromChain: booleanSchema
+ .default(false)
+ .optional()
+ .describe(CERTIFICATES.RENEW.removeRootsFromChain),
+ renewalKeySource: z
+ .nativeEnum(CertificateRenewalKeySource)
+ .optional()
+ .describe(CERTIFICATES.RENEW.renewalKeySource),
+ csr: csrSchema.optional().describe(CERTIFICATES.RENEW.csr),
+ attributes: certificateAttributesSchema.optional().describe(CERTIFICATES.RENEW.attributes)
})
- .optional(),
+ .nullish(),
response: {
200: z.object({
certificate: z.string().trim(),
@@ -1200,7 +1181,10 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
certificateId: req.params.id,
- removeRootsFromChain: req.body?.removeRootsFromChain
+ removeRootsFromChain: req.body?.removeRootsFromChain,
+ renewalKeySource: req.body?.renewalKeySource,
+ csr: req.body?.csr,
+ attributes: req.body?.attributes
});
await server.services.auditLog.createAuditLog({
@@ -1374,6 +1358,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
caType: z.enum(["internal", "external"]).nullable().optional(),
profileName: z.string().nullable().optional(),
applicationName: z.string().nullable().optional(),
+ hasPrivateKey: z.boolean().describe(CERTIFICATES.GET.hasPrivateKey),
metadata: z.array(z.object({ key: z.string(), value: z.string() })).optional()
})
})
diff --git a/backend/src/services/certificate-common/certificate-constants.ts b/backend/src/services/certificate-common/certificate-constants.ts
index e98eeb794b..88da9db626 100644
--- a/backend/src/services/certificate-common/certificate-constants.ts
+++ b/backend/src/services/certificate-common/certificate-constants.ts
@@ -1,5 +1,7 @@
import { z } from "zod";
+import { ms } from "@app/lib/ms";
+
/**
* Knex's `t.string(col)` maps to `varchar(255)`, which is what every PKI table uses for its
* free-form text columns. Validate against the same bound at the API edge so an over-long value
@@ -8,6 +10,10 @@ import { z } from "zod";
*/
export const PKI_TEXT_COLUMN_MAX_LENGTH = 255;
+export const PKI_ALT_NAMES_COLUMN_MAX_LENGTH = 4096;
+
+const MAX_CERTIFICATE_TTL_MS = 100 * 365 * 24 * 60 * 60 * 1000;
+
/**
* Free-form description of a PKI resource. Bounded to the `varchar(255)` description column shared
* by pki_certificate_profiles, pki_certificate_policies, pki_syncs, and
@@ -18,10 +24,6 @@ export const pkiDescriptionSchema = z
.trim()
.max(PKI_TEXT_COLUMN_MAX_LENGTH, `Description cannot exceed ${PKI_TEXT_COLUMN_MAX_LENGTH} characters`);
-/**
- * A single X.509 subject attribute (CN, O, OU, C, ST, L). Every column these land in —
- * certificate_requests, certificates, internal_certificate_authorities — is `varchar(255)`.
- */
export const subjectAttributeSchema = z.string().trim().max(PKI_TEXT_COLUMN_MAX_LENGTH);
export const domainComponentSchema = z
@@ -31,11 +33,6 @@ export const domainComponentSchema = z
.max(255)
.refine((value) => !value.includes(","), { message: "Domain component cannot contain a comma" });
-/**
- * Domain components are persisted comma-joined into a single `varchar(255)` column
- * (certificate_requests.domainComponents, certificates.subjectDomainComponents), so the combined
- * length is what has to fit — bounding each component individually is not enough.
- */
export const domainComponentsSchema = z
.array(domainComponentSchema)
.max(50)
@@ -76,16 +73,6 @@ export enum TAltNameType {
UPN = "upn"
}
-/**
- * Single source of truth for subject alternative name types.
- *
- * To support a new one: add a member to CertSubjectAlternativeNameType and to TAltNameType
- * (certificate-types.ts), then add one row here.
- *
- * `generalNameType` is the value @peculiar/x509 uses for the GeneralName, both when parsing a CSR
- * and when building the extension. `otherNameOid` is set only for types carried as an otherName
- * rather than a native GeneralName choice.
- */
export const CERT_SUBJECT_ALTERNATIVE_NAMES: Record<
CertSubjectAlternativeNameType,
{ generalNameType: TAltNameType; otherNameOid?: string }
@@ -206,46 +193,21 @@ export const mapKeyUsageToLegacy = (usage: CertKeyUsageType): string => {
}
};
+const KEY_USAGE_BY_ALIAS = new Map<string, CertKeyUsageType>(
+ Object.values(CertKeyUsageType).flatMap((standard) => [
+ [mapKeyUsageToLegacy(standard), standard] as const,
+ [standard, standard] as const
+ ])
+);
+
export const mapLegacyKeyUsageToStandard = (usage: string): CertKeyUsageType => {
- switch (usage) {
- case "digitalSignature":
- case "digital_signature":
- return CertKeyUsageType.DIGITAL_SIGNATURE;
- case "keyEncipherment":
- case "key_encipherment":
- return CertKeyUsageType.KEY_ENCIPHERMENT;
- case "nonRepudiation":
- case "non_repudiation":
- return CertKeyUsageType.NON_REPUDIATION;
- case "dataEncipherment":
- case "data_encipherment":
- return CertKeyUsageType.DATA_ENCIPHERMENT;
- case "keyAgreement":
- case "key_agreement":
- return CertKeyUsageType.KEY_AGREEMENT;
- case "keyCertSign":
- case "key_cert_sign":
- return CertKeyUsageType.KEY_CERT_SIGN;
- case "cRLSign":
- case "crl_sign":
- return CertKeyUsageType.CRL_SIGN;
- case "encipherOnly":
- case "encipher_only":
- return CertKeyUsageType.ENCIPHER_ONLY;
- case "decipherOnly":
- case "decipher_only":
- return CertKeyUsageType.DECIPHER_ONLY;
- default:
- throw new Error(`Unknown key usage: ${usage}`);
+ const standard = KEY_USAGE_BY_ALIAS.get(usage);
+ if (!standard) {
+ throw new Error(`Unknown key usage: ${usage}`);
}
+ return standard;
};
-/**
- * Single source of truth for extended key usages.
- *
- * To support a new one: add a member to CertExtendedKeyUsageType and to CertExtendedKeyUsage
- * (certificate-types.ts), then add one row here.
- */
export const CERT_EXTENDED_KEY_USAGES: Record<
CertExtendedKeyUsageType,
{ oid: string; legacyName: CertExtendedKeyUsage }
@@ -281,6 +243,20 @@ export const mapLegacyExtendedKeyUsageToStandard = (usage: string): CertExtended
return standard;
};
+export const normalizeKeyUsagesForResponse = (usages: readonly string[] | null | undefined): string[] =>
+ (usages ?? []).map((usage) => KEY_USAGE_BY_ALIAS.get(usage) ?? usage);
+
+export const normalizeExtendedKeyUsagesForResponse = (usages: readonly string[] | null | undefined): string[] =>
+ (usages ?? []).map((usage) => EXTENDED_KEY_USAGE_BY_ALIAS.get(usage) ?? usage);
+
+export const withNormalizedUsagesForResponse = <T extends { keyUsages?: unknown; extendedKeyUsages?: unknown }>(
+ row: T
+): T => ({
+ ...row,
+ keyUsages: normalizeKeyUsagesForResponse(row.keyUsages as string[] | null | undefined),
+ extendedKeyUsages: normalizeExtendedKeyUsagesForResponse(row.extendedKeyUsages as string[] | null | undefined)
+});
+
export enum CertKeyAlgorithm {
RSA_2048 = "RSA_2048",
RSA_3072 = "RSA_3072",
@@ -373,3 +349,50 @@ export const SAN_EFFECT_OPTIONS = Object.values(CertSanEffect);
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 const subjectAlternativeNameSchema = z.object({
+ type: z.nativeEnum(CertSubjectAlternativeNameType),
+ value: z
+ .string()
+ .trim()
+ .min(1, "SAN value cannot be empty")
+ .max(PKI_TEXT_COLUMN_MAX_LENGTH, `SAN value cannot exceed ${PKI_TEXT_COLUMN_MAX_LENGTH} characters`)
+});
+
+export const certificateAttributesSchema = z.object({
+ commonName: subjectAttributeSchema.nullish(),
+ organization: subjectAttributeSchema.nullish(),
+ organizationalUnit: subjectAttributeSchema.nullish(),
+ country: subjectAttributeSchema.nullish(),
+ state: subjectAttributeSchema.nullish(),
+ locality: subjectAttributeSchema.nullish(),
+ domainComponents: domainComponentsSchema.nullish(),
+ keyUsages: z.nativeEnum(CertKeyUsageType).array().max(20).optional(),
+ extendedKeyUsages: z.nativeEnum(CertExtendedKeyUsageType).array().max(20).optional(),
+ altNames: z
+ .array(subjectAlternativeNameSchema)
+ .max(100, "Cannot exceed 100 subject alternative names")
+ .refine(
+ (names) => names.map((san) => san.value).join(",").length <= PKI_ALT_NAMES_COLUMN_MAX_LENGTH,
+ `Subject alternative names cannot exceed ${PKI_ALT_NAMES_COLUMN_MAX_LENGTH} characters in total`
+ )
+ .optional(),
+ signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(),
+ keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional(),
+ ttl: z
+ .string()
+ .trim()
+ .max(32)
+ .refine((val) => {
+ if (!val) return true;
+ const parsed = ms(val);
+ return parsed > 0 && parsed <= MAX_CERTIFICATE_TTL_MS;
+ }, "TTL must be a positive duration that ends within 100 years")
+ .optional(),
+ basicConstraints: z
+ .object({
+ isCA: z.boolean(),
+ pathLength: z.number().int().min(0).max(255).optional()
+ })
+ .optional()
+});
diff --git a/backend/src/services/certificate-common/certificate-csr-utils.ts b/backend/src/services/certificate-common/certificate-csr-utils.ts
index fdfadc4418..5619006c8e 100644
--- a/backend/src/services/certificate-common/certificate-csr-utils.ts
+++ b/backend/src/services/certificate-common/certificate-csr-utils.ts
@@ -35,8 +35,18 @@ import {
* This allows applyProfileDefaults to correctly apply defaults for missing fields
* (e.g., ACME clients like CertBot often omit CN, putting domain only in SAN).
*/
+export const parseCsr = (csr: string): x509.Pkcs10CertificateRequest => {
+ try {
+ return new x509.Pkcs10CertificateRequest(csr);
+ } catch {
+ throw new BadRequestError({
+ message: "The certificate signing request could not be parsed. Supply a PEM-encoded PKCS#10 request."
+ });
+ }
+};
+
export const extractCertificateRequestFromCSR = (csr: string): TCertificateRequest => {
- const csrObj = new x509.Pkcs10CertificateRequest(csr);
+ const csrObj = parseCsr(csr);
const subject = extractDnParts(csrObj.subjectName);
// Only include keys for fields that have values, so applyProfileDefaults
@@ -119,7 +129,7 @@ export const buildSubjectOverrideForCsr = (
"commonName" | "organization" | "organizationalUnit" | "country" | "state" | "locality" | "domainComponents"
>
): string => {
- const csrSubject = extractDnParts(new x509.Pkcs10CertificateRequest(csr).subjectName);
+ const csrSubject = extractDnParts(parseCsr(csr).subjectName);
return createDistinguishedName({
commonName: csrSubject.commonName ?? request.commonName,
@@ -138,7 +148,7 @@ export const buildSubjectOverrideForCsr = (
* @returns Object containing keyAlgorithm and signatureAlgorithm
*/
export const extractAlgorithmsFromCSR = (csr: string) => {
- const csrObj = new x509.Pkcs10CertificateRequest(csr);
+ const csrObj = parseCsr(csr);
// Extract key algorithm from public key
const { publicKey } = csrObj;
diff --git a/backend/src/services/certificate-common/certificate-issuance-utils.ts b/backend/src/services/certificate-common/certificate-issuance-utils.ts
index d77e310e39..a4aba09b29 100644
--- a/backend/src/services/certificate-common/certificate-issuance-utils.ts
+++ b/backend/src/services/certificate-common/certificate-issuance-utils.ts
@@ -34,29 +34,7 @@ import {
convertKeyUsageArrayToLegacy
} from "./certificate-utils";
-/**
- * Parses a TTL string (e.g., "30d", "24h", "60m") and returns the equivalent in days
- */
-export const parseTtlToDays = (ttl: string): number => {
- const match = ttl.match(new RE2("^(\\d+)([dhm])$"));
- if (!match) {
- throw new BadRequestError({ message: `Invalid TTL format: ${ttl}` });
- }
-
- const [, value, unit] = match;
- const numValue = parseInt(value, 10);
-
- switch (unit) {
- case "d":
- return numValue;
- case "h":
- return Math.ceil(numValue / 24);
- case "m":
- return Math.ceil(numValue / (24 * 60));
- default:
- throw new BadRequestError({ message: `Unsupported TTL unit: ${unit}` });
- }
-};
+export const parseTtlToDays = (ttl: string): number => Math.ceil(ms(ttl) / (24 * 60 * 60 * 1000));
/**
* Calculates the renewal threshold in days, ensuring it doesn't exceed the certificate TTL
@@ -110,6 +88,31 @@ export const calculateFinalRenewBeforeDays = (
return isValidRenewalTiming(renewBeforeDays, certificateExpiryDate) ? renewBeforeDays : undefined;
};
+export const resolveRenewedCertificateRenewBeforeDays = ({
+ apiConfig,
+ previousRenewBeforeDays,
+ ttl,
+ notAfter
+}: {
+ apiConfig?: { autoRenew?: boolean; renewBeforeDays?: number };
+ previousRenewBeforeDays?: number | null;
+ ttl: string;
+ notAfter: Date;
+}): number | undefined => {
+ const desiredRenewBeforeDays =
+ (apiConfig?.autoRenew ? apiConfig.renewBeforeDays : undefined) ?? previousRenewBeforeDays ?? undefined;
+ if (!desiredRenewBeforeDays) {
+ return undefined;
+ }
+
+ const renewBeforeDays = calculateRenewalThreshold(desiredRenewBeforeDays, parseTtlToDays(ttl));
+ if (!renewBeforeDays) {
+ return undefined;
+ }
+
+ return isValidRenewalTiming(renewBeforeDays, notAfter) ? renewBeforeDays : undefined;
+};
+
/**
* Resolves the effective API enrollment config for auto-renew.
* When an applicationId is present, the application-profile junction's config takes
@@ -334,12 +337,14 @@ export const generateSelfSignedCertificate = async ({
certificateRequest,
policy,
effectiveSignatureAlgorithm,
- effectiveKeyAlgorithm
+ effectiveKeyAlgorithm,
+ existingKeyPair
}: {
certificateRequest: TSelfSignedCertificateRequest;
policy?: TCertificatePolicy | null;
effectiveSignatureAlgorithm: CertSignatureAlgorithm;
effectiveKeyAlgorithm: CertKeyAlgorithm;
+ existingKeyPair?: CryptoKeyPair;
}): Promise<TSelfSignedCertificateResult> => {
const certificateSubject = buildCertificateSubjectFromTemplate(certificateRequest, policy?.subject);
const subjectAlternativeNames = buildSubjectAlternativeNamesFromTemplate(
@@ -363,7 +368,9 @@ export const generateSelfSignedCertificate = async ({
const keyGenAlg = keyAlgorithmToAlgCfg(effectiveKeyAlgorithm);
const keyGenCrypto = isPqcAlgorithm(effectiveKeyAlgorithm) ? getPqcCrypto() : crypto.nativeCrypto;
- const keyPair = await keyGenCrypto.subtle.generateKey(keyGenAlg as RsaHashedKeyGenParams, true, ["sign", "verify"]);
+ const keyPair =
+ existingKeyPair ??
+ (await keyGenCrypto.subtle.generateKey(keyGenAlg as RsaHashedKeyGenParams, true, ["sign", "verify"]));
const signatureAlgorithmConfig = signatureAlgorithmToAlgCfg(effectiveSignatureAlgorithm, effectiveKeyAlgorithm);
diff --git a/backend/src/services/certificate-common/certificate-permission-fns.ts b/backend/src/services/certificate-common/certificate-permission-fns.ts
new file mode 100644
index 0000000000..c8a09015db
--- /dev/null
+++ b/backend/src/services/certificate-common/certificate-permission-fns.ts
@@ -0,0 +1,92 @@
+import { ForbiddenError, MongoAbility, subject } from "@casl/ability";
+import { Knex } from "knex";
+
+import { ActionProjectType, ResourceType } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionCertificateActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import {
+ ResourcePermissionCertificateActions,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+
+import { TResourceMetadataDALFactory } from "../resource-metadata/resource-metadata-dal";
+
+type TCertificateSubjectFields = {
+ id: string;
+ projectId: string;
+ applicationId?: string | null;
+ commonName?: string | null;
+ altNames?: string | null;
+ serialNumber?: string | null;
+};
+
+type TAssertCanEditCertificateDTO = {
+ certificate: TCertificateSubjectFields;
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
+ resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find">;
+ tx?: Knex;
+};
+
+export const assertCanEditCertificate = async ({
+ certificate,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ permissionService,
+ resourceMetadataDAL,
+ tx
+}: TAssertCanEditCertificateDTO): Promise<{
+ certMetadata: { key: string; value: string }[];
+ projectPermission?: MongoAbility;
+}> => {
+ if (certificate.applicationId) {
+ const { permission } = await permissionService.getResourcePermission({
+ actor,
+ actorId,
+ projectId: certificate.projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: certificate.applicationId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionCertificateActions.Edit,
+ ResourcePermissionSub.Certificates
+ );
+
+ return { certMetadata: [] };
+ }
+
+ const metadataRows = await resourceMetadataDAL.find({ certificateId: certificate.id }, { tx });
+ const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: certificate.projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateActions.Edit,
+ subject(ProjectPermissionSub.Certificates, {
+ commonName: certificate.commonName ?? undefined,
+ altNames: certificate.altNames?.split(",").map((s) => s.trim()),
+ serialNumber: certificate.serialNumber ?? undefined,
+ metadata: certMetadata
+ })
+ );
+
+ return { certMetadata, projectPermission: permission };
+};
diff --git a/backend/src/services/certificate-request/certificate-request-fns.ts b/backend/src/services/certificate-request/certificate-request-fns.ts
new file mode 100644
index 0000000000..f2ff63565c
--- /dev/null
+++ b/backend/src/services/certificate-request/certificate-request-fns.ts
@@ -0,0 +1,62 @@
+import { Knex } from "knex";
+
+import { InternalServerError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+
+import { CertificateIssuanceOperation } from "../certificate-common/certificate-constants";
+import { TCertificateRequestDALFactory } from "./certificate-request-dal";
+import { CertificateRequestStatus } from "./certificate-request-types";
+
+type TCertificateRequestBookkeepingDAL = Pick<
+ TCertificateRequestDALFactory,
+ "attachCertificate" | "transitionFromPending"
+>;
+
+export const attachCertificateToPendingRequest = async (
+ certificateRequestDAL: TCertificateRequestBookkeepingDAL,
+ {
+ certificateRequestId,
+ certificateId,
+ projectId,
+ operation
+ }: {
+ certificateRequestId: string;
+ certificateId: string;
+ projectId: string;
+ operation: CertificateIssuanceOperation;
+ },
+ tx: Knex
+) => {
+ const attachedRequest = await certificateRequestDAL.attachCertificate(certificateRequestId, certificateId, tx);
+ if (!attachedRequest) {
+ logger.error(
+ { certificateRequestId, projectId, operation },
+ `Certificate request left a pending status mid-operation, aborting [certificateRequestId=${certificateRequestId}]`
+ );
+ throw new InternalServerError({
+ message: "Certificate request is no longer pending, so the operation was aborted"
+ });
+ }
+};
+
+export const markPendingRequestFailed = async (
+ certificateRequestDAL: TCertificateRequestBookkeepingDAL,
+ {
+ certificateRequestId,
+ error,
+ fallbackMessage
+ }: { certificateRequestId: string; error: unknown; fallbackMessage: string }
+) => {
+ try {
+ await certificateRequestDAL.transitionFromPending(
+ certificateRequestId,
+ CertificateRequestStatus.FAILED,
+ error instanceof Error ? error.message : fallbackMessage
+ );
+ } catch (bookkeepingErr) {
+ logger.error(
+ bookkeepingErr,
+ `Failed to mark certificate request as failed [certificateRequestId=${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
new file mode 100644
index 0000000000..647c0841e7
--- /dev/null
+++ b/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts
@@ -0,0 +1,202 @@
+import { webcrypto } from "node:crypto";
+
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ CertExtendedKeyUsageType,
+ CertKeyAlgorithm,
+ CertKeyUsageType,
+ CertSubjectAlternativeNameType
+} from "../certificate-common/certificate-constants";
+import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
+import {
+ assertCsrRenewalAttributes,
+ buildRenewalCertificateRequest,
+ certificateSpanToTtl,
+ importKeyPairFromPem,
+ resolveRenewalKeySource
+} from "./certificate-renewal-fns";
+import { CertificateRenewalKeySource } from "./certificate-v3-types";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }
+}));
+
+const original: TCertificateRequest = {
+ commonName: "web.example.com",
+ organization: "Example Corp",
+ organizationalUnit: "Platform Engineering",
+ country: "US",
+ state: "California",
+ locality: "San Francisco",
+ domainComponents: ["example", "com"],
+ keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE, CertKeyUsageType.KEY_ENCIPHERMENT],
+ extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH],
+ subjectAlternativeNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "web.example.com" }],
+ validity: { ttl: "30d" },
+ keyAlgorithm: "RSA_2048",
+ signatureAlgorithm: "RSA-SHA256"
+};
+
+describe("resolveRenewalKeySource", () => {
+ it("defaults to a new key pair", () => {
+ expect(resolveRenewalKeySource({})).toBe(CertificateRenewalKeySource.New);
+ });
+
+ it("resolves each source", () => {
+ expect(resolveRenewalKeySource({ renewalKeySource: CertificateRenewalKeySource.Reuse })).toBe(
+ CertificateRenewalKeySource.Reuse
+ );
+ expect(resolveRenewalKeySource({ renewalKeySource: CertificateRenewalKeySource.Csr, csr: "csr" })).toBe(
+ CertificateRenewalKeySource.Csr
+ );
+ });
+
+ it("rejects a CSR alongside any other key source, and a csr source without one", () => {
+ expect(() => resolveRenewalKeySource({ renewalKeySource: CertificateRenewalKeySource.Csr })).toThrow(
+ /signing request is required/
+ );
+ expect(() => resolveRenewalKeySource({ renewalKeySource: CertificateRenewalKeySource.Reuse, csr: "csr" })).toThrow(
+ /only be supplied with renewalKeySource 'csr'/
+ );
+ expect(() => resolveRenewalKeySource({ csr: "csr" })).toThrow(/only be supplied with renewalKeySource 'csr'/);
+ });
+});
+
+describe("assertCsrRenewalAttributes", () => {
+ it("allows validity and basic constraints", () => {
+ expect(() => assertCsrRenewalAttributes({ ttl: "30d", basicConstraints: { isCA: false } })).not.toThrow();
+ });
+
+ it("rejects anything the CSR already carries, naming the fields", () => {
+ expect(() => assertCsrRenewalAttributes({ commonName: "other.example.com", ttl: "30d" })).toThrow(/common name/);
+ expect(() =>
+ assertCsrRenewalAttributes({ altNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "a.com" }] })
+ ).toThrow(/subject alternative names/);
+ });
+
+ it("ignores keys that are present but undefined", () => {
+ expect(() => assertCsrRenewalAttributes({ commonName: undefined, ttl: "30d" })).not.toThrow();
+ });
+});
+
+describe("buildRenewalCertificateRequest", () => {
+ it("returns the certificate unchanged when nothing was supplied", () => {
+ expect(buildRenewalCertificateRequest({ original })).toEqual(original);
+ expect(buildRenewalCertificateRequest({ original, attributes: {} })).toEqual(original);
+ });
+
+ it("applies only the fields the caller supplied", () => {
+ const result = buildRenewalCertificateRequest({
+ original,
+ attributes: { commonName: "api.example.com", ttl: "90d" }
+ });
+
+ expect(result.commonName).toBe("api.example.com");
+ expect(result.validity).toEqual({ ttl: "90d" });
+ expect(result.organization).toBe("Example Corp");
+ expect(result.locality).toBe("San Francisco");
+ expect(result.keyUsages).toEqual(original.keyUsages);
+ expect(result.subjectAlternativeNames).toEqual(original.subjectAlternativeNames);
+ });
+
+ it("clears a field when it is explicitly set to null", () => {
+ const result = buildRenewalCertificateRequest({
+ original,
+ attributes: { organizationalUnit: null, domainComponents: null }
+ });
+
+ expect(result.organizationalUnit).toBeUndefined();
+ expect(result.domainComponents).toBeUndefined();
+ expect(result.organization).toBe("Example Corp");
+ });
+
+ it("replaces list-valued fields wholesale rather than merging them", () => {
+ const result = buildRenewalCertificateRequest({
+ original,
+ attributes: {
+ altNames: [{ type: CertSubjectAlternativeNameType.IP_ADDRESS, value: "10.0.0.1" }],
+ keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE]
+ }
+ });
+
+ expect(result.subjectAlternativeNames).toEqual([
+ { type: CertSubjectAlternativeNameType.IP_ADDRESS, value: "10.0.0.1" }
+ ]);
+ expect(result.keyUsages).toEqual([CertKeyUsageType.DIGITAL_SIGNATURE]);
+ expect(result.extendedKeyUsages).toEqual(original.extendedKeyUsages);
+ });
+
+ it("accepts an empty SAN list as a real instruction to remove them", () => {
+ const result = buildRenewalCertificateRequest({ original, attributes: { altNames: [] } });
+ expect(result.subjectAlternativeNames).toEqual([]);
+ });
+
+ it("carries the algorithms so callers never have to fall back to the certificate's own", () => {
+ const result = buildRenewalCertificateRequest({
+ original,
+ attributes: { keyAlgorithm: CertKeyAlgorithm.ECDSA_P256 }
+ });
+
+ expect(result.keyAlgorithm).toBe(CertKeyAlgorithm.ECDSA_P256);
+ expect(result.signatureAlgorithm).toBe("RSA-SHA256");
+ });
+});
+
+describe("certificateSpanToTtl", () => {
+ it("expresses the span in the largest whole unit that fits", () => {
+ const base = new Date("2026-01-01T00:00:00Z");
+ const plus = (ms: number) => new Date(base.getTime() + ms);
+
+ expect(certificateSpanToTtl(base, plus(30 * 24 * 60 * 60 * 1000))).toBe("30d");
+ expect(certificateSpanToTtl(base, plus(5 * 60 * 60 * 1000))).toBe("5h");
+ expect(certificateSpanToTtl(base, plus(90 * 1000))).toBe("1m");
+ expect(certificateSpanToTtl(base, plus(30 * 1000))).toBe("30s");
+ });
+});
+
+describe("importKeyPairFromPem", () => {
+ const generatePkcs8Pem = async (algorithm: RsaHashedKeyGenParams | EcKeyGenParams) => {
+ const pair = (await webcrypto.subtle.generateKey(algorithm, true, ["sign", "verify"])) as CryptoKeyPair;
+ const pkcs8 = Buffer.from(await webcrypto.subtle.exportKey("pkcs8", pair.privateKey));
+ return {
+ pem: `-----BEGIN PRIVATE KEY-----\n${pkcs8.toString("base64").replace(/(.{64})/g, "$1\n")}\n-----END PRIVATE KEY-----\n`,
+ spki: Buffer.from(await webcrypto.subtle.exportKey("spki", pair.publicKey)).toString("base64")
+ };
+ };
+
+ it("derives the matching public key from a stored RSA private key", async () => {
+ const { pem, spki } = await generatePkcs8Pem({
+ name: "RSASSA-PKCS1-v1_5",
+ modulusLength: 2048,
+ publicExponent: new Uint8Array([1, 0, 1]),
+ hash: "SHA-256"
+ });
+
+ const keyPair = await importKeyPairFromPem({
+ privateKeyPem: pem,
+ keyAlgorithm: CertKeyAlgorithm.RSA_2048
+ });
+
+ const exported = Buffer.from(await webcrypto.subtle.exportKey("spki", keyPair.publicKey)).toString("base64");
+ expect(exported).toBe(spki);
+ });
+
+ it("derives the matching public key from a stored EC private key", async () => {
+ const { pem, spki } = await generatePkcs8Pem({ name: "ECDSA", namedCurve: "P-256" });
+
+ const keyPair = await importKeyPairFromPem({
+ privateKeyPem: pem,
+ keyAlgorithm: CertKeyAlgorithm.ECDSA_P256
+ });
+
+ const exported = Buffer.from(await webcrypto.subtle.exportKey("spki", keyPair.publicKey)).toString("base64");
+ expect(exported).toBe(spki);
+ });
+
+ it("rejects an unreadable key with a message that names the alternative", async () => {
+ await expect(
+ importKeyPairFromPem({ privateKeyPem: "not-a-key", keyAlgorithm: CertKeyAlgorithm.RSA_2048 })
+ ).rejects.toThrow("Renew with a new key pair");
+ });
+});
diff --git a/backend/src/services/certificate-v3/certificate-renewal-fns.ts b/backend/src/services/certificate-v3/certificate-renewal-fns.ts
new file mode 100644
index 0000000000..4e6214d2e0
--- /dev/null
+++ b/backend/src/services/certificate-v3/certificate-renewal-fns.ts
@@ -0,0 +1,335 @@
+import * as x509 from "@peculiar/x509";
+import RE2 from "re2";
+
+import { crypto } from "@app/lib/crypto/cryptography";
+import { derivePublicKeyFromSecret, getPqcCrypto, isPqcCryptoKey } from "@app/lib/crypto/pqc";
+import { isPqcAlgorithm } from "@app/lib/crypto/pqc/pqc-utils";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { CertKeyAlgorithm, CertStatus, mapSanTypeToX509Type } from "@app/services/certificate/certificate-types";
+import { TCertificateAuthorityWithAssociatedCa } from "@app/services/certificate-authority/certificate-authority-dal";
+import { CaCapability, CaStatus, CaType } from "@app/services/certificate-authority/certificate-authority-enums";
+import {
+ createDistinguishedName,
+ keyAlgorithmToAlgCfg
+} from "@app/services/certificate-authority/certificate-authority-fns";
+import { caSupportsCapability } from "@app/services/certificate-authority/certificate-authority-maps";
+
+import { CertKeyUsageType } from "../certificate-common/certificate-constants";
+import {
+ extractAlgorithmsFromCSR,
+ extractCertificateRequestFromCSR
+} from "../certificate-common/certificate-csr-utils";
+import { mapEnumsForValidation } from "../certificate-common/certificate-utils";
+import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
+import { CertificateRenewalKeySource, TRenewalAttributes } from "./certificate-v3-types";
+
+export enum CertificateRenewalMode {
+ Signed = "signed",
+ KeyPreserving = "key-preserving",
+ ExternalCa = "external-ca"
+}
+
+const CSR_RENEWAL_EDITABLE_ATTRIBUTES = new Set<keyof TRenewalAttributes>(["ttl", "basicConstraints"]);
+
+const RENEWAL_ATTRIBUTE_LABELS: Record<keyof TRenewalAttributes, string> = {
+ commonName: "common name",
+ organization: "organization",
+ organizationalUnit: "organizational unit",
+ country: "country",
+ state: "state",
+ locality: "locality",
+ domainComponents: "domain components",
+ altNames: "subject alternative names",
+ keyUsages: "key usages",
+ extendedKeyUsages: "extended key usages",
+ signatureAlgorithm: "signature algorithm",
+ keyAlgorithm: "key algorithm",
+ ttl: "TTL",
+ basicConstraints: "basic constraints"
+};
+
+export const resolveRenewalKeySource = ({
+ renewalKeySource,
+ csr
+}: {
+ renewalKeySource?: CertificateRenewalKeySource;
+ csr?: string;
+}): CertificateRenewalKeySource => {
+ const keySource = renewalKeySource ?? CertificateRenewalKeySource.New;
+
+ if (keySource === CertificateRenewalKeySource.Csr && !csr) {
+ throw new BadRequestError({
+ message: `A certificate signing request is required when renewing with renewalKeySource '${CertificateRenewalKeySource.Csr}'.`
+ });
+ }
+
+ if (keySource !== CertificateRenewalKeySource.Csr && csr) {
+ throw new BadRequestError({
+ message: `A certificate signing request can only be supplied with renewalKeySource '${CertificateRenewalKeySource.Csr}', not '${keySource}'.`
+ });
+ }
+
+ return keySource;
+};
+
+export const assertCsrRenewalAttributes = (attributes?: TRenewalAttributes) => {
+ if (!attributes) return;
+
+ const rejected = (Object.keys(attributes) as (keyof TRenewalAttributes)[])
+ .filter((key) => attributes[key] !== undefined && !CSR_RENEWAL_EDITABLE_ATTRIBUTES.has(key))
+ .map((key) => RENEWAL_ATTRIBUTE_LABELS[key] ?? key);
+
+ if (rejected.length > 0) {
+ 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.`
+ });
+ }
+};
+
+/**
+ * Renewal copies the current certificate and applies only what the caller explicitly changed.
+ * Profile defaults are deliberately not consulted: they describe what a *new* certificate should
+ * look like, and applying them here would silently rewrite fields the caller never touched.
+ *
+ * A key present with a `null` value clears the field; an absent key keeps the original value.
+ */
+export const buildRenewalCertificateRequest = ({
+ original,
+ attributes
+}: {
+ original: TCertificateRequest;
+ attributes?: TRenewalAttributes;
+}): TCertificateRequest => {
+ if (!attributes) return original;
+
+ return {
+ ...original,
+ ...(attributes.commonName !== undefined && { commonName: attributes.commonName ?? undefined }),
+ ...(attributes.organization !== undefined && { organization: attributes.organization ?? undefined }),
+ ...(attributes.organizationalUnit !== undefined && {
+ organizationalUnit: attributes.organizationalUnit ?? undefined
+ }),
+ ...(attributes.country !== undefined && { country: attributes.country ?? undefined }),
+ ...(attributes.state !== undefined && { state: attributes.state ?? undefined }),
+ ...(attributes.locality !== undefined && { locality: attributes.locality ?? undefined }),
+ ...(attributes.domainComponents !== undefined && {
+ domainComponents: attributes.domainComponents ?? undefined
+ }),
+ ...(attributes.altNames !== undefined && { subjectAlternativeNames: attributes.altNames }),
+ ...(attributes.keyUsages !== undefined && { keyUsages: attributes.keyUsages }),
+ ...(attributes.extendedKeyUsages !== undefined && { extendedKeyUsages: attributes.extendedKeyUsages }),
+ ...(attributes.signatureAlgorithm !== undefined && { signatureAlgorithm: attributes.signatureAlgorithm }),
+ ...(attributes.keyAlgorithm !== undefined && { keyAlgorithm: attributes.keyAlgorithm }),
+ ...(attributes.ttl !== undefined && { validity: { ttl: attributes.ttl } }),
+ ...(attributes.basicConstraints !== undefined && { basicConstraints: attributes.basicConstraints })
+ };
+};
+
+export const buildCsrRenewalCertificateRequest = ({
+ csr,
+ attributes
+}: {
+ csr: string;
+ attributes?: TRenewalAttributes;
+}): TCertificateRequest => {
+ const csrRequest = mapEnumsForValidation(extractCertificateRequestFromCSR(csr));
+ const { keyAlgorithm, signatureAlgorithm } = extractAlgorithmsFromCSR(csr);
+
+ const requestedBasicConstraints = attributes?.basicConstraints ?? csrRequest.basicConstraints;
+ const isCA =
+ requestedBasicConstraints?.isCA === true ||
+ (csrRequest.keyUsages?.includes(CertKeyUsageType.KEY_CERT_SIGN) ?? false);
+
+ const basicConstraints = isCA
+ ? { isCA: true, pathLength: requestedBasicConstraints?.pathLength }
+ : requestedBasicConstraints;
+
+ return {
+ ...csrRequest,
+ keyAlgorithm,
+ signatureAlgorithm,
+ ...(attributes?.ttl && { validity: { ttl: attributes.ttl } }),
+ ...(basicConstraints && { basicConstraints })
+ };
+};
+
+export const certificateSpanToTtl = (notBefore: Date, notAfter: Date): string => {
+ const diffMs = notAfter.getTime() - notBefore.getTime();
+
+ const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));
+ if (days > 0) return `${days}d`;
+
+ const hours = Math.floor(diffMs / (1000 * 60 * 60));
+ if (hours > 0) return `${hours}h`;
+
+ const minutes = Math.floor(diffMs / (1000 * 60));
+ if (minutes > 0) return `${minutes}m`;
+
+ return `${Math.floor(diffMs / 1000)}s`;
+};
+
+export const buildRenewalDistinguishedName = (certificateRequest: TCertificateRequest): string =>
+ createDistinguishedName({
+ commonName: certificateRequest.commonName,
+ organization: certificateRequest.organization,
+ ou: certificateRequest.organizationalUnit,
+ country: certificateRequest.country,
+ province: certificateRequest.state,
+ locality: certificateRequest.locality,
+ domainComponents: certificateRequest.domainComponents
+ });
+
+const pemBodyToDer = (pem: string): Buffer =>
+ Buffer.from(pem.replace(new RE2("-----(BEGIN|END)[^-]+-----", "g"), "").replace(new RE2("\\s", "g"), ""), "base64");
+
+export const importKeyPairFromPem = async ({
+ privateKeyPem,
+ keyAlgorithm
+}: {
+ privateKeyPem: string;
+ keyAlgorithm: CertKeyAlgorithm;
+}): Promise<CryptoKeyPair> => {
+ const algorithm = keyAlgorithmToAlgCfg(keyAlgorithm);
+ const isPqc = isPqcAlgorithm(keyAlgorithm);
+ const cryptoEngine = isPqc ? getPqcCrypto() : crypto.nativeCrypto;
+
+ try {
+ if (isPqc) {
+ const privateKeyDer = pemBodyToDer(privateKeyPem);
+ const privateKey = await cryptoEngine.subtle.importKey("pkcs8", privateKeyDer, algorithm, true, ["sign"]);
+ if (!isPqcCryptoKey(privateKey)) {
+ throw new Error(`Expected a PQC key handle for ${keyAlgorithm}`);
+ }
+ const { spkiDer } = await derivePublicKeyFromSecret(privateKey.algorithm.name, privateKey.rawKey);
+ const publicKey = await cryptoEngine.subtle.importKey("spki", spkiDer, algorithm, true, ["verify"]);
+ return { privateKey, publicKey };
+ }
+
+ const privateKeyObject = crypto.nativeCrypto.createPrivateKey({
+ key: privateKeyPem,
+ format: "pem",
+ type: "pkcs8"
+ });
+ const publicKeyObject = crypto.nativeCrypto.createPublicKey(privateKeyObject);
+
+ const privateKey = await cryptoEngine.subtle.importKey(
+ "pkcs8",
+ privateKeyObject.export({ format: "der", type: "pkcs8" }),
+ algorithm,
+ true,
+ ["sign"]
+ );
+ const publicKey = await cryptoEngine.subtle.importKey(
+ "spki",
+ publicKeyObject.export({ format: "der", type: "spki" }),
+ algorithm,
+ true,
+ ["verify"]
+ );
+ return { privateKey, publicKey };
+ } catch (err) {
+ logger.error(err, `Failed to import a stored ${keyAlgorithm} private key for renewal`);
+ throw new BadRequestError({
+ message: `The stored private key could not be reused for renewal because its algorithm '${keyAlgorithm}' is not supported by this server. Renew with a new key pair, or supply a CSR generated from the existing key.`
+ });
+ }
+};
+
+export const buildCsrFromExistingKey = async ({
+ privateKeyPem,
+ keyAlgorithm,
+ certificateRequest
+}: {
+ privateKeyPem: string;
+ keyAlgorithm: CertKeyAlgorithm;
+ certificateRequest: TCertificateRequest;
+}): Promise<string> => {
+ const algorithm = keyAlgorithmToAlgCfg(keyAlgorithm);
+ const { privateKey, publicKey } = await importKeyPairFromPem({ privateKeyPem, keyAlgorithm });
+
+ const altNames = (certificateRequest.subjectAlternativeNames ?? []).map((san) => ({
+ type: mapSanTypeToX509Type(san.type),
+ value: san.value
+ }));
+
+ const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
+ name: buildRenewalDistinguishedName(certificateRequest),
+ keys: { privateKey, publicKey },
+ signingAlgorithm: algorithm,
+ ...(altNames.length > 0 && {
+ extensions: [new x509.SubjectAlternativeNameExtension(altNames, false)]
+ })
+ });
+
+ return csrObj.toString("pem");
+};
+
+export const validateRenewalEligibility = (
+ certificate: {
+ id: string;
+ status: string;
+ notBefore: Date;
+ notAfter: Date;
+ revokedAt?: Date | null;
+ renewedByCertificateId?: string | null;
+ profileId?: string | null;
+ caId?: string | null;
+ pkiSubscriberId?: string | null;
+ },
+ ca: TCertificateAuthorityWithAssociatedCa
+) => {
+ const errors: string[] = [];
+
+ if (certificate.status !== CertStatus.ACTIVE) {
+ errors.push(`Certificate status is ${certificate.status}, must be ${CertStatus.ACTIVE}`);
+ }
+
+ const now = new Date();
+ if (certificate.notAfter <= now) {
+ errors.push("Certificate is already expired");
+ }
+
+ if (certificate.revokedAt) {
+ errors.push("Certificate is revoked and cannot be renewed");
+ }
+
+ const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;
+ const isImportedCertificate = certificate.pkiSubscriberId != null && !certificate.profileId;
+
+ if (!caSupportsCapability(caType, CaCapability.RENEW_CERTIFICATES)) {
+ errors.push(`CA type ${String(caType)} does not support renewal`);
+ }
+
+ if (isImportedCertificate) {
+ errors.push("Externally imported certificates cannot be renewed");
+ }
+
+ if (ca.status !== CaStatus.ACTIVE) {
+ errors.push(`Certificate Authority is ${ca.status}, must be ${CaStatus.ACTIVE}`);
+ }
+
+ if (certificate.renewedByCertificateId) {
+ errors.push("Certificate has already been renewed");
+ }
+
+ const certificateTtlInDays = Math.ceil(
+ (certificate.notAfter.getTime() - certificate.notBefore.getTime()) / (24 * 60 * 60 * 1000)
+ );
+
+ if (ca.internalCa?.notAfter) {
+ const caExpiryDate = new Date(ca.internalCa.notAfter);
+ const proposedCertExpiryDate = new Date(now.getTime() + certificateTtlInDays * 24 * 60 * 60 * 1000);
+
+ if (proposedCertExpiryDate > caExpiryDate) {
+ errors.push(
+ `New certificate would expire (${proposedCertExpiryDate.toISOString()}) after its issuing CA (${caExpiryDate.toISOString()})`
+ );
+ }
+ }
+
+ return {
+ isEligible: errors.length === 0,
+ errors
+ };
+};
diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.ts
new file mode 100644
index 0000000000..3e0dd57b78
--- /dev/null
+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts
@@ -0,0 +1,1294 @@
+import { ForbiddenError, subject } from "@casl/ability";
+import { randomUUID } from "crypto";
+import { Knex } from "knex";
+
+import { ActionProjectType, TCertificates } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionCertificateProfileActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { ms } from "@app/lib/ms";
+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 { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
+import { CertKeyAlgorithm, CertSignatureAlgorithm, CertStatus } from "@app/services/certificate/certificate-types";
+import {
+ TCertificateAuthorityDALFactory,
+ TCertificateAuthorityWithAssociatedCa
+} from "@app/services/certificate-authority/certificate-authority-dal";
+import { CaCapability, CaType } from "@app/services/certificate-authority/certificate-authority-enums";
+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 { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
+import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
+import {
+ EnrollmentType,
+ IssuerType,
+ TCertificateProfileWithConfigs
+} from "@app/services/certificate-profile/certificate-profile-types";
+import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
+import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+
+import { TCertificateIssuanceQueueFactory } from "../certificate-authority/certificate-issuance-queue";
+import {
+ CertificateIssuanceOperation,
+ mapExtendedKeyUsageToLegacy,
+ mapKeyUsageToLegacy
+} from "../certificate-common/certificate-constants";
+import {
+ detectSanType,
+ extractCertificateFromBuffer,
+ getEffectiveAlgorithms,
+ isValidRenewalTiming,
+ resolveEffectiveApiConfig,
+ resolveRenewedCertificateRenewBeforeDays,
+ validateAlgorithmCompatibility,
+ validateCaSupport
+} from "../certificate-common/certificate-issuance-utils";
+import { assertCanEditCertificate } from "../certificate-common/certificate-permission-fns";
+import {
+ convertExtendedKeyUsageArrayToLegacy,
+ convertKeyUsageArrayToLegacy,
+ normalizeDateForApi,
+ removeRootCaFromChain
+} from "../certificate-common/certificate-utils";
+import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
+import { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";
+import {
+ attachCertificateToPendingRequest,
+ markPendingRequestFailed
+} from "../certificate-request/certificate-request-fns";
+import { TCertificateRequestServiceFactory } from "../certificate-request/certificate-request-service";
+import { CertificateRequestStatus } from "../certificate-request/certificate-request-types";
+import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
+import { TPkiApplicationProfileDALFactory } from "../pki-application/pki-application-profile-dal";
+import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";
+import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
+import { addRenewedCertificateToSyncs, triggerAutoSyncForCertificate } from "../pki-sync/pki-sync-utils";
+import { TResourceMetadataDALFactory } from "../resource-metadata/resource-metadata-dal";
+import { copyMetadataFromCertificate } from "../resource-metadata/resource-metadata-fns";
+import {
+ assertCsrRenewalAttributes,
+ buildCsrFromExistingKey,
+ buildCsrRenewalCertificateRequest,
+ buildRenewalCertificateRequest,
+ buildRenewalDistinguishedName,
+ CertificateRenewalMode,
+ certificateSpanToTtl,
+ importKeyPairFromPem,
+ resolveRenewalKeySource,
+ validateRenewalEligibility
+} from "./certificate-renewal-fns";
+import { processSelfSignedCertificate } from "./certificate-self-signed-fns";
+import { parseExtendedKeyUsages, parseKeyUsages } from "./certificate-v3-fns";
+import {
+ CertificateRenewalKeySource,
+ TCertificateIssuanceResponse,
+ TDisableRenewalConfigDTO,
+ TDisableRenewalResponse,
+ TRenewalConfigResponse,
+ TRenewCertificateDTO,
+ TUpdateRenewalConfigDTO
+} from "./certificate-v3-types";
+
+type TCertificateRenewalServiceFactoryDep = {
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ | "findById"
+ | "updateById"
+ | "transaction"
+ | "create"
+ | "getRequestEnrollmentTypeByCertId"
+ | "getOriginatingRequestByCertId"
+ >;
+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;
+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
+ certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;
+ certificatePolicyService: Pick<TCertificatePolicyServiceFactory, "validateRequestAgainstPolicy" | "getPolicyById">;
+ internalCaService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa" | "issueCertFromCa">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
+ certificateSyncDAL: Pick<
+ TCertificateSyncDALFactory,
+ "findPkiSyncIdsByCertificateId" | "addCertificates" | "findByPkiSyncAndCertificate" | "updateSyncMetadata"
+ >;
+ pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
+ pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
+ kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
+ projectDAL: TProjectDALFactory;
+ certificateIssuanceQueue: Pick<TCertificateIssuanceQueueFactory, "queueCertificateIssuance">;
+ certificateRequestService: Pick<TCertificateRequestServiceFactory, "createCertificateRequest">;
+ certificateRequestDAL: Pick<TCertificateRequestDALFactory, "attachCertificate" | "transitionFromPending">;
+ resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete" | "find">;
+ pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
+ pkiApplicationProfileDAL: Pick<
+ TPkiApplicationProfileDALFactory,
+ "findAllByProfileId" | "findOneByApplicationAndProfile"
+ >;
+ apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;
+ resolveApplicationIdForProfile: TResolveApplicationIdForProfile;
+ reportCertificateIssued: TReportCertificateIssued;
+};
+
+type TRenewalActor = {
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+};
+
+export type TResolveApplicationIdForProfile = (
+ profile: { id: string; projectId: string; slug: string },
+ explicitApplicationId: string | undefined,
+ actorCtx: { actor: ActorType; actorId: string; actorAuthMethod: ActorAuthMethod; actorOrgId: string },
+ enrollmentType: EnrollmentType
+) => Promise<string | undefined>;
+
+export type TReportCertificateIssued = (args: {
+ orgId: string;
+ projectId: string;
+ profileId?: string;
+ applicationId?: string;
+ enrollmentType: EnrollmentType;
+ operation: CertificateIssuanceOperation;
+ actor: ActorType;
+ actorId: string;
+}) => Promise<void>;
+
+export type TCertificateRenewalServiceFactory = ReturnType<typeof certificateRenewalServiceFactory>;
+
+export const certificateRenewalServiceFactory = ({
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ certificateAuthorityDAL,
+ certificateProfileDAL,
+ certificatePolicyService,
+ internalCaService,
+ permissionService,
+ certificateSyncDAL,
+ pkiSyncDAL,
+ pkiSyncQueue,
+ kmsService,
+ projectDAL,
+ certificateIssuanceQueue,
+ certificateRequestService,
+ certificateRequestDAL,
+ resourceMetadataDAL,
+ pkiAlertV2Queue,
+ pkiApplicationProfileDAL,
+ apiEnrollmentConfigDAL,
+ resolveApplicationIdForProfile: $resolveApplicationIdForProfile,
+ reportCertificateIssued: $reportCertificateIssued
+}: TCertificateRenewalServiceFactoryDep) => {
+ const $linkRenewedCertificate = async (
+ {
+ newCert,
+ originalCert,
+ finalRenewBeforeDays,
+ isRenewalLinkPreset = false,
+ certificateRequestId,
+ certificateRequestCreatedAt,
+ orgId
+ }: {
+ newCert: TCertificates;
+ originalCert: TCertificates;
+ finalRenewBeforeDays?: number;
+ isRenewalLinkPreset?: boolean;
+ certificateRequestId: string;
+ certificateRequestCreatedAt: Date;
+ orgId: string;
+ },
+ tx: Parameters<TCertificateDALFactory["updateById"]>[2]
+ ) => {
+ const renewalUpdate: {
+ profileId?: string | null;
+ renewedFromCertificateId?: string;
+ renewBeforeDays?: number;
+ applicationId?: string | null;
+ } = isRenewalLinkPreset
+ ? {}
+ : { profileId: originalCert.profileId || null, renewedFromCertificateId: originalCert.id };
+
+ if (finalRenewBeforeDays !== undefined) renewalUpdate.renewBeforeDays = finalRenewBeforeDays;
+ if (originalCert.applicationId) renewalUpdate.applicationId = originalCert.applicationId;
+ if (Object.keys(renewalUpdate).length > 0) {
+ await certificateDAL.updateById(newCert.id, renewalUpdate, tx);
+ }
+
+ await certificateDAL.updateById(originalCert.id, { renewedByCertificateId: newCert.id, renewalError: null }, tx);
+ await addRenewedCertificateToSyncs(originalCert.id, newCert.id, { certificateSyncDAL }, tx);
+
+ await copyMetadataFromCertificate(resourceMetadataDAL, {
+ sourceCertificateId: originalCert.id,
+ targetCertificateId: newCert.id,
+ targetCertificateRequestId: certificateRequestId,
+ targetCertificateRequestCreatedAt: certificateRequestCreatedAt,
+ orgId,
+ tx
+ });
+ };
+
+ const $finalizeRenewal = async ({
+ newCertificateId,
+ originalCert,
+ profile,
+ certificate,
+ issuingCaCertificate,
+ certificateChain,
+ serialNumber,
+ certificateRequestId,
+ commonName,
+ fallbackProfileName,
+ removeRootsFromChain,
+ actor,
+ actorId,
+ actorOrgId
+ }: {
+ newCertificateId: string;
+ originalCert: TCertificates;
+ profile: { slug?: string | null; project?: { orgId?: string } | null } | null;
+ certificate: string;
+ issuingCaCertificate: string;
+ certificateChain: string;
+ serialNumber: string;
+ certificateRequestId: string;
+ commonName: string;
+ fallbackProfileName: string;
+ removeRootsFromChain?: boolean;
+ actor: ActorType;
+ actorId: string;
+ actorOrgId: string;
+ }): Promise<TCertificateIssuanceResponse> => {
+ await triggerAutoSyncForCertificate(newCertificateId, { certificateSyncDAL, pkiSyncDAL, pkiSyncQueue });
+
+ try {
+ await pkiAlertV2Queue?.queueCertificateEvent({
+ certificateId: newCertificateId,
+ projectId: originalCert.projectId,
+ eventType: PkiAlertEventType.RENEWAL,
+ applicationId: originalCert.applicationId ?? null
+ });
+ } catch {
+ logger.debug("Failed to queue PKI renewal alert event");
+ }
+
+ await $reportCertificateIssued({
+ orgId: profile?.project?.orgId ?? actorOrgId,
+ projectId: originalCert.projectId,
+ profileId: originalCert.profileId ?? undefined,
+ applicationId: originalCert.applicationId ?? undefined,
+ enrollmentType: EnrollmentType.API,
+ operation: CertificateIssuanceOperation.RENEW,
+ actor,
+ actorId
+ });
+
+ return {
+ status: CertificateRequestStatus.ISSUED,
+ certificate,
+ issuingCaCertificate,
+ certificateChain: removeRootsFromChain ? removeRootCaFromChain(certificateChain) : certificateChain,
+ serialNumber,
+ certificateId: newCertificateId,
+ certificateRequestId,
+ projectId: originalCert.projectId,
+ profileName: profile?.slug || fallbackProfileName,
+ commonName
+ };
+ };
+
+ const $decryptCertificatePrivateKey = async ({
+ projectId,
+ encryptedPrivateKey
+ }: {
+ projectId: string;
+ encryptedPrivateKey: Buffer;
+ }): Promise<string> => {
+ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({ projectId, projectDAL, kmsService });
+ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: certificateManagerKmsId });
+ const decryptedPrivateKey = await kmsDecryptor({ cipherTextBlob: encryptedPrivateKey });
+ return decryptedPrivateKey.toString("utf-8");
+ };
+
+ const $completeKeyPreservingRenewal = async ({
+ keySource,
+ csr,
+ ca,
+ profile,
+ policy,
+ originalCert,
+ certificateRequest,
+ certificateSecret,
+ originalCsr,
+ ttl,
+ notBefore,
+ notAfter,
+ finalRenewBeforeDays,
+ effectiveKeyAlgorithm,
+ effectiveSignatureAlgorithm,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ removeRootsFromChain
+ }: {
+ keySource: CertificateRenewalKeySource;
+ csr?: string;
+ ca: TCertificateAuthorityWithAssociatedCa;
+ profile: Awaited<ReturnType<TCertificateProfileDALFactory["findByIdWithConfigs"]>> | null;
+ policy: Awaited<ReturnType<TCertificatePolicyServiceFactory["getPolicyById"]>> | null;
+ originalCert: TCertificates;
+ certificateRequest: TCertificateRequest;
+ certificateSecret: { encryptedPrivateKey: Buffer } | undefined;
+ originalCsr: string | null;
+ ttl: string;
+ notBefore: Date;
+ notAfter: Date;
+ finalRenewBeforeDays: number | undefined;
+ effectiveKeyAlgorithm: CertKeyAlgorithm;
+ effectiveSignatureAlgorithm: CertSignatureAlgorithm;
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ removeRootsFromChain?: boolean;
+ }): Promise<TCertificateIssuanceResponse> => {
+ const isCsrAuthoritative = keySource === CertificateRenewalKeySource.Csr;
+ const requestedAltNames = certificateRequest.subjectAlternativeNames ?? [];
+
+ let renewalCsr: string;
+ if (isCsrAuthoritative) {
+ renewalCsr = csr as string;
+ } else if (certificateSecret) {
+ renewalCsr = await buildCsrFromExistingKey({
+ privateKeyPem: await $decryptCertificatePrivateKey({
+ projectId: originalCert.projectId,
+ encryptedPrivateKey: certificateSecret.encryptedPrivateKey
+ }),
+ keyAlgorithm: effectiveKeyAlgorithm,
+ certificateRequest
+ });
+ } else {
+ if (originalCert.altNames && requestedAltNames.length === 0) {
+ throw new BadRequestError({
+ message:
+ "Every subject alternative name cannot be removed while reusing this certificate's key pair, because Infisical does not hold its private key and can only renew from the original signing request. Supply a CSR with the names you want, or renew with a new key pair."
+ });
+ }
+ renewalCsr = originalCsr as string;
+ }
+
+ const subjectOverride = buildRenewalDistinguishedName(certificateRequest);
+
+ const shouldIssueAsCA = certificateRequest.basicConstraints?.isCA === true;
+ const caBasicConstraints = shouldIssueAsCA
+ ? { isCA: true, pathLength: policy?.basicConstraints?.maxPathLength }
+ : undefined;
+
+ const pendingRequest = await certificateRequestService.createCertificateRequest({
+ internal: true,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId: originalCert.projectId,
+ caId: ca.id,
+ profileId: originalCert.profileId ?? undefined,
+ applicationId: originalCert.applicationId ?? undefined,
+ csr: renewalCsr,
+ commonName: certificateRequest.commonName,
+ altNames: requestedAltNames.length > 0 ? requestedAltNames : undefined,
+ keyUsages: certificateRequest.keyUsages,
+ extendedKeyUsages: certificateRequest.extendedKeyUsages,
+ notBefore,
+ notAfter,
+ keyAlgorithm: effectiveKeyAlgorithm,
+ signatureAlgorithm: effectiveSignatureAlgorithm,
+ metadata: `Renewed from certificate ID: ${originalCert.id}`,
+ status: CertificateRequestStatus.PENDING,
+ ttl,
+ enrollmentType: EnrollmentType.API,
+ organization: certificateRequest.organization,
+ organizationalUnit: certificateRequest.organizationalUnit,
+ country: certificateRequest.country,
+ state: certificateRequest.state,
+ locality: certificateRequest.locality,
+ domainComponents: certificateRequest.domainComponents,
+ ...(certificateRequest.basicConstraints && { basicConstraints: certificateRequest.basicConstraints })
+ });
+
+ let certResult: Awaited<ReturnType<typeof internalCaService.signCertFromCa>>;
+ try {
+ certResult = await internalCaService.signCertFromCa({
+ isInternal: true,
+ caId: ca.id,
+ csr: renewalCsr,
+ subjectOverride,
+ commonName: certificateRequest.commonName,
+ altNames: isCsrAuthoritative ? undefined : requestedAltNames.map((san) => san.value).join(","),
+ basicConstraints: caBasicConstraints,
+ pathLength: certificateRequest.basicConstraints?.pathLength,
+ ttl,
+ notBefore: normalizeDateForApi(notBefore),
+ notAfter: normalizeDateForApi(notAfter),
+ keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages),
+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages),
+ signatureAlgorithm: effectiveSignatureAlgorithm,
+ keyAlgorithm: effectiveKeyAlgorithm,
+ isFromProfile: true,
+ onPersisted: async (newCert, tx) => {
+ if (keySource === CertificateRenewalKeySource.Reuse && certificateSecret) {
+ await certificateSecretDAL.create(
+ { certId: newCert.id, encryptedPrivateKey: certificateSecret.encryptedPrivateKey },
+ tx
+ );
+ }
+
+ await attachCertificateToPendingRequest(
+ certificateRequestDAL,
+ {
+ certificateRequestId: pendingRequest.id,
+ certificateId: newCert.id,
+ projectId: originalCert.projectId,
+ operation: CertificateIssuanceOperation.RENEW
+ },
+ tx
+ );
+
+ await $linkRenewedCertificate(
+ {
+ newCert,
+ originalCert,
+ finalRenewBeforeDays,
+ certificateRequestId: pendingRequest.id,
+ certificateRequestCreatedAt: pendingRequest.createdAt,
+ orgId: actorOrgId
+ },
+ tx
+ );
+ }
+ });
+ } catch (err) {
+ await markPendingRequestFailed(certificateRequestDAL, {
+ certificateRequestId: pendingRequest.id,
+ error: err,
+ fallbackMessage: "Certificate renewal failed"
+ });
+ throw err;
+ }
+
+ return $finalizeRenewal({
+ newCertificateId: certResult.certificateId,
+ originalCert,
+ profile: profile ?? null,
+ certificate: extractCertificateFromBuffer(certResult.certificate as unknown as Buffer),
+ issuingCaCertificate: extractCertificateFromBuffer(certResult.issuingCaCertificate as unknown as Buffer),
+ certificateChain: extractCertificateFromBuffer(certResult.certificateChain as unknown as Buffer),
+ serialNumber: certResult.serialNumber,
+ certificateRequestId: pendingRequest.id,
+ commonName: certResult.commonName || "",
+ fallbackProfileName: "Renewed Certificate",
+ removeRootsFromChain,
+ actor,
+ actorId,
+ actorOrgId
+ });
+ };
+
+ const $loadRenewalSubject = async (
+ { certificateId, keySource }: { certificateId: string; keySource: CertificateRenewalKeySource },
+ tx: Knex
+ ) => {
+ const originalCert = await certificateDAL.findById(certificateId, tx);
+ if (!originalCert) {
+ throw new NotFoundError({ message: "Certificate not found" });
+ }
+
+ if (!originalCert.profileId) {
+ throw new ForbiddenRequestError({
+ message: "Only certificates issued from a profile can be renewed"
+ });
+ }
+
+ const originalSignatureAlgorithm = Object.values(CertSignatureAlgorithm).includes(
+ originalCert.signatureAlgorithm as CertSignatureAlgorithm
+ )
+ ? (originalCert.signatureAlgorithm as CertSignatureAlgorithm)
+ : undefined;
+ const originalKeyAlgorithm = Object.values(CertKeyAlgorithm).includes(originalCert.keyAlgorithm as CertKeyAlgorithm)
+ ? (originalCert.keyAlgorithm as CertKeyAlgorithm)
+ : undefined;
+
+ const profile = await certificateProfileDAL.findByIdWithConfigs(originalCert.profileId, tx);
+ if (!profile) {
+ throw new NotFoundError({ message: "Certificate profile not found" });
+ }
+
+ const originatingRequest = await certificateDAL.getOriginatingRequestByCertId(originalCert.id, tx);
+ const { enrollmentType } = originatingRequest;
+ if (enrollmentType && enrollmentType !== EnrollmentType.API) {
+ throw new ForbiddenRequestError({
+ message: `Certificate is not eligible for renewal: ${enrollmentType.toUpperCase()} certificates cannot be renewed`
+ });
+ }
+
+ const certificateSecret = await certificateSecretDAL.findOne({ certId: originalCert.id }, tx);
+ const originalCsr =
+ !certificateSecret && keySource === CertificateRenewalKeySource.Reuse ? originatingRequest.csr : null;
+
+ if (keySource === CertificateRenewalKeySource.Reuse && !certificateSecret && !originalCsr) {
+ throw new BadRequestError({
+ message:
+ "This certificate's key pair cannot be reused because Infisical holds neither its private key nor the signing request it was issued from. Renew with a new key pair, or for a CA-issued certificate supply a CSR generated from the existing key."
+ });
+ }
+
+ return {
+ originalCert,
+ profile,
+ certificateSecret,
+ originalCsr,
+ originalSignatureAlgorithm,
+ originalKeyAlgorithm
+ };
+ };
+
+ const $authorizeRenewal = async ({
+ originalCert,
+ profile,
+ actorCtx
+ }: {
+ originalCert: { applicationId?: string | null };
+ profile: { id: string; projectId: string; slug: string };
+ actorCtx: TRenewalActor;
+ }) => {
+ if (originalCert.applicationId) {
+ await $resolveApplicationIdForProfile(profile, originalCert.applicationId, actorCtx, EnrollmentType.API);
+ return;
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ ...actorCtx,
+ projectId: profile.projectId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateProfileActions.IssueCert,
+ subject(ProjectPermissionSub.CertificateProfiles, { slug: profile.slug })
+ );
+ };
+
+ const $resolveRenewalIssuer = async (
+ {
+ originalCert,
+ profile,
+ actorCtx,
+ internal
+ }: {
+ originalCert: TCertificates;
+ profile: TCertificateProfileWithConfigs;
+ actorCtx: TRenewalActor;
+ internal: boolean;
+ },
+ tx: Knex
+ ) => {
+ const issuerType = profile.issuerType || (originalCert.caId ? IssuerType.CA : IssuerType.SELF_SIGNED);
+
+ let ca: TCertificateAuthorityWithAssociatedCa | undefined;
+ let caType: CaType | undefined;
+ if (issuerType === IssuerType.CA) {
+ const caId = profile.caId || originalCert.caId;
+ if (!caId) {
+ throw new NotFoundError({ message: "Certificate Authority ID not found" });
+ }
+
+ ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId, tx);
+ if (!ca) {
+ throw new NotFoundError({ message: "Certificate Authority not found" });
+ }
+
+ assertCaInProfileProject(ca, profile);
+
+ const eligibilityCheck = validateRenewalEligibility(originalCert, ca);
+ if (!eligibilityCheck.isEligible) {
+ const renewalError = `Certificate is not eligible for renewal: ${eligibilityCheck.errors.join(", ")}`;
+ await certificateDAL.updateById(originalCert.id, { renewalError }, tx);
+ throw new BadRequestError({ message: renewalError });
+ }
+
+ caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;
+ if (caType === CaType.INTERNAL) {
+ validateCaSupport(ca, "direct certificate issuance");
+ }
+ }
+
+ const policyId = profile.certificatePolicyId || originalCert.certificateTemplateId;
+ const policy = policyId ? await certificatePolicyService.getPolicyById({ ...actorCtx, policyId, internal }) : null;
+
+ if (!policy) {
+ throw new NotFoundError({ message: "Certificate policy not found for this profile" });
+ }
+
+ return { issuerType, ca, caType, policy };
+ };
+
+ const $buildValidatedRenewalRequest = async (
+ {
+ originalCert,
+ policy,
+ csrRenewalRequest,
+ attributes,
+ keySource
+ }: {
+ originalCert: TCertificates;
+ policy: Parameters<TCertificatePolicyServiceFactory["validateRequestAgainstPolicy"]>[0];
+ csrRenewalRequest: TCertificateRequest | null;
+ attributes?: TRenewCertificateDTO["attributes"];
+ keySource: CertificateRenewalKeySource;
+ },
+ tx: Knex
+ ) => {
+ const originalTtl = certificateSpanToTtl(originalCert.notBefore, originalCert.notAfter);
+
+ const originalRequest: TCertificateRequest = {
+ commonName: originalCert.commonName || undefined,
+ organization: originalCert.subjectOrganization || undefined,
+ organizationalUnit: originalCert.subjectOrganizationalUnit || undefined,
+ country: originalCert.subjectCountry || undefined,
+ state: originalCert.subjectState || undefined,
+ locality: originalCert.subjectLocality || undefined,
+ domainComponents: originalCert.subjectDomainComponents
+ ? originalCert.subjectDomainComponents.split(",")
+ : undefined,
+ keyUsages: parseKeyUsages(originalCert.keyUsages),
+ extendedKeyUsages: parseExtendedKeyUsages(originalCert.extendedKeyUsages),
+ subjectAlternativeNames: originalCert.altNames
+ ? originalCert.altNames.split(",").map((san) => detectSanType(san.trim()))
+ : [],
+ validity: { ttl: originalTtl },
+ signatureAlgorithm: originalCert.signatureAlgorithm || undefined,
+ keyAlgorithm: originalCert.keyAlgorithm || undefined,
+ ...(originalCert.isCA && {
+ basicConstraints: { isCA: true, pathLength: originalCert.pathLength ?? undefined }
+ })
+ };
+
+ const mergedRequest =
+ csrRenewalRequest ?? buildRenewalCertificateRequest({ original: originalRequest, attributes });
+
+ if (
+ keySource === CertificateRenewalKeySource.Reuse &&
+ attributes?.keyAlgorithm &&
+ attributes.keyAlgorithm !== originalCert.keyAlgorithm
+ ) {
+ throw new BadRequestError({
+ message: `The key algorithm cannot be changed to '${attributes.keyAlgorithm}' while reusing the existing key pair, which is '${originalCert.keyAlgorithm}'. Renew with a new key pair to change it.`
+ });
+ }
+
+ const ttl = mergedRequest.validity?.ttl || originalTtl;
+ const certificateRequest = { ...mergedRequest, validity: { ttl } };
+
+ const validationResult = certificatePolicyService.validateRequestAgainstPolicy(policy, certificateRequest);
+ if (!validationResult.isValid) {
+ await certificateDAL.updateById(
+ originalCert.id,
+ { renewalError: `Policy validation failed: ${validationResult.errors.join(", ")}` },
+ tx
+ );
+ throw new BadRequestError({
+ message: `Certificate renewal failed. Errors: ${validationResult.errors.join(", ")}`
+ });
+ }
+
+ return { certificateRequest, ttl };
+ };
+
+ const $assertKeySourceSupported = ({
+ keySource,
+ issuerType,
+ caType,
+ hasStoredKey
+ }: {
+ keySource: CertificateRenewalKeySource;
+ issuerType: IssuerType;
+ caType?: CaType;
+ hasStoredKey: boolean;
+ }) => {
+ if (keySource === CertificateRenewalKeySource.New) return;
+
+ if (issuerType !== IssuerType.CA) {
+ if (keySource === CertificateRenewalKeySource.Csr) {
+ throw new BadRequestError({
+ message:
+ "Self-signed certificates cannot be renewed from a signing request, because signing one requires the private key that a request does not carry. Reuse the existing key pair, or renew with a new one."
+ });
+ }
+ if (!hasStoredKey) {
+ throw new BadRequestError({
+ message:
+ "This self-signed certificate's key pair cannot be reused because Infisical does not hold its private key, which is what signs a self-signed certificate. Renew with a new key pair."
+ });
+ }
+ return;
+ }
+
+ if (keySource === CertificateRenewalKeySource.Reuse && caType !== CaType.INTERNAL) {
+ throw new BadRequestError({
+ message: `Certificates issued by a ${caType?.toUpperCase() ?? "external"} certificate authority cannot reuse their existing key pair on renewal. Renew with a new key pair, or supply a CSR generated from the existing key.`
+ });
+ }
+ };
+
+ const renewCertificate = async ({
+ certificateId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ internal = false,
+ removeRootsFromChain,
+ renewalKeySource: requestedKeySource,
+ csr,
+ attributes
+ }: Omit<TRenewCertificateDTO, "certificateRequestId"> & {
+ internal?: boolean;
+ }): Promise<TCertificateIssuanceResponse> => {
+ const actorCtx: TRenewalActor = { actor, actorId, actorAuthMethod, actorOrgId };
+ const keySource = resolveRenewalKeySource({ renewalKeySource: requestedKeySource, csr });
+ let csrRenewalRequest: TCertificateRequest | null = null;
+ if (keySource === CertificateRenewalKeySource.Csr && csr) {
+ assertCsrRenewalAttributes(attributes);
+ csrRenewalRequest = buildCsrRenewalCertificateRequest({ csr, attributes });
+ }
+
+ const renewalResult = await certificateDAL.transaction(async (tx) => {
+ const {
+ originalCert,
+ profile,
+ certificateSecret,
+ originalCsr,
+ originalSignatureAlgorithm,
+ originalKeyAlgorithm
+ } = await $loadRenewalSubject({ certificateId, keySource }, tx);
+
+ if (!internal) {
+ await $authorizeRenewal({ originalCert, profile, actorCtx });
+ }
+
+ const { issuerType, ca, caType, policy } = await $resolveRenewalIssuer(
+ { originalCert, profile, actorCtx, internal },
+ tx
+ );
+
+ const { certificateRequest, ttl } = await $buildValidatedRenewalRequest(
+ { originalCert, policy, csrRenewalRequest, attributes, keySource },
+ tx
+ );
+
+ const notBefore = new Date();
+ const notAfter = new Date(Date.now() + ms(ttl));
+
+ const effectiveApiConfig = await resolveEffectiveApiConfig({
+ applicationId: originalCert.applicationId ?? undefined,
+ profileId: profile.id,
+ profileApiConfig: profile.apiConfig,
+ pkiApplicationProfileDAL,
+ apiEnrollmentConfigDAL
+ });
+ const finalRenewBeforeDays = resolveRenewedCertificateRenewBeforeDays({
+ apiConfig: effectiveApiConfig,
+ previousRenewBeforeDays: originalCert.renewBeforeDays,
+ ttl,
+ notAfter
+ });
+
+ const { signatureAlgorithm: effectiveSignatureAlgorithm, keyAlgorithm: effectiveKeyAlgorithm } =
+ getEffectiveAlgorithms(
+ certificateRequest.signatureAlgorithm as CertSignatureAlgorithm,
+ certificateRequest.keyAlgorithm as CertKeyAlgorithm,
+ originalSignatureAlgorithm,
+ originalKeyAlgorithm
+ );
+ const renewalAltNames = certificateRequest.subjectAlternativeNames ?? [];
+ const renewalBasicConstraints = certificateRequest.basicConstraints?.isCA
+ ? { isCA: true, pathLength: certificateRequest.basicConstraints.pathLength }
+ : undefined;
+
+ $assertKeySourceSupported({ keySource, issuerType, caType, hasStoredKey: Boolean(certificateSecret) });
+
+ if (keySource !== CertificateRenewalKeySource.New && caType === CaType.INTERNAL && ca) {
+ validateCaSupport(ca, "CSR signing");
+ validateAlgorithmCompatibility(ca, { algorithms: policy?.algorithms } as {
+ algorithms?: { signature?: string[] };
+ });
+
+ return {
+ renewalMode: CertificateRenewalMode.KeyPreserving as const,
+ keySource,
+ csr,
+ ca,
+ profile,
+ policy,
+ originalCert,
+ certificateRequest,
+ certificateSecret,
+ originalCsr,
+ ttl,
+ notBefore,
+ notAfter,
+ finalRenewBeforeDays,
+ effectiveKeyAlgorithm,
+ effectiveSignatureAlgorithm
+ };
+ }
+
+ let certificate: string;
+ let certificateChain: string;
+ let issuingCaCertificate: string;
+ let serialNumber: string;
+ let newCert: TCertificates;
+
+ if (issuerType === IssuerType.CA) {
+ if (!ca) {
+ throw new NotFoundError({ message: "Certificate Authority not found for CA-signed certificate renewal" });
+ }
+
+ if (caType === CaType.INTERNAL) {
+ validateAlgorithmCompatibility(ca, {
+ algorithms: policy.algorithms
+ } as { algorithms?: { signature?: string[] } });
+
+ const caResult = await internalCaService.issueCertFromCa({
+ caId: ca.id,
+ friendlyName: originalCert.friendlyName || certificateRequest.commonName || "Renewed Certificate",
+ commonName: certificateRequest.commonName || "",
+ altNames: renewalAltNames.map((san) => san.value).join(","),
+ ...(renewalBasicConstraints && {
+ basicConstraints: { isCA: true, pathLength: policy?.basicConstraints?.maxPathLength },
+ pathLength: renewalBasicConstraints.pathLength
+ }),
+ ttl,
+ notBefore: normalizeDateForApi(notBefore),
+ notAfter: normalizeDateForApi(notAfter),
+ keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages),
+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages),
+ signatureAlgorithm: effectiveSignatureAlgorithm,
+ keyAlgorithm: effectiveKeyAlgorithm,
+ isFromProfile: true,
+ organization: certificateRequest.organization,
+ ou: certificateRequest.organizationalUnit,
+ country: certificateRequest.country,
+ state: certificateRequest.state,
+ locality: certificateRequest.locality,
+ domainComponents: certificateRequest.domainComponents,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ internal: true,
+ tx
+ });
+
+ certificate = caResult.certificate;
+ certificateChain = caResult.certificateChain;
+ issuingCaCertificate = caResult.issuingCaCertificate;
+ serialNumber = caResult.serialNumber;
+
+ const foundCert = await certificateDAL.findById(caResult.certificateId, tx);
+ if (!foundCert) {
+ throw new NotFoundError({ message: "Certificate was signed but could not be found in database" });
+ }
+ newCert = foundCert;
+ } else if (caType && caSupportsCapability(caType, CaCapability.RENEW_CERTIFICATES)) {
+ return {
+ renewalMode: CertificateRenewalMode.ExternalCa as const,
+ ca,
+ profile,
+ originalCert,
+ certificateRequest,
+ renewalAltNames,
+ renewalBasicConstraints,
+ effectiveSignatureAlgorithm,
+ effectiveKeyAlgorithm,
+ ttl
+ };
+ } else {
+ throw new BadRequestError({
+ message: `CA type ${String(caType)} does not support certificate renewal`
+ });
+ }
+ } else {
+ const existingKeyPair =
+ keySource === CertificateRenewalKeySource.Reuse && certificateSecret
+ ? await importKeyPairFromPem({
+ privateKeyPem: await $decryptCertificatePrivateKey({
+ projectId: originalCert.projectId,
+ encryptedPrivateKey: certificateSecret.encryptedPrivateKey
+ }),
+ keyAlgorithm: effectiveKeyAlgorithm
+ })
+ : undefined;
+
+ const selfSignedRenewalResult = await processSelfSignedCertificate({
+ certificateRequest: { ...certificateRequest, altNames: renewalAltNames },
+ policy,
+ profile,
+ originalCert,
+ effectiveAlgorithms: {
+ signatureAlgorithm: effectiveSignatureAlgorithm,
+ keyAlgorithm: effectiveKeyAlgorithm
+ },
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ kmsService,
+ projectDAL,
+ tx,
+ isRenewal: true,
+ existingKeyPair
+ });
+
+ certificate = selfSignedRenewalResult.selfSignedResult.certificate.toString("utf8");
+ certificateChain = selfSignedRenewalResult.selfSignedResult.certificate.toString("utf8"); // Self-signed has no chain
+ issuingCaCertificate = ""; // No issuing CA for self-signed
+ serialNumber = selfSignedRenewalResult.selfSignedResult.serialNumber;
+ newCert = selfSignedRenewalResult.certificateData;
+ }
+
+ const certRequestResult = await certificateRequestService.createCertificateRequest({
+ internal: true,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId: originalCert.projectId,
+ tx,
+ caId: ca?.id || originalCert.caId || undefined,
+ profileId: originalCert.profileId || undefined,
+ applicationId: originalCert.applicationId ?? undefined,
+ commonName: certificateRequest.commonName,
+ altNames: renewalAltNames.length > 0 ? renewalAltNames : undefined,
+ keyUsages: certificateRequest.keyUsages,
+ extendedKeyUsages: certificateRequest.extendedKeyUsages,
+ notBefore: new Date(newCert.notBefore),
+ notAfter: new Date(newCert.notAfter),
+ keyAlgorithm: effectiveKeyAlgorithm,
+ signatureAlgorithm: effectiveSignatureAlgorithm,
+ metadata: `Renewed from certificate ID: ${originalCert.id}`,
+ status: CertificateRequestStatus.ISSUED,
+ certificateId: newCert.id,
+ ttl,
+ enrollmentType: EnrollmentType.API,
+ organization: certificateRequest.organization,
+ organizationalUnit: certificateRequest.organizationalUnit,
+ country: certificateRequest.country,
+ state: certificateRequest.state,
+ locality: certificateRequest.locality,
+ domainComponents: certificateRequest.domainComponents,
+ ...(renewalBasicConstraints && { basicConstraints: renewalBasicConstraints })
+ });
+
+ await $linkRenewedCertificate(
+ {
+ newCert,
+ originalCert,
+ finalRenewBeforeDays,
+ isRenewalLinkPreset: issuerType !== IssuerType.CA,
+ certificateRequestId: certRequestResult.id,
+ certificateRequestCreatedAt: certRequestResult.createdAt,
+ orgId: actorOrgId
+ },
+ tx
+ );
+
+ return {
+ renewalMode: CertificateRenewalMode.Signed as const,
+ certificate,
+ certificateChain,
+ issuingCaCertificate,
+ serialNumber,
+ newCert,
+ originalCert,
+ profile,
+ certRequestResult
+ };
+ });
+
+ if (renewalResult.renewalMode === CertificateRenewalMode.KeyPreserving) {
+ return $completeKeyPreservingRenewal({
+ ...renewalResult,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ removeRootsFromChain
+ });
+ }
+
+ if (renewalResult.renewalMode === CertificateRenewalMode.ExternalCa) {
+ const {
+ ca,
+ profile,
+ originalCert,
+ certificateRequest: renewalRequest,
+ renewalAltNames: structuredAltNames,
+ renewalBasicConstraints,
+ effectiveSignatureAlgorithm,
+ effectiveKeyAlgorithm,
+ ttl
+ } = renewalResult;
+
+ const renewalOrderId = randomUUID();
+
+ const certificateRequest = await certificateRequestService.createCertificateRequest({
+ internal: true,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId: originalCert.projectId,
+ profileId: profile?.id,
+ applicationId: originalCert.applicationId ?? undefined,
+ caId: ca.id,
+ csr,
+ commonName: renewalRequest.commonName,
+ altNames: structuredAltNames.length > 0 ? structuredAltNames : undefined,
+ keyUsages: renewalRequest.keyUsages,
+ extendedKeyUsages: renewalRequest.extendedKeyUsages,
+ keyAlgorithm: effectiveKeyAlgorithm,
+ signatureAlgorithm: effectiveSignatureAlgorithm,
+ metadata: `Renewed from certificate ID: ${originalCert.id}`,
+ status: CertificateRequestStatus.PENDING,
+ ttl,
+ enrollmentType: EnrollmentType.API,
+ organization: renewalRequest.organization,
+ organizationalUnit: renewalRequest.organizationalUnit,
+ country: renewalRequest.country,
+ state: renewalRequest.state,
+ locality: renewalRequest.locality,
+ domainComponents: renewalRequest.domainComponents,
+ basicConstraints: renewalBasicConstraints
+ });
+
+ await copyMetadataFromCertificate(resourceMetadataDAL, {
+ sourceCertificateId: originalCert.id,
+ targetCertificateRequestId: certificateRequest.id,
+ targetCertificateRequestCreatedAt: certificateRequest.createdAt,
+ orgId: actorOrgId
+ });
+
+ await certificateIssuanceQueue.queueCertificateIssuance({
+ certificateId: renewalOrderId,
+ profileId: profile?.id || "",
+ caId: ca.id,
+ caType: (ca.externalCa?.type as CaType) ?? CaType.INTERNAL,
+ commonName: renewalRequest.commonName || "",
+ altNames: structuredAltNames,
+ ttl,
+ signatureAlgorithm: effectiveSignatureAlgorithm,
+ keyAlgorithm: effectiveKeyAlgorithm,
+ keyUsages: (renewalRequest.keyUsages ?? []).map(mapKeyUsageToLegacy),
+ extendedKeyUsages: (renewalRequest.extendedKeyUsages ?? []).map(mapExtendedKeyUsageToLegacy),
+ organization: renewalRequest.organization,
+ organizationalUnit: renewalRequest.organizationalUnit,
+ country: renewalRequest.country,
+ state: renewalRequest.state,
+ locality: renewalRequest.locality,
+ isRenewal: true,
+ originalCertificateId: certificateId,
+ certificateRequestId: certificateRequest.id,
+ basicConstraints: renewalBasicConstraints,
+ ...(csr && { csr }),
+ ...(originalCert.applicationId && { applicationId: originalCert.applicationId })
+ });
+
+ return {
+ status: CertificateRequestStatus.PENDING,
+ certificate: "", // External CA renewal is async
+ certificateChain: "",
+ issuingCaCertificate: "",
+ serialNumber: "",
+ certificateId: renewalOrderId,
+ certificateRequestId: certificateRequest.id,
+ projectId: originalCert.projectId,
+ profileName: profile?.slug || "External CA Profile",
+ commonName: renewalRequest.commonName || ""
+ };
+ }
+
+ return $finalizeRenewal({
+ newCertificateId: renewalResult.newCert.id,
+ originalCert: renewalResult.originalCert,
+ profile: renewalResult.profile ?? null,
+ certificate: renewalResult.certificate,
+ issuingCaCertificate: renewalResult.issuingCaCertificate,
+ certificateChain: renewalResult.certificateChain,
+ serialNumber: renewalResult.serialNumber,
+ certificateRequestId: renewalResult.certRequestResult?.id || "",
+ commonName: renewalResult.newCert.commonName || "",
+ fallbackProfileName: "Self-signed Certificate",
+ removeRootsFromChain,
+ actor,
+ actorId,
+ actorOrgId
+ });
+ };
+
+ const $loadCertificateForRenewalConfig = async ({
+ certificateId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: {
+ certificateId: string;
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ }) => {
+ const certificate = await certificateDAL.findById(certificateId);
+ if (!certificate) {
+ throw new NotFoundError({ message: "Certificate not found" });
+ }
+
+ await assertCanEditCertificate({
+ certificate,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ permissionService,
+ resourceMetadataDAL
+ });
+
+ if (!certificate.profileId) {
+ throw new BadRequestError({
+ message: "Certificate is not eligible for auto-renewal: certificate was not issued from a profile"
+ });
+ }
+
+ return certificate;
+ };
+
+ const updateRenewalConfig = async ({
+ certificateId,
+ renewBeforeDays,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TUpdateRenewalConfigDTO): Promise<TRenewalConfigResponse> => {
+ const certificate = await $loadCertificateForRenewalConfig({
+ certificateId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ const enrollmentType = await certificateDAL.getRequestEnrollmentTypeByCertId(certificate.id);
+ if (enrollmentType && enrollmentType !== EnrollmentType.API) {
+ throw new ForbiddenRequestError({
+ message: `Certificate is not eligible for auto-renewal: ${enrollmentType.toUpperCase()} certificates cannot be auto-renewed`
+ });
+ }
+
+ const certificateSecret = await certificateSecretDAL.findOne({ certId: certificate.id });
+ if (!certificateSecret) {
+ throw new ForbiddenRequestError({
+ message:
+ "Certificate is not eligible for auto-renewal: certificates issued from CSR (external private key) cannot be auto-renewed"
+ });
+ }
+
+ if (certificate.status !== CertStatus.ACTIVE) {
+ throw new BadRequestError({
+ message: `Certificate is not eligible for auto-renewal: certificate status is ${certificate.status}, must be ${CertStatus.ACTIVE}`
+ });
+ }
+
+ const now = new Date();
+ if (certificate.notAfter <= now) {
+ throw new BadRequestError({
+ message: "Certificate is not eligible for auto-renewal: certificate has expired"
+ });
+ }
+
+ if (certificate.revokedAt) {
+ throw new BadRequestError({
+ message: "Certificate is not eligible for auto-renewal: certificate has been revoked"
+ });
+ }
+
+ if (certificate.renewedByCertificateId) {
+ throw new BadRequestError({
+ message: "Certificate is not eligible for auto-renewal: certificate has already been renewed"
+ });
+ }
+
+ const certificateTtlInDays = Math.ceil(
+ (new Date(certificate.notAfter).getTime() - new Date(certificate.notBefore).getTime()) / (24 * 60 * 60 * 1000)
+ );
+
+ if (renewBeforeDays >= certificateTtlInDays) {
+ throw new BadRequestError({
+ message: "Invalid renewal configuration: renewal threshold exceeds certificate validity period"
+ });
+ }
+
+ if (!isValidRenewalTiming(renewBeforeDays, new Date(certificate.notAfter))) {
+ throw new BadRequestError({
+ message: "Invalid renewal configuration: renewal would be triggered immediately or in the past"
+ });
+ }
+
+ await certificateDAL.updateById(certificateId, { renewBeforeDays });
+
+ return {
+ projectId: certificate.projectId,
+ renewBeforeDays,
+ commonName: certificate.commonName || ""
+ };
+ };
+
+ const disableRenewalConfig = async ({
+ certificateId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TDisableRenewalConfigDTO): Promise<TDisableRenewalResponse> => {
+ const certificate = await $loadCertificateForRenewalConfig({
+ certificateId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ await certificateDAL.updateById(certificateId, { renewBeforeDays: null });
+
+ return {
+ projectId: certificate.projectId,
+ commonName: certificate.commonName || ""
+ };
+ };
+
+ return {
+ renewCertificate,
+ updateRenewalConfig,
+ disableRenewalConfig
+ };
+};
diff --git a/backend/src/services/certificate-v3/certificate-self-signed-fns.ts b/backend/src/services/certificate-v3/certificate-self-signed-fns.ts
new file mode 100644
index 0000000000..472e36d60b
--- /dev/null
+++ b/backend/src/services/certificate-v3/certificate-self-signed-fns.ts
@@ -0,0 +1,260 @@
+import { BadRequestError } from "@app/lib/errors";
+import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
+import { extractCertificateFields } from "@app/services/certificate/certificate-fns";
+import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
+import { CertKeyAlgorithm, CertSignatureAlgorithm, CertStatus } from "@app/services/certificate/certificate-types";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+
+import {
+ CertExtendedKeyUsageType,
+ CertKeyUsageType,
+ CertSubjectAlternativeNameType
+} from "../certificate-common/certificate-constants";
+import { generateSelfSignedCertificate } from "../certificate-common/certificate-issuance-utils";
+import {
+ convertExtendedKeyUsageArrayToLegacy,
+ convertKeyUsageArrayToLegacy
+} from "../certificate-common/certificate-utils";
+
+const createSelfSignedCertificateRecord = async ({
+ selfSignedResult,
+ certificateRequest,
+ profile,
+ originalCert,
+ certificateDAL,
+ tx,
+ isRenewal = false
+}: {
+ selfSignedResult: Awaited<ReturnType<typeof generateSelfSignedCertificate>>;
+ certificateRequest: {
+ commonName?: string;
+ keyUsages?: CertKeyUsageType[];
+ extendedKeyUsages?: CertExtendedKeyUsageType[];
+ };
+ profile?: { id: string; projectId: string } | null;
+ originalCert?: {
+ id: string;
+ friendlyName?: string | null;
+ commonName?: string | null;
+ projectId: string;
+ };
+ certificateDAL: Pick<TCertificateDALFactory, "create" | "updateById">;
+ tx: Parameters<TCertificateDALFactory["create"]>[1];
+ isRenewal?: boolean;
+}) => {
+ const subjectCommonName =
+ (selfSignedResult.certificateSubject.common_name as string) ||
+ certificateRequest.commonName ||
+ originalCert?.commonName ||
+ "";
+
+ const altNamesList = selfSignedResult.subjectAlternativeNames.map((san) => san.value).join(",");
+
+ const projectId = originalCert?.projectId || profile?.projectId;
+ if (!projectId) {
+ throw new BadRequestError({ message: "Project ID is required for certificate creation" });
+ }
+
+ const baseRecord = {
+ serialNumber: selfSignedResult.serialNumber,
+ friendlyName: originalCert?.friendlyName || subjectCommonName,
+ commonName: subjectCommonName,
+ altNames: altNamesList,
+ status: CertStatus.ACTIVE,
+ notBefore: selfSignedResult.notBefore,
+ notAfter: selfSignedResult.notAfter,
+ projectId,
+ keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
+ profileId: profile?.id || null
+ };
+
+ const renewalRecord =
+ isRenewal && originalCert
+ ? {
+ renewedFromCertificateId: originalCert.id
+ }
+ : {};
+
+ const parsedFields = extractCertificateFields(selfSignedResult.certificate);
+
+ return certificateDAL.create(
+ {
+ ...baseRecord,
+ ...renewalRecord,
+ ...parsedFields
+ },
+ tx
+ );
+};
+
+const createEncryptedCertificateData = async ({
+ certificateId,
+ certificate,
+ privateKey,
+ projectId,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ kmsService,
+ projectDAL,
+ tx
+}: {
+ certificateId: string;
+ certificate: Buffer;
+ privateKey: Buffer;
+ projectId: string;
+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
+ kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;
+ projectDAL: TProjectDALFactory;
+ tx: Parameters<TCertificateBodyDALFactory["create"]>[1];
+}) => {
+ const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
+ projectId,
+ projectDAL,
+ kmsService
+ });
+
+ const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKeyId });
+
+ const encryptedCertificate = await kmsEncryptor({
+ plainText: certificate
+ });
+
+ await certificateBodyDAL.create(
+ {
+ certId: certificateId,
+ encryptedCertificate: encryptedCertificate.cipherTextBlob
+ },
+ tx
+ );
+
+ const encryptedPrivateKey = await kmsEncryptor({
+ plainText: privateKey
+ });
+
+ await certificateSecretDAL.create(
+ {
+ certId: certificateId,
+ encryptedPrivateKey: encryptedPrivateKey.cipherTextBlob
+ },
+ tx
+ );
+};
+
+export const processSelfSignedCertificate = async ({
+ certificateRequest,
+ policy,
+ profile,
+ originalCert,
+ effectiveAlgorithms,
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ kmsService,
+ projectDAL,
+ tx,
+ isRenewal = false,
+ existingKeyPair
+}: {
+ certificateRequest: {
+ commonName?: string;
+ organization?: string;
+ organizationalUnit?: string;
+ country?: string;
+ state?: string;
+ locality?: string;
+ domainComponents?: string[];
+ keyUsages?: CertKeyUsageType[];
+ extendedKeyUsages?: CertExtendedKeyUsageType[];
+ altNames?: Array<{ type: CertSubjectAlternativeNameType; value: string }>;
+ validity: { ttl: string };
+ notBefore?: Date;
+ notAfter?: Date;
+ };
+ policy?: {
+ subject?: Array<{
+ type: string;
+ allowed?: string[];
+ required?: string[];
+ denied?: string[];
+ }>;
+ sans?: Array<{
+ type: string;
+ allowed?: string[];
+ required?: string[];
+ denied?: string[];
+ }>;
+ } | null;
+ profile?: { id: string; projectId: string } | null;
+ originalCert?: {
+ id: string;
+ friendlyName?: string | null;
+ commonName?: string | null;
+ projectId: string;
+ };
+ effectiveAlgorithms: {
+ signatureAlgorithm: CertSignatureAlgorithm;
+ keyAlgorithm: CertKeyAlgorithm;
+ };
+ certificateDAL: Pick<TCertificateDALFactory, "create" | "updateById">;
+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
+ kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;
+ projectDAL: TProjectDALFactory;
+ tx: Parameters<TCertificateDALFactory["create"]>[1];
+ isRenewal?: boolean;
+ existingKeyPair?: CryptoKeyPair;
+}) => {
+ const projectId = originalCert?.projectId || profile?.projectId;
+ if (!projectId) {
+ throw new BadRequestError({ message: "Project ID is required for certificate creation" });
+ }
+
+ const selfSignedResult = await generateSelfSignedCertificate({
+ certificateRequest,
+ policy,
+ effectiveSignatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,
+ effectiveKeyAlgorithm: effectiveAlgorithms.keyAlgorithm,
+ existingKeyPair
+ });
+
+ const certificateData = await createSelfSignedCertificateRecord({
+ selfSignedResult,
+ certificateRequest,
+ profile,
+ originalCert,
+ certificateDAL,
+ tx,
+ isRenewal
+ });
+
+ await certificateDAL.updateById(
+ certificateData.id,
+ {
+ signatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,
+ keyAlgorithm: effectiveAlgorithms.keyAlgorithm
+ },
+ tx
+ );
+
+ await createEncryptedCertificateData({
+ certificateId: certificateData.id,
+ certificate: selfSignedResult.certificate,
+ privateKey: selfSignedResult.privateKey,
+ projectId,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ kmsService,
+ projectDAL,
+ tx
+ });
+
+ return {
+ selfSignedResult,
+ certificateData
+ };
+};
diff --git a/backend/src/services/certificate-v3/certificate-v3-fns.ts b/backend/src/services/certificate-v3/certificate-v3-fns.ts
index c41f4b21d5..f605187a58 100644
--- a/backend/src/services/certificate-v3/certificate-v3-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-fns.ts
@@ -2,7 +2,14 @@ import RE2 from "re2";
import { BadRequestError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
-
+import { CertExtendedKeyUsage, CertKeyUsage } from "@app/services/certificate/certificate-types";
+
+import {
+ CertExtendedKeyUsageType,
+ CertKeyUsageType,
+ mapLegacyExtendedKeyUsageToStandard,
+ mapLegacyKeyUsageToStandard
+} from "../certificate-common/certificate-constants";
import { TCertificateProfileDefaults } from "../certificate-profile/certificate-profile-types";
export const parseTtlToDays = (ttl: string): number => {
@@ -152,3 +159,56 @@ export const applyProfileDefaults = <
altNames
};
};
+
+export const parseKeyUsages = (keyUsages: unknown): CertKeyUsageType[] => {
+ if (!keyUsages) return [];
+
+ const validKeyUsages = [...Object.values(CertKeyUsageType), ...Object.values(CertKeyUsage)] as string[];
+
+ const normalize = (usage: string): CertKeyUsageType | null => {
+ if (validKeyUsages.includes(usage)) {
+ return mapLegacyKeyUsageToStandard(usage as CertKeyUsageType);
+ }
+ return null;
+ };
+
+ let raw: string[];
+
+ if (Array.isArray(keyUsages)) {
+ raw = keyUsages.filter((u): u is string => typeof u === "string");
+ } else if (typeof keyUsages === "string") {
+ raw = keyUsages.split(",").map((u) => u.trim());
+ } else {
+ return [];
+ }
+
+ return raw.map((u) => normalize(u)).filter((u): u is CertKeyUsageType => u !== null);
+};
+
+export const parseExtendedKeyUsages = (extendedKeyUsages: unknown): CertExtendedKeyUsageType[] => {
+ if (!extendedKeyUsages) return [];
+
+ const validExtendedKeyUsages = [
+ ...Object.values(CertExtendedKeyUsageType),
+ ...Object.values(CertExtendedKeyUsage)
+ ] as string[];
+
+ const normalize = (usage: string): CertExtendedKeyUsageType | null => {
+ if (validExtendedKeyUsages.includes(usage)) {
+ return mapLegacyExtendedKeyUsageToStandard(usage as CertExtendedKeyUsageType);
+ }
+ return null;
+ };
+
+ let raw: string[];
+
+ if (Array.isArray(extendedKeyUsages)) {
+ raw = extendedKeyUsages.filter((u): u is string => typeof u === "string");
+ } else if (typeof extendedKeyUsages === "string") {
+ raw = extendedKeyUsages.split(",").map((u) => u.trim());
+ } else {
+ return [];
+ }
+
+ return raw.map((u) => normalize(u)).filter((u): u is CertExtendedKeyUsageType => u !== null);
+};
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 a2d1eec48e..a9f10042f4 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -34,6 +34,7 @@ import {
extractCertificateRequestFromCSR
} from "../certificate-common/certificate-csr-utils";
import { certificateV3ServiceFactory, TCertificateV3ServiceFactory } from "./certificate-v3-service";
+import { CertificateRenewalKeySource } from "./certificate-v3-types";
vi.mock("../certificate-common/certificate-csr-utils", () => ({
extractCertificateRequestFromCSR: vi.fn(),
@@ -68,12 +69,20 @@ describe("CertificateV3Service", () => {
const mockCertificateDAL: Pick<
TCertificateDALFactory,
- "findOne" | "findById" | "updateById" | "transaction" | "create" | "find" | "getRequestEnrollmentTypeByCertId"
+ | "findOne"
+ | "findById"
+ | "updateById"
+ | "transaction"
+ | "create"
+ | "find"
+ | "getRequestEnrollmentTypeByCertId"
+ | "getOriginatingRequestByCertId"
> = {
findOne: vi.fn(),
findById: vi.fn(),
updateById: vi.fn(),
getRequestEnrollmentTypeByCertId: vi.fn().mockResolvedValue(null),
+ getOriginatingRequestByCertId: vi.fn().mockResolvedValue({ enrollmentType: null, csr: null }),
create: vi.fn().mockResolvedValue({
id: "new-cert-id",
serialNumber: "123456789",
@@ -117,9 +126,10 @@ describe("CertificateV3Service", () => {
const mockCertificatePolicyService: Pick<
TCertificatePolicyServiceFactory,
- "validateCertificateRequest" | "getPolicyById"
+ "validateCertificateRequest" | "validateRequestAgainstPolicy" | "getPolicyById"
> = {
validateCertificateRequest: vi.fn(),
+ validateRequestAgainstPolicy: vi.fn().mockReturnValue({ isValid: true, errors: [] }),
getPolicyById: vi.fn()
};
@@ -198,6 +208,10 @@ describe("CertificateV3Service", () => {
return callback(mockTx);
});
vi.mocked(mockCertificateDAL.getRequestEnrollmentTypeByCertId).mockResolvedValue(null);
+ vi.mocked(mockCertificateDAL.getOriginatingRequestByCertId).mockResolvedValue({
+ enrollmentType: null,
+ csr: null
+ });
mockCertificateIssuanceQueue.queueCertificateIssuance.mockResolvedValue(undefined);
mockCertificateRequestService.createCertificateRequest.mockResolvedValue({ id: "cert-req-123" });
@@ -1987,7 +2001,7 @@ describe("CertificateV3Service", () => {
vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
- vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
+ vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
isValid: true,
errors: [],
warnings: []
@@ -2052,7 +2066,7 @@ describe("CertificateV3Service", () => {
...mockPolicy,
basicConstraints: { isCA: "allowed", maxPathLength: 2 }
} as any);
- vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
+ vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
isValid: true,
errors: [],
warnings: []
@@ -2094,7 +2108,7 @@ describe("CertificateV3Service", () => {
vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
- vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
+ vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
isValid: false,
errors: ["Requested path length (3) exceeds maximum allowed by policy (2)."],
warnings: []
@@ -2104,8 +2118,8 @@ describe("CertificateV3Service", () => {
"exceeds maximum allowed by policy"
);
- expect(mockCertificatePolicyService.validateCertificateRequest).toHaveBeenCalledWith(
- "policy-123",
+ expect(mockCertificatePolicyService.validateRequestAgainstPolicy).toHaveBeenCalledWith(
+ mockPolicy,
expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 3 } })
);
expect(mockInternalCaService.issueCertFromCa).not.toHaveBeenCalled();
@@ -2116,7 +2130,7 @@ describe("CertificateV3Service", () => {
vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
- vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
+ vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
isValid: false,
errors: ["Subject alternative name not allowed"],
warnings: []
@@ -2181,10 +2195,14 @@ describe("CertificateV3Service", () => {
).rejects.toThrow("Only certificates issued from a profile can be renewed");
});
- it("should reject renewal if certificate was issued from CSR (external private key)", async () => {
+ it("refuses to reuse a key pair it holds neither the key nor the signing request for", async () => {
vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue(null as any);
+ vi.mocked(mockCertificateDAL.getOriginatingRequestByCertId).mockResolvedValue({
+ enrollmentType: EnrollmentType.API,
+ csr: null
+ });
vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
const mockTx = {};
@@ -2194,22 +2212,19 @@ describe("CertificateV3Service", () => {
await expect(
service.renewCertificate({
certificateId: "cert-123",
+ renewalKeySource: CertificateRenewalKeySource.Reuse,
...mockActor
})
- ).rejects.toThrow(ForbiddenRequestError);
-
- await expect(
- service.renewCertificate({
- certificateId: "cert-123",
- ...mockActor
- })
- ).rejects.toThrow("certificates issued from CSR (external private key) cannot be renewed");
+ ).rejects.toThrow("cannot be reused");
});
it("should reject renewal for a protocol-enrolled certificate", async () => {
vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
- vi.mocked(mockCertificateDAL.getRequestEnrollmentTypeByCertId).mockResolvedValue(EnrollmentType.ACME);
+ vi.mocked(mockCertificateDAL.getOriginatingRequestByCertId).mockResolvedValue({
+ enrollmentType: EnrollmentType.ACME,
+ csr: null
+ });
vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
await expect(
@@ -2402,7 +2417,7 @@ describe("CertificateV3Service", () => {
vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
- vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
+ vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
isValid: true,
errors: [],
warnings: []
@@ -2478,13 +2493,7 @@ describe("CertificateV3Service", () => {
commonName: ""
});
- expect(mockCertificateDAL.updateById).toHaveBeenCalledWith(
- "cert-123",
- {
- renewBeforeDays: 7
- },
- expect.anything()
- );
+ expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", { renewBeforeDays: 7 });
});
it("should reject update if certificate is not from profile", async () => {
@@ -2606,7 +2615,7 @@ describe("CertificateV3Service", () => {
renewBeforeDays: 7,
commonName: ""
});
- expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", { renewBeforeDays: 7 }, expect.anything());
+ expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", { renewBeforeDays: 7 });
});
it("should reject update for a protocol-enrolled certificate regardless of key presence", async () => {
@@ -2725,13 +2734,7 @@ describe("CertificateV3Service", () => {
commonName: ""
});
- expect(mockCertificateDAL.updateById).toHaveBeenCalledWith(
- "cert-123",
- {
- renewBeforeDays: null
- },
- expect.anything()
- );
+ expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", { renewBeforeDays: null });
});
it("should reject disable if certificate is not from profile", async () => {
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index efca384285..a466d60cda 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -1,8 +1,7 @@
import { ForbiddenError, subject } from "@casl/ability";
import { randomUUID } from "crypto";
-import RE2 from "re2";
-import { ActionProjectType, ResourceType, TCertificates } from "@app/db/schemas";
+import { ActionProjectType, ResourceType } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
@@ -15,7 +14,7 @@ import {
ResourcePermissionSub
} from "@app/ee/services/permission/resource-permission";
import { TPkiAcmeAccountDALFactory } from "@app/ee/services/pki-acme/pki-acme-account-dal";
-import { BadRequestError, ForbiddenRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { ms } from "@app/lib/ms";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
@@ -31,22 +30,12 @@ import {
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 { extractCertificateFields } from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
-import {
- CertExtendedKeyUsage,
- CertKeyAlgorithm,
- CertKeyUsage,
- CertSignatureAlgorithm,
- CertStatus
-} from "@app/services/certificate/certificate-types";
+import { CertKeyAlgorithm, CertSignatureAlgorithm } from "@app/services/certificate/certificate-types";
import { validateAcmIssuanceInputs } from "@app/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns";
import { validateAwsPcaCaIssuanceInputs } from "@app/services/certificate-authority/aws-pca/aws-pca-certificate-authority-validators";
-import {
- TCertificateAuthorityDALFactory,
- TCertificateAuthorityWithAssociatedCa
-} from "@app/services/certificate-authority/certificate-authority-dal";
-import { CaStatus, CaType } from "@app/services/certificate-authority/certificate-authority-enums";
+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 { validateGoDaddyIssuanceInputs } from "@app/services/certificate-authority/godaddy/godaddy-certificate-authority-validators";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
@@ -59,19 +48,13 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { TUserDALFactory } from "@app/services/user/user-dal";
import {
- CertExtendedKeyUsageType,
CertificateIssuanceOperation,
CertKeyUsageType,
- CertPolicyState,
- mapExtendedKeyUsageToLegacy,
- mapKeyUsageToLegacy,
- mapLegacyExtendedKeyUsageToStandard,
- mapLegacyKeyUsageToStandard
+ CertPolicyState
} from "../certificate-common/certificate-constants";
import {
buildSubjectOverrideForCsr,
@@ -80,15 +63,13 @@ import {
} from "../certificate-common/certificate-csr-utils";
import {
calculateFinalRenewBeforeDays,
- detectSanType,
extractCertificateFromBuffer,
- generateSelfSignedCertificate,
getEffectiveAlgorithms,
- isValidRenewalTiming,
resolveEffectiveApiConfig,
validateAlgorithmCompatibility,
validateCaSupport
} from "../certificate-common/certificate-issuance-utils";
+import { assertCanEditCertificate } from "../certificate-common/certificate-permission-fns";
import { reportCertificateIssued } from "../certificate-common/certificate-telemetry-fns";
import {
bufferToString,
@@ -103,37 +84,43 @@ import {
} from "../certificate-common/certificate-utils";
import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
import { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";
+import {
+ attachCertificateToPendingRequest,
+ markPendingRequestFailed
+} from "../certificate-request/certificate-request-fns";
import { TCertificateRequestServiceFactory } from "../certificate-request/certificate-request-service";
import { CertificateRequestStatus } from "../certificate-request/certificate-request-types";
import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
import { TPkiApplicationProfileDALFactory } from "../pki-application/pki-application-profile-dal";
import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
-import { addRenewedCertificateToSyncs, triggerAutoSyncForCertificate } from "../pki-sync/pki-sync-utils";
import { TResourceMetadataDALFactory } from "../resource-metadata/resource-metadata-dal";
import {
- copyMetadataFromCertificate,
insertMetadataForCertificate,
insertMetadataForCertificateRequest
} from "../resource-metadata/resource-metadata-fns";
+import { certificateRenewalServiceFactory } from "./certificate-renewal-service";
+import { processSelfSignedCertificate } from "./certificate-self-signed-fns";
import { applyProfileDefaults, resolveEffectiveTtl } from "./certificate-v3-fns";
import {
TCertificateIssuanceResponse,
- TDisableRenewalConfigDTO,
- TDisableRenewalResponse,
TIssueCertificateFromProfileDTO,
TOrderCertificateFromProfileDTO,
- TRenewalConfigResponse,
- TRenewCertificateDTO,
TSignCertificateFromProfileDTO,
- TUpdateCertificateDTO,
- TUpdateRenewalConfigDTO
+ TUpdateCertificateDTO
} from "./certificate-v3-types";
type TCertificateV3ServiceFactoryDep = {
certificateDAL: Pick<
TCertificateDALFactory,
- "findOne" | "findById" | "updateById" | "transaction" | "create" | "find" | "getRequestEnrollmentTypeByCertId"
+ | "findOne"
+ | "findById"
+ | "updateById"
+ | "transaction"
+ | "create"
+ | "find"
+ | "getRequestEnrollmentTypeByCertId"
+ | "getOriginatingRequestByCertId"
>;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;
@@ -143,7 +130,10 @@ type TCertificateV3ServiceFactoryDep = {
>;
certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs" | "findById">;
acmeAccountDAL: Pick<TPkiAcmeAccountDALFactory, "findById">;
- certificatePolicyService: Pick<TCertificatePolicyServiceFactory, "validateCertificateRequest" | "getPolicyById">;
+ certificatePolicyService: Pick<
+ TCertificatePolicyServiceFactory,
+ "validateCertificateRequest" | "validateRequestAgainstPolicy" | "getPolicyById"
+ >;
internalCaService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa" | "issueCertFromCa">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
certificateSyncDAL: Pick<
@@ -289,398 +279,6 @@ const validateProfileAndPermissions = async ({
return profile;
};
-const validateRenewalEligibility = (
- certificate: {
- id: string;
- status: string;
- notBefore: Date;
- notAfter: Date;
- revokedAt?: Date | null;
- renewedByCertificateId?: string | null;
- profileId?: string | null;
- caId?: string | null;
- pkiSubscriberId?: string | null;
- },
- ca: TCertificateAuthorityWithAssociatedCa
-) => {
- const errors: string[] = [];
-
- if (certificate.status !== CertStatus.ACTIVE) {
- errors.push(`Certificate status is ${certificate.status}, must be ${CertStatus.ACTIVE}`);
- }
-
- const now = new Date();
- if (certificate.notAfter <= now) {
- errors.push("Certificate is already expired");
- }
-
- if (certificate.revokedAt) {
- errors.push("Certificate is revoked and cannot be renewed");
- }
-
- const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;
- const isInternalCa = caType === CaType.INTERNAL;
- const isConnectedExternalCa =
- caType === CaType.ACME ||
- caType === CaType.AZURE_AD_CS ||
- caType === CaType.ADCS ||
- caType === CaType.AWS_PCA ||
- caType === CaType.AWS_ACM_PUBLIC_CA ||
- caType === CaType.DIGICERT ||
- caType === CaType.VENAFI_TPP ||
- caType === CaType.GODADDY;
- const isImportedCertificate = certificate.pkiSubscriberId != null && !certificate.profileId;
-
- if (!isInternalCa && !isConnectedExternalCa) {
- errors.push(`CA type ${String(caType)} does not support renewal`);
- }
-
- if (isImportedCertificate) {
- errors.push("Externally imported certificates cannot be renewed");
- }
-
- if (ca.status !== CaStatus.ACTIVE) {
- errors.push(`Certificate Authority is ${ca.status}, must be ${CaStatus.ACTIVE}`);
- }
-
- if (certificate.renewedByCertificateId) {
- errors.push("Certificate has already been renewed");
- }
-
- const certificateTtlInDays = Math.ceil(
- (certificate.notAfter.getTime() - certificate.notBefore.getTime()) / (24 * 60 * 60 * 1000)
- );
-
- if (ca.internalCa?.notAfter) {
- const caExpiryDate = new Date(ca.internalCa.notAfter);
- const proposedCertExpiryDate = new Date(now.getTime() + certificateTtlInDays * 24 * 60 * 60 * 1000);
-
- if (proposedCertExpiryDate > caExpiryDate) {
- errors.push(
- `New certificate would expire (${proposedCertExpiryDate.toISOString()}) after its issuing CA (${caExpiryDate.toISOString()})`
- );
- }
- }
-
- return {
- isEligible: errors.length === 0,
- errors
- };
-};
-
-const parseKeyUsages = (keyUsages: unknown): CertKeyUsageType[] => {
- if (!keyUsages) return [];
-
- const validKeyUsages = [...Object.values(CertKeyUsageType), ...Object.values(CertKeyUsage)] as string[];
-
- const normalize = (usage: string): CertKeyUsageType | null => {
- if (validKeyUsages.includes(usage)) {
- return mapLegacyKeyUsageToStandard(usage as CertKeyUsageType);
- }
- return null;
- };
-
- let raw: string[];
-
- if (Array.isArray(keyUsages)) {
- raw = keyUsages.filter((u): u is string => typeof u === "string");
- } else if (typeof keyUsages === "string") {
- raw = keyUsages.split(",").map((u) => u.trim());
- } else {
- return [];
- }
-
- return raw.map((u) => normalize(u)).filter((u): u is CertKeyUsageType => u !== null);
-};
-
-const parseExtendedKeyUsages = (extendedKeyUsages: unknown): CertExtendedKeyUsageType[] => {
- if (!extendedKeyUsages) return [];
-
- const validExtendedKeyUsages = [
- ...Object.values(CertExtendedKeyUsageType),
- ...Object.values(CertExtendedKeyUsage)
- ] as string[];
-
- const normalize = (usage: string): CertExtendedKeyUsageType | null => {
- if (validExtendedKeyUsages.includes(usage)) {
- return mapLegacyExtendedKeyUsageToStandard(usage as CertExtendedKeyUsageType);
- }
- return null;
- };
-
- let raw: string[];
-
- if (Array.isArray(extendedKeyUsages)) {
- raw = extendedKeyUsages.filter((u): u is string => typeof u === "string");
- } else if (typeof extendedKeyUsages === "string") {
- raw = extendedKeyUsages.split(",").map((u) => u.trim());
- } else {
- return [];
- }
-
- return raw.map((u) => normalize(u)).filter((u): u is CertExtendedKeyUsageType => u !== null);
-};
-
-const createSelfSignedCertificateRecord = async ({
- selfSignedResult,
- certificateRequest,
- profile,
- originalCert,
- certificateDAL,
- tx,
- isRenewal = false
-}: {
- selfSignedResult: Awaited<ReturnType<typeof generateSelfSignedCertificate>>;
- certificateRequest: {
- commonName?: string;
- keyUsages?: CertKeyUsageType[];
- extendedKeyUsages?: CertExtendedKeyUsageType[];
- };
- profile?: { id: string; projectId: string } | null;
- originalCert?: {
- id: string;
- friendlyName?: string | null;
- commonName?: string | null;
- projectId: string;
- };
- certificateDAL: Pick<TCertificateDALFactory, "create" | "updateById">;
- tx: Parameters<TCertificateDALFactory["create"]>[1];
- isRenewal?: boolean;
-}) => {
- const subjectCommonName =
- (selfSignedResult.certificateSubject.common_name as string) ||
- certificateRequest.commonName ||
- originalCert?.commonName ||
- "";
-
- const altNamesList = selfSignedResult.subjectAlternativeNames.map((san) => san.value).join(",");
-
- const projectId = originalCert?.projectId || profile?.projectId;
- if (!projectId) {
- throw new BadRequestError({ message: "Project ID is required for certificate creation" });
- }
-
- const baseRecord = {
- serialNumber: selfSignedResult.serialNumber,
- friendlyName: originalCert?.friendlyName || subjectCommonName,
- commonName: subjectCommonName,
- altNames: altNamesList,
- status: CertStatus.ACTIVE,
- notBefore: selfSignedResult.notBefore,
- notAfter: selfSignedResult.notAfter,
- projectId,
- keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
- extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
- profileId: profile?.id || null
- };
-
- const renewalRecord =
- isRenewal && originalCert
- ? {
- renewedFromCertificateId: originalCert.id
- }
- : {};
-
- // Extract certificate fields for storage
- const parsedFields = extractCertificateFields(selfSignedResult.certificate);
-
- return certificateDAL.create(
- {
- ...baseRecord,
- ...renewalRecord,
- ...parsedFields
- },
- tx
- );
-};
-
-const createEncryptedCertificateData = async ({
- certificateId,
- certificate,
- privateKey,
- projectId,
- certificateBodyDAL,
- certificateSecretDAL,
- kmsService,
- projectDAL,
- tx
-}: {
- certificateId: string;
- certificate: Buffer;
- privateKey: Buffer;
- projectId: string;
- certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
- certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
- kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;
- projectDAL: TProjectDALFactory;
- tx: Parameters<TCertificateBodyDALFactory["create"]>[1];
-}) => {
- const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
- projectId,
- projectDAL,
- kmsService
- });
-
- const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKeyId });
-
- const encryptedCertificate = await kmsEncryptor({
- plainText: certificate
- });
-
- await certificateBodyDAL.create(
- {
- certId: certificateId,
- encryptedCertificate: encryptedCertificate.cipherTextBlob
- },
- tx
- );
-
- const encryptedPrivateKey = await kmsEncryptor({
- plainText: privateKey
- });
-
- await certificateSecretDAL.create(
- {
- certId: certificateId,
- encryptedPrivateKey: encryptedPrivateKey.cipherTextBlob
- },
- tx
- );
-};
-
-const parseTtlToMs = (ttl: string): number => {
- const regex = new RE2("^(\\d+)(s|m|h|d)$");
- const match = regex.exec(ttl);
-
- if (!match) throw new Error(`Invalid TTL format: ${ttl}`);
-
- const value = parseInt(match[1], 10);
- const unit = match[2];
-
- switch (unit) {
- case "s":
- return value * 1000;
- case "m":
- return value * 60 * 1000;
- case "h":
- return value * 60 * 60 * 1000;
- case "d":
- return value * 24 * 60 * 60 * 1000;
- default:
- throw new Error(`Unknown TTL unit: ${unit}`);
- }
-};
-
-const processSelfSignedCertificate = async ({
- certificateRequest,
- policy,
- profile,
- originalCert,
- effectiveAlgorithms,
- certificateDAL,
- certificateBodyDAL,
- certificateSecretDAL,
- kmsService,
- projectDAL,
- tx,
- isRenewal = false
-}: {
- certificateRequest: {
- commonName?: string;
- organization?: string;
- organizationalUnit?: string;
- country?: string;
- state?: string;
- locality?: string;
- domainComponents?: string[];
- keyUsages?: CertKeyUsageType[];
- extendedKeyUsages?: CertExtendedKeyUsageType[];
- validity: { ttl: string };
- notBefore?: Date;
- notAfter?: Date;
- };
- policy?: {
- subject?: Array<{
- type: string;
- allowed?: string[];
- required?: string[];
- denied?: string[];
- }>;
- sans?: Array<{
- type: string;
- allowed?: string[];
- required?: string[];
- denied?: string[];
- }>;
- } | null;
- profile?: { id: string; projectId: string } | null;
- originalCert?: {
- id: string;
- friendlyName?: string | null;
- commonName?: string | null;
- projectId: string;
- };
- effectiveAlgorithms: {
- signatureAlgorithm: CertSignatureAlgorithm;
- keyAlgorithm: CertKeyAlgorithm;
- };
- certificateDAL: Pick<TCertificateDALFactory, "create" | "updateById">;
- certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
- certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
- kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;
- projectDAL: TProjectDALFactory;
- tx: Parameters<TCertificateDALFactory["create"]>[1];
- isRenewal?: boolean;
-}) => {
- const projectId = originalCert?.projectId || profile?.projectId;
- if (!projectId) {
- throw new BadRequestError({ message: "Project ID is required for certificate creation" });
- }
-
- const selfSignedResult = await generateSelfSignedCertificate({
- certificateRequest,
- policy,
- effectiveSignatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,
- effectiveKeyAlgorithm: effectiveAlgorithms.keyAlgorithm
- });
-
- const certificateData = await createSelfSignedCertificateRecord({
- selfSignedResult,
- certificateRequest,
- profile,
- originalCert,
- certificateDAL,
- tx,
- isRenewal
- });
-
- await certificateDAL.updateById(
- certificateData.id,
- {
- signatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,
- keyAlgorithm: effectiveAlgorithms.keyAlgorithm
- },
- tx
- );
-
- await createEncryptedCertificateData({
- certificateId: certificateData.id,
- certificate: selfSignedResult.certificate,
- privateKey: selfSignedResult.privateKey,
- projectId,
- certificateBodyDAL,
- certificateSecretDAL,
- kmsService,
- projectDAL,
- tx
- });
-
- return {
- selfSignedResult,
- certificateData
- };
-};
-
export const certificateV3ServiceFactory = ({
certificateDAL,
certificateBodyDAL,
@@ -1946,16 +1544,16 @@ export const certificateV3ServiceFactory = ({
// cancelled request can never silently yield an issued certificate. The signature itself is
// wasted, which is the right trade: an unstored signature costs an HSM operation and a
// serial, whereas committing would hand back a certificate nothing accounts for.
- const attachedRequest = await certificateRequestDAL.attachCertificate(pendingRequest.id, newCert.id, tx);
- if (!attachedRequest) {
- logger.error(
- { certificateRequestId: pendingRequest.id, projectId: profile.projectId },
- `Certificate request left a pending status during signing, aborting issuance [certificateRequestId=${pendingRequest.id}]`
- );
- throw new InternalServerError({
- message: "Certificate request is no longer pending, so issuance was aborted"
- });
- }
+ await attachCertificateToPendingRequest(
+ certificateRequestDAL,
+ {
+ certificateRequestId: pendingRequest.id,
+ certificateId: newCert.id,
+ projectId: profile.projectId,
+ operation: CertificateIssuanceOperation.SIGN
+ },
+ tx
+ );
if (metadata && metadata.length > 0) {
await insertMetadataForCertificate(resourceMetadataDAL, {
@@ -1975,21 +1573,11 @@ export const certificateV3ServiceFactory = ({
}
});
} catch (err) {
- // The request row is why this is recoverable. Mark it failed so the attempt is accounted for
- // rather than disappearing silently. This is best-effort bookkeeping on an already-failing path,
- // so its own failure must not replace the error the caller actually needs to see.
- try {
- await certificateRequestDAL.transitionFromPending(
- pendingRequest.id,
- CertificateRequestStatus.FAILED,
- err instanceof Error ? err.message : "Certificate issuance failed"
- );
- } catch (bookkeepingErr) {
- logger.error(
- bookkeepingErr,
- `Failed to mark certificate request as failed [certificateRequestId=${pendingRequest.id}]`
- );
- }
+ await markPendingRequestFailed(certificateRequestDAL, {
+ certificateRequestId: pendingRequest.id,
+ error: err,
+ fallbackMessage: "Certificate issuance failed"
+ });
throw err;
}
@@ -2444,926 +2032,89 @@ export const certificateV3ServiceFactory = ({
});
};
- const renewCertificate = async ({
+ const updateCertificate = async ({
certificateId,
+ metadata,
actor,
actorId,
actorAuthMethod,
- actorOrgId,
- internal = false,
- removeRootsFromChain
- }: Omit<TRenewCertificateDTO, "certificateRequestId"> & {
- internal?: boolean;
- }): Promise<TCertificateIssuanceResponse> => {
- const renewalResult = await certificateDAL.transaction(async (tx) => {
- const originalCert = await certificateDAL.findById(certificateId, tx);
- if (!originalCert) {
- throw new NotFoundError({ message: "Certificate not found" });
- }
-
- if (!originalCert.profileId) {
- throw new ForbiddenRequestError({
- message: "Only certificates issued from a profile can be renewed"
- });
- }
-
- // Validate and cast algorithms with fallbacks
- let originalSignatureAlgorithm = Object.values(CertSignatureAlgorithm).includes(
- originalCert.signatureAlgorithm as CertSignatureAlgorithm
- )
- ? (originalCert.signatureAlgorithm as CertSignatureAlgorithm)
- : CertSignatureAlgorithm.RSA_SHA256;
- let originalKeyAlgorithm = Object.values(CertKeyAlgorithm).includes(originalCert.keyAlgorithm as CertKeyAlgorithm)
- ? (originalCert.keyAlgorithm as CertKeyAlgorithm)
- : CertKeyAlgorithm.RSA_2048;
-
- // For external CA certificates without stored algorithm info, extract from certificate
- if (!originalSignatureAlgorithm || !originalKeyAlgorithm) {
- const isExternalCA = originalCert.caId && !originalCert.caId.startsWith("internal");
-
- if (isExternalCA) {
- // For external CA certificates, we can extract algorithm info from the cert or use defaults
- originalSignatureAlgorithm = originalSignatureAlgorithm || CertSignatureAlgorithm.RSA_SHA256;
- originalKeyAlgorithm = originalKeyAlgorithm || CertKeyAlgorithm.RSA_2048;
- } else {
- throw new BadRequestError({
- message:
- "Original certificate does not have algorithm information stored. Cannot renew certificate issued before algorithm tracking was implemented."
- });
- }
- }
-
- let profile = null;
- if (originalCert.profileId) {
- profile = await certificateProfileDAL.findByIdWithConfigs(originalCert.profileId);
- if (!profile) {
- throw new NotFoundError({ message: "Certificate profile not found" });
- }
- }
-
- const enrollmentType = await certificateDAL.getRequestEnrollmentTypeByCertId(originalCert.id, tx);
- if (enrollmentType && enrollmentType !== EnrollmentType.API) {
- throw new ForbiddenRequestError({
- message: `Certificate is not eligible for renewal: ${enrollmentType.toUpperCase()} certificates cannot be renewed`
- });
- }
-
- const certificateSecret = await certificateSecretDAL.findOne({ certId: originalCert.id }, tx);
- if (!certificateSecret) {
- throw new ForbiddenRequestError({
- message:
- "Certificate is not eligible for renewal: certificates issued from CSR (external private key) cannot be renewed"
- });
- }
-
- if (!internal) {
- const projectId = profile?.projectId || originalCert.projectId;
-
- if (originalCert.applicationId) {
- const originalProfile = await certificateProfileDAL.findByIdWithConfigs(originalCert.profileId);
- if (!originalProfile) {
- throw new NotFoundError({ message: "Original certificate profile not found" });
- }
- await $resolveApplicationIdForProfile(
- originalProfile,
- originalCert.applicationId,
- {
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- },
- EnrollmentType.API
- );
- } else if (profile) {
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
- });
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionCertificateProfileActions.IssueCert,
- subject(ProjectPermissionSub.CertificateProfiles, { slug: profile.slug })
- );
- }
- }
-
- const issuerType = profile?.issuerType || (originalCert.caId ? IssuerType.CA : IssuerType.SELF_SIGNED);
-
- let ca;
- if (issuerType === IssuerType.CA) {
- const caId = profile?.caId || originalCert.caId;
- if (!caId) {
- throw new NotFoundError({ message: "Certificate Authority ID not found" });
- }
-
- ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
- if (!ca) {
- throw new NotFoundError({ message: "Certificate Authority not found" });
- }
-
- assertCaInProfileProject(ca, profile ?? originalCert);
-
- const eligibilityCheck = validateRenewalEligibility(originalCert, ca);
- if (!eligibilityCheck.isEligible) {
- await certificateDAL.updateById(
- originalCert.id,
- {
- renewalError: `Certificate is not eligible for renewal: ${eligibilityCheck.errors.join(", ")}`
- },
- tx
- );
- throw new BadRequestError({
- message: `Certificate is not eligible for renewal: ${eligibilityCheck.errors.join(", ")}`
- });
- }
-
- const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;
- if (caType === CaType.INTERNAL) {
- validateCaSupport(ca, "direct certificate issuance");
- }
- }
-
- const policyId = profile?.certificatePolicyId || originalCert.certificateTemplateId;
- const policy = policyId
- ? await certificatePolicyService.getPolicyById({
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- policyId,
- internal
- })
- : null;
-
- if (!policy && profile) {
- throw new NotFoundError({ message: "Certificate policy not found for this profile" });
- }
-
- const getSimpleTtl = (startDate: Date, endDate: Date): string => {
- const diffMs = endDate.getTime() - startDate.getTime();
-
- const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));
- if (days > 0) return `${days}d`;
-
- const hours = Math.floor(diffMs / (1000 * 60 * 60));
- if (hours > 0) return `${hours}h`;
-
- const minutes = Math.floor(diffMs / (1000 * 60));
- if (minutes > 0) return `${minutes}m`;
+ actorOrgId
+ }: TUpdateCertificateDTO) => {
+ const certificate = await certificateDAL.findById(certificateId);
+ if (!certificate) {
+ throw new NotFoundError({ message: "Certificate not found" });
+ }
- const seconds = Math.floor(diffMs / 1000);
- return `${seconds}s`;
- };
+ const { projectPermission } = await assertCanEditCertificate({
+ certificate,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ permissionService,
+ resourceMetadataDAL
+ });
- const ttl = getSimpleTtl(originalCert.notBefore, originalCert.notAfter);
-
- const certificateRequest = {
- commonName: originalCert.commonName || undefined,
- organization: originalCert.subjectOrganization || undefined,
- organizationalUnit: originalCert.subjectOrganizationalUnit || undefined,
- country: originalCert.subjectCountry || undefined,
- state: originalCert.subjectState || undefined,
- locality: originalCert.subjectLocality || undefined,
- domainComponents: originalCert.subjectDomainComponents
- ? originalCert.subjectDomainComponents.split(",")
- : undefined,
- keyUsages: parseKeyUsages(originalCert.keyUsages),
- extendedKeyUsages: parseExtendedKeyUsages(originalCert.extendedKeyUsages),
- subjectAlternativeNames: originalCert.altNames
- ? originalCert.altNames.split(",").map((san) => detectSanType(san.trim()))
- : [],
- validity: {
- ttl
- },
- signatureAlgorithm: originalCert.signatureAlgorithm || undefined,
- keyAlgorithm: originalCert.keyAlgorithm || undefined,
- ...(originalCert.isCA && {
- basicConstraints: { isCA: true, pathLength: originalCert.pathLength ?? undefined }
+ if (metadata && projectPermission) {
+ ForbiddenError.from(projectPermission).throwUnlessCan(
+ ProjectPermissionCertificateActions.Edit,
+ subject(ProjectPermissionSub.Certificates, {
+ commonName: certificate.commonName,
+ altNames: certificate.altNames?.split(",").map((s) => s.trim()),
+ serialNumber: certificate.serialNumber,
+ metadata
})
- };
+ );
+ }
- let validationResult: { isValid: boolean; errors: string[] } = { isValid: true, errors: [] };
- if (profile?.certificatePolicyId) {
- validationResult = await certificatePolicyService.validateCertificateRequest(
- profile.certificatePolicyId,
- certificateRequest
- );
- }
+ let updatedMetadata: Array<{ key: string; value: string }> = [];
- if (!validationResult.isValid) {
- await certificateDAL.updateById(
- originalCert.id,
- {
- renewalError: `Policy validation failed: ${validationResult.errors.join(", ")}`
- },
+ if (metadata) {
+ await certificateDAL.transaction(async (tx) => {
+ await resourceMetadataDAL.delete({ certificateId }, tx);
+ await insertMetadataForCertificate(resourceMetadataDAL, {
+ metadata,
+ certificateId,
+ orgId: actorOrgId,
tx
- );
-
- throw new BadRequestError({
- message: `Certificate renewal failed. Errors: ${validationResult.errors.join(", ")}`
});
- }
-
- const notBefore = new Date();
- const notAfter = new Date(Date.now() + parseTtlToMs(ttl));
-
- const effectiveApiConfig = profile
- ? await resolveEffectiveApiConfig({
- applicationId: originalCert.applicationId ?? undefined,
- profileId: profile.id,
- profileApiConfig: profile.apiConfig,
- pkiApplicationProfileDAL,
- apiEnrollmentConfigDAL
- })
- : undefined;
- const finalRenewBeforeDays = profile
- ? calculateFinalRenewBeforeDays({ apiConfig: effectiveApiConfig }, ttl, notAfter)
- : undefined;
-
- let certificate: string;
- let certificateChain: string;
- let issuingCaCertificate: string;
- let serialNumber: string;
- let newCert: TCertificates;
-
- if (issuerType === IssuerType.CA) {
- // CA-signed certificate renewal
- if (!ca) {
- throw new NotFoundError({ message: "Certificate Authority not found for CA-signed certificate renewal" });
- }
-
- const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;
+ });
+ updatedMetadata = metadata;
+ }
- // Only validate algorithm compatibility for internal CAs
- if (caType === CaType.INTERNAL) {
- validateAlgorithmCompatibility(ca, {
- algorithms: policy?.algorithms
- } as { algorithms?: { signature?: string[] } });
- }
+ return { metadata: updatedMetadata, projectId: certificate.projectId, commonName: certificate.commonName };
+ };
- if (caType === CaType.INTERNAL) {
- // Internal CA renewal - existing logic
- const caResult = await internalCaService.issueCertFromCa({
- caId: ca.id,
- friendlyName: originalCert.friendlyName || originalCert.commonName || "Renewed Certificate",
- commonName: originalCert.commonName || "",
- altNames: originalCert.altNames || "",
- ...(originalCert.isCA && {
- basicConstraints: { isCA: true, pathLength: policy?.basicConstraints?.maxPathLength },
- pathLength: originalCert.pathLength ?? undefined
- }),
- ttl,
- notBefore: normalizeDateForApi(notBefore),
- notAfter: normalizeDateForApi(notAfter),
- keyUsages: convertKeyUsageArrayToLegacy(parseKeyUsages(originalCert.keyUsages)),
- extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(
- parseExtendedKeyUsages(originalCert.extendedKeyUsages)
- ),
- signatureAlgorithm: originalSignatureAlgorithm,
- keyAlgorithm: originalKeyAlgorithm,
- isFromProfile: true,
- organization: originalCert.subjectOrganization || undefined,
- ou: originalCert.subjectOrganizationalUnit || undefined,
- country: originalCert.subjectCountry || undefined,
- state: originalCert.subjectState || undefined,
- locality: originalCert.subjectLocality || undefined,
- domainComponents: originalCert.subjectDomainComponents
- ? originalCert.subjectDomainComponents.split(",")
- : undefined,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- internal: true,
- tx
- });
-
- certificate = caResult.certificate;
- certificateChain = caResult.certificateChain;
- issuingCaCertificate = caResult.issuingCaCertificate;
- serialNumber = caResult.serialNumber;
-
- const foundCert = await certificateDAL.findById(caResult.certificateId, tx);
- if (!foundCert) {
- throw new NotFoundError({ message: "Certificate was signed but could not be found in database" });
- }
- newCert = foundCert;
- } else if (
- caType === CaType.ACME ||
- caType === CaType.AZURE_AD_CS ||
- caType === CaType.ADCS ||
- caType === CaType.AWS_PCA ||
- caType === CaType.DIGICERT ||
- caType === CaType.AWS_ACM_PUBLIC_CA ||
- caType === CaType.VENAFI_TPP ||
- caType === CaType.GODADDY
- ) {
- // External CA renewal - mark for async processing outside transaction
- return {
- isExternalCA: true,
- ca,
- profile,
- originalCert,
- originalSignatureAlgorithm,
- originalKeyAlgorithm,
- ttl
- };
- } else {
- throw new BadRequestError({
- message: `CA type ${String(caType)} does not support certificate renewal`
- });
- }
- } else {
- // Self-signed certificate renewal
- const effectiveAlgorithms = getEffectiveAlgorithms(
- undefined,
- undefined,
- originalSignatureAlgorithm,
- originalKeyAlgorithm
- );
-
- const selfSignedRenewalResult = await processSelfSignedCertificate({
- certificateRequest,
- policy,
- profile,
- originalCert,
- effectiveAlgorithms,
- certificateDAL,
- certificateBodyDAL,
- certificateSecretDAL,
- kmsService,
- projectDAL,
- tx,
- isRenewal: true
- });
-
- certificate = selfSignedRenewalResult.selfSignedResult.certificate.toString("utf8");
- certificateChain = selfSignedRenewalResult.selfSignedResult.certificate.toString("utf8"); // Self-signed has no chain
- issuingCaCertificate = ""; // No issuing CA for self-signed
- serialNumber = selfSignedRenewalResult.selfSignedResult.serialNumber;
- newCert = selfSignedRenewalResult.certificateData;
- }
-
- if (!newCert) {
- throw new NotFoundError({ message: "Certificate was signed but could not be found in database" });
- }
-
- // For self-signed certificates, we already set the renewal data during creation
- // For CA-signed certificates, we need to set it now
- if (issuerType === IssuerType.CA) {
- const renewalUpdateData: {
- profileId: string | null;
- renewedFromCertificateId: string;
- renewBeforeDays?: number;
- applicationId?: string | null;
- } = {
- profileId: originalCert.profileId || null,
- renewedFromCertificateId: originalCert.id
- };
-
- if (finalRenewBeforeDays !== undefined) {
- renewalUpdateData.renewBeforeDays = finalRenewBeforeDays;
- }
-
- if (originalCert.applicationId) {
- renewalUpdateData.applicationId = originalCert.applicationId;
- }
-
- await certificateDAL.updateById(newCert.id, renewalUpdateData, tx);
- } else {
- const selfSignedUpdate: { renewBeforeDays?: number; applicationId?: string | null } = {};
- if (finalRenewBeforeDays !== undefined) {
- selfSignedUpdate.renewBeforeDays = finalRenewBeforeDays;
- }
- if (originalCert.applicationId) {
- selfSignedUpdate.applicationId = originalCert.applicationId;
- }
- if (Object.keys(selfSignedUpdate).length > 0) {
- await certificateDAL.updateById(newCert.id, selfSignedUpdate, tx);
- }
- }
-
- await certificateDAL.updateById(
- originalCert.id,
- {
- renewedByCertificateId: newCert.id,
- renewalError: null
- },
- tx
- );
-
- await addRenewedCertificateToSyncs(originalCert.id, newCert.id, { certificateSyncDAL }, tx);
-
- const renewalAltNames = originalCert.altNames
- ? originalCert.altNames.split(",").map((san) => detectSanType(san.trim()))
- : undefined;
-
- const certRequestResult = await certificateRequestService.createCertificateRequest({
- internal: true,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- projectId: originalCert.projectId,
- tx,
- caId: ca?.id || originalCert.caId || undefined,
- profileId: originalCert.profileId || undefined,
- applicationId: originalCert.applicationId ?? undefined,
- commonName: originalCert.commonName || undefined,
- altNames: renewalAltNames,
- keyUsages: parseKeyUsages(originalCert.keyUsages),
- extendedKeyUsages: parseExtendedKeyUsages(originalCert.extendedKeyUsages),
- notBefore: new Date(newCert.notBefore),
- notAfter: new Date(newCert.notAfter),
- keyAlgorithm: originalKeyAlgorithm,
- signatureAlgorithm: originalSignatureAlgorithm,
- metadata: `Renewed from certificate ID: ${originalCert.id}`,
- status: CertificateRequestStatus.ISSUED,
- certificateId: newCert.id,
- ttl,
- enrollmentType: EnrollmentType.API,
- organization: certificateRequest.organization,
- organizationalUnit: certificateRequest.organizationalUnit,
- country: certificateRequest.country,
- state: certificateRequest.state,
- locality: certificateRequest.locality,
- domainComponents: certificateRequest.domainComponents,
- ...(originalCert.isCA && {
- basicConstraints: { isCA: true, pathLength: originalCert.pathLength ?? undefined }
- })
- });
-
- // Copy metadata from original cert to new cert and cert request
- await copyMetadataFromCertificate(resourceMetadataDAL, {
- sourceCertificateId: originalCert.id,
- targetCertificateId: newCert.id,
- targetCertificateRequestId: certRequestResult.id,
- targetCertificateRequestCreatedAt: certRequestResult.createdAt,
- orgId: actorOrgId,
- tx
- });
-
- return {
- certificate,
- certificateChain,
- issuingCaCertificate,
- serialNumber,
- newCert,
- originalCert,
- profile,
- certRequestResult
- };
- });
-
- let certificateRequestId: string = renewalResult.certRequestResult?.id || "";
-
- // Handle external CA renewals separately
- if ("isExternalCA" in renewalResult && renewalResult.isExternalCA) {
- const { ca, profile, originalCert, originalSignatureAlgorithm, originalKeyAlgorithm, ttl } = renewalResult;
-
- const renewalOrderId = randomUUID();
- const altNamesArray = originalCert.altNames
- ? originalCert.altNames.split(",").map((san: string) => san.trim())
- : [];
- const structuredAltNames = altNamesArray.map((san) => detectSanType(san));
-
- const renewalBasicConstraints = originalCert.isCA
- ? { isCA: true, pathLength: originalCert.pathLength ?? undefined }
- : undefined;
-
- const certificateRequest = await certificateRequestService.createCertificateRequest({
- internal: true,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- projectId: originalCert.projectId,
- profileId: profile?.id,
- applicationId: originalCert.applicationId ?? undefined,
- caId: ca.id,
- commonName: originalCert.commonName || undefined,
- altNames: structuredAltNames.length > 0 ? structuredAltNames : undefined,
- keyUsages: parseKeyUsages(originalCert.keyUsages),
- extendedKeyUsages: parseExtendedKeyUsages(originalCert.extendedKeyUsages),
- keyAlgorithm: originalKeyAlgorithm,
- signatureAlgorithm: originalSignatureAlgorithm,
- metadata: `Renewed from certificate ID: ${originalCert.id}`,
- status: CertificateRequestStatus.PENDING,
- ttl,
- enrollmentType: EnrollmentType.API,
- organization: originalCert.subjectOrganization || undefined,
- organizationalUnit: originalCert.subjectOrganizationalUnit || undefined,
- country: originalCert.subjectCountry || undefined,
- state: originalCert.subjectState || undefined,
- locality: originalCert.subjectLocality || undefined,
- domainComponents: originalCert.subjectDomainComponents
- ? originalCert.subjectDomainComponents.split(",")
- : undefined,
- basicConstraints: renewalBasicConstraints
- });
-
- certificateRequestId = certificateRequest.id;
-
- // Copy metadata from original cert to new cert request
- await copyMetadataFromCertificate(resourceMetadataDAL, {
- sourceCertificateId: originalCert.id,
- targetCertificateRequestId: certificateRequest.id,
- targetCertificateRequestCreatedAt: certificateRequest.createdAt,
- orgId: actorOrgId
- });
-
- await certificateIssuanceQueue.queueCertificateIssuance({
- certificateId: renewalOrderId,
- profileId: profile?.id || "",
- caId: ca.id,
- caType: (ca.externalCa?.type as CaType) ?? CaType.INTERNAL,
- commonName: originalCert.commonName || "",
- altNames: structuredAltNames,
- ttl,
- signatureAlgorithm: originalSignatureAlgorithm,
- keyAlgorithm: originalKeyAlgorithm,
- keyUsages: parseKeyUsages(originalCert.keyUsages).map(mapKeyUsageToLegacy),
- extendedKeyUsages: parseExtendedKeyUsages(originalCert.extendedKeyUsages).map(mapExtendedKeyUsageToLegacy),
- organization: originalCert.subjectOrganization || undefined,
- organizationalUnit: originalCert.subjectOrganizationalUnit || undefined,
- country: originalCert.subjectCountry || undefined,
- state: originalCert.subjectState || undefined,
- locality: originalCert.subjectLocality || undefined,
- isRenewal: true,
- originalCertificateId: certificateId,
- certificateRequestId: certificateRequest.id,
- basicConstraints: renewalBasicConstraints,
- ...(originalCert.applicationId && { applicationId: originalCert.applicationId })
- });
-
- return {
- status: CertificateRequestStatus.PENDING,
- certificate: "", // External CA renewal is async
- certificateChain: "",
- issuingCaCertificate: "",
- serialNumber: "",
- certificateId: renewalOrderId,
- certificateRequestId: certificateRequest.id,
- projectId: originalCert.projectId,
- profileName: profile?.slug || "External CA Profile",
- commonName: originalCert.commonName || ""
- };
- }
-
- // Type check to ensure we have internal CA renewal result
- if ("isExternalCA" in renewalResult) {
- throw new BadRequestError({ message: "External CA renewals should be handled asynchronously" });
- }
-
- await triggerAutoSyncForCertificate(renewalResult.newCert.id, {
- certificateSyncDAL,
- pkiSyncDAL,
- pkiSyncQueue
- });
-
- let finalCertificateChain = renewalResult.certificateChain;
- if (removeRootsFromChain) {
- finalCertificateChain = removeRootCaFromChain(finalCertificateChain);
- }
-
- try {
- await pkiAlertV2Queue?.queueCertificateEvent({
- certificateId: renewalResult.newCert.id,
- projectId: renewalResult.originalCert.projectId,
- eventType: PkiAlertEventType.RENEWAL,
- applicationId: renewalResult.originalCert.applicationId ?? null
- });
- } catch {
- logger.debug("Failed to queue PKI renewal alert event");
- }
-
- await $reportCertificateIssued({
- orgId: renewalResult.profile?.project?.orgId ?? actorOrgId,
- projectId: renewalResult.originalCert.projectId,
- profileId: renewalResult.originalCert.profileId ?? undefined,
- applicationId: renewalResult.originalCert.applicationId ?? undefined,
- enrollmentType: EnrollmentType.API,
- operation: CertificateIssuanceOperation.RENEW,
- actor,
- actorId
- });
-
- return {
- status: CertificateRequestStatus.ISSUED,
- certificate: renewalResult.certificate,
- issuingCaCertificate: renewalResult.issuingCaCertificate,
- certificateChain: finalCertificateChain,
- serialNumber: renewalResult.serialNumber,
- certificateId: renewalResult.newCert.id,
- certificateRequestId,
- projectId: renewalResult.originalCert.projectId,
- profileName: renewalResult.profile?.slug || "Self-signed Certificate",
- commonName: renewalResult.originalCert.commonName || ""
- };
- };
-
- const updateRenewalConfig = async ({
- certificateId,
- renewBeforeDays,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- }: TUpdateRenewalConfigDTO): Promise<TRenewalConfigResponse> => {
- const certificate = await certificateDAL.findById(certificateId);
- if (!certificate) {
- throw new NotFoundError({ message: "Certificate not found" });
- }
-
- const metadataRows = await resourceMetadataDAL.find({ certificateId: certificate.id });
- const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
-
- if (certificate.applicationId) {
- const { permission } = await permissionService.getResourcePermission({
- actor,
- actorId,
- projectId: certificate.projectId,
- resourceType: ResourceType.CertificateApplication,
- resourceId: certificate.applicationId,
- actorAuthMethod,
- actorOrgId
- });
- ForbiddenError.from(permission).throwUnlessCan(
- ResourcePermissionCertificateActions.Edit,
- ResourcePermissionSub.Certificates
- );
- } else {
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: certificate.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionCertificateActions.Edit,
- subject(ProjectPermissionSub.Certificates, {
- commonName: certificate.commonName,
- altNames: certificate.altNames?.split(",").map((s) => s.trim()),
- serialNumber: certificate.serialNumber,
- metadata: certMetadata
- })
- );
- }
-
- if (!certificate.profileId) {
- throw new BadRequestError({
- message: "Certificate is not eligible for auto-renewal: certificate was not issued from a profile"
- });
- }
-
- const profile = await certificateProfileDAL.findByIdWithConfigs(certificate.profileId);
- if (!profile) {
- throw new NotFoundError({ message: "Certificate profile not found" });
- }
-
- const enrollmentType = await certificateDAL.getRequestEnrollmentTypeByCertId(certificate.id);
- if (enrollmentType && enrollmentType !== EnrollmentType.API) {
- throw new ForbiddenRequestError({
- message: `Certificate is not eligible for auto-renewal: ${enrollmentType.toUpperCase()} certificates cannot be auto-renewed`
- });
- }
-
- const certificateSecret = await certificateSecretDAL.findOne({ certId: certificate.id });
- if (!certificateSecret) {
- throw new ForbiddenRequestError({
- message:
- "Certificate is not eligible for auto-renewal: certificates issued from CSR (external private key) cannot be auto-renewed"
- });
- }
-
- if (certificate.status !== CertStatus.ACTIVE) {
- throw new BadRequestError({
- message: `Certificate is not eligible for auto-renewal: certificate status is ${certificate.status}, must be active`
- });
- }
-
- const now = new Date();
- if (certificate.notAfter <= now) {
- throw new BadRequestError({
- message: "Certificate is not eligible for auto-renewal: certificate has expired"
- });
- }
-
- if (certificate.revokedAt) {
- throw new BadRequestError({
- message: "Certificate is not eligible for auto-renewal: certificate has been revoked"
- });
- }
-
- if (certificate.renewedByCertificateId) {
- throw new BadRequestError({
- message: "Certificate is not eligible for auto-renewal: certificate has already been renewed"
- });
- }
-
- const certificateTtlInDays = Math.ceil(
- (new Date(certificate.notAfter).getTime() - new Date(certificate.notBefore).getTime()) / (24 * 60 * 60 * 1000)
- );
-
- if (renewBeforeDays >= certificateTtlInDays) {
- throw new BadRequestError({
- message: "Invalid renewal configuration: renewal threshold exceeds certificate validity period"
- });
- }
-
- if (!isValidRenewalTiming(renewBeforeDays, new Date(certificate.notAfter))) {
- throw new BadRequestError({
- message: "Invalid renewal configuration: renewal would be triggered immediately or in the past"
- });
- }
-
- await certificateDAL.transaction(async (tx) => {
- await certificateDAL.updateById(
- certificateId,
- {
- renewBeforeDays
- },
- tx
- );
- });
-
- return {
- projectId: certificate.projectId,
- renewBeforeDays,
- commonName: certificate.commonName || ""
- };
- };
-
- const disableRenewalConfig = async ({
- certificateId,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- }: TDisableRenewalConfigDTO): Promise<TDisableRenewalResponse> => {
- const certificate = await certificateDAL.findById(certificateId);
- if (!certificate) {
- throw new NotFoundError({ message: "Certificate not found" });
- }
-
- const metadataRows = await resourceMetadataDAL.find({ certificateId: certificate.id });
- const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
-
- if (certificate.applicationId) {
- const { permission } = await permissionService.getResourcePermission({
- actor,
- actorId,
- projectId: certificate.projectId,
- resourceType: ResourceType.CertificateApplication,
- resourceId: certificate.applicationId,
- actorAuthMethod,
- actorOrgId
- });
- ForbiddenError.from(permission).throwUnlessCan(
- ResourcePermissionCertificateActions.Edit,
- ResourcePermissionSub.Certificates
- );
- } else {
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: certificate.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionCertificateActions.Edit,
- subject(ProjectPermissionSub.Certificates, {
- commonName: certificate.commonName,
- altNames: certificate.altNames?.split(",").map((s) => s.trim()),
- serialNumber: certificate.serialNumber,
- metadata: certMetadata
- })
- );
- }
-
- if (!certificate.profileId) {
- throw new BadRequestError({
- message: "Certificate is not eligible for auto-renewal: certificate was not issued from a profile"
- });
- }
-
- const profile = await certificateProfileDAL.findByIdWithConfigs(certificate.profileId);
- if (!profile) {
- throw new NotFoundError({ message: "Certificate profile not found" });
- }
-
- await certificateDAL.transaction(async (tx) => {
- await certificateDAL.updateById(
- certificateId,
- {
- renewBeforeDays: null
- },
- tx
- );
- });
-
- return {
- projectId: certificate.projectId,
- commonName: certificate.commonName || ""
- };
- };
-
- const updateCertificate = async ({
- certificateId,
- metadata,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- }: TUpdateCertificateDTO) => {
- const certificate = await certificateDAL.findById(certificateId);
- if (!certificate) {
- throw new NotFoundError({ message: "Certificate not found" });
- }
-
- const currentMetadataRows = await resourceMetadataDAL.find({ certificateId: certificate.id });
- const currentMetadata = currentMetadataRows.map(({ key, value }) => ({ key, value: value || "" }));
-
- if (certificate.applicationId) {
- const { permission: resourcePermission } = await permissionService.getResourcePermission({
- actor,
- actorId,
- projectId: certificate.projectId,
- resourceType: ResourceType.CertificateApplication,
- resourceId: certificate.applicationId,
- actorAuthMethod,
- actorOrgId
- });
- ForbiddenError.from(resourcePermission).throwUnlessCan(
- ResourcePermissionCertificateActions.Edit,
- ResourcePermissionSub.Certificates
- );
- } else {
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: certificate.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
- });
-
- const currentSubject = subject(ProjectPermissionSub.Certificates, {
- commonName: certificate.commonName,
- altNames: certificate.altNames?.split(",").map((s) => s.trim()),
- serialNumber: certificate.serialNumber,
- metadata: currentMetadata
- });
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.Edit, currentSubject);
-
- if (metadata) {
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionCertificateActions.Edit,
- subject(ProjectPermissionSub.Certificates, {
- commonName: certificate.commonName,
- altNames: certificate.altNames?.split(",").map((s) => s.trim()),
- serialNumber: certificate.serialNumber,
- metadata
- })
- );
- }
- }
-
- let updatedMetadata: Array<{ key: string; value: string }> = [];
-
- if (metadata) {
- await certificateDAL.transaction(async (tx) => {
- await resourceMetadataDAL.delete({ certificateId }, tx);
- await insertMetadataForCertificate(resourceMetadataDAL, {
- metadata,
- certificateId,
- orgId: actorOrgId,
- tx
- });
- });
- updatedMetadata = metadata;
- }
-
- return { metadata: updatedMetadata, projectId: certificate.projectId, commonName: certificate.commonName };
- };
+ const renewalService = certificateRenewalServiceFactory({
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ certificateAuthorityDAL,
+ certificateProfileDAL,
+ certificatePolicyService,
+ internalCaService,
+ permissionService,
+ certificateSyncDAL,
+ pkiSyncDAL,
+ pkiSyncQueue,
+ kmsService,
+ projectDAL,
+ certificateIssuanceQueue,
+ certificateRequestService,
+ certificateRequestDAL,
+ resourceMetadataDAL,
+ pkiAlertV2Queue,
+ pkiApplicationProfileDAL,
+ apiEnrollmentConfigDAL,
+ resolveApplicationIdForProfile: $resolveApplicationIdForProfile,
+ reportCertificateIssued: $reportCertificateIssued
+ });
return {
+ ...renewalService,
issueCertificateFromProfile,
signCertificateFromProfile,
orderCertificate,
- renewCertificate,
- updateRenewalConfig,
- disableRenewalConfig,
updateCertificate
};
};
diff --git a/backend/src/services/certificate-v3/certificate-v3-types.ts b/backend/src/services/certificate-v3/certificate-v3-types.ts
index 398edd9909..e2c06a3dd4 100644
--- a/backend/src/services/certificate-v3/certificate-v3-types.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-types.ts
@@ -3,7 +3,9 @@ import { TProjectPermission } from "@app/lib/types";
import {
CertExtendedKeyUsageType,
CertificateRequestStatus,
+ CertKeyAlgorithm,
CertKeyUsageType,
+ CertSignatureAlgorithm,
CertSubjectAlternativeNameType
} from "../certificate-common/certificate-constants";
import { EnrollmentType } from "../certificate-profile/certificate-profile-types";
@@ -57,10 +59,6 @@ export type TSignCertificateFromProfileDTO = {
pathLength?: number;
};
applicationId?: string;
- /**
- * Links the certificate request this issuance creates back to its ACME order, so a crash between
- * signing and persistence can be reconciled by `checkAndSyncAcmeOrderStatus`.
- */
acmeOrderId?: string;
} & Omit<TProjectPermission, "projectId">;
@@ -126,10 +124,42 @@ export type TCertificatePendingApprovalResponse = TCertificateIssuanceResponse &
status: CertificateRequestStatus.PENDING_APPROVAL;
};
+export enum CertificateRenewalKeySource {
+ New = "new",
+ Reuse = "reuse",
+ Csr = "csr"
+}
+
+export type TRenewalAttributes = {
+ commonName?: string | null;
+ organization?: string | null;
+ organizationalUnit?: string | null;
+ country?: string | null;
+ state?: string | null;
+ locality?: string | null;
+ domainComponents?: string[] | null;
+ altNames?: Array<{
+ type: CertSubjectAlternativeNameType;
+ value: string;
+ }>;
+ keyUsages?: CertKeyUsageType[];
+ extendedKeyUsages?: CertExtendedKeyUsageType[];
+ signatureAlgorithm?: CertSignatureAlgorithm;
+ keyAlgorithm?: CertKeyAlgorithm;
+ ttl?: string;
+ basicConstraints?: {
+ isCA: boolean;
+ pathLength?: number;
+ };
+};
+
export type TRenewCertificateDTO = {
certificateId: string;
removeRootsFromChain?: boolean;
certificateRequestId?: string;
+ renewalKeySource?: CertificateRenewalKeySource;
+ csr?: string;
+ attributes?: TRenewalAttributes;
} & Omit<TProjectPermission, "projectId">;
export type TUpdateRenewalConfigDTO = {
diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.ts
index caf3d3e13f..29457151b6 100644
--- a/backend/src/services/certificate/certificate-dal.ts
+++ b/backend/src/services/certificate/certificate-dal.ts
@@ -10,6 +10,12 @@ import {
type ProcessedPermissionRules
} from "@app/lib/knex/permission-filter-utils";
import { isUuidV4 } from "@app/lib/validator";
+import {
+ mapExtendedKeyUsageToLegacy,
+ mapLegacyExtendedKeyUsageToStandard,
+ normalizeExtendedKeyUsagesForResponse,
+ normalizeKeyUsagesForResponse
+} from "@app/services/certificate-common/certificate-constants";
import { applyMetadataFilter } from "@app/services/resource-metadata/resource-metadata-fns";
import { keySizeToAlgorithms } from "./certificate-fns";
@@ -33,6 +39,14 @@ export const NON_PQC_KEY_ALGORITHMS: string[] = [
export type TCertificateDALFactory = ReturnType<typeof certificateDALFactory>;
+const toLegacyExtendedKeyUsageForQuery = (usage: string): string => {
+ try {
+ return mapExtendedKeyUsageToLegacy(mapLegacyExtendedKeyUsageToStandard(usage));
+ } catch {
+ return usage;
+ }
+};
+
export const certificateDALFactory = (db: TDbClient) => {
const certificateOrm = ormify(db, TableName.Certificate);
@@ -183,7 +197,9 @@ export const certificateDALFactory = (db: TDbClient) => {
}
if (filters.extendedKeyUsage) {
- q = q.whereRaw(`"${TableName.Certificate}"."extendedKeyUsages" @> ARRAY[?]::text[]`, [filters.extendedKeyUsage]);
+ q = q.whereRaw(`"${TableName.Certificate}"."extendedKeyUsages" @> ARRAY[?]::text[]`, [
+ toLegacyExtendedKeyUsageForQuery(filters.extendedKeyUsage)
+ ]);
}
if (filters.keyAlgorithm) {
@@ -453,7 +469,12 @@ export const certificateDALFactory = (db: TDbClient) => {
query = query.orderBy("createdAt", "desc");
const certs = await query;
- return certs.map((cert) => ({ ...cert, hasPrivateKey: Boolean(cert.privateKeyRef) }));
+ return certs.map((cert) => ({
+ ...cert,
+ hasPrivateKey: Boolean(cert.privateKeyRef),
+ keyUsages: normalizeKeyUsagesForResponse(cert.keyUsages),
+ extendedKeyUsages: normalizeExtendedKeyUsagesForResponse(cert.extendedKeyUsages)
+ }));
} catch (error) {
throw new DatabaseError({ error, name: "Find active certificates for sync" });
}
@@ -555,21 +576,27 @@ export const certificateDALFactory = (db: TDbClient) => {
}
};
- const getRequestEnrollmentTypeByCertId = async (certId: string, tx?: Knex): Promise<string | null> => {
+ const getOriginatingRequestByCertId = async (
+ certId: string,
+ tx?: Knex
+ ): Promise<{ enrollmentType: string | null; csr: string | null }> => {
try {
// Primary, not replica: eligibility checks must not miss a recently-issued request row.
const row = (await (tx || db)(TableName.CertificateRequests)
.where(`${TableName.CertificateRequests}.certificateId`, certId)
.orderBy(`${TableName.CertificateRequests}.createdAt`, "asc")
- .select(`${TableName.CertificateRequests}.enrollmentType`)
- .first()) as { enrollmentType?: string | null } | undefined;
+ .select(`${TableName.CertificateRequests}.enrollmentType`, `${TableName.CertificateRequests}.csr`)
+ .first()) as { enrollmentType?: string | null; csr?: string | null } | undefined;
- return row?.enrollmentType ?? null;
+ return { enrollmentType: row?.enrollmentType ?? null, csr: row?.csr ?? null };
} catch (error) {
- throw new DatabaseError({ error, name: "Get request enrollment type by cert id" });
+ throw new DatabaseError({ error, name: "Get originating request by cert id" });
}
};
+ const getRequestEnrollmentTypeByCertId = async (certId: string, tx?: Knex): Promise<string | null> =>
+ (await getOriginatingRequestByCertId(certId, tx)).enrollmentType;
+
type TCertificateWithInventoryFields = TCertificates & {
hasPrivateKey: boolean;
caName?: string | null;
@@ -702,7 +729,9 @@ export const certificateDALFactory = (db: TDbClient) => {
const results = await query;
return results.map((row) => ({
...row,
- hasPrivateKey: row.privateKeyRef !== null
+ hasPrivateKey: row.privateKeyRef !== null,
+ keyUsages: normalizeKeyUsagesForResponse(row.keyUsages),
+ extendedKeyUsages: normalizeExtendedKeyUsagesForResponse(row.extendedKeyUsages)
}));
} catch (error) {
throw new DatabaseError({ error, name: "Find certificates with private key info" });
@@ -714,6 +743,7 @@ export const certificateDALFactory = (db: TDbClient) => {
profileName?: string | null;
applicationName?: string | null;
caType?: "internal" | "external" | null;
+ hasPrivateKey: boolean;
};
type TCertificateLookupFilter = { id: string; serialNumber?: never } | { id?: never; serialNumber: string };
@@ -740,11 +770,13 @@ export const certificateDALFactory = (db: TDbClient) => {
`${TableName.InternalCertificateAuthority}.caId`
)
.leftJoin(TableName.PkiApplication, `${TableName.Certificate}.applicationId`, `${TableName.PkiApplication}.id`)
+ .leftJoin(TableName.CertificateSecret, `${TableName.Certificate}.id`, `${TableName.CertificateSecret}.certId`)
.select(selectAllTableCols(TableName.Certificate))
.select(db.ref("name").withSchema(TableName.CertificateAuthority).as("caName"))
.select(db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName"))
.select(db.ref("name").withSchema(TableName.PkiApplication).as("applicationName"))
- .select(db.ref("id").withSchema(TableName.InternalCertificateAuthority).as("internalCaId"));
+ .select(db.ref("id").withSchema(TableName.InternalCertificateAuthority).as("internalCaId"))
+ .select(db.ref("certId").withSchema(TableName.CertificateSecret).as("privateKeyRef"));
if (filter.id) {
query = query.where(`${TableName.Certificate}.id`, filter.id);
@@ -753,21 +785,27 @@ export const certificateDALFactory = (db: TDbClient) => {
}
const result = (await query.first()) as
- | (TCertificateWithRequestDetails & { internalCaId?: string | null })
+ | (TCertificateWithRequestDetails & { internalCaId?: string | null; privateKeyRef?: string | null })
| undefined;
if (!result) {
return undefined;
}
- const { internalCaId, ...rest } = result;
+ const { internalCaId, privateKeyRef, ...rest } = result;
let caType: "internal" | "external" | null = null;
if (result.caId) {
caType = internalCaId ? "internal" : "external";
}
- return { ...rest, caType } as TCertificateWithRequestDetails;
+ return {
+ ...rest,
+ caType,
+ hasPrivateKey: Boolean(privateKeyRef),
+ keyUsages: normalizeKeyUsagesForResponse(rest.keyUsages),
+ extendedKeyUsages: normalizeExtendedKeyUsagesForResponse(rest.extendedKeyUsages)
+ } as TCertificateWithRequestDetails;
} catch (error) {
throw new DatabaseError({ error, name: "Find certificate with full details" });
}
@@ -1180,6 +1218,7 @@ export const certificateDALFactory = (db: TDbClient) => {
findActiveCertificatesForSync,
findCertificatesEligibleForRenewal,
getRequestEnrollmentTypeByCertId,
+ getOriginatingRequestByCertId,
findWithPrivateKeyInfo,
findWithFullDetails,
getDashboardStats,
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index 7eeef1c60b..7630257bd4 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -25,6 +25,7 @@ import { CaCapability, CaType } from "@app/services/certificate-authority/certif
import { caSupportsCapability } from "@app/services/certificate-authority/certificate-authority-maps";
import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";
import { TCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service";
+import { withNormalizedUsagesForResponse } from "@app/services/certificate-common/certificate-constants";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -416,7 +417,7 @@ export const certificateServiceFactory = ({
usageMeteringService.emitForProject(cert.projectId, ActiveCerts.key);
return {
- deletedCert
+ deletedCert: withNormalizedUsagesForResponse(deletedCert)
};
};
@@ -1232,7 +1233,7 @@ export const certificateServiceFactory = ({
}
const [updatedCert] = await certificateDAL.update({ id: cert.id }, { applicationId });
- return { certificate: updatedCert, application };
+ return { certificate: withNormalizedUsagesForResponse(updatedCert), application };
};
return {
diff --git a/backend/src/services/pki-sync/pki-sync-utils.ts b/backend/src/services/pki-sync/pki-sync-utils.ts
index 838f767607..15a77fa8b6 100644
--- a/backend/src/services/pki-sync/pki-sync-utils.ts
+++ b/backend/src/services/pki-sync/pki-sync-utils.ts
@@ -72,7 +72,7 @@ export const addRenewedCertificateToSyncs = async (
tx?: Knex
) => {
try {
- const pkiSyncIds = await dependencies.certificateSyncDAL.findPkiSyncIdsByCertificateId(oldCertificateId);
+ const pkiSyncIds = await dependencies.certificateSyncDAL.findPkiSyncIdsByCertificateId(oldCertificateId, tx);
if (pkiSyncIds.length === 0) {
return;
@@ -81,7 +81,8 @@ export const addRenewedCertificateToSyncs = async (
const addPromises = pkiSyncIds.map(async (pkiSyncId) => {
const oldCertificateRecord = await dependencies.certificateSyncDAL.findByPkiSyncAndCertificate(
pkiSyncId,
- oldCertificateId
+ oldCertificateId,
+ tx
);
await dependencies.certificateSyncDAL.addCertificates(
diff --git a/backend/src/services/resource-metadata/resource-metadata-fns.ts b/backend/src/services/resource-metadata/resource-metadata-fns.ts
index b54afe225e..76a4500def 100644
--- a/backend/src/services/resource-metadata/resource-metadata-fns.ts
+++ b/backend/src/services/resource-metadata/resource-metadata-fns.ts
@@ -24,7 +24,7 @@ export const copyMetadataFromRequestToCertificate = async (
tx?: Knex;
}
) => {
- const certRequestMetadata = await resourceMetadataDAL.find({ certificateRequestId });
+ const certRequestMetadata = await resourceMetadataDAL.find({ certificateRequestId }, { tx });
if (certRequestMetadata.length > 0) {
await resourceMetadataDAL.insertMany(
certRequestMetadata.map(({ key, value, orgId }) => ({
@@ -113,7 +113,7 @@ export const copyMetadataFromCertificate = async (
tx?: Knex;
}
) => {
- const originalMetadata = await resourceMetadataDAL.find({ certificateId: sourceCertificateId });
+ const originalMetadata = await resourceMetadataDAL.find({ certificateId: sourceCertificateId }, { tx });
if (originalMetadata.length === 0) return;
if (targetCertificateId) {
diff --git a/docs/docs.json b/docs/docs.json
index 66608e3ac9..d4df6b125a 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -955,6 +955,7 @@
"pages": [
"documentation/platform/pki/applications/overview",
"documentation/platform/pki/applications/certificates",
+ "documentation/platform/pki/applications/certificate-renewal",
{
"group": "Enrollment Methods",
"pages": [
diff --git a/docs/documentation/platform/pki/applications/certificate-renewal.mdx b/docs/documentation/platform/pki/applications/certificate-renewal.mdx
new file mode 100644
index 0000000000..e225d3a33b
--- /dev/null
+++ b/docs/documentation/platform/pki/applications/certificate-renewal.mdx
@@ -0,0 +1,183 @@
+---
+title: "Renewing Certificates"
+sidebarTitle: "Renewal"
+description: "Manually renew a certificate, and change its subject, names, validity, or key pair as part of the renewal."
+---
+
+Certificates expire, and the details they carry go out of date. A manual renewal issues a replacement for a certificate you already have, and lets you correct it at the same time: add a name the service now answers to, extend the validity, or decide whether the replacement keeps the current key pair.
+
+This is the counterpart to automatic renewal, which reissues a certificate exactly as it is on a schedule. Reach for a manual renewal when something about the certificate needs to change, or when you want the replacement now rather than at the next renewal window.
+
+<Note>
+ A certificate can be renewed when it was issued from a [certificate profile](/documentation/platform/pki/applications/enrollment-methods/api), is still active, and has not already been renewed. Certificates obtained through [ACME](/documentation/platform/pki/applications/enrollment-methods/acme), [EST](/documentation/platform/pki/applications/enrollment-methods/est), or [SCEP](/documentation/platform/pki/applications/enrollment-methods/scep) are renewed by the client that requested them, not from here.
+</Note>
+
+## How a renewal is built
+
+The renewed certificate starts as an exact copy of the one being renewed. Only what you explicitly change is different.
+
+| What you do | What happens |
+|-------------|--------------|
+| Leave a field alone | The current value carries over |
+| Change a field | The new value is used |
+| Clear a field | The attribute is dropped from the renewed certificate |
+| Edit a list, such as names or key usages | The list you submit replaces the current one |
+
+Defaults configured on the certificate profile are deliberately not applied. They describe what a **new** certificate should look like, so applying them during a renewal would rewrite fields you never touched. The profile's [certificate policy](/documentation/platform/pki/settings/policies) still validates the result, so a renewal cannot produce a certificate the policy would have rejected at issuance.
+
+## Choosing how the key pair is handled
+
+The first step of the renewal asks how to handle the key pair. This is the one decision that cannot be changed afterwards, because it determines the key the replacement certificate certifies.
+
+| Option | What happens |
+|--------|--------------|
+| **Reuse the existing key pair** | The renewed certificate carries the same public key. Anything pinned to that key, such as a key-pinned client or a device that cannot rotate its key, keeps working. |
+| **Generate a new key pair** | A fresh key pair is created for the renewed certificate. This is the default. |
+| **Use a CSR** | You supply a certificate signing request with its own key. |
+
+<Warning>
+ Reusing a key pair extends the lifetime of that key by another full validity period. If the key were ever exposed, a renewal that reuses it carries the exposure forward. Prefer a new key pair unless something in your environment depends on the current one.
+</Warning>
+
+### Availability by issuer
+
+Not every option applies to every certificate. The renewal wizard greys out the ones that do not, and explains why.
+
+| Issuer | Reuse the key pair | Use a CSR |
+|--------|--------------------|-----------|
+| **Private CA** | Yes | Yes |
+| **External CA** | No, these CAs only accept a freshly generated key | Yes |
+| **Self-signed** | Yes | No, see below |
+
+A self-signed certificate is signed by the private key that matches its own public key. A signing request carries only a public key, so there would be nothing to sign the renewal with. Reuse works because the existing key pair is available to sign with.
+
+Reuse is available for certificates issued with an Infisical-managed key pair. A certificate you issued from your own signing request can reuse its public key too: the renewal is made from that original request, so the key stays on your side.
+
+## What you can change
+
+| Property | Notes |
+|----------|-------|
+| Subject attributes | Common name, organization, organizational unit, country, state, locality, domain components |
+| Subject alternative names | Add, remove, or change the type of any name |
+| Validity | A duration such as `90d`, `12h`, or `1y` |
+| 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 |
+
+<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.
+</Warning>
+
+### 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.
+
+Sending a property the CSR already carries is rejected rather than quietly ignored, so a renewal never silently discards something you asked for.
+
+## Renewing a certificate
+
+<Tabs>
+ <Tab title="Web UI">
+ <Steps>
+ <Step title="Open the certificate">
+ Go to the **Certificates** tab of your Application and select the certificate you want to renew.
+ </Step>
+ <Step title="Start the renewal">
+ Open the **Options** menu and choose **Renew Now**.
+ </Step>
+ <Step title="Choose how the key pair is handled">
+ Pick one of the three options above. If you chose **Use a CSR**, paste it on the next step and you are done.
+ </Step>
+ <Step title="Adjust the subject and names">
+ The subject attributes and alternative names are prefilled 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**.
+ </Step>
+ </Steps>
+
+ Infisical opens the renewed certificate when it is issued.
+
+ </Tab>
+ <Tab title="API">
+ Renew a certificate and change the properties you want in the same request. Everything you leave out is copied from the current certificate.
+
+ ```bash
+ curl -X POST "https://app.infisical.com/api/v1/cert-manager/certificates/<certificate-id>/renew" \
+ -H "Authorization: Bearer <your-access-token>" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "renewalKeySource": "reuse",
+ "attributes": {
+ "commonName": "api.example.com",
+ "altNames": [
+ { "type": "dns_name", "value": "api.example.com" },
+ { "type": "dns_name", "value": "api-internal.example.com" }
+ ],
+ "ttl": "90d"
+ }
+ }'
+ ```
+
+ `renewalKeySource` accepts `new`, `reuse`, or `csr`. Supply `csr` alongside `renewalKeySource: "csr"`. To clear an attribute, send it as `null`.
+
+ A request with no body renews the certificate as it is with a new key pair, so existing automation keeps working unchanged.
+
+ See the [Renew Certificate endpoint](/api-reference/endpoints/certificates/renew) for the full request and response.
+
+ </Tab>
+</Tabs>
+
+## After a renewal
+
+The renewal produces a new certificate with its own serial number, linked to the one it replaced.
+
+- The previous certificate stays valid until its own expiry, so you can roll over on your own schedule. It cannot be renewed a second time.
+- Metadata carries over to the renewed certificate.
+- Certificate syncs attached to the certificate move to the renewed one and push it to their destinations.
+- Automatic renewal carries over. A certificate set to renew 4 days before expiry keeps that window, measured against the renewed certificate's own expiry rather than the previous one.
+
+<Note>
+ The window is re-derived for the renewed certificate's validity, so it can come back smaller. Renew
+ a 30 day certificate that renews 20 days early into a 5 day one and the window shrinks to fit,
+ because it has to stay shorter than the certificate it applies to.
+</Note>
+
+Deploy the renewed certificate before the previous one expires. Renewing does not revoke the certificate it replaces, so if the old one was compromised, [revoke it](/documentation/platform/pki/applications/certificates) explicitly.
+
+## FAQ
+
+<AccordionGroup>
+ <Accordion title="Does renewing revoke the certificate it replaces?">
+ No. The previous certificate stays valid until its own expiry date, which gives you a window to deploy the replacement. If you need the previous certificate to stop being trusted immediately, revoke it, and it will appear in the issuing CA's [CRL](/documentation/platform/pki/ca/crl-distribution).
+ </Accordion>
+ <Accordion title="Why is the key algorithm locked when I reuse the key pair?">
+ The algorithm is a property of the key itself, so it cannot change while the key stays the same. To move from RSA to an elliptic curve key, or to a larger key size, renew with a new key pair.
+ </Accordion>
+ <Accordion title="What happens if the certificate policy changed since the certificate was issued?">
+ The renewal is validated against the policy as it is now, so a certificate that no longer satisfies the policy is rejected with a message naming the field at fault. Adjust the values during the renewal so they fit the current policy.
+ </Accordion>
+ <Accordion title="Can I renew a certificate that Infisical did not generate the key for?">
+ Yes. Choose a new key pair, or supply a CSR generated from the existing key. A certificate issued from a signing request can also reuse its public key, in which case the renewal is made from that original request.
+ </Accordion>
+ <Accordion title="Can I renew several certificates at once?">
+ Manual renewal handles one certificate at a time. To keep many certificates current without intervention, enable [automatic renewal](/documentation/platform/pki/applications/certificates) so Infisical reissues them before they expire.
+ </Accordion>
+</AccordionGroup>
+
+## What's Next?
+
+<CardGroup cols={2}>
+ <Card title="Certificates" icon="certificate" href="/documentation/platform/pki/applications/certificates">
+ Inspect, export, and revoke certificates in your inventory.
+ </Card>
+ <Card title="Certificate Syncs" icon="arrows-rotate" href="/documentation/platform/pki/applications/certificate-syncs/overview">
+ Push renewed certificates to their destinations automatically.
+ </Card>
+ <Card title="Alerting" icon="bell" href="/documentation/platform/pki/applications/alerting/overview">
+ Get notified before certificates expire.
+ </Card>
+ <Card title="Certificate Policies" icon="shield-check" href="/documentation/platform/pki/settings/policies">
+ Constrain what a renewed certificate may contain.
+ </Card>
+</CardGroup>
diff --git a/docs/documentation/platform/pki/applications/certificates.mdx b/docs/documentation/platform/pki/applications/certificates.mdx
index b594ab978b..35c1877b6d 100644
--- a/docs/documentation/platform/pki/applications/certificates.mdx
+++ b/docs/documentation/platform/pki/applications/certificates.mdx
@@ -34,7 +34,7 @@ From the certificate details page, use the **Options** menu:
|--------|-------------|
| **Export** | Download as PEM (individual files) or PKCS12 (single encrypted bundle) |
| **Enable Auto-Renewal** | Infisical renews automatically before expiration |
-| **Renew Now** | Manually trigger renewal |
+| **Renew Now** | [Renew the certificate](/documentation/platform/pki/applications/certificate-renewal), optionally changing its subject, names, validity, or key pair |
| **Manage Syncs** | Push to cloud destinations (ACM, Key Vault, etc.) |
| **Revoke** | Revoke with a reason code; certificate appears in CRL |
| **Delete** | Remove from inventory |
@@ -60,9 +60,12 @@ For automated issuance, configure an [enrollment method](/documentation/platform
|------|--------------|
| **Client-driven** | The client (Certbot, cert-manager, Infisical Agent) monitors expiration and requests renewal |
| **Server-driven** | Infisical automatically renews before expiration and pushes to [syncs](/documentation/platform/pki/applications/certificate-syncs/overview) |
+| **Manual** | You renew on demand from the certificate, and can change its properties as part of the renewal |
Server-driven renewal requires [API enrollment](/documentation/platform/pki/applications/enrollment-methods/api) with Infisical-managed keys. Enable it on the [enrollment method](/documentation/platform/pki/applications/enrollment-methods/api) or toggle it per-certificate.
+Both automatic types reissue the certificate exactly as it is. To change the subject, the names it covers, its validity, or how its key pair is handled, [renew it manually](/documentation/platform/pki/applications/certificate-renewal).
+
## Export Formats
| Format | Use Case |
@@ -83,6 +86,9 @@ openssl verify -crl_check -CAfile chain.pem -CRLfile crl.pem cert.pem
## What's Next?
<CardGroup cols={2}>
+ <Card title="Renewal" icon="rotate" href="/documentation/platform/pki/applications/certificate-renewal">
+ Renew a certificate and change its properties at the same time.
+ </Card>
<Card title="Certificate Syncs" icon="arrows-rotate" href="/documentation/platform/pki/applications/certificate-syncs/overview">
Push certificates to AWS ACM, Azure Key Vault, and other destinations.
</Card>
diff --git a/frontend/src/hooks/api/certificates/enums.tsx b/frontend/src/hooks/api/certificates/enums.tsx
index 005ef29d69..6395877ed8 100644
--- a/frontend/src/hooks/api/certificates/enums.tsx
+++ b/frontend/src/hooks/api/certificates/enums.tsx
@@ -50,6 +50,12 @@ export enum CertExtendedKeyUsage {
ANY_PURPOSE = "any_purpose"
}
+export enum CertificateRenewalKeySource {
+ New = "new",
+ Reuse = "reuse",
+ Csr = "csr"
+}
+
export enum CertSource {
Issued = "issued",
Discovered = "discovered",
@@ -64,3 +70,8 @@ export enum CertificateRequestStatus {
FAILED = "failed",
REJECTED = "rejected"
}
+
+export enum CertificateIssuerKind {
+ Internal = "internal",
+ External = "external"
+}
diff --git a/frontend/src/hooks/api/certificates/mutations.tsx b/frontend/src/hooks/api/certificates/mutations.tsx
index 559d3ee12e..ec897b3d60 100644
--- a/frontend/src/hooks/api/certificates/mutations.tsx
+++ b/frontend/src/hooks/api/certificates/mutations.tsx
@@ -111,10 +111,10 @@ export const useImportCertificate = () => {
export const useRenewCertificate = () => {
const queryClient = useQueryClient();
return useMutation<TRenewCertificateResponse, object, TRenewCertificateDTO>({
- mutationFn: async ({ certificateId }) => {
+ mutationFn: async ({ certificateId, ...body }) => {
const { data } = await apiRequest.post<TRenewCertificateResponse>(
`/api/v1/cert-manager/certificates/${certificateId}/renew`,
- {}
+ body
);
return data;
},
diff --git a/frontend/src/hooks/api/certificates/types.ts b/frontend/src/hooks/api/certificates/types.ts
index 2cc74e209c..48da56f293 100644
--- a/frontend/src/hooks/api/certificates/types.ts
+++ b/frontend/src/hooks/api/certificates/types.ts
@@ -1,5 +1,7 @@
import {
CertExtendedKeyUsage,
+ CertificateIssuerKind,
+ CertificateRenewalKeySource,
CertificateRequestStatus,
CertKeyUsage,
CertSource,
@@ -55,7 +57,7 @@ export type TCertificate = {
caName?: string | null;
profileName?: string | null;
enrollmentType?: string | null;
- caType?: "internal" | "external" | null;
+ caType?: CertificateIssuerKind | null;
applicationId?: string | null;
applicationName?: string | null;
source?: TCertificateSource;
@@ -97,8 +99,34 @@ export type TImportCertificateResponse = {
serialNumber: string;
};
+export type TRenewCertificateAttributes = {
+ commonName?: string | null;
+ organization?: string | null;
+ organizationalUnit?: string | null;
+ country?: string | null;
+ state?: string | null;
+ locality?: string | null;
+ domainComponents?: string[] | null;
+ keyUsages?: string[];
+ extendedKeyUsages?: string[];
+ altNames?: Array<{
+ type: string;
+ value: string;
+ }>;
+ signatureAlgorithm?: string;
+ keyAlgorithm?: string;
+ ttl?: string;
+ basicConstraints?: {
+ isCA: boolean;
+ pathLength?: number;
+ };
+};
+
export type TRenewCertificateDTO = {
certificateId: string;
+ renewalKeySource?: CertificateRenewalKeySource;
+ csr?: string;
+ attributes?: TRenewCertificateAttributes;
};
export type TRenewCertificateResponse = {
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
index 5d1e096d78..5b7bba1ef4 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
@@ -388,7 +388,6 @@ const Page = () => {
)}
{!isInventoryView &&
(certificate.profileId || certificate.caId) &&
- certificate.hasPrivateKey !== false &&
!certificate.renewedByCertificateId &&
!isRevoked &&
!isExpired && (
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx
index 0ccbec4cbe..72cfef3251 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx
@@ -4,6 +4,7 @@ import { Control, Controller } from "react-hook-form";
import {
Badge,
Field,
+ FieldDescription,
FieldError,
FieldLabel,
Select,
@@ -33,6 +34,7 @@ type AlgorithmSelectProps = {
nonePlaceholder?: string;
selectPlaceholder: string;
renderOptions: (options: AlgorithmOption[]) => ReactNode;
+ disabledReason?: string;
};
const AlgorithmSelect = ({
@@ -45,7 +47,8 @@ const AlgorithmSelect = ({
isRequired,
nonePlaceholder,
selectPlaceholder,
- renderOptions
+ renderOptions,
+ disabledReason
}: AlgorithmSelectProps) => (
<Controller
control={control}
@@ -59,6 +62,7 @@ const AlgorithmSelect = ({
<Select
value={value ?? (nonePlaceholder ? NONE_VALUE : "")}
onValueChange={(e) => onChange(e === NONE_VALUE ? null : e)}
+ disabled={Boolean(disabledReason)}
>
<SelectTrigger className="w-full" isError={Boolean(error)}>
<SelectValue
@@ -67,6 +71,7 @@ const AlgorithmSelect = ({
</SelectTrigger>
<SelectContent position="popper">{renderOptions(options)}</SelectContent>
</Select>
+ {disabledReason && <FieldDescription>{disabledReason}</FieldDescription>}
<FieldError>{error}</FieldError>
</Field>
)}
@@ -85,6 +90,7 @@ type AlgorithmSelectorsProps = {
isRequired?: boolean;
nonePlaceholder?: string;
hideSignatureAlgorithm?: boolean;
+ keyAlgorithmDisabledReason?: string;
};
export const AlgorithmSelectors = ({
@@ -98,7 +104,8 @@ export const AlgorithmSelectors = ({
keyFieldName = "keyAlgorithm",
isRequired = true,
nonePlaceholder,
- hideSignatureAlgorithm = false
+ hideSignatureAlgorithm = false,
+ keyAlgorithmDisabledReason
}: AlgorithmSelectorsProps) => {
const { subscription } = useSubscription();
@@ -147,6 +154,7 @@ export const AlgorithmSelectors = ({
nonePlaceholder={nonePlaceholder}
selectPlaceholder="Select key algorithm"
renderOptions={renderOptions}
+ disabledReason={keyAlgorithmDisabledReason}
/>
</div>
);
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/BasicConstraintsField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/BasicConstraintsField.tsx
new file mode 100644
index 0000000000..d91dbd0538
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/BasicConstraintsField.tsx
@@ -0,0 +1,105 @@
+import { Control, Controller, UseFormSetValue } from "react-hook-form";
+
+import {
+ Checkbox,
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input
+} from "@app/components/v3";
+
+type Props = {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ control: Control<any>;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ setValue: UseFormSetValue<any>;
+ isCA: boolean;
+ templateRequiresCA: boolean;
+ maxPathLength?: number;
+ isPathLengthRequired?: boolean;
+ idPrefix?: string;
+};
+
+export const BasicConstraintsField = ({
+ control,
+ setValue,
+ isCA,
+ templateRequiresCA,
+ maxPathLength,
+ isPathLengthRequired = false,
+ idPrefix = "basic-constraints"
+}: Props) => (
+ <div>
+ <p className="text-sm font-medium text-foreground">Basic Constraints</p>
+ <div className="mt-4 space-y-4">
+ <Controller
+ control={control}
+ name="basicConstraints.isCA"
+ render={({ field: { value, onChange } }) => (
+ <div className="flex items-start gap-3">
+ <Checkbox
+ id={`${idPrefix}-isCA`}
+ variant="project"
+ isChecked={templateRequiresCA || value || false}
+ isDisabled={templateRequiresCA}
+ onCheckedChange={(checked) => {
+ if (templateRequiresCA) return;
+ onChange(checked);
+ if (!checked) setValue("basicConstraints.pathLength", null);
+ }}
+ />
+ <span className="text-sm text-foreground">
+ Issue as Certificate Authority
+ <span className="mt-1 block text-xs text-muted">
+ This certificate will be issued with the CA:TRUE extension.
+ </span>
+ </span>
+ </div>
+ )}
+ />
+
+ {isCA && (
+ <Controller
+ control={control}
+ name="basicConstraints.pathLength"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Path Length {isPathLengthRequired && <span className="text-danger">*</span>}
+ </FieldLabel>
+ <Input
+ {...field}
+ type="number"
+ min={0}
+ max={maxPathLength}
+ isError={Boolean(error)}
+ placeholder={
+ isPathLengthRequired
+ ? "Enter path length (required)"
+ : "Leave empty for no constraint"
+ }
+ value={field.value ?? ""}
+ onChange={(e) => {
+ const raw = e.target.value;
+ if (raw === "") {
+ field.onChange(null);
+ return;
+ }
+ const parsed = parseInt(raw, 10);
+ field.onChange(Number.isNaN(parsed) ? null : parsed);
+ }}
+ />
+ <FieldDescription>
+ {maxPathLength !== undefined
+ ? `Sets the pathLen for this CA certificate. Controls how many levels of sub-CAs can exist below. This CA supports 0 to ${maxPathLength}; 0 means it can only sign end-entity certificates.`
+ : "Sets the pathLen for this CA certificate. Controls how many levels of sub-CAs can exist below. Empty means unlimited; 0 means it can only sign end-entity certificates."}
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ )}
+ </div>
+ </div>
+);
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
index 5a58daca35..4960ad1d43 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate } from "@tanstack/react-router";
@@ -8,8 +8,6 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import {
Button,
- Checkbox,
- DocumentationLinkBadge,
Empty,
EmptyContent,
EmptyMedia,
@@ -26,17 +24,9 @@ import {
SelectItem,
SelectTrigger,
SelectValue,
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
- Stepper,
- StepperList,
- StepperStep,
TextArea
} from "@app/components/v3";
import { useOrganization, useProject } from "@app/context";
-import { isIPv4, isIPv6 } from "@app/helpers/ip";
import { useGetCert } from "@app/hooks/api";
import { CaType } from "@app/hooks/api/ca";
import { useGetCertificatePolicyById } from "@app/hooks/api/certificatePolicies";
@@ -53,7 +43,10 @@ import {
} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
import { AlgorithmSelectors } from "./AlgorithmSelectors";
+import { BasicConstraintsField } from "./BasicConstraintsField";
import { buildManagedRequest } from "./buildManagedRequest";
+import { detectSanTypeFromValue } from "./certificateUtils";
+import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";
import { KeyUsageSection } from "./KeyUsageSection";
import { SubjectAltNamesField } from "./SubjectAltNamesField";
import { SubjectAttributesField } from "./SubjectAttributesField";
@@ -191,17 +184,7 @@ type Props = {
type IssuanceStepKey = "profile" | "csr" | "subject" | "options" | "metadata";
-const STEP_META: Record<
- IssuanceStepKey,
- {
- name: string;
- shortDescription: string;
- title: string;
- subtitle: string;
- rightLabel: string;
- rightDescription: string;
- }
-> = {
+const STEP_META: Record<IssuanceStepKey, WizardStep> = {
profile: {
name: "Profile",
shortDescription: "Method and profile",
@@ -275,8 +258,6 @@ export const CertificateIssuanceModal = ({
const { currentOrg } = useOrganization();
const navigate = useNavigate();
- const [step, setStep] = useState(0);
-
const inputSerialNumber =
(popUp?.issueCertificate?.data as { serialNumber: string })?.serialNumber || "";
const sanitizedSerialNumber = inputSerialNumber.replace(/[^a-fA-F0-9:]/g, "");
@@ -401,13 +382,13 @@ export const CertificateIssuanceModal = ({
return keys;
}, [requestMethod, constraints.shouldShowSubjectSection, constraints.shouldShowSanSection]);
- const currentStepKey = stepKeys[Math.min(step, stepKeys.length - 1)];
- const currentStepMeta = STEP_META[currentStepKey];
- const isLastStep = step === stepKeys.length - 1;
+ const { step, setStep, currentStepKey, goBack, goNext, onFormInvalid } = useWizardSteps({
+ stepKeys,
+ stepFields: STEP_FIELDS,
+ invalidMessage: "Please fix the highlighted fields before requesting."
+ });
- useEffect(() => {
- if (step > stepKeys.length - 1) setStep(stepKeys.length - 1);
- }, [stepKeys.length, step]);
+ const steps = useMemo(() => stepKeys.map((key) => STEP_META[key]), [stepKeys]);
useEffect(() => {
if (cert) {
@@ -425,13 +406,7 @@ export const CertificateIssuanceModal = ({
subjectAltNames: cert.subjectAltNames
? cert.subjectAltNames.split(",").map((name) => {
const trimmed = name.trim();
- if (trimmed.includes("@"))
- return { type: CertSubjectAlternativeNameType.EMAIL, value: trimmed };
- if (isIPv4(trimmed) || isIPv6(trimmed))
- return { type: CertSubjectAlternativeNameType.IP_ADDRESS, value: trimmed };
- if (trimmed.startsWith("http"))
- return { type: CertSubjectAlternativeNameType.URI, value: trimmed };
- return { type: CertSubjectAlternativeNameType.DNS_NAME, value: trimmed };
+ return { type: detectSanTypeFromValue(trimmed), value: trimmed };
})
: [],
ttl: "",
@@ -559,62 +534,37 @@ export const CertificateIssuanceModal = ({
]
);
- const getModalTitle = () => {
- if (cert) return "Certificate Details";
- return "Request New Certificate";
- };
-
- const getModalSubTitle = () => {
- if (cert) return "View certificate information";
- return "Request a new certificate using a certificate profile";
- };
-
const selectedProfileReady = Boolean(profileId || actualSelectedProfileId);
- const goBack = () => setStep((s) => Math.max(0, s - 1));
- const goNext = () => {
- if (currentStepKey === "profile" && !selectedProfileReady) return;
- setStep((s) => Math.min(stepKeys.length - 1, s + 1));
- };
-
- const onFormInvalid = (errors: Record<string, unknown>) => {
- const errorKeys = Object.keys(errors);
- const idx = stepKeys.findIndex((key) =>
- STEP_FIELDS[key].some((fieldName) => errorKeys.includes(fieldName))
- );
- if (idx >= 0) setStep(idx);
- createNotification({
- text: "Please fix the highlighted fields before requesting.",
- type: "error"
- });
- };
-
return (
- <Sheet
- open={popUp?.issueCertificate?.isOpen}
+ <CertificateWizardSheet
+ isOpen={Boolean(popUp?.issueCertificate?.isOpen)}
onOpenChange={(isOpen) => {
handlePopUpToggle("issueCertificate", isOpen);
if (!isOpen) {
resetAllState();
}
}}
- >
- <SheetContent className="flex h-full max-h-full flex-col gap-y-0 p-0 sm:max-w-[1100px]">
- <SheetHeader className="border-b border-border">
- <SheetTitle>
- <div className="flex w-full items-start gap-2">
- <div className="flex h-10 w-10 items-center justify-center rounded-md bg-project/10 text-project">
- <FileBadge className="h-5 w-5" />
- </div>
- <div>
- <div className="flex items-center gap-x-2 text-foreground">{getModalTitle()}</div>
- <p className="text-sm leading-4 text-muted">{getModalSubTitle()}</p>
- </div>
- </div>
- </SheetTitle>
- </SheetHeader>
-
- {cert ? (
+ icon={<FileBadge className="h-5 w-5" />}
+ title={cert ? "Certificate Details" : "Request New Certificate"}
+ description={
+ cert
+ ? "View certificate information"
+ : "Request a new certificate using a certificate profile"
+ }
+ steps={steps}
+ activeStep={step}
+ onStepChange={setStep}
+ docsHref={PkiDocsUrls.applications.certificates}
+ submitLabel="Request Certificate"
+ onSubmit={handleSubmit(onFormSubmit, onFormInvalid)}
+ onBack={goBack}
+ onContinue={goNext}
+ isSubmitting={isSubmitting}
+ isSubmitDisabled={!actualSelectedProfile && !profileId}
+ isContinueDisabled={currentStepKey === "profile" && !selectedProfileReady}
+ overrideContent={
+ cert ? (
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-6">
<h4 className="text-sm font-medium text-foreground">Certificate Details</h4>
<p className="mt-1 text-sm text-muted">Serial Number: {cert.serialNumber}</p>
@@ -622,463 +572,284 @@ export const CertificateIssuanceModal = ({
<p className="text-sm text-muted">Common Name: {cert.commonName}</p>
<p className="text-sm text-muted">Status: {cert.status}</p>
</div>
- ) : (
- <form onSubmit={(e) => e.preventDefault()} className="flex min-h-0 flex-1 flex-col">
- <div className="flex min-h-0 flex-1 overflow-hidden">
- <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">
- <p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">
- Setup steps
- </p>
- <Stepper
- activeStep={step}
- orientation="vertical"
- onStepChange={(i) => {
- if (isSubmitting) return;
- if (i < step) setStep(i);
- }}
- >
- <StepperList>
- {stepKeys.map((key, i) => (
- <StepperStep
- key={key}
- index={i}
- title={STEP_META[key].name}
- description={STEP_META[key].shortDescription}
- />
- ))}
- </StepperList>
- </Stepper>
- </aside>
-
- <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">
- <div className="mb-6">
- <h2 className="text-lg font-semibold text-foreground">{currentStepMeta.title}</h2>
- <p className="mt-1 text-sm text-muted">{currentStepMeta.subtitle}</p>
- </div>
-
- {currentStepKey === "profile" && (
- <div className="space-y-5">
- <Controller
+ ) : undefined
+ }
+ >
+ {currentStepKey === "profile" && (
+ <div className="space-y-5">
+ <Controller
+ control={control}
+ name="requestMethod"
+ render={({ field: { onChange, value } }) => (
+ <Field>
+ <FieldLabel>Request Method</FieldLabel>
+ <FieldContent>
+ <Select value={value} onValueChange={(val) => onChange(val as RequestMethod)}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={RequestMethod.MANAGED}>Managed</SelectItem>
+ <SelectItem value={RequestMethod.CSR}>
+ Certificate Signing Request (CSR)
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ Managed generates and manages the private key for you. CSR lets you provide your
+ own certificate signing request when you need to manage your own private key.
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ {!profileId && (
+ <Controller
+ control={control}
+ name="profileId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Certificate Profile <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Select value={value || ""} onValueChange={(val) => onChange(val)}>
+ <SelectTrigger className="w-full" isError={Boolean(error)}>
+ <SelectValue placeholder="Select a certificate profile" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {availableProfiles.length === 0 && applicationId ? (
+ <div className="px-3 py-3 text-xs leading-snug whitespace-normal text-muted">
+ Only profiles with API enrollment configured on this Application are
+ listed here. Configure API enrollment under this Application&apos;s
+ Settings tab.
+ </div>
+ ) : (
+ availableProfiles.map((profile) => (
+ <SelectItem key={profile.id} value={profile.id}>
+ {profile.slug}
+ </SelectItem>
+ ))
+ )}
+ </SelectContent>
+ </Select>
+ {isAdcsProfile && <FieldDescription>{externalCaHint}</FieldDescription>}
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+ </div>
+ )}
+
+ {currentStepKey !== "profile" && (actualSelectedProfile || profileId) && (
+ <div className="space-y-4">
+ {currentStepKey === "options" && profileId && isAdcsProfile && (
+ <p className="mb-4 text-xs text-mineshaft-400">{externalCaHint}</p>
+ )}
+
+ {currentStepKey === "csr" && (
+ <Controller
+ control={control}
+ name="csr"
+ render={({ field: { value, ...field }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>
+ Certificate Signing Request (CSR) <span className="text-danger">*</span>
+ </FieldLabel>
+ <TextArea
+ {...field}
+ value={value ?? ""}
+ spellCheck={false}
+ isError={Boolean(error)}
+ placeholder={
+ "-----BEGIN CERTIFICATE REQUEST-----\n" +
+ "MIIByDCCAU4CAQAwfjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWEx\n" +
+ "FjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xEjAQBgNVBAoMCURlbW8gQ29ycDEUMBIG\n" +
+ "A1UECwwLRW5naW5lZXJpbmcxGDAWBgNVBAMMD2FwcC5leGFtcGxlLmNvbTB2MBAG\n" +
+ "ByqGSM49AgEGBSuBBAAiA2IABDHV5yengUugeBcpjsw+iAaxSkCr16LMr3ITyvlM\n" +
+ "lDv+AE0Ddc6FsFXJicBfTalM3AKl5F14OCBRfI2jugWJOGCLcKYqRDTDevxQmgCI\n" +
+ "IfpRM6+jzPkqe0PsuLhYiRfbFKBRME8GCSqGSIb3DQEJDjFCMEAwPgYDVR0RBDcw\n" +
+ "NYIPYXBwLmV4YW1wbGUuY29tghEqLmFwcC5leGFtcGxlLmNvbYIJbG9jYWxob3N0\n" +
+ "hwR/AAABMAoGCCqGSM49BAMCA2gAMGUCMGQQYs4lTSc3r/5MlabDx4m+sWaAtDhO\n" +
+ "17c3TaoDZOMG6r45mgUskPGTripXV9ItTQIxAJypXNlHnMvks7MO4LmicPqku4MF\n" +
+ "IeFqqXMFzC9uAO3iQ8/ji6ukvT6a9A3DE9LLIg==\n" +
+ "-----END CERTIFICATE REQUEST-----"
+ }
+ rows={13}
+ className="w-full font-mono text-xs"
+ />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ )}
+
+ {currentStepKey === "subject" && constraints.shouldShowSubjectSection && (
+ <SubjectAttributesField
+ control={control}
+ allowedAttributeTypes={constraints.allowedSubjectAttributeTypes}
+ error={
+ (formState.errors as { subjectAttributes?: { message?: string } }).subjectAttributes
+ ?.message
+ }
+ />
+ )}
+
+ {currentStepKey === "subject" && constraints.shouldShowSanSection && (
+ <SubjectAltNamesField
+ control={control}
+ allowedSanTypes={constraints.allowedSanTypes}
+ error={
+ (formState.errors as { subjectAltNames?: { message?: string } }).subjectAltNames
+ ?.message
+ }
+ />
+ )}
+
+ {(currentStepKey === "csr" || currentStepKey === "options") && !isAdcsProfile && (
+ <Controller
+ control={control}
+ name="ttl"
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>
+ Time to Live (TTL) <span className="text-danger">*</span>
+ </FieldLabel>
+ <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(error)} />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ )}
+
+ {currentStepKey === "options" && (
+ <>
+ <AlgorithmSelectors
+ control={control}
+ availableSignatureAlgorithms={availableSignatureAlgorithms}
+ availableKeyAlgorithms={availableKeyAlgorithms}
+ hideSignatureAlgorithm={isAdcsProfile}
+ signatureError={
+ (formState.errors as { signatureAlgorithm?: { message?: string } })
+ .signatureAlgorithm?.message
+ }
+ keyError={
+ (formState.errors as { keyAlgorithm?: { message?: string } }).keyAlgorithm
+ ?.message
+ }
+ />
+
+ {!isAdcsProfile && (
+ <div className="mt-4 space-y-6">
+ <KeyUsageSection
+ control={control}
+ title="Key Usages"
+ namePrefix="keyUsages"
+ options={filteredKeyUsages}
+ requiredUsages={constraints.requiredKeyUsages}
+ />
+ <KeyUsageSection
+ control={control}
+ title="Extended Key Usages"
+ namePrefix="extendedKeyUsages"
+ options={filteredExtendedKeyUsages}
+ requiredUsages={constraints.requiredExtendedKeyUsages}
+ />
+ {constraints.templateAllowsCA && (
+ <BasicConstraintsField
control={control}
- name="requestMethod"
- render={({ field: { onChange, value } }) => (
- <Field>
- <FieldLabel>Request Method</FieldLabel>
- <FieldContent>
- <Select
- value={value}
- onValueChange={(val) => onChange(val as RequestMethod)}
- >
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent position="popper">
- <SelectItem value={RequestMethod.MANAGED}>Managed</SelectItem>
- <SelectItem value={RequestMethod.CSR}>
- Certificate Signing Request (CSR)
- </SelectItem>
- </SelectContent>
- </Select>
- <FieldDescription>
- Managed generates and manages the private key for you. CSR lets you
- provide your own certificate signing request when you need to manage
- your own private key.
- </FieldDescription>
- </FieldContent>
- </Field>
- )}
+ setValue={setValue}
+ isCA={watchedIsCA}
+ templateRequiresCA={constraints.templateRequiresCA}
+ maxPathLength={isAwsPcaProfile ? AWS_PCA_MAX_CA_PATH_LENGTH : undefined}
+ isPathLengthRequired={
+ isAwsPcaProfile ||
+ (typeof constraints.maxPathLength === "number" &&
+ constraints.maxPathLength !== -1)
+ }
+ idPrefix="issuance"
/>
-
- {!profileId && (
+ )}
+ </div>
+ )}
+ </>
+ )}
+
+ {currentStepKey === "metadata" && (
+ <div>
+ <p className="text-sm font-medium text-foreground">Metadata</p>
+ {metadataFields.length === 0 ? (
+ <Empty className="mt-3 border py-8">
+ <EmptyMedia variant="icon">
+ <Tags />
+ </EmptyMedia>
+ <EmptyTitle>No metadata added</EmptyTitle>
+ <EmptyContent>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => appendMetadata({ key: "", value: "" })}
+ >
+ <Plus className="size-4" /> Add entry
+ </Button>
+ </EmptyContent>
+ </Empty>
+ ) : (
+ <div className="mt-3 space-y-2">
+ {metadataFields.map((metaField, index) => (
+ <div key={metaField.id} className="flex items-start gap-2">
<Controller
control={control}
- name="profileId"
- render={({ field: { onChange, value }, fieldState: { error } }) => (
- <Field>
- <FieldLabel>
- Certificate Profile <span className="text-danger">*</span>
- </FieldLabel>
- <FieldContent>
- <Select value={value || ""} onValueChange={(val) => onChange(val)}>
- <SelectTrigger className="w-full" isError={Boolean(error)}>
- <SelectValue placeholder="Select a certificate profile" />
- </SelectTrigger>
- <SelectContent position="popper">
- {availableProfiles.length === 0 && applicationId ? (
- <div className="px-3 py-3 text-xs leading-snug whitespace-normal text-muted">
- Only profiles with API enrollment configured on this
- Application are listed here. Configure API enrollment under
- this Application&apos;s Settings tab.
- </div>
- ) : (
- availableProfiles.map((profile) => (
- <SelectItem key={profile.id} value={profile.id}>
- {profile.slug}
- </SelectItem>
- ))
- )}
- </SelectContent>
- </Select>
- {isAdcsProfile && (
- <FieldDescription>{externalCaHint}</FieldDescription>
- )}
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
+ name={`metadata.${index}.key`}
+ render={({ field, fieldState: { error } }) => (
+ <Input
+ {...field}
+ placeholder="Key"
+ className="flex-1"
+ isError={Boolean(error)}
+ />
)}
/>
- )}
- </div>
- )}
-
- {currentStepKey !== "profile" && (actualSelectedProfile || profileId) && (
- <div className="space-y-4">
- {currentStepKey === "options" && profileId && isAdcsProfile && (
- <p className="mb-4 text-xs text-mineshaft-400">{externalCaHint}</p>
- )}
-
- {currentStepKey === "csr" && (
<Controller
control={control}
- name="csr"
- render={({ field: { value, ...field }, fieldState: { error } }) => (
- <Field className="mb-4">
- <FieldLabel>
- Certificate Signing Request (CSR){" "}
- <span className="text-danger">*</span>
- </FieldLabel>
- <TextArea
- {...field}
- value={value ?? ""}
- spellCheck={false}
- isError={Boolean(error)}
- placeholder={
- "-----BEGIN CERTIFICATE REQUEST-----\n" +
- "MIIByDCCAU4CAQAwfjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWEx\n" +
- "FjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xEjAQBgNVBAoMCURlbW8gQ29ycDEUMBIG\n" +
- "A1UECwwLRW5naW5lZXJpbmcxGDAWBgNVBAMMD2FwcC5leGFtcGxlLmNvbTB2MBAG\n" +
- "ByqGSM49AgEGBSuBBAAiA2IABDHV5yengUugeBcpjsw+iAaxSkCr16LMr3ITyvlM\n" +
- "lDv+AE0Ddc6FsFXJicBfTalM3AKl5F14OCBRfI2jugWJOGCLcKYqRDTDevxQmgCI\n" +
- "IfpRM6+jzPkqe0PsuLhYiRfbFKBRME8GCSqGSIb3DQEJDjFCMEAwPgYDVR0RBDcw\n" +
- "NYIPYXBwLmV4YW1wbGUuY29tghEqLmFwcC5leGFtcGxlLmNvbYIJbG9jYWxob3N0\n" +
- "hwR/AAABMAoGCCqGSM49BAMCA2gAMGUCMGQQYs4lTSc3r/5MlabDx4m+sWaAtDhO\n" +
- "17c3TaoDZOMG6r45mgUskPGTripXV9ItTQIxAJypXNlHnMvks7MO4LmicPqku4MF\n" +
- "IeFqqXMFzC9uAO3iQ8/ji6ukvT6a9A3DE9LLIg==\n" +
- "-----END CERTIFICATE REQUEST-----"
- }
- rows={13}
- className="w-full font-mono text-xs"
- />
- <FieldError errors={[error]} />
- </Field>
+ name={`metadata.${index}.value`}
+ render={({ field }) => (
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ placeholder="Value (optional)"
+ className="flex-1"
+ />
)}
/>
- )}
-
- {currentStepKey === "subject" && constraints.shouldShowSubjectSection && (
- <SubjectAttributesField
- control={control}
- allowedAttributeTypes={constraints.allowedSubjectAttributeTypes}
- error={
- (formState.errors as { subjectAttributes?: { message?: string } })
- .subjectAttributes?.message
- }
- />
- )}
-
- {currentStepKey === "subject" && constraints.shouldShowSanSection && (
- <SubjectAltNamesField
- control={control}
- allowedSanTypes={constraints.allowedSanTypes}
- error={
- (formState.errors as { subjectAltNames?: { message?: string } })
- .subjectAltNames?.message
- }
- />
- )}
-
- {(currentStepKey === "csr" || currentStepKey === "options") &&
- !isAdcsProfile && (
- <Controller
- control={control}
- name="ttl"
- render={({ field, fieldState: { error } }) => (
- <Field className="mb-4">
- <FieldLabel>
- Time to Live (TTL) <span className="text-danger">*</span>
- </FieldLabel>
- <Input
- {...field}
- placeholder="30d, 1y, 8760h"
- isError={Boolean(error)}
- />
- <FieldError errors={[error]} />
- </Field>
- )}
- />
- )}
-
- {currentStepKey === "options" && (
- <>
- <AlgorithmSelectors
- control={control}
- availableSignatureAlgorithms={availableSignatureAlgorithms}
- availableKeyAlgorithms={availableKeyAlgorithms}
- hideSignatureAlgorithm={isAdcsProfile}
- signatureError={
- (formState.errors as { signatureAlgorithm?: { message?: string } })
- .signatureAlgorithm?.message
- }
- keyError={
- (formState.errors as { keyAlgorithm?: { message?: string } })
- .keyAlgorithm?.message
- }
- />
-
- {!isAdcsProfile && (
- <div className="mt-4 space-y-6">
- <KeyUsageSection
- control={control}
- title="Key Usages"
- namePrefix="keyUsages"
- options={filteredKeyUsages}
- requiredUsages={constraints.requiredKeyUsages}
- />
- <KeyUsageSection
- control={control}
- title="Extended Key Usages"
- namePrefix="extendedKeyUsages"
- options={filteredExtendedKeyUsages}
- requiredUsages={constraints.requiredExtendedKeyUsages}
- />
- {constraints.templateAllowsCA && (
- <div>
- <p className="text-sm font-medium text-foreground">
- Basic Constraints
- </p>
- <div className="mt-4 space-y-4">
- <Controller
- control={control}
- name="basicConstraints.isCA"
- render={({ field: { value, onChange } }) => (
- <div className="flex items-start gap-3">
- <Checkbox
- id="isCA"
- variant="project"
- isChecked={
- constraints.templateRequiresCA || value || false
- }
- isDisabled={constraints.templateRequiresCA}
- onCheckedChange={(checked) => {
- if (!constraints.templateRequiresCA) {
- onChange(checked);
- if (!checked) {
- setValue("basicConstraints.pathLength", null);
- }
- }
- }}
- />
- <span className="text-sm text-foreground">
- Issue as Certificate Authority
- <span className="mt-1 block text-xs text-muted">
- This certificate will be issued with the CA:TRUE
- extension.
- </span>
- </span>
- </div>
- )}
- />
-
- {watchedIsCA && (
- <Controller
- control={control}
- name="basicConstraints.pathLength"
- render={({ field, fieldState: { error } }) => {
- const isPathLengthRequired =
- isAwsPcaProfile ||
- (typeof constraints.maxPathLength === "number" &&
- constraints.maxPathLength !== -1);
- return (
- <Field>
- <FieldLabel>
- Path Length{" "}
- {isPathLengthRequired && (
- <span className="text-danger">*</span>
- )}
- </FieldLabel>
- <Input
- {...field}
- type="number"
- min={0}
- max={
- isAwsPcaProfile
- ? AWS_PCA_MAX_CA_PATH_LENGTH
- : undefined
- }
- isError={Boolean(error)}
- placeholder={
- isPathLengthRequired
- ? "Enter path length (required)"
- : "Leave empty for no constraint"
- }
- value={field.value ?? ""}
- onChange={(e) => {
- const val = e.target.value;
- if (val === "") {
- field.onChange(null);
- } else {
- const numVal = parseInt(val, 10);
- field.onChange(
- Number.isNaN(numVal) ? null : numVal
- );
- }
- }}
- />
- <FieldDescription>
- {isAwsPcaProfile
- ? `Sets the pathLen for this CA certificate. Controls how many levels of sub-CAs can exist below. AWS Private CA supports 0 to ${AWS_PCA_MAX_CA_PATH_LENGTH}; 0 means it can only sign end-entity certificates.`
- : "Sets the pathLen for this CA certificate. Controls how many levels of sub-CAs can exist below. Empty means unlimited; 0 means it can only sign end-entity certificates."}
- </FieldDescription>
- <FieldError errors={[error]} />
- </Field>
- );
- }}
- />
- )}
- </div>
- </div>
- )}
- </div>
- )}
- </>
- )}
-
- {currentStepKey === "metadata" && (
- <div>
- <p className="text-sm font-medium text-foreground">Metadata</p>
- {metadataFields.length === 0 ? (
- <Empty className="mt-3 border py-8">
- <EmptyMedia variant="icon">
- <Tags />
- </EmptyMedia>
- <EmptyTitle>No metadata added</EmptyTitle>
- <EmptyContent>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => appendMetadata({ key: "", value: "" })}
- >
- <Plus className="size-4" /> Add entry
- </Button>
- </EmptyContent>
- </Empty>
- ) : (
- <div className="mt-3 space-y-2">
- {metadataFields.map((metaField, index) => (
- <div key={metaField.id} className="flex items-start gap-2">
- <Controller
- control={control}
- name={`metadata.${index}.key`}
- render={({ field, fieldState: { error } }) => (
- <Input
- {...field}
- placeholder="Key"
- className="flex-1"
- isError={Boolean(error)}
- />
- )}
- />
- <Controller
- control={control}
- name={`metadata.${index}.value`}
- render={({ field }) => (
- <Input
- {...field}
- value={field.value ?? ""}
- placeholder="Value (optional)"
- className="flex-1"
- />
- )}
- />
- <IconButton
- type="button"
- variant="ghost"
- aria-label="Remove metadata entry"
- onClick={() => removeMetadata(index)}
- >
- <Trash2 />
- </IconButton>
- </div>
- ))}
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => appendMetadata({ key: "", value: "" })}
- >
- <Plus className="size-4" /> Add entry
- </Button>
- </div>
- )}
- </div>
- )}
- </div>
- )}
- </div>
-
- <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">
- <div className="mb-auto">
- <div className="flex items-center justify-between gap-2">
- <p className="text-[11px] font-medium tracking-wider text-muted uppercase">
- Step {step + 1} · {currentStepMeta.rightLabel}
- </p>
- <DocumentationLinkBadge href={PkiDocsUrls.applications.certificates} />
- </div>
- <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>
- <p className="mt-2 text-sm leading-relaxed text-muted">
- {currentStepMeta.rightDescription}
- </p>
- </div>
- </aside>
- </div>
-
- <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-6 py-4">
- <span className="text-xs text-muted" />
- <div className="flex items-center gap-3">
- <span className="text-xs text-muted">
- Step {step + 1} of {stepKeys.length}
- </span>
- {step > 0 && (
- <Button type="button" variant="outline" onClick={goBack}>
- Back
- </Button>
- )}
- {isLastStep ? (
+ <IconButton
+ type="button"
+ variant="ghost"
+ aria-label="Remove metadata entry"
+ onClick={() => removeMetadata(index)}
+ >
+ <Trash2 />
+ </IconButton>
+ </div>
+ ))}
<Button
type="button"
- variant="project"
- isPending={isSubmitting}
- isDisabled={isSubmitting || (!actualSelectedProfile && !profileId)}
- onClick={handleSubmit(onFormSubmit, onFormInvalid)}
+ variant="outline"
+ size="sm"
+ onClick={() => appendMetadata({ key: "", value: "" })}
>
- Request Certificate
+ <Plus className="size-4" /> Add entry
</Button>
- ) : (
- <Button
- type="button"
- variant="project"
- isDisabled={!selectedProfileReady}
- onClick={goNext}
- >
- Continue
- </Button>
- )}
- </div>
+ </div>
+ )}
</div>
- </form>
- )}
- </SheetContent>
- </Sheet>
+ )}
+ </div>
+ )}
+ </CertificateWizardSheet>
);
};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
index 3459beed57..b992255fde 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
@@ -1,10 +1,142 @@
-import { faRedo } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useEffect, useMemo, useRef } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useNavigate } from "@tanstack/react-router";
+import { RefreshCw } from "lucide-react";
+import { z } from "zod";
import { createNotification } from "@app/components/notifications";
-import { Button, Modal, ModalContent } from "@app/components/v2";
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input,
+ RadioGroup,
+ RadioGroupItem,
+ TextArea
+} from "@app/components/v3";
+import { useOrganization, useProject } from "@app/context";
import { useRenewCertificate } from "@app/hooks/api";
+import { useGetCertificatePolicyById } from "@app/hooks/api/certificatePolicies";
+import { IssuerType, useGetCertificateProfileById } from "@app/hooks/api/certificateProfiles";
+import {
+ CertificateIssuerKind,
+ CertificateRenewalKeySource
+} from "@app/hooks/api/certificates/enums";
+import { useGetCertificateById } from "@app/hooks/api/certificates/queries";
import { UsePopUpState } from "@app/hooks/usePopUp";
+import { PkiDocsUrls } from "@app/pages/cert-manager/pki-docs-urls";
+import {
+ CertSubjectAlternativeNameType,
+ CertSubjectAttributeType
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+
+import { AlgorithmSelectors } from "./AlgorithmSelectors";
+import { BasicConstraintsField } from "./BasicConstraintsField";
+import { buildRenewalFormDefaults, buildRenewalRequestAttributes } from "./certificateRenewalUtils";
+import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";
+import { KeyUsageSection } from "./KeyUsageSection";
+import { SubjectAltNamesField } from "./SubjectAltNamesField";
+import { SubjectAttributesField } from "./SubjectAttributesField";
+import {
+ DEFAULT_TEMPLATE_CONSTRAINTS,
+ deriveTemplateConstraints,
+ useCertificatePolicyOptions
+} from "./useCertificatePolicy";
+
+const formSchema = z
+ .object({
+ keySource: z.nativeEnum(CertificateRenewalKeySource),
+ csr: z.string().trim().optional(),
+ ttl: z.string().trim().min(1, "TTL is required"),
+ subjectAttributes: z
+ .array(
+ z.object({
+ type: z.nativeEnum(CertSubjectAttributeType),
+ value: z.string().trim().min(1, "Value is required")
+ })
+ )
+ .default([]),
+ subjectAltNames: z
+ .array(
+ z.object({
+ type: z.nativeEnum(CertSubjectAlternativeNameType),
+ value: z.string().trim().min(1, "Value is required")
+ })
+ )
+ .default([]),
+ basicConstraints: z
+ .object({
+ isCA: z.boolean().default(false),
+ pathLength: z.number().min(0).nullable().optional()
+ })
+ .default({ isCA: false }),
+ signatureAlgorithm: z.string().optional(),
+ keyAlgorithm: z.string().optional(),
+ keyUsages: z.record(z.boolean().optional()).default({}),
+ extendedKeyUsages: z.record(z.boolean().optional()).default({})
+ })
+ .superRefine((data, ctx) => {
+ if (data.keySource === CertificateRenewalKeySource.Csr && !data.csr) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["csr"],
+ message: "A certificate signing request is required"
+ });
+ }
+ });
+
+export type RenewalFormData = z.infer<typeof formSchema>;
+
+type RenewalStepKey = "setup" | "csr" | "subject" | "options";
+
+const STEP_META: Record<RenewalStepKey, WizardStep> = {
+ setup: {
+ name: "Renewal setup",
+ shortDescription: "Key pair",
+ subtitle: "Choose how this renewal handles the key pair.",
+ rightDescription:
+ "Decide whether the renewed certificate reuses the existing key pair or generates a new one. The key algorithm is fixed whenever the key is reused."
+ },
+ csr: {
+ name: "Signing request",
+ 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."
+ },
+ subject: {
+ name: "Subject",
+ shortDescription: "Names and SANs",
+ subtitle: "These are copied from the current certificate. Change only what should differ.",
+ rightDescription:
+ "Subject attributes and alternative names identify the certificate. They start as a copy of the current certificate, and the profile's policy still constrains what they may contain."
+ },
+ options: {
+ name: "Options",
+ shortDescription: "Validity and key usage",
+ title: "Certificate options",
+ 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."
+ }
+};
+
+const STEP_FIELDS: Record<RenewalStepKey, string[]> = {
+ setup: ["keySource"],
+ csr: ["csr", "ttl"],
+ subject: ["subjectAttributes", "subjectAltNames"],
+ options: [
+ "ttl",
+ "signatureAlgorithm",
+ "keyAlgorithm",
+ "keyUsages",
+ "extendedKeyUsages",
+ "basicConstraints"
+ ]
+};
type Props = {
popUp: UsePopUpState<["renewCertificate"]>;
@@ -15,66 +147,397 @@ type Props = {
};
export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { mutateAsync: renewCertificate, isPending: isRenewing } = useRenewCertificate();
+ const { currentProject } = useProject();
+ const { currentOrg } = useOrganization();
+ const navigate = useNavigate();
+
+ const isOpen = Boolean(popUp?.renewCertificate?.isOpen);
+ const { certificateId } = (popUp?.renewCertificate?.data as { certificateId?: string }) ?? {};
+
+ const { data: certificateData } = useGetCertificateById(
+ isOpen && certificateId ? certificateId : ""
+ );
+ const certificate = certificateData?.certificate;
+
+ const { data: profile } = useGetCertificateProfileById({
+ profileId: certificate?.profileId ?? ""
+ });
+ const { data: policyData } = useGetCertificatePolicyById({
+ policyId: profile?.certificatePolicyId ?? "",
+ applicationId: certificate?.applicationId ?? undefined
+ });
+
+ const constraints = useMemo(
+ () => (policyData ? deriveTemplateConstraints(policyData) : DEFAULT_TEMPLATE_CONSTRAINTS),
+ [policyData]
+ );
+
+ const isPolicyResolved =
+ Boolean(policyData) || (Boolean(profile) && !profile?.certificatePolicyId);
+ const {
+ filteredKeyUsages,
+ filteredExtendedKeyUsages,
+ availableSignatureAlgorithms,
+ availableKeyAlgorithms
+ } = useCertificatePolicyOptions(constraints);
+
+ const { mutateAsync: renewCertificate } = useRenewCertificate();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ watch,
+ setValue,
+ formState,
+ formState: { isSubmitting }
+ } = useForm<RenewalFormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ keySource: CertificateRenewalKeySource.New,
+ ttl: "",
+ subjectAttributes: [],
+ subjectAltNames: [],
+ basicConstraints: { isCA: false },
+ keyUsages: {},
+ extendedKeyUsages: {}
+ }
+ });
+
+ const keySource = watch("keySource");
+ const watchedIsCA = watch("basicConstraints.isCA") || false;
+ const sanTypesInForm = (watch("subjectAltNames") ?? []).map((san) => san.type).join(",");
+ const subjectTypesInForm = (watch("subjectAttributes") ?? []).map((attr) => attr.type).join(",");
+
+ const selectableSanTypes = useMemo(
+ () =>
+ Array.from(
+ new Set([
+ ...constraints.allowedSanTypes,
+ ...(sanTypesInForm ? (sanTypesInForm.split(",") as CertSubjectAlternativeNameType[]) : [])
+ ])
+ ),
+ [constraints.allowedSanTypes, sanTypesInForm]
+ );
+
+ const selectableSubjectAttributeTypes = useMemo(
+ () =>
+ Array.from(
+ new Set([
+ ...constraints.allowedSubjectAttributeTypes,
+ ...(subjectTypesInForm
+ ? (subjectTypesInForm.split(",") as CertSubjectAttributeType[])
+ : [])
+ ])
+ ),
+ [constraints.allowedSubjectAttributeTypes, subjectTypesInForm]
+ );
+
+ const isSelfSigned = certificate
+ ? (profile?.issuerType ?? (certificate.caId ? IssuerType.CA : IssuerType.SELF_SIGNED)) ===
+ IssuerType.SELF_SIGNED
+ : false;
+ let reuseRefusalReason: string | undefined;
+ if (isSelfSigned && certificate?.hasPrivateKey === false) {
+ reuseRefusalReason =
+ "Infisical does not hold this certificate's private key, which is what signs a self-signed certificate.";
+ } else if (!isSelfSigned && certificate?.caType === CertificateIssuerKind.External) {
+ reuseRefusalReason =
+ "The issuing certificate authority does not support reusing an existing key pair.";
+ }
+ const csrRefusalReason = isSelfSigned
+ ? "A self-signed certificate is signed by its own private key, which a signing request does not carry."
+ : undefined;
+ const isReuseAllowed = !reuseRefusalReason;
+ const isCsrAllowed = !csrRefusalReason;
+
+ useEffect(() => {
+ const isRefused =
+ (keySource === CertificateRenewalKeySource.Reuse && !isReuseAllowed) ||
+ (keySource === CertificateRenewalKeySource.Csr && !isCsrAllowed);
+ if (isRefused) setValue("keySource", CertificateRenewalKeySource.New);
+ }, [keySource, isReuseAllowed, isCsrAllowed, setValue]);
+
+ const stepKeys = useMemo<RenewalStepKey[]>(() => {
+ if (keySource === CertificateRenewalKeySource.Csr) return ["setup", "csr"];
+ const keys: RenewalStepKey[] = ["setup"];
+ if (constraints.shouldShowSubjectSection || constraints.shouldShowSanSection)
+ keys.push("subject");
+ keys.push("options");
+ return keys;
+ }, [keySource, constraints.shouldShowSubjectSection, constraints.shouldShowSanSection]);
+
+ const { step, setStep, currentStepKey, goBack, goNext, onFormInvalid } = useWizardSteps({
+ stepKeys,
+ stepFields: STEP_FIELDS,
+ invalidMessage: "Please fix the highlighted fields before renewing."
+ });
+
+ const steps = useMemo(() => stepKeys.map((key) => STEP_META[key]), [stepKeys]);
+
+ const seededCertificateIdRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (!isOpen) {
+ seededCertificateIdRef.current = null;
+ return;
+ }
+ if (!certificate || !isPolicyResolved || seededCertificateIdRef.current === certificate.id)
+ return;
+
+ seededCertificateIdRef.current = certificate.id;
+ reset(buildRenewalFormDefaults(certificate, constraints));
+ setStep(0);
+ }, [isOpen, certificate, isPolicyResolved, constraints, reset]);
+
+ const closeWizard = () => {
+ handlePopUpToggle("renewCertificate", false);
+ reset();
+ setStep(0);
+ };
- const onRenewConfirm = async () => {
- const { certificateId } = popUp.renewCertificate.data as { certificateId: string };
+ const onFormSubmit = async (formData: RenewalFormData) => {
+ if (!certificateId) return;
const result = await renewCertificate({
- certificateId
+ certificateId,
+ renewalKeySource: formData.keySource,
+ ...(formData.keySource === CertificateRenewalKeySource.Csr && { csr: formData.csr }),
+ attributes: buildRenewalRequestAttributes({ formData, constraints })
});
- const notificationText = result.certificateRequestId
- ? `Certificate renewal initiated successfully. Certificate Request ID: ${result.certificateRequestId}`
- : "Certificate renewed successfully";
-
createNotification({
- text: notificationText,
+ text: result.certificateId
+ ? "Certificate renewed successfully"
+ : `Certificate renewal submitted. This may take a few minutes to process. Certificate Request ID: ${result.certificateRequestId}`,
type: "success"
});
- handlePopUpToggle("renewCertificate", false);
- };
+ closeWizard();
- const certificateData = popUp.renewCertificate.data as {
- certificateId: string;
- commonName: string;
- profileId: string;
+ if (currentOrg?.id && currentProject?.id && result.certificateId && result.certificate) {
+ navigate({
+ to: "/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId",
+ params: {
+ orgId: currentOrg.id,
+ projectId: currentProject.id,
+ certificateId: result.certificateId
+ }
+ });
+ }
};
+ const keySourceOptions = useMemo(
+ () => [
+ {
+ value: CertificateRenewalKeySource.Reuse,
+ label: "Reuse the existing key pair",
+ description: certificate?.hasPrivateKey
+ ? "Keep the same private and public key."
+ : "Renew from the signing request this certificate was issued from, so the public key stays the same.",
+ isDisabled: !isReuseAllowed,
+ disabledReason: reuseRefusalReason
+ },
+ {
+ value: CertificateRenewalKeySource.New,
+ label: "Generate a new key pair",
+ description: "Issue the certificate with a brand new key.",
+ isDisabled: false
+ },
+ {
+ value: CertificateRenewalKeySource.Csr,
+ label: "Use a CSR",
+ description: "Provide a certificate signing request with its own key.",
+ isDisabled: !isCsrAllowed,
+ disabledReason: csrRefusalReason
+ }
+ ],
+ [certificate?.hasPrivateKey, isReuseAllowed, isCsrAllowed, reuseRefusalReason, csrRefusalReason]
+ );
+
return (
- <Modal
- isOpen={popUp?.renewCertificate?.isOpen}
- onOpenChange={(isOpen) => {
- handlePopUpToggle("renewCertificate", isOpen);
- }}
+ <CertificateWizardSheet
+ isOpen={isOpen}
+ onOpenChange={(open) => (open ? handlePopUpToggle("renewCertificate", true) : closeWizard())}
+ icon={<RefreshCw className="h-5 w-5" />}
+ title="Renew certificate"
+ description={certificate?.commonName || certificate?.friendlyName || "Certificate"}
+ steps={steps}
+ activeStep={step}
+ onStepChange={setStep}
+ docsHref={PkiDocsUrls.applications.certificateRenewal}
+ submitLabel="Renew certificate"
+ onSubmit={handleSubmit(onFormSubmit, onFormInvalid)}
+ onBack={goBack}
+ onContinue={goNext}
+ isSubmitting={isSubmitting}
+ isSubmitDisabled={!certificate}
+ isContinueDisabled={!certificate}
>
- <ModalContent title={`Renew Certificate: ${certificateData?.commonName || ""}`}>
- <div className="mb-6">
- <p className="mb-4 text-sm text-mineshaft-300">
- Are you sure you want to renew this certificate now?
- </p>
+ {currentStepKey === "setup" && (
+ <Controller
+ control={control}
+ name="keySource"
+ render={({ field: { onChange, value } }) => (
+ <Field>
+ <FieldLabel>Key pair</FieldLabel>
+ <FieldContent>
+ <RadioGroup value={value} onValueChange={onChange} className="gap-2">
+ {keySourceOptions.map((option) => (
+ <FieldLabel
+ key={option.value}
+ htmlFor={`key-source-${option.value}`}
+ variant="project"
+ >
+ <Field orientation="horizontal" className="items-center gap-3">
+ <div className="min-w-0 flex-1 text-left">
+ <p className="text-sm font-medium text-foreground">{option.label}</p>
+ <p className="text-xs text-muted">
+ {option.isDisabled ? option.disabledReason : option.description}
+ </p>
+ </div>
+ <RadioGroupItem
+ id={`key-source-${option.value}`}
+ value={option.value}
+ disabled={option.isDisabled}
+ className="sr-only"
+ />
+ </Field>
+ </FieldLabel>
+ ))}
+ </RadioGroup>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+
+ {currentStepKey === "csr" && (
+ <div className="space-y-4">
+ <Controller
+ control={control}
+ name="csr"
+ render={({ field: { value, ...field }, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Certificate signing request <span className="text-danger">*</span>
+ </FieldLabel>
+ <TextArea
+ {...field}
+ value={value ?? ""}
+ spellCheck={false}
+ isError={Boolean(error)}
+ placeholder="-----BEGIN CERTIFICATE REQUEST-----"
+ rows={12}
+ className="w-full font-mono text-xs"
+ />
+ <FieldDescription>
+ The subject, key, and extensions are taken from this CSR.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="ttl"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Validity (TTL) <span className="text-danger">*</span>
+ </FieldLabel>
+ <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(error)} />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ </div>
+ )}
+
+ {currentStepKey === "subject" && (
+ <div className="space-y-4">
+ {constraints.shouldShowSubjectSection && (
+ <SubjectAttributesField
+ control={control}
+ allowedAttributeTypes={selectableSubjectAttributeTypes}
+ error={
+ (formState.errors as { subjectAttributes?: { message?: string } }).subjectAttributes
+ ?.message
+ }
+ />
+ )}
+ {constraints.shouldShowSanSection && (
+ <SubjectAltNamesField
+ control={control}
+ allowedSanTypes={selectableSanTypes}
+ error={
+ (formState.errors as { subjectAltNames?: { message?: string } }).subjectAltNames
+ ?.message
+ }
+ />
+ )}
</div>
+ )}
+
+ {currentStepKey === "options" && (
+ <div className="space-y-4">
+ <Controller
+ control={control}
+ name="ttl"
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>
+ Validity (TTL) <span className="text-danger">*</span>
+ </FieldLabel>
+ <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(error)} />
+ <FieldDescription>
+ The renewed certificate is valid for this long, starting now.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+
+ <AlgorithmSelectors
+ control={control}
+ availableSignatureAlgorithms={availableSignatureAlgorithms}
+ availableKeyAlgorithms={availableKeyAlgorithms}
+ keyAlgorithmDisabledReason={
+ keySource === CertificateRenewalKeySource.Reuse
+ ? "The key algorithm is fixed while the existing key pair is reused."
+ : undefined
+ }
+ />
- <div className="flex items-center gap-3">
- <Button
- onClick={onRenewConfirm}
- colorSchema="primary"
- isLoading={isRenewing}
- isDisabled={isRenewing}
- >
- <FontAwesomeIcon icon={faRedo} className="mr-2" />
- Renew Now
- </Button>
- <Button
- colorSchema="secondary"
- variant="plain"
- onClick={() => handlePopUpToggle("renewCertificate", false)}
- >
- Cancel
- </Button>
+ <div className="mt-4 space-y-6">
+ <KeyUsageSection
+ control={control}
+ title="Key Usages"
+ namePrefix="keyUsages"
+ options={filteredKeyUsages}
+ requiredUsages={constraints.requiredKeyUsages}
+ />
+ <KeyUsageSection
+ control={control}
+ title="Extended Key Usages"
+ namePrefix="extendedKeyUsages"
+ options={filteredExtendedKeyUsages}
+ requiredUsages={constraints.requiredExtendedKeyUsages}
+ />
+ {constraints.templateAllowsCA && (
+ <BasicConstraintsField
+ control={control}
+ setValue={setValue}
+ isCA={watchedIsCA}
+ templateRequiresCA={constraints.templateRequiresCA}
+ maxPathLength={
+ constraints.maxPathLength === -1 ? undefined : constraints.maxPathLength
+ }
+ idPrefix="renewal"
+ />
+ )}
+ </div>
</div>
- </ModalContent>
- </Modal>
+ )}
+ </CertificateWizardSheet>
);
};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx
new file mode 100644
index 0000000000..23e4ff3af0
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateWizardSheet.tsx
@@ -0,0 +1,215 @@
+import { ReactNode, useCallback, useMemo, useState } from "react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ DocumentationLinkBadge,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ Stepper,
+ StepperList,
+ StepperStep
+} from "@app/components/v3";
+
+export type WizardStep = {
+ name: string;
+ shortDescription: string;
+ title?: string;
+ subtitle: string;
+ rightLabel?: string;
+ rightDescription: string;
+};
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ icon: ReactNode;
+ title: string;
+ description?: string;
+ steps: WizardStep[];
+ activeStep: number;
+ onStepChange: (index: number) => void;
+ docsHref?: string;
+ children: ReactNode;
+ overrideContent?: ReactNode;
+ submitLabel: string;
+ onSubmit: () => void;
+ onBack: () => void;
+ onContinue: () => void;
+ isSubmitting?: boolean;
+ isSubmitDisabled?: boolean;
+ isContinueDisabled?: boolean;
+};
+
+export const useWizardSteps = <TStepKey extends string>({
+ stepKeys,
+ stepFields,
+ invalidMessage
+}: {
+ stepKeys: readonly TStepKey[];
+ stepFields: Record<TStepKey, string[]>;
+ invalidMessage: string;
+}) => {
+ const [step, setStep] = useState(0);
+ const activeStep = Math.min(step, stepKeys.length - 1);
+
+ const goBack = useCallback(() => setStep((s) => Math.max(0, s - 1)), []);
+ const goNext = useCallback(
+ () => setStep((s) => Math.min(stepKeys.length - 1, s + 1)),
+ [stepKeys.length]
+ );
+
+ const onFormInvalid = useCallback(
+ (errors: Record<string, unknown>) => {
+ const errorKeys = Object.keys(errors);
+ const idx = stepKeys.findIndex((key) =>
+ stepFields[key].some((name) => errorKeys.includes(name))
+ );
+ if (idx >= 0) setStep(idx);
+ createNotification({ text: invalidMessage, type: "error" });
+ },
+ [stepKeys, stepFields, invalidMessage]
+ );
+
+ return {
+ step: activeStep,
+ setStep,
+ currentStepKey: stepKeys[activeStep],
+ isLastStep: activeStep === stepKeys.length - 1,
+ goBack,
+ goNext,
+ onFormInvalid
+ };
+};
+
+export const CertificateWizardSheet = ({
+ isOpen,
+ onOpenChange,
+ icon,
+ title,
+ description,
+ steps,
+ activeStep,
+ onStepChange,
+ docsHref,
+ children,
+ overrideContent,
+ submitLabel,
+ onSubmit,
+ onBack,
+ onContinue,
+ isSubmitting = false,
+ isSubmitDisabled = false,
+ isContinueDisabled = false
+}: Props) => {
+ const step = steps[Math.min(activeStep, steps.length - 1)];
+ const isLastStep = activeStep === steps.length - 1;
+
+ const stepperSteps = useMemo(
+ () =>
+ steps.map((s, i) => (
+ <StepperStep key={s.name} index={i} title={s.name} description={s.shortDescription} />
+ )),
+ [steps]
+ );
+
+ return (
+ <Sheet open={isOpen} onOpenChange={onOpenChange}>
+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 p-0 sm:max-w-[1100px]">
+ <SheetHeader className="border-b border-border">
+ <div className="flex w-full items-start gap-2">
+ <div className="flex h-10 w-10 items-center justify-center rounded-md bg-project/10 text-project">
+ {icon}
+ </div>
+ <div className="min-w-0">
+ <SheetTitle>{title}</SheetTitle>
+ {description && (
+ <SheetDescription className="truncate text-muted">{description}</SheetDescription>
+ )}
+ </div>
+ </div>
+ </SheetHeader>
+
+ {overrideContent ?? (
+ <form onSubmit={(e) => e.preventDefault()} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">
+ <p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">
+ Setup steps
+ </p>
+ <Stepper
+ activeStep={activeStep}
+ orientation="vertical"
+ onStepChange={(i) => {
+ if (isSubmitting) return;
+ if (i < activeStep) onStepChange(i);
+ }}
+ >
+ <StepperList>{stepperSteps}</StepperList>
+ </Stepper>
+ </aside>
+
+ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">
+ <div className="mb-6">
+ <h2 className="text-lg font-semibold text-foreground">
+ {step.title ?? step.name}
+ </h2>
+ <p className="mt-1 text-sm text-muted">{step.subtitle}</p>
+ </div>
+ {children}
+ </div>
+
+ <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">
+ <div className="mb-auto">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">
+ Step {activeStep + 1} · {step.rightLabel ?? step.name}
+ </p>
+ {docsHref && <DocumentationLinkBadge href={docsHref} />}
+ </div>
+ <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>
+ <p className="mt-2 text-sm leading-relaxed text-muted">{step.rightDescription}</p>
+ </div>
+ </aside>
+ </div>
+
+ <SheetFooter className="shrink-0 items-center justify-end border-t px-6">
+ <span className="text-xs text-muted">
+ Step {activeStep + 1} of {steps.length}
+ </span>
+ {activeStep > 0 && (
+ <Button type="button" variant="outline" onClick={onBack}>
+ Back
+ </Button>
+ )}
+ {isLastStep ? (
+ <Button
+ type="button"
+ variant="project"
+ isPending={isSubmitting}
+ isDisabled={isSubmitting || isSubmitDisabled}
+ onClick={onSubmit}
+ >
+ {submitLabel}
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ variant="project"
+ isDisabled={isContinueDisabled}
+ onClick={onContinue}
+ >
+ Continue
+ </Button>
+ )}
+ </SheetFooter>
+ </form>
+ )}
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
index caa82e7194..5d44dd43a6 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
@@ -1207,7 +1207,6 @@ export const CertificatesTable = ({
const canRenew =
!isInventoryView &&
(certificate.profileId || certificate.caId) &&
- certificate.hasPrivateKey !== false &&
!certificate.renewedByCertificateId &&
!isRevoked &&
!isExpired;
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts
index a5717a158c..8d83f4bf49 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/buildManagedRequest.ts
@@ -4,7 +4,7 @@ import { TUnifiedCertificateIssuanceDTO } from "@app/hooks/api/certificates/type
import { CertSubjectAttributeType } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
import type { FormData } from "./CertificateIssuanceModal";
-import { filterUsages, formatSubjectAltNames } from "./certificateUtils";
+import { filterUsages, formatSubjectAltNames, SUBJECT_ATTR_MAP } from "./certificateUtils";
import type { TemplateConstraints } from "./useCertificatePolicy";
type ManagedFormData = Extract<FormData, { requestMethod: "managed" }>;
@@ -15,23 +15,6 @@ type ManagedIssuanceRequest = Omit<TUnifiedCertificateIssuanceDTO, "attributes">
};
};
-type SubjectAttrKey =
- | "commonName"
- | "organization"
- | "organizationalUnit"
- | "country"
- | "state"
- | "locality";
-
-const SUBJECT_ATTR_MAP: { attrType: CertSubjectAttributeType; requestKey: SubjectAttrKey }[] = [
- { attrType: CertSubjectAttributeType.COMMON_NAME, requestKey: "commonName" },
- { attrType: CertSubjectAttributeType.ORGANIZATION, requestKey: "organization" },
- { attrType: CertSubjectAttributeType.ORGANIZATIONAL_UNIT, requestKey: "organizationalUnit" },
- { attrType: CertSubjectAttributeType.COUNTRY, requestKey: "country" },
- { attrType: CertSubjectAttributeType.STATE, requestKey: "state" },
- { attrType: CertSubjectAttributeType.LOCALITY, requestKey: "locality" }
-];
-
type BuildManagedRequestParams = {
formData: ManagedFormData;
applicationId?: string;
@@ -81,8 +64,9 @@ export const buildManagedRequest = ({
if (subjectAttributes && subjectAttributes.length > 0) {
SUBJECT_ATTR_MAP.forEach(({ attrType, requestKey }) => {
const attr = subjectAttributes.find((a) => a.type === attrType);
- if (attr?.value) {
- request.attributes[requestKey] = attr.value;
+ const value = attr?.value?.trim();
+ if (value) {
+ request.attributes[requestKey] = value;
} else if (defaults?.[requestKey]) {
request.attributes[requestKey] = null;
}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
new file mode 100644
index 0000000000..cffd51354e
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
@@ -0,0 +1,139 @@
+import { CertificateRenewalKeySource } from "@app/hooks/api/certificates/enums";
+import { TCertificate, TRenewCertificateAttributes } from "@app/hooks/api/certificates/types";
+import {
+ CertSubjectAlternativeNameType,
+ CertSubjectAttributeType
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+
+import type { RenewalFormData } from "./CertificateRenewalModal";
+import {
+ filterUsages,
+ formatSubjectAltNames,
+ getAttributeValue,
+ sanTypeCandidatesFromValue,
+ SUBJECT_ATTR_MAP
+} from "./certificateUtils";
+import type { TemplateConstraints } from "./useCertificatePolicy";
+
+const MS_PER_DAY = 24 * 60 * 60 * 1000;
+
+const deriveTtlFromCertificate = (cert: TCertificate): string => {
+ const spanMs = new Date(cert.notAfter).getTime() - new Date(cert.notBefore).getTime();
+ if (!Number.isFinite(spanMs) || spanMs <= 0) return "";
+
+ const days = Math.floor(spanMs / MS_PER_DAY);
+ if (days > 0) return `${days}d`;
+
+ const hours = Math.max(1, Math.floor(spanMs / (60 * 60 * 1000)));
+ return `${hours}h`;
+};
+
+const resolveSanType = (
+ value: string,
+ allowedSanTypes: CertSubjectAlternativeNameType[]
+): CertSubjectAlternativeNameType => {
+ const candidates = sanTypeCandidatesFromValue(value);
+ if (!allowedSanTypes.length) return candidates[0];
+ return candidates.find((candidate) => allowedSanTypes.includes(candidate)) ?? candidates[0];
+};
+
+const parseCertificateSans = (
+ cert: TCertificate,
+ allowedSanTypes: CertSubjectAlternativeNameType[]
+): { type: CertSubjectAlternativeNameType; value: string }[] => {
+ const raw = cert.subjectAltNames || cert.altNames || "";
+ return raw
+ .split(",")
+ .map((san) => san.trim())
+ .filter(Boolean)
+ .map((value) => ({ type: resolveSanType(value, allowedSanTypes), value }));
+};
+
+const buildSubjectAttributes = (cert: TCertificate) => {
+ const attributes: { type: CertSubjectAttributeType; value: string }[] = [];
+
+ SUBJECT_ATTR_MAP.forEach(({ attrType, requestKey }) => {
+ const value = requestKey === "commonName" ? cert.commonName : cert.subject?.[requestKey];
+ if (value) attributes.push({ type: attrType, value });
+ });
+
+ cert.subject?.domainComponents?.forEach((dc) => {
+ if (dc) attributes.push({ type: CertSubjectAttributeType.DOMAIN_COMPONENT, value: dc });
+ });
+
+ return attributes;
+};
+
+export const buildRenewalFormDefaults = (
+ cert: TCertificate,
+ constraints: TemplateConstraints
+): RenewalFormData => ({
+ keySource: CertificateRenewalKeySource.New,
+ csr: "",
+ ttl: deriveTtlFromCertificate(cert),
+ subjectAttributes: buildSubjectAttributes(cert),
+ subjectAltNames: parseCertificateSans(cert, constraints.allowedSanTypes),
+ basicConstraints: {
+ isCA: Boolean(cert.basicConstraints?.isCA),
+ pathLength: cert.basicConstraints?.pathLength ?? null
+ },
+ signatureAlgorithm: cert.signatureAlgorithm ?? "",
+ keyAlgorithm: cert.keyAlgorithm ?? "",
+ keyUsages: Object.fromEntries((cert.keyUsages ?? []).map((usage) => [usage, true])),
+ extendedKeyUsages: Object.fromEntries(
+ (cert.extendedKeyUsages ?? []).map((usage) => [usage, true])
+ )
+});
+
+const buildBasicConstraints = (
+ formData: RenewalFormData,
+ constraints: TemplateConstraints
+): TRenewCertificateAttributes["basicConstraints"] => {
+ if (!constraints.templateAllowsCA) return undefined;
+
+ const isCA = constraints.templateRequiresCA || formData.basicConstraints.isCA;
+ const { pathLength } = formData.basicConstraints;
+
+ return { isCA, ...(isCA && pathLength !== null && pathLength !== undefined && { pathLength }) };
+};
+
+export const buildRenewalRequestAttributes = ({
+ formData,
+ constraints
+}: {
+ formData: RenewalFormData;
+ constraints: TemplateConstraints;
+}): TRenewCertificateAttributes => {
+ const basicConstraints = buildBasicConstraints(formData, constraints);
+
+ if (formData.keySource === CertificateRenewalKeySource.Csr) {
+ return { ttl: formData.ttl, ...(basicConstraints && { basicConstraints }) };
+ }
+
+ const attributes: TRenewCertificateAttributes = {
+ ttl: formData.ttl,
+ keyUsages: filterUsages(formData.keyUsages as Record<string, boolean>),
+ extendedKeyUsages: filterUsages(formData.extendedKeyUsages as Record<string, boolean>),
+ ...(formData.signatureAlgorithm && { signatureAlgorithm: formData.signatureAlgorithm }),
+ ...(formData.keySource !== CertificateRenewalKeySource.Reuse &&
+ formData.keyAlgorithm && { keyAlgorithm: formData.keyAlgorithm }),
+ ...(basicConstraints && { basicConstraints })
+ };
+
+ if (constraints.shouldShowSubjectSection) {
+ SUBJECT_ATTR_MAP.forEach(({ attrType, requestKey }) => {
+ attributes[requestKey] = getAttributeValue(formData.subjectAttributes, attrType) || null;
+ });
+
+ attributes.domainComponents = formData.subjectAttributes
+ .filter((attr) => attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT)
+ .map((attr) => attr.value.trim())
+ .filter(Boolean);
+ }
+
+ if (constraints.shouldShowSanSection) {
+ attributes.altNames = formatSubjectAltNames(formData.subjectAltNames);
+ }
+
+ return attributes;
+};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateUtils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateUtils.ts
index 3bdf49d7d7..0d3f967aa0 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateUtils.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateUtils.ts
@@ -1,4 +1,8 @@
-import { CertSubjectAlternativeNameType } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+import { isIPv4, isIPv6 } from "@app/helpers/ip";
+import {
+ CertSubjectAlternativeNameType,
+ CertSubjectAttributeType
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
export const getSanPlaceholder = (sanType: CertSubjectAlternativeNameType): string => {
switch (sanType) {
@@ -30,6 +34,17 @@ export type SubjectAltName = {
value: string;
};
+export const sanTypeCandidatesFromValue = (value: string): CertSubjectAlternativeNameType[] => {
+ if (isIPv4(value) || isIPv6(value)) return [CertSubjectAlternativeNameType.IP_ADDRESS];
+ if (value.includes("@"))
+ return [CertSubjectAlternativeNameType.EMAIL, CertSubjectAlternativeNameType.UPN];
+ if (value.startsWith("http")) return [CertSubjectAlternativeNameType.URI];
+ return [CertSubjectAlternativeNameType.DNS_NAME];
+};
+
+export const detectSanTypeFromValue = (value: string): CertSubjectAlternativeNameType =>
+ sanTypeCandidatesFromValue(value)[0];
+
export const formatSubjectAltNames = (subjectAltNames: SubjectAltName[]) => {
return subjectAltNames
.filter((san) => san.value.trim())
@@ -48,7 +63,24 @@ export const filterUsages = <T extends Record<string, boolean>>(usages: T): stri
export const getAttributeValue = (
subjectAttributes: Array<{ type: string; value: string }> | undefined,
type: string
-): string => {
- const foundAttr = subjectAttributes?.find((attr) => attr.type === type);
- return foundAttr?.value || "";
-};
+): string => subjectAttributes?.find((attr) => attr.type === type)?.value?.trim() || "";
+
+export type SubjectAttrKey =
+ | "commonName"
+ | "organization"
+ | "organizationalUnit"
+ | "country"
+ | "state"
+ | "locality";
+
+export const SUBJECT_ATTR_MAP: {
+ attrType: CertSubjectAttributeType;
+ requestKey: SubjectAttrKey;
+}[] = [
+ { attrType: CertSubjectAttributeType.COMMON_NAME, requestKey: "commonName" },
+ { attrType: CertSubjectAttributeType.ORGANIZATION, requestKey: "organization" },
+ { attrType: CertSubjectAttributeType.ORGANIZATIONAL_UNIT, requestKey: "organizationalUnit" },
+ { attrType: CertSubjectAttributeType.COUNTRY, requestKey: "country" },
+ { attrType: CertSubjectAttributeType.STATE, requestKey: "state" },
+ { attrType: CertSubjectAttributeType.LOCALITY, requestKey: "locality" }
+];
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
index d9a4edbfdf..c387ca30d2 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificatePolicy.ts
@@ -72,36 +72,90 @@ export type TemplateConstraints = {
maxPathLength?: number;
};
-export const useCertificatePolicy = (
- templateData: any,
- selectedProfile: any,
- isModalOpen: boolean,
- setValue: UseFormSetValue<any>,
- watch: UseFormWatch<any>
-) => {
- const [constraints, setConstraints] = useState<TemplateConstraints>({
- allowedKeyUsages: [],
- allowedExtendedKeyUsages: [],
- requiredKeyUsages: [],
- requiredExtendedKeyUsages: [],
- restrictKeyUsages: false,
- restrictExtendedKeyUsages: false,
- allowedSignatureAlgorithms: [],
- allowedKeyAlgorithms: [],
- allowedSanTypes: [
- CertSubjectAlternativeNameType.DNS_NAME,
- CertSubjectAlternativeNameType.IP_ADDRESS,
- CertSubjectAlternativeNameType.EMAIL,
- CertSubjectAlternativeNameType.URI
+export const DEFAULT_TEMPLATE_CONSTRAINTS: TemplateConstraints = {
+ allowedKeyUsages: [],
+ allowedExtendedKeyUsages: [],
+ requiredKeyUsages: [],
+ requiredExtendedKeyUsages: [],
+ restrictKeyUsages: false,
+ restrictExtendedKeyUsages: false,
+ allowedSignatureAlgorithms: [],
+ allowedKeyAlgorithms: [],
+ allowedSanTypes: [
+ CertSubjectAlternativeNameType.DNS_NAME,
+ CertSubjectAlternativeNameType.IP_ADDRESS,
+ CertSubjectAlternativeNameType.EMAIL,
+ CertSubjectAlternativeNameType.URI
+ ],
+ allowedSubjectAttributeTypes: [CertSubjectAttributeType.COMMON_NAME],
+ shouldShowSanSection: true,
+ shouldShowSubjectSection: true,
+ templateAllowsCA: false,
+ templateRequiresCA: false,
+ maxPathLength: undefined
+};
+
+export const deriveTemplateConstraints = (templateData: any): TemplateConstraints => {
+ const isCaPolicy =
+ (templateData.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED;
+ const templateAllowsCA =
+ isCaPolicy === CertPolicyState.ALLOWED || isCaPolicy === CertPolicyState.REQUIRED;
+
+ const sanTypes: CertSubjectAlternativeNameType[] = templateData.sans
+ ? Array.from(
+ new Set<CertSubjectAlternativeNameType>(
+ templateData.sans.map(
+ (sanPolicy: any) => sanPolicy.type as CertSubjectAlternativeNameType
+ )
+ )
+ )
+ : [...DEFAULT_TEMPLATE_CONSTRAINTS.allowedSanTypes];
+ const subjectAttributeTypes: CertSubjectAttributeType[] = templateData.subject
+ ? Array.from(
+ new Set<CertSubjectAttributeType>(
+ templateData.subject.map(
+ (subjectPolicy: any) => subjectPolicy.type as CertSubjectAttributeType
+ )
+ )
+ )
+ : [
+ CertSubjectAttributeType.COMMON_NAME,
+ CertSubjectAttributeType.ORGANIZATION,
+ CertSubjectAttributeType.ORGANIZATIONAL_UNIT,
+ CertSubjectAttributeType.COUNTRY,
+ CertSubjectAttributeType.STATE,
+ CertSubjectAttributeType.LOCALITY,
+ CertSubjectAttributeType.DOMAIN_COMPONENT
+ ];
+
+ const constraints: TemplateConstraints = {
+ allowedSignatureAlgorithms: templateData.algorithms?.signature || [],
+ allowedKeyAlgorithms: templateData.algorithms?.keyAlgorithm || [],
+ allowedKeyUsages: [
+ ...(templateData.keyUsages?.required || []),
+ ...(templateData.keyUsages?.allowed || [])
+ ],
+ allowedExtendedKeyUsages: [
+ ...(templateData.extendedKeyUsages?.required || []),
+ ...(templateData.extendedKeyUsages?.allowed || [])
],
- allowedSubjectAttributeTypes: [CertSubjectAttributeType.COMMON_NAME],
- shouldShowSanSection: true,
- shouldShowSubjectSection: true,
- templateAllowsCA: false,
- templateRequiresCA: false,
- maxPathLength: undefined
- });
+ requiredKeyUsages: templateData.keyUsages?.required || [],
+ requiredExtendedKeyUsages: templateData.extendedKeyUsages?.required || [],
+ restrictKeyUsages: Boolean(templateData.keyUsages),
+ restrictExtendedKeyUsages: Boolean(templateData.extendedKeyUsages),
+ allowedSanTypes: sanTypes,
+ allowedSubjectAttributeTypes: subjectAttributeTypes,
+ shouldShowSanSection: sanTypes.length > 0,
+ shouldShowSubjectSection: subjectAttributeTypes.length > 0,
+ templateAllowsCA,
+ templateRequiresCA: isCaPolicy === CertPolicyState.REQUIRED,
+ maxPathLength: templateData.basicConstraints?.maxPathLength
+ };
+
+ return constraints;
+};
+export const useCertificatePolicyOptions = (constraints: TemplateConstraints) => {
const filteredKeyUsages = useMemo(() => {
if (!constraints.restrictKeyUsages) return [...KEY_USAGES_OPTIONS];
return KEY_USAGES_OPTIONS.filter(({ value }) => constraints.allowedKeyUsages.includes(value));
@@ -140,29 +194,32 @@ export const useCertificatePolicy = (
.map((opt) => ({ value: opt.value as string, label: opt.label }));
}, [constraints.allowedKeyAlgorithms]);
+ return {
+ filteredKeyUsages,
+ filteredExtendedKeyUsages,
+ availableSignatureAlgorithms,
+ availableKeyAlgorithms
+ };
+};
+
+export const useCertificatePolicy = (
+ templateData: any,
+ selectedProfile: any,
+ isModalOpen: boolean,
+ setValue: UseFormSetValue<any>,
+ watch: UseFormWatch<any>
+) => {
+ const [constraints, setConstraints] = useState<TemplateConstraints>(DEFAULT_TEMPLATE_CONSTRAINTS);
+
+ const {
+ filteredKeyUsages,
+ filteredExtendedKeyUsages,
+ availableSignatureAlgorithms,
+ availableKeyAlgorithms
+ } = useCertificatePolicyOptions(constraints);
+
const resetConstraints = () => {
- setConstraints({
- allowedKeyUsages: [],
- allowedExtendedKeyUsages: [],
- requiredKeyUsages: [],
- requiredExtendedKeyUsages: [],
- restrictKeyUsages: false,
- restrictExtendedKeyUsages: false,
- allowedSignatureAlgorithms: [],
- allowedKeyAlgorithms: [],
- allowedSanTypes: [
- CertSubjectAlternativeNameType.DNS_NAME,
- CertSubjectAlternativeNameType.IP_ADDRESS,
- CertSubjectAlternativeNameType.EMAIL,
- CertSubjectAlternativeNameType.URI
- ],
- allowedSubjectAttributeTypes: [CertSubjectAttributeType.COMMON_NAME],
- shouldShowSanSection: true,
- shouldShowSubjectSection: true,
- templateAllowsCA: false,
- templateRequiresCA: false,
- maxPathLength: undefined
- });
+ setConstraints(DEFAULT_TEMPLATE_CONSTRAINTS);
};
const prevProfileIdRef = useRef<string | undefined>(undefined);
@@ -172,37 +229,8 @@ export const useCertificatePolicy = (
const profileChanged = prevProfileIdRef.current !== selectedProfile.id;
prevProfileIdRef.current = selectedProfile.id;
- // CA issuance is a privilege boundary: an undefined basicConstraints policy denies CA by default
- const isCaPolicy =
- (templateData.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED;
- const templateAllowsCA =
- isCaPolicy === CertPolicyState.ALLOWED || isCaPolicy === CertPolicyState.REQUIRED;
- const templateRequiresCA = isCaPolicy === CertPolicyState.REQUIRED;
- const maxPathLength = templateData.basicConstraints?.maxPathLength;
-
- const newConstraints: TemplateConstraints = {
- allowedSignatureAlgorithms: templateData.algorithms?.signature || [],
- allowedKeyAlgorithms: templateData.algorithms?.keyAlgorithm || [],
- allowedKeyUsages: [
- ...(templateData.keyUsages?.required || []),
- ...(templateData.keyUsages?.allowed || [])
- ],
- allowedExtendedKeyUsages: [
- ...(templateData.extendedKeyUsages?.required || []),
- ...(templateData.extendedKeyUsages?.allowed || [])
- ],
- requiredKeyUsages: templateData.keyUsages?.required || [],
- requiredExtendedKeyUsages: templateData.extendedKeyUsages?.required || [],
- restrictKeyUsages: Boolean(templateData.keyUsages),
- restrictExtendedKeyUsages: Boolean(templateData.extendedKeyUsages),
- allowedSanTypes: [],
- allowedSubjectAttributeTypes: [],
- shouldShowSanSection: true,
- shouldShowSubjectSection: true,
- templateAllowsCA,
- templateRequiresCA,
- maxPathLength
- };
+ const newConstraints = deriveTemplateConstraints(templateData);
+ const { templateRequiresCA } = newConstraints;
// Pre-populate from profile defaults
const defaults = selectedProfile?.defaults;
@@ -229,53 +257,6 @@ export const useCertificatePolicy = (
}
}
- // Handle SAN types. An undefined SAN policy allows every SAN type (allow all).
- // A defined SAN policy constrains to exactly its listed types — an empty
- // array means no SAN is allowed. Only an undefined policy allows all SAN types.
- if (templateData.sans) {
- const sanTypes: CertSubjectAlternativeNameType[] = [];
- templateData.sans.forEach((sanPolicy: any) => {
- if (!sanTypes.includes(sanPolicy.type)) {
- sanTypes.push(sanPolicy.type);
- }
- });
- newConstraints.allowedSanTypes = sanTypes;
- newConstraints.shouldShowSanSection = sanTypes.length > 0;
- } else {
- newConstraints.allowedSanTypes = [
- CertSubjectAlternativeNameType.DNS_NAME,
- CertSubjectAlternativeNameType.IP_ADDRESS,
- CertSubjectAlternativeNameType.EMAIL,
- CertSubjectAlternativeNameType.URI
- ];
- newConstraints.shouldShowSanSection = true;
- }
-
- // A defined subject policy constrains to exactly its listed types — an
- // empty array means no subject attribute is allowed. Only an undefined policy allows all.
- if (templateData.subject) {
- const subjectTypes: CertSubjectAttributeType[] = [];
- templateData.subject.forEach((subjectPolicy: any) => {
- if (!subjectTypes.includes(subjectPolicy.type)) {
- subjectTypes.push(subjectPolicy.type as CertSubjectAttributeType);
- }
- });
- newConstraints.allowedSubjectAttributeTypes = subjectTypes;
- newConstraints.shouldShowSubjectSection = subjectTypes.length > 0;
- } else {
- newConstraints.shouldShowSubjectSection = true;
- // No subject policy allows every subject attribute type (allow all)
- newConstraints.allowedSubjectAttributeTypes = [
- CertSubjectAttributeType.COMMON_NAME,
- CertSubjectAttributeType.ORGANIZATION,
- CertSubjectAttributeType.ORGANIZATIONAL_UNIT,
- CertSubjectAttributeType.COUNTRY,
- CertSubjectAttributeType.STATE,
- CertSubjectAttributeType.LOCALITY,
- CertSubjectAttributeType.DOMAIN_COMPONENT
- ];
- }
-
// Pre-populate subject attributes from profile defaults
const defaultSubjectAttrs: Array<{ type: CertSubjectAttributeType; value: string }> = [];
if (defaults?.commonName) {
diff --git a/frontend/src/pages/cert-manager/pki-docs-urls.ts b/frontend/src/pages/cert-manager/pki-docs-urls.ts
index 2080f96400..02ff293452 100644
--- a/frontend/src/pages/cert-manager/pki-docs-urls.ts
+++ b/frontend/src/pages/cert-manager/pki-docs-urls.ts
@@ -38,6 +38,7 @@ export const PkiDocsUrls = {
applications: {
overview: `${PKI_DOCS_BASE_URL}/applications/overview`,
certificates: `${PKI_DOCS_BASE_URL}/applications/certificates`,
+ certificateRenewal: `${PKI_DOCS_BASE_URL}/applications/certificate-renewal`,
approvals: `${PKI_DOCS_BASE_URL}/applications/approvals`,
enrollment: {
overview: `${PKI_DOCS_BASE_URL}/applications/enrollment-methods/overview`,