Added Microsoft ADCS connector

This commit is contained in:
Carlos Monastyrski
2025-08-27 02:45:46 -03:00
parent 5c21ac3182
commit 4e2592960d
79 changed files with 3500 additions and 514 deletions
@@ -0,0 +1,12 @@
export enum AzureAdCsTemplateType {
WEB_SERVER = "WebServer",
COMPUTER = "Computer",
USER = "User",
DOMAIN_CONTROLLER = "DomainController",
SUBORDINATE_CA = "SubordinateCA"
}
export enum AzureAdCsAuthMethod {
CLIENT_CERTIFICATE = "client-certificate",
KERBEROS = "kerberos"
}
@@ -0,0 +1,35 @@
import { z } from "zod";
import { CaType } from "../certificate-authority-enums";
import {
BaseCertificateAuthoritySchema,
GenericCreateCertificateAuthorityFieldsSchema,
GenericUpdateCertificateAuthorityFieldsSchema
} from "../certificate-authority-schemas";
export const AzureAdCsCertificateAuthorityConfigurationSchema = z.object({
azureAdcsConnectionId: z.string().uuid().trim().describe("Azure ADCS Connection ID")
});
export const AzureAdCsCertificateAuthorityCredentialsSchema = z.object({
clientId: z.string(),
clientSecret: z.string().optional(),
certificateThumbprint: z.string().optional()
});
export const AzureAdCsCertificateAuthoritySchema = BaseCertificateAuthoritySchema.extend({
type: z.literal(CaType.AZURE_AD_CS),
configuration: AzureAdCsCertificateAuthorityConfigurationSchema
});
export const CreateAzureAdCsCertificateAuthoritySchema = GenericCreateCertificateAuthorityFieldsSchema(
CaType.AZURE_AD_CS
).extend({
configuration: AzureAdCsCertificateAuthorityConfigurationSchema
});
export const UpdateAzureAdCsCertificateAuthoritySchema = GenericUpdateCertificateAuthorityFieldsSchema(
CaType.AZURE_AD_CS
).extend({
configuration: AzureAdCsCertificateAuthorityConfigurationSchema.optional()
});
@@ -0,0 +1,15 @@
import { z } from "zod";
import {
AzureAdCsCertificateAuthoritySchema,
CreateAzureAdCsCertificateAuthoritySchema,
UpdateAzureAdCsCertificateAuthoritySchema
} from "./azure-ad-cs-certificate-authority-schemas";
export type TAzureAdCsCertificateAuthority = z.infer<typeof AzureAdCsCertificateAuthoritySchema>;
export type TAzureAdCsCertificateAuthorityInput = z.infer<typeof CreateAzureAdCsCertificateAuthoritySchema>;
export type TCreateAzureAdCsCertificateAuthorityDTO = z.infer<typeof CreateAzureAdCsCertificateAuthoritySchema>;
export type TUpdateAzureAdCsCertificateAuthorityDTO = z.infer<typeof UpdateAzureAdCsCertificateAuthoritySchema>;
@@ -1,6 +1,7 @@
export enum CaType {
INTERNAL = "internal",
ACME = "acme"
ACME = "acme",
AZURE_AD_CS = "azure-ad-cs"
}
export enum InternalCaType {
@@ -17,3 +18,9 @@ export enum CaStatus {
export enum CaRenewalType {
EXISTING = "existing"
}
export enum CaCapability {
ISSUE_CERTIFICATES = "issue-certificates",
REVOKE_CERTIFICATES = "revoke-certificates",
RENEW_CERTIFICATES = "renew-certificates"
}
@@ -1,6 +1,33 @@
import { CaType } from "./certificate-authority-enums";
import { CaCapability, CaType } from "./certificate-authority-enums";
export const CERTIFICATE_AUTHORITIES_TYPE_MAP: Record<CaType, string> = {
[CaType.INTERNAL]: "Internal",
[CaType.ACME]: "ACME"
[CaType.ACME]: "ACME",
[CaType.AZURE_AD_CS]: "Azure AD Certificate Service"
};
export const CERTIFICATE_AUTHORITIES_CAPABILITIES_MAP: Record<CaType, CaCapability[]> = {
[CaType.INTERNAL]: [
CaCapability.ISSUE_CERTIFICATES,
CaCapability.REVOKE_CERTIFICATES,
CaCapability.RENEW_CERTIFICATES
],
[CaType.ACME]: [
CaCapability.ISSUE_CERTIFICATES,
CaCapability.REVOKE_CERTIFICATES,
CaCapability.RENEW_CERTIFICATES
],
[CaType.AZURE_AD_CS]: [
CaCapability.ISSUE_CERTIFICATES,
CaCapability.RENEW_CERTIFICATES
// Note: REVOKE_CERTIFICATES intentionally omitted - not supported by ADCS connector
]
};
/**
* Check if a certificate authority type supports a specific capability
*/
export const caSupportsCapability = (caType: CaType, capability: CaCapability): boolean => {
const capabilities = CERTIFICATE_AUTHORITIES_CAPABILITIES_MAP[caType] || [];
return capabilities.includes(capability);
};
@@ -21,6 +21,7 @@ import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-
import { TPkiSubscriberDALFactory } from "../pki-subscriber/pki-subscriber-dal";
import { SubscriberOperationStatus } from "../pki-subscriber/pki-subscriber-types";
import { AcmeCertificateAuthorityFns } from "./acme/acme-certificate-authority-fns";
import { AzureAdCsCertificateAuthorityFns } from "./azure-ad-cs/azure-ad-cs-certificate-authority-fns";
import { TCertificateAuthorityDALFactory } from "./certificate-authority-dal";
import { CaType } from "./certificate-authority-enums";
import { keyAlgorithmToAlgCfg } from "./certificate-authority-fns";
@@ -33,7 +34,7 @@ import {
type TCertificateAuthorityQueueFactoryDep = {
certificateAuthorityDAL: TCertificateAuthorityDALFactory;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
keyStore: Pick<TKeyStoreFactory, "acquireLock" | "setItemWithExpiry" | "getItem">;
@@ -82,6 +83,19 @@ export const certificateAuthorityQueueFactory = ({
projectDAL
});
const azureAdCsFns = AzureAdCsCertificateAuthorityFns({
appConnectionDAL,
appConnectionService,
certificateAuthorityDAL,
externalCertificateAuthorityDAL,
certificateDAL,
certificateBodyDAL,
certificateSecretDAL,
kmsService,
pkiSubscriberDAL,
projectDAL
});
// TODO 1: auto-periodic rotation
// TODO 2: manual rotation
@@ -158,6 +172,13 @@ export const certificateAuthorityQueueFactory = ({
lastOperationMessage: "Certificate ordered successfully",
lastOperationAt: new Date()
});
} else if (caType === CaType.AZURE_AD_CS) {
await azureAdCsFns.orderSubscriberCertificate(subscriberId);
await pkiSubscriberDAL.updateById(subscriberId, {
lastOperationStatus: SubscriberOperationStatus.SUCCESS,
lastOperationMessage: "Certificate ordered successfully",
lastOperationAt: new Date()
});
}
} catch (e: unknown) {
if (e instanceof Error) {
@@ -2,7 +2,11 @@ import { ForbiddenError } from "@casl/ability";
import { ActionProjectType, TableName } from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import {
ProjectPermissionActions,
ProjectPermissionCertificateActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { OrgServiceActor } from "@app/lib/types";
@@ -22,6 +26,14 @@ import {
TCreateAcmeCertificateAuthorityDTO,
TUpdateAcmeCertificateAuthorityDTO
} from "./acme/acme-certificate-authority-types";
import {
AzureAdCsCertificateAuthorityFns,
castDbEntryToAzureAdCsCertificateAuthority
} from "./azure-ad-cs/azure-ad-cs-certificate-authority-fns";
import {
TCreateAzureAdCsCertificateAuthorityDTO,
TUpdateAzureAdCsCertificateAuthorityDTO
} from "./azure-ad-cs/azure-ad-cs-certificate-authority-types";
import { TCertificateAuthorityDALFactory } from "./certificate-authority-dal";
import { CaType } from "./certificate-authority-enums";
import {
@@ -34,7 +46,7 @@ import { TInternalCertificateAuthorityServiceFactory } from "./internal/internal
import { TCreateInternalCertificateAuthorityDTO } from "./internal/internal-certificate-authority-types";
type TCertificateAuthorityServiceFactoryDep = {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
certificateAuthorityDAL: Pick<
TCertificateAuthorityDALFactory,
@@ -91,6 +103,19 @@ export const certificateAuthorityServiceFactory = ({
projectDAL
});
const azureAdCsFns = AzureAdCsCertificateAuthorityFns({
appConnectionDAL,
appConnectionService,
certificateAuthorityDAL,
externalCertificateAuthorityDAL,
certificateDAL,
certificateBodyDAL,
certificateSecretDAL,
kmsService,
pkiSubscriberDAL,
projectDAL
});
const createCertificateAuthority = async (
{ type, projectId, name, enableDirectIssuance, configuration, status }: TCreateCertificateAuthorityDTO,
actor: OrgServiceActor
@@ -146,6 +171,17 @@ export const certificateAuthorityServiceFactory = ({
});
}
if (type === CaType.AZURE_AD_CS) {
return azureAdCsFns.createCertificateAuthority({
name,
projectId,
configuration: configuration as TCreateAzureAdCsCertificateAuthorityDTO["configuration"],
enableDirectIssuance,
status,
actor
});
}
throw new BadRequestError({ message: "Invalid certificate authority type" });
};
@@ -205,6 +241,10 @@ export const certificateAuthorityServiceFactory = ({
return castDbEntryToAcmeCertificateAuthority(certificateAuthority);
}
if (type === CaType.AZURE_AD_CS) {
return castDbEntryToAzureAdCsCertificateAuthority(certificateAuthority);
}
throw new BadRequestError({ message: "Invalid certificate authority type" });
};
@@ -249,6 +289,10 @@ export const certificateAuthorityServiceFactory = ({
return acmeFns.listCertificateAuthorities({ projectId });
}
if (type === CaType.AZURE_AD_CS) {
return azureAdCsFns.listCertificateAuthorities({ projectId });
}
throw new BadRequestError({ message: "Invalid certificate authority type" });
};
@@ -323,6 +367,17 @@ export const certificateAuthorityServiceFactory = ({
});
}
if (type === CaType.AZURE_AD_CS) {
return azureAdCsFns.updateCertificateAuthority({
id: certificateAuthority.id,
configuration: configuration as TUpdateAzureAdCsCertificateAuthorityDTO["configuration"],
enableDirectIssuance,
actor,
status,
name
});
}
throw new BadRequestError({ message: "Invalid certificate authority type" });
};
@@ -384,14 +439,98 @@ export const certificateAuthorityServiceFactory = ({
return castDbEntryToAcmeCertificateAuthority(certificateAuthority);
}
if (type === CaType.AZURE_AD_CS) {
return castDbEntryToAzureAdCsCertificateAuthority(certificateAuthority);
}
throw new BadRequestError({ message: "Invalid certificate authority type" });
};
const orderSubscriberCertificate = async (subscriberId: string, actor: OrgServiceActor) => {
const subscriber = await pkiSubscriberDAL.findById(subscriberId);
if (!subscriber.caId) {
throw new BadRequestError({ message: "Subscriber does not have a CA" });
}
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(subscriber.caId);
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
actorId: actor.id,
projectId: ca.projectId,
actorAuthMethod: actor.authMethod,
actorOrgId: actor.orgId,
actionProjectType: ActionProjectType.CertificateManager
});
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionCertificateActions.Create,
ProjectPermissionSub.Certificates
);
if (!ca.externalCa && !ca.internalCa) {
throw new BadRequestError({ message: "Certificate authority configuration not found" });
}
if (ca.externalCa?.type === CaType.ACME) {
return acmeFns.orderSubscriberCertificate(subscriberId);
}
if (ca.externalCa?.type === CaType.AZURE_AD_CS) {
return azureAdCsFns.orderSubscriberCertificate(subscriberId);
}
if (ca.internalCa) {
// Handle internal CA certificate ordering - this would need to be implemented
throw new BadRequestError({ message: "Internal CA certificate ordering not yet supported" });
}
throw new BadRequestError({ message: "Unsupported certificate authority type" });
};
const getAzureAdcsTemplates = async ({
caId,
projectId,
actor,
actorId,
actorAuthMethod,
actorOrgId
}: {
caId: string;
projectId: string;
actor: OrgServiceActor["type"];
actorId: string;
actorAuthMethod: OrgServiceActor["authMethod"];
actorOrgId?: string;
}) => {
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
});
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionCertificateActions.Read,
ProjectPermissionSub.Certificates
);
return azureAdCsFns.getTemplates({
caId,
projectId
});
};
return {
createCertificateAuthority,
findCertificateAuthorityByNameAndProjectId,
listCertificateAuthoritiesByProjectId,
updateCertificateAuthority,
deleteCertificateAuthority
deleteCertificateAuthority,
orderSubscriberCertificate,
getAzureAdcsTemplates
};
};
@@ -1,13 +1,23 @@
import { TAcmeCertificateAuthority, TAcmeCertificateAuthorityInput } from "./acme/acme-certificate-authority-types";
import {
TAzureAdCsCertificateAuthority,
TAzureAdCsCertificateAuthorityInput
} from "./azure-ad-cs/azure-ad-cs-certificate-authority-types";
import { CaType } from "./certificate-authority-enums";
import {
TInternalCertificateAuthority,
TInternalCertificateAuthorityInput
} from "./internal/internal-certificate-authority-types";
export type TCertificateAuthority = TInternalCertificateAuthority | TAcmeCertificateAuthority;
export type TCertificateAuthority =
| TInternalCertificateAuthority
| TAcmeCertificateAuthority
| TAzureAdCsCertificateAuthority;
export type TCertificateAuthorityInput = TInternalCertificateAuthorityInput | TAcmeCertificateAuthorityInput;
export type TCertificateAuthorityInput =
| TInternalCertificateAuthorityInput
| TAcmeCertificateAuthorityInput
| TAzureAdCsCertificateAuthorityInput;
export type TCreateCertificateAuthorityDTO = Omit<TCertificateAuthority, "id">;
@@ -8,6 +8,8 @@ import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
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";
@@ -19,9 +21,12 @@ import {
TAltNameMapping
} from "@app/services/certificate/certificate-types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TPkiSubscriberDALFactory } from "@app/services/pki-subscriber/pki-subscriber-dal";
import { TPkiSubscriberProperties } from "@app/services/pki-subscriber/pki-subscriber-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { AzureAdCsCertificateAuthorityFns } from "../azure-ad-cs/azure-ad-cs-certificate-authority-fns";
import { TCertificateAuthorityCertDALFactory } from "../certificate-authority-cert-dal";
import { TCertificateAuthorityDALFactory } from "../certificate-authority-dal";
import { CaStatus } from "../certificate-authority-enums";
@@ -33,18 +38,102 @@ import {
} from "../certificate-authority-fns";
import { TCertificateAuthoritySecretDALFactory } from "../certificate-authority-secret-dal";
import { validateAndMapAltNameType } from "../certificate-authority-validators";
import { TExternalCertificateAuthorityDALFactory } from "../external-certificate-authority-dal";
import { TIssueCertWithTemplateDTO } from "./internal-certificate-authority-types";
type TInternalCertificateAuthorityFnsDeps = {
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa" | "findById">;
certificateAuthorityDAL: Pick<
TCertificateAuthorityDALFactory,
"findByIdWithAssociatedCa" | "findById" | "create" | "transaction" | "updateById" | "findWithAssociatedCa"
>;
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
certificateAuthorityCrlDAL: Pick<TCertificateAuthorityCrlDALFactory, "findOne">;
projectDAL: Pick<TProjectDALFactory, "findById" | "transaction" | "findOne" | "updateById">;
kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "encryptWithKmsKey" | "generateKmsKey">;
kmsService: Pick<
TKmsServiceFactory,
"decryptWithKmsKey" | "encryptWithKmsKey" | "generateKmsKey" | "createCipherPairWithDataKey"
>;
certificateDAL: Pick<TCertificateDALFactory, "create" | "transaction">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
appConnectionDAL?: Pick<TAppConnectionDALFactory, "findById" | "updateById">;
appConnectionService?: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
externalCertificateAuthorityDAL?: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
pkiSubscriberDAL?: Pick<TPkiSubscriberDALFactory, "findById">;
};
const buildSubjectDN = (commonName: string, properties?: TPkiSubscriberProperties): string => {
// Validate and sanitize common name - it's required and cannot be empty
if (!commonName || !commonName.trim()) {
throw new BadRequestError({ message: "Common Name is required and cannot be empty" });
}
const sanitizedCN = commonName.trim().replace(/[,=+<>#;\\]/g, ""); // Remove problematic characters
if (!sanitizedCN) {
throw new BadRequestError({ message: "Common Name contains only invalid characters" });
}
let subject = `CN=${sanitizedCN}`;
// Helper function to validate and sanitize DN component values
const sanitizeComponent = (value: string | undefined): string | null => {
if (!value || typeof value !== "string") return null;
const trimmed = value.trim();
if (!trimmed) return null;
// Remove problematic characters for DN components
const sanitized = trimmed.replace(/[,=+<>#;\\"/\r\n\t]/g, "").trim();
// Additional validation to prevent empty components
if (sanitized.length === 0) return null;
// Ensure the component doesn't start or end with spaces or problematic chars
const finalSanitized = sanitized.replace(/^[\s-_.]+|[\s-_.]+$/g, "");
return finalSanitized.length > 0 ? finalSanitized : null;
};
// Build DN components in proper X.500 ordering
const emailAddress = sanitizeComponent(properties?.emailAddress);
if (emailAddress) {
// Enhanced email validation for DN usage
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (emailRegex.test(emailAddress) && emailAddress.length > 5 && emailAddress.length < 64) {
subject += `,E=${emailAddress}`;
}
}
const organizationalUnit = sanitizeComponent(properties?.organizationalUnit);
if (organizationalUnit && organizationalUnit.length <= 64) {
subject += `,OU=${organizationalUnit}`;
}
const organization = sanitizeComponent(properties?.organization);
if (organization && organization.length <= 64) {
subject += `,O=${organization}`;
}
const locality = sanitizeComponent(properties?.locality);
if (locality && locality.length <= 64) {
subject += `,L=${locality}`;
}
const state = sanitizeComponent(properties?.state);
if (state && state.length <= 64) {
subject += `,ST=${state}`;
}
const country = sanitizeComponent(properties?.country);
if (country) {
// Country code must be exactly 2 uppercase letters
const countryCode = country.toUpperCase().replace(/[^A-Z]/g, "");
if (countryCode.length === 2) {
subject += `,C=${countryCode}`;
}
}
return subject;
};
export const InternalCertificateAuthorityFns = ({
@@ -56,7 +145,11 @@ export const InternalCertificateAuthorityFns = ({
certificateAuthorityCrlDAL,
certificateDAL,
certificateBodyDAL,
certificateSecretDAL
certificateSecretDAL,
appConnectionDAL,
appConnectionService,
externalCertificateAuthorityDAL,
pkiSubscriberDAL
}: TInternalCertificateAuthorityFnsDeps) => {
const issueCertificate = async (
subscriber: TPkiSubscribers,
@@ -102,7 +195,7 @@ export const InternalCertificateAuthorityFns = ({
const leafKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
name: `CN=${subscriber.commonName}`,
name: buildSubjectDN(subscriber.commonName, subscriber.properties as TPkiSubscriberProperties | undefined),
keys: leafKeys,
signingAlgorithm: alg,
extensions: [
@@ -518,8 +611,30 @@ export const InternalCertificateAuthorityFns = ({
};
};
const issueCertificateWithAzureAdCs = async (subscriberId: string) => {
if (!appConnectionDAL || !appConnectionService || !externalCertificateAuthorityDAL || !pkiSubscriberDAL) {
throw new BadRequestError({ message: "Azure AD CS dependencies not available" });
}
const azureAdCsFns = AzureAdCsCertificateAuthorityFns({
appConnectionDAL,
appConnectionService,
certificateAuthorityDAL,
externalCertificateAuthorityDAL,
certificateDAL,
certificateBodyDAL,
certificateSecretDAL,
kmsService,
projectDAL,
pkiSubscriberDAL
});
return azureAdCsFns.orderSubscriberCertificate(subscriberId);
};
return {
issueCertificate,
issueCertificateWithTemplate
issueCertificateWithTemplate,
issueCertificateWithAzureAdCs
};
};