Skip to content

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

Add cert manager CA auto renew, rework of CA installation and added venafi external sign flow

Carlos Monastyrski32c87d848edd
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index c854b713b4..03ea8d2b2c 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -72,6 +72,8 @@ import { TAuthSignupFactory } from "@app/services/auth/auth-signup-service";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TCertificateServiceFactory } from "@app/services/certificate/certificate-service";
+import { TCaAutoRenewalQueueFactory } from "@app/services/certificate-authority/ca-auto-renewal-queue";
+import { TCaSigningConfigServiceFactory } from "@app/services/certificate-authority/ca-signing-config/ca-signing-config-service";
import { TCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
import { TCertificateEstV3ServiceFactory } from "@app/services/certificate-est-v3/certificate-est-v3-service";
@@ -389,6 +391,8 @@ declare module "fastify" {
aiMcpActivityLog: TAiMcpActivityLogServiceFactory;
approvalPolicy: TApprovalPolicyServiceFactory;
appConnectionCredentialRotation: TAppConnectionCredentialRotationServiceFactory;
+ caSigningConfig: TCaSigningConfigServiceFactory;
+ caAutoRenewalQueue: TCaAutoRenewalQueueFactory;
};
// this is exclusive use for middlewares in which we need to inject data
// everywhere else access using service layer
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index f6895de0ac..8745d2ddc4 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -89,6 +89,9 @@ import {
TBackupPrivateKey,
TBackupPrivateKeyInsert,
TBackupPrivateKeyUpdate,
+ TCaSigningConfigs,
+ TCaSigningConfigsInsert,
+ TCaSigningConfigsUpdate,
TCertificateAuthorities,
TCertificateAuthoritiesInsert,
TCertificateAuthoritiesUpdate,
@@ -1682,5 +1685,10 @@ declare module "knex/types/tables" {
TAppConnectionCredentialRotationsInsert,
TAppConnectionCredentialRotationsUpdate
>;
+ [TableName.CaSigningConfig]: KnexOriginal.CompositeTableType<
+ TCaSigningConfigs,
+ TCaSigningConfigsInsert,
+ TCaSigningConfigsUpdate
+ >;
}
}
diff --git a/backend/src/db/migrations/20260218180000_add-ca-signing-configs.ts b/backend/src/db/migrations/20260218180000_add-ca-signing-configs.ts
new file mode 100644
index 0000000000..1aa00cfb1e
--- /dev/null
+++ b/backend/src/db/migrations/20260218180000_add-ca-signing-configs.ts
@@ -0,0 +1,84 @@
+/* eslint-disable no-await-in-loop */
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.CaSigningConfig))) {
+ await knex.schema.createTable(TableName.CaSigningConfig, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.uuid("caId").notNullable().unique();
+ t.foreign("caId").references("id").inTable(TableName.InternalCertificateAuthority).onDelete("CASCADE");
+ t.string("type").notNullable();
+ t.uuid("parentCaId").nullable();
+ t.foreign("parentCaId").references("id").inTable(TableName.CertificateAuthority).onDelete("SET NULL");
+ t.uuid("appConnectionId").nullable();
+ t.foreign("appConnectionId").references("id").inTable(TableName.AppConnection).onDelete("SET NULL");
+ t.jsonb("destinationConfig").nullable();
+ t.string("lastExternalCertificateId").nullable();
+ t.timestamps(true, true, true);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.CaSigningConfig);
+
+ const internalCas = await knex(TableName.InternalCertificateAuthority).select("id", "type", "parentCaId");
+
+ for (const ca of internalCas) {
+ let signingType: string;
+ let parentCaId: string | null = null;
+
+ if (ca.type === "root") {
+ signingType = "internal";
+ } else if (ca.parentCaId) {
+ signingType = "internal";
+ parentCaId = ca.parentCaId;
+ } else {
+ signingType = "manual";
+ }
+
+ await knex(TableName.CaSigningConfig).insert({
+ caId: ca.id,
+ type: signingType,
+ parentCaId
+ });
+ }
+ }
+
+ if (await knex.schema.hasTable(TableName.InternalCertificateAuthority)) {
+ const hasAutoRenewalEnabled = await knex.schema.hasColumn(
+ TableName.InternalCertificateAuthority,
+ "autoRenewalEnabled"
+ );
+ if (!hasAutoRenewalEnabled) {
+ await knex.schema.alterTable(TableName.InternalCertificateAuthority, (t) => {
+ t.boolean("autoRenewalEnabled").defaultTo(false).notNullable();
+ t.integer("autoRenewalDaysBeforeExpiry").nullable();
+ t.string("lastRenewalStatus").nullable();
+ t.text("lastRenewalMessage").nullable();
+ t.datetime("lastRenewalAt").nullable();
+ });
+ }
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.InternalCertificateAuthority)) {
+ const hasAutoRenewalEnabled = await knex.schema.hasColumn(
+ TableName.InternalCertificateAuthority,
+ "autoRenewalEnabled"
+ );
+ if (hasAutoRenewalEnabled) {
+ await knex.schema.alterTable(TableName.InternalCertificateAuthority, (t) => {
+ t.dropColumn("autoRenewalEnabled");
+ t.dropColumn("autoRenewalDaysBeforeExpiry");
+ t.dropColumn("lastRenewalStatus");
+ t.dropColumn("lastRenewalMessage");
+ t.dropColumn("lastRenewalAt");
+ });
+ }
+ }
+
+ await dropOnUpdateTrigger(knex, TableName.CaSigningConfig);
+ await knex.schema.dropTableIfExists(TableName.CaSigningConfig);
+}
diff --git a/backend/src/db/schemas/ca-signing-configs.ts b/backend/src/db/schemas/ca-signing-configs.ts
new file mode 100644
index 0000000000..55c86b0c16
--- /dev/null
+++ b/backend/src/db/schemas/ca-signing-configs.ts
@@ -0,0 +1,19 @@
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const CaSigningConfigsSchema = z.object({
+ id: z.string().uuid(),
+ caId: z.string().uuid(),
+ type: z.string(),
+ parentCaId: z.string().uuid().nullable().optional(),
+ appConnectionId: z.string().uuid().nullable().optional(),
+ destinationConfig: z.unknown().nullable().optional(),
+ lastExternalCertificateId: z.string().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TCaSigningConfigs = z.infer<typeof CaSigningConfigsSchema>;
+export type TCaSigningConfigsInsert = Omit<z.input<typeof CaSigningConfigsSchema>, TImmutableDBKeys>;
+export type TCaSigningConfigsUpdate = Partial<Omit<z.input<typeof CaSigningConfigsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 23985f8b95..cf3a2f1c96 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -27,6 +27,7 @@ export * from "./audit-logs";
export * from "./auth-token-sessions";
export * from "./auth-tokens";
export * from "./backup-private-key";
+export * from "./ca-signing-configs";
export * from "./certificate-authorities";
export * from "./certificate-authority-certs";
export * from "./certificate-authority-crl";
diff --git a/backend/src/db/schemas/internal-certificate-authorities.ts b/backend/src/db/schemas/internal-certificate-authorities.ts
index 70f31c1553..b6b7a5181f 100644
--- a/backend/src/db/schemas/internal-certificate-authorities.ts
+++ b/backend/src/db/schemas/internal-certificate-authorities.ts
@@ -25,7 +25,12 @@ export const InternalCertificateAuthoritiesSchema = z.object({
notBefore: z.date().nullable().optional(),
notAfter: z.date().nullable().optional(),
activeCaCertId: z.string().uuid().nullable().optional(),
- caId: z.string().uuid()
+ caId: z.string().uuid(),
+ autoRenewalEnabled: z.boolean().default(false),
+ autoRenewalDaysBeforeExpiry: z.number().nullable().optional(),
+ lastRenewalStatus: z.string().nullable().optional(),
+ lastRenewalMessage: z.string().nullable().optional(),
+ lastRenewalAt: z.date().nullable().optional()
});
export type TInternalCertificateAuthorities = z.infer<typeof InternalCertificateAuthoritiesSchema>;
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index b1867440c5..2f5534f70a 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -267,7 +267,8 @@ export enum TableName {
ApprovalRequestApprovals = "approval_request_approvals",
ApprovalRequestGrants = "approval_request_grants",
- QueueJobs = "queue_jobs"
+ QueueJobs = "queue_jobs",
+ CaSigningConfig = "ca_signing_configs"
}
export type TImmutableDBKeys = "id" | "createdAt" | "updatedAt" | "commitId";
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 daf881b85f..0910874d77 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -339,6 +339,12 @@ export enum EventType {
IMPORT_CA_CERT = "import-certificate-authority-cert",
GET_CA_CRLS = "get-certificate-authority-crls",
GENERATE_CA_CERTIFICATE = "generate-ca-certificate",
+ INSTALL_CA_CERT_VENAFI = "install-ca-cert-venafi",
+ CREATE_CA_SIGNING_CONFIG = "create-ca-signing-config",
+ GET_CA_SIGNING_CONFIG = "get-ca-signing-config",
+ UPDATE_CA_SIGNING_CONFIG = "update-ca-signing-config",
+ GET_CA_AUTO_RENEWAL_CONFIG = "get-ca-auto-renewal-config",
+ UPDATE_CA_AUTO_RENEWAL_CONFIG = "update-ca-auto-renewal-config",
ISSUE_CERT = "issue-cert",
IMPORT_CERT = "import-cert",
SIGN_CERT = "sign-cert",
@@ -2556,6 +2562,56 @@ interface GenerateCaCertificate {
};
}
+interface InstallCaCertVenafi {
+ type: EventType.INSTALL_CA_CERT_VENAFI;
+ metadata: {
+ caId: string;
+ dn: string;
+ };
+}
+
+interface CreateCaSigningConfig {
+ type: EventType.CREATE_CA_SIGNING_CONFIG;
+ metadata: {
+ caId: string;
+ dn: string;
+ signingConfigType: string;
+ };
+}
+
+interface GetCaSigningConfig {
+ type: EventType.GET_CA_SIGNING_CONFIG;
+ metadata: {
+ caId: string;
+ dn: string;
+ };
+}
+
+interface UpdateCaSigningConfig {
+ type: EventType.UPDATE_CA_SIGNING_CONFIG;
+ metadata: {
+ caId: string;
+ dn: string;
+ };
+}
+
+interface GetCaAutoRenewalConfig {
+ type: EventType.GET_CA_AUTO_RENEWAL_CONFIG;
+ metadata: {
+ caId: string;
+ dn: string;
+ };
+}
+
+interface UpdateCaAutoRenewalConfig {
+ type: EventType.UPDATE_CA_AUTO_RENEWAL_CONFIG;
+ metadata: {
+ caId: string;
+ dn: string;
+ autoRenewalEnabled?: boolean;
+ };
+}
+
interface IssueCert {
type: EventType.ISSUE_CERT;
metadata: {
@@ -5449,6 +5505,12 @@ export type Event =
| ImportCaCert
| GetCaCrls
| GenerateCaCertificate
+ | InstallCaCertVenafi
+ | CreateCaSigningConfig
+ | GetCaSigningConfig
+ | UpdateCaSigningConfig
+ | GetCaAutoRenewalConfig
+ | UpdateCaAutoRenewalConfig
| IssueCert
| ImportCert
| SignCert
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 26cefff54e..9e408a029e 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2101,6 +2101,24 @@ export const CERTIFICATE_AUTHORITIES = {
caId: "The ID of the CA to get the certificate revocation lists (CRLs) for.",
id: "The ID of certificate revocation list (CRL).",
crl: "The certificate revocation list (CRL)."
+ },
+ INSTALL_CERT_VENAFI: {
+ caId: "The ID of the CA to install the certificate for via Venafi."
+ },
+ CREATE_SIGNING_CONFIG: {
+ caId: "The ID of the CA to create a signing configuration for."
+ },
+ GET_SIGNING_CONFIG: {
+ caId: "The ID of the CA to get the signing configuration for."
+ },
+ UPDATE_SIGNING_CONFIG: {
+ caId: "The ID of the CA to update the signing configuration for."
+ },
+ GET_AUTO_RENEWAL: {
+ caId: "The ID of the CA to get the auto-renewal configuration for."
+ },
+ UPDATE_AUTO_RENEWAL: {
+ caId: "The ID of the CA to update the auto-renewal configuration for."
}
};
@@ -2741,6 +2759,10 @@ export const AppConnections = {
},
OPEN_ROUTER: {
apiKey: "The OpenRouter Provisioning API key used to manage API keys."
+ },
+ VENAFI: {
+ apiKey: "The API key used to authenticate with Venafi TLS Protect Cloud.",
+ region: "The region of your Venafi TLS Protect Cloud instance (e.g., 'us', 'eu')."
}
}
};
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 4f7ea47777..d1a5a2be88 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -104,7 +104,8 @@ export enum QueueName {
AppConnectionCredentialRotation = "app-connection-credential-rotation",
AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",
AuditLogClickHouseBatch = "audit-log-clickhouse-batch",
- PamDiscoveryScan = "pam-discovery-scan"
+ PamDiscoveryScan = "pam-discovery-scan",
+ CaAutoRenewal = "ca-auto-renewal"
}
export enum QueueJobs {
@@ -173,7 +174,9 @@ export enum QueueJobs {
AppConnectionCredentialRotationSendNotification = "app-connection-credential-rotation-send-notification",
AuditLogClickHouseBatch = "audit-log-clickhouse-batch-job",
PamDiscoverySourceRunScan = "pam-discovery-run-scan",
- PamDiscoveryScheduledScan = "pam-discovery-scheduled-scan"
+ PamDiscoveryScheduledScan = "pam-discovery-scheduled-scan",
+ CaDailyAutoRenewal = "ca-daily-auto-renewal",
+ CaVenafiInstall = "ca-venafi-install-job"
}
export type TQueueOptions = {
@@ -526,7 +529,16 @@ export type TQueueJobTypes = {
}
| {
name: QueueJobs.PamDiscoveryScheduledScan;
+ payload: undefined;
+ };
+ [QueueName.CaAutoRenewal]:
+ | {
+ name: QueueJobs.CaDailyAutoRenewal;
payload: undefined;
+ }
+ | {
+ name: QueueJobs.CaVenafiInstall;
+ payload: { caId: string; maxPathLength?: number };
};
};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 7c8c946046..b9f8d3011d 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -229,6 +229,9 @@ import { certificateBodyDALFactory } from "@app/services/certificate/certificate
import { certificateDALFactory } from "@app/services/certificate/certificate-dal";
import { certificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import { certificateServiceFactory } from "@app/services/certificate/certificate-service";
+import { caAutoRenewalQueueFactory } from "@app/services/certificate-authority/ca-auto-renewal-queue";
+import { caSigningConfigDALFactory } from "@app/services/certificate-authority/ca-signing-config/ca-signing-config-dal";
+import { caSigningConfigServiceFactory } from "@app/services/certificate-authority/ca-signing-config/ca-signing-config-service";
import { certificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";
import { certificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
import { certificateAuthorityQueueFactory } from "@app/services/certificate-authority/certificate-authority-queue";
@@ -1201,6 +1204,7 @@ export const registerRoutes = async (
const certificateAuthorityDAL = certificateAuthorityDALFactory(db);
const internalCertificateAuthorityDAL = internalCertificateAuthorityDALFactory(db);
+ const caSigningConfigDAL = caSigningConfigDALFactory(db);
const externalCertificateAuthorityDAL = externalCertificateAuthorityDALFactory(db);
const certificateAuthorityCertDAL = certificateAuthorityCertDALFactory(db);
const certificateAuthoritySecretDAL = certificateAuthoritySecretDALFactory(db);
@@ -2336,6 +2340,23 @@ export const registerRoutes = async (
permissionService
});
+ const caAutoRenewalQueue = caAutoRenewalQueueFactory({
+ queueService,
+ internalCertificateAuthorityDAL,
+ caSigningConfigDAL,
+ internalCertificateAuthorityService,
+ appConnectionDAL,
+ kmsService
+ });
+
+ const caSigningConfigService = caSigningConfigServiceFactory({
+ caSigningConfigDAL,
+ certificateAuthorityDAL,
+ internalCertificateAuthorityDAL,
+ permissionService,
+ caAutoRenewalQueue
+ });
+
const certificateAuthorityService = certificateAuthorityServiceFactory({
certificateAuthorityDAL,
permissionService,
@@ -2871,6 +2892,7 @@ export const registerRoutes = async (
await pkiSubscriberQueue.startDailyAutoRenewalJob();
await pkiAlertV2Queue.init();
await certificateV3Queue.init();
+ await caAutoRenewalQueue.startDailyAutoRenewalJob();
await microsoftTeamsService.start();
await eventBusService.init();
@@ -2945,6 +2967,7 @@ export const registerRoutes = async (
sshHostGroup: sshHostGroupService,
certificateAuthority: certificateAuthorityService,
internalCertificateAuthority: internalCertificateAuthorityService,
+ caSigningConfig: caSigningConfigService,
certificateTemplate: certificateTemplateService,
certificatePolicy: certificatePolicyService,
certificateProfile: certificateProfileService,
@@ -3017,7 +3040,8 @@ export const registerRoutes = async (
aiMcpEndpoint: aiMcpEndpointService,
aiMcpActivityLog: aiMcpActivityLogService,
approvalPolicy: approvalPolicyService,
- appConnectionCredentialRotation: appConnectionCredentialRotationService
+ appConnectionCredentialRotation: appConnectionCredentialRotationService,
+ caAutoRenewalQueue
});
const cronJobs: CronJob[] = [];
diff --git a/backend/src/server/routes/sanitizedSchemas.ts b/backend/src/server/routes/sanitizedSchemas.ts
index 2eb0c90f8b..7bd4c3c316 100644
--- a/backend/src/server/routes/sanitizedSchemas.ts
+++ b/backend/src/server/routes/sanitizedSchemas.ts
@@ -289,7 +289,12 @@ export const InternalCertificateAuthorityResponseSchema = CertificateAuthorities
InternalCertificateAuthoritiesSchema.omit({
caId: true,
notAfter: true,
- notBefore: true
+ notBefore: true,
+ autoRenewalEnabled: true,
+ autoRenewalDaysBeforeExpiry: true,
+ lastRenewalStatus: true,
+ lastRenewalMessage: true,
+ lastRenewalAt: true
})
).extend({
requireTemplateForIssuance: z.boolean().optional(),
diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts
index af42002ba4..ed60976089 100644
--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts
@@ -146,6 +146,7 @@ import {
SanitizedTerraformCloudConnectionSchema,
TerraformCloudConnectionListItemSchema
} from "@app/services/app-connection/terraform-cloud";
+import { SanitizedVenafiConnectionSchema, VenafiConnectionListItemSchema } from "@app/services/app-connection/venafi";
import { SanitizedVercelConnectionSchema, VercelConnectionListItemSchema } from "@app/services/app-connection/vercel";
import {
SanitizedWindmillConnectionSchema,
@@ -206,7 +207,8 @@ const SanitizedAppConnectionSchema = z.union([
...SanitizedSmbConnectionSchema.options,
...SanitizedSshConnectionSchema.options,
...SanitizedDbtConnectionSchema.options,
- ...SanitizedOpenRouterConnectionSchema.options
+ ...SanitizedOpenRouterConnectionSchema.options,
+ ...SanitizedVenafiConnectionSchema.options
]);
const AppConnectionOptionsSchema = z.discriminatedUnion("app", [
@@ -260,7 +262,8 @@ const AppConnectionOptionsSchema = z.discriminatedUnion("app", [
SmbConnectionListItemSchema,
SshConnectionListItemSchema,
DbtConnectionListItemSchema,
- OpenRouterConnectionListItemSchema
+ OpenRouterConnectionListItemSchema,
+ VenafiConnectionListItemSchema
]);
export const registerAppConnectionRouter = async (server: FastifyZodProvider) => {
diff --git a/backend/src/server/routes/v1/app-connection-routers/index.ts b/backend/src/server/routes/v1/app-connection-routers/index.ts
index 43100d4cb4..07f3556b2d 100644
--- a/backend/src/server/routes/v1/app-connection-routers/index.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/index.ts
@@ -48,6 +48,7 @@ import { registerSshConnectionRouter } from "./ssh-connection-router";
import { registerSupabaseConnectionRouter } from "./supabase-connection-router";
import { registerTeamCityConnectionRouter } from "./teamcity-connection-router";
import { registerTerraformCloudConnectionRouter } from "./terraform-cloud-router";
+import { registerVenafiConnectionRouter } from "./venafi-connection-router";
import { registerVercelConnectionRouter } from "./vercel-connection-router";
import { registerWindmillConnectionRouter } from "./windmill-connection-router";
import { registerZabbixConnectionRouter } from "./zabbix-connection-router";
@@ -106,5 +107,6 @@ export const APP_CONNECTION_REGISTER_ROUTER_MAP: Record<AppConnection, (server:
[AppConnection.Dbt]: registerDbtConnectionRouter,
[AppConnection.SMB]: registerSmbConnectionRouter,
[AppConnection.OpenRouter]: registerOpenRouterConnectionRouter,
- [AppConnection.CircleCI]: registerCircleCIConnectionRouter
+ [AppConnection.CircleCI]: registerCircleCIConnectionRouter,
+ [AppConnection.Venafi]: registerVenafiConnectionRouter
};
diff --git a/backend/src/server/routes/v1/app-connection-routers/venafi-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/venafi-connection-router.ts
new file mode 100644
index 0000000000..2cb662f8e1
--- /dev/null
+++ b/backend/src/server/routes/v1/app-connection-routers/venafi-connection-router.ts
@@ -0,0 +1,89 @@
+import z from "zod";
+
+import { readLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import {
+ CreateVenafiConnectionSchema,
+ SanitizedVenafiConnectionSchema,
+ UpdateVenafiConnectionSchema
+} from "@app/services/app-connection/venafi/venafi-connection-schema";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+import { registerAppConnectionEndpoints } from "./app-connection-endpoints";
+
+export const registerVenafiConnectionRouter = async (server: FastifyZodProvider) => {
+ registerAppConnectionEndpoints({
+ app: AppConnection.Venafi,
+ server,
+ sanitizedResponseSchema: SanitizedVenafiConnectionSchema,
+ createSchema: CreateVenafiConnectionSchema,
+ updateSchema: UpdateVenafiConnectionSchema
+ });
+
+ server.route({
+ method: "GET",
+ url: `/:connectionId/venafi-applications`,
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listVenafiApplications",
+ params: z.object({
+ connectionId: z.string().uuid()
+ }),
+ response: {
+ 200: z
+ .object({
+ id: z.string(),
+ name: z.string()
+ })
+ .array()
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { connectionId } = req.params;
+
+ const applications = await server.services.appConnection.venafi.listApplications(connectionId, req.permission);
+ return applications;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: `/:connectionId/venafi-issuing-templates`,
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listVenafiIssuingTemplates",
+ params: z.object({
+ connectionId: z.string().uuid()
+ }),
+ querystring: z.object({
+ applicationId: z.string().min(1, "Application ID is required")
+ }),
+ response: {
+ 200: z
+ .object({
+ id: z.string(),
+ name: z.string()
+ })
+ .array()
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { connectionId } = req.params;
+ const { applicationId } = req.query;
+
+ const templates = await server.services.appConnection.venafi.listIssuingTemplates(
+ connectionId,
+ applicationId,
+ req.permission
+ );
+ return templates;
+ }
+ });
+};
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 e79459f5e4..e175f6a6a6 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
@@ -1,10 +1,12 @@
import { z } from "zod";
+import { CaSigningConfigsSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, CERTIFICATE_AUTHORITIES } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
+import { CaSigningConfigType } from "@app/services/certificate-authority/ca-signing-config/ca-signing-config-enums";
import { CaRenewalType, CaType } from "@app/services/certificate-authority/certificate-authority-enums";
import { validateCaDateField } from "@app/services/certificate-authority/certificate-authority-validators";
import {
@@ -15,6 +17,14 @@ import {
import { registerCertificateAuthorityEndpoints } from "./certificate-authority-endpoints";
+const CaAutoRenewalResponseSchema = z.object({
+ autoRenewalEnabled: z.boolean(),
+ autoRenewalDaysBeforeExpiry: z.number().nullable(),
+ lastRenewalStatus: z.string().nullable(),
+ lastRenewalMessage: z.string().nullable(),
+ lastRenewalAt: z.date().nullable()
+});
+
export const registerInternalCertificateAuthorityRouter = async (server: FastifyZodProvider) => {
registerCertificateAuthorityEndpoints({
caType: CaType.INTERNAL,
@@ -606,4 +616,310 @@ export const registerInternalCertificateAuthorityRouter = async (server: Fastify
return Buffer.from(caCert.rawData);
}
});
+
+ server.route({
+ method: "POST",
+ url: "/:caId/install-certificate-venafi",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ operationId: "installCaCertificateVenafi",
+ tags: [ApiDocsTags.PkiCertificateAuthorities],
+ description: "Install a CA certificate via Venafi TLS Protect Cloud",
+ params: z.object({
+ caId: z.string().trim().describe(CERTIFICATE_AUTHORITIES.INSTALL_CERT_VENAFI.caId)
+ }),
+ body: z.object({
+ maxPathLength: z.number().min(-1).default(-1)
+ }),
+ response: {
+ 202: z.object({
+ message: z.string(),
+ caId: z.string()
+ })
+ }
+ },
+ handler: async (req, reply) => {
+ const { ca } = await server.services.caSigningConfig.installCertificateVenafi({
+ caId: req.params.caId,
+ maxPathLength: req.body.maxPathLength,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: ca.projectId,
+ event: {
+ type: EventType.INSTALL_CA_CERT_VENAFI,
+ metadata: {
+ caId: ca.id,
+ dn: ca.dn
+ }
+ }
+ });
+
+ return reply.status(202).send({
+ message: "Certificate installation queued",
+ caId: req.params.caId
+ });
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:caId/signing-config",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ operationId: "createCaSigningConfig",
+ tags: [ApiDocsTags.PkiCertificateAuthorities],
+ description: "Create a signing configuration for a CA",
+ params: z.object({
+ caId: z.string().trim().describe(CERTIFICATE_AUTHORITIES.CREATE_SIGNING_CONFIG.caId)
+ }),
+ body: z.object({
+ type: z.nativeEnum(CaSigningConfigType),
+ parentCaId: z.string().uuid().optional(),
+ appConnectionId: z.string().uuid().optional(),
+ destinationConfig: z
+ .object({
+ applicationId: z.string().min(1),
+ issuingTemplateId: z.string().min(1),
+ validityPeriod: z.number().int().min(1).optional()
+ })
+ .optional()
+ }),
+ response: {
+ 200: CaSigningConfigsSchema
+ }
+ },
+ handler: async (req) => {
+ const { config, ca } = await server.services.caSigningConfig.createSigningConfig({
+ caId: req.params.caId,
+ ...req.body,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: ca.projectId,
+ event: {
+ type: EventType.CREATE_CA_SIGNING_CONFIG,
+ metadata: {
+ caId: ca.id,
+ dn: ca.dn,
+ signingConfigType: req.body.type
+ }
+ }
+ });
+
+ return config;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:caId/signing-config",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ operationId: "getCaSigningConfig",
+ tags: [ApiDocsTags.PkiCertificateAuthorities],
+ description: "Get the signing configuration for a CA",
+ params: z.object({
+ caId: z.string().trim().describe(CERTIFICATE_AUTHORITIES.GET_SIGNING_CONFIG.caId)
+ }),
+ response: {
+ 200: CaSigningConfigsSchema
+ }
+ },
+ handler: async (req) => {
+ const { config, ca } = await server.services.caSigningConfig.getSigningConfig({
+ caId: req.params.caId,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: ca.projectId,
+ event: {
+ type: EventType.GET_CA_SIGNING_CONFIG,
+ metadata: {
+ caId: ca.id,
+ dn: ca.dn
+ }
+ }
+ });
+
+ return config;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:caId/signing-config",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ operationId: "updateCaSigningConfig",
+ tags: [ApiDocsTags.PkiCertificateAuthorities],
+ description: "Update the signing configuration for a CA",
+ params: z.object({
+ caId: z.string().trim().describe(CERTIFICATE_AUTHORITIES.UPDATE_SIGNING_CONFIG.caId)
+ }),
+ body: z.object({
+ parentCaId: z.string().uuid().optional(),
+ appConnectionId: z.string().uuid().optional(),
+ destinationConfig: z
+ .object({
+ applicationId: z.string().min(1),
+ issuingTemplateId: z.string().min(1),
+ validityPeriod: z.number().int().min(1).optional()
+ })
+ .optional()
+ }),
+ response: {
+ 200: CaSigningConfigsSchema
+ }
+ },
+ handler: async (req) => {
+ const { config, ca } = await server.services.caSigningConfig.updateSigningConfig({
+ caId: req.params.caId,
+ ...req.body,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: ca.projectId,
+ event: {
+ type: EventType.UPDATE_CA_SIGNING_CONFIG,
+ metadata: {
+ caId: ca.id,
+ dn: ca.dn
+ }
+ }
+ });
+
+ return config;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:caId/auto-renewal",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ operationId: "getCaAutoRenewalConfig",
+ tags: [ApiDocsTags.PkiCertificateAuthorities],
+ description: "Get auto-renewal configuration for a CA",
+ params: z.object({
+ caId: z.string().trim().describe(CERTIFICATE_AUTHORITIES.GET_AUTO_RENEWAL.caId)
+ }),
+ response: {
+ 200: CaAutoRenewalResponseSchema
+ }
+ },
+ handler: async (req) => {
+ const { ca, ...autoRenewalConfig } = await server.services.caSigningConfig.getAutoRenewalConfig({
+ caId: req.params.caId,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: ca.projectId,
+ event: {
+ type: EventType.GET_CA_AUTO_RENEWAL_CONFIG,
+ metadata: {
+ caId: ca.id,
+ dn: ca.dn
+ }
+ }
+ });
+
+ return autoRenewalConfig;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:caId/auto-renewal",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ operationId: "updateCaAutoRenewalConfig",
+ tags: [ApiDocsTags.PkiCertificateAuthorities],
+ description: "Update auto-renewal configuration for a CA",
+ params: z.object({
+ caId: z.string().trim().describe(CERTIFICATE_AUTHORITIES.UPDATE_AUTO_RENEWAL.caId)
+ }),
+ body: z.object({
+ autoRenewalEnabled: z.boolean().optional(),
+ autoRenewalDaysBeforeExpiry: z.number().min(1).max(365).optional()
+ }),
+ response: {
+ 200: CaAutoRenewalResponseSchema
+ }
+ },
+ handler: async (req) => {
+ const { ca, ...autoRenewalConfig } = await server.services.caSigningConfig.updateAutoRenewalConfig({
+ caId: req.params.caId,
+ ...req.body,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: ca.projectId,
+ event: {
+ type: EventType.UPDATE_CA_AUTO_RENEWAL_CONFIG,
+ metadata: {
+ caId: ca.id,
+ dn: ca.dn,
+ autoRenewalEnabled: req.body.autoRenewalEnabled
+ }
+ }
+ });
+
+ return autoRenewalConfig;
+ }
+ });
};
diff --git a/backend/src/services/app-connection/app-connection-enums.ts b/backend/src/services/app-connection/app-connection-enums.ts
index 5d4570d735..3bfd3c859c 100644
--- a/backend/src/services/app-connection/app-connection-enums.ts
+++ b/backend/src/services/app-connection/app-connection-enums.ts
@@ -49,7 +49,8 @@ export enum AppConnection {
Dbt = "dbt",
SMB = "smb",
OpenRouter = "open-router",
- CircleCI = "circleci"
+ CircleCI = "circleci",
+ Venafi = "venafi"
}
export enum AWSRegion {
diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.ts
index 472740cfb1..561be59115 100644
--- a/backend/src/services/app-connection/app-connection-fns.ts
+++ b/backend/src/services/app-connection/app-connection-fns.ts
@@ -178,6 +178,7 @@ import {
TerraformCloudConnectionMethod,
validateTerraformCloudConnectionCredentials
} from "./terraform-cloud";
+import { getVenafiConnectionListItem, validateVenafiConnectionCredentials, VenafiConnectionMethod } from "./venafi";
import { VercelConnectionMethod } from "./vercel";
import { getVercelConnectionListItem, validateVercelConnectionCredentials } from "./vercel/vercel-connection-fns";
import {
@@ -207,7 +208,8 @@ const PKI_APP_CONNECTIONS = [
AppConnection.AzureKeyVault,
AppConnection.Chef,
AppConnection.DNSMadeEasy,
- AppConnection.AzureDNS
+ AppConnection.AzureDNS,
+ AppConnection.Venafi
];
export const listAppConnectionOptions = (projectType?: ProjectType) => {
@@ -262,7 +264,8 @@ export const listAppConnectionOptions = (projectType?: ProjectType) => {
getDbtConnectionListItem(),
getSmbConnectionListItem(),
getOpenRouterConnectionListItem(),
- getCircleCIConnectionListItem()
+ getCircleCIConnectionListItem(),
+ getVenafiConnectionListItem()
]
.filter((option) => {
switch (projectType) {
@@ -403,7 +406,8 @@ export const validateAppConnectionCredentials = async (
[AppConnection.Dbt]: validateDbtConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.SMB]: validateSmbConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.OpenRouter]: validateOpenRouterConnectionCredentials as TAppConnectionCredentialsValidator,
- [AppConnection.CircleCI]: validateCircleCIConnectionCredentials as TAppConnectionCredentialsValidator
+ [AppConnection.CircleCI]: validateCircleCIConnectionCredentials as TAppConnectionCredentialsValidator,
+ [AppConnection.Venafi]: validateVenafiConnectionCredentials as TAppConnectionCredentialsValidator
};
return VALIDATE_APP_CONNECTION_CREDENTIALS_MAP[appConnection.app](appConnection, gatewayService, gatewayV2Service);
@@ -481,6 +485,8 @@ export const getAppConnectionMethodName = (method: TAppConnection["method"]) =>
return "SSH Key";
case SmbConnectionMethod.Credentials:
return "Credentials";
+ case VenafiConnectionMethod.ApiKey:
+ return "API Key";
case RenderConnectionMethod.ApiKey:
case ChecklyConnectionMethod.ApiKey:
case OctopusDeployConnectionMethod.ApiKey:
@@ -594,7 +600,8 @@ export const TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM: Record<
[AppConnection.Dbt]: platformManagedCredentialsNotSupported,
[AppConnection.SMB]: platformManagedCredentialsNotSupported,
[AppConnection.OpenRouter]: platformManagedCredentialsNotSupported,
- [AppConnection.CircleCI]: platformManagedCredentialsNotSupported
+ [AppConnection.CircleCI]: platformManagedCredentialsNotSupported,
+ [AppConnection.Venafi]: platformManagedCredentialsNotSupported
};
export const enterpriseAppCheck = async (
diff --git a/backend/src/services/app-connection/app-connection-maps.ts b/backend/src/services/app-connection/app-connection-maps.ts
index 367a108963..f9e861aab1 100644
--- a/backend/src/services/app-connection/app-connection-maps.ts
+++ b/backend/src/services/app-connection/app-connection-maps.ts
@@ -51,7 +51,8 @@ export const APP_CONNECTION_NAME_MAP: Record<AppConnection, string> = {
[AppConnection.Dbt]: "DBT",
[AppConnection.SMB]: "SMB",
[AppConnection.OpenRouter]: "OpenRouter",
- [AppConnection.CircleCI]: "CircleCI"
+ [AppConnection.CircleCI]: "CircleCI",
+ [AppConnection.Venafi]: "Venafi TLS Protect Cloud"
};
export const APP_CONNECTION_PLAN_MAP: Record<AppConnection, AppConnectionPlanType> = {
@@ -105,5 +106,6 @@ export const APP_CONNECTION_PLAN_MAP: Record<AppConnection, AppConnectionPlanTyp
[AppConnection.Dbt]: AppConnectionPlanType.Regular,
[AppConnection.SMB]: AppConnectionPlanType.Regular,
[AppConnection.OpenRouter]: AppConnectionPlanType.Regular,
- [AppConnection.CircleCI]: AppConnectionPlanType.Regular
+ [AppConnection.CircleCI]: AppConnectionPlanType.Regular,
+ [AppConnection.Venafi]: AppConnectionPlanType.Regular
};
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index 87587052cf..ebde2e20d2 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -130,6 +130,8 @@ import { ValidateTeamCityConnectionCredentialsSchema } from "./teamcity";
import { teamcityConnectionService } from "./teamcity/teamcity-connection-service";
import { ValidateTerraformCloudConnectionCredentialsSchema } from "./terraform-cloud";
import { terraformCloudConnectionService } from "./terraform-cloud/terraform-cloud-connection-service";
+import { ValidateVenafiConnectionCredentialsSchema } from "./venafi/venafi-connection-schema";
+import { venafiConnectionService } from "./venafi/venafi-connection-service";
import { ValidateVercelConnectionCredentialsSchema } from "./vercel";
import { vercelConnectionService } from "./vercel/vercel-connection-service";
import { ValidateWindmillConnectionCredentialsSchema } from "./windmill";
@@ -203,7 +205,8 @@ const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TValidateAp
[AppConnection.SSH]: ValidateSshConnectionCredentialsSchema,
[AppConnection.Dbt]: ValidateDbtConnectionCredentialsSchema,
[AppConnection.SMB]: ValidateSmbConnectionCredentialsSchema,
- [AppConnection.CircleCI]: ValidateCircleCIConnectionCredentialsSchema
+ [AppConnection.CircleCI]: ValidateCircleCIConnectionCredentialsSchema,
+ [AppConnection.Venafi]: ValidateVenafiConnectionCredentialsSchema
};
export const appConnectionServiceFactory = ({
@@ -1059,6 +1062,7 @@ export const appConnectionServiceFactory = ({
flyio: flyioConnectionService(connectAppConnectionById),
gitlab: gitlabConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
cloudflare: cloudflareConnectionService(connectAppConnectionById),
+ venafi: venafiConnectionService(connectAppConnectionById),
dnsMadeEasy: dnsMadeEasyConnectionService(connectAppConnectionById),
azureDns: azureDnsConnectionService(connectAppConnectionById),
zabbix: zabbixConnectionService(connectAppConnectionById),
diff --git a/backend/src/services/app-connection/app-connection-types.ts b/backend/src/services/app-connection/app-connection-types.ts
index 198de071d8..13c6a3f419 100644
--- a/backend/src/services/app-connection/app-connection-types.ts
+++ b/backend/src/services/app-connection/app-connection-types.ts
@@ -281,6 +281,12 @@ import {
TTerraformCloudConnectionInput,
TValidateTerraformCloudConnectionCredentialsSchema
} from "./terraform-cloud";
+import {
+ TValidateVenafiConnectionCredentialsSchema,
+ TVenafiConnection,
+ TVenafiConnectionConfig,
+ TVenafiConnectionInput
+} from "./venafi";
import {
TValidateVercelConnectionCredentialsSchema,
TVercelConnection,
@@ -352,6 +358,7 @@ export type TAppConnection = { id: string } & (
| TSmbConnection
| TOpenRouterConnection
| TCircleCIConnection
+ | TVenafiConnection
);
export type TAppConnectionRaw = NonNullable<Awaited<ReturnType<TAppConnectionDALFactory["findById"]>>>;
@@ -414,6 +421,7 @@ export type TAppConnectionInput = { id: string } & (
| TSmbConnectionInput
| TOpenRouterConnectionInput
| TCircleCIConnectionInput
+ | TVenafiConnectionInput
);
export type TSqlConnectionInput =
@@ -504,7 +512,8 @@ export type TAppConnectionConfig =
| TDbtConnectionConfig
| TSmbConnectionConfig
| TOpenRouterConnectionConfig
- | TCircleCIConnectionConfig;
+ | TCircleCIConnectionConfig
+ | TVenafiConnectionConfig;
export type TValidateAppConnectionCredentialsSchema =
| TValidateAwsConnectionCredentialsSchema
@@ -557,7 +566,8 @@ export type TValidateAppConnectionCredentialsSchema =
| TValidateDbtConnectionCredentialsSchema
| TValidateSmbConnectionCredentialsSchema
| TValidateOpenRouterConnectionCredentialsSchema
- | TValidateCircleCIConnectionCredentialsSchema;
+ | TValidateCircleCIConnectionCredentialsSchema
+ | TValidateVenafiConnectionCredentialsSchema;
export type TListAwsConnectionKmsKeys = {
connectionId: string;
diff --git a/backend/src/services/app-connection/venafi/index.ts b/backend/src/services/app-connection/venafi/index.ts
new file mode 100644
index 0000000000..bfeac2218a
--- /dev/null
+++ b/backend/src/services/app-connection/venafi/index.ts
@@ -0,0 +1,5 @@
+export * from "./venafi-connection-enum";
+export * from "./venafi-connection-fns";
+export * from "./venafi-connection-schema";
+export * from "./venafi-connection-service";
+export * from "./venafi-connection-types";
diff --git a/backend/src/services/app-connection/venafi/venafi-connection-enum.ts b/backend/src/services/app-connection/venafi/venafi-connection-enum.ts
new file mode 100644
index 0000000000..fb0d56b73b
--- /dev/null
+++ b/backend/src/services/app-connection/venafi/venafi-connection-enum.ts
@@ -0,0 +1,12 @@
+export enum VenafiConnectionMethod {
+ ApiKey = "api-key"
+}
+
+export enum VenafiRegion {
+ US = "us",
+ EU = "eu",
+ AU = "au",
+ UK = "uk",
+ SG = "sg",
+ CA = "ca"
+}
diff --git a/backend/src/services/app-connection/venafi/venafi-connection-fns.ts b/backend/src/services/app-connection/venafi/venafi-connection-fns.ts
new file mode 100644
index 0000000000..1dffe8c1a3
--- /dev/null
+++ b/backend/src/services/app-connection/venafi/venafi-connection-fns.ts
@@ -0,0 +1,179 @@
+import { AxiosError } from "axios";
+
+import { request } from "@app/lib/config/request";
+import { BadRequestError } from "@app/lib/errors";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+
+import { VenafiConnectionMethod, VenafiRegion } from "./venafi-connection-enum";
+import { TVenafiConnection, TVenafiConnectionConfig } from "./venafi-connection-types";
+
+type TVenafiCredentials = {
+ apiKey: string;
+ region: VenafiRegion;
+};
+
+type TVenafiApplication = {
+ id: string;
+ name: string;
+};
+
+type TVenafiIssuingTemplate = {
+ id: string;
+ name: string;
+};
+
+type TVenafiApplicationDetail = {
+ id: string;
+ name: string;
+ certificateIssuingTemplateAliasIdMap: Record<string, string>;
+};
+
+type TVenafiApplicationsResponse = {
+ applications: TVenafiApplicationDetail[];
+};
+
+type TVenafiIssuingTemplateDetail = {
+ id: string;
+ name: string;
+ certificateAuthority: string;
+};
+
+type TVenafiIssuingTemplatesResponse = {
+ certificateIssuingTemplates: TVenafiIssuingTemplateDetail[];
+};
+
+const VENAFI_REGION_BASE_URLS: Record<VenafiRegion, string> = {
+ [VenafiRegion.US]: "https://api.venafi.cloud",
+ [VenafiRegion.EU]: "https://api.eu.venafi.cloud",
+ [VenafiRegion.AU]: "https://api.au.venafi.cloud",
+ [VenafiRegion.UK]: "https://api.uk.venafi.cloud",
+ [VenafiRegion.SG]: "https://api.sg.venafi.cloud",
+ [VenafiRegion.CA]: "https://api.ca.venafi.cloud"
+};
+
+export const getVenafiBaseUrl = (region: VenafiRegion): string => {
+ return VENAFI_REGION_BASE_URLS[region];
+};
+
+export const getVenafiHeaders = (apiKey: string) => ({
+ "tppl-api-key": apiKey,
+ Accept: "application/json"
+});
+
+export const getVenafiConnectionListItem = () => {
+ return {
+ name: "Venafi TLS Protect Cloud" as const,
+ app: AppConnection.Venafi as const,
+ methods: Object.values(VenafiConnectionMethod) as [VenafiConnectionMethod.ApiKey]
+ };
+};
+
+export const validateVenafiConnectionCredentials = async (config: TVenafiConnectionConfig) => {
+ const { apiKey, region } = config.credentials as TVenafiCredentials;
+
+ const baseUrl = getVenafiBaseUrl(region);
+
+ try {
+ const resp = await request.get(`${baseUrl}/v1/useraccounts`, {
+ headers: getVenafiHeaders(apiKey)
+ });
+
+ if (resp.data === null) {
+ throw new BadRequestError({
+ message: "Unable to validate connection: Invalid API key provided."
+ });
+ }
+ } catch (error: unknown) {
+ if (error instanceof BadRequestError) {
+ throw error;
+ }
+ if (error instanceof AxiosError) {
+ throw new BadRequestError({
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ message: `Failed to validate credentials: ${error.response?.data?.error || error.message || "Unknown error"}`
+ });
+ }
+ throw new BadRequestError({
+ message: `Failed to validate credentials: ${(error as Error)?.message || "Unknown error"}`
+ });
+ }
+
+ return config.credentials;
+};
+
+export const listVenafiApplications = async (appConnection: TVenafiConnection): Promise<TVenafiApplication[]> => {
+ const { apiKey, region } = appConnection.credentials as TVenafiCredentials;
+ const baseUrl = getVenafiBaseUrl(region);
+
+ try {
+ const { data } = await request.get<TVenafiApplicationsResponse>(`${baseUrl}/outagedetection/v1/applications`, {
+ headers: getVenafiHeaders(apiKey)
+ });
+
+ return (data.applications || []).map((app) => ({
+ id: app.id,
+ name: app.name
+ }));
+ } catch (error: unknown) {
+ if (error instanceof AxiosError) {
+ throw new BadRequestError({
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ message: `Failed to list Venafi applications: ${error.response?.data?.error || error.message || "Unknown error"}`
+ });
+ }
+ throw new BadRequestError({
+ message: `Failed to list Venafi applications: ${(error as Error)?.message || "Unknown error"}`
+ });
+ }
+};
+
+export const listVenafiIssuingTemplates = async (
+ appConnection: TVenafiConnection,
+ applicationId: string
+): Promise<TVenafiIssuingTemplate[]> => {
+ const { apiKey, region } = appConnection.credentials as TVenafiCredentials;
+ const baseUrl = getVenafiBaseUrl(region);
+
+ try {
+ // Fetch the application detail to get its linked template IDs
+ const { data: appData } = await request.get<TVenafiApplicationDetail>(
+ `${baseUrl}/outagedetection/v1/applications/${encodeURIComponent(applicationId)}`,
+ {
+ headers: getVenafiHeaders(apiKey)
+ }
+ );
+
+ const templateAliasMap = appData.certificateIssuingTemplateAliasIdMap;
+ if (!templateAliasMap || Object.keys(templateAliasMap).length === 0) {
+ return [];
+ }
+
+ const templateIds = new Set(Object.values(templateAliasMap));
+
+ // Fetch all issuing templates and filter to those linked to this application
+ const { data: templatesData } = await request.get<TVenafiIssuingTemplatesResponse>(
+ `${baseUrl}/v1/certificateissuingtemplates`,
+ {
+ headers: getVenafiHeaders(apiKey)
+ }
+ );
+
+ return (templatesData.certificateIssuingTemplates || [])
+ .filter((template) => templateIds.has(template.id))
+ .map((template) => ({
+ id: template.id,
+ name: template.name
+ }));
+ } catch (error: unknown) {
+ if (error instanceof BadRequestError) throw error;
+ if (error instanceof AxiosError) {
+ throw new BadRequestError({
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ message: `Failed to list Venafi issuing templates: ${error.response?.data?.error || error.message || "Unknown error"}`
+ });
+ }
+ throw new BadRequestError({
+ message: `Failed to list Venafi issuing templates: ${(error as Error)?.message || "Unknown error"}`
+ });
+ }
+};
diff --git a/backend/src/services/app-connection/venafi/venafi-connection-schema.ts b/backend/src/services/app-connection/venafi/venafi-connection-schema.ts
new file mode 100644
index 0000000000..22f8fb6b57
--- /dev/null
+++ b/backend/src/services/app-connection/venafi/venafi-connection-schema.ts
@@ -0,0 +1,60 @@
+import z from "zod";
+
+import { AppConnections } from "@app/lib/api-docs";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import {
+ BaseAppConnectionSchema,
+ GenericCreateAppConnectionFieldsSchema,
+ GenericUpdateAppConnectionFieldsSchema
+} from "@app/services/app-connection/app-connection-schemas";
+
+import { APP_CONNECTION_NAME_MAP } from "../app-connection-maps";
+import { VenafiConnectionMethod, VenafiRegion } from "./venafi-connection-enum";
+
+export const VenafiConnectionApiKeyCredentialsSchema = z.object({
+ apiKey: z.string().trim().min(1, "API key required").max(256, "API key cannot exceed 256 characters"),
+ region: z.nativeEnum(VenafiRegion).describe("The region of the Venafi TLS Protect Cloud instance")
+});
+
+const BaseVenafiConnectionSchema = BaseAppConnectionSchema.extend({ app: z.literal(AppConnection.Venafi) });
+
+export const VenafiConnectionSchema = BaseVenafiConnectionSchema.extend({
+ method: z.literal(VenafiConnectionMethod.ApiKey),
+ credentials: VenafiConnectionApiKeyCredentialsSchema
+});
+
+export const SanitizedVenafiConnectionSchema = z.discriminatedUnion("method", [
+ BaseVenafiConnectionSchema.extend({
+ method: z.literal(VenafiConnectionMethod.ApiKey),
+ credentials: VenafiConnectionApiKeyCredentialsSchema.pick({ region: true })
+ }).describe(JSON.stringify({ title: `${APP_CONNECTION_NAME_MAP[AppConnection.Venafi]} (API Key)` }))
+]);
+
+export const ValidateVenafiConnectionCredentialsSchema = z.discriminatedUnion("method", [
+ z.object({
+ method: z.literal(VenafiConnectionMethod.ApiKey).describe(AppConnections.CREATE(AppConnection.Venafi).method),
+ credentials: VenafiConnectionApiKeyCredentialsSchema.describe(
+ AppConnections.CREATE(AppConnection.Venafi).credentials
+ )
+ })
+]);
+
+export const CreateVenafiConnectionSchema = ValidateVenafiConnectionCredentialsSchema.and(
+ GenericCreateAppConnectionFieldsSchema(AppConnection.Venafi)
+);
+
+export const UpdateVenafiConnectionSchema = z
+ .object({
+ credentials: VenafiConnectionApiKeyCredentialsSchema.optional().describe(
+ AppConnections.UPDATE(AppConnection.Venafi).credentials
+ )
+ })
+ .and(GenericUpdateAppConnectionFieldsSchema(AppConnection.Venafi));
+
+export const VenafiConnectionListItemSchema = z
+ .object({
+ name: z.literal("Venafi TLS Protect Cloud"),
+ app: z.literal(AppConnection.Venafi),
+ methods: z.nativeEnum(VenafiConnectionMethod).array()
+ })
+ .describe(JSON.stringify({ title: APP_CONNECTION_NAME_MAP[AppConnection.Venafi] }));
diff --git a/backend/src/services/app-connection/venafi/venafi-connection-service.ts b/backend/src/services/app-connection/venafi/venafi-connection-service.ts
new file mode 100644
index 0000000000..4ebbd12159
--- /dev/null
+++ b/backend/src/services/app-connection/venafi/venafi-connection-service.ts
@@ -0,0 +1,28 @@
+import { OrgServiceActor } from "@app/lib/types";
+
+import { AppConnection } from "../app-connection-enums";
+import { listVenafiApplications, listVenafiIssuingTemplates } from "./venafi-connection-fns";
+import { TVenafiConnection } from "./venafi-connection-types";
+
+type TGetAppConnectionFunc = (
+ app: AppConnection,
+ connectionId: string,
+ actor: OrgServiceActor
+) => Promise<TVenafiConnection>;
+
+export const venafiConnectionService = (getAppConnection: TGetAppConnectionFunc) => {
+ const listApplications = async (connectionId: string, actor: OrgServiceActor) => {
+ const appConnection = await getAppConnection(AppConnection.Venafi, connectionId, actor);
+ return listVenafiApplications(appConnection);
+ };
+
+ const listIssuingTemplates = async (connectionId: string, applicationId: string, actor: OrgServiceActor) => {
+ const appConnection = await getAppConnection(AppConnection.Venafi, connectionId, actor);
+ return listVenafiIssuingTemplates(appConnection, applicationId);
+ };
+
+ return {
+ listApplications,
+ listIssuingTemplates
+ };
+};
diff --git a/backend/src/services/app-connection/venafi/venafi-connection-types.ts b/backend/src/services/app-connection/venafi/venafi-connection-types.ts
new file mode 100644
index 0000000000..a8f443fe25
--- /dev/null
+++ b/backend/src/services/app-connection/venafi/venafi-connection-types.ts
@@ -0,0 +1,22 @@
+import z from "zod";
+
+import { DiscriminativePick } from "@app/lib/types";
+
+import { AppConnection } from "../app-connection-enums";
+import {
+ CreateVenafiConnectionSchema,
+ ValidateVenafiConnectionCredentialsSchema,
+ VenafiConnectionSchema
+} from "./venafi-connection-schema";
+
+export type TVenafiConnection = z.infer<typeof VenafiConnectionSchema>;
+
+export type TVenafiConnectionInput = z.infer<typeof CreateVenafiConnectionSchema> & {
+ app: AppConnection.Venafi;
+};
+
+export type TValidateVenafiConnectionCredentialsSchema = typeof ValidateVenafiConnectionCredentialsSchema;
+
+export type TVenafiConnectionConfig = DiscriminativePick<TVenafiConnectionInput, "method" | "app" | "credentials"> & {
+ orgId: string;
+};
diff --git a/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts b/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts
new file mode 100644
index 0000000000..bee35b1f91
--- /dev/null
+++ b/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts
@@ -0,0 +1,366 @@
+/* eslint-disable no-continue, no-await-in-loop */
+import RE2 from "re2";
+
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+
+import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";
+import { decryptAppConnectionCredentials } from "../app-connection/app-connection-fns";
+import { TVenafiConnection } from "../app-connection/venafi/venafi-connection-types";
+import { TKmsServiceFactory } from "../kms/kms-service";
+import { TCaSigningConfigDALFactory } from "./ca-signing-config/ca-signing-config-dal";
+import { CaSigningConfigType } from "./ca-signing-config/ca-signing-config-enums";
+import { VenafiDestinationConfigSchema } from "./ca-signing-config/ca-signing-config-types";
+import {
+ downloadVenafiCertificate,
+ pollVenafiCertificateIssuance,
+ renewVenafiCertificate,
+ submitCsrToVenafi
+} from "./ca-signing-config/venafi-signing-fns";
+import { CaRenewalStatus } from "./certificate-authority-enums";
+import { TInternalCertificateAuthorityDALFactory } from "./internal/internal-certificate-authority-dal";
+import { TInternalCertificateAuthorityServiceFactory } from "./internal/internal-certificate-authority-service";
+
+type TCaAutoRenewalQueueFactoryDep = {
+ queueService: TQueueServiceFactory;
+ internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "find" | "findOne" | "updateById">;
+ caSigningConfigDAL: Pick<TCaSigningConfigDALFactory, "findByCaId" | "updateById">;
+ internalCertificateAuthorityService: Pick<
+ TInternalCertificateAuthorityServiceFactory,
+ "getCaCsr" | "importCertToCa" | "renewCaCert"
+ >;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+};
+
+export type TCaAutoRenewalQueueFactory = ReturnType<typeof caAutoRenewalQueueFactory>;
+
+const BATCH_SIZE = 100;
+const MAX_RENEWAL_MESSAGE_LENGTH = 1024;
+const PEM_CERT_REGEX = new RE2("-----BEGIN CERTIFICATE-----[\\s\\S]*?-----END CERTIFICATE-----", "g");
+
+export const caAutoRenewalQueueFactory = ({
+ queueService,
+ internalCertificateAuthorityDAL,
+ caSigningConfigDAL,
+ internalCertificateAuthorityService,
+ appConnectionDAL,
+ kmsService
+}: TCaAutoRenewalQueueFactoryDep) => {
+ /**
+ * Shared helper that handles the full Venafi certificate issuance flow:
+ * get signing config, get CSR, submit to Venafi, poll, download, import.
+ */
+ const processVenafiCertificateIssuance = async ({
+ caId,
+ internalCaId,
+ maxPathLength
+ }: {
+ caId: string;
+ internalCaId: string;
+ maxPathLength?: number;
+ }) => {
+ const signingConfig = await caSigningConfigDAL.findByCaId(internalCaId);
+ if (!signingConfig) {
+ throw new Error("No signing config found");
+ }
+
+ if (signingConfig.type !== CaSigningConfigType.Venafi) {
+ throw new Error(`Signing config type '${signingConfig.type}' is not Venafi`);
+ }
+
+ if (!signingConfig.appConnectionId) {
+ throw new Error("Venafi signing config is missing app connection");
+ }
+
+ const parseResult = VenafiDestinationConfigSchema.safeParse(signingConfig.destinationConfig);
+ if (!parseResult.success) {
+ throw new Error("Venafi signing config has invalid or missing destination configuration");
+ }
+ const destinationConfig = parseResult.data;
+
+ const { csr } = await internalCertificateAuthorityService.getCaCsr({
+ isInternal: true,
+ caId,
+ ...(maxPathLength !== undefined && { maxPathLength })
+ });
+
+ const appConnection = await appConnectionDAL.findById(signingConfig.appConnectionId);
+ if (!appConnection) {
+ throw new Error(`Venafi app connection ${signingConfig.appConnectionId} not found`);
+ }
+
+ const credentials = (await decryptAppConnectionCredentials({
+ orgId: appConnection.orgId,
+ encryptedCredentials: appConnection.encryptedCredentials,
+ kmsService,
+ projectId: appConnection.projectId
+ })) as TVenafiConnection["credentials"];
+
+ const { apiKey, region } = credentials;
+
+ let requestId: string;
+ if (signingConfig.lastExternalCertificateId) {
+ requestId = await renewVenafiCertificate({
+ apiKey,
+ region,
+ existingCertificateId: signingConfig.lastExternalCertificateId,
+ csr,
+ destinationConfig
+ });
+ } else {
+ requestId = await submitCsrToVenafi({
+ apiKey,
+ region,
+ csr,
+ destinationConfig
+ });
+ }
+
+ const { certificateId } = await pollVenafiCertificateIssuance({
+ apiKey,
+ region,
+ requestId
+ });
+
+ const pemBundle = await downloadVenafiCertificate({
+ apiKey,
+ region,
+ certificateId
+ });
+
+ const pemCerts = pemBundle.match(PEM_CERT_REGEX);
+ if (!pemCerts || pemCerts.length === 0) {
+ throw new Error("Failed to parse certificate from Venafi response");
+ }
+
+ const certificate = pemCerts[0];
+ const certificateChain = pemCerts.slice(1).join("\n");
+
+ await internalCertificateAuthorityService.importCertToCa({
+ isInternal: true,
+ caId,
+ certificate,
+ certificateChain
+ });
+
+ await caSigningConfigDAL.updateById(signingConfig.id, {
+ lastExternalCertificateId: certificateId
+ });
+
+ await internalCertificateAuthorityDAL.updateById(internalCaId, {
+ lastRenewalStatus: CaRenewalStatus.SUCCESS,
+ lastRenewalMessage: null,
+ lastRenewalAt: new Date()
+ });
+ };
+
+ const processInternalCaRenewal = async ({
+ caId,
+ internalCaId,
+ notBefore,
+ notAfter
+ }: {
+ caId: string;
+ internalCaId: string;
+ notBefore: Date;
+ notAfter: Date;
+ }) => {
+ const currentDurationMs = notAfter.getTime() - notBefore.getTime();
+ if (currentDurationMs <= 0) {
+ throw new Error("Cannot determine certificate validity duration for auto-renewal");
+ }
+
+ const newNotAfter = new Date(Date.now() + currentDurationMs);
+
+ await internalCertificateAuthorityService.renewCaCert({
+ isInternal: true,
+ caId,
+ notAfter: newNotAfter.toISOString()
+ });
+
+ await internalCertificateAuthorityDAL.updateById(internalCaId, {
+ lastRenewalStatus: CaRenewalStatus.SUCCESS,
+ lastRenewalMessage: null,
+ lastRenewalAt: new Date()
+ });
+ };
+
+ queueService.start(QueueName.CaAutoRenewal, async (job) => {
+ if (job.name === QueueJobs.CaVenafiInstall) {
+ const { caId, maxPathLength } = job.data as { caId: string; maxPathLength?: number };
+
+ logger.info({ caId }, `${QueueJobs.CaVenafiInstall}: processing Venafi install`);
+
+ const internalCa = await internalCertificateAuthorityDAL.findOne({ caId });
+ if (!internalCa) {
+ logger.error({ caId }, `${QueueJobs.CaVenafiInstall}: internal CA not found`);
+ return;
+ }
+
+ try {
+ await processVenafiCertificateIssuance({
+ caId,
+ internalCaId: internalCa.id,
+ maxPathLength
+ });
+
+ logger.info({ caId }, `${QueueJobs.CaVenafiInstall}: successfully installed certificate via Venafi`);
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
+ logger.error(error, `${QueueJobs.CaVenafiInstall}: CA ${caId} Venafi install failed`);
+
+ await internalCertificateAuthorityDAL.updateById(internalCa.id, {
+ lastRenewalStatus: CaRenewalStatus.FAILED,
+ lastRenewalMessage: errorMessage.substring(0, MAX_RENEWAL_MESSAGE_LENGTH)
+ });
+ }
+
+ return;
+ }
+
+ if (job.name !== QueueJobs.CaDailyAutoRenewal) return;
+
+ logger.info(`${QueueJobs.CaDailyAutoRenewal}: queue task started`);
+
+ const now = new Date();
+ let offset = 0;
+ let totalProcessed = 0;
+ let totalRenewed = 0;
+ let totalFailed = 0;
+
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ const internalCas = await internalCertificateAuthorityDAL.find(
+ { autoRenewalEnabled: true },
+ { limit: BATCH_SIZE, offset }
+ );
+
+ if (internalCas.length === 0) break;
+
+ for (const internalCa of internalCas) {
+ totalProcessed += 1;
+
+ try {
+ if (!internalCa.notAfter || !internalCa.autoRenewalDaysBeforeExpiry) {
+ continue;
+ }
+
+ const expiryDate = new Date(internalCa.notAfter);
+ const renewalThreshold = new Date(expiryDate);
+ renewalThreshold.setDate(renewalThreshold.getDate() - internalCa.autoRenewalDaysBeforeExpiry);
+
+ if (now < renewalThreshold) {
+ continue;
+ }
+
+ const signingConfig = await caSigningConfigDAL.findByCaId(internalCa.id);
+ if (!signingConfig) {
+ logger.warn(`CA ${internalCa.caId}: no signing config found, skipping auto-renewal`);
+ continue;
+ }
+
+ if (signingConfig.type === CaSigningConfigType.Manual) {
+ logger.warn(`CA ${internalCa.caId}: manual signing config does not support auto-renewal`);
+ await internalCertificateAuthorityDAL.updateById(internalCa.id, {
+ autoRenewalEnabled: false,
+ lastRenewalStatus: CaRenewalStatus.FAILED,
+ lastRenewalMessage: "Auto-renewal is not supported for manual signing configuration"
+ });
+ continue;
+ }
+
+ if (signingConfig.type === CaSigningConfigType.Internal) {
+ if (!internalCa.notBefore) {
+ throw new Error("Cannot auto-renew: certificate has no notBefore date");
+ }
+ await processInternalCaRenewal({
+ caId: internalCa.caId,
+ internalCaId: internalCa.id,
+ notBefore: new Date(internalCa.notBefore),
+ notAfter: expiryDate
+ });
+ } else if (signingConfig.type === CaSigningConfigType.Venafi) {
+ await processVenafiCertificateIssuance({
+ caId: internalCa.caId,
+ internalCaId: internalCa.id
+ });
+ }
+
+ totalRenewed += 1;
+ logger.info(`CA ${internalCa.caId}: successfully auto-renewed (${signingConfig.type})`);
+ } catch (error) {
+ totalFailed += 1;
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
+ logger.error(error, `CA ${internalCa.caId}: auto-renewal failed`);
+
+ await internalCertificateAuthorityDAL.updateById(internalCa.id, {
+ autoRenewalEnabled: false,
+ lastRenewalStatus: CaRenewalStatus.FAILED,
+ lastRenewalMessage: errorMessage.substring(0, MAX_RENEWAL_MESSAGE_LENGTH)
+ });
+ }
+ }
+
+ offset += BATCH_SIZE;
+ }
+
+ logger.info(
+ `${QueueJobs.CaDailyAutoRenewal}: completed. Processed: ${totalProcessed}, Renewed: ${totalRenewed}, Failed: ${totalFailed}`
+ );
+ });
+
+ const startDailyAutoRenewalJob = async () => {
+ await queueService.stopRepeatableJob(
+ QueueName.CaAutoRenewal,
+ QueueJobs.CaDailyAutoRenewal,
+ { pattern: "0 0 * * *", utc: true },
+ QueueName.CaAutoRenewal
+ );
+
+ await queueService.queue(QueueName.CaAutoRenewal, QueueJobs.CaDailyAutoRenewal, undefined, {
+ jobId: QueueJobs.CaDailyAutoRenewal,
+ repeat: {
+ pattern: "0 0 * * *",
+ utc: true,
+ key: QueueJobs.CaDailyAutoRenewal
+ },
+ removeOnComplete: true,
+ removeOnFail: true
+ });
+ };
+
+ const queueVenafiInstall = async (caId: string, maxPathLength?: number) => {
+ const internalCa = await internalCertificateAuthorityDAL.findOne({ caId });
+ if (!internalCa) {
+ throw new NotFoundError({ message: `Internal CA with caId ${caId} not found` });
+ }
+
+ if (internalCa.lastRenewalStatus === CaRenewalStatus.PENDING) {
+ throw new BadRequestError({ message: "A certificate installation is already in progress for this CA" });
+ }
+
+ await internalCertificateAuthorityDAL.updateById(internalCa.id, {
+ lastRenewalStatus: CaRenewalStatus.PENDING,
+ lastRenewalMessage: null
+ });
+
+ await queueService.queue(
+ QueueName.CaAutoRenewal,
+ QueueJobs.CaVenafiInstall,
+ { caId, maxPathLength },
+ {
+ jobId: `venafi-install-${caId}-${Date.now()}`,
+ removeOnComplete: true,
+ removeOnFail: true
+ }
+ );
+ };
+
+ queueService.listen(QueueName.CaAutoRenewal, "failed", (_, err) => {
+ logger.error(err, `${QueueName.CaAutoRenewal}: job failed`);
+ });
+
+ return { startDailyAutoRenewalJob, queueVenafiInstall };
+};
diff --git a/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-dal.ts b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-dal.ts
new file mode 100644
index 0000000000..b1bcd7b617
--- /dev/null
+++ b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-dal.ts
@@ -0,0 +1,19 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TCaSigningConfigDALFactory = ReturnType<typeof caSigningConfigDALFactory>;
+
+export const caSigningConfigDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.CaSigningConfig);
+
+ const findByCaId = async (caId: string) => {
+ const config = await db.replicaNode()(TableName.CaSigningConfig).where({ caId }).first();
+ return config;
+ };
+
+ return {
+ ...orm,
+ findByCaId
+ };
+};
diff --git a/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-enums.ts b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-enums.ts
new file mode 100644
index 0000000000..1b71e2d70c
--- /dev/null
+++ b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-enums.ts
@@ -0,0 +1,5 @@
+export enum CaSigningConfigType {
+ Internal = "internal",
+ Manual = "manual",
+ Venafi = "venafi"
+}
diff --git a/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-service.ts b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-service.ts
new file mode 100644
index 0000000000..8b28d6a41c
--- /dev/null
+++ b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-service.ts
@@ -0,0 +1,445 @@
+import { ForbiddenError, subject } from "@casl/ability";
+
+import { ActionProjectType } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionCertificateAuthorityActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+
+import { TCaAutoRenewalQueueFactory } from "../ca-auto-renewal-queue";
+import { TCertificateAuthorityDALFactory } from "../certificate-authority-dal";
+import { CaStatus, InternalCaType } from "../certificate-authority-enums";
+import { TInternalCertificateAuthorityDALFactory } from "../internal/internal-certificate-authority-dal";
+import { TCaSigningConfigDALFactory } from "./ca-signing-config-dal";
+import { CaSigningConfigType } from "./ca-signing-config-enums";
+import {
+ TCreateCaSigningConfigDTO,
+ TGetCaSigningConfigDTO,
+ TUpdateCaSigningConfigDTO,
+ TVenafiDestinationConfig,
+ VenafiDestinationConfigSchema
+} from "./ca-signing-config-types";
+
+type TCaSigningConfigServiceFactoryDep = {
+ caSigningConfigDAL: Pick<
+ TCaSigningConfigDALFactory,
+ "create" | "findByCaId" | "updateById" | "deleteById" | "findOne" | "transaction"
+ >;
+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
+ internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "findOne" | "updateById">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ caAutoRenewalQueue: Pick<TCaAutoRenewalQueueFactory, "queueVenafiInstall">;
+};
+
+export type TCaSigningConfigServiceFactory = ReturnType<typeof caSigningConfigServiceFactory>;
+
+export const caSigningConfigServiceFactory = ({
+ caSigningConfigDAL,
+ certificateAuthorityDAL,
+ internalCertificateAuthorityDAL,
+ permissionService,
+ caAutoRenewalQueue
+}: TCaSigningConfigServiceFactoryDep) => {
+ const getOrCreateLegacySigningConfig = async (internalCaId: string, caType: string, parentCaId?: string | null) => {
+ const existing = await caSigningConfigDAL.findByCaId(internalCaId);
+ if (existing) return existing;
+
+ const isRoot = caType === InternalCaType.ROOT;
+ const hasInternalParent = !!parentCaId;
+
+ if (isRoot || hasInternalParent) {
+ return caSigningConfigDAL.create({
+ caId: internalCaId,
+ type: CaSigningConfigType.Internal,
+ parentCaId: hasInternalParent ? parentCaId : undefined
+ });
+ }
+
+ return caSigningConfigDAL.create({
+ caId: internalCaId,
+ type: CaSigningConfigType.Manual
+ });
+ };
+
+ const createSigningConfig = async ({
+ caId,
+ type,
+ parentCaId,
+ appConnectionId,
+ destinationConfig,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TCreateCaSigningConfigDTO & {
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca) throw new NotFoundError({ message: `CA with ID ${caId} not found` });
+
+ 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 })
+ );
+
+ const internalCa = await internalCertificateAuthorityDAL.findOne({ caId });
+ if (!internalCa) throw new NotFoundError({ message: `Internal CA with caId ${caId} not found` });
+
+ // Root CAs can only have internal signing
+ if (internalCa.type === InternalCaType.ROOT && type !== CaSigningConfigType.Internal) {
+ throw new BadRequestError({ message: "Root CAs can only use internal signing configuration" });
+ }
+
+ // If a config already exists with a different type (e.g., auto-created "manual"), replace it
+ const existing = await caSigningConfigDAL.findByCaId(internalCa.id);
+ if (existing && existing.type === type) {
+ throw new BadRequestError({ message: "Signing configuration already exists for this CA. Use update instead." });
+ }
+
+ // Venafi requires appConnectionId and destinationConfig
+ if (type === CaSigningConfigType.Venafi) {
+ if (!appConnectionId) {
+ throw new BadRequestError({ message: "App connection ID is required for Venafi signing" });
+ }
+ if (!destinationConfig) {
+ throw new BadRequestError({ message: "Destination config is required for Venafi signing" });
+ }
+ }
+
+ const config = await caSigningConfigDAL.transaction(async (tx) => {
+ if (existing) {
+ await caSigningConfigDAL.deleteById(existing.id, tx);
+ }
+
+ return caSigningConfigDAL.create(
+ {
+ caId: internalCa.id,
+ type,
+ parentCaId: type === CaSigningConfigType.Internal ? parentCaId : undefined,
+ appConnectionId: type === CaSigningConfigType.Venafi ? appConnectionId : undefined,
+ destinationConfig: type === CaSigningConfigType.Venafi ? destinationConfig : undefined
+ },
+ tx
+ );
+ });
+
+ return { config, ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId } };
+ };
+
+ const getSigningConfig = async ({
+ caId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TGetCaSigningConfigDTO & {
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca) throw new NotFoundError({ message: `CA with ID ${caId} not found` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: ca.projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateAuthorityActions.Read,
+ subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })
+ );
+
+ const internalCa = await internalCertificateAuthorityDAL.findOne({ caId });
+ if (!internalCa) throw new NotFoundError({ message: `Internal CA with caId ${caId} not found` });
+
+ const config = await getOrCreateLegacySigningConfig(internalCa.id, internalCa.type, internalCa.parentCaId);
+
+ return { config, ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId } };
+ };
+
+ const updateSigningConfig = async ({
+ caId,
+ parentCaId,
+ appConnectionId,
+ destinationConfig,
+ lastExternalCertificateId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TUpdateCaSigningConfigDTO & {
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca) throw new NotFoundError({ message: `CA with ID ${caId} not found` });
+
+ 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 })
+ );
+
+ const internalCa = await internalCertificateAuthorityDAL.findOne({ caId });
+ if (!internalCa) throw new NotFoundError({ message: `Internal CA with caId ${caId} not found` });
+
+ const existing = await caSigningConfigDAL.findByCaId(internalCa.id);
+ if (!existing) throw new NotFoundError({ message: "No signing configuration found for this CA" });
+
+ // Type cannot be changed
+ const updateData: {
+ parentCaId?: string | null;
+ appConnectionId?: string;
+ destinationConfig?: TVenafiDestinationConfig;
+ lastExternalCertificateId?: string;
+ } = {};
+
+ if (existing.type === CaSigningConfigType.Internal && parentCaId !== undefined) {
+ updateData.parentCaId = parentCaId;
+ }
+
+ if (existing.type === CaSigningConfigType.Venafi) {
+ if (appConnectionId !== undefined) updateData.appConnectionId = appConnectionId;
+ if (destinationConfig !== undefined) updateData.destinationConfig = destinationConfig;
+ if (lastExternalCertificateId !== undefined) updateData.lastExternalCertificateId = lastExternalCertificateId;
+ }
+
+ if (Object.keys(updateData).length === 0) {
+ return { config: existing, ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId } };
+ }
+
+ const config = await caSigningConfigDAL.updateById(existing.id, updateData);
+ return { config, ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId } };
+ };
+
+ const getAutoRenewalConfig = async ({
+ caId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TGetCaSigningConfigDTO & {
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca) throw new NotFoundError({ message: `CA with ID ${caId} not found` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: ca.projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateAuthorityActions.Read,
+ subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })
+ );
+
+ const internalCa = await internalCertificateAuthorityDAL.findOne({ caId });
+ if (!internalCa) throw new NotFoundError({ message: `Internal CA with caId ${caId} not found` });
+
+ return {
+ autoRenewalEnabled: internalCa.autoRenewalEnabled ?? false,
+ autoRenewalDaysBeforeExpiry: internalCa.autoRenewalDaysBeforeExpiry ?? null,
+ lastRenewalStatus: internalCa.lastRenewalStatus ?? null,
+ lastRenewalMessage: internalCa.lastRenewalMessage ?? null,
+ lastRenewalAt: internalCa.lastRenewalAt ?? null,
+ ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId }
+ };
+ };
+
+ const updateAutoRenewalConfig = async ({
+ caId,
+ autoRenewalEnabled,
+ autoRenewalDaysBeforeExpiry,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: {
+ caId: string;
+ autoRenewalEnabled?: boolean;
+ autoRenewalDaysBeforeExpiry?: number;
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca) throw new NotFoundError({ message: `CA with ID ${caId} not found` });
+
+ 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 })
+ );
+
+ const internalCa = await internalCertificateAuthorityDAL.findOne({ caId });
+ if (!internalCa) throw new NotFoundError({ message: `Internal CA with caId ${caId} not found` });
+
+ if (autoRenewalEnabled && ca.status !== CaStatus.ACTIVE) {
+ throw new BadRequestError({ message: "CA must be active to enable auto-renewal" });
+ }
+
+ if (autoRenewalEnabled && !autoRenewalDaysBeforeExpiry && !internalCa.autoRenewalDaysBeforeExpiry) {
+ throw new BadRequestError({
+ message: "autoRenewalDaysBeforeExpiry must be provided when enabling auto-renewal"
+ });
+ }
+
+ if (autoRenewalEnabled) {
+ const signingConfig = await getOrCreateLegacySigningConfig(internalCa.id, internalCa.type, internalCa.parentCaId);
+
+ if (signingConfig.type === CaSigningConfigType.Manual) {
+ throw new BadRequestError({
+ message: "Auto-renewal cannot be enabled for CAs with manual signing configuration"
+ });
+ }
+ }
+
+ const updateData: {
+ autoRenewalEnabled?: boolean;
+ autoRenewalDaysBeforeExpiry?: number;
+ lastRenewalStatus?: string | null;
+ lastRenewalMessage?: string | null;
+ } = {};
+ if (autoRenewalEnabled !== undefined) updateData.autoRenewalEnabled = autoRenewalEnabled;
+ if (autoRenewalDaysBeforeExpiry !== undefined) updateData.autoRenewalDaysBeforeExpiry = autoRenewalDaysBeforeExpiry;
+
+ if (autoRenewalEnabled) {
+ updateData.lastRenewalStatus = null;
+ updateData.lastRenewalMessage = null;
+ }
+
+ if (Object.keys(updateData).length === 0) {
+ return {
+ autoRenewalEnabled: internalCa.autoRenewalEnabled ?? false,
+ autoRenewalDaysBeforeExpiry: internalCa.autoRenewalDaysBeforeExpiry ?? null,
+ lastRenewalStatus: internalCa.lastRenewalStatus ?? null,
+ lastRenewalMessage: internalCa.lastRenewalMessage ?? null,
+ lastRenewalAt: internalCa.lastRenewalAt ?? null,
+ ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId }
+ };
+ }
+
+ const updated = await internalCertificateAuthorityDAL.updateById(internalCa.id, updateData);
+
+ return {
+ autoRenewalEnabled: updated.autoRenewalEnabled ?? false,
+ autoRenewalDaysBeforeExpiry: updated.autoRenewalDaysBeforeExpiry ?? null,
+ lastRenewalStatus: updated.lastRenewalStatus ?? null,
+ lastRenewalMessage: updated.lastRenewalMessage ?? null,
+ lastRenewalAt: updated.lastRenewalAt ?? null,
+ ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId }
+ };
+ };
+
+ const installCertificateVenafi = async ({
+ caId,
+ maxPathLength,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: {
+ caId: string;
+ maxPathLength?: number;
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca) throw new NotFoundError({ message: `CA with ID ${caId} not found` });
+
+ 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 })
+ );
+
+ const internalCa = await internalCertificateAuthorityDAL.findOne({ caId });
+ if (!internalCa) throw new NotFoundError({ message: `Internal CA with caId ${caId} not found` });
+
+ const signingConfig = await getOrCreateLegacySigningConfig(internalCa.id, internalCa.type, internalCa.parentCaId);
+
+ if (signingConfig.type !== CaSigningConfigType.Venafi) {
+ throw new BadRequestError({ message: "CA signing config is not configured for Venafi" });
+ }
+
+ if (!signingConfig.appConnectionId) {
+ throw new BadRequestError({ message: "Venafi signing config is missing app connection" });
+ }
+
+ const parseResult = VenafiDestinationConfigSchema.safeParse(signingConfig.destinationConfig);
+ if (!parseResult.success) {
+ throw new BadRequestError({ message: "Venafi signing config has invalid or missing destination configuration" });
+ }
+
+ await caAutoRenewalQueue.queueVenafiInstall(caId, maxPathLength);
+
+ return { ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId } };
+ };
+
+ return {
+ createSigningConfig,
+ getSigningConfig,
+ updateSigningConfig,
+ getAutoRenewalConfig,
+ updateAutoRenewalConfig,
+ installCertificateVenafi
+ };
+};
diff --git a/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-types.ts b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-types.ts
new file mode 100644
index 0000000000..ec29fb2c7d
--- /dev/null
+++ b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-types.ts
@@ -0,0 +1,31 @@
+import { z } from "zod";
+
+import { CaSigningConfigType } from "./ca-signing-config-enums";
+
+export const VenafiDestinationConfigSchema = z.object({
+ applicationId: z.string().min(1),
+ issuingTemplateId: z.string().min(1),
+ validityPeriod: z.number().int().positive().optional()
+});
+
+export type TVenafiDestinationConfig = z.infer<typeof VenafiDestinationConfigSchema>;
+
+export type TCreateCaSigningConfigDTO = {
+ caId: string;
+ type: CaSigningConfigType;
+ parentCaId?: string;
+ appConnectionId?: string;
+ destinationConfig?: TVenafiDestinationConfig;
+};
+
+export type TUpdateCaSigningConfigDTO = {
+ caId: string;
+ parentCaId?: string;
+ appConnectionId?: string;
+ destinationConfig?: TVenafiDestinationConfig;
+ lastExternalCertificateId?: string;
+};
+
+export type TGetCaSigningConfigDTO = {
+ caId: string;
+};
diff --git a/backend/src/services/certificate-authority/ca-signing-config/index.ts b/backend/src/services/certificate-authority/ca-signing-config/index.ts
new file mode 100644
index 0000000000..eadd763f47
--- /dev/null
+++ b/backend/src/services/certificate-authority/ca-signing-config/index.ts
@@ -0,0 +1,4 @@
+export * from "./ca-signing-config-dal";
+export * from "./ca-signing-config-enums";
+export * from "./ca-signing-config-service";
+export * from "./ca-signing-config-types";
diff --git a/backend/src/services/certificate-authority/ca-signing-config/venafi-signing-fns.ts b/backend/src/services/certificate-authority/ca-signing-config/venafi-signing-fns.ts
new file mode 100644
index 0000000000..147243e630
--- /dev/null
+++ b/backend/src/services/certificate-authority/ca-signing-config/venafi-signing-fns.ts
@@ -0,0 +1,235 @@
+/* eslint-disable no-await-in-loop */
+import { AxiosError } from "axios";
+
+import { request } from "@app/lib/config/request";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { VenafiRegion } from "@app/services/app-connection/venafi/venafi-connection-enum";
+import { getVenafiBaseUrl, getVenafiHeaders } from "@app/services/app-connection/venafi/venafi-connection-fns";
+
+import { TVenafiDestinationConfig } from "./ca-signing-config-types";
+
+type TVenafiApiParams = {
+ apiKey: string;
+ region: VenafiRegion;
+};
+
+type TSubmitCsrToVenafiParams = TVenafiApiParams & {
+ csr: string;
+ destinationConfig: TVenafiDestinationConfig;
+};
+
+type TVenafiCertificateRequestItem = {
+ id: string;
+ certificateIds?: string[];
+ status?: string;
+ errorInformation?: {
+ type?: string;
+ code?: number;
+ message?: string;
+ args?: string[];
+ };
+};
+
+type TVenafiCertificateRequestResponse = {
+ certificateRequests: TVenafiCertificateRequestItem[];
+};
+
+const VENAFI_POLL_INTERVAL_MS = 5000;
+const VENAFI_POLL_MAX_ATTEMPTS = 60; // 5 minutes max
+
+type TVenafiErrorResponse = {
+ errors?: { code?: number; message?: string; args?: string[] }[];
+};
+
+const getVenafiErrorMessage = (error: AxiosError): string => {
+ const data = error.response?.data as TVenafiErrorResponse | undefined;
+ const errors = data?.errors;
+ if (errors && errors.length > 0 && errors[0].message) {
+ return errors[0].message;
+ }
+ return error.message || "Unknown error";
+};
+
+export const submitCsrToVenafi = async ({
+ apiKey,
+ region,
+ csr,
+ destinationConfig
+}: TSubmitCsrToVenafiParams): Promise<string> => {
+ const baseUrl = getVenafiBaseUrl(region);
+ try {
+ const { data } = await request.post<TVenafiCertificateRequestResponse>(
+ `${baseUrl}/outagedetection/v1/certificaterequests`,
+ {
+ certificateSigningRequest: csr,
+ applicationId: destinationConfig.applicationId,
+ certificateIssuingTemplateId: destinationConfig.issuingTemplateId,
+ ...(destinationConfig.validityPeriod && {
+ validityPeriod: `P${destinationConfig.validityPeriod}D`
+ })
+ },
+ {
+ headers: getVenafiHeaders(apiKey)
+ }
+ );
+
+ const certRequest = data.certificateRequests?.[0];
+ if (!certRequest?.id) {
+ throw new BadRequestError({ message: "Venafi did not return a certificate request ID" });
+ }
+ return certRequest.id;
+ } catch (error: unknown) {
+ if (error instanceof BadRequestError) throw error;
+ if (error instanceof AxiosError) {
+ throw new BadRequestError({
+ message: `Failed to submit CSR to Venafi: ${getVenafiErrorMessage(error)}`
+ });
+ }
+ throw new BadRequestError({
+ message: "Failed to submit CSR to Venafi"
+ });
+ }
+};
+
+export const checkVenafiRequestStatus = async ({
+ apiKey,
+ region,
+ requestId
+}: TVenafiApiParams & { requestId: string }): Promise<TVenafiCertificateRequestItem> => {
+ const baseUrl = getVenafiBaseUrl(region);
+
+ try {
+ const { data } = await request.get<TVenafiCertificateRequestItem>(
+ `${baseUrl}/outagedetection/v1/certificaterequests/${requestId}`,
+ {
+ headers: getVenafiHeaders(apiKey)
+ }
+ );
+
+ return data;
+ } catch (error: unknown) {
+ if (error instanceof AxiosError) {
+ throw new BadRequestError({
+ message: `Failed to check Venafi request status: ${getVenafiErrorMessage(error)}`
+ });
+ }
+ throw new BadRequestError({
+ message: "Failed to check Venafi request status"
+ });
+ }
+};
+
+export const downloadVenafiCertificate = async ({
+ apiKey,
+ region,
+ certificateId
+}: TVenafiApiParams & { certificateId: string }): Promise<string> => {
+ const baseUrl = getVenafiBaseUrl(region);
+
+ try {
+ const { data } = await request.get<string>(`${baseUrl}/outagedetection/v1/certificates/${certificateId}/contents`, {
+ params: {
+ format: "PEM",
+ chainOrder: "EE_FIRST"
+ },
+ headers: {
+ "tppl-api-key": apiKey
+ }
+ });
+
+ return data;
+ } catch (error: unknown) {
+ if (error instanceof AxiosError) {
+ throw new BadRequestError({
+ message: `Failed to download certificate from Venafi: ${getVenafiErrorMessage(error)}`
+ });
+ }
+ throw new BadRequestError({
+ message: "Failed to download certificate from Venafi"
+ });
+ }
+};
+
+export const pollVenafiCertificateIssuance = async ({
+ apiKey,
+ region,
+ requestId
+}: TVenafiApiParams & { requestId: string }): Promise<{ certificateId: string }> => {
+ for (let attempt = 0; attempt < VENAFI_POLL_MAX_ATTEMPTS; attempt += 1) {
+ const status = await checkVenafiRequestStatus({ apiKey, region, requestId });
+
+ if (status.certificateIds && status.certificateIds.length > 0) {
+ return { certificateId: status.certificateIds[0] };
+ }
+
+ if (status.status === "FAILED" || status.status === "REJECTED") {
+ const errorDetail = status.errorInformation?.message;
+ throw new BadRequestError({
+ message: errorDetail
+ ? `Venafi certificate request ${status.status.toLowerCase()}: ${errorDetail}`
+ : `Venafi certificate request ${status.status.toLowerCase()}`
+ });
+ }
+
+ logger.info(
+ `Venafi certificate request ${requestId} still pending (attempt ${attempt + 1}/${VENAFI_POLL_MAX_ATTEMPTS})`
+ );
+
+ await new Promise((resolve) => {
+ setTimeout(resolve, VENAFI_POLL_INTERVAL_MS);
+ });
+ }
+
+ throw new BadRequestError({
+ message: "Venafi certificate issuance timed out"
+ });
+};
+
+export const renewVenafiCertificate = async ({
+ apiKey,
+ region,
+ existingCertificateId,
+ csr,
+ destinationConfig
+}: TVenafiApiParams & {
+ existingCertificateId: string;
+ csr: string;
+ destinationConfig: TVenafiDestinationConfig;
+}): Promise<string> => {
+ const baseUrl = getVenafiBaseUrl(region);
+
+ try {
+ const { data } = await request.post<TVenafiCertificateRequestResponse>(
+ `${baseUrl}/outagedetection/v1/certificaterequests`,
+ {
+ certificateSigningRequest: csr,
+ applicationId: destinationConfig.applicationId,
+ certificateIssuingTemplateId: destinationConfig.issuingTemplateId,
+ existingCertificateId,
+ ...(destinationConfig.validityPeriod && {
+ validityPeriod: `P${destinationConfig.validityPeriod}D`
+ })
+ },
+ {
+ headers: getVenafiHeaders(apiKey)
+ }
+ );
+
+ const certRequest = data.certificateRequests?.[0];
+ if (!certRequest?.id) {
+ throw new BadRequestError({ message: "Venafi did not return a certificate request ID" });
+ }
+ return certRequest.id;
+ } catch (error: unknown) {
+ if (error instanceof BadRequestError) throw error;
+ if (error instanceof AxiosError) {
+ throw new BadRequestError({
+ message: `Failed to renew certificate via Venafi: ${getVenafiErrorMessage(error)}`
+ });
+ }
+ throw new BadRequestError({
+ message: "Failed to renew certificate via Venafi"
+ });
+ }
+};
diff --git a/backend/src/services/certificate-authority/certificate-authority-enums.ts b/backend/src/services/certificate-authority/certificate-authority-enums.ts
index c747eefc80..7b56dc1bb0 100644
--- a/backend/src/services/certificate-authority/certificate-authority-enums.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-enums.ts
@@ -20,6 +20,12 @@ export enum CaRenewalType {
EXISTING = "existing"
}
+export enum CaRenewalStatus {
+ PENDING = "pending",
+ SUCCESS = "success",
+ FAILED = "failed"
+}
+
export enum CaCapability {
ISSUE_CERTIFICATES = "issue-certificates",
REVOKE_CERTIFICATES = "revoke-certificates",
diff --git a/backend/src/services/certificate-authority/certificate-authority-fns.ts b/backend/src/services/certificate-authority/certificate-authority-fns.ts
index e64fa61b54..ec55ef9e36 100644
--- a/backend/src/services/certificate-authority/certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-fns.ts
@@ -2,7 +2,7 @@
import * as x509 from "@peculiar/x509";
import { crypto } from "@app/lib/crypto/cryptography";
-import { NotFoundError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { CertKeyAlgorithm, CertStatus } from "../certificate/certificate-types";
@@ -68,6 +68,64 @@ export const parseDistinguishedName = (dn: string): TDNParts => {
return parts;
};
+/**
+ * Validates that an imported certificate's subject DN and BasicConstraints
+ * match the CA's stored configuration. Collects all mismatches and throws
+ * a single error listing every discrepancy.
+ */
+export const validateImportedCertificate = (
+ certObj: x509.X509Certificate,
+ caConfig: {
+ commonName: string;
+ organization: string;
+ ou: string;
+ country: string;
+ province: string;
+ locality: string;
+ maxPathLength: number | null;
+ }
+) => {
+ const mismatches: string[] = [];
+
+ const certDn = parseDistinguishedName(certObj.subject);
+
+ const dnFieldChecks: { label: string; expected: string; actual: string | undefined }[] = [
+ { label: "Common Name (CN)", expected: caConfig.commonName, actual: certDn.commonName },
+ { label: "Organization (O)", expected: caConfig.organization, actual: certDn.organization },
+ { label: "Organizational Unit (OU)", expected: caConfig.ou, actual: certDn.ou },
+ { label: "Country (C)", expected: caConfig.country, actual: certDn.country },
+ { label: "State/Province (ST)", expected: caConfig.province, actual: certDn.province },
+ { label: "Locality (L)", expected: caConfig.locality, actual: certDn.locality }
+ ];
+
+ for (const check of dnFieldChecks) {
+ if (check.expected && check.expected !== (check.actual ?? "")) {
+ mismatches.push(`${check.label} mismatch (expected '${check.expected}', got '${check.actual || ""}')`);
+ }
+ }
+
+ const basicConstraints = certObj.getExtension(x509.BasicConstraintsExtension);
+
+ if (!basicConstraints || !basicConstraints.ca) {
+ mismatches.push("Certificate is not a CA certificate (BasicConstraints CA flag is not set)");
+ }
+
+ if (caConfig.maxPathLength !== null && caConfig.maxPathLength >= 0 && basicConstraints) {
+ const certPathLength = basicConstraints.pathLength;
+ if (certPathLength === undefined || certPathLength !== caConfig.maxPathLength) {
+ mismatches.push(
+ `Path length mismatch (expected ${caConfig.maxPathLength}, got ${certPathLength === undefined ? "unlimited" : certPathLength})`
+ );
+ }
+ }
+
+ if (mismatches.length > 0) {
+ throw new BadRequestError({
+ message: `Imported certificate does not match CA configuration: ${mismatches.join("; ")}`
+ });
+ }
+};
+
export const keyAlgorithmToAlgCfg = (keyAlgorithm: CertKeyAlgorithm) => {
switch (keyAlgorithm) {
case CertKeyAlgorithm.RSA_3072:
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 e4ea4826d9..44bf462b3b 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
@@ -55,7 +55,8 @@ import {
getCaCredentials,
keyAlgorithmToAlgCfg,
parseDistinguishedName,
- signatureAlgorithmToAlgCfg
+ signatureAlgorithmToAlgCfg,
+ validateImportedCertificate
} from "../certificate-authority-fns";
import { TCertificateAuthorityQueueFactory } from "../certificate-authority-queue";
import { TCertificateAuthoritySecretDALFactory } from "../certificate-authority-secret-dal";
@@ -513,23 +514,28 @@ export const internalCertificateAuthorityServiceFactory = ({
/**
* Return certificate signing request (CSR) made with CA with id [caId]
*/
- const getCaCsr = async ({ caId, actorId, actorAuthMethod, actor, actorOrgId }: TGetCaCsrDTO) => {
+ const getCaCsr = async (params: TGetCaCsrDTO) => {
+ const { caId, maxPathLength } = params;
+ const isInternal = "isInternal" in params && params.isInternal === true;
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
if (!ca.internalCa) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: ca.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
- });
+ if (!isInternal) {
+ const { actor, actorId, actorAuthMethod, actorOrgId } = params;
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: ca.projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionCertificateAuthorityActions.Create,
- subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })
- );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateAuthorityActions.Create,
+ subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })
+ );
+ }
if (ca.internalCa.type === InternalCaType.ROOT)
throw new BadRequestError({ message: "Root CA cannot generate CSR" });
@@ -544,6 +550,11 @@ export const internalCertificateAuthorityServiceFactory = ({
const alg = keyAlgorithmToAlgCfg(ca.internalCa.keyAlgorithm as CertKeyAlgorithm);
+ const effectivePathLength =
+ maxPathLength !== undefined && maxPathLength >= 0 ? maxPathLength : (ca.internalCa.maxPathLength ?? -1);
+ const resolvedPathLength =
+ effectivePathLength === -1 || effectivePathLength === null ? undefined : effectivePathLength;
+
const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
name: ca.internalCa.dn,
keys: {
@@ -552,13 +563,16 @@ export const internalCertificateAuthorityServiceFactory = ({
},
signingAlgorithm: alg,
extensions: [
+ new x509.BasicConstraintsExtension(true, resolvedPathLength, true),
// eslint-disable-next-line no-bitwise
new x509.KeyUsagesExtension(
x509.KeyUsageFlags.keyCertSign |
x509.KeyUsageFlags.cRLSign |
x509.KeyUsageFlags.digitalSignature |
- x509.KeyUsageFlags.keyEncipherment
- )
+ x509.KeyUsageFlags.keyEncipherment,
+ true
+ ),
+ await x509.SubjectKeyIdentifierExtension.create(caPublicKey)
],
attributes: [new x509.ChallengePasswordAttribute("password")]
});
@@ -574,26 +588,38 @@ export const internalCertificateAuthorityServiceFactory = ({
* Note 1: This CA renewal method is only applicable to CAs with internal parent CAs
* Note 2: Currently implements CA renewal with same key-pair only
*/
- const renewCaCert = async ({ caId, notAfter, actorId, actorAuthMethod, actor, actorOrgId }: TRenewCaCertDTO) => {
+ const renewCaCert = async ({
+ caId,
+ notAfter,
+ actorId,
+ actorAuthMethod,
+ actor,
+ actorOrgId,
+ ...rest
+ }: TRenewCaCertDTO) => {
+ const isInternal = "isInternal" in rest && rest.isInternal === true;
+
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
if (!ca.internalCa) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });
if (!ca.internalCa.activeCaCertId)
throw new BadRequestError({ message: "CA does not have a certificate installed" });
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: ca.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
- });
+ if (!isInternal) {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor!,
+ actorId: actorId!,
+ projectId: ca.projectId,
+ actorAuthMethod: actorAuthMethod!,
+ actorOrgId: actorOrgId!,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionCertificateAuthorityActions.IssueCACertificate,
- subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })
- );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateAuthorityActions.IssueCACertificate,
+ subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })
+ );
+ }
if (ca.status === CaStatus.DISABLED) throw new BadRequestError({ message: "CA is disabled" });
@@ -1221,6 +1247,16 @@ export const internalCertificateAuthorityServiceFactory = ({
const certObj = new x509.X509Certificate(certificate);
const maxPathLength = certObj.getExtension(x509.BasicConstraintsExtension)?.pathLength;
+ validateImportedCertificate(certObj, {
+ commonName: ca.internalCa.commonName,
+ organization: ca.internalCa.organization,
+ ou: ca.internalCa.ou,
+ country: ca.internalCa.country,
+ province: ca.internalCa.province,
+ locality: ca.internalCa.locality,
+ maxPathLength: ca.internalCa.maxPathLength ?? null
+ });
+
// validate imported certificate and certificate chain
const certificates = extractX509CertFromChain(certificateChain)?.map((cert) => new x509.X509Certificate(cert));
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 5d345b8cc8..3daa126890 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
@@ -98,14 +98,40 @@ export type TGenerateRootCaCertificateDTO = {
} & Omit<TProjectPermission, "projectId">;
export type TGetCaCsrDTO = {
- caId: string;
-} & Omit<TProjectPermission, "projectId">;
+ isInternal?: boolean;
+ maxPathLength?: number;
+} & (
+ | {
+ isInternal: true;
+ caId: string;
+ actorId?: undefined;
+ actorAuthMethod?: undefined;
+ actor?: undefined;
+ actorOrgId?: undefined;
+ }
+ | ({
+ isInternal?: false;
+ caId: string;
+ } & Omit<TProjectPermission, "projectId">)
+);
-export type TRenewCaCertDTO = {
- caId: string;
- notAfter: string;
- type: CaRenewalType;
-} & Omit<TProjectPermission, "projectId">;
+export type TRenewCaCertDTO =
+ | {
+ isInternal: true;
+ caId: string;
+ notAfter: string;
+ type?: CaRenewalType;
+ actorId?: undefined;
+ actorAuthMethod?: undefined;
+ actor?: undefined;
+ actorOrgId?: undefined;
+ }
+ | ({
+ isInternal?: false;
+ caId: string;
+ notAfter: string;
+ type: CaRenewalType;
+ } & Omit<TProjectPermission, "projectId">);
export type TGetCaCertsDTO = {
caId: string;
diff --git a/docs/api-reference/endpoints/app-connections/venafi/available.mdx b/docs/api-reference/endpoints/app-connections/venafi/available.mdx
new file mode 100644
index 0000000000..18ae1dcd33
--- /dev/null
+++ b/docs/api-reference/endpoints/app-connections/venafi/available.mdx
@@ -0,0 +1,4 @@
+---
+title: "Available"
+openapi: "GET /api/v1/app-connections/venafi/available"
+---
diff --git a/docs/api-reference/endpoints/app-connections/venafi/create.mdx b/docs/api-reference/endpoints/app-connections/venafi/create.mdx
new file mode 100644
index 0000000000..44e844d76e
--- /dev/null
+++ b/docs/api-reference/endpoints/app-connections/venafi/create.mdx
@@ -0,0 +1,6 @@
+---
+title: "Create"
+openapi: "POST /api/v1/app-connections/venafi"
+---
+
+Check out the configuration docs for [Venafi Connections](/integrations/app-connections/venafi) for a step-by-step guide.
diff --git a/docs/api-reference/endpoints/app-connections/venafi/delete.mdx b/docs/api-reference/endpoints/app-connections/venafi/delete.mdx
new file mode 100644
index 0000000000..30b9748776
--- /dev/null
+++ b/docs/api-reference/endpoints/app-connections/venafi/delete.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete"
+openapi: "DELETE /api/v1/app-connections/venafi/{connectionId}"
+---
diff --git a/docs/api-reference/endpoints/app-connections/venafi/get-by-id.mdx b/docs/api-reference/endpoints/app-connections/venafi/get-by-id.mdx
new file mode 100644
index 0000000000..aa181cb1b7
--- /dev/null
+++ b/docs/api-reference/endpoints/app-connections/venafi/get-by-id.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get by ID"
+openapi: "GET /api/v1/app-connections/venafi/{connectionId}"
+---
diff --git a/docs/api-reference/endpoints/app-connections/venafi/get-by-name.mdx b/docs/api-reference/endpoints/app-connections/venafi/get-by-name.mdx
new file mode 100644
index 0000000000..6acfad15ca
--- /dev/null
+++ b/docs/api-reference/endpoints/app-connections/venafi/get-by-name.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get by Name"
+openapi: "GET /api/v1/app-connections/venafi/connection-name/{connectionName}"
+---
diff --git a/docs/api-reference/endpoints/app-connections/venafi/list.mdx b/docs/api-reference/endpoints/app-connections/venafi/list.mdx
new file mode 100644
index 0000000000..f62e4eaaf8
--- /dev/null
+++ b/docs/api-reference/endpoints/app-connections/venafi/list.mdx
@@ -0,0 +1,4 @@
+---
+title: "List"
+openapi: "GET /api/v1/app-connections/venafi"
+---
diff --git a/docs/api-reference/endpoints/app-connections/venafi/update.mdx b/docs/api-reference/endpoints/app-connections/venafi/update.mdx
new file mode 100644
index 0000000000..5464055d57
--- /dev/null
+++ b/docs/api-reference/endpoints/app-connections/venafi/update.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update"
+openapi: "PATCH /api/v1/app-connections/venafi/{connectionId}"
+---
diff --git a/docs/api-reference/endpoints/certificate-authorities/internal/create-signing-config.mdx b/docs/api-reference/endpoints/certificate-authorities/internal/create-signing-config.mdx
new file mode 100644
index 0000000000..fe522f968e
--- /dev/null
+++ b/docs/api-reference/endpoints/certificate-authorities/internal/create-signing-config.mdx
@@ -0,0 +1,4 @@
+---
+title: "Create Signing Config"
+openapi: "POST /api/v1/cert-manager/ca/internal/{caId}/signing-config"
+---
diff --git a/docs/api-reference/endpoints/certificate-authorities/internal/get-auto-renewal.mdx b/docs/api-reference/endpoints/certificate-authorities/internal/get-auto-renewal.mdx
new file mode 100644
index 0000000000..e581f7d165
--- /dev/null
+++ b/docs/api-reference/endpoints/certificate-authorities/internal/get-auto-renewal.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get Auto-Renewal Config"
+openapi: "GET /api/v1/cert-manager/ca/internal/{caId}/auto-renewal"
+---
diff --git a/docs/api-reference/endpoints/certificate-authorities/internal/get-signing-config.mdx b/docs/api-reference/endpoints/certificate-authorities/internal/get-signing-config.mdx
new file mode 100644
index 0000000000..fc6e709c85
--- /dev/null
+++ b/docs/api-reference/endpoints/certificate-authorities/internal/get-signing-config.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get Signing Config"
+openapi: "GET /api/v1/cert-manager/ca/internal/{caId}/signing-config"
+---
diff --git a/docs/api-reference/endpoints/certificate-authorities/internal/install-cert-venafi.mdx b/docs/api-reference/endpoints/certificate-authorities/internal/install-cert-venafi.mdx
new file mode 100644
index 0000000000..c5cd891662
--- /dev/null
+++ b/docs/api-reference/endpoints/certificate-authorities/internal/install-cert-venafi.mdx
@@ -0,0 +1,4 @@
+---
+title: "Install Venafi Certificate"
+openapi: "POST /api/v1/cert-manager/ca/internal/{caId}/install-certificate-venafi"
+---
diff --git a/docs/api-reference/endpoints/certificate-authorities/internal/update-auto-renewal.mdx b/docs/api-reference/endpoints/certificate-authorities/internal/update-auto-renewal.mdx
new file mode 100644
index 0000000000..739520fc7f
--- /dev/null
+++ b/docs/api-reference/endpoints/certificate-authorities/internal/update-auto-renewal.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update Auto-Renewal Config"
+openapi: "PATCH /api/v1/cert-manager/ca/internal/{caId}/auto-renewal"
+---
diff --git a/docs/api-reference/endpoints/certificate-authorities/internal/update-signing-config.mdx b/docs/api-reference/endpoints/certificate-authorities/internal/update-signing-config.mdx
new file mode 100644
index 0000000000..bb3c59ab6c
--- /dev/null
+++ b/docs/api-reference/endpoints/certificate-authorities/internal/update-signing-config.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update Signing Config"
+openapi: "PATCH /api/v1/cert-manager/ca/internal/{caId}/signing-config"
+---
diff --git a/docs/docs.json b/docs/docs.json
index 84f21a9d9c..356ea1b3c9 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -153,6 +153,7 @@
"integrations/app-connections/supabase",
"integrations/app-connections/teamcity",
"integrations/app-connections/terraform-cloud",
+ "integrations/app-connections/venafi",
"integrations/app-connections/vercel",
"integrations/app-connections/windmill",
"integrations/app-connections/smb",
@@ -782,7 +783,8 @@
"documentation/platform/pki/ca/digicert",
"documentation/platform/pki/ca/sectigo",
"documentation/platform/pki/ca/azure-adcs",
- "documentation/platform/pki/ca/aws-pca"
+ "documentation/platform/pki/ca/aws-pca",
+ "documentation/platform/pki/ca/venafi"
]
}
]
@@ -1736,6 +1738,18 @@
"api-reference/endpoints/app-connections/terraform-cloud/delete"
]
},
+ {
+ "group": "Venafi",
+ "pages": [
+ "api-reference/endpoints/app-connections/venafi/list",
+ "api-reference/endpoints/app-connections/venafi/available",
+ "api-reference/endpoints/app-connections/venafi/get-by-id",
+ "api-reference/endpoints/app-connections/venafi/get-by-name",
+ "api-reference/endpoints/app-connections/venafi/create",
+ "api-reference/endpoints/app-connections/venafi/update",
+ "api-reference/endpoints/app-connections/venafi/delete"
+ ]
+ },
{
"group": "Vercel",
"pages": [
@@ -2783,9 +2797,30 @@
"api-reference/endpoints/certificate-authorities/internal/list-ca-certs",
"api-reference/endpoints/certificate-authorities/internal/csr",
"api-reference/endpoints/certificate-authorities/internal/cert",
- "api-reference/endpoints/certificate-authorities/internal/sign-intermediate",
- "api-reference/endpoints/certificate-authorities/internal/import-cert",
- "api-reference/endpoints/certificate-authorities/internal/crl"
+ "api-reference/endpoints/certificate-authorities/internal/crl",
+ {
+ "group": "Installation",
+ "pages": [
+ "api-reference/endpoints/certificate-authorities/internal/sign-intermediate",
+ "api-reference/endpoints/certificate-authorities/internal/import-cert",
+ "api-reference/endpoints/certificate-authorities/internal/install-cert-venafi"
+ ]
+ },
+ {
+ "group": "Signing Config",
+ "pages": [
+ "api-reference/endpoints/certificate-authorities/internal/create-signing-config",
+ "api-reference/endpoints/certificate-authorities/internal/get-signing-config",
+ "api-reference/endpoints/certificate-authorities/internal/update-signing-config"
+ ]
+ },
+ {
+ "group": "Auto-Renewal",
+ "pages": [
+ "api-reference/endpoints/certificate-authorities/internal/get-auto-renewal",
+ "api-reference/endpoints/certificate-authorities/internal/update-auto-renewal"
+ ]
+ }
]
}
]
diff --git a/docs/documentation/platform/pki/ca/external-ca.mdx b/docs/documentation/platform/pki/ca/external-ca.mdx
index c6a64b92ba..4accec1918 100644
--- a/docs/documentation/platform/pki/ca/external-ca.mdx
+++ b/docs/documentation/platform/pki/ca/external-ca.mdx
@@ -39,6 +39,7 @@ Infisical currently supports the following External CA types out of the box:
- [ACME CA](/documentation/platform/pki/ca/acme-ca): An ACME-compatible CA that supports the ACME protocol, such as Let's Encrypt, ZeroSSL, Buypass, DigiCert, Sectigo, etc.
- [Azure ADCS](/documentation/platform/pki/ca/azure-adcs): A Microsoft Active Directory Certificate Services (ADCS) that supports the ADCS protocol.
- [AWS Private CA](/documentation/platform/pki/ca/aws-pca): An AWS Private Certificate Authority (PCA) for cloud-native private certificate management.
+- [Venafi TLS Protect Cloud](/documentation/platform/pki/ca/venafi): Use Venafi TLS Protect Cloud as an external CA to sign internal intermediate CAs, with support for auto-renewal.
If you don’t see a specific external CA listed here or need a dedicated integration guide, please reach out to [email protected] and we’ll help you set up the integration for your external CA.
diff --git a/docs/documentation/platform/pki/ca/private-ca.mdx b/docs/documentation/platform/pki/ca/private-ca.mdx
index 67b38b455a..b1ae32b890 100644
--- a/docs/documentation/platform/pki/ca/private-ca.mdx
+++ b/docs/documentation/platform/pki/ca/private-ca.mdx
@@ -72,43 +72,69 @@ consisting of an (optional) root CA and an intermediate CA.
</Note>
</Step>
<Step title="Creating an intermediate CA">
- 2.1. To create an intermediate CA, press **Create CA** again but this time specifying the **CA Type** to be **Intermediate**. Fill out the details for the intermediate CA.
+ To create an intermediate CA, press **Create CA** again but this time specifying the **CA Type** to be **Intermediate**. Fill out the details for the intermediate CA.
![pki create intermediate ca](/images/platform/pki/ca/ca-create-intermediate.png)
- 2.2. Next, press the **Install Certificate** option on the intermediate CA from step 1.1.
+ Next, press the **Install Certificate** option on the intermediate CA.
![pki install cert opt](/images/platform/pki/ca/ca-install-intermediate-opt.png)
- 2.3a. If you created a root CA in step 1, select **Infisical CA** for the **Parent CA Type** field.
+ You will be presented with the installation method selector. Choose how the signing certificate for this CA should be issued:
- Next, set the **Parent CA** to the root CA created in step 1 and configure the intended **Valid Until** and **Path Length** fields on the intermediate CA; feel free to use the prefilled values.
+ ![pki install select method](/images/platform/pki/ca/ca-install-select-method.png)
- ![pki install cert](/images/platform/pki/ca/ca-install-intermediate.png)
+ <Tabs>
+ <Tab title="Infisical CA">
+ Select **Infisical CA** and press **Continue**. This option chains the intermediate CA to a root or intermediate CA managed by Infisical.
- Here's some guidance on each field:
+ Set the **Parent CA** to the root CA created in step 1 and configure the intended **Valid Until** and **Path Length** fields on the intermediate CA; feel free to use the prefilled values.
- - Parent CA: The parent CA to which this intermediate CA will be chained. In this case, it should be the root CA created in step 1.
- - Valid Until: The date until which the CA is valid in the date time string format specified [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format). The date must be within the validity period of the parent CA.
- - Path Length: The maximum number of intermediate CAs that can be chained to this CA. The path length must be less than the path length of the parent CA.
+ ![pki install infisical ca](/images/platform/pki/ca/ca-install-infisical-ca.png)
- Finally, press **Install** to chain the intermediate CA to the root CA; this creates a Certificate Signing Request (CSR) for the intermediate CA, creates an intermediate certificate using the root CA private key and CSR, and imports the signed certificate back to the intermediate CA.
+ Here's some guidance on each field:
- ![pki cas](/images/platform/pki/ca/cas.png)
+ - Parent CA: The parent CA to which this intermediate CA will be chained. In this case, it should be the root CA created in step 1.
+ - Valid Until: The date until which the CA is valid in the date time string format specified [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format). The date must be within the validity period of the parent CA.
+ - Path Length: The maximum number of intermediate CAs that can be chained to this CA. The path length must be less than the path length of the parent CA.
- Great! You've successfully created a Private CA hierarchy with a root CA and an intermediate CA. Now check out the [Certificates section](/documentation/platform/pki/certificates/overview) to learn more about how to issue X.509 certificates using the intermediate CA.
+ Press **Install** to chain the intermediate CA to the root CA. This creates a Certificate Signing Request (CSR) for the intermediate CA, creates an intermediate certificate using the root CA private key and CSR, and imports the signed certificate back to the intermediate CA.
- 2.3b. If you have an external root CA, select **External CA** for the **Parent CA Type** field.
+ ![pki cas](/images/platform/pki/ca/cas.png)
- Next, use the provided intermediate CSR to generate a certificate from your external root CA and paste the PEM-encoded certificate back into the **Certificate Body** field; the PEM-encoded external root CA certificate should be pasted under the **Certificate Chain** field.
+ You've successfully created a Private CA hierarchy with a root CA and an intermediate CA. Now check out the [Certificates section](/documentation/platform/pki/certificates/overview) to learn more about how to issue X.509 certificates using the intermediate CA.
+ </Tab>
+ <Tab title="Manual">
+ Select **Manual** and press **Continue**. This option allows you to sign the intermediate CA certificate using an external root CA that you manage outside of Infisical.
- ![pki ca csr](/images/platform/pki/ca/ca-install-intermediate-csr.png)
+ Use the provided CSR to generate a certificate from your external root CA and paste the PEM-encoded certificate back into the **Certificate Body** field; the PEM-encoded external root CA certificate should be pasted under the **Certificate Chain** field.
- Finally, press **Install** to import the certificate and certificate chain as part of the installation step for the intermediate CA
+ ![pki install manual](/images/platform/pki/ca/ca-install-manual.png)
- Great! You've successfully created a Private CA hierarchy with an intermediate CA chained to an external root CA.
- Now check out the [Certificates section](/documentation/platform/pki/certificates/overview) to learn more about how to issue X.509 certificates using the intermediate CA.
+ Press **Install** to import the certificate and certificate chain as part of the installation step for the intermediate CA.
+ You've successfully created a Private CA hierarchy with an intermediate CA chained to an external root CA.
+ Now check out the [Certificates section](/documentation/platform/pki/certificates/overview) to learn more about how to issue X.509 certificates using the intermediate CA.
+ </Tab>
+ <Tab title="External CA">
+ Select **External CA (Automated)** and press **Continue**. This option connects to a third-party CA provider to handle certificate signing and renewal automatically via API.
+
+ You will be prompted to choose a CA integration provider:
+
+ ![pki install external select](/images/platform/pki/ca/ca-install-external-select.png)
+
+ Infisical currently supports the following external CA providers for signing intermediate CAs:
+
+ - [Venafi TLS Protect Cloud](/documentation/platform/pki/ca/venafi)
+
+ <Note>
+ When using an external CA, the certificate issued by the provider **must** correspond to the CSR generated by Infisical.
+ If the external CA returns a certificate that does not match the CSR (e.g., different subject or key), the installation will fail.
+ </Note>
+
+ Refer to the provider-specific documentation linked above for detailed setup and installation instructions.
+ </Tab>
+ </Tabs>
</Step>
</Steps>
</Tab>
@@ -150,109 +176,111 @@ consisting of an (optional) root CA and an intermediate CA.
</Step>
<Step title="Creating an intermediate CA">
- 2.1. To create an intermediate CA, make an API request to the [Create CA](/api-reference/endpoints/certificate-authorities/create) API endpoint, specifying the `type` as `intermediate`.
-
+ To create an intermediate CA, make an API request to the [Create CA](/api-reference/endpoints/certificate-authorities/create) API endpoint, specifying the `type` as `intermediate`.
+
### Sample request
-
+
```bash Request
- curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal' \
- --header 'Authorization: Bearer <access-token>' \
- --header 'Content-Type: application/json' \
- --data-raw '{
+ curl --location --request POST ‘https://app.infisical.com/api/v1/cert-manager/ca/internal’ \
+ --header ‘Authorization: Bearer <access-token>’ \
+ --header ‘Content-Type: application/json’ \
+ --data-raw ‘{
"projectSlug": "<your-project-slug>",
"type": "intermediate",
"commonName": "My Intermediate CA"
- }'
- ```
-
- ### Sample response
-
- ```bash Response
- {
- ca: {
- id: "<intermediate-ca-id>",
- type: "intermediate",
- commonName: "My Intermediate CA",
- ...
- }
- }
- ```
-
- 2.2. Next, get a certificate signing request from the intermediate CA by making an API request to the [Get CSR](/api-reference/endpoints/certificate-authorities/csr) API endpoint.
-
- ### Sample request
-
- ```bash Request
- curl --location --request GET 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<intermediate-ca-id>/csr' \
- --header 'Authorization: Bearer <access-token>' \
- --data-raw ''
+ }’
```
### Sample response
- ```bash Response
+ ```json Response
{
- csr: "..."
+ "ca": {
+ "id": "<intermediate-ca-id>",
+ "type": "intermediate",
+ "commonName": "My Intermediate CA"
+ }
}
```
- If using an external root CA, then use the CSR to generate a certificate for the intermediate CA using your external root CA and skip to step 2.4.
+ Next, install a certificate for the intermediate CA using one of the following methods:
- 2.3. Next, create an intermediate certificate by making an API request to the [Sign Intermediate](/api-reference/endpoints/certificate-authorities/sign-intermediate) API endpoint
- containing the CSR from step 2.2, referencing the root CA created in step 1.
+ <Tabs>
+ <Tab title="Infisical CA">
+ Get a CSR from the intermediate CA, sign it with the root CA, and import the certificate back.
- ### Sample request
+ **Get the CSR:**
- ```bash Request
- curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<root-ca-id>/sign-intermediate' \
- --header 'Content-Type: application/json' \
- --data-raw '{
- "csr": "<csr>",
- "notAfter": "2029-06-12"
- }'
- ```
-
- ### Sample response
-
- ```bash Response
- {
- certificate: "...",
- certificateChain: "...",
- issuingCaCertificate: "...",
- serialNumber: "...",
- }
- ```
-
- <Note>
- The `notAfter` value must be within the validity period of the root CA that is if the root CA is valid until `2029-06-12`, the intermediate CA must be valid until a date before `2029-06-12`.
- </Note>
-
- 2.4. Finally, import the intermediate certificate and certificate chain from step 2.3 back to the intermediate CA by making an API request to the [Import Certificate](/api-reference/endpoints/certificate-authorities/import-cert) API endpoint.
-
- If using an external root CA, then import the generated certificate and root CA certificate under certificate chain back into the intermediate CA.
+ ```bash Request
+ curl --location --request GET ‘https://app.infisical.com/api/v1/cert-manager/ca/internal/<intermediate-ca-id>/csr’ \
+ --header ‘Authorization: Bearer <access-token>’
+ ```
- ### Sample request
+ **Sign the intermediate certificate using the root CA:**
- ```bash Request
- curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<intermediate-ca-id>/import-certificate' \
- --header 'Authorization: Bearer <access-token>' \
- --header 'Content-Type: application/json' \
- --data-raw '{
- "certificate": "<certificate>",
- "certificateChain": "<certificate-chain>"
- }'
- ```
+ ```bash Request
+ curl --location --request POST ‘https://app.infisical.com/api/v1/cert-manager/ca/internal/<root-ca-id>/sign-intermediate’ \
+ --header ‘Authorization: Bearer <access-token>’ \
+ --header ‘Content-Type: application/json’ \
+ --data-raw ‘{
+ "csr": "<csr>",
+ "notAfter": "2029-06-12"
+ }’
+ ```
- ### Sample response
+ <Note>
+ The `notAfter` value must be within the validity period of the root CA.
+ </Note>
- ```bash Response
- {
- message: "Successfully imported certificate to CA",
- caId: "..."
- }
- ```
+ **Import the signed certificate back to the intermediate CA:**
+
+ ```bash Request
+ curl --location --request POST ‘https://app.infisical.com/api/v1/cert-manager/ca/internal/<intermediate-ca-id>/import-certificate’ \
+ --header ‘Authorization: Bearer <access-token>’ \
+ --header ‘Content-Type: application/json’ \
+ --data-raw ‘{
+ "certificate": "<certificate>",
+ "certificateChain": "<certificate-chain>"
+ }’
+ ```
+
+ You’ve successfully created a Private CA hierarchy. Now check out the [Subscribers](/documentation/platform/pki/subscribers) page to learn more about issuing certificates.
+ </Tab>
+ <Tab title="Manual">
+ Get the CSR from the intermediate CA and use it to generate a certificate from your external root CA.
+
+ **Get the CSR:**
+
+ ```bash Request
+ curl --location --request GET ‘https://app.infisical.com/api/v1/cert-manager/ca/internal/<intermediate-ca-id>/csr’ \
+ --header ‘Authorization: Bearer <access-token>’
+ ```
+
+ Use this CSR with your external root CA to generate a signed certificate. Then import the certificate and chain back:
+
+ ```bash Request
+ curl --location --request POST ‘https://app.infisical.com/api/v1/cert-manager/ca/internal/<intermediate-ca-id>/import-certificate’ \
+ --header ‘Authorization: Bearer <access-token>’ \
+ --header ‘Content-Type: application/json’ \
+ --data-raw ‘{
+ "certificate": "<certificate-from-external-ca>",
+ "certificateChain": "<external-root-ca-certificate>"
+ }’
+ ```
+
+ You’ve successfully chained an intermediate CA to an external root CA. Now check out the [Subscribers](/documentation/platform/pki/subscribers) page to learn more about issuing certificates.
+ </Tab>
+ <Tab title="External CA">
+ You can use an external CA provider to automatically sign the intermediate CA certificate via API. See the provider-specific documentation for the full API workflow:
+
+ - [Venafi TLS Protect Cloud](/documentation/platform/pki/ca/venafi)
- Great! You’ve successfully created a Private CA hierarchy with a root CA and an intermediate CA. Now check out the [Subscribers](/documentation/platform/pki/subscribers) page to learn more about how to issue X.509 certificates using the intermediate CA.
+ <Note>
+ When using an external CA, the certificate issued by the provider **must** correspond to the CSR generated by Infisical.
+ If the external CA returns a certificate that does not match the CSR, the installation will fail.
+ </Note>
+ </Tab>
+ </Tabs>
</Step>
</Steps>
@@ -264,13 +292,9 @@ consisting of an (optional) root CA and an intermediate CA.
In the following steps, we explore how to renew a CA certificate.
<Note>
- If renewing an intermediate CA chained to an Infisical CA, then Infisical will
- automate the process of generating a new certificate for the intermediate CA for you.
-
-If renewing an intermediate CA chained to an external parent CA, you'll be
-required to generate a new certificate from the external parent CA and manually import
-the certificate back to the intermediate CA.
-
+ - If renewing an intermediate CA chained to an **Infisical CA**, Infisical will automate the process of generating a new certificate for you.
+ - If renewing an intermediate CA signed by an **external CA provider** (e.g., Venafi), you can configure [auto-renewal](/documentation/platform/pki/ca/venafi#auto-renewal) to automate the process.
+ - If renewing an intermediate CA chained to an **external parent CA via manual import**, you'll need to generate a new certificate from the external parent CA and manually import it back.
</Note>
<Tabs>
@@ -326,9 +350,7 @@ the certificate back to the intermediate CA.
anticipate supporting CA renewal via new key pair in the coming month.
</Accordion>
<Accordion title="Does Infisical support chaining an Intermediate CA to an external CA?">
- Yes. You may obtain a CSR from the Intermediate CA and use it to generate a
- certificate from your external CA. The certificate, along with the external
- CA certificate chain, can be imported back to the Intermediate CA as part of
- the CA installation step.
+ Yes. You can either manually obtain a CSR and import the signed certificate, or use an integrated external CA provider
+ like [Venafi TLS Protect Cloud](/documentation/platform/pki/ca/venafi) to automate the signing process.
</Accordion>
</AccordionGroup>
diff --git a/docs/documentation/platform/pki/ca/venafi.mdx b/docs/documentation/platform/pki/ca/venafi.mdx
new file mode 100644
index 0000000000..baf0be7213
--- /dev/null
+++ b/docs/documentation/platform/pki/ca/venafi.mdx
@@ -0,0 +1,302 @@
+---
+title: "Venafi TLS Protect Cloud"
+sidebarTitle: "Venafi"
+description: "Learn how to use Venafi TLS Protect Cloud as an external CA to sign internal intermediate CAs in Infisical."
+---
+
+## Concept
+
+Infisical can use Venafi TLS Protect Cloud as an external Certificate Authority to sign your internal intermediate CAs. This allows you to leverage Venafi's cloud-based PKI infrastructure while managing your CA hierarchy within Infisical.
+
+The flow works as follows:
+
+<div align="center">
+
+```mermaid
+sequenceDiagram
+ participant Infisical
+ participant Venafi as Venafi TLS Protect Cloud
+
+ Infisical->>Infisical: Generate CSR for Intermediate CA
+ Infisical->>Venafi: Submit CSR via API
+ Venafi->>Venafi: Sign certificate using Issuing Template
+ Venafi-->>Infisical: Return signed certificate + chain
+ Infisical->>Infisical: Import certificate to Intermediate CA
+```
+
+</div>
+
+1. Infisical generates a Certificate Signing Request (CSR) for the intermediate CA.
+2. The CSR is submitted to Venafi TLS Protect Cloud via the configured Application and Issuing Template.
+3. Venafi signs the certificate and returns it along with the certificate chain.
+4. Infisical imports the signed certificate back into the intermediate CA.
+
+<Warning>
+ The certificate issued by Venafi **must** correspond to the CSR generated by Infisical.
+ If the Issuing Template in Venafi is misconfigured and produces a certificate that does not match the CSR
+ (e.g., different subject, different key), the installation will fail.
+
+ Ensure your Venafi Issuing Template is configured to honor the CSR's subject fields and key.
+</Warning>
+
+## Prerequisites
+
+- A [Venafi Connection](/integrations/app-connections/venafi) configured in your organization
+- A Venafi Application with an Issuing Template that supports CA certificate issuance
+- An intermediate CA created in Infisical (not yet installed)
+
+## Guide to Installing an Intermediate CA via Venafi
+
+<Tabs>
+ <Tab title="Infisical UI">
+ <Steps>
+ <Step title="Create an Intermediate CA">
+ If you haven't already, head to your Certificate Management Project > Certificate Authorities > Internal Certificate Authorities and press **Create CA**.
+
+ Set the **CA Type** to **Intermediate** and fill out the details for the intermediate CA (Common Name, Organization, Key Algorithm, etc.).
+ </Step>
+ <Step title="Open the Install Certificate Modal">
+ Press the **Install Certificate** option on the intermediate CA you just created. Select **External CA (Automated)** and press **Continue**.
+
+ ![pki install select method](/images/platform/pki/ca/ca-install-select-method.png)
+ </Step>
+ <Step title="Select Venafi TLS Protect Cloud">
+ Choose **Venafi TLS Protect Cloud** as the CA integration provider and press **Continue**.
+
+ ![pki install external select](/images/platform/pki/ca/ca-install-external-select.png)
+ </Step>
+ <Step title="Configure the Venafi Signing Details">
+ Fill out the following fields:
+
+ ![pki install venafi form](/images/platform/pki/ca/ca-install-venafi.png)
+
+ - **Venafi Connection**: Select the Venafi Connection to use for signing.
+ - **Application**: Select the Venafi Application that contains the Issuing Template for CA certificate issuance.
+ - **Issuing Template**: Select the Issuing Template within the Application that will be used to sign the intermediate CA certificate.
+ - **Validity Period (Days)**: The number of days the certificate should be valid. This is optional and depends on your Issuing Template configuration.
+ - **Path Length**: The maximum number of intermediate CAs that can be chained below this CA. Use `-1` for no limit, or `0` to prevent further chaining.
+ </Step>
+ <Step title="Install the Certificate">
+ Press **Install** to submit the CSR to Venafi and import the signed certificate.
+
+ <Note>
+ The installation is processed asynchronously. After clicking Install, the certificate request is queued
+ and you will see the CA status update once the certificate has been signed and imported.
+ </Note>
+ </Step>
+ </Steps>
+ </Tab>
+ <Tab title="API">
+ <Steps>
+ <Step title="Create an Intermediate CA">
+ If you haven't already, create an intermediate CA by making an API request to the [Create CA](/api-reference/endpoints/certificate-authorities/create) API endpoint.
+
+ ### Sample request
+
+ ```bash Request
+ curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "projectSlug": "<your-project-slug>",
+ "type": "intermediate",
+ "commonName": "My Intermediate CA"
+ }'
+ ```
+
+ ### Sample response
+
+ ```json Response
+ {
+ "ca": {
+ "id": "<intermediate-ca-id>",
+ "type": "intermediate",
+ "commonName": "My Intermediate CA"
+ }
+ }
+ ```
+ </Step>
+ <Step title="Create a Venafi Signing Configuration">
+ Create a signing configuration for the intermediate CA that points to your Venafi Connection and Application.
+
+ ### Sample request
+
+ ```bash Request
+ curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<intermediate-ca-id>/signing-config' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "type": "venafi",
+ "appConnectionId": "<venafi-connection-id>",
+ "destinationConfig": {
+ "applicationId": "<venafi-application-id>",
+ "issuingTemplateId": "<venafi-issuing-template-id>",
+ "validityPeriod": 365
+ }
+ }'
+ ```
+
+ ### Sample response
+
+ ```json Response
+ {
+ "signingConfig": {
+ "id": "...",
+ "caId": "<intermediate-ca-id>",
+ "type": "venafi",
+ "appConnectionId": "<venafi-connection-id>",
+ "destinationConfig": {
+ "applicationId": "<venafi-application-id>",
+ "issuingTemplateId": "<venafi-issuing-template-id>",
+ "validityPeriod": 365
+ }
+ }
+ }
+ ```
+
+ <Note>
+ - `type` must be `"venafi"`
+ - `appConnectionId` is the ID of your Venafi Connection
+ - `destinationConfig.applicationId` is the ID of the Venafi Application
+ - `destinationConfig.issuingTemplateId` is the ID of the Issuing Template
+ - `destinationConfig.validityPeriod` is optional, specified in days
+ </Note>
+ </Step>
+ <Step title="Install the Certificate via Venafi">
+ Trigger the certificate installation by submitting the CSR to Venafi.
+
+ ### Sample request
+
+ ```bash Request
+ curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<intermediate-ca-id>/install-certificate-venafi' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "maxPathLength": -1
+ }'
+ ```
+
+ ### Sample response
+
+ ```json Response
+ {
+ "message": "Successfully queued certificate installation via Venafi",
+ "caId": "<intermediate-ca-id>"
+ }
+ ```
+
+ <Note>
+ The installation is processed asynchronously. The response returns HTTP 202 (Accepted) to indicate the request has been queued.
+ Poll the CA details endpoint to check when the certificate has been installed.
+ </Note>
+ </Step>
+ </Steps>
+ </Tab>
+</Tabs>
+
+## Auto-Renewal
+
+Infisical supports automatic renewal of intermediate CA certificates signed by Venafi. When enabled, Infisical will automatically submit a new CSR to Venafi and import the renewed certificate before the current one expires.
+
+<Tabs>
+ <Tab title="Infisical UI">
+ Navigate to the CA details page of your Venafi-signed intermediate CA. Click the **edit** (pencil) icon in the Details section to open the renewal settings.
+
+ ![pki venafi auto-renewal page](/images/platform/pki/ca/ca-venafi-auto-renewal-page.png)
+
+ Toggle **Auto-Renewal** on and set the **Days Before Expiry** to configure when the renewal should be triggered.
+
+ ![pki venafi auto-renewal modal](/images/platform/pki/ca/ca-venafi-auto-renewal-modal.png)
+ </Tab>
+ <Tab title="API">
+ ### Enable Auto-Renewal
+
+ ```bash Request
+ curl --location --request PATCH 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<intermediate-ca-id>/auto-renewal' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "autoRenewalEnabled": true,
+ "autoRenewalDaysBeforeExpiry": 30
+ }'
+ ```
+
+ ### Sample response
+
+ ```json Response
+ {
+ "autoRenewalEnabled": true,
+ "autoRenewalDaysBeforeExpiry": 30,
+ "lastRenewalStatus": null,
+ "lastRenewalMessage": null,
+ "lastRenewalAt": null
+ }
+ ```
+
+ <Note>
+ - `autoRenewalDaysBeforeExpiry` must be between 1 and 365 days
+ - Auto-renewal is only available for CAs with an external signing configuration (e.g., Venafi)
+ - The renewal status can be checked via the GET auto-renewal endpoint
+ </Note>
+ </Tab>
+</Tabs>
+
+## Manual Renewal
+
+You can also manually trigger a renewal for a Venafi-signed intermediate CA at any time.
+
+<Tabs>
+ <Tab title="Infisical UI">
+ Navigate to the CA details page and press the **Renew CA** button.
+
+ ![pki venafi renew page](/images/platform/pki/ca/ca-venafi-renew-page.png)
+
+ The renewal modal will confirm that this CA is configured to use Venafi TLS Protect Cloud for signing. Press **Renew via Venafi** to submit a new CSR to Venafi and install the renewed certificate.
+
+ ![pki venafi renew modal](/images/platform/pki/ca/ca-venafi-renew-modal.png)
+ </Tab>
+ <Tab title="API">
+ To manually renew a Venafi-signed CA, make an API request to the [Renew CA](/api-reference/endpoints/certificate-authorities/internal/renew) API endpoint.
+
+ ```bash Request
+ curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<intermediate-ca-id>/renew' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "type": "existing"
+ }'
+ ```
+
+ For Venafi-signed CAs, Infisical will automatically submit the CSR to Venafi and import the renewed certificate.
+ </Tab>
+</Tabs>
+
+## Signing Configuration Management
+
+You can view and update the signing configuration for a Venafi-signed CA at any time:
+
+- **GET** `/:caId/signing-config` — Retrieve the current signing configuration
+- **PATCH** `/:caId/signing-config` — Update the Venafi connection, application, issuing template, or validity period
+
+Updating the signing configuration does not affect the currently installed certificate. Changes take effect on the next installation or renewal.
+
+## FAQ
+
+<AccordionGroup>
+ <Accordion title="What happens if Venafi issues a certificate that doesn't match the CSR?">
+ The installation will fail. Infisical validates that the returned certificate matches the CSR's public key.
+ Check your Venafi Issuing Template configuration to ensure it honors the CSR's subject fields and key algorithm.
+ </Accordion>
+ <Accordion title="Can I switch from Venafi signing to Infisical CA signing?">
+ Yes. You can update the signing configuration to change the type. Create a new signing configuration with `type: "internal"` and specify the parent CA.
+ Then renew or reinstall the intermediate CA certificate.
+ </Accordion>
+ <Accordion title="What Venafi regions are supported?">
+ Infisical supports the following Venafi TLS Protect Cloud regions: US, EU, AU, UK, SG, and CA.
+ Select the region that matches your Venafi instance when creating the connection.
+ </Accordion>
+ <Accordion title="Is the certificate installation synchronous or asynchronous?">
+ The installation is asynchronous. When you trigger the installation, the request is queued and processed in the background.
+ The API returns HTTP 202 (Accepted) immediately. You can monitor the CA status to check when the certificate has been installed.
+ </Accordion>
+</AccordionGroup>
diff --git a/docs/images/platform/pki/ca/ca-install-external-select.png b/docs/images/platform/pki/ca/ca-install-external-select.png
new file mode 100644
index 0000000000..9f6fc9f5aa
Binary files /dev/null and b/docs/images/platform/pki/ca/ca-install-external-select.png differ
diff --git a/docs/images/platform/pki/ca/ca-install-infisical-ca.png b/docs/images/platform/pki/ca/ca-install-infisical-ca.png
new file mode 100644
index 0000000000..83e46e0056
Binary files /dev/null and b/docs/images/platform/pki/ca/ca-install-infisical-ca.png differ
diff --git a/docs/images/platform/pki/ca/ca-install-manual.png b/docs/images/platform/pki/ca/ca-install-manual.png
new file mode 100644
index 0000000000..05a7df6e07
Binary files /dev/null and b/docs/images/platform/pki/ca/ca-install-manual.png differ
diff --git a/docs/images/platform/pki/ca/ca-install-select-method.png b/docs/images/platform/pki/ca/ca-install-select-method.png
new file mode 100644
index 0000000000..be9333f05e
Binary files /dev/null and b/docs/images/platform/pki/ca/ca-install-select-method.png differ
diff --git a/docs/images/platform/pki/ca/ca-install-venafi.png b/docs/images/platform/pki/ca/ca-install-venafi.png
new file mode 100644
index 0000000000..05f30c4452
Binary files /dev/null and b/docs/images/platform/pki/ca/ca-install-venafi.png differ
diff --git a/docs/images/platform/pki/ca/ca-venafi-auto-renewal-modal.png b/docs/images/platform/pki/ca/ca-venafi-auto-renewal-modal.png
new file mode 100644
index 0000000000..f460f30ab6
Binary files /dev/null and b/docs/images/platform/pki/ca/ca-venafi-auto-renewal-modal.png differ
diff --git a/docs/images/platform/pki/ca/ca-venafi-auto-renewal-page.png b/docs/images/platform/pki/ca/ca-venafi-auto-renewal-page.png
new file mode 100644
index 0000000000..9464a70ab5
Binary files /dev/null and b/docs/images/platform/pki/ca/ca-venafi-auto-renewal-page.png differ
diff --git a/docs/images/platform/pki/ca/ca-venafi-renew-modal.png b/docs/images/platform/pki/ca/ca-venafi-renew-modal.png
new file mode 100644
index 0000000000..c66d010ed8
Binary files /dev/null and b/docs/images/platform/pki/ca/ca-venafi-renew-modal.png differ
diff --git a/docs/images/platform/pki/ca/ca-venafi-renew-page.png b/docs/images/platform/pki/ca/ca-venafi-renew-page.png
new file mode 100644
index 0000000000..4460d9725f
Binary files /dev/null and b/docs/images/platform/pki/ca/ca-venafi-renew-page.png differ
diff --git a/docs/integrations/app-connections/venafi.mdx b/docs/integrations/app-connections/venafi.mdx
new file mode 100644
index 0000000000..c464066957
--- /dev/null
+++ b/docs/integrations/app-connections/venafi.mdx
@@ -0,0 +1,47 @@
+---
+title: "Venafi Connection"
+description: "Learn how to configure a Venafi TLS Protect Cloud Connection for Infisical."
+---
+
+Connect Infisical to Venafi TLS Protect Cloud to use Venafi as an external CA for signing internal intermediate certificate authorities.
+
+## Prerequisites
+
+- A [Venafi TLS Protect Cloud](https://venafi.com/) account
+- An API key generated from your Venafi TLS Protect Cloud dashboard
+
+## Connection Setup
+
+<Steps>
+ <Step title="Navigate to App Connections">
+ Navigate to the **App Connections** tab on the **Organization Settings** page.
+ ![App Connections Tab](/images/app-connections/general/add-connection.png)
+ </Step>
+ <Step title="Add Connection">
+ Select the **Venafi TLS Protect Cloud** option from the connection options modal.
+ </Step>
+ <Step title="Configure Connection Details">
+ Configure the following fields:
+
+ - **Name**: A friendly name for this Venafi connection (e.g., "Production Venafi")
+ - **Method**: The authentication method. Currently only **API Key** is supported.
+ - **Region**: The region of your Venafi TLS Protect Cloud instance. Supported regions:
+ - US (United States)
+ - EU (Europe)
+ - AU (Australia)
+ - UK (United Kingdom)
+ - SG (Singapore)
+ - CA (Canada)
+ - **API Key**: The API key from your Venafi TLS Protect Cloud dashboard
+
+ Click **Connect to Venafi** to validate your credentials and create the connection.
+
+ <Note>
+ Infisical validates the API key by connecting to the Venafi TLS Protect Cloud API during connection creation.
+ If the validation fails, check that your API key is correct and that you have selected the right region.
+ </Note>
+ </Step>
+ <Step title="Connection Created">
+ Your **Venafi Connection** is now available for use with internal intermediate CAs in your Infisical projects.
+ </Step>
+</Steps>
diff --git a/frontend/public/images/integrations/Venafi.png b/frontend/public/images/integrations/Venafi.png
new file mode 100644
index 0000000000..527cafb7cc
Binary files /dev/null and b/frontend/public/images/integrations/Venafi.png differ
diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.ts
index 3ccf7dfc4a..ddbe66464b 100644
--- a/frontend/src/helpers/appConnections.ts
+++ b/frontend/src/helpers/appConnections.ts
@@ -66,6 +66,7 @@ import { RenderConnectionMethod } from "@app/hooks/api/appConnections/types/rend
import { SmbConnectionMethod } from "@app/hooks/api/appConnections/types/smb-connection";
import { SshConnectionMethod } from "@app/hooks/api/appConnections/types/ssh-connection";
import { SupabaseConnectionMethod } from "@app/hooks/api/appConnections/types/supabase-connection";
+import { VenafiConnectionMethod } from "@app/hooks/api/appConnections/types/venafi-connection";
export const APP_CONNECTION_MAP: Record<
AppConnection,
@@ -150,7 +151,8 @@ export const APP_CONNECTION_MAP: Record<
[AppConnection.Dbt]: { name: "DBT", image: "DBT.png" },
[AppConnection.SMB]: { name: "SMB", image: "SMB.png", size: 50 },
[AppConnection.OpenRouter]: { name: "OpenRouter", image: "OpenRouter.png" },
- [AppConnection.CircleCI]: { name: "CircleCI", image: "CircleCI.png" }
+ [AppConnection.CircleCI]: { name: "CircleCI", image: "CircleCI.png" },
+ [AppConnection.Venafi]: { name: "Venafi TLS Protect Cloud", image: "Venafi.png" }
};
export const getAppConnectionMethodDetails = (method: TAppConnection["method"]) => {
@@ -192,7 +194,8 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"])
case LaravelForgeConnectionMethod.ApiToken:
case DbtConnectionMethod.ApiToken:
case CircleCIConnectionMethod.ApiToken:
- return { name: "API Token", icon: faKey };
+ case VenafiConnectionMethod.ApiKey:
+ return { name: "API Key", icon: faKey };
case PostgresConnectionMethod.UsernameAndPassword:
case MsSqlConnectionMethod.UsernameAndPassword:
case MySqlConnectionMethod.UsernameAndPassword:
diff --git a/frontend/src/hooks/api/appConnections/enums.ts b/frontend/src/hooks/api/appConnections/enums.ts
index c7f18ec549..3bfec6fe40 100644
--- a/frontend/src/hooks/api/appConnections/enums.ts
+++ b/frontend/src/hooks/api/appConnections/enums.ts
@@ -49,5 +49,6 @@ export enum AppConnection {
Dbt = "dbt",
SMB = "smb",
OpenRouter = "open-router",
- CircleCI = "circleci"
+ CircleCI = "circleci",
+ Venafi = "venafi"
}
diff --git a/frontend/src/hooks/api/appConnections/types/app-options.ts b/frontend/src/hooks/api/appConnections/types/app-options.ts
index ff400e8c44..d053d4003d 100644
--- a/frontend/src/hooks/api/appConnections/types/app-options.ts
+++ b/frontend/src/hooks/api/appConnections/types/app-options.ts
@@ -220,6 +220,10 @@ export type TCircleCISyncConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.CircleCI;
};
+export type TVenafiConnectionOption = TAppConnectionOptionBase & {
+ app: AppConnection.Venafi;
+};
+
export type TAppConnectionOption =
| TAwsConnectionOption
| TGitHubConnectionOption
@@ -271,7 +275,8 @@ export type TAppConnectionOption =
| TOctopusDeployConnectionOption
| TSshConnectionOption
| TDbtConnectionOption
- | TSmbConnectionOption;
+ | TSmbConnectionOption
+ | TVenafiConnectionOption;
export type TAppConnectionOptionMap = {
[AppConnection.AWS]: TAwsConnectionOption;
@@ -325,4 +330,5 @@ export type TAppConnectionOptionMap = {
[AppConnection.Dbt]: TDbtConnectionOption;
[AppConnection.SMB]: TSmbConnectionOption;
[AppConnection.CircleCI]: TCircleCISyncConnectionOption;
+ [AppConnection.Venafi]: TVenafiConnectionOption;
};
diff --git a/frontend/src/hooks/api/appConnections/types/index.ts b/frontend/src/hooks/api/appConnections/types/index.ts
index 1ab14c83da..9e481fd070 100644
--- a/frontend/src/hooks/api/appConnections/types/index.ts
+++ b/frontend/src/hooks/api/appConnections/types/index.ts
@@ -48,6 +48,7 @@ import { TSshConnection } from "./ssh-connection";
import { TSupabaseConnection } from "./supabase-connection";
import { TTeamCityConnection } from "./teamcity-connection";
import { TTerraformCloudConnection } from "./terraform-cloud-connection";
+import { TVenafiConnection } from "./venafi-connection";
import { TVercelConnection } from "./vercel-connection";
import { TWindmillConnection } from "./windmill-connection";
import { TZabbixConnection } from "./zabbix-connection";
@@ -99,6 +100,7 @@ export * from "./ssh-connection";
export * from "./supabase-connection";
export * from "./teamcity-connection";
export * from "./terraform-cloud-connection";
+export * from "./venafi-connection";
export * from "./vercel-connection";
export * from "./windmill-connection";
export * from "./zabbix-connection";
@@ -154,7 +156,8 @@ export type TAppConnection =
| TDbtConnection
| TSmbConnection
| TOpenRouterConnection
- | TCircleCIConnection;
+ | TCircleCIConnection
+ | TVenafiConnection;
export type TAvailableAppConnection = Pick<TAppConnection, "name" | "id" | "projectId">;
diff --git a/frontend/src/hooks/api/appConnections/types/venafi-connection.ts b/frontend/src/hooks/api/appConnections/types/venafi-connection.ts
new file mode 100644
index 0000000000..581b4d9d4d
--- /dev/null
+++ b/frontend/src/hooks/api/appConnections/types/venafi-connection.ts
@@ -0,0 +1,32 @@
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { TRootAppConnection } from "@app/hooks/api/appConnections/types/root-connection";
+
+export enum VenafiConnectionMethod {
+ ApiKey = "api-key"
+}
+
+export enum VenafiRegion {
+ US = "us",
+ EU = "eu",
+ AU = "au",
+ UK = "uk",
+ SG = "sg",
+ CA = "ca"
+}
+
+export const VENAFI_REGION_LABELS: Record<VenafiRegion, string> = {
+ [VenafiRegion.US]: "US",
+ [VenafiRegion.EU]: "EU",
+ [VenafiRegion.AU]: "Australia",
+ [VenafiRegion.UK]: "UK",
+ [VenafiRegion.SG]: "Singapore",
+ [VenafiRegion.CA]: "Canada"
+};
+
+export type TVenafiConnection = TRootAppConnection & { app: AppConnection.Venafi } & {
+ method: VenafiConnectionMethod.ApiKey;
+ credentials: {
+ apiKey: string;
+ region: VenafiRegion;
+ };
+};
diff --git a/frontend/src/hooks/api/appConnections/venafi/index.ts b/frontend/src/hooks/api/appConnections/venafi/index.ts
new file mode 100644
index 0000000000..2c1906d369
--- /dev/null
+++ b/frontend/src/hooks/api/appConnections/venafi/index.ts
@@ -0,0 +1,2 @@
+export * from "./queries";
+export * from "./types";
diff --git a/frontend/src/hooks/api/appConnections/venafi/queries.tsx b/frontend/src/hooks/api/appConnections/venafi/queries.tsx
new file mode 100644
index 0000000000..b4bf8f7828
--- /dev/null
+++ b/frontend/src/hooks/api/appConnections/venafi/queries.tsx
@@ -0,0 +1,66 @@
+import { useQuery, UseQueryOptions } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { appConnectionKeys } from "../queries";
+import { TVenafiApplication, TVenafiIssuingTemplate } from "./types";
+
+const venafiConnectionKeys = {
+ all: [...appConnectionKeys.all, "venafi"] as const,
+ listApplications: (connectionId: string) =>
+ [...venafiConnectionKeys.all, "applications", connectionId] as const,
+ listIssuingTemplates: (connectionId: string, applicationId: string) =>
+ [...venafiConnectionKeys.all, "issuing-templates", connectionId, applicationId] as const
+};
+
+export const useVenafiConnectionListApplications = (
+ connectionId: string,
+ options?: Omit<
+ UseQueryOptions<
+ TVenafiApplication[],
+ unknown,
+ TVenafiApplication[],
+ ReturnType<typeof venafiConnectionKeys.listApplications>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: venafiConnectionKeys.listApplications(connectionId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TVenafiApplication[]>(
+ `/api/v1/app-connections/venafi/${connectionId}/venafi-applications`
+ );
+
+ return data;
+ },
+ ...options
+ });
+};
+
+export const useVenafiConnectionListIssuingTemplates = (
+ connectionId: string,
+ applicationId: string,
+ options?: Omit<
+ UseQueryOptions<
+ TVenafiIssuingTemplate[],
+ unknown,
+ TVenafiIssuingTemplate[],
+ ReturnType<typeof venafiConnectionKeys.listIssuingTemplates>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: venafiConnectionKeys.listIssuingTemplates(connectionId, applicationId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TVenafiIssuingTemplate[]>(
+ `/api/v1/app-connections/venafi/${connectionId}/venafi-issuing-templates`,
+ { params: { applicationId } }
+ );
+
+ return data;
+ },
+ ...options
+ });
+};
diff --git a/frontend/src/hooks/api/appConnections/venafi/types.ts b/frontend/src/hooks/api/appConnections/venafi/types.ts
new file mode 100644
index 0000000000..c574e4d28c
--- /dev/null
+++ b/frontend/src/hooks/api/appConnections/venafi/types.ts
@@ -0,0 +1,9 @@
+export type TVenafiApplication = {
+ id: string;
+ name: string;
+};
+
+export type TVenafiIssuingTemplate = {
+ id: string;
+ name: string;
+};
diff --git a/frontend/src/hooks/api/ca/enums.tsx b/frontend/src/hooks/api/ca/enums.tsx
index b7900b486a..869bfc6fe3 100644
--- a/frontend/src/hooks/api/ca/enums.tsx
+++ b/frontend/src/hooks/api/ca/enums.tsx
@@ -27,8 +27,20 @@ export enum AcmeDnsProvider {
AzureDNS = "azure-dns"
}
+export enum CaRenewalStatus {
+ PENDING = "pending",
+ SUCCESS = "success",
+ FAILED = "failed"
+}
+
export enum CaCapability {
ISSUE_CERTIFICATES = "issue-certificates",
REVOKE_CERTIFICATES = "revoke-certificates",
RENEW_CERTIFICATES = "renew-certificates"
}
+
+export enum CaSigningConfigType {
+ INTERNAL = "internal",
+ MANUAL = "manual",
+ VENAFI = "venafi"
+}
diff --git a/frontend/src/hooks/api/ca/index.tsx b/frontend/src/hooks/api/ca/index.tsx
index e3a1851a44..a2ff2994c4 100644
--- a/frontend/src/hooks/api/ca/index.tsx
+++ b/frontend/src/hooks/api/ca/index.tsx
@@ -1,24 +1,39 @@
-export { AcmeDnsProvider, CaRenewalType, CaStatus, CaType, InternalCaType } from "./enums";
+export {
+ AcmeDnsProvider,
+ CaRenewalStatus,
+ CaRenewalType,
+ CaSigningConfigType,
+ CaStatus,
+ CaType,
+ InternalCaType
+} from "./enums";
export {
useCreateCa,
+ useCreateCaSigningConfig,
useCreateCertificate,
useCreateCertificateV3,
useDeleteCa,
useGenerateCaCertificate,
useImportCaCertificate,
+ useInstallCaCertificateVenafi,
useOrderCertificateWithProfile,
useRenewCa,
useSignIntermediate,
- useUpdateCa
+ useUpdateCa,
+ useUpdateCaAutoRenewal,
+ useUpdateCaSigningConfig
} from "./mutations";
+export type { TCaAutoRenewalConfig, TCaSigningConfig } from "./queries";
export {
useGetAzureAdcsTemplates,
useGetCa,
+ useGetCaAutoRenewal,
useGetCaCert,
useGetCaCerts,
useGetCaCertTemplates,
useGetCaCrls,
useGetCaCsr,
+ useGetCaSigningConfig,
useGetInternalCaById,
useListCasByProjectId,
useListCasByTypeAndProjectId,
diff --git a/frontend/src/hooks/api/ca/mutations.tsx b/frontend/src/hooks/api/ca/mutations.tsx
index cc8adf4679..e9abf72f49 100644
--- a/frontend/src/hooks/api/ca/mutations.tsx
+++ b/frontend/src/hooks/api/ca/mutations.tsx
@@ -3,7 +3,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { projectKeys } from "../projects";
-import { CaType } from "./enums";
+import { CaRenewalStatus, CaType } from "./enums";
import { caKeys } from "./queries";
import {
TCreateCertificateAuthorityDTO,
@@ -214,6 +214,123 @@ export const useRenewCa = () => {
});
};
+export const useInstallCaCertificateVenafi = (projectId: string) => {
+ const queryClient = useQueryClient();
+ return useMutation<
+ { message: string; caId: string },
+ object,
+ { caId: string; maxPathLength?: number }
+ >({
+ mutationFn: async ({ caId, ...body }) => {
+ const { data } = await apiRequest.post<{ message: string; caId: string }>(
+ `/api/v1/cert-manager/ca/internal/${caId}/install-certificate-venafi`,
+ body
+ );
+ return data;
+ },
+ onSuccess: (_, { caId }) => {
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaAutoRenewal(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaSigningConfig(caId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectCas({ projectId }) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaById(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
+ queryClient.invalidateQueries({
+ queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL, projectId)
+ });
+ }
+ });
+};
+
+export const useCreateCaSigningConfig = () => {
+ const queryClient = useQueryClient();
+ return useMutation<
+ unknown,
+ object,
+ {
+ caId: string;
+ type: string;
+ parentCaId?: string;
+ appConnectionId?: string;
+ destinationConfig?: {
+ applicationId: string;
+ issuingTemplateId: string;
+ validityPeriod?: number;
+ };
+ }
+ >({
+ mutationFn: async ({ caId, ...body }) => {
+ const { data } = await apiRequest.post(
+ `/api/v1/cert-manager/ca/internal/${caId}/signing-config`,
+ body
+ );
+ return data;
+ },
+ onSuccess: (_, { caId }) => {
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaSigningConfig(caId) });
+ }
+ });
+};
+
+export const useUpdateCaSigningConfig = () => {
+ const queryClient = useQueryClient();
+ return useMutation<
+ unknown,
+ object,
+ {
+ caId: string;
+ appConnectionId?: string;
+ destinationConfig?: {
+ applicationId: string;
+ issuingTemplateId: string;
+ validityPeriod?: number;
+ };
+ }
+ >({
+ mutationFn: async ({ caId, ...body }) => {
+ const { data } = await apiRequest.patch(
+ `/api/v1/cert-manager/ca/internal/${caId}/signing-config`,
+ body
+ );
+ return data;
+ },
+ onSuccess: (_, { caId }) => {
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaSigningConfig(caId) });
+ }
+ });
+};
+
+export const useUpdateCaAutoRenewal = () => {
+ const queryClient = useQueryClient();
+ return useMutation<
+ {
+ autoRenewalEnabled: boolean;
+ autoRenewalDaysBeforeExpiry: number | null;
+ lastRenewalStatus: CaRenewalStatus | null;
+ lastRenewalMessage: string | null;
+ lastRenewalAt: string | null;
+ },
+ object,
+ {
+ caId: string;
+ autoRenewalEnabled?: boolean;
+ autoRenewalDaysBeforeExpiry?: number;
+ }
+ >({
+ mutationFn: async ({ caId, ...body }) => {
+ const { data } = await apiRequest.patch(
+ `/api/v1/cert-manager/ca/internal/${caId}/auto-renewal`,
+ body
+ );
+ return data;
+ },
+ onSuccess: (_, { caId }) => {
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaAutoRenewal(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaById(caId) });
+ }
+ });
+};
+
export const useGenerateCaCertificate = () => {
const queryClient = useQueryClient();
return useMutation<
diff --git a/frontend/src/hooks/api/ca/queries.tsx b/frontend/src/hooks/api/ca/queries.tsx
index 162f6c5aaf..7c5b60f785 100644
--- a/frontend/src/hooks/api/ca/queries.tsx
+++ b/frontend/src/hooks/api/ca/queries.tsx
@@ -3,7 +3,7 @@ import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { TCertificateTemplate } from "../certificateTemplates/types";
-import { CaType } from "./enums";
+import { CaRenewalStatus, CaSigningConfigType, CaType } from "./enums";
import {
TAzureAdCsTemplate,
TInternalCertificateAuthority,
@@ -26,7 +26,9 @@ export const caKeys = {
getAzureAdcsTemplates: (caId: string, projectId: string) => [
{ caId, projectId },
"azure-adcs-templates"
- ]
+ ],
+ getCaSigningConfig: (caId: string) => [{ caId }, "ca-signing-config"],
+ getCaAutoRenewal: (caId: string) => [{ caId }, "ca-auto-renewal"]
};
export const useGetCa = ({
@@ -202,6 +204,61 @@ export const useGetCaCertTemplates = (caId: string) => {
});
};
+export type TCaSigningConfig = {
+ id: string;
+ caId: string;
+ type: CaSigningConfigType;
+ parentCaId: string | null;
+ appConnectionId: string | null;
+ destinationConfig: {
+ applicationId: string;
+ issuingTemplateId: string;
+ validityPeriod?: number;
+ } | null;
+ lastExternalCertificateId: string | null;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TCaAutoRenewalConfig = {
+ autoRenewalEnabled: boolean;
+ autoRenewalDaysBeforeExpiry: number | null;
+ lastRenewalStatus: CaRenewalStatus | null;
+ lastRenewalMessage: string | null;
+ lastRenewalAt: string | null;
+};
+
+export const useGetCaSigningConfig = (caId: string, options?: { enabled?: boolean }) => {
+ return useQuery({
+ queryKey: caKeys.getCaSigningConfig(caId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TCaSigningConfig>(
+ `/api/v1/cert-manager/ca/internal/${caId}/signing-config`
+ );
+ return data;
+ },
+ enabled: options?.enabled !== undefined ? options.enabled : Boolean(caId)
+ });
+};
+
+export const useGetCaAutoRenewal = (caId: string, options?: { enabled?: boolean }) => {
+ return useQuery({
+ queryKey: caKeys.getCaAutoRenewal(caId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TCaAutoRenewalConfig>(
+ `/api/v1/cert-manager/ca/internal/${caId}/auto-renewal`
+ );
+ return data;
+ },
+ enabled: options?.enabled !== undefined ? options.enabled : Boolean(caId),
+ refetchInterval: (query) => {
+ const { data } = query.state;
+ if (data?.lastRenewalStatus === CaRenewalStatus.PENDING) return 3000;
+ return false;
+ }
+ });
+};
+
export const useGetAzureAdcsTemplates = ({
caId,
projectId,
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
index 9b35907012..e1b166aab2 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
@@ -35,7 +35,8 @@ import {
CaCrlsSection,
CaDetailsSection,
CaGenerateRootCertModal,
- CaRenewalModal
+ CaRenewalModal,
+ CaSigningConfigSection
} from "./components";
const Page = () => {
@@ -145,6 +146,7 @@ const Page = () => {
<div className="flex flex-col gap-5 lg:flex-row">
<div className="w-full lg:max-w-[24rem]">
<CaDetailsSection caId={data.id} />
+ <CaSigningConfigSection caId={data.id} />
<CaCertDetailsSection caId={data.id} />
</div>
<div className="flex flex-1 flex-col gap-y-5">
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertDetailsSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertDetailsSection.tsx
index 3ae18c672c..4e127fc057 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertDetailsSection.tsx
@@ -5,6 +5,7 @@ import {
DetailValue,
UnstableCard,
UnstableCardContent,
+ UnstableCardDescription,
UnstableCardHeader,
UnstableCardTitle
} from "@app/components/v3";
@@ -43,6 +44,7 @@ export const CaCertDetailsSection = ({ caId }: Props) => {
<UnstableCard className="mt-4 w-full">
<UnstableCardHeader className="border-b">
<UnstableCardTitle>Certificate Details</UnstableCardTitle>
+ <UnstableCardDescription>Subject and issuer information</UnstableCardDescription>
</UnstableCardHeader>
<UnstableCardContent>
<DetailGroup>
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertificatesSection/CaCertificatesSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertificatesSection/CaCertificatesSection.tsx
index d107f2ad14..e894689dfe 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertificatesSection/CaCertificatesSection.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertificatesSection/CaCertificatesSection.tsx
@@ -4,14 +4,27 @@ import { ArrowDownToLineIcon, RefreshCcwIcon } from "lucide-react";
import { ProjectPermissionCan } from "@app/components/permissions";
import {
Button,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
UnstableCard,
UnstableCardAction,
UnstableCardContent,
+ UnstableCardDescription,
UnstableCardHeader,
UnstableCardTitle
} from "@app/components/v3";
import { ProjectPermissionCertificateAuthorityActions, ProjectPermissionSub } from "@app/context";
-import { CaStatus, CaType, InternalCaType, useGetCa } from "@app/hooks/api";
+import {
+ CaRenewalStatus,
+ CaSigningConfigType,
+ CaStatus,
+ CaType,
+ InternalCaType,
+ useGetCa,
+ useGetCaAutoRenewal,
+ useGetCaSigningConfig
+} from "@app/hooks/api";
import { TInternalCertificateAuthority } from "@app/hooks/api/ca/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -34,6 +47,13 @@ export const CaCertificatesSection = ({ caId, caName, handlePopUpOpen }: Props)
const ca = data as TInternalCertificateAuthority;
+ const { data: signingConfig } = useGetCaSigningConfig(caId);
+ const { data: autoRenewal } = useGetCaAutoRenewal(caId, {
+ enabled: Boolean(caId)
+ });
+
+ const isVenafiPending = autoRenewal?.lastRenewalStatus === CaRenewalStatus.PENDING;
+
const renderActionButton = () => {
if (!ca) return null;
@@ -44,30 +64,39 @@ export const CaCertificatesSection = ({ caId, caName, handlePopUpOpen }: Props)
a={subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })}
>
{(isAllowed) => (
- <Button
- isDisabled={!isAllowed}
- variant="project"
- size="xs"
- onClick={() => {
- if (
- ca.configuration.type === InternalCaType.INTERMEDIATE &&
- !ca.configuration.parentCaId
- ) {
- handlePopUpOpen("installCaCert", {
- caId: ca.id,
- isParentCaExternal: true
- });
- return;
- }
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ isDisabled={!isAllowed || isVenafiPending}
+ variant="project"
+ size="xs"
+ onClick={() => {
+ // Manual external CAs show the install modal with CSR for manual renewal
+ if (
+ ca.configuration.type === InternalCaType.INTERMEDIATE &&
+ !ca.configuration.parentCaId &&
+ signingConfig?.type !== CaSigningConfigType.VENAFI
+ ) {
+ handlePopUpOpen("installCaCert", {
+ caId: ca.id,
+ isParentCaExternal: true
+ });
+ return;
+ }
- handlePopUpOpen("renewCa", {
- caId: ca.id
- });
- }}
- >
- <RefreshCcwIcon />
- Renew CA
- </Button>
+ handlePopUpOpen("renewCa", {
+ caId: ca.id
+ });
+ }}
+ >
+ <RefreshCcwIcon />
+ Renew CA
+ </Button>
+ </TooltipTrigger>
+ {isVenafiPending && (
+ <TooltipContent>Certificate installation is in progress</TooltipContent>
+ )}
+ </Tooltip>
)}
</ProjectPermissionCan>
);
@@ -97,19 +126,26 @@ export const CaCertificatesSection = ({ caId, caName, handlePopUpOpen }: Props)
);
}
return (
- <Button
- isDisabled={!isAllowed}
- variant="project"
- size="xs"
- onClick={() => {
- handlePopUpOpen("installCaCert", {
- caId: ca.id
- });
- }}
- >
- <ArrowDownToLineIcon />
- Install CA Certificate
- </Button>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ isDisabled={!isAllowed || isVenafiPending}
+ variant="project"
+ size="xs"
+ onClick={() => {
+ handlePopUpOpen("installCaCert", {
+ caId: ca.id
+ });
+ }}
+ >
+ <ArrowDownToLineIcon />
+ Install CA Certificate
+ </Button>
+ </TooltipTrigger>
+ {isVenafiPending && (
+ <TooltipContent>Certificate installation is in progress</TooltipContent>
+ )}
+ </Tooltip>
);
}}
</ProjectPermissionCan>
@@ -123,6 +159,7 @@ export const CaCertificatesSection = ({ caId, caName, handlePopUpOpen }: Props)
<UnstableCard className="w-full">
<UnstableCardHeader className="border-b">
<UnstableCardTitle>CA Certificates</UnstableCardTitle>
+ <UnstableCardDescription>Issued and active certificates</UnstableCardDescription>
<UnstableCardAction>{renderActionButton()}</UnstableCardAction>
</UnstableCardHeader>
<UnstableCardContent>
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
index ca07450e07..47cd36388b 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
@@ -1,6 +1,31 @@
+import { useEffect, useRef } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useQueryClient } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
-import { CheckIcon, ClipboardListIcon, ExternalLinkIcon } from "lucide-react";
+import { addDays, format } from "date-fns";
+import {
+ AlertTriangleIcon,
+ CheckIcon,
+ ClipboardListIcon,
+ ExternalLinkIcon,
+ InfoIcon,
+ LoaderIcon,
+ PencilIcon
+} from "lucide-react";
+import { z } from "zod";
+import { createNotification } from "@app/components/notifications";
+import {
+ Button as ButtonV2,
+ FormControl,
+ Input,
+ Modal,
+ ModalClose,
+ ModalContent,
+ Switch as SwitchV2,
+ Tooltip as TooltipV2
+} from "@app/components/v2";
import {
Badge,
Detail,
@@ -10,18 +35,32 @@ import {
Tooltip,
TooltipContent,
TooltipTrigger,
+ UnstableAlert,
+ UnstableAlertTitle,
UnstableCard,
+ UnstableCardAction,
UnstableCardContent,
+ UnstableCardDescription,
UnstableCardHeader,
UnstableCardTitle,
UnstableIconButton
} from "@app/components/v3";
import { useOrganization, useProject } from "@app/context";
import { useTimedReset } from "@app/hooks";
-import { CaStatus, CaType, InternalCaType, useGetCa } from "@app/hooks/api";
+import {
+ CaRenewalStatus,
+ CaStatus,
+ CaType,
+ InternalCaType,
+ useGetCa,
+ useGetCaAutoRenewal,
+ useUpdateCaAutoRenewal
+} from "@app/hooks/api";
import { caStatusToNameMap, caTypeToNameMap } from "@app/hooks/api/ca/constants";
+import { caKeys } from "@app/hooks/api/ca/queries";
import { TInternalCertificateAuthority } from "@app/hooks/api/ca/types";
import { certKeyAlgorithmToNameMap } from "@app/hooks/api/certificates/constants";
+import { usePopUp } from "@app/hooks/usePopUp";
type Props = {
caId: string;
@@ -40,12 +79,21 @@ const getStatusVariant = (status: CaStatus) => {
}
};
+const autoRenewalSchema = z.object({
+ autoRenewalEnabled: z.boolean(),
+ autoRenewalDaysBeforeExpiry: z.coerce.number().min(1).max(365)
+});
+
+type AutoRenewalFormData = z.infer<typeof autoRenewalSchema>;
+
export const CaDetailsSection = ({ caId }: Props) => {
const { currentOrg } = useOrganization();
const { currentProject } = useProject();
+ const queryClient = useQueryClient();
const [, isCopyingId, setCopyTextId] = useTimedReset<string>({
initialState: "Copy ID to clipboard"
});
+ const { popUp, handlePopUpToggle } = usePopUp(["editAutoRenewal"] as const);
const { data } = useGetCa({
caId,
@@ -64,88 +112,332 @@ export const CaDetailsSection = ({ caId }: Props) => {
const parentCa = parentCaData as TInternalCertificateAuthority | undefined;
+ const { data: autoRenewal } = useGetCaAutoRenewal(caId, {
+ enabled:
+ Boolean(caId) &&
+ (ca?.status === CaStatus.ACTIVE || ca?.status === CaStatus.PENDING_CERTIFICATE)
+ });
+
+ const prevStatusRef = useRef(autoRenewal?.lastRenewalStatus);
+ useEffect(() => {
+ const prevStatus = prevStatusRef.current;
+ const currentStatus = autoRenewal?.lastRenewalStatus;
+ prevStatusRef.current = currentStatus;
+
+ if (
+ prevStatus === CaRenewalStatus.PENDING &&
+ currentStatus &&
+ currentStatus !== CaRenewalStatus.PENDING
+ ) {
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaById(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
+ queryClient.invalidateQueries({
+ queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL, currentProject.id)
+ });
+ }
+ }, [autoRenewal?.lastRenewalStatus, caId, currentProject.id, queryClient]);
+
+ const { mutateAsync: updateAutoRenewal } = useUpdateCaAutoRenewal();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ watch,
+ formState: { isSubmitting }
+ } = useForm<AutoRenewalFormData>({
+ resolver: zodResolver(autoRenewalSchema),
+ values: {
+ autoRenewalEnabled: autoRenewal?.autoRenewalEnabled ?? false,
+ autoRenewalDaysBeforeExpiry: autoRenewal?.autoRenewalDaysBeforeExpiry ?? 30
+ }
+ });
+
+ const watchEnabled = watch("autoRenewalEnabled");
+
if (!ca) {
return <div />;
}
+ const onAutoRenewalSubmit = async ({
+ autoRenewalEnabled,
+ autoRenewalDaysBeforeExpiry
+ }: AutoRenewalFormData) => {
+ try {
+ await updateAutoRenewal({
+ caId,
+ autoRenewalEnabled,
+ ...(autoRenewalEnabled && { autoRenewalDaysBeforeExpiry })
+ });
+ createNotification({
+ text: "Renewal settings updated",
+ type: "success"
+ });
+ handlePopUpToggle("editAutoRenewal", false);
+ } catch {
+ createNotification({
+ text: "Failed to update renewal settings",
+ type: "error"
+ });
+ }
+ };
+
+ const getNextRenewalDate = () => {
+ if (
+ !autoRenewal?.autoRenewalEnabled ||
+ !autoRenewal.autoRenewalDaysBeforeExpiry ||
+ !ca.configuration.notAfter
+ ) {
+ return null;
+ }
+ return addDays(new Date(ca.configuration.notAfter), -autoRenewal.autoRenewalDaysBeforeExpiry);
+ };
+
+ const showAutoRenewal =
+ (ca.status === CaStatus.ACTIVE || ca.status === CaStatus.PENDING_CERTIFICATE) && autoRenewal;
+
return (
- <UnstableCard className="w-full">
- <UnstableCardHeader className="border-b">
- <UnstableCardTitle>CA Details</UnstableCardTitle>
- </UnstableCardHeader>
- <UnstableCardContent>
- <DetailGroup>
- <Detail>
- <DetailLabel>CA Type</DetailLabel>
- <DetailValue>{caTypeToNameMap[ca.configuration.type]}</DetailValue>
- </Detail>
-
- <Detail>
- <DetailLabel>CA ID</DetailLabel>
- <DetailValue className="flex items-center gap-x-1">
- <span className="break-all">{ca.id}</span>
- <Tooltip>
- <TooltipTrigger asChild>
- <UnstableIconButton
- variant="ghost"
- size="xs"
- onClick={() => {
- navigator.clipboard.writeText(ca.id);
- setCopyTextId("Copied");
- }}
- >
- {isCopyingId ? <CheckIcon /> : <ClipboardListIcon className="text-label" />}
- </UnstableIconButton>
- </TooltipTrigger>
- <TooltipContent>{isCopyingId ? "Copied" : "Copy ID to clipboard"}</TooltipContent>
- </Tooltip>
- </DetailValue>
- </Detail>
-
- {ca.configuration.type === InternalCaType.INTERMEDIATE &&
- ca.status !== CaStatus.PENDING_CERTIFICATE && (
- <Detail>
- <DetailLabel>Parent CA</DetailLabel>
- <DetailValue className="flex items-center gap-x-1">
- {ca.configuration.parentCaId ? (
- <Badge variant="neutral" asChild>
- <Link
- to="/organizations/$orgId/projects/cert-manager/$projectId/ca/$caId"
- params={{
- orgId: currentOrg.id,
- projectId: currentProject.id,
- caId: ca.configuration.parentCaId
- }}
- >
- {parentCa?.name || ca.configuration.parentCaId}
- <ExternalLinkIcon />
- </Link>
+ <>
+ <UnstableCard className="w-full">
+ <UnstableCardHeader className="border-b">
+ <UnstableCardTitle>Details</UnstableCardTitle>
+ <UnstableCardDescription>Certificate authority details</UnstableCardDescription>
+ {showAutoRenewal && (
+ <UnstableCardAction>
+ <UnstableIconButton
+ variant="outline"
+ size="xs"
+ onClick={() => handlePopUpToggle("editAutoRenewal", true)}
+ >
+ <PencilIcon />
+ </UnstableIconButton>
+ </UnstableCardAction>
+ )}
+ </UnstableCardHeader>
+ <UnstableCardContent>
+ <DetailGroup>
+ <Detail>
+ <DetailLabel>CA Type</DetailLabel>
+ <DetailValue>{caTypeToNameMap[ca.configuration.type]}</DetailValue>
+ </Detail>
+
+ <Detail>
+ <DetailLabel>CA ID</DetailLabel>
+ <DetailValue className="flex items-center gap-x-1">
+ <span className="break-all">{ca.id}</span>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <UnstableIconButton
+ variant="ghost"
+ size="xs"
+ onClick={() => {
+ navigator.clipboard.writeText(ca.id);
+ setCopyTextId("Copied");
+ }}
+ >
+ {isCopyingId ? <CheckIcon /> : <ClipboardListIcon className="text-label" />}
+ </UnstableIconButton>
+ </TooltipTrigger>
+ <TooltipContent>{isCopyingId ? "Copied" : "Copy ID to clipboard"}</TooltipContent>
+ </Tooltip>
+ </DetailValue>
+ </Detail>
+
+ {ca.configuration.type === InternalCaType.INTERMEDIATE &&
+ ca.status !== CaStatus.PENDING_CERTIFICATE && (
+ <Detail>
+ <DetailLabel>Parent CA</DetailLabel>
+ <DetailValue className="flex items-center gap-x-1">
+ {ca.configuration.parentCaId ? (
+ <Badge variant="neutral" asChild>
+ <Link
+ to="/organizations/$orgId/projects/cert-manager/$projectId/ca/$caId"
+ params={{
+ orgId: currentOrg.id,
+ projectId: currentProject.id,
+ caId: ca.configuration.parentCaId
+ }}
+ >
+ {parentCa?.name || ca.configuration.parentCaId}
+ <ExternalLinkIcon />
+ </Link>
+ </Badge>
+ ) : (
+ <span className="break-all">N/A - External Parent CA</span>
+ )}
+ </DetailValue>
+ </Detail>
+ )}
+
+ <Detail>
+ <DetailLabel>Name</DetailLabel>
+ <DetailValue>{ca.name}</DetailValue>
+ </Detail>
+
+ <Detail>
+ <DetailLabel>Status</DetailLabel>
+ <DetailValue>
+ <Badge variant={getStatusVariant(ca.status)}>{caStatusToNameMap[ca.status]}</Badge>
+ </DetailValue>
+ </Detail>
+
+ <Detail>
+ <DetailLabel>Key Algorithm</DetailLabel>
+ <DetailValue>{certKeyAlgorithmToNameMap[ca.configuration.keyAlgorithm]}</DetailValue>
+ </Detail>
+
+ {showAutoRenewal && (
+ <>
+ <Detail>
+ <DetailLabel>Auto-Renewal</DetailLabel>
+ <DetailValue>
+ <Badge variant={autoRenewal.autoRenewalEnabled ? "success" : "neutral"}>
+ {autoRenewal.autoRenewalEnabled ? "Enabled" : "Disabled"}
</Badge>
- ) : (
- <span className="break-all">N/A - External Parent CA</span>
- )}
- </DetailValue>
- </Detail>
+ </DetailValue>
+ </Detail>
+
+ {autoRenewal.lastRenewalAt && (
+ <Detail>
+ <DetailLabel>Last Renewal</DetailLabel>
+ <DetailValue>
+ {format(new Date(autoRenewal.lastRenewalAt), "MMM d, yyyy 'at' h:mm a")}
+ </DetailValue>
+ </Detail>
+ )}
+
+ {autoRenewal.lastRenewalStatus && (
+ <Detail>
+ <DetailLabel>Last Installation Status</DetailLabel>
+ <DetailValue>
+ {autoRenewal.lastRenewalStatus === CaRenewalStatus.FAILED &&
+ autoRenewal.lastRenewalMessage ? (
+ <TooltipV2
+ position="right"
+ content={autoRenewal.lastRenewalMessage}
+ className="max-w-md break-words"
+ >
+ <Badge variant="danger">Failed</Badge>
+ </TooltipV2>
+ ) : (
+ <Badge
+ variant={(() => {
+ if (autoRenewal.lastRenewalStatus === CaRenewalStatus.SUCCESS)
+ return "success";
+ if (autoRenewal.lastRenewalStatus === CaRenewalStatus.PENDING)
+ return "info";
+ return "danger";
+ })()}
+ >
+ {autoRenewal.lastRenewalStatus === CaRenewalStatus.PENDING
+ ? "Installing..."
+ : autoRenewal.lastRenewalStatus.charAt(0).toUpperCase() +
+ autoRenewal.lastRenewalStatus.slice(1)}
+ </Badge>
+ )}
+ </DetailValue>
+ </Detail>
+ )}
+ </>
)}
+ </DetailGroup>
+
+ {showAutoRenewal && autoRenewal.lastRenewalStatus === CaRenewalStatus.PENDING && (
+ <UnstableAlert variant="info" className="mt-2">
+ <LoaderIcon className="animate-spin" />
+ <UnstableAlertTitle>Certificate installation in progress...</UnstableAlertTitle>
+ </UnstableAlert>
+ )}
- <Detail>
- <DetailLabel>Name</DetailLabel>
- <DetailValue>{ca.name}</DetailValue>
- </Detail>
-
- <Detail>
- <DetailLabel>Status</DetailLabel>
- <DetailValue>
- <Badge variant={getStatusVariant(ca.status)}>{caStatusToNameMap[ca.status]}</Badge>
- </DetailValue>
- </Detail>
-
- <Detail>
- <DetailLabel>Key Algorithm</DetailLabel>
- <DetailValue>{certKeyAlgorithmToNameMap[ca.configuration.keyAlgorithm]}</DetailValue>
- </Detail>
- </DetailGroup>
- </UnstableCardContent>
- </UnstableCard>
+ {showAutoRenewal &&
+ autoRenewal.lastRenewalStatus !== CaRenewalStatus.PENDING &&
+ autoRenewal.autoRenewalEnabled &&
+ (autoRenewal.lastRenewalStatus === CaRenewalStatus.FAILED &&
+ autoRenewal.lastRenewalMessage ? (
+ <UnstableAlert className="mt-2 border-warning/20 bg-warning/5 text-warning">
+ <AlertTriangleIcon />
+ <UnstableAlertTitle>
+ Last renewal failed: {autoRenewal.lastRenewalMessage}
+ </UnstableAlertTitle>
+ </UnstableAlert>
+ ) : (
+ (() => {
+ const nextRenewalDate = getNextRenewalDate();
+ if (!nextRenewalDate) return null;
+ return (
+ <UnstableAlert variant="info" className="mt-2">
+ <InfoIcon />
+ <UnstableAlertTitle>
+ Next auto-renewal: {format(nextRenewalDate, "MMM d, yyyy")}
+ </UnstableAlertTitle>
+ </UnstableAlert>
+ );
+ })()
+ ))}
+ </UnstableCardContent>
+ </UnstableCard>
+
+ <Modal
+ isOpen={popUp.editAutoRenewal.isOpen}
+ onOpenChange={(isOpen) => {
+ handlePopUpToggle("editAutoRenewal", isOpen);
+ if (!isOpen) reset();
+ }}
+ >
+ <ModalContent title="Edit Renewal Settings">
+ <form onSubmit={handleSubmit(onAutoRenewalSubmit)}>
+ <Controller
+ control={control}
+ name="autoRenewalEnabled"
+ render={({ field: { value, onChange } }) => (
+ <FormControl>
+ <SwitchV2
+ id="auto-renewal-enabled"
+ className="bg-mineshaft-400/80 shadow-inner data-[state=checked]:bg-green/80"
+ thumbClassName="bg-mineshaft-800"
+ isChecked={value}
+ onCheckedChange={onChange}
+ >
+ Auto-Renewal
+ </SwitchV2>
+ </FormControl>
+ )}
+ />
+ {watchEnabled && (
+ <Controller
+ control={control}
+ name="autoRenewalDaysBeforeExpiry"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Days Before Expiry"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ helperText="Number of days before certificate expiry to trigger auto-renewal"
+ >
+ <Input {...field} type="number" min={1} max={365} />
+ </FormControl>
+ )}
+ />
+ )}
+ <div className="flex w-full justify-between gap-4 pt-4">
+ <ModalClose asChild>
+ <ButtonV2 colorSchema="secondary" variant="plain">
+ Cancel
+ </ButtonV2>
+ </ModalClose>
+ <ButtonV2
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting}
+ type="submit"
+ colorSchema="secondary"
+ >
+ Save
+ </ButtonV2>
+ </div>
+ </form>
+ </ModalContent>
+ </Modal>
+ </>
);
};
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx
index c6283da375..10da8b503e 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx
@@ -1,4 +1,3 @@
-// import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
@@ -16,10 +15,10 @@ import {
import { useProject } from "@app/context";
import {
CaRenewalType,
+ CaSigningConfigType,
+ useGetCaSigningConfig,
+ useInstallCaCertificateVenafi,
useRenewCa
- // useGetCaById,
- // CaType,
- // CaStatus
} from "@app/hooks/api/ca";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -52,55 +51,82 @@ export const CaRenewalModal = ({ popUp, handlePopUpToggle }: Props) => {
caId: string;
};
- // const { data: ca } = useGetCaById(popUpData?.caId || "");
- // const { data: parentCa } = useGetCaById(ca?.parentCaId || "");
+ const caId = popUpData?.caId || "";
+
+ const { data: signingConfig } = useGetCaSigningConfig(caId, {
+ enabled: !!caId
+ });
+
+ const isVenafi = signingConfig?.type === CaSigningConfigType.VENAFI;
+
const { mutateAsync: renewCa } = useRenewCa();
+ const { mutateAsync: installVenafiCert, isPending: isVenafiRenewing } =
+ useInstallCaCertificateVenafi(currentProject.id);
const {
control,
handleSubmit,
reset,
formState: { isSubmitting }
- // setValue
} = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
type: CaRenewalType.EXISTING,
- notAfter: "" // TODO: consider setting a default value
+ notAfter: ""
}
});
- // useEffect(() => {
- // if (ca && ca.status === CaStatus.ACTIVE) {
- // const notBeforeDate = new Date(ca.notBefore as string);
- // const notAfterDate = new Date(ca.notAfter as string);
-
- // const newNotAfterDate = new Date(
- // notAfterDate.getTime() + notAfterDate.getTime() - notBeforeDate.getTime()
- // );
-
- // setValue("notAfter", newNotAfterDate.toISOString().split("T")[0]);
- // }
- // }, [ca, parentCa]);
-
const onFormSubmit = async ({ type, notAfter }: FormData) => {
if (!projectSlug || !popUpData.caId) return;
- await renewCa({
- projectSlug,
- caId: popUpData.caId,
- notAfter,
- type
- });
-
- handlePopUpToggle("renewCa", false);
-
- createNotification({
- text: "Successfully renewed CA",
- type: "success"
- });
+ try {
+ await renewCa({
+ projectSlug,
+ caId: popUpData.caId,
+ notAfter,
+ type
+ });
+
+ handlePopUpToggle("renewCa", false);
+
+ createNotification({
+ text: "Successfully renewed CA",
+ type: "success"
+ });
+
+ reset();
+ } catch (err) {
+ createNotification({
+ text:
+ (err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
+ "Failed to renew CA",
+ type: "error"
+ });
+ }
+ };
- reset();
+ const onVenafiRenew = async () => {
+ if (!caId) return;
+
+ try {
+ await installVenafiCert({
+ caId
+ });
+
+ handlePopUpToggle("renewCa", false);
+
+ createNotification({
+ text: "Certificate renewal has been queued",
+ type: "success"
+ });
+ } catch (err) {
+ createNotification({
+ text:
+ (err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
+ "Failed to renew CA certificate via Venafi",
+ type: "error"
+ });
+ }
};
return (
@@ -112,66 +138,93 @@ export const CaRenewalModal = ({ popUp, handlePopUpToggle }: Props) => {
}}
>
<ModalContent title="Renew CA">
- <form onSubmit={handleSubmit(onFormSubmit)}>
- <Controller
- control={control}
- name="type"
- defaultValue={CaRenewalType.EXISTING}
- render={({ field: { onChange, ...field }, fieldState: { error } }) => (
- <FormControl
- label="CA Renewal Method"
- errorText={error?.message}
- isError={Boolean(error)}
+ {isVenafi ? (
+ <div>
+ <p className="mb-4 text-sm text-mineshaft-300">
+ This CA is configured to use Venafi TLS Protect Cloud for signing. Clicking renew will
+ submit a new CSR to Venafi and install the renewed certificate.
+ </p>
+ <div className="flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ onClick={onVenafiRenew}
+ isLoading={isVenafiRenewing}
+ isDisabled={isVenafiRenewing}
>
- <Select
- defaultValue={field.value}
- {...field}
- onValueChange={(e) => onChange(e)}
- className="w-full"
- >
- {caRenewalTypes.map(({ label, value }) => (
- <SelectItem value={String(value || "")} key={label}>
- {label}
- </SelectItem>
- ))}
- </Select>
- </FormControl>
- )}
- />
- <Controller
- control={control}
- defaultValue=""
- name="notAfter"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Valid Until"
- isError={Boolean(error)}
- errorText={error?.message}
- isRequired
+ Renew via Venafi
+ </Button>
+ <Button
+ colorSchema="secondary"
+ variant="plain"
+ onClick={() => handlePopUpToggle("renewCa", false)}
>
- <Input {...field} placeholder="YYYY-MM-DD" />
- </FormControl>
- )}
- />
- <div className="flex items-center">
- <Button
- className="mr-4"
- size="sm"
- type="submit"
- isLoading={isSubmitting}
- isDisabled={isSubmitting}
- >
- Renew
- </Button>
- <Button
- colorSchema="secondary"
- variant="plain"
- onClick={() => handlePopUpToggle("renewCa", false)}
- >
- Cancel
- </Button>
+ Cancel
+ </Button>
+ </div>
</div>
- </form>
+ ) : (
+ <form onSubmit={handleSubmit(onFormSubmit)}>
+ <Controller
+ control={control}
+ name="type"
+ defaultValue={CaRenewalType.EXISTING}
+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (
+ <FormControl
+ label="CA Renewal Method"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ >
+ <Select
+ defaultValue={field.value}
+ {...field}
+ onValueChange={(e) => onChange(e)}
+ className="w-full"
+ >
+ {caRenewalTypes.map(({ label, value }) => (
+ <SelectItem value={String(value || "")} key={label}>
+ {label}
+ </SelectItem>
+ ))}
+ </Select>
+ </FormControl>
+ )}
+ />
+ <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>
+ )}
+ />
+ <div className="flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ type="submit"
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting}
+ >
+ Renew
+ </Button>
+ <Button
+ colorSchema="secondary"
+ variant="plain"
+ onClick={() => handlePopUpToggle("renewCa", false)}
+ >
+ Cancel
+ </Button>
+ </div>
+ </form>
+ )}
</ModalContent>
</Modal>
);
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsx
new file mode 100644
index 0000000000..6ea539ecda
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsx
@@ -0,0 +1,372 @@
+import { subject } from "@casl/ability";
+import { Controller, useForm } from "react-hook-form";
+import { SingleValue } from "react-select";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PencilIcon } from "lucide-react";
+import { z } from "zod";
+
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { createNotification } from "@app/components/notifications";
+import {
+ Button as ButtonV2,
+ FilterableSelect,
+ FormControl,
+ Input,
+ Modal,
+ ModalClose,
+ ModalContent
+} from "@app/components/v2";
+import {
+ Badge,
+ Detail,
+ DetailGroup,
+ DetailLabel,
+ DetailValue,
+ UnstableCard,
+ UnstableCardAction,
+ UnstableCardContent,
+ UnstableCardDescription,
+ UnstableCardHeader,
+ UnstableCardTitle,
+ UnstableIconButton
+} from "@app/components/v3";
+import {
+ ProjectPermissionCertificateAuthorityActions,
+ ProjectPermissionSub,
+ useProject
+} from "@app/context";
+import {
+ CaSigningConfigType,
+ CaStatus,
+ CaType,
+ useGetCa,
+ useGetCaSigningConfig,
+ useUpdateCaSigningConfig
+} from "@app/hooks/api";
+import {
+ TAvailableAppConnection,
+ useListAvailableAppConnections
+} from "@app/hooks/api/appConnections";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import {
+ TVenafiApplication,
+ TVenafiIssuingTemplate,
+ useVenafiConnectionListApplications,
+ useVenafiConnectionListIssuingTemplates
+} from "@app/hooks/api/appConnections/venafi";
+import { TInternalCertificateAuthority } from "@app/hooks/api/ca/types";
+import { usePopUp } from "@app/hooks/usePopUp";
+
+type Props = {
+ caId: string;
+};
+
+const signingTypeLabels: Record<CaSigningConfigType, string> = {
+ [CaSigningConfigType.INTERNAL]: "Internal (Infisical CA)",
+ [CaSigningConfigType.MANUAL]: "Manual",
+ [CaSigningConfigType.VENAFI]: "Venafi TLS Protect Cloud"
+};
+
+const getSigningTypeBadgeVariant = (type: CaSigningConfigType) => {
+ if (type === CaSigningConfigType.INTERNAL) return "info";
+ return "neutral";
+};
+
+const editSchema = z.object({
+ appConnectionId: z.string().min(1, "App connection is required"),
+ applicationId: z.string().min(1, "Application is required"),
+ issuingTemplateId: z.string().min(1, "Issuing Template is required"),
+ validityPeriod: z.coerce
+ .number()
+ .int()
+ .min(1, "Must be at least 1 day")
+ .optional()
+ .or(z.literal(""))
+});
+
+type EditFormData = z.infer<typeof editSchema>;
+
+export const CaSigningConfigSection = ({ caId }: Props) => {
+ const { currentProject } = useProject();
+ const { popUp, handlePopUpToggle } = usePopUp(["editSigningConfig"] as const);
+
+ const { data: caData } = useGetCa({
+ caId,
+ type: CaType.INTERNAL
+ });
+
+ const ca = caData as TInternalCertificateAuthority;
+
+ const { data: signingConfig } = useGetCaSigningConfig(caId, {
+ enabled: Boolean(caId) && ca?.status !== CaStatus.PENDING_CERTIFICATE
+ });
+
+ const { mutateAsync: updateSigningConfig } = useUpdateCaSigningConfig();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ watch,
+ setValue,
+ formState: { isSubmitting }
+ } = useForm<EditFormData>({
+ resolver: zodResolver(editSchema),
+ values: {
+ appConnectionId: signingConfig?.appConnectionId ?? "",
+ applicationId: signingConfig?.destinationConfig?.applicationId ?? "",
+ issuingTemplateId: signingConfig?.destinationConfig?.issuingTemplateId ?? "",
+ validityPeriod: signingConfig?.destinationConfig?.validityPeriod ?? ""
+ }
+ });
+
+ const selectedConnectionId = watch("appConnectionId");
+ const selectedApplicationId = watch("applicationId");
+
+ const { data: availableVenafiConnections, isPending: isVenafiPending } =
+ useListAvailableAppConnections(AppConnection.Venafi, currentProject.id);
+
+ const { data: applications = [], isPending: isApplicationsLoading } =
+ useVenafiConnectionListApplications(selectedConnectionId ?? "", {
+ enabled: !!selectedConnectionId && popUp.editSigningConfig.isOpen
+ });
+
+ const { data: issuingTemplates = [], isPending: isTemplatesLoading } =
+ useVenafiConnectionListIssuingTemplates(
+ selectedConnectionId ?? "",
+ selectedApplicationId ?? "",
+ {
+ enabled: !!selectedConnectionId && !!selectedApplicationId && popUp.editSigningConfig.isOpen
+ }
+ );
+
+ if (!ca || ca.status === CaStatus.PENDING_CERTIFICATE || !signingConfig) {
+ return null;
+ }
+
+ const isVenafi = signingConfig.type === CaSigningConfigType.VENAFI;
+
+ const onEditSubmit = async ({
+ appConnectionId,
+ applicationId,
+ issuingTemplateId,
+ validityPeriod
+ }: EditFormData) => {
+ try {
+ await updateSigningConfig({
+ caId,
+ appConnectionId,
+ destinationConfig: {
+ applicationId,
+ issuingTemplateId,
+ ...(typeof validityPeriod === "number" && { validityPeriod })
+ }
+ });
+ createNotification({
+ text: "Signing configuration updated",
+ type: "success"
+ });
+ handlePopUpToggle("editSigningConfig", false);
+ } catch {
+ createNotification({
+ text: "Failed to update signing configuration",
+ type: "error"
+ });
+ }
+ };
+
+ return (
+ <>
+ <UnstableCard className="mt-5 w-full">
+ <UnstableCardHeader className="border-b">
+ <UnstableCardTitle>Signing Configuration</UnstableCardTitle>
+ <UnstableCardDescription>
+ How this CA&apos;s certificate is signed
+ </UnstableCardDescription>
+ {isVenafi && ca?.name && (
+ <UnstableCardAction>
+ <ProjectPermissionCan
+ I={ProjectPermissionCertificateAuthorityActions.Edit}
+ a={subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })}
+ >
+ {(isAllowed) => (
+ <UnstableIconButton
+ variant="outline"
+ size="xs"
+ isDisabled={!isAllowed}
+ onClick={() => handlePopUpToggle("editSigningConfig", true)}
+ >
+ <PencilIcon />
+ </UnstableIconButton>
+ )}
+ </ProjectPermissionCan>
+ </UnstableCardAction>
+ )}
+ </UnstableCardHeader>
+ <UnstableCardContent>
+ <DetailGroup>
+ <Detail>
+ <DetailLabel>Signing Method</DetailLabel>
+ <DetailValue>
+ <Badge variant={getSigningTypeBadgeVariant(signingConfig.type)}>
+ {signingTypeLabels[signingConfig.type] || signingConfig.type}
+ </Badge>
+ </DetailValue>
+ </Detail>
+
+ {isVenafi && signingConfig.destinationConfig && (
+ <>
+ <Detail>
+ <DetailLabel>Application ID</DetailLabel>
+ <DetailValue>{signingConfig.destinationConfig.applicationId}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Issuing Template ID</DetailLabel>
+ <DetailValue>{signingConfig.destinationConfig.issuingTemplateId}</DetailValue>
+ </Detail>
+ {signingConfig.destinationConfig.validityPeriod && (
+ <Detail>
+ <DetailLabel>Validity Period</DetailLabel>
+ <DetailValue>{signingConfig.destinationConfig.validityPeriod} days</DetailValue>
+ </Detail>
+ )}
+ </>
+ )}
+ </DetailGroup>
+ </UnstableCardContent>
+ </UnstableCard>
+
+ {isVenafi && (
+ <Modal
+ isOpen={popUp.editSigningConfig.isOpen}
+ onOpenChange={(isOpen) => {
+ handlePopUpToggle("editSigningConfig", isOpen);
+ if (!isOpen) reset();
+ }}
+ >
+ <ModalContent title="Edit Signing Configuration" bodyClassName="overflow-visible">
+ <form onSubmit={handleSubmit(onEditSubmit)}>
+ <Controller
+ control={control}
+ name="appConnectionId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="Venafi Connection"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ >
+ <FilterableSelect
+ isLoading={isVenafiPending}
+ value={(availableVenafiConnections || []).find((conn) => conn.id === value)}
+ onChange={(option) => {
+ const selected = option as SingleValue<TAvailableAppConnection>;
+ onChange(selected?.id ?? "");
+ setValue("applicationId", "");
+ setValue("issuingTemplateId", "");
+ }}
+ options={availableVenafiConnections || []}
+ placeholder="Select a Venafi connection..."
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="applicationId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="Application"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ >
+ <FilterableSelect
+ isLoading={isApplicationsLoading && !!selectedConnectionId}
+ isDisabled={!selectedConnectionId}
+ value={applications.find((app) => app.id === value)}
+ onChange={(option) => {
+ const selected = option as SingleValue<TVenafiApplication>;
+ onChange(selected?.id ?? "");
+ setValue("issuingTemplateId", "");
+ }}
+ options={applications}
+ placeholder={
+ selectedConnectionId
+ ? "Select an application..."
+ : "Select a connection first"
+ }
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="issuingTemplateId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="Issuing Template"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ >
+ <FilterableSelect
+ isLoading={isTemplatesLoading && !!selectedApplicationId}
+ isDisabled={!selectedApplicationId}
+ value={issuingTemplates.find((tmpl) => tmpl.id === value)}
+ onChange={(option) => {
+ const selected = option as SingleValue<TVenafiIssuingTemplate>;
+ onChange(selected?.id ?? "");
+ }}
+ options={issuingTemplates}
+ placeholder={
+ selectedApplicationId
+ ? "Select an issuing template..."
+ : "Select an application first"
+ }
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="validityPeriod"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Validity Period (Days)"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ helperText="Number of days the certificate should be valid"
+ >
+ <Input {...field} type="number" placeholder="365" />
+ </FormControl>
+ )}
+ />
+ <div className="flex w-full justify-between gap-4 pt-4">
+ <ModalClose asChild>
+ <ButtonV2 colorSchema="secondary" variant="plain">
+ Cancel
+ </ButtonV2>
+ </ModalClose>
+ <ButtonV2
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting}
+ type="submit"
+ colorSchema="secondary"
+ >
+ Save
+ </ButtonV2>
+ </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 4ee9a45b59..41f683a8ce 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/index.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/index.tsx
@@ -4,3 +4,4 @@ export { CaCrlsSection } from "./CaCrlsSection";
export { CaDetailsSection } from "./CaDetailsSection";
export { CaGenerateRootCertModal } from "./CaGenerateRootCertModal";
export { CaRenewalModal } from "./CaRenewalModal";
+export { CaSigningConfigSection } from "./CaSigningConfigSection";
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/CaInstallCertModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/CaInstallCertModal.tsx
index 1095e0d3e5..a9e0925d51 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/CaInstallCertModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/CaInstallCertModal.tsx
@@ -1,74 +1,341 @@
-import { useEffect, useState } from "react";
+import { useState } from "react";
+import {
+ ArrowLeftIcon,
+ ArrowRightIcon,
+ FileTextIcon,
+ LinkIcon,
+ ShieldCheckIcon
+} from "lucide-react";
-import { FormControl, Modal, ModalContent, Select, SelectItem } from "@app/components/v2";
+import { Modal, ModalContent } from "@app/components/v2";
+import { Badge, Button } from "@app/components/v3";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { ExternalCaInstallForm } from "./ExternalCaInstallForm";
import { InternalCaInstallForm } from "./InternalCaInstallForm";
+import { VenafiCaInstallForm } from "./VenafiCaInstallForm";
type Props = {
popUp: UsePopUpState<["installCaCert"]>;
handlePopUpToggle: (popUpName: keyof UsePopUpState<["installCaCert"]>, state?: boolean) => void;
};
-enum ParentCaType {
+enum SigningMethod {
Internal = "internal",
- External = "external"
+ Manual = "manual",
+ Automated = "automated"
}
+type TSigningMethodOption = {
+ value: SigningMethod;
+ name: string;
+ description: string;
+ icon: typeof FileTextIcon;
+};
+
+const SIGNING_METHOD_OPTIONS: TSigningMethodOption[] = [
+ {
+ value: SigningMethod.Internal,
+ name: "Infisical CA",
+ description:
+ "Sign with an internal Infisical root or intermediate CA. Fully managed, no external setup needed.",
+ icon: ShieldCheckIcon
+ },
+ {
+ value: SigningMethod.Manual,
+ name: "Manual",
+ description:
+ "Download the CSR, sign it with your own root CA, then upload the signed certificate chain.",
+ icon: FileTextIcon
+ },
+ {
+ value: SigningMethod.Automated,
+ name: "External CA (Automated)",
+ description:
+ "Connect to a third-party CA provider. Certificate signing and renewal are handled automatically via API.",
+ icon: LinkIcon
+ }
+];
+
+type TIntegration = {
+ id: string;
+ name: string;
+ description: string;
+ image?: string;
+};
+
+const INTEGRATIONS: TIntegration[] = [
+ {
+ id: "venafi",
+ name: "Venafi TLS Protect Cloud",
+ description: "Automated certificate lifecycle management",
+ image: "/images/integrations/Venafi.png"
+ }
+];
+
+enum Step {
+ ChooseMethod = "choose-method",
+ ChooseIntegration = "choose-integration",
+ Form = "form"
+}
+
+type RadioCardProps = {
+ isSelected: boolean;
+ onClick: () => void;
+ icon?: React.ReactNode;
+ name: string;
+ description: string;
+ badge?: string;
+ className?: string;
+};
+
+const RadioCard = ({
+ isSelected,
+ onClick,
+ icon,
+ name,
+ description,
+ badge,
+ className
+}: RadioCardProps) => (
+ <button
+ type="button"
+ onClick={onClick}
+ className={`flex items-center gap-4 rounded-md border px-4 py-4 text-left transition-colors ${
+ isSelected
+ ? "border-project/50 bg-project/5"
+ : "border-mineshaft-600 bg-mineshaft-700 hover:bg-mineshaft-600"
+ } ${className ?? ""}`}
+ >
+ {icon}
+ <div className="flex-1">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-mineshaft-100">{name}</span>
+ {badge && <Badge variant="neutral">{badge}</Badge>}
+ </div>
+ <p className="mt-0.5 text-xs text-mineshaft-400">{description}</p>
+ </div>
+ <div
+ className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 ${
+ isSelected ? "border-none bg-project/30" : "border-mineshaft-500"
+ }`}
+ >
+ {isSelected && <div className="h-2 w-2 rounded-full bg-mineshaft-300" />}
+ </div>
+ </button>
+);
+
export const CaInstallCertModal = ({ popUp, handlePopUpToggle }: Props) => {
- const popupData = popUp?.installCaCert?.data;
- const caId = popupData?.caId || "";
- const isParentCaExternal = popupData?.isParentCaExternal || false;
- const [parentCaType, setParentCaType] = useState<ParentCaType>(ParentCaType.Internal);
-
- useEffect(() => {
- if (popupData?.isParentCaExternal) {
- setParentCaType(ParentCaType.External);
+ const popupData = popUp?.installCaCert?.data as { caId: string } | undefined;
+ const caId = popupData?.caId ?? "";
+
+ const [step, setStep] = useState<Step>(Step.ChooseMethod);
+ const [selectedMethod, setSelectedMethod] = useState<SigningMethod | null>(null);
+ const [selectedIntegration, setSelectedIntegration] = useState<string | null>(null);
+
+ const resetState = () => {
+ setStep(Step.ChooseMethod);
+ setSelectedMethod(null);
+ setSelectedIntegration(null);
+ };
+
+ const goBackToMethodSelection = () => {
+ setStep(Step.ChooseMethod);
+ setSelectedIntegration(null);
+ };
+
+ const handleContinue = () => {
+ if (!selectedMethod) return;
+
+ if (selectedMethod === SigningMethod.Automated) {
+ setStep(Step.ChooseIntegration);
+ return;
}
- }, [popupData]);
- const renderForm = (parentCaTypeInput: ParentCaType) => {
- switch (parentCaTypeInput) {
- case ParentCaType.Internal:
+ setStep(Step.Form);
+ };
+
+ const handleIntegrationContinue = () => {
+ if (!selectedIntegration) return;
+ setStep(Step.Form);
+ };
+
+ const renderForm = () => {
+ switch (selectedMethod) {
+ case SigningMethod.Internal:
return <InternalCaInstallForm caId={caId} handlePopUpToggle={handlePopUpToggle} />;
- default:
+ case SigningMethod.Automated:
+ return <VenafiCaInstallForm caId={caId} handlePopUpToggle={handlePopUpToggle} />;
+ case SigningMethod.Manual:
return <ExternalCaInstallForm caId={caId} handlePopUpToggle={handlePopUpToggle} />;
+ default:
+ return null;
}
};
+ const renderMethodSelection = () => (
+ <>
+ <div className="flex flex-col gap-3">
+ {SIGNING_METHOD_OPTIONS.map((option) => (
+ <RadioCard
+ key={option.value}
+ isSelected={selectedMethod === option.value}
+ onClick={() => setSelectedMethod(option.value)}
+ icon={
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-mineshaft-600">
+ <option.icon className="h-5 w-5 text-mineshaft-300" />
+ </div>
+ }
+ name={option.name}
+ description={option.description}
+ />
+ ))}
+ </div>
+ <div className="mt-6 flex items-center justify-end gap-2">
+ <Button variant="outline" onClick={() => handlePopUpToggle("installCaCert", false)}>
+ Cancel
+ </Button>
+ <Button variant="neutral" isDisabled={!selectedMethod} onClick={handleContinue}>
+ {selectedMethod === SigningMethod.Automated ? "Choose Integration" : "Continue"}
+ {selectedMethod === SigningMethod.Automated && <ArrowRightIcon />}
+ </Button>
+ </div>
+ </>
+ );
+
+ const renderIntegrationSelection = () => (
+ <>
+ <div className="flex flex-col gap-2">
+ {INTEGRATIONS.map((integration) => (
+ <RadioCard
+ key={integration.id}
+ isSelected={selectedIntegration === integration.id}
+ onClick={() => setSelectedIntegration(integration.id)}
+ icon={
+ integration.image ? (
+ <img
+ src={integration.image}
+ alt={`${integration.name} logo`}
+ className="h-8 w-8 rounded-md bg-bunker-500 object-contain p-1"
+ />
+ ) : undefined
+ }
+ name={integration.name}
+ description={integration.description}
+ className="py-3"
+ />
+ ))}
+ </div>
+ <div className="mt-6 flex items-center justify-end gap-2">
+ <Button variant="outline" onClick={goBackToMethodSelection}>
+ Back
+ </Button>
+ <Button
+ variant="neutral"
+ isDisabled={!selectedIntegration}
+ onClick={handleIntegrationContinue}
+ >
+ Continue
+ </Button>
+ </div>
+ </>
+ );
+
+ const renderFormStep = () => {
+ const selectedOption = SIGNING_METHOD_OPTIONS.find((o) => o.value === selectedMethod);
+ const integration = INTEGRATIONS.find((i) => i.id === selectedIntegration);
+
+ const isAutomated = selectedMethod === SigningMethod.Automated;
+ const displayName = isAutomated && integration ? integration.name : selectedOption?.name;
+ const displayDesc =
+ isAutomated && integration ? integration.description : selectedOption?.description;
+ const displayImage = isAutomated && integration ? integration.image : undefined;
+ const DisplayIcon = selectedOption?.icon;
+
+ return (
+ <>
+ <div className="mb-4 flex gap-3">
+ {displayImage ? (
+ <img
+ src={displayImage}
+ alt={`${displayName} logo`}
+ className="mt-0.5 h-8 w-8 shrink-0 rounded-md bg-bunker-500 object-contain p-1"
+ />
+ ) : (
+ DisplayIcon && (
+ <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-bunker-500">
+ <DisplayIcon className="h-4 w-4 text-mineshaft-300" />
+ </div>
+ )
+ )}
+ <div className="flex-1">
+ <div className="flex items-center">
+ <span className="flex-1 text-sm font-medium text-mineshaft-100">{displayName}</span>
+ <button
+ type="button"
+ className="shrink-0 text-xs text-mineshaft-400 underline underline-offset-2 hover:text-mineshaft-300"
+ onClick={resetState}
+ >
+ Change method
+ </button>
+ </div>
+ <p className="mt-0.5 text-xs text-mineshaft-400">{displayDesc}</p>
+ </div>
+ </div>
+ <hr className="-mx-6 mb-4 border-mineshaft-600" />
+ {renderForm()}
+ </>
+ );
+ };
+
+ const getTitle = () => {
+ if (step === Step.ChooseIntegration) {
+ return (
+ <div>
+ <button
+ type="button"
+ className="mb-2 flex items-center gap-1 text-xs text-mineshaft-400 hover:text-mineshaft-300"
+ onClick={goBackToMethodSelection}
+ >
+ <ArrowLeftIcon className="h-3 w-3" />
+ Back
+ </button>
+ <span>Choose a CA Integration</span>
+ </div>
+ );
+ }
+ return "Install Intermediate CA Certificate";
+ };
+
+ const getSubTitle = () => {
+ if (step === Step.ChooseMethod) {
+ return "Choose how the signing certificate for this CA should be issued.";
+ }
+ if (step === Step.ChooseIntegration) {
+ return "Select a provider to automate certificate signing for this intermediate CA.";
+ }
+ return undefined;
+ };
+
+ const needsOverflowVisible = step === Step.Form && selectedMethod === SigningMethod.Automated;
+
return (
<Modal
isOpen={popUp?.installCaCert?.isOpen}
onOpenChange={(isOpen) => {
+ if (!isOpen) resetState();
handlePopUpToggle("installCaCert", isOpen);
}}
>
<ModalContent
- title={`${isParentCaExternal ? "Renew" : "Install"} Intermediate CA certificate`}
+ title={getTitle()}
+ className="max-w-lg"
+ bodyClassName={needsOverflowVisible ? "overflow-visible" : undefined}
+ subTitle={getSubTitle()}
>
- <FormControl label="Parent CA Type">
- <Select
- value={parentCaType}
- onValueChange={(e) => setParentCaType(e as ParentCaType)}
- className="w-full"
- isDisabled={isParentCaExternal}
- >
- <SelectItem
- value={ParentCaType.Internal}
- key={`parent-ca-type-${ParentCaType.Internal}`}
- >
- Infisical CA
- </SelectItem>
- <SelectItem
- value={ParentCaType.External}
- key={`parent-ca-type-${ParentCaType.External}`}
- >
- External CA
- </SelectItem>
- </Select>
- </FormControl>
- {renderForm(parentCaType)}
+ {step === Step.ChooseMethod && renderMethodSelection()}
+ {step === Step.ChooseIntegration && renderIntegrationSelection()}
+ {step === Step.Form && renderFormStep()}
</ModalContent>
</Modal>
);
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsx
new file mode 100644
index 0000000000..27714054a0
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsx
@@ -0,0 +1,287 @@
+import { Controller, useForm } from "react-hook-form";
+import { SingleValue } from "react-select";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ FilterableSelect,
+ FormControl,
+ Input,
+ Select,
+ SelectItem
+} from "@app/components/v2";
+import { useProject } from "@app/context";
+import {
+ CaSigningConfigType,
+ useCreateCaSigningConfig,
+ useGetCaSigningConfig,
+ useInstallCaCertificateVenafi,
+ useUpdateCaSigningConfig
+} from "@app/hooks/api";
+import {
+ TAvailableAppConnection,
+ useListAvailableAppConnections
+} from "@app/hooks/api/appConnections";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import {
+ TVenafiApplication,
+ TVenafiIssuingTemplate,
+ useVenafiConnectionListApplications,
+ useVenafiConnectionListIssuingTemplates
+} from "@app/hooks/api/appConnections/venafi";
+import { UsePopUpState } from "@app/hooks/usePopUp";
+
+const schema = z.object({
+ appConnectionId: z.string().min(1, "App connection is required"),
+ applicationId: z.string().min(1, "Application is required"),
+ issuingTemplateId: z.string().min(1, "Issuing Template is required"),
+ validityPeriod: z.coerce
+ .number()
+ .int()
+ .min(1, "Must be at least 1 day")
+ .optional()
+ .or(z.literal("")),
+ maxPathLength: z.string()
+});
+
+type FormData = z.infer<typeof schema>;
+
+type Props = {
+ caId: string;
+ handlePopUpToggle: (popUpName: keyof UsePopUpState<["installCaCert"]>, state?: boolean) => void;
+};
+
+export const VenafiCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
+ const { currentProject } = useProject();
+
+ const { data: availableVenafiConnections, isPending: isVenafiPending } =
+ useListAvailableAppConnections(AppConnection.Venafi, currentProject.id);
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ watch,
+ setValue,
+ formState: { isSubmitting }
+ } = useForm<FormData>({
+ resolver: zodResolver(schema),
+ defaultValues: {
+ maxPathLength: "-1"
+ }
+ });
+
+ const selectedConnectionId = watch("appConnectionId");
+ const selectedApplicationId = watch("applicationId");
+
+ const { data: applications = [], isPending: isApplicationsLoading } =
+ useVenafiConnectionListApplications(selectedConnectionId ?? "", {
+ enabled: !!selectedConnectionId
+ });
+
+ const { data: issuingTemplates = [], isPending: isTemplatesLoading } =
+ useVenafiConnectionListIssuingTemplates(
+ selectedConnectionId ?? "",
+ selectedApplicationId ?? "",
+ {
+ enabled: !!selectedConnectionId && !!selectedApplicationId
+ }
+ );
+
+ const { data: existingSigningConfig } = useGetCaSigningConfig(caId, { enabled: !!caId });
+ const { mutateAsync: createSigningConfig } = useCreateCaSigningConfig();
+ const { mutateAsync: updateSigningConfig } = useUpdateCaSigningConfig();
+ const { mutateAsync: installVenafiCert } = useInstallCaCertificateVenafi(currentProject.id);
+
+ const onFormSubmit = async ({
+ appConnectionId,
+ applicationId,
+ issuingTemplateId,
+ validityPeriod,
+ maxPathLength
+ }: FormData) => {
+ if (!caId) return;
+
+ try {
+ const signingConfigPayload = {
+ applicationId,
+ issuingTemplateId,
+ ...(typeof validityPeriod === "number" && { validityPeriod })
+ };
+
+ if (existingSigningConfig?.type === CaSigningConfigType.VENAFI) {
+ await updateSigningConfig({
+ caId,
+ appConnectionId,
+ destinationConfig: signingConfigPayload
+ });
+ } else {
+ await createSigningConfig({
+ caId,
+ type: CaSigningConfigType.VENAFI,
+ appConnectionId,
+ destinationConfig: signingConfigPayload
+ });
+ }
+
+ await installVenafiCert({
+ caId,
+ maxPathLength: Number(maxPathLength)
+ });
+
+ reset();
+ handlePopUpToggle("installCaCert", false);
+ createNotification({
+ text: "Certificate installation has been queued",
+ type: "success"
+ });
+ } catch (err) {
+ createNotification({
+ text:
+ (err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
+ "Failed to install certificate via Venafi",
+ type: "error"
+ });
+ }
+ };
+
+ return (
+ <form onSubmit={handleSubmit(onFormSubmit)}>
+ <Controller
+ control={control}
+ name="appConnectionId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="Venafi Connection"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ >
+ <FilterableSelect
+ isLoading={isVenafiPending}
+ value={(availableVenafiConnections || []).find((conn) => conn.id === value)}
+ onChange={(option) => {
+ const selected = option as SingleValue<TAvailableAppConnection>;
+ onChange(selected?.id ?? "");
+ setValue("applicationId", "");
+ setValue("issuingTemplateId", "");
+ }}
+ options={availableVenafiConnections || []}
+ placeholder="Select a Venafi connection..."
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="applicationId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="Application"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ >
+ <FilterableSelect
+ isLoading={isApplicationsLoading && !!selectedConnectionId}
+ isDisabled={!selectedConnectionId}
+ value={applications.find((app) => app.id === value)}
+ onChange={(option) => {
+ const selected = option as SingleValue<TVenafiApplication>;
+ onChange(selected?.id ?? "");
+ setValue("issuingTemplateId", "");
+ }}
+ options={applications}
+ placeholder={
+ selectedConnectionId ? "Select an application..." : "Select a connection first"
+ }
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="issuingTemplateId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="Issuing Template"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ >
+ <FilterableSelect
+ isLoading={isTemplatesLoading && !!selectedApplicationId}
+ isDisabled={!selectedApplicationId}
+ value={issuingTemplates.find((tmpl) => tmpl.id === value)}
+ onChange={(option) => {
+ const selected = option as SingleValue<TVenafiIssuingTemplate>;
+ onChange(selected?.id ?? "");
+ }}
+ options={issuingTemplates}
+ placeholder={
+ selectedApplicationId
+ ? "Select an issuing template..."
+ : "Select an application first"
+ }
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="validityPeriod"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Validity Period (Days)"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ helperText="Number of days the certificate should be valid"
+ >
+ <Input {...field} type="number" placeholder="365" />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="maxPathLength"
+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (
+ <FormControl label="Path Length" errorText={error?.message} isError={Boolean(error)}>
+ <Select {...field} onValueChange={onChange} className="w-full">
+ {[-1, 0, 1, 2, 3].map((value) => (
+ <SelectItem value={String(value)} key={`ca-path-length-${value}`}>
+ {String(value)}
+ </SelectItem>
+ ))}
+ </Select>
+ </FormControl>
+ )}
+ />
+ <div className="flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ type="submit"
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting}
+ >
+ Install
+ </Button>
+ <Button
+ colorSchema="secondary"
+ variant="plain"
+ onClick={() => handlePopUpToggle("installCaCert", false)}
+ >
+ Cancel
+ </Button>
+ </div>
+ </form>
+ );
+};
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
index 27d5d45e8d..12e591afed 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
@@ -62,6 +62,7 @@ import { SshConnectionForm } from "./SshConnectionForm";
import { SupabaseConnectionForm } from "./SupabaseConnectionForm";
import { TeamCityConnectionForm } from "./TeamCityConnectionForm";
import { TerraformCloudConnectionForm } from "./TerraformCloudConnectionForm";
+import { VenafiConnectionForm } from "./VenafiConnectionForm";
import { VercelConnectionForm } from "./VercelConnectionForm";
import { WindmillConnectionForm } from "./WindmillConnectionForm";
import { ZabbixConnectionForm } from "./ZabbixConnectionForm";
@@ -261,6 +262,8 @@ const CreateForm = ({ app, onComplete, projectId }: CreateFormProps) => {
return <OpenRouterConnectionForm onSubmit={onSubmit} />;
case AppConnection.CircleCI:
return <CircleCIConnectionForm onSubmit={onSubmit} />;
+ case AppConnection.Venafi:
+ return <VenafiConnectionForm onSubmit={onSubmit} />;
default:
throw new Error(`Unhandled App ${app}`);
}
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/VenafiConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/VenafiConnectionForm.tsx
new file mode 100644
index 0000000000..3c0b8f6a8d
--- /dev/null
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/VenafiConnectionForm.tsx
@@ -0,0 +1,168 @@
+import { Controller, FormProvider, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import {
+ Button,
+ FormControl,
+ ModalClose,
+ SecretInput,
+ Select,
+ SelectItem
+} from "@app/components/v2";
+import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import { TVenafiConnection } from "@app/hooks/api/appConnections";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import {
+ VENAFI_REGION_LABELS,
+ VenafiConnectionMethod,
+ VenafiRegion
+} from "@app/hooks/api/appConnections/types/venafi-connection";
+
+import {
+ genericAppConnectionFieldsSchema,
+ GenericAppConnectionsFields
+} from "./GenericAppConnectionFields";
+
+type Props = {
+ appConnection?: TVenafiConnection;
+ onSubmit: (formData: FormData) => Promise<void>;
+};
+
+const rootSchema = genericAppConnectionFieldsSchema.extend({
+ app: z.literal(AppConnection.Venafi)
+});
+
+const formSchema = z.discriminatedUnion("method", [
+ rootSchema.extend({
+ method: z.literal(VenafiConnectionMethod.ApiKey),
+ credentials: z.object({
+ apiKey: z.string().trim().min(1, "API Key required"),
+ region: z.nativeEnum(VenafiRegion)
+ })
+ })
+]);
+
+type FormData = z.infer<typeof formSchema>;
+
+export const VenafiConnectionForm = ({ appConnection, onSubmit }: Props) => {
+ const isUpdate = Boolean(appConnection);
+
+ const form = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: appConnection ?? {
+ app: AppConnection.Venafi,
+ method: VenafiConnectionMethod.ApiKey,
+ credentials: {
+ region: VenafiRegion.US
+ }
+ }
+ });
+
+ const {
+ handleSubmit,
+ control,
+ formState: { isSubmitting, isDirty }
+ } = form;
+
+ return (
+ <FormProvider {...form}>
+ <form onSubmit={handleSubmit(onSubmit)}>
+ {!isUpdate && <GenericAppConnectionsFields />}
+ <Controller
+ name="method"
+ control={control}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl
+ tooltipText={`The method you would like to use to connect with ${
+ APP_CONNECTION_MAP[AppConnection.Venafi].name
+ }. This field cannot be changed after creation.`}
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Method"
+ >
+ <Select
+ isDisabled={isUpdate}
+ value={value}
+ onValueChange={(val) => onChange(val)}
+ className="w-full border border-mineshaft-500"
+ position="popper"
+ dropdownContainerClassName="max-w-none"
+ >
+ {Object.values(VenafiConnectionMethod).map((method) => {
+ return (
+ <SelectItem value={method} key={method}>
+ {getAppConnectionMethodDetails(method).name}
+ </SelectItem>
+ );
+ })}
+ </Select>
+ </FormControl>
+ )}
+ />
+ <Controller
+ name="credentials.region"
+ control={control}
+ shouldUnregister
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Region"
+ tooltipClassName="max-w-sm"
+ tooltipText="The region of your Venafi TLS Protect Cloud instance."
+ >
+ <Select
+ value={value}
+ onValueChange={(val) => onChange(val)}
+ className="w-full border border-mineshaft-500"
+ position="popper"
+ >
+ {Object.values(VenafiRegion).map((region) => (
+ <SelectItem value={region} key={region}>
+ {VENAFI_REGION_LABELS[region]}
+ </SelectItem>
+ ))}
+ </Select>
+ </FormControl>
+ )}
+ />
+ <Controller
+ name="credentials.apiKey"
+ control={control}
+ shouldUnregister
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="API Key"
+ >
+ <SecretInput
+ containerClassName="text-gray-400 group-focus-within:border-primary-400/50! border border-mineshaft-500 bg-mineshaft-900 px-2.5 py-1.5"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ />
+ </FormControl>
+ )}
+ />
+ <div className="mt-8 flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ type="submit"
+ colorSchema="secondary"
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting || (isUpdate && !isDirty)}
+ >
+ {isUpdate ? "Update Credentials" : "Connect to Venafi"}
+ </Button>
+ <ModalClose asChild>
+ <Button colorSchema="secondary" variant="plain">
+ Cancel
+ </Button>
+ </ModalClose>
+ </div>
+ </form>
+ </FormProvider>
+ );
+};