Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Add SCEP enrollment method
Carlos Monastyrskifc4101743f2c
diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex 4770131c43..0d0af1d3c4 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -56,6 +56,8 @@"@opentelemetry/resources": "^1.28.0","@opentelemetry/sdk-metrics": "^1.28.0","@opentelemetry/semantic-conventions": "^1.27.0",+ "@peculiar/asn1-cms": "^2.6.1",+ "@peculiar/asn1-pkcs9": "^2.6.1","@peculiar/asn1-schema": "^2.3.8","@peculiar/x509": "^1.12.1","@react-email/components": "^1.0.1",@@ -16236,14 +16238,14 @@}},"node_modules/@peculiar/asn1-cms": {- "version": "2.6.0",- "resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.6.0.tgz",- "integrity": "sha512-2uZqP+ggSncESeUF/9Su8rWqGclEfEiz1SyU02WX5fUONFfkjzS2Z/F1Li0ofSmf4JqYXIOdCAZqIXAIBAT1OA==",+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.6.1.tgz",+ "integrity": "sha512-vdG4fBF6Lkirkcl53q6eOdn3XYKt+kJTG59edgRZORlg/3atWWEReRCx5rYE1ZzTTX6vLK5zDMjHh7vbrcXGtw==","license": "MIT","dependencies": {"@peculiar/asn1-schema": "^2.6.0",- "@peculiar/asn1-x509": "^2.6.0",- "@peculiar/asn1-x509-attr": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.1",+ "@peculiar/asn1-x509-attr": "^2.6.1","asn1js": "^3.0.6","tslib": "^2.8.1"}@@ -16273,55 +16275,55 @@}},"node_modules/@peculiar/asn1-pfx": {- "version": "2.6.0",- "resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.6.0.tgz",- "integrity": "sha512-rtUvtf+tyKGgokHHmZzeUojRZJYPxoD/jaN1+VAB4kKR7tXrnDCA/RAWXAIhMJJC+7W27IIRGe9djvxKgsldCQ==",+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.6.1.tgz",+ "integrity": "sha512-nB5jVQy3MAAWvq0KY0R2JUZG8bO/bTLpnwyOzXyEh/e54ynGTatAR+csOnXkkVD9AFZ2uL8Z7EV918+qB1qDvw==","license": "MIT","dependencies": {- "@peculiar/asn1-cms": "^2.6.0",- "@peculiar/asn1-pkcs8": "^2.6.0",- "@peculiar/asn1-rsa": "^2.6.0",+ "@peculiar/asn1-cms": "^2.6.1",+ "@peculiar/asn1-pkcs8": "^2.6.1",+ "@peculiar/asn1-rsa": "^2.6.1","@peculiar/asn1-schema": "^2.6.0","asn1js": "^3.0.6","tslib": "^2.8.1"}},"node_modules/@peculiar/asn1-pkcs8": {- "version": "2.6.0",- "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.6.0.tgz",- "integrity": "sha512-KyQ4D8G/NrS7Fw3XCJrngxmjwO/3htnA0lL9gDICvEQ+GJ+EPFqldcJQTwPIdvx98Tua+WjkdKHSC0/Km7T+lA==",+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.6.1.tgz",+ "integrity": "sha512-JB5iQ9Izn5yGMw3ZG4Nw3Xn/hb/G38GYF3lf7WmJb8JZUydhVGEjK/ZlFSWhnlB7K/4oqEs8HnfFIKklhR58Tw==","license": "MIT","dependencies": {"@peculiar/asn1-schema": "^2.6.0",- "@peculiar/asn1-x509": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.1","asn1js": "^3.0.6","tslib": "^2.8.1"}},"node_modules/@peculiar/asn1-pkcs9": {- "version": "2.6.0",- "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.6.0.tgz",- "integrity": "sha512-b78OQ6OciW0aqZxdzliXGYHASeCvvw5caqidbpQRYW2mBtXIX2WhofNXTEe7NyxTb0P6J62kAAWLwn0HuMF1Fw==",+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.6.1.tgz",+ "integrity": "sha512-5EV8nZoMSxeWmcxWmmcolg22ojZRgJg+Y9MX2fnE2bGRo5KQLqV5IL9kdSQDZxlHz95tHvIq9F//bvL1OeNILw==","license": "MIT","dependencies": {- "@peculiar/asn1-cms": "^2.6.0",- "@peculiar/asn1-pfx": "^2.6.0",- "@peculiar/asn1-pkcs8": "^2.6.0",+ "@peculiar/asn1-cms": "^2.6.1",+ "@peculiar/asn1-pfx": "^2.6.1",+ "@peculiar/asn1-pkcs8": "^2.6.1","@peculiar/asn1-schema": "^2.6.0",- "@peculiar/asn1-x509": "^2.6.0",- "@peculiar/asn1-x509-attr": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.1",+ "@peculiar/asn1-x509-attr": "^2.6.1","asn1js": "^3.0.6","tslib": "^2.8.1"}},"node_modules/@peculiar/asn1-rsa": {- "version": "2.6.0",- "resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.6.0.tgz",- "integrity": "sha512-Nu4C19tsrTsCp9fDrH+sdcOKoVfdfoQQ7S3VqjJU6vedR7tY3RLkQ5oguOIB3zFW33USDUuYZnPEQYySlgha4w==",+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.6.1.tgz",+ "integrity": "sha512-1nVMEh46SElUt5CB3RUTV4EG/z7iYc7EoaDY5ECwganibQPkZ/Y2eMsTKB/LeyrUJ+W/tKoD9WUqIy8vB+CEdA==","license": "MIT","dependencies": {"@peculiar/asn1-schema": "^2.6.0",- "@peculiar/asn1-x509": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.1","asn1js": "^3.0.6","tslib": "^2.8.1"}@@ -16338,9 +16340,9 @@}},"node_modules/@peculiar/asn1-x509": {- "version": "2.6.0",- "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.6.0.tgz",- "integrity": "sha512-uzYbPEpoQiBoTq0/+jZtpM6Gq6zADBx+JNFP3yqRgziWBxQ/Dt/HcuvRfm9zJTPdRcBqPNdaRHTVwpyiq6iNMA==",+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.6.1.tgz",+ "integrity": "sha512-O9jT5F1A2+t3r7C4VT7LYGXqkGLK7Kj1xFpz7U0isPrubwU5PbDoyYtx6MiGst29yq7pXN5vZbQFKRCP+lLZlA==","license": "MIT","dependencies": {"@peculiar/asn1-schema": "^2.6.0",@@ -16350,13 +16352,13 @@}},"node_modules/@peculiar/asn1-x509-attr": {- "version": "2.6.0",- "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.6.0.tgz",- "integrity": "sha512-MuIAXFX3/dc8gmoZBkwJWxUWOSvG4MMDntXhrOZpJVMkYX+MYc/rUAU2uJOved9iJEoiUx7//3D8oG83a78UJA==",+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.6.1.tgz",+ "integrity": "sha512-tlW6cxoHwgcQghnJwv3YS+9OO1737zgPogZ+CgWRUK4roEwIPzRH4JEiG770xe5HX2ATfCpmX60gurfWIF9dcQ==","license": "MIT","dependencies": {"@peculiar/asn1-schema": "^2.6.0",- "@peculiar/asn1-x509": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.1","asn1js": "^3.0.6","tslib": "^2.8.1"}diff --git a/backend/package.json b/backend/package.jsonindex bdbb38781e..becce563c4 100644--- a/backend/package.json+++ b/backend/package.json@@ -114,18 +114,18 @@"eslint-plugin-simple-import-sort": "^10.0.0","nock": "^14.0.10","nodemon": "^3.0.2",+ "ora": "^7.0.1","pino-pretty": "^10.2.3","prompt-sync": "^4.2.0","react-email": "^5.0.6","rimraf": "^5.0.5",+ "ts-node": "^10.9.2","tsc-alias": "^1.8.8",+ "tsconfig-paths": "^4.2.0","tsup": "^8.5.0","tsx": "^4.4.0","typescript": "^5.3.2",- "vitest": "^3.0.6",- "ora": "^7.0.1",- "ts-node": "^10.9.2",- "tsconfig-paths": "^4.2.0"+ "vitest": "^3.0.6"},"dependencies": {"@aws-sdk/client-acm-pca": "^3.992.0",@@ -135,7 +135,6 @@"@aws-sdk/client-route-53": "^3.810.0","@aws-sdk/client-secrets-manager": "^3.504.0","@aws-sdk/client-sts": "^3.600.0",- "aws-sdk": "^2.1553.0","@casl/ability": "^6.5.0","@clickhouse/client": "^1.17.0","@elastic/elasticsearch": "^9.1.1",@@ -176,6 +175,8 @@"@opentelemetry/resources": "^1.28.0","@opentelemetry/sdk-metrics": "^1.28.0","@opentelemetry/semantic-conventions": "^1.27.0",+ "@peculiar/asn1-cms": "^2.6.1",+ "@peculiar/asn1-pkcs9": "^2.6.1","@peculiar/asn1-schema": "^2.3.8","@peculiar/x509": "^1.12.1","@react-email/components": "^1.0.1",@@ -188,7 +189,9 @@"@ucast/mongo2js": "^1.3.4","acme-client": "^5.4.0","ajv": "^8.12.0",+ "asn1js": "^3.0.6","argon2": "^0.31.2",+ "aws-sdk": "^2.1553.0","axios": "^1.12.0","axios-ntlm": "^1.4.4","axios-retry": "^4.0.0",diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 0235cffe4b..032b1f7500 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -39,6 +39,7 @@ import { TPitServiceFactory } from "@app/ee/services/pit/pit-service";import { TPkiAcmeServiceFactory } from "@app/ee/services/pki-acme/pki-acme-types";import { TPkiDiscoveryServiceFactory } from "@app/ee/services/pki-discovery/pki-discovery-service";import { TPkiInstallationServiceFactory } from "@app/ee/services/pki-discovery/pki-installation-service";+import { TPkiScepServiceFactory } from "@app/ee/services/pki-scep/pki-scep-service";import { TProjectEventsService } from "@app/ee/services/project-events/project-events-service";import { TProjectEventsSSEService } from "@app/ee/services/project-events/project-events-sse-service";import { TProjectTemplateServiceFactory } from "@app/ee/services/project-template/project-template-types";@@ -322,6 +323,7 @@ declare module "fastify" {certificateAuthorityCrl: TCertificateAuthorityCrlServiceFactory;certificateEst: TCertificateEstServiceFactory;pkiAcme: TPkiAcmeServiceFactory;+ pkiScep: TPkiScepServiceFactory;certificateEstV3: TCertificateEstV3ServiceFactory;pkiCollection: TPkiCollectionServiceFactory;pkiSubscriber: TPkiSubscriberServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 298c82c54f..925a0b05e8 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -368,6 +368,12 @@ import {TPkiEstEnrollmentConfigs,TPkiEstEnrollmentConfigsInsert,TPkiEstEnrollmentConfigsUpdate,+ TPkiScepEnrollmentConfigs,+ TPkiScepEnrollmentConfigsInsert,+ TPkiScepEnrollmentConfigsUpdate,+ TPkiScepTransactions,+ TPkiScepTransactionsInsert,+ TPkiScepTransactionsUpdate,TPkiSigners,TPkiSignersInsert,TPkiSignersUpdate,@@ -847,6 +853,16 @@ declare module "knex/types/tables" {TPkiEstEnrollmentConfigsInsert,TPkiEstEnrollmentConfigsUpdate>;+ [TableName.PkiScepEnrollmentConfig]: KnexOriginal.CompositeTableType<+ TPkiScepEnrollmentConfigs,+ TPkiScepEnrollmentConfigsInsert,+ TPkiScepEnrollmentConfigsUpdate+ >;+ [TableName.PkiScepTransaction]: KnexOriginal.CompositeTableType<+ TPkiScepTransactions,+ TPkiScepTransactionsInsert,+ TPkiScepTransactionsUpdate+ >;[TableName.PkiApiEnrollmentConfig]: KnexOriginal.CompositeTableType<TPkiApiEnrollmentConfigs,TPkiApiEnrollmentConfigsInsert,diff --git a/backend/src/db/migrations/20260325201236_add-scep-enrollment.ts b/backend/src/db/migrations/20260325201236_add-scep-enrollment.tsnew file mode 100644index 0000000000..7fae4266b8--- /dev/null+++ b/backend/src/db/migrations/20260325201236_add-scep-enrollment.ts@@ -0,0 +1,99 @@+import { Knex } from "knex";++import { dropConstraintIfExists } from "@app/db/migrations/utils/dropConstraintIfExists";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++const ENROLLMENT_TYPE_CHECK_CONSTRAINT = "pki_certificate_profiles_enrollment_type_check";+const SCEP_TRANSACTION_UNIQUE_INDEX = "pki_scep_transactions_profile_id_transaction_id_unique";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.PkiScepEnrollmentConfig))) {+ await knex.schema.createTable(TableName.PkiScepEnrollmentConfig, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.binary("encryptedRaPrivateKey").notNullable();+ t.text("raCertificate").notNullable();+ t.timestamp("raCertExpiresAt").notNullable();+ t.text("hashedChallengePassword").notNullable();+ t.boolean("includeCaCertInResponse").notNullable().defaultTo(true);+ t.boolean("allowCertBasedRenewal").notNullable().defaultTo(true);+ t.timestamps(true, true, true);+ });++ await createOnUpdateTrigger(knex, TableName.PkiScepEnrollmentConfig);+ }++ if (!(await knex.schema.hasTable(TableName.PkiScepTransaction))) {+ await knex.schema.createTable(TableName.PkiScepTransaction, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("profileId").notNullable();+ t.foreign("profileId").references("id").inTable(TableName.PkiCertificateProfile).onDelete("CASCADE");++ t.string("transactionId", 256).notNullable();+ t.binary("senderNonce").notNullable();+ t.binary("signerCertDer").notNullable();++ t.uuid("certificateRequestId").nullable();+ t.index("certificateRequestId");++ t.timestamp("expiresAt").notNullable();+ t.index("expiresAt");++ t.timestamps(true, true, true);++ t.unique(["profileId", "transactionId"], { indexName: SCEP_TRANSACTION_UNIQUE_INDEX });+ });++ await createOnUpdateTrigger(knex, TableName.PkiScepTransaction);+ }++ if (!(await knex.schema.hasColumn(TableName.PkiCertificateProfile, "scepConfigId"))) {+ await knex.schema.alterTable(TableName.PkiCertificateProfile, (t) => {+ t.uuid("scepConfigId");+ t.foreign("scepConfigId").references("id").inTable(TableName.PkiScepEnrollmentConfig).onDelete("SET NULL");+ t.index("scepConfigId");+ });+ }++ await dropConstraintIfExists(TableName.PkiCertificateProfile, ENROLLMENT_TYPE_CHECK_CONSTRAINT, knex);+ if (await knex.schema.hasColumn(TableName.PkiCertificateProfile, "enrollmentType")) {+ await knex.schema.alterTable(TableName.PkiCertificateProfile, (t) => {+ t.string("enrollmentType")+ .notNullable()+ .checkIn(["api", "est", "acme", "scep"], ENROLLMENT_TYPE_CHECK_CONSTRAINT)+ .alter();+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.PkiScepTransaction)) {+ await knex.schema.dropTable(TableName.PkiScepTransaction);+ await dropOnUpdateTrigger(knex, TableName.PkiScepTransaction);+ }++ await dropConstraintIfExists(TableName.PkiCertificateProfile, ENROLLMENT_TYPE_CHECK_CONSTRAINT, knex);+ if (await knex.schema.hasColumn(TableName.PkiCertificateProfile, "enrollmentType")) {+ await knex.schema.alterTable(TableName.PkiCertificateProfile, (t) => {+ t.string("enrollmentType")+ .notNullable()+ .checkIn(["api", "est", "acme"], ENROLLMENT_TYPE_CHECK_CONSTRAINT)+ .alter();+ });+ }++ if (await knex.schema.hasColumn(TableName.PkiCertificateProfile, "scepConfigId")) {+ await knex.schema.alterTable(TableName.PkiCertificateProfile, (t) => {+ t.dropForeign(["scepConfigId"]);+ t.dropIndex("scepConfigId");+ t.dropColumn("scepConfigId");+ });+ }++ if (await knex.schema.hasTable(TableName.PkiScepEnrollmentConfig)) {+ await knex.schema.dropTable(TableName.PkiScepEnrollmentConfig);+ await dropOnUpdateTrigger(knex, TableName.PkiScepEnrollmentConfig);+ }+}diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex df2f8d59ed..734bd084e4 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -143,6 +143,8 @@ export * from "./pki-discovery-configs";export * from "./pki-discovery-installations";export * from "./pki-discovery-scan-history";export * from "./pki-est-enrollment-configs";+export * from "./pki-scep-enrollment-configs";+export * from "./pki-scep-transactions";export * from "./pki-signers";export * from "./pki-signing-operations";export * from "./pki-subscribers";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 159d9cb462..5e85b8992e 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -30,6 +30,8 @@ export enum TableName {PkiEstEnrollmentConfig = "pki_est_enrollment_configs",PkiApiEnrollmentConfig = "pki_api_enrollment_configs",PkiAcmeEnrollmentConfig = "pki_acme_enrollment_configs",+ PkiScepEnrollmentConfig = "pki_scep_enrollment_configs",+ PkiScepTransaction = "pki_scep_transactions",PkiSubscriber = "pki_subscribers",PkiAlert = "pki_alerts",PkiAlertsV2 = "pki_alerts_v2",diff --git a/backend/src/db/schemas/pki-certificate-profiles.ts b/backend/src/db/schemas/pki-certificate-profiles.tsindex 7923b346ef..6595f396a4 100644--- a/backend/src/db/schemas/pki-certificate-profiles.ts+++ b/backend/src/db/schemas/pki-certificate-profiles.ts@@ -20,6 +20,7 @@ export const PkiCertificateProfilesSchema = z.object({createdAt: z.date(),updatedAt: z.date(),acmeConfigId: z.string().uuid().nullable().optional(),+ scepConfigId: z.string().uuid().nullable().optional(),issuerType: z.string().default("ca"),externalConfigs: z.string().nullable().optional(),defaults: z.unknown().nullable().optional()diff --git a/backend/src/db/schemas/pki-scep-enrollment-configs.ts b/backend/src/db/schemas/pki-scep-enrollment-configs.tsnew file mode 100644index 0000000000..22dd50fd39--- /dev/null+++ b/backend/src/db/schemas/pki-scep-enrollment-configs.ts@@ -0,0 +1,28 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const PkiScepEnrollmentConfigsSchema = z.object({+ id: z.string().uuid(),+ encryptedRaPrivateKey: zodBuffer,+ raCertificate: z.string(),+ raCertExpiresAt: z.date(),+ hashedChallengePassword: z.string(),+ includeCaCertInResponse: z.boolean().default(true),+ allowCertBasedRenewal: z.boolean().default(true),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TPkiScepEnrollmentConfigs = z.infer<typeof PkiScepEnrollmentConfigsSchema>;+export type TPkiScepEnrollmentConfigsInsert = Omit<z.input<typeof PkiScepEnrollmentConfigsSchema>, TImmutableDBKeys>;+export type TPkiScepEnrollmentConfigsUpdate = Partial<+ Omit<z.input<typeof PkiScepEnrollmentConfigsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/pki-scep-transactions.ts b/backend/src/db/schemas/pki-scep-transactions.tsnew file mode 100644index 0000000000..623cd57844--- /dev/null+++ b/backend/src/db/schemas/pki-scep-transactions.ts@@ -0,0 +1,26 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const PkiScepTransactionsSchema = z.object({+ id: z.string().uuid(),+ profileId: z.string().uuid(),+ transactionId: z.string(),+ senderNonce: zodBuffer,+ signerCertDer: zodBuffer,+ certificateRequestId: z.string().uuid().nullable().optional(),+ expiresAt: z.date(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TPkiScepTransactions = z.infer<typeof PkiScepTransactionsSchema>;+export type TPkiScepTransactionsInsert = Omit<z.input<typeof PkiScepTransactionsSchema>, TImmutableDBKeys>;+export type TPkiScepTransactionsUpdate = Partial<Omit<z.input<typeof PkiScepTransactionsSchema>, TImmutableDBKeys>>;diff --git a/backend/src/ee/routes/scep/pki-scep-router.ts b/backend/src/ee/routes/scep/pki-scep-router.tsnew file mode 100644index 0000000000..e68b6e6dfe--- /dev/null+++ b/backend/src/ee/routes/scep/pki-scep-router.ts@@ -0,0 +1,116 @@+import { z } from "zod";++import { BadRequestError } from "@app/lib/errors";+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";++const MAX_SCEP_MESSAGE_SIZE = 64 * 1024; // 64KB++export const registerPkiScepRouter = async (server: FastifyZodProvider) => {+ const bufferParser = (_req: unknown, body: Buffer, done: (err: null, result: Buffer) => void) => {+ done(null, body);+ };+ const parserOpts = { parseAs: "buffer" as const, bodyLimit: MAX_SCEP_MESSAGE_SIZE };++ server.addContentTypeParser("application/x-pki-message", parserOpts, bufferParser);+ server.addContentTypeParser("application/octet-stream", parserOpts, bufferParser);++ // SCEP clients may send POST without a Content-Type header — normalize before body parsing+ server.addHook("onRequest", async (req) => {+ if (+ req.method === "POST" &&+ (!req.headers["content-type"] || req.headers["content-type"] === "application/octet-stream")+ ) {+ // eslint-disable-next-line no-param-reassign+ req.headers["content-type"] = "application/x-pki-message";+ }+ });++ server.route({+ method: "GET",+ url: "/:profileId/pkiclient.exe",+ config: {+ rateLimit: readLimit+ },+ schema: {+ params: z.object({+ profileId: z.string().uuid()+ }),+ querystring: z.object({+ operation: z.string(),+ message: z.string().optional()+ })+ },+ handler: async (req, res) => {+ const { profileId } = req.params;+ const { operation, message: messageBase64 } = req.query;++ switch (operation) {+ case "GetCACaps": {+ const caps = await server.services.pkiScep.getCaCaps({ profileId });+ void res.header("Content-Type", "text/plain");+ return caps;+ }++ case "GetCACert": {+ const certBundle = await server.services.pkiScep.getCaCert({ profileId });+ void res.header("Content-Type", "application/x-x509-ca-ra-cert");+ return res.send(certBundle);+ }++ case "PKIOperation": {+ if (!messageBase64) {+ throw new BadRequestError({ message: "Missing message parameter for PKIOperation" });+ }+ const messageBuffer = Buffer.from(messageBase64, "base64");+ const clientIp = req.ip || "unknown";++ const response = await server.services.pkiScep.handlePkiOperation({+ profileId,+ message: messageBuffer,+ clientIp+ });++ void res.header("Content-Type", "application/x-pki-message");+ return res.send(response);+ }++ default:+ throw new BadRequestError({ message: `Unsupported SCEP operation: ${operation}` });+ }+ }+ });++ server.route({+ method: "POST",+ url: "/:profileId/pkiclient.exe",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ params: z.object({+ profileId: z.string().uuid()+ }),+ querystring: z.object({+ operation: z.string().optional()+ })+ },+ handler: async (req, res) => {+ const { profileId } = req.params;+ const clientIp = req.ip || "unknown";+ const body = req.body as Buffer;++ if (!body || body.length === 0) {+ throw new BadRequestError({ message: "Empty PKIOperation request body" });+ }++ const response = await server.services.pkiScep.handlePkiOperation({+ profileId,+ message: body,+ clientIp+ });++ void res.header("Content-Type", "application/x-pki-message");+ return res.send(response);+ }+ });+};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex a2e5310b83..4f0708c188 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -87,7 +87,8 @@ export type TCreateAuditLogDTO = {| KmipClientActor| AcmeProfileActor| AcmeAccountActor- | EstAccountActor;+ | EstAccountActor+ | ScepAccountActor;orgId?: string;projectId?: string;} & BaseAuthData;@@ -696,7 +697,9 @@ export enum EventType {GET_PKI_SIGNERS = "get-pki-signers",GET_PKI_SIGNER_PUBLIC_KEY = "get-pki-signer-public-key",GET_PKI_SIGNING_OPERATIONS = "get-pki-signing-operations",- PKI_SIGNER_SIGN = "pki-signer-sign"+ PKI_SIGNER_SIGN = "pki-signer-sign",+ SCEP_ENROLLMENT = "scep-enrollment",+ SCEP_RENEWAL = "scep-renewal"}// Maps each actor type to the JSONB key that holds the actor's primary ID in actorMetadata.@@ -710,7 +713,8 @@ export const ACTOR_TYPE_TO_METADATA_ID_KEY: Partial<Record<ActorType, string>> =[ActorType.SERVICE]: "serviceId",[ActorType.ACME_PROFILE]: "profileId",[ActorType.ACME_ACCOUNT]: "accountId",- [ActorType.EST_ACCOUNT]: "profileId"+ [ActorType.EST_ACCOUNT]: "profileId",+ [ActorType.SCEP_ACCOUNT]: "profileId"};export const filterableSecretEvents: EventType[] = [@@ -768,6 +772,10 @@ interface EstAccountActorMetadata {profileId: string;}+interface ScepAccountActorMetadata {+ profileId: string;+}+interface UnknownUserActorMetadata {}export interface UserActor {@@ -819,6 +827,10 @@ export interface EstAccountActor {type: ActorType.EST_ACCOUNT;metadata: EstAccountActorMetadata;}+export interface ScepAccountActor {+ type: ActorType.SCEP_ACCOUNT;+ metadata: ScepAccountActorMetadata;+}export type Actor =| UserActor| ServiceActor@@ -828,7 +840,8 @@ export type Actor =| KmipClientActor| AcmeProfileActor| AcmeAccountActor- | EstAccountActor;+ | EstAccountActor+ | ScepAccountActor;interface GetSecretsEvent {type: EventType.GET_SECRETS;@@ -5470,6 +5483,38 @@ interface ListDynamicSecretLeasesEvent {};}+interface ScepEnrollmentEvent {+ type: EventType.SCEP_ENROLLMENT;+ metadata: {+ profileId: string;+ profileSlug: string;+ transactionId: string;+ csrSubject: string;+ challengeType: "static";+ status: "success" | "pending" | "failure";+ failReason?: string;+ issuedCertificateId?: string;+ issuedSerialNumber?: string;+ clientIp: string;+ };+}++interface ScepRenewalEvent {+ type: EventType.SCEP_RENEWAL;+ metadata: {+ profileId: string;+ profileSlug: string;+ transactionId: string;+ csrSubject: string;+ existingCertificateSerial?: string;+ status: "success" | "pending" | "failure";+ failReason?: string;+ issuedCertificateId?: string;+ issuedSerialNumber?: string;+ clientIp: string;+ };+}+export type Event =| CreateSubOrganizationEvent| UpdateSubOrganizationEvent@@ -5966,4 +6011,6 @@ export type Event =| RenewDynamicSecretLeaseEvent| GetDynamicSecretLeaseEvent| UpdateCertificateCleanupConfigEvent- | CertificateCleanupCompletedEvent;+ | CertificateCleanupCompletedEvent+ | ScepEnrollmentEvent+ | ScepRenewalEvent;diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.tsindex e94f89113d..f3b8e7ea33 100644--- a/backend/src/ee/services/license/license-fns.ts+++ b/backend/src/ee/services/license/license-fns.ts@@ -100,6 +100,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({},pkiEst: false,pkiAcme: false,+ pkiScep: true,enforceMfa: false,projectTemplates: false,kmip: false,diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.tsindex 10f2dab406..940da9b683 100644--- a/backend/src/ee/services/license/license-types.ts+++ b/backend/src/ee/services/license/license-types.ts@@ -79,6 +79,7 @@ export type TFeatureSet = {};pkiEst: boolean;pkiAcme: false;+ pkiScep: boolean;enforceMfa: boolean;projectTemplates: false;kmip: false;diff --git a/backend/src/ee/services/pki-scep/pki-scep-attributes.ts b/backend/src/ee/services/pki-scep/pki-scep-attributes.tsnew file mode 100644index 0000000000..2bdc6227b8--- /dev/null+++ b/backend/src/ee/services/pki-scep/pki-scep-attributes.ts@@ -0,0 +1,83 @@+import * as asn1js from "asn1js";+import { Attribute } from "pkijs";++import { BadRequestError } from "@app/lib/errors";++import { SCEP_OIDS, ScepFailInfo, ScepMessageType, ScepPkiStatus } from "./pki-scep-types";++const findAttributeValue = (attributes: Attribute[], oid: string): asn1js.BaseBlock | undefined => {+ const attr = attributes.find((a) => a.type === oid);+ if (!attr || !attr.values || attr.values.length === 0) return undefined;+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return+ return attr.values[0];+};++export const extractScepAttributes = (+ attributes: Attribute[]+): {+ messageType: ScepMessageType;+ transactionId: string;+ senderNonce: Buffer;+} => {+ const messageTypeValue = findAttributeValue(attributes, SCEP_OIDS.messageType);+ if (!messageTypeValue) throw new BadRequestError({ message: "Missing SCEP messageType attribute" });+ const messageType = (messageTypeValue as asn1js.PrintableString).getValue() as ScepMessageType;++ const transactionIdValue = findAttributeValue(attributes, SCEP_OIDS.transactionId);+ if (!transactionIdValue) throw new BadRequestError({ message: "Missing SCEP transactionId attribute" });+ const transactionId = (transactionIdValue as asn1js.PrintableString).getValue();++ const senderNonceValue = findAttributeValue(attributes, SCEP_OIDS.senderNonce);+ if (!senderNonceValue) throw new BadRequestError({ message: "Missing SCEP senderNonce attribute" });+ const senderNonce = Buffer.from((senderNonceValue as asn1js.OctetString).getValue());++ return { messageType, transactionId, senderNonce };+};++export const buildResponseAttributes = ({+ transactionId,+ recipientNonce,+ senderNonce,+ pkiStatus,+ failInfo+}: {+ transactionId: string;+ recipientNonce: Buffer;+ senderNonce: Buffer;+ pkiStatus: ScepPkiStatus;+ failInfo?: ScepFailInfo;+}): Attribute[] => {+ const attrs: Attribute[] = [+ new Attribute({+ type: SCEP_OIDS.messageType,+ values: [new asn1js.PrintableString({ value: ScepMessageType.CertRep })]+ }),+ new Attribute({+ type: SCEP_OIDS.transactionId,+ values: [new asn1js.PrintableString({ value: transactionId })]+ }),+ new Attribute({+ type: SCEP_OIDS.pkiStatus,+ values: [new asn1js.PrintableString({ value: pkiStatus })]+ }),+ new Attribute({+ type: SCEP_OIDS.recipientNonce,+ values: [new asn1js.OctetString({ valueHex: recipientNonce })]+ }),+ new Attribute({+ type: SCEP_OIDS.senderNonce,+ values: [new asn1js.OctetString({ valueHex: senderNonce })]+ })+ ];++ if (failInfo !== undefined && pkiStatus === ScepPkiStatus.FAILURE) {+ attrs.push(+ new Attribute({+ type: SCEP_OIDS.failInfo,+ values: [new asn1js.PrintableString({ value: failInfo })]+ })+ );+ }++ return attrs;+};diff --git a/backend/src/ee/services/pki-scep/pki-scep-crypto.ts b/backend/src/ee/services/pki-scep/pki-scep-crypto.tsnew file mode 100644index 0000000000..3fd899b1ad--- /dev/null+++ b/backend/src/ee/services/pki-scep/pki-scep-crypto.ts@@ -0,0 +1,117 @@+import nodeCrypto from "node:crypto";++import forge from "node-forge";++import { BadRequestError } from "@app/lib/errors";++import { CIPHER_OID_MAP } from "./pki-scep-types";++// Node.js native crypto removed RSA_PKCS1_PADDING for privateDecrypt (CVE-2023-46809).+// SCEP mandates PKCS#1 v1.5 key transport per RFC 8894, so we use node-forge.+export const rsaPkcs1Decrypt = (encryptedKey: Buffer, privateKeyDer: Buffer): Buffer => {+ const privateKeyPem = nodeCrypto+ .createPrivateKey({ key: privateKeyDer, format: "der", type: "pkcs8" })+ .export({ type: "pkcs8", format: "pem" }) as string;++ const forgePrivateKey = forge.pki.privateKeyFromPem(privateKeyPem);+ const decrypted = forgePrivateKey.decrypt(forge.util.createBuffer(encryptedKey).getBytes(), "RSAES-PKCS1-V1_5");++ return Buffer.from(decrypted, "binary");+};++export const symmetricDecrypt = (encryptedContent: Buffer, key: Buffer, iv: Buffer, cipherOid: string): Buffer => {+ const cipherInfo = CIPHER_OID_MAP[cipherOid];+ if (!cipherInfo) {+ throw new BadRequestError({ message: `Unsupported cipher OID: ${cipherOid}` });+ }++ const decipher = nodeCrypto.createDecipheriv(cipherInfo.algorithm, key, iv);+ return Buffer.concat([decipher.update(encryptedContent), decipher.final()]);+};++export const symmetricEncryptWithOid = (+ content: Buffer,+ cipherOid?: string+): { encryptedContent: Buffer; key: Buffer; iv: Buffer; cipherOid: string } => {+ const resolvedOid = cipherOid && CIPHER_OID_MAP[cipherOid] ? cipherOid : "2.16.840.1.101.3.4.1.42"; // default AES-256-CBC+ const cipherInfo = CIPHER_OID_MAP[resolvedOid];++ const key = nodeCrypto.randomBytes(cipherInfo.keyLength);+ const iv = nodeCrypto.randomBytes(cipherInfo.ivLength);++ const cipher = nodeCrypto.createCipheriv(cipherInfo.algorithm, key, iv);+ const encryptedContent = Buffer.concat([cipher.update(content), cipher.final()]);++ return { encryptedContent, key, iv, cipherOid: resolvedOid };+};++export const rsaPkcs1Encrypt = (key: Buffer, recipientPublicKeyDer: Buffer): Buffer => {+ const publicKey = nodeCrypto.createPublicKey({+ key: recipientPublicKeyDer,+ format: "der",+ type: "spki"+ });++ return nodeCrypto.publicEncrypt(+ {+ key: publicKey,+ padding: nodeCrypto.constants.RSA_PKCS1_PADDING+ },+ key+ );+};++export const rsaSign = (data: Buffer, privateKeyDer: Buffer): Buffer => {+ const privateKey = nodeCrypto.createPrivateKey({+ key: privateKeyDer,+ format: "der",+ type: "pkcs8"+ });++ const signer = nodeCrypto.createSign("RSA-SHA256");+ signer.update(data);+ return signer.sign(privateKey);+};++const DIGEST_OID_TO_ALGO: Record<string, string> = {+ "2.16.840.1.101.3.4.2.1": "RSA-SHA256",+ "1.3.14.3.2.26": "RSA-SHA1",+ "2.16.840.1.101.3.4.2.2": "RSA-SHA384",+ "2.16.840.1.101.3.4.2.3": "RSA-SHA512"+};++export const rsaVerify = (+ data: Buffer,+ signature: Buffer,+ certificateDer: Buffer,+ digestAlgorithmOid?: string+): boolean => {+ const cert = new nodeCrypto.X509Certificate(certificateDer);+ const { publicKey } = cert;++ // If the digest algorithm OID is known from SignerInfo, use it directly+ if (digestAlgorithmOid) {+ const algo = DIGEST_OID_TO_ALGO[digestAlgorithmOid];+ if (algo) {+ const verifier = nodeCrypto.createVerify(algo);+ verifier.update(data);+ return verifier.verify(publicKey, signature);+ }+ }++ // Fallback: try all supported algorithms+ const algorithms = ["RSA-SHA256", "RSA-SHA1", "RSA-SHA384", "RSA-SHA512"];+ for (const algo of algorithms) {+ try {+ const verifier = nodeCrypto.createVerify(algo);+ verifier.update(data);+ if (verifier.verify(publicKey, signature)) {+ return true;+ }+ } catch {+ // Algorithm not supported or key incompatible — try next+ }+ }++ return false;+};diff --git a/backend/src/ee/services/pki-scep/pki-scep-fns.ts b/backend/src/ee/services/pki-scep/pki-scep-fns.tsnew file mode 100644index 0000000000..62b13ca8ab--- /dev/null+++ b/backend/src/ee/services/pki-scep/pki-scep-fns.ts@@ -0,0 +1,56 @@+import crypto from "node:crypto";++import * as x509 from "@peculiar/x509";++const RA_CERT_VALIDITY_YEARS = 10;++export const generateRaCertificate = async (+ slug: string+): Promise<{+ privateKeyDer: ArrayBuffer;+ certificatePem: string;+ expiresAt: Date;+}> => {+ x509.cryptoProvider.set(crypto.webcrypto as Crypto);++ const keyPair = await crypto.webcrypto.subtle.generateKey(+ {+ name: "RSASSA-PKCS1-v1_5",+ modulusLength: 4096,+ publicExponent: new Uint8Array([1, 0, 1]),+ hash: "SHA-256"+ },+ true,+ ["sign", "verify"]+ );++ const now = new Date();+ const notAfter = new Date(now);+ notAfter.setFullYear(notAfter.getFullYear() + RA_CERT_VALIDITY_YEARS);++ const cert = await x509.X509CertificateGenerator.createSelfSigned({+ serialNumber: crypto.randomBytes(16).toString("hex"),+ name: `CN=Infisical SCEP RA - ${slug}`,+ notBefore: now,+ notAfter,+ signingAlgorithm: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },+ keys: keyPair,+ extensions: [+ // eslint-disable-next-line no-bitwise+ new x509.KeyUsagesExtension(x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment, true),+ new x509.BasicConstraintsExtension(false, undefined, true)+ ]+ });++ const privateKeyDer = await crypto.webcrypto.subtle.exportKey("pkcs8", keyPair.privateKey);++ return {+ privateKeyDer,+ certificatePem: cert.toString("pem"),+ expiresAt: notAfter+ };+};++export const getScepCapabilities = (): string => {+ return ["POSTPKIOperation", "SHA-256", "SHA-1", "AES", "DES3", "SCEPStandard", "Renewal"].join("\n");+};diff --git a/backend/src/ee/services/pki-scep/pki-scep-message-builder.ts b/backend/src/ee/services/pki-scep/pki-scep-message-builder.tsnew file mode 100644index 0000000000..e05a155c03--- /dev/null+++ b/backend/src/ee/services/pki-scep/pki-scep-message-builder.ts@@ -0,0 +1,287 @@+import nodeCrypto from "node:crypto";++import * as asn1js from "asn1js";+import {+ AlgorithmIdentifier,+ Attribute,+ Certificate,+ ContentInfo,+ EncapsulatedContentInfo,+ IssuerAndSerialNumber,+ SignedAndUnsignedAttributes,+ SignedData,+ SignerInfo+} from "pkijs";++import { buildResponseAttributes } from "./pki-scep-attributes";+import { rsaPkcs1Encrypt, rsaSign, symmetricEncryptWithOid } from "./pki-scep-crypto";+import { ScepFailInfo, ScepPkiStatus } from "./pki-scep-types";++export const buildCertRepSuccess = ({+ issuedCertDer,+ recipientCertDer,+ raCertDer,+ raPrivateKeyDer,+ transactionId,+ recipientNonce,+ clientCipherOid+}: {+ issuedCertDer: Buffer;+ recipientCertDer: Buffer;+ raCertDer: Buffer;+ raPrivateKeyDer: Buffer;+ transactionId: string;+ recipientNonce: Buffer;+ clientCipherOid?: string;+}): Buffer => {+ // Step 1: Wrap the issued certificate in a degenerate PKCS#7 (cert-only SignedData)+ const issuedCertAsn1 = asn1js.fromBER(issuedCertDer);+ const issuedCert = new Certificate({ schema: issuedCertAsn1.result });+ const degenerateSignedData = new SignedData({+ version: 1,+ encapContentInfo: new EncapsulatedContentInfo({+ eContentType: "1.2.840.113549.1.7.1" // id-data+ }),+ certificates: [issuedCert]+ });+ const degenerateContent = new ContentInfo({+ contentType: "1.2.840.113549.1.7.2", // id-signedData+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ content: degenerateSignedData.toSchema()+ });+ const certPayload = Buffer.from(degenerateContent.toSchema().toBER(false));++ // Step 2: Encrypt the cert payload in an EnvelopedData for the device+ // Extract the device's public key from its self-signed certificate+ const recipientCert = new nodeCrypto.X509Certificate(recipientCertDer);+ const recipientPublicKeyDer = Buffer.from(recipientCert.publicKey.export({ type: "spki", format: "der" }));++ const { encryptedContent, key: cek, iv, cipherOid } = symmetricEncryptWithOid(certPayload, clientCipherOid);+ const encryptedCek = rsaPkcs1Encrypt(cek, recipientPublicKeyDer);++ // Build EnvelopedData ASN.1 manually and wrap in ContentInfo+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ const envelopedDataDer = buildEnvelopedDataDer(encryptedCek, encryptedContent, iv, cipherOid, recipientCertDer);++ // Wrap the EnvelopedData in a ContentInfo (PKCS#7 wrapper)+ const innerContentInfo = new asn1js.Sequence({+ value: [+ new asn1js.ObjectIdentifier({ value: "1.2.840.113549.1.7.3" }), // id-envelopedData+ new asn1js.Constructed({+ idBlock: { tagClass: 3, tagNumber: 0 }, // [0] EXPLICIT+ value: [asn1js.fromBER(envelopedDataDer).result]+ })+ ]+ });+ const innerContentInfoDer = Buffer.from(innerContentInfo.toBER(false));++ // Step 3: Build the outer SignedData+ const senderNonce = nodeCrypto.randomBytes(16);+ const responseAttrs = buildResponseAttributes({+ transactionId,+ recipientNonce,+ senderNonce,+ pkiStatus: ScepPkiStatus.SUCCESS+ });++ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ return buildSignedCertRep(innerContentInfoDer, responseAttrs, raCertDer, raPrivateKeyDer);+};++export const buildCertRepPending = ({+ raCertDer,+ raPrivateKeyDer,+ transactionId,+ recipientNonce+}: {+ raCertDer: Buffer;+ raPrivateKeyDer: Buffer;+ transactionId: string;+ recipientNonce: Buffer;+}): Buffer => {+ const senderNonce = nodeCrypto.randomBytes(16);+ const responseAttrs = buildResponseAttributes({+ transactionId,+ recipientNonce,+ senderNonce,+ pkiStatus: ScepPkiStatus.PENDING+ });++ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ return buildSignedCertRep(null, responseAttrs, raCertDer, raPrivateKeyDer);+};++export const buildCertRepFailure = ({+ raCertDer,+ raPrivateKeyDer,+ transactionId,+ recipientNonce,+ failInfo+}: {+ raCertDer: Buffer;+ raPrivateKeyDer: Buffer;+ transactionId: string;+ recipientNonce: Buffer;+ failInfo: ScepFailInfo;+}): Buffer => {+ const senderNonce = nodeCrypto.randomBytes(16);+ const responseAttrs = buildResponseAttributes({+ transactionId,+ recipientNonce,+ senderNonce,+ pkiStatus: ScepPkiStatus.FAILURE,+ failInfo+ });++ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ return buildSignedCertRep(null, responseAttrs, raCertDer, raPrivateKeyDer);+};++const buildSignedCertRep = (+ innerContent: Buffer | null,+ responseAttrs: Attribute[],+ raCertDer: Buffer,+ raPrivateKeyDer: Buffer+): Buffer => {+ const raCertAsn1 = asn1js.fromBER(raCertDer);+ const raCert = new Certificate({ schema: raCertAsn1.result });++ const encapContentInfo = new EncapsulatedContentInfo({+ eContentType: "1.2.840.113549.1.7.1" // id-data+ });++ if (innerContent) {+ encapContentInfo.eContent = new asn1js.OctetString({ valueHex: innerContent });+ }++ const signedAttrs = new SignedAndUnsignedAttributes({+ type: 0, // signedAttrs+ attributes: [+ // Content type attribute (required for signed attributes)+ new Attribute({+ type: "1.2.840.113549.1.9.3", // contentType+ values: [new asn1js.ObjectIdentifier({ value: "1.2.840.113549.1.7.1" })] // id-data+ }),+ // Message digest attribute+ new Attribute({+ type: "1.2.840.113549.1.9.4", // messageDigest+ values: [+ new asn1js.OctetString({+ valueHex: nodeCrypto+ .createHash("sha256")+ .update(Buffer.from(innerContent || Buffer.alloc(0)))+ .digest()+ })+ ]+ }),+ // SCEP response attributes+ ...responseAttrs+ ]+ });++ // Sign the signed attributes+ const signedAttrsDer = Buffer.from(signedAttrs.toSchema().toBER(false));+ signedAttrsDer[0] = 0x31; // Replace [0] IMPLICIT tag with SET tag for signing+ const signature = rsaSign(signedAttrsDer, raPrivateKeyDer);++ // Build SignerInfo+ const signerInfo = new SignerInfo({+ version: 1,+ sid: new IssuerAndSerialNumber({+ issuer: raCert.issuer,+ serialNumber: raCert.serialNumber+ }),+ digestAlgorithm: new AlgorithmIdentifier({+ algorithmId: "2.16.840.1.101.3.4.2.1" // SHA-256+ }),+ signedAttrs,+ signatureAlgorithm: new AlgorithmIdentifier({+ algorithmId: "1.2.840.113549.1.1.11" // sha256WithRSAEncryption+ }),+ signature: new asn1js.OctetString({ valueHex: signature })+ });++ // Build the SignedData+ const signedData = new SignedData({+ version: 1,+ digestAlgorithms: [+ new AlgorithmIdentifier({+ algorithmId: "2.16.840.1.101.3.4.2.1" // SHA-256+ })+ ],+ encapContentInfo,+ certificates: [raCert],+ signerInfos: [signerInfo]+ });++ // Wrap in ContentInfo+ const contentInfo = new ContentInfo({+ contentType: "1.2.840.113549.1.7.2", // id-signedData+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ content: signedData.toSchema()+ });++ return Buffer.from(contentInfo.toSchema().toBER(false));+};++const buildEnvelopedDataDer = (+ encryptedCek: Buffer,+ encryptedContent: Buffer,+ iv: Buffer,+ cipherOid: string,+ recipientCertDer: Buffer+): Buffer => {+ const recipientCertAsn1 = asn1js.fromBER(recipientCertDer);+ const recipientCert = new Certificate({ schema: recipientCertAsn1.result });++ // Build KeyTransRecipientInfo+ const ktri = new asn1js.Sequence({+ value: [+ // version+ new asn1js.Integer({ value: 0 }),+ // rid+ new IssuerAndSerialNumber({+ issuer: recipientCert.issuer,+ serialNumber: recipientCert.serialNumber+ }).toSchema(),+ // keyEncryptionAlgorithm+ new AlgorithmIdentifier({+ algorithmId: "1.2.840.113549.1.1.1" // rsaEncryption+ }).toSchema(),+ // encryptedKey+ new asn1js.OctetString({ valueHex: encryptedCek })+ ]+ });++ // Build EncryptedContentInfo+ const encryptedContentInfo = new asn1js.Sequence({+ value: [+ // contentType (id-data)+ new asn1js.ObjectIdentifier({ value: "1.2.840.113549.1.7.1" }),+ // contentEncryptionAlgorithm+ new AlgorithmIdentifier({+ algorithmId: cipherOid,+ algorithmParams: new asn1js.OctetString({ valueHex: iv })+ }).toSchema(),+ // encryptedContent+ new asn1js.Primitive({+ idBlock: { tagClass: 3, tagNumber: 0 }, // context-specific [0]+ valueHex: encryptedContent+ })+ ]+ });++ // Build EnvelopedData+ const envelopedData = new asn1js.Sequence({+ value: [+ // version+ new asn1js.Integer({ value: 0 }),+ // recipientInfos+ new asn1js.Set({ value: [ktri] }),+ // encryptedContentInfo+ encryptedContentInfo+ ]+ });++ return Buffer.from(envelopedData.toBER(false));+};diff --git a/backend/src/ee/services/pki-scep/pki-scep-message-parser.ts b/backend/src/ee/services/pki-scep/pki-scep-message-parser.tsnew file mode 100644index 0000000000..668235c398--- /dev/null+++ b/backend/src/ee/services/pki-scep/pki-scep-message-parser.ts@@ -0,0 +1,364 @@+import nodeCrypto from "node:crypto";++import * as asn1js from "asn1js";+import { Certificate, ContentInfo, SignedData } from "pkijs";++import { BadRequestError } from "@app/lib/errors";++import { extractScepAttributes } from "./pki-scep-attributes";+import { rsaPkcs1Decrypt, rsaVerify, symmetricDecrypt } from "./pki-scep-crypto";+import { ScepMessageType, TParsedScepMessage } from "./pki-scep-types";++export const parseScepMessage = (derMessage: Buffer, raPrivateKeyDer: Buffer): TParsedScepMessage => {+ // Parse the outer ContentInfo+ const contentInfoAsn1 = asn1js.fromBER(derMessage);+ if (contentInfoAsn1.offset === -1) {+ throw new BadRequestError({ message: "Failed to parse SCEP message: invalid DER encoding" });+ }+ const contentInfo = new ContentInfo({ schema: contentInfoAsn1.result });++ if (contentInfo.contentType !== "1.2.840.113549.1.7.2") {+ throw new BadRequestError({ message: `Unexpected content type: ${contentInfo.contentType}, expected SignedData` });+ }++ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ const signedData = new SignedData({ schema: contentInfo.content });++ if (!signedData.certificates || signedData.certificates.length === 0) {+ throw new BadRequestError({ message: "No certificates found in SCEP SignedData" });+ }++ const signerCert = signedData.certificates[0];+ if (!(signerCert instanceof Certificate)) {+ throw new BadRequestError({ message: "Invalid signer certificate in SCEP SignedData" });+ }+ const signerCertDer = Buffer.from(signerCert.toSchema().toBER(false));++ // Extract SCEP attributes+ if (!signedData.signerInfos || signedData.signerInfos.length === 0) {+ throw new BadRequestError({ message: "No signerInfos found in SCEP SignedData" });+ }++ const signerInfo = signedData.signerInfos[0];+ if (!signerInfo.signedAttrs) {+ throw new BadRequestError({ message: "No signed attributes found" });+ }++ const scepAttrs = extractScepAttributes(signerInfo.signedAttrs.attributes);++ // Verify messageDigest attribute matches the hash of the encapsulated content (RFC 5652 §11.2)+ const DIGEST_OID_TO_HASH: Record<string, string> = {+ "2.16.840.1.101.3.4.2.1": "sha256",+ "1.3.14.3.2.26": "sha1",+ "2.16.840.1.101.3.4.2.2": "sha384",+ "2.16.840.1.101.3.4.2.3": "sha512"+ };++ const messageDigestAttr = signerInfo.signedAttrs.attributes.find((a) => a.type === "1.2.840.113549.1.9.4");+ if (messageDigestAttr && messageDigestAttr.values.length > 0 && signedData.encapContentInfo?.eContent) {+ const claimedDigest = Buffer.from((messageDigestAttr.values[0] as asn1js.OctetString).valueBlock.valueHexView);+ const hashAlgo = DIGEST_OID_TO_HASH[signerInfo.digestAlgorithm.algorithmId];++ if (hashAlgo) {+ const eContentBer = signedData.encapContentInfo.eContent.toBER(false);+ const eContentParsed = asn1js.fromBER(Buffer.from(eContentBer));+ const eContentBytes =+ eContentParsed.result instanceof asn1js.OctetString+ ? Buffer.from(eContentParsed.result.getValue())+ : Buffer.from(eContentBer);+ const computedDigest = nodeCrypto.createHash(hashAlgo).update(eContentBytes).digest();++ if (!claimedDigest.equals(computedDigest)) {+ throw new BadRequestError({ message: "SCEP message integrity check failed: messageDigest mismatch" });+ }+ }+ }++ // Verify the signature over the signed attributes+ if (signerInfo.signature) {+ const signedAttrsDer = Buffer.from(signerInfo.signedAttrs.toSchema().toBER(false));+ // CMS spec (RFC 5652 §5.4): signed attributes are encoded as SET (0x31) for verification+ signedAttrsDer[0] = 0x31;+ const signatureBytes = Buffer.from(signerInfo.signature.valueBlock.valueHexView);++ // Extract the digest algorithm from SignerInfo per RFC 5652 §5.3+ const digestAlgoOid = signerInfo.digestAlgorithm.algorithmId;+ if (!rsaVerify(signedAttrsDer, signatureBytes, signerCertDer, digestAlgoOid)) {+ throw new BadRequestError({ message: "SCEP message signature verification failed" });+ }+ }++ // For PKCSReq and RenewalReq, decrypt the inner EnvelopedData+ let csr: Buffer | undefined;+ let clientCipherOid: string | undefined;++ if (scepAttrs.messageType === ScepMessageType.PKCSReq || scepAttrs.messageType === ScepMessageType.RenewalReq) {+ if (!signedData.encapContentInfo || !signedData.encapContentInfo.eContent) {+ throw new BadRequestError({ message: "No encapsulated content in SCEP SignedData for PKCSReq/RenewalReq" });+ }++ // Extract the raw DER bytes of the EnvelopedData from the eContent.+ // The eContent is an ASN.1 OctetString (possibly constructed) that wraps+ // the DER-encoded EnvelopedData. We serialize it to BER, then extract just+ // the value bytes (stripping the outer OctetString TLV wrapper).+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ const envelopedDataDer = extractEContentBytes(signedData.encapContentInfo.eContent);++ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ const decrypted = decryptEnvelopedDataRaw(envelopedDataDer, raPrivateKeyDer);+ csr = decrypted.plainText;+ clientCipherOid = decrypted.cipherOid;+ }++ return {+ messageType: scepAttrs.messageType,+ transactionId: scepAttrs.transactionId,+ senderNonce: scepAttrs.senderNonce,+ signerCertDer,+ csr,+ clientCipherOid+ };+};++const extractEContentBytes = (eContent: asn1js.BaseBlock): Buffer => {+ const berBytes = eContent.toBER(false);+ const fullBuf = Buffer.from(berBytes);++ // Parse it back to get just the value portion+ const parsed = asn1js.fromBER(fullBuf);+ if (parsed.offset === -1) {+ // If parsing fails, treat the whole thing as raw bytes+ return fullBuf;+ }++ const { result } = parsed;++ // If it's an OctetString, get its value bytes+ if (result instanceof asn1js.OctetString) {+ // For constructed OctetStrings, getValue() concatenates all chunks+ const valueBytes = result.getValue();+ return Buffer.from(valueBytes);+ }++ // If it's a context-specific tag (e.g., [0] EXPLICIT wrapping), get the inner content+ if (result.idBlock.tagClass === 3) {+ // Context-specific — get inner bytes by stripping the outer TLV+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ const innerBytes = extractTlvValueBytes(fullBuf);+ return innerBytes;+ }++ // Otherwise, return the raw BER bytes as-is+ return fullBuf;+};++/* eslint-disable no-bitwise */+const extractTlvValueBytes = (der: Buffer): Buffer => {+ if (der.length < 2) {+ throw new BadRequestError({ message: "DER TLV too short to parse" });+ }++ let offset = 0;++ // High-tag-number form: if lower 5 bits are all 1s, subsequent bytes encode the tag+ if ((der[offset] & 0x1f) === 0x1f) {+ offset += 1;+ while (offset < der.length && (der[offset] & 0x80) !== 0) {+ offset += 1;+ }+ offset += 1; // skip the last tag byte+ } else {+ offset += 1;+ }++ if (offset >= der.length) {+ throw new BadRequestError({ message: "DER TLV truncated: no length byte" });+ }++ // Parse length+ if (der[offset] & 0x80) {+ const numLengthBytes = der[offset] & 0x7f;+ offset += 1 + numLengthBytes;+ } else {+ offset += 1;+ }++ if (offset > der.length) {+ throw new BadRequestError({ message: "DER TLV truncated: offset exceeds buffer" });+ }++ return der.subarray(offset);+};+/* eslint-enable no-bitwise */++const extractRawBytes = (element: asn1js.BaseBlock): Buffer => {+ // Case 1: OctetString — use getValue() which handles both primitive and constructed forms+ if (element instanceof asn1js.OctetString) {+ return Buffer.from(element.getValue());+ }++ // Case 2: element has valueBlock with valueHexView+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment+ const vb = element.valueBlock as any;+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ if (vb.valueHexView instanceof Uint8Array && vb.valueHexView.length > 0) {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ return Buffer.from(vb.valueHexView as Uint8Array);+ }++ // Case 3: element has valueBlock with valueHex+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ if (vb.valueHex instanceof ArrayBuffer && vb.valueHex.byteLength > 0) {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ return Buffer.from(vb.valueHex as ArrayBuffer);+ }++ // Case 4: Constructed type+ // Serialize to DER and strip the outer tag+length to get raw value bytes+ const fullDer = Buffer.from(element.toBER(false));+ return extractTlvValueBytes(fullDer);+};++const decryptEnvelopedDataRaw = (+ envelopedDataDer: Buffer,+ raPrivateKeyDer: Buffer+): { plainText: Buffer; cipherOid: string } => {+ const asn1 = asn1js.fromBER(envelopedDataDer);+ if (asn1.offset === -1) {+ throw new BadRequestError({ message: "Failed to parse EnvelopedData DER" });+ }++ let seq = asn1.result as asn1js.Sequence;+ let valueBlock = seq.valueBlock.value;++ // The eContent may be wrapped in a ContentInfo SEQUENCE:+ // SEQUENCE { OID(envelopedData), [0] EXPLICIT { SEQUENCE(EnvelopedData) } }+ if (+ valueBlock.length === 2 &&+ valueBlock[0] instanceof asn1js.ObjectIdentifier &&+ valueBlock[0].getValue() === "1.2.840.113549.1.7.3" // id-envelopedData+ ) {+ // Extract the EnvelopedData from inside+ const contextWrapper = valueBlock[1];+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access+ const innerElements = (contextWrapper.valueBlock as any).value as asn1js.BaseBlock[];+ if (innerElements && innerElements.length > 0) {+ seq = innerElements[0] as asn1js.Sequence;+ valueBlock = seq.valueBlock.value;+ }+ }++ // valueBlock[0] = version (Integer)+ // valueBlock[1] = recipientInfos (Set)+ // valueBlock[2] = encryptedContentInfo (Sequence)++ if (valueBlock.length < 3) {+ throw new BadRequestError({+ message: `EnvelopedData has unexpected structure: expected >= 3 elements, got ${valueBlock.length}`+ });+ }++ // Extract encrypted key from first RecipientInfo+ const recipientInfosSet = valueBlock[1] as asn1js.Set;+ if (+ !recipientInfosSet.valueBlock ||+ !recipientInfosSet.valueBlock.value ||+ recipientInfosSet.valueBlock.value.length === 0+ ) {+ throw new BadRequestError({ message: "No RecipientInfo found in EnvelopedData" });+ }++ const firstRecipientInfo = recipientInfosSet.valueBlock.value[0] as asn1js.Sequence;+ const ktri = firstRecipientInfo.valueBlock.value;++ // The encryptedKey is the LAST element of KeyTransRecipientInfo+ // Per RFC 5652: version, rid, keyEncryptionAlgorithm, encryptedKey+ // The encryptedKey is an OCTET STRING, but some encoders may produce it differently.+ const encryptedKeyElement = ktri[ktri.length - 1];+ const encryptedKey = extractRawBytes(encryptedKeyElement);++ if (encryptedKey.length === 0) {+ throw new BadRequestError({ message: "Failed to extract encrypted key from KeyTransRecipientInfo" });+ }++ // Decrypt the content-encryption key using RSA PKCS1v1.5+ const contentEncryptionKey = rsaPkcs1Decrypt(encryptedKey, raPrivateKeyDer);++ // Extract encrypted content info+ const encContentInfo = (valueBlock[2] as asn1js.Sequence).valueBlock.value;++ if (encContentInfo.length < 3) {+ throw new BadRequestError({+ message: `EncryptedContentInfo has unexpected structure: expected >= 3 elements, got ${encContentInfo.length}`+ });+ }++ // encContentInfo[0] = contentType OID+ // encContentInfo[1] = contentEncryptionAlgorithm (SEQUENCE { OID, params })+ // encContentInfo[2] = encryptedContent++ // Get cipher algorithm OID and IV from AlgorithmIdentifier+ const algoSeq = (encContentInfo[1] as asn1js.Sequence).valueBlock.value;+ const cipherOid = (algoSeq[0] as asn1js.ObjectIdentifier).getValue();++ // IV is the second element of the AlgorithmIdentifier+ const ivElement = algoSeq[1];+ const iv = extractRawBytes(ivElement);++ if (iv.length === 0) {+ throw new BadRequestError({ message: "Failed to extract IV from content encryption algorithm" });+ }++ // Get the encrypted content+ const encContentElement = encContentInfo[2];+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ const encryptedContent = extractEncryptedContent(encContentElement);++ if (encryptedContent.length === 0) {+ throw new BadRequestError({ message: "Failed to extract encrypted content from EncryptedContentInfo" });+ }++ // Decrypt the content+ return {+ plainText: symmetricDecrypt(encryptedContent, contentEncryptionKey, iv, cipherOid),+ cipherOid+ };+};++const extractEncryptedContent = (element: asn1js.BaseBlock): Buffer => {+ if (element instanceof asn1js.OctetString) {+ return Buffer.from(element.getValue());+ }++ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment+ const vb = element.valueBlock as any;++ // Check if it's a constructed type with sub-elements+ // Constructed context-specific tags have valueBlock.value as an array of sub-elements+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ if (Array.isArray(vb.value) && (vb.value as asn1js.BaseBlock[]).length > 0) {+ const chunks: Buffer[] = [];+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ for (const sub of vb.value as asn1js.BaseBlock[]) {+ chunks.push(extractRawBytes(sub));+ }+ return Buffer.concat(chunks);+ }++ // Primitive context-specific raw value bytes are in valueHexView or valueHex+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ if (vb.valueHexView instanceof Uint8Array && vb.valueHexView.length > 0) {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ return Buffer.from(vb.valueHexView as Uint8Array);+ }++ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ if (vb.valueHex instanceof ArrayBuffer && vb.valueHex.byteLength > 0) {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ return Buffer.from(vb.valueHex as ArrayBuffer);+ }++ // Last resort: serialize to DER and strip the tag+length+ const fullDer = Buffer.from(element.toBER(false));+ return extractTlvValueBytes(fullDer);+};diff --git a/backend/src/ee/services/pki-scep/pki-scep-service.ts b/backend/src/ee/services/pki-scep/pki-scep-service.tsnew file mode 100644index 0000000000..fcd071f385--- /dev/null+++ b/backend/src/ee/services/pki-scep/pki-scep-service.ts@@ -0,0 +1,725 @@+import * as x509 from "@peculiar/x509";++import { extractX509CertFromChain } from "@app/lib/certificates/extract-certificate";+import { crypto } from "@app/lib/crypto/cryptography";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { ActorType } from "@app/services/auth/auth-type";+import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";+import { isCertChainValid } from "@app/services/certificate/certificate-fns";+import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";+import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";+import { getCaCertChain, getCaCertChains } from "@app/services/certificate-authority/certificate-authority-fns";+import { TCertificatePolicyDALFactory } from "@app/services/certificate-policy/certificate-policy-dal";+import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";+import { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types";+import { TCertificateRequestDALFactory } from "@app/services/certificate-request/certificate-request-dal";+import { CertificateRequestStatus } from "@app/services/certificate-request/certificate-request-types";+import { resolveEffectiveTtl } from "@app/services/certificate-v3/certificate-v3-fns";+import { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";+import { TScepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-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 { EventType, TAuditLogServiceFactory } from "../audit-log/audit-log-types";+import { convertRawCertsToPkcs7 } from "../certificate-est/certificate-est-fns";+import { TLicenseServiceFactory } from "../license/license-service";+import { getScepCapabilities } from "./pki-scep-fns";+import { buildCertRepFailure, buildCertRepPending, buildCertRepSuccess } from "./pki-scep-message-builder";+import { parseScepMessage } from "./pki-scep-message-parser";+import { TScepTransactionDALFactory } from "./pki-scep-transaction-dal";+import {+ ScepFailInfo,+ ScepMessageType,+ TGetCaCapsDTO,+ TGetCaCertDTO,+ THandlePkiOperationDTO,+ TParsedScepMessage+} from "./pki-scep-types";++type TPkiScepServiceFactoryDep = {+ certificateV3Service: Pick<TCertificateV3ServiceFactory, "signCertificateFromProfile">;+ certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;+ scepEnrollmentConfigDAL: Pick<TScepEnrollmentConfigDALFactory, "findById">;+ scepTransactionDAL: TScepTransactionDALFactory;+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;+ certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find" | "findById">;+ certificateRequestDAL: Pick<TCertificateRequestDALFactory, "findById">;+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;+ kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "findById">;+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;+};++export type TPkiScepServiceFactory = ReturnType<typeof pkiScepServiceFactory>;++const SCEP_TRANSACTION_EXPIRY_HOURS = 24;++export const pkiScepServiceFactory = ({+ certificateV3Service,+ certificateProfileDAL,+ scepEnrollmentConfigDAL,+ scepTransactionDAL,+ certificateAuthorityDAL,+ certificateAuthorityCertDAL,+ certificateRequestDAL,+ certificateBodyDAL,+ projectDAL,+ kmsService,+ licenseService,+ certificatePolicyDAL,+ auditLogService+}: TPkiScepServiceFactoryDep) => {+ const loadScepContext = async (profileId: string) => {+ const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);+ if (!profile) {+ throw new NotFoundError({ message: "Certificate profile not found" });+ }++ if (profile.enrollmentType !== EnrollmentType.SCEP) {+ throw new BadRequestError({ message: "Profile is not configured for SCEP enrollment" });+ }++ if (!profile.scepConfigId) {+ throw new BadRequestError({ message: "SCEP enrollment not configured for this profile" });+ }++ if (!profile.caId) {+ throw new BadRequestError({ message: "Self-signed certificates are not supported for SCEP enrollment" });+ }++ const scepConfig = await scepEnrollmentConfigDAL.findById(profile.scepConfigId);+ if (!scepConfig) {+ throw new NotFoundError({ message: "SCEP configuration not found" });+ }++ const project = await projectDAL.findOne({ id: profile.projectId });+ if (!project) {+ throw new NotFoundError({ message: "Project not found" });+ }++ const plan = await licenseService.getPlan(project.orgId);+ if (!plan.pkiScep) {+ throw new BadRequestError({+ message: "Failed to perform SCEP operation due to plan restriction. Upgrade to the Enterprise plan."+ });+ }++ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({+ projectId: profile.projectId,+ projectDAL,+ kmsService+ });+ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: certificateManagerKmsId });+ const raPrivateKeyDer = await kmsDecryptor({ cipherTextBlob: scepConfig.encryptedRaPrivateKey });++ const raCert = new x509.X509Certificate(scepConfig.raCertificate);+ const raCertDer = Buffer.from(raCert.rawData);++ return { profile, scepConfig, project, raPrivateKeyDer, raCertDer };+ };++ const getCaCaps = async ({ profileId }: TGetCaCapsDTO): Promise<string> => {+ const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);+ if (!profile || profile.enrollmentType !== EnrollmentType.SCEP) {+ throw new NotFoundError({ message: "SCEP profile not found" });+ }++ return getScepCapabilities();+ };++ const getCaCert = async ({ profileId }: TGetCaCertDTO): Promise<Buffer> => {+ const { profile, scepConfig } = await loadScepContext(profileId);++ const raCert = new x509.X509Certificate(scepConfig.raCertificate);+ const rawCerts: ArrayBuffer[] = [raCert.rawData];++ if (scepConfig.includeCaCertInResponse && profile.caId) {+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId);+ if (ca?.internalCa?.activeCaCertId) {+ const { caCert, caCertChain } = await getCaCertChain({+ caCertId: ca.internalCa.activeCaCertId,+ certificateAuthorityDAL,+ certificateAuthorityCertDAL,+ projectDAL,+ kmsService+ });++ const caCertObj = new x509.X509Certificate(caCert);+ rawCerts.push(caCertObj.rawData);++ if (caCertChain) {+ const chainCerts = extractX509CertFromChain(caCertChain);+ for (const cert of chainCerts) {+ rawCerts.push(new x509.X509Certificate(cert).rawData);+ }+ }+ }+ }++ const base64Pkcs7 = convertRawCertsToPkcs7(rawCerts);+ return Buffer.from(base64Pkcs7, "base64");+ };++ type TScepContext = Awaited<ReturnType<typeof loadScepContext>>;++ const derToPem = (der: Buffer, label: string): string => {+ const base64 = der.toString("base64").replace(/(.{64})/g, "$1\n");+ return `-----BEGIN ${label}-----\n${base64}\n-----END ${label}-----`;+ };++ const resolveIssuanceParams = async (profile: TScepContext["profile"]) => {+ const policy = profile.certificatePolicyId+ ? await certificatePolicyDAL.findById(profile.certificatePolicyId)+ : null;+ const ttl = resolveEffectiveTtl({+ requestTtl: undefined,+ profileDefaultTtlDays: profile.defaults?.ttlDays,+ policyMaxValidity: policy?.validity?.max,+ flowDefaultTtl: "90d"+ });+ return { ttl };+ };++ const handlePkiOperation = async ({ profileId, message, clientIp }: THandlePkiOperationDTO): Promise<Buffer> => {+ const { profile, scepConfig, project, raPrivateKeyDer, raCertDer } = await loadScepContext(profileId);++ const parsed = parseScepMessage(message, raPrivateKeyDer);++ switch (parsed.messageType) {+ case ScepMessageType.PKCSReq:+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ return handleEnrollment({+ profile,+ scepConfig,+ project,+ raPrivateKeyDer,+ raCertDer,+ parsed,+ clientIp+ });++ case ScepMessageType.RenewalReq:+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ return handleRenewal({+ profile,+ scepConfig,+ project,+ raPrivateKeyDer,+ raCertDer,+ parsed,+ clientIp+ });++ case ScepMessageType.GetCertInitial:+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ return handleGetCertInitial({+ profile,+ raPrivateKeyDer,+ raCertDer,+ parsed+ });++ default:+ throw new BadRequestError({ message: `Unsupported SCEP message type: ${parsed.messageType}` });+ }+ };++ // Check if a signer certificate was issued by the profile's CA+ const isSignerCertIssuedByCa = async (signerCertDer: Buffer, profile: TScepContext["profile"]): Promise<boolean> => {+ try {+ const signerCert = new x509.X509Certificate(signerCertDer);++ if (new Date() > signerCert.notAfter) {+ return false;+ }++ const caCertChains = await getCaCertChains({+ caId: profile.caId!,+ certificateAuthorityCertDAL,+ certificateAuthorityDAL,+ projectDAL,+ kmsService+ });++ const verifiedChains = await Promise.all(+ caCertChains.map(async (chain) => {+ const caCert = new x509.X509Certificate(chain.certificate);+ const chainCerts = chain.certificateChain+ ? extractX509CertFromChain(chain.certificateChain).map((c) => new x509.X509Certificate(c))+ : [];+ return isCertChainValid([signerCert, caCert, ...chainCerts]);+ })+ );++ return verifiedChains.some(Boolean);+ } catch {+ return false;+ }+ };++ const handleEnrollment = async ({+ profile,+ scepConfig,+ project,+ raPrivateKeyDer,+ raCertDer,+ parsed,+ clientIp+ }: {+ profile: TScepContext["profile"];+ scepConfig: TScepContext["scepConfig"];+ project: TScepContext["project"];+ raPrivateKeyDer: Buffer;+ raCertDer: Buffer;+ parsed: TParsedScepMessage;+ clientIp: string;+ }): Promise<Buffer> => {+ if (!parsed.csr) {+ throw new BadRequestError({ message: "No CSR found in SCEP enrollment request" });+ }++ const csrObj = new x509.Pkcs10CertificateRequest(parsed.csr);+ const challengePasswordOid = "1.2.840.113549.1.9.7"; // PKCS#9 challengePassword+ const challengeAttr = csrObj.attributes.find((attr) => attr.type === challengePasswordOid);++ let challengePassword = "";+ if (challengeAttr && challengeAttr.values && challengeAttr.values.length > 0) {+ // The challengePassword is typically a UTF8String or PrintableString+ // @peculiar/x509 returns ASN.1 ArrayBuffer values+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any+ const raw = challengeAttr.values[0] as any;+ if (raw instanceof ArrayBuffer || raw instanceof Uint8Array) {+ // The value is DER-encoded ASN.1 string+ // Strip the tag+length to get the actual string bytes+ const buf = Buffer.from(raw);+ // ASN.1 string: tag (1 byte) + length (1+ bytes) + value+ let offset = 1; // skip tag+ // eslint-disable-next-line no-bitwise+ if (buf[offset] & 0x80) {+ // eslint-disable-next-line no-bitwise+ const numLenBytes = buf[offset] & 0x7f;+ offset += 1 + numLenBytes;+ } else {+ offset += 1;+ }+ challengePassword = buf.subarray(offset).toString("utf-8");+ } else if (typeof raw === "string") {+ challengePassword = raw;+ } else {+ challengePassword = String(raw);+ }+ }++ const isValid = challengePassword+ ? await crypto.hashing().compareHash(challengePassword, scepConfig.hashedChallengePassword)+ : false;++ if (!isValid) {+ // Many SCEP clients (including sscep) send PKCSReq for both initial enrollment+ // and renewal — they don't use RenewalReq (messageType=17). Detect renewal by+ // checking if the signer cert chains to the profile CA.+ if (scepConfig.allowCertBasedRenewal) {+ const isRenewalViaPKCSReq = await isSignerCertIssuedByCa(parsed.signerCertDer, profile);+ if (isRenewalViaPKCSReq) {+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ return handleRenewal({+ profile,+ scepConfig,+ project,+ raPrivateKeyDer,+ raCertDer,+ parsed,+ clientIp+ });+ }+ }++ void auditLogService.createAuditLog({+ projectId: profile.projectId,+ actor: {+ type: ActorType.SCEP_ACCOUNT,+ metadata: { profileId: profile.id }+ },+ event: {+ type: EventType.SCEP_ENROLLMENT,+ metadata: {+ profileId: profile.id,+ profileSlug: profile.slug,+ transactionId: parsed.transactionId,+ csrSubject: csrObj.subject,+ challengeType: "static" as const,+ status: "failure" as const,+ failReason: "Invalid challenge password",+ clientIp+ }+ }+ });++ return buildCertRepFailure({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ failInfo: ScepFailInfo.BadRequest+ });+ }++ const { ttl } = await resolveIssuanceParams(profile);+ const csrPem = derToPem(Buffer.from(parsed.csr), "CERTIFICATE REQUEST");++ const result = await certificateV3Service.signCertificateFromProfile({+ actor: ActorType.SCEP_ACCOUNT,+ actorId: profile.id,+ actorAuthMethod: null,+ actorOrgId: project.orgId,+ profileId: profile.id,+ csr: csrPem,+ validity: { ttl },+ enrollmentType: EnrollmentType.SCEP+ });++ if (result.status === CertificateRequestStatus.PENDING_APPROVAL) {+ const expiresAt = new Date();+ expiresAt.setHours(expiresAt.getHours() + SCEP_TRANSACTION_EXPIRY_HOURS);++ await scepTransactionDAL.create({+ profileId: profile.id,+ transactionId: parsed.transactionId,+ senderNonce: parsed.senderNonce,+ signerCertDer: parsed.signerCertDer,+ certificateRequestId: result.certificateRequestId,+ expiresAt+ });++ void auditLogService.createAuditLog({+ projectId: profile.projectId,+ actor: {+ type: ActorType.SCEP_ACCOUNT,+ metadata: { profileId: profile.id }+ },+ event: {+ type: EventType.SCEP_ENROLLMENT,+ metadata: {+ profileId: profile.id,+ profileSlug: profile.slug,+ transactionId: parsed.transactionId,+ csrSubject: csrObj.subject,+ challengeType: "static" as const,+ status: "pending" as const,+ clientIp+ }+ }+ });++ return buildCertRepPending({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce+ });+ }++ if (!result.certificate) {+ throw new BadRequestError({ message: "Certificate issuance failed" });+ }++ const issuedCert = new x509.X509Certificate(result.certificate);+ const issuedCertDer = Buffer.from(issuedCert.rawData);++ void auditLogService.createAuditLog({+ projectId: profile.projectId,+ actor: {+ type: ActorType.SCEP_ACCOUNT,+ metadata: { profileId: profile.id }+ },+ event: {+ type: EventType.SCEP_ENROLLMENT,+ metadata: {+ profileId: profile.id,+ profileSlug: profile.slug,+ transactionId: parsed.transactionId,+ csrSubject: csrObj.subject,+ challengeType: "static" as const,+ status: "success" as const,+ issuedCertificateId: result.certificateId,+ issuedSerialNumber: result.serialNumber,+ clientIp+ }+ }+ });++ return buildCertRepSuccess({+ issuedCertDer,+ recipientCertDer: parsed.signerCertDer,+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ clientCipherOid: parsed.clientCipherOid+ });+ };++ const handleRenewal = async ({+ profile,+ scepConfig,+ project,+ raPrivateKeyDer,+ raCertDer,+ parsed,+ clientIp+ }: {+ profile: TScepContext["profile"];+ scepConfig: TScepContext["scepConfig"];+ project: TScepContext["project"];+ raPrivateKeyDer: Buffer;+ raCertDer: Buffer;+ parsed: TParsedScepMessage;+ clientIp: string;+ }): Promise<Buffer> => {+ if (!scepConfig.allowCertBasedRenewal) {+ return buildCertRepFailure({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ failInfo: ScepFailInfo.BadRequest+ });+ }++ if (!parsed.csr) {+ throw new BadRequestError({ message: "No CSR found in SCEP renewal request" });+ }++ const csrObj = new x509.Pkcs10CertificateRequest(parsed.csr);++ const signerCert = new x509.X509Certificate(parsed.signerCertDer);+ const isValidSigner = await isSignerCertIssuedByCa(parsed.signerCertDer, profile);+ if (!isValidSigner) {+ void auditLogService.createAuditLog({+ projectId: profile.projectId,+ actor: {+ type: ActorType.SCEP_ACCOUNT,+ metadata: { profileId: profile.id }+ },+ event: {+ type: EventType.SCEP_RENEWAL,+ metadata: {+ profileId: profile.id,+ profileSlug: profile.slug,+ transactionId: parsed.transactionId,+ csrSubject: csrObj.subject,+ status: "failure" as const,+ failReason: "Signer certificate is expired or does not chain to profile CA",+ clientIp+ }+ }+ });++ return buildCertRepFailure({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ failInfo: ScepFailInfo.BadCertId+ });+ }++ const { ttl } = await resolveIssuanceParams(profile);+ const csrPem = derToPem(Buffer.from(parsed.csr), "CERTIFICATE REQUEST");++ const result = await certificateV3Service.signCertificateFromProfile({+ actor: ActorType.SCEP_ACCOUNT,+ actorId: profile.id,+ actorAuthMethod: null,+ actorOrgId: project.orgId,+ profileId: profile.id,+ csr: csrPem,+ validity: { ttl },+ enrollmentType: EnrollmentType.SCEP+ });++ if (result.status === CertificateRequestStatus.PENDING_APPROVAL) {+ const expiresAt = new Date();+ expiresAt.setHours(expiresAt.getHours() + SCEP_TRANSACTION_EXPIRY_HOURS);++ await scepTransactionDAL.create({+ profileId: profile.id,+ transactionId: parsed.transactionId,+ senderNonce: parsed.senderNonce,+ signerCertDer: parsed.signerCertDer,+ certificateRequestId: result.certificateRequestId,+ expiresAt+ });++ return buildCertRepPending({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce+ });+ }++ if (!result.certificate) {+ throw new BadRequestError({ message: "Certificate renewal failed" });+ }++ const issuedCert = new x509.X509Certificate(result.certificate);++ void auditLogService.createAuditLog({+ projectId: profile.projectId,+ actor: {+ type: ActorType.SCEP_ACCOUNT,+ metadata: { profileId: profile.id }+ },+ event: {+ type: EventType.SCEP_RENEWAL,+ metadata: {+ profileId: profile.id,+ profileSlug: profile.slug,+ transactionId: parsed.transactionId,+ csrSubject: csrObj.subject,+ existingCertificateSerial: signerCert.serialNumber,+ status: "success" as const,+ issuedCertificateId: result.certificateId,+ issuedSerialNumber: result.serialNumber,+ clientIp+ }+ }+ });++ return buildCertRepSuccess({+ issuedCertDer: Buffer.from(issuedCert.rawData),+ recipientCertDer: parsed.signerCertDer,+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ clientCipherOid: parsed.clientCipherOid+ });+ };++ const handleGetCertInitial = async ({+ profile,+ raPrivateKeyDer,+ raCertDer,+ parsed+ }: {+ profile: TScepContext["profile"];+ raPrivateKeyDer: Buffer;+ raCertDer: Buffer;+ parsed: TParsedScepMessage;+ }): Promise<Buffer> => {+ const transaction = await scepTransactionDAL.findByProfileAndTransactionId(profile.id, parsed.transactionId);++ if (!transaction) {+ return buildCertRepFailure({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ failInfo: ScepFailInfo.BadCertId+ });+ }++ if (new Date() > new Date(transaction.expiresAt)) {+ return buildCertRepFailure({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ failInfo: ScepFailInfo.BadTime+ });+ }++ if (!transaction.certificateRequestId) {+ return buildCertRepFailure({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ failInfo: ScepFailInfo.BadRequest+ });+ }++ const certRequest = await certificateRequestDAL.findById(transaction.certificateRequestId);+ if (!certRequest) {+ return buildCertRepFailure({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ failInfo: ScepFailInfo.BadRequest+ });+ }++ switch (certRequest.status) {+ case CertificateRequestStatus.PENDING_APPROVAL:+ return buildCertRepPending({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce+ });++ case CertificateRequestStatus.ISSUED: {+ if (!certRequest.certificateId) {+ return buildCertRepFailure({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ failInfo: ScepFailInfo.BadRequest+ });+ }++ const certBody = await certificateBodyDAL.findOne({ certId: certRequest.certificateId });+ if (!certBody || !certBody.encryptedCertificate) {+ return buildCertRepFailure({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ failInfo: ScepFailInfo.BadRequest+ });+ }++ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({+ projectId: profile.projectId,+ projectDAL,+ kmsService+ });+ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: certificateManagerKmsId });+ const decryptedCert = await kmsDecryptor({ cipherTextBlob: certBody.encryptedCertificate });++ const issuedCertDer = Buffer.from(new x509.X509Certificate(decryptedCert).rawData);++ return buildCertRepSuccess({+ issuedCertDer,+ recipientCertDer: transaction.signerCertDer,+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce+ });+ }++ default:+ return buildCertRepFailure({+ raCertDer,+ raPrivateKeyDer,+ transactionId: parsed.transactionId,+ recipientNonce: parsed.senderNonce,+ failInfo: ScepFailInfo.BadRequest+ });+ }+ };++ return {+ getCaCaps,+ getCaCert,+ handlePkiOperation+ };+};diff --git a/backend/src/ee/services/pki-scep/pki-scep-transaction-dal.ts b/backend/src/ee/services/pki-scep/pki-scep-transaction-dal.tsnew file mode 100644index 0000000000..9f1c1061ca--- /dev/null+++ b/backend/src/ee/services/pki-scep/pki-scep-transaction-dal.ts@@ -0,0 +1,40 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify } from "@app/lib/knex";++export type TScepTransactionDALFactory = ReturnType<typeof scepTransactionDALFactory>;++export const scepTransactionDALFactory = (db: TDbClient) => {+ const scepTransactionOrm = ormify(db, TableName.PkiScepTransaction);++ const findByProfileAndTransactionId = async (profileId: string, transactionId: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.PkiScepTransaction)+ .where({ profileId, transactionId })+ .first();++ return result || null;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find SCEP transaction by profileId and transactionId" });+ }+ };++ const pruneExpiredTransactions = async (tx?: Knex) => {+ try {+ const deletedCount = await (tx || db)(TableName.PkiScepTransaction).where("expiresAt", "<", new Date()).delete();++ return deletedCount;+ } catch (error) {+ throw new DatabaseError({ error, name: "Prune expired SCEP transactions" });+ }+ };++ return {+ ...scepTransactionOrm,+ findByProfileAndTransactionId,+ pruneExpiredTransactions+ };+};diff --git a/backend/src/ee/services/pki-scep/pki-scep-types.ts b/backend/src/ee/services/pki-scep/pki-scep-types.tsnew file mode 100644index 0000000000..135b4a3e7e--- /dev/null+++ b/backend/src/ee/services/pki-scep/pki-scep-types.ts@@ -0,0 +1,58 @@+export enum ScepMessageType {+ CertRep = "3",+ RenewalReq = "17",+ PKCSReq = "19",+ GetCertInitial = "20"+}++export enum ScepPkiStatus {+ SUCCESS = "0",+ FAILURE = "2",+ PENDING = "3"+}++export enum ScepFailInfo {+ BadAlg = "0",+ BadMessageCheck = "1",+ BadRequest = "2",+ BadTime = "3",+ BadCertId = "4"+}++export const SCEP_OIDS = {+ transactionId: "2.16.840.1.113733.1.9.7",+ messageType: "2.16.840.1.113733.1.9.2",+ pkiStatus: "2.16.840.1.113733.1.9.3",+ failInfo: "2.16.840.1.113733.1.9.4",+ senderNonce: "2.16.840.1.113733.1.9.5",+ recipientNonce: "2.16.840.1.113733.1.9.6"+} as const;++export const CIPHER_OID_MAP: Record<string, { algorithm: string; keyLength: number; ivLength: number }> = {+ "2.16.840.1.101.3.4.1.2": { algorithm: "aes-128-cbc", keyLength: 16, ivLength: 16 }, // AES-128-CBC+ "2.16.840.1.101.3.4.1.42": { algorithm: "aes-256-cbc", keyLength: 32, ivLength: 16 }, // AES-256-CBC+ "1.2.840.113549.3.7": { algorithm: "des-ede3-cbc", keyLength: 24, ivLength: 8 } // 3DES-CBC (DES-EDE3-CBC)+};++export interface TParsedScepMessage {+ messageType: ScepMessageType;+ transactionId: string;+ senderNonce: Buffer;+ signerCertDer: Buffer;+ csr?: Buffer;+ clientCipherOid?: string;+}++export type TGetCaCapsDTO = {+ profileId: string;+};++export type TGetCaCertDTO = {+ profileId: string;+};++export type THandlePkiOperationDTO = {+ profileId: string;+ message: Buffer;+ clientIp: string;+};diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.tsindex 961d05b36f..b155a12dfb 100644--- a/backend/src/server/plugins/auth/inject-identity.ts+++ b/backend/src/server/plugins/auth/inject-identity.ts@@ -150,7 +150,7 @@ export const injectIdentity = fp(return;}- if (req.url.includes(".well-known/est") || req.url.includes("/api/v3/auth/")) {+ if (req.url.includes(".well-known/est") || req.url.includes("/scep/") || req.url.includes("/api/v3/auth/")) {return;}diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 500891120e..635b36d091 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -11,6 +11,7 @@ import {registerRfc9728ProtectedResourceMetadataRouter} from "@app/ee/routes/ai/mcp-endpoint-metadata-router";import { registerCertificateEstRouter } from "@app/ee/routes/est/certificate-est-router";+import { registerPkiScepRouter } from "@app/ee/routes/scep/pki-scep-router";import { registerV1EERoutes } from "@app/ee/routes/v1";import { registerV2EERoutes } from "@app/ee/routes/v2";import {@@ -118,6 +119,8 @@ import { pkiDiscoveryQueueFactory } from "@app/ee/services/pki-discovery/pki-disimport { pkiDiscoveryScanHistoryDALFactory } from "@app/ee/services/pki-discovery/pki-discovery-scan-history-dal";import { pkiDiscoveryServiceFactory } from "@app/ee/services/pki-discovery/pki-discovery-service";import { pkiInstallationServiceFactory } from "@app/ee/services/pki-discovery/pki-installation-service";+import { pkiScepServiceFactory } from "@app/ee/services/pki-scep/pki-scep-service";+import { scepTransactionDALFactory } from "@app/ee/services/pki-scep/pki-scep-transaction-dal";import { projectEventsServiceFactory } from "@app/ee/services/project-events/project-events-service";import { projectEventsSSEServiceFactory } from "@app/ee/services/project-events/project-events-sse-service";import { projectTemplateDALFactory } from "@app/ee/services/project-template/project-template-dal";@@ -265,6 +268,7 @@ import { convertorServiceFactory } from "@app/services/convertor/convertor-serviimport { acmeEnrollmentConfigDALFactory } from "@app/services/enrollment-config/acme-enrollment-config-dal";import { apiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";import { estEnrollmentConfigDALFactory } from "@app/services/enrollment-config/est-enrollment-config-dal";+import { scepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-dal";import { externalGroupOrgRoleMappingDALFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-dal";import { externalGroupOrgRoleMappingServiceFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-service";import { externalMigrationQueueFactory } from "@app/services/external-migration/external-migration-queue";@@ -1222,6 +1226,8 @@ export const registerRoutes = async (const apiEnrollmentConfigDAL = apiEnrollmentConfigDALFactory(db);const estEnrollmentConfigDAL = estEnrollmentConfigDALFactory(db);const acmeEnrollmentConfigDAL = acmeEnrollmentConfigDALFactory(db);+ const scepEnrollmentConfigDAL = scepEnrollmentConfigDALFactory(db);+ const scepTransactionDAL = scepTransactionDALFactory(db);const acmeAccountDAL = pkiAcmeAccountDALFactory(db);const acmeOrderDAL = pkiAcmeOrderDALFactory(db);const acmeAuthDAL = pkiAcmeAuthDALFactory(db);@@ -1335,6 +1341,7 @@ export const registerRoutes = async (apiEnrollmentConfigDAL,estEnrollmentConfigDAL,acmeEnrollmentConfigDAL,+ scepEnrollmentConfigDAL,certificateBodyDAL,certificateSecretDAL,certificateAuthorityDAL,@@ -2122,6 +2129,7 @@ export const registerRoutes = async (approvalRequestDAL,approvalRequestGrantsDAL,certificateRequestDAL,+ scepTransactionDAL,queueJobsDAL});@@ -2558,6 +2566,22 @@ export const registerRoutes = async (certificatePolicyDAL});+ const pkiScepService = pkiScepServiceFactory({+ certificateV3Service,+ certificateProfileDAL,+ scepEnrollmentConfigDAL,+ scepTransactionDAL,+ certificateAuthorityDAL,+ certificateAuthorityCertDAL,+ certificateRequestDAL,+ certificateBodyDAL,+ projectDAL,+ kmsService,+ licenseService,+ certificatePolicyDAL,+ auditLogService+ });+const acmeChallengeService = pkiAcmeChallengeServiceFactory({acmeChallengeDAL,auditLogService@@ -3030,6 +3054,7 @@ export const registerRoutes = async (certificateAuthorityCrl: certificateAuthorityCrlService,certificateEst: certificateEstService,pkiAcme: pkiAcmeService,+ pkiScep: pkiScepService,pit: pitService,pkiAlert: pkiAlertService,pkiCollection: pkiCollectionService,@@ -3201,6 +3226,7 @@ export const registerRoutes = async (// register special routesawait server.register(registerCertificateEstRouter, { prefix: "/.well-known/est" });+ await server.register(registerPkiScepRouter, { prefix: "/scep" });await server.register(registerMcpEndpointMetadataRouter, { prefix: "/mcp-endpoints" });await server.register(registerMcpEndpointAuthServerMetadataRouter, {prefix: "/.well-known/oauth-authorization-server"diff --git a/backend/src/server/routes/v1/certificate-profiles-router.ts b/backend/src/server/routes/v1/certificate-profiles-router.tsindex c510f4aac9..37a53e8c75 100644--- a/backend/src/server/routes/v1/certificate-profiles-router.ts+++ b/backend/src/server/routes/v1/certificate-profiles-router.ts@@ -85,6 +85,13 @@ export const registerCertificateProfilesRouter = async (skipEabBinding: z.boolean().optional()}).optional(),+ scepConfig: z+ .object({+ challengePassword: z.string().min(8),+ includeCaCertInResponse: z.boolean().optional(),+ allowCertBasedRenewal: z.boolean().optional()+ })+ .optional(),externalConfigs: ExternalConfigUnionSchema,defaults: z.object({@@ -155,34 +162,56 @@ export const registerCertificateProfilesRouter = async (.refine((data) => {if (data.enrollmentType === EnrollmentType.EST) {- return !data.apiConfig && !data.acmeConfig;+ return !data.apiConfig && !data.acmeConfig && !data.scepConfig;}return true;},{- message: "EST enrollment type cannot have API or ACME configuration"+ message: "EST enrollment type cannot have API, ACME, or SCEP configuration"}).refine((data) => {if (data.enrollmentType === EnrollmentType.API) {- return !data.estConfig && !data.acmeConfig;+ return !data.estConfig && !data.acmeConfig && !data.scepConfig;}return true;},{- message: "API enrollment type cannot have EST or ACME configuration"+ message: "API enrollment type cannot have EST, ACME, or SCEP configuration"}).refine((data) => {if (data.enrollmentType === EnrollmentType.ACME) {- return !data.estConfig && !data.apiConfig;+ return !data.estConfig && !data.apiConfig && !data.scepConfig;+ }+ return true;+ },+ {+ message: "ACME enrollment type cannot have EST, API, or SCEP configuration"+ }+ )+ .refine(+ (data) => {+ if (data.enrollmentType === EnrollmentType.SCEP) {+ return !!data.scepConfig?.challengePassword;+ }+ return true;+ },+ {+ message: "SCEP enrollment type requires SCEP configuration with a challenge password"+ }+ )+ .refine(+ (data) => {+ if (data.enrollmentType === EnrollmentType.SCEP) {+ return !data.estConfig && !data.apiConfig && !data.acmeConfig;}return true;},{- message: "ACME enrollment type cannot have EST or API configuration"+ message: "SCEP enrollment type cannot have EST, API, or ACME configuration"}).refine(@@ -321,6 +350,16 @@ export const registerCertificateProfilesRouter = async (skipEabBinding: z.boolean().optional()}).optional(),+ scepConfig: z+ .object({+ id: z.string(),+ scepEndpointUrl: z.string(),+ raCertificatePem: z.string(),+ raCertExpiresAt: z.date(),+ includeCaCertInResponse: z.boolean(),+ allowCertBasedRenewal: z.boolean()+ })+ .optional(),externalConfigs: ExternalConfigUnionSchema,defaults: CertificateProfileDefaultsResponseSchema}).array(),@@ -413,6 +452,16 @@ export const registerCertificateProfilesRouter = async (skipEabBinding: z.boolean().optional()}).optional(),+ scepConfig: z+ .object({+ id: z.string(),+ scepEndpointUrl: z.string(),+ raCertificatePem: z.string(),+ raCertExpiresAt: z.date(),+ includeCaCertInResponse: z.boolean(),+ allowCertBasedRenewal: z.boolean()+ })+ .optional(),externalConfigs: ExternalConfigUnionSchema})})@@ -527,6 +576,13 @@ export const registerCertificateProfilesRouter = async (skipEabBinding: z.boolean().optional()}).optional(),+ scepConfig: z+ .object({+ challengePassword: z.string().min(8).optional(),+ includeCaCertInResponse: z.boolean().optional(),+ allowCertBasedRenewal: z.boolean().optional()+ })+ .optional(),externalConfigs: ExternalConfigUnionSchema,defaults: z.object({diff --git a/backend/src/services/auth/auth-type.ts b/backend/src/services/auth/auth-type.tsindex d04465871f..280433ffa4 100644--- a/backend/src/services/auth/auth-type.ts+++ b/backend/src/services/auth/auth-type.ts@@ -44,6 +44,7 @@ export enum ActorType { // would extend to AWS, Azure, ...ACME_PROFILE = "acmeProfile",ACME_ACCOUNT = "acmeAccount",EST_ACCOUNT = "estAccount",+ SCEP_ACCOUNT = "scepAccount",UNKNOWN_USER = "unknownUser"}diff --git a/backend/src/services/certificate-profile/certificate-profile-dal.ts b/backend/src/services/certificate-profile/certificate-profile-dal.tsindex 3e58a154c0..b0ba1f02c7 100644--- a/backend/src/services/certificate-profile/certificate-profile-dal.ts+++ b/backend/src/services/certificate-profile/certificate-profile-dal.ts@@ -159,6 +159,11 @@ export const certificateProfileDALFactory = (db: TDbClient) => {`${TableName.PkiCertificateProfile}.acmeConfigId`,`${TableName.PkiAcmeEnrollmentConfig}.id`)+ .leftJoin(+ TableName.PkiScepEnrollmentConfig,+ `${TableName.PkiCertificateProfile}.scepConfigId`,+ `${TableName.PkiScepEnrollmentConfig}.id`+ ).select(selectAllTableCols(TableName.PkiCertificateProfile)).select(db.ref("id").withSchema(TableName.Project).as("projectId"),@@ -189,7 +194,18 @@ export const certificateProfileDALFactory = (db: TDbClient) => {.ref("skipDnsOwnershipVerification").withSchema(TableName.PkiAcmeEnrollmentConfig).as("acmeConfigSkipDnsOwnershipVerification"),- db.ref("skipEabBinding").withSchema(TableName.PkiAcmeEnrollmentConfig).as("acmeConfigSkipEabBinding")+ db.ref("skipEabBinding").withSchema(TableName.PkiAcmeEnrollmentConfig).as("acmeConfigSkipEabBinding"),+ db.ref("id").withSchema(TableName.PkiScepEnrollmentConfig).as("scepConfigDbId"),+ db.ref("raCertificate").withSchema(TableName.PkiScepEnrollmentConfig).as("scepConfigRaCertificate"),+ db.ref("raCertExpiresAt").withSchema(TableName.PkiScepEnrollmentConfig).as("scepConfigRaCertExpiresAt"),+ db+ .ref("includeCaCertInResponse")+ .withSchema(TableName.PkiScepEnrollmentConfig)+ .as("scepConfigIncludeCaCertInResponse"),+ db+ .ref("allowCertBasedRenewal")+ .withSchema(TableName.PkiScepEnrollmentConfig)+ .as("scepConfigAllowCertBasedRenewal")).where(`${TableName.PkiCertificateProfile}.id`, id).first();@@ -225,6 +241,16 @@ export const certificateProfileDALFactory = (db: TDbClient) => {} as TCertificateProfileWithConfigs["acmeConfig"]): undefined;+ const scepConfig = result.scepConfigDbId+ ? ({+ id: result.scepConfigDbId,+ raCertificatePem: result.scepConfigRaCertificate,+ raCertExpiresAt: result.scepConfigRaCertExpiresAt,+ includeCaCertInResponse: result.scepConfigIncludeCaCertInResponse ?? true,+ allowCertBasedRenewal: result.scepConfigAllowCertBasedRenewal ?? true+ } as TCertificateProfileWithConfigs["scepConfig"])+ : undefined;+const certificateAuthority = result.caId? ({id: result.caId,@@ -263,6 +289,7 @@ export const certificateProfileDALFactory = (db: TDbClient) => {estConfigId: result.estConfigId,apiConfigId: result.apiConfigId,acmeConfigId: result.acmeConfigId,+ scepConfigId: result.scepConfigId,externalConfigs: result.externalConfigs? (JSON.parse(result.externalConfigs) as Record<string, unknown>): null,@@ -272,6 +299,7 @@ export const certificateProfileDALFactory = (db: TDbClient) => {estConfig,apiConfig,acmeConfig,+ scepConfig,project,certificateAuthority,certificatePolicy@@ -367,6 +395,11 @@ export const certificateProfileDALFactory = (db: TDbClient) => {`${TableName.PkiCertificateProfile}.acmeConfigId`,`${TableName.PkiAcmeEnrollmentConfig}.id`)+ .leftJoin(+ TableName.PkiScepEnrollmentConfig,+ `${TableName.PkiCertificateProfile}.scepConfigId`,+ `${TableName.PkiScepEnrollmentConfig}.id`+ ).select(selectAllTableCols(TableName.PkiCertificateProfile)).select(db.ref("id").withSchema(TableName.CertificateAuthority).as("caId"),@@ -389,7 +422,15 @@ export const certificateProfileDALFactory = (db: TDbClient) => {.ref("skipDnsOwnershipVerification").withSchema(TableName.PkiAcmeEnrollmentConfig).as("acmeSkipDnsOwnershipVerification"),- db.ref("skipEabBinding").withSchema(TableName.PkiAcmeEnrollmentConfig).as("acmeSkipEabBinding")+ db.ref("skipEabBinding").withSchema(TableName.PkiAcmeEnrollmentConfig).as("acmeSkipEabBinding"),+ db.ref("id").withSchema(TableName.PkiScepEnrollmentConfig).as("scepId"),+ db.ref("raCertificate").withSchema(TableName.PkiScepEnrollmentConfig).as("scepRaCertificate"),+ db.ref("raCertExpiresAt").withSchema(TableName.PkiScepEnrollmentConfig).as("scepRaCertExpiresAt"),+ db+ .ref("includeCaCertInResponse")+ .withSchema(TableName.PkiScepEnrollmentConfig)+ .as("scepIncludeCaCertInResponse"),+ db.ref("allowCertBasedRenewal").withSchema(TableName.PkiScepEnrollmentConfig).as("scepAllowCertBasedRenewal"));if (processedRules) {@@ -432,6 +473,16 @@ export const certificateProfileDALFactory = (db: TDbClient) => {}: undefined;+ const scepConfigResult = result.scepId+ ? {+ id: result.scepId as string,+ raCertificatePem: result.scepRaCertificate as string,+ raCertExpiresAt: result.scepRaCertExpiresAt as Date,+ includeCaCertInResponse: (result.scepIncludeCaCertInResponse as boolean) ?? true,+ allowCertBasedRenewal: (result.scepAllowCertBasedRenewal as boolean) ?? true+ }+ : undefined;+const certificateAuthority = result.caId? {id: result.caId as string,@@ -454,6 +505,7 @@ export const certificateProfileDALFactory = (db: TDbClient) => {estConfigId: result.estConfigId,apiConfigId: result.apiConfigId,acmeConfigId: result.acmeConfigId,+ scepConfigId: result.scepConfigId,externalConfigs: result.externalConfigs? (JSON.parse(result.externalConfigs as string) as Record<string, unknown>): null,@@ -463,6 +515,7 @@ export const certificateProfileDALFactory = (db: TDbClient) => {estConfig,apiConfig,acmeConfig,+ scepConfig: scepConfigResult,certificateAuthority};diff --git a/backend/src/services/certificate-profile/certificate-profile-service.test.ts b/backend/src/services/certificate-profile/certificate-profile-service.test.tsindex 6129227682..3311627c0a 100644--- a/backend/src/services/certificate-profile/certificate-profile-service.test.ts+++ b/backend/src/services/certificate-profile/certificate-profile-service.test.ts@@ -17,6 +17,7 @@ import type { TCertificatePolicyDALFactory } from "../certificate-policy/certifiimport { TAcmeEnrollmentConfigDALFactory } from "../enrollment-config/acme-enrollment-config-dal";import type { TApiEnrollmentConfigDALFactory } from "../enrollment-config/api-enrollment-config-dal";import type { TEstEnrollmentConfigDALFactory } from "../enrollment-config/est-enrollment-config-dal";+import type { TScepEnrollmentConfigDALFactory } from "../enrollment-config/scep-enrollment-config-dal";import type { TKmsServiceFactory } from "../kms/kms-service";import type { TProjectDALFactory } from "../project/project-dal";import type { TCertificateProfileDALFactory } from "./certificate-profile-dal";@@ -166,6 +167,17 @@ describe("CertificateProfileService", () => {delete: vi.fn()} as unknown as TAcmeEnrollmentConfigDALFactory;+ const mockScepEnrollmentConfigDAL = {+ create: vi.fn().mockResolvedValue({ id: "scep-config-123" }),+ findById: vi.fn(),+ updateById: vi.fn(),+ transaction: vi.fn(),+ find: vi.fn(),+ findOne: vi.fn(),+ update: vi.fn(),+ delete: vi.fn()+ } as unknown as TScepEnrollmentConfigDALFactory;+const mockPermissionService = {getProjectPermission: vi.fn().mockResolvedValue({permission: {@@ -258,6 +270,7 @@ describe("CertificateProfileService", () => {apiEnrollmentConfigDAL: mockApiEnrollmentConfigDAL,estEnrollmentConfigDAL: mockEstEnrollmentConfigDAL,acmeEnrollmentConfigDAL: mockAcmeEnrollmentConfigDAL,+ scepEnrollmentConfigDAL: mockScepEnrollmentConfigDAL,certificateBodyDAL: mockCertificateBodyDAL,certificateSecretDAL: mockCertificateSecretDAL,certificateAuthorityDAL: mockCertificateAuthorityDAL,diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.tsindex d9857fd999..3d5adfd061 100644--- a/backend/src/services/certificate-profile/certificate-profile-service.ts+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts@@ -27,8 +27,14 @@ import { TCertificatePolicyServiceFactory } from "../certificate-policy/certificimport { TCertificateRequest } from "../certificate-policy/certificate-policy-types";import { TAcmeEnrollmentConfigDALFactory } from "../enrollment-config/acme-enrollment-config-dal";import { TApiEnrollmentConfigDALFactory } from "../enrollment-config/api-enrollment-config-dal";-import { TAcmeConfigData, TApiConfigData, TEstConfigData } from "../enrollment-config/enrollment-config-types";+import {+ TAcmeConfigData,+ TApiConfigData,+ TEstConfigData,+ TScepConfigData+} from "../enrollment-config/enrollment-config-types";import { TEstEnrollmentConfigDALFactory } from "../enrollment-config/est-enrollment-config-dal";+import { TScepEnrollmentConfigDALFactory } from "../enrollment-config/scep-enrollment-config-dal";import { TKmsServiceFactory } from "../kms/kms-service";import { TProjectDALFactory } from "../project/project-dal";import { getProjectKmsCertificateKeyId } from "../project/project-fns";@@ -218,11 +224,12 @@ const decryptCaChain = async (export type TCertificateProfileCreateData = Omit<TCertificateProfileInsert,- "estConfigId" | "apiConfigId" | "acmeConfigId"+ "estConfigId" | "apiConfigId" | "acmeConfigId" | "scepConfigId"> & {estConfig?: TEstConfigData;apiConfig?: TApiConfigData;acmeConfig?: TAcmeConfigData;+ scepConfig?: TScepConfigData;};type TCertificateProfileServiceFactoryDep = {@@ -232,6 +239,7 @@ type TCertificateProfileServiceFactoryDep = {apiEnrollmentConfigDAL: TApiEnrollmentConfigDALFactory;estEnrollmentConfigDAL: TEstEnrollmentConfigDALFactory;acmeEnrollmentConfigDAL: TAcmeEnrollmentConfigDALFactory;+ scepEnrollmentConfigDAL: TScepEnrollmentConfigDALFactory;certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;@@ -274,6 +282,7 @@ export const certificateProfileServiceFactory = ({apiEnrollmentConfigDAL,estEnrollmentConfigDAL,acmeEnrollmentConfigDAL,+ scepEnrollmentConfigDAL,certificateBodyDAL,certificateSecretDAL,certificateAuthorityDAL,@@ -392,12 +401,59 @@ export const certificateProfileServiceFactory = ({});}}+ if (data.enrollmentType === EnrollmentType.SCEP && !data.scepConfig) {+ throw new ForbiddenRequestError({+ message: "SCEP enrollment requires SCEP configuration"+ });+ }++ // Perform crypto operations before the transaction to avoid holding DB connections+ let precomputedScepConfig:+ | {+ encryptedRaPrivateKey: Buffer;+ raCertificatePem: string;+ raCertExpiresAt: Date;+ hashedChallengePassword: string;+ includeCaCertInResponse: boolean;+ allowCertBasedRenewal: boolean;+ }+ | undefined;++ if (data.enrollmentType === EnrollmentType.SCEP && data.scepConfig) {+ const { generateRaCertificate } = await import("@app/ee/services/pki-scep/pki-scep-fns");+ const raCert = await generateRaCertificate(data.slug);++ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({+ projectId,+ projectDAL,+ kmsService+ });+ const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKmsId });+ const { cipherTextBlob: encryptedRaPrivateKey } = await kmsEncryptor({+ plainText: Buffer.from(raCert.privateKeyDer)+ });++ const appCfg = getConfig();+ const hashedChallengePassword = await crypto+ .hashing()+ .createHash(data.scepConfig.challengePassword, appCfg.SALT_ROUNDS);++ precomputedScepConfig = {+ encryptedRaPrivateKey,+ raCertificatePem: raCert.certificatePem,+ raCertExpiresAt: raCert.expiresAt,+ hashedChallengePassword,+ includeCaCertInResponse: data.scepConfig.includeCaCertInResponse ?? true,+ allowCertBasedRenewal: data.scepConfig.allowCertBasedRenewal ?? true+ };+ }// Create enrollment configs and profileconst profile = await certificateProfileDAL.transaction(async (tx) => {let estConfigId: string | null = null;let apiConfigId: string | null = null;let acmeConfigId: string | null = null;+ let scepConfigId: string | null = null;if (data.enrollmentType === EnrollmentType.EST && data.estConfig) {const appCfg = getConfig();@@ -444,10 +500,23 @@ export const certificateProfileServiceFactory = ({tx);acmeConfigId = acmeConfig.id;+ } else if (precomputedScepConfig) {+ const scepConfig = await scepEnrollmentConfigDAL.create(+ {+ encryptedRaPrivateKey: precomputedScepConfig.encryptedRaPrivateKey,+ raCertificate: precomputedScepConfig.raCertificatePem,+ raCertExpiresAt: precomputedScepConfig.raCertExpiresAt,+ hashedChallengePassword: precomputedScepConfig.hashedChallengePassword,+ includeCaCertInResponse: precomputedScepConfig.includeCaCertInResponse,+ allowCertBasedRenewal: precomputedScepConfig.allowCertBasedRenewal+ },+ tx+ );+ scepConfigId = scepConfig.id;}// Create the profile with the created config IDs- const { estConfig, apiConfig, acmeConfig, ...profileData } = data;+ const { estConfig, apiConfig, acmeConfig, scepConfig: profileScepConfig, ...profileData } = data;const profileResult = await certificateProfileDAL.create({...profileData,@@ -455,6 +524,7 @@ export const certificateProfileServiceFactory = ({estConfigId,apiConfigId,acmeConfigId,+ scepConfigId,externalConfigs: data.externalConfigs},tx@@ -584,7 +654,7 @@ export const certificateProfileServiceFactory = ({const updatedData =finalIssuerType === IssuerType.SELF_SIGNED && existingProfile.caId ? { ...data, caId: null } : data;- const { estConfig, apiConfig, acmeConfig, ...profileUpdateData } = updatedData;+ const { estConfig, apiConfig, acmeConfig, scepConfig, ...profileUpdateData } = updatedData;const updatedProfile = await certificateProfileDAL.transaction(async (tx) => {if (estConfig && existingProfile.estConfigId) {@@ -639,6 +709,29 @@ export const certificateProfileServiceFactory = ({}}+ if (scepConfig && existingProfile.scepConfigId) {+ const scepUpdateData: {+ hashedChallengePassword?: string;+ includeCaCertInResponse?: boolean;+ allowCertBasedRenewal?: boolean;+ } = {};++ if (scepConfig.challengePassword) {+ scepUpdateData.hashedChallengePassword = await crypto+ .hashing()+ .createHash(scepConfig.challengePassword, getConfig().SALT_ROUNDS);+ }+ if (scepConfig.includeCaCertInResponse !== undefined) {+ scepUpdateData.includeCaCertInResponse = scepConfig.includeCaCertInResponse;+ }+ if (scepConfig.allowCertBasedRenewal !== undefined) {+ scepUpdateData.allowCertBasedRenewal = scepConfig.allowCertBasedRenewal;+ }+ if (Object.keys(scepUpdateData).length > 0) {+ await scepEnrollmentConfigDAL.updateById(existingProfile.scepConfigId, scepUpdateData, tx);+ }+ }+const profileResult = await certificateProfileDAL.updateById(profileId, profileUpdateData, tx);return profileResult;});@@ -742,6 +835,12 @@ export const certificateProfileServiceFactory = ({}}+ if (profile.enrollmentType === EnrollmentType.SCEP && profile.scepConfig) {+ const appCfg = getConfig();+ const siteUrl = appCfg.SITE_URL ?? "";+ profile.scepConfig.scepEndpointUrl = `${siteUrl}/scep/${profile.id}/pkiclient.exe`;+ }+// Parse externalConfigs from JSON string to object if it existslet parsedExternalConfigs: Record<string, unknown> | null = null;if (profile.externalConfigs && typeof profile.externalConfigs === "string") {@@ -908,12 +1007,17 @@ export const certificateProfileServiceFactory = ({}const converted = convertDalToService(profileWithConfigs);+ const appCfg = getConfig();+ const siteUrl = appCfg.SITE_URL ?? "";const result: TCertificateProfileWithConfigs = {...converted,estConfig: decryptedEstConfig,apiConfig: profileWithConfigs.apiConfig,acmeConfig: profileWithConfigs.acmeConfig? { ...profileWithConfigs.acmeConfig, directoryUrl: buildUrl(profile.id, "/directory") }+ : undefined,+ scepConfig: profileWithConfigs.scepConfig+ ? { ...profileWithConfigs.scepConfig, scepEndpointUrl: `${siteUrl}/scep/${profile.id}/pkiclient.exe` }: undefined};diff --git a/backend/src/services/certificate-profile/certificate-profile-types.ts b/backend/src/services/certificate-profile/certificate-profile-types.tsindex f591b0e655..5d38505e46 100644--- a/backend/src/services/certificate-profile/certificate-profile-types.ts+++ b/backend/src/services/certificate-profile/certificate-profile-types.ts@@ -14,7 +14,8 @@ import {export enum EnrollmentType {API = "api",EST = "est",- ACME = "acme"+ ACME = "acme",+ SCEP = "scep"}export enum IssuerType {@@ -78,6 +79,11 @@ export type TCertificateProfileUpdate = Omit<skipDnsOwnershipVerification?: boolean;skipEabBinding?: boolean;};+ scepConfig?: {+ challengePassword?: string;+ includeCaCertInResponse?: boolean;+ allowCertBasedRenewal?: boolean;+ };};export type TCertificateProfileWithConfigs = TCertificateProfile & {@@ -117,6 +123,14 @@ export type TCertificateProfileWithConfigs = TCertificateProfile & {skipDnsOwnershipVerification?: boolean;skipEabBinding?: boolean;};+ scepConfig?: {+ id: string;+ scepEndpointUrl: string;+ raCertificatePem: string;+ raCertExpiresAt: Date;+ includeCaCertInResponse: boolean;+ allowCertBasedRenewal: boolean;+ };};export interface TCertificateProfileCertificate {diff --git a/backend/src/services/certificate-request/certificate-request-service.ts b/backend/src/services/certificate-request/certificate-request-service.tsindex e5bd543d84..cbf12187af 100644--- a/backend/src/services/certificate-request/certificate-request-service.ts+++ b/backend/src/services/certificate-request/certificate-request-service.ts@@ -136,7 +136,12 @@ export const certificateRequestServiceFactory = ({status,...requestData}: TCreateCertificateRequestDTO & { tx?: Knex }) => {- if (actor !== ActorType.ACME_ACCOUNT && actor !== ActorType.PLATFORM && actor !== ActorType.EST_ACCOUNT) {+ if (+ actor !== ActorType.ACME_ACCOUNT &&+ actor !== ActorType.PLATFORM &&+ actor !== ActorType.EST_ACCOUNT &&+ actor !== ActorType.SCEP_ACCOUNT+ ) {const { permission } = await permissionService.getProjectPermission({actor,actorId,diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.tsindex eb23031d5b..81e2731891 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts@@ -217,6 +217,15 @@ const validateProfileAndPermissions = async ({return profile;}+ if (actor === ActorType.SCEP_ACCOUNT && requiredEnrollmentType === EnrollmentType.SCEP) {+ if (actorId !== profile.id) {+ throw new ForbiddenRequestError({+ message: "SCEP profile mismatch"+ });+ }+ return profile;+ }+const { permission } = await permissionService.getProjectPermission({actor,actorId,@@ -699,7 +708,7 @@ export const certificateV3ServiceFactory = ({acmeAccountDAL,permissionService,requiredEnrollmentType: EnrollmentType.API,- isInternal: actor === ActorType.EST_ACCOUNT+ isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT});const approvalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](ApprovalPolicyType.CertRequest);@@ -1266,7 +1275,7 @@ export const certificateV3ServiceFactory = ({acmeAccountDAL,permissionService,requiredEnrollmentType: enrollmentType,- isInternal: actor === ActorType.EST_ACCOUNT+ isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT});if (!profile.caId) {@@ -1635,7 +1644,7 @@ export const certificateV3ServiceFactory = ({acmeAccountDAL,permissionService,requiredEnrollmentType: EnrollmentType.API,- isInternal: actor === ActorType.EST_ACCOUNT+ isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT});let certificateRequest: TCertificateRequest;diff --git a/backend/src/services/enrollment-config/enrollment-config-types.ts b/backend/src/services/enrollment-config/enrollment-config-types.tsindex ef4b6332b9..badf981a17 100644--- a/backend/src/services/enrollment-config/enrollment-config-types.ts+++ b/backend/src/services/enrollment-config/enrollment-config-types.ts@@ -13,6 +13,11 @@ import {TPkiEstEnrollmentConfigsInsert,TPkiEstEnrollmentConfigsUpdate} from "@app/db/schemas/pki-est-enrollment-configs";+import {+ TPkiScepEnrollmentConfigs,+ TPkiScepEnrollmentConfigsInsert,+ TPkiScepEnrollmentConfigsUpdate+} from "@app/db/schemas/pki-scep-enrollment-configs";export type TEstEnrollmentConfig = TPkiEstEnrollmentConfigs;export type TEstEnrollmentConfigInsert = TPkiEstEnrollmentConfigsInsert;@@ -41,3 +46,13 @@ export interface TAcmeConfigData {skipDnsOwnershipVerification?: boolean;skipEabBinding?: boolean;}++export type TScepEnrollmentConfig = TPkiScepEnrollmentConfigs;+export type TScepEnrollmentConfigInsert = TPkiScepEnrollmentConfigsInsert;+export type TScepEnrollmentConfigUpdate = TPkiScepEnrollmentConfigsUpdate;++export interface TScepConfigData {+ challengePassword: string;+ includeCaCertInResponse?: boolean;+ allowCertBasedRenewal?: boolean;+}diff --git a/backend/src/services/enrollment-config/scep-enrollment-config-dal.ts b/backend/src/services/enrollment-config/scep-enrollment-config-dal.tsnew file mode 100644index 0000000000..702e67d551--- /dev/null+++ b/backend/src/services/enrollment-config/scep-enrollment-config-dal.ts@@ -0,0 +1,11 @@+import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TScepEnrollmentConfigDALFactory = ReturnType<typeof scepEnrollmentConfigDALFactory>;++export const scepEnrollmentConfigDALFactory = (db: TDbClient) => {+ const scepEnrollmentConfigOrm = ormify(db, TableName.PkiScepEnrollmentConfig);++ return scepEnrollmentConfigOrm;+};diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.tsindex 92f053d63a..3bc04bac64 100644--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts@@ -1,4 +1,5 @@import { TAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";+import { TScepTransactionDALFactory } from "@app/ee/services/pki-scep/pki-scep-transaction-dal";import { TScimServiceFactory } from "@app/ee/services/scim/scim-types";import { TSnapshotDALFactory } from "@app/ee/services/secret-snapshot/snapshot-dal";import { TKeyValueStoreDALFactory } from "@app/keystore/key-value-store-dal";@@ -37,6 +38,7 @@ type TDailyResourceCleanUpQueueServiceFactoryDep = {approvalRequestDAL: Pick<TApprovalRequestDALFactory, "markExpiredRequests">;approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "markExpiredGrants">;certificateRequestDAL: Pick<TCertificateRequestDALFactory, "markExpiredApprovalRequests">;+ scepTransactionDAL: Pick<TScepTransactionDALFactory, "pruneExpiredTransactions">;queueJobsDAL: Pick<TQueueJobsDALFactory, "pruneQueueJobs">;};@@ -60,6 +62,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({approvalRequestDAL,approvalRequestGrantsDAL,certificateRequestDAL,+ scepTransactionDAL,queueJobsDAL}: TDailyResourceCleanUpQueueServiceFactoryDep) => {const appCfg = getConfig();@@ -90,6 +93,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({await userNotificationDAL.pruneNotifications();await keyValueStoreDAL.pruneExpiredKeys();await queueJobsDAL.pruneQueueJobs();+ await scepTransactionDAL.pruneExpiredTransactions();const expiredApprovalRequestIds = await approvalRequestDAL.markExpiredRequests();if (expiredApprovalRequestIds.length > 0) {await certificateRequestDAL.markExpiredApprovalRequests(expiredApprovalRequestIds);diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex 551376a19e..88fa1a4359 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -6,6 +6,7 @@ import {IdentityActor,KmipClientActor,PlatformActor,+ ScepAccountActor,ScimClientActor,ServiceActor,UnknownUserActor,@@ -116,7 +117,8 @@ export type TSecretModifiedEvent = {| AcmeAccountActor| AcmeProfileActor| KmipClientActor- | EstAccountActor;+ | EstAccountActor+ | ScepAccountActor;};};diff --git a/docs/docs.json b/docs/docs.jsonindex 2ae1bfd162..557e96ccb0 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -735,7 +735,8 @@"documentation/platform/pki/enrollment-methods/overview","documentation/platform/pki/enrollment-methods/api","documentation/platform/pki/enrollment-methods/acme",- "documentation/platform/pki/enrollment-methods/est"+ "documentation/platform/pki/enrollment-methods/est",+ "documentation/platform/pki/enrollment-methods/scep"]},{diff --git a/docs/documentation/platform/pki/enrollment-methods/overview.mdx b/docs/documentation/platform/pki/enrollment-methods/overview.mdxindex df203c35cc..9c881c5d07 100644--- a/docs/documentation/platform/pki/enrollment-methods/overview.mdx+++ b/docs/documentation/platform/pki/enrollment-methods/overview.mdx@@ -10,5 +10,6 @@ Refer to the documentation for each enrollment method below to learn more about- [API](/documentation/platform/pki/enrollment-methods/api): Enroll certificates via API.- [ACME](/documentation/platform/pki/enrollment-methods/acme): Enroll certificates using the ACME protocol.- [EST](/documentation/platform/pki/enrollment-methods/est): Enroll certificates using the EST protocol.+- [SCEP](/documentation/platform/pki/enrollment-methods/scep): Enroll certificates using the SCEP protocol.Note that beyond using an enrollment method, you can also deliver a certificate to a target destination using supported [certificate syncs](https://infisical.com/docs/documentation/platform/pki/certificate-syncs/overview).diff --git a/docs/documentation/platform/pki/enrollment-methods/scep.mdx b/docs/documentation/platform/pki/enrollment-methods/scep.mdxindex 977e7b388e..2fde69313b 100644--- a/docs/documentation/platform/pki/enrollment-methods/scep.mdx+++ b/docs/documentation/platform/pki/enrollment-methods/scep.mdx@@ -3,6 +3,184 @@ title: "Certificate Enrollment via SCEP"sidebarTitle: "SCEP"----<Info>- SCEP-based certificate enrollment is currently under development and will be included in a future release.-</Info>+## Concept++The SCEP enrollment method allows you to issue and manage certificates against a specific [certificate profile](/documentation/platform/pki/certificates/profiles) using the [SCEP protocol](https://en.wikipedia.org/wiki/Simple_Certificate_Enrollment_Protocol) (Simple Certificate Enrollment Protocol).+This method is suitable for provisioning certificates to network devices, mobile devices, printers, routers, and other endpoints that support the SCEP protocol.++Infisical's SCEP service is based on [RFC 8894](https://datatracker.ietf.org/doc/html/rfc8894) and implements the following operations:++- **GetCACaps**: returns the SCEP server's supported capabilities (algorithms, features).+- **GetCACert**: returns the RA (Registration Authority) certificate and the CA certificate chain in a PKCS#7 bundle.+- **PKIOperation**: processes certificate enrollment requests (PKCSReq), renewal requests (RenewalReq), and certificate polling (GetCertInitial).++These SCEP endpoints are exposed under the `/scep` path and structured as:++```+https://app.infisical.com/scep/{profile_id}/pkiclient.exe+```++For self-hosted Infisical instances, replace `app.infisical.com` with your instance's domain.++## Prerequisites++- A SCEP-compatible client (e.g., [sscep](https://github.com/certnanny/sscep)) or a network device with built-in SCEP support.+- A certificate profile with a **CA-issued** issuer type. Self-signed issuer types are not supported for SCEP.++<Note>+ SCEP enrollment requires an **Enterprise** plan.+</Note>++## Guide to Certificate Enrollment via SCEP++In the following steps, we walk through how to issue an X.509 certificate using the SCEP enrollment method.++<Steps>+ <Step title="Create a certificate profile with SCEP enrollment">+ Create a [certificate profile](/documentation/platform/pki/certificates/profiles) with **SCEP** selected as the enrollment method and fill in the SCEP-specific configuration.++ Here's some guidance on each SCEP-specific configuration field:++ - **Challenge Password**: A shared secret that SCEP clients must include in their certificate signing request (CSR) to authenticate with Infisical's SCEP server. Must be at least 8 characters.+ - **Include CA Cert in Response**: When enabled, the CA certificate chain is included alongside the RA certificate in the GetCACert response. Most SCEP clients expect this to be enabled (default: enabled).+ - **Allow Certificate-Based Renewal**: When enabled, devices that already hold a valid certificate issued by the same CA can renew their certificate without providing the challenge password (default: enabled).++ </Step>+ <Step title="Obtain the SCEP endpoint URL">+ Once the certificate profile is created, you can obtain the SCEP endpoint URL from the certificate profile details page.++ The SCEP endpoint URL follows the structure:++ ```+ https://app.infisical.com/scep/{profile_id}/pkiclient.exe+ ```++ Where `{profile_id}` is the UUID of the certificate profile. This is the URL you provide to your SCEP clients as the SCEP server URL.++ </Step>+ <Step title="Configure your SCEP client and enroll">+ Provide the **SCEP endpoint URL** and **challenge password** from the previous steps to your SCEP client.++ Below is an example using [sscep](https://github.com/certnanny/sscep), an open-source SCEP client.++ **1. Retrieve the CA/RA certificates:**++ ```bash+ sscep getca \+ -u https://app.infisical.com/scep/{profile_id}/pkiclient.exe \+ -c ca.pem+ ```++ This writes the RA certificate to `ca.pem-0` and the CA certificate to `ca.pem-1` (when "Include CA Cert in Response" is enabled).++ **2. Generate a device key and CSR with the challenge password:**++ The challenge password must be embedded in the CSR as a PKCS#9 attribute. Create an OpenSSL config file to include it:++ ```bash+ cat > device-csr.cnf << 'EOF'+ [req]+ default_bits = 2048+ prompt = no+ distinguished_name = dn+ attributes = req_attributes++ [dn]+ CN = my-device.example.com++ [req_attributes]+ challengePassword = your-challenge-password+ EOF++ # Generate the key and CSR+ openssl genrsa -out device.key 2048+ openssl req -new -key device.key -out device.csr -config device-csr.cnf+ ```++ **3. Create a self-signed certificate for the sscep signing identity:**++ sscep requires a local signing certificate to sign the SCEP request envelope:++ ```bash+ openssl x509 -req -in device.csr -signkey device.key \+ -out device-selfsigned.pem -days 1+ ```++ **4. Enroll via SCEP:**++ ```bash+ sscep enroll \+ -u https://app.infisical.com/scep/{profile_id}/pkiclient.exe \+ -c ca.pem-0 \+ -k device.key \+ -r device.csr \+ -l device-cert.pem \+ -K device.key \+ -O device-selfsigned.pem \+ -E aes256 \+ -S sha256+ ```++ On success, the issued certificate is written to `device-cert.pem`.++ <Note>+ Flag reference for the enroll command:+ - `-c ca.pem-0` is the RA certificate from step 1+ - `-K` / `-O` are the signing key and self-signed certificate used to sign the SCEP message envelope+ - `-E aes256` selects AES-256-CBC encryption+ - `-S sha256` selects SHA-256 for the message digest+ </Note>++ <Note>+ SCEP uses CMS/PKCS#7 encrypted messages to protect the certificate request in transit. The challenge password is included inside the encrypted envelope and is never sent in plaintext over the network.+ </Note>++ </Step>+ <Step title="Renew a certificate via SCEP (optional)">+ If **Allow Certificate-Based Renewal** is enabled on the certificate profile, devices that already hold a valid certificate issued by the same CA can renew without the challenge password.++ The device signs the SCEP request with its existing issued certificate instead of a self-signed one. Using sscep:++ ```bash+ # Generate a new CSR (no challenge password needed for renewal)+ openssl req -new -key device.key -out device-renew.csr \+ -subj "/CN=my-device.example.com"++ # Enroll using the issued certificate as the signing identity+ sscep enroll \+ -u https://app.infisical.com/scep/{profile_id}/pkiclient.exe \+ -c ca.pem-0 \+ -k device.key \+ -r device-renew.csr \+ -l device-renewed.pem \+ -K device.key \+ -O device-cert.pem \+ -E aes256 \+ -S sha256+ ```++ The key difference from the initial enrollment is `-O device-cert.pem` (the previously issued certificate) instead of `-O device-selfsigned.pem`. On success, the renewed certificate is written to `device-renewed.pem`.+ </Step>+</Steps>++## Supported Algorithms++Infisical's SCEP server supports the following algorithms for the CMS message exchange:++- **Encryption**: AES-256-CBC, AES-128-CBC, 3DES-CBC (DES-EDE3-CBC)+- **Signing**: SHA-256, SHA-384, SHA-512, SHA-1+++## FAQ++<AccordionGroup>+ <Accordion title="What is the RA certificate?">+ The RA (Registration Authority) certificate is automatically generated when you create a SCEP-enabled certificate profile. It is used to encrypt and sign the SCEP message exchange between the client and server. The RA certificate has a 10-year validity and is separate from your CA certificate.+ </Accordion>+ <Accordion title="Can devices renew their certificates without the challenge password?">+ Yes, if **Allow Certificate-Based Renewal** is enabled on the certificate profile. Devices that already hold a valid certificate issued by the same CA can submit a renewal request (RenewalReq) signed with their existing certificate, without needing the challenge password.+ </Accordion>+ <Accordion title="What happens if my SCEP client uses an unsupported encryption algorithm?">+ The server will reject the request with a `400 Bad Request` error indicating the unsupported cipher OID. Configure your client to use AES-256-CBC (`-E aes256` in sscep) for compatibility.+ </Accordion>+</AccordionGroup>diff --git a/frontend/src/hooks/api/certificateProfiles/types.ts b/frontend/src/hooks/api/certificateProfiles/types.tsindex f4739a1e03..76c432a91e 100644--- a/frontend/src/hooks/api/certificateProfiles/types.ts+++ b/frontend/src/hooks/api/certificateProfiles/types.ts@@ -1,7 +1,8 @@export enum EnrollmentType {API = "api",EST = "est",- ACME = "acme"+ ACME = "acme",+ SCEP = "scep"}export enum IssuerType {@@ -81,6 +82,14 @@ export type TCertificateProfileWithDetails = TCertificateProfile & {skipDnsOwnershipVerification?: boolean;skipEabBinding?: boolean;};+ scepConfig?: {+ id: string;+ scepEndpointUrl: string;+ raCertificatePem: string;+ raCertExpiresAt: string;+ includeCaCertInResponse: boolean;+ allowCertBasedRenewal: boolean;+ };};export type TCreateCertificateProfileDTO = {@@ -104,6 +113,11 @@ export type TCreateCertificateProfileDTO = {skipDnsOwnershipVerification?: boolean;skipEabBinding?: boolean;};+ scepConfig?: {+ challengePassword: string;+ includeCaCertInResponse?: boolean;+ allowCertBasedRenewal?: boolean;+ };externalConfigs?: Record<string, unknown> | null;defaults?: TCertificateProfileDefaults | null;};@@ -127,6 +141,11 @@ export type TUpdateCertificateProfileDTO = {skipDnsOwnershipVerification?: boolean;skipEabBinding?: boolean;};+ scepConfig?: {+ challengePassword?: string;+ includeCaCertInResponse?: boolean;+ allowCertBasedRenewal?: boolean;+ };externalConfigs?: Record<string, unknown> | null;defaults?: TCertificateProfileDefaults | null;};diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificateProfilesTab.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificateProfilesTab.tsxindex e5498e266a..75be970be4 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificateProfilesTab.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificateProfilesTab.tsx@@ -13,6 +13,7 @@ import {} from "@app/context/ProjectPermissionContext/types";import { usePopUp } from "@app/hooks";import {+ EnrollmentType,TCertificateProfileWithDetails,useDeleteCertificateProfile} from "@app/hooks/api/certificateProfiles";@@ -20,6 +21,7 @@ import {import { CreateProfileModal } from "./CreateProfileModal";import { ProfileList } from "./ProfileList";import { RevealAcmeEabSecretModal } from "./RevealAcmeEabSecretModal";+import { ScepDetailsModal } from "./ScepDetailsModal";export const CertificateProfilesTab = () => {const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);@@ -27,6 +29,7 @@ export const CertificateProfilesTab = () => {const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);const [isRevealProfileAcmeEabSecretModalOpen, setIsRevealProfileAcmeEabSecretModalOpen] =useState(false);+ const [isScepDetailsModalOpen, setIsScepDetailsModalOpen] = useState(false);const [selectedProfile, setSelectedProfile] = useState<TCertificateProfileWithDetails | null>(null);@@ -48,6 +51,11 @@ export const CertificateProfilesTab = () => {setIsRevealProfileAcmeEabSecretModalOpen(true);};+ const handleViewScepDetails = (profile: TCertificateProfileWithDetails) => {+ setSelectedProfile(profile);+ setIsScepDetailsModalOpen(true);+ };+const handleDeleteProfile = (profile: TCertificateProfileWithDetails) => {setSelectedProfile(profile);setIsDeleteModalOpen(true);@@ -102,6 +110,7 @@ export const CertificateProfilesTab = () => {<ProfileListonEditProfile={handleEditProfile}onRevealProfileAcmeEabSecret={handleRevealProfileAcmeEabSecret}+ onViewScepDetails={handleViewScepDetails}onDeleteProfile={handleDeleteProfile}/>@@ -125,7 +134,7 @@ export const CertificateProfilesTab = () => {mode="edit"/>- {selectedProfile.enrollmentType === "acme" && (+ {selectedProfile.enrollmentType === EnrollmentType.ACME && (<RevealAcmeEabSecretModalisOpen={isRevealProfileAcmeEabSecretModalOpen}onClose={() => {@@ -136,6 +145,17 @@ export const CertificateProfilesTab = () => {/>)}+ {selectedProfile.enrollmentType === EnrollmentType.SCEP && (+ <ScepDetailsModal+ isOpen={isScepDetailsModalOpen}+ onClose={() => {+ setIsScepDetailsModalOpen(false);+ setSelectedProfile(null);+ }}+ profile={selectedProfile}+ />+ )}+<DeleteActionModalisOpen={isDeleteModalOpen}title={`Delete Certificate Profile ${selectedProfile.slug}?`}diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsxindex 8ab083e33d..828ae79736 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx@@ -104,6 +104,7 @@ const configurationFields = ["estConfig","apiConfig","acmeConfig",+ "scepConfig","externalConfigs"] as const;@@ -171,6 +172,13 @@ const createSchema = zskipEabBinding: z.boolean().optional()}).optional(),+ scepConfig: z+ .object({+ challengePassword: z.string().min(8, "Challenge password must be at least 8 characters"),+ includeCaCertInResponse: z.boolean().optional(),+ allowCertBasedRenewal: z.boolean().optional()+ })+ .optional(),externalConfigs: z.object({template: z.string().min(1, "Azure ADCS template is required")@@ -211,37 +219,59 @@ const createSchema = zmessage: "ACME enrollment type requires ACME configuration"})+ .refine(+ (data) => {+ if (data.enrollmentType === EnrollmentType.SCEP) {+ return !!data.scepConfig;+ }+ return true;+ },+ {+ message: "SCEP enrollment type requires SCEP configuration"+ }+ ).refine((data) => {if (data.enrollmentType === EnrollmentType.EST) {- return !data.apiConfig && !data.acmeConfig;+ return !data.apiConfig && !data.acmeConfig && !data.scepConfig;}return true;},{- message: "EST enrollment type cannot have API or ACME configuration"+ message: "EST enrollment type cannot have API, ACME, or SCEP configuration"}).refine((data) => {if (data.enrollmentType === EnrollmentType.API) {- return !data.estConfig && !data.acmeConfig;+ return !data.estConfig && !data.acmeConfig && !data.scepConfig;}return true;},{- message: "API enrollment type cannot have EST or ACME configuration"+ message: "API enrollment type cannot have EST, ACME, or SCEP configuration"}).refine((data) => {if (data.enrollmentType === EnrollmentType.ACME) {- return !data.estConfig && !data.apiConfig;+ return !data.estConfig && !data.apiConfig && !data.scepConfig;}return true;},{- message: "ACME enrollment type cannot have EST or API configuration"+ message: "ACME enrollment type cannot have EST, API, or SCEP configuration"+ }+ )+ .refine(+ (data) => {+ if (data.enrollmentType === EnrollmentType.SCEP) {+ return !data.estConfig && !data.apiConfig && !data.acmeConfig;+ }+ return true;+ },+ {+ message: "SCEP enrollment type cannot have EST, API, or ACME configuration"}).refine(@@ -328,6 +358,13 @@ const editSchema = zskipEabBinding: z.boolean().optional()}).optional(),+ scepConfig: z+ .object({+ challengePassword: z.string().optional(),+ includeCaCertInResponse: z.boolean().optional(),+ allowCertBasedRenewal: z.boolean().optional()+ })+ .optional(),externalConfigs: z.object({template: z.string().optional()@@ -368,37 +405,59 @@ const editSchema = zmessage: "ACME enrollment type requires ACME configuration"})+ .refine(+ (data) => {+ if (data.enrollmentType === EnrollmentType.SCEP) {+ return !!data.scepConfig;+ }+ return true;+ },+ {+ message: "SCEP enrollment type requires SCEP configuration"+ }+ ).refine((data) => {if (data.enrollmentType === EnrollmentType.EST) {- return !data.apiConfig && !data.acmeConfig;+ return !data.apiConfig && !data.acmeConfig && !data.scepConfig;}return true;},{- message: "EST enrollment type cannot have API or ACME configuration"+ message: "EST enrollment type cannot have API, ACME, or SCEP configuration"}).refine((data) => {if (data.enrollmentType === EnrollmentType.API) {- return !data.estConfig && !data.acmeConfig;+ return !data.estConfig && !data.acmeConfig && !data.scepConfig;}return true;},{- message: "API enrollment type cannot have EST or ACME configuration"+ message: "API enrollment type cannot have EST, ACME, or SCEP configuration"}).refine((data) => {if (data.enrollmentType === EnrollmentType.ACME) {- return !data.estConfig && !data.apiConfig;+ return !data.estConfig && !data.apiConfig && !data.scepConfig;+ }+ return true;+ },+ {+ message: "ACME enrollment type cannot have EST, API, or SCEP configuration"+ }+ )+ .refine(+ (data) => {+ if (data.enrollmentType === EnrollmentType.SCEP) {+ return !data.estConfig && !data.apiConfig && !data.acmeConfig;}return true;},{- message: "ACME enrollment type cannot have EST or API configuration"+ message: "SCEP enrollment type cannot have EST, API, or ACME configuration"}).refine(@@ -670,6 +729,14 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }skipEabBinding: profile.acmeConfig?.skipEabBinding || false}: undefined,+ scepConfig:+ profile.enrollmentType === EnrollmentType.SCEP+ ? {+ challengePassword: "",+ includeCaCertInResponse: profile.scepConfig?.includeCaCertInResponse ?? true,+ allowCertBasedRenewal: profile.scepConfig?.allowCertBasedRenewal ?? true+ }+ : undefined,externalConfigs: profile.externalConfigs? {template:@@ -697,6 +764,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }skipDnsOwnershipVerification: false,skipEabBinding: false},+ scepConfig: undefined,externalConfigs: undefined,defaults: undefined}@@ -831,7 +899,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }certificateAuthorityId: profile.caId || undefined,certificatePolicyId: profile.certificatePolicyId,estConfig:- profile.enrollmentType === "est"+ profile.enrollmentType === EnrollmentType.EST? {disableBootstrapCaValidation:profile.estConfig?.disableBootstrapCaValidation || false,@@ -840,7 +908,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }}: undefined,apiConfig:- profile.enrollmentType === "api"+ profile.enrollmentType === EnrollmentType.API? {autoRenew: profile.apiConfig?.autoRenew || false,renewBeforeDays: profile.apiConfig?.renewBeforeDays || 30@@ -854,6 +922,14 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }skipEabBinding: profile.acmeConfig?.skipEabBinding || false}: undefined,+ scepConfig:+ profile.enrollmentType === EnrollmentType.SCEP+ ? {+ challengePassword: "",+ includeCaCertInResponse: profile.scepConfig?.includeCaCertInResponse ?? true,+ allowCertBasedRenewal: profile.scepConfig?.allowCertBasedRenewal ?? true+ }+ : undefined,externalConfigs: profile.externalConfigs? {template:@@ -916,6 +992,8 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }updateData.apiConfig = data.apiConfig;} else if (data.enrollmentType === EnrollmentType.ACME && data.acmeConfig) {updateData.acmeConfig = data.acmeConfig;+ } else if (data.enrollmentType === EnrollmentType.SCEP && data.scepConfig) {+ updateData.scepConfig = data.scepConfig;}if (data.externalConfigs) {@@ -954,6 +1032,8 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }createData.apiConfig = data.apiConfig;} else if (data.enrollmentType === EnrollmentType.ACME && data.acmeConfig) {createData.acmeConfig = data.acmeConfig;+ } else if (data.enrollmentType === EnrollmentType.SCEP && data.scepConfig) {+ createData.scepConfig = data.scepConfig;}if (data.externalConfigs) {@@ -1111,6 +1191,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }skipDnsOwnershipVerification: false,skipEabBinding: false});+ setValue("scepConfig", undefined);}onChange(value);}}@@ -1230,27 +1311,39 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }// Reset defaults when policy changessetValue("defaults", undefined);- if (watchedEnrollmentType === "est") {+ if (watchedEnrollmentType === EnrollmentType.EST) {setValue("apiConfig", undefined);setValue("estConfig", {disableBootstrapCaValidation: false,passphrase: ""});setValue("acmeConfig", undefined);- } else if (watchedEnrollmentType === "api") {+ setValue("scepConfig", undefined);+ } else if (watchedEnrollmentType === EnrollmentType.API) {setValue("apiConfig", {autoRenew: false,renewBeforeDays: 30});setValue("estConfig", undefined);setValue("acmeConfig", undefined);- } else if (watchedEnrollmentType === "acme") {+ setValue("scepConfig", undefined);+ } else if (watchedEnrollmentType === EnrollmentType.ACME) {setValue("estConfig", undefined);setValue("apiConfig", undefined);setValue("acmeConfig", {skipDnsOwnershipVerification: false,skipEabBinding: false});+ setValue("scepConfig", undefined);+ } else if (watchedEnrollmentType === EnrollmentType.SCEP) {+ setValue("estConfig", undefined);+ setValue("apiConfig", undefined);+ setValue("acmeConfig", undefined);+ setValue("scepConfig", {+ challengePassword: "",+ includeCaCertInResponse: true,+ allowCertBasedRenewal: true+ });}}}options={policyOptions}@@ -1281,27 +1374,39 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }<Select{...field}onValueChange={(value) => {- if (value === "est") {+ if (value === EnrollmentType.EST) {setValue("apiConfig", undefined);setValue("estConfig", {disableBootstrapCaValidation: false,passphrase: ""});setValue("acmeConfig", undefined);- } else if (value === "api") {+ setValue("scepConfig", undefined);+ } else if (value === EnrollmentType.API) {setValue("apiConfig", {autoRenew: false,renewBeforeDays: 30});setValue("estConfig", undefined);setValue("acmeConfig", undefined);- } else if (value === "acme") {+ setValue("scepConfig", undefined);+ } else if (value === EnrollmentType.ACME) {setValue("apiConfig", undefined);setValue("estConfig", undefined);setValue("acmeConfig", {skipDnsOwnershipVerification: false,skipEabBinding: false});+ setValue("scepConfig", undefined);+ } else if (value === EnrollmentType.SCEP) {+ setValue("apiConfig", undefined);+ setValue("estConfig", undefined);+ setValue("acmeConfig", undefined);+ setValue("scepConfig", {+ challengePassword: "",+ includeCaCertInResponse: true,+ allowCertBasedRenewal: true+ });}onChange(value);}}@@ -1309,12 +1414,15 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }position="popper"isDisabled={Boolean(isEdit)}>- <SelectItem value="api">API</SelectItem>+ <SelectItem value={EnrollmentType.API}>API</SelectItem>+ {watchedIssuerType !== IssuerType.SELF_SIGNED && (+ <SelectItem value={EnrollmentType.EST}>EST</SelectItem>+ )}{watchedIssuerType !== IssuerType.SELF_SIGNED && (- <SelectItem value="est">EST</SelectItem>+ <SelectItem value={EnrollmentType.ACME}>ACME</SelectItem>)}{watchedIssuerType !== IssuerType.SELF_SIGNED && (- <SelectItem value="acme">ACME</SelectItem>+ <SelectItem value={EnrollmentType.SCEP}>SCEP</SelectItem>)}</Select></FormControl>@@ -1322,7 +1430,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }/>{/* EST Configuration */}- {watchedEnrollmentType === "est" && (+ {watchedEnrollmentType === EnrollmentType.EST && (<div className="mb-4 space-y-4"><div className="space-y-4"><Controller@@ -1400,7 +1508,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" })}{/* API Configuration */}- {watchedEnrollmentType === "api" && (+ {watchedEnrollmentType === EnrollmentType.API && (<div className="mb-4 space-y-4"><Controllercontrol={control}@@ -1426,7 +1534,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" })}{/* ACME Configuration */}- {watchedEnrollmentType === "acme" && (+ {watchedEnrollmentType === EnrollmentType.ACME && (<div className="mb-4 space-y-4"><Controllercontrol={control}@@ -1500,6 +1608,80 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }/></div>)}++ {/* SCEP Configuration */}+ {watchedEnrollmentType === EnrollmentType.SCEP && (+ <div className="mb-4 space-y-4">+ <Controller+ control={control}+ name="scepConfig.challengePassword"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Challenge Password"+ isRequired={!isEdit}+ isError={Boolean(error)}+ errorText={error?.message}+ >+ <Input+ {...field}+ type="password"+ placeholder="Enter SCEP challenge password"+ className="w-full"+ />+ </FormControl>+ )}+ />++ <Controller+ control={control}+ name="scepConfig.includeCaCertInResponse"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl isError={Boolean(error)} errorText={error?.message}>+ <div className="flex items-center gap-3 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4">+ <Checkbox+ id="includeCaCertInResponse"+ isChecked={value ?? true}+ onCheckedChange={onChange}+ />+ <div className="space-y-1">+ <span className="text-sm font-medium text-mineshaft-100">+ Include CA Certificate in Response+ </span>+ <p className="text-xs text-bunker-300">+ Include the CA certificate chain in SCEP responses+ </p>+ </div>+ </div>+ </FormControl>+ )}+ />++ <Controller+ control={control}+ name="scepConfig.allowCertBasedRenewal"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl isError={Boolean(error)} errorText={error?.message}>+ <div className="flex items-center gap-3 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4">+ <Checkbox+ id="allowCertBasedRenewal"+ isChecked={value ?? true}+ onCheckedChange={onChange}+ />+ <div className="space-y-1">+ <span className="text-sm font-medium text-mineshaft-100">+ Allow Certificate-Based Renewal+ </span>+ <p className="text-xs text-bunker-300">+ Allow clients to renew certificates using an existing valid+ certificate instead of the challenge password+ </p>+ </div>+ </div>+ </FormControl>+ )}+ />+ </div>+ )}{watchedAutoRenew && (<div className="mb-4 space-y-4"><Controllerdiff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsxindex a2f34504dc..830bc28b75 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx@@ -21,11 +21,13 @@ interface Props {onEditProfile: (profile: TCertificateProfileWithDetails) => void;onDeleteProfile: (profile: TCertificateProfileWithDetails) => void;onRevealProfileAcmeEabSecret: (profile: TCertificateProfileWithDetails) => void;+ onViewScepDetails: (profile: TCertificateProfileWithDetails) => void;}export const ProfileList = ({onEditProfile,onRevealProfileAcmeEabSecret,+ onViewScepDetails,onDeleteProfile}: Props) => {const { currentProject } = useProject();@@ -94,6 +96,7 @@ export const ProfileList = ({profile={profile}onEditProfile={onEditProfile}onRevealProfileAcmeEabSecret={onRevealProfileAcmeEabSecret}+ onViewScepDetails={onViewScepDetails}onDeleteProfile={onDeleteProfile}/>))}diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileRow.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileRow.tsxindex d4db06a748..5a42f5ec6c 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileRow.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileRow.tsx@@ -32,13 +32,18 @@ import {import { usePopUp, useToggle } from "@app/hooks";import { useGetInternalCaById } from "@app/hooks/api/ca/queries";import { useGetCertificatePolicyById } from "@app/hooks/api/certificatePolicies";-import { IssuerType, TCertificateProfile } from "@app/hooks/api/certificateProfiles";+import {+ EnrollmentType,+ IssuerType,+ TCertificateProfile+} from "@app/hooks/api/certificateProfiles";import { CertificateIssuanceModal } from "@app/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal";interface Props {profile: TCertificateProfile;onEditProfile: (profile: TCertificateProfile) => void;onRevealProfileAcmeEabSecret: (profile: TCertificateProfile) => void;+ onViewScepDetails: (profile: TCertificateProfile) => void;onDeleteProfile: (profile: TCertificateProfile) => void;}@@ -46,6 +51,7 @@ export const ProfileRow = ({profile,onEditProfile,onRevealProfileAcmeEabSecret,+ onViewScepDetails,onDeleteProfile}: Props) => {const isInternalCa = !profile.certificateAuthority?.isExternal;@@ -75,7 +81,8 @@ export const ProfileRow = ({const config = {api: { variant: "ghost" as const, label: "API" },est: { variant: "ghost" as const, label: "EST" },- acme: { variant: "ghost" as const, label: "ACME" }+ acme: { variant: "ghost" as const, label: "ACME" },+ scep: { variant: "ghost" as const, label: "SCEP" }} as const;const configKey = Object.keys(config).includes(enrollmentType)@@ -149,7 +156,7 @@ export const ProfileRow = ({)}</ProjectPermissionCan>- {profile.enrollmentType === "acme" && (+ {profile.enrollmentType === EnrollmentType.ACME && (<ProjectPermissionCanI={ProjectPermissionCertificateProfileActions.RevealAcmeEabSecret}a={subject(ProjectPermissionSub.CertificateProfiles, { slug: profile.slug })}@@ -169,7 +176,27 @@ export const ProfileRow = ({}</ProjectPermissionCan>)}- {profile.enrollmentType === "api" && (+ {profile.enrollmentType === EnrollmentType.SCEP && (+ <ProjectPermissionCan+ I={ProjectPermissionCertificateProfileActions.Read}+ a={subject(ProjectPermissionSub.CertificateProfiles, { slug: profile.slug })}+ >+ {(isAllowed) =>+ isAllowed && (+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ onViewScepDetails(profile);+ }}+ icon={<FontAwesomeIcon icon={faEye} className="w-3" />}+ >+ View SCEP Details+ </DropdownMenuItem>+ )+ }+ </ProjectPermissionCan>+ )}+ {profile.enrollmentType === EnrollmentType.API && (<ProjectPermissionCanI={ProjectPermissionCertificateProfileActions.IssueCert}a={subject(ProjectPermissionSub.CertificateProfiles, { slug: profile.slug })}diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ScepDetailsModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ScepDetailsModal.tsxnew file mode 100644index 0000000000..8614308747--- /dev/null+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ScepDetailsModal.tsx@@ -0,0 +1,103 @@+import { faCheck, faCopy, faDownload } from "@fortawesome/free-solid-svg-icons";+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";++import { FormLabel, IconButton, Input, Modal, ModalContent } from "@app/components/v2";+import { downloadFile } from "@app/helpers/download";+import { useToggle } from "@app/hooks";+import { TCertificateProfileWithDetails } from "@app/hooks/api/certificateProfiles";++const RESET_COPIED_DELAY = 1 * 1000;++type Props = {+ isOpen: boolean;+ onClose: () => void;+ profile: TCertificateProfileWithDetails;+};++export const ScepDetailsModal = ({ isOpen, onClose, profile }: Props) => {+ const [isUrlCopied, setIsUrlCopied] = useToggle(false);++ const { scepConfig } = profile;+ const scepEndpointUrl = scepConfig?.scepEndpointUrl ?? "";++ if (!scepConfig) {+ return (+ <Modal isOpen={isOpen} onOpenChange={(open) => !open && onClose()}>+ <ModalContent title="SCEP Enrollment Details">+ <p className="text-sm text-mineshaft-400">+ SCEP configuration is not available for this profile.+ </p>+ </ModalContent>+ </Modal>+ );+ }++ const raCertPem = scepConfig.raCertificatePem;+ const raCertExpiresAt = scepConfig.raCertExpiresAt+ ? new Date(scepConfig.raCertExpiresAt).toLocaleDateString("en-US", {+ year: "numeric",+ month: "long",+ day: "numeric"+ })+ : "Unknown";++ return (+ <Modal+ isOpen={isOpen}+ onOpenChange={(open) => {+ if (!open) {+ onClose();+ }+ }}+ >+ <ModalContent+ title="SCEP Enrollment Details"+ subTitle="To enroll devices via SCEP, configure your MDM or device with the following details."+ >+ <FormLabel+ label="SCEP Endpoint URL"+ tooltipText="The URL your SCEP client or MDM should point to for certificate enrollment."+ />+ <div className="flex gap-2">+ <Input value={scepEndpointUrl} isDisabled />+ <IconButton+ ariaLabel="copy"+ variant="outline_bg"+ colorSchema="secondary"+ onClick={() => {+ navigator.clipboard.writeText(scepEndpointUrl);+ setIsUrlCopied.on();+ setTimeout(() => {+ setIsUrlCopied.off();+ }, RESET_COPIED_DELAY);+ }}+ className="w-10"+ >+ <FontAwesomeIcon icon={isUrlCopied ? faCheck : faCopy} />+ </IconButton>+ </div>++ <FormLabel+ label="RA Certificate"+ className="mt-4"+ tooltipText="The Registration Authority certificate used by SCEP clients to encrypt enrollment requests."+ />+ <div className="flex items-center justify-between rounded-md border border-mineshaft-600 bg-mineshaft-900 px-4 py-3">+ <p className="text-xs text-mineshaft-400">Expires: {raCertExpiresAt}</p>+ <IconButton+ ariaLabel="download RA certificate"+ variant="outline_bg"+ colorSchema="secondary"+ onClick={() =>+ downloadFile(raCertPem, `${profile.slug}-ra-cert.pem`, "application/x-pem-file")+ }+ className="flex items-center gap-2"+ >+ <FontAwesomeIcon icon={faDownload} />+ <span className="text-sm">Download PEM</span>+ </IconButton>+ </div>+ </ModalContent>+ </Modal>+ );+};diff --git a/nginx/default.conf b/nginx/default.confindex 0234ac7a5e..241aa299cd 100644--- a/nginx/default.conf+++ b/nginx/default.conf@@ -57,6 +57,19 @@ server {proxy_cookie_path / "/; HttpOnly; SameSite=strict";}+ location /scep {+ proxy_set_header X-Real-RIP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;++ proxy_set_header Host $http_host;+ proxy_set_header X-NginX-Proxy true;++ proxy_pass http://backend:4000;+ proxy_redirect off;++ proxy_cookie_path / "/; HttpOnly; SameSite=strict";+ }+location /.well-known/est {proxy_set_header X-Real-RIP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;diff --git a/nginx/default.dev.conf b/nginx/default.dev.confindex 0adc8a5f00..99c90a581d 100644--- a/nginx/default.dev.conf+++ b/nginx/default.dev.conf@@ -76,6 +76,19 @@ server {proxy_cookie_path / "/; HttpOnly; SameSite=strict";}+ location /scep {+ proxy_set_header X-Real-RIP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;++ proxy_set_header Host $http_host;+ proxy_set_header X-NginX-Proxy true;++ proxy_pass http://api;+ proxy_redirect off;++ proxy_cookie_path / "/; HttpOnly; SameSite=strict";+ }+location ~ /\.well-known {proxy_set_header X-Real-RIP $remote_addr;