Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Address PR comments
Carlos Monastyrskia4e00dc303d0
diff --git a/.infisicalignore b/.infisicalignoreindex 63decac3da..f576422dea 100644--- a/.infisicalignore+++ b/.infisicalignore@@ -66,4 +66,4 @@ backend/src/ee/services/honey-token/honey-token-service.ts:generic-api-key:49docs/integrations/app-connections/ovh.mdx:private-key:84docs/integrations/app-connections/datadog.mdx:generic-api-key:161docs/integrations/app-connections/qovery.mdx:generic-api-key:96-backend/src/services/certificate-v3/certificate-renewal-fns.test.ts:private-key:163+backend/src/services/certificate-v3/certificate-renewal-fns.test.ts:private-key:164diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 8037cc47d8..29df81cef6 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -34,6 +34,7 @@ import { TCreateAppConnectionDTO, TUpdateAppConnectionDTO } from "@app/services/import { ActorType } from "@app/services/auth/auth-type";import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "@app/services/certificate/certificate-types";import { CaStatus } from "@app/services/certificate-authority/certificate-authority-enums";+import { CertificateRenewalKeySource, TRenewalAuditChange } from "@app/services/certificate-v3/certificate-v3-types";import { TIdentityTrustedIp } from "@app/services/identity/identity-types";import {TAWSAuthDetails,@@ -3976,6 +3977,8 @@ interface RenewCertificate {newCertificateId: string;profileName: string;commonName: string;+ renewalKeySource: CertificateRenewalKeySource;+ changedAttributes: TRenewalAuditChange[];};}diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.tsindex 00c445d975..d15aff98c9 100644--- a/backend/src/server/routes/v1/certificate-router.ts+++ b/backend/src/server/routes/v1/certificate-router.ts@@ -5,7 +5,6 @@ import { z } from "zod";import { CertificatesSchema } from "@app/db/schemas";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { ApiDocsTags, CERTIFICATES } from "@app/lib/api-docs";-import { NotFoundError } from "@app/lib/errors";import { ms } from "@app/lib/ms";import { isUuidV4 } from "@app/lib/validator";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";@@ -1170,17 +1169,6 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const originalCertificate = await server.services.certificate.getCert({- actor: req.permission.type,- actorId: req.permission.id,- actorAuthMethod: req.permission.authMethod,- actorOrgId: req.permission.orgId,- id: req.params.id- });- if (!originalCertificate) {- throw new NotFoundError({ message: "Original certificate not found" });- }-const data = await server.services.certificateV3.renewCertificate({actor: req.permission.type,actorId: req.permission.id,@@ -1202,7 +1190,9 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {originalCertificateId: req.params.id,newCertificateId: data.certificateId || "",profileName: data.profileName,- commonName: data.commonName || ""+ commonName: data.commonName || "",+ renewalKeySource: req.body?.renewalKeySource ?? CertificateRenewalKeySource.New,+ changedAttributes: data.changedAttributes ?? []}}});diff --git a/backend/src/server/routes/v3/deprecated-certificates-router.ts b/backend/src/server/routes/v3/deprecated-certificates-router.tsindex d10966f95a..d100a25611 100644--- a/backend/src/server/routes/v3/deprecated-certificates-router.ts+++ b/backend/src/server/routes/v3/deprecated-certificates-router.ts@@ -19,7 +19,10 @@ import { mapEnumsForValidation } from "@app/services/certificate-common/certificimport { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types";import { CertificateRequestStatus } from "@app/services/certificate-request/certificate-request-types";import { validateTemplateRegexField } from "@app/services/certificate-template/certificate-template-validators";-import { TCertificateIssuedResponse } from "@app/services/certificate-v3/certificate-v3-types";+import {+ CertificateRenewalKeySource,+ TCertificateIssuedResponse+} from "@app/services/certificate-v3/certificate-v3-types";import { booleanSchema } from "../sanitizedSchemas";@@ -501,6 +504,8 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) =>event: {type: EventType.RENEW_CERTIFICATE,metadata: {+ renewalKeySource: CertificateRenewalKeySource.New,+ changedAttributes: certificateData.changedAttributes ?? [],originalCertificateId: req.params.certificateId,newCertificateId: certificateData.certificateId,profileName: certificateData.profileName,diff --git a/backend/src/services/certificate-common/certificate-constants.ts b/backend/src/services/certificate-common/certificate-constants.tsindex f607e882aa..ec9a8e977f 100644--- a/backend/src/services/certificate-common/certificate-constants.ts+++ b/backend/src/services/certificate-common/certificate-constants.ts@@ -250,20 +250,6 @@ export const mapLegacyExtendedKeyUsageToStandard = (usage: string): CertExtendedreturn 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",diff --git a/backend/src/services/certificate-common/certificate-issuance-utils.ts b/backend/src/services/certificate-common/certificate-issuance-utils.tsindex beaf53ba55..667d33ef50 100644--- a/backend/src/services/certificate-common/certificate-issuance-utils.ts+++ b/backend/src/services/certificate-common/certificate-issuance-utils.ts@@ -35,7 +35,14 @@ import {convertKeyUsageArrayToLegacy} from "./certificate-utils";-export const parseTtlToDays = (ttl: string): number => Math.ceil(ms(ttl) / (24 * 60 * 60 * 1000));+export const parseTtlToDays = (ttl: string): number => {+ const durationMs = ms(ttl);+ if (!durationMs || durationMs <= 0) {+ throw new BadRequestError({ message: `Invalid TTL '${ttl}'. Use a duration such as '30d', '12h', or '1y'.` });+ }++ return Math.ceil(durationMs / (24 * 60 * 60 * 1000));+};/*** Calculates the renewal threshold in days, ensuring it doesn't exceed the certificate TTLdiff --git a/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts b/backend/src/services/certificate-v3/certificate-renewal-fns.test.tsindex 647c0841e7..a54f801386 100644--- a/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts+++ b/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts@@ -6,14 +6,18 @@ import {CertExtendedKeyUsageType,CertKeyAlgorithm,CertKeyUsageType,+ CertSignatureAlgorithm,CertSubjectAlternativeNameType} from "../certificate-common/certificate-constants";import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";import {assertCsrRenewalAttributes,+ buildCsrRenewalCertificateRequest,+ buildRenewalAuditChanges,buildRenewalCertificateRequest,certificateSpanToTtl,importKeyPairFromPem,+ isCertificateContentEdit,resolveRenewalKeySource} from "./certificate-renewal-fns";import { CertificateRenewalKeySource } from "./certificate-v3-types";@@ -200,3 +204,130 @@ describe("importKeyPairFromPem", () => {).rejects.toThrow("Renew with a new key pair");});});++const CSR_PEM = `-----BEGIN CERTIFICATE REQUEST-----+MIICyjCCAbICAQAwQzEdMBsGA1UEAwwUZnJvbS1jc3IuZXhhbXBsZS5jb20xFTAT+BgNVBAoMDEV4YW1wbGUgQ29ycDELMAkGA1UEBhMCVVMwggEiMA0GCSqGSIb3DQEB+AQUAA4IBDwAwggEKAoIBAQDK2rfCBjscc47ffKzImc4cs8ARSAoVdxxhUwRIPRKa+oWazByeQVSCDPj8L7C1WvGaNpre29G7nIe9+T1gvR2x00PJ62TE7fKNcLvEl4+zV+W2wZ4/P/SV5/t7yAlnd+oYvc8NQ7I5648/elzb9LXPzSY7MwHJjNKVZmqzUG/S6J+6bPa20i/WB4A5kLtiNWN5UZRZMG4tWknqpPoGflM5UC/vHdcIXwOEaB8BOEGqhKs+pfqclrq5eIXqN9fUmVTSLIDj5aIRS90fz9MLt9aIEZy+ixEC68KWkkmAtqoVqNZZ+CM17KYqHlbSdNh2sxNCxlqtCN4fQOsvKW4LpckaxjJIdAgMBAAGgQjBABgkqhkiG+9w0BCQ4xMzAxMC8GA1UdEQQoMCaCEWNzci1hLmV4YW1wbGUuY29tghFjc3ItYi5l+eGFtcGxlLmNvbTANBgkqhkiG9w0BAQsFAAOCAQEAYImLw0nLLorTvLwwmc5pTwq/+fLEbNmU/UGU5yirTE6ZvZ4m7Ux5yoLLlEGj8FkhSRbIa/yNlX8O/fE62Bv0spQ1j+MdNVsXe6Nk5bDh3IbxUrDFw7LzGMkkE3mbskHWoQDKHY7RLgGkrPxDZuEb6sUOv0+hIi0sn3rB6UncFoh09lzp2P7PMOuRT3WAZV2e3Sp0Iniiz8GUtGMdu98saC+or6Y+nK6dxfdkgRRPX+0Z/Su41uX6QBh1tbHdHY7mL0ZuqlD6cUQ8L/vHNzRJVY7hxhI2+r5EYNQvwLPvpPtwb6/5hKykcW6t2IDZNu8d5cg2hXI74eBjZCo8M+W+E/SDi8A==+-----END CERTIFICATE REQUEST-----`;++describe("buildRenewalAuditChanges", () => {+ const cert = {+ commonName: "web.example.com",+ altNames: "web.example.com",+ keyUsages: ["digitalSignature"],+ extendedKeyUsages: ["serverAuth"],+ signatureAlgorithm: "RSA-SHA256",+ keyAlgorithm: "RSA_2048",+ subjectOrganization: "Example Corp",+ subjectOrganizationalUnit: null,+ subjectCountry: "US",+ subjectState: null,+ subjectLocality: null,+ subjectDomainComponents: null,+ isCA: false,+ pathLength: null,+ notBefore: new Date("2026-01-01T00:00:00Z"),+ notAfter: new Date("2026-01-31T00:00:00Z")+ };++ const unchangedRequest: TCertificateRequest = {+ commonName: "web.example.com",+ organization: "Example Corp",+ country: "US",+ subjectAlternativeNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "web.example.com" }],+ keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE],+ extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH],+ signatureAlgorithm: CertSignatureAlgorithm.RSA_SHA256,+ keyAlgorithm: CertKeyAlgorithm.RSA_2048,+ validity: { ttl: "30d" }+ };++ it("records nothing when the renewal reproduces the certificate", () => {+ expect(buildRenewalAuditChanges(cert, unchangedRequest)).toEqual([]);+ });++ it("does not report a change when stored legacy usage names resolve to the same usages", () => {+ expect(+ buildRenewalAuditChanges(cert, { ...unchangedRequest, keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE] })+ ).toEqual([]);+ });++ it("records before and after for each changed attribute", () => {+ expect(+ buildRenewalAuditChanges(cert, {+ ...unchangedRequest,+ commonName: "api.example.com",+ subjectAlternativeNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "api.example.com" }],+ validity: { ttl: "90d" }+ })+ ).toEqual([+ { field: "commonName", from: "web.example.com", to: "api.example.com" },+ { field: "altNames", from: "web.example.com", to: "api.example.com" },+ { field: "ttl", from: "30d", to: "90d" }+ ]);+ });++ it("records a cleared field as an empty value", () => {+ expect(buildRenewalAuditChanges(cert, { ...unchangedRequest, organization: undefined })).toEqual([+ { field: "organization", from: "Example Corp", to: "" }+ ]);+ });++ it("renders basic constraints and lists readably", () => {+ expect(+ buildRenewalAuditChanges(cert, {+ ...unchangedRequest,+ basicConstraints: { isCA: true, pathLength: 2 },+ keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE, CertKeyUsageType.KEY_ENCIPHERMENT]+ })+ ).toEqual([+ { field: "keyUsages", from: "digital_signature", to: "digital_signature,key_encipherment" },+ { field: "basicConstraints", from: "isCA=false", to: "isCA=true pathLength=2" }+ ]);+ });++ it("records the subject a CSR renewal rewrites, which never appears in the request attributes", () => {+ const fromCsr = buildCsrRenewalCertificateRequest({ csr: CSR_PEM, attributes: { ttl: "30d" } });++ expect(buildRenewalAuditChanges(cert, fromCsr)).toEqual(+ expect.arrayContaining([+ { field: "commonName", from: "web.example.com", to: "from-csr.example.com" },+ { field: "altNames", from: "web.example.com", to: "csr-a.example.com,csr-b.example.com" }+ ])+ );+ });+});++describe("isCertificateContentEdit", () => {+ it("is false for a renewal that supplies nothing", () => {+ expect(isCertificateContentEdit({ keySource: CertificateRenewalKeySource.New })).toBe(false);+ expect(isCertificateContentEdit({ keySource: CertificateRenewalKeySource.New, attributes: {} })).toBe(false);+ expect(isCertificateContentEdit({ keySource: CertificateRenewalKeySource.Reuse, attributes: {} })).toBe(false);+ });++ it("is true when any attribute is supplied, including one that clears a field", () => {+ expect(isCertificateContentEdit({ keySource: CertificateRenewalKeySource.New, attributes: { ttl: "90d" } })).toBe(+ true+ );+ expect(+ isCertificateContentEdit({ keySource: CertificateRenewalKeySource.New, attributes: { organization: null } })+ ).toBe(true);+ });++ it("is true for a CSR renewal, which rewrites the subject from the CSR", () => {+ expect(isCertificateContentEdit({ keySource: CertificateRenewalKeySource.Csr })).toBe(true);+ });+});diff --git a/backend/src/services/certificate-v3/certificate-renewal-fns.ts b/backend/src/services/certificate-v3/certificate-renewal-fns.tsindex a2faac2a17..94bc614ff6 100644--- a/backend/src/services/certificate-v3/certificate-renewal-fns.ts+++ b/backend/src/services/certificate-v3/certificate-renewal-fns.ts@@ -1,6 +1,7 @@import * as x509 from "@peculiar/x509";import RE2 from "re2";+import { TCertificates } from "@app/db/schemas";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";@@ -23,7 +24,8 @@ import {} 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";+import { parseExtendedKeyUsages, parseKeyUsages } from "./certificate-v3-fns";+import { CertificateRenewalKeySource, TRenewalAttributes, TRenewalAuditChange } from "./certificate-v3-types";export enum CertificateRenewalMode {SelfSigned = "self-signed",@@ -32,25 +34,149 @@ export enum CertificateRenewalMode {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 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`;+};++type TRenewalAuditSubject = Pick<+ TCertificates,+ | "commonName"+ | "altNames"+ | "keyUsages"+ | "extendedKeyUsages"+ | "signatureAlgorithm"+ | "keyAlgorithm"+ | "subjectOrganization"+ | "subjectOrganizationalUnit"+ | "subjectCountry"+ | "subjectState"+ | "subjectLocality"+ | "subjectDomainComponents"+ | "isCA"+ | "pathLength"+ | "notBefore"+ | "notAfter"+>;++const formatBasicConstraints = (isCA: boolean | null | undefined, pathLength: number | null | undefined) =>+ `isCA=${Boolean(isCA)}${pathLength === null || pathLength === undefined ? "" : ` pathLength=${pathLength}`}`;++type TRenewalAttributeDescriptor<K extends keyof TRenewalAttributes> = {+ label: string;+ csrEditable?: true;+ apply: (value: TRenewalAttributes[K]) => Partial<TCertificateRequest>;+ current: (original: TRenewalAuditSubject) => string;+ issued: (request: TCertificateRequest) => string;};+const text = (value: string | null | undefined) => value ?? "";+const list = (values: readonly string[] | null | undefined) => (values ?? []).join(",");++const RENEWAL_ATTRIBUTES: { [K in keyof TRenewalAttributes]-?: TRenewalAttributeDescriptor<K> } = {+ commonName: {+ label: "common name",+ apply: (value) => ({ commonName: value ?? undefined }),+ current: (original) => text(original.commonName),+ issued: (request) => text(request.commonName)+ },+ organization: {+ label: "organization",+ apply: (value) => ({ organization: value ?? undefined }),+ current: (original) => text(original.subjectOrganization),+ issued: (request) => text(request.organization)+ },+ organizationalUnit: {+ label: "organizational unit",+ apply: (value) => ({ organizationalUnit: value ?? undefined }),+ current: (original) => text(original.subjectOrganizationalUnit),+ issued: (request) => text(request.organizationalUnit)+ },+ country: {+ label: "country",+ apply: (value) => ({ country: value ?? undefined }),+ current: (original) => text(original.subjectCountry),+ issued: (request) => text(request.country)+ },+ state: {+ label: "state",+ apply: (value) => ({ state: value ?? undefined }),+ current: (original) => text(original.subjectState),+ issued: (request) => text(request.state)+ },+ locality: {+ label: "locality",+ apply: (value) => ({ locality: value ?? undefined }),+ current: (original) => text(original.subjectLocality),+ issued: (request) => text(request.locality)+ },+ domainComponents: {+ label: "domain components",+ apply: (value) => ({ domainComponents: value ?? undefined }),+ current: (original) => text(original.subjectDomainComponents),+ issued: (request) => list(request.domainComponents)+ },+ altNames: {+ label: "subject alternative names",+ apply: (value) => ({ subjectAlternativeNames: value }),+ current: (original) => text(original.altNames),+ issued: (request) => (request.subjectAlternativeNames ?? []).map((san) => san.value).join(",")+ },+ keyUsages: {+ label: "key usages",+ apply: (value) => ({ keyUsages: value }),+ current: (original) => list(parseKeyUsages(original.keyUsages)),+ issued: (request) => list(request.keyUsages)+ },+ extendedKeyUsages: {+ label: "extended key usages",+ apply: (value) => ({ extendedKeyUsages: value }),+ current: (original) => list(parseExtendedKeyUsages(original.extendedKeyUsages)),+ issued: (request) => list(request.extendedKeyUsages)+ },+ signatureAlgorithm: {+ label: "signature algorithm",+ apply: (value) => ({ signatureAlgorithm: value }),+ current: (original) => text(original.signatureAlgorithm),+ issued: (request) => text(request.signatureAlgorithm)+ },+ keyAlgorithm: {+ label: "key algorithm",+ apply: (value) => ({ keyAlgorithm: value }),+ current: (original) => text(original.keyAlgorithm),+ issued: (request) => text(request.keyAlgorithm)+ },+ ttl: {+ label: "TTL",+ csrEditable: true,+ apply: (value) => ({ validity: { ttl: value as string } }),+ current: (original) => certificateSpanToTtl(original.notBefore, original.notAfter),+ issued: (request) => text(request.validity?.ttl)+ },+ basicConstraints: {+ label: "basic constraints",+ csrEditable: true,+ apply: (value) => ({ basicConstraints: value }),+ current: (original) => formatBasicConstraints(original.isCA, original.pathLength),+ issued: (request) => formatBasicConstraints(request.basicConstraints?.isCA, request.basicConstraints?.pathLength)+ }+};++const RENEWAL_ATTRIBUTE_KEYS = Object.keys(RENEWAL_ATTRIBUTES) as (keyof TRenewalAttributes)[];++const suppliedAttributeKeys = (attributes: TRenewalAttributes) =>+ RENEWAL_ATTRIBUTE_KEYS.filter((key) => attributes[key] !== undefined);+export const resolveRenewalKeySource = ({renewalKeySource,csr@@ -75,12 +201,25 @@ export const resolveRenewalKeySource = ({return keySource;};+export const isCertificateContentEdit = ({+ keySource,+ attributes+}: {+ keySource: CertificateRenewalKeySource;+ attributes?: TRenewalAttributes;+}): boolean => {+ if (keySource === CertificateRenewalKeySource.Csr) return true;+ if (!attributes) return false;++ return suppliedAttributeKeys(attributes).length > 0;+};+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);+ const rejected = suppliedAttributeKeys(attributes)+ .filter((key) => !RENEWAL_ATTRIBUTES[key].csrEditable)+ .map((key) => RENEWAL_ATTRIBUTES[key].label);if (rejected.length > 0) {throw new BadRequestError({@@ -105,27 +244,13 @@ export const buildRenewalCertificateRequest = ({}): 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+ return suppliedAttributeKeys(attributes).reduce<TCertificateRequest>(+ (request, key) => ({+ ...request,+ ...(RENEWAL_ATTRIBUTES[key] as TRenewalAttributeDescriptor<typeof key>).apply(attributes[key])}),- ...(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 })- };+ original+ );};export const buildCsrRenewalCertificateRequest = ({@@ -156,20 +281,15 @@ export const buildCsrRenewalCertificateRequest = ({};};-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 buildRenewalAuditChanges = (+ original: TRenewalAuditSubject,+ issuedRequest: TCertificateRequest+): TRenewalAuditChange[] =>+ RENEWAL_ATTRIBUTE_KEYS.map((field) => ({+ field,+ from: RENEWAL_ATTRIBUTES[field].current(original),+ to: RENEWAL_ATTRIBUTES[field].issued(issuedRequest)+ })).filter(({ from, to }) => from !== to);export const buildRenewalDistinguishedName = (certificateRequest: TCertificateRequest): string =>createDistinguishedName({diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.tsindex 1fe285c6d5..978e0ac9c2 100644--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts@@ -3,11 +3,13 @@ import { randomUUID } from "crypto";import { Knex } from "knex";import { ActionProjectType, TCertificates } from "@app/db/schemas";+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ProjectPermissionCertificateProfileActions,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";+import { isPqcAlgorithm } from "@app/lib/crypto/pqc/pqc-utils";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { ms } from "@app/lib/ms";@@ -63,7 +65,8 @@ import {convertExtendedKeyUsageArrayToLegacy,convertKeyUsageArrayToLegacy,normalizeDateForApi,- removeRootCaFromChain+ removeRootCaFromChain,+ validatePqcLicense} from "../certificate-common/certificate-utils";import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";import { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";@@ -84,11 +87,13 @@ import {assertCsrRenewalAttributes,buildCsrFromExistingKey,buildCsrRenewalCertificateRequest,+ buildRenewalAuditChanges,buildRenewalCertificateRequest,buildRenewalDistinguishedName,CertificateRenewalMode,certificateSpanToTtl,importKeyPairFromPem,+ isCertificateContentEdit,resolveRenewalKeySource,validateRenewalEligibility} from "./certificate-renewal-fns";@@ -99,6 +104,8 @@ import {TCertificateIssuanceResponse,TDisableRenewalConfigDTO,TDisableRenewalResponse,+ TRenewalAttributes,+ TRenewalAuditChange,TRenewalConfigResponse,TRenewCertificateDTO,TUpdateRenewalConfigDTO@@ -139,10 +146,20 @@ type TCertificateRenewalServiceFactoryDep = {"findAllByProfileId" | "findOneByApplicationAndProfile">;apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;resolveApplicationIdForProfile: TResolveApplicationIdForProfile;reportCertificateIssued: TReportCertificateIssued;};+class RenewalBlockedError extends BadRequestError {+ readonly renewalError: string;++ constructor(renewalError: string) {+ super({ message: renewalError });+ this.renewalError = renewalError;+ }+}+type TRenewalActor = {actor: ActorType;actorId: string;@@ -191,6 +208,7 @@ export const certificateRenewalServiceFactory = ({pkiAlertV2Queue,pkiApplicationProfileDAL,apiEnrollmentConfigDAL,+ licenseService,resolveApplicationIdForProfile: $resolveApplicationIdForProfile,reportCertificateIssued: $reportCertificateIssued}: TCertificateRenewalServiceFactoryDep) => {@@ -567,21 +585,29 @@ export const certificateRenewalServiceFactory = ({};};- const $authorizeRenewal = async ({- originalCert,- profile,- actorCtx- }: {- originalCert: TCertificates;- profile: { id: string; projectId: string; slug: string };- actorCtx: TRenewalActor;- }) => {- const { certMetadata, projectPermission } = await assertCanEditCertificate({- certificate: originalCert,- ...actorCtx,- permissionService,- resourceMetadataDAL- });+ const $authorizeRenewal = async (+ {+ originalCert,+ profile,+ actorCtx,+ isEditingCertificate+ }: {+ originalCert: TCertificates;+ profile: { id: string; projectId: string; slug: string };+ actorCtx: TRenewalActor;+ isEditingCertificate: boolean;+ },+ tx: Knex+ ) => {+ const { certMetadata, projectPermission } = isEditingCertificate+ ? await assertCanEditCertificate({+ certificate: originalCert,+ ...actorCtx,+ permissionService,+ resourceMetadataDAL,+ tx+ })+ : { certMetadata: [] as { key: string; value: string }[], projectPermission: undefined };if (originalCert.applicationId) {await $resolveApplicationIdForProfile(profile, originalCert.applicationId, actorCtx, EnrollmentType.API);@@ -636,9 +662,7 @@ export const certificateRenewalServiceFactory = ({const eligibilityCheck = validateRenewalEligibility(originalCert, ca, requestedTtl);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 });+ throw new RenewalBlockedError(`Certificate is not eligible for renewal: ${eligibilityCheck.errors.join(", ")}`);}caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;@@ -657,22 +681,23 @@ export const certificateRenewalServiceFactory = ({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 $buildValidatedRenewalRequest = ({+ originalCert,+ policy,+ csrRenewalRequest,+ attributes,+ keySource,+ originalSignatureAlgorithm,+ originalKeyAlgorithm+ }: {+ originalCert: TCertificates;+ policy: Parameters<TCertificatePolicyServiceFactory["validateRequestAgainstPolicy"]>[0];+ csrRenewalRequest: TCertificateRequest | null;+ attributes?: TRenewCertificateDTO["attributes"];+ keySource: CertificateRenewalKeySource;+ originalSignatureAlgorithm?: CertSignatureAlgorithm;+ originalKeyAlgorithm?: CertKeyAlgorithm;+ }) => {const originalTtl = certificateSpanToTtl(originalCert.notBefore, originalCert.notAfter);const originalRequest: TCertificateRequest = {@@ -691,8 +716,8 @@ export const certificateRenewalServiceFactory = ({? originalCert.altNames.split(",").map((san) => detectSanType(san.trim())): [],validity: { ttl: originalTtl },- signatureAlgorithm: originalCert.signatureAlgorithm || undefined,- keyAlgorithm: originalCert.keyAlgorithm || undefined,+ signatureAlgorithm: originalSignatureAlgorithm,+ keyAlgorithm: originalKeyAlgorithm,...(originalCert.isCA && {basicConstraints: { isCA: true, pathLength: originalCert.pathLength ?? undefined }})@@ -716,14 +741,7 @@ export const certificateRenewalServiceFactory = ({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(", ")}`- });+ throw new RenewalBlockedError(`Certificate renewal failed. Errors: ${validationResult.errors.join(", ")}`);}return { certificateRequest, ttl };@@ -905,6 +923,34 @@ export const certificateRenewalServiceFactory = ({});};+ const $assertRequestedAlgorithmsLicensed = async ({+ certificateId,+ csrRenewalRequest,+ attributes+ }: {+ certificateId: string;+ csrRenewalRequest: TCertificateRequest | null;+ attributes?: TRenewalAttributes;+ }) => {+ const requested = [+ attributes?.keyAlgorithm,+ attributes?.signatureAlgorithm,+ csrRenewalRequest?.keyAlgorithm,+ csrRenewalRequest?.signatureAlgorithm+ ].filter((algorithm): algorithm is string => typeof algorithm === "string" && isPqcAlgorithm(algorithm));++ if (!requested.length) return;++ const originalCert = await certificateDAL.findById(certificateId);+ if (!originalCert) {+ throw new NotFoundError({ message: "Certificate not found" });+ }++ for await (const keyAlgorithm of requested) {+ await validatePqcLicense({ keyAlgorithm, projectId: originalCert.projectId, projectDAL, licenseService });+ }+ };+const renewCertificate = async ({certificateId,actor,@@ -927,240 +973,265 @@ export const certificateRenewalServiceFactory = ({csrRenewalRequest = buildCsrRenewalCertificateRequest({ csr, attributes });}- const renewalResult = await certificateDAL.transaction(async (tx) => {- const {- originalCert,- profile,- certificateSecret,- originalCsr,- originalSignatureAlgorithm,- originalKeyAlgorithm- } = await $loadRenewalSubject({ certificateId, keySource }, tx);+ const isEditingCertificate = isCertificateContentEdit({ keySource, attributes });+ let changedAttributes: TRenewalAuditChange[] = [];- const renewalAuth = internal ? undefined : await $authorizeRenewal({ originalCert, profile, actorCtx });+ await $assertRequestedAlgorithmsLicensed({ certificateId, csrRenewalRequest, attributes });- const { issuerType, ca, caType, policy } = await $resolveRenewalIssuer(- {+ const runRenewal = () =>+ certificateDAL.transaction(async (tx) => {+ const {originalCert,profile,- actorCtx,- internal,- requestedTtl: csrRenewalRequest?.validity?.ttl ?? attributes?.ttl- },- tx- );-- const { certificateRequest, ttl } = await $buildValidatedRenewalRequest(- { originalCert, policy, csrRenewalRequest, attributes, keySource },- tx- );-- if (renewalAuth?.projectPermission) {- assertCanEditCertificateResult({- projectPermission: renewalAuth.projectPermission,- commonName: certificateRequest.commonName,- altNames: (certificateRequest.subjectAlternativeNames ?? []).map((san) => san.value),- serialNumber: originalCert.serialNumber,- metadata: renewalAuth.certMetadata- });- }+ certificateSecret,+ originalCsr,+ originalSignatureAlgorithm,+ originalKeyAlgorithm+ } = await $loadRenewalSubject({ certificateId, keySource }, tx);- const notBefore = new Date();- const notAfter = new Date(Date.now() + ms(ttl));+ const renewalAuth = internal+ ? undefined+ : await $authorizeRenewal({ originalCert, profile, actorCtx, isEditingCertificate }, tx);- 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 { issuerType, ca, caType, policy } = await $resolveRenewalIssuer(+ {+ originalCert,+ profile,+ actorCtx,+ internal,+ requestedTtl: csrRenewalRequest?.validity?.ttl ?? attributes?.ttl+ },+ tx+ );- const { signatureAlgorithm: effectiveSignatureAlgorithm, keyAlgorithm: effectiveKeyAlgorithm } =- getEffectiveAlgorithms(- certificateRequest.signatureAlgorithm as CertSignatureAlgorithm,- certificateRequest.keyAlgorithm as CertKeyAlgorithm,+ const { certificateRequest, ttl } = $buildValidatedRenewalRequest({+ originalCert,+ policy,+ csrRenewalRequest,+ attributes,+ keySource,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) });+ changedAttributes = buildRenewalAuditChanges(originalCert, { ...certificateRequest, validity: { ttl } });- if (keySource !== CertificateRenewalKeySource.New && caType === CaType.INTERNAL && ca) {- validateCaSupport(ca, "CSR signing");- validateAlgorithmCompatibility(ca, { algorithms: policy?.algorithms } as {- algorithms?: { signature?: string[] };- });+ if (renewalAuth?.projectPermission) {+ assertCanEditCertificateResult({+ projectPermission: renewalAuth.projectPermission,+ commonName: certificateRequest.commonName,+ altNames: (certificateRequest.subjectAlternativeNames ?? []).map((san) => san.value),+ serialNumber: originalCert.serialNumber,+ metadata: renewalAuth.certMetadata+ });+ }- return {- renewalMode: CertificateRenewalMode.KeyPreserving as const,- keySource,- csr,- ca,- profile,- policy,- originalCert,- certificateRequest,- certificateSecret,- originalCsr,+ 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,- notBefore,- notAfter,- finalRenewBeforeDays,- effectiveKeyAlgorithm,- effectiveSignatureAlgorithm- };- }+ notAfter+ });- if (issuerType === IssuerType.CA) {- if (!ca) {- throw new NotFoundError({ message: "Certificate Authority not found for CA-signed certificate renewal" });- }+ 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;- if (caType === CaType.INTERNAL) {- validateAlgorithmCompatibility(ca, {- algorithms: policy.algorithms- } as { algorithms?: { signature?: string[] } });+ $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.InternalCa as const,+ renewalMode: CertificateRenewalMode.KeyPreserving as const,+ keySource,+ csr,ca,profile,policy,originalCert,certificateRequest,- renewalAltNames,- renewalBasicConstraints,+ certificateSecret,+ originalCsr,ttl,notBefore,notAfter,finalRenewBeforeDays,- effectiveSignatureAlgorithm,- effectiveKeyAlgorithm- };- }- if (caType && caSupportsCapability(caType, CaCapability.RENEW_CERTIFICATES)) {- return {- renewalMode: CertificateRenewalMode.ExternalCa as const,- ca,- profile,- originalCert,- certificateRequest,- renewalAltNames,- renewalBasicConstraints,- effectiveSignatureAlgorithm,effectiveKeyAlgorithm,- ttl+ effectiveSignatureAlgorithm};}- throw new BadRequestError({- message: `CA type ${String(caType)} does not support certificate renewal`++ 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[] } });++ return {+ renewalMode: CertificateRenewalMode.InternalCa as const,+ ca,+ profile,+ policy,+ originalCert,+ certificateRequest,+ renewalAltNames,+ renewalBasicConstraints,+ ttl,+ notBefore,+ notAfter,+ finalRenewBeforeDays,+ effectiveSignatureAlgorithm,+ effectiveKeyAlgorithm+ };+ }+ if (caType && caSupportsCapability(caType, CaCapability.RENEW_CERTIFICATES)) {+ return {+ renewalMode: CertificateRenewalMode.ExternalCa as const,+ ca,+ profile,+ originalCert,+ certificateRequest,+ renewalAltNames,+ renewalBasicConstraints,+ effectiveSignatureAlgorithm,+ effectiveKeyAlgorithm,+ ttl+ };+ }+ throw new BadRequestError({+ message: `CA type ${String(caType)} does not support certificate renewal`+ });+ }++ 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});- }- const existingKeyPair =- keySource === CertificateRenewalKeySource.Reuse && certificateSecret- ? await importKeyPairFromPem({- privateKeyPem: await $decryptCertificatePrivateKey({- projectId: originalCert.projectId,- encryptedPrivateKey: certificateSecret.encryptedPrivateKey- }),- keyAlgorithm: effectiveKeyAlgorithm- })- : undefined;+ const certificate = selfSignedRenewalResult.selfSignedResult.certificate.toString("utf8");+ const { serialNumber } = selfSignedRenewalResult.selfSignedResult;+ const newCert = selfSignedRenewalResult.certificateData;- const selfSignedRenewalResult = await processSelfSignedCertificate({- certificateRequest: { ...certificateRequest, altNames: renewalAltNames },- policy,- profile,- originalCert,- effectiveAlgorithms: {+ 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,- keyAlgorithm: effectiveKeyAlgorithm- },- certificateDAL,- certificateBodyDAL,- certificateSecretDAL,- kmsService,- projectDAL,- tx,- isRenewal: true,- existingKeyPair- });-- const certificate = selfSignedRenewalResult.selfSignedResult.certificate.toString("utf8");- const { serialNumber } = selfSignedRenewalResult.selfSignedResult;- const newCert = selfSignedRenewalResult.certificateData;+ 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 })+ });- 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: true,+ certificateRequestId: certRequestResult.id,+ certificateRequestCreatedAt: certRequestResult.createdAt,+ orgId: actorOrgId+ },+ tx+ );- await $linkRenewedCertificate(- {+ return {+ renewalMode: CertificateRenewalMode.SelfSigned as const,+ certificate,+ serialNumber,newCert,originalCert,- finalRenewBeforeDays,- isRenewalLinkPreset: true,- certificateRequestId: certRequestResult.id,- certificateRequestCreatedAt: certRequestResult.createdAt,- orgId: actorOrgId- },- tx- );+ profile,+ certRequestResult+ };+ });- return {- renewalMode: CertificateRenewalMode.SelfSigned as const,- certificate,- serialNumber,- newCert,- originalCert,- profile,- certRequestResult- };- });+ let renewalResult: Awaited<ReturnType<typeof runRenewal>>;+ try {+ renewalResult = await runRenewal();+ } catch (err) {+ if (err instanceof RenewalBlockedError) {+ await certificateDAL.updateById(certificateId, { renewalError: err.renewalError });+ }+ throw err;+ }if (renewalResult.renewalMode === CertificateRenewalMode.KeyPreserving) {- return $completeKeyPreservingRenewal({+ const response = await $completeKeyPreservingRenewal({...renewalResult,actor,actorId,@@ -1168,10 +1239,12 @@ export const certificateRenewalServiceFactory = ({actorOrgId,removeRootsFromChain});+ return { ...response, changedAttributes };}if (renewalResult.renewalMode === CertificateRenewalMode.InternalCa) {- return $completeInternalCaRenewal({ ...renewalResult, actorCtx, removeRootsFromChain });+ const response = await $completeInternalCaRenewal({ ...renewalResult, actorCtx, removeRootsFromChain });+ return { ...response, changedAttributes };}if (renewalResult.renewalMode === CertificateRenewalMode.ExternalCa) {@@ -1261,11 +1334,12 @@ export const certificateRenewalServiceFactory = ({certificateRequestId: certificateRequest.id,projectId: originalCert.projectId,profileName: profile?.slug || "External CA Profile",- commonName: renewalRequest.commonName || ""+ commonName: renewalRequest.commonName || "",+ changedAttributes};}- return $finalizeRenewal({+ const response = await $finalizeRenewal({newCertificateId: renewalResult.newCert.id,originalCert: renewalResult.originalCert,profile: renewalResult.profile ?? null,@@ -1281,6 +1355,7 @@ export const certificateRenewalServiceFactory = ({actorId,actorOrgId});+ return { ...response, changedAttributes };};const $loadCertificateForRenewalConfig = async ({diff --git a/backend/src/services/certificate-v3/certificate-v3-fns.ts b/backend/src/services/certificate-v3/certificate-v3-fns.tsindex f605187a58..264cc295f3 100644--- a/backend/src/services/certificate-v3/certificate-v3-fns.ts+++ b/backend/src/services/certificate-v3/certificate-v3-fns.ts@@ -1,5 +1,3 @@-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";@@ -12,27 +10,6 @@ import {} from "../certificate-common/certificate-constants";import { TCertificateProfileDefaults } from "../certificate-profile/certificate-profile-types";-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 num = parseInt(value, 10);-- switch (unit) {- case "d":- return num;- case "h":- return Math.ceil(num / 24);- case "m":- return Math.ceil(num / (24 * 60));- default:- throw new BadRequestError({ message: `Invalid TTL unit: ${unit}` });- }-};-export const calculateRenewalThreshold = (profileRenewBeforeDays: number | undefined,certificateTtlInDays: numberdiff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.tsindex ed855753f4..69360fcc26 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts@@ -2171,14 +2171,9 @@ describe("CertificateV3Service", () => {})).rejects.toThrow("Certificate renewal failed. Errors: Subject alternative name not allowed");- // Should store policy validation error- expect(mockCertificateDAL.updateById).toHaveBeenCalledWith(- "cert-123",- {- renewalError: "Policy validation failed: Subject alternative name not allowed"- },- expect.anything()- );+ expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", {+ renewalError: "Certificate renewal failed. Errors: Subject alternative name not allowed"+ });});it("should reject renewal if certificate has no profile and no CA", async () => {diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.tsindex 0986e4c149..3851d3617a 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts@@ -2107,6 +2107,7 @@ export const certificateV3ServiceFactory = ({pkiAlertV2Queue,pkiApplicationProfileDAL,apiEnrollmentConfigDAL,+ licenseService,resolveApplicationIdForProfile: $resolveApplicationIdForProfile,reportCertificateIssued: $reportCertificateIssued});diff --git a/backend/src/services/certificate-v3/certificate-v3-types.ts b/backend/src/services/certificate-v3/certificate-v3-types.tsindex e2c06a3dd4..72a79bb3fc 100644--- a/backend/src/services/certificate-v3/certificate-v3-types.ts+++ b/backend/src/services/certificate-v3/certificate-v3-types.ts@@ -109,6 +109,7 @@ export type TCertificateIssuanceResponse = {serialNumber?: string;certificateId?: string;message?: string;+ changedAttributes?: TRenewalAuditChange[];};export type TCertificateIssuedResponse = TCertificateIssuanceResponse & {@@ -130,6 +131,12 @@ export enum CertificateRenewalKeySource {Csr = "csr"}+export type TRenewalAuditChange = {+ field: keyof TRenewalAttributes;+ from: string;+ to: string;+};+export type TRenewalAttributes = {commonName?: string | null;organization?: string | null;diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.tsindex 29457151b6..6f24bcdba9 100644--- a/backend/src/services/certificate/certificate-dal.ts+++ b/backend/src/services/certificate/certificate-dal.ts@@ -12,9 +12,7 @@ import {import { isUuidV4 } from "@app/lib/validator";import {mapExtendedKeyUsageToLegacy,- mapLegacyExtendedKeyUsageToStandard,- normalizeExtendedKeyUsagesForResponse,- normalizeKeyUsagesForResponse+ mapLegacyExtendedKeyUsageToStandard} from "@app/services/certificate-common/certificate-constants";import { applyMetadataFilter } from "@app/services/resource-metadata/resource-metadata-fns";@@ -471,9 +469,7 @@ export const certificateDALFactory = (db: TDbClient) => {const certs = await query;return certs.map((cert) => ({...cert,- hasPrivateKey: Boolean(cert.privateKeyRef),- keyUsages: normalizeKeyUsagesForResponse(cert.keyUsages),- extendedKeyUsages: normalizeExtendedKeyUsagesForResponse(cert.extendedKeyUsages)+ hasPrivateKey: Boolean(cert.privateKeyRef)}));} catch (error) {throw new DatabaseError({ error, name: "Find active certificates for sync" });@@ -729,9 +725,7 @@ export const certificateDALFactory = (db: TDbClient) => {const results = await query;return results.map((row) => ({...row,- hasPrivateKey: row.privateKeyRef !== null,- keyUsages: normalizeKeyUsagesForResponse(row.keyUsages),- extendedKeyUsages: normalizeExtendedKeyUsagesForResponse(row.extendedKeyUsages)+ hasPrivateKey: row.privateKeyRef !== null}));} catch (error) {throw new DatabaseError({ error, name: "Find certificates with private key info" });@@ -802,9 +796,7 @@ export const certificateDALFactory = (db: TDbClient) => {return {...rest,caType,- hasPrivateKey: Boolean(privateKeyRef),- keyUsages: normalizeKeyUsagesForResponse(rest.keyUsages),- extendedKeyUsages: normalizeExtendedKeyUsagesForResponse(rest.extendedKeyUsages)+ hasPrivateKey: Boolean(privateKeyRef)} as TCertificateWithRequestDetails;} catch (error) {throw new DatabaseError({ error, name: "Find certificate with full details" });diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex 7630257bd4..7eeef1c60b 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -25,7 +25,6 @@ import { CaCapability, CaType } from "@app/services/certificate-authority/certifimport { 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";@@ -417,7 +416,7 @@ export const certificateServiceFactory = ({usageMeteringService.emitForProject(cert.projectId, ActiveCerts.key);return {- deletedCert: withNormalizedUsagesForResponse(deletedCert)+ deletedCert};};@@ -1233,7 +1232,7 @@ export const certificateServiceFactory = ({}const [updatedCert] = await certificateDAL.update({ id: cert.id }, { applicationId });- return { certificate: withNormalizedUsagesForResponse(updatedCert), application };+ return { certificate: updatedCert, application };};return {diff --git a/docs/documentation/platform/pki/applications/certificate-renewal.mdx b/docs/documentation/platform/pki/applications/certificate-renewal.mdxindex 01b7b9c052..940e779ecb 100644--- a/docs/documentation/platform/pki/applications/certificate-renewal.mdx+++ b/docs/documentation/platform/pki/applications/certificate-renewal.mdx@@ -51,6 +51,10 @@ Not every option applies to every certificate. The renewal wizard greys out theA 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.+<Note>+ Certificates issued through Active Directory Certificate Services or Azure AD Certificate Services take their validity, key usages, extended key usages and basic constraints from the CA's own certificate template. The renewal wizard hides those fields for such certificates, because anything set here would be discarded by the CA. You can still change the subject and the alternative names.+</Note>+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@@ -68,6 +72,10 @@ Reuse is available for certificates issued with an Infisical-managed key pair. AChanging 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>+### Permissions++Renewing a certificate as it stands needs only permission to issue from its certificate profile. Changing any of the properties above additionally needs **Edit** on certificates, so a role scoped to issuance alone can keep certificates current without being able to alter what they contain.+### Renewing from a signing requestWhen 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.diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsxindex c3dd2bff2f..ae96dfefe4 100644--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx@@ -72,7 +72,8 @@ const Page = () => {};const { data: certificateData, isLoading } = useGetCertificateById(certificateId);const certificate = certificateData?.certificate;- const isInventoryView = !fromApplication;+ const parentApplication = certificate?.applicationName ?? fromApplication;+ const isInventoryView = !parentApplication;const projectId = currentProject?.id || "";@@ -267,13 +268,13 @@ const Page = () => {} else {pageBody = (<div className="mx-auto mb-6 w-full max-w-8xl">- {fromApplication && (+ {parentApplication && (<Linkto="/organizations/$orgId/projects/cert-manager/$projectId/applications/$applicationName"params={{orgId: currentOrg.id,projectId,- applicationName: fromApplication+ applicationName: parentApplication}}search={{ selectedTab: "certificates" }}className="mb-4 flex w-fit items-center gap-x-1 text-sm text-mineshaft-400 transition duration-100 hover:text-mineshaft-400/80"@@ -282,7 +283,7 @@ const Page = () => {Go back to Application</Link>)}- {!fromApplication && fromHsmConnector && (+ {!parentApplication && fromHsmConnector && (<Linkto="/organizations/$orgId/projects/cert-manager/$projectId/hsm-connectors/$connectorId"params={{@@ -296,7 +297,7 @@ const Page = () => {HSM Connector</Link>)}- {!fromApplication && !fromHsmConnector && (+ {!parentApplication && !fromHsmConnector && (<Linkto="/organizations/$orgId/projects/cert-manager/$projectId/inventory"params={{@@ -471,7 +472,11 @@ const Page = () => {/><CertificateRevocationModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} /><CertificateManageRenewalModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />- <CertificateRenewalModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />+ <CertificateRenewalModal+ popUp={popUp}+ applicationName={parentApplication}+ handlePopUpToggle={handlePopUpToggle}+ /><CertificateManagePkiSyncsModalpopUp={popUp.managePkiSyncs}handlePopUpToggle={handlePopUpToggle}diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateDetailsSection.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateDetailsSection.tsxindex e7121a428b..eeb3229fda 100644--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateDetailsSection.tsx+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateDetailsSection.tsx@@ -26,18 +26,18 @@ type Props = {// Preserve list for key usage terms that need special formatting// These terms have acronyms or specific capitalization that shouldn't be converted from camelCaseconst KEY_USAGE_DISPLAY_MAP: Record<string, string> = {- cRLSign: "CRL Sign"+ cRLSign: "CRL Sign",+ crl_sign: "CRL Sign"};export const CertificateDetailsSection = ({ certificateId }: Props) => {const { data, isLoading } = useGetCertificateById(certificateId);- // Format key usage names, checking preserve list firstconst formatKeyUsage = (usage: string): string => {if (KEY_USAGE_DISPLAY_MAP[usage]) {return KEY_USAGE_DISPLAY_MAP[usage];}- return toTitleCase(camelCaseToSpaces(usage));+ return toTitleCase(camelCaseToSpaces(usage).replace(/_/g, " "));};if (isLoading) {diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsxindex 72cfef3251..aa48f774e9 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/AlgorithmSelectors.tsx@@ -65,9 +65,13 @@ const AlgorithmSelect = ({disabled={Boolean(disabledReason)}><SelectTrigger className="w-full" isError={Boolean(error)}>- <SelectValue- placeholder={options.length > 0 ? selectPlaceholder : "No algorithms available"}- />+ {value ? (+ <SelectValue />+ ) : (+ <span className="text-muted">+ {options.length > 0 ? selectPlaceholder : "No algorithms available"}+ </span>+ )}</SelectTrigger><SelectContent position="popper">{renderOptions(options)}</SelectContent></Select>@@ -91,6 +95,8 @@ type AlgorithmSelectorsProps = {nonePlaceholder?: string;hideSignatureAlgorithm?: boolean;keyAlgorithmDisabledReason?: string;+ keyAlgorithmRequired?: boolean;+ keyAlgorithmPlaceholder?: string;};export const AlgorithmSelectors = ({@@ -105,7 +111,9 @@ export const AlgorithmSelectors = ({isRequired = true,nonePlaceholder,hideSignatureAlgorithm = false,- keyAlgorithmDisabledReason+ keyAlgorithmDisabledReason,+ keyAlgorithmRequired = isRequired,+ keyAlgorithmPlaceholder = "Select key algorithm"}: AlgorithmSelectorsProps) => {const { subscription } = useSubscription();@@ -150,9 +158,9 @@ export const AlgorithmSelectors = ({options={availableKeyAlgorithms}error={keyError}shouldUnregister={shouldUnregister}- isRequired={isRequired}+ isRequired={keyAlgorithmRequired}nonePlaceholder={nonePlaceholder}- selectPlaceholder="Select key algorithm"+ selectPlaceholder={keyAlgorithmPlaceholder}renderOptions={renderOptions}disabledReason={keyAlgorithmDisabledReason}/>diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsxindex 80b6cb5135..1b3a79af5e 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx@@ -45,7 +45,12 @@ import {import { AlgorithmSelectors } from "./AlgorithmSelectors";import { BasicConstraintsField } from "./BasicConstraintsField";import { buildManagedRequest } from "./buildManagedRequest";-import { detectSanTypeFromValue } from "./certificateUtils";+import {+ detectSanTypeFromValue,+ EXTERNAL_CA_TEMPLATE_HINT,+ isExternalTemplateCa,+ rowErrorsOf+} from "./certificateUtils";import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";import { KeyUsageSection } from "./KeyUsageSection";import { SubjectAltNamesField } from "./SubjectAltNamesField";@@ -351,15 +356,12 @@ export const CertificateIssuanceModal = ({);const externalCaType = actualSelectedProfile?.certificateAuthority?.externalType;- const isAdcsProfile = externalCaType === CaType.ADCS || externalCaType === CaType.AZURE_AD_CS;+ const isAdcsProfile = isExternalTemplateCa(externalCaType);isAdcsProfileRef.current = isAdcsProfile;const isAwsPcaProfile = externalCaType === CaType.AWS_PCA;isAwsPcaProfileRef.current = isAwsPcaProfile;- const externalCaHint =- "Validity, key usages, extended key usages and basic constraints are controlled by the external CA's certificate template.";-const { data: policyData } = useGetCertificatePolicyById({policyId: actualSelectedProfile?.certificatePolicyId || "",applicationId@@ -552,13 +554,6 @@ export const CertificateIssuanceModal = ({]);- const rowErrorsOf = (fieldErrors: unknown): (string | undefined)[] | undefined =>- Array.isArray(fieldErrors)- ? (fieldErrors as ({ value?: { message?: string } } | undefined)[]).map(- (rowError) => rowError?.value?.message- )- : undefined;-const selectedProfileReady = Boolean(profileId || actualSelectedProfileId);return (@@ -671,7 +666,9 @@ export const CertificateIssuanceModal = ({Configure API enrollment under this Application's Settings tab.</FieldDescription>)}- {isAdcsProfile && <FieldDescription>{externalCaHint}</FieldDescription>}+ {isAdcsProfile && (+ <FieldDescription>{EXTERNAL_CA_TEMPLATE_HINT}</FieldDescription>+ )}<FieldError errors={[error]} /></FieldContent></Field>@@ -684,7 +681,7 @@ export const CertificateIssuanceModal = ({{currentStepKey !== "profile" && (actualSelectedProfile || profileId) && (<div className="space-y-4">{currentStepKey === "options" && profileId && isAdcsProfile && (- <p className="mb-4 text-xs text-mineshaft-400">{externalCaHint}</p>+ <p className="mb-4 text-xs text-mineshaft-400">{EXTERNAL_CA_TEMPLATE_HINT}</p>)}{currentStepKey === "csr" && (@@ -746,6 +743,9 @@ export const CertificateIssuanceModal = ({(formState.errors as { subjectAltNames?: { message?: string } }).subjectAltNames?.message}+ rowErrors={rowErrorsOf(+ (formState.errors as { subjectAltNames?: unknown }).subjectAltNames+ )}/>)}diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsxindex 37bbd3cb6a..bff33a15d7 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx@@ -22,8 +22,10 @@ import { useRenewCertificate } from "@app/hooks/api";import { useGetCertificatePolicyById } from "@app/hooks/api/certificatePolicies";import { IssuerType, useGetCertificateProfileById } from "@app/hooks/api/certificateProfiles";import {+ certKeyAlgorithms,EXTENDED_KEY_USAGES_OPTIONS,- KEY_USAGES_OPTIONS+ KEY_USAGES_OPTIONS,+ SIGNATURE_ALGORITHMS_OPTIONS} from "@app/hooks/api/certificates/constants";import {CertificateIssuerKind,@@ -44,6 +46,7 @@ import {buildRenewalRequestAttributes,unionUsageOptions} from "./certificateRenewalUtils";+import { isExternalTemplateCa, rowErrorsOf } from "./certificateUtils";import { CertificateWizardSheet, useWizardSteps, WizardStep } from "./CertificateWizardSheet";import { KeyUsageSection } from "./KeyUsageSection";import { SubjectAltNamesField } from "./SubjectAltNamesField";@@ -94,8 +97,28 @@ const formSchema = zmessage: "A certificate signing request is required"});}+ if (data.keySource !== CertificateRenewalKeySource.Csr) {+ if (!data.signatureAlgorithm) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["signatureAlgorithm"],+ message: "Signature algorithm is required"+ });+ }+ if (data.keySource === CertificateRenewalKeySource.New && !data.keyAlgorithm) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["keyAlgorithm"],+ message: "Key algorithm is required"+ });+ }+ }});+const externalTemplateFormSchema = formSchema.innerType().omit({ ttl: true }).extend({+ ttl: z.string().trim().optional()+});+export type RenewalFormData = z.infer<typeof formSchema>;type RenewalStepKey = "setup" | "csr" | "subject" | "options";@@ -132,6 +155,14 @@ const STEP_META: Record<RenewalStepKey, WizardStep> = {}};+const EXTERNAL_TEMPLATE_OPTIONS_STEP: WizardStep = {+ ...STEP_META.options,+ shortDescription: "Key algorithm",+ subtitle: "Choose the key algorithm for the renewed certificate.",+ rightDescription:+ "The issuing certificate authority takes validity, key usages, extended key usages and basic constraints from its own certificate template, so they cannot be set here."+};+const STEP_FIELDS: Record<RenewalStepKey, string[]> = {setup: ["keySource"],csr: ["csr", "ttl"],@@ -148,13 +179,14 @@ const STEP_FIELDS: Record<RenewalStepKey, string[]> = {type Props = {popUp: UsePopUpState<["renewCertificate"]>;+ applicationName?: string;handlePopUpToggle: (popUpName: keyof UsePopUpState<["renewCertificate"]>,state?: boolean) => void;};-export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) => {+export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpToggle }: Props) => {const { currentProject } = useProject();const { currentOrg } = useOrganization();const navigate = useNavigate();@@ -175,6 +207,12 @@ export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) =>applicationId: certificate?.applicationId ?? undefined});+ const isExternalTemplateProfile = isExternalTemplateCa(+ profile?.certificateAuthority?.externalType+ );+ const isExternalTemplateProfileRef = useRef(false);+ isExternalTemplateProfileRef.current = isExternalTemplateProfile;+const constraints = useMemo(() => (policyData ? deriveTemplateConstraints(policyData) : DEFAULT_TEMPLATE_CONSTRAINTS),[policyData]@@ -197,10 +235,16 @@ export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) =>reset,watch,setValue,+ trigger,formState,formState: { isSubmitting }} = useForm<RenewalFormData>({- resolver: zodResolver(formSchema),+ resolver: (values, context, options) =>+ zodResolver(isExternalTemplateProfileRef.current ? externalTemplateFormSchema : formSchema)(+ values,+ context,+ options+ ),defaultValues: {keySource: CertificateRenewalKeySource.New,ttl: "",@@ -250,6 +294,22 @@ export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) =>[filteredExtendedKeyUsages, watchedExtendedKeyUsages]);+ const watchedKeyAlgorithm = watch("keyAlgorithm");+ const watchedSignatureAlgorithm = watch("signatureAlgorithm");+ const selectableKeyAlgorithms = useMemo(+ () => unionUsageOptions(availableKeyAlgorithms, certKeyAlgorithms, watchedKeyAlgorithm ?? ""),+ [availableKeyAlgorithms, watchedKeyAlgorithm]+ );+ const selectableSignatureAlgorithms = useMemo(+ () =>+ unionUsageOptions(+ availableSignatureAlgorithms,+ SIGNATURE_ALGORITHMS_OPTIONS,+ watchedSignatureAlgorithm ?? ""+ ),+ [availableSignatureAlgorithms, watchedSignatureAlgorithm]+ );+const selectableSubjectAttributeTypes = useMemo(() =>Array.from(@@ -300,10 +360,19 @@ export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) =>const { step, setStep, currentStepKey, goBack, goNext, onFormInvalid } = useWizardSteps({stepKeys,stepFields: STEP_FIELDS,- invalidMessage: "Please fix the highlighted fields before renewing."+ invalidMessage: "Please fix the highlighted fields before renewing.",+ validateStep: (fields) => trigger(fields as (keyof RenewalFormData)[])});- const steps = useMemo(() => stepKeys.map((key) => STEP_META[key]), [stepKeys]);+ const steps = useMemo(+ () =>+ stepKeys.map((key) =>+ key === "options" && isExternalTemplateProfile+ ? EXTERNAL_TEMPLATE_OPTIONS_STEP+ : STEP_META[key]+ ),+ [stepKeys, isExternalTemplateProfile]+ );const seededCertificateIdRef = useRef<string | null>(null);useEffect(() => {@@ -332,7 +401,11 @@ export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) =>certificateId,renewalKeySource: formData.keySource,...(formData.keySource === CertificateRenewalKeySource.Csr && { csr: formData.csr }),- attributes: buildRenewalRequestAttributes({ formData, constraints })+ attributes: buildRenewalRequestAttributes({+ formData,+ constraints,+ isExternalTemplateProfile+ })});createNotification({@@ -351,7 +424,8 @@ export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) =>orgId: currentOrg.id,projectId: currentProject.id,certificateId: result.certificateId- }+ },+ ...(applicationName && { search: { fromApplication: applicationName } })});}};@@ -493,6 +567,9 @@ export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) =>(formState.errors as { subjectAttributes?: { message?: string } }).subjectAttributes?.message}+ rowErrors={rowErrorsOf(+ (formState.errors as { subjectAttributes?: unknown }).subjectAttributes+ )}/>)}{constraints.shouldShowSanSection && (@@ -503,6 +580,9 @@ export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) =>(formState.errors as { subjectAltNames?: { message?: string } }).subjectAltNames?.message}+ rowErrors={rowErrorsOf(+ (formState.errors as { subjectAltNames?: unknown }).subjectAltNames+ )}/>)}</div>@@ -510,62 +590,75 @@ export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) =>{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>- )}- />+ {!isExternalTemplateProfile && (+ <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>+ )}+ />+ )}<AlgorithmSelectorscontrol={control}- availableSignatureAlgorithms={availableSignatureAlgorithms}- availableKeyAlgorithms={availableKeyAlgorithms}+ availableSignatureAlgorithms={selectableSignatureAlgorithms}+ availableKeyAlgorithms={selectableKeyAlgorithms}keyAlgorithmDisabledReason={keySource === CertificateRenewalKeySource.Reuse? "The key algorithm is fixed while the existing key pair is reused.": undefined}+ hideSignatureAlgorithm={isExternalTemplateProfile}+ signatureError={formState.errors.signatureAlgorithm?.message}+ keyError={formState.errors.keyAlgorithm?.message}+ keyAlgorithmRequired={keySource !== CertificateRenewalKeySource.Reuse}+ keyAlgorithmPlaceholder={+ keySource === CertificateRenewalKeySource.Reuse+ ? "Unchanged (existing key pair)"+ : "Select key algorithm"+ }/>- <div className="mt-4 space-y-6">- <KeyUsageSection- control={control}- title="Key Usages"- namePrefix="keyUsages"- options={selectableKeyUsages}- requiredUsages={constraints.requiredKeyUsages}- />- <KeyUsageSection- control={control}- title="Extended Key Usages"- namePrefix="extendedKeyUsages"- options={selectableExtendedKeyUsages}- requiredUsages={constraints.requiredExtendedKeyUsages}- />- {constraints.templateAllowsCA && (- <BasicConstraintsField+ {!isExternalTemplateProfile && (+ <div className="mt-4 space-y-6">+ <KeyUsageSectioncontrol={control}- setValue={setValue}- isCA={watchedIsCA}- templateRequiresCA={constraints.templateRequiresCA}- maxPathLength={- constraints.maxPathLength === -1 ? undefined : constraints.maxPathLength- }- idPrefix="renewal"+ title="Key Usages"+ namePrefix="keyUsages"+ options={selectableKeyUsages}+ requiredUsages={constraints.requiredKeyUsages}/>- )}- </div>+ <KeyUsageSection+ control={control}+ title="Extended Key Usages"+ namePrefix="extendedKeyUsages"+ options={selectableExtendedKeyUsages}+ 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>)}</CertificateWizardSheet>diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsxindex 727b28474d..63ad36bd9e 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx@@ -201,7 +201,11 @@ export const CertificatesSection = ({onFormatSelected={handleCertificateExport}/><CertificateManageRenewalModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />- <CertificateRenewalModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />+ <CertificateRenewalModal+ popUp={popUp}+ applicationName={applicationName}+ handlePopUpToggle={handlePopUpToggle}+ /><CertificateRevocationModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} /><CertificateManagePkiSyncsModalpopUp={popUp.managePkiSyncs}diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsxindex e7ec09d399..811a0a9dcd 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/SubjectAltNamesField.tsx@@ -22,6 +22,7 @@ type SubjectAltNamesFieldProps = {control: Control<any>;allowedSanTypes: CertSubjectAlternativeNameType[];error?: string;+ rowErrors?: (string | undefined)[];shouldUnregister?: boolean;namePrefix?: string;};@@ -30,6 +31,7 @@ export const SubjectAltNamesField = ({control,allowedSanTypes,error,+ rowErrors,shouldUnregister,namePrefix = "subjectAltNames"}: SubjectAltNamesFieldProps) => {@@ -71,16 +73,20 @@ export const SubjectAltNamesField = ({))}</SelectContent></Select>- <Input- value={san.value}- onChange={(e) => {- const newValue = [...currentValues];- newValue[index] = { ...san, value: e.target.value };- onChange(newValue);- }}- placeholder={getSanPlaceholder(san.type)}- className="flex-1"- />+ <div className="flex-1">+ <Input+ value={san.value}+ onChange={(e) => {+ const newValue = [...currentValues];+ newValue[index] = { ...san, value: e.target.value };+ onChange(newValue);+ }}+ placeholder={getSanPlaceholder(san.type)}+ isError={Boolean(rowErrors?.[index])}+ className="w-full"+ />+ {rowErrors?.[index] ? <FieldError>{rowErrors[index]}</FieldError> : null}+ </div><IconButtontype="button"variant="ghost"diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.tsindex 7b6129493f..d72411735d 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts@@ -1,6 +1,12 @@+import {+ certKeyAlgorithms,+ SIGNATURE_ALGORITHMS_OPTIONS+} from "@app/hooks/api/certificates/constants";import { CertificateRenewalKeySource } from "@app/hooks/api/certificates/enums";import { TCertificate, TRenewCertificateAttributes } from "@app/hooks/api/certificates/types";import {+ CertExtendedKeyUsageType,+ CertKeyUsageType,CertSubjectAlternativeNameType,CertSubjectAttributeType} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";@@ -17,6 +23,27 @@ import type { TemplateConstraints } from "./useCertificatePolicy";const MS_PER_DAY = 24 * 60 * 60 * 1000;+const usageByCollapsedName = <T extends string>(values: T[], aliases: Record<string, T> = {}) =>+ new Map<string, T>([+ ...values.map((value) => [value.replace(/_/g, "").toLowerCase(), value] as [string, T]),+ ...(Object.entries(aliases) as [string, T][])+ ]);++const KNOWN_SIGNATURE_ALGORITHMS = new Set<string>(+ SIGNATURE_ALGORITHMS_OPTIONS.map((o) => o.value)+);+const KNOWN_KEY_ALGORITHMS = new Set<string>(certKeyAlgorithms.map((o) => o.value as string));++const KEY_USAGE_BY_NAME = usageByCollapsedName(Object.values(CertKeyUsageType));+const EXTENDED_KEY_USAGE_BY_NAME = usageByCollapsedName(Object.values(CertExtendedKeyUsageType), {+ anyextendedkeyusage: CertExtendedKeyUsageType.ANY_PURPOSE+});++const toUsageFormKeys = (usages: string[] | undefined, known: Map<string, string>) =>+ Object.fromEntries(+ (usages ?? []).map((usage) => [known.get(usage.replace(/_/g, "").toLowerCase()) ?? usage, true])+ );+const deriveTtlFromCertificate = (cert: TCertificate): string => {const spanMs = new Date(cert.notAfter).getTime() - new Date(cert.notBefore).getTime();if (!Number.isFinite(spanMs) || spanMs <= 0) return "";@@ -91,12 +118,14 @@ export const buildRenewalFormDefaults = (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])- )+ signatureAlgorithm: KNOWN_SIGNATURE_ALGORITHMS.has(cert.signatureAlgorithm ?? "")+ ? (cert.signatureAlgorithm as string)+ : "",+ keyAlgorithm: KNOWN_KEY_ALGORITHMS.has(cert.keyAlgorithm ?? "")+ ? (cert.keyAlgorithm as string)+ : "",+ keyUsages: toUsageFormKeys(cert.keyUsages, KEY_USAGE_BY_NAME),+ extendedKeyUsages: toUsageFormKeys(cert.extendedKeyUsages, EXTENDED_KEY_USAGE_BY_NAME)});const buildBasicConstraints = (@@ -113,10 +142,12 @@ const buildBasicConstraints = (export const buildRenewalRequestAttributes = ({formData,- constraints+ constraints,+ isExternalTemplateProfile = false}: {formData: RenewalFormData;constraints: TemplateConstraints;+ isExternalTemplateProfile?: boolean;}): TRenewCertificateAttributes => {// The CSR carries its own basic constraints and the CSR step offers no control over them, so// sending the previous certificate's would silently override what the caller actually signed.@@ -126,15 +157,20 @@ export const buildRenewalRequestAttributes = ({const basicConstraints = buildBasicConstraints(formData, constraints);- 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 })- };+ const attributes: TRenewCertificateAttributes = isExternalTemplateProfile+ ? {+ ...(formData.keySource !== CertificateRenewalKeySource.Reuse &&+ formData.keyAlgorithm && { keyAlgorithm: formData.keyAlgorithm })+ }+ : {+ 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 }) => {diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateUtils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateUtils.tsindex 0d3f967aa0..ae58689e39 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateUtils.ts+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateUtils.ts@@ -1,4 +1,5 @@import { isIPv4, isIPv6 } from "@app/helpers/ip";+import { CaType } from "@app/hooks/api/ca";import {CertSubjectAlternativeNameType,CertSubjectAttributeType@@ -54,6 +55,13 @@ export const formatSubjectAltNames = (subjectAltNames: SubjectAltName[]) => {}));};+export const rowErrorsOf = (fieldErrors: unknown): (string | undefined)[] | undefined =>+ Array.isArray(fieldErrors)+ ? (fieldErrors as ({ value?: { message?: string } } | undefined)[]).map(+ (rowError) => rowError?.value?.message+ )+ : undefined;+export const filterUsages = <T extends Record<string, boolean>>(usages: T): string[] => {return Object.entries(usages).filter(([, value]) => value)@@ -84,3 +92,9 @@ export const SUBJECT_ATTR_MAP: {{ attrType: CertSubjectAttributeType.STATE, requestKey: "state" },{ attrType: CertSubjectAttributeType.LOCALITY, requestKey: "locality" }];++export const isExternalTemplateCa = (externalCaType?: CaType | string | null) =>+ externalCaType === CaType.ADCS || externalCaType === CaType.AZURE_AD_CS;++export const EXTERNAL_CA_TEMPLATE_HINT =+ "Validity, key usages, extended key usages and basic constraints are controlled by the external CA's certificate template.";