Skip to content

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

Add native Windows ADCS conenction logic

Carlos Monastyrski9ec80b90ddee
diff --git a/backend/src/db/migrations/20260703091544_add-pki-signer-external-ca-config.ts b/backend/src/db/migrations/20260703091544_add-pki-signer-external-ca-config.ts
new file mode 100644
index 0000000000..2b03b14194
--- /dev/null
+++ b/backend/src/db/migrations/20260703091544_add-pki-signer-external-ca-config.ts
@@ -0,0 +1,21 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasColumn = await knex.schema.hasColumn(TableName.PkiSigners, "externalCaConfig");
+ if (!hasColumn) {
+ await knex.schema.alterTable(TableName.PkiSigners, (t) => {
+ t.jsonb("externalCaConfig");
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasColumn = await knex.schema.hasColumn(TableName.PkiSigners, "externalCaConfig");
+ if (hasColumn) {
+ await knex.schema.alterTable(TableName.PkiSigners, (t) => {
+ t.dropColumn("externalCaConfig");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/pki-signers.ts b/backend/src/db/schemas/pki-signers.ts
index ebab3e66b1..f26d67b0e9 100644
--- a/backend/src/db/schemas/pki-signers.ts
+++ b/backend/src/db/schemas/pki-signers.ts
@@ -23,7 +23,8 @@ export const PkiSignersSchema = z.object({
certificateTtlDays: z.number().nullable().optional(),
certificateRenewBeforeDays: z.number().nullable().optional(),
certificateFailureReason: z.string().nullable().optional(),
- keyAlgorithm: z.string().default("RSA_2048")
+ keyAlgorithm: z.string().default("RSA_2048"),
+ externalCaConfig: z.unknown().nullable().optional()
});
export type TPkiSigners = z.infer<typeof PkiSignersSchema>;
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 0374d8b944..afd8477b86 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -372,6 +372,7 @@ export enum EventType {
DELETE_SSH_CERTIFICATE_TEMPLATE = "delete-ssh-certificate-template",
GET_SSH_CERTIFICATE_TEMPLATE = "get-ssh-certificate-template",
GET_AZURE_AD_TEMPLATES = "get-azure-ad-templates",
+ GET_ADCS_TEMPLATES = "get-adcs-templates",
GET_SSH_HOST = "get-ssh-host",
CREATE_SSH_HOST = "create-ssh-host",
UPDATE_SSH_HOST = "update-ssh-host",
@@ -3767,6 +3768,14 @@ interface GetAzureAdCsTemplatesEvent {
};
}
+interface GetAdcsTemplatesEvent {
+ type: EventType.GET_ADCS_TEMPLATES;
+ metadata: {
+ caId: string;
+ amount: number;
+ };
+}
+
interface UpdateCertificateTemplateEstConfig {
type: EventType.UPDATE_CERTIFICATE_TEMPLATE_EST_CONFIG;
metadata: {
@@ -7877,6 +7886,7 @@ export type Event =
| OrderCertificateFromProfile
| RenewCertificate
| GetAzureAdCsTemplatesEvent
+ | GetAdcsTemplatesEvent
| AttemptCreateSlackIntegration
| AttemptReinstallSlackIntegration
| UpdateSlackIntegration
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 5b07520476..5b91865775 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2199,6 +2199,9 @@ export const CERTIFICATE_AUTHORITIES = {
INSTALL_CERT_ADCS: {
caId: "The ID of the CA to install the certificate for via Azure AD CS."
},
+ INSTALL_CERT_ADCS_NATIVE: {
+ caId: "The ID of the CA to install the certificate for via ADCS."
+ },
CREATE_SIGNING_CONFIG: {
caId: "The ID of the CA to create a signing configuration for."
},
diff --git a/backend/src/lib/gateway-v2/adcs-rpc.ts b/backend/src/lib/gateway-v2/adcs-rpc.ts
new file mode 100644
index 0000000000..a2ba40cd68
--- /dev/null
+++ b/backend/src/lib/gateway-v2/adcs-rpc.ts
@@ -0,0 +1,154 @@
+import http from "node:http";
+
+import { logger } from "@app/lib/logger";
+
+export type AdcsRpcEndpoint = "/v1/test" | "/v1/discover-ca" | "/v1/templates" | "/v1/enroll";
+
+export type AdcsRpcRequestBody = {
+ host: string;
+ username: string;
+ password: string;
+ caName?: string;
+ params?: Record<string, unknown>;
+};
+
+export type AdcsTemplate = { name: string };
+export type AdcsTemplatesResult = { templates: AdcsTemplate[] };
+export type AdcsEnrollResult = {
+ disposition: number;
+ requestId: number;
+ certificatePem: string;
+ chainPem: string;
+ dispositionMessage?: string;
+ hresult?: number;
+};
+
+// CR_DISP_* request-disposition codes (small values) from ICertRequestD::Request.
+const ADCS_REQUEST_DISPOSITIONS: Record<number, string> = {
+ 0: "The request is incomplete.",
+ 1: "The certificate authority could not process the request.",
+ 2: "The request was denied by the certificate authority policy or an administrator.",
+ 5: "The request is pending administrator approval on the certificate authority."
+};
+
+// Common CERTSRV_E_*/HRESULT failure codes AD CS returns when a request cannot be issued.
+const ADCS_HRESULT_MESSAGES: Record<number, string> = {
+ 0x80094800: "The requested certificate template is not supported or is not published by this certificate authority.",
+ 0x80094801: "The request does not specify a certificate template.",
+ 0x80094012: "The connection account does not have Enroll permission on the requested certificate template.",
+ 0x80094011: "The certificate template requires an email address in the subject, which was not provided.",
+ 0x80094009: "The certificate template requires a DNS name in the subject alternative name, which was not provided.",
+ 0x80094003: "The subject name in the request is invalid or not permitted by the certificate template.",
+ 0x80070005: "Access was denied by the certificate authority.",
+ 0x80070057:
+ "The certificate authority rejected the request arguments. Verify the certificate authority name and template."
+};
+
+/**
+ * Turns an AD CS enrollment failure into an actionable message. Prefers the known
+ * meaning of the disposition/HRESULT, folds in the CA's own status string when present,
+ * and always includes the raw code + request id for support.
+ */
+export const describeAdcsDisposition = (
+ disposition: number,
+ opts?: { requestId?: number; dispositionMessage?: string; hresult?: number }
+): string => {
+ // Normalize a signed int32 (e.g. -2146875392) to its unsigned 32-bit form (0x80094800).
+ const raw = opts?.hresult ?? disposition;
+ const code = raw < 0 ? raw + 2 ** 32 : raw;
+ const hex = `0x${code.toString(16).padStart(8, "0")}`;
+ // CR_DISP_* codes are small (0-5); CERTSRV_E_*/HRESULTs have the high bit set (> 0xffff),
+ // so magnitude disambiguates which table to consult when no explicit hresult is given.
+ const known = ADCS_HRESULT_MESSAGES[code] ?? (code <= 0xffff ? ADCS_REQUEST_DISPOSITIONS[code] : undefined);
+ const caMessage = opts?.dispositionMessage?.trim();
+
+ let reason = known;
+ if (!reason && caMessage) {
+ reason = caMessage;
+ } else if (reason && caMessage && !reason.toLowerCase().includes(caMessage.toLowerCase())) {
+ reason = `${reason} (CA reported: ${caMessage})`;
+ }
+
+ const suffix = [`[disposition=${hex}]`];
+ if (opts?.requestId) suffix.push(`[requestId=${opts.requestId}]`);
+
+ return `Active Directory Certificate Service did not issue the certificate.${reason ? ` ${reason}` : ""} ${suffix.join(" ")}`;
+};
+
+// CR_DISP_ISSUED: the CA issued the certificate (MS-WCCE ICertRequestD::Request disposition).
+export const ADCS_DISPOSITION_ISSUED = 3;
+
+export type AdcsRpcSuccess<T> = { ok: true; status: number; result: T };
+export type AdcsRpcFailure = { ok: false; status: number; errorMessage: string };
+export type AdcsRpcResponse<T> = AdcsRpcSuccess<T> | AdcsRpcFailure;
+
+// Enrollment can take longer than a simple property read (CA policy modules,
+// pending approval checks), so allow a generous ceiling.
+export const ADCS_RPC_TIMEOUT_MS = 90_000;
+
+export const callAdcsEndpoint = async <T>(args: {
+ port: number;
+ endpoint: AdcsRpcEndpoint;
+ body: AdcsRpcRequestBody;
+}): Promise<AdcsRpcResponse<T>> => {
+ const payload = JSON.stringify(args.body);
+ return new Promise<AdcsRpcResponse<T>>((resolve, reject) => {
+ const req = http.request(
+ {
+ host: "127.0.0.1",
+ port: args.port,
+ path: args.endpoint,
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "Content-Length": Buffer.byteLength(payload).toString(),
+ Connection: "close"
+ },
+ timeout: ADCS_RPC_TIMEOUT_MS
+ },
+ (res) => {
+ const chunks: Buffer[] = [];
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
+ res.on("end", () => {
+ const text = Buffer.concat(chunks).toString("utf8");
+ const status = res.statusCode ?? 0;
+ if (!text) {
+ resolve({ ok: false, status, errorMessage: `Empty response body from Gateway (status ${status})` });
+ return;
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ resolve({ ok: false, status, errorMessage: `Malformed response body from Gateway: ${text.slice(0, 256)}` });
+ return;
+ }
+ if (status >= 200 && status < 300) {
+ const { result } = parsed as { result?: T };
+ if (result === undefined) {
+ resolve({ ok: false, status, errorMessage: "Gateway response missing `result` field" });
+ return;
+ }
+ resolve({ ok: true, status, result });
+ return;
+ }
+ const errEnv = (parsed as { error?: { message?: string } }).error;
+ resolve({ ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` });
+ });
+ res.on("error", (err) => {
+ logger.warn({ err }, `ADCS RPC response stream error [port=${args.port}]`);
+ reject(err);
+ });
+ }
+ );
+ req.on("timeout", () => {
+ req.destroy(new Error(`ADCS RPC timed out after ${ADCS_RPC_TIMEOUT_MS}ms`));
+ });
+ req.on("error", (err) => {
+ logger.warn({ err }, `ADCS RPC request error [port=${args.port}]`);
+ reject(err);
+ });
+ req.write(payload);
+ req.end();
+ });
+};
diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.ts
index 7c37d5014b..dafd9eea30 100644
--- a/backend/src/lib/gateway-v2/gateway-v2.ts
+++ b/backend/src/lib/gateway-v2/gateway-v2.ts
@@ -96,7 +96,8 @@ export const createGatewayConnection = async (
[GatewayProxyProtocol.Pam]: ["infisical-pam-proxy"],
[GatewayProxyProtocol.PamRdpBrowser]: ["infisical-pam-rdp-browser"],
[GatewayProxyProtocol.PamSessionCancellation]: ["infisical-pam-session-cancellation"],
- [GatewayProxyProtocol.Pkcs11]: ["infisical-pkcs11"]
+ [GatewayProxyProtocol.Pkcs11]: ["infisical-pkcs11"],
+ [GatewayProxyProtocol.Adcs]: ["infisical-adcs"]
};
const tlsOptions: tls.ConnectionOptions = {
diff --git a/backend/src/lib/gateway/types.ts b/backend/src/lib/gateway/types.ts
index cf22b9fdba..a874846fc3 100644
--- a/backend/src/lib/gateway/types.ts
+++ b/backend/src/lib/gateway/types.ts
@@ -12,7 +12,8 @@ export enum GatewayProxyProtocol {
Pam = "pam",
PamRdpBrowser = "pam-rdp-browser",
PamSessionCancellation = "pam-session-cancellation",
- Pkcs11 = "pkcs11"
+ Pkcs11 = "pkcs11",
+ Adcs = "adcs"
}
export enum GatewayHttpProxyActions {
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 86bf9b8626..5c7cda14fb 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -185,6 +185,7 @@ export enum QueueJobs {
CaDailyAutoRenewal = "ca-daily-auto-renewal",
CaVenafiInstall = "ca-venafi-install-job",
CaAdcsInstall = "ca-adcs-install-job",
+ CaNativeAdcsInstall = "ca-native-adcs-install-job",
CertificateCleanup = "certificate-cleanup-job",
DailySecretSyncRetry = "daily-secret-sync-retry-job",
DigiCertOrderPolling = "digicert-order-polling-job",
@@ -516,6 +517,10 @@ export type TQueueJobTypes = {
| {
name: QueueJobs.CaAdcsInstall;
payload: { caId: string; maxPathLength?: number };
+ }
+ | {
+ name: QueueJobs.CaNativeAdcsInstall;
+ payload: { caId: string; maxPathLength?: number };
};
[QueueName.ProjectHardDelete]: {
name: QueueJobs.ProjectHardDelete;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 171ef8d466..e4243deb76 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2944,7 +2944,9 @@ export const registerRoutes = async (
caSigningConfigDAL,
internalCertificateAuthorityService,
appConnectionDAL,
- kmsService
+ kmsService,
+ gatewayV2Service,
+ gatewayPoolService
});
const caSigningConfigService = caSigningConfigServiceFactory({
diff --git a/backend/src/server/routes/v1/app-connection-routers/adcs-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/adcs-connection-router.ts
new file mode 100644
index 0000000000..a192a3579c
--- /dev/null
+++ b/backend/src/server/routes/v1/app-connection-routers/adcs-connection-router.ts
@@ -0,0 +1,56 @@
+import z from "zod";
+
+import { readLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import {
+ CreateADCSConnectionSchema,
+ SanitizedADCSConnectionSchema,
+ UpdateADCSConnectionSchema
+} from "@app/services/app-connection/adcs";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+import { registerAppConnectionEndpoints } from "./app-connection-endpoints";
+
+export const registerADCSConnectionRouter = async (server: FastifyZodProvider) => {
+ registerAppConnectionEndpoints({
+ app: AppConnection.ADCS,
+ server,
+ sanitizedResponseSchema: SanitizedADCSConnectionSchema,
+ createSchema: CreateADCSConnectionSchema,
+ updateSchema: UpdateADCSConnectionSchema
+ });
+
+ server.route({
+ method: "GET",
+ url: `/:connectionId/certificate-templates`,
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listAdcsCertificateTemplates",
+ params: z.object({
+ connectionId: z.string().uuid()
+ }),
+ querystring: z.object({
+ caName: z.string().trim().min(1).optional()
+ }),
+ response: {
+ 200: z.object({
+ templates: z.object({ name: z.string() }).array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { connectionId } = req.params;
+ const { caName } = req.query;
+ const templates = await server.services.appConnection.adcs.listCertificateTemplates(
+ connectionId,
+ caName,
+ req.permission
+ );
+ return { templates };
+ }
+ });
+};
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 7e991ffdd1..3a4094ed4b 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
@@ -15,6 +15,10 @@ import {
OnePassConnectionListItemSchema,
SanitizedOnePassConnectionSchema
} from "@app/services/app-connection/1password";
+import {
+ ADCSConnectionListItemSchema,
+ SanitizedADCSConnectionSchema
+} from "@app/services/app-connection/adcs/adcs-connection-schemas";
import {
AnthropicConnectionListItemSchema,
SanitizedAnthropicConnectionSchema
@@ -269,6 +273,7 @@ const SanitizedAppConnectionSchema = z.union([
...SanitizedNorthflankConnectionSchema.options,
...SanitizedOktaConnectionSchema.options,
...SanitizedAzureADCSConnectionSchema.options,
+ ...SanitizedADCSConnectionSchema.options,
...SanitizedRedisConnectionSchema.options,
...SanitizedMongoDBConnectionSchema.options,
...SanitizedLaravelForgeConnectionSchema.options,
@@ -345,6 +350,7 @@ const AppConnectionOptionsSchema = z.discriminatedUnion("app", [
NorthflankConnectionListItemSchema,
OktaConnectionListItemSchema,
AzureADCSConnectionListItemSchema,
+ ADCSConnectionListItemSchema,
RedisConnectionListItemSchema,
MongoDBConnectionListItemSchema,
LaravelForgeConnectionListItemSchema,
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 360015696a..5a117c2350 100644
--- a/backend/src/server/routes/v1/app-connection-routers/index.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/index.ts
@@ -4,6 +4,7 @@ import { registerOracleDBConnectionRouter } from "@app/ee/routes/v1/app-connecti
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { registerOnePassConnectionRouter } from "./1password-connection-router";
+import { registerADCSConnectionRouter } from "./adcs-connection-router";
import { registerAnthropicConnectionRouter } from "./anthropic-connection-router";
import { registerAuth0ConnectionRouter } from "./auth0-connection-router";
import { registerAwsConnectionRouter } from "./aws-connection-router";
@@ -87,6 +88,7 @@ export const APP_CONNECTION_REGISTER_ROUTER_MAP: Record<AppConnection, (server:
[AppConnection.AzureClientSecrets]: registerAzureClientSecretsConnectionRouter,
[AppConnection.AzureDevOps]: registerAzureDevOpsConnectionRouter,
[AppConnection.AzureADCS]: registerAzureADCSConnectionRouter,
+ [AppConnection.ADCS]: registerADCSConnectionRouter,
[AppConnection.AzureDNS]: registerAzureDnsConnectionRouter,
[AppConnection.Databricks]: registerDatabricksConnectionRouter,
[AppConnection.Humanitec]: registerHumanitecConnectionRouter,
diff --git a/backend/src/server/routes/v1/certificate-authority-routers/adcs-certificate-authority-router.ts b/backend/src/server/routes/v1/certificate-authority-routers/adcs-certificate-authority-router.ts
new file mode 100644
index 0000000000..88ecb533ac
--- /dev/null
+++ b/backend/src/server/routes/v1/certificate-authority-routers/adcs-certificate-authority-router.ts
@@ -0,0 +1,80 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { readLimit } from "@app/server/config/rateLimiter";
+import { openApiHidden } from "@app/server/lib/schemas";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import {
+ ADCSCertificateAuthoritySchema,
+ CreateADCSCertificateAuthoritySchema,
+ UpdateADCSCertificateAuthoritySchema
+} from "@app/services/certificate-authority/adcs/adcs-certificate-authority-schemas";
+import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";
+
+import { registerCertificateAuthorityEndpoints } from "./certificate-authority-endpoints";
+
+export const registerADCSCertificateAuthorityRouter = async (server: FastifyZodProvider) => {
+ registerCertificateAuthorityEndpoints({
+ caType: CaType.ADCS,
+ server,
+ responseSchema: ADCSCertificateAuthoritySchema,
+ createSchema: CreateADCSCertificateAuthoritySchema,
+ updateSchema: UpdateADCSCertificateAuthoritySchema
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:caId/templates",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ operationId: "getAdcsTemplates",
+ description: "Get available certificate templates from ADCS CA",
+ params: z.object({
+ caId: z.string().describe("ADCS CA ID")
+ }),
+ querystring: z.object({
+ projectId: z.string().optional().describe(openApiHidden())
+ }),
+ response: {
+ 200: z.object({
+ templates: z.array(
+ z.object({
+ id: z.string().describe("Template identifier"),
+ name: z.string().describe("Template display name")
+ })
+ )
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const projectId = req.internalCertManagerProjectId;
+ const templates = await server.services.certificateAuthority.getADCSTemplates({
+ caId: req.params.caId,
+ projectId,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId,
+ event: {
+ type: EventType.GET_ADCS_TEMPLATES,
+ metadata: {
+ caId: req.params.caId,
+ amount: templates.length
+ }
+ }
+ });
+
+ return { templates };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/certificate-authority-routers/general-certificate-authority-router.ts b/backend/src/server/routes/v1/certificate-authority-routers/general-certificate-authority-router.ts
index d20844b4dd..7845a63777 100644
--- a/backend/src/server/routes/v1/certificate-authority-routers/general-certificate-authority-router.ts
+++ b/backend/src/server/routes/v1/certificate-authority-routers/general-certificate-authority-router.ts
@@ -7,6 +7,7 @@ import { openApiHidden } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
import { SanitizedAcmeCertificateAuthoritySchema } from "@app/services/certificate-authority/acme/acme-certificate-authority-schemas";
+import { ADCSCertificateAuthoritySchema } from "@app/services/certificate-authority/adcs/adcs-certificate-authority-schemas";
import { AwsAcmPublicCaCertificateAuthoritySchema } from "@app/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-schemas";
import { AwsPcaCertificateAuthoritySchema } from "@app/services/certificate-authority/aws-pca/aws-pca-certificate-authority-schemas";
import { AzureAdCsCertificateAuthoritySchema } from "@app/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-schemas";
@@ -20,6 +21,7 @@ const CertificateAuthoritySchema = z.discriminatedUnion("type", [
InternalCertificateAuthoritySchema,
SanitizedAcmeCertificateAuthoritySchema,
AzureAdCsCertificateAuthoritySchema,
+ ADCSCertificateAuthoritySchema,
AwsPcaCertificateAuthoritySchema,
DigiCertCertificateAuthoritySchema,
GoDaddyCertificateAuthoritySchema,
@@ -75,6 +77,14 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
req.permission
);
+ const adcsCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
+ {
+ projectId,
+ type: CaType.ADCS
+ },
+ req.permission
+ );
+
const awsPcaCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
projectId,
@@ -125,6 +135,7 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
...(internalCas ?? []).map((ca) => ca.id),
...(acmeCas ?? []).map((ca) => ca.id),
...(azureAdCsCas ?? []).map((ca) => ca.id),
+ ...(adcsCas ?? []).map((ca) => ca.id),
...(awsPcaCas ?? []).map((ca) => ca.id),
...(digicertCas ?? []).map((ca) => ca.id),
...(awsAcmPublicCas ?? []).map((ca) => ca.id),
@@ -140,6 +151,7 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
...(internalCas ?? []),
...(acmeCas ?? []),
...(azureAdCsCas ?? []),
+ ...(adcsCas ?? []),
...(awsPcaCas ?? []),
...(digicertCas ?? []),
...(awsAcmPublicCas ?? []),
diff --git a/backend/src/server/routes/v1/certificate-authority-routers/index.ts b/backend/src/server/routes/v1/certificate-authority-routers/index.ts
index 34e23e02e2..ea1074c012 100644
--- a/backend/src/server/routes/v1/certificate-authority-routers/index.ts
+++ b/backend/src/server/routes/v1/certificate-authority-routers/index.ts
@@ -1,6 +1,7 @@
import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";
import { registerAcmeCertificateAuthorityRouter } from "./acme-certificate-authority-router";
+import { registerADCSCertificateAuthorityRouter } from "./adcs-certificate-authority-router";
import { registerAwsAcmPublicCaCertificateAuthorityRouter } from "./aws-acm-public-ca-certificate-authority-router";
import { registerAwsPcaCertificateAuthorityRouter } from "./aws-pca-certificate-authority-router";
import { registerAzureAdCsCertificateAuthorityRouter } from "./azure-ad-cs-certificate-authority-router";
@@ -16,6 +17,7 @@ export const CERTIFICATE_AUTHORITY_REGISTER_ROUTER_MAP: Record<CaType, (server:
[CaType.INTERNAL]: registerInternalCertificateAuthorityRouter,
[CaType.ACME]: registerAcmeCertificateAuthorityRouter,
[CaType.AZURE_AD_CS]: registerAzureAdCsCertificateAuthorityRouter,
+ [CaType.ADCS]: registerADCSCertificateAuthorityRouter,
[CaType.AWS_PCA]: registerAwsPcaCertificateAuthorityRouter,
[CaType.DIGICERT]: registerDigiCertCertificateAuthorityRouter,
[CaType.GODADDY]: registerGoDaddyCertificateAuthorityRouter,
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 d02207a142..6b5470582a 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
@@ -9,6 +9,7 @@ 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 {
+ AdcsDestinationConfigSchema,
AzureAdCsDestinationConfigSchema,
DestinationConfigSchema,
VenafiDestinationConfigSchema
@@ -718,7 +719,7 @@ export const registerInternalCertificateAuthorityRouter = async (server: Fastify
hide: false,
operationId: "installCaCertificateAdcs",
tags: [ApiDocsTags.PkiCertificateAuthorities],
- description: "Install a CA certificate via Azure AD CS",
+ description: "Install a CA certificate via Azure AD CS (Web Enrollment)",
params: z.object({
caId: z.string().trim().describe(CERTIFICATE_AUTHORITIES.INSTALL_CERT_ADCS.caId)
}),
@@ -761,6 +762,60 @@ export const registerInternalCertificateAuthorityRouter = async (server: Fastify
}
});
+ server.route({
+ method: "POST",
+ url: "/:caId/install-certificate-adcs-native",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ operationId: "installCaCertificateAdcsNative",
+ tags: [ApiDocsTags.PkiCertificateAuthorities],
+ description: "Install a CA certificate via ADCS",
+ params: z.object({
+ caId: z.string().trim().describe(CERTIFICATE_AUTHORITIES.INSTALL_CERT_ADCS_NATIVE.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.installCertificateAdcsNative({
+ 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_ADCS,
+ 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",
@@ -793,6 +848,11 @@ export const registerInternalCertificateAuthorityRouter = async (server: Fastify
type: z.literal(CaSigningConfigType.AzureAdCs),
appConnectionId: z.string().uuid(),
destinationConfig: AzureAdCsDestinationConfigSchema
+ }),
+ z.object({
+ type: z.literal(CaSigningConfigType.Adcs),
+ appConnectionId: z.string().uuid(),
+ destinationConfig: AdcsDestinationConfigSchema
})
]),
response: {
diff --git a/backend/src/server/routes/v1/signer-routers/schemas.ts b/backend/src/server/routes/v1/signer-routers/schemas.ts
index e7686a4b2d..0cb25ac1f9 100644
--- a/backend/src/server/routes/v1/signer-routers/schemas.ts
+++ b/backend/src/server/routes/v1/signer-routers/schemas.ts
@@ -16,6 +16,15 @@ export const SignerExternalConfigurationSchema = z.discriminatedUnion("caType",
.describe(
"Reissue into this existing DigiCert order instead of placing a new order (reuses the subscription slot)."
)
+ }),
+ z.object({
+ caType: z.literal(CaType.ADCS),
+ template: z
+ .string()
+ .trim()
+ .min(1)
+ .optional()
+ .describe("The AD CS certificate template this signer requests when issuing (e.g. a code-signing template).")
})
]);
diff --git a/backend/src/server/routes/v2/certificate-authority-router.ts b/backend/src/server/routes/v2/certificate-authority-router.ts
index b77bfdb3a3..7aa91c3631 100644
--- a/backend/src/server/routes/v2/certificate-authority-router.ts
+++ b/backend/src/server/routes/v2/certificate-authority-router.ts
@@ -7,6 +7,7 @@ import { openApiHidden } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
import { SanitizedAcmeCertificateAuthoritySchema } from "@app/services/certificate-authority/acme/acme-certificate-authority-schemas";
+import { ADCSCertificateAuthoritySchema } from "@app/services/certificate-authority/adcs/adcs-certificate-authority-schemas";
import { AwsAcmPublicCaCertificateAuthoritySchema } from "@app/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-schemas";
import { AwsPcaCertificateAuthoritySchema } from "@app/services/certificate-authority/aws-pca/aws-pca-certificate-authority-schemas";
import { AzureAdCsCertificateAuthoritySchema } from "@app/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-schemas";
@@ -20,6 +21,7 @@ const CertificateAuthoritySchema = z.discriminatedUnion("type", [
InternalCertificateAuthoritySchema,
SanitizedAcmeCertificateAuthoritySchema,
AzureAdCsCertificateAuthoritySchema,
+ ADCSCertificateAuthoritySchema,
AwsPcaCertificateAuthoritySchema,
DigiCertCertificateAuthoritySchema,
GoDaddyCertificateAuthoritySchema,
diff --git a/backend/src/services/app-connection/adcs/adcs-connection-enums.ts b/backend/src/services/app-connection/adcs/adcs-connection-enums.ts
new file mode 100644
index 0000000000..c561c43ffe
--- /dev/null
+++ b/backend/src/services/app-connection/adcs/adcs-connection-enums.ts
@@ -0,0 +1,3 @@
+export enum ADCSConnectionMethod {
+ UsernamePassword = "username-password"
+}
diff --git a/backend/src/services/app-connection/adcs/adcs-connection-fns.ts b/backend/src/services/app-connection/adcs/adcs-connection-fns.ts
new file mode 100644
index 0000000000..75fd4fe913
--- /dev/null
+++ b/backend/src/services/app-connection/adcs/adcs-connection-fns.ts
@@ -0,0 +1,166 @@
+import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { BadRequestError } from "@app/lib/errors";
+import { GatewayProxyProtocol } from "@app/lib/gateway/types";
+import { AdcsRpcEndpoint, callAdcsEndpoint } from "@app/lib/gateway-v2/adcs-rpc";
+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+
+import { ADCSConnectionMethod } from "./adcs-connection-enums";
+import { TADCSConnectionConfig } from "./adcs-connection-types";
+
+// The gateway routes ADCS operations by ALPN, so the target host/port carried in
+// the client certificate is not used. A stable placeholder keeps routing happy.
+const ADCS_TARGET_HOST = "adcs";
+
+export type TADCSGatewayDeps = {
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+};
+
+export const getADCSConnectionListItem = () => ({
+ name: "ADCS" as const,
+ app: AppConnection.ADCS as const,
+ methods: Object.values(ADCSConnectionMethod) as [ADCSConnectionMethod.UsernamePassword]
+});
+
+/**
+ * Runs a single MS-WCCE operation on the gateway that sits inside the customer
+ * network. AD CS speaks DCOM, which the control plane cannot reach directly, so
+ * a gateway is always required for this connection.
+ */
+export const executeAdcsGatewayOperation = async <T>(
+ args: {
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ credentials: { host: string; username: string; password: string };
+ endpoint: AdcsRpcEndpoint;
+ caName?: string;
+ params?: Record<string, unknown>;
+ },
+ deps: TADCSGatewayDeps
+): Promise<T> => {
+ const { gatewayV2Service, gatewayPoolService } = deps;
+
+ if (args.gatewayPoolId && !gatewayPoolService) {
+ throw new BadRequestError({ message: "Pool-backed connections require gatewayPoolService at the call site" });
+ }
+
+ const gatewayId =
+ args.gatewayPoolId && gatewayPoolService
+ ? await gatewayPoolService.resolveEffectiveGatewayId({
+ gatewayId: args.gatewayId,
+ gatewayPoolId: args.gatewayPoolId
+ })
+ : args.gatewayId;
+
+ if (!gatewayId) {
+ throw new BadRequestError({
+ message: "ADCS connections require a gateway to reach the certificate authority."
+ });
+ }
+
+ const connectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
+ gatewayId,
+ targetHost: ADCS_TARGET_HOST,
+ targetPort: 0
+ });
+ if (!connectionDetails) {
+ throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
+ }
+
+ const response = await withGatewayV2Proxy(
+ async (port) =>
+ callAdcsEndpoint<T>({
+ port,
+ endpoint: args.endpoint,
+ body: {
+ host: args.credentials.host,
+ username: args.credentials.username,
+ password: args.credentials.password,
+ caName: args.caName,
+ params: args.params
+ }
+ }),
+ {
+ protocol: GatewayProxyProtocol.Adcs,
+ relayHost: connectionDetails.relayHost,
+ gateway: connectionDetails.gateway,
+ relay: connectionDetails.relay
+ }
+ );
+
+ if (!response.ok) {
+ const errorMessage = response.errorMessage ?? "";
+ // E_INVALIDARG (0x80070057) from the CA almost always means the CA authority name
+ // or the requested template is wrong, rather than a transport-level failure.
+ if (errorMessage.includes("E_INVALIDARG") || errorMessage.includes("0x80070057")) {
+ throw new BadRequestError({
+ message:
+ "The certificate authority rejected the request (E_INVALIDARG). Verify the certificate authority name and template are correct for this host."
+ });
+ }
+ throw new BadRequestError({ message: `ADCS gateway operation failed: ${errorMessage}` });
+ }
+ return response.result;
+};
+
+type TAdcsConnectionTarget = {
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ credentials: { host: string; username: string; password: string };
+};
+
+/**
+ * Returns the caller-supplied CA name, or discovers it from the CA host's registry over the
+ * gateway (the CertSvc "Active" value) when omitted. `getTarget` is only invoked when discovery
+ * is needed, so callers that already have a CA name pay no gateway/credential cost.
+ */
+export const resolveAdcsCaName = async (
+ caName: string | undefined,
+ getTarget: () => Promise<TAdcsConnectionTarget>,
+ deps: TADCSGatewayDeps
+): Promise<string> => {
+ if (caName) return caName;
+
+ const target = await getTarget();
+ const discovered = await executeAdcsGatewayOperation<{ caName: string }>(
+ { ...target, endpoint: "/v1/discover-ca" },
+ deps
+ );
+ if (!discovered?.caName) {
+ throw new BadRequestError({
+ message:
+ "Could not automatically discover the certificate authority name from the host. Provide the Certificate Authority name explicitly."
+ });
+ }
+ return discovered.caName;
+};
+
+export const validateADCSConnectionCredentials = async (
+ config: TADCSConnectionConfig,
+ _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
+) => {
+ try {
+ await executeAdcsGatewayOperation<{ ok: boolean }>(
+ {
+ gatewayId: config.gatewayId,
+ gatewayPoolId: config.gatewayPoolId,
+ credentials: config.credentials,
+ endpoint: "/v1/test"
+ },
+ { gatewayV2Service }
+ );
+
+ return config.credentials;
+ } catch (error) {
+ throw new BadRequestError({
+ message: `Unable to validate connection: ${
+ (error as Error)?.message?.replaceAll(config.credentials.password, "********************") ??
+ "verify credentials"
+ }`
+ });
+ }
+};
diff --git a/backend/src/services/app-connection/adcs/adcs-connection-schemas.ts b/backend/src/services/app-connection/adcs/adcs-connection-schemas.ts
new file mode 100644
index 0000000000..bbfa889ee8
--- /dev/null
+++ b/backend/src/services/app-connection/adcs/adcs-connection-schemas.ts
@@ -0,0 +1,67 @@
+import { z } from "zod";
+
+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 { ADCSConnectionMethod } from "./adcs-connection-enums";
+
+export const ADCSUsernamePasswordCredentialsSchema = z.object({
+ host: z
+ .string()
+ .trim()
+ .min(1, "CA host required")
+ .max(255)
+ .describe("The AD CS server's DNS name (FQDN), for example ca01.corp.example.com."),
+ username: z
+ .string()
+ .trim()
+ .min(1, "Username required")
+ .max(255)
+ .describe("Windows login: DOMAIN\\user or user@domain."),
+ password: z.string().trim().min(1, "Password required").max(255).describe("The account password.")
+});
+
+const BaseADCSConnectionSchema = BaseAppConnectionSchema.extend({ app: z.literal(AppConnection.ADCS) });
+
+export const ADCSConnectionSchema = BaseADCSConnectionSchema.extend({
+ method: z.literal(ADCSConnectionMethod.UsernamePassword),
+ credentials: ADCSUsernamePasswordCredentialsSchema
+});
+
+export const SanitizedADCSConnectionSchema = z.discriminatedUnion("method", [
+ BaseADCSConnectionSchema.extend({
+ method: z.literal(ADCSConnectionMethod.UsernamePassword),
+ // Never return the password.
+ credentials: ADCSUsernamePasswordCredentialsSchema.pick({ host: true, username: true })
+ }).describe(JSON.stringify({ title: `${APP_CONNECTION_NAME_MAP[AppConnection.ADCS]} (Username and Password)` }))
+]);
+
+export const ValidateADCSConnectionCredentialsSchema = z.discriminatedUnion("method", [
+ z.object({
+ method: z.literal(ADCSConnectionMethod.UsernamePassword),
+ credentials: ADCSUsernamePasswordCredentialsSchema
+ })
+]);
+
+export const CreateADCSConnectionSchema = ValidateADCSConnectionCredentialsSchema.and(
+ GenericCreateAppConnectionFieldsSchema(AppConnection.ADCS, { supportsGateways: true })
+);
+
+export const UpdateADCSConnectionSchema = z
+ .object({
+ credentials: ADCSUsernamePasswordCredentialsSchema.optional()
+ })
+ .and(GenericUpdateAppConnectionFieldsSchema(AppConnection.ADCS, { supportsGateways: true }));
+
+export const ADCSConnectionListItemSchema = z
+ .object({
+ name: z.literal("ADCS"),
+ app: z.literal(AppConnection.ADCS),
+ methods: z.nativeEnum(ADCSConnectionMethod).array()
+ })
+ .describe(JSON.stringify({ title: APP_CONNECTION_NAME_MAP[AppConnection.ADCS] }));
diff --git a/backend/src/services/app-connection/adcs/adcs-connection-service.ts b/backend/src/services/app-connection/adcs/adcs-connection-service.ts
new file mode 100644
index 0000000000..abea158cc8
--- /dev/null
+++ b/backend/src/services/app-connection/adcs/adcs-connection-service.ts
@@ -0,0 +1,46 @@
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { AdcsTemplatesResult } from "@app/lib/gateway-v2/adcs-rpc";
+import { OrgServiceActor } from "@app/lib/types";
+
+import { AppConnection } from "../app-connection-enums";
+import { executeAdcsGatewayOperation, resolveAdcsCaName } from "./adcs-connection-fns";
+import { TADCSConnection } from "./adcs-connection-types";
+
+type TGetAppConnectionFunc = (
+ app: AppConnection,
+ connectionId: string,
+ actor: OrgServiceActor
+) => Promise<TADCSConnection>;
+
+export const adcsConnectionService = (
+ getAppConnection: TGetAppConnectionFunc,
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">
+) => {
+ const targetFor = (appConnection: TADCSConnection) => ({
+ gatewayId: appConnection.gatewayId,
+ gatewayPoolId: appConnection.gatewayPoolId,
+ credentials: appConnection.credentials
+ });
+
+ const listCertificateTemplates = async (connectionId: string, caName: string | undefined, actor: OrgServiceActor) => {
+ const appConnection = await getAppConnection(AppConnection.ADCS, connectionId, actor);
+ const result = await executeAdcsGatewayOperation<AdcsTemplatesResult>(
+ {
+ ...targetFor(appConnection),
+ endpoint: "/v1/templates",
+ caName: await resolveAdcsCaName(caName, async () => targetFor(appConnection), {
+ gatewayV2Service,
+ gatewayPoolService
+ })
+ },
+ { gatewayV2Service, gatewayPoolService }
+ );
+ return result.templates;
+ };
+
+ return {
+ listCertificateTemplates
+ };
+};
diff --git a/backend/src/services/app-connection/adcs/adcs-connection-types.ts b/backend/src/services/app-connection/adcs/adcs-connection-types.ts
new file mode 100644
index 0000000000..60e72768c4
--- /dev/null
+++ b/backend/src/services/app-connection/adcs/adcs-connection-types.ts
@@ -0,0 +1,23 @@
+import { z } from "zod";
+
+import { DiscriminativePick } from "@app/lib/types";
+
+import { AppConnection } from "../app-connection-enums";
+import {
+ ADCSConnectionSchema,
+ CreateADCSConnectionSchema,
+ ValidateADCSConnectionCredentialsSchema
+} from "./adcs-connection-schemas";
+
+export type TADCSConnection = z.infer<typeof ADCSConnectionSchema>;
+
+export type TADCSConnectionInput = z.infer<typeof CreateADCSConnectionSchema> & {
+ app: AppConnection.ADCS;
+};
+
+export type TValidateADCSConnectionCredentialsSchema = typeof ValidateADCSConnectionCredentialsSchema;
+
+export type TADCSConnectionConfig = DiscriminativePick<
+ TADCSConnectionInput,
+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId"
+>;
diff --git a/backend/src/services/app-connection/adcs/index.ts b/backend/src/services/app-connection/adcs/index.ts
new file mode 100644
index 0000000000..7b24c4d54d
--- /dev/null
+++ b/backend/src/services/app-connection/adcs/index.ts
@@ -0,0 +1,5 @@
+export * from "./adcs-connection-enums";
+export * from "./adcs-connection-fns";
+export * from "./adcs-connection-schemas";
+export * from "./adcs-connection-service";
+export * from "./adcs-connection-types";
diff --git a/backend/src/services/app-connection/app-connection-enums.ts b/backend/src/services/app-connection/app-connection-enums.ts
index 8103a45f21..6af243e63e 100644
--- a/backend/src/services/app-connection/app-connection-enums.ts
+++ b/backend/src/services/app-connection/app-connection-enums.ts
@@ -9,6 +9,7 @@ export enum AppConnection {
AzureClientSecrets = "azure-client-secrets",
AzureDevOps = "azure-devops",
AzureADCS = "azure-adcs",
+ ADCS = "adcs",
AzureDNS = "azure-dns",
Humanitec = "humanitec",
TerraformCloud = "terraform-cloud",
diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.ts
index 167866aa49..ea4cc91ba7 100644
--- a/backend/src/services/app-connection/app-connection-fns.ts
+++ b/backend/src/services/app-connection/app-connection-fns.ts
@@ -35,6 +35,7 @@ import {
OnePassConnectionMethod,
validateOnePassConnectionCredentials
} from "./1password";
+import { ADCSConnectionMethod, getADCSConnectionListItem, validateADCSConnectionCredentials } from "./adcs";
import {
AnthropicConnectionMethod,
getAnthropicConnectionListItem,
@@ -291,6 +292,7 @@ const PKI_APP_CONNECTIONS = [
AppConnection.AWS,
AppConnection.Cloudflare,
AppConnection.AzureADCS,
+ AppConnection.ADCS,
AppConnection.AzureKeyVault,
AppConnection.Chef,
AppConnection.DNSMadeEasy,
@@ -313,6 +315,7 @@ export const listAppConnectionOptions = (projectType?: ProjectType) => {
getAzureAppConfigurationConnectionListItem(),
getAzureDevopsConnectionListItem(),
getAzureADCSConnectionListItem(),
+ getADCSConnectionListItem(),
getDatabricksConnectionListItem(),
getHumanitecConnectionListItem(),
getTerraformCloudConnectionListItem(),
@@ -551,6 +554,7 @@ export const validateAppConnectionCredentials = async (
validateAzureClientSecretsConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.AzureDevOps]: validateAzureDevOpsConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.AzureADCS]: validateAzureADCSConnectionCredentials as TAppConnectionCredentialsValidator,
+ [AppConnection.ADCS]: validateADCSConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.Humanitec]: validateHumanitecConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.Postgres]: validateSqlConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.MsSql]: validateSqlConnectionCredentials as TAppConnectionCredentialsValidator,
@@ -684,6 +688,7 @@ export const getAppConnectionMethodName = (method: TAppConnection["method"]) =>
case MySqlConnectionMethod.UsernameAndPassword:
case OracleDBConnectionMethod.UsernameAndPassword:
case AzureADCSConnectionMethod.UsernamePassword:
+ case ADCSConnectionMethod.UsernamePassword:
case RedisConnectionMethod.UsernameAndPassword:
case MongoDBConnectionMethod.UsernameAndPassword:
return "Username & Password";
@@ -807,6 +812,7 @@ export const TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM: Record<
[AppConnection.AzureAppConfiguration]: platformManagedCredentialsNotSupported,
[AppConnection.AzureDevOps]: platformManagedCredentialsNotSupported,
[AppConnection.AzureADCS]: platformManagedCredentialsNotSupported,
+ [AppConnection.ADCS]: platformManagedCredentialsNotSupported,
[AppConnection.Humanitec]: platformManagedCredentialsNotSupported,
[AppConnection.Postgres]: transferSqlConnectionCredentialsToPlatform as TAppConnectionTransitionCredentialsToPlatform,
[AppConnection.MsSql]: transferSqlConnectionCredentialsToPlatform as TAppConnectionTransitionCredentialsToPlatform,
diff --git a/backend/src/services/app-connection/app-connection-maps.ts b/backend/src/services/app-connection/app-connection-maps.ts
index 21e4a9a999..1467a8c61c 100644
--- a/backend/src/services/app-connection/app-connection-maps.ts
+++ b/backend/src/services/app-connection/app-connection-maps.ts
@@ -9,7 +9,8 @@ export const APP_CONNECTION_NAME_MAP: Record<AppConnection, string> = {
[AppConnection.AzureAppConfiguration]: "Azure App Configuration",
[AppConnection.AzureClientSecrets]: "Azure Client Secrets",
[AppConnection.AzureDevOps]: "Azure DevOps",
- [AppConnection.AzureADCS]: "Azure ADCS",
+ [AppConnection.AzureADCS]: "Azure ADCS (Web Enrollment)",
+ [AppConnection.ADCS]: "ADCS",
[AppConnection.AzureDNS]: "Azure DNS",
[AppConnection.Databricks]: "Databricks",
[AppConnection.Humanitec]: "Humanitec",
@@ -86,6 +87,7 @@ export const APP_CONNECTION_PLAN_MAP: Record<AppConnection, AppConnectionPlanTyp
[AppConnection.AzureClientSecrets]: AppConnectionPlanType.Regular,
[AppConnection.AzureDevOps]: AppConnectionPlanType.Regular,
[AppConnection.AzureADCS]: AppConnectionPlanType.Regular,
+ [AppConnection.ADCS]: AppConnectionPlanType.Regular,
[AppConnection.AzureDNS]: AppConnectionPlanType.Regular,
[AppConnection.Databricks]: AppConnectionPlanType.Regular,
[AppConnection.Humanitec]: 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 780eafcd80..1cb97afa27 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -46,6 +46,8 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";
import { ValidateOnePassConnectionCredentialsSchema } from "./1password";
import { onePassConnectionService } from "./1password/1password-connection-service";
+import { ValidateADCSConnectionCredentialsSchema } from "./adcs/adcs-connection-schemas";
+import { adcsConnectionService } from "./adcs/adcs-connection-service";
import { ValidateAnthropicConnectionCredentialsSchema } from "./anthropic";
import { TAppConnectionDALFactory } from "./app-connection-dal";
import { AppConnection } from "./app-connection-enums";
@@ -211,6 +213,7 @@ const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TValidateAp
[AppConnection.AzureAppConfiguration]: ValidateAzureAppConfigurationConnectionCredentialsSchema,
[AppConnection.AzureDevOps]: ValidateAzureDevOpsConnectionCredentialsSchema,
[AppConnection.AzureADCS]: ValidateAzureADCSConnectionCredentialsSchema,
+ [AppConnection.ADCS]: ValidateADCSConnectionCredentialsSchema,
[AppConnection.Databricks]: ValidateDatabricksConnectionCredentialsSchema,
[AppConnection.Humanitec]: ValidateHumanitecConnectionCredentialsSchema,
[AppConnection.TerraformCloud]: ValidateTerraformCloudConnectionCredentialsSchema,
@@ -1349,6 +1352,7 @@ export const appConnectionServiceFactory = ({
cloudflare: cloudflareConnectionService(connectAppConnectionById),
venafi: venafiConnectionService(connectAppConnectionById),
azureAdcs: azureAdcsConnectionService(connectAppConnectionById),
+ adcs: adcsConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),
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 4cf6b7375b..ab206b0a25 100644
--- a/backend/src/services/app-connection/app-connection-types.ts
+++ b/backend/src/services/app-connection/app-connection-types.ts
@@ -27,6 +27,12 @@ import {
TOnePassConnectionInput,
TValidateOnePassConnectionCredentialsSchema
} from "./1password";
+import {
+ TADCSConnection,
+ TADCSConnectionConfig,
+ TADCSConnectionInput,
+ TValidateADCSConnectionCredentialsSchema
+} from "./adcs/adcs-connection-types";
import {
TAnthropicConnection,
TAnthropicConnectionConfig,
@@ -443,6 +449,7 @@ export type TAppConnection = { id: string; configuration?: TAppConnectionConfigu
| TAzureAppConfigurationConnection
| TAzureDevOpsConnection
| TAzureADCSConnection
+ | TADCSConnection
| TDatabricksConnection
| THumanitecConnection
| TTerraformCloudConnection
@@ -527,6 +534,7 @@ export type TAppConnectionInput = { id: string } & (
| TAzureAppConfigurationConnectionInput
| TAzureDevOpsConnectionInput
| TAzureADCSConnectionInput
+ | TADCSConnectionInput
| TDatabricksConnectionInput
| THumanitecConnectionInput
| TTerraformCloudConnectionInput
@@ -646,6 +654,7 @@ export type TAppConnectionConfig =
| TAzureAppConfigurationConnectionConfig
| TAzureDevOpsConnectionConfig
| TAzureADCSConnectionConfig
+ | TADCSConnectionConfig
| TAzureClientSecretsConnectionConfig
| TDatabricksConnectionConfig
| THumanitecConnectionConfig
@@ -719,6 +728,7 @@ export type TValidateAppConnectionCredentialsSchema =
| TValidateAzureClientSecretsConnectionCredentialsSchema
| TValidateAzureDevOpsConnectionCredentialsSchema
| TValidateAzureADCSConnectionCredentialsSchema
+ | TValidateADCSConnectionCredentialsSchema
| TValidateDatabricksConnectionCredentialsSchema
| TValidateHumanitecConnectionCredentialsSchema
| TValidatePostgresConnectionCredentialsSchema
diff --git a/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts
new file mode 100644
index 0000000000..995722a85e
--- /dev/null
+++ b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts
@@ -0,0 +1,653 @@
+import * as x509 from "@peculiar/x509";
+import RE2 from "re2";
+
+import { TableName } from "@app/db/schemas";
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { crypto } from "@app/lib/crypto/cryptography";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import {
+ ADCS_DISPOSITION_ISSUED,
+ AdcsEnrollResult,
+ AdcsTemplatesResult,
+ describeAdcsDisposition
+} from "@app/lib/gateway-v2/adcs-rpc";
+import { ProcessedPermissionRules } from "@app/lib/knex/permission-filter-utils";
+import { OrgServiceActor } from "@app/lib/types";
+import { executeAdcsGatewayOperation, resolveAdcsCaName } from "@app/services/app-connection/adcs";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
+import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
+import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
+import {
+ CertExtendedKeyUsage,
+ CertKeyAlgorithm,
+ CertKeyUsage,
+ CertSignatureAlgorithm,
+ CertStatus,
+ TAltNameType
+} from "@app/services/certificate/certificate-types";
+import { calculateFinalRenewBeforeDays } from "@app/services/certificate-common/certificate-issuance-utils";
+import { CertificateRequestCancelledError } from "@app/services/certificate-common/certificate-request-errors";
+import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+
+import { TCertificateAuthorityDALFactory } from "../certificate-authority-dal";
+import { CaStatus, CaType } from "../certificate-authority-enums";
+import { keyAlgorithmToAlgCfg } from "../certificate-authority-fns";
+import { TExternalCertificateAuthorityDALFactory } from "../external-certificate-authority-dal";
+import {
+ TADCSCertificateAuthority,
+ TCreateADCSCertificateAuthorityDTO,
+ TUpdateADCSCertificateAuthorityDTO
+} from "./adcs-certificate-authority-types";
+import { getAdcsConnectionCredentials } from "./adcs-connection-credentials";
+
+// @peculiar/x509 reports the signature algorithm as { name, hash }; map it to the stored enum.
+const SIG_ALG_MAP: Record<string, Record<string, CertSignatureAlgorithm>> = {
+ "RSASSA-PKCS1-v1_5": {
+ "SHA-256": CertSignatureAlgorithm.RSA_SHA256,
+ "SHA-384": CertSignatureAlgorithm.RSA_SHA384,
+ "SHA-512": CertSignatureAlgorithm.RSA_SHA512
+ },
+ ECDSA: {
+ "SHA-256": CertSignatureAlgorithm.ECDSA_SHA256,
+ "SHA-384": CertSignatureAlgorithm.ECDSA_SHA384,
+ "SHA-512": CertSignatureAlgorithm.ECDSA_SHA512
+ }
+};
+
+// The CA (not the request) decides how it signs, so read the algorithm off the issued certificate.
+const extractIssuedSignatureAlgorithm = (certObj: x509.X509Certificate): CertSignatureAlgorithm | undefined => {
+ try {
+ const { name } = certObj.signatureAlgorithm;
+ const hashName = (certObj.signatureAlgorithm as { hash?: { name?: string } }).hash?.name;
+ if (!hashName) return undefined;
+ return SIG_ALG_MAP[name]?.[hashName];
+ } catch {
+ return undefined;
+ }
+};
+
+const buildSubjectDN = (commonName: string): string => {
+ if (!commonName || !commonName.trim()) {
+ throw new BadRequestError({ message: "Common Name is required and cannot be empty" });
+ }
+
+ const trimmedCN = commonName.trim();
+
+ const invalidCharsRegex = new RE2("[,=+<>#;\\\\\\]]");
+ if (invalidCharsRegex.test(trimmedCN)) {
+ throw new BadRequestError({
+ message: "Common Name contains invalid characters: , = + < > # ; \\ ]"
+ });
+ }
+
+ return `CN=${trimmedCN}`;
+};
+
+export const castDbEntryToADCSCertificateAuthority = (
+ ca: Awaited<ReturnType<TCertificateAuthorityDALFactory["findByIdWithAssociatedCa"]>>
+): TADCSCertificateAuthority & { credentials: Buffer | null | undefined } => {
+ if (!ca.externalCa?.id) {
+ throw new BadRequestError({ message: "Malformed Active Directory Certificate Service certificate authority" });
+ }
+
+ if (!ca.externalCa.appConnectionId) {
+ throw new BadRequestError({
+ message: "ADCS app connection ID is missing from certificate authority configuration"
+ });
+ }
+
+ const configuration = ca.externalCa.configuration as { caName?: string } | null;
+
+ if (!configuration?.caName) {
+ throw new BadRequestError({
+ message: "ADCS CA name is missing from certificate authority configuration"
+ });
+ }
+
+ return {
+ id: ca.id,
+ type: CaType.ADCS,
+ enableDirectIssuance: ca.enableDirectIssuance,
+ name: ca.name,
+ projectId: ca.projectId,
+ credentials: ca.externalCa.credentials,
+ configuration: {
+ appConnectionId: ca.externalCa.appConnectionId,
+ caName: configuration.caName
+ },
+ status: ca.status as CaStatus
+ };
+};
+
+type TADCSCertificateAuthorityFnsDeps = {
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
+ certificateAuthorityDAL: Pick<
+ TCertificateAuthorityDALFactory,
+ "create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
+ >;
+ externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
+ certificateDAL: Pick<TCertificateDALFactory, "create" | "transaction" | "updateById">;
+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
+ kmsService: Pick<
+ TKmsServiceFactory,
+ "encryptWithKmsKey" | "generateKmsKey" | "createCipherPairWithDataKey" | "decryptWithKmsKey"
+ >;
+ projectDAL: Pick<TProjectDALFactory, "findById" | "findOne" | "updateById" | "transaction">;
+ certificateProfileDAL?: Pick<TCertificateProfileDALFactory, "findById">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+};
+
+export const ADCSCertificateAuthorityFns = ({
+ appConnectionDAL,
+ appConnectionService,
+ certificateAuthorityDAL,
+ externalCertificateAuthorityDAL,
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ kmsService,
+ projectDAL,
+ certificateProfileDAL,
+ gatewayV2Service,
+ gatewayPoolService
+}: TADCSCertificateAuthorityFnsDeps) => {
+ const createCertificateAuthority = async ({
+ name,
+ projectId,
+ configuration,
+ actor,
+ status
+ }: {
+ status: CaStatus;
+ name: string;
+ projectId: string;
+ configuration: TCreateADCSCertificateAuthorityDTO["configuration"];
+ actor: OrgServiceActor;
+ }) => {
+ const { appConnectionId, caName } = configuration;
+ const appConnection = await appConnectionDAL.findById(appConnectionId);
+
+ if (!appConnection) {
+ throw new NotFoundError({ message: `App connection with ID '${appConnectionId}' not found` });
+ }
+
+ if (appConnection.app !== AppConnection.ADCS) {
+ throw new BadRequestError({
+ message: `App connection with ID '${appConnectionId}' is not an ADCS connection`
+ });
+ }
+
+ await appConnectionService.validateAppConnectionUsageById(
+ appConnection.app as AppConnection,
+ { connectionId: appConnectionId, projectId },
+ actor
+ );
+
+ // The CA name is optional on input: when omitted, it is discovered from the CA host over the
+ // gateway (before the transaction, since discovery is a network call).
+ const resolvedCaName = await resolveAdcsCaName(
+ caName,
+ () => getAdcsConnectionCredentials(appConnectionId, appConnectionDAL, kmsService),
+ { gatewayV2Service, gatewayPoolService }
+ );
+
+ const caEntity = await certificateAuthorityDAL.transaction(async (tx) => {
+ try {
+ const ca = await certificateAuthorityDAL.create(
+ {
+ projectId,
+ enableDirectIssuance: false,
+ name,
+ status
+ },
+ tx
+ );
+
+ await externalCertificateAuthorityDAL.create(
+ {
+ caId: ca.id,
+ appConnectionId,
+ type: CaType.ADCS,
+ configuration: { caName: resolvedCaName }
+ },
+ tx
+ );
+
+ return await certificateAuthorityDAL.findByIdWithAssociatedCa(ca.id, tx);
+ } catch (error) {
+ // 23505 = unique constraint violation
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
+ if ((error as any)?.error?.code === "23505") {
+ throw new BadRequestError({
+ message: "Certificate authority with the same name already exists in your project"
+ });
+ }
+ throw error;
+ }
+ });
+
+ if (!caEntity.externalCa?.id) {
+ throw new BadRequestError({ message: "Failed to create ADCS certificate authority" });
+ }
+
+ return castDbEntryToADCSCertificateAuthority(caEntity);
+ };
+
+ const updateCertificateAuthority = async ({
+ id,
+ status,
+ configuration,
+ actor,
+ name
+ }: {
+ id: string;
+ status?: CaStatus;
+ configuration?: TUpdateADCSCertificateAuthorityDTO["configuration"];
+ actor: OrgServiceActor;
+ name?: string;
+ }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(id);
+ if (!ca || !ca.externalCa) {
+ throw new NotFoundError({ message: `Certificate authority with ID '${id}' not found` });
+ }
+
+ // Resolve the CA name outside the transaction (discovery is a gateway call).
+ const resolvedUpdateCaName = configuration
+ ? await resolveAdcsCaName(
+ configuration.caName,
+ () => getAdcsConnectionCredentials(configuration.appConnectionId, appConnectionDAL, kmsService),
+ { gatewayV2Service, gatewayPoolService }
+ )
+ : undefined;
+
+ const updatedCa = await certificateAuthorityDAL.transaction(async (tx) => {
+ if (configuration) {
+ const { appConnectionId } = configuration;
+ const appConnection = await appConnectionDAL.findById(appConnectionId);
+
+ if (!appConnection) {
+ throw new NotFoundError({ message: `App connection with ID '${appConnectionId}' not found` });
+ }
+
+ if (appConnection.app !== AppConnection.ADCS) {
+ throw new BadRequestError({
+ message: `App connection with ID '${appConnectionId}' is not an ADCS connection`
+ });
+ }
+
+ await appConnectionService.validateAppConnectionUsageById(
+ appConnection.app as AppConnection,
+ { connectionId: appConnectionId, projectId: ca.projectId },
+ actor
+ );
+
+ await externalCertificateAuthorityDAL.update(
+ { caId: id, type: CaType.ADCS },
+ {
+ appConnectionId,
+ configuration: { caName: resolvedUpdateCaName }
+ },
+ tx
+ );
+ }
+
+ if (name || status) {
+ await certificateAuthorityDAL.updateById(
+ id,
+ {
+ name,
+ status
+ },
+ tx
+ );
+ }
+
+ return certificateAuthorityDAL.findByIdWithAssociatedCa(id, tx);
+ });
+
+ if (!updatedCa.externalCa?.id) {
+ throw new BadRequestError({ message: "Failed to update ADCS certificate authority" });
+ }
+
+ return castDbEntryToADCSCertificateAuthority(updatedCa);
+ };
+
+ const getCertificateAuthority = async ({ caId, projectId }: { caId: string; projectId: string }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca || ca.projectId !== projectId) {
+ throw new NotFoundError({ message: "Certificate Authority not found" });
+ }
+
+ return castDbEntryToADCSCertificateAuthority(ca);
+ };
+
+ const deleteCertificateAuthority = async ({ caId, projectId }: { caId: string; projectId: string }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca || ca.projectId !== projectId) {
+ throw new NotFoundError({ message: "Certificate Authority not found" });
+ }
+
+ const adcsCa = castDbEntryToADCSCertificateAuthority(ca);
+ await certificateAuthorityDAL.updateById(caId, { status: CaStatus.DISABLED });
+
+ return adcsCa;
+ };
+
+ const listCertificateAuthorities = async ({
+ projectId,
+ permissionFilters
+ }: {
+ projectId: string;
+ permissionFilters?: ProcessedPermissionRules;
+ }) => {
+ const cas = await certificateAuthorityDAL.findWithAssociatedCa(
+ {
+ [`${TableName.CertificateAuthority}.projectId` as "projectId"]: projectId,
+ [`${TableName.ExternalCertificateAuthority}.type` as "type"]: CaType.ADCS
+ },
+ {},
+ permissionFilters
+ );
+
+ return cas.map(castDbEntryToADCSCertificateAuthority);
+ };
+
+ const orderCertificate = async ({
+ caId,
+ profileId,
+ commonName,
+ altNames = [],
+ keyUsages = [],
+ extendedKeyUsages = [],
+ template,
+ validity,
+ signatureAlgorithm,
+ keyAlgorithm = CertKeyAlgorithm.RSA_2048,
+ isRenewal,
+ originalCertificateId,
+ isCancelled
+ }: {
+ caId: string;
+ profileId?: string;
+ commonName: string;
+ altNames?: string[];
+ keyUsages?: CertKeyUsage[];
+ extendedKeyUsages?: CertExtendedKeyUsage[];
+ template?: string;
+ validity: { ttl: string };
+ signatureAlgorithm?: string;
+ keyAlgorithm?: CertKeyAlgorithm;
+ isRenewal?: boolean;
+ originalCertificateId?: string;
+ isCancelled?: () => Promise<boolean>;
+ }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca.externalCa || ca.externalCa.type !== CaType.ADCS) {
+ throw new BadRequestError({ message: "CA is not an Active Directory Certificate Service CA" });
+ }
+
+ const adcsCa = castDbEntryToADCSCertificateAuthority(ca);
+ if (adcsCa.status !== CaStatus.ACTIVE) {
+ throw new BadRequestError({ message: "CA is disabled" });
+ }
+
+ const templateInput = template?.trim();
+ if (!templateInput) {
+ throw new BadRequestError({
+ message: "A certificate template is required to issue through Active Directory Certificate Service."
+ });
+ }
+
+ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
+ projectId: ca.projectId,
+ projectDAL,
+ kmsService
+ });
+
+ const kmsEncryptor = await kmsService.encryptWithKmsKey({
+ kmsId: certificateManagerKmsId
+ });
+
+ const { credentials, gatewayId, gatewayPoolId } = await getAdcsConnectionCredentials(
+ adcsCa.configuration.appConnectionId,
+ appConnectionDAL,
+ kmsService
+ );
+
+ let alg;
+ if (signatureAlgorithm) {
+ switch (signatureAlgorithm.toUpperCase()) {
+ case "RSA-SHA256":
+ case "SHA256WITHRSA":
+ alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);
+ break;
+ case "RSA-SHA384":
+ case "SHA384WITHRSA":
+ alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_3072);
+ break;
+ case "RSA-SHA512":
+ case "SHA512WITHRSA":
+ alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_4096);
+ break;
+ case "ECDSA-SHA256":
+ case "SHA256WITHECDSA":
+ alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.ECDSA_P256);
+ break;
+ case "ECDSA-SHA384":
+ case "SHA384WITHECDSA":
+ alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.ECDSA_P384);
+ break;
+ case "ECDSA-SHA512":
+ case "SHA512WITHECDSA":
+ alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.ECDSA_P521);
+ break;
+ default:
+ alg = keyAlgorithmToAlgCfg(keyAlgorithm);
+ break;
+ }
+ } else {
+ alg = keyAlgorithmToAlgCfg(keyAlgorithm);
+ }
+
+ const leafKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
+ const skLeafObj = crypto.nativeCrypto.KeyObject.from(leafKeys.privateKey);
+ const skLeaf = skLeafObj.export({ format: "pem", type: "pkcs8" }) as string;
+
+ const subjectDN = buildSubjectDN(commonName);
+
+ const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
+ name: subjectDN,
+ keys: leafKeys,
+ signingAlgorithm: alg,
+ ...(altNames.length > 0 && {
+ extensions: [
+ new x509.SubjectAlternativeNameExtension(
+ altNames.map((sanValue) => ({ type: "dns" as TAltNameType, value: sanValue })),
+ false
+ )
+ ]
+ })
+ });
+
+ // MS-WCCE expects the CSR as base64-encoded DER PKCS#10.
+ const csrDerBase64 = Buffer.from(new Uint8Array(csrObj.rawData)).toString("base64");
+
+ const enrollResult = await executeAdcsGatewayOperation<AdcsEnrollResult>(
+ {
+ gatewayId,
+ gatewayPoolId,
+ credentials,
+ endpoint: "/v1/enroll",
+ caName: adcsCa.configuration.caName,
+ params: { template: templateInput, csr: csrDerBase64 }
+ },
+ { gatewayV2Service, gatewayPoolService }
+ );
+
+ if (enrollResult.disposition !== ADCS_DISPOSITION_ISSUED || !enrollResult.certificatePem) {
+ throw new BadRequestError({
+ message: describeAdcsDisposition(enrollResult.disposition, {
+ requestId: enrollResult.requestId,
+ dispositionMessage: enrollResult.dispositionMessage,
+ hresult: enrollResult.hresult
+ })
+ });
+ }
+
+ let cleanedCertificatePem = enrollResult.certificatePem.trim();
+ cleanedCertificatePem = cleanedCertificatePem
+ .replace(new RE2("\\r\\n", "g"), "\n")
+ .replace(new RE2("\\r", "g"), "\n")
+ .trim();
+
+ let certObj: x509.X509Certificate;
+ try {
+ certObj = new x509.X509Certificate(cleanedCertificatePem);
+ } catch (error) {
+ throw new BadRequestError({
+ message: `Failed to parse certificate from Active Directory Certificate Service: ${error instanceof Error ? error.message : "Unknown error"}`
+ });
+ }
+
+ const { cipherTextBlob: encryptedCertificate } = await kmsEncryptor({
+ plainText: Buffer.from(new Uint8Array(certObj.rawData))
+ });
+
+ const certificateChainPem = enrollResult.chainPem || "";
+
+ const { cipherTextBlob: encryptedCertificateChain } = await kmsEncryptor({
+ plainText: Buffer.from(certificateChainPem)
+ });
+
+ const { cipherTextBlob: encryptedPrivateKey } = await kmsEncryptor({
+ plainText: Buffer.from(skLeaf)
+ });
+
+ if (isCancelled && (await isCancelled())) {
+ throw new CertificateRequestCancelledError();
+ }
+
+ let certificateId: string;
+
+ await certificateDAL.transaction(async (tx) => {
+ const cert = await certificateDAL.create(
+ {
+ caId: ca.id,
+ profileId,
+ status: CertStatus.ACTIVE,
+ friendlyName: commonName,
+ commonName,
+ altNames: altNames.join(","),
+ serialNumber: certObj.serialNumber,
+ notBefore: certObj.notBefore,
+ notAfter: certObj.notAfter,
+ keyUsages,
+ extendedKeyUsages,
+ keyAlgorithm,
+ signatureAlgorithm: extractIssuedSignatureAlgorithm(certObj) ?? signatureAlgorithm,
+ projectId: ca.projectId,
+ renewedFromCertificateId: isRenewal && originalCertificateId ? originalCertificateId : null
+ },
+ tx
+ );
+
+ certificateId = cert.id;
+
+ if (isRenewal && originalCertificateId) {
+ await certificateDAL.updateById(originalCertificateId, { renewedByCertificateId: cert.id }, tx);
+ }
+
+ await certificateBodyDAL.create(
+ {
+ certId: cert.id,
+ encryptedCertificate,
+ encryptedCertificateChain
+ },
+ tx
+ );
+
+ await certificateSecretDAL.create(
+ {
+ certId: cert.id,
+ encryptedPrivateKey
+ },
+ tx
+ );
+
+ if (profileId && validity?.ttl && certificateProfileDAL) {
+ const profile = await certificateProfileDAL.findById(profileId, tx);
+ if (profile) {
+ const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
+ profile as { apiConfig?: { autoRenew?: boolean; renewBeforeDays?: number } },
+ validity.ttl,
+ certObj.notAfter
+ );
+ if (finalRenewBeforeDays !== undefined) {
+ await certificateDAL.updateById(cert.id, { renewBeforeDays: finalRenewBeforeDays }, tx);
+ }
+ }
+ }
+ });
+
+ return {
+ certificate: cleanedCertificatePem,
+ certificateChain: certificateChainPem,
+ privateKey: skLeaf,
+ serialNumber: certObj.serialNumber,
+ certificateId: certificateId!,
+ ca: adcsCa
+ };
+ };
+
+ const getCertificateTemplates = async ({ caId, projectId }: { caId: string; projectId: string }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca || ca.projectId !== projectId) {
+ throw new NotFoundError({ message: "Certificate Authority not found" });
+ }
+
+ const adcsCa = castDbEntryToADCSCertificateAuthority(ca);
+
+ const { credentials, gatewayId, gatewayPoolId } = await getAdcsConnectionCredentials(
+ adcsCa.configuration.appConnectionId,
+ appConnectionDAL,
+ kmsService
+ );
+
+ const { templates } = await executeAdcsGatewayOperation<AdcsTemplatesResult>(
+ {
+ gatewayId,
+ gatewayPoolId,
+ credentials,
+ endpoint: "/v1/templates",
+ caName: adcsCa.configuration.caName
+ },
+ { gatewayV2Service, gatewayPoolService }
+ );
+
+ // The enrollment path sends `CertificateTemplate:<name>`, so the stored value must be the template name.
+ return templates.map((template) => ({
+ id: template.name,
+ name: template.name
+ }));
+ };
+
+ return {
+ createCertificateAuthority,
+ getCertificateAuthority,
+ updateCertificateAuthority,
+ deleteCertificateAuthority,
+ listCertificateAuthorities,
+ orderCertificate,
+ getCertificateTemplates
+ };
+};
diff --git a/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-schemas.ts b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-schemas.ts
new file mode 100644
index 0000000000..18032e2efc
--- /dev/null
+++ b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-schemas.ts
@@ -0,0 +1,33 @@
+import { z } from "zod";
+
+import { CaType } from "../certificate-authority-enums";
+import {
+ BaseCertificateAuthoritySchema,
+ GenericCreateCertificateAuthorityFieldsSchema,
+ GenericUpdateCertificateAuthorityFieldsSchema
+} from "../certificate-authority-schemas";
+
+export const ADCSCertificateAuthorityConfigurationSchema = z.object({
+ appConnectionId: z.string().uuid().trim().describe("The ADCS App Connection ID."),
+ caName: z
+ .string()
+ .trim()
+ .min(1)
+ .optional()
+ .describe(
+ "The AD CS certification authority name. Optional: discovered automatically from the CA host when omitted."
+ )
+});
+
+export const ADCSCertificateAuthoritySchema = BaseCertificateAuthoritySchema.extend({
+ type: z.literal(CaType.ADCS),
+ configuration: ADCSCertificateAuthorityConfigurationSchema
+});
+
+export const CreateADCSCertificateAuthoritySchema = GenericCreateCertificateAuthorityFieldsSchema(CaType.ADCS).extend({
+ configuration: ADCSCertificateAuthorityConfigurationSchema
+});
+
+export const UpdateADCSCertificateAuthoritySchema = GenericUpdateCertificateAuthorityFieldsSchema(CaType.ADCS).extend({
+ configuration: ADCSCertificateAuthorityConfigurationSchema.optional()
+});
diff --git a/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-types.ts b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-types.ts
new file mode 100644
index 0000000000..e6a3478048
--- /dev/null
+++ b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-types.ts
@@ -0,0 +1,13 @@
+import { z } from "zod";
+
+import {
+ ADCSCertificateAuthoritySchema,
+ CreateADCSCertificateAuthoritySchema,
+ UpdateADCSCertificateAuthoritySchema
+} from "./adcs-certificate-authority-schemas";
+
+export type TADCSCertificateAuthority = z.infer<typeof ADCSCertificateAuthoritySchema>;
+
+export type TCreateADCSCertificateAuthorityDTO = z.infer<typeof CreateADCSCertificateAuthoritySchema>;
+
+export type TUpdateADCSCertificateAuthorityDTO = z.infer<typeof UpdateADCSCertificateAuthoritySchema>;
diff --git a/backend/src/services/certificate-authority/adcs/adcs-connection-credentials.ts b/backend/src/services/certificate-authority/adcs/adcs-connection-credentials.ts
new file mode 100644
index 0000000000..df42ef043d
--- /dev/null
+++ b/backend/src/services/certificate-authority/adcs/adcs-connection-credentials.ts
@@ -0,0 +1,43 @@
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+export type TAdcsResolvedConnection = {
+ credentials: { host: string; username: string; password: string };
+ gatewayId: string | null;
+ gatewayPoolId: string | null;
+};
+
+export const getAdcsConnectionCredentials = async (
+ appConnectionId: string,
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">,
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
+): Promise<TAdcsResolvedConnection> => {
+ const appConnection = await appConnectionDAL.findById(appConnectionId);
+ if (!appConnection) {
+ throw new NotFoundError({ message: `App connection with ID '${appConnectionId}' not found` });
+ }
+
+ if (appConnection.app !== AppConnection.ADCS) {
+ throw new BadRequestError({ message: `Connection with ID '${appConnectionId}' is not an ADCS connection` });
+ }
+
+ if (!appConnection.encryptedCredentials) {
+ throw new BadRequestError({ message: "App connection has no stored credentials" });
+ }
+
+ const credentials = (await decryptAppConnectionCredentials({
+ orgId: appConnection.orgId,
+ kmsService,
+ encryptedCredentials: appConnection.encryptedCredentials,
+ projectId: appConnection.projectId
+ })) as { host: string; username: string; password: string };
+
+ return {
+ credentials,
+ gatewayId: appConnection.gatewayId ?? null,
+ gatewayPoolId: appConnection.gatewayPoolId ?? null
+ };
+};
diff --git a/backend/src/services/certificate-authority/adcs/index.ts b/backend/src/services/certificate-authority/adcs/index.ts
new file mode 100644
index 0000000000..acd1511c68
--- /dev/null
+++ b/backend/src/services/certificate-authority/adcs/index.ts
@@ -0,0 +1,3 @@
+export * from "./adcs-certificate-authority-fns";
+export * from "./adcs-certificate-authority-schemas";
+export * from "./adcs-certificate-authority-types";
diff --git a/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts b/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts
index 0e4cb97150..eded800c7d 100644
--- a/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts
+++ b/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts
@@ -1,6 +1,8 @@
/* eslint-disable no-continue, no-await-in-loop */
import RE2 from "re2";
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
@@ -11,10 +13,12 @@ import { decryptAppConnectionCredentials } from "../app-connection/app-connectio
import { getAzureADCSConnectionCredentials } from "../app-connection/azure-adcs/azure-adcs-connection-fns";
import { TVenafiConnection } from "../app-connection/venafi/venafi-connection-types";
import { TKmsServiceFactory } from "../kms/kms-service";
+import { submitCsrToNativeAdcs } from "./ca-signing-config/adcs-native-signing-fns";
import { submitCsrToAdcs } from "./ca-signing-config/adcs-signing-fns";
import { TCaSigningConfigDALFactory } from "./ca-signing-config/ca-signing-config-dal";
import { CaSigningConfigType } from "./ca-signing-config/ca-signing-config-enums";
import {
+ AdcsDestinationConfigSchema,
AzureAdCsDestinationConfigSchema,
VenafiDestinationConfigSchema
} from "./ca-signing-config/ca-signing-config-types";
@@ -39,6 +43,8 @@ type TCaAutoRenewalQueueFactoryDep = {
>;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
export type TCaAutoRenewalQueueFactory = ReturnType<typeof caAutoRenewalQueueFactory>;
@@ -54,7 +60,9 @@ export const caAutoRenewalQueueFactory = ({
caSigningConfigDAL,
internalCertificateAuthorityService,
appConnectionDAL,
- kmsService
+ kmsService,
+ gatewayV2Service,
+ gatewayPoolService
}: TCaAutoRenewalQueueFactoryDep) => {
/**
* Shared helper that handles the full Venafi certificate issuance flow:
@@ -262,6 +270,64 @@ export const caAutoRenewalQueueFactory = ({
});
};
+ const processNativeAdcsCertificateIssuance = 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.Adcs) {
+ throw new Error(`Signing config type '${signingConfig.type}' is not ADCS`);
+ }
+
+ if (!signingConfig.appConnectionId) {
+ throw new Error("ADCS signing config is missing app connection");
+ }
+
+ const parseResult = AdcsDestinationConfigSchema.safeParse(signingConfig.destinationConfig);
+ if (!parseResult.success) {
+ throw new Error("ADCS signing config has invalid or missing destination configuration");
+ }
+ const destinationConfig = parseResult.data;
+
+ const { csr } = await internalCertificateAuthorityService.getCaCsr({
+ isInternal: true,
+ caId,
+ ...(maxPathLength !== undefined && { maxPathLength })
+ });
+
+ const { certificate, certificateChain } = await submitCsrToNativeAdcs(
+ {
+ appConnectionId: signingConfig.appConnectionId,
+ csr,
+ template: destinationConfig.template,
+ caName: destinationConfig.caName
+ },
+ { appConnectionDAL, kmsService, gatewayV2Service, gatewayPoolService }
+ );
+
+ await internalCertificateAuthorityService.importCertToCa({
+ isInternal: true,
+ caId,
+ certificate,
+ certificateChain
+ });
+
+ 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 };
@@ -327,6 +393,38 @@ export const caAutoRenewalQueueFactory = ({
return;
}
+ if (job.name === QueueJobs.CaNativeAdcsInstall) {
+ const { caId, maxPathLength } = job.data as { caId: string; maxPathLength?: number };
+
+ logger.info({ caId }, `${QueueJobs.CaNativeAdcsInstall}: processing native ADCS install`);
+
+ const internalCa = await internalCertificateAuthorityDAL.findOne({ caId });
+ if (!internalCa) {
+ logger.error({ caId }, `${QueueJobs.CaNativeAdcsInstall}: internal CA not found`);
+ return;
+ }
+
+ try {
+ await processNativeAdcsCertificateIssuance({
+ caId,
+ internalCaId: internalCa.id,
+ maxPathLength
+ });
+
+ logger.info({ caId }, `${QueueJobs.CaNativeAdcsInstall}: successfully installed certificate via native ADCS`);
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
+ logger.error(error, `${QueueJobs.CaNativeAdcsInstall}: CA ${caId} native ADCS 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`);
@@ -409,6 +507,11 @@ export const caAutoRenewalQueueFactory = ({
caId: internalCa.caId,
internalCaId: internalCa.id
});
+ } else if (signingConfig.type === CaSigningConfigType.Adcs) {
+ await processNativeAdcsCertificateIssuance({
+ caId: internalCa.caId,
+ internalCaId: internalCa.id
+ });
}
}
@@ -502,9 +605,36 @@ export const caAutoRenewalQueueFactory = ({
);
};
+ const queueNativeAdcsInstall = 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.CaNativeAdcsInstall,
+ { caId, maxPathLength },
+ {
+ jobId: `native-adcs-install-${caId}-${Date.now()}`,
+ removeOnComplete: true,
+ removeOnFail: true
+ }
+ );
+ };
+
queueService.listen(QueueName.CaAutoRenewal, "failed", (_, err) => {
logger.error(err, `${QueueName.CaAutoRenewal}: job failed`);
});
- return { startDailyAutoRenewalJob, queueVenafiInstall, queueAdcsInstall };
+ return { startDailyAutoRenewalJob, queueVenafiInstall, queueAdcsInstall, queueNativeAdcsInstall };
};
diff --git a/backend/src/services/certificate-authority/ca-signing-config/adcs-native-signing-fns.ts b/backend/src/services/certificate-authority/ca-signing-config/adcs-native-signing-fns.ts
new file mode 100644
index 0000000000..28d74809a8
--- /dev/null
+++ b/backend/src/services/certificate-authority/ca-signing-config/adcs-native-signing-fns.ts
@@ -0,0 +1,87 @@
+import RE2 from "re2";
+
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { BadRequestError } from "@app/lib/errors";
+import { ADCS_DISPOSITION_ISSUED, AdcsEnrollResult, describeAdcsDisposition } from "@app/lib/gateway-v2/adcs-rpc";
+import { logger } from "@app/lib/logger";
+import { executeAdcsGatewayOperation, resolveAdcsCaName } from "@app/services/app-connection/adcs";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { getAdcsConnectionCredentials } from "../adcs/adcs-connection-credentials";
+
+const RE_CSR_BEGIN = new RE2("-----BEGIN CERTIFICATE REQUEST-----", "g");
+const RE_CSR_END = new RE2("-----END CERTIFICATE REQUEST-----", "g");
+const RE_CSR_NEWLINES = new RE2("\\s", "g");
+const RE_CRLF_NORMALIZE = new RE2("\\r\\n?", "g");
+
+type TAdcsNativeGatewayDeps = {
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+};
+
+/**
+ * Submits the intermediate CA's CSR to a native AD CS over the gateway (MS-WCCE)
+ * and returns the issued certificate plus its chain. The caName is discovered from
+ * the CA host when not supplied so the gateway call happens before any DB write.
+ */
+export const submitCsrToNativeAdcs = async (
+ params: {
+ appConnectionId: string;
+ csr: string;
+ template: string;
+ caName?: string;
+ },
+ deps: TAdcsNativeGatewayDeps & {
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ }
+): Promise<{ certificate: string; certificateChain: string }> => {
+ const { appConnectionId, csr, template } = params;
+ const { appConnectionDAL, kmsService, gatewayV2Service, gatewayPoolService } = deps;
+
+ const { credentials, gatewayId, gatewayPoolId } = await getAdcsConnectionCredentials(
+ appConnectionId,
+ appConnectionDAL,
+ kmsService
+ );
+
+ const resolvedCaName = await resolveAdcsCaName(
+ params.caName,
+ async () => ({ gatewayId, gatewayPoolId, credentials }),
+ { gatewayV2Service, gatewayPoolService }
+ );
+
+ // MS-WCCE expects the CSR as base64-encoded DER PKCS#10.
+ const csrDerBase64 = csr.replace(RE_CSR_BEGIN, "").replace(RE_CSR_END, "").replace(RE_CSR_NEWLINES, "");
+
+ const enrollResult = await executeAdcsGatewayOperation<AdcsEnrollResult>(
+ {
+ gatewayId,
+ gatewayPoolId,
+ credentials,
+ endpoint: "/v1/enroll",
+ caName: resolvedCaName,
+ params: { template: template.trim(), csr: csrDerBase64 }
+ },
+ { gatewayV2Service, gatewayPoolService }
+ );
+
+ if (enrollResult.disposition !== ADCS_DISPOSITION_ISSUED || !enrollResult.certificatePem) {
+ throw new BadRequestError({
+ message: describeAdcsDisposition(enrollResult.disposition, {
+ requestId: enrollResult.requestId,
+ dispositionMessage: enrollResult.dispositionMessage,
+ hresult: enrollResult.hresult
+ })
+ });
+ }
+
+ logger.info({ requestId: enrollResult.requestId }, "ADCS native signing: intermediate CA certificate issued");
+
+ const certificate = enrollResult.certificatePem.replace(RE_CRLF_NORMALIZE, "\n").trim();
+ const certificateChain = (enrollResult.chainPem || "").replace(RE_CRLF_NORMALIZE, "\n").trim();
+
+ return { certificate, certificateChain };
+};
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
index ecb7104876..f73eddb55b 100644
--- 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
@@ -2,5 +2,6 @@ export enum CaSigningConfigType {
Internal = "internal",
Manual = "manual",
Venafi = "venafi",
- AzureAdCs = "azure-ad-cs"
+ AzureAdCs = "azure-ad-cs",
+ Adcs = "adcs"
}
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
index 29e8d03771..aa7a4bf81c 100644
--- 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
@@ -17,7 +17,9 @@ import { TInternalCertificateAuthorityDALFactory } from "../internal/internal-ce
import { TCaSigningConfigDALFactory } from "./ca-signing-config-dal";
import { CaSigningConfigType } from "./ca-signing-config-enums";
import {
+ AdcsDestinationConfigSchema,
AzureAdCsDestinationConfigSchema,
+ TAdcsDestinationConfig,
TAzureAdCsDestinationConfig,
TCreateCaSigningConfigDTO,
TGetCaSigningConfigDTO,
@@ -35,7 +37,10 @@ type TCaSigningConfigServiceFactoryDep = {
internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "findOne" | "updateById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
- caAutoRenewalQueue: Pick<TCaAutoRenewalQueueFactory, "queueVenafiInstall" | "queueAdcsInstall">;
+ caAutoRenewalQueue: Pick<
+ TCaAutoRenewalQueueFactory,
+ "queueVenafiInstall" | "queueAdcsInstall" | "queueNativeAdcsInstall"
+ >;
};
export type TCaSigningConfigServiceFactory = ReturnType<typeof caSigningConfigServiceFactory>;
@@ -133,7 +138,21 @@ export const caSigningConfigServiceFactory = ({
await validateAppConnectionOrg(appConnectionId, actorOrgId);
}
- const isExternalCa = type === CaSigningConfigType.Venafi || type === CaSigningConfigType.AzureAdCs;
+ if (type === CaSigningConfigType.Adcs) {
+ if (!appConnectionId) {
+ throw new BadRequestError({ message: "App connection ID is required for ADCS signing" });
+ }
+ if (!destinationConfig) {
+ throw new BadRequestError({ message: "Destination config is required for ADCS signing" });
+ }
+ AdcsDestinationConfigSchema.parse(destinationConfig);
+ await validateAppConnectionOrg(appConnectionId, actorOrgId);
+ }
+
+ const isExternalCa =
+ type === CaSigningConfigType.Venafi ||
+ type === CaSigningConfigType.AzureAdCs ||
+ type === CaSigningConfigType.Adcs;
const config = await caSigningConfigDAL.transaction(async (tx) => {
if (existing) {
@@ -239,7 +258,7 @@ export const caSigningConfigServiceFactory = ({
const updateData: {
parentCaId?: string | null;
appConnectionId?: string;
- destinationConfig?: TVenafiDestinationConfig | TAzureAdCsDestinationConfig;
+ destinationConfig?: TVenafiDestinationConfig | TAzureAdCsDestinationConfig | TAdcsDestinationConfig;
lastExternalCertificateId?: string;
} = {};
@@ -270,6 +289,17 @@ export const caSigningConfigServiceFactory = ({
}
}
+ if (existing.type === CaSigningConfigType.Adcs) {
+ if (appConnectionId !== undefined) {
+ await validateAppConnectionOrg(appConnectionId, actorOrgId);
+ updateData.appConnectionId = appConnectionId;
+ }
+ if (destinationConfig !== undefined) {
+ AdcsDestinationConfigSchema.parse(destinationConfig);
+ updateData.destinationConfig = destinationConfig;
+ }
+ }
+
if (Object.keys(updateData).length === 0) {
return { config: existing, ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId } };
}
@@ -548,6 +578,63 @@ export const caSigningConfigServiceFactory = ({
return { ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId } };
};
+ const installCertificateAdcsNative = 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.IssueCACertificate,
+ 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 getSigningConfigByCaId(internalCa.id);
+
+ if (signingConfig.type !== CaSigningConfigType.Adcs) {
+ throw new BadRequestError({ message: "CA signing config is not configured for ADCS" });
+ }
+
+ if (!signingConfig.appConnectionId) {
+ throw new BadRequestError({ message: "ADCS signing config is missing app connection" });
+ }
+
+ const parseResult = AdcsDestinationConfigSchema.safeParse(signingConfig.destinationConfig);
+ if (!parseResult.success) {
+ throw new BadRequestError({
+ message: "ADCS signing config has invalid or missing destination configuration"
+ });
+ }
+
+ await caAutoRenewalQueue.queueNativeAdcsInstall(caId, maxPathLength);
+
+ return { ca: { id: ca.id, dn: ca.internalCa?.dn ?? "", projectId: ca.projectId } };
+ };
+
return {
createSigningConfig,
getSigningConfig,
@@ -555,6 +642,7 @@ export const caSigningConfigServiceFactory = ({
getAutoRenewalConfig,
updateAutoRenewalConfig,
installCertificateVenafi,
- installCertificateAzureAdCs
+ installCertificateAzureAdCs,
+ installCertificateAdcsNative
};
};
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
index 7e88514df6..56b46d314a 100644
--- 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
@@ -23,22 +23,38 @@ export const AzureAdCsDestinationConfigSchema = z.object({
export type TAzureAdCsDestinationConfig = z.infer<typeof AzureAdCsDestinationConfigSchema>;
+export const AdcsDestinationConfigSchema = z.object({
+ template: z
+ .string()
+ .min(1)
+ .refine((v) => RE_NO_NEWLINES.test(v), "Template name must not contain newline characters"),
+ caName: z
+ .string()
+ .min(1)
+ .refine((v) => RE_NO_NEWLINES.test(v), "CA name must not contain newline characters")
+ .optional()
+});
+
+export type TAdcsDestinationConfig = z.infer<typeof AdcsDestinationConfigSchema>;
+
// Union of all external CA destination config schemas — extend here when adding new providers
-export const DestinationConfigSchema = VenafiDestinationConfigSchema.or(AzureAdCsDestinationConfigSchema);
+export const DestinationConfigSchema = VenafiDestinationConfigSchema.or(AzureAdCsDestinationConfigSchema).or(
+ AdcsDestinationConfigSchema
+);
export type TCreateCaSigningConfigDTO = {
caId: string;
type: CaSigningConfigType;
parentCaId?: string;
appConnectionId?: string;
- destinationConfig?: TVenafiDestinationConfig | TAzureAdCsDestinationConfig;
+ destinationConfig?: TVenafiDestinationConfig | TAzureAdCsDestinationConfig | TAdcsDestinationConfig;
};
export type TUpdateCaSigningConfigDTO = {
caId: string;
parentCaId?: string;
appConnectionId?: string;
- destinationConfig?: TVenafiDestinationConfig | TAzureAdCsDestinationConfig;
+ destinationConfig?: TVenafiDestinationConfig | TAzureAdCsDestinationConfig | TAdcsDestinationConfig;
lastExternalCertificateId?: string;
};
diff --git a/backend/src/services/certificate-authority/certificate-authority-enums.ts b/backend/src/services/certificate-authority/certificate-authority-enums.ts
index 80bab6efc4..cd5a8f0e11 100644
--- a/backend/src/services/certificate-authority/certificate-authority-enums.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-enums.ts
@@ -2,6 +2,7 @@ export enum CaType {
INTERNAL = "internal",
ACME = "acme",
AZURE_AD_CS = "azure-ad-cs",
+ ADCS = "adcs",
AWS_PCA = "aws-pca",
DIGICERT = "digicert",
AWS_ACM_PUBLIC_CA = "aws-acm-public-ca",
diff --git a/backend/src/services/certificate-authority/certificate-authority-maps.ts b/backend/src/services/certificate-authority/certificate-authority-maps.ts
index 03c60970a9..3aaae9b5e7 100644
--- a/backend/src/services/certificate-authority/certificate-authority-maps.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-maps.ts
@@ -4,6 +4,7 @@ export const CERTIFICATE_AUTHORITIES_TYPE_MAP: Record<CaType, string> = {
[CaType.INTERNAL]: "Internal",
[CaType.ACME]: "ACME-compatible CA",
[CaType.AZURE_AD_CS]: "Active Directory Certificate Service",
+ [CaType.ADCS]: "Active Directory Certificate Service (Gateway)",
[CaType.AWS_PCA]: "AWS Private Certificate Authority",
[CaType.DIGICERT]: "DigiCert",
[CaType.AWS_ACM_PUBLIC_CA]: "AWS ACM Public CA",
@@ -23,6 +24,11 @@ export const CERTIFICATE_AUTHORITIES_CAPABILITIES_MAP: Record<CaType, CaCapabili
CaCapability.RENEW_CERTIFICATES
// Note: REVOKE_CERTIFICATES intentionally omitted - not supported by ADCS connector
],
+ [CaType.ADCS]: [
+ CaCapability.ISSUE_CERTIFICATES,
+ CaCapability.RENEW_CERTIFICATES
+ // Note: REVOKE_CERTIFICATES intentionally omitted - MS-WCCE enrollment does not support revocation
+ ],
[CaType.AWS_PCA]: [
CaCapability.ISSUE_CERTIFICATES,
CaCapability.REVOKE_CERTIFICATES,
diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.ts
index fb02898e32..19935a1296 100644
--- a/backend/src/services/certificate-authority/certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts
@@ -42,6 +42,14 @@ import {
TCreateAcmeCertificateAuthorityDTO,
TUpdateAcmeCertificateAuthorityDTO
} from "./acme/acme-certificate-authority-types";
+import {
+ ADCSCertificateAuthorityFns,
+ castDbEntryToADCSCertificateAuthority
+} from "./adcs/adcs-certificate-authority-fns";
+import {
+ TCreateADCSCertificateAuthorityDTO,
+ TUpdateADCSCertificateAuthorityDTO
+} from "./adcs/adcs-certificate-authority-types";
import {
AwsAcmPublicCaCertificateAuthorityFns,
castDbEntryToAwsAcmPublicCaCertificateAuthority
@@ -200,6 +208,21 @@ export const certificateAuthorityServiceFactory = ({
certificateProfileDAL
});
+ const adcsFns = ADCSCertificateAuthorityFns({
+ appConnectionDAL,
+ appConnectionService,
+ certificateAuthorityDAL,
+ externalCertificateAuthorityDAL,
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ kmsService,
+ projectDAL,
+ certificateProfileDAL,
+ gatewayV2Service,
+ gatewayPoolService
+ });
+
const venafiTppFns = VenafiTppCertificateAuthorityFns({
appConnectionDAL,
appConnectionService,
@@ -328,6 +351,16 @@ export const certificateAuthorityServiceFactory = ({
});
}
+ if (type === CaType.ADCS) {
+ return adcsFns.createCertificateAuthority({
+ name,
+ projectId,
+ configuration: configuration as TCreateADCSCertificateAuthorityDTO["configuration"],
+ status,
+ actor
+ });
+ }
+
if (type === CaType.AWS_PCA) {
return awsPcaFns.createCertificateAuthority({
name,
@@ -433,6 +466,10 @@ export const certificateAuthorityServiceFactory = ({
return castDbEntryToAzureAdCsCertificateAuthority(certificateAuthority);
}
+ if (type === CaType.ADCS) {
+ return castDbEntryToADCSCertificateAuthority(certificateAuthority);
+ }
+
if (type === CaType.AWS_PCA) {
return castDbEntryToAwsPcaCertificateAuthority(certificateAuthority);
}
@@ -516,6 +553,10 @@ export const certificateAuthorityServiceFactory = ({
return castDbEntryToAzureAdCsCertificateAuthority(certificateAuthority);
}
+ if (type === CaType.ADCS) {
+ return castDbEntryToADCSCertificateAuthority(certificateAuthority);
+ }
+
if (type === CaType.AWS_PCA) {
return castDbEntryToAwsPcaCertificateAuthority(certificateAuthority);
}
@@ -594,6 +635,10 @@ export const certificateAuthorityServiceFactory = ({
return azureAdCsFns.listCertificateAuthorities({ projectId, permissionFilters });
}
+ if (type === CaType.ADCS) {
+ return adcsFns.listCertificateAuthorities({ projectId, permissionFilters });
+ }
+
if (type === CaType.AWS_PCA) {
return awsPcaFns.listCertificateAuthorities({ projectId, permissionFilters });
}
@@ -699,6 +744,16 @@ export const certificateAuthorityServiceFactory = ({
});
}
+ if (type === CaType.ADCS) {
+ return adcsFns.updateCertificateAuthority({
+ id: certificateAuthority.id,
+ configuration: configuration as TUpdateADCSCertificateAuthorityDTO["configuration"],
+ actor,
+ status,
+ name
+ });
+ }
+
if (type === CaType.AWS_PCA) {
return awsPcaFns.updateCertificateAuthority({
id: certificateAuthority.id,
@@ -809,6 +864,10 @@ export const certificateAuthorityServiceFactory = ({
return castDbEntryToAzureAdCsCertificateAuthority(certificateAuthority);
}
+ if (type === CaType.ADCS) {
+ return castDbEntryToADCSCertificateAuthority(certificateAuthority);
+ }
+
if (type === CaType.AWS_PCA) {
return castDbEntryToAwsPcaCertificateAuthority(certificateAuthority);
}
@@ -911,6 +970,16 @@ export const certificateAuthorityServiceFactory = ({
});
}
+ if (type === CaType.ADCS) {
+ return adcsFns.updateCertificateAuthority({
+ id: certificateAuthority.id,
+ configuration: configuration as TUpdateADCSCertificateAuthorityDTO["configuration"],
+ actor,
+ status,
+ name
+ });
+ }
+
if (type === CaType.AWS_PCA) {
return awsPcaFns.updateCertificateAuthority({
id: certificateAuthority.id,
@@ -1027,6 +1096,10 @@ export const certificateAuthorityServiceFactory = ({
return castDbEntryToAzureAdCsCertificateAuthority(certificateAuthority);
}
+ if (type === CaType.ADCS) {
+ return castDbEntryToADCSCertificateAuthority(certificateAuthority);
+ }
+
if (type === CaType.AWS_PCA) {
return castDbEntryToAwsPcaCertificateAuthority(certificateAuthority);
}
@@ -1094,6 +1167,50 @@ export const certificateAuthorityServiceFactory = ({
});
};
+ const getADCSTemplates = async ({
+ caId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: {
+ caId: string;
+ projectId: string;
+ actor: OrgServiceActor["type"];
+ actorId: string;
+ actorAuthMethod: OrgServiceActor["authMethod"];
+ actorOrgId?: string;
+ }) => {
+ const certificateAuthority = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+
+ if (!certificateAuthority)
+ throw new NotFoundError({
+ message: `Could not find certificate authority with id "${caId}"`
+ });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateAuthorityActions.Read,
+ subject(ProjectPermissionSub.CertificateAuthorities, {
+ name: certificateAuthority.name
+ })
+ );
+
+ return adcsFns.getCertificateTemplates({
+ caId,
+ projectId
+ });
+ };
+
const getCaById = async ({
caId,
actor,
@@ -1277,6 +1394,7 @@ export const certificateAuthorityServiceFactory = ({
updateCertificateAuthority,
deleteCertificateAuthority,
getAzureAdcsTemplates,
+ getADCSTemplates,
getCaById,
deprecatedUpdateCertificateAuthority,
deprecatedDeleteCertificateAuthority,
diff --git a/backend/src/services/certificate-authority/certificate-authority-types.ts b/backend/src/services/certificate-authority/certificate-authority-types.ts
index 414f956c4d..6d75bddec1 100644
--- a/backend/src/services/certificate-authority/certificate-authority-types.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-types.ts
@@ -1,4 +1,5 @@
import { TAcmeCertificateAuthority, TAcmeCertificateAuthorityInput } from "./acme/acme-certificate-authority-types";
+import { TADCSCertificateAuthority, TCreateADCSCertificateAuthorityDTO } from "./adcs/adcs-certificate-authority-types";
import {
TAwsAcmPublicCaCertificateAuthority,
TCreateAwsAcmPublicCaCertificateAuthorityDTO
@@ -33,6 +34,7 @@ export type TCertificateAuthority =
| TInternalCertificateAuthority
| TAcmeCertificateAuthority
| TAzureAdCsCertificateAuthority
+ | TADCSCertificateAuthority
| TAwsPcaCertificateAuthority
| TDigiCertCertificateAuthority
| TGoDaddyCertificateAuthority
@@ -43,6 +45,7 @@ export type TCertificateAuthorityInput =
| TInternalCertificateAuthorityInput
| TAcmeCertificateAuthorityInput
| TCreateAzureAdCsCertificateAuthorityDTO
+ | TCreateADCSCertificateAuthorityDTO
| TCreateAwsPcaCertificateAuthorityDTO
| TCreateDigiCertCertificateAuthorityDTO
| TCreateGoDaddyCertificateAuthorityDTO
diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
index 45f984bd79..18befcf97e 100644
--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts
+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
@@ -55,6 +55,7 @@ import {
runWithAcmeOrderTimeout
} from "./acme/acme-certificate-authority-errors";
import { AcmeCertificateAuthorityFns } from "./acme/acme-certificate-authority-fns";
+import { ADCSCertificateAuthorityFns } from "./adcs/adcs-certificate-authority-fns";
import { AcmPendingError } from "./aws-acm-public-ca/aws-acm-public-ca-certificate-authority-errors";
import { AwsAcmPublicCaCertificateAuthorityFns } from "./aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns";
import { AwsPcaCertificateAuthorityFns } from "./aws-pca/aws-pca-certificate-authority-fns";
@@ -96,6 +97,25 @@ const ensureCsrPemFormat = (csr: string): string => {
return `-----BEGIN CERTIFICATE REQUEST-----\n${base64Lines.join("\n")}\n-----END CERTIFICATE REQUEST-----`;
};
+const extractProfileTemplate = async (
+ certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findById"> | undefined,
+ profileId: string | undefined
+): Promise<string | undefined> => {
+ if (!certificateProfileDAL || !profileId) return undefined;
+ try {
+ const profile = await certificateProfileDAL.findById(profileId);
+ if (profile?.externalConfigs && typeof profile.externalConfigs === "object" && profile.externalConfigs !== null) {
+ const { template } = profile.externalConfigs;
+ if (typeof template === "string") return template;
+ }
+ } catch (error) {
+ logger.warn(
+ `Failed to fetch profile ${profileId} for template extraction: ${error instanceof Error ? error.message : String(error)}`
+ );
+ }
+ return undefined;
+};
+
export type TIssueCertificateFromProfileJobData = {
certificateId: string;
profileId?: string;
@@ -217,6 +237,21 @@ export const certificateIssuanceQueueFactory = ({
certificateProfileDAL
});
+ const adcsFns = ADCSCertificateAuthorityFns({
+ appConnectionDAL,
+ appConnectionService,
+ certificateAuthorityDAL,
+ externalCertificateAuthorityDAL,
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ kmsService,
+ projectDAL,
+ certificateProfileDAL,
+ gatewayV2Service,
+ gatewayPoolService
+ });
+
const awsPcaFns = AwsPcaCertificateAuthorityFns({
appConnectionDAL,
appConnectionService,
@@ -530,26 +565,7 @@ export const certificateIssuanceQueueFactory = ({
}
} else if (ca.externalCa?.type === CaType.AZURE_AD_CS) {
await setPending("Submitting the request to Azure AD CS");
- let template: string | undefined;
- if (certificateProfileDAL && profileId) {
- try {
- const profile = await certificateProfileDAL.findById(profileId);
- if (
- profile?.externalConfigs &&
- typeof profile.externalConfigs === "object" &&
- profile.externalConfigs !== null
- ) {
- const configs = profile.externalConfigs;
- if (typeof configs.template === "string") {
- template = configs.template;
- }
- }
- } catch (error) {
- logger.warn(
- `Failed to fetch profile ${profileId} for template extraction: ${error instanceof Error ? error.message : String(error)}`
- );
- }
- }
+ const template = await extractProfileTemplate(certificateProfileDAL, profileId);
const azureParams = {
caId,
@@ -594,6 +610,74 @@ export const certificateIssuanceQueueFactory = ({
certificateId: azureResult.certificateId
});
+ logger.info(`Certificate attached to request [certificateRequestId=${certificateRequestId}]`);
+ } catch (attachError) {
+ logger.error(
+ attachError,
+ `Failed to attach certificate to request [certificateRequestId=${certificateRequestId}]`
+ );
+ try {
+ await certificateRequestService.updateCertificateRequestStatus({
+ certificateRequestId,
+ status: CertificateRequestStatus.FAILED,
+ errorMessage: `Failed to attach certificate: ${attachError instanceof Error ? attachError.message : String(attachError)}`
+ });
+ } catch (statusUpdateError) {
+ logger.error(
+ statusUpdateError,
+ `Failed to update certificate request status [certificateRequestId=${certificateRequestId}]`
+ );
+ }
+ }
+ }
+ } else if (ca.externalCa?.type === CaType.ADCS) {
+ await setPending("Submitting the request to Active Directory Certificate Service");
+ const template = await extractProfileTemplate(certificateProfileDAL, profileId);
+
+ const adcsParams = {
+ caId,
+ profileId,
+ commonName: commonName || "",
+ altNames: altNames?.map((san) => san.value) || [],
+ keyUsages: keyUsages as CertKeyUsage[],
+ extendedKeyUsages: extendedKeyUsages as CertExtendedKeyUsage[],
+ validity: { ttl },
+ signatureAlgorithm,
+ keyAlgorithm: keyAlgorithm as CertKeyAlgorithm,
+ isRenewal,
+ originalCertificateId,
+ template,
+ isCancelled
+ };
+
+ if (await isCancelled()) {
+ logger.info(
+ `Cancelled before Active Directory Certificate Service order [certificateRequestId=${certificateRequestId}]`
+ );
+ return;
+ }
+
+ const adcsResult = await adcsFns.orderCertificate(adcsParams as Parameters<typeof adcsFns.orderCertificate>[0]);
+
+ if (await isCancelled()) {
+ logger.info(
+ `Cancelled after Active Directory Certificate Service order [certificateRequestId=${certificateRequestId}]`
+ );
+ return;
+ }
+
+ if (certificateRequestId && certificateRequestService && adcsResult?.certificateId) {
+ try {
+ await certificateRequestService.attachCertificateToRequest({
+ certificateRequestId,
+ certificateId: adcsResult.certificateId
+ });
+
+ await copyMetadataFromRequestToCertificate(resourceMetadataDAL, {
+ certificateRequestId,
+ certificateId: adcsResult.certificateId
+ });
+
logger.info(`Certificate attached to request [certificateRequestId=${certificateRequestId}]`);
} catch (attachError) {
logger.error(
@@ -1242,6 +1326,7 @@ export const certificateIssuanceQueueFactory = ({
processCertificateIssuanceJobs,
acmeFns,
azureAdCsFns,
+ adcsFns,
awsPcaFns,
awsAcmPublicCaFns,
digicertFns,
diff --git a/backend/src/services/certificate-profile/certificate-profile-external-config-schemas.ts b/backend/src/services/certificate-profile/certificate-profile-external-config-schemas.ts
index e9889ff193..d2b0a01f09 100644
--- a/backend/src/services/certificate-profile/certificate-profile-external-config-schemas.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-external-config-schemas.ts
@@ -12,6 +12,16 @@ export const AzureAdCsExternalConfigSchema = z.object({
.describe("Certificate template name for Azure AD CS")
});
+/**
+ * External configuration schema for Active Directory Certificate Service Certificate Authority
+ */
+export const ADCSExternalConfigSchema = z.object({
+ template: z
+ .string()
+ .min(1, "Template name is required for Active Directory Certificate Service")
+ .describe("Certificate template name for Active Directory Certificate Service")
+});
+
/**
* External configuration schema for ACME Certificate Authority
*/
@@ -47,6 +57,7 @@ export const GoDaddyExternalConfigSchema = z.object({});
*/
export const ExternalConfigSchemaMap = {
[CaType.AZURE_AD_CS]: AzureAdCsExternalConfigSchema,
+ [CaType.ADCS]: ADCSExternalConfigSchema,
[CaType.ACME]: AcmeExternalConfigSchema,
[CaType.AWS_PCA]: AwsPcaExternalConfigSchema,
[CaType.DIGICERT]: DigiCertExternalConfigSchema,
@@ -75,6 +86,7 @@ export const createExternalConfigSchema = (caType?: CaType | null) => {
export const ExternalConfigUnionSchema = z
.union([
AzureAdCsExternalConfigSchema,
+ ADCSExternalConfigSchema,
AcmeExternalConfigSchema,
AwsPcaExternalConfigSchema,
DigiCertExternalConfigSchema,
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.ts
index 3d01589139..3fc5fb17fd 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts
@@ -102,6 +102,14 @@ const validateTemplateByExternalCaType = (
});
}
break;
+ case CaType.ADCS:
+ if (!externalConfigs?.template || typeof externalConfigs.template !== "string") {
+ throw new ForbiddenRequestError({
+ message:
+ "Active Directory Certificate Service Certificate Authority requires a template to be specified in external configs"
+ });
+ }
+ break;
default:
break;
}
diff --git a/backend/src/services/certificate-v3/certificate-approval-fns.ts b/backend/src/services/certificate-v3/certificate-approval-fns.ts
index f7a767b039..9025090c13 100644
--- a/backend/src/services/certificate-v3/certificate-approval-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-approval-fns.ts
@@ -639,6 +639,7 @@ export const certificateApprovalServiceFactory = (
if (
caType !== CaType.ACME &&
caType !== CaType.AZURE_AD_CS &&
+ caType !== CaType.ADCS &&
caType !== CaType.AWS_PCA &&
caType !== CaType.AWS_ACM_PUBLIC_CA &&
caType !== CaType.VENAFI_TPP &&
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index 43878fd8de..a912891185 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -319,6 +319,7 @@ const validateRenewalEligibility = (
const isConnectedExternalCa =
caType === CaType.ACME ||
caType === CaType.AZURE_AD_CS ||
+ caType === CaType.ADCS ||
caType === CaType.AWS_PCA ||
caType === CaType.AWS_ACM_PUBLIC_CA ||
caType === CaType.DIGICERT ||
@@ -2165,6 +2166,7 @@ export const certificateV3ServiceFactory = ({
if (
caType === CaType.ACME ||
caType === CaType.AZURE_AD_CS ||
+ caType === CaType.ADCS ||
caType === CaType.AWS_PCA ||
caType === CaType.DIGICERT ||
caType === CaType.AWS_ACM_PUBLIC_CA ||
@@ -2576,6 +2578,7 @@ export const certificateV3ServiceFactory = ({
} else if (
caType === CaType.ACME ||
caType === CaType.AZURE_AD_CS ||
+ caType === CaType.ADCS ||
caType === CaType.AWS_PCA ||
caType === CaType.DIGICERT ||
caType === CaType.AWS_ACM_PUBLIC_CA ||
diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.ts
index 672a570eea..a229fefbc3 100644
--- a/backend/src/services/signer/signer-issuance-service.ts
+++ b/backend/src/services/signer/signer-issuance-service.ts
@@ -32,6 +32,7 @@ import { CertKeySource, HsmKeyAlgorithm, SignerIssuanceJobStatus, SignerStatus }
import { formatSignerIssuanceErrorReason, isTerminalIssuanceError } from "./signer-issuance-errors";
import { hsmKeyAlgorithmToCertKeyAlgorithm, verifyCodeSigningEku } from "./signer-issuance-fns";
import { TSignerIssuanceJobDALFactory } from "./signer-issuance-job-dal";
+import { SignerExternalCaConfigSchema } from "./signer-types";
const POLL_INTERVAL_PATTERN = "*/15 * * * *"; // every 15 minutes
const POLL_BATCH = 25;
@@ -78,13 +79,16 @@ export type TSignerIssuanceServiceFactory = ReturnType<typeof signerIssuanceServ
type TSignerIssuanceServiceDeps = {
signerIssuanceJobDAL: TSignerIssuanceJobDALFactory;
- signerDAL: Pick<TSignerDALFactory, "updateById" | "transaction">;
+ signerDAL: Pick<TSignerDALFactory, "updateById" | "transaction" | "findById">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create" | "updateById">;
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "decryptWithKmsKey" | "generateKmsKey">;
- certificateIssuanceQueue: Pick<TCertificateIssuanceQueueFactory, "awsPcaFns" | "azureAdCsFns" | "digicertFns">;
+ certificateIssuanceQueue: Pick<
+ TCertificateIssuanceQueueFactory,
+ "awsPcaFns" | "azureAdCsFns" | "adcsFns" | "digicertFns"
+ >;
cronJob: TCronJobFactory;
hsmConnectorService: Pick<THsmConnectorServiceFactory, "generateKeyPair" | "sign" | "assertAttachPermission">;
certificateDAL: Pick<TCertificateDALFactory, "updateById" | "findById">;
@@ -121,7 +125,7 @@ export const signerIssuanceServiceFactory = ({
hsmConnectorService,
certificateDAL
}: TSignerIssuanceServiceDeps) => {
- const { awsPcaFns, azureAdCsFns, digicertFns } = certificateIssuanceQueue;
+ const { awsPcaFns, azureAdCsFns, adcsFns, digicertFns } = certificateIssuanceQueue;
const buildCsrForSigner = async (
commonName: string,
@@ -370,6 +374,9 @@ export const signerIssuanceServiceFactory = ({
case CaType.AZURE_AD_CS:
await stepSyncWithCsr(job, CaType.AZURE_AD_CS);
break;
+ case CaType.ADCS:
+ await stepSyncWithCsr(job, CaType.ADCS);
+ break;
case CaType.AWS_PCA:
await stepSyncWithCsr(job, CaType.AWS_PCA);
break;
@@ -379,7 +386,7 @@ export const signerIssuanceServiceFactory = ({
default:
await markJobFailed(
job,
- `CA type '${job.caType}' is not supported for code signing. Choose Internal CA, AWS Private CA, Azure AD CS, or DigiCert.`
+ `CA type '${job.caType}' is not supported for code signing. Choose Internal CA, AWS Private CA, Azure AD CS, Active Directory Certificate Service, or DigiCert.`
);
}
} catch (err) {
@@ -513,7 +520,10 @@ export const signerIssuanceServiceFactory = ({
);
};
- const stepSyncWithCsr = async (job: TPkiSignerCertificateIssuanceJobs, kind: CaType.AZURE_AD_CS | CaType.AWS_PCA) => {
+ const stepSyncWithCsr = async (
+ job: TPkiSignerCertificateIssuanceJobs,
+ kind: CaType.AZURE_AD_CS | CaType.ADCS | CaType.AWS_PCA
+ ) => {
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(job.caId);
if (!ca) {
await markJobFailed(job, "Certificate authority is no longer available.");
@@ -546,6 +556,37 @@ export const signerIssuanceServiceFactory = ({
throw new BadRequestError({ message: "Azure AD CS order returned without a certificate id." });
}
certificateId = azureResult.certificateId;
+ } else if (kind === CaType.ADCS) {
+ if (job.keySource === CertKeySource.Hsm) {
+ throw new BadRequestError({
+ message:
+ "HSM-backed signers are not supported with Active Directory Certificate Service yet. Use AWS Private CA, or switch the signer's key source to Infisical."
+ });
+ }
+ const signer = await signerDAL.findById(job.signerId);
+ const externalCaConfig = SignerExternalCaConfigSchema.safeParse(signer?.externalCaConfig);
+ const adcsTemplate =
+ externalCaConfig.success && externalCaConfig.data.caType === CaType.ADCS
+ ? externalCaConfig.data.template
+ : undefined;
+ const adcsResult = await adcsFns.orderCertificate({
+ caId: job.caId,
+ commonName: job.commonName,
+ altNames: [],
+ keyUsages: [CertKeyUsage.DIGITAL_SIGNATURE, CertKeyUsage.KEY_ENCIPHERMENT],
+ extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],
+ validity: { ttl: `${job.certificateTtlDays}d` },
+ keyAlgorithm: job.keyAlgorithm as CertKeyAlgorithm,
+ template: adcsTemplate,
+ isRenewal: false,
+ isCancelled: async () => false
+ });
+ if (!adcsResult?.certificateId) {
+ throw new BadRequestError({
+ message: "Active Directory Certificate Service order returned without a certificate id."
+ });
+ }
+ certificateId = adcsResult.certificateId;
} else {
const awsResult = await awsPcaFns.orderCertificate({
caId: job.caId,
diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.ts
index 332caa599e..2c2675d6d5 100644
--- a/backend/src/services/signer/signer-service.ts
+++ b/backend/src/services/signer/signer-service.ts
@@ -67,6 +67,7 @@ import {
} from "./signer-issuance-fns";
import { TSignerIssuanceServiceFactory } from "./signer-issuance-service";
import {
+ SignerExternalCaConfigSchema,
TCreateSignerDTO,
TDeleteSignerDTO,
TDisableSignerDTO,
@@ -78,6 +79,7 @@ import {
TListSigningOperationsDTO,
TReissueCertificateDTO,
TSignDataDTO,
+ TSignerExternalCaConfig,
TUpdateSignerDTO
} from "./signer-types";
import { TSigningOperationDALFactory } from "./signing-operation-dal";
@@ -85,14 +87,19 @@ import { TSigningOperationDALFactory } from "./signing-operation-dal";
const MAX_DATA_BYTES = 128;
const DEFAULT_CERTIFICATE_TTL_DAYS = 365;
-const CODE_SIGNING_SUPPORTED_EXTERNAL_CA_TYPES = new Set<CaType>([CaType.AWS_PCA, CaType.AZURE_AD_CS, CaType.DIGICERT]);
+const CODE_SIGNING_SUPPORTED_EXTERNAL_CA_TYPES = new Set<CaType>([
+ CaType.AWS_PCA,
+ CaType.AZURE_AD_CS,
+ CaType.ADCS,
+ CaType.DIGICERT
+]);
const assertCaTypeSupportsCodeSigning = (caType: CaType): void => {
if (caType === CaType.INTERNAL) return;
if (!CODE_SIGNING_SUPPORTED_EXTERNAL_CA_TYPES.has(caType)) {
throw new BadRequestError({
message:
- "Code signing is only supported on Internal CAs, AWS Private CA, Azure AD CS, and DigiCert. Pick a different certificate authority."
+ "Code signing is only supported on Internal CAs, AWS Private CA, Azure AD CS, ADCS, and DigiCert. Pick a different certificate authority."
});
}
};
@@ -436,10 +443,30 @@ export const signerServiceFactory = ({
const isExternalCa = resolvedCaType !== null && resolvedCaType !== CaType.INTERNAL;
- if (resolvedCaType === CaType.AZURE_AD_CS && dto.certificate?.keySource === CertKeySource.Hsm) {
+ const adcsTemplate =
+ createExternalConfig?.caType === CaType.ADCS ? createExternalConfig.template?.trim() || undefined : undefined;
+ if (adcsTemplate && resolvedCaType !== CaType.ADCS) {
throw new BadRequestError({
message:
- "HSM-backed signers are not supported with Azure AD CS yet. Use AWS Private CA, an Internal CA, or switch the signer's key source to Infisical-managed."
+ "A certificate template can only be set for signers backed by an Active Directory Certificate Service CA."
+ });
+ }
+ if (resolvedCaType === CaType.ADCS && !adcsTemplate) {
+ throw new BadRequestError({
+ message: "A certificate template is required for signers backed by an Active Directory Certificate Service CA."
+ });
+ }
+ const externalCaConfig: TSignerExternalCaConfig | null = adcsTemplate
+ ? { caType: CaType.ADCS, template: adcsTemplate }
+ : null;
+
+ if (
+ (resolvedCaType === CaType.AZURE_AD_CS || resolvedCaType === CaType.ADCS) &&
+ dto.certificate?.keySource === CertKeySource.Hsm
+ ) {
+ throw new BadRequestError({
+ message:
+ "HSM-backed signers are not supported with AD CS yet. Use AWS Private CA, an Internal CA, or switch the signer's key source to Infisical-managed."
});
}
@@ -494,7 +521,8 @@ export const signerServiceFactory = ({
keyAlgorithm,
status: initialStatus,
approvalPolicyId: policy.id,
- certificateFailureReason: null
+ certificateFailureReason: null,
+ externalCaConfig
},
tx
);
@@ -1201,6 +1229,30 @@ export const signerServiceFactory = ({
await digicertFns.assertCodeSigningOrderReusable(ca.id, explicitReissueOrderId);
}
+ const providedAdcsTemplate =
+ reissueExternalConfig?.caType === CaType.ADCS ? reissueExternalConfig.template?.trim() || undefined : undefined;
+ if (providedAdcsTemplate && reissueCaType !== CaType.ADCS) {
+ throw new BadRequestError({
+ message:
+ "A certificate template can only be set for signers backed by an Active Directory Certificate Service CA."
+ });
+ }
+ const existingConfig = SignerExternalCaConfigSchema.safeParse(signer.externalCaConfig);
+ const existingAdcsTemplate =
+ existingConfig.success && existingConfig.data.caType === CaType.ADCS ? existingConfig.data.template : undefined;
+ let nextExternalCaConfig: TSignerExternalCaConfig | null = null;
+ if (reissueCaType === CaType.ADCS) {
+ // Keep the signer's existing template when the request doesn't supply a new one.
+ const template = providedAdcsTemplate ?? existingAdcsTemplate;
+ if (!template) {
+ throw new BadRequestError({
+ message:
+ "A certificate template is required for signers backed by an Active Directory Certificate Service CA."
+ });
+ }
+ nextExternalCaConfig = { caType: CaType.ADCS, template };
+ }
+
let nextCommonName = signer.commonName;
let effectiveTtl = signer.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS;
if (!explicitReissueOrderId) {
@@ -1242,10 +1294,10 @@ export const signerServiceFactory = ({
: null)
});
- if (reissueCaType === CaType.AZURE_AD_CS && target.isHsm) {
+ if ((reissueCaType === CaType.AZURE_AD_CS || reissueCaType === CaType.ADCS) && target.isHsm) {
throw new BadRequestError({
message:
- "HSM-backed signers are not supported with Azure AD CS yet. Use AWS Private CA, an Internal CA, or switch the signer's key source to Infisical."
+ "HSM-backed signers are not supported with AD CS yet. Use AWS Private CA, an Internal CA, or switch the signer's key source to Infisical."
});
}
@@ -1261,7 +1313,8 @@ export const signerServiceFactory = ({
caId: dto.caId,
commonName: nextCommonName,
certificateTtlDays: effectiveTtl,
- keyAlgorithm: target.keyAlgorithm
+ keyAlgorithm: target.keyAlgorithm,
+ externalCaConfig: nextExternalCaConfig
});
const reissueCtx: TReissueExecutionContext = {
diff --git a/backend/src/services/signer/signer-types.ts b/backend/src/services/signer/signer-types.ts
index 3cad7ee658..c06059b133 100644
--- a/backend/src/services/signer/signer-types.ts
+++ b/backend/src/services/signer/signer-types.ts
@@ -1,3 +1,5 @@
+import { z } from "zod";
+
import { SigningAlgorithm } from "@app/lib/crypto/sign/types";
import { TProjectPermission } from "@app/lib/types";
@@ -23,10 +25,24 @@ export type TSignerCertificateInput = {
hsmConnectorId?: string;
};
-export type TSignerExternalConfigurationInput = {
- caType: CaType.DIGICERT;
- reissueFromExternalOrderId?: string;
-};
+export type TSignerExternalConfigurationInput =
+ | {
+ caType: CaType.DIGICERT;
+ reissueFromExternalOrderId?: string;
+ }
+ | {
+ caType: CaType.ADCS;
+ template?: string;
+ };
+
+export const SignerExternalCaConfigSchema = z.discriminatedUnion("caType", [
+ z.object({
+ caType: z.literal(CaType.ADCS),
+ template: z.string().trim().min(1).optional()
+ })
+]);
+
+export type TSignerExternalCaConfig = z.infer<typeof SignerExternalCaConfigSchema>;
export type TCreateSignerDTO = {
name: string;
diff --git a/docs/docs.json b/docs/docs.json
index 4b2717289d..3c29ca55bf 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -109,6 +109,7 @@
"integrations/app-connections/1password",
"integrations/app-connections/anthropic",
"integrations/app-connections/auth0",
+ "integrations/app-connections/adcs",
"integrations/app-connections/aws",
"integrations/app-connections/azure-app-configuration",
"integrations/app-connections/azure-adcs",
@@ -893,6 +894,7 @@
"documentation/platform/pki/ca/godaddy",
"documentation/platform/pki/ca/sectigo",
"documentation/platform/pki/ca/azure-adcs",
+ "documentation/platform/pki/ca/adcs",
"documentation/platform/pki/ca/aws-pca",
"documentation/platform/pki/ca/aws-acm-public-ca",
"documentation/platform/pki/ca/venafi",
diff --git a/docs/documentation/platform/pki/ca/adcs.mdx b/docs/documentation/platform/pki/ca/adcs.mdx
new file mode 100644
index 0000000000..50c084d508
--- /dev/null
+++ b/docs/documentation/platform/pki/ca/adcs.mdx
@@ -0,0 +1,207 @@
+---
+title: "Microsoft AD CS (Native)"
+description: "Learn how to issue and manage certificates using Microsoft Active Directory Certificate Services (AD CS) over MS-WCCE through an Infisical Gateway."
+---
+
+Issue and manage certificates using Microsoft Active Directory Certificate Services (AD CS) over the native Windows Client Certificate Enrollment protocol (MS-WCCE). Requests are relayed through an Infisical [Gateway](/documentation/platform/gateways/overview) that runs inside your network, so the AD CS server is never exposed to Infisical.
+
+<Note>
+ This is the native AD CS integration (MS-WCCE over DCOM through a Gateway). It is separate from the [Azure ADCS (Web Enrollment)](/documentation/platform/pki/ca/azure-adcs) integration, which uses the AD CS web enrollment pages over HTTPS.
+</Note>
+
+## Prerequisites
+
+Before setting up the native AD CS integration, ensure you have:
+
+- A Microsoft Active Directory Certificate Services (AD CS) server (Enterprise CA)
+- An Infisical [Gateway](/documentation/platform/gateways/overview) deployed inside the network that can reach the AD CS server over DCOM
+- A domain account with Enroll permission on the certificate templates you plan to use
+- An ADCS app connection configured (see [ADCS Connection](/integrations/app-connections/adcs))
+
+You can use AD CS in a few ways: as an **External CA** that issues certificates directly, to back a **code signing signer**, or to **sign internal intermediate CAs** so you can build an Infisical-managed CA hierarchy backed by your AD CS server. In every case the certificate template is chosen by the issuance flow (profile, signer, or intermediate CA), not by the CA itself.
+
+<Note>
+ The certificate authority name is discovered automatically from the CA host. Provide it explicitly only when discovery cannot run in your environment.
+</Note>
+
+<Tabs>
+ <Tab title="External CA">
+ <Steps>
+ <Step title="Navigate to External Certificate Authorities">
+ In **Certificate Manager**, go to **Certificate Authorities** and scroll to the **External Certificate Authorities** section.
+ </Step>
+
+ <Step title="Create a New ADCS Certificate Authority">
+ Click **Create CA** and configure:
+ - **Type**: Choose **ADCS**
+ - **Name**: Friendly name for this CA (for example, `production-adcs`)
+ - **ADCS Connection**: Choose your ADCS connection
+ - **Certificate Authority**: Optional. Leave blank to discover it automatically from the CA host.
+ </Step>
+
+ <Step title="Create a Certificate Profile">
+ Go to **Certificate Manager → Certificate Profiles** and create a new profile:
+ - **Certificate Authority**: Select your ADCS CA
+ - **Certificate Template**: Select from the templates published on your CA
+ - Configure the default certificate attributes (TTL, key algorithm, and so on)
+ </Step>
+
+ <Step title="Create an Application and Configure Enrollment">
+ Go to **Certificate Manager → Applications** and create an Application:
+ - Attach the profile you created
+ - Configure an [enrollment method](/documentation/platform/pki/applications/enrollment-methods/overview) (API, ACME, EST, or SCEP)
+ - Assign the members who need to issue certificates
+ </Step>
+
+ <Step title="Issue a Certificate">
+ In your Application, go to the **Certificate Requests** tab and click **Request**:
+ - Select the profile linked to your ADCS CA
+ - Fill in the certificate details (common name, SANs, TTL)
+ - Click **Submit**
+
+ The request is relayed through the Gateway to AD CS and issued using the profile's template.
+ </Step>
+ </Steps>
+
+ ## Certificate Templates
+
+ Infisical retrieves the templates published on your CA in real time, so a profile can only reference a template that exists and is reachable. The template lives on the issuance flow (the profile), not on the CA.
+
+ Ensure the templates you use are configured with:
+
+ - **Enroll permission** for the connection account
+ - **Subject name requirements** matching your requests
+ - **Key usage and extended key usage** appropriate for your use case
+ </Tab>
+
+ <Tab title="Code Signing Signers">
+ A [code signing signer](/documentation/platform/pki/code-signing/signers) backed by an ADCS CA requests a code-signing certificate from AD CS. The signer owns its certificate template.
+
+ When you create or edit a signer whose CA is an ADCS CA, the **Certificate** step shows a required **Certificate Template** field. Pick a code-signing template published on your CA (one that carries the Code Signing extended key usage).
+
+ <Note>
+ The issued certificate must carry the Code Signing extended key usage or Infisical rejects it. Use a template configured for code signing on your CA.
+ </Note>
+ </Tab>
+
+ <Tab title="Signing Internal Intermediate CAs">
+ You can use AD CS to **sign internal intermediate CAs** in Infisical. This lets you build an Infisical-managed CA hierarchy where the intermediate CA's certificate is issued by your AD CS server, with support for auto-renewal. Infisical generates the CSR, relays it to AD CS through the Gateway using the configured template, and imports the signed certificate and chain.
+
+ <Warning>
+ The certificate template must allow "Supply in the request" for subject information so that the CSR's subject fields are honored. A subordinate CA template (for example, `SubCA`) is the typical choice.
+ </Warning>
+
+ ## Installing an Intermediate CA Certificate via AD CS
+
+ <Tabs>
+ <Tab title="Infisical UI">
+ <Steps>
+ <Step title="Create an Intermediate CA">
+ Go to **Certificate Authorities → Internal Certificate Authorities** and press **Create CA**. Set the type to **Intermediate** and fill out the CA details.
+ </Step>
+ <Step title="Open the Install Certificate Modal">
+ Press **Install CA Certificate** on the intermediate CA, select **External CA (Automated)**, and press **Choose Integration**.
+ </Step>
+ <Step title="Select ADCS">
+ Choose **ADCS** as the integration provider.
+ </Step>
+ <Step title="Configure Signing Details">
+ Configure the following:
+ - **ADCS Connection**: Select your ADCS connection.
+ - **Certificate Template**: The subordinate CA template name (for example, `SubCA`).
+ - **Path Length**: Max intermediate CAs below this one (`-1` for no limit, `0` to prevent chaining).
+ </Step>
+ <Step title="Install">
+ Press **Install**. The request is queued and processed asynchronously.
+ </Step>
+ </Steps>
+ </Tab>
+ <Tab title="API">
+ <Steps>
+ <Step title="Create a Signing Configuration">
+ ```bash Request
+ curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<ca-id>/signing-config' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "type": "adcs",
+ "appConnectionId": "<adcs-connection-id>",
+ "destinationConfig": {
+ "template": "SubCA"
+ }
+ }'
+ ```
+ </Step>
+ <Step title="Install the Certificate">
+ ```bash Request
+ curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<ca-id>/install-certificate-adcs-native' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "maxPathLength": -1
+ }'
+ ```
+
+ Returns HTTP 202. Poll the CA details endpoint to check when the certificate has been installed.
+ </Step>
+ </Steps>
+ </Tab>
+ </Tabs>
+
+ ## Auto-Renewal
+
+ Infisical supports automatic renewal of intermediate CA certificates signed by AD CS. When enabled, Infisical submits a fresh CSR to AD CS through the Gateway and imports the renewed certificate before the current one expires.
+
+ <Tabs>
+ <Tab title="Infisical UI">
+ Navigate to the CA details page of your AD CS-signed intermediate CA. Click the **edit** (pencil) icon in the Details section to open the renewal settings.
+
+ Toggle **Auto-Renewal** on and set the **Days Before Expiry** to configure when the renewal should be triggered.
+ </Tab>
+ <Tab title="API">
+ ```bash Request
+ curl --location --request PATCH 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<ca-id>/auto-renewal' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "autoRenewalEnabled": true,
+ "autoRenewalDaysBeforeExpiry": 7
+ }'
+ ```
+
+ <Note>
+ - `autoRenewalDaysBeforeExpiry` must be less than the certificate's TTL and at most 30 days
+ - Auto-renewal is only available for CAs with an external signing configuration
+ </Note>
+ </Tab>
+ </Tabs>
+ </Tab>
+</Tabs>
+
+## Limitations
+
+<Note>
+ - Requests are issued immediately. Templates that require manual approval or are held by CA policy are not supported.
+ - Certificate revocation is not supported by the native AD CS integration.
+ - Authentication uses NTLM.
+</Note>
+
+## Troubleshooting
+
+<AccordionGroup>
+ <Accordion title="The requested certificate template is not supported">
+ The CA rejected the request with `CERTSRV_E_UNSUPPORTED_CERT_TYPE`. The template is either not published on the CA or the name is wrong. Confirm the template is published (`certutil -CATemplates`) and that the name matches exactly.
+ </Accordion>
+ <Accordion title="Enroll permission denied">
+ The connection account does not have Enroll permission on the requested template. Grant Enroll to the account on the template's security settings.
+ </Accordion>
+ <Accordion title="The certificate authority name could not be discovered">
+ Discovery reads the CA name from the host's registry over the network, which requires the Remote Registry service to be running and reachable from the Gateway. If it cannot run, set the certificate authority name explicitly on the external CA.
+ </Accordion>
+ <Accordion title="Signer rejected: missing Code Signing extended key usage">
+ The template used for a code signing signer does not produce a code-signing certificate. Point the signer at a template that carries the Code Signing extended key usage.
+ </Accordion>
+ <Accordion title="Gateway connectivity issues">
+ Verify the Gateway can reach the AD CS host over DCOM (MS-WCCE) and that the domain account credentials are correct.
+ </Accordion>
+</AccordionGroup>
diff --git a/docs/documentation/platform/pki/ca/external-ca.mdx b/docs/documentation/platform/pki/ca/external-ca.mdx
index baebb71da4..1f984de9bb 100644
--- a/docs/documentation/platform/pki/ca/external-ca.mdx
+++ b/docs/documentation/platform/pki/ca/external-ca.mdx
@@ -56,8 +56,11 @@ Infisical can act as an ACME client, allowing integration with any [ACME-compati
<Card title="AWS Private CA" icon="aws" href="/documentation/platform/pki/ca/aws-pca">
Cloud-native private certificate management via AWS PCA.
</Card>
- <Card title="Azure ADCS" icon="microsoft" href="/documentation/platform/pki/ca/azure-adcs">
- Microsoft Active Directory Certificate Services integration.
+ <Card title="Azure ADCS (Web Enrollment)" icon="microsoft" href="/documentation/platform/pki/ca/azure-adcs">
+ Microsoft AD CS via the web enrollment pages over HTTPS.
+ </Card>
+ <Card title="ADCS (Native)" icon="microsoft" href="/documentation/platform/pki/ca/adcs">
+ Microsoft AD CS over MS-WCCE through an Infisical Gateway.
</Card>
<Card title="Venafi TLS Protect Cloud" icon="cloud" href="/documentation/platform/pki/ca/venafi">
Venafi's cloud-based certificate management platform.
diff --git a/docs/documentation/platform/pki/code-signing/signers.mdx b/docs/documentation/platform/pki/code-signing/signers.mdx
index f3b3276d80..098b2e76d8 100644
--- a/docs/documentation/platform/pki/code-signing/signers.mdx
+++ b/docs/documentation/platform/pki/code-signing/signers.mdx
@@ -62,7 +62,8 @@ In **Certificate Manager → Code Signing → Signers**, click **Create Signer**
| Field | Description |
|-------|-------------|
- | **Certificate Authority** | The CA that issues the certificate. Internal CAs issue immediately. External CAs (AWS Private CA, Azure AD CS, DigiCert) issue asynchronously and the Signer enters **Pending** until the cert lands. |
+ | **Certificate Authority** | The CA that issues the certificate. Internal CAs issue immediately. External CAs (AWS Private CA, Azure AD CS, ADCS, DigiCert) issue asynchronously and the Signer enters **Pending** until the cert lands. |
+ | **Certificate Template** | ADCS CAs only, required. The AD CS template this Signer requests. Pick a code-signing template published on your CA. |
| **Common Name** | The legal name shown on the certificate, for example `Acme Mobile, Inc.`. You can change it later; doing so reissues the certificate. |
| **Validity (days)** | How long each issued certificate is valid for. Default 365. |
| **Renew before (days)** | Optional, 1 to 30. Auto-renew this many days before expiry. Must be less than Validity. Leave empty to disable auto-renewal. |
diff --git a/docs/integrations/app-connections/adcs.mdx b/docs/integrations/app-connections/adcs.mdx
new file mode 100644
index 0000000000..7c2c638dc9
--- /dev/null
+++ b/docs/integrations/app-connections/adcs.mdx
@@ -0,0 +1,49 @@
+---
+title: "ADCS Connection"
+description: "Learn how to configure a native ADCS Connection for Infisical certificate management."
+---
+
+Connect Infisical to Microsoft Active Directory Certificate Services (AD CS) over MS-WCCE through an Infisical [Gateway](/documentation/platform/gateways/overview). The Gateway runs inside your network and speaks to the CA directly, so the AD CS server never needs to be exposed to Infisical.
+
+<Note>
+ This is the native AD CS integration. It talks to the CA over the Windows Client Certificate Enrollment protocol (MS-WCCE) through a Gateway. It is separate from the [Azure ADCS (Web Enrollment)](/integrations/app-connections/azure-adcs) connection, which uses the AD CS web enrollment pages over HTTPS.
+</Note>
+
+## Prerequisites
+
+- A Microsoft Active Directory Certificate Services (AD CS) server (Enterprise CA)
+- An Infisical [Gateway](/documentation/platform/gateways/overview) deployed inside the network that can reach the AD CS server
+- A domain account with Enroll permission on the certificate templates you plan to use
+- Network connectivity from the Gateway to the AD CS server over DCOM (MS-WCCE)
+
+<Note>
+ The connection authenticates with NTLM. The Gateway reaches the CA host over DCOM. No inbound access to the AD CS server from Infisical is required, and no configuration file is created on the Gateway.
+</Note>
+
+## 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 **ADCS Connection** option from the connection options modal.
+ </Step>
+ <Step title="Configure Connection Details">
+ - **Name**: Friendly name for this connection (for example, `production-adcs`)
+ - **CA Host**: The AD CS server hostname or IP reachable from the Gateway (for example, `ca01.corp.example.com`)
+ - **Username**: Domain account in the form `DOMAIN\username` or `[email protected]`
+ - **Password**: Password for the domain account
+ - **Gateway**: The Gateway that can reach the AD CS server
+
+ A Gateway is required. The control plane cannot reach AD CS over DCOM directly, so every operation is relayed through the Gateway.
+ </Step>
+ <Step title="Connection Created">
+ Your **ADCS Connection** is now available for use in your Infisical projects.
+ </Step>
+</Steps>
+
+## Certificate Authority Name
+
+The AD CS certificate authority name is discovered automatically from the CA host, so you do not have to enter it. If discovery cannot run in your environment (for example, the Remote Registry service is disabled on the CA host), provide the certificate authority name explicitly when creating the [external CA](/documentation/platform/pki/ca/adcs).
diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.ts
index a63e152398..c90368747f 100644
--- a/frontend/src/helpers/appConnections.ts
+++ b/frontend/src/helpers/appConnections.ts
@@ -50,6 +50,7 @@ import {
WindmillConnectionMethod,
ZabbixConnectionMethod
} from "@app/hooks/api/appConnections/types";
+import { AdcsConnectionMethod } from "@app/hooks/api/appConnections/types/adcs-connection";
import { AnthropicConnectionMethod } from "@app/hooks/api/appConnections/types/anthropic-connection";
import { AzureDNSConnectionMethod } from "@app/hooks/api/appConnections/types/azure-dns-connection";
import { AzureEntraIdConnectionMethod } from "@app/hooks/api/appConnections/types/azure-entra-id-connection";
@@ -153,10 +154,16 @@ export const APP_CONNECTION_MAP: Record<
description: "Pipeline and project access for Azure DevOps."
},
[AppConnection.AzureADCS]: {
- name: "Azure ADCS",
+ name: "Azure ADCS (Web Enrollment)",
image: "Microsoft Azure.png",
category: "CERTIFICATES",
- description: "Issue certificates via Active Directory Certificate Services."
+ description: "Issue certificates via Active Directory Certificate Services web enrollment."
+ },
+ [AppConnection.ADCS]: {
+ name: "ADCS",
+ image: "Microsoft Azure.png",
+ category: "CERTIFICATES",
+ description: "Issue certificates via Active Directory Certificate Services over the Gateway."
},
[AppConnection.AzureDNS]: {
name: "Azure DNS",
@@ -615,6 +622,7 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"])
case MySqlConnectionMethod.UsernameAndPassword:
case OracleDBConnectionMethod.UsernameAndPassword:
case AzureADCSConnectionMethod.UsernamePassword:
+ case AdcsConnectionMethod.UsernamePassword:
case RedisConnectionMethod.UsernameAndPassword:
case MongoDBConnectionMethod.UsernameAndPassword:
return { name: "Username & Password", icon: faLock };
diff --git a/frontend/src/hooks/api/appConnections/adcs/index.ts b/frontend/src/hooks/api/appConnections/adcs/index.ts
new file mode 100644
index 0000000000..b69c251208
--- /dev/null
+++ b/frontend/src/hooks/api/appConnections/adcs/index.ts
@@ -0,0 +1 @@
+export * from "./queries";
diff --git a/frontend/src/hooks/api/appConnections/adcs/queries.tsx b/frontend/src/hooks/api/appConnections/adcs/queries.tsx
new file mode 100644
index 0000000000..7bca7a46bb
--- /dev/null
+++ b/frontend/src/hooks/api/appConnections/adcs/queries.tsx
@@ -0,0 +1,39 @@
+import { useQuery, UseQueryOptions } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { appConnectionKeys } from "../queries";
+
+export type TAdcsCertificateTemplate = {
+ name: string;
+};
+
+const adcsConnectionKeys = {
+ all: [...appConnectionKeys.all, "adcs"] as const,
+ listTemplates: (connectionId: string) => [...adcsConnectionKeys.all, "templates", connectionId] as const
+};
+
+export const useAdcsConnectionListCertificateTemplates = (
+ connectionId: string,
+ options?: Omit<
+ UseQueryOptions<
+ TAdcsCertificateTemplate[],
+ unknown,
+ TAdcsCertificateTemplate[],
+ ReturnType<typeof adcsConnectionKeys.listTemplates>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: adcsConnectionKeys.listTemplates(connectionId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ templates: TAdcsCertificateTemplate[] }>(
+ `/api/v1/app-connections/adcs/${connectionId}/certificate-templates`
+ );
+
+ return data.templates;
+ },
+ ...options
+ });
+};
diff --git a/frontend/src/hooks/api/appConnections/enums.ts b/frontend/src/hooks/api/appConnections/enums.ts
index 9a35cf11ee..448e7ee9cc 100644
--- a/frontend/src/hooks/api/appConnections/enums.ts
+++ b/frontend/src/hooks/api/appConnections/enums.ts
@@ -8,6 +8,7 @@ export enum AppConnection {
AzureClientSecrets = "azure-client-secrets",
AzureDevOps = "azure-devops",
AzureADCS = "azure-adcs",
+ ADCS = "adcs",
AzureDNS = "azure-dns",
Databricks = "databricks",
Humanitec = "humanitec",
diff --git a/frontend/src/hooks/api/appConnections/types/adcs-connection.ts b/frontend/src/hooks/api/appConnections/types/adcs-connection.ts
new file mode 100644
index 0000000000..b89f81f022
--- /dev/null
+++ b/frontend/src/hooks/api/appConnections/types/adcs-connection.ts
@@ -0,0 +1,21 @@
+import { z } from "zod";
+
+import { AppConnection } from "../enums";
+import { TRootAppConnection } from "./root-connection";
+
+export enum AdcsConnectionMethod {
+ UsernamePassword = "username-password"
+}
+
+export const CreateAdcsConnectionSchema = z.object({
+ caHost: z.string().min(1, "CA Host is required"),
+ username: z.string().min(1, "Username is required"),
+ password: z.string().min(1, "Password is required")
+});
+
+export type TCreateAdcsConnection = z.infer<typeof CreateAdcsConnectionSchema>;
+
+export type TAdcsConnection = TRootAppConnection & { app: AppConnection.ADCS } & {
+ method: AdcsConnectionMethod.UsernamePassword;
+ credentials: TCreateAdcsConnection;
+};
diff --git a/frontend/src/hooks/api/appConnections/types/app-options.ts b/frontend/src/hooks/api/appConnections/types/app-options.ts
index 6541fa1c2e..4b7accd7d2 100644
--- a/frontend/src/hooks/api/appConnections/types/app-options.ts
+++ b/frontend/src/hooks/api/appConnections/types/app-options.ts
@@ -192,6 +192,10 @@ export type TAzureAdCsConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.AzureADCS;
};
+export type TAdcsConnectionOption = TAppConnectionOptionBase & {
+ app: AppConnection.ADCS;
+};
+
export type TRedisConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.Redis;
};
@@ -349,6 +353,7 @@ export type TAppConnectionOption =
| TCircleCISyncConnectionOption
| TCloud66ConnectionOption
| TAzureAdCsConnectionOption
+ | TAdcsConnectionOption
| TLaravelForgeConnectionOption
| TRedisConnectionOption
| TMongoDBConnectionOption
@@ -423,6 +428,7 @@ export type TAppConnectionOptionMap = {
[AppConnection.Okta]: TOktaConnectionOption;
[AppConnection.OpenRouter]: TOpenRouterConnectionOption;
[AppConnection.AzureADCS]: TAzureAdCsConnectionOption;
+ [AppConnection.ADCS]: TAdcsConnectionOption;
[AppConnection.Redis]: TRedisConnectionOption;
[AppConnection.MongoDB]: TMongoDBConnectionOption;
[AppConnection.LaravelForge]: TLaravelForgeConnectionOption;
diff --git a/frontend/src/hooks/api/appConnections/types/index.ts b/frontend/src/hooks/api/appConnections/types/index.ts
index 956de5365d..98e11992fa 100644
--- a/frontend/src/hooks/api/appConnections/types/index.ts
+++ b/frontend/src/hooks/api/appConnections/types/index.ts
@@ -1,5 +1,6 @@
import { AppConnection } from "../enums";
import { TOnePassConnection } from "./1password-connection";
+import { TAdcsConnection } from "./adcs-connection";
import { TAnthropicConnection } from "./anthropic-connection";
import { TAppConnectionOption } from "./app-options";
import { TAuth0Connection } from "./auth0-connection";
@@ -75,6 +76,7 @@ import { TWindmillConnection } from "./windmill-connection";
import { TZabbixConnection } from "./zabbix-connection";
export * from "./1password-connection";
+export * from "./adcs-connection";
export * from "./auth0-connection";
export * from "./aws-connection";
export * from "./azure-adcs-connection";
@@ -155,6 +157,7 @@ export type TAppConnection =
| TAzureClientSecretsConnection
| TAzureDevOpsConnection
| TAzureADCSConnection
+ | TAdcsConnection
| TDatabricksConnection
| THumanitecConnection
| TTerraformCloudConnection
diff --git a/frontend/src/hooks/api/ca/constants.tsx b/frontend/src/hooks/api/ca/constants.tsx
index 271a3cf1c5..ab1717d7fd 100644
--- a/frontend/src/hooks/api/ca/constants.tsx
+++ b/frontend/src/hooks/api/ca/constants.tsx
@@ -40,6 +40,7 @@ export const CA_TYPE_CAPABILITIES_MAP: Record<CaType, CaCapability[]> = {
CaCapability.RENEW_CERTIFICATES
],
[CaType.AZURE_AD_CS]: [CaCapability.ISSUE_CERTIFICATES, CaCapability.RENEW_CERTIFICATES],
+ [CaType.ADCS]: [CaCapability.ISSUE_CERTIFICATES, CaCapability.RENEW_CERTIFICATES],
[CaType.AWS_PCA]: [
CaCapability.ISSUE_CERTIFICATES,
CaCapability.REVOKE_CERTIFICATES,
@@ -65,7 +66,8 @@ export const CA_TYPE_CAPABILITIES_MAP: Record<CaType, CaCapability[]> = {
export const EXTERNAL_CA_TYPE_NAME_MAP: Record<string, string> = {
[CaType.ACME]: "ACME",
- [CaType.AZURE_AD_CS]: "Active Directory Certificate Services (AD CS)",
+ [CaType.AZURE_AD_CS]: "Azure ADCS (Web Enrollment)",
+ [CaType.ADCS]: "ADCS",
[CaType.AWS_PCA]: "AWS Private CA (PCA)",
[CaType.DIGICERT]: "DigiCert CertCentral",
[CaType.AWS_ACM_PUBLIC_CA]: "AWS ACM Public CA",
diff --git a/frontend/src/hooks/api/ca/enums.tsx b/frontend/src/hooks/api/ca/enums.tsx
index 148d47bcbf..ad699f3846 100644
--- a/frontend/src/hooks/api/ca/enums.tsx
+++ b/frontend/src/hooks/api/ca/enums.tsx
@@ -2,6 +2,7 @@ export enum CaType {
INTERNAL = "internal",
ACME = "acme",
AZURE_AD_CS = "azure-ad-cs",
+ ADCS = "adcs",
AWS_PCA = "aws-pca",
DIGICERT = "digicert",
AWS_ACM_PUBLIC_CA = "aws-acm-public-ca",
@@ -47,7 +48,8 @@ export enum CaSigningConfigType {
INTERNAL = "internal",
MANUAL = "manual",
VENAFI = "venafi",
- AZURE_ADCS = "azure-ad-cs"
+ AZURE_ADCS = "azure-ad-cs",
+ ADCS = "adcs"
}
export enum GoDaddyProductType {
diff --git a/frontend/src/hooks/api/ca/index.tsx b/frontend/src/hooks/api/ca/index.tsx
index 51dc824018..61cc1825fb 100644
--- a/frontend/src/hooks/api/ca/index.tsx
+++ b/frontend/src/hooks/api/ca/index.tsx
@@ -19,6 +19,7 @@ export {
useGenerateCaCertificate,
useImportCaCertificate,
useInstallCaCertificateAdcs,
+ useInstallCaCertificateAdcsNative,
useInstallCaCertificateVenafi,
useOrderCertificateWithProfile,
useRenewCa,
@@ -29,6 +30,7 @@ export {
} from "./mutations";
export type { TCaAutoRenewalConfig, TCaSigningConfig } from "./queries";
export {
+ useGetAdcsTemplates,
useGetAzureAdcsTemplates,
useGetCa,
useGetCaAutoRenewal,
diff --git a/frontend/src/hooks/api/ca/mutations.tsx b/frontend/src/hooks/api/ca/mutations.tsx
index e511ae240d..c0e00d3a24 100644
--- a/frontend/src/hooks/api/ca/mutations.tsx
+++ b/frontend/src/hooks/api/ca/mutations.tsx
@@ -219,40 +219,21 @@ export const useRenewCa = () => {
});
};
-export const useInstallCaCertificateVenafi = () => {
- 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: caKeys.getCaById(caId) });
- queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
- queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
- queryClient.invalidateQueries({
- queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL)
- });
- queryClient.invalidateQueries({
- queryKey: caKeys.listCasByProjectId()
- });
- queryClient.invalidateQueries({
- predicate: (query) => query.queryKey.includes("project-cas")
- });
- }
- });
+const invalidateCaInstallQueries = (
+ queryClient: ReturnType<typeof useQueryClient>,
+ caId: string
+) => {
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaAutoRenewal(caId) });
+ queryClient.invalidateQueries({ queryKey: caKeys.getCaSigningConfig(caId) });
+ 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) });
+ queryClient.invalidateQueries({ queryKey: caKeys.listCasByProjectId() });
+ queryClient.invalidateQueries({ predicate: (query) => query.queryKey.includes("project-cas") });
};
-export const useInstallCaCertificateAdcs = () => {
+const useInstallCaCertificate = (endpoint: string) => {
const queryClient = useQueryClient();
return useMutation<
{ message: string; caId: string },
@@ -261,30 +242,22 @@ export const useInstallCaCertificateAdcs = () => {
>({
mutationFn: async ({ caId, ...body }) => {
const { data } = await apiRequest.post<{ message: string; caId: string }>(
- `/api/v1/cert-manager/ca/internal/${caId}/install-certificate-adcs`,
+ `/api/v1/cert-manager/ca/internal/${caId}/${endpoint}`,
body
);
return data;
},
- onSuccess: (_, { caId }) => {
- queryClient.invalidateQueries({ queryKey: caKeys.getCaAutoRenewal(caId) });
- queryClient.invalidateQueries({ queryKey: caKeys.getCaSigningConfig(caId) });
- 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)
- });
- queryClient.invalidateQueries({
- queryKey: caKeys.listCasByProjectId()
- });
- queryClient.invalidateQueries({
- predicate: (query) => query.queryKey.includes("project-cas")
- });
- }
+ onSuccess: (_, { caId }) => invalidateCaInstallQueries(queryClient, caId)
});
};
+export const useInstallCaCertificateVenafi = () =>
+ useInstallCaCertificate("install-certificate-venafi");
+export const useInstallCaCertificateAdcs = () =>
+ useInstallCaCertificate("install-certificate-adcs");
+export const useInstallCaCertificateAdcsNative = () =>
+ useInstallCaCertificate("install-certificate-adcs-native");
+
export const useCreateCaSigningConfig = () => {
const queryClient = useQueryClient();
return useMutation<
diff --git a/frontend/src/hooks/api/ca/queries.tsx b/frontend/src/hooks/api/ca/queries.tsx
index c289354c13..834c2178c8 100644
--- a/frontend/src/hooks/api/ca/queries.tsx
+++ b/frontend/src/hooks/api/ca/queries.tsx
@@ -5,6 +5,7 @@ import { apiRequest } from "@app/config/request";
import { TCertificateTemplate } from "../certificateTemplates/types";
import { CaRenewalStatus, CaSigningConfigType, CaType } from "./enums";
import {
+ TAdcsTemplate,
TAzureAdCsTemplate,
TInternalCertificateAuthority,
TUnifiedCertificateAuthority
@@ -24,6 +25,7 @@ export const caKeys = {
getCaCertTemplates: (caId: string) => [{ caId }, "ca-cert-templates"],
getCaEstConfig: (caId: string) => [{ caId }, "ca-est-config"],
getAzureAdcsTemplates: (caId: string) => [{ caId }, "azure-adcs-templates"],
+ getAdcsTemplates: (caId: string) => [{ caId }, "adcs-templates"],
getCaSigningConfig: (caId: string) => [{ caId }, "ca-signing-config"],
getCaAutoRenewal: (caId: string) => [{ caId }, "ca-auto-renewal"]
};
@@ -82,6 +84,7 @@ export const useListExternalCasByProjectId = () => {
const [
acmeResponse,
azureAdCsResponse,
+ adcsResponse,
awsPcaResponse,
digicertResponse,
awsAcmPublicCaResponse,
@@ -92,6 +95,7 @@ export const useListExternalCasByProjectId = () => {
apiRequest.get<TUnifiedCertificateAuthority[]>(
`/api/v1/cert-manager/ca/${CaType.AZURE_AD_CS}`
),
+ apiRequest.get<TUnifiedCertificateAuthority[]>(`/api/v1/cert-manager/ca/${CaType.ADCS}`),
apiRequest.get<TUnifiedCertificateAuthority[]>(`/api/v1/cert-manager/ca/${CaType.AWS_PCA}`),
apiRequest.get<TUnifiedCertificateAuthority[]>(
`/api/v1/cert-manager/ca/${CaType.DIGICERT}`
@@ -115,6 +119,10 @@ export const useListExternalCasByProjectId = () => {
allCas.push(...azureAdCsResponse.value.data);
}
+ if (adcsResponse.status === "fulfilled") {
+ allCas.push(...adcsResponse.value.data);
+ }
+
if (awsPcaResponse.status === "fulfilled") {
allCas.push(...awsPcaResponse.value.data);
}
@@ -300,3 +308,16 @@ export const useGetAzureAdcsTemplates = ({
enabled: Boolean(caId && isAzureAdcsCa)
});
};
+
+export const useGetAdcsTemplates = ({ caId, isAdcsCa }: { caId: string; isAdcsCa: boolean }) => {
+ return useQuery({
+ queryKey: caKeys.getAdcsTemplates(caId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{
+ templates: TAdcsTemplate[];
+ }>(`/api/v1/cert-manager/ca/adcs/${caId}/templates`);
+ return data;
+ },
+ enabled: Boolean(caId && isAdcsCa)
+ });
+};
diff --git a/frontend/src/hooks/api/ca/types.ts b/frontend/src/hooks/api/ca/types.ts
index ab25b1b239..702118988d 100644
--- a/frontend/src/hooks/api/ca/types.ts
+++ b/frontend/src/hooks/api/ca/types.ts
@@ -41,6 +41,19 @@ export type TAzureAdCsCertificateAuthority = {
};
};
+export type TAdcsCertificateAuthority = {
+ id: string;
+ projectId: string;
+ type: CaType.ADCS;
+ status: CaStatus;
+ name: string;
+ enableDirectIssuance: boolean;
+ configuration: {
+ appConnectionId: string;
+ caName: string;
+ };
+};
+
export type TAwsPcaCertificateAuthority = {
id: string;
projectId: string;
@@ -160,6 +173,7 @@ export const MAX_DISTRIBUTION_POINT_URL_LENGTH = 2048;
export type TUnifiedCertificateAuthority =
| TAcmeCertificateAuthority
| TAzureAdCsCertificateAuthority
+ | TAdcsCertificateAuthority
| TAwsPcaCertificateAuthority
| TDigiCertCertificateAuthority
| TGoDaddyCertificateAuthority
@@ -238,6 +252,11 @@ export type TAzureAdCsTemplate = {
description?: string;
};
+export type TAdcsTemplate = {
+ id: string;
+ name: string;
+};
+
export type TImportCaCertificateDTO = {
caId: string;
certificate: string;
diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.ts
index 4c4005aac3..cefe7771a2 100644
--- a/frontend/src/hooks/api/signers/types.ts
+++ b/frontend/src/hooks/api/signers/types.ts
@@ -4,10 +4,15 @@ export type TGetUserSignerPermissionDTO = {
signerId: string;
};
-export type TSignerExternalConfiguration = {
- caType: CaType.DIGICERT;
- reissueFromExternalOrderId?: string;
-};
+export type TSignerExternalConfiguration =
+ | {
+ caType: CaType.DIGICERT;
+ reissueFromExternalOrderId?: string;
+ }
+ | {
+ caType: CaType.ADCS;
+ template?: string;
+ };
export enum SignerStatus {
Pending = "pending",
@@ -99,6 +104,7 @@ export type TSigner = {
certificateTtlDays?: number | null;
certificateRenewBeforeDays?: number | null;
keyAlgorithm?: SignerKeyAlgorithm | string | null;
+ externalCaConfig?: { caType: CaType.ADCS; template?: string } | null;
lastSignedAt?: string | null;
createdAt: string;
updatedAt: string;
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsx
index a7cd6c05a0..09591a7838 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsx
@@ -47,6 +47,7 @@ import {
TAvailableAppConnection,
useListAvailableAppConnections
} from "@app/hooks/api/appConnections";
+import { useAdcsConnectionListCertificateTemplates } from "@app/hooks/api/appConnections/adcs";
import { useAzureAdcsConnectionListTemplates } from "@app/hooks/api/appConnections/azure-adcs";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import {
@@ -66,7 +67,8 @@ const signingTypeLabels: Record<CaSigningConfigType, string> = {
[CaSigningConfigType.INTERNAL]: "Internal (Infisical CA)",
[CaSigningConfigType.MANUAL]: "Manual",
[CaSigningConfigType.VENAFI]: "Venafi TLS Protect Cloud",
- [CaSigningConfigType.AZURE_ADCS]: "Azure AD CS"
+ [CaSigningConfigType.AZURE_ADCS]: "Azure AD CS (Web Enrollment)",
+ [CaSigningConfigType.ADCS]: "ADCS"
};
const getSigningTypeBadgeVariant = (type: CaSigningConfigType) => {
@@ -88,7 +90,7 @@ const editSchema = z.object({
type EditFormData = z.infer<typeof editSchema>;
-const adcsEditSchema = z.object({
+const azureAdcsEditSchema = z.object({
appConnectionId: z.string().min(1, "App connection is required"),
template: z.string().min(1, "Certificate template is required"),
validityPeriod: z.coerce
@@ -99,7 +101,15 @@ const adcsEditSchema = z.object({
.or(z.literal(""))
});
-type AdcsEditFormData = z.infer<typeof adcsEditSchema>;
+type AzureAdcsEditFormData = z.infer<typeof azureAdcsEditSchema>;
+
+// Native ADCS derives validity from the CA template, so there is no validity period field.
+const nativeAdcsEditSchema = z.object({
+ appConnectionId: z.string().min(1, "App connection is required"),
+ template: z.string().min(1, "Certificate template is required")
+});
+
+type NativeAdcsEditFormData = z.infer<typeof nativeAdcsEditSchema>;
export const CaSigningConfigSection = ({ caId }: Props) => {
const { currentProject } = useProject();
@@ -157,19 +167,19 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
}
);
- const { data: availableAdcsConnections, isPending: isAdcsConnectionsPending } =
+ const { data: availableAzureAdcsConnections, isPending: isAzureAdcsConnectionsPending } =
useListAvailableAppConnections(AppConnection.AzureADCS, currentProject.id, {
enabled: signingConfig?.type === CaSigningConfigType.AZURE_ADCS
});
const {
- control: adcsControl,
- handleSubmit: handleAdcsSubmit,
- reset: adcsReset,
- watch: adcsWatch,
- formState: { isSubmitting: isAdcsSubmitting }
- } = useForm<AdcsEditFormData>({
- resolver: zodResolver(adcsEditSchema),
+ control: azureAdcsControl,
+ handleSubmit: handleAzureAdcsSubmit,
+ reset: azureAdcsReset,
+ watch: azureAdcsWatch,
+ formState: { isSubmitting: isAzureAdcsSubmitting }
+ } = useForm<AzureAdcsEditFormData>({
+ resolver: zodResolver(azureAdcsEditSchema),
values: {
appConnectionId: signingConfig?.appConnectionId ?? "",
template: (signingConfig?.destinationConfig?.template as string) ?? "",
@@ -177,11 +187,37 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
}
});
- const selectedAdcsConnectionId = adcsWatch("appConnectionId");
+ const selectedAzureAdcsConnectionId = azureAdcsWatch("appConnectionId");
+
+ const { data: azureAdcsTemplates = [], isPending: isAzureAdcsTemplatesLoading } =
+ useAzureAdcsConnectionListTemplates(selectedAzureAdcsConnectionId ?? "", {
+ enabled: !!selectedAzureAdcsConnectionId && popUp.editSigningConfig.isOpen
+ });
+
+ const { data: availableNativeAdcsConnections, isPending: isNativeAdcsConnectionsPending } =
+ useListAvailableAppConnections(AppConnection.ADCS, currentProject.id, {
+ enabled: signingConfig?.type === CaSigningConfigType.ADCS
+ });
+
+ const {
+ control: nativeAdcsControl,
+ handleSubmit: handleNativeAdcsSubmit,
+ reset: nativeAdcsReset,
+ watch: nativeAdcsWatch,
+ formState: { isSubmitting: isNativeAdcsSubmitting }
+ } = useForm<NativeAdcsEditFormData>({
+ resolver: zodResolver(nativeAdcsEditSchema),
+ values: {
+ appConnectionId: signingConfig?.appConnectionId ?? "",
+ template: (signingConfig?.destinationConfig?.template as string) ?? ""
+ }
+ });
+
+ const selectedNativeAdcsConnectionId = nativeAdcsWatch("appConnectionId");
- const { data: adcsTemplates = [], isPending: isAdcsTemplatesLoading } =
- useAzureAdcsConnectionListTemplates(selectedAdcsConnectionId ?? "", {
- enabled: !!selectedAdcsConnectionId && popUp.editSigningConfig.isOpen
+ const { data: nativeAdcsTemplates = [], isPending: isNativeAdcsTemplatesLoading } =
+ useAdcsConnectionListCertificateTemplates(selectedNativeAdcsConnectionId ?? "", {
+ enabled: !!selectedNativeAdcsConnectionId && popUp.editSigningConfig.isOpen
});
if (!ca || ca.status === CaStatus.PENDING_CERTIFICATE || !signingConfig) {
@@ -189,7 +225,8 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
}
const isVenafi = signingConfig.type === CaSigningConfigType.VENAFI;
- const isAdcs = signingConfig.type === CaSigningConfigType.AZURE_ADCS;
+ const isAzureAdcs = signingConfig.type === CaSigningConfigType.AZURE_ADCS;
+ const isNativeAdcs = signingConfig.type === CaSigningConfigType.ADCS;
const onEditSubmit = async ({
appConnectionId,
@@ -226,7 +263,7 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
<CardHeader className="border-b">
<CardTitle>Signing Configuration</CardTitle>
<CardDescription>How this CA&apos;s certificate is signed</CardDescription>
- {(isVenafi || isAdcs) && ca?.name && (
+ {(isVenafi || isAzureAdcs || isNativeAdcs) && ca?.name && (
<CardAction>
<ProjectPermissionCan
I={ProjectPermissionCertificateAuthorityActions.Edit}
@@ -282,7 +319,7 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
</>
)}
- {isAdcs && signingConfig.destinationConfig && (
+ {isAzureAdcs && signingConfig.destinationConfig && (
<>
<Detail>
<DetailLabel>Certificate Template</DetailLabel>
@@ -298,22 +335,29 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
)}
</>
)}
+
+ {isNativeAdcs && signingConfig.destinationConfig && (
+ <Detail>
+ <DetailLabel>Certificate Template</DetailLabel>
+ <DetailValue>{signingConfig.destinationConfig.template as string}</DetailValue>
+ </Detail>
+ )}
</DetailGroup>
</CardContent>
</Card>
- {isAdcs && (
+ {isAzureAdcs && (
<Modal
isOpen={popUp.editSigningConfig.isOpen}
onOpenChange={(isOpen) => {
handlePopUpToggle("editSigningConfig", isOpen);
- if (!isOpen) adcsReset();
+ if (!isOpen) azureAdcsReset();
}}
>
<ModalContent title="Edit Signing Configuration" bodyClassName="overflow-visible">
<form
- onSubmit={handleAdcsSubmit(
- async ({ appConnectionId, template, validityPeriod }: AdcsEditFormData) => {
+ onSubmit={handleAzureAdcsSubmit(
+ async ({ appConnectionId, template, validityPeriod }: AzureAdcsEditFormData) => {
try {
await updateSigningConfig({
caId,
@@ -338,7 +382,7 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
)}
>
<Controller
- control={adcsControl}
+ control={azureAdcsControl}
name="appConnectionId"
render={({ field: { onChange, value }, fieldState: { error } }) => (
<FormControl
@@ -348,13 +392,13 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
isRequired
>
<FilterableSelect
- isLoading={isAdcsConnectionsPending}
- value={(availableAdcsConnections || []).find((conn) => conn.id === value)}
+ isLoading={isAzureAdcsConnectionsPending}
+ value={(availableAzureAdcsConnections || []).find((conn) => conn.id === value)}
onChange={(option) => {
const selected = option as SingleValue<TAvailableAppConnection>;
onChange(selected?.id ?? "");
}}
- options={availableAdcsConnections || []}
+ options={availableAzureAdcsConnections || []}
placeholder="Select an Azure AD CS connection..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
@@ -363,7 +407,7 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
)}
/>
<Controller
- control={adcsControl}
+ control={azureAdcsControl}
name="template"
render={({ field: { onChange, value }, fieldState: { error } }) => (
<FormControl
@@ -373,18 +417,18 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
isRequired
>
<FilterableSelect
- isLoading={isAdcsTemplatesLoading && !!selectedAdcsConnectionId}
- isDisabled={!selectedAdcsConnectionId}
+ isLoading={isAzureAdcsTemplatesLoading && !!selectedAzureAdcsConnectionId}
+ isDisabled={!selectedAzureAdcsConnectionId}
value={
- adcsTemplates.find((t) => t === value) ? { label: value, value } : null
+ azureAdcsTemplates.find((t) => t === value) ? { label: value, value } : null
}
onChange={(option) => {
const selected = option as SingleValue<{ label: string; value: string }>;
onChange(selected?.value ?? "");
}}
- options={adcsTemplates.map((t) => ({ label: t, value: t }))}
+ options={azureAdcsTemplates.map((t) => ({ label: t, value: t }))}
placeholder={
- selectedAdcsConnectionId
+ selectedAzureAdcsConnectionId
? "Select a template..."
: "Select a connection first"
}
@@ -395,7 +439,7 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
)}
/>
<Controller
- control={adcsControl}
+ control={azureAdcsControl}
name="validityPeriod"
render={({ field, fieldState: { error } }) => (
<FormControl
@@ -415,8 +459,123 @@ export const CaSigningConfigSection = ({ caId }: Props) => {
</ButtonV2>
</ModalClose>
<ButtonV2
- isLoading={isAdcsSubmitting}
- isDisabled={isAdcsSubmitting}
+ isLoading={isAzureAdcsSubmitting}
+ isDisabled={isAzureAdcsSubmitting}
+ type="submit"
+ colorSchema="secondary"
+ >
+ Save
+ </ButtonV2>
+ </div>
+ </form>
+ </ModalContent>
+ </Modal>
+ )}
+
+ {isNativeAdcs && (
+ <Modal
+ isOpen={popUp.editSigningConfig.isOpen}
+ onOpenChange={(isOpen) => {
+ handlePopUpToggle("editSigningConfig", isOpen);
+ if (!isOpen) nativeAdcsReset();
+ }}
+ >
+ <ModalContent title="Edit Signing Configuration" bodyClassName="overflow-visible">
+ <form
+ onSubmit={handleNativeAdcsSubmit(
+ async ({ appConnectionId, template }: NativeAdcsEditFormData) => {
+ try {
+ await updateSigningConfig({
+ caId,
+ appConnectionId,
+ destinationConfig: {
+ template
+ }
+ });
+ createNotification({
+ text: "Signing configuration updated",
+ type: "success"
+ });
+ handlePopUpToggle("editSigningConfig", false);
+ } catch {
+ createNotification({
+ text: "Failed to update signing configuration",
+ type: "error"
+ });
+ }
+ }
+ )}
+ >
+ <Controller
+ control={nativeAdcsControl}
+ name="appConnectionId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="ADCS Connection"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ >
+ <FilterableSelect
+ isLoading={isNativeAdcsConnectionsPending}
+ value={(availableNativeAdcsConnections || []).find(
+ (conn) => conn.id === value
+ )}
+ onChange={(option) => {
+ const selected = option as SingleValue<TAvailableAppConnection>;
+ onChange(selected?.id ?? "");
+ }}
+ options={availableNativeAdcsConnections || []}
+ placeholder="Select an ADCS connection..."
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={nativeAdcsControl}
+ name="template"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="Certificate Template"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ >
+ <FilterableSelect
+ isLoading={isNativeAdcsTemplatesLoading && !!selectedNativeAdcsConnectionId}
+ isDisabled={!selectedNativeAdcsConnectionId}
+ value={
+ nativeAdcsTemplates.find((t) => t.name === value)
+ ? { label: value, value }
+ : null
+ }
+ onChange={(option) => {
+ const selected = option as SingleValue<{ label: string; value: string }>;
+ onChange(selected?.value ?? "");
+ }}
+ options={nativeAdcsTemplates.map((t) => ({ label: t.name, value: t.name }))}
+ placeholder={
+ selectedNativeAdcsConnectionId
+ ? "Select a template..."
+ : "Select a connection first"
+ }
+ getOptionLabel={(option) => option.label}
+ getOptionValue={(option) => option.value}
+ />
+ </FormControl>
+ )}
+ />
+ <div className="flex w-full justify-between gap-4 pt-4">
+ <ModalClose asChild>
+ <ButtonV2 colorSchema="secondary" variant="plain">
+ Cancel
+ </ButtonV2>
+ </ModalClose>
+ <ButtonV2
+ isLoading={isNativeAdcsSubmitting}
+ isDisabled={isNativeAdcsSubmitting}
type="submit"
colorSchema="secondary"
>
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsNativeCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsNativeCaInstallForm.tsx
new file mode 100644
index 0000000000..833d0d0c24
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsNativeCaInstallForm.tsx
@@ -0,0 +1,233 @@
+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,
+ useInstallCaCertificateAdcsNative,
+ useUpdateCaSigningConfig
+} from "@app/hooks/api";
+import {
+ TAvailableAppConnection,
+ useListAvailableAppConnections
+} from "@app/hooks/api/appConnections";
+import { useAdcsConnectionListCertificateTemplates } from "@app/hooks/api/appConnections/adcs";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { UsePopUpState } from "@app/hooks/usePopUp";
+
+const schema = z.object({
+ appConnectionId: z.string().min(1, "App connection is required"),
+ template: z.string().min(1, "Certificate template is required"),
+ maxPathLength: z.string()
+});
+
+type FormData = z.infer<typeof schema>;
+
+type Props = {
+ caId: string;
+ handlePopUpToggle: (popUpName: keyof UsePopUpState<["installCaCert"]>, state?: boolean) => void;
+};
+
+export const AdcsNativeCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
+ const { currentProject } = useProject();
+
+ const { data: availableAdcsConnections, isPending: isAdcsPending } =
+ useListAvailableAppConnections(AppConnection.ADCS, currentProject.id);
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ watch,
+ formState: { isSubmitting }
+ } = useForm<FormData>({
+ resolver: zodResolver(schema),
+ defaultValues: {
+ maxPathLength: "-1"
+ }
+ });
+
+ const selectedConnectionId = watch("appConnectionId");
+
+ const { data: templates = [], isPending: isTemplatesLoading } =
+ useAdcsConnectionListCertificateTemplates(selectedConnectionId ?? "", {
+ enabled: !!selectedConnectionId
+ });
+
+ const { data: existingSigningConfig } = useGetCaSigningConfig(caId, { enabled: !!caId });
+ const { mutateAsync: createSigningConfig } = useCreateCaSigningConfig();
+ const { mutateAsync: updateSigningConfig } = useUpdateCaSigningConfig();
+ const { mutateAsync: installAdcsNativeCert } = useInstallCaCertificateAdcsNative();
+
+ const onFormSubmit = async ({ appConnectionId, template, maxPathLength }: FormData) => {
+ if (!caId) return;
+
+ try {
+ const destinationConfig = { template };
+
+ if (existingSigningConfig?.type === CaSigningConfigType.ADCS) {
+ await updateSigningConfig({
+ caId,
+ appConnectionId,
+ destinationConfig
+ });
+ } else {
+ await createSigningConfig({
+ caId,
+ type: CaSigningConfigType.ADCS,
+ appConnectionId,
+ destinationConfig
+ });
+ }
+
+ await installAdcsNativeCert({
+ 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 ADCS",
+ type: "error"
+ });
+ }
+ };
+
+ return (
+ <form onSubmit={handleSubmit(onFormSubmit)}>
+ <Controller
+ control={control}
+ name="appConnectionId"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="ADCS Connection"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ >
+ <FilterableSelect
+ isLoading={isAdcsPending}
+ value={(availableAdcsConnections || []).find((conn) => conn.id === value)}
+ onChange={(option) => {
+ const selected = option as SingleValue<TAvailableAppConnection>;
+ onChange(selected?.id ?? "");
+ }}
+ options={availableAdcsConnections || []}
+ placeholder="Select an ADCS connection..."
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="template"
+ render={({ field: { onChange, value, ...field }, fieldState: { error } }) => {
+ if (isTemplatesLoading && !!selectedConnectionId) {
+ return (
+ <FormControl label="Certificate Template" isRequired>
+ <FilterableSelect
+ isLoading
+ isDisabled
+ options={[]}
+ value={null}
+ onChange={() => {}}
+ placeholder="Loading templates..."
+ />
+ </FormControl>
+ );
+ }
+ if (templates.length > 0) {
+ return (
+ <FormControl
+ label="Certificate Template"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ >
+ <FilterableSelect
+ isDisabled={!selectedConnectionId}
+ value={templates.find((t) => t.name === value) ? { label: value, value } : null}
+ onChange={(option) => {
+ const selected = option as SingleValue<{ label: string; value: string }>;
+ onChange(selected?.value ?? "");
+ }}
+ options={templates.map((t) => ({ label: t.name, value: t.name }))}
+ placeholder="Select a template..."
+ getOptionLabel={(option) => option.label}
+ getOptionValue={(option) => option.value}
+ />
+ </FormControl>
+ );
+ }
+ return (
+ <FormControl
+ label="Certificate Template"
+ errorText={error?.message}
+ isError={Boolean(error)}
+ isRequired
+ helperText="Enter the subordinate CA template name (e.g. SubCA)."
+ >
+ <Input {...field} value={value} onChange={onChange} placeholder="SubCA" />
+ </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/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/CaInstallCertModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/CaInstallCertModal.tsx
index ef54d5db42..348d4338a9 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/CaInstallCertModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/CaInstallCertModal.tsx
@@ -12,6 +12,7 @@ import { Badge, Button } from "@app/components/v3";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { AdcsCaInstallForm } from "./AdcsCaInstallForm";
+import { AdcsNativeCaInstallForm } from "./AdcsNativeCaInstallForm";
import { ExternalCaInstallForm } from "./ExternalCaInstallForm";
import { InternalCaInstallForm } from "./InternalCaInstallForm";
import { VenafiCaInstallForm } from "./VenafiCaInstallForm";
@@ -74,9 +75,15 @@ const INTEGRATIONS: TIntegration[] = [
},
{
id: "azure-adcs",
- name: "Azure AD CS",
+ name: "Azure AD CS (Web Enrollment)",
description: "Microsoft Active Directory Certificate Services",
image: "/images/integrations/Microsoft Azure.png"
+ },
+ {
+ id: "adcs",
+ name: "ADCS",
+ description: "Microsoft AD CS (native)",
+ image: "/images/integrations/Microsoft Azure.png"
}
];
@@ -175,6 +182,9 @@ export const CaInstallCertModal = ({ popUp, handlePopUpToggle }: Props) => {
if (selectedIntegration === "azure-adcs") {
return <AdcsCaInstallForm caId={caId} handlePopUpToggle={handlePopUpToggle} />;
}
+ if (selectedIntegration === "adcs") {
+ return <AdcsNativeCaInstallForm caId={caId} handlePopUpToggle={handlePopUpToggle} />;
+ }
if (selectedIntegration === "venafi") {
return <VenafiCaInstallForm caId={caId} handlePopUpToggle={handlePopUpToggle} />;
}
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
index 83fcd09c54..432063727a 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
@@ -120,6 +120,14 @@ const azureAdCsConfigurationSchema = z.object({
})
});
+const adcsConfigurationSchema = z.object({
+ adcsConnection: z.object({
+ id: z.string().min(1, "ADCS Connection is required"),
+ name: z.string()
+ }),
+ caName: z.string().trim().optional()
+});
+
const awsPcaConfigurationSchema = z.object({
awsConnection: z.object({
id: z.string().min(1, "AWS Connection is required"),
@@ -216,6 +224,10 @@ const schema = z.discriminatedUnion("type", [
type: z.literal(CaType.AZURE_AD_CS),
configuration: azureAdCsConfigurationSchema
}),
+ baseSchema.extend({
+ type: z.literal(CaType.ADCS),
+ configuration: adcsConfigurationSchema
+ }),
baseSchema.extend({
type: z.literal(CaType.AWS_PCA),
configuration: awsPcaConfigurationSchema
@@ -247,7 +259,8 @@ type Props = {
const caTypes = [
{ label: "ACME", value: CaType.ACME },
- { label: "Active Directory Certificate Services (AD CS)", value: CaType.AZURE_AD_CS },
+ { label: "Azure ADCS (Web Enrollment)", value: CaType.AZURE_AD_CS },
+ { label: "ADCS", value: CaType.ADCS },
{ label: "AWS Private CA (PCA)", value: CaType.AWS_PCA },
{ label: "AWS ACM Public CA", value: CaType.AWS_ACM_PUBLIC_CA },
{ label: "DigiCert CertCentral", value: CaType.DIGICERT },
@@ -303,6 +316,19 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
}
}
});
+ } else if (initialType === CaType.ADCS) {
+ reset({
+ type: CaType.ADCS,
+ name: "",
+ status: CaStatus.ACTIVE,
+ configuration: {
+ adcsConnection: {
+ id: "",
+ name: ""
+ },
+ caName: ""
+ }
+ });
} else if (initialType === CaType.AWS_PCA) {
reset({
type: CaType.AWS_PCA,
@@ -427,6 +453,11 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
enabled: caType === CaType.AZURE_AD_CS
});
+ const { data: availableAdcsConnections, isPending: isAdcsPending } =
+ useListAvailableAppConnections(AppConnection.ADCS, currentProject.id, {
+ enabled: caType === CaType.ADCS
+ });
+
const { data: availableAwsConnections, isPending: isAwsPending } = useListAvailableAppConnections(
AppConnection.AWS,
currentProject.id,
@@ -454,6 +485,9 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
if (caType === CaType.AZURE_AD_CS) {
return availableAzureConnections || [];
}
+ if (caType === CaType.ADCS) {
+ return availableAdcsConnections || [];
+ }
if (caType === CaType.AWS_PCA || caType === CaType.AWS_ACM_PUBLIC_CA) {
return availableAwsConnections || [];
}
@@ -479,6 +513,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
availableDNSMadeEasyConnections,
availableAzureDNSConnections,
availableAzureConnections,
+ availableAdcsConnections,
availableAwsConnections,
availableDigiCertConnections,
availableVenafiTppConnections,
@@ -491,6 +526,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
isDNSMadeEasyPending ||
isAzureDNSPending ||
(isAzurePending && caType === CaType.AZURE_AD_CS) ||
+ (isAdcsPending && caType === CaType.ADCS) ||
(isAwsPending && (caType === CaType.AWS_PCA || caType === CaType.AWS_ACM_PUBLIC_CA)) ||
(isDigiCertPending && caType === CaType.DIGICERT) ||
(isVenafiTppPending && caType === CaType.VENAFI_TPP) ||
@@ -560,6 +596,23 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
}
}
});
+ } else if (ca.type === CaType.ADCS && availableConnections?.length) {
+ const selectedConnection = availableConnections?.find(
+ (connection) => connection.id === ca.configuration.appConnectionId
+ );
+
+ reset({
+ type: ca.type,
+ name: ca.name,
+ status: ca.status,
+ configuration: {
+ adcsConnection: {
+ id: ca.configuration.appConnectionId,
+ name: selectedConnection?.name || ""
+ },
+ caName: ca.configuration.caName
+ }
+ });
} else if (ca.type === CaType.AWS_PCA && availableConnections?.length) {
const selectedConnection = availableConnections?.find(
(connection) => connection.id === ca.configuration.appConnectionId
@@ -745,6 +798,11 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
configPayload = {
azureAdcsConnectionId: formConfiguration.azureAdcsConnection.id
};
+ } else if (type === CaType.ADCS && "adcsConnection" in formConfiguration) {
+ configPayload = {
+ appConnectionId: formConfiguration.adcsConnection.id,
+ ...(formConfiguration.caName?.trim() ? { caName: formConfiguration.caName.trim() } : {})
+ };
} else if (type === CaType.AWS_PCA && "awsConnection" in formConfiguration) {
configPayload = {
appConnectionId: formConfiguration.awsConnection.id,
@@ -1139,6 +1197,53 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
name="configuration.azureAdcsConnection"
/>
)}
+ {caType === CaType.ADCS && (
+ <>
+ <Controller
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl
+ tooltipText="ADCS App Connection contains the Windows domain credentials and Gateway used to reach the AD CS server."
+ isError={Boolean(error)}
+ errorText={error?.message}
+ label="ADCS Connection"
+ isRequired
+ >
+ <FilterableSelect
+ menuPlacement="top"
+ value={value}
+ onChange={(newValue) => {
+ onChange(newValue);
+ }}
+ isLoading={isPending}
+ options={availableConnections}
+ placeholder="Select connection..."
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ components={{ Option: AppConnectionOption }}
+ />
+ </FormControl>
+ )}
+ control={control}
+ name="configuration.adcsConnection"
+ />
+ <Controller
+ control={control}
+ defaultValue=""
+ name="configuration.caName"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Certificate Authority"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ isOptional
+ tooltipText="The AD CS certificate authority name (the CA's common name), e.g. corp-ca01-CA. Leave blank to discover it automatically from the CA host."
+ >
+ <Input {...field} placeholder="Auto-discovered if left blank" />
+ </FormControl>
+ )}
+ />
+ </>
+ )}
{caType === CaType.AWS_PCA && (
<>
<Controller
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
index 4e7455050c..091e42d2c5 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
@@ -19,7 +19,9 @@ import {
import { ROUTE_PATHS } from "@app/const/routes";
import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";
import { getCaIssuanceCapabilities } from "@app/hooks/api/ca";
+import { CaType } from "@app/hooks/api/ca/enums";
+import { AdcsTemplateField } from "../../../components/AdcsTemplateField";
import { CertificateForm } from "./schemas";
import { CaGroup, CaOption } from "./types";
@@ -59,6 +61,9 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateSt
const reissueOrderId = form.watch("reissueFromExternalOrderId");
const isReissue = Boolean(reissueOrderId);
+ const isAdcs = selectedCa?.caType === CaType.ADCS;
+ const adcsConnectionId = selectedCa?.adcs?.appConnectionId;
+
useEffect(() => {
if (!canReuseOrder && reissueOrderId) {
form.setValue("reissueFromExternalOrderId", null);
@@ -129,6 +134,15 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateSt
)}
/>
+ {isAdcs && (
+ <AdcsTemplateField
+ control={form.control}
+ name="adcsTemplate"
+ connectionId={adcsConnectionId}
+ description="Select a code-signing template published on your CA."
+ />
+ )}
+
{canReuseOrder && (
<Controller
name="reissueFromExternalOrderId"
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
index ddab8a72e8..a011143dbb 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
@@ -84,6 +84,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
if (ca.type === CaType.INTERNAL) return true;
if (ca.type === CaType.AWS_PCA) return true;
if (ca.type === CaType.AZURE_AD_CS) return true;
+ if (ca.type === CaType.ADCS) return true;
if (ca.type === CaType.DIGICERT) {
return ca.configuration?.purpose === DigiCertCaPurpose.CodeSigning;
}
@@ -101,6 +102,10 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
organizationId: ca.configuration.organizationId,
productNameId: ca.configuration.productNameId
}
+ : undefined,
+ adcs:
+ ca.type === CaType.ADCS
+ ? { appConnectionId: ca.configuration.appConnectionId }
: undefined
}));
}, [cas.data]);
@@ -152,7 +157,8 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
keyAlgorithm: state.keyAlgorithm,
keySource: state.keySource,
hsmConnectorId: state.hsmConnectorId,
- reissueFromExternalOrderId: state.reissueFromExternalOrderId
+ reissueFromExternalOrderId: state.reissueFromExternalOrderId,
+ adcsTemplate: state.adcsTemplate
}
});
@@ -178,7 +184,8 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
keyAlgorithm: SignerKeyAlgorithm.RSA_2048,
keySource: CertKeySource.Infisical,
hsmConnectorId: null,
- reissueFromExternalOrderId: null
+ reissueFromExternalOrderId: null,
+ adcsTemplate: ""
});
};
@@ -215,6 +222,20 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
}
: undefined;
+ const selectedCaType = caOptions.find((o) => o.id === state.caId)?.caType;
+ let externalConfiguration;
+ if (state.reissueFromExternalOrderId) {
+ externalConfiguration = {
+ caType: CaType.DIGICERT,
+ reissueFromExternalOrderId: state.reissueFromExternalOrderId
+ } as const;
+ } else if (selectedCaType === CaType.ADCS && state.adcsTemplate.trim()) {
+ externalConfiguration = {
+ caType: CaType.ADCS,
+ template: state.adcsTemplate.trim()
+ } as const;
+ }
+
await createSigner.mutateAsync({
projectId,
name: state.name,
@@ -231,12 +252,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
})),
approvalPolicy,
certificate,
- externalConfiguration: state.reissueFromExternalOrderId
- ? {
- caType: CaType.DIGICERT,
- reissueFromExternalOrderId: state.reissueFromExternalOrderId
- }
- : undefined
+ externalConfiguration
});
handleClose(false);
@@ -263,7 +279,8 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
keyAlgorithm: values.keyAlgorithm,
keySource: values.keySource,
hsmConnectorId: values.hsmConnectorId ?? null,
- reissueFromExternalOrderId: values.reissueFromExternalOrderId ?? null
+ reissueFromExternalOrderId: values.reissueFromExternalOrderId ?? null,
+ adcsTemplate: values.adcsTemplate ?? ""
}));
};
@@ -285,6 +302,13 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
"reissueFromExternalOrderId"
]);
if (!ok) return;
+ if (
+ selectedCa?.caType === CaType.ADCS &&
+ !certificateForm.getValues("adcsTemplate")?.trim()
+ ) {
+ certificateForm.setError("adcsTemplate", { message: "Certificate template is required" });
+ return;
+ }
persistCertificateForm();
setStep(2);
return;
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
index e76734ebed..a56e5c03d7 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
@@ -39,7 +39,9 @@ export const certificateSchema = z
keySource: z.nativeEnum(CertKeySource).default(CertKeySource.Infisical),
hsmConnectorId: z.string().uuid().optional().nullable(),
// DigiCert code signing only: reissue into this existing order instead of placing a new one.
- reissueFromExternalOrderId: z.string().nullable().optional().default(null)
+ reissueFromExternalOrderId: z.string().nullable().optional().default(null),
+ // AD CS only: the certificate template this signer requests when issuing.
+ adcsTemplate: z.string().trim().optional().default("")
})
.refine(
(data) =>
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts
index 0a71bc1627..9bdef1b23f 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts
@@ -10,6 +10,7 @@ export type CaOption = {
groupType: CaGroup;
caType: CaType;
digicert?: { appConnectionId: string; organizationId: number; productNameId: string };
+ adcs?: { appConnectionId: string };
};
export type MemberOption = { value: string; label: string };
@@ -52,6 +53,7 @@ export type WizardState = {
keySource: CertKeySource;
hsmConnectorId: string | null;
reissueFromExternalOrderId: string | null;
+ adcsTemplate: string;
pendingMembers: PendingMember[];
policySteps: PolicyStep[];
maxSignings: number | null;
@@ -69,6 +71,7 @@ export const INITIAL_WIZARD_STATE: WizardState = {
keySource: CertKeySource.Infisical,
hsmConnectorId: null,
reissueFromExternalOrderId: null,
+ adcsTemplate: "",
pendingMembers: [],
policySteps: [],
maxSignings: null,
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
index 4c56ceb2b5..e9559e523d 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState } from "react";
-import { Controller, useForm } from "react-hook-form";
+import { Control, Controller, useForm } from "react-hook-form";
import { SingleValue } from "react-select";
import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
@@ -36,7 +36,11 @@ import {
} from "@app/context/ProjectPermissionContext/types";
import { usePopUp } from "@app/hooks";
import { CaType } from "@app/hooks/api/ca/enums";
-import { useGetAzureAdcsTemplates, useListCasByProjectId } from "@app/hooks/api/ca/queries";
+import {
+ useGetAdcsTemplates,
+ useGetAzureAdcsTemplates,
+ useListCasByProjectId
+} from "@app/hooks/api/ca/queries";
import {
TCertificatePolicy,
useGetCertificatePolicyById,
@@ -212,6 +216,50 @@ const editSchema = z
export type FormData = z.infer<typeof createSchema>;
+type ExternalCaTemplateOption = { id: string; name: string; description?: string };
+
+const ExternalCaTemplateSelect = ({
+ control,
+ templates,
+ valueKey,
+ placeholder
+}: {
+ control: Control<FormData>;
+ templates: ExternalCaTemplateOption[];
+ valueKey: "id" | "name";
+ placeholder: string;
+}) => (
+ <Controller
+ control={control}
+ name="externalConfigs.template"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <FormControl
+ label="Windows ADCS Template"
+ isRequired
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <FilterableSelect
+ value={templates.find((template) => template[valueKey] === value) || null}
+ onChange={(selected) => {
+ const option = Array.isArray(selected) ? selected[0] : selected;
+ onChange(
+ option && typeof option === "object" && valueKey in option
+ ? option[valueKey] || ""
+ : ""
+ );
+ }}
+ getOptionLabel={(template) => template.name}
+ getOptionValue={(template) => template[valueKey]}
+ options={templates}
+ placeholder={placeholder}
+ className="w-full"
+ />
+ </FormControl>
+ )}
+ />
+);
+
// Convert profile defaults from API format to form format
const convertDefaultsToForm = (
defaults: TCertificateProfileDefaults | null | undefined
@@ -546,6 +594,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
// Get the selected CA to check if it's Azure ADCS
const selectedCa = certificateAuthorities.find((ca) => ca.id === watchedCertificateAuthorityId);
const isAzureAdcsCa = selectedCa?.type === CaType.AZURE_AD_CS;
+ const isAdcsCa = selectedCa?.type === CaType.ADCS;
// ACM Public CA issues certificates with a fixed 198-day validity, so pin the TTL default.
const isAwsAcmPublicCa = selectedCa?.type === CaType.AWS_ACM_PUBLIC_CA;
@@ -555,6 +604,11 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
isAzureAdcsCa
});
+ const { data: adcsTemplatesData } = useGetAdcsTemplates({
+ caId: watchedCertificateAuthorityId || "",
+ isAdcsCa
+ });
+
// Reset step to 0 when modal opens/closes
useEffect(() => {
if (isOpen) {
@@ -568,13 +622,15 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
}
}, [isEdit, isClone, profile, reset, allCaData]);
- // Additional effect to reset external configs when Azure ADCS templates are loaded
+ // Re-apply the saved template once the external CA's templates have loaded (edit/clone).
useEffect(() => {
+ const templatesLoaded =
+ (isAzureAdcsCa && azureAdcsTemplatesData?.templates) ||
+ (isAdcsCa && adcsTemplatesData?.templates);
if (
(isEdit || isClone) &&
profile &&
- isAzureAdcsCa &&
- azureAdcsTemplatesData?.templates &&
+ templatesLoaded &&
profile.externalConfigs &&
typeof profile.externalConfigs === "object" &&
profile.externalConfigs !== null &&
@@ -582,7 +638,16 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
) {
setValue("externalConfigs.template", profile.externalConfigs.template);
}
- }, [isEdit, isClone, profile, isAzureAdcsCa, azureAdcsTemplatesData, setValue]);
+ }, [
+ isEdit,
+ isClone,
+ profile,
+ isAzureAdcsCa,
+ isAdcsCa,
+ azureAdcsTemplatesData,
+ adcsTemplatesData,
+ setValue
+ ]);
// Pin TTL to 198 days when the selected CA is AWS ACM Public CA — backend rejects any other value.
// Also re-applies when the user lands on the Defaults tab (policy selected) so the field shows 198
@@ -596,13 +661,10 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
const onFormSubmit = async (data: FormData) => {
if (!currentProject?.id && !isEdit) return;
- // Validate Azure ADCS template requirement
- if (
- isAzureAdcsCa &&
- (!data.externalConfigs?.template || data.externalConfigs.template.trim() === "")
- ) {
+ // Both AD CS variants require a template on the profile's external config.
+ if ((isAzureAdcsCa || isAdcsCa) && !data.externalConfigs?.template?.trim()) {
createNotification({
- text: "Azure ADCS Certificate Authority requires a template to be specified",
+ text: `${isAzureAdcsCa ? "Azure ADCS" : "ADCS"} Certificate Authority requires a template to be specified`,
type: "error"
});
return;
@@ -869,45 +931,21 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
/>
)}
- {/* Azure ADCS Template Selection */}
{isAzureAdcsCa && (
- <Controller
+ <ExternalCaTemplateSelect
control={control}
- name="externalConfigs.template"
- render={({ field: { onChange, value }, fieldState: { error } }) => (
- <FormControl
- label="Windows ADCS Template"
- isRequired
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <FilterableSelect
- value={
- azureAdcsTemplatesData?.templates.find(
- (template) => template.id === value
- ) || null
- }
- onChange={(selectedTemplate) => {
- if (Array.isArray(selectedTemplate)) {
- onChange(selectedTemplate[0]?.id || "");
- } else if (
- selectedTemplate &&
- typeof selectedTemplate === "object" &&
- "id" in selectedTemplate
- ) {
- onChange(selectedTemplate.id || "");
- } else {
- onChange("");
- }
- }}
- getOptionLabel={(template) => template.name}
- getOptionValue={(template) => template.id}
- options={azureAdcsTemplatesData?.templates || []}
- placeholder="Select an Azure ADCS certificate template"
- className="w-full"
- />
- </FormControl>
- )}
+ templates={azureAdcsTemplatesData?.templates || []}
+ valueKey="id"
+ placeholder="Select an Azure ADCS certificate template"
+ />
+ )}
+
+ {isAdcsCa && (
+ <ExternalCaTemplateSelect
+ control={control}
+ templates={adcsTemplatesData?.templates || []}
+ valueKey="name"
+ placeholder="Select an ADCS certificate template"
/>
)}
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx
index 6dbfdb37bb..02408e5f91 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx
@@ -17,7 +17,9 @@ import {
} from "@app/components/v3";
import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";
import { getCaIssuanceCapabilities } from "@app/hooks/api/ca";
+import { CaType } from "@app/hooks/api/ca/enums";
+import { AdcsTemplateField } from "../../../components/AdcsTemplateField";
import { CertificateForm } from "./schemas";
import { CaGroup, CaOption } from "./types";
@@ -52,6 +54,9 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateSt
const reissueOrderId = form.watch("reissueFromExternalOrderId");
const isReissue = Boolean(reissueOrderId);
+ const isAdcs = selectedCa?.caType === CaType.ADCS;
+ const adcsConnectionId = selectedCa?.adcs?.appConnectionId;
+
useEffect(() => {
if (!canReuseOrder && reissueOrderId) {
form.setValue("reissueFromExternalOrderId", null);
@@ -110,6 +115,15 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateSt
)}
/>
+ {isAdcs && (
+ <AdcsTemplateField
+ control={form.control}
+ name="adcsTemplate"
+ connectionId={adcsConnectionId}
+ description="Select a code-signing template published on your CA. Changing it reissues the certificate."
+ />
+ )}
+
{canReuseOrder && (
<Controller
name="reissueFromExternalOrderId"
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx
index c3ad32b821..8eea0dcfbb 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx
@@ -72,6 +72,7 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
if (ca.type === CaType.INTERNAL) return true;
if (ca.type === CaType.AWS_PCA) return true;
if (ca.type === CaType.AZURE_AD_CS) return true;
+ if (ca.type === CaType.ADCS) return true;
if (ca.type === CaType.DIGICERT) {
return ca.configuration?.purpose === DigiCertCaPurpose.CodeSigning;
}
@@ -89,10 +90,17 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
organizationId: ca.configuration.organizationId,
productNameId: ca.configuration.productNameId
}
+ : undefined,
+ adcs:
+ ca.type === CaType.ADCS
+ ? { appConnectionId: ca.configuration.appConnectionId }
: undefined
}));
}, [cas.data]);
+ const signerAdcsTemplate =
+ signer.externalCaConfig?.caType === CaType.ADCS ? (signer.externalCaConfig.template ?? "") : "";
+
const basicsForm = useForm<BasicsForm>({
resolver: zodResolver(basicsSchema),
values: { name: signer.name, description: signer.description ?? "" }
@@ -108,7 +116,8 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
keySource: currentKeySource,
keyAlgorithm: currentKeyAlgorithm,
hsmConnectorId: currentHsmConnectorId,
- reissueFromExternalOrderId: null
+ reissueFromExternalOrderId: null,
+ adcsTemplate: signerAdcsTemplate
}
});
@@ -129,8 +138,10 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
const watchedHsmConnectorId = certificateForm.watch("hsmConnectorId");
const watchedKeyAlgorithm = certificateForm.watch("keyAlgorithm");
const watchedReissueOrderId = certificateForm.watch("reissueFromExternalOrderId");
+ const watchedAdcsTemplate = certificateForm.watch("adcsTemplate");
const selectedCa = caOptions.find((o) => o.id === watchedCaId) ?? null;
+ const isAdcs = selectedCa?.caType === CaType.ADCS;
const { requiresHsm, minRsaKeyBits } = getCaIssuanceCapabilities(selectedCa?.caType);
useEffect(() => {
@@ -149,8 +160,14 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
(watchedHsmConnectorId ?? null) !== currentHsmConnectorId);
const keyAlgorithmChanged = watchedKeyAlgorithm !== currentKeyAlgorithm;
const isReissueFromOrder = Boolean(watchedReissueOrderId);
+ const adcsTemplateChanged = isAdcs && (watchedAdcsTemplate?.trim() ?? "") !== signerAdcsTemplate;
const shouldReissue =
- caSwap || subjectChanged || keySourceChanged || keyAlgorithmChanged || isReissueFromOrder;
+ caSwap ||
+ subjectChanged ||
+ keySourceChanged ||
+ keyAlgorithmChanged ||
+ isReissueFromOrder ||
+ adcsTemplateChanged;
const handleOpenChange = (open: boolean) => {
if (!open) {
@@ -164,13 +181,20 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
keySource: currentKeySource,
keyAlgorithm: currentKeyAlgorithm,
hsmConnectorId: currentHsmConnectorId,
- reissueFromExternalOrderId: null
+ reissueFromExternalOrderId: null,
+ adcsTemplate: signerAdcsTemplate
});
}
onOpenChange(open);
};
const onSave = async () => {
+ if (isAdcs && !certificateForm.getValues("adcsTemplate")?.trim()) {
+ certificateForm.setError("adcsTemplate", { message: "Certificate template is required" });
+ setStep(1);
+ return;
+ }
+
setSubmitting(true);
try {
const basics = basicsForm.getValues();
@@ -200,12 +224,21 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
: undefined
}
: undefined,
- externalConfiguration: cert.reissueFromExternalOrderId
- ? {
- caType: CaType.DIGICERT,
+ externalConfiguration: (() => {
+ if (cert.reissueFromExternalOrderId) {
+ return {
+ caType: CaType.DIGICERT as const,
reissueFromExternalOrderId: cert.reissueFromExternalOrderId
- }
- : undefined
+ };
+ }
+ if (isAdcs) {
+ return {
+ caType: CaType.ADCS as const,
+ template: cert.adcsTemplate?.trim() || undefined
+ };
+ }
+ return undefined;
+ })()
});
}
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts
index 4690cc3230..b3497907e2 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts
@@ -39,7 +39,9 @@ export const certificateSchema = z
keyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048),
hsmConnectorId: z.string().uuid().optional().nullable(),
// DigiCert code signing only: reissue into this existing order instead of placing a new one.
- reissueFromExternalOrderId: z.string().nullable().optional().default(null)
+ reissueFromExternalOrderId: z.string().nullable().optional().default(null),
+ // AD CS only: the certificate template this signer requests when issuing.
+ adcsTemplate: z.string().trim().optional().default("")
})
.refine(
(data) =>
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.ts
index 1179b09201..4414d31dce 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.ts
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.ts
@@ -9,6 +9,7 @@ export type CaOption = {
groupType: CaGroup;
caType: CaType;
digicert?: { appConnectionId: string; organizationId: number; productNameId: string };
+ adcs?: { appConnectionId: string };
};
export type StepConfig = {
diff --git a/frontend/src/pages/cert-manager/components/AdcsTemplateField.tsx b/frontend/src/pages/cert-manager/components/AdcsTemplateField.tsx
new file mode 100644
index 0000000000..b5fd276abd
--- /dev/null
+++ b/frontend/src/pages/cert-manager/components/AdcsTemplateField.tsx
@@ -0,0 +1,104 @@
+import { Control, Controller, FieldValues, Path } from "react-hook-form";
+import { InfoIcon } from "lucide-react";
+
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ FilterableSelect,
+ Input,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { useAdcsConnectionListCertificateTemplates } from "@app/hooks/api/appConnections/adcs";
+
+type Props<T extends FieldValues> = {
+ control: Control<T>;
+ name: Path<T>;
+ connectionId: string | undefined;
+ description: string;
+};
+
+export const AdcsTemplateField = <T extends FieldValues>({
+ control,
+ name,
+ connectionId,
+ description
+}: Props<T>) => {
+ const { data: templates = [], isLoading } = useAdcsConnectionListCertificateTemplates(connectionId ?? "", {
+ enabled: Boolean(connectionId)
+ });
+ const options = templates.map((t) => ({ value: t.name, label: t.name }));
+ type Option = (typeof options)[number];
+
+ return (
+ <Controller
+ control={control}
+ name={name}
+ render={({ field, fieldState: { error } }) => {
+ let templateControl: JSX.Element;
+ if (isLoading && connectionId) {
+ templateControl = (
+ <FilterableSelect
+ isLoading
+ isDisabled
+ options={[]}
+ value={null}
+ onChange={() => {}}
+ placeholder="Loading templates..."
+ />
+ );
+ } else if (options.length > 0) {
+ templateControl = (
+ <FilterableSelect<Option>
+ isClearable
+ options={options}
+ value={options.find((o) => o.value === field.value) ?? null}
+ onChange={(selected) => field.onChange((selected as Option | null)?.value ?? "")}
+ getOptionLabel={(o) => o.label}
+ getOptionValue={(o) => o.value}
+ placeholder="Select a template..."
+ isError={Boolean(error)}
+ />
+ );
+ } else {
+ templateControl = (
+ <Input
+ value={typeof field.value === "string" ? field.value : ""}
+ onChange={field.onChange}
+ placeholder="e.g. CodeSigning"
+ isError={Boolean(error)}
+ />
+ );
+ }
+
+ return (
+ <Field>
+ <FieldLabel>
+ <span className="inline-flex items-center gap-1.5">
+ Certificate Template <span className="text-danger">*</span>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="h-3.5 w-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ The AD CS template this signer requests. Use a code-signing template published
+ on your CA.
+ </TooltipContent>
+ </Tooltip>
+ </span>
+ </FieldLabel>
+ <FieldContent>
+ {templateControl}
+ <FieldDescription>{description}</FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ );
+ }}
+ />
+ );
+};
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AdcsConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AdcsConnectionForm.tsx
new file mode 100644
index 0000000000..dc0a75053e
--- /dev/null
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AdcsConnectionForm.tsx
@@ -0,0 +1,238 @@
+import { Controller, FormProvider, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Info } from "lucide-react";
+import { z } from "zod";
+
+import { OrgPermissionCan } from "@app/components/permissions";
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input,
+ SecretInput,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";
+import { OrgPermissionSubjects, useSubscription } from "@app/context";
+import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";
+import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import { AdcsConnectionMethod, TAdcsConnection } from "@app/hooks/api/appConnections";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+
+import { AppConnectionFormFooter } from "./AppConnectionFormFooter";
+import {
+ genericAppConnectionFieldsSchema,
+ GenericAppConnectionsFields
+} from "./GenericAppConnectionFields";
+
+type Props = {
+ appConnection?: TAdcsConnection;
+ onSubmit: (formData: FormData) => Promise<void>;
+};
+
+const rootSchema = genericAppConnectionFieldsSchema.extend({
+ app: z.literal(AppConnection.ADCS)
+});
+
+const formSchema = z
+ .discriminatedUnion("method", [
+ rootSchema.extend({
+ method: z.literal(AdcsConnectionMethod.UsernamePassword),
+ credentials: z.object({
+ caHost: z.string().trim().min(1, "CA Host required"),
+ username: z.string().trim().min(1, "Username required"),
+ password: z.string().trim().min(1, "Password required")
+ })
+ })
+ ])
+ .superRefine((data, ctx) => {
+ if (!data.gatewayId) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Gateway required",
+ path: ["gatewayId"]
+ });
+ }
+ });
+
+type FormData = z.infer<typeof formSchema>;
+
+export const AdcsConnectionForm = ({ appConnection, onSubmit }: Props) => {
+ const isUpdate = Boolean(appConnection);
+
+ const form = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: appConnection ?? {
+ app: AppConnection.ADCS,
+ method: AdcsConnectionMethod.UsernamePassword,
+ gatewayId: null,
+ gatewayPoolId: null,
+ credentials: {
+ caHost: "",
+ username: "",
+ password: ""
+ }
+ }
+ });
+
+ const { handleSubmit, control, setValue, watch } = form;
+
+ const gatewayId = watch("gatewayId");
+ const gatewayPoolId = watch("gatewayPoolId");
+ const { subscription } = useSubscription();
+
+ return (
+ <FormProvider {...form}>
+ <form onSubmit={handleSubmit(onSubmit)}>
+ {!isUpdate && <GenericAppConnectionsFields />}
+ <Controller
+ name="method"
+ control={control}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>
+ Method
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm">
+ {`The method you would like to use to connect with ${
+ APP_CONNECTION_MAP[AppConnection.ADCS].name
+ }. This field cannot be changed after creation.`}
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <Select disabled={isUpdate} value={value} onValueChange={(val) => onChange(val)}>
+ <SelectTrigger className="w-full" isError={Boolean(error)}>
+ <SelectValue placeholder="Select a method..." />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {Object.values(AdcsConnectionMethod).map((method) => {
+ return (
+ <SelectItem value={method} key={method}>
+ {getAppConnectionMethodDetails(method).name}
+ </SelectItem>
+ );
+ })}
+ </SelectContent>
+ </Select>
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ {subscription.gateway && (
+ <OrgPermissionCan
+ I={OrgGatewayPermissionActions.AttachGateways}
+ a={OrgPermissionSubjects.Gateway}
+ >
+ {(isAllowed) => (
+ <Controller
+ name="gatewayId"
+ control={control}
+ render={({ fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>Gateway</FieldLabel>
+ {isAllowed ? (
+ <GatewayPicker
+ isDisabled={!isAllowed}
+ value={{
+ gatewayId: gatewayId ?? null,
+ gatewayPoolId: gatewayPoolId ?? null
+ }}
+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {
+ setValue("gatewayId", newGwId, { shouldDirty: true });
+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });
+ }}
+ />
+ ) : (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <GatewayPicker
+ isDisabled={!isAllowed}
+ value={{
+ gatewayId: gatewayId ?? null,
+ gatewayPoolId: gatewayPoolId ?? null
+ }}
+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {
+ setValue("gatewayId", newGwId, { shouldDirty: true });
+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });
+ }}
+ />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ Restricted access. You don&apos;t have permission to attach gateways to
+ resources.
+ </TooltipContent>
+ </Tooltip>
+ )}
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ )}
+ </OrgPermissionCan>
+ )}
+ <Controller
+ name="credentials.caHost"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel htmlFor="ca-host">CA Host</FieldLabel>
+ <Input
+ id="ca-host"
+ {...field}
+ placeholder="ca01.corp.example.com"
+ isError={Boolean(error?.message)}
+ />
+ <FieldDescription>The CA server&apos;s DNS name, not a URL</FieldDescription>
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ <div className="grid grid-cols-2 gap-2">
+ <Controller
+ name="credentials.username"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel htmlFor="username">Username</FieldLabel>
+ <Input
+ id="username"
+ {...field}
+ placeholder="DOMAIN\\username or [email protected]"
+ isError={Boolean(error?.message)}
+ />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ <Controller
+ name="credentials.password"
+ control={control}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel htmlFor="password">Password</FieldLabel>
+ <SecretInput value={value} onChange={(e) => onChange(e.target.value)} />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ </div>
+ <AppConnectionFormFooter
+ submitLabel={isUpdate ? "Update Credentials" : "Connect to ADCS"}
+ />
+ </form>
+ </FormProvider>
+ );
+};
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 5476e5e78c..0332d8c65e 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
@@ -15,6 +15,7 @@ import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { DiscriminativePick } from "@app/types";
import { OnePassConnectionForm } from "./1PasswordConnectionForm";
+import { AdcsConnectionForm } from "./AdcsConnectionForm";
import { AnthropicConnectionForm } from "./AnthropicConnectionForm";
import { AppConnectionFormProvider } from "./AppConnectionFormContext";
import { Auth0ConnectionForm } from "./Auth0ConnectionForm";
@@ -201,6 +202,8 @@ const CreateForm = ({ app, onComplete, projectId }: CreateFormProps) => {
return <AzureAppConfigurationConnectionForm onSubmit={onSubmit} projectId={projectId} />;
case AppConnection.AzureADCS:
return <AzureADCSConnectionForm onSubmit={onSubmit} />;
+ case AppConnection.ADCS:
+ return <AdcsConnectionForm onSubmit={onSubmit} />;
case AppConnection.Databricks:
return <DatabricksConnectionForm onSubmit={onSubmit} />;
case AppConnection.Humanitec:
@@ -434,6 +437,8 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {
);
case AppConnection.AzureADCS:
return <AzureADCSConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;
+ case AppConnection.ADCS:
+ return <AdcsConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;
case AppConnection.Databricks:
return <DatabricksConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.Humanitec: