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 Windows and Linux servers PKI sync
Carlos Monastyrski401cca5a7162
diff --git a/backend/src/db/migrations/20260708161542_add-pki-sync-encrypted-credentials.ts b/backend/src/db/migrations/20260708161542_add-pki-sync-encrypted-credentials.tsnew file mode 100644index 0000000000..f4c8084887--- /dev/null+++ b/backend/src/db/migrations/20260708161542_add-pki-sync-encrypted-credentials.ts@@ -0,0 +1,19 @@+import { Knex } from "knex";++import { TableName } from "@app/db/schemas";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasColumn(TableName.PkiSync, "encryptedCredentials"))) {+ await knex.schema.alterTable(TableName.PkiSync, (t) => {+ t.binary("encryptedCredentials").nullable();+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasColumn(TableName.PkiSync, "encryptedCredentials")) {+ await knex.schema.alterTable(TableName.PkiSync, (t) => {+ t.dropColumn("encryptedCredentials");+ });+ }+}diff --git a/backend/src/db/schemas/pki-syncs.ts b/backend/src/db/schemas/pki-syncs.tsindex 79ad9a2092..6da5f5bbbc 100644--- a/backend/src/db/schemas/pki-syncs.ts+++ b/backend/src/db/schemas/pki-syncs.ts@@ -5,6 +5,8 @@import { z } from "zod";+import { zodBuffer } from "@app/lib/zod";+import { TImmutableDBKeys } from "./models";export const PkiSyncsSchema = z.object({@@ -33,7 +35,8 @@ export const PkiSyncsSchema = z.object({lastRemoveJobId: z.string().nullable().optional(),lastRemoveMessage: z.string().nullable().optional(),lastRemovedAt: z.date().nullable().optional(),- applicationId: z.string().uuid().nullable().optional()+ applicationId: z.string().uuid().nullable().optional(),+ encryptedCredentials: zodBuffer.nullable().optional()});export type TPkiSyncs = z.infer<typeof PkiSyncsSchema>;diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex d56c6ecfe9..c1d0857a68 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -4770,6 +4770,8 @@ interface CreatePkiSyncEvent {name: string;destination: string;applicationId?: string;+ connectionId?: string;+ hasCredentials?: boolean;};}diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.tsindex dafd9eea30..e31489233d 100644--- a/backend/src/lib/gateway-v2/gateway-v2.ts+++ b/backend/src/lib/gateway-v2/gateway-v2.ts@@ -97,7 +97,8 @@ export const createGatewayConnection = async ([GatewayProxyProtocol.PamRdpBrowser]: ["infisical-pam-rdp-browser"],[GatewayProxyProtocol.PamSessionCancellation]: ["infisical-pam-session-cancellation"],[GatewayProxyProtocol.Pkcs11]: ["infisical-pkcs11"],- [GatewayProxyProtocol.Adcs]: ["infisical-adcs"]+ [GatewayProxyProtocol.Adcs]: ["infisical-adcs"],+ [GatewayProxyProtocol.WinRm]: ["infisical-winrm"]};const tlsOptions: tls.ConnectionOptions = {diff --git a/backend/src/lib/gateway-v2/winrm-rpc.ts b/backend/src/lib/gateway-v2/winrm-rpc.tsnew file mode 100644index 0000000000..af6d6f3693--- /dev/null+++ b/backend/src/lib/gateway-v2/winrm-rpc.ts@@ -0,0 +1,102 @@+import http from "node:http";++import { logger } from "@app/lib/logger";++export type WinRmRpcEndpoint = "/v1/test" | "/v1/deliver" | "/v1/remove";++export type WinRmTransportParams = {+ useHttps?: boolean;+ insecure?: boolean;+};++export type WinRmDeliverFile = {+ path: string;+ contentBase64: string;+};++export type WinRmRpcRequestBody = {+ username: string;+ password: string;+ params?: Record<string, unknown>;+};++export type WinRmTestResult = { ok: boolean };+export type WinRmDeliverResult = { delivered: number };+export type WinRmRemoveResult = { removed: number };++export type WinRmRpcSuccess<T> = { ok: true; status: number; result: T };+export type WinRmRpcFailure = { ok: false; status: number; errorMessage: string };+export type WinRmRpcResponse<T> = WinRmRpcSuccess<T> | WinRmRpcFailure;++// A WinRM session sets up NTLM and runs one or more PowerShell commands per file,+// each of which can take a few seconds on a loaded host, so allow a generous ceiling.+// This must exceed the gateway's own connection deadline (op 120s + 15s flush margin) so a+// gateway-side timeout surfaces as its structured error rather than an opaque client timeout.+export const WINRM_RPC_TIMEOUT_MS = 150_000;++export const callWinRmEndpoint = async <T>(args: {+ port: number;+ endpoint: WinRmRpcEndpoint;+ body: WinRmRpcRequestBody;+}): Promise<WinRmRpcResponse<T>> => {+ const payload = JSON.stringify(args.body);+ return new Promise<WinRmRpcResponse<T>>((resolve, reject) => {+ const req = http.request(+ {+ host: "127.0.0.1",+ port: args.port,+ path: args.endpoint,+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Content-Length": Buffer.byteLength(payload).toString(),+ Connection: "close"+ },+ timeout: WINRM_RPC_TIMEOUT_MS+ },+ (res) => {+ const chunks: Buffer[] = [];+ res.on("data", (chunk: Buffer) => chunks.push(chunk));+ res.on("end", () => {+ const text = Buffer.concat(chunks).toString("utf8");+ const status = res.statusCode ?? 0;+ if (!text) {+ resolve({ ok: false, status, errorMessage: `Empty response body from Gateway (status ${status})` });+ return;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch {+ resolve({ ok: false, status, errorMessage: `Malformed response body from Gateway: ${text.slice(0, 256)}` });+ return;+ }+ if (status >= 200 && status < 300) {+ const { result } = parsed as { result?: T };+ if (result === undefined) {+ resolve({ ok: false, status, errorMessage: "Gateway response missing `result` field" });+ return;+ }+ resolve({ ok: true, status, result });+ return;+ }+ const errEnv = (parsed as { error?: { message?: string } }).error;+ resolve({ ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` });+ });+ res.on("error", (err) => {+ logger.warn({ err }, `WinRM RPC response stream error [port=${args.port}]`);+ reject(err);+ });+ }+ );+ req.on("timeout", () => {+ req.destroy(new Error(`WinRM RPC timed out after ${WINRM_RPC_TIMEOUT_MS}ms`));+ });+ req.on("error", (err) => {+ logger.warn({ err }, `WinRM RPC request error [port=${args.port}]`);+ reject(err);+ });+ req.write(payload);+ req.end();+ });+};diff --git a/backend/src/lib/gateway/types.ts b/backend/src/lib/gateway/types.tsindex a874846fc3..dad8291bdc 100644--- a/backend/src/lib/gateway/types.ts+++ b/backend/src/lib/gateway/types.ts@@ -13,7 +13,8 @@ export enum GatewayProxyProtocol {PamRdpBrowser = "pam-rdp-browser",PamSessionCancellation = "pam-session-cancellation",Pkcs11 = "pkcs11",- Adcs = "adcs"+ Adcs = "adcs",+ WinRm = "winrm"}export enum GatewayHttpProxyActions {diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex a1f765e37f..4fbef0d320 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -3482,7 +3482,8 @@ export const registerRoutes = async (appConnectionService,permissionService,licenseService,- pkiSyncQueue+ pkiSyncQueue,+ kmsService});const pkiDiscoveryQueue = pkiDiscoveryQueueFactory({diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.tsindex b22645071b..dee00a6bfc 100644--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts@@ -238,6 +238,10 @@ import {SanitizedWindmillConnectionSchema,WindmillConnectionListItemSchema} from "@app/services/app-connection/windmill";+import {+ SanitizedWinRMConnectionSchema,+ WinRMConnectionListItemSchema+} from "@app/services/app-connection/winrm/winrm-connection-schemas";import { SanitizedZabbixConnectionSchema, ZabbixConnectionListItemSchema } from "@app/services/app-connection/zabbix";import { AuthMode } from "@app/services/auth/auth-type";@@ -287,6 +291,7 @@ const SanitizedAppConnectionSchema = z.union([...SanitizedOktaConnectionSchema.options,...SanitizedAzureADCSConnectionSchema.options,...SanitizedADCSConnectionSchema.options,+ ...SanitizedWinRMConnectionSchema.options,...SanitizedRedisConnectionSchema.options,...SanitizedMongoDBConnectionSchema.options,...SanitizedLaravelForgeConnectionSchema.options,@@ -368,6 +373,7 @@ const AppConnectionOptionsSchema = z.discriminatedUnion("app", [OktaConnectionListItemSchema,AzureADCSConnectionListItemSchema,ADCSConnectionListItemSchema,+ WinRMConnectionListItemSchema,RedisConnectionListItemSchema,MongoDBConnectionListItemSchema,LaravelForgeConnectionListItemSchema,diff --git a/backend/src/server/routes/v1/app-connection-routers/index.ts b/backend/src/server/routes/v1/app-connection-routers/index.tsindex 06a3a2ebe2..61f195b647 100644--- a/backend/src/server/routes/v1/app-connection-routers/index.ts+++ b/backend/src/server/routes/v1/app-connection-routers/index.ts@@ -77,6 +77,7 @@ import { registerVenafiConnectionRouter } from "./venafi-connection-router";import { registerVenafiTppConnectionRouter } from "./venafi-tpp-connection-router";import { registerVercelConnectionRouter } from "./vercel-connection-router";import { registerWindmillConnectionRouter } from "./windmill-connection-router";+import { registerWinRMConnectionRouter } from "./winrm-connection-router";import { registerZabbixConnectionRouter } from "./zabbix-connection-router";export * from "./app-connection-router";@@ -134,6 +135,7 @@ export const APP_CONNECTION_REGISTER_ROUTER_MAP: Record<AppConnection, (server:[AppConnection.SSH]: registerSshConnectionRouter,[AppConnection.Dbt]: registerDbtConnectionRouter,[AppConnection.SMB]: registerSmbConnectionRouter,+ [AppConnection.WinRM]: registerWinRMConnectionRouter,[AppConnection.OpenRouter]: registerOpenRouterConnectionRouter,[AppConnection.OpenAI]: registerOpenAIConnectionRouter,[AppConnection.CircleCI]: registerCircleCIConnectionRouter,diff --git a/backend/src/server/routes/v1/app-connection-routers/winrm-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/winrm-connection-router.tsnew file mode 100644index 0000000000..2f018b37ee--- /dev/null+++ b/backend/src/server/routes/v1/app-connection-routers/winrm-connection-router.ts@@ -0,0 +1,18 @@+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import {+ CreateWinRMConnectionSchema,+ SanitizedWinRMConnectionSchema,+ UpdateWinRMConnectionSchema+} from "@app/services/app-connection/winrm";++import { registerAppConnectionEndpoints } from "./app-connection-endpoints";++export const registerWinRMConnectionRouter = async (server: FastifyZodProvider) => {+ registerAppConnectionEndpoints({+ app: AppConnection.WinRM,+ server,+ sanitizedResponseSchema: SanitizedWinRMConnectionSchema,+ createSchema: CreateWinRMConnectionSchema,+ updateSchema: UpdateWinRMConnectionSchema+ });+};diff --git a/backend/src/server/routes/v1/pki-sync-routers/index.ts b/backend/src/server/routes/v1/pki-sync-routers/index.tsindex dda3a31445..a2e474b560 100644--- a/backend/src/server/routes/v1/pki-sync-routers/index.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/index.ts@@ -7,7 +7,9 @@ import { registerAzureKeyVaultPkiSyncRouter } from "./azure-key-vault-pki-sync-rimport { registerChefPkiSyncRouter } from "./chef-pki-sync-router";import { registerCloudflareCustomCertificatePkiSyncRouter } from "./cloudflare-custom-certificate-pki-sync-router";import { registerF5BigIpPkiSyncRouter } from "./f5-big-ip-pki-sync-router";+import { registerLinuxServerPkiSyncRouter } from "./linux-server-pki-sync-router";import { registerNetScalerPkiSyncRouter } from "./netscaler-pki-sync-router";+import { registerWindowsServerPkiSyncRouter } from "./windows-server-pki-sync-router";export * from "./pki-sync-router";@@ -22,5 +24,7 @@ export const PKI_SYNC_REGISTER_ROUTER_MAP: Record<[PkiSync.Chef]: registerChefPkiSyncRouter,[PkiSync.CloudflareCustomCertificate]: registerCloudflareCustomCertificatePkiSyncRouter,[PkiSync.NetScaler]: registerNetScalerPkiSyncRouter,- [PkiSync.F5BigIp]: registerF5BigIpPkiSyncRouter+ [PkiSync.F5BigIp]: registerF5BigIpPkiSyncRouter,+ [PkiSync.LinuxServer]: registerLinuxServerPkiSyncRouter,+ [PkiSync.WindowsServer]: registerWindowsServerPkiSyncRouter};diff --git a/backend/src/server/routes/v1/pki-sync-routers/linux-server-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/linux-server-pki-sync-router.tsnew file mode 100644index 0000000000..b8a9b2ca96--- /dev/null+++ b/backend/src/server/routes/v1/pki-sync-routers/linux-server-pki-sync-router.ts@@ -0,0 +1,23 @@+import {+ CreateLinuxServerPkiSyncSchema,+ LINUX_SERVER_PKI_SYNC_LIST_OPTION,+ LinuxServerPkiSyncSchema,+ UpdateLinuxServerPkiSyncSchema+} from "@app/services/pki-sync/linux-server";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";++import { registerSyncPkiEndpoints } from "./pki-sync-endpoints";++export const registerLinuxServerPkiSyncRouter = async (server: FastifyZodProvider, enableOperationId: boolean = true) =>+ registerSyncPkiEndpoints({+ destination: PkiSync.LinuxServer,+ server,+ responseSchema: LinuxServerPkiSyncSchema,+ createSchema: CreateLinuxServerPkiSyncSchema,+ updateSchema: UpdateLinuxServerPkiSyncSchema,+ syncOptions: {+ canImportCertificates: LINUX_SERVER_PKI_SYNC_LIST_OPTION.canImportCertificates,+ canRemoveCertificates: LINUX_SERVER_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ },+ enableOperationId+ });diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.tsindex d943affb8e..4a3db052da 100644--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts@@ -29,6 +29,7 @@ export const registerSyncPkiEndpoints = ({connectionId: string;destinationConfig: Record<string, unknown>;syncOptions?: Record<string, unknown>;+ credentials?: { exportPassword?: string };description?: string;isAutoSyncEnabled?: boolean;subscriberId?: string | null;@@ -167,6 +168,8 @@ export const registerSyncPkiEndpoints = ({pkiSyncId: pkiSync.id,name: pkiSync.name,destination,+ connectionId: pkiSync.connectionId,+ hasCredentials: Boolean(req.body.credentials?.exportPassword),...(pkiSync.applicationId && { applicationId: pkiSync.applicationId })}}diff --git a/backend/src/server/routes/v1/pki-sync-routers/windows-server-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/windows-server-pki-sync-router.tsnew file mode 100644index 0000000000..8029049fff--- /dev/null+++ b/backend/src/server/routes/v1/pki-sync-routers/windows-server-pki-sync-router.ts@@ -0,0 +1,26 @@+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";+import {+ CreateWindowsServerPkiSyncSchema,+ UpdateWindowsServerPkiSyncSchema,+ WINDOWS_SERVER_PKI_SYNC_LIST_OPTION,+ WindowsServerPkiSyncSchema+} from "@app/services/pki-sync/windows-server";++import { registerSyncPkiEndpoints } from "./pki-sync-endpoints";++export const registerWindowsServerPkiSyncRouter = async (+ server: FastifyZodProvider,+ enableOperationId: boolean = true+) =>+ registerSyncPkiEndpoints({+ destination: PkiSync.WindowsServer,+ server,+ responseSchema: WindowsServerPkiSyncSchema,+ createSchema: CreateWindowsServerPkiSyncSchema,+ updateSchema: UpdateWindowsServerPkiSyncSchema,+ syncOptions: {+ canImportCertificates: WINDOWS_SERVER_PKI_SYNC_LIST_OPTION.canImportCertificates,+ canRemoveCertificates: WINDOWS_SERVER_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ },+ enableOperationId+ });diff --git a/backend/src/services/app-connection/app-connection-enums.ts b/backend/src/services/app-connection/app-connection-enums.tsindex aade305f09..44b4109b6c 100644--- a/backend/src/services/app-connection/app-connection-enums.ts+++ b/backend/src/services/app-connection/app-connection-enums.ts@@ -50,6 +50,7 @@ export enum AppConnection {SSH = "ssh",Dbt = "dbt",SMB = "smb",+ WinRM = "winrm",OpenRouter = "open-router",OpenAI = "openai",CircleCI = "circleci",diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.tsindex abeda2af23..751192345b 100644--- a/backend/src/services/app-connection/app-connection-fns.ts+++ b/backend/src/services/app-connection/app-connection-fns.ts@@ -281,6 +281,7 @@ import {validateWindmillConnectionCredentials,WindmillConnectionMethod} from "./windmill";+import { getWinRMConnectionListItem, validateWinRMConnectionCredentials, WinRMConnectionMethod } from "./winrm";import { getZabbixConnectionListItem, validateZabbixConnectionCredentials, ZabbixConnectionMethod } from "./zabbix";const SECRET_SYNC_APP_CONNECTION_MAP = Object.fromEntries(@@ -310,7 +311,9 @@ const PKI_APP_CONNECTIONS = [AppConnection.NetScaler,AppConnection.DigiCert,AppConnection.F5BigIp,- AppConnection.GoDaddy+ AppConnection.GoDaddy,+ AppConnection.SSH,+ AppConnection.WinRM];export const listAppConnectionOptions = (projectType?: ProjectType) => {@@ -324,6 +327,7 @@ export const listAppConnectionOptions = (projectType?: ProjectType) => {getAzureDevopsConnectionListItem(),getAzureADCSConnectionListItem(),getADCSConnectionListItem(),+ getWinRMConnectionListItem(),getDatabricksConnectionListItem(),getHumanitecConnectionListItem(),getTerraformCloudConnectionListItem(),@@ -567,6 +571,7 @@ export const validateAppConnectionCredentials = async ([AppConnection.AzureDevOps]: validateAzureDevOpsConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.AzureADCS]: validateAzureADCSConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.ADCS]: validateADCSConnectionCredentials as TAppConnectionCredentialsValidator,+ [AppConnection.WinRM]: validateWinRMConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.Humanitec]: validateHumanitecConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.Postgres]: validateSqlConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.MsSql]: validateSqlConnectionCredentials as TAppConnectionCredentialsValidator,@@ -706,6 +711,7 @@ export const getAppConnectionMethodName = (method: TAppConnection["method"]) =>case OracleDBConnectionMethod.UsernameAndPassword:case AzureADCSConnectionMethod.UsernamePassword:case ADCSConnectionMethod.UsernamePassword:+ case WinRMConnectionMethod.UsernamePassword:case RedisConnectionMethod.UsernameAndPassword:case MongoDBConnectionMethod.UsernameAndPassword:return "Username & Password";@@ -833,6 +839,7 @@ export const TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM: Record<[AppConnection.AzureDevOps]: platformManagedCredentialsNotSupported,[AppConnection.AzureADCS]: platformManagedCredentialsNotSupported,[AppConnection.ADCS]: platformManagedCredentialsNotSupported,+ [AppConnection.WinRM]: platformManagedCredentialsNotSupported,[AppConnection.Humanitec]: platformManagedCredentialsNotSupported,[AppConnection.Postgres]: transferSqlConnectionCredentialsToPlatform as TAppConnectionTransitionCredentialsToPlatform,[AppConnection.MsSql]: transferSqlConnectionCredentialsToPlatform as TAppConnectionTransitionCredentialsToPlatform,diff --git a/backend/src/services/app-connection/app-connection-maps.ts b/backend/src/services/app-connection/app-connection-maps.tsindex c473013de0..b034bd6d46 100644--- a/backend/src/services/app-connection/app-connection-maps.ts+++ b/backend/src/services/app-connection/app-connection-maps.ts@@ -51,7 +51,8 @@ export const APP_CONNECTION_NAME_MAP: Record<AppConnection, string> = {[AppConnection.OctopusDeploy]: "Octopus Deploy",[AppConnection.SSH]: "SSH",[AppConnection.Dbt]: "DBT",- [AppConnection.SMB]: "SMB",+ [AppConnection.SMB]: "Windows (SMB)",+ [AppConnection.WinRM]: "Windows (WinRM)",[AppConnection.OpenRouter]: "OpenRouter",[AppConnection.OpenAI]: "OpenAI",[AppConnection.CircleCI]: "CircleCI",@@ -133,6 +134,7 @@ export const APP_CONNECTION_PLAN_MAP: Record<AppConnection, AppConnectionPlanTyp[AppConnection.SSH]: AppConnectionPlanType.Regular,[AppConnection.Dbt]: AppConnectionPlanType.Regular,[AppConnection.SMB]: AppConnectionPlanType.Regular,+ [AppConnection.WinRM]: AppConnectionPlanType.Regular,[AppConnection.OpenRouter]: AppConnectionPlanType.Regular,[AppConnection.OpenAI]: AppConnectionPlanType.Regular,[AppConnection.CircleCI]: AppConnectionPlanType.Regular,diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex 67637652c5..d2ced3171f 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -187,6 +187,7 @@ import { ValidateVercelConnectionCredentialsSchema } from "./vercel";import { vercelConnectionService } from "./vercel/vercel-connection-service";import { ValidateWindmillConnectionCredentialsSchema } from "./windmill";import { windmillConnectionService } from "./windmill/windmill-connection-service";+import { ValidateWinRMConnectionCredentialsSchema } from "./winrm/winrm-connection-schemas";import { ValidateZabbixConnectionCredentialsSchema } from "./zabbix";import { zabbixConnectionService } from "./zabbix/zabbix-connection-service";@@ -222,6 +223,7 @@ const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TValidateAp[AppConnection.AzureDevOps]: ValidateAzureDevOpsConnectionCredentialsSchema,[AppConnection.AzureADCS]: ValidateAzureADCSConnectionCredentialsSchema,[AppConnection.ADCS]: ValidateADCSConnectionCredentialsSchema,+ [AppConnection.WinRM]: ValidateWinRMConnectionCredentialsSchema,[AppConnection.Databricks]: ValidateDatabricksConnectionCredentialsSchema,[AppConnection.Humanitec]: ValidateHumanitecConnectionCredentialsSchema,[AppConnection.TerraformCloud]: ValidateTerraformCloudConnectionCredentialsSchema,diff --git a/backend/src/services/app-connection/app-connection-types.ts b/backend/src/services/app-connection/app-connection-types.tsindex 2b95cc8c05..2cfb9318fd 100644--- a/backend/src/services/app-connection/app-connection-types.ts+++ b/backend/src/services/app-connection/app-connection-types.ts@@ -455,6 +455,12 @@ import {TWindmillConnectionConfig,TWindmillConnectionInput} from "./windmill";+import {+ TValidateWinRMConnectionCredentialsSchema,+ TWinRMConnection,+ TWinRMConnectionConfig,+ TWinRMConnectionInput+} from "./winrm/winrm-connection-types";import {TValidateZabbixConnectionCredentialsSchema,TZabbixConnection,@@ -474,6 +480,7 @@ export type TAppConnection = { id: string; configuration?: TAppConnectionConfigu| TAzureDevOpsConnection| TAzureADCSConnection| TADCSConnection+ | TWinRMConnection| TDatabricksConnection| THumanitecConnection| TTerraformCloudConnection@@ -563,6 +570,7 @@ export type TAppConnectionInput = { id: string } & (| TAzureDevOpsConnectionInput| TAzureADCSConnectionInput| TADCSConnectionInput+ | TWinRMConnectionInput| TDatabricksConnectionInput| THumanitecConnectionInput| TTerraformCloudConnectionInput@@ -687,6 +695,7 @@ export type TAppConnectionConfig =| TAzureDevOpsConnectionConfig| TAzureADCSConnectionConfig| TADCSConnectionConfig+ | TWinRMConnectionConfig| TAzureClientSecretsConnectionConfig| TDatabricksConnectionConfig| THumanitecConnectionConfig@@ -765,6 +774,7 @@ export type TValidateAppConnectionCredentialsSchema =| TValidateAzureDevOpsConnectionCredentialsSchema| TValidateAzureADCSConnectionCredentialsSchema| TValidateADCSConnectionCredentialsSchema+ | TValidateWinRMConnectionCredentialsSchema| TValidateDatabricksConnectionCredentialsSchema| TValidateHumanitecConnectionCredentialsSchema| TValidatePostgresConnectionCredentialsSchemadiff --git a/backend/src/services/app-connection/smb/smb-connection-fns.ts b/backend/src/services/app-connection/smb/smb-connection-fns.tsindex 885c88bc4f..4279bf5989 100644--- a/backend/src/services/app-connection/smb/smb-connection-fns.ts+++ b/backend/src/services/app-connection/smb/smb-connection-fns.ts@@ -13,7 +13,7 @@ import { TSmbConnectionConfig } from "./smb-connection-types";export const getSmbConnectionListItem = () => {return {- name: "Windows" as const,+ name: "Windows (SMB)" as const,app: AppConnection.SMB as const,methods: Object.values(SmbConnectionMethod) as [SmbConnectionMethod.Credentials]};diff --git a/backend/src/services/app-connection/smb/smb-connection-schemas.ts b/backend/src/services/app-connection/smb/smb-connection-schemas.tsindex aed0c64f7a..2625563197 100644--- a/backend/src/services/app-connection/smb/smb-connection-schemas.ts+++ b/backend/src/services/app-connection/smb/smb-connection-schemas.ts@@ -121,7 +121,7 @@ export const SanitizedSmbConnectionSchema = z.discriminatedUnion("method", [// List item schemaexport const SmbConnectionListItemSchema = z.object({- name: z.literal("Windows"),+ name: z.literal("Windows (SMB)"),app: z.literal(AppConnection.SMB),methods: z.nativeEnum(SmbConnectionMethod).array()})diff --git a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts b/backend/src/services/app-connection/ssh/ssh-connection-fns.tsindex 1dcc2b6c1a..79165588ce 100644--- a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts+++ b/backend/src/services/app-connection/ssh/ssh-connection-fns.ts@@ -161,7 +161,7 @@ export const getSshConnectionClient = async (export const executeWithPotentialGateway = async <T>(config: TSshConnectionConfig,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId"> | undefined,operation: (targetHost: string, targetPort: number) => Promise<T>,gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">): Promise<T> => {@@ -178,6 +178,10 @@ export const executeWithPotentialGateway = async <T>(: directGatewayId;if (gatewayId) {+ if (!gatewayV2Service) {+ throw new BadRequestError({ message: "Gateway-backed connections require gatewayV2Service at the call site" });+ }+await blockLocalAndPrivateIpAddresses(`ssh://${credentials.host}:${credentials.port}`, true);const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({@@ -208,6 +212,28 @@ export const executeWithPotentialGateway = async <T>(return operation(credentials.host, credentials.port);};+export const withSshConnection = async <T>(+ config: TSshConnectionConfig,+ gatewayServices: {+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+ },+ operation: (client: Client) => Promise<T>+): Promise<T> =>+ executeWithPotentialGateway(+ config,+ gatewayServices.gatewayV2Service,+ async (targetHost, targetPort) => {+ const client = await getSshConnectionClient(config, targetHost, targetPort);+ try {+ return await operation(client);+ } finally {+ client.destroy();+ }+ },+ gatewayServices.gatewayPoolService+ );+export const validateSshConnectionCredentials = async (config: TSshConnectionConfig,_gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,diff --git a/backend/src/services/app-connection/winrm/index.ts b/backend/src/services/app-connection/winrm/index.tsnew file mode 100644index 0000000000..5d62b81b80--- /dev/null+++ b/backend/src/services/app-connection/winrm/index.ts@@ -0,0 +1,4 @@+export * from "./winrm-connection-enums";+export * from "./winrm-connection-fns";+export * from "./winrm-connection-schemas";+export * from "./winrm-connection-types";diff --git a/backend/src/services/app-connection/winrm/winrm-connection-enums.ts b/backend/src/services/app-connection/winrm/winrm-connection-enums.tsnew file mode 100644index 0000000000..0762484cfd--- /dev/null+++ b/backend/src/services/app-connection/winrm/winrm-connection-enums.ts@@ -0,0 +1,3 @@+export enum WinRMConnectionMethod {+ UsernamePassword = "username-password"+}diff --git a/backend/src/services/app-connection/winrm/winrm-connection-fns.ts b/backend/src/services/app-connection/winrm/winrm-connection-fns.tsnew file mode 100644index 0000000000..6a843a049f--- /dev/null+++ b/backend/src/services/app-connection/winrm/winrm-connection-fns.ts@@ -0,0 +1,133 @@+import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { BadRequestError } from "@app/lib/errors";+import { GatewayProxyProtocol } from "@app/lib/gateway/types";+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";+import { callWinRmEndpoint, WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-rpc";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";++import { WinRMConnectionMethod } from "./winrm-connection-enums";+import { TWinRMConnectionConfig } from "./winrm-connection-types";++export type TWinRMGatewayDeps = {+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+};++export type TWinRMCredentials = {+ host: string;+ port: number;+ username: string;+ password: string;+ useHttps?: boolean;+ insecure?: boolean;+};++export const getWinRMConnectionListItem = () => ({+ name: "Windows (WinRM)" as const,+ app: AppConnection.WinRM as const,+ methods: Object.values(WinRMConnectionMethod) as [WinRMConnectionMethod.UsernamePassword]+});++/**+ * Runs a single WinRM operation on the gateway that sits inside the customer+ * network. Node cannot perform WinRM message sealing, so delivery always runs on+ * the gateway (Go/masterzen) and a gateway is always required for this connection.+ * The target host/port travel in the signed routing extension; only the transport+ * flags and operation payload go in the request body.+ */+export const executeWinRMGatewayOperation = async <T>(+ args: {+ gatewayId?: string | null;+ gatewayPoolId?: string | null;+ credentials: TWinRMCredentials;+ endpoint: WinRmRpcEndpoint;+ params?: Record<string, unknown>;+ },+ deps: TWinRMGatewayDeps+): Promise<T> => {+ const { gatewayV2Service, gatewayPoolService } = deps;++ if (args.gatewayPoolId && !gatewayPoolService) {+ throw new BadRequestError({ message: "Pool-backed connections require gatewayPoolService at the call site" });+ }++ const gatewayId =+ args.gatewayPoolId && gatewayPoolService+ ? await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: args.gatewayId,+ gatewayPoolId: args.gatewayPoolId+ })+ : args.gatewayId;++ if (!gatewayId) {+ throw new BadRequestError({+ message: "Windows (WinRM) connections require a gateway to reach the host."+ });+ }++ const connectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId,+ targetHost: args.credentials.host,+ targetPort: args.credentials.port+ });+ if (!connectionDetails) {+ throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });+ }++ const response = await withGatewayV2Proxy(+ async (port) =>+ callWinRmEndpoint<T>({+ port,+ endpoint: args.endpoint,+ body: {+ username: args.credentials.username,+ password: args.credentials.password,+ params: {+ useHttps: args.credentials.useHttps ?? false,+ insecure: args.credentials.insecure ?? false,+ ...args.params+ }+ }+ }),+ {+ protocol: GatewayProxyProtocol.WinRm,+ relayHost: connectionDetails.relayHost,+ gateway: connectionDetails.gateway,+ relay: connectionDetails.relay+ }+ );++ if (!response.ok) {+ throw new BadRequestError({ message: `WinRM gateway operation failed: ${response.errorMessage ?? ""}` });+ }+ return response.result;+};++export const validateWinRMConnectionCredentials = async (+ config: TWinRMConnectionConfig,+ _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+) => {+ try {+ await executeWinRMGatewayOperation<{ ok: boolean }>(+ {+ gatewayId: config.gatewayId,+ gatewayPoolId: config.gatewayPoolId,+ credentials: config.credentials,+ endpoint: "/v1/test"+ },+ { gatewayV2Service }+ );++ return config.credentials;+ } catch (error) {+ throw new BadRequestError({+ message: `Unable to validate connection: ${+ (error as Error)?.message?.replaceAll(config.credentials.password, "********************") ??+ "verify credentials"+ }`+ });+ }+};diff --git a/backend/src/services/app-connection/winrm/winrm-connection-schemas.ts b/backend/src/services/app-connection/winrm/winrm-connection-schemas.tsnew file mode 100644index 0000000000..00c9563ec3--- /dev/null+++ b/backend/src/services/app-connection/winrm/winrm-connection-schemas.ts@@ -0,0 +1,85 @@+import { z } from "zod";++import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import {+ BaseAppConnectionSchema,+ GenericCreateAppConnectionFieldsSchema,+ GenericUpdateAppConnectionFieldsSchema+} from "@app/services/app-connection/app-connection-schemas";++import { APP_CONNECTION_NAME_MAP } from "../app-connection-maps";+import { WinRMConnectionMethod } from "./winrm-connection-enums";++export const WinRMUsernamePasswordCredentialsSchema = z.object({+ host: z+ .string()+ .trim()+ .min(1, "Host required")+ .max(255)+ .describe("The Windows host's DNS name (FQDN) or IP address."),+ port: z.coerce+ .number()+ .int()+ .min(1)+ .max(65535)+ .default(5985)+ .describe("The WinRM port. 5985 for NTLM-encrypted HTTP, 5986 for HTTPS."),+ username: z+ .string()+ .trim()+ .min(1, "Username required")+ .max(255)+ .describe("Windows login: DOMAIN\\user or user@domain."),+ password: z.string().min(1, "Password required").max(255).describe("The account password."),+ useHttps: z.boolean().default(false).describe("Use HTTPS (port 5986) instead of NTLM-encrypted HTTP (port 5985)."),+ insecure: z+ .boolean()+ .default(false)+ .describe("Skip TLS certificate verification when HTTPS is used (for self-signed WinRM listeners).")+});++const BaseWinRMConnectionSchema = BaseAppConnectionSchema.extend({ app: z.literal(AppConnection.WinRM) });++export const WinRMConnectionSchema = BaseWinRMConnectionSchema.extend({+ method: z.literal(WinRMConnectionMethod.UsernamePassword),+ credentials: WinRMUsernamePasswordCredentialsSchema+});++export const SanitizedWinRMConnectionSchema = z.discriminatedUnion("method", [+ BaseWinRMConnectionSchema.extend({+ method: z.literal(WinRMConnectionMethod.UsernamePassword),+ // Never return the password.+ credentials: WinRMUsernamePasswordCredentialsSchema.pick({+ host: true,+ port: true,+ username: true,+ useHttps: true,+ insecure: true+ })+ }).describe(JSON.stringify({ title: `${APP_CONNECTION_NAME_MAP[AppConnection.WinRM]} (Username and Password)` }))+]);++export const ValidateWinRMConnectionCredentialsSchema = z.discriminatedUnion("method", [+ z.object({+ method: z.literal(WinRMConnectionMethod.UsernamePassword),+ credentials: WinRMUsernamePasswordCredentialsSchema+ })+]);++export const CreateWinRMConnectionSchema = ValidateWinRMConnectionCredentialsSchema.and(+ GenericCreateAppConnectionFieldsSchema(AppConnection.WinRM, { supportsGateways: true })+);++export const UpdateWinRMConnectionSchema = z+ .object({+ credentials: WinRMUsernamePasswordCredentialsSchema.optional()+ })+ .and(GenericUpdateAppConnectionFieldsSchema(AppConnection.WinRM, { supportsGateways: true }));++export const WinRMConnectionListItemSchema = z+ .object({+ name: z.literal("Windows (WinRM)"),+ app: z.literal(AppConnection.WinRM),+ methods: z.nativeEnum(WinRMConnectionMethod).array()+ })+ .describe(JSON.stringify({ title: APP_CONNECTION_NAME_MAP[AppConnection.WinRM] }));diff --git a/backend/src/services/app-connection/winrm/winrm-connection-types.ts b/backend/src/services/app-connection/winrm/winrm-connection-types.tsnew file mode 100644index 0000000000..4a495e3699--- /dev/null+++ b/backend/src/services/app-connection/winrm/winrm-connection-types.ts@@ -0,0 +1,23 @@+import { z } from "zod";++import { DiscriminativePick } from "@app/lib/types";++import { AppConnection } from "../app-connection-enums";+import {+ CreateWinRMConnectionSchema,+ ValidateWinRMConnectionCredentialsSchema,+ WinRMConnectionSchema+} from "./winrm-connection-schemas";++export type TWinRMConnection = z.infer<typeof WinRMConnectionSchema>;++export type TWinRMConnectionInput = z.infer<typeof CreateWinRMConnectionSchema> & {+ app: AppConnection.WinRM;+};++export type TValidateWinRMConnectionCredentialsSchema = typeof ValidateWinRMConnectionCredentialsSchema;++export type TWinRMConnectionConfig = DiscriminativePick<+ TWinRMConnectionInput,+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId"+>;diff --git a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.ts b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.tsindex 6fd6789606..5cac44a538 100644--- a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.ts@@ -63,10 +63,6 @@ export const F5BigIpPkiSyncOptionsSchema = z.object({.min(1, "Certificate name schema is required").refine((schema) => {- if (!schema.includes("{{certificateId}}") && !schema.includes("{{shortCertificateId}}")) {- return false;- }-const testName = buildCertificateNameSchemaTestName(schema);const hasForbiddenChars = F5_BIG_IP_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) =>@@ -77,7 +73,7 @@ export const F5BigIpPkiSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include the {{certificateId}} or {{shortCertificateId}} placeholder and result in names that contain only alphanumeric characters, hyphens (-), underscores (_), and periods (.) and be 1-255 characters long for F5 BIG-IP. Available placeholders: {{certificateId}}, {{shortCertificateId}}, {{profileId}}, {{applicationId}}, {{applicationName}}, {{commonName}}"+ "Certificate name schema must result in names that contain only alphanumeric characters, hyphens (-), underscores (_), and periods (.) and be 1-255 characters long for F5 BIG-IP. Available placeholders: {{certificateId}}, {{shortCertificateId}}, {{profileId}}, {{applicationId}}, {{applicationName}}, {{commonName}}. A schema with no placeholder can be linked to only one certificate."})});diff --git a/backend/src/services/pki-sync/linux-server/index.ts b/backend/src/services/pki-sync/linux-server/index.tsnew file mode 100644index 0000000000..ecaee4cb48--- /dev/null+++ b/backend/src/services/pki-sync/linux-server/index.ts@@ -0,0 +1,4 @@+export * from "./linux-server-pki-sync-constants";+export * from "./linux-server-pki-sync-fns";+export * from "./linux-server-pki-sync-schemas";+export * from "./linux-server-pki-sync-types";diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-constants.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-constants.tsnew file mode 100644index 0000000000..d603aac676--- /dev/null+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-constants.ts@@ -0,0 +1,30 @@+import RE2 from "re2";++import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";++/**+ * Linux Server file-name constraints. The certificate name schema produces the file's base name+ * (the export format appends the extension). The base must be a single POSIX path segment, so path+ * separators, traversal, and control characters are disallowed.+ */+export const LINUX_SERVER_NAMING = {+ NAME_PATTERN: new RE2("^[a-zA-Z0-9._-]{1,200}$"),+ FORBIDDEN_CHARACTERS: '/\\\0:*?"<>|',+ MAX_NAME_LENGTH: 200,+ MIN_NAME_LENGTH: 1,+ ALLOWED_CHARACTER_PATTERN: "^[a-zA-Z0-9._-]{1,200}$"+} as const;++export const LINUX_SERVER_PKI_SYNC_LIST_OPTION = {+ name: "Linux Server" as const,+ connection: AppConnection.SSH,+ destination: PkiSync.LinuxServer,+ canImportCertificates: false,+ canRemoveCertificates: true,+ defaultCertificateNameSchema: "{{commonName}}",+ forbiddenCharacters: LINUX_SERVER_NAMING.FORBIDDEN_CHARACTERS,+ allowedCharacterPattern: LINUX_SERVER_NAMING.ALLOWED_CHARACTER_PATTERN,+ maxCertificateNameLength: LINUX_SERVER_NAMING.MAX_NAME_LENGTH,+ minCertificateNameLength: LINUX_SERVER_NAMING.MIN_NAME_LENGTH+} as const;diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.tsnew file mode 100644index 0000000000..2ab5d1bf32--- /dev/null+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts@@ -0,0 +1,345 @@+/* eslint-disable no-await-in-loop */+import crypto from "node:crypto";+import path from "node:path";++import RE2 from "re2";+import { Client } from "ssh2";++import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { logger } from "@app/lib/logger";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { SshConnectionMethod } from "@app/services/app-connection/ssh/ssh-connection-enums";+import { withSshConnection } from "@app/services/app-connection/ssh/ssh-connection-fns";+import { TSshConnectionConfig } from "@app/services/app-connection/ssh/ssh-connection-types";+import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";++import { PkiSyncError } from "../pki-sync-errors";+import { exportCertificateForSync, PkiSyncExportFormat } from "../pki-sync-export-fns";+import { TCertificateMap, TPkiSyncWithCredentials } from "../pki-sync-types";+import { TLinuxServerPkiSyncConfig } from "./linux-server-pki-sync-types";++type TLinuxServerPkiSyncFactoryDeps = {+ certificateSyncDAL: Pick<+ TCertificateSyncDALFactory,+ "findByPkiSyncId" | "findByPkiSyncAndCertificate" | "updateById" | "addCertificates" | "removeCertificates"+ >;+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+};++type TLinuxServerSyncOptions = {+ certificateNameSchema?: string;+ exportFormat?: PkiSyncExportFormat;+ includePrivateKey?: boolean;+ canRemoveCertificates?: boolean;+};++const buildSshConfig = (pkiSync: TPkiSyncWithCredentials): TSshConnectionConfig => {+ const { connection } = pkiSync;+ const credentials = connection.credentials as { privateKey?: string };++ let method: SshConnectionMethod;+ if (connection.method === SshConnectionMethod.SshKey || connection.method === SshConnectionMethod.Password) {+ method = connection.method as SshConnectionMethod;+ } else {+ method = credentials.privateKey ? SshConnectionMethod.SshKey : SshConnectionMethod.Password;+ }++ return {+ app: AppConnection.SSH,+ method,+ credentials: connection.credentials as TSshConnectionConfig["credentials"],+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId,+ orgId: connection.orgId+ } as TSshConnectionConfig;+};++// SFTP surfaces a missing destination directory as an ENOENT "No such file" error; matched so it+// can be reported as an actionable "directory does not exist" message rather than a raw SSH error.+const NO_SUCH_FILE_ERROR = new RE2("no such file", "i");++const openSftp = (client: Client) =>+ new Promise<import("ssh2").SFTPWrapper>((resolve, reject) => {+ client.sftp((err, sftp) => (err ? reject(err) : resolve(sftp)));+ });++const writeFileAtomic = (+ sftp: import("ssh2").SFTPWrapper,+ filePath: string,+ content: Buffer,+ mode: number+): Promise<void> => {+ // A per-write random suffix keeps concurrent syncs (e.g. a manual trigger overlapping an auto-sync)+ // from sharing one temp path and orphaning it: OpenSSH rename is not atomic-overwrite, so we+ // unlink-then-rename, and a shared temp name would let one job recreate the file another just moved.+ const tmpPath = `${filePath}.${crypto.randomBytes(6).toString("hex")}.infisical.tmp`;+ return new Promise<void>((resolve, reject) => {+ const cleanupTmpThen = (finalize: () => void) => sftp.unlink(tmpPath, () => finalize());++ sftp.writeFile(tmpPath, content, { mode }, (writeErr) => {+ if (writeErr) return reject(writeErr);+ // Remove any existing target first for portable rename semantics, then move the temp file in.+ return sftp.unlink(filePath, () => {+ sftp.rename(tmpPath, filePath, (renameErr) => {+ if (renameErr) return cleanupTmpThen(() => reject(renameErr));+ return resolve();+ });+ });+ });+ });+};++const unlinkIfExists = (sftp: import("ssh2").SFTPWrapper, filePath: string): Promise<void> =>+ new Promise<void>((resolve) => {+ sftp.unlink(filePath, () => resolve());+ });++const TEMP_FILE_MARKER = ".infisical.tmp";+// A write completes in seconds, so any temp file older than this was left by an interrupted run+// (dropped connection between write and rename) and is safe to remove even if another sync shares+// this directory.+const STALE_TEMP_AGE_SECONDS = 60;++const sweepStaleTempFiles = (sftp: import("ssh2").SFTPWrapper, dir: string): Promise<void> =>+ new Promise<void>((resolve) => {+ sftp.readdir(dir, (err, entries) => {+ if (err || !entries) return resolve();+ const cutoff = Math.floor(Date.now() / 1000) - STALE_TEMP_AGE_SECONDS;+ const stale = entries.filter((e) => e.filename.endsWith(TEMP_FILE_MARKER) && e.attrs.mtime < cutoff);+ if (stale.length === 0) return resolve();+ let remaining = stale.length;+ stale.forEach((e) => {+ sftp.unlink(path.posix.join(dir, e.filename), () => {+ remaining -= 1;+ if (remaining === 0) resolve();+ });+ });+ return undefined;+ });+ });++export const linuxServerPkiSyncFactory = ({+ certificateSyncDAL,+ gatewayV2Service,+ gatewayPoolService+}: TLinuxServerPkiSyncFactoryDeps) => {+ const syncCertificates = async (+ pkiSync: TPkiSyncWithCredentials,+ certificateMap: TCertificateMap+ ): Promise<{+ uploaded: number;+ removed?: number;+ failedRemovals?: number;+ skipped: number;+ details?: {+ failedUploads?: Array<{ name: string; error: string }>;+ failedRemovals?: Array<{ name: string; error: string }>;+ skippedCertificates?: Array<{ name: string; reason: string }>;+ };+ }> => {+ const config = pkiSync.destinationConfig as TLinuxServerPkiSyncConfig;+ const options = (pkiSync.syncOptions ?? {}) as TLinuxServerSyncOptions;+ const format = options.exportFormat ?? PkiSyncExportFormat.Pem;+ const includePrivateKey = options.includePrivateKey ?? true;+ const canRemoveCertificates = options.canRemoveCertificates ?? false;+ const exportPassword = pkiSync.syncCredentials?.exportPassword;++ const failedUploads: Array<{ name: string; error: string }> = [];+ const failedRemovals: Array<{ name: string; error: string }> = [];+ const skippedCertificates: Array<{ name: string; reason: string }> = [];+ // Paths written for currently-active certificates this run. A renewed cert reuses the same file+ // name as the cert it replaced, so removal reconciliation must not delete a path that was just+ // (re)written here, or a renewal would delete its own freshly delivered file.+ const deliveredPaths = new Set<string>();+ let uploaded = 0;+ let removed = 0;++ const sshConfig = buildSshConfig(pkiSync);++ await withSshConnection(sshConfig, { gatewayV2Service, gatewayPoolService }, async (client) => {+ const sftp = await openSftp(client);+ await sweepStaleTempFiles(sftp, config.destinationPath);++ for (const [baseName, certData] of Object.entries(certificateMap)) {+ const { cert, privateKey, certificateChain, certificateId } = certData;++ if (!cert) {+ skippedCertificates.push({ name: baseName, reason: "Missing certificate data" });+ // eslint-disable-next-line no-continue+ continue;+ }++ // Private key is required for PKCS#12, and for PEM when the operator asked to include it.+ // If the key is not available (external CSR or HSM key), fail rather than deliver a keyless file.+ const keyRequired = format === PkiSyncExportFormat.Pkcs12 || includePrivateKey;+ if (keyRequired && !privateKey) {+ failedUploads.push({+ name: baseName,+ error:+ "Private key is required but is not available for this certificate (for example, it was issued from an external CSR)"+ });+ // eslint-disable-next-line no-continue+ continue;+ }++ try {+ const files = await exportCertificateForSync({+ format,+ certificate: cert,+ certificateChain,+ privateKey,+ includePrivateKey,+ password: exportPassword,+ alias: baseName+ });++ const writtenPaths: string[] = [];+ for (const file of files) {+ const filePath = path.posix.join(config.destinationPath, `${baseName}${file.suffix}`);+ try {+ await writeFileAtomic(sftp, filePath, file.content, file.isPrivateKey ? 0o600 : 0o644);+ } catch (writeErr) {+ const msg = (writeErr as Error)?.message ?? "";+ if (NO_SUCH_FILE_ERROR.test(msg)) {+ throw new PkiSyncError({+ message: `Destination directory "${config.destinationPath}" does not exist or is not writable`+ });+ }+ throw writeErr;+ }+ writtenPaths.push(filePath);+ deliveredPaths.add(filePath);+ }++ // Record the delivered paths so removal and re-sync act on exactly what was written.+ const primaryPath = writtenPaths[0];+ if (typeof certificateId === "string") {+ let record = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);+ if (!record) {+ [record] = await certificateSyncDAL.addCertificates(pkiSync.id, [+ { certificateId, externalIdentifier: primaryPath }+ ]);+ }+ if (record) {+ await certificateSyncDAL.updateById(record.id, {+ externalIdentifier: primaryPath,+ syncMetadata: { files: writtenPaths }+ });+ }+ }++ uploaded += 1;+ logger.info(+ `Linux Server PKI sync [syncId=${pkiSync.id}]: wrote ${writtenPaths.length} file(s) for "${baseName}"`+ );+ } catch (err) {+ failedUploads.push({ name: baseName, error: (err as Error)?.message ?? "Unknown error" });+ }+ }++ // Reconcile removals: delete files for certificates we previously delivered that are no longer+ // in the active set (revoked, expired, or unlinked from the sync), then drop their tracking+ // rows. certificateMap holds the full active set, so anything tracked but absent is orphaned.+ if (canRemoveCertificates) {+ const activeCertificateIds = new Set(+ Object.values(certificateMap)+ .map((certData) => certData.certificateId)+ .filter((id): id is string => typeof id === "string")+ );+ const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);++ for (const record of existingSyncRecords) {+ if (!record.certificateId || activeCertificateIds.has(record.certificateId)) {+ // eslint-disable-next-line no-continue+ continue;+ }+ const files = (record.syncMetadata as { files?: string[] } | undefined)?.files?.length+ ? (record.syncMetadata as { files: string[] }).files+ : [record.externalIdentifier].filter((p): p is string => Boolean(p));+ // Skip any path an active certificate just wrote: on renewal the new cert reuses the old+ // one's file name, so deleting it would remove the freshly delivered file. The stale row is+ // still dropped so the superseded certificate stops being tracked.+ const filesToDelete = files.filter((filePath) => !deliveredPaths.has(filePath));+ try {+ for (const filePath of filesToDelete) {+ await unlinkIfExists(sftp, filePath);+ }+ await certificateSyncDAL.removeCertificates(pkiSync.id, [record.certificateId]);+ if (filesToDelete.length > 0) removed += 1;+ logger.info(+ `Linux Server PKI sync [syncId=${pkiSync.id}]: removed ${filesToDelete.length} orphaned file(s) for certificate ${record.certificateId}`+ );+ } catch (err) {+ failedRemovals.push({+ name: record.externalIdentifier ?? record.certificateId,+ error: (err as Error)?.message ?? "Unknown error"+ });+ }+ }+ }+ });++ return {+ uploaded,+ removed: removed > 0 ? removed : undefined,+ failedRemovals: failedRemovals.length > 0 ? failedRemovals.length : undefined,+ skipped: skippedCertificates.length,+ details: {+ failedUploads: failedUploads.length > 0 ? failedUploads : undefined,+ failedRemovals: failedRemovals.length > 0 ? failedRemovals : undefined,+ skippedCertificates: skippedCertificates.length > 0 ? skippedCertificates : undefined+ }+ };+ };++ const removeCertificates = async (+ pkiSync: TPkiSyncWithCredentials,+ certificateNames: string[],+ deps?: {+ certificateSyncDAL?: Pick<TCertificateSyncDALFactory, "findByPkiSyncId">;+ certificateMap?: TCertificateMap;+ }+ ): Promise<void> => {+ if (certificateNames.length === 0) return;++ const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);+ const pathsToRemove = new Set<string>();+ const certificateIdsToUntrack: string[] = [];++ for (const certName of certificateNames) {+ const certificateId = deps?.certificateMap?.[certName]?.certificateId;+ const record = certificateId ? existingSyncRecords.find((r) => r.certificateId === certificateId) : undefined;+ if (!certificateId || !record) {+ // eslint-disable-next-line no-continue+ continue;+ }+ certificateIdsToUntrack.push(certificateId);+ const files = (record.syncMetadata as { files?: string[] } | undefined)?.files;+ if (files?.length) {+ files.forEach((f) => pathsToRemove.add(f));+ } else if (record.externalIdentifier) {+ pathsToRemove.add(record.externalIdentifier);+ }+ }++ if (pathsToRemove.size > 0) {+ const sshConfig = buildSshConfig(pkiSync);+ await withSshConnection(sshConfig, { gatewayV2Service, gatewayPoolService }, async (client) => {+ const sftp = await openSftp(client);+ for (const filePath of pathsToRemove) {+ await unlinkIfExists(sftp, filePath);+ logger.info(`Linux Server PKI sync [syncId=${pkiSync.id}]: removed "${filePath}"`);+ }+ });+ }++ // Untrack the removed certificates so they are no longer reported as synced and not re-delivered.+ if (certificateIdsToUntrack.length > 0) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, certificateIdsToUntrack);+ }+ };++ return { syncCertificates, removeCertificates };+};diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.test.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.test.tsnew file mode 100644index 0000000000..62f3e06f4f--- /dev/null+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.test.ts@@ -0,0 +1,59 @@+import { LinuxServerPkiSyncConfigSchema, LinuxServerPkiSyncOptionsSchema } from "./linux-server-pki-sync-schemas";++const parseName = (certificateNameSchema: string) =>+ LinuxServerPkiSyncOptionsSchema.safeParse({ certificateNameSchema }).success;++const parsePath = (destinationPath: string) => LinuxServerPkiSyncConfigSchema.safeParse({ destinationPath }).success;++describe("Linux Server certificateNameSchema validation", () => {+ test("accepts a fixed name with no placeholder (single-certificate sync)", () => {+ expect(parseName("server")).toBe(true);+ expect(parseName("my-cert_v1.0")).toBe(true);+ });++ test("accepts the supported placeholders", () => {+ expect(parseName("{{commonName}}")).toBe(true);+ expect(parseName("{{certificateId}}")).toBe(true);+ expect(parseName("cert-{{shortCertificateId}}")).toBe(true);+ expect(parseName("{{profileId}}-{{commonName}}")).toBe(true);+ });++ test("rejects path separators in the compiled name", () => {+ // The name is a single file segment; slashes/backslashes are not allowed. Traversal is+ // impossible from a single segment: a format suffix is always appended (".." -> "...pem").+ expect(parseName("sub/dir")).toBe(false);+ expect(parseName("a\\b")).toBe(false);+ });++ test("rejects characters outside the allowed set", () => {+ expect(parseName("cert*")).toBe(false);+ expect(parseName("cert name")).toBe(false);+ expect(parseName("{{environment}}")).toBe(false);+ });++ test("requires a schema (rejects empty)", () => {+ expect(parseName("")).toBe(false);+ expect(LinuxServerPkiSyncOptionsSchema.safeParse({}).success).toBe(false);+ });+});++describe("Linux Server destinationPath validation", () => {+ test("accepts absolute POSIX paths", () => {+ expect(parsePath("/etc/ssl/certs")).toBe(true);+ expect(parsePath("/home/ec2-user/certs")).toBe(true);+ });++ test("rejects relative paths", () => {+ expect(parsePath("etc/ssl/certs")).toBe(false);+ expect(parsePath("./certs")).toBe(false);+ });++ test("rejects paths containing traversal", () => {+ expect(parsePath("/etc/../etc/certs")).toBe(false);+ expect(parsePath("/certs/..")).toBe(false);+ });++ test("rejects an empty path", () => {+ expect(parsePath("")).toBe(false);+ });+});diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.tsnew file mode 100644index 0000000000..c99894a8bf--- /dev/null+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts@@ -0,0 +1,102 @@+import RE2 from "re2";+import { z } from "zod";++import { openApiHidden } from "@app/server/lib/schemas";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";+import { PkiSyncExportFormat } from "@app/services/pki-sync/pki-sync-export-fns";+import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";++import { LINUX_SERVER_NAMING } from "./linux-server-pki-sync-constants";++const PATH_TRAVERSAL = new RE2("(^|/)\\.\\.(/|$)");++export const LinuxServerPkiSyncConfigSchema = z.object({+ destinationPath: z+ .string()+ .trim()+ .min(1, "Destination path is required")+ .max(4096, "Destination path is too long")+ .refine((p) => p.startsWith("/"), { message: "Destination path must be absolute (start with /)" })+ .refine((p) => !PATH_TRAVERSAL.test(p), { message: "Destination path must not contain '..'" })+});++export const LinuxServerPkiSyncOptionsSchema = z.object({+ canRemoveCertificates: z.boolean().default(false),+ includeRootCa: z.boolean().default(false),+ includePrivateKey: z.boolean().default(true),+ exportFormat: z.nativeEnum(PkiSyncExportFormat).default(PkiSyncExportFormat.Pem),+ certificateNameSchema: z+ .string()+ .trim()+ .min(1, "Certificate name schema is required")+ .refine(+ (schema) => {+ const testName = buildCertificateNameSchemaTestName(schema);+ const hasForbiddenChars = LINUX_SERVER_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) =>+ testName.includes(char)+ );+ return LINUX_SERVER_NAMING.NAME_PATTERN.test(testName) && !hasForbiddenChars;+ },+ {+ message:+ "Certificate name schema must resolve to a single file name of 1-200 characters using only letters, digits, dots (.), dashes (-), and underscores (_). Available placeholders: {{certificateId}}, {{shortCertificateId}}, {{profileId}}, {{applicationId}}, {{applicationName}}, {{commonName}}. A schema with no placeholder can be linked to only one certificate."+ }+ )+});++// Sync-level secrets (the PKCS#12 export password) accepted on create/update. Stored encrypted in+// pki_syncs.encryptedCredentials and never returned.+export const LinuxServerPkiSyncCredentialsSchema = z.object({+ exportPassword: z.string().min(1).optional()+});++export const LinuxServerPkiSyncSchema = PkiSyncSchema.extend({+ destination: z.literal(PkiSync.LinuxServer),+ destinationConfig: LinuxServerPkiSyncConfigSchema,+ syncOptions: LinuxServerPkiSyncOptionsSchema+});++export const CreateLinuxServerPkiSyncSchema = z+ .object({+ name: z.string().trim().min(1).max(256),+ description: z.string().optional(),+ isAutoSyncEnabled: z.boolean().default(true),+ destinationConfig: LinuxServerPkiSyncConfigSchema,+ syncOptions: LinuxServerPkiSyncOptionsSchema,+ credentials: LinuxServerPkiSyncCredentialsSchema.optional(),+ subscriberId: z.string().nullish(),+ connectionId: z.string(),+ projectId: z.string().trim().min(1).optional().describe(openApiHidden()),+ applicationId: z.string().uuid().optional(),+ certificateIds: z.array(z.string().uuid()).optional()+ })+ .superRefine((data, ctx) => {+ if (data.syncOptions.exportFormat === PkiSyncExportFormat.Pkcs12 && !data.credentials?.exportPassword) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["credentials", "exportPassword"],+ message: "A password is required when the export format is PKCS#12"+ });+ }+ });++export const UpdateLinuxServerPkiSyncSchema = z.object({+ name: z.string().trim().min(1).max(256).optional(),+ description: z.string().optional(),+ isAutoSyncEnabled: z.boolean().optional(),+ destinationConfig: LinuxServerPkiSyncConfigSchema.optional(),+ syncOptions: LinuxServerPkiSyncOptionsSchema.optional(),+ credentials: LinuxServerPkiSyncCredentialsSchema.optional(),+ subscriberId: z.string().nullish(),+ connectionId: z.string().optional()+});++export const LinuxServerPkiSyncListItemSchema = z.object({+ name: z.literal("Linux Server"),+ connection: z.literal(AppConnection.SSH),+ destination: z.literal(PkiSync.LinuxServer),+ canImportCertificates: z.literal(false),+ canRemoveCertificates: z.literal(true)+});diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-types.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-types.tsnew file mode 100644index 0000000000..d25d77ce9b--- /dev/null+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-types.ts@@ -0,0 +1,22 @@+import { z } from "zod";++import { TSshConnection } from "@app/services/app-connection/ssh/ssh-connection-types";++import {+ CreateLinuxServerPkiSyncSchema,+ LinuxServerPkiSyncConfigSchema,+ LinuxServerPkiSyncSchema,+ UpdateLinuxServerPkiSyncSchema+} from "./linux-server-pki-sync-schemas";++export type TLinuxServerPkiSyncConfig = z.infer<typeof LinuxServerPkiSyncConfigSchema>;++export type TLinuxServerPkiSync = z.infer<typeof LinuxServerPkiSyncSchema>;++export type TLinuxServerPkiSyncInput = z.infer<typeof CreateLinuxServerPkiSyncSchema>;++export type TLinuxServerPkiSyncUpdate = z.infer<typeof UpdateLinuxServerPkiSyncSchema>;++export type TLinuxServerPkiSyncWithCredentials = TLinuxServerPkiSync & {+ connection: TSshConnection;+};diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.test.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.test.tsindex e6ffdb0c23..91c9937168 100644--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.test.ts+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.test.ts@@ -15,10 +15,9 @@ describe("NetScaler certificateNameSchema validation", () => {expect(parseSchema("{{applicationId}}-{{shortCertificateId}}")).toBe(true);});- test("requires the {{certificateId}} or {{shortCertificateId}} placeholder", () => {- expect(parseSchema("{{commonName}}")).toBe(false);- expect(parseSchema("static-name")).toBe(false);- expect(parseSchema("{{profileId}}-{{applicationId}}")).toBe(false);+ test("accepts a schema with no certificate-id placeholder (single-certificate sync)", () => {+ expect(parseSchema("static-name")).toBe(true);+ expect(parseSchema("{{profileId}}")).toBe(true);});test("rejects the removed placeholders", () => {diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.tsindex 38743e0868..9998cfab56 100644--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts@@ -22,10 +22,6 @@ export const NetScalerPkiSyncOptionsSchema = z.object({.min(1, "Certificate name schema is required").refine((schema) => {- if (!schema.includes("{{certificateId}}") && !schema.includes("{{shortCertificateId}}")) {- return false;- }-const testName = buildCertificateNameSchemaTestName(schema);const hasForbiddenChars = NETSCALER_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) =>@@ -36,7 +32,7 @@ export const NetScalerPkiSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include the {{certificateId}} or {{shortCertificateId}} placeholder and result in names that contain only alphanumeric characters, hyphens (-), underscores (_), and periods (.) and be 1-63 characters long for NetScaler. Available placeholders: {{certificateId}}, {{shortCertificateId}}, {{profileId}}, {{applicationId}}, {{applicationName}}, {{commonName}}"+ "Certificate name schema must result in names that contain only alphanumeric characters, hyphens (-), underscores (_), and periods (.) and be 1-63 characters long for NetScaler. Available placeholders: {{certificateId}}, {{shortCertificateId}}, {{profileId}}, {{applicationId}}, {{applicationName}}, {{commonName}}. A schema with no placeholder can be linked to only one certificate."})});diff --git a/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.ts b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.tsindex dc2fffee8d..0f38cb214f 100644--- a/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.ts+++ b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.ts@@ -202,6 +202,15 @@ describe("sanitizeCertificateNameValue", () => {test("no-op without a destination", () => {expect(sanitizeCertificateNameValue("app.example.com")).toBe("app.example.com");});++ test("strips path separators for server destinations so a common name cannot escape the directory", () => {+ // A malicious common name must not be able to introduce path separators into the on-disk file name.+ expect(sanitizeCertificateNameValue("../../etc/cron.d/evil", PkiSync.LinuxServer)).toBe("..-..-etc-cron.d-evil");+ expect(sanitizeCertificateNameValue("..\\..\\Windows\\evil", PkiSync.WindowsServer)).toBe("..-..-Windows-evil");+ // Dots are kept so legitimate FQDNs survive.+ expect(sanitizeCertificateNameValue("app.example.com", PkiSync.LinuxServer)).toBe("app.example.com");+ expect(sanitizeCertificateNameValue("app.example.com", PkiSync.WindowsServer)).toBe("app.example.com");+ });});describe("buildManagedCertificateNameRegexSource", () => {diff --git a/backend/src/services/pki-sync/pki-sync-certificate-name-fns.ts b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.tsindex fd917d7478..5258802063 100644--- a/backend/src/services/pki-sync/pki-sync-certificate-name-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.ts@@ -40,7 +40,9 @@ const NAME_VALUE_DISALLOWED_CHARS: Partial<Record<PkiSync, RE2>> = {[PkiSync.AwsElasticLoadBalancer]: new RE2("[^a-zA-Z0-9 _-]", "g"),[PkiSync.AwsSecretsManager]: new RE2("[^a-zA-Z0-9_-]", "g"),[PkiSync.NetScaler]: new RE2("[^a-zA-Z0-9._-]", "g"),- [PkiSync.F5BigIp]: new RE2("[^a-zA-Z0-9._-]", "g")+ [PkiSync.F5BigIp]: new RE2("[^a-zA-Z0-9._-]", "g"),+ [PkiSync.LinuxServer]: new RE2("[^a-zA-Z0-9._-]", "g"),+ [PkiSync.WindowsServer]: new RE2("[^a-zA-Z0-9._-]", "g")};export const sanitizeCertificateNameValue = (value: string, destination?: PkiSync): string => {@@ -56,6 +58,12 @@ export const SHORT_UUID_NAME_REGEX_FRAGMENT = "[0-9A-Za-z]{22}";export const certificateNameSchemaHasFreeTextPlaceholder = (schema?: string): boolean =>Boolean(schema && (schema.includes("{{commonName}}") || schema.includes("{{applicationName}}")));+const ANY_PLACEHOLDER_REGEX = new RE2(+ "\\{\\{(certificateId|shortCertificateId|profileId|applicationId|applicationName|commonName)\\}\\}"+);+export const certificateNameSchemaAllowsMultipleCertificates = (schema?: string): boolean =>+ Boolean(schema && ANY_PLACEHOLDER_REGEX.test(schema));+const PLACEHOLDER_OR_CHAR_REGEX = new RE2("\\{\\{(certificateId|shortCertificateId|profileId|applicationId|applicationName|commonName)\\}\\}|[\\s\\S]","g"diff --git a/backend/src/services/pki-sync/pki-sync-credentials-fns.ts b/backend/src/services/pki-sync/pki-sync-credentials-fns.tsnew file mode 100644index 0000000000..7f18f9200e--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-credentials-fns.ts@@ -0,0 +1,46 @@+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";++export type TPkiSyncCredentials = {+ exportPassword?: string;+};++type TKmsService = Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;++export const encryptPkiSyncCredentials = async ({+ orgId,+ projectId,+ credentials,+ kmsService+}: {+ orgId: string;+ projectId: string | null | undefined;+ credentials: TPkiSyncCredentials;+ kmsService: TKmsService;+}): Promise<Buffer> => {+ const { encryptor } = await kmsService.createCipherPairWithDataKey(+ projectId ? { type: KmsDataKey.SecretManager, projectId } : { type: KmsDataKey.Organization, orgId }+ );++ const { cipherTextBlob } = encryptor({ plainText: Buffer.from(JSON.stringify(credentials)) });+ return cipherTextBlob;+};++export const decryptPkiSyncCredentials = async ({+ orgId,+ projectId,+ encryptedCredentials,+ kmsService+}: {+ orgId: string;+ projectId: string | null | undefined;+ encryptedCredentials: Buffer;+ kmsService: TKmsService;+}): Promise<TPkiSyncCredentials> => {+ const { decryptor } = await kmsService.createCipherPairWithDataKey(+ projectId ? { type: KmsDataKey.SecretManager, projectId } : { type: KmsDataKey.Organization, orgId }+ );++ const decrypted = decryptor({ cipherTextBlob: encryptedCredentials });+ return JSON.parse(decrypted.toString()) as TPkiSyncCredentials;+};diff --git a/backend/src/services/pki-sync/pki-sync-enums.ts b/backend/src/services/pki-sync/pki-sync-enums.tsindex 3f1c25d332..6d05db17bd 100644--- a/backend/src/services/pki-sync/pki-sync-enums.ts+++ b/backend/src/services/pki-sync/pki-sync-enums.ts@@ -6,7 +6,9 @@ export enum PkiSync {Chef = "chef",CloudflareCustomCertificate = "cloudflare-custom-certificate",NetScaler = "netscaler",- F5BigIp = "f5-big-ip"+ F5BigIp = "f5-big-ip",+ LinuxServer = "linux-server",+ WindowsServer = "windows-server"}export enum PkiSyncStatus {diff --git a/backend/src/services/pki-sync/pki-sync-export-fns.test.ts b/backend/src/services/pki-sync/pki-sync-export-fns.test.tsnew file mode 100644index 0000000000..145a886e13--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-export-fns.test.ts@@ -0,0 +1,51 @@+import { exportCertificateForSync, PkiSyncExportFormat, TExportedCertificateFile } from "./pki-sync-export-fns";++const CERT = "-----BEGIN CERTIFICATE-----\ncert\n-----END CERTIFICATE-----";+const CHAIN = "-----BEGIN CERTIFICATE-----\nchain\n-----END CERTIFICATE-----";+const KEY = "-----BEGIN PRIVATE KEY-----\nkey\n-----END PRIVATE KEY-----";++const suffixes = (files: TExportedCertificateFile[]) => files.map((f) => f.suffix).sort();++describe("exportCertificateForSync (PEM)", () => {+ test("writes certificate, chain, and key when the key is included", async () => {+ const files = await exportCertificateForSync({+ format: PkiSyncExportFormat.Pem,+ certificate: CERT,+ certificateChain: CHAIN,+ privateKey: KEY,+ includePrivateKey: true,+ alias: "api.example.com"+ });++ expect(suffixes(files)).toEqual([".chain.pem", ".key", ".pem"]);+ const key = files.find((f) => f.suffix === ".key");+ expect(key?.isPrivateKey).toBe(true);+ expect(key?.content.toString()).toBe(KEY);+ expect(files.find((f) => f.suffix === ".pem")?.content.toString()).toBe(CERT);+ });++ test("omits the key file when includePrivateKey is false", async () => {+ const files = await exportCertificateForSync({+ format: PkiSyncExportFormat.Pem,+ certificate: CERT,+ certificateChain: CHAIN,+ privateKey: KEY,+ includePrivateKey: false,+ alias: "api.example.com"+ });++ expect(suffixes(files)).toEqual([".chain.pem", ".pem"]);+ });++ test("omits the chain file when no chain is provided", async () => {+ const files = await exportCertificateForSync({+ format: PkiSyncExportFormat.Pem,+ certificate: CERT,+ privateKey: KEY,+ includePrivateKey: true,+ alias: "api.example.com"+ });++ expect(suffixes(files)).toEqual([".key", ".pem"]);+ });+});diff --git a/backend/src/services/pki-sync/pki-sync-export-fns.ts b/backend/src/services/pki-sync/pki-sync-export-fns.tsnew file mode 100644index 0000000000..fb76571bff--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-export-fns.ts@@ -0,0 +1,63 @@+import { generatePkcs12FromCertificate } from "@app/services/certificate/certificate-fns";++export enum PkiSyncExportFormat {+ Pem = "pem",+ Pkcs12 = "pkcs12"+}++export type TExportedCertificateFile = {+ suffix: string;+ content: Buffer;+ isPrivateKey?: boolean;+};++export type TExportCertificateForSyncParams = {+ format: PkiSyncExportFormat;+ certificate: string;+ certificateChain?: string;+ privateKey?: string;+ includePrivateKey: boolean;+ // Required for PKCS#12.+ password?: string;+ // Friendly name / alias used inside a PKCS#12 keystore.+ alias: string;+};++/**+ * Packages a certificate for delivery to a server. The extension is decided here from the format,+ * never from the caller's name schema (the schema only provides the base name):+ * - PEM -> "<base>.pem" (cert), "<base>.chain.pem" (chain), "<base>.key" (key, when included)+ * - PKCS#12 -> "<base>.pfx" (cert + chain + key, password-protected)+ *+ * The caller is responsible for deciding whether the private key is available and whether it is+ * required (see the destination factories, which fail the certificate when includePrivateKey is set+ * but the key cannot be exported). This helper assumes inputs are valid and only guards PKCS#12.+ */+export const exportCertificateForSync = ({+ format,+ certificate,+ certificateChain,+ privateKey,+ includePrivateKey,+ password,+ alias+}: TExportCertificateForSyncParams): Promise<TExportedCertificateFile[]> | TExportedCertificateFile[] => {+ if (format === PkiSyncExportFormat.Pkcs12) {+ return generatePkcs12FromCertificate({+ certificate,+ certificateChain: certificateChain ?? "",+ privateKey: privateKey ?? "",+ password: password ?? "",+ alias+ }).then((pfx) => [{ suffix: ".pfx", content: pfx }]);+ }++ const files: TExportedCertificateFile[] = [{ suffix: ".pem", content: Buffer.from(certificate, "utf8") }];+ if (certificateChain) {+ files.push({ suffix: ".chain.pem", content: Buffer.from(certificateChain, "utf8") });+ }+ if (includePrivateKey && privateKey) {+ files.push({ suffix: ".key", content: Buffer.from(privateKey, "utf8"), isPrivateKey: true });+ }+ return files;+};diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.tsindex 429f265db1..26fd780f2c 100644--- a/backend/src/services/pki-sync/pki-sync-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.ts@@ -24,6 +24,8 @@ import { CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION } from "./cloudflareimport { cloudflareCustomCertificatePkiSyncFactory } from "./cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-fns";import { F5_BIG_IP_PKI_SYNC_LIST_OPTION } from "./f5-big-ip/f5-big-ip-pki-sync-constants";import { f5BigIpPkiSyncFactory } from "./f5-big-ip/f5-big-ip-pki-sync-fns";+import { LINUX_SERVER_PKI_SYNC_LIST_OPTION } from "./linux-server/linux-server-pki-sync-constants";+import { linuxServerPkiSyncFactory } from "./linux-server/linux-server-pki-sync-fns";import { NETSCALER_PKI_SYNC_LIST_OPTION } from "./netscaler/netscaler-pki-sync-constants";import { netScalerPkiSyncFactory } from "./netscaler/netscaler-pki-sync-fns";import {@@ -33,6 +35,8 @@ import {} from "./pki-sync-certificate-name-fns";import { PkiSync } from "./pki-sync-enums";import { TCertificateMap, TPkiSyncWithCredentials } from "./pki-sync-types";+import { WINDOWS_SERVER_PKI_SYNC_LIST_OPTION } from "./windows-server/windows-server-pki-sync-constants";+import { windowsServerPkiSyncFactory } from "./windows-server/windows-server-pki-sync-fns";const ENTERPRISE_PKI_SYNCS: PkiSync[] = [];@@ -44,7 +48,9 @@ const PKI_SYNC_LIST_OPTIONS = {[PkiSync.Chef]: CHEF_PKI_SYNC_LIST_OPTION,[PkiSync.CloudflareCustomCertificate]: CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION,[PkiSync.NetScaler]: NETSCALER_PKI_SYNC_LIST_OPTION,- [PkiSync.F5BigIp]: F5_BIG_IP_PKI_SYNC_LIST_OPTION+ [PkiSync.F5BigIp]: F5_BIG_IP_PKI_SYNC_LIST_OPTION,+ [PkiSync.LinuxServer]: LINUX_SERVER_PKI_SYNC_LIST_OPTION,+ [PkiSync.WindowsServer]: WINDOWS_SERVER_PKI_SYNC_LIST_OPTION};export const enterprisePkiSyncCheck = async (@@ -160,6 +166,12 @@ export const PkiSyncFns = {case PkiSync.F5BigIp: {throw new Error("F5 BIG-IP does not support importing certificates into Infisical");}+ case PkiSync.LinuxServer: {+ throw new Error("Linux Server does not support importing certificates into Infisical");+ }+ case PkiSync.WindowsServer: {+ throw new Error("Windows Server does not support importing certificates into Infisical");+ }default:throw new Error(`Unsupported PKI sync destination: ${String(pkiSync.destination)}`);}@@ -263,6 +275,27 @@ export const PkiSyncFns = {});return f5BigIpPkiSync.syncCertificates(pkiSync, certificateMap);}+ case PkiSync.LinuxServer: {+ checkPkiSyncDestination(pkiSync, PkiSync.LinuxServer as PkiSync);+ const linuxServerPkiSync = linuxServerPkiSyncFactory({+ certificateSyncDAL: dependencies.certificateSyncDAL,+ gatewayV2Service: dependencies.gatewayV2Service,+ gatewayPoolService: dependencies.gatewayPoolService+ });+ return linuxServerPkiSync.syncCertificates(pkiSync, certificateMap);+ }+ case PkiSync.WindowsServer: {+ checkPkiSyncDestination(pkiSync, PkiSync.WindowsServer as PkiSync);+ if (!dependencies.gatewayV2Service) {+ throw new Error("Windows Server sync requires a gateway to reach the host.");+ }+ const windowsServerPkiSync = windowsServerPkiSyncFactory({+ certificateSyncDAL: dependencies.certificateSyncDAL,+ gatewayV2Service: dependencies.gatewayV2Service,+ gatewayPoolService: dependencies.gatewayPoolService+ });+ return windowsServerPkiSync.syncCertificates(pkiSync, certificateMap);+ }default:throw new Error(`Unsupported PKI sync destination: ${String(pkiSync.destination)}`);}@@ -385,6 +418,34 @@ export const PkiSyncFns = {});break;}+ case PkiSync.LinuxServer: {+ checkPkiSyncDestination(pkiSync, PkiSync.LinuxServer as PkiSync);+ const linuxServerPkiSync = linuxServerPkiSyncFactory({+ certificateSyncDAL: dependencies.certificateSyncDAL,+ gatewayV2Service: dependencies.gatewayV2Service,+ gatewayPoolService: dependencies.gatewayPoolService+ });+ await linuxServerPkiSync.removeCertificates(pkiSync, certificateNames, {+ certificateSyncDAL: dependencies.certificateSyncDAL,+ certificateMap: dependencies.certificateMap+ });+ break;+ }+ case PkiSync.WindowsServer: {+ checkPkiSyncDestination(pkiSync, PkiSync.WindowsServer as PkiSync);+ if (!dependencies.gatewayV2Service) {+ throw new Error("Windows Server sync requires a gateway to reach the host.");+ }+ const windowsServerPkiSync = windowsServerPkiSyncFactory({+ certificateSyncDAL: dependencies.certificateSyncDAL,+ gatewayV2Service: dependencies.gatewayV2Service,+ gatewayPoolService: dependencies.gatewayPoolService+ });+ await windowsServerPkiSync.removeCertificates(pkiSync, certificateNames, {+ certificateMap: dependencies.certificateMap+ });+ break;+ }default:throw new Error(`Unsupported PKI sync destination: ${String(pkiSync.destination)}`);}diff --git a/backend/src/services/pki-sync/pki-sync-maps.ts b/backend/src/services/pki-sync/pki-sync-maps.tsindex d822b2553f..9c09b8729d 100644--- a/backend/src/services/pki-sync/pki-sync-maps.ts+++ b/backend/src/services/pki-sync/pki-sync-maps.ts@@ -10,7 +10,9 @@ export const PKI_SYNC_NAME_MAP: Record<PkiSync, string> = {[PkiSync.Chef]: "Chef",[PkiSync.CloudflareCustomCertificate]: "Cloudflare Custom SSL Certificate",[PkiSync.NetScaler]: "NetScaler",- [PkiSync.F5BigIp]: "F5 BIG-IP"+ [PkiSync.F5BigIp]: "F5 BIG-IP",+ [PkiSync.LinuxServer]: "Linux Server",+ [PkiSync.WindowsServer]: "Windows Server"};export const PKI_SYNC_CONNECTION_MAP: Record<PkiSync, AppConnection> = {@@ -21,5 +23,7 @@ export const PKI_SYNC_CONNECTION_MAP: Record<PkiSync, AppConnection> = {[PkiSync.Chef]: AppConnection.Chef,[PkiSync.CloudflareCustomCertificate]: AppConnection.Cloudflare,[PkiSync.NetScaler]: AppConnection.NetScaler,- [PkiSync.F5BigIp]: AppConnection.F5BigIp+ [PkiSync.F5BigIp]: AppConnection.F5BigIp,+ [PkiSync.LinuxServer]: AppConnection.SSH,+ [PkiSync.WindowsServer]: AppConnection.WinRM};diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.tsindex a0df4b1437..8a34949a4d 100644--- a/backend/src/services/pki-sync/pki-sync-queue.ts+++ b/backend/src/services/pki-sync/pki-sync-queue.ts@@ -4,6 +4,7 @@ import * as x509 from "@peculiar/x509";import { AxiosError } from "axios";import { Job } from "bullmq";import { randomUUID } from "crypto";+import RE2 from "re2";import { TCertificates } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";@@ -17,6 +18,8 @@ import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";+// eslint-disable-next-line import/order+import { decryptPkiSyncCredentials } from "@app/services/pki-sync/pki-sync-credentials-fns";import { TProjectDALFactory } from "@app/services/project/project-dal";import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";@@ -82,6 +85,9 @@ type PkiSyncActionJob = Job<const JITTER_MS = 10 * 1000;const REQUEUE_MS = 30 * 1000;const REQUEUE_LIMIT = 30;++const DASH_REGEX = new RE2("-", "g");+const NON_ALPHANUMERIC_REGEX = new RE2("[^a-zA-Z0-9]", "g");const CONNECTION_CONCURRENCY_LIMIT = 3;const getRequeueDelay = (failureCount?: number) => {@@ -302,20 +308,20 @@ export const pkiSyncQueueFactory = ({);} else {const stableId = cert.profileId- ? `${cert.profileId.replace(/-/g, "")}-${(cert.commonName || "").replace(/[^a-zA-Z0-9]/g, "")}`- : certificate.id.replace(/-/g, "");+ ? `${cert.profileId.replace(DASH_REGEX, "")}-${(cert.commonName || "").replace(NON_ALPHANUMERIC_REGEX, "")}`+ : certificate.id.replace(DASH_REGEX, "");certificateName = `Infisical-${stableId}`;}const alternativeNames: string[] = [];- const legacyName = `Infisical-${certificate.id.replace(/-/g, "")}`;+ const legacyName = `Infisical-${certificate.id.replace(DASH_REGEX, "")}`;if (legacyName !== certificateName) {alternativeNames.push(legacyName);}if (cert.renewedFromCertificateId) {- const originalLegacyName = `Infisical-${cert.renewedFromCertificateId.replace(/-/g, "")}`;+ const originalLegacyName = `Infisical-${cert.renewedFromCertificateId.replace(DASH_REGEX, "")}`;alternativeNames.push(originalLegacyName);}@@ -448,13 +454,23 @@ export const pkiSyncQueueFactory = ({projectId: appConnectionProjectId});+ const syncCredentials = pkiSync.encryptedCredentials+ ? await decryptPkiSyncCredentials({+ orgId,+ projectId: pkiSync.projectId,+ encryptedCredentials: pkiSync.encryptedCredentials,+ kmsService+ })+ : undefined;+const pkiSyncWithCredentials = {...pkiSync,connection: {...pkiSync.connection,credentials,projectType: project?.type- }+ },+ syncCredentials} as TPkiSyncWithCredentials;const { certificateMap, certificateMetadata } = await $getInfisicalCertificates(pkiSync);@@ -714,7 +730,7 @@ export const pkiSyncQueueFactory = ({const $handleRemoveCertificatesJob = async (job: TPkiSyncRemoveCertificatesDTO, pkiSync: TPkiSyncRaw) => {const {- data: { syncId, auditLogInfo, deleteSyncOnComplete }+ data: { syncId, auditLogInfo, deleteSyncOnComplete, certificateIds: certificateIdsToRemove }} = job;await enterprisePkiSyncCheck(@@ -755,7 +771,14 @@ export const pkiSyncQueueFactory = ({projectId: appConnectionProjectId});- const { certificateMap } = await $getInfisicalCertificates(pkiSync);+ const certificateMap: TCertificateMap = certificateIdsToRemove?.length+ ? Object.fromEntries(+ certificateIdsToRemove.map((certId, index) => [+ `certificate-${index}`,+ { cert: "", privateKey: "", certificateId: certId }+ ])+ )+ : (await $getInfisicalCertificates(pkiSync)).certificateMap;await PkiSyncFns.removeCertificates({@@ -778,6 +801,12 @@ export const pkiSyncQueueFactory = ({});+ // Untrack the removed certs only after their files are gone, so a failed removal keeps the+ // tracking row (and its paths) for a retry rather than orphaning the files.+ if (certificateIdsToRemove?.length) {+ await certificateSyncDAL.removeCertificates(syncId, certificateIdsToRemove);+ }+isSuccess = true;} catch (err) {logger.error(diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.tsindex fe1a0cd735..9fe07ca2d5 100644--- a/backend/src/services/pki-sync/pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts@@ -26,18 +26,11 @@ export const PkiSyncOptionsSchema = z.object({.join("|");const allowedContentRegex = new RE2(`^([a-zA-Z0-9_\\-/]|${allowedPlaceholdersRegexPart})*$`);- const contentIsValid = allowedContentRegex.test(val);-- if (val.trim()) {- const certificateIdIsPresent = val.includes("{{certificateId}}") || val.includes("{{shortCertificateId}}");- return contentIsValid && certificateIdIsPresent;- }-- return contentIsValid;+ return allowedContentRegex.test(val);},{message:- "Certificate name schema must include the {{certificateId}} or {{shortCertificateId}} placeholder. It can also include {{profileId}}, {{applicationId}}, {{applicationName}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed besides the placeholders."+ "Certificate name schema may include the {{certificateId}}, {{shortCertificateId}}, {{profileId}}, {{applicationId}}, {{applicationName}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed besides the placeholders. A schema with no placeholder can be linked to only one certificate."})});diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex a83d7f9312..f8bfede0dd 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -13,12 +13,15 @@ import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError }import { OrgServiceActor } from "@app/lib/types";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TPkiSubscriberDALFactory } from "@app/services/pki-subscriber/pki-subscriber-dal";import { TCertificateDALFactory } from "../certificate/certificate-dal";import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";import { CertificateSyncStatus } from "../certificate-sync/certificate-sync-enums";import { TSyncMetadata } from "../certificate-sync/certificate-sync-schemas";+import { certificateNameSchemaAllowsMultipleCertificates } from "./pki-sync-certificate-name-fns";+import { encryptPkiSyncCredentials } from "./pki-sync-credentials-fns";import { TPkiSyncDALFactory } from "./pki-sync-dal";import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";import { enterprisePkiSyncCheck, getPkiSyncProviderCapabilities, listPkiSyncOptions } from "./pki-sync-fns";@@ -75,6 +78,7 @@ type TPkiSyncServiceFactoryDep = {appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;pkiSyncQueue: Pick<TPkiSyncQueueFactory,"queuePkiSyncSyncCertificatesById" | "queuePkiSyncImportCertificatesById" | "queuePkiSyncRemoveCertificatesById"@@ -91,6 +95,7 @@ export const pkiSyncServiceFactory = ({appConnectionService,permissionService,licenseService,+ kmsService,pkiSyncQueue}: TPkiSyncServiceFactoryDep) => {const $resourceFallback = async (@@ -190,6 +195,20 @@ export const pkiSyncServiceFactory = ({});}};++ const assertSchemaAllowsCertificateCount = (+ syncOptions: Record<string, unknown> | undefined,+ resultingCertificateCount: number+ ) => {+ const schema = syncOptions?.certificateNameSchema as string | undefined;+ if (resultingCertificateCount > 1 && !certificateNameSchemaAllowsMultipleCertificates(schema)) {+ throw new BadRequestError({+ message:+ "This sync's certificate name schema has no placeholder, so it can be linked to only one certificate. Add a placeholder such as {{commonName}} or {{certificateId}} to sync multiple certificates."+ });+ }+ };+const createPkiSync = async ({name,@@ -202,7 +221,8 @@ export const pkiSyncServiceFactory = ({connectionId,projectId,applicationId,- certificateIds = []+ certificateIds = [],+ credentials}: Omit<TCreatePkiSyncDTO, "auditLogInfo">,actor: OrgServiceActor): Promise<TPkiSync> => {@@ -247,8 +267,13 @@ export const pkiSyncServiceFactory = ({if (certificateIds.length > 0) {await validateCertificatesForSync(certificateIds, projectId, applicationId);+ assertSchemaAllowsCertificateCount(resolvedSyncOptions, certificateIds.length);}+ const encryptedCredentials = credentials?.exportPassword+ ? await encryptPkiSyncCredentials({ orgId: actor.orgId, projectId, credentials, kmsService })+ : undefined;+try {const pkiSync = await pkiSyncDAL.create({name,@@ -257,6 +282,7 @@ export const pkiSyncServiceFactory = ({isAutoSyncEnabled,destinationConfig,syncOptions: resolvedSyncOptions,+ encryptedCredentials,subscriberId,connectionId,projectId,@@ -297,7 +323,8 @@ export const pkiSyncServiceFactory = ({syncOptions,subscriberId,connectionId,- certificateIds+ certificateIds,+ credentials}: Omit<TUpdatePkiSyncDTO, "auditLogInfo" | "projectId">,actor: OrgServiceActor): Promise<TPkiSync> => {@@ -383,9 +410,12 @@ export const pkiSyncServiceFactory = ({};}+ const effectiveSyncOptions = (resolvedSyncOptions ?? pkiSync.syncOptions) as Record<string, unknown> | undefined;+if (certificateIds !== undefined) {if (certificateIds.length > 0) {await validateCertificatesForSync(certificateIds, pkiSync.projectId, pkiSync.applicationId);+ assertSchemaAllowsCertificateCount(effectiveSyncOptions, certificateIds.length);}await certificateSyncDAL.removeAllCertificatesFromSync(id);@@ -395,8 +425,15 @@ export const pkiSyncServiceFactory = ({certificateIds.map((certId) => ({ certificateId: certId })));}+ } else if (syncOptions) {+ const existingCount = (await certificateSyncDAL.findByPkiSyncId(id)).length;+ assertSchemaAllowsCertificateCount(effectiveSyncOptions, existingCount);}+ const encryptedCredentials = credentials?.exportPassword+ ? await encryptPkiSyncCredentials({ orgId: actor.orgId, projectId: pkiSync.projectId, credentials, kmsService })+ : undefined;+const updatedPkiSync = await pkiSyncDAL.updateById(id, {name,description,@@ -404,7 +441,8 @@ export const pkiSyncServiceFactory = ({destinationConfig,syncOptions: resolvedSyncOptions,subscriberId,- connectionId+ connectionId,+ ...(encryptedCredentials ? { encryptedCredentials } : {})});return updatedPkiSync as TPkiSync;@@ -694,6 +732,12 @@ export const pkiSyncServiceFactory = ({await validateCertificatesForSync(certificateIds, pkiSync.projectId, pkiSync.applicationId);+ const existingCount = (await certificateSyncDAL.findByPkiSyncId(pkiSyncId)).length;+ assertSchemaAllowsCertificateCount(+ pkiSync.syncOptions as Record<string, unknown> | undefined,+ existingCount + certificateIds.length+ );+const addedCertificates = await certificateSyncDAL.addCertificates(pkiSyncId,certificateIds.map((id) => ({ certificateId: id }))@@ -737,10 +781,16 @@ export const pkiSyncServiceFactory = ({actor);- const removedCount = await certificateSyncDAL.removeCertificates(pkiSyncId, certificateIds);-- if (pkiSync.isAutoSyncEnabled) {- await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSyncId });+ const syncOptions = pkiSync.syncOptions as { canRemoveCertificates?: boolean } | undefined;+ let removedCount: number;+ if (syncOptions?.canRemoveCertificates) {+ await pkiSyncQueue.queuePkiSyncRemoveCertificatesById({ syncId: pkiSyncId, certificateIds });+ removedCount = certificateIds.length;+ } else {+ removedCount = await certificateSyncDAL.removeCertificates(pkiSyncId, certificateIds);+ if (pkiSync.isAutoSyncEnabled) {+ await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSyncId });+ }}return {diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.tsindex 7d0cfe2222..2d167e7eae 100644--- a/backend/src/services/pki-sync/pki-sync-types.ts+++ b/backend/src/services/pki-sync/pki-sync-types.ts@@ -66,10 +66,12 @@ export type TPkiSyncWithCredentials = TPkiSync & {name: string;app: string;credentials: Record<string, unknown>;+ method?: string;orgId: string;gatewayId?: string;gatewayPoolId?: string | null;};+ syncCredentials?: { exportPassword?: string };};export type TPkiSyncListItem = TPkiSync & {@@ -103,6 +105,7 @@ export type TCreatePkiSyncDTO = {projectId: string;applicationId?: string;certificateIds?: string[];+ credentials?: { exportPassword?: string };auditLogInfo: AuditLogInfo;resourceInternalMetadata?: ResourceMetadataDTO;};@@ -119,6 +122,7 @@ export type TUpdatePkiSyncDTO = {subscriberId?: string | null;connectionId?: string;certificateIds?: string[];+ credentials?: { exportPassword?: string };auditLogInfo: AuditLogInfo;resourceInternalMetadata?: ResourceMetadataDTO;};@@ -232,6 +236,7 @@ export type TQueuePkiSyncRemoveCertificatesByIdDTO = {syncId: string;auditLogInfo?: AuditLogInfo;deleteSyncOnComplete?: boolean;+ certificateIds?: string[];};export type TPkiSyncSyncCertificatesDTO = Job<diff --git a/backend/src/services/pki-sync/windows-server/index.ts b/backend/src/services/pki-sync/windows-server/index.tsnew file mode 100644index 0000000000..189a12c711--- /dev/null+++ b/backend/src/services/pki-sync/windows-server/index.ts@@ -0,0 +1,4 @@+export * from "./windows-server-pki-sync-constants";+export * from "./windows-server-pki-sync-fns";+export * from "./windows-server-pki-sync-schemas";+export * from "./windows-server-pki-sync-types";diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-constants.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-constants.tsnew file mode 100644index 0000000000..57bded597b--- /dev/null+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-constants.ts@@ -0,0 +1,30 @@+import RE2 from "re2";++import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";++/**+ * Windows Server file-name constraints. The certificate name schema produces the file's base name+ * (the export format appends the extension). The base must be a single path segment, so path+ * separators, traversal, and characters Windows forbids in file names are disallowed.+ */+export const WINDOWS_SERVER_NAMING = {+ NAME_PATTERN: new RE2("^[a-zA-Z0-9._-]{1,200}$"),+ FORBIDDEN_CHARACTERS: '/\\\0:*?"<>|',+ MAX_NAME_LENGTH: 200,+ MIN_NAME_LENGTH: 1,+ ALLOWED_CHARACTER_PATTERN: "^[a-zA-Z0-9._-]{1,200}$"+} as const;++export const WINDOWS_SERVER_PKI_SYNC_LIST_OPTION = {+ name: "Windows Server" as const,+ connection: AppConnection.WinRM,+ destination: PkiSync.WindowsServer,+ canImportCertificates: false,+ canRemoveCertificates: true,+ defaultCertificateNameSchema: "{{commonName}}",+ forbiddenCharacters: WINDOWS_SERVER_NAMING.FORBIDDEN_CHARACTERS,+ allowedCharacterPattern: WINDOWS_SERVER_NAMING.ALLOWED_CHARACTER_PATTERN,+ maxCertificateNameLength: WINDOWS_SERVER_NAMING.MAX_NAME_LENGTH,+ minCertificateNameLength: WINDOWS_SERVER_NAMING.MIN_NAME_LENGTH+} as const;diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.tsnew file mode 100644index 0000000000..30305fcab1--- /dev/null+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts@@ -0,0 +1,258 @@+/* eslint-disable no-await-in-loop */+import RE2 from "re2";++import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { executeWinRMGatewayOperation, TWinRMConnection, TWinRMCredentials } from "@app/services/app-connection/winrm";+import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";++import { exportCertificateForSync, PkiSyncExportFormat } from "../pki-sync-export-fns";+import { TCertificateMap, TPkiSyncWithCredentials } from "../pki-sync-types";+import { TWindowsServerPkiSyncConfig } from "./windows-server-pki-sync-types";++type TWindowsServerPkiSyncFactoryDeps = {+ certificateSyncDAL: Pick<+ TCertificateSyncDALFactory,+ "findByPkiSyncId" | "findByPkiSyncAndCertificate" | "updateById" | "addCertificates" | "removeCertificates"+ >;+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+};++type TWindowsServerSyncOptions = {+ certificateNameSchema?: string;+ exportFormat?: PkiSyncExportFormat;+ includePrivateKey?: boolean;+ canRemoveCertificates?: boolean;+};++const TRAILING_BACKSLASH = new RE2("\\\\+$");+const winPathJoin = (dir: string, name: string): string => `${dir.replace(TRAILING_BACKSLASH, "")}\\${name}`;++const buildWinRMTarget = (pkiSync: TPkiSyncWithCredentials) => {+ const { connection } = pkiSync;+ const credentials = connection.credentials as TWinRMConnection["credentials"];++ const winrmCredentials: TWinRMCredentials = {+ host: credentials.host,+ port: credentials.port ?? 5985,+ username: credentials.username,+ password: credentials.password,+ useHttps: credentials.useHttps,+ insecure: credentials.insecure+ };++ return {+ credentials: winrmCredentials,+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ };+};++export const windowsServerPkiSyncFactory = ({+ certificateSyncDAL,+ gatewayV2Service,+ gatewayPoolService+}: TWindowsServerPkiSyncFactoryDeps) => {+ const gatewayDeps = { gatewayV2Service, gatewayPoolService };++ const syncCertificates = async (+ pkiSync: TPkiSyncWithCredentials,+ certificateMap: TCertificateMap+ ): Promise<{+ uploaded: number;+ removed?: number;+ failedRemovals?: number;+ skipped: number;+ details?: {+ failedUploads?: Array<{ name: string; error: string }>;+ failedRemovals?: Array<{ name: string; error: string }>;+ skippedCertificates?: Array<{ name: string; reason: string }>;+ };+ }> => {+ const config = pkiSync.destinationConfig as TWindowsServerPkiSyncConfig;+ const options = (pkiSync.syncOptions ?? {}) as TWindowsServerSyncOptions;+ const format = options.exportFormat ?? PkiSyncExportFormat.Pkcs12;+ const includePrivateKey = options.includePrivateKey ?? true;+ const canRemoveCertificates = options.canRemoveCertificates ?? false;+ const exportPassword = pkiSync.syncCredentials?.exportPassword;++ const failedUploads: Array<{ name: string; error: string }> = [];+ const failedRemovals: Array<{ name: string; error: string }> = [];+ const skippedCertificates: Array<{ name: string; reason: string }> = [];+ // Paths written for currently-active certificates this run. A renewed cert reuses the same file+ // name as the cert it replaced, so removal reconciliation must not delete a path that was just+ // (re)written here, or a renewal would delete its own freshly delivered file.+ const deliveredPaths = new Set<string>();+ const target = buildWinRMTarget(pkiSync);+ let uploaded = 0;+ let removed = 0;++ // Deliver each certificate over its own gateway operation so one certificate's failure is+ // recorded against that certificate only, rather than failing the whole batch.+ for (const [baseName, certData] of Object.entries(certificateMap)) {+ const { cert, privateKey, certificateChain, certificateId } = certData;++ if (!cert) {+ skippedCertificates.push({ name: baseName, reason: "Missing certificate data" });+ // eslint-disable-next-line no-continue+ continue;+ }++ const keyRequired = format === PkiSyncExportFormat.Pkcs12 || includePrivateKey;+ if (keyRequired && !privateKey) {+ failedUploads.push({+ name: baseName,+ error:+ "Private key is required but is not available for this certificate (for example, it was issued from an external CSR)"+ });+ // eslint-disable-next-line no-continue+ continue;+ }++ try {+ const exported = await exportCertificateForSync({+ format,+ certificate: cert,+ certificateChain,+ privateKey,+ includePrivateKey,+ password: exportPassword,+ alias: baseName+ });++ const paths: string[] = [];+ const files: Array<{ path: string; contentBase64: string }> = [];+ for (const file of exported) {+ const fullPath = winPathJoin(config.destinationPath, `${baseName}${file.suffix}`);+ files.push({ path: fullPath, contentBase64: file.content.toString("base64") });+ paths.push(fullPath);+ deliveredPaths.add(fullPath);+ }++ await executeWinRMGatewayOperation({ ...target, endpoint: "/v1/deliver", params: { files } }, gatewayDeps);++ if (typeof certificateId === "string") {+ let record = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);+ if (!record) {+ [record] = await certificateSyncDAL.addCertificates(pkiSync.id, [+ { certificateId, externalIdentifier: paths[0] }+ ]);+ }+ if (record) {+ await certificateSyncDAL.updateById(record.id, {+ externalIdentifier: paths[0],+ syncMetadata: { files: paths }+ });+ }+ }+ uploaded += 1;+ } catch (err) {+ failedUploads.push({ name: baseName, error: (err as Error)?.message ?? "Unknown error" });+ }+ }++ // Reconcile removals: delete files for certificates we previously delivered that are no longer+ // in the active set (revoked, expired, or unlinked from the sync), then drop their tracking rows.+ // certificateMap holds the full active set, so anything tracked but absent is orphaned.+ if (canRemoveCertificates) {+ const activeCertificateIds = new Set(+ Object.values(certificateMap)+ .map((certData) => certData.certificateId)+ .filter((id): id is string => typeof id === "string")+ );+ const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);+ const orphans = existingSyncRecords.filter(+ (record) => record.certificateId && !activeCertificateIds.has(record.certificateId)+ );++ if (orphans.length > 0) {+ // Skip any path an active certificate just wrote: on renewal the new cert reuses the old+ // one's file name, so deleting it would remove the freshly delivered file. The stale rows are+ // still dropped so superseded certificates stop being tracked.+ const orphanPaths = orphans+ .flatMap((record) => {+ const files = (record.syncMetadata as { files?: string[] } | undefined)?.files;+ return files?.length ? files : [record.externalIdentifier].filter((p): p is string => Boolean(p));+ })+ .filter((filePath) => !deliveredPaths.has(filePath));++ try {+ if (orphanPaths.length > 0) {+ await executeWinRMGatewayOperation(+ { ...target, endpoint: "/v1/remove", params: { paths: orphanPaths } },+ gatewayDeps+ );+ }+ await certificateSyncDAL.removeCertificates(+ pkiSync.id,+ orphans.map((record) => record.certificateId)+ );+ removed = orphanPaths.length > 0 ? orphans.length : 0;+ } catch (err) {+ failedRemovals.push({+ name: `${orphans.length} certificate(s)`,+ error: (err as Error)?.message ?? "Unknown error"+ });+ }+ }+ }++ return {+ uploaded,+ removed: removed > 0 ? removed : undefined,+ failedRemovals: failedRemovals.length > 0 ? failedRemovals.length : undefined,+ skipped: skippedCertificates.length,+ details: {+ failedUploads: failedUploads.length > 0 ? failedUploads : undefined,+ failedRemovals: failedRemovals.length > 0 ? failedRemovals : undefined,+ skippedCertificates: skippedCertificates.length > 0 ? skippedCertificates : undefined+ }+ };+ };++ const removeCertificates = async (+ pkiSync: TPkiSyncWithCredentials,+ certificateNames: string[],+ deps?: {+ certificateMap?: TCertificateMap;+ }+ ): Promise<void> => {+ if (certificateNames.length === 0) return;++ const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);+ const pathsToRemove = new Set<string>();+ const certificateIdsToUntrack: string[] = [];++ for (const certName of certificateNames) {+ const certificateId = deps?.certificateMap?.[certName]?.certificateId;+ const record = certificateId ? existingSyncRecords.find((r) => r.certificateId === certificateId) : undefined;+ if (!certificateId || !record) {+ // eslint-disable-next-line no-continue+ continue;+ }+ certificateIdsToUntrack.push(certificateId);+ const recordFiles = (record.syncMetadata as { files?: string[] } | undefined)?.files;+ if (recordFiles?.length) {+ recordFiles.forEach((f) => pathsToRemove.add(f));+ } else if (record.externalIdentifier) {+ pathsToRemove.add(record.externalIdentifier);+ }+ }++ if (pathsToRemove.size > 0) {+ const target = buildWinRMTarget(pkiSync);+ await executeWinRMGatewayOperation(+ { ...target, endpoint: "/v1/remove", params: { paths: Array.from(pathsToRemove) } },+ gatewayDeps+ );+ }++ // Untrack the removed certificates so they are no longer reported as synced and not re-delivered.+ if (certificateIdsToUntrack.length > 0) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, certificateIdsToUntrack);+ }+ };++ return { syncCertificates, removeCertificates };+};diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.test.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.test.tsnew file mode 100644index 0000000000..d0a94db3fd--- /dev/null+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.test.ts@@ -0,0 +1,58 @@+import { WindowsServerPkiSyncConfigSchema, WindowsServerPkiSyncOptionsSchema } from "./windows-server-pki-sync-schemas";++const parseName = (certificateNameSchema: string) =>+ WindowsServerPkiSyncOptionsSchema.safeParse({ certificateNameSchema }).success;++const parsePath = (destinationPath: string) => WindowsServerPkiSyncConfigSchema.safeParse({ destinationPath }).success;++describe("Windows Server certificateNameSchema validation", () => {+ test("accepts a fixed name with no placeholder (single-certificate sync)", () => {+ expect(parseName("server")).toBe(true);+ expect(parseName("my-cert_v1.0")).toBe(true);+ });++ test("accepts the supported placeholders", () => {+ expect(parseName("{{commonName}}")).toBe(true);+ expect(parseName("{{certificateId}}")).toBe(true);+ expect(parseName("cert-{{shortCertificateId}}")).toBe(true);+ });++ test("rejects path separators and forbidden characters", () => {+ expect(parseName("sub/dir")).toBe(false);+ expect(parseName("a\\b")).toBe(false);+ expect(parseName("cert*")).toBe(false);+ expect(parseName("cert:name")).toBe(false);+ });++ test("requires a schema (rejects empty)", () => {+ expect(parseName("")).toBe(false);+ expect(WindowsServerPkiSyncOptionsSchema.safeParse({}).success).toBe(false);+ });+});++describe("Windows Server destinationPath validation", () => {+ test("accepts absolute drive-letter paths", () => {+ expect(parsePath("C:\\certs")).toBe(true);+ expect(parsePath("D:\\ProgramData\\ssl\\certs")).toBe(true);+ });++ test("accepts UNC paths", () => {+ expect(parsePath("\\\\server\\share")).toBe(true);+ expect(parsePath("\\\\host\\share\\certs")).toBe(true);+ });++ test("rejects relative and non-Windows paths", () => {+ expect(parsePath("certs")).toBe(false);+ expect(parsePath("/etc/ssl/certs")).toBe(false);+ expect(parsePath("certs\\sub")).toBe(false);+ });++ test("rejects paths containing traversal", () => {+ expect(parsePath("C:\\certs\\..\\other")).toBe(false);+ expect(parsePath("C:\\certs\\..")).toBe(false);+ });++ test("rejects an empty path", () => {+ expect(parsePath("")).toBe(false);+ });+});diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.tsnew file mode 100644index 0000000000..358665e6cc--- /dev/null+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts@@ -0,0 +1,121 @@+import RE2 from "re2";+import { z } from "zod";++import { openApiHidden } from "@app/server/lib/schemas";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";+import { PkiSyncExportFormat } from "@app/services/pki-sync/pki-sync-export-fns";+import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";++import { WINDOWS_SERVER_NAMING } from "./windows-server-pki-sync-constants";++// Accepts a drive-letter path (C:\...) or a UNC path (\\server\share\...).+const WINDOWS_ABSOLUTE_PATH = new RE2("^([a-zA-Z]:\\\\|\\\\\\\\)");+// Rejects a ".." path segment. Windows treats both "\" and "/" as separators, so both must be+// checked or "C:\certs/../.." would slip past a backslash-only test.+const WINDOWS_PATH_TRAVERSAL = new RE2("(^|[\\\\/])\\.\\.([\\\\/]|$)");+// The path is embedded in a PowerShell single-quoted literal on the gateway. Restricting it to a+// conservative Windows-path character set keeps out shell metacharacters and the Unicode quote+// code points PowerShell also treats as string delimiters, so it cannot break out of the literal.+const WINDOWS_PATH_ALLOWED_CHARS = new RE2("^[A-Za-z0-9 ._\\-\\\\/:]+$");+// Runs of 2+ separators (e.g. C:\\certs). Windows can normalize these to a different location, so a+// delivery would silently land elsewhere; a single leading UNC prefix (\\server) is stripped first.+const WINDOWS_DOUBLE_SEPARATOR = new RE2("[\\\\/]{2,}");++export const WindowsServerPkiSyncConfigSchema = z.object({+ destinationPath: z+ .string()+ .trim()+ .min(1, "Destination path is required")+ .max(4096, "Destination path is too long")+ .refine((p) => WINDOWS_ABSOLUTE_PATH.test(p), {+ message: "Destination path must be an absolute Windows path (for example C:\\certs or \\\\server\\share)"+ })+ .refine((p) => WINDOWS_PATH_ALLOWED_CHARS.test(p), {+ message: "Destination path may only contain letters, digits, spaces, and the characters . _ - \\ / :"+ })+ .refine((p) => !WINDOWS_PATH_TRAVERSAL.test(p), { message: "Destination path must not contain '..'" })+ .refine((p) => !WINDOWS_DOUBLE_SEPARATOR.test(p.startsWith("\\\\") ? p.slice(2) : p), {+ message: "Destination path must not contain consecutive path separators"+ })+});++export const WindowsServerPkiSyncOptionsSchema = z.object({+ canRemoveCertificates: z.boolean().default(false),+ includeRootCa: z.boolean().default(false),+ includePrivateKey: z.boolean().default(true),+ exportFormat: z.nativeEnum(PkiSyncExportFormat).default(PkiSyncExportFormat.Pkcs12),+ certificateNameSchema: z+ .string()+ .trim()+ .min(1, "Certificate name schema is required")+ .refine(+ (schema) => {+ const testName = buildCertificateNameSchemaTestName(schema);+ const hasForbiddenChars = WINDOWS_SERVER_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) =>+ testName.includes(char)+ );+ return WINDOWS_SERVER_NAMING.NAME_PATTERN.test(testName) && !hasForbiddenChars;+ },+ {+ message:+ "Certificate name schema must resolve to a single file name of 1-200 characters using only letters, digits, dots (.), dashes (-), and underscores (_). Available placeholders: {{certificateId}}, {{shortCertificateId}}, {{profileId}}, {{applicationId}}, {{applicationName}}, {{commonName}}. A schema with no placeholder can be linked to only one certificate."+ }+ )+});++// Sync-level secrets (the PKCS#12 export password) accepted on create/update. Stored encrypted in+// pki_syncs.encryptedCredentials and never returned.+export const WindowsServerPkiSyncCredentialsSchema = z.object({+ exportPassword: z.string().min(1).optional()+});++export const WindowsServerPkiSyncSchema = PkiSyncSchema.extend({+ destination: z.literal(PkiSync.WindowsServer),+ destinationConfig: WindowsServerPkiSyncConfigSchema,+ syncOptions: WindowsServerPkiSyncOptionsSchema+});++export const CreateWindowsServerPkiSyncSchema = z+ .object({+ name: z.string().trim().min(1).max(256),+ description: z.string().optional(),+ isAutoSyncEnabled: z.boolean().default(true),+ destinationConfig: WindowsServerPkiSyncConfigSchema,+ syncOptions: WindowsServerPkiSyncOptionsSchema,+ credentials: WindowsServerPkiSyncCredentialsSchema.optional(),+ subscriberId: z.string().nullish(),+ connectionId: z.string(),+ projectId: z.string().trim().min(1).optional().describe(openApiHidden()),+ applicationId: z.string().uuid().optional(),+ certificateIds: z.array(z.string().uuid()).optional()+ })+ .superRefine((data, ctx) => {+ if (data.syncOptions.exportFormat === PkiSyncExportFormat.Pkcs12 && !data.credentials?.exportPassword) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["credentials", "exportPassword"],+ message: "A password is required when the export format is PKCS#12"+ });+ }+ });++export const UpdateWindowsServerPkiSyncSchema = z.object({+ name: z.string().trim().min(1).max(256).optional(),+ description: z.string().optional(),+ isAutoSyncEnabled: z.boolean().optional(),+ destinationConfig: WindowsServerPkiSyncConfigSchema.optional(),+ syncOptions: WindowsServerPkiSyncOptionsSchema.optional(),+ credentials: WindowsServerPkiSyncCredentialsSchema.optional(),+ subscriberId: z.string().nullish(),+ connectionId: z.string().optional()+});++export const WindowsServerPkiSyncListItemSchema = z.object({+ name: z.literal("Windows Server"),+ connection: z.literal(AppConnection.WinRM),+ destination: z.literal(PkiSync.WindowsServer),+ canImportCertificates: z.literal(false),+ canRemoveCertificates: z.literal(true)+});diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-types.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-types.tsnew file mode 100644index 0000000000..ce1840c0b6--- /dev/null+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-types.ts@@ -0,0 +1,19 @@+import { z } from "zod";++import {+ CreateWindowsServerPkiSyncSchema,+ WindowsServerPkiSyncConfigSchema,+ WindowsServerPkiSyncListItemSchema,+ WindowsServerPkiSyncOptionsSchema,+ WindowsServerPkiSyncSchema+} from "./windows-server-pki-sync-schemas";++export type TWindowsServerPkiSync = z.infer<typeof WindowsServerPkiSyncSchema>;++export type TWindowsServerPkiSyncConfig = z.infer<typeof WindowsServerPkiSyncConfigSchema>;++export type TWindowsServerPkiSyncOptions = z.infer<typeof WindowsServerPkiSyncOptionsSchema>;++export type TWindowsServerPkiSyncListItem = z.infer<typeof WindowsServerPkiSyncListItemSchema>;++export type TCreateWindowsServerPkiSync = z.infer<typeof CreateWindowsServerPkiSyncSchema>;diff --git a/docs/api-reference/endpoints/app-connections/winrm/available.mdx b/docs/api-reference/endpoints/app-connections/winrm/available.mdxnew file mode 100644index 0000000000..a62846130e--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/winrm/available.mdx@@ -0,0 +1,4 @@+---+title: "Available"+openapi: "GET /api/v1/app-connections/winrm/available"+---diff --git a/docs/api-reference/endpoints/app-connections/winrm/create.mdx b/docs/api-reference/endpoints/app-connections/winrm/create.mdxnew file mode 100644index 0000000000..382c0afa80--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/winrm/create.mdx@@ -0,0 +1,8 @@+---+title: "Create"+openapi: "POST /api/v1/app-connections/winrm"+---++<Note>+ Check out the configuration docs for [Windows (WinRM) Connections](/integrations/app-connections/winrm) to learn how to obtain the required credentials.+</Note>diff --git a/docs/api-reference/endpoints/app-connections/winrm/delete.mdx b/docs/api-reference/endpoints/app-connections/winrm/delete.mdxnew file mode 100644index 0000000000..f6c4351a50--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/winrm/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete"+openapi: "DELETE /api/v1/app-connections/winrm/{connectionId}"+---diff --git a/docs/api-reference/endpoints/app-connections/winrm/get-by-id.mdx b/docs/api-reference/endpoints/app-connections/winrm/get-by-id.mdxnew file mode 100644index 0000000000..3fd2d0db53--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/winrm/get-by-id.mdx@@ -0,0 +1,4 @@+---+title: "Get by ID"+openapi: "GET /api/v1/app-connections/winrm/{connectionId}"+---diff --git a/docs/api-reference/endpoints/app-connections/winrm/get-by-name.mdx b/docs/api-reference/endpoints/app-connections/winrm/get-by-name.mdxnew file mode 100644index 0000000000..d69c9e5dfe--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/winrm/get-by-name.mdx@@ -0,0 +1,4 @@+---+title: "Get by Name"+openapi: "GET /api/v1/app-connections/winrm/connection-name/{connectionName}"+---diff --git a/docs/api-reference/endpoints/app-connections/winrm/list.mdx b/docs/api-reference/endpoints/app-connections/winrm/list.mdxnew file mode 100644index 0000000000..79df2cd892--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/winrm/list.mdx@@ -0,0 +1,4 @@+---+title: "List"+openapi: "GET /api/v1/app-connections/winrm"+---diff --git a/docs/api-reference/endpoints/app-connections/winrm/update.mdx b/docs/api-reference/endpoints/app-connections/winrm/update.mdxnew file mode 100644index 0000000000..14a8318cc9--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/winrm/update.mdx@@ -0,0 +1,8 @@+---+title: "Update"+openapi: "PATCH /api/v1/app-connections/winrm/{connectionId}"+---++<Note>+ Check out the configuration docs for [Windows (WinRM) Connections](/integrations/app-connections/winrm) to learn how to obtain the required credentials.+</Note>diff --git a/docs/api-reference/endpoints/pki/syncs/linux-server/create.mdx b/docs/api-reference/endpoints/pki/syncs/linux-server/create.mdxnew file mode 100644index 0000000000..7184ee90cc--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/linux-server/create.mdx@@ -0,0 +1,4 @@+---+title: "Create Linux Server PKI Sync"+openapi: "POST /api/v1/cert-manager/syncs/linux-server"+---diff --git a/docs/api-reference/endpoints/pki/syncs/linux-server/delete.mdx b/docs/api-reference/endpoints/pki/syncs/linux-server/delete.mdxnew file mode 100644index 0000000000..64b328df8f--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/linux-server/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete Linux Server PKI Sync"+openapi: "DELETE /api/v1/cert-manager/syncs/linux-server/{pkiSyncId}"+---diff --git a/docs/api-reference/endpoints/pki/syncs/linux-server/get-by-id.mdx b/docs/api-reference/endpoints/pki/syncs/linux-server/get-by-id.mdxnew file mode 100644index 0000000000..2d28ad0405--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/linux-server/get-by-id.mdx@@ -0,0 +1,4 @@+---+title: "Get Linux Server PKI Sync by ID"+openapi: "GET /api/v1/cert-manager/syncs/linux-server/{pkiSyncId}"+---diff --git a/docs/api-reference/endpoints/pki/syncs/linux-server/list.mdx b/docs/api-reference/endpoints/pki/syncs/linux-server/list.mdxnew file mode 100644index 0000000000..44f491cd81--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/linux-server/list.mdx@@ -0,0 +1,4 @@+---+title: "List Linux Server PKI Syncs"+openapi: "GET /api/v1/cert-manager/syncs/linux-server"+---diff --git a/docs/api-reference/endpoints/pki/syncs/linux-server/remove-certificates.mdx b/docs/api-reference/endpoints/pki/syncs/linux-server/remove-certificates.mdxnew file mode 100644index 0000000000..f57dd25ffe--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/linux-server/remove-certificates.mdx@@ -0,0 +1,4 @@+---+title: "Remove Certificates from Linux Server"+openapi: "POST /api/v1/cert-manager/syncs/linux-server/{pkiSyncId}/remove-certificates"+---diff --git a/docs/api-reference/endpoints/pki/syncs/linux-server/sync-certificates.mdx b/docs/api-reference/endpoints/pki/syncs/linux-server/sync-certificates.mdxnew file mode 100644index 0000000000..5be4cc419d--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/linux-server/sync-certificates.mdx@@ -0,0 +1,4 @@+---+title: "Sync Certificates to Linux Server"+openapi: "POST /api/v1/cert-manager/syncs/linux-server/{pkiSyncId}/sync"+---diff --git a/docs/api-reference/endpoints/pki/syncs/linux-server/update.mdx b/docs/api-reference/endpoints/pki/syncs/linux-server/update.mdxnew file mode 100644index 0000000000..e879db182a--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/linux-server/update.mdx@@ -0,0 +1,4 @@+---+title: "Update Linux Server PKI Sync"+openapi: "PATCH /api/v1/cert-manager/syncs/linux-server/{pkiSyncId}"+---diff --git a/docs/api-reference/endpoints/pki/syncs/windows-server/create.mdx b/docs/api-reference/endpoints/pki/syncs/windows-server/create.mdxnew file mode 100644index 0000000000..ea11ef0267--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/windows-server/create.mdx@@ -0,0 +1,4 @@+---+title: "Create Windows Server PKI Sync"+openapi: "POST /api/v1/cert-manager/syncs/windows-server"+---diff --git a/docs/api-reference/endpoints/pki/syncs/windows-server/delete.mdx b/docs/api-reference/endpoints/pki/syncs/windows-server/delete.mdxnew file mode 100644index 0000000000..8332195c73--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/windows-server/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete Windows Server PKI Sync"+openapi: "DELETE /api/v1/cert-manager/syncs/windows-server/{pkiSyncId}"+---diff --git a/docs/api-reference/endpoints/pki/syncs/windows-server/get-by-id.mdx b/docs/api-reference/endpoints/pki/syncs/windows-server/get-by-id.mdxnew file mode 100644index 0000000000..97ba4a31be--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/windows-server/get-by-id.mdx@@ -0,0 +1,4 @@+---+title: "Get Windows Server PKI Sync by ID"+openapi: "GET /api/v1/cert-manager/syncs/windows-server/{pkiSyncId}"+---diff --git a/docs/api-reference/endpoints/pki/syncs/windows-server/list.mdx b/docs/api-reference/endpoints/pki/syncs/windows-server/list.mdxnew file mode 100644index 0000000000..6e74a632c3--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/windows-server/list.mdx@@ -0,0 +1,4 @@+---+title: "List Windows Server PKI Syncs"+openapi: "GET /api/v1/cert-manager/syncs/windows-server"+---diff --git a/docs/api-reference/endpoints/pki/syncs/windows-server/remove-certificates.mdx b/docs/api-reference/endpoints/pki/syncs/windows-server/remove-certificates.mdxnew file mode 100644index 0000000000..d88bd17d27--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/windows-server/remove-certificates.mdx@@ -0,0 +1,4 @@+---+title: "Remove Certificates from Windows Server"+openapi: "POST /api/v1/cert-manager/syncs/windows-server/{pkiSyncId}/remove-certificates"+---diff --git a/docs/api-reference/endpoints/pki/syncs/windows-server/sync-certificates.mdx b/docs/api-reference/endpoints/pki/syncs/windows-server/sync-certificates.mdxnew file mode 100644index 0000000000..0de58af2be--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/windows-server/sync-certificates.mdx@@ -0,0 +1,4 @@+---+title: "Sync Certificates to Windows Server"+openapi: "POST /api/v1/cert-manager/syncs/windows-server/{pkiSyncId}/sync"+---diff --git a/docs/api-reference/endpoints/pki/syncs/windows-server/update.mdx b/docs/api-reference/endpoints/pki/syncs/windows-server/update.mdxnew file mode 100644index 0000000000..d7253b28b0--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/windows-server/update.mdx@@ -0,0 +1,4 @@+---+title: "Update Windows Server PKI Sync"+openapi: "PATCH /api/v1/cert-manager/syncs/windows-server/{pkiSyncId}"+---diff --git a/docs/docs.json b/docs/docs.jsonindex 36ed0fe3ca..d706ea92a3 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -182,6 +182,7 @@"integrations/app-connections/vercel","integrations/app-connections/windmill","integrations/app-connections/smb",+ "integrations/app-connections/winrm","integrations/app-connections/zabbix"]}@@ -923,7 +924,9 @@"documentation/platform/pki/applications/certificate-syncs/chef","documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate","documentation/platform/pki/applications/certificate-syncs/f5-big-ip",- "documentation/platform/pki/applications/certificate-syncs/netscaler"+ "documentation/platform/pki/applications/certificate-syncs/netscaler",+ "documentation/platform/pki/applications/certificate-syncs/linux-server",+ "documentation/platform/pki/applications/certificate-syncs/windows-server"]}]@@ -2223,6 +2226,18 @@"api-reference/endpoints/app-connections/smb/delete"]},+ {+ "group": "Windows (WinRM)",+ "pages": [+ "api-reference/endpoints/app-connections/winrm/list",+ "api-reference/endpoints/app-connections/winrm/available",+ "api-reference/endpoints/app-connections/winrm/get-by-id",+ "api-reference/endpoints/app-connections/winrm/get-by-name",+ "api-reference/endpoints/app-connections/winrm/create",+ "api-reference/endpoints/app-connections/winrm/update",+ "api-reference/endpoints/app-connections/winrm/delete"+ ]+ },{"group": "Zabbix","pages": [@@ -3606,6 +3621,30 @@"api-reference/endpoints/pki/syncs/netscaler/sync-certificates","api-reference/endpoints/pki/syncs/netscaler/remove-certificates"]+ },+ {+ "group": "Linux Server",+ "pages": [+ "api-reference/endpoints/pki/syncs/linux-server/list",+ "api-reference/endpoints/pki/syncs/linux-server/get-by-id",+ "api-reference/endpoints/pki/syncs/linux-server/create",+ "api-reference/endpoints/pki/syncs/linux-server/update",+ "api-reference/endpoints/pki/syncs/linux-server/delete",+ "api-reference/endpoints/pki/syncs/linux-server/sync-certificates",+ "api-reference/endpoints/pki/syncs/linux-server/remove-certificates"+ ]+ },+ {+ "group": "Windows Server",+ "pages": [+ "api-reference/endpoints/pki/syncs/windows-server/list",+ "api-reference/endpoints/pki/syncs/windows-server/get-by-id",+ "api-reference/endpoints/pki/syncs/windows-server/create",+ "api-reference/endpoints/pki/syncs/windows-server/update",+ "api-reference/endpoints/pki/syncs/windows-server/delete",+ "api-reference/endpoints/pki/syncs/windows-server/sync-certificates",+ "api-reference/endpoints/pki/syncs/windows-server/remove-certificates"+ ]}]}diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdxnew file mode 100644index 0000000000..eb9fc087f8--- /dev/null+++ b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx@@ -0,0 +1,120 @@+---+title: "Linux Server"+sidebarTitle: "Linux Server"+description: "Deploy certificates to Linux servers over SSH."+---++Deploy certificates from Infisical to a directory on a Linux server over SSH. Files are written atomically over SFTP so a reader never sees a partially written certificate or key.++<Info>+ Certificate Syncs are configured per Application. First select which certificates to sync, then configure the Linux Server destination.+</Info>++## Prerequisites++- An [SSH Connection](/integrations/app-connections/ssh) with access to the target server+- The destination directory must already exist on the server and the connection user must be able to write to it+- The server must be reachable from Infisical, either directly or through an [Infisical Gateway](/documentation/platform/gateways/overview)++## Create a Linux Server Sync++<Tabs>+ <Tab title="Infisical UI">+ 1. In your Application, go to the **Certificate Syncs** tab and click **Create Sync**.++ 2. Select the **Linux Server** option.++ 3. Configure the **Destination**:+ - **SSH Connection**: The SSH Connection used to reach the server.+ - **Destination Directory**: The absolute path to the directory where certificate files are written, for example `/etc/ssl/certs`.++ 4. Configure the **Sync Options**:+ - **Export Format**: Choose **PEM** to write separate certificate, chain, and key files, or **PKCS#12** to write a single password-protected `.pfx` bundle.+ - **PKCS#12 Password**: Required when the export format is PKCS#12. It protects the delivered bundle.+ - **Include Private Key**: For PEM, controls whether the private key is written alongside the certificate. The sync fails for a certificate whose key is not available, for example one issued from an external CSR.+ - **Include Root CA in Certificate Chain**: Include the root CA in the delivered chain. Leave it off when the consuming service only needs the intermediates.+ - **Enable Removal of Certificates**: Delete the delivered files from the server when a certificate is removed from the sync, revoked, or expired.+ - **Certificate Name Schema**: The base file name, using placeholders such as `{{commonName}}`, `{{certificateId}}`, or `{{shortCertificateId}}`. The export format adds the extension. A schema with no placeholder can be linked to only one certificate.+ - **Auto-Sync Enabled**: Automatically sync certificates when changes occur.++ 5. Configure the **Details**:+ - **Name**: The name of your sync.+ - **Description**: Optional description.++ 6. Select which certificates should be synced.++ 7. Review and click **Create Sync**.+ </Tab>+ <Tab title="API">+ To create a **Linux Server Certificate Sync**, make an API request to the [Create Linux Server PKI Sync](/api-reference/endpoints/pki/syncs/linux-server/create) endpoint.++ ### Sample request++ ```bash Request+ curl --request POST \+ --url https://app.infisical.com/api/v1/cert-manager/syncs/linux-server \+ --header 'Authorization: Bearer <access-token>' \+ --header 'Content-Type: application/json' \+ --data '{+ "name": "my-linux-cert-sync",+ "applicationId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "connectionId": "550e8400-e29b-41d4-a716-446655440000",+ "isAutoSyncEnabled": true,+ "certificateIds": ["550e8400-e29b-41d4-a716-446655440000"],+ "syncOptions": {+ "exportFormat": "pem",+ "includePrivateKey": true,+ "canRemoveCertificates": true,+ "certificateNameSchema": "{{commonName}}"+ },+ "destinationConfig": {+ "destinationPath": "/etc/ssl/certs"+ }+ }'+ ```+ </Tab>+</Tabs>++## Export Formats++<Note>+ The file extension is decided by the export format, not by the name schema. The name schema only provides the base name.+ - **PEM**: `<name>.pem` (certificate), `<name>.chain.pem` (chain), and `<name>.key` (private key, when included).+ - **PKCS#12**: `<name>.pfx`, a single password-protected bundle containing the certificate, chain, and key.+</Note>++## How It Works++When syncing certificates, Infisical opens an SSH session to the server and, for each certificate:++1. Packages the certificate in the chosen export format.+2. Writes each file to a temporary name in the destination directory.+3. Renames the temporary file over the final name so the delivered file is always complete.++## Removing Certificates++When certificate removal is enabled and a certificate is removed from the sync, revoked, or expired, Infisical deletes exactly the files it delivered for that certificate.++## FAQ++<Accordion title="Can I import certificates from a Linux server back into Infisical?">+ No. The Linux Server sync only delivers certificates to the server. It does not read certificates back into Infisical.+</Accordion>++<Accordion title="What happens if the destination directory does not exist?">+ The sync fails with a clear error. Create the directory and grant the connection user write access, then run the sync again.+</Accordion>++## What's Next?++<CardGroup cols={2}>+ <Card title="Windows Server" icon="windows" href="/documentation/platform/pki/applications/certificate-syncs/windows-server">+ Deploy certificates to Windows servers over WinRM.+ </Card>+ <Card title="Auto-Renewal" icon="arrows-spin" href="/documentation/platform/pki/applications/certificates#renewal">+ Enable automatic certificate renewal and syncing.+ </Card>+ <Card title="Other Sync Destinations" icon="arrows-rotate" href="/documentation/platform/pki/applications/certificate-syncs/overview">+ View all supported sync destinations.+ </Card>+</CardGroup>diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdxindex 6f28e3919a..516a49d3ca 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx@@ -80,6 +80,12 @@ flowchart LR<Card title="NetScaler" icon="server" href="/documentation/platform/pki/applications/certificate-syncs/netscaler">Deploy certificates to Citrix NetScaler ADC.</Card>+ <Card title="Linux Server" icon="linux" href="/documentation/platform/pki/applications/certificate-syncs/linux-server">+ Deploy certificates to Linux servers over SSH.+ </Card>+ <Card title="Windows Server" icon="windows" href="/documentation/platform/pki/applications/certificate-syncs/windows-server">+ Deploy certificates to Windows servers over WinRM.+ </Card></CardGroup><Note>diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdxnew file mode 100644index 0000000000..c5a337b3e2--- /dev/null+++ b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx@@ -0,0 +1,139 @@+---+title: "Windows Server"+sidebarTitle: "Windows Server"+description: "Deploy certificates to Windows servers over WinRM."+---++Deploy certificates from Infisical to a directory on a Windows server over WinRM. Files are written atomically so a reader never sees a partially written certificate or key.++<Info>+ Certificate Syncs are configured per Application. First select which certificates to sync, then configure the Windows Server destination.+</Info>++## Prerequisites++- A [Windows (WinRM) Connection](/integrations/app-connections/winrm) with access to the target server+- An [Infisical Gateway](/documentation/platform/gateways/overview) that can reach the server. Windows delivery always runs through the Gateway.+- The connection user must be able to write to the destination directory++<Note>+ Windows delivery runs on the Gateway because it uses WinRM message encryption, which lets a certificate travel confidentially over the default WinRM listener without a server certificate. This is the same zero-configuration posture most Windows hosts already ship with.+</Note>++## Create a Windows Server Sync++<Tabs>+ <Tab title="Infisical UI">+ 1. In your Application, go to the **Certificate Syncs** tab and click **Create Sync**.++ 2. Select the **Windows Server** option.++ 3. Configure the **Destination**:+ - **Windows (WinRM) Connection**: The WinRM Connection used to reach the server.+ - **Destination Directory**: The absolute Windows path where certificate files are written, either a drive path like `C:\certs` or a UNC share like `\\server\share\certs`. It is created if it does not exist. The path cannot contain `..` segments or consecutive separators.++ 4. Configure the **Sync Options**:+ - **Export Format**: Choose **PKCS#12** to write a single password-protected `.pfx` bundle, or **PEM** to write separate certificate, chain, and key files.+ - **PKCS#12 Password**: Required when the export format is PKCS#12. It protects the delivered bundle.+ - **Include Private Key**: For PEM, controls whether the private key is written alongside the certificate. The sync fails for a certificate whose key is not available, for example one issued from an external CSR.+ - **Include Root CA in Certificate Chain**: Include the root CA in the delivered chain. Leave it off when the consuming service only needs the intermediates.+ - **Enable Removal of Certificates**: Delete the delivered files from the server when a certificate is removed from the sync, revoked, or expired.+ - **Certificate Name Schema**: The base file name, using placeholders such as `{{commonName}}`, `{{certificateId}}`, or `{{shortCertificateId}}`. The export format adds the extension. A schema with no placeholder can be linked to only one certificate.+ - **Auto-Sync Enabled**: Automatically sync certificates when changes occur.++ 5. Configure the **Details**:+ - **Name**: The name of your sync.+ - **Description**: Optional description.++ 6. Select which certificates should be synced.++ 7. Review and click **Create Sync**.+ </Tab>+ <Tab title="API">+ To create a **Windows Server Certificate Sync**, make an API request to the [Create Windows Server PKI Sync](/api-reference/endpoints/pki/syncs/windows-server/create) endpoint.++ ### Sample request++ ```bash Request+ curl --request POST \+ --url https://app.infisical.com/api/v1/cert-manager/syncs/windows-server \+ --header 'Authorization: Bearer <access-token>' \+ --header 'Content-Type: application/json' \+ --data '{+ "name": "my-windows-cert-sync",+ "applicationId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "connectionId": "550e8400-e29b-41d4-a716-446655440000",+ "isAutoSyncEnabled": true,+ "certificateIds": ["550e8400-e29b-41d4-a716-446655440000"],+ "credentials": {+ "exportPassword": "a-strong-password"+ },+ "syncOptions": {+ "exportFormat": "pkcs12",+ "canRemoveCertificates": true,+ "certificateNameSchema": "{{commonName}}"+ },+ "destinationConfig": {+ "destinationPath": "C:\\certs"+ }+ }'+ ```+ </Tab>+</Tabs>++## Export Formats++<Note>+ The file extension is decided by the export format, not by the name schema. The name schema only provides the base name.+ - **PKCS#12**: `<name>.pfx`, a single password-protected bundle containing the certificate, chain, and key.+ - **PEM**: `<name>.pem` (certificate), `<name>.chain.pem` (chain), and `<name>.key` (private key, when included).+</Note>++## How It Works++When syncing certificates, Infisical asks the Gateway to open a WinRM session to the server and, for each certificate:++1. Packages the certificate in the chosen export format.+2. Writes each file to a temporary name in the destination directory.+3. Renames the temporary file over the final name so the delivered file is always complete.++## Removing Certificates++When certificate removal is enabled and a certificate is removed from the sync, revoked, or expired, Infisical deletes exactly the files it delivered for that certificate.++## Using Synced Certificates with IIS Centralized Certificate Store++IIS can serve a synced PKCS#12 certificate directly from a shared folder through the Centralized Certificate Store (CCS). To wire this up, set the sync to deliver into the CCS folder and make the two sides agree:++<Note>+ - **Export format**: PKCS#12. CCS reads `.pfx` files only.+ - **Destination Directory**: the folder IIS CCS is configured to read.+ - **Certificate Name Schema**: use `{{commonName}}` so each file is named `<hostname>.pfx`. CCS matches the incoming request hostname to the file name.+ - **PKCS#12 Password**: must match the private key password configured on the IIS Centralized Certificate Store. IIS uses that one password to open every `.pfx` in the folder.+</Note>++These are IIS requirements, configured once on the Windows host (the CCS feature, its store folder, and the store account). Infisical only delivers the `.pfx`. IIS is responsible for loading and serving it.++## FAQ++<Accordion title="Which transport does the sync use?">+ By default the connection uses the standard WinRM HTTP listener on port 5985 with NTLM message encryption. HTTPS on port 5986 is also supported for hosts that require it.+</Accordion>++<Accordion title="Can I import certificates from a Windows server back into Infisical?">+ No. The Windows Server sync only delivers certificates to the server. It does not read certificates back into Infisical.+</Accordion>++## What's Next?++<CardGroup cols={2}>+ <Card title="Linux Server" icon="linux" href="/documentation/platform/pki/applications/certificate-syncs/linux-server">+ Deploy certificates to Linux servers over SSH.+ </Card>+ <Card title="Auto-Renewal" icon="arrows-spin" href="/documentation/platform/pki/applications/certificates#renewal">+ Enable automatic certificate renewal and syncing.+ </Card>+ <Card title="Other Sync Destinations" icon="arrows-rotate" href="/documentation/platform/pki/applications/certificate-syncs/overview">+ View all supported sync destinations.+ </Card>+</CardGroup>diff --git a/docs/integrations/app-connections/winrm.mdx b/docs/integrations/app-connections/winrm.mdxnew file mode 100644index 0000000000..9cd5876014--- /dev/null+++ b/docs/integrations/app-connections/winrm.mdx@@ -0,0 +1,87 @@+---+title: "Windows (WinRM) Connection"+description: "Learn how to configure a Windows (WinRM) Connection for Infisical."+---++Infisical supports connecting to Windows hosts over WinRM to deliver certificates. Because WinRM message encryption runs in the Gateway, this connection always routes through an [Infisical Gateway](/documentation/platform/gateways/overview) inside your network.++## Setup++<Tabs>+ <Tab title="Infisical UI">+ <Steps>+ <Step title="Gather WinRM Details">+ You will need the following for the target Windows host:++ - **Host**: The DNS name (FQDN) or IP address of the Windows host.+ - **Port**: The WinRM port. `5985` for HTTP with NTLM message encryption, `5986` for HTTPS.+ - **Username**: A Windows login, either `DOMAIN\user` or `[email protected]`.+ - **Password**: The account password.++ <Note>+ The account must be able to open a WinRM session and write to the destination directory used by the certificate sync.+ </Note>+ </Step>+ <Step title="Navigate to App Connections">+ In the Infisical dashboard, navigate to **Organization Settings** > **App Connections** and click **Add Connection**.+ </Step>+ <Step title="Select Windows (WinRM)">+ Select the **Windows (WinRM)** option from the list of available connections.+ </Step>+ <Step title="Fill in Connection Details">+ Fill in the connection form:++ - **Gateway**: The Gateway that can reach the Windows host. This is required.+ - **Host**: The DNS name or IP address of the Windows host.+ - **Port**: The WinRM port.+ - **Username** and **Password**: The Windows account credentials.+ - **Transport**: Choose HTTP with NTLM message encryption on port 5985, or HTTPS on port 5986.+ - **TLS Certificate Verification**: For HTTPS, choose whether to verify the listener certificate. Skip verification only for a self-signed listener.++ Click **Connect to Windows (WinRM)** to validate and save your connection.+ </Step>+ <Step title="Connection Created">+ Your Windows (WinRM) Connection is now available for use with the [Windows Server Certificate Sync](/documentation/platform/pki/applications/certificate-syncs/windows-server).+ </Step>+ </Steps>+ </Tab>+ <Tab title="API">+ To create a Windows (WinRM) Connection via API, send a request to the [Create WinRM Connection](/api-reference/endpoints/app-connections/winrm/create) endpoint.++ The connection must be attached to a Gateway that can reach the Windows host, so `gatewayId` is required.++ ### Sample request++ ```bash Request+ curl --request POST \+ --url https://app.infisical.com/api/v1/app-connections/winrm \+ --header 'Authorization: Bearer <access-token>' \+ --header 'Content-Type: application/json' \+ --data '{+ "name": "my-winrm-connection",+ "method": "username-password",+ "gatewayId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "credentials": {+ "host": "win01.corp.example.com",+ "port": 5985,+ "username": "DOMAIN\\svc-infisical",+ "password": "[PASSWORD]",+ "useHttps": false,+ "insecure": false+ }+ }'+ ```+ </Tab>+</Tabs>++## Transport++<Note>+ The default transport is the standard WinRM HTTP listener on port 5985 with NTLM message encryption. This keeps the certificate and key confidential without a server certificate on the host, which is the zero-configuration posture most Windows hosts ship with. HTTPS on port 5986 is supported for hosts that require it.+</Note>++## FAQ++<Accordion title="Why does this connection require a Gateway?">+ WinRM message encryption must be performed by a component inside your network. The Gateway performs it, which lets a certificate travel confidentially over the default listener without a server certificate on every host.+</Accordion>diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsxindex 0513d2d4c5..f5ec635ec2 100644--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx@@ -1,5 +1,5 @@import { useState } from "react";-import { Controller, FormProvider, useForm } from "react-hook-form";+import { Controller, FieldPath, FormProvider, useForm } from "react-hook-form";import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { Tab } from "@headlessui/react";@@ -9,7 +9,13 @@ import { createNotification } from "@app/components/notifications";import { Button, FormControl, Switch } from "@app/components/v2";import { useProject } from "@app/context";import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";-import { PkiSync, TPkiSync, useCreatePkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";+import {+ PkiSync,+ PkiSyncExportFormat,+ TPkiSync,+ useCreatePkiSync,+ usePkiSyncOption+} from "@app/hooks/api/pkiSyncs";import { PkiSyncFormSchema, TPkiSyncForm } from "./schemas/pki-sync-schema";import { PkiSyncCertificatesFields } from "./PkiSyncCertificatesFields";@@ -23,38 +29,46 @@ type Props = {onComplete: (pkiSync: TPkiSync) => void;destination: PkiSync;onCancel: () => void;- initialData?: any;+ initialData?: Partial<TPkiSyncForm>;applicationId?: string;};const getFormTabs = (destination: PkiSync-): { name: string; key: string; fields: (keyof TPkiSyncForm)[] }[] => {+): { name: string; key: string; fields: FieldPath<TPkiSyncForm>[] }[] => {const baseTabs = [{name: "Destination",key: "destination",- fields: ["connection", "destinationConfig"] as (keyof TPkiSyncForm)[]+ fields: ["connection", "destinationConfig"] as FieldPath<TPkiSyncForm>[]},- { name: "Sync Options", key: "options", fields: ["syncOptions"] as (keyof TPkiSyncForm)[] }+ {+ name: "Sync Options",+ key: "options",+ fields: ["syncOptions", "credentials"] as FieldPath<TPkiSyncForm>[]+ }];if (destination === PkiSync.Chef || destination === PkiSync.AwsSecretsManager) {baseTabs.push({name: "Mappings",key: "mappings",- fields: ["syncOptions"] as (keyof TPkiSyncForm)[]+ fields: ["syncOptions"] as FieldPath<TPkiSyncForm>[]});}baseTabs.push(- { name: "Details", key: "details", fields: ["name", "description"] as (keyof TPkiSyncForm)[] },+ {+ name: "Details",+ key: "details",+ fields: ["name", "description"] as FieldPath<TPkiSyncForm>[]+ },{name: "Certificates",key: "certificates",- fields: ["certificateIds"] as (keyof TPkiSyncForm)[]+ fields: ["certificateIds"] as FieldPath<TPkiSyncForm>[]},- { name: "Review", key: "review", fields: [] as (keyof TPkiSyncForm)[] }+ { name: "Review", key: "review", fields: [] as FieldPath<TPkiSyncForm>[] });return baseTabs;@@ -89,6 +103,13 @@ export const CreatePkiSyncForm = ({canRemoveCertificates: false,preserveArn: true,certificateNameSchema: syncOption?.defaultCertificateNameSchema,+ ...((destination === PkiSync.LinuxServer || destination === PkiSync.WindowsServer) && {+ exportFormat:+ destination === PkiSync.WindowsServer+ ? PkiSyncExportFormat.Pkcs12+ : PkiSyncExportFormat.Pem,+ includePrivateKey: true+ }),...((destination === PkiSync.Chef || destination === PkiSync.AwsSecretsManager) && {fieldMappings: {certificate: "certificate",diff --git a/frontend/src/components/pki-syncs/forms/LinuxServerPkiSyncFields.tsx b/frontend/src/components/pki-syncs/forms/LinuxServerPkiSyncFields.tsxnew file mode 100644index 0000000000..5c467b55d4--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/LinuxServerPkiSyncFields.tsx@@ -0,0 +1,31 @@+import { Controller, useFormContext } from "react-hook-form";++import { FormControl, Input } from "@app/components/v2";+import { PkiSync } from "@app/hooks/api/pkiSyncs";++import { TPkiSyncForm } from "./schemas/pki-sync-schema";+import { PkiSyncConnectionField } from "./PkiSyncConnectionField";++export const LinuxServerPkiSyncFields = () => {+ const { control } = useFormContext<TPkiSyncForm & { destination: PkiSync.LinuxServer }>();++ return (+ <>+ <PkiSyncConnectionField />+ <Controller+ name="destinationConfig.destinationPath"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl+ isError={Boolean(error)}+ errorText={error?.message}+ label="Destination Directory"+ tooltipText="The absolute path to the directory on the server where certificate files are written. The directory must already exist."+ >+ <Input value={value ?? ""} onChange={onChange} placeholder="/etc/ssl/certs" />+ </FormControl>+ )}+ />+ </>+ );+};diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsxindex 9e75d052f1..af1024f1e5 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx@@ -10,7 +10,9 @@ import { AzureKeyVaultPkiSyncFields } from "./AzureKeyVaultPkiSyncFields";import { ChefPkiSyncFields } from "./ChefPkiSyncFields";import { CloudflareCustomCertificatePkiSyncFields } from "./CloudflareCustomCertificatePkiSyncFields";import { F5BigIpPkiSyncFields } from "./F5BigIpPkiSyncFields";+import { LinuxServerPkiSyncFields } from "./LinuxServerPkiSyncFields";import { NetScalerPkiSyncFields } from "./NetScalerPkiSyncFields";+import { WindowsServerPkiSyncFields } from "./WindowsServerPkiSyncFields";export const PkiSyncDestinationFields = () => {const { watch } = useFormContext<TPkiSyncForm>();@@ -34,6 +36,10 @@ export const PkiSyncDestinationFields = () => {return <NetScalerPkiSyncFields />;case PkiSync.F5BigIp:return <F5BigIpPkiSyncFields />;+ case PkiSync.LinuxServer:+ return <LinuxServerPkiSyncFields />;+ case PkiSync.WindowsServer:+ return <WindowsServerPkiSyncFields />;default:return (<div className="flex items-center justify-center rounded-md border border-red-500 bg-red-100 p-4 text-red-700">diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsxindex 5385bdb3db..ee10cdaa56 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx@@ -2,8 +2,8 @@ import { Controller, useFormContext } from "react-hook-form";import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { FormControl, Input, Switch, Tooltip } from "@app/components/v2";-import { PkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";+import { FormControl, Input, Select, SelectItem, Switch, Tooltip } from "@app/components/v2";+import { PkiSync, PkiSyncExportFormat, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";import { TPkiSyncForm } from "../schemas/pki-sync-schema";@@ -415,6 +415,82 @@ export const PkiSyncOptionsFields = ({ destination }: Props) => {/>)}+ {(currentDestination === PkiSync.LinuxServer ||+ currentDestination === PkiSync.WindowsServer) && (+ <>+ <Controller+ control={control}+ name="syncOptions.exportFormat"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl+ isError={Boolean(error)}+ errorText={error?.message}+ label="Export Format"+ tooltipText="PEM writes separate certificate, chain, and key files. PKCS#12 writes a single password-protected .pfx bundle."+ >+ <Select+ value={value ?? PkiSyncExportFormat.Pem}+ onValueChange={(v) => onChange(v as PkiSyncExportFormat)}+ className="w-full border border-mineshaft-500"+ position="popper"+ >+ <SelectItem value={PkiSyncExportFormat.Pem}>PEM</SelectItem>+ <SelectItem value={PkiSyncExportFormat.Pkcs12}>PKCS#12 (.pfx)</SelectItem>+ </Select>+ </FormControl>+ )}+ />+ {watch("syncOptions.exportFormat") === PkiSyncExportFormat.Pkcs12 && (+ <Controller+ control={control}+ name="credentials.exportPassword"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl+ isError={Boolean(error)}+ errorText={error?.message}+ label="PKCS#12 Password"+ tooltipText="Protects the .pfx bundle. When editing, leave blank to keep the current password."+ >+ <Input+ type="password"+ value={value ?? ""}+ onChange={onChange}+ placeholder="Enter a password"+ />+ </FormControl>+ )}+ />+ )}+ {watch("syncOptions.exportFormat") !== PkiSyncExportFormat.Pkcs12 && (+ <Controller+ control={control}+ name="syncOptions.includePrivateKey"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl isError={Boolean(error)} errorText={error?.message}>+ <Switch+ className="bg-mineshaft-400/80 shadow-inner data-[state=checked]:bg-green/80"+ id="include-private-key"+ thumbClassName="bg-mineshaft-800"+ onCheckedChange={onChange}+ isChecked={value ?? true}+ >+ <p>+ Include Private Key{" "}+ <Tooltip+ className="max-w-md"+ content="When on, the certificate's private key is written alongside the certificate as a .key file. The sync fails for a certificate whose key is not available (for example, one issued from an external CSR)."+ >+ <FontAwesomeIcon icon={faQuestionCircle} size="sm" className="ml-1" />+ </Tooltip>+ </p>+ </Switch>+ </FormControl>+ )}+ />+ )}+ </>+ )}+<Controllercontrol={control}name="syncOptions.certificateNameSchema"@@ -455,13 +531,24 @@ export const PkiSyncOptionsFields = ({ destination }: Props) => {belongs to</li></ul>- <span className="mt-1 text-xs text-bunker-300">- The schema must include <code>{"{{certificateId}}"}</code> or{" "}- <code>{"{{shortCertificateId}}"}</code> so each certificate gets a unique name.- The template itself can only contain letters, numbers, and the separators- allowed by the destination. When placeholders resolve, any characters the- destination doesn't support are replaced with hyphens.- </span>+ {currentDestination === PkiSync.LinuxServer ||+ currentDestination === PkiSync.WindowsServer ? (+ <span className="mt-1 text-xs text-bunker-300">+ A placeholder is optional here. Include one (for example{" "}+ <code>{"{{commonName}}"}</code>) so each certificate resolves to a distinct+ file name. A schema with no placeholder resolves to a fixed name and can be+ linked to only one certificate. When placeholders resolve, any characters the+ destination doesn't support are replaced with hyphens.+ </span>+ ) : (+ <span className="mt-1 text-xs text-bunker-300">+ The schema must include <code>{"{{certificateId}}"}</code> or{" "}+ <code>{"{{shortCertificateId}}"}</code> so each certificate gets a unique+ name. The template itself can only contain letters, numbers, and the+ separators allowed by the destination. When placeholders resolve, any+ characters the destination doesn't support are replaced with hyphens.+ </span>+ )}</div>{syncOption?.forbiddenCharacters && syncOption.forbiddenCharacters.length > 0 && (<div className="flex flex-col">diff --git a/frontend/src/components/pki-syncs/forms/WindowsServerPkiSyncFields.tsx b/frontend/src/components/pki-syncs/forms/WindowsServerPkiSyncFields.tsxnew file mode 100644index 0000000000..b354d26dab--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/WindowsServerPkiSyncFields.tsx@@ -0,0 +1,31 @@+import { Controller, useFormContext } from "react-hook-form";++import { FormControl, Input } from "@app/components/v2";+import { PkiSync } from "@app/hooks/api/pkiSyncs";++import { TPkiSyncForm } from "./schemas/pki-sync-schema";+import { PkiSyncConnectionField } from "./PkiSyncConnectionField";++export const WindowsServerPkiSyncFields = () => {+ const { control } = useFormContext<TPkiSyncForm & { destination: PkiSync.WindowsServer }>();++ return (+ <>+ <PkiSyncConnectionField />+ <Controller+ name="destinationConfig.destinationPath"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl+ isError={Boolean(error)}+ errorText={error?.message}+ label="Destination Directory"+ tooltipText="The absolute Windows path to the directory where certificate files are written (for example C:\certs). It is created if it does not exist."+ >+ <Input value={value ?? ""} onChange={onChange} placeholder="C:\certs" />+ </FormControl>+ )}+ />+ </>+ );+};diff --git a/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.tsnew file mode 100644index 0000000000..0f99511f1c--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts@@ -0,0 +1,78 @@+import { z } from "zod";++import { PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";++import { BasePkiSyncSchema } from "./base-pki-sync-schema";++const compileNameSchema = (val: string) =>+ val+ .replace(/\{\{shortCertificateId\}\}/g, "0".repeat(22))+ .replace(/\{\{certificateId\}\}/g, "0".repeat(32))+ .replace(/\{\{profileId\}\}/g, "0".repeat(32))+ .replace(/\{\{applicationId\}\}/g, "0".repeat(32))+ .replace(/\{\{applicationName\}\}/g, "application-name")+ .replace(/\{\{commonName\}\}/g, "common-name");++const LinuxServerSyncOptionsSchema = z.object({+ exportFormat: z.nativeEnum(PkiSyncExportFormat).default(PkiSyncExportFormat.Pem),+ includePrivateKey: z.boolean().default(true),+ certificateNameSchema: z+ .string()+ .trim()+ .min(1, "Certificate name schema is required")+ .refine(+ (val) => {+ const compiled = compileNameSchema(val);+ return /^[a-zA-Z0-9._-]{1,200}$/.test(compiled);+ },+ {+ message:+ "Certificate name schema must resolve to a single file name of 1-200 characters using only letters, digits, dots (.), dashes (-), and underscores (_). Available placeholders: {{certificateId}}, {{shortCertificateId}}, {{profileId}}, {{applicationId}}, {{applicationName}}, {{commonName}}. A schema with no placeholder can be linked to only one certificate."+ }+ )+});++const DestinationPathSchema = z+ .string()+ .trim()+ .min(1, "Destination path is required")+ .max(4096, "Destination path is too long")+ .refine((p) => p.startsWith("/"), { message: "Destination path must be absolute (start with /)" })+ .refine((p) => !/(^|\/)\.\.(\/|$)/.test(p), {+ message: "Destination path must not contain '..'"+ });++export const LinuxServerPkiSyncDestinationSchema = BasePkiSyncSchema(+ LinuxServerSyncOptionsSchema+).merge(+ z.object({+ destination: z.literal(PkiSync.LinuxServer),+ destinationConfig: z.object({+ destinationPath: DestinationPathSchema+ }),+ credentials: z+ .object({+ exportPassword: z.string().min(1).optional()+ })+ .optional()+ })+);++export const UpdateLinuxServerPkiSyncDestinationSchema =+ LinuxServerPkiSyncDestinationSchema.partial().merge(+ z.object({+ name: z+ .string()+ .trim()+ .min(1, "Name is required")+ .max(255, "Name must be less than 255 characters"),+ destination: z.literal(PkiSync.LinuxServer),+ connection: z.object({+ id: z.string().uuid("Invalid connection ID format"),+ name: z+ .string()+ .min(1, "Connection name is required")+ .max(255, "Connection name must be less than 255 characters")+ })+ })+ );diff --git a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.tsindex d6b9eeb4f3..127ab9197a 100644--- a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts@@ -1,5 +1,7 @@import { z } from "zod";+import { PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";+import {AwsCertificateManagerPkiSyncDestinationSchema,UpdateAwsCertificateManagerPkiSyncDestinationSchema@@ -28,10 +30,18 @@ import {F5BigIpPkiSyncDestinationSchema,UpdateF5BigIpPkiSyncDestinationSchema} from "./f5-big-ip-pki-sync-destination-schema";+import {+ LinuxServerPkiSyncDestinationSchema,+ UpdateLinuxServerPkiSyncDestinationSchema+} from "./linux-server-pki-sync-destination-schema";import {NetScalerPkiSyncDestinationSchema,UpdateNetScalerPkiSyncDestinationSchema} from "./netscaler-pki-sync-destination-schema";+import {+ UpdateWindowsServerPkiSyncDestinationSchema,+ WindowsServerPkiSyncDestinationSchema+} from "./windows-server-pki-sync-destination-schema";const PkiSyncUnionSchema = z.discriminatedUnion("destination", [AzureKeyVaultPkiSyncDestinationSchema,@@ -41,7 +51,9 @@ const PkiSyncUnionSchema = z.discriminatedUnion("destination", [ChefPkiSyncDestinationSchema,CloudflareCustomCertificatePkiSyncDestinationSchema,NetScalerPkiSyncDestinationSchema,- F5BigIpPkiSyncDestinationSchema+ F5BigIpPkiSyncDestinationSchema,+ LinuxServerPkiSyncDestinationSchema,+ WindowsServerPkiSyncDestinationSchema]);const UpdatePkiSyncUnionSchema = z.discriminatedUnion("destination", [@@ -52,10 +64,24 @@ const UpdatePkiSyncUnionSchema = z.discriminatedUnion("destination", [UpdateChefPkiSyncDestinationSchema,UpdateCloudflareCustomCertificatePkiSyncDestinationSchema,UpdateNetScalerPkiSyncDestinationSchema,- UpdateF5BigIpPkiSyncDestinationSchema+ UpdateF5BigIpPkiSyncDestinationSchema,+ UpdateLinuxServerPkiSyncDestinationSchema,+ UpdateWindowsServerPkiSyncDestinationSchema]);-export const PkiSyncFormSchema = PkiSyncUnionSchema;+export const PkiSyncFormSchema = PkiSyncUnionSchema.superRefine((data, ctx) => {+ if (+ (data.destination === PkiSync.WindowsServer || data.destination === PkiSync.LinuxServer) &&+ data.syncOptions?.exportFormat === PkiSyncExportFormat.Pkcs12 &&+ !data.credentials?.exportPassword+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["credentials", "exportPassword"],+ message: "A password is required for PKCS#12 exports"+ });+ }+});export const UpdatePkiSyncFormSchema = UpdatePkiSyncUnionSchema;diff --git a/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.tsnew file mode 100644index 0000000000..9edbb01811--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts@@ -0,0 +1,78 @@+import { z } from "zod";++import { PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";++import { BasePkiSyncSchema } from "./base-pki-sync-schema";++const compileNameSchema = (val: string) =>+ val+ .replace(/\{\{shortCertificateId\}\}/g, "0".repeat(22))+ .replace(/\{\{certificateId\}\}/g, "0".repeat(32))+ .replace(/\{\{profileId\}\}/g, "0".repeat(32))+ .replace(/\{\{applicationId\}\}/g, "0".repeat(32))+ .replace(/\{\{applicationName\}\}/g, "application-name")+ .replace(/\{\{commonName\}\}/g, "common-name");++const WindowsServerSyncOptionsSchema = z.object({+ exportFormat: z.nativeEnum(PkiSyncExportFormat).default(PkiSyncExportFormat.Pkcs12),+ includePrivateKey: z.boolean().default(true),+ certificateNameSchema: z+ .string()+ .trim()+ .min(1, "Certificate name schema is required")+ .refine((val) => /^[a-zA-Z0-9._-]{1,200}$/.test(compileNameSchema(val)), {+ message:+ "Certificate name schema must resolve to a single file name of 1-200 characters using only letters, digits, dots (.), dashes (-), and underscores (_). Available placeholders: {{certificateId}}, {{shortCertificateId}}, {{profileId}}, {{applicationId}}, {{applicationName}}, {{commonName}}. A schema with no placeholder can be linked to only one certificate."+ })+});++const WindowsDestinationPathSchema = z+ .string()+ .trim()+ .min(1, "Destination path is required")+ .max(4096, "Destination path is too long")+ .refine((p) => /^([a-zA-Z]:\\|\\\\)/.test(p), {+ message:+ "Destination path must be an absolute Windows path (for example C:\\certs or \\\\server\\share)"+ })+ .refine((p) => !/(^|[\\/])\.\.([\\/]|$)/.test(p), {+ message: "Destination path must not contain '..'"+ })+ .refine((p) => !/[\\/]{2,}/.test(p.startsWith("\\\\") ? p.slice(2) : p), {+ message: "Destination path must not contain consecutive path separators"+ });++export const WindowsServerPkiSyncDestinationSchema = BasePkiSyncSchema(+ WindowsServerSyncOptionsSchema+).merge(+ z.object({+ destination: z.literal(PkiSync.WindowsServer),+ destinationConfig: z.object({+ destinationPath: WindowsDestinationPathSchema+ }),+ credentials: z+ .object({+ exportPassword: z.string().min(1).optional()+ })+ .optional()+ })+);++export const UpdateWindowsServerPkiSyncDestinationSchema =+ WindowsServerPkiSyncDestinationSchema.partial().merge(+ z.object({+ name: z+ .string()+ .trim()+ .min(1, "Name is required")+ .max(255, "Name must be less than 255 characters"),+ destination: z.literal(PkiSync.WindowsServer),+ connection: z.object({+ id: z.string().uuid("Invalid connection ID format"),+ name: z+ .string()+ .min(1, "Connection name is required")+ .max(255, "Connection name must be less than 255 characters")+ })+ })+ );diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.tsindex 7e4ac18e69..b11bb9febe 100644--- a/frontend/src/helpers/appConnections.ts+++ b/frontend/src/helpers/appConnections.ts@@ -93,6 +93,7 @@ import { TravisCIConnectionMethod } from "@app/hooks/api/appConnections/types/trimport { TriggerDevConnectionMethod } from "@app/hooks/api/appConnections/types/trigger-dev-connection";import { VenafiConnectionMethod } from "@app/hooks/api/appConnections/types/venafi-connection";import { VenafiTppConnectionMethod } from "@app/hooks/api/appConnections/types/venafi-tpp-connection";+import { WinRMConnectionMethod } from "@app/hooks/api/appConnections/types/winrm-connection";import { IntegrationsListPageTabs } from "@app/types/integrations";export const APP_CONNECTION_MAP: Record<@@ -412,12 +413,18 @@ export const APP_CONNECTION_MAP: Record<description: "Account and job access for dbt."},[AppConnection.SMB]: {- name: "SMB",+ name: "Windows (SMB)",image: "SMB.png",size: 50,category: "STORAGE",description: "Connect to an SMB/CIFS file share."},+ [AppConnection.WinRM]: {+ name: "Windows (WinRM)",+ image: "Windows.png",+ category: "INFRASTRUCTURE",+ description: "Connect to a Windows host over WinRM via the Gateway."+ },[AppConnection.OpenRouter]: {name: "OpenRouter",image: "OpenRouter.png",@@ -720,6 +727,8 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"])return { name: "SSH Key", icon: faKey };case SmbConnectionMethod.Credentials:return { name: "Credentials", icon: faLock };+ case WinRMConnectionMethod.UsernamePassword:+ return { name: "Username & Password", icon: faLock };case ExternalInfisicalConnectionMethod.MachineIdentityUniversalAuth:return { name: "Machine Identity - Universal Auth", icon: faKey };case NetScalerConnectionMethod.BasicAuth:diff --git a/frontend/src/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.tsindex e9db4a8abc..feff1d6264 100644--- a/frontend/src/helpers/pkiSyncs.ts+++ b/frontend/src/helpers/pkiSyncs.ts@@ -39,6 +39,14 @@ export const PKI_SYNC_MAP: Record<[PkiSync.F5BigIp]: {name: "F5 BIG-IP",image: "F5 BIG-IP.png"+ },+ [PkiSync.LinuxServer]: {+ name: "Linux Server",+ image: "SSH.png"+ },+ [PkiSync.WindowsServer]: {+ name: "Windows Server",+ image: "Windows.png"}};@@ -50,5 +58,7 @@ export const PKI_SYNC_CONNECTION_MAP: Record<PkiSync, AppConnection> = {[PkiSync.Chef]: AppConnection.Chef,[PkiSync.CloudflareCustomCertificate]: AppConnection.Cloudflare,[PkiSync.NetScaler]: AppConnection.NetScaler,- [PkiSync.F5BigIp]: AppConnection.F5BigIp+ [PkiSync.F5BigIp]: AppConnection.F5BigIp,+ [PkiSync.LinuxServer]: AppConnection.SSH,+ [PkiSync.WindowsServer]: AppConnection.WinRM};diff --git a/frontend/src/hooks/api/appConnections/enums.ts b/frontend/src/hooks/api/appConnections/enums.tsindex e63000329e..963b67f21e 100644--- a/frontend/src/hooks/api/appConnections/enums.ts+++ b/frontend/src/hooks/api/appConnections/enums.ts@@ -49,6 +49,7 @@ export enum AppConnection {SSH = "ssh",Dbt = "dbt",SMB = "smb",+ WinRM = "winrm",OpenRouter = "open-router",OpenAI = "openai",CircleCI = "circleci",diff --git a/frontend/src/hooks/api/appConnections/types/app-options.ts b/frontend/src/hooks/api/appConnections/types/app-options.tsindex 02ba74b4cf..00a90ce405 100644--- a/frontend/src/hooks/api/appConnections/types/app-options.ts+++ b/frontend/src/hooks/api/appConnections/types/app-options.ts@@ -224,6 +224,10 @@ export type TSmbConnectionOption = TAppConnectionOptionBase & {app: AppConnection.SMB;};+export type TWinRMConnectionOption = TAppConnectionOptionBase & {+ app: AppConnection.WinRM;+};+export type TOpenRouterConnectionOption = TAppConnectionOptionBase & {app: AppConnection.OpenRouter;};@@ -380,6 +384,7 @@ export type TAppConnectionOption =| TSshConnectionOption| TDbtConnectionOption| TSmbConnectionOption+ | TWinRMConnectionOption| TAzureEntraIdConnectionOption| TVenafiConnectionOption| TVenafiTppConnectionOption@@ -458,6 +463,7 @@ export type TAppConnectionOptionMap = {[AppConnection.SSH]: TSshConnectionOption;[AppConnection.Dbt]: TDbtConnectionOption;[AppConnection.SMB]: TSmbConnectionOption;+ [AppConnection.WinRM]: TWinRMConnectionOption;[AppConnection.CircleCI]: TCircleCISyncConnectionOption;[AppConnection.Cloud66]: TCloud66ConnectionOption;[AppConnection.AzureEntraId]: TAzureEntraIdConnectionOption;diff --git a/frontend/src/hooks/api/appConnections/types/index.ts b/frontend/src/hooks/api/appConnections/types/index.tsindex e10ad41139..0b8a8f4f66 100644--- a/frontend/src/hooks/api/appConnections/types/index.ts+++ b/frontend/src/hooks/api/appConnections/types/index.ts@@ -77,6 +77,7 @@ import { TVenafiConnection } from "./venafi-connection";import { TVenafiTppConnection } from "./venafi-tpp-connection";import { TVercelConnection } from "./vercel-connection";import { TWindmillConnection } from "./windmill-connection";+import { TWinRMConnection } from "./winrm-connection";import { TZabbixConnection } from "./zabbix-connection";export * from "./1password-connection";@@ -153,6 +154,7 @@ export * from "./venafi-connection";export * from "./venafi-tpp-connection";export * from "./vercel-connection";export * from "./windmill-connection";+export * from "./winrm-connection";export * from "./zabbix-connection";export type TAppConnection =@@ -206,6 +208,7 @@ export type TAppConnection =| TSshConnection| TDbtConnection| TSmbConnection+ | TWinRMConnection| TOpenRouterConnection| TOpenAIConnection| TAnthropicConnectiondiff --git a/frontend/src/hooks/api/appConnections/types/winrm-connection.ts b/frontend/src/hooks/api/appConnections/types/winrm-connection.tsnew file mode 100644index 0000000000..ff221de11a--- /dev/null+++ b/frontend/src/hooks/api/appConnections/types/winrm-connection.ts@@ -0,0 +1,18 @@+import { AppConnection } from "../enums";+import { TRootAppConnection } from "./root-connection";++export enum WinRMConnectionMethod {+ UsernamePassword = "username-password"+}++export type TWinRMConnection = TRootAppConnection & { app: AppConnection.WinRM } & {+ method: WinRMConnectionMethod.UsernamePassword;+ credentials: {+ host: string;+ port?: number;+ username: string;+ password: string;+ useHttps?: boolean;+ insecure?: boolean;+ };+};diff --git a/frontend/src/hooks/api/pkiSyncs/enums.ts b/frontend/src/hooks/api/pkiSyncs/enums.tsindex 50e0de6ff1..16db6bdb86 100644--- a/frontend/src/hooks/api/pkiSyncs/enums.ts+++ b/frontend/src/hooks/api/pkiSyncs/enums.ts@@ -6,7 +6,14 @@ export enum PkiSync {Chef = "chef",CloudflareCustomCertificate = "cloudflare-custom-certificate",NetScaler = "netscaler",- F5BigIp = "f5-big-ip"+ F5BigIp = "f5-big-ip",+ LinuxServer = "linux-server",+ WindowsServer = "windows-server"+}++export enum PkiSyncExportFormat {+ Pem = "pem",+ Pkcs12 = "pkcs12"}export enum PkiSyncStatus {diff --git a/frontend/src/hooks/api/pkiSyncs/types/index.ts b/frontend/src/hooks/api/pkiSyncs/types/index.tsindex 0b98bafa60..a2082896f1 100644--- a/frontend/src/hooks/api/pkiSyncs/types/index.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/index.ts@@ -1,4 +1,4 @@-import { PkiSync } from "@app/hooks/api/pkiSyncs";+import { PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";import { TAwsCertificateManagerPkiSync } from "./aws-certificate-manager-sync";import { TAwsElasticLoadBalancerPkiSync } from "./aws-elastic-load-balancer-sync";@@ -7,7 +7,9 @@ import { TAzureKeyVaultPkiSync } from "./azure-key-vault-sync";import { TChefPkiSync } from "./chef-sync";import { TCloudflareCustomCertificatePkiSync } from "./cloudflare-custom-certificate-sync";import { TF5BigIpPkiSync } from "./f5-big-ip-sync";+import { TLinuxServerPkiSync } from "./linux-server-sync";import { TNetScalerPkiSync } from "./netscaler-sync";+import { TWindowsServerPkiSync } from "./windows-server-sync";export type TPkiSyncOption = {name: string;@@ -30,7 +32,9 @@ export type TPkiSync =| TChefPkiSync| TCloudflareCustomCertificatePkiSync| TNetScalerPkiSync- | TF5BigIpPkiSync;+ | TF5BigIpPkiSync+ | TLinuxServerPkiSync+ | TWindowsServerPkiSync;export type TListPkiSyncs = { pkiSyncs: TPkiSync[] };@@ -50,6 +54,9 @@ type TCreatePkiSyncDTOBase = {preserveItemOnRenewal?: boolean;updateExistingCertificates?: boolean;preserveSecretOnRenewal?: boolean;+ includeRootCa?: boolean;+ exportFormat?: PkiSyncExportFormat;+ includePrivateKey?: boolean;fieldMappings?: {certificate: string;privateKey: string;@@ -57,6 +64,9 @@ type TCreatePkiSyncDTOBase = {caCertificate: string;};};+ credentials?: {+ exportPassword?: string;+ };isAutoSyncEnabled: boolean;subscriberId?: string | null;certificateIds?: string[];@@ -83,6 +93,7 @@ export type TCreatePkiSyncDTO = TCreatePkiSyncDTOBase & {profileName?: string;createProfileIfMissing?: boolean;parentProfile?: string;+ destinationPath?: string;};};@@ -123,4 +134,6 @@ export * from "./chef-sync";export * from "./cloudflare-custom-certificate-sync";export * from "./common";export * from "./f5-big-ip-sync";+export * from "./linux-server-sync";export * from "./netscaler-sync";+export * from "./windows-server-sync";diff --git a/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.tsnew file mode 100644index 0000000000..73a85ed476--- /dev/null+++ b/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts@@ -0,0 +1,20 @@+import { AppConnection } from "@app/hooks/api/appConnections/enums";++import { PkiSync, PkiSyncExportFormat } from "../enums";+import { TRootPkiSync } from "./common";++export type TLinuxServerPkiSync = TRootPkiSync & {+ destination: PkiSync.LinuxServer;+ destinationConfig: {+ destinationPath: string;+ };+ syncOptions: TRootPkiSync["syncOptions"] & {+ exportFormat?: PkiSyncExportFormat;+ includePrivateKey?: boolean;+ };+ connection: {+ app: AppConnection.SSH;+ name: string;+ id: string;+ };+};diff --git a/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.tsnew file mode 100644index 0000000000..d3e5708b6d--- /dev/null+++ b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts@@ -0,0 +1,20 @@+import { AppConnection } from "@app/hooks/api/appConnections/enums";++import { PkiSync, PkiSyncExportFormat } from "../enums";+import { TRootPkiSync } from "./common";++export type TWindowsServerPkiSync = TRootPkiSync & {+ destination: PkiSync.WindowsServer;+ destinationConfig: {+ destinationPath: string;+ };+ syncOptions: TRootPkiSync["syncOptions"] & {+ exportFormat?: PkiSyncExportFormat;+ includePrivateKey?: boolean;+ };+ connection: {+ app: AppConnection.WinRM;+ name: string;+ id: string;+ };+};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsxindex 1dcd175190..c24e1f2aee 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx@@ -14,7 +14,9 @@ import {AzureKeyVaultPkiSyncDestinationSection,ChefPkiSyncDestinationSection,F5BigIpPkiSyncDestinationSection,- NetScalerPkiSyncDestinationSection+ LinuxServerPkiSyncDestinationSection,+ NetScalerPkiSyncDestinationSection,+ WindowsServerPkiSyncDestinationSection} from "./PkiSyncDestinationSection/index";const GenericFieldLabel = ({ label, children }: { label: string; children: React.ReactNode }) => (@@ -57,6 +59,12 @@ export const PkiSyncDestinationSection = ({ pkiSync, onEditDestination }: Props)case PkiSync.F5BigIp:DestinationComponents = <F5BigIpPkiSyncDestinationSection pkiSync={pkiSync} />;break;+ case PkiSync.LinuxServer:+ DestinationComponents = <LinuxServerPkiSyncDestinationSection pkiSync={pkiSync} />;+ break;+ case PkiSync.WindowsServer:+ DestinationComponents = <WindowsServerPkiSyncDestinationSection pkiSync={pkiSync} />;+ break;default:// For future destinations, return null (no additional fields to show)DestinationComponents = null;diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsxnew file mode 100644index 0000000000..dc02875823--- /dev/null+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsx@@ -0,0 +1,29 @@+/* eslint-disable jsx-a11y/label-has-associated-control */+import { PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";+import { TLinuxServerPkiSync } from "@app/hooks/api/pkiSyncs/types/linux-server-sync";++const GenericFieldLabel = ({ label, children }: { label: string; children: React.ReactNode }) => (+ <div className="mb-4">+ <p className="text-sm font-medium text-mineshaft-300">{label}</p>+ <div className="text-sm text-mineshaft-300">{children}</div>+ </div>+);++type Props = {+ pkiSync: TLinuxServerPkiSync;+};++export const LinuxServerPkiSyncDestinationSection = ({ pkiSync }: Props) => {+ const exportFormat = pkiSync.syncOptions.exportFormat ?? PkiSyncExportFormat.Pem;++ return (+ <>+ <GenericFieldLabel label="Destination Directory">+ {pkiSync.destinationConfig.destinationPath}+ </GenericFieldLabel>+ <GenericFieldLabel label="Export Format">+ {exportFormat === PkiSyncExportFormat.Pkcs12 ? "PKCS#12 (.pfx)" : "PEM"}+ </GenericFieldLabel>+ </>+ );+};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsxnew file mode 100644index 0000000000..67c3b43ff7--- /dev/null+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsx@@ -0,0 +1,29 @@+/* eslint-disable jsx-a11y/label-has-associated-control */+import { PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";+import { TWindowsServerPkiSync } from "@app/hooks/api/pkiSyncs/types/windows-server-sync";++const GenericFieldLabel = ({ label, children }: { label: string; children: React.ReactNode }) => (+ <div className="mb-4">+ <p className="text-sm font-medium text-mineshaft-300">{label}</p>+ <div className="text-sm text-mineshaft-300">{children}</div>+ </div>+);++type Props = {+ pkiSync: TWindowsServerPkiSync;+};++export const WindowsServerPkiSyncDestinationSection = ({ pkiSync }: Props) => {+ const exportFormat = pkiSync.syncOptions.exportFormat ?? PkiSyncExportFormat.Pkcs12;++ return (+ <>+ <GenericFieldLabel label="Destination Directory">+ {pkiSync.destinationConfig.destinationPath}+ </GenericFieldLabel>+ <GenericFieldLabel label="Export Format">+ {exportFormat === PkiSyncExportFormat.Pkcs12 ? "PKCS#12 (.pfx)" : "PEM"}+ </GenericFieldLabel>+ </>+ );+};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.tsindex 26da31da1c..435fde4d0d 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts@@ -4,4 +4,6 @@ export { AwsSecretsManagerPkiSyncDestinationSection } from "./AwsSecretsManagerPexport { AzureKeyVaultPkiSyncDestinationSection } from "./AzureKeyVaultPkiSyncDestinationSection";export { ChefPkiSyncDestinationSection } from "./ChefPkiSyncDestinationSection";export { F5BigIpPkiSyncDestinationSection } from "./F5BigIpPkiSyncDestinationSection";+export { LinuxServerPkiSyncDestinationSection } from "./LinuxServerPkiSyncDestinationSection";export { NetScalerPkiSyncDestinationSection } from "./NetScalerPkiSyncDestinationSection";+export { WindowsServerPkiSyncDestinationSection } from "./WindowsServerPkiSyncDestinationSection";diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsxindex 2943ba2363..648766e265 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx@@ -92,6 +92,7 @@ import { VenafiConnectionForm } from "./VenafiConnectionForm";import { VenafiTppConnectionForm } from "./VenafiTppConnectionForm";import { VercelConnectionForm } from "./VercelConnectionForm";import { WindmillConnectionForm } from "./WindmillConnectionForm";+import { WinRMConnectionForm } from "./WinRMConnectionForm";import { ZabbixConnectionForm } from "./ZabbixConnectionForm";type AppConnectionFormData = DiscriminativePick<@@ -208,6 +209,8 @@ const CreateForm = ({ app, onComplete, projectId }: CreateFormProps) => {return <AzureADCSConnectionForm onSubmit={onSubmit} />;case AppConnection.ADCS:return <AdcsConnectionForm onSubmit={onSubmit} />;+ case AppConnection.WinRM:+ return <WinRMConnectionForm onSubmit={onSubmit} />;case AppConnection.Databricks:return <DatabricksConnectionForm onSubmit={onSubmit} />;case AppConnection.Humanitec:@@ -451,6 +454,8 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {return <AzureADCSConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;case AppConnection.ADCS:return <AdcsConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;+ case AppConnection.WinRM:+ return <WinRMConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;case AppConnection.Databricks:return <DatabricksConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;case AppConnection.Humanitec:diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/WinRMConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/WinRMConnectionForm.tsxnew file mode 100644index 0000000000..3cef968e32--- /dev/null+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/WinRMConnectionForm.tsx@@ -0,0 +1,313 @@+import { Controller, FormProvider, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { Info } from "lucide-react";+import { z } from "zod";++import { OrgPermissionCan } from "@app/components/permissions";+import {+ Field,+ FieldDescription,+ FieldError,+ FieldLabel,+ Input,+ SecretInput,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";+import { OrgPermissionSubjects } from "@app/context";+import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";+import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";+import { TWinRMConnection, WinRMConnectionMethod } from "@app/hooks/api/appConnections";+import { AppConnection } from "@app/hooks/api/appConnections/enums";++import { AppConnectionFormFooter } from "./AppConnectionFormFooter";+import {+ genericAppConnectionFieldsSchema,+ GenericAppConnectionsFields+} from "./GenericAppConnectionFields";++type Props = {+ appConnection?: TWinRMConnection;+ onSubmit: (formData: FormData) => Promise<void>;+};++const rootSchema = genericAppConnectionFieldsSchema.extend({+ app: z.literal(AppConnection.WinRM)+});++const formSchema = z+ .discriminatedUnion("method", [+ rootSchema.extend({+ method: z.literal(WinRMConnectionMethod.UsernamePassword),+ credentials: z.object({+ host: z.string().trim().min(1, "Host required"),+ port: z.coerce.number().int().min(1).max(65535),+ username: z.string().trim().min(1, "Username required"),+ password: z.string().min(1, "Password required"),+ useHttps: z.boolean(),+ insecure: z.boolean()+ })+ })+ ])+ .superRefine((data, ctx) => {+ if (!data.gatewayId) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Gateway required",+ path: ["gatewayId"]+ });+ }+ });++type FormData = z.infer<typeof formSchema>;++export const WinRMConnectionForm = ({ appConnection, onSubmit }: Props) => {+ const isUpdate = Boolean(appConnection);++ const form = useForm<FormData>({+ resolver: zodResolver(formSchema),+ defaultValues: appConnection ?? {+ app: AppConnection.WinRM,+ method: WinRMConnectionMethod.UsernamePassword,+ gatewayId: null,+ gatewayPoolId: null,+ credentials: {+ host: "",+ port: 5985,+ username: "",+ password: "",+ useHttps: false,+ insecure: false+ }+ }+ });++ const { handleSubmit, control, setValue, watch } = form;++ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");+ const useHttps = watch("credentials.useHttps");++ return (+ <FormProvider {...form}>+ <form onSubmit={handleSubmit(onSubmit)}>+ {!isUpdate && <GenericAppConnectionsFields />}+ <Controller+ name="method"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>+ Method+ <Tooltip>+ <TooltipTrigger asChild>+ <Info />+ </TooltipTrigger>+ <TooltipContent className="max-w-sm">+ {`The method you would like to use to connect with ${+ APP_CONNECTION_MAP[AppConnection.WinRM].name+ }. This field cannot be changed after creation.`}+ </TooltipContent>+ </Tooltip>+ </FieldLabel>+ <Select disabled={isUpdate} value={value} onValueChange={(val) => onChange(val)}>+ <SelectTrigger className="w-full" isError={Boolean(error)}>+ <SelectValue placeholder="Select a method..." />+ </SelectTrigger>+ <SelectContent position="popper">+ {Object.values(WinRMConnectionMethod).map((method) => {+ return (+ <SelectItem value={method} key={method}>+ {getAppConnectionMethodDetails(method).name}+ </SelectItem>+ );+ })}+ </SelectContent>+ </Select>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ <OrgPermissionCan+ I={OrgGatewayPermissionActions.AttachGateways}+ a={OrgPermissionSubjects.Gateway}+ >+ {(isAllowed) => (+ <Controller+ name="gatewayId"+ control={control}+ render={({ fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>Gateway</FieldLabel>+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <GatewayPicker+ isRequired+ isDisabled={!isAllowed}+ value={{+ gatewayId: gatewayId ?? null,+ gatewayPoolId: gatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </TooltipTrigger>+ {!isAllowed && (+ <TooltipContent>+ Restricted access. You don't have permission to attach gateways to+ resources.+ </TooltipContent>+ )}+ </Tooltip>+ <FieldDescription>+ Windows hosts are reached over WinRM through a Gateway inside your network.+ </FieldDescription>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ )}+ </OrgPermissionCan>+ <div className="grid grid-cols-3 gap-2">+ <Controller+ name="credentials.host"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field className="col-span-2 mb-4">+ <FieldLabel htmlFor="host">Host</FieldLabel>+ <Input+ id="host"+ {...field}+ placeholder="win01.corp.example.com"+ isError={Boolean(error?.message)}+ />+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ <Controller+ name="credentials.port"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="port">Port</FieldLabel>+ <Input+ id="port"+ type="number"+ {...field}+ onChange={(e) => field.onChange(Number(e.target.value))}+ isError={Boolean(error?.message)}+ />+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ </div>+ <div className="grid grid-cols-2 gap-2">+ <Controller+ name="credentials.username"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="username">Username</FieldLabel>+ <Input+ id="username"+ {...field}+ placeholder="DOMAIN\\username or [email protected]"+ isError={Boolean(error?.message)}+ />+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ <Controller+ name="credentials.password"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="password">Password</FieldLabel>+ <SecretInput value={value} onChange={(e) => onChange(e.target.value)} />+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ </div>+ <Controller+ name="credentials.useHttps"+ control={control}+ render={({ field: { value }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>Transport</FieldLabel>+ <Select+ value={value ? "https" : "http"}+ onValueChange={(val) => {+ const https = val === "https";+ setValue("credentials.useHttps", https, { shouldDirty: true });+ setValue("credentials.port", https ? 5986 : 5985, { shouldDirty: true });+ if (!https) {+ setValue("credentials.insecure", false, { shouldDirty: true });+ }+ }}+ >+ <SelectTrigger className="w-full" isError={Boolean(error)}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value="http">+ HTTP with NTLM message encryption (port 5985)+ </SelectItem>+ <SelectItem value="https">HTTPS (port 5986)</SelectItem>+ </SelectContent>+ </Select>+ <FieldDescription>+ HTTP uses NTLM message encryption and needs no server certificate. HTTPS requires a+ WinRM HTTPS listener on the host.+ </FieldDescription>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ {useHttps && (+ <Controller+ name="credentials.insecure"+ control={control}+ render={({ field: { value }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>TLS Certificate Verification</FieldLabel>+ <Select+ value={value ? "skip" : "verify"}+ onValueChange={(val) =>+ setValue("credentials.insecure", val === "skip", { shouldDirty: true })+ }+ >+ <SelectTrigger className="w-full" isError={Boolean(error)}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value="verify">Verify certificate</SelectItem>+ <SelectItem value="skip">Skip verification (self-signed listener)</SelectItem>+ </SelectContent>+ </Select>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ )}+ <AppConnectionFormFooter+ submitLabel={isUpdate ? "Update Credentials" : "Connect to Windows (WinRM)"}+ />+ </form>+ </FormProvider>+ );+};