Skip to content

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

Renew certificates from the originating request instead of the issued certificate

Carlos Monastyrski149bf854c5cc
diff --git a/backend/src/db/migrations/20260923181422_backfill-certificate-request-from-certificate.ts b/backend/src/db/migrations/20260923181422_backfill-certificate-request-from-certificate.ts
new file mode 100644
index 0000000000..b5dbb0b763
--- /dev/null
+++ b/backend/src/db/migrations/20260923181422_backfill-certificate-request-from-certificate.ts
@@ -0,0 +1,59 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const BACKFILL_BATCH_SIZE = 5_000;
+const MAX_BACKFILL_BATCHES = 10_000;
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.CertificateRequests))) return;
+
+ const gapPredicate = `EXISTS (SELECT 1 FROM ?? AS i WHERE i."caId" = c."caId")
+ AND ((r.organization IS NULL AND c."subjectOrganization" IS NOT NULL)
+ OR (r."organizationalUnit" IS NULL AND c."subjectOrganizationalUnit" IS NOT NULL)
+ OR (r.country IS NULL AND c."subjectCountry" IS NOT NULL)
+ OR (r.state IS NULL AND c."subjectState" IS NOT NULL)
+ OR (r.locality IS NULL AND c."subjectLocality" IS NOT NULL))`;
+
+ for (let batch = 0; batch < MAX_BACKFILL_BATCHES; batch += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const result = await knex.raw(
+ `UPDATE ?? AS r SET
+ organization = COALESCE(r.organization, c."subjectOrganization"),
+ "organizationalUnit" = COALESCE(r."organizationalUnit", c."subjectOrganizationalUnit"),
+ country = COALESCE(r.country, c."subjectCountry"),
+ state = COALESCE(r.state, c."subjectState"),
+ locality = COALESCE(r.locality, c."subjectLocality")
+ FROM ?? AS c
+ WHERE c.id = r."certificateId"
+ AND ${gapPredicate}
+ AND r.id IN (
+ SELECT r2.id FROM ?? AS r2
+ JOIN ?? AS c2 ON c2.id = r2."certificateId"
+ WHERE EXISTS (SELECT 1 FROM ?? AS i2 WHERE i2."caId" = c2."caId")
+ AND ((r2.organization IS NULL AND c2."subjectOrganization" IS NOT NULL)
+ OR (r2."organizationalUnit" IS NULL AND c2."subjectOrganizationalUnit" IS NOT NULL)
+ OR (r2.country IS NULL AND c2."subjectCountry" IS NOT NULL)
+ OR (r2.state IS NULL AND c2."subjectState" IS NOT NULL)
+ OR (r2.locality IS NULL AND c2."subjectLocality" IS NOT NULL))
+ LIMIT ?
+ )`,
+ [
+ TableName.CertificateRequests,
+ TableName.Certificate,
+ TableName.InternalCertificateAuthority,
+ TableName.CertificateRequests,
+ TableName.Certificate,
+ TableName.InternalCertificateAuthority,
+ BACKFILL_BATCH_SIZE
+ ]
+ );
+
+ if (!result.rowCount) break;
+ }
+}
+
+export async function down(): Promise<void> {}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.ts
index 2d848a09c0..be1d17652c 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts
@@ -1380,8 +1380,7 @@ export const pkiAcmeServiceFactory = ({
extendedKeyUsages: certificateRequest.extendedKeyUsages || null,
notBefore: finalizingOrder.notBefore || null,
notAfter: finalizingOrder.notAfter || null,
- keyAlgorithm: null,
- signatureAlgorithm: null,
+ ...extractAlgorithmsFromCSR(csr),
ttl,
enrollmentType: EnrollmentType.ACME,
status: CertificateRequestStatus.PENDING_APPROVAL,
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index cf91545042..af8accdd97 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2276,6 +2276,15 @@ export const CERTIFICATES = {
"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."
},
+ RENEWAL_PREVIEW: {
+ id: "The ID of the certificate to preview a renewal for.",
+ hasOriginatingRequest:
+ "Whether the certificate has a recorded originating request. When false the preview falls back to the issued certificate, which is the case for imported and discovered certificates.",
+ request:
+ "The values a renewal will request, taken from the request that produced this certificate including any profile defaults it recorded.",
+ issuerModifiedFields:
+ "Fields the issuing authority set differently from the request, each with the requested and issued values. A renewal asks for the requested value again unless it is changed."
+ },
REVOKE: {
id: "The ID or SHA-1/SHA-256 thumbprint of the certificate to revoke. Thumbprint colons and casing are ignored.",
serialNumber:
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index b1e580be88..4344cbab87 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -1173,6 +1173,57 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "GET",
+ url: "/:id/renewal-preview",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ schema: {
+ hide: true,
+ operationId: "getCertificateRenewalPreview",
+ tags: [ApiDocsTags.PkiCertificates],
+ description:
+ "Get the values a renewal of this certificate will request, taken from the request that produced it, together with the fields the issuing authority changed.",
+ params: z.object({
+ id: z.string().trim().uuid().describe(CERTIFICATES.RENEWAL_PREVIEW.id)
+ }),
+ response: {
+ 200: z.object({
+ hasOriginatingRequest: z.boolean().describe(CERTIFICATES.RENEWAL_PREVIEW.hasOriginatingRequest),
+ request: z
+ .object({
+ commonName: z.string().optional(),
+ organization: z.string().optional(),
+ organizationalUnit: z.string().optional(),
+ country: z.string().optional(),
+ state: z.string().optional(),
+ locality: z.string().optional(),
+ domainComponents: z.array(z.string()).optional(),
+ altNames: z.array(z.object({ type: z.string(), value: z.string() })),
+ keyUsages: z.array(z.string()),
+ extendedKeyUsages: z.array(z.string()),
+ keyAlgorithm: z.string().optional(),
+ signatureAlgorithm: z.string().optional()
+ })
+ .describe(CERTIFICATES.RENEWAL_PREVIEW.request),
+ issuerModifiedFields: z
+ .array(z.object({ field: z.string(), requested: z.string(), issued: z.string() }))
+ .describe(CERTIFICATES.RENEWAL_PREVIEW.issuerModifiedFields)
+ })
+ }
+ },
+ handler: async (req) =>
+ server.services.certificateV3.getRenewalPreview({
+ certificateId: req.params.id,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ })
+ });
+
server.route({
method: "POST",
url: "/:id/renew",
diff --git a/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts b/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts
index af6c90b425..2bfc6ef10e 100644
--- a/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts
+++ b/backend/src/services/certificate-v3/certificate-renewal-fns.test.ts
@@ -1,4 +1,6 @@
import { webcrypto } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
@@ -16,6 +18,7 @@ import {
buildCsrRenewalCertificateRequest,
buildRenewalAuditChanges,
buildRenewalCertificateRequest,
+ buildRenewalPreview,
certificateSpanToTtl,
importKeyPairFromPem,
isCertificateContentEdit,
@@ -67,6 +70,20 @@ describe("resolveRenewalAltNames", () => {
});
});
+describe("renewal never re-evaluates profile defaults", () => {
+ const renewalPreviews = ["certificate-renewal-service.ts", "certificate-renewal-fns.ts"];
+
+ it("keeps applyProfileDefaults and profile.defaults out of the renewal path", () => {
+ for (const file of renewalPreviews) {
+ const source = readFileSync(join(__dirname, file), "utf8");
+
+ expect(source, `${file} must not apply profile defaults during a renewal`).not.toMatch(
+ /applyProfileDefaults|profile\.defaults/
+ );
+ }
+ });
+});
+
describe("resolveRenewalSubject", () => {
const issuerWritten = {
subjectOrganization: "Mock Issuer Corp",
@@ -199,15 +216,17 @@ describe("resolveRenewalUsages", () => {
});
});
- it("reads the certificate back when the request recorded no usages, because ACME never records them", () => {
+ it("reads the certificate back only when the column is null, which means nothing was ever recorded", () => {
expect(resolveRenewalUsages({ exists: true, keyUsages: null, extendedKeyUsages: null }, issued)).toEqual({
keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE, CertKeyUsageType.KEY_ENCIPHERMENT],
extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH]
});
+ });
+ it("asks for no usages again when the request recorded none, so the authority chooses as it did before", () => {
expect(resolveRenewalUsages({ exists: true, keyUsages: [], extendedKeyUsages: [] }, issued)).toEqual({
- keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE, CertKeyUsageType.KEY_ENCIPHERMENT],
- extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH]
+ keyUsages: [],
+ extendedKeyUsages: []
});
});
@@ -425,25 +444,6 @@ 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",
@@ -456,23 +456,23 @@ describe("buildRenewalAuditChanges", () => {
validity: { ttl: "30d" }
};
- it("records nothing when the renewal reproduces the certificate", () => {
- expect(buildRenewalAuditChanges(cert, unchangedRequest)).toEqual([]);
+ it("records nothing when the renewal replays the request unchanged", () => {
+ expect(buildRenewalAuditChanges(unchangedRequest, unchangedRequest)).toEqual([]);
+ });
+
+ it("records nothing when the authority rewrote the certificate but the caller edited nothing", () => {
+ const replayed = { ...unchangedRequest };
+
+ expect(buildRenewalAuditChanges(replayed, { ...replayed })).toEqual([]);
});
it("records a custom extension change with the readable values, not their DER", () => {
- const withExtension = {
- ...cert,
- customExtensions: [
- {
- oid: "1.3.6.1.4.1.99001.1",
- critical: false,
- value: encodeCustomExtensionValue("1.3.6.1.4.1.99001.1", "before")
- }
- ]
+ const withExtensionRequest: TCertificateRequest = {
+ ...unchangedRequest,
+ customExtensions: [{ oid: "1.3.6.1.4.1.99001.1", value: "before" }]
};
- const changes = buildRenewalAuditChanges(withExtension, {
+ const changes = buildRenewalAuditChanges(withExtensionRequest, {
...unchangedRequest,
customExtensions: [{ oid: "1.3.6.1.4.1.99001.1", value: "after" }]
});
@@ -483,19 +483,13 @@ describe("buildRenewalAuditChanges", () => {
});
it("records nothing when the custom extensions are unchanged", () => {
- const withExtension = {
- ...cert,
- customExtensions: [
- {
- oid: "1.3.6.1.4.1.99001.1",
- critical: false,
- value: encodeCustomExtensionValue("1.3.6.1.4.1.99001.1", "same")
- }
- ]
+ const withExtensionRequest: TCertificateRequest = {
+ ...unchangedRequest,
+ customExtensions: [{ oid: "1.3.6.1.4.1.99001.1", value: "same" }]
};
expect(
- buildRenewalAuditChanges(withExtension, {
+ buildRenewalAuditChanges(withExtensionRequest, {
...unchangedRequest,
customExtensions: [{ oid: "1.3.6.1.4.1.99001.1", value: "same" }]
})
@@ -504,13 +498,16 @@ describe("buildRenewalAuditChanges", () => {
it("does not report a change when stored legacy usage names resolve to the same usages", () => {
expect(
- buildRenewalAuditChanges(cert, { ...unchangedRequest, keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE] })
+ buildRenewalAuditChanges(unchangedRequest, {
+ ...unchangedRequest,
+ keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE]
+ })
).toEqual([]);
});
it("records before and after for each changed attribute", () => {
expect(
- buildRenewalAuditChanges(cert, {
+ buildRenewalAuditChanges(unchangedRequest, {
...unchangedRequest,
commonName: "api.example.com",
subjectAlternativeNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "api.example.com" }],
@@ -524,14 +521,14 @@ describe("buildRenewalAuditChanges", () => {
});
it("records a cleared field as an empty value", () => {
- expect(buildRenewalAuditChanges(cert, { ...unchangedRequest, organization: undefined })).toEqual([
+ expect(buildRenewalAuditChanges(unchangedRequest, { ...unchangedRequest, organization: undefined })).toEqual([
{ field: "organization", from: "Example Corp", to: "" }
]);
});
it("renders basic constraints and lists readably", () => {
expect(
- buildRenewalAuditChanges(cert, {
+ buildRenewalAuditChanges(unchangedRequest, {
...unchangedRequest,
basicConstraints: { isCA: true, pathLength: 2 },
keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE, CertKeyUsageType.KEY_ENCIPHERMENT]
@@ -545,7 +542,7 @@ describe("buildRenewalAuditChanges", () => {
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(buildRenewalAuditChanges(unchangedRequest, 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" }
@@ -574,3 +571,84 @@ describe("isCertificateContentEdit", () => {
expect(isCertificateContentEdit({ keySource: CertificateRenewalKeySource.Csr })).toBe(true);
});
});
+
+describe("buildRenewalPreview", () => {
+ const certificate = {
+ commonName: "issued.example.com",
+ altNames: "issued.example.com",
+ subjectOrganization: null,
+ subjectOrganizationalUnit: null,
+ subjectCountry: null,
+ subjectState: null,
+ subjectLocality: null,
+ subjectDomainComponents: null,
+ keyUsages: ["digitalSignature"],
+ extendedKeyUsages: ["serverAuth"],
+ keyAlgorithm: CertKeyAlgorithm.RSA_2048,
+ signatureAlgorithm: CertSignatureAlgorithm.RSA_SHA256,
+ customExtensions: []
+ };
+
+ const requested = {
+ exists: true,
+ commonName: "issued.example.com",
+ organization: null,
+ organizationalUnit: null,
+ country: null,
+ state: null,
+ locality: null,
+ domainComponents: null,
+ altNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "issued.example.com" }],
+ keyUsages: ["digital_signature"],
+ extendedKeyUsages: ["server_auth"],
+ keyAlgorithm: CertKeyAlgorithm.RSA_2048,
+ signatureAlgorithm: CertSignatureAlgorithm.RSA_SHA256
+ };
+
+ it("reports nothing when the authority issued what was asked for", () => {
+ expect(buildRenewalPreview(requested, certificate).issuerModifiedFields).toEqual([]);
+ });
+
+ it("does not read a legacy value the form cannot offer as an authority change", () => {
+ const legacy = "RSA_2048";
+ const { request, issuerModifiedFields } = buildRenewalPreview(
+ { ...requested, signatureAlgorithm: legacy },
+ { ...certificate, signatureAlgorithm: legacy }
+ );
+
+ expect(request.signatureAlgorithm).toBeUndefined();
+ expect(issuerModifiedFields.map((entry) => entry.field)).not.toContain("signatureAlgorithm");
+ });
+
+ it("does not report a reordering or a stray space as an authority change", () => {
+ const reordered = buildRenewalPreview(
+ { ...requested, keyUsages: ["key_encipherment", "digital_signature"] },
+ { ...certificate, keyUsages: ["digitalSignature", "keyEncipherment"] }
+ );
+ expect(reordered.issuerModifiedFields.map((entry) => entry.field)).not.toContain("keyUsages");
+
+ const spaced = buildRenewalPreview(requested, { ...certificate, altNames: " issued.example.com " });
+ expect(spaced.issuerModifiedFields.map((entry) => entry.field)).not.toContain("altNames");
+ });
+
+ it("keeps domain component order significant, since it is part of the distinguished name", () => {
+ const { issuerModifiedFields } = buildRenewalPreview(
+ { ...requested, domainComponents: "example,com" },
+ { ...certificate, subjectDomainComponents: "com,example" }
+ );
+ expect(issuerModifiedFields.map((entry) => entry.field)).toContain("domainComponents");
+ });
+
+ it("reports a usage the authority swapped, in one vocabulary", () => {
+ const { issuerModifiedFields } = buildRenewalPreview(
+ { ...requested, extendedKeyUsages: ["client_auth"] },
+ certificate
+ );
+
+ expect(issuerModifiedFields).toContainEqual({
+ field: "extendedKeyUsages",
+ requested: "client_auth",
+ issued: "server_auth"
+ });
+ });
+});
diff --git a/backend/src/services/certificate-v3/certificate-renewal-fns.ts b/backend/src/services/certificate-v3/certificate-renewal-fns.ts
index 55e94215f4..a01b29fdc0 100644
--- a/backend/src/services/certificate-v3/certificate-renewal-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-renewal-fns.ts
@@ -8,7 +8,12 @@ import { isPqcAlgorithm } from "@app/lib/crypto/pqc/pqc-utils";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { ms } from "@app/lib/ms";
-import { CertKeyAlgorithm, CertStatus, mapSanTypeToX509Type } from "@app/services/certificate/certificate-types";
+import {
+ CertKeyAlgorithm,
+ CertSignatureAlgorithm,
+ 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 {
@@ -262,15 +267,75 @@ export const resolveRenewalCustomExtensions = (
): TRequestCustomExtension[] =>
toRequestCustomExtensions(requested.exists ? requested.customExtensions : certificate.customExtensions);
+const splitStoredList = (stored: string | null | undefined): string[] | undefined => {
+ const values = (stored ?? "")
+ .split(",")
+ .map((entry) => entry.trim())
+ .filter(Boolean);
+
+ return values.length ? values : undefined;
+};
+
+const askedFor = <T>(exists: boolean, recorded: T[] | null): T[] | null => (exists ? recorded : null);
+
export const resolveRenewalUsages = (
requested: { exists: boolean; keyUsages: string[] | null; extendedKeyUsages: string[] | null },
certificate: { keyUsages?: unknown; extendedKeyUsages?: unknown }
-): { keyUsages: CertKeyUsageType[]; extendedKeyUsages: CertExtendedKeyUsageType[] } => {
- const asked = <T>(recorded: T[] | null): T[] | null => (requested.exists && recorded?.length ? recorded : null);
+): { keyUsages: CertKeyUsageType[]; extendedKeyUsages: CertExtendedKeyUsageType[] } => ({
+ keyUsages: parseKeyUsages(askedFor(requested.exists, requested.keyUsages) ?? certificate.keyUsages),
+ extendedKeyUsages: parseExtendedKeyUsages(
+ askedFor(requested.exists, requested.extendedKeyUsages) ?? certificate.extendedKeyUsages
+ )
+});
+
+type TOriginatingRenewalRequest = {
+ exists: boolean;
+ commonName: string | null;
+ organization: string | null;
+ organizationalUnit: string | null;
+ country: string | null;
+ state: string | null;
+ locality: string | null;
+ domainComponents: string | null;
+ altNames: { type: CertSubjectAlternativeNameType; value: string }[] | null;
+ keyUsages: string[] | null;
+ extendedKeyUsages: string[] | null;
+ keyAlgorithm: string | null;
+ signatureAlgorithm: string | null;
+};
+
+type TRenewalCertificateFacts = {
+ commonName?: string | null;
+ subjectOrganization?: string | null;
+ subjectOrganizationalUnit?: string | null;
+ subjectCountry?: string | null;
+ subjectState?: string | null;
+ subjectLocality?: string | null;
+ subjectDomainComponents?: string | null;
+ altNames?: string | null;
+ keyUsages?: unknown;
+ extendedKeyUsages?: unknown;
+ keyAlgorithm?: string | null;
+ signatureAlgorithm?: string | null;
+};
+
+const asKeyAlgorithm = (value?: string | null): CertKeyAlgorithm | undefined =>
+ Object.values(CertKeyAlgorithm).includes(value as CertKeyAlgorithm) ? (value as CertKeyAlgorithm) : undefined;
+
+const asSignatureAlgorithm = (value?: string | null): CertSignatureAlgorithm | undefined =>
+ Object.values(CertSignatureAlgorithm).includes(value as CertSignatureAlgorithm)
+ ? (value as CertSignatureAlgorithm)
+ : undefined;
+
+export const resolveRenewalAlgorithms = (
+ requested: { exists: boolean; keyAlgorithm: string | null; signatureAlgorithm: string | null },
+ certificate: { keyAlgorithm?: string | null; signatureAlgorithm?: string | null }
+): { keyAlgorithm?: CertKeyAlgorithm; signatureAlgorithm?: CertSignatureAlgorithm } => {
+ const source = requested.exists ? requested : certificate;
return {
- keyUsages: parseKeyUsages(asked(requested.keyUsages) ?? certificate.keyUsages),
- extendedKeyUsages: parseExtendedKeyUsages(asked(requested.extendedKeyUsages) ?? certificate.extendedKeyUsages)
+ keyAlgorithm: asKeyAlgorithm(source.keyAlgorithm),
+ signatureAlgorithm: asSignatureAlgorithm(source.signatureAlgorithm)
};
};
@@ -310,7 +375,7 @@ export const resolveRenewalSubject = (
country: source.country || undefined,
state: source.state || undefined,
locality: source.locality || undefined,
- domainComponents: source.domainComponents?.split(",") ?? undefined
+ domainComponents: splitStoredList(source.domainComponents)
};
};
@@ -318,9 +383,10 @@ export const resolveRenewalAltNames = (
requested: { exists: boolean; altNames: { type: CertSubjectAlternativeNameType; value: string }[] | null },
certificateAltNames: string | null | undefined
): { type: CertSubjectAlternativeNameType; value: string }[] => {
- if (requested.exists) return requested.altNames ?? [];
+ const recorded = askedFor(requested.exists, requested.altNames);
+ if (recorded) return recorded;
- return certificateAltNames?.split(",").map((san) => detectSanType(san.trim())) ?? [];
+ return (splitStoredList(certificateAltNames) ?? []).map((san) => detectSanType(san));
};
/**
@@ -377,15 +443,88 @@ export const buildCsrRenewalCertificateRequest = ({
};
export const buildRenewalAuditChanges = (
- original: TRenewalAuditSubject,
+ replayedRequest: TCertificateRequest,
issuedRequest: TCertificateRequest
): TRenewalAuditChange[] =>
RENEWAL_ATTRIBUTE_KEYS.map((field) => ({
field,
- from: RENEWAL_ATTRIBUTES[field].current(original),
+ from: RENEWAL_ATTRIBUTES[field].issued(replayedRequest),
to: RENEWAL_ATTRIBUTES[field].issued(issuedRequest)
})).filter(({ from, to }) => from !== to);
+export type TIssuerModifiedField = {
+ field: string;
+ requested: string;
+ issued: string;
+};
+
+export const buildRenewalPreview = (requested: TOriginatingRenewalRequest, certificate: TRenewalCertificateFacts) => {
+ const subject = resolveRenewalSubject(requested, certificate);
+ const usages = resolveRenewalUsages(requested, certificate);
+ const algorithms = resolveRenewalAlgorithms(requested, certificate);
+ const altNames = resolveRenewalAltNames(requested, certificate.altNames);
+
+ const request = {
+ commonName: requested.exists ? (requested.commonName ?? undefined) : (certificate.commonName ?? undefined),
+ ...subject,
+ ...usages,
+ ...algorithms,
+ altNames
+ };
+
+ const issuedSubject = {
+ commonName: certificate.commonName ?? undefined,
+ organization: certificate.subjectOrganization ?? undefined,
+ organizationalUnit: certificate.subjectOrganizationalUnit ?? undefined,
+ country: certificate.subjectCountry ?? undefined,
+ state: certificate.subjectState ?? undefined,
+ locality: certificate.subjectLocality ?? undefined
+ };
+
+ const joined = (values?: string[]) => (values ?? []).join(",");
+ const issuerModifiedFields: TIssuerModifiedField[] = [];
+ const note = (field: string, requestedValue?: string, issuedValue?: string) => {
+ if ((requestedValue ?? "") !== (issuedValue ?? "")) {
+ issuerModifiedFields.push({ field, requested: requestedValue ?? "", issued: issuedValue ?? "" });
+ }
+ };
+
+ const noteSet = (field: string, requestedValue: string, issuedValue: string) => {
+ const normalize = (value: string) => (splitStoredList(value) ?? []).sort().join(",");
+ if (normalize(requestedValue) !== normalize(issuedValue)) {
+ issuerModifiedFields.push({ field, requested: requestedValue, issued: issuedValue });
+ }
+ };
+
+ const seededSubject: Record<string, string | undefined> = {
+ commonName: request.commonName,
+ organization: request.organization,
+ organizationalUnit: request.organizationalUnit,
+ country: request.country,
+ state: request.state,
+ locality: request.locality
+ };
+ Object.entries(issuedSubject).forEach(([field, issuedValue]) => {
+ note(field, seededSubject[field], issuedValue);
+ });
+ note(
+ "domainComponents",
+ joined(request.domainComponents),
+ joined(splitStoredList(certificate.subjectDomainComponents) ?? [])
+ );
+ noteSet("altNames", joined(altNames.map((san) => san.value)), joined(splitStoredList(certificate.altNames) ?? []));
+ noteSet("keyUsages", joined(usages.keyUsages), joined(parseKeyUsages(certificate.keyUsages)));
+ noteSet(
+ "extendedKeyUsages",
+ joined(usages.extendedKeyUsages),
+ joined(parseExtendedKeyUsages(certificate.extendedKeyUsages))
+ );
+ note("keyAlgorithm", algorithms.keyAlgorithm, asKeyAlgorithm(certificate.keyAlgorithm));
+ note("signatureAlgorithm", algorithms.signatureAlgorithm, asSignatureAlgorithm(certificate.signatureAlgorithm));
+
+ return { request, issuerModifiedFields, hasOriginatingRequest: requested.exists };
+};
+
export const buildRenewalDistinguishedName = (certificateRequest: TCertificateRequest): string =>
createDistinguishedName({
commonName: certificateRequest.commonName,
diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.ts
index f5bf45c6c6..7fc24bffe8 100644
--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts
+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts
@@ -102,10 +102,12 @@ import {
buildRenewalAuditChanges,
buildRenewalCertificateRequest,
buildRenewalDistinguishedName,
+ buildRenewalPreview,
CertificateRenewalMode,
certificateSpanToTtl,
importKeyPairFromPem,
isCertificateContentEdit,
+ resolveRenewalAlgorithms,
resolveRenewalAltNames,
resolveRenewalCustomExtensions,
resolveRenewalKeySource,
@@ -464,7 +466,7 @@ export const certificateRenewalServiceFactory = ({
applicationId: originalCert.applicationId ?? undefined,
csr: renewalCsr,
commonName: certificateRequest.commonName,
- altNames: requestedAltNames.length > 0 ? requestedAltNames : undefined,
+ altNames: requestedAltNames,
keyUsages: certificateRequest.keyUsages,
extendedKeyUsages: certificateRequest.extendedKeyUsages,
notBefore,
@@ -580,21 +582,15 @@ export const certificateRenewalServiceFactory = ({
});
}
- 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 { signatureAlgorithm: originalSignatureAlgorithm, keyAlgorithm: originalKeyAlgorithm } =
+ resolveRenewalAlgorithms(originatingRequest, originalCert);
+
const { enrollmentType } = originatingRequest;
if (enrollmentType && enrollmentType !== EnrollmentType.API) {
throw new ForbiddenRequestError({
@@ -791,7 +787,12 @@ export const certificateRenewalServiceFactory = ({
throw new RenewalBlockedError(`Certificate renewal failed. Errors: ${validationResult.errors.join(", ")}`);
}
- return { certificateRequest, ttl, resolvedCustomExtensions: validationResult.resolvedCustomExtensions };
+ return {
+ certificateRequest,
+ replayedRequest: originalRequest,
+ ttl,
+ resolvedCustomExtensions: validationResult.resolvedCustomExtensions
+ };
};
const $assertKeySourceSupported = ({
@@ -873,7 +874,7 @@ export const certificateRenewalServiceFactory = ({
profileId: originalCert.profileId ?? undefined,
applicationId: originalCert.applicationId ?? undefined,
commonName: certificateRequest.commonName,
- altNames: renewalAltNames.length > 0 ? renewalAltNames : undefined,
+ altNames: renewalAltNames,
keyUsages: certificateRequest.keyUsages,
extendedKeyUsages: certificateRequest.extendedKeyUsages,
notBefore,
@@ -1113,7 +1114,7 @@ export const certificateRenewalServiceFactory = ({
tx
);
- const { certificateRequest, ttl, resolvedCustomExtensions } = $buildValidatedRenewalRequest({
+ const { certificateRequest, replayedRequest, ttl, resolvedCustomExtensions } = $buildValidatedRenewalRequest({
originalCert,
policy,
csrRenewalRequest,
@@ -1125,7 +1126,7 @@ export const certificateRenewalServiceFactory = ({
profileCustomExtensions: profile?.defaults?.customExtensions
});
- changedAttributes = buildRenewalAuditChanges(originalCert, { ...certificateRequest, validity: { ttl } });
+ changedAttributes = buildRenewalAuditChanges(replayedRequest, { ...certificateRequest, validity: { ttl } });
if (renewalAuth?.projectPermission) {
assertCanEditCertificateResult({
@@ -1291,7 +1292,7 @@ export const certificateRenewalServiceFactory = ({
profileId: originalCert.profileId || undefined,
applicationId: originalCert.applicationId ?? undefined,
commonName: certificateRequest.commonName,
- altNames: renewalAltNames.length > 0 ? renewalAltNames : undefined,
+ altNames: renewalAltNames,
keyUsages: certificateRequest.keyUsages,
extendedKeyUsages: certificateRequest.extendedKeyUsages,
notBefore: new Date(newCert.notBefore),
@@ -1404,7 +1405,7 @@ export const certificateRenewalServiceFactory = ({
caId: ca.id,
csr,
commonName: renewalRequest.commonName,
- altNames: structuredAltNames.length > 0 ? structuredAltNames : undefined,
+ altNames: structuredAltNames,
keyUsages: renewalRequest.keyUsages,
extendedKeyUsages: renewalRequest.extendedKeyUsages,
keyAlgorithm: effectiveKeyAlgorithm,
@@ -1528,6 +1529,32 @@ export const certificateRenewalServiceFactory = ({
return certificate;
};
+ const getRenewalPreview = async ({
+ certificateId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: {
+ certificateId: string;
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ }) => {
+ const certificate = await $loadCertificateForRenewalConfig({
+ certificateId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ const originatingRequest = await certificateDAL.getOriginatingRequestByCertId(certificate.id);
+
+ return buildRenewalPreview(originatingRequest, certificate);
+ };
+
const updateRenewalConfig = async ({
certificateId,
renewBeforeDays,
@@ -1638,6 +1665,7 @@ export const certificateRenewalServiceFactory = ({
return {
renewCertificate,
+ getRenewalPreview,
updateRenewalConfig,
disableRenewalConfig
};
diff --git a/backend/src/services/certificate-v3/certificate-v3-fns.test.ts b/backend/src/services/certificate-v3/certificate-v3-fns.test.ts
index 8d74c0ed51..b656479d65 100644
--- a/backend/src/services/certificate-v3/certificate-v3-fns.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-fns.test.ts
@@ -61,6 +61,24 @@ CP3TUvonGhGkLZsMUGaQaWu9N0oaLbdhttDycyaG3lfba3xdfL/vouoC0CTwlMAZ
8Gn5fDcpjA==
-----END CERTIFICATE REQUEST-----`;
+const FULL_SUBJECT_CSR = `-----BEGIN CERTIFICATE REQUEST-----
+MIICwTCCAakCAQAwfDEZMBcGA1UEAwwQZnVsbC5leGFtcGxlLmNvbTESMBAGA1UE
+CgwJRnVsbCBDb3JwMREwDwYDVQQLDAhQbGF0Zm9ybTELMAkGA1UEBhMCVVMxEzAR
+BgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDVNhbiBGcmFuY2lzY28wggEiMA0G
+CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9BgEbpkoYkvBmRy+xyW19HtTWrbST
+5Ol2LC4HF35nBr3pFhwr9+Xd7UeGJQpRr4b3hc/VpLfPq5V4gciz9lvP+O02Fljn
+oAQgAyZaqoygADP/qwyGRzNsPW/sG2Mf1GWsRs4dGW8Yl7LTJ9Hs20RnCx/LWrLE
+SzuOfi3UiIg+HbgASi+7T8DBp7y0Qy8cPqQbBHi4qTbQpwLonPHOA3OK+O7l/vp6
+mFNvFLqVjSRKZY6E5A1laRLIhRMwFeJEjvmWmTgObJj++1pBoE8VJSQCUu5ujcme
+wO68a1ljm0Wvw0zGPKsXB9a8oU2kVvaCeCVSJf7DlCZorl8NKJN674aPAgMBAAGg
+ADANBgkqhkiG9w0BAQsFAAOCAQEAKhdZAPm5CwpCy3Jh7ASOcTKc+ukvtvR5/VIr
+xG9VFGUMIq8PdWgfFAo/K8sONfzOcVFZnal26yE3im+wXuymMwCChgUkSXcx25ns
+bzZxTO/O/4XbVNSQSagv+NOc8qYlTv0jbUtCCdbYTMCYoELYnTpInFW29eTkrR1i
+cjSLzQcD1OyZ4yowgnnQYx0KZm8CKxmDCsu/+vY6AmfuLJluuXBvXzZuax/RNe6/
+Pzl7ofVUGbGcn5nvIBcCtbf/0ZGXsPKxDsuBlzs76gZBc4VYc3l7qhDmz3k74T07
+oNhXP6h9e3jYLWU+USpa+j8DgWDbwI7OK9CNYYHB4XLuoR2rNg==
+-----END CERTIFICATE REQUEST-----`;
+
const TLS_DEFAULTS: TCertificateProfileDefaults = {
keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE, CertKeyUsageType.KEY_ENCIPHERMENT],
extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH]
@@ -117,6 +135,45 @@ describe("applyProfileDefaults", () => {
expect(request.commonName).toBe("fallback.local");
});
+ it("carries every subject attribute the CSR names through to the persisted request", () => {
+ expect(forCsr(FULL_SUBJECT_CSR, null)).toMatchObject({
+ commonName: "full.example.com",
+ organization: "Full Corp",
+ organizationalUnit: "Platform",
+ country: "US",
+ state: "California",
+ locality: "San Francisco"
+ });
+ });
+
+ it("lets a profile default fill a subject attribute the CSR leaves out", () => {
+ const request = forCsr(EMPTY_SUBJECT_CSR, {
+ ...TLS_DEFAULTS,
+ organization: "Default Org",
+ country: "US"
+ });
+
+ expect(request.organization).toBe("Default Org");
+ expect(request.country).toBe("US");
+ });
+
+ it("never lets a profile default overwrite a subject attribute the CSR carries", () => {
+ const fromCsr = forCsr(FULL_SUBJECT_CSR, null);
+ const withDefaults = forCsr(FULL_SUBJECT_CSR, {
+ ...TLS_DEFAULTS,
+ commonName: "default.example.com",
+ organization: "Default Org",
+ organizationalUnit: "Default OU",
+ country: "ZZ",
+ state: "Default State",
+ locality: "Default City"
+ });
+
+ for (const field of ["commonName", "organization", "organizationalUnit", "country", "state", "locality"] as const) {
+ if (fromCsr[field] !== undefined) expect(withDefaults[field]).toBe(fromCsr[field]);
+ }
+ });
+
it("fills usages while leaving CSR-derived algorithms untouched", () => {
const request = applyProfileDefaults(
{
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 da9bfd5ad0..4e33ce043c 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -3,6 +3,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
import { createMongoAbility, ForbiddenError } from "@casl/ability";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -266,7 +269,9 @@ describe("CertificateV3Service", () => {
altNames: null,
keyUsages: null,
extendedKeyUsages: null,
- customExtensions: null
+ customExtensions: null,
+ keyAlgorithm: null,
+ signatureAlgorithm: null
});
mockCertificateIssuanceQueue.queueCertificateIssuance.mockResolvedValue(undefined);
@@ -1587,6 +1592,17 @@ describe("CertificateV3Service", () => {
);
});
+ it("persists the CSR subject on the request row when an approval policy applies", async () => {
+ const source = readFileSync(join(__dirname, "certificate-v3-service.ts"), "utf8");
+ const approvalWrite = source.slice(source.indexOf("CertificateRequestStatus.PENDING_APPROVAL") - 2500);
+
+ for (const field of ["organization", "organizationalUnit", "country", "state", "locality"]) {
+ expect(approvalWrite, `the CSR approval branch must persist ${field}`).toContain(
+ `${field}: mappedCertificateRequest.${field}`
+ );
+ }
+ });
+
it("passes basicConstraints to the issuance queue for AWS Private CA", async () => {
setupCa(CaType.AWS_PCA);
vi.mocked(mockApprovalPolicyDAL.findByProjectId).mockResolvedValue([]);
@@ -2670,6 +2686,99 @@ describe("CertificateV3Service", () => {
);
});
+ describe("sources the new request from the originating certificate request", () => {
+ const originatingRequest = {
+ enrollmentType: EnrollmentType.API,
+ csr: null,
+ exists: true,
+ commonName: "asked-for.example.com",
+ organization: "Asked Corp",
+ organizationalUnit: "Asked OU",
+ country: "GB",
+ state: "Asked State",
+ locality: "Asked City",
+ domainComponents: null,
+ altNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "asked-for.example.com" }],
+ keyUsages: ["digital_signature"],
+ extendedKeyUsages: ["client_auth"],
+ customExtensions: null,
+ keyAlgorithm: null,
+ signatureAlgorithm: null
+ };
+
+ beforeEach(() => {
+ vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
+ ...mockOriginalCert,
+ commonName: "ca-rewrote.example.com",
+ subjectOrganization: "Issuer Corp",
+ subjectOrganizationalUnit: "Issuer OU",
+ subjectCountry: "US",
+ subjectState: "Issuer State",
+ subjectLocality: "Issuer City",
+ altNames: "ca-added.example.com",
+ keyUsages: ["digital_signature", "key_encipherment"],
+ extendedKeyUsages: ["server_auth"]
+ } as never);
+ vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({
+ id: "secret-123",
+ certId: "cert-123"
+ } as never);
+ vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
+ vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
+ vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
+ vi.mocked(mockCertificateDAL.getOriginatingRequestByCertId).mockResolvedValue(originatingRequest);
+ vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
+ isValid: true,
+ errors: [],
+ warnings: []
+ } as never);
+ vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue({
+ certificate: "cert",
+ certificateChain: "chain",
+ issuingCaCertificate: "issuing-ca",
+ privateKey: "key",
+ serialNumber: "123456",
+ certificateId: "renewed-cert-1"
+ } as never);
+ vi.mocked(mockCertificateDAL.transaction).mockImplementation(
+ async (callback: (tx: never) => Promise<unknown>) => callback(undefined as never)
+ );
+ });
+
+ const expectedRequest = expect.objectContaining({
+ commonName: "asked-for.example.com",
+ organization: "Asked Corp",
+ organizationalUnit: "Asked OU",
+ country: "GB",
+ state: "Asked State",
+ locality: "Asked City",
+ keyUsages: ["digital_signature"],
+ extendedKeyUsages: ["client_auth"]
+ });
+
+ it("uses it for a manual renewal", async () => {
+ await service.renewCertificate({ certificateId: "cert-123", ...mockActor });
+
+ expect(mockCertificateRequestService.createCertificateRequest).toHaveBeenCalledWith(expectedRequest);
+ });
+
+ it("uses it for a scheduled renewal", async () => {
+ await service.renewCertificate({ certificateId: "cert-123", internal: true, ...mockActor });
+
+ expect(mockCertificateRequestService.createCertificateRequest).toHaveBeenCalledWith(expectedRequest);
+ });
+
+ it("still runs the certificate policy over what it replays", async () => {
+ await service.renewCertificate({ certificateId: "cert-123", ...mockActor });
+
+ expect(mockCertificatePolicyService.validateRequestAgainstPolicy).toHaveBeenCalledWith(
+ mockPolicy,
+ expect.objectContaining({ commonName: "asked-for.example.com" }),
+ expect.anything()
+ );
+ });
+ });
+
// The policy only sees a CA renewal as a CA request if basicConstraints are passed to it,
// so this covers denied policies and tightened path lengths on both renewal paths.
it("sends the certificate's CA constraints to policy validation on renewal", async () => {
@@ -2830,7 +2939,9 @@ describe("CertificateV3Service", () => {
altNames: null,
keyUsages: null,
extendedKeyUsages: null,
- customExtensions: null
+ customExtensions: null,
+ keyAlgorithm: null,
+ signatureAlgorithm: null
});
vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
@@ -2864,7 +2975,9 @@ describe("CertificateV3Service", () => {
altNames: null,
keyUsages: null,
extendedKeyUsages: null,
- customExtensions: null
+ customExtensions: null,
+ keyAlgorithm: null,
+ signatureAlgorithm: null
});
vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index 0daa3b5411..f80fcfb826 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -652,9 +652,9 @@ export const certificateV3ServiceFactory = ({
altNames: certificateRequestWithDefaults.altNames
? JSON.stringify(certificateRequestWithDefaults.altNames)
: null,
- keyUsages: convertKeyUsageArrayToLegacy(certificateRequestWithDefaults.keyUsages) || null,
+ keyUsages: convertKeyUsageArrayToLegacy(certificateRequestWithDefaults.keyUsages) || [],
extendedKeyUsages:
- convertExtendedKeyUsageArrayToLegacy(certificateRequestWithDefaults.extendedKeyUsages) || null,
+ convertExtendedKeyUsageArrayToLegacy(certificateRequestWithDefaults.extendedKeyUsages) || [],
notBefore: certificateRequestWithDefaults.notBefore || null,
notAfter: certificateRequestWithDefaults.notAfter || null,
keyAlgorithm: certificateRequestWithDefaults.keyAlgorithm || null,
@@ -865,12 +865,12 @@ export const certificateV3ServiceFactory = ({
tx,
profileId: profile.id,
applicationId,
- commonName: certificateRequest.commonName,
- altNames: certificateRequest.altNames,
- keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages),
- extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages),
- notBefore: certificateRequest.notBefore,
- notAfter: certificateRequest.notAfter,
+ commonName: certificateRequestWithDefaults.commonName,
+ altNames: certificateRequestWithDefaults.altNames,
+ keyUsages: convertKeyUsageArrayToLegacy(certificateRequestWithDefaults.keyUsages),
+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequestWithDefaults.extendedKeyUsages),
+ notBefore: certificateRequestWithDefaults.notBefore,
+ notAfter: certificateRequestWithDefaults.notAfter,
keyAlgorithm: effectiveKeyAlgorithm,
signatureAlgorithm: effectiveSignatureAlgorithm,
status: CertificateRequestStatus.ISSUED,
@@ -878,12 +878,12 @@ export const certificateV3ServiceFactory = ({
customExtensions: resolvedCustomExtensions,
ttl: resolvedTtl,
enrollmentType: EnrollmentType.API,
- organization: certificateRequest.organization,
- organizationalUnit: certificateRequest.organizationalUnit,
- country: certificateRequest.country,
- state: certificateRequest.state,
- locality: certificateRequest.locality,
- domainComponents: certificateRequest.domainComponents
+ organization: certificateRequestWithDefaults.organization,
+ organizationalUnit: certificateRequestWithDefaults.organizationalUnit,
+ country: certificateRequestWithDefaults.country,
+ state: certificateRequestWithDefaults.state,
+ locality: certificateRequestWithDefaults.locality,
+ domainComponents: certificateRequestWithDefaults.domainComponents
});
if (metadata && metadata.length > 0) {
@@ -1135,26 +1135,26 @@ export const certificateV3ServiceFactory = ({
caId: ca.id,
profileId: profile.id,
applicationId,
- commonName: certificateRequest.commonName,
- altNames: certificateRequest.altNames,
- keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages),
- extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages),
- notBefore: certificateRequest.notBefore,
- notAfter: certificateRequest.notAfter,
+ commonName: certificateRequestWithDefaults.commonName,
+ altNames: certificateRequestWithDefaults.altNames,
+ keyUsages: convertKeyUsageArrayToLegacy(certificateRequestWithDefaults.keyUsages),
+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequestWithDefaults.extendedKeyUsages),
+ notBefore: certificateRequestWithDefaults.notBefore,
+ notAfter: certificateRequestWithDefaults.notAfter,
keyAlgorithm: effectiveKeyAlgorithm,
signatureAlgorithm: effectiveSignatureAlgorithm,
status: CertificateRequestStatus.ISSUED,
certificateId: certResult.certificateId,
customExtensions: resolvedCustomExtensions,
- basicConstraints: certificateRequest.basicConstraints,
- ttl: certificateRequest.validity.ttl,
+ basicConstraints: certificateRequestWithDefaults.basicConstraints,
+ ttl: effectiveTtl,
enrollmentType: EnrollmentType.API,
- organization: certificateRequest.organization,
- organizationalUnit: certificateRequest.organizationalUnit,
- country: certificateRequest.country,
- state: certificateRequest.state,
- locality: certificateRequest.locality,
- domainComponents: certificateRequest.domainComponents
+ organization: certificateRequestWithDefaults.organization,
+ organizationalUnit: certificateRequestWithDefaults.organizationalUnit,
+ country: certificateRequestWithDefaults.country,
+ state: certificateRequestWithDefaults.state,
+ locality: certificateRequestWithDefaults.locality,
+ domainComponents: certificateRequestWithDefaults.domainComponents
});
if (metadata && metadata.length > 0) {
@@ -1433,8 +1433,13 @@ export const certificateV3ServiceFactory = ({
domainComponents: mappedCertificateRequest.domainComponents
? mappedCertificateRequest.domainComponents.join(",")
: null,
- keyUsages: convertKeyUsageArrayToLegacy(mappedCertificateRequest.keyUsages) || null,
- extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(mappedCertificateRequest.extendedKeyUsages) || null,
+ keyUsages: convertKeyUsageArrayToLegacy(mappedCertificateRequest.keyUsages) || [],
+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(mappedCertificateRequest.extendedKeyUsages) || [],
+ organization: mappedCertificateRequest.organization || null,
+ organizationalUnit: mappedCertificateRequest.organizationalUnit || null,
+ country: mappedCertificateRequest.country || null,
+ state: mappedCertificateRequest.state || null,
+ locality: mappedCertificateRequest.locality || null,
notBefore: notBefore || null,
notAfter: notAfter || null,
keyAlgorithm: extractedKeyAlgorithm || null,
@@ -1588,7 +1593,12 @@ export const certificateV3ServiceFactory = ({
basicConstraints,
customExtensions: resolvedCustomExtensions,
ttl: validity.ttl,
- enrollmentType
+ enrollmentType,
+ organization: mappedCertificateRequest.organization,
+ organizationalUnit: mappedCertificateRequest.organizationalUnit,
+ country: mappedCertificateRequest.country,
+ state: mappedCertificateRequest.state,
+ locality: mappedCertificateRequest.locality
});
const effectiveApiConfig = await resolveEffectiveApiConfig({
@@ -1790,12 +1800,11 @@ export const certificateV3ServiceFactory = ({
certificateRequest.notAfter = certificateOrder.notAfter;
}
} else {
- const rawRequest: TCertificateRequest = {
+ const orderedFields = {
commonName: certificateOrder.commonName,
keyUsages: certificateOrder.keyUsages,
extendedKeyUsages: certificateOrder.extendedKeyUsages,
subjectAlternativeNames: certificateOrder.altNames,
- validity: certificateOrder.validity,
notBefore: certificateOrder.notBefore,
notAfter: certificateOrder.notAfter,
signatureAlgorithm: certificateOrder.signatureAlgorithm,
@@ -1808,6 +1817,10 @@ export const certificateV3ServiceFactory = ({
locality: certificateOrder.locality,
customExtensions: certificateOrder.customExtensions
};
+ const rawRequest = {
+ validity: certificateOrder.validity,
+ ...Object.fromEntries(Object.entries(orderedFields).filter(([, value]) => value !== undefined))
+ } as TCertificateRequest;
certificateRequest = applyProfileDefaults(rawRequest, profile.defaults);
}
@@ -1833,6 +1846,11 @@ export const certificateV3ServiceFactory = ({
};
}
+ const orderEffectiveTtl = resolveEffectiveTtl({
+ requestTtl: certificateOrder.validity?.ttl,
+ profileDefaultTtlDays: profile.defaults?.ttlDays,
+ flowDefaultTtl: ""
+ });
const mappedCertificateRequest = mapEnumsForValidation(certificateRequest);
if (certificateOrder.csr) {
@@ -1882,7 +1900,7 @@ export const certificateV3ServiceFactory = ({
csr: certificateOrder.csr,
keyAlgorithm: certificateOrder.keyAlgorithm,
altNames: certificateOrder.altNames,
- ttl: certificateOrder.validity?.ttl,
+ ttl: orderEffectiveTtl,
notBefore: certificateOrder.notBefore,
notAfter: certificateOrder.notAfter,
organization: certificateRequest.organization,
@@ -1931,13 +1949,13 @@ export const certificateV3ServiceFactory = ({
altNames: certificateRequest.subjectAlternativeNames
? JSON.stringify(certificateRequest.subjectAlternativeNames)
: null,
- keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || null,
- extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || null,
+ keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
notBefore: certificateOrder.notBefore || null,
notAfter: certificateOrder.notAfter || null,
keyAlgorithm: extractedKeyAlgorithm || certificateRequest.keyAlgorithm || null,
signatureAlgorithm: extractedSignatureAlgorithm || certificateRequest.signatureAlgorithm || null,
- ttl: certificateOrder.validity?.ttl || null,
+ ttl: orderEffectiveTtl || null,
metadata: certificateOrder.template ? JSON.stringify({ template: certificateOrder.template }) : null,
organization: certificateRequest.organization || null,
organizationalUnit: certificateRequest.organizationalUnit || null,
@@ -2073,7 +2091,7 @@ export const certificateV3ServiceFactory = ({
csr: certificateOrder.csr,
keyAlgorithm: certificateOrder.keyAlgorithm,
altNames: certificateOrder.altNames,
- ttl: certificateOrder.validity?.ttl,
+ ttl: orderEffectiveTtl,
notBefore: certificateOrder.notBefore,
notAfter: certificateOrder.notAfter,
organization: certificateRequest.organization,
@@ -2110,17 +2128,18 @@ export const certificateV3ServiceFactory = ({
caId: ca.id,
profileId: profile.id,
applicationId,
- commonName: certificateOrder.commonName || "",
- keyUsages: convertKeyUsageArrayToLegacy(certificateOrder.keyUsages) || [],
- extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateOrder.extendedKeyUsages) || [],
- keyAlgorithm: certificateOrder.keyAlgorithm || "",
- signatureAlgorithm: certificateOrder.signatureAlgorithm || "",
- altNames: certificateOrder.altNames,
- notBefore: certificateOrder.notBefore,
- notAfter: certificateOrder.notAfter,
+ csr: certificateOrder.csr,
+ commonName: certificateRequest.commonName || "",
+ keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
+ keyAlgorithm: certificateRequest.keyAlgorithm || "",
+ signatureAlgorithm: certificateRequest.signatureAlgorithm || "",
+ altNames: certificateRequest.subjectAlternativeNames,
+ notBefore: certificateRequest.notBefore,
+ notAfter: certificateRequest.notAfter,
status: CertificateRequestStatus.PENDING,
customExtensions: orderCustomExtensions,
- ttl: certificateOrder.validity?.ttl,
+ ttl: orderEffectiveTtl,
enrollmentType: EnrollmentType.API,
organization: certificateRequest.organization,
organizationalUnit: certificateRequest.organizationalUnit,
@@ -2145,8 +2164,8 @@ export const certificateV3ServiceFactory = ({
profileId: profile.id,
caId: profile.caId || "",
caType,
- ttl: certificateOrder.validity?.ttl || "1y",
- signatureAlgorithm: certificateOrder.signatureAlgorithm || "",
+ ttl: orderEffectiveTtl || "1y",
+ signatureAlgorithm: certificateRequest.signatureAlgorithm || "",
keyAlgorithm: certificateRequest.keyAlgorithm || "",
commonName: certificateRequest.commonName || "",
altNames:
diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.ts
index 770c322687..c41e044b21 100644
--- a/backend/src/services/certificate/certificate-dal.ts
+++ b/backend/src/services/certificate/certificate-dal.ts
@@ -65,6 +65,8 @@ export type TOriginatingCertificateRequest = {
keyUsages: string[] | null;
extendedKeyUsages: string[] | null;
customExtensions: unknown;
+ keyAlgorithm: string | null;
+ signatureAlgorithm: string | null;
};
export const certificateDALFactory = (db: TDbClient) => {
@@ -777,7 +779,9 @@ export const certificateDALFactory = (db: TDbClient) => {
`${TableName.CertificateRequests}.altNames`,
`${TableName.CertificateRequests}.keyUsages`,
`${TableName.CertificateRequests}.extendedKeyUsages`,
- `${TableName.CertificateRequests}.customExtensions`
+ `${TableName.CertificateRequests}.customExtensions`,
+ `${TableName.CertificateRequests}.keyAlgorithm`,
+ `${TableName.CertificateRequests}.signatureAlgorithm`
)
.first()) as Partial<TOriginatingCertificateRequest> | undefined;
@@ -795,7 +799,9 @@ export const certificateDALFactory = (db: TDbClient) => {
altNames: row?.altNames ?? null,
keyUsages: row?.keyUsages ?? null,
extendedKeyUsages: row?.extendedKeyUsages ?? null,
- customExtensions: row?.customExtensions ?? null
+ customExtensions: row?.customExtensions ?? null,
+ keyAlgorithm: row?.keyAlgorithm ?? null,
+ signatureAlgorithm: row?.signatureAlgorithm ?? null
};
} catch (error) {
throw new DatabaseError({ error, name: "Get originating request by cert id" });
diff --git a/frontend/src/hooks/api/certificates/index.tsx b/frontend/src/hooks/api/certificates/index.tsx
index d1b495088a..1771f9cd1b 100644
--- a/frontend/src/hooks/api/certificates/index.tsx
+++ b/frontend/src/hooks/api/certificates/index.tsx
@@ -20,6 +20,7 @@ export {
useGetCertBundle,
useGetCertDashboardStats,
useGetCertificateById,
+ useGetCertificateRenewalPreview,
useGetCertificateRequest,
useGetCertPqcTrend,
useListCertificateRequests
diff --git a/frontend/src/hooks/api/certificates/queries.tsx b/frontend/src/hooks/api/certificates/queries.tsx
index 4d38364bb7..22ea6e813f 100644
--- a/frontend/src/hooks/api/certificates/queries.tsx
+++ b/frontend/src/hooks/api/certificates/queries.tsx
@@ -6,6 +6,7 @@ import {
TActivityTrendResponse,
TCertificate,
TCertificateByIdResponse,
+ TCertificateRenewalPreview,
TCertificateRequestDetails,
TDashboardStats,
TListCertificateRequestsParams,
@@ -18,6 +19,7 @@ export const certKeys = {
getCertBody: (serialNumber: string) => [{ serialNumber }, "certBody"],
getCertBundle: (serialNumber: string) => [{ serialNumber }, "certBundle"],
getCertificateById: (certificateId: string) => [{ certificateId }, "certificateById"],
+ getRenewalPreview: (certificateId: string) => [{ certificateId }, "certificateRenewalSource"],
getCertificateRequest: (requestId: string) => [{ requestId }, "certificateRequest"],
listCertificateRequests: (params: TListCertificateRequestsParams) => [
"certificateRequests",
@@ -87,6 +89,19 @@ export const useGetCertBundle = (serialNumber: string) => {
});
};
+export const useGetCertificateRenewalPreview = (certificateId: string, enabled = true) => {
+ return useQuery({
+ queryKey: certKeys.getRenewalPreview(certificateId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TCertificateRenewalPreview>(
+ `/api/v1/cert-manager/certificates/${certificateId}/renewal-preview`
+ );
+ return data;
+ },
+ enabled: enabled && Boolean(certificateId)
+ });
+};
+
export const useGetCertificateById = (certificateId: string) => {
return useQuery({
queryKey: certKeys.getCertificateById(certificateId),
diff --git a/frontend/src/hooks/api/certificates/types.ts b/frontend/src/hooks/api/certificates/types.ts
index 389c6282bf..09419ebcd5 100644
--- a/frontend/src/hooks/api/certificates/types.ts
+++ b/frontend/src/hooks/api/certificates/types.ts
@@ -379,3 +379,28 @@ export type TTriggerCertificateRequestValidationResponse = {
status: CertificateRequestStatus;
orderStatus?: string;
};
+
+export type TIssuerModifiedField = {
+ field: string;
+ requested: string;
+ issued: string;
+};
+
+export type TCertificateRenewalPreview = {
+ hasOriginatingRequest: boolean;
+ request: {
+ commonName?: string;
+ organization?: string;
+ organizationalUnit?: string;
+ country?: string;
+ state?: string;
+ locality?: string;
+ domainComponents?: string[];
+ altNames: { type: string; value: string }[];
+ keyUsages: string[];
+ extendedKeyUsages: string[];
+ keyAlgorithm?: string;
+ signatureAlgorithm?: string;
+ };
+ issuerModifiedFields: TIssuerModifiedField[];
+};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
index 3f947cd587..a502463af0 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate } from "@tanstack/react-router";
@@ -35,7 +35,10 @@ import {
CertificateIssuerKind,
CertificateRenewalKeySource
} from "@app/hooks/api/certificates/enums";
-import { useGetCertificateById } from "@app/hooks/api/certificates/queries";
+import {
+ useGetCertificateById,
+ useGetCertificateRenewalPreview
+} from "@app/hooks/api/certificates/queries";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { useWizardSteps } from "@app/hooks/useWizardSteps";
import { PkiDocsUrls } from "@app/pages/cert-manager/pki-docs-urls";
@@ -54,6 +57,7 @@ import {
} from "./certificateRenewalUtils";
import { isExternalTemplateCa, rowErrorsOf } from "./certificateUtils";
import { CertificateWizardSheet, WizardStep } from "./CertificateWizardSheet";
+import { IssuerModifiedHint, IssuerModifiedNotice } from "./IssuerModifiedNotice";
import { KeyUsageSection } from "./KeyUsageSection";
import { RequestCustomExtensionsField } from "./RequestCustomExtensionsField";
import { SubjectAltNamesField } from "./SubjectAltNamesField";
@@ -178,6 +182,23 @@ const STEP_META: Record<RenewalStepKey, WizardStep> = {
}
};
+const REPLAYED_STEP_COPY: Partial<Record<RenewalStepKey, Partial<WizardStep>>> = {
+ subject: {
+ subtitle: "These are copied from the original request. Change only what should differ.",
+ rightDescription:
+ "Subject attributes and alternative names identify the certificate. They start as a copy of the request that produced it, so anything the authority added on its own is called out below rather than repeated here."
+ },
+ options: {
+ rightDescription:
+ "Every value here starts as a copy of the request that produced this certificate, including any profile defaults it recorded, and is validated against the profile's policy at issuance."
+ },
+ extensions: {
+ subtitle: "These are copied from the original request. Change only what should differ.",
+ rightDescription:
+ "Custom extensions start as a copy of the request that produced this certificate, and the profile's policy still constrains which object identifiers are permitted and what values they may take."
+ }
+};
+
const EXTERNAL_TEMPLATE_OPTIONS_STEP: WizardStep = {
...STEP_META.options,
shortDescription: "Key algorithm",
@@ -210,6 +231,17 @@ type Props = {
) => void;
};
+const SUBJECT_ISSUER_FIELDS = new Set([
+ "commonName",
+ "organization",
+ "organizationalUnit",
+ "country",
+ "state",
+ "locality",
+ "domainComponents",
+ "altNames"
+]);
+
export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpToggle }: Props) => {
const { currentProject } = useProject();
const { currentOrg } = useOrganization();
@@ -223,6 +255,15 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
);
const certificate = certificateData?.certificate;
+ const { data: renewalPreview, isPending: isRenewalPreviewPending } =
+ useGetCertificateRenewalPreview(isOpen && certificateId ? certificateId : "");
+ const hasOriginatingRequest = renewalPreview?.hasOriginatingRequest ?? false;
+ const issuerModifiedFields = renewalPreview?.issuerModifiedFields ?? [];
+ const issuerModifiedByField = useMemo(
+ () => new Map(issuerModifiedFields.map((entry) => [entry.field, entry])),
+ [issuerModifiedFields]
+ );
+
const { data: profile } = useGetCertificateProfileById({
profileId: certificate?.profileId ?? ""
});
@@ -437,25 +478,39 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
const steps = useMemo(
() =>
- stepKeys.map((key) =>
- key === "options" && isExternalTemplateProfile
- ? EXTERNAL_TEMPLATE_OPTIONS_STEP
- : STEP_META[key]
- ),
- [stepKeys, isExternalTemplateProfile]
+ stepKeys.map((key) => {
+ const meta =
+ key === "options" && isExternalTemplateProfile
+ ? EXTERNAL_TEMPLATE_OPTIONS_STEP
+ : STEP_META[key];
+ return hasOriginatingRequest ? { ...meta, ...(REPLAYED_STEP_COPY[key] ?? {}) } : meta;
+ }),
+ [stepKeys, isExternalTemplateProfile, hasOriginatingRequest]
);
+ const subjectIssuerChanges = useMemo(
+ () => issuerModifiedFields.filter((entry) => SUBJECT_ISSUER_FIELDS.has(entry.field)),
+ [issuerModifiedFields]
+ );
+
+ const [isSeeded, setIsSeeded] = useState(false);
const seededCertificateIdRef = useRef<string | null>(null);
useEffect(() => {
if (!isOpen) {
seededCertificateIdRef.current = null;
+ setIsSeeded(false);
return;
}
- if (!certificate || !isPolicyResolved || seededCertificateIdRef.current === certificate.id)
+ if (
+ !certificate ||
+ !isPolicyResolved ||
+ isRenewalPreviewPending ||
+ seededCertificateIdRef.current === certificate.id
+ )
return;
seededCertificateIdRef.current = certificate.id;
- const renewalDefaults = buildRenewalFormDefaults(certificate, constraints);
+ const renewalDefaults = buildRenewalFormDefaults(certificate, constraints, renewalPreview);
// Seed the rows the policy requires so they are visible as fields from the start.
const seeded = withRequiredRows(
buildPolicyRules(policyData),
@@ -468,7 +523,17 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
subjectAltNames: seeded.subjectAltNames
});
setStep(0);
- }, [isOpen, certificate, isPolicyResolved, constraints, policyData, reset]);
+ setIsSeeded(true);
+ }, [
+ isOpen,
+ certificate,
+ isPolicyResolved,
+ isRenewalPreviewPending,
+ renewalPreview,
+ constraints,
+ policyData,
+ reset
+ ]);
const closeWizard = () => {
handlePopUpToggle("renewCertificate", false);
@@ -570,8 +635,8 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
onBack={goBack}
onContinue={goNext}
isSubmitting={isSubmitting}
- isSubmitDisabled={!certificate}
- isContinueDisabled={!certificate}
+ isSubmitDisabled={!certificate || !isSeeded}
+ isContinueDisabled={!certificate || !isSeeded}
>
{currentStepKey === "setup" && (
<Controller
@@ -681,6 +746,7 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
revealPolicyErrors={policy.isRevealed("subjectAltNames")}
/>
)}
+ <IssuerModifiedNotice fields={subjectIssuerChanges} />
</div>
)}
@@ -728,23 +794,33 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
: "Select key algorithm"
}
/>
+ {!isExternalTemplateProfile && (
+ <IssuerModifiedHint field={issuerModifiedByField.get("signatureAlgorithm")} />
+ )}
+ <IssuerModifiedHint field={issuerModifiedByField.get("keyAlgorithm")} />
{!isExternalTemplateProfile && (
<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}
- />
+ <div>
+ <KeyUsageSection
+ control={control}
+ title="Key Usages"
+ namePrefix="keyUsages"
+ options={selectableKeyUsages}
+ requiredUsages={constraints.requiredKeyUsages}
+ />
+ <IssuerModifiedHint field={issuerModifiedByField.get("keyUsages")} />
+ </div>
+ <div>
+ <KeyUsageSection
+ control={control}
+ title="Extended Key Usages"
+ namePrefix="extendedKeyUsages"
+ options={selectableExtendedKeyUsages}
+ requiredUsages={constraints.requiredExtendedKeyUsages}
+ />
+ <IssuerModifiedHint field={issuerModifiedByField.get("extendedKeyUsages")} />
+ </div>
{constraints.templateAllowsCA && (
<BasicConstraintsField
control={control}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts
index 31516a2586..e51973e836 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts
@@ -18,12 +18,12 @@ export const getCertSourceLabel = (source: TCertificateSource): string => {
export const RENEWAL_UNAVAILABLE_NO_PROFILE =
"Renewal is unavailable because the certificate profile this certificate was issued from no longer exists.";
-type TCertificateRenewalSource = {
+type TCertificateRenewalPreview = {
profileId?: string | null;
source?: string | null;
};
-export const isManagedCertificate = (certificate: TCertificateRenewalSource) =>
+export const isManagedCertificate = (certificate: TCertificateRenewalPreview) =>
(certificate.source ?? CertSource.Issued) === CertSource.Issued;
type TCertificateStatusSource = {
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/IssuerModifiedNotice.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/IssuerModifiedNotice.tsx
new file mode 100644
index 0000000000..a44b033fa7
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/IssuerModifiedNotice.tsx
@@ -0,0 +1,101 @@
+import { faCircleInfo } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+
+import { TIssuerModifiedField } from "@app/hooks/api/certificates/types";
+import {
+ CertExtendedKeyUsageType,
+ CertKeyUsageType,
+ formatExtendedKeyUsage,
+ formatKeyUsage
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+
+type Props = {
+ fields: TIssuerModifiedField[];
+};
+
+export const ISSUER_MODIFIED_LABELS: Record<string, 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",
+ keyAlgorithm: "Key algorithm",
+ signatureAlgorithm: "Signature algorithm"
+};
+
+const FORMATTERS: Record<string, (value: string) => string> = {
+ keyUsages: (value) => formatKeyUsage(value as CertKeyUsageType),
+ extendedKeyUsages: (value) => formatExtendedKeyUsage(value as CertExtendedKeyUsageType)
+};
+
+export const formatIssuerValue = (field: TIssuerModifiedField, value: string) => {
+ const format = FORMATTERS[field.field];
+ if (!format) return value;
+ return value
+ .split(",")
+ .map((entry) => entry.trim())
+ .filter(Boolean)
+ .map(format)
+ .join(", ");
+};
+
+export const describeIssuerChange = (field: TIssuerModifiedField) => {
+ const label = ISSUER_MODIFIED_LABELS[field.field] ?? field.field;
+ const issued = formatIssuerValue(field, field.issued);
+ if (!issued) return `${label}: omitted`;
+ return `${label}: ${issued}`;
+};
+
+export const IssuerModifiedNotice = ({ fields }: Props) => {
+ if (fields.length === 0) return null;
+
+ return (
+ <div className="rounded-md border border-mineshaft-600 bg-mineshaft-800 p-3">
+ <div className="flex items-start gap-2">
+ <FontAwesomeIcon icon={faCircleInfo} className="mt-0.5 text-yellow-500" />
+ <div className="space-y-1 text-sm">
+ <p className="text-mineshaft-100">
+ The certificate authority set these values at last issuance.
+ </p>
+ {fields.map((field) => (
+ <p key={field.field} className="text-mineshaft-300">
+ {describeIssuerChange(field)}
+ </p>
+ ))}
+ <p className="text-mineshaft-400">
+ Edit a field above to request a different value, or renew unchanged to let the authority
+ set it again.
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+const describeIssuerHint = (requested: string, issued: string) => {
+ if (!issued) return `The certificate authority omitted ${requested} at last issuance.`;
+ return `The certificate authority set ${issued} at last issuance.`;
+};
+
+type HintProps = {
+ field?: TIssuerModifiedField;
+};
+
+export const IssuerModifiedHint = ({ field }: HintProps) => {
+ if (!field) return null;
+
+ const requested = formatIssuerValue(field, field.requested);
+ const issued = formatIssuerValue(field, field.issued);
+
+ return (
+ <p className="mt-1 text-xs text-yellow-600">
+ <FontAwesomeIcon icon={faCircleInfo} className="mr-1" />
+ {describeIssuerHint(requested, issued)}
+ </p>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.test.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.test.ts
new file mode 100644
index 0000000000..9b1b3aaf79
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+
+import { CertSubjectAlternativeNameType } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+
+import { buildRenewalFormDefaults } from "./certificateRenewalUtils";
+
+const certificate = {
+ id: "cert-1",
+ commonName: "ca-rewrote.example.com",
+ altNames: "ca-added.example.com",
+ subject: { organization: "Issuer Corp", country: "US" },
+ keyUsages: ["digitalSignature", "keyEncipherment"],
+ extendedKeyUsages: ["serverAuth"],
+ keyAlgorithm: "RSA_2048",
+ signatureAlgorithm: "RSA-SHA384",
+ notBefore: "2026-01-01T00:00:00Z",
+ notAfter: "2026-01-31T00:00:00Z",
+ customExtensions: []
+} as never;
+
+const constraints = {
+ allowedSanTypes: [CertSubjectAlternativeNameType.DNS_NAME],
+ shouldShowSubjectSection: true,
+ shouldShowSanSection: true,
+ templateAllowsCA: false
+} as never;
+
+const renewalPreview = {
+ hasOriginatingRequest: true,
+ request: {
+ commonName: "asked-for.example.com",
+ altNames: [],
+ keyUsages: ["digital_signature"],
+ extendedKeyUsages: ["client_auth"],
+ keyAlgorithm: "RSA_2048",
+ signatureAlgorithm: "RSA-SHA256"
+ },
+ issuerModifiedFields: []
+};
+
+describe("buildRenewalFormDefaults", () => {
+ it("seeds from the originating request, not from what the authority issued", () => {
+ const defaults = buildRenewalFormDefaults(certificate, constraints, renewalPreview);
+
+ expect(defaults.subjectAttributes?.map((attr) => attr.value)).toEqual([
+ "asked-for.example.com"
+ ]);
+ expect(defaults.subjectAltNames).toEqual([]);
+ expect(defaults.signatureAlgorithm).toBe("RSA-SHA256");
+ expect(defaults.keyUsages).toEqual({ digital_signature: true });
+ expect(defaults.extendedKeyUsages).toEqual({ client_auth: true });
+ });
+
+ it("falls back to the certificate when no request lies behind it, for imports and discovery", () => {
+ const defaults = buildRenewalFormDefaults(certificate, constraints, {
+ ...renewalPreview,
+ hasOriginatingRequest: false
+ });
+
+ expect(defaults.subjectAttributes?.map((attr) => attr.value)).toContain(
+ "ca-rewrote.example.com"
+ );
+ expect(defaults.subjectAltNames?.map((san) => san.value)).toEqual(["ca-added.example.com"]);
+ expect(defaults.signatureAlgorithm).toBe("RSA-SHA384");
+ });
+});
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
index 7408339bf0..39f232be88 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
@@ -3,7 +3,11 @@ import {
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 {
+ TCertificate,
+ TCertificateRenewalPreview,
+ TRenewCertificateAttributes
+} from "@app/hooks/api/certificates/types";
import {
CertExtendedKeyUsageType,
CertKeyUsageType,
@@ -106,27 +110,65 @@ export const unionUsageOptions = <T extends { value: string }>(
return [...allowed, ...all.filter((o) => missing.includes(o.value))];
};
+const pickKnown = (known: Set<string>, value?: string | null) =>
+ known.has(value ?? "") ? (value as string) : "";
+
+const buildSeedSubjectAttributes = (request: TCertificateRenewalPreview["request"]) => {
+ const attributes: { type: CertSubjectAttributeType; value: string }[] = [];
+
+ SUBJECT_ATTR_MAP.forEach(({ attrType, requestKey }) => {
+ const value = request[requestKey as keyof typeof request];
+ if (typeof value === "string" && value) attributes.push({ type: attrType, value });
+ });
+
+ request.domainComponents?.forEach((dc) => {
+ if (dc) attributes.push({ type: CertSubjectAttributeType.DOMAIN_COMPONENT, value: dc });
+ });
+
+ return attributes;
+};
+
export const buildRenewalFormDefaults = (
cert: TCertificate,
- constraints: TemplateConstraints
+ constraints: TemplateConstraints,
+ renewalPreview?: TCertificateRenewalPreview
): RenewalFormData => ({
keySource: CertificateRenewalKeySource.New,
csr: "",
ttl: deriveTtlFromCertificate(cert),
- subjectAttributes: buildSubjectAttributes(cert),
- subjectAltNames: parseCertificateSans(cert, constraints.allowedSanTypes),
+ subjectAttributes: renewalPreview?.hasOriginatingRequest
+ ? buildSeedSubjectAttributes(renewalPreview.request)
+ : buildSubjectAttributes(cert),
+ subjectAltNames: renewalPreview?.hasOriginatingRequest
+ ? renewalPreview.request.altNames.map(({ value }) => ({
+ type: resolveSanType(value, constraints.allowedSanTypes),
+ value
+ }))
+ : parseCertificateSans(cert, constraints.allowedSanTypes),
basicConstraints: {
isCA: Boolean(cert.basicConstraints?.isCA),
pathLength: cert.basicConstraints?.pathLength ?? null
},
- 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),
+ signatureAlgorithm: pickKnown(
+ KNOWN_SIGNATURE_ALGORITHMS,
+ renewalPreview?.hasOriginatingRequest
+ ? renewalPreview.request.signatureAlgorithm
+ : cert.signatureAlgorithm
+ ),
+ keyAlgorithm: pickKnown(
+ KNOWN_KEY_ALGORITHMS,
+ renewalPreview?.hasOriginatingRequest ? renewalPreview.request.keyAlgorithm : cert.keyAlgorithm
+ ),
+ keyUsages: toUsageFormKeys(
+ renewalPreview?.hasOriginatingRequest ? renewalPreview.request.keyUsages : cert.keyUsages,
+ KEY_USAGE_BY_NAME
+ ),
+ extendedKeyUsages: toUsageFormKeys(
+ renewalPreview?.hasOriginatingRequest
+ ? renewalPreview.request.extendedKeyUsages
+ : cert.extendedKeyUsages,
+ EXTENDED_KEY_USAGE_BY_NAME
+ ),
customExtensions: (cert.customExtensions ?? [])
.filter(
(extension) =>