Skip to content

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

Fixes and improvements on PKI CAs

Carlos Monastyrski4cdba8e97740
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index b89137ec6e..b5d4e661ba 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -324,6 +324,7 @@ export enum EventType {
SIGN_INTERMEDIATE = "sign-intermediate",
IMPORT_CA_CERT = "import-certificate-authority-cert",
GET_CA_CRLS = "get-certificate-authority-crls",
+ GENERATE_CA_CERTIFICATE = "generate-ca-certificate",
ISSUE_CERT = "issue-cert",
IMPORT_CERT = "import-cert",
SIGN_CERT = "sign-cert",
@@ -2318,6 +2319,16 @@ interface GetCaCrls {
};
}
+interface GenerateCaCertificate {
+ type: EventType.GENERATE_CA_CERTIFICATE;
+ metadata: {
+ caId: string;
+ dn: string;
+ serialNumber: string;
+ parentCaId?: string;
+ };
+}
+
interface IssueCert {
type: EventType.ISSUE_CERT;
metadata: {
@@ -4527,6 +4538,7 @@ export type Event =
| SignIntermediate
| ImportCaCert
| GetCaCrls
+ | GenerateCaCertificate
| IssueCert
| ImportCert
| SignCert
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 81b0c0de2a..ff03ec9613 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -1913,6 +1913,17 @@ export const CERTIFICATE_AUTHORITIES = {
serialNumber: "The serial number of the CA certificate.",
version: "The version of the CA certificate. The version is incremented for each CA renewal operation."
},
+ GENERATE_CA_CERTIFICATE: {
+ caId: "The ID of the CA to generate a certificate for.",
+ parentCaId: "The ID of the parent CA to sign the intermediate certificate with. Not required for root CAs.",
+ notBefore: "The date and time when the CA becomes valid in YYYY-MM-DDTHH:mm:ss.sssZ format.",
+ notAfter: "The date and time when the CA expires in YYYY-MM-DDTHH:mm:ss.sssZ format.",
+ maxPathLength:
+ "The maximum number of intermediate CAs that may follow this CA in the certificate / CA chain. A maxPathLength of -1 implies no path limit on the chain.",
+ certificate: "The generated CA certificate.",
+ certificateChain: "The certificate chain of the CA.",
+ serialNumber: "The serial number of the CA certificate."
+ },
SIGN_INTERMEDIATE: {
caId: "The ID of the CA to sign the intermediate certificate with.",
csr: "The pem-encoded CSR to sign with the CA.",
diff --git a/backend/src/server/routes/v1/certificate-authority-routers/internal-certificate-authority-router.ts b/backend/src/server/routes/v1/certificate-authority-routers/internal-certificate-authority-router.ts
index 73e3bde54a..648a869bbd 100644
--- a/backend/src/server/routes/v1/certificate-authority-routers/internal-certificate-authority-router.ts
+++ b/backend/src/server/routes/v1/certificate-authority-routers/internal-certificate-authority-router.ts
@@ -128,6 +128,113 @@ export const registerInternalCertificateAuthorityRouter = async (server: Fastify
}
});
+ server.route({
+ method: "POST",
+ url: "/:caId/certificate",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.PkiCertificateAuthorities],
+ description: "Generate certificate for a Certificate Authority",
+ params: z.object({
+ caId: z.string().trim().describe(CERTIFICATE_AUTHORITIES.GENERATE_CA_CERTIFICATE.caId)
+ }),
+ body: z.object({
+ notBefore: validateCaDateField.describe(CERTIFICATE_AUTHORITIES.GENERATE_CA_CERTIFICATE.notBefore),
+ notAfter: validateCaDateField.describe(CERTIFICATE_AUTHORITIES.GENERATE_CA_CERTIFICATE.notAfter),
+ maxPathLength: z
+ .number()
+ .min(-1)
+ .default(-1)
+ .describe(CERTIFICATE_AUTHORITIES.GENERATE_CA_CERTIFICATE.maxPathLength),
+ parentCaId: z.string().trim().optional().describe("Parent CA ID for intermediate certificate generation")
+ }),
+ response: {
+ 200: z.object({
+ certificate: z.string().trim().describe(CERTIFICATE_AUTHORITIES.GENERATE_CA_CERTIFICATE.certificate),
+ certificateChain: z
+ .string()
+ .trim()
+ .describe(CERTIFICATE_AUTHORITIES.GENERATE_CA_CERTIFICATE.certificateChain),
+ serialNumber: z.string().trim().describe(CERTIFICATE_AUTHORITIES.GENERATE_CA_CERTIFICATE.serialNumber)
+ })
+ }
+ },
+ handler: async (req) => {
+ const { parentCaId, ...certificateData } = req.body;
+
+ let certificate: string;
+ let certificateChain: string;
+ let serialNumber: string;
+ let ca: { id: string; dn: string; projectId: string };
+
+ if (parentCaId) {
+ const intermediateCert = await server.services.internalCertificateAuthority.generateIntermediateCaCertificate({
+ caId: req.params.caId,
+ parentCaId,
+ notBefore: certificateData.notBefore,
+ notAfter: certificateData.notAfter,
+ maxPathLength: certificateData.maxPathLength,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ certificate = intermediateCert.certificate;
+ certificateChain = intermediateCert.certificateChain;
+ serialNumber = intermediateCert.serialNumber;
+
+ ca = await server.services.internalCertificateAuthority.getCaById({
+ caId: req.params.caId,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+ } else {
+ const rootCert = await server.services.internalCertificateAuthority.generateRootCaCertificate({
+ caId: req.params.caId,
+ notBefore: certificateData.notBefore,
+ notAfter: certificateData.notAfter,
+ maxPathLength: certificateData.maxPathLength,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ certificate = rootCert.certificate;
+ certificateChain = rootCert.certificateChain;
+ serialNumber = rootCert.serialNumber;
+ ca = rootCert.ca;
+ }
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: ca.projectId,
+ event: {
+ type: EventType.GENERATE_CA_CERTIFICATE,
+ metadata: {
+ caId: ca.id,
+ dn: ca.dn,
+ serialNumber,
+ ...(parentCaId && { parentCaId })
+ }
+ }
+ });
+
+ return {
+ certificate,
+ certificateChain,
+ serialNumber
+ };
+ }
+ });
+
server.route({
method: "GET",
url: "/:caId/ca-certificates",
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
index 91b7727ec3..f47524e7f8 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
@@ -19,6 +19,7 @@ import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
import { alphaNumericNanoId } from "@app/lib/nanoid";
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -60,6 +61,7 @@ import { TInternalCertificateAuthorityDALFactory } from "./internal-certificate-
import {
TCreateCaDTO,
TDeleteCaDTO,
+ TGenerateRootCaCertificateDTO,
TGetCaCertDTO,
TGetCaCertificateTemplatesDTO,
TGetCaCertsDTO,
@@ -194,12 +196,16 @@ export const internalCertificateAuthorityServiceFactory = ({
const keys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
const newCa = await certificateAuthorityDAL.transaction(async (tx) => {
- const notBeforeDate = notBefore ? new Date(notBefore) : new Date();
+ let notBeforeDate: Date | undefined;
+ if (notAfter) {
+ notBeforeDate = notBefore ? new Date(notBefore) : new Date();
+ }
// if undefined, set [notAfterDate] to 10 years from now
- const notAfterDate = notAfter
- ? new Date(notAfter)
- : new Date(new Date().setFullYear(new Date().getFullYear() + 10));
+ let notAfterDate: Date | undefined;
+ if (notAfter) {
+ notAfterDate = new Date(new Date().setFullYear(new Date().getFullYear() + 10));
+ }
const serialNumber = createSerialNumber();
@@ -207,7 +213,7 @@ export const internalCertificateAuthorityServiceFactory = ({
{
projectId,
name: name || slugify(`${(friendlyName || dn).slice(0, 16)}-${alphaNumericNanoId(8)}`),
- status: type === InternalCaType.ROOT ? CaStatus.ACTIVE : CaStatus.PENDING_CERTIFICATE,
+ status: notAfter && type === InternalCaType.ROOT ? CaStatus.ACTIVE : CaStatus.PENDING_CERTIFICATE,
enableDirectIssuance: false
},
tx
@@ -228,9 +234,11 @@ export const internalCertificateAuthorityServiceFactory = ({
keyAlgorithm,
...(type === InternalCaType.ROOT && {
maxPathLength,
- notBefore: notBeforeDate,
- notAfter: notAfterDate,
- serialNumber
+ ...(notAfter && {
+ notBefore: notBeforeDate,
+ notAfter: notAfterDate,
+ serialNumber
+ })
})
},
tx
@@ -263,7 +271,7 @@ export const internalCertificateAuthorityServiceFactory = ({
tx
);
- if (type === InternalCaType.ROOT) {
+ if (type === InternalCaType.ROOT && notAfter) {
// note: create self-signed cert only applicable for root CA
const cert = await x509.X509CertificateGenerator.createSelfSigned({
name: dn,
@@ -1174,6 +1182,134 @@ export const internalCertificateAuthorityServiceFactory = ({
return { ca: expandInternalCa(ca) };
};
+ const generateIntermediateCaCertificate = async ({
+ caId,
+ parentCaId,
+ notBefore,
+ notAfter,
+ maxPathLength,
+ actorId,
+ actorAuthMethod,
+ actor,
+ actorOrgId,
+ tx
+ }: {
+ caId: string;
+ parentCaId: string;
+ notBefore: string;
+ notAfter: string;
+ maxPathLength?: number;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actor: ActorType;
+ actorOrgId: string | undefined;
+ tx?: Knex.Transaction;
+ }) => {
+ const intermediateCa = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId, tx);
+ if (!intermediateCa.internalCa) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
+
+ const parentCa = await certificateAuthorityDAL.findByIdWithAssociatedCa(parentCaId, tx);
+ if (!parentCa.internalCa) throw new NotFoundError({ message: `Parent CA with ID '${parentCaId}' not found` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: intermediateCa.projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateAuthorityActions.Create,
+ subject(ProjectPermissionSub.CertificateAuthorities, { name: intermediateCa.name })
+ );
+
+ const caSecret = await certificateAuthoritySecretDAL.findOne(
+ {
+ caId: intermediateCa.id
+ },
+ tx
+ );
+
+ if (!caSecret) throw new NotFoundError({ message: "Failed to find CA secret" });
+
+ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
+ projectId: intermediateCa.projectId,
+ projectDAL,
+ kmsService
+ });
+
+ const kmsDecryptor = await kmsService.decryptWithKmsKey({
+ kmsId: certificateManagerKmsId
+ });
+
+ const caPrivateKey = await kmsDecryptor({
+ cipherTextBlob: caSecret.encryptedPrivateKey
+ });
+
+ const alg = keyAlgorithmToAlgCfg(intermediateCa.internalCa.keyAlgorithm as CertKeyAlgorithm);
+
+ const skObj = crypto.nativeCrypto.createPrivateKey({ key: caPrivateKey, format: "der", type: "pkcs8" });
+ const pkObj = crypto.nativeCrypto.createPublicKey(skObj);
+ const publicKeyBuffer = pkObj.export({ format: "der", type: "spki" });
+
+ const privateKey = await crypto.nativeCrypto.subtle.importKey("pkcs8", caPrivateKey, alg, true, ["sign"]);
+ const publicKey = await crypto.nativeCrypto.subtle.importKey("spki", publicKeyBuffer, alg, true, ["verify"]);
+
+ const keys = {
+ privateKey,
+ publicKey
+ };
+
+ const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
+ name: intermediateCa.internalCa.dn,
+ keys,
+ signingAlgorithm: alg,
+ extensions: [
+ new x509.BasicConstraintsExtension(true, maxPathLength === -1 ? undefined : maxPathLength, true),
+ new x509.KeyUsagesExtension(
+ x509.KeyUsageFlags.keyCertSign |
+ x509.KeyUsageFlags.cRLSign |
+ x509.KeyUsageFlags.digitalSignature |
+ x509.KeyUsageFlags.keyEncipherment,
+ true
+ ),
+ await x509.SubjectKeyIdentifierExtension.create(keys.publicKey)
+ ]
+ });
+
+ const csrPem = csrObj.toString("pem");
+
+ const signedResult = await signIntermediate({
+ caId: parentCaId,
+ csr: csrPem,
+ notBefore,
+ notAfter,
+ maxPathLength: maxPathLength ?? -1,
+ actorId,
+ actorAuthMethod,
+ actor,
+ actorOrgId: actorOrgId!
+ });
+
+ await importCertToCa({
+ caId,
+ certificate: signedResult.certificate,
+ certificateChain: signedResult.certificateChain,
+ actorId,
+ actorAuthMethod,
+ actor,
+ actorOrgId: actorOrgId!
+ });
+
+ return {
+ certificate: signedResult.certificate,
+ certificateChain: signedResult.certificateChain,
+ serialNumber: signedResult.serialNumber
+ };
+ };
+
/**
* Return new leaf certificate issued by CA with id [caId] and private key.
* Note: private key and CSR are generated within Infisical.
@@ -2007,6 +2143,150 @@ export const internalCertificateAuthorityServiceFactory = ({
};
};
+ const generateRootCaCertificate = async ({
+ caId,
+ notBefore,
+ notAfter,
+ maxPathLength,
+ actorId,
+ actorAuthMethod,
+ actor,
+ actorOrgId
+ }: TGenerateRootCaCertificateDTO) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca?.internalCa) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
+ if (ca.internalCa.type !== InternalCaType.ROOT) {
+ throw new BadRequestError({ message: "Certificate generation is only available for root CAs" });
+ }
+ if (ca.status === CaStatus.ACTIVE) {
+ throw new BadRequestError({ message: "CA already has an active certificate" });
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: ca.projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateAuthorityActions.Edit,
+ subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })
+ );
+
+ return certificateAuthorityDAL.transaction(async (tx) => {
+ const notBeforeDate = new Date(notBefore);
+ const notAfterDate = new Date(notAfter);
+ const serialNumber = createSerialNumber();
+
+ await internalCertificateAuthorityDAL.updateById(
+ ca.internalCa!.id,
+ {
+ notBefore: notBeforeDate,
+ notAfter: notAfterDate,
+ serialNumber,
+ ...(maxPathLength !== undefined && { maxPathLength })
+ },
+ tx
+ );
+
+ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
+ projectId: ca.projectId,
+ projectDAL,
+ kmsService
+ });
+ const kmsEncryptor = await kmsService.encryptWithKmsKey({
+ kmsId: certificateManagerKmsId
+ });
+
+ const caSecret = await certificateAuthoritySecretDAL.findOne({ caId });
+ if (!caSecret) throw new NotFoundError({ message: "CA secret not found" });
+
+ const kmsDecryptor = await kmsService.decryptWithKmsKey({
+ kmsId: certificateManagerKmsId
+ });
+ const privateKeyBlob = await kmsDecryptor({ cipherTextBlob: caSecret.encryptedPrivateKey });
+ if (!ca.internalCa) throw new BadRequestError({ message: "CA internal configuration not found" });
+
+ const alg = keyAlgorithmToAlgCfg(ca.internalCa.keyAlgorithm as CertKeyAlgorithm);
+
+ const actualPrivateKey = await crypto.nativeCrypto.subtle.importKey("pkcs8", privateKeyBlob, alg, true, ["sign"]);
+
+ const skObj = crypto.nativeCrypto.createPrivateKey({ key: privateKeyBlob, format: "der", type: "pkcs8" });
+ const pkObj = crypto.nativeCrypto.createPublicKey(skObj);
+ const publicKeyBuffer = pkObj.export({ format: "der", type: "spki" });
+ const actualPublicKey = await crypto.nativeCrypto.subtle.importKey("spki", publicKeyBuffer, alg, true, [
+ "verify"
+ ]);
+
+ const cert = await x509.X509CertificateGenerator.createSelfSigned({
+ name: ca.internalCa.dn,
+ serialNumber,
+ notBefore: notBeforeDate,
+ notAfter: notAfterDate,
+ signingAlgorithm: alg,
+ keys: { privateKey: actualPrivateKey, publicKey: actualPublicKey },
+ extensions: [
+ new x509.BasicConstraintsExtension(
+ true,
+ maxPathLength === -1 || maxPathLength === null || maxPathLength === undefined
+ ? undefined
+ : Number(maxPathLength),
+ true
+ ),
+ // eslint-disable-next-line no-bitwise
+ new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true),
+ await x509.SubjectKeyIdentifierExtension.create(actualPublicKey)
+ ]
+ });
+
+ const { cipherTextBlob: encryptedCertificate } = await kmsEncryptor({
+ plainText: Buffer.from(new Uint8Array(cert.rawData))
+ });
+
+ const { cipherTextBlob: encryptedCertificateChain } = await kmsEncryptor({
+ plainText: Buffer.alloc(0)
+ });
+
+ const caCert = await certificateAuthorityCertDAL.create(
+ {
+ caId: ca.id,
+ encryptedCertificate,
+ encryptedCertificateChain,
+ version: 1,
+ caSecretId: caSecret.id
+ },
+ tx
+ );
+
+ await internalCertificateAuthorityDAL.updateById(
+ ca.internalCa.id,
+ {
+ activeCaCertId: caCert.id
+ },
+ tx
+ );
+
+ await certificateAuthorityDAL.updateById(
+ ca.id,
+ {
+ status: CaStatus.ACTIVE
+ },
+ tx
+ );
+
+ const updatedCa = await certificateAuthorityDAL.findByIdWithAssociatedCa(ca.id, tx);
+
+ return {
+ certificate: cert.toString("pem"),
+ certificateChain: "",
+ serialNumber,
+ ca: expandInternalCa(updatedCa)
+ };
+ });
+ };
+
return {
createCa,
getCaById,
@@ -2019,8 +2299,10 @@ export const internalCertificateAuthorityServiceFactory = ({
getCaCertById,
signIntermediate,
importCertToCa,
+ generateIntermediateCaCertificate,
issueCertFromCa,
signCertFromCa,
- getCaCertificateTemplates
+ getCaCertificateTemplates,
+ generateRootCaCertificate
};
};
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
index c13f85aa5f..bf5ca4ac0e 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
@@ -89,6 +89,13 @@ export type TDeleteCaDTO = {
caId: string;
} & Omit<TProjectPermission, "projectId">;
+export type TGenerateRootCaCertificateDTO = {
+ caId: string;
+ notBefore: string;
+ notAfter: string;
+ maxPathLength?: number | null;
+} & Omit<TProjectPermission, "projectId">;
+
export type TGetCaCsrDTO = {
caId: string;
} & Omit<TProjectPermission, "projectId">;
diff --git a/backend/src/services/certificate-profile/certificate-profile-dal.ts b/backend/src/services/certificate-profile/certificate-profile-dal.ts
index 3a8f99f1ae..33caf3ef3a 100644
--- a/backend/src/services/certificate-profile/certificate-profile-dal.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-dal.ts
@@ -202,12 +202,14 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
} as TCertificateProfileWithConfigs["acmeConfig"])
: undefined;
- const certificateAuthority = {
- id: result.caId,
- projectId: result.caProjectId,
- status: result.caStatus,
- name: result.caName
- } as TCertificateProfileWithConfigs["certificateAuthority"];
+ const certificateAuthority = result.caId
+ ? ({
+ id: result.caId,
+ projectId: result.caProjectId,
+ status: result.caStatus,
+ name: result.caName
+ } as TCertificateProfileWithConfigs["certificateAuthority"])
+ : undefined;
const certificateTemplate =
result.templateId && result.templateProjectId && result.templateName
diff --git a/frontend/src/hooks/api/ca/index.tsx b/frontend/src/hooks/api/ca/index.tsx
index 04a44dbd64..e3a1851a44 100644
--- a/frontend/src/hooks/api/ca/index.tsx
+++ b/frontend/src/hooks/api/ca/index.tsx
@@ -4,6 +4,7 @@ export {
useCreateCertificate,
useCreateCertificateV3,
useDeleteCa,
+ useGenerateCaCertificate,
useImportCaCertificate,
useOrderCertificateWithProfile,
useRenewCa,
diff --git a/frontend/src/hooks/api/ca/mutations.tsx b/frontend/src/hooks/api/ca/mutations.tsx
index e87e1cf2d5..cc8adf4679 100644
--- a/frontend/src/hooks/api/ca/mutations.tsx
+++ b/frontend/src/hooks/api/ca/mutations.tsx
@@ -213,3 +213,37 @@ export const useRenewCa = () => {
}
});
};
+
+export const useGenerateCaCertificate = () => {
+ const queryClient = useQueryClient();
+ return useMutation<
+ { certificate: string; certificateChain: string; serialNumber: string },
+ object,
+ {
+ caId: string;
+ parentCaId?: string;
+ notBefore: string;
+ notAfter: string;
+ maxPathLength?: number;
+ }
+ >({
+ mutationFn: async ({ caId, ...body }) => {
+ const { data } = await apiRequest.post<{
+ certificate: string;
+ certificateChain: string;
+ serialNumber: string;
+ }>(`/api/v1/cert-manager/ca/internal/${caId}/certificate`, body);
+ return data;
+ },
+ onSuccess: (_, { caId }) => {
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaById(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaCsr(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaCrl(caId) });
+ queryClient.invalidateQueries({
+ queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL, "")
+ });
+ }
+ });
+};
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
index 4f12c39501..e8f9316e73 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
@@ -36,6 +36,7 @@ import {
CaCertificatesSection,
CaCrlsSection,
CaDetailsSection,
+ CaGenerateRootCertModal,
CaRenewalModal
} from "./components";
@@ -60,7 +61,8 @@ const Page = () => {
"ca",
"deleteCa",
"installCaCert",
- "renewCa"
+ "renewCa",
+ "generateRootCaCert"
] as const);
const onRemoveCaSubmit = async () => {
@@ -168,6 +170,7 @@ const Page = () => {
<CaModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
<CaRenewalModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
<CaInstallCertModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
+ <CaGenerateRootCertModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
<DeleteActionModal
isOpen={popUp.deleteCa.isOpen}
title={`Are you sure you want to remove the CA ${
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
index 8f88a3f2e1..0cd13eaece 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
@@ -16,7 +16,7 @@ import { UsePopUpState } from "@app/hooks/usePopUp";
type Props = {
caId: string;
handlePopUpOpen: (
- popUpName: keyof UsePopUpState<["ca", "renewCa", "installCaCert"]>,
+ popUpName: keyof UsePopUpState<["ca", "renewCa", "installCaCert", "generateRootCaCert"]>,
data?: object
) => void;
};
@@ -198,6 +198,23 @@ export const CaDetailsSection = ({ caId, handlePopUpOpen }: Props) => {
a={subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })}
>
{(isAllowed) => {
+ if (ca.configuration.type === InternalCaType.ROOT) {
+ return (
+ <Button
+ isDisabled={!isAllowed}
+ className="mt-4 w-full"
+ colorSchema="primary"
+ type="submit"
+ onClick={() => {
+ handlePopUpOpen("generateRootCaCert", {
+ caId: ca.id
+ });
+ }}
+ >
+ Generate Certificate
+ </Button>
+ );
+ }
return (
<Button
isDisabled={!isAllowed}
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaGenerateRootCertModal.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaGenerateRootCertModal.tsx
new file mode 100644
index 0000000000..6fecf6e8fc
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaGenerateRootCertModal.tsx
@@ -0,0 +1,171 @@
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ FormControl,
+ Input,
+ Modal,
+ ModalContent,
+ Select,
+ SelectItem
+} from "@app/components/v2";
+import { useGenerateCaCertificate } from "@app/hooks/api";
+import { UsePopUpState } from "@app/hooks/usePopUp";
+
+const isValidDate = (dateString: string) => {
+ const date = new Date(dateString);
+ return !Number.isNaN(date.getTime());
+};
+
+const schema = z
+ .object({
+ notAfter: z.string().trim().refine(isValidDate, { message: "Invalid date format" }),
+ maxPathLength: z
+ .string()
+ .optional()
+ .refine((val) => !val || (!Number.isNaN(Number(val)) && Number(val) >= -1), {
+ message: "Must be -1 or a non-negative number"
+ })
+ })
+ .required()
+ .refine(
+ (data) => {
+ const now = new Date();
+ const notAfter = new Date(data.notAfter);
+ return notAfter > now;
+ },
+ {
+ message: "Valid until date must be in the future",
+ path: ["notAfter"]
+ }
+ );
+
+export type FormData = z.infer<typeof schema>;
+
+type Props = {
+ popUp: UsePopUpState<["generateRootCaCert"]>;
+ handlePopUpToggle: (
+ popUpName: keyof UsePopUpState<["generateRootCaCert"]>,
+ state?: boolean
+ ) => void;
+};
+
+export const CaGenerateRootCertModal = ({ popUp, handlePopUpToggle }: Props) => {
+ const popUpData = popUp?.generateRootCaCert?.data as {
+ caId: string;
+ };
+
+ const { mutateAsync: generateCaCertificate } = useGenerateCaCertificate();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isSubmitting }
+ } = useForm<FormData>({
+ resolver: zodResolver(schema),
+ defaultValues: {
+ notAfter: "",
+ maxPathLength: "-1"
+ }
+ });
+
+ const onFormSubmit = async ({ notAfter, maxPathLength }: FormData) => {
+ if (!popUpData.caId) return;
+
+ const now = new Date().toISOString();
+
+ await generateCaCertificate({
+ caId: popUpData.caId,
+ notBefore: now,
+ notAfter,
+ maxPathLength: maxPathLength !== "-1" ? Number(maxPathLength) : undefined
+ });
+
+ handlePopUpToggle("generateRootCaCert", false);
+
+ createNotification({
+ text: "Successfully generated root CA certificate",
+ type: "success"
+ });
+
+ reset();
+ };
+
+ return (
+ <Modal
+ isOpen={popUp?.generateRootCaCert?.isOpen}
+ onOpenChange={(isOpen) => {
+ handlePopUpToggle("generateRootCaCert", isOpen);
+ reset();
+ }}
+ >
+ <ModalContent title="Generate Root CA Certificate">
+ <form onSubmit={handleSubmit(onFormSubmit)}>
+ <Controller
+ control={control}
+ defaultValue=""
+ name="notAfter"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Valid Until"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ isRequired
+ >
+ <Input {...field} placeholder="YYYY-MM-DD" />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ defaultValue="-1"
+ name="maxPathLength"
+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (
+ <FormControl
+ label="Max Path Length"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ helperText="Maximum depth of valid certificate paths"
+ >
+ <Select
+ defaultValue={field.value}
+ {...field}
+ onValueChange={(e) => onChange(e)}
+ className="w-full"
+ >
+ {[-1, 0, 1, 2, 3, 4].map((value) => (
+ <SelectItem value={String(value)} key={`ca-max-path-length-${value}`}>
+ {`${value}`}
+ </SelectItem>
+ ))}
+ </Select>
+ </FormControl>
+ )}
+ />
+ <div className="flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ type="submit"
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting}
+ >
+ Generate Certificate
+ </Button>
+ <Button
+ colorSchema="secondary"
+ variant="plain"
+ onClick={() => handlePopUpToggle("generateRootCaCert", false)}
+ >
+ Cancel
+ </Button>
+ </div>
+ </form>
+ </ModalContent>
+ </Modal>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/index.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/index.tsx
index 95a4868f25..b13d5d74e0 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/index.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/index.tsx
@@ -1,4 +1,5 @@
export { CaCertificatesSection } from "./CaCertificatesSection/CaCertificatesSection";
export { CaCrlsSection } from "./CaCrlsSection";
export { CaDetailsSection } from "./CaDetailsSection";
+export { CaGenerateRootCertModal } from "./CaGenerateRootCertModal";
export { CaRenewalModal } from "./CaRenewalModal";
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx
index f33b8c43ff..3d01ecac48 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx
@@ -9,11 +9,9 @@ import { Button, FormControl, Input, Select, SelectItem } from "@app/components/
import { useProject } from "@app/context";
import {
CaStatus,
- useGetCaCsr,
+ useGenerateCaCertificate,
useGetInternalCaById,
- useImportCaCertificate,
- useListWorkspaceCas,
- useSignIntermediate
+ useListWorkspaceCas
} from "@app/hooks/api";
import { caTypeToNameMap } from "@app/hooks/api/ca/constants";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -52,10 +50,8 @@ export const InternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
status: CaStatus.ACTIVE
});
const { data: ca } = useGetInternalCaById(caId);
- const { data: csr } = useGetCaCsr(caId);
- const { mutateAsync: signIntermediate } = useSignIntermediate();
- const { mutateAsync: importCaCertificate } = useImportCaCertificate(currentProject.id);
+ const { mutateAsync: generateCaCertificate } = useGenerateCaCertificate();
const {
control,
@@ -103,28 +99,25 @@ export const InternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
}
}, [parentCa]);
- const onFormSubmit = async ({ notAfter, maxPathLength }: FormData) => {
- if (!csr || !caId || !currentProject?.slug) return;
+ const onFormSubmit = async ({
+ parentCaId: formParentCaId,
+ notAfter,
+ maxPathLength
+ }: FormData) => {
+ if (!caId) return;
- const { certificate, certificateChain } = await signIntermediate({
- caId: parentCaId,
- csr,
+ await generateCaCertificate({
+ caId,
+ parentCaId: formParentCaId,
maxPathLength: Number(maxPathLength),
notAfter,
notBefore: new Date().toISOString()
});
- await importCaCertificate({
- caId,
- projectSlug: currentProject?.slug,
- certificate,
- certificateChain
- });
-
reset();
createNotification({
- text: "Successfully installed certificate for CA",
+ text: "Successfully installed certificate for intermediate CA",
type: "success"
});
handlePopUpToggle("installCaCert", false);