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 PKI windows and linux post-sync command support
Carlos Monastyrski2f4ce0bb43a0
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex f5076817fa..8ce2b374fb 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -47,6 +47,7 @@ import {import { TAllowedFields } from "@app/services/identity-ldap-auth/identity-ldap-auth-types";import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";import { PkiItemType } from "@app/services/pki-collection/pki-collection-types";+import { TPostSyncCommandResult } from "@app/services/pki-sync/pki-sync-post-sync-command-fns";import { SecretSync, SecretSyncImportBehavior } from "@app/services/secret-sync/secret-sync-enums";import {TCreateSecretSyncDTO,@@ -4842,6 +4843,7 @@ interface PkiSyncSyncCertificatesEvent {syncMessage: string | null;jobId: string;jobRanAt: Date;+ postSyncCommand?: TPostSyncCommandResult;};}diff --git a/backend/src/lib/gateway-v2/ssh-rpc.ts b/backend/src/lib/gateway-v2/ssh-rpc.tsindex c91c8cd7b9..c1f1129814 100644--- a/backend/src/lib/gateway-v2/ssh-rpc.ts+++ b/backend/src/lib/gateway-v2/ssh-rpc.ts@@ -1,5 +1,11 @@import { postGatewayRpc } from "./gateway-rpc";+export enum SshExecAuthMethod {+ Password = "password",+ PublicKey = "public-key",+ Certificate = "certificate"+}+export type SshExecCredentials = {authMethod: string;username: string;diff --git a/backend/src/lib/gateway-v2/winrm-rpc.ts b/backend/src/lib/gateway-v2/winrm-rpc.tsindex cbe398857c..ddc3b70d8a 100644--- a/backend/src/lib/gateway-v2/winrm-rpc.ts+++ b/backend/src/lib/gateway-v2/winrm-rpc.ts@@ -4,6 +4,7 @@ export enum WinRmRpcEndpoint {Test = "/v1/test-connection",DeliverFiles = "/v1/deliver-files",RemoveFiles = "/v1/remove-files",+ RunCommand = "/v1/run-command",EnumerateAccounts = "/v1/enumerate-accounts",EnumerateDependencies = "/v1/enumerate-dependencies",RotateCredential = "/v1/rotate-credential",@@ -31,6 +32,7 @@ export type WinRmRpcRequestBody = {export type WinRmTestResult = { ok: boolean };export type WinRmDeliverResult = { delivered: number };export type WinRmRemoveResult = { removed: number };+export type WinRmRunCommandResult = { stdout: string; stderr: string; exitCode: number };export type WinRmRpcSuccess<T> = { ok: true; status: number; result: T };export type WinRmRpcFailure = { ok: false; status: number; errorMessage: string };diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex e23b544dcf..7b18f3a79e 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -3660,6 +3660,7 @@ export const registerRoutes = async (certificateDAL,certificateSyncDAL,pkiSubscriberDAL,+ appConnectionDAL,appConnectionService,permissionService,licenseService,diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.tsindex c692a41602..d0cac9d2b7 100644--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts@@ -74,6 +74,7 @@ const PkiSyncOptionsSchema = z.object({destination: z.nativeEnum(PkiSync),canImportCertificates: z.boolean(),canRemoveCertificates: z.boolean(),+ canRunPostSyncCommand: z.boolean().optional(),maxCertificates: z.number().optional(),defaultCertificateNameSchema: z.string().optional(),forbiddenCharacters: z.string().optional(),diff --git a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts b/backend/src/services/app-connection/ssh/ssh-connection-fns.tsindex 953ef9bbd8..b7b53cd21f 100644--- a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts+++ b/backend/src/services/app-connection/ssh/ssh-connection-fns.ts@@ -6,6 +6,7 @@ import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2import { BadRequestError, InternalServerError } from "@app/lib/errors";import { GatewayProxyProtocol } from "@app/lib/gateway";import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";+import { callSshExec, SshExecAuthMethod, SshExecCredentials, SshExecResult } from "@app/lib/gateway-v2/ssh-rpc";import { logger } from "@app/lib/logger";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";import { AppConnection } from "@app/services/app-connection/app-connection-enums";@@ -236,6 +237,93 @@ export const withSshConnection = async <T>(gatewayServices.gatewayPoolService);+type TSshGatewayServices = {+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+};++const toSshExecCredentials = (config: TSshConnectionConfig): SshExecCredentials => {+ switch (config.method) {+ case SshConnectionMethod.Password:+ return {+ authMethod: SshExecAuthMethod.Password,+ username: config.credentials.username,+ password: config.credentials.password+ };+ case SshConnectionMethod.SshKey:+ return {+ authMethod: SshExecAuthMethod.PublicKey,+ username: config.credentials.username,+ privateKey: config.credentials.privateKey+ };+ default:+ throw new InternalServerError({+ message: `Unhandled connection method: ${(config as { method: string }).method}`+ });+ }+};++export const executeSshCommandViaGateway = async (+ config: TSshConnectionConfig,+ gatewayServices: TSshGatewayServices,+ args: { command: string; timeoutMs: number }+): Promise<SshExecResult> => {+ const { gatewayV2Service, gatewayPoolService } = gatewayServices;+ const { gatewayId: directGatewayId, gatewayPoolId, credentials } = config;++ if (gatewayPoolId && !gatewayPoolService) {+ throw new InternalServerError({+ message: "Pool-backed connections require gatewayPoolService at the call site"+ });+ }++ const gatewayId =+ gatewayPoolId && gatewayPoolService+ ? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: directGatewayId, gatewayPoolId })+ : directGatewayId;++ if (!gatewayId) {+ throw new BadRequestError({+ message: "Running a command on the host requires the SSH connection to use a gateway."+ });+ }+ if (!gatewayV2Service) {+ throw new InternalServerError({ message: "Gateway-backed commands require gatewayV2Service at the call site" });+ }++ await blockLocalAndPrivateIpAddresses(`ssh://${credentials.host}:${credentials.port}`, true);++ const connectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId,+ targetHost: credentials.host,+ targetPort: credentials.port+ });+ if (!connectionDetails) {+ throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });+ }++ const response = await withGatewayV2Proxy(+ async (proxyPort) =>+ callSshExec({+ port: proxyPort,+ command: args.command,+ credentials: toSshExecCredentials(config),+ timeoutMs: args.timeoutMs+ }),+ {+ protocol: GatewayProxyProtocol.Discovery,+ relayHost: connectionDetails.relayHost,+ gateway: connectionDetails.gateway,+ relay: connectionDetails.relay+ }+ );++ if (!response.ok) {+ throw new BadRequestError({ message: response.errorMessage });+ }+ return response.result;+};+export const validateSshConnectionCredentials = async (config: TSshConnectionConfig,_gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,diff --git a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-constants.ts b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-constants.tsindex 265e00cac0..696df12b5b 100644--- a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-constants.ts@@ -44,6 +44,7 @@ export const AWS_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION = {destination: PkiSync.AwsCertificateManager,canImportCertificates: false,canRemoveCertificates: true,+ canRunPostSyncCommand: false,defaultCertificateNameSchema: "Infisical-{{certificateId}}",forbiddenCharacters: AWS_CERTIFICATE_MANAGER_CERTIFICATE_NAMING.FORBIDDEN_CHARACTERS,allowedCharacterPattern: AWS_CERTIFICATE_MANAGER_CERTIFICATE_NAMING.ALLOWED_CHARACTER_PATTERN,diff --git a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.tsindex 137f044ef3..0de9bc2908 100644--- a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts@@ -4,7 +4,7 @@ import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection, AWSRegion } 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 { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";+import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";import { AWS_CERTIFICATE_MANAGER_CERTIFICATE_NAMING } from "./aws-certificate-manager-pki-sync-constants";@@ -17,6 +17,7 @@ const AwsCertificateManagerPkiSyncOptionsSchema = z.object({canRemoveCertificates: z.boolean().default(true),includeRootCa: z.boolean().default(false),preserveArn: z.boolean().default(true),+ postSyncCommand: PostSyncCommandSchema,certificateNameSchema: z.string().trim()diff --git a/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-constants.ts b/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-constants.tsindex 6f7165b034..3ca297ef0e 100644--- a/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-constants.ts@@ -6,5 +6,6 @@ export const AWS_ELASTIC_LOAD_BALANCER_PKI_SYNC_LIST_OPTION = {connection: AppConnection.AWS,destination: PkiSync.AwsElasticLoadBalancer,canImportCertificates: false,- canRemoveCertificates: true+ canRemoveCertificates: true,+ canRunPostSyncCommand: false} as const;diff --git a/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.tsindex e71a290b5c..859a744ba1 100644--- a/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts@@ -3,7 +3,7 @@ import { z } from "zod";import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";-import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";+import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";export const AwsElasticLoadBalancerListenerSchema = z.object({listenerArn: z.string().min(1, "Listener ARN is required"),@@ -25,7 +25,8 @@ const AwsElasticLoadBalancerPkiSyncOptionsSchema = z.object({canRemoveCertificates: z.boolean().default(false),preserveArn: z.boolean().default(true),includeRootCa: z.boolean().default(false),- certificateNameSchema: z.string().optional()+ certificateNameSchema: z.string().optional(),+ postSyncCommand: PostSyncCommandSchema});export const AwsElasticLoadBalancerPkiSyncSchema = PkiSyncSchema.extend({diff --git a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-constants.ts b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-constants.tsindex e066b05ff5..83a7414f15 100644--- a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-constants.ts@@ -62,6 +62,7 @@ export const AWS_SECRETS_MANAGER_PKI_SYNC_LIST_OPTION = {destination: PkiSync.AwsSecretsManager,canImportCertificates: false,canRemoveCertificates: true,+ canRunPostSyncCommand: false,defaultCertificateNameSchema: "infisical-{{certificateId}}",forbiddenCharacters: AWS_SECRETS_MANAGER_PKI_SYNC_CERTIFICATE_NAMING.FORBIDDEN_CHARACTERS,allowedCharacterPattern: AWS_SECRETS_MANAGER_PKI_SYNC_CERTIFICATE_NAMING.ALLOWED_CHARACTER_PATTERN,diff --git a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.tsindex cb95a6fa0a..021b67c1c3 100644--- a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts@@ -4,7 +4,7 @@ import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection, AWSRegion } 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 { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";+import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";import { AWS_SECRETS_MANAGER_PKI_SYNC_CERTIFICATE_NAMING } from "./aws-secrets-manager-pki-sync-constants";@@ -26,6 +26,7 @@ const AwsSecretsManagerPkiSyncOptionsSchema = z.object({includeRootCa: z.boolean().default(false),preserveSecretOnRenewal: z.boolean().default(true),updateExistingCertificates: z.boolean().default(true),+ postSyncCommand: PostSyncCommandSchema,certificateNameSchema: z.string().trim()diff --git a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-constants.ts b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-constants.tsindex 3c64bc86de..1e83d2e121 100644--- a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-constants.ts@@ -44,6 +44,7 @@ export const AZURE_KEY_VAULT_PKI_SYNC_LIST_OPTION = {destination: PkiSync.AzureKeyVault,canImportCertificates: false,canRemoveCertificates: true,+ canRunPostSyncCommand: false,defaultCertificateNameSchema: "Infisical-PKI-Sync-{{certificateId}}",forbiddenCharacters: AZURE_KEY_VAULT_CERTIFICATE_NAMING.FORBIDDEN_CHARACTERS,allowedCharacterPattern: AZURE_KEY_VAULT_CERTIFICATE_NAMING.ALLOWED_CHARACTER_PATTERN,diff --git a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.tsindex 7a7ce920d1..299e17d66c 100644--- a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts@@ -5,7 +5,7 @@ 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 { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";+import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";import { AZURE_KEY_VAULT_CERTIFICATE_NAMING } from "./azure-key-vault-pki-sync-constants";@@ -20,6 +20,7 @@ export const AzureKeyVaultPkiSyncOptionsSchema = z.object({canRemoveCertificates: z.boolean().default(true),includeRootCa: z.boolean().default(false),enableVersioning: z.boolean().default(true),+ postSyncCommand: PostSyncCommandSchema,certificateNameSchema: z.string().trim()diff --git a/backend/src/services/pki-sync/chef/chef-pki-sync-list-constants.ts b/backend/src/services/pki-sync/chef/chef-pki-sync-list-constants.tsindex 1142da2ac6..70c4eded1b 100644--- a/backend/src/services/pki-sync/chef/chef-pki-sync-list-constants.ts+++ b/backend/src/services/pki-sync/chef/chef-pki-sync-list-constants.ts@@ -6,5 +6,6 @@ export const CHEF_PKI_SYNC_LIST_OPTION = {connection: AppConnection.Chef,destination: PkiSync.Chef,canImportCertificates: false,- canRemoveCertificates: true+ canRemoveCertificates: true,+ canRunPostSyncCommand: false} as const;diff --git a/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-constants.ts b/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-constants.tsindex bd99677d7d..fc31e4e1bf 100644--- a/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-constants.ts@@ -44,6 +44,7 @@ export const CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION = {destination: PkiSync.CloudflareCustomCertificate,canImportCertificates: false,canRemoveCertificates: true,+ canRunPostSyncCommand: false,defaultCertificateNameSchema: "Infisical-{{certificateId}}",forbiddenCharacters: CLOUDFLARE_CUSTOM_CERTIFICATE_NAMING.FORBIDDEN_CHARACTERS,allowedCharacterPattern: CLOUDFLARE_CUSTOM_CERTIFICATE_NAMING.ALLOWED_CHARACTER_PATTERN,diff --git a/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts b/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.tsindex 2616c17cd1..4bf7b7a748 100644--- a/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts@@ -4,7 +4,7 @@ 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 { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";+import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";import { CLOUDFLARE_CUSTOM_CERTIFICATE_NAMING } from "./cloudflare-custom-certificate-pki-sync-constants";@@ -15,6 +15,7 @@ export const CloudflareCustomCertificatePkiSyncConfigSchema = z.object({// API-facing schema - only exposes user-configurable optionsexport const CloudflareCustomCertificatePkiSyncOptionsSchema = z.object({canRemoveCertificates: z.boolean().default(true),+ postSyncCommand: PostSyncCommandSchema,certificateNameSchema: z.string().trim()diff --git a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-constants.ts b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-constants.tsindex e49d43f8b2..34c45252ff 100644--- a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-constants.ts@@ -30,6 +30,7 @@ export const F5_BIG_IP_PKI_SYNC_LIST_OPTION = {destination: PkiSync.F5BigIp,canImportCertificates: false,canRemoveCertificates: true,+ canRunPostSyncCommand: false,defaultCertificateNameSchema: "Infisical-{{certificateId}}",forbiddenCharacters: F5_BIG_IP_NAMING.FORBIDDEN_CHARACTERS,allowedCharacterPattern: F5_BIG_IP_NAMING.ALLOWED_CHARACTER_PATTERN,diff --git a/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-constants.ts b/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-constants.tsindex 5e4d07de9e..08dba79817 100644--- a/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-constants.ts@@ -23,6 +23,7 @@ export const KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION = {destination: PkiSync.KempLoadMaster,canImportCertificates: false,canRemoveCertificates: true,+ canRunPostSyncCommand: false,defaultCertificateNameSchema: "Infisical-{{certificateId}}",forbiddenCharacters: KEMP_LOADMASTER_NAMING.FORBIDDEN_CHARACTERS,allowedCharacterPattern: KEMP_LOADMASTER_NAMING.ALLOWED_CHARACTER_PATTERN,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.tsindex d603aac676..042dbf7b25 100644--- 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.ts@@ -22,6 +22,7 @@ export const LINUX_SERVER_PKI_SYNC_LIST_OPTION = {destination: PkiSync.LinuxServer,canImportCertificates: false,canRemoveCertificates: true,+ canRunPostSyncCommand: true,defaultCertificateNameSchema: "{{commonName}}",forbiddenCharacters: LINUX_SERVER_NAMING.FORBIDDEN_CHARACTERS,allowedCharacterPattern: LINUX_SERVER_NAMING.ALLOWED_CHARACTER_PATTERN,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.tsindex 39939883ea..dcc75f4b43 100644--- 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.ts@@ -10,13 +10,21 @@ import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2import { 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 { executeSshCommandViaGateway, 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 { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-schemas";import { PkiSyncError } from "../pki-sync-errors";import { exportCertificateForSync, PemCertificateExtension, PkiSyncExportFormat } from "../pki-sync-export-fns";+import {+ buildPostSyncCommandPlan,+ POST_SYNC_COMMAND_TIMEOUT_MS,+ renderPostSyncCommand,+ runPostSyncCommand,+ toPosixShellLiteral,+ TPostSyncCommandPlan+} from "../pki-sync-post-sync-command-fns";import { TCertificateMap, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "../pki-sync-types";import { TLinuxServerPkiSyncConfig } from "./linux-server-pki-sync-types";@@ -40,6 +48,7 @@ type TLinuxServerSyncOptions = {privateKeyFileMode?: string;owner?: string;group?: string;+ postSyncCommand?: string;};const buildSshConfig = (pkiSync: TPkiSyncWithCredentials): TSshConnectionConfig => {@@ -83,9 +92,6 @@ const parseFileMode = (mode: string | undefined, fallback: number): number => {return Number.isNaN(parsed) ? fallback : parsed;};-// Escapes a value for a POSIX single-quoted shell literal so a path is safe to embed in a command.-const singleQuote = (value: string): string => `'${value.replace(/'/g, "'\\''")}'`;-const applyOwnership = (client: Client,owner: string | undefined,@@ -98,7 +104,7 @@ const applyOwnership = (return;}const spec = `${owner ?? ""}${group ? `:${group}` : ""}`;- const target = singleQuote(filePath);+ const target = toPosixShellLiteral(filePath);const command = `chown ${spec} -- ${target} 2>/dev/null || sudo -n chown ${spec} -- ${target}`;client.exec(command, (err, stream) => {if (err) {@@ -219,6 +225,27 @@ const reconcileLinuxServerRemovals = async (args: {return { removed, failedRemovals };};+const runLinuxServerPostSyncCommand = ({+ syncId,+ plan,+ sshConfig,+ gatewayServices+}: {+ syncId: string;+ plan: TPostSyncCommandPlan;+ sshConfig: TSshConnectionConfig;+ gatewayServices: Pick<TLinuxServerPkiSyncFactoryDeps, "gatewayV2Service" | "gatewayPoolService">;+}) =>+ runPostSyncCommand({+ syncId,+ secretsToRedact: [plan.context.pkcs12Password],+ execute: () =>+ executeSshCommandViaGateway(sshConfig, gatewayServices, {+ command: renderPostSyncCommand(plan.command, plan.context, toPosixShellLiteral),+ timeoutMs: POST_SYNC_COMMAND_TIMEOUT_MS+ })+ });+export const linuxServerPkiSyncFactory = ({certificateSyncDAL,gatewayV2Service,@@ -240,10 +267,10 @@ export const linuxServerPkiSyncFactory = ({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.+ // Paths confirmed on the host this run. Keeps the removal pass from deleting a file a renewal+ // just rewrote under the same name, and tells the post-sync command what landed.const deliveredPaths = new Set<string>();+ const deliveredCertificates: Array<{ path: string; commonName?: string }> = [];let uploaded = 0;let removed = 0;@@ -307,8 +334,8 @@ export const linuxServerPkiSyncFactory = ({deliveredPaths.add(filePath);}- // Record the delivered paths so removal and re-sync act on exactly what was written.const primaryPath = writtenPaths[0];+ deliveredCertificates.push({ path: primaryPath, commonName: certData.commonName ?? undefined });if (typeof certificateId === "string") {let record = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);if (!record) {@@ -334,7 +361,7 @@ export const linuxServerPkiSyncFactory = ({}// Delete files for certificates no longer active and drop their tracking rows.- if (canRemoveCertificates) {+ if (canRemoveCertificates && failedUploads.length === 0) {const reconciliation = await reconcileLinuxServerRemovals({sftp,pkiSync,@@ -344,14 +371,35 @@ export const linuxServerPkiSyncFactory = ({});removed += reconciliation.removed;failedRemovals.push(...reconciliation.failedRemovals);+ } else if (canRemoveCertificates) {+ logger.info(+ `Linux Server PKI sync [syncId=${pkiSync.id}]: skipped certificate removal because ${failedUploads.length} certificate(s) failed to deliver`+ );}});+ const postSyncCommandPlan = buildPostSyncCommandPlan({+ command: options.postSyncCommand,+ destinationDirectory: config.destinationPath,+ deliveredPaths,+ deliveredCertificates,+ pkcs12Password: format === PkiSyncExportFormat.Pkcs12 ? exportPassword : undefined+ });+ const postSyncCommand = postSyncCommandPlan+ ? await runLinuxServerPostSyncCommand({+ syncId: pkiSync.id,+ plan: postSyncCommandPlan,+ sshConfig,+ gatewayServices: { gatewayV2Service, gatewayPoolService }+ })+ : undefined;+return {uploaded,removed: removed > 0 ? removed : undefined,failedRemovals: failedRemovals.length > 0 ? failedRemovals.length : undefined,skipped: skippedCertificates.length,+ postSyncCommand,details: {failedUploads: failedUploads.length > 0 ? failedUploads : undefined,failedRemovals: failedRemovals.length > 0 ? failedRemovals : undefined,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.tsindex 62f3e06f4f..5fe4ef7800 100644--- 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.ts@@ -57,3 +57,31 @@ describe("Linux Server destinationPath validation", () => {expect(parsePath("")).toBe(false);});});++describe("Linux Server postSyncCommand validation", () => {+ const parseCommand = (postSyncCommand: string) =>+ LinuxServerPkiSyncOptionsSchema.safeParse({ certificateNameSchema: "server", postSyncCommand });++ test("accepts a single-line and a multi-line command", () => {+ expect(parseCommand("sudo systemctl reload nginx").success).toBe(true);+ expect(parseCommand("sudo systemctl reload nginx\nsudo systemctl reload haproxy").success).toBe(true);+ });++ test("accepts shell metacharacters, since the command is arbitrary shell by design", () => {+ expect(parseCommand("test -f {{certificatePath}} && sudo systemctl reload nginx || exit 1").success).toBe(true);+ });++ test("treats an empty or whitespace-only command as no command", () => {+ expect(parseCommand("").data?.postSyncCommand).toBeUndefined();+ expect(parseCommand(" ").data?.postSyncCommand).toBeUndefined();+ });++ test("rejects a command beyond the length limit", () => {+ expect(parseCommand("a".repeat(2048)).success).toBe(true);+ expect(parseCommand("a".repeat(2049)).success).toBe(false);+ });++ test("is optional", () => {+ expect(LinuxServerPkiSyncOptionsSchema.safeParse({ certificateNameSchema: "server" }).success).toBe(true);+ });+});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.tsindex 621190fa98..660f81647a 100644--- 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.ts@@ -5,7 +5,7 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enumsimport { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";import { PemCertificateExtension, PkiSyncExportFormat } from "@app/services/pki-sync/pki-sync-export-fns";-import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";+import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";import { LINUX_SERVER_NAMING } from "./linux-server-pki-sync-constants";@@ -56,6 +56,7 @@ export const LinuxServerPkiSyncOptionsSchema = z.object({.max(32).refine((v) => POSIX_NAME.test(v), { message: "Group must be a valid Linux group name" }).optional(),+ postSyncCommand: PostSyncCommandSchema,certificateNameSchema: z.string().trim()diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-constants.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-constants.tsindex 774902c925..0eefdf49c0 100644--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-constants.ts@@ -22,6 +22,7 @@ export const NETSCALER_PKI_SYNC_LIST_OPTION = {destination: PkiSync.NetScaler,canImportCertificates: false,canRemoveCertificates: true,+ canRunPostSyncCommand: false,defaultCertificateNameSchema: "Infisical-{{certificateId}}",forbiddenCharacters: NETSCALER_NAMING.FORBIDDEN_CHARACTERS,allowedCharacterPattern: NETSCALER_NAMING.ALLOWED_CHARACTER_PATTERN,diff --git a/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-constants.ts b/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-constants.tsindex aca2dc69a2..f668563a7d 100644--- a/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-constants.ts@@ -7,5 +7,6 @@ export const NUTANIX_PRISM_CENTRAL_PKI_SYNC_LIST_OPTION = {destination: PkiSync.NutanixPrismCentral,canImportCertificates: false,canRemoveCertificates: false,+ canRunPostSyncCommand: false,maxCertificates: 1} as const;diff --git a/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-schemas.ts b/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-schemas.tsindex 6af3c2c8d8..3a045b470f 100644--- a/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-schemas.ts@@ -3,7 +3,7 @@ import { z } from "zod";import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";-import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";+import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";export const NutanixPrismCentralPkiSyncConfigSchema = z.object({clusterId: z.string().min(1, "Cluster ID is required"),@@ -12,7 +12,8 @@ export const NutanixPrismCentralPkiSyncConfigSchema = z.object({export const NutanixPrismCentralPkiSyncOptionsSchema = z.object({canImportCertificates: z.literal(false).default(false),- canRemoveCertificates: z.literal(false).default(false)+ canRemoveCertificates: z.literal(false).default(false),+ postSyncCommand: PostSyncCommandSchema});export const NutanixPrismCentralPkiSyncSchema = PkiSyncSchema.extend({diff --git a/backend/src/services/pki-sync/pki-sync-fns.test.ts b/backend/src/services/pki-sync/pki-sync-fns.test.tsindex e2bc3fe0a0..1f7fed1ae4 100644--- a/backend/src/services/pki-sync/pki-sync-fns.test.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.test.ts@@ -1,4 +1,5 @@-import { matchesCertificateNameSchema } from "./pki-sync-fns";+import { PkiSync } from "./pki-sync-enums";+import { getPkiSyncProviderCapabilities, matchesCertificateNameSchema } from "./pki-sync-fns";// A dash-stripped UUID (what {{certificateId}}, {{profileId}}, {{applicationId}} resolve to).const HEX = "550e8400e29b41d4a716446655440000";@@ -90,3 +91,26 @@ describe("matchesCertificateNameSchema (managed-certificate detection for cleanuexpect(matchesCertificateNameSchema(`weird/name-${HEX}`, schema)).toBe(false);});});++describe("getPkiSyncProviderCapabilities: canRunPostSyncCommand", () => {+ // The service rejects a command on this, and the UI reads it from the API to decide whether the+ // Post-Sync Command step exists, so a destination added without it goes wrong in both places.+ const SHELL_DESTINATIONS = [PkiSync.LinuxServer, PkiSync.WindowsServer];++ test.each(SHELL_DESTINATIONS)("%s can run one", (destination) => {+ expect(getPkiSyncProviderCapabilities(destination).canRunPostSyncCommand).toBe(true);+ });++ test.each(Object.values(PkiSync).filter((destination) => !SHELL_DESTINATIONS.includes(destination)))(+ "%s cannot run one",+ (destination) => {+ expect(getPkiSyncProviderCapabilities(destination).canRunPostSyncCommand).toBe(false);+ }+ );++ test("every destination states the capability, so a new one cannot leave it undefined", () => {+ Object.values(PkiSync).forEach((destination) => {+ expect(typeof getPkiSyncProviderCapabilities(destination).canRunPostSyncCommand).toBe("boolean");+ });+ });+});diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.tsindex 99b496f221..330b7bf058 100644--- a/backend/src/services/pki-sync/pki-sync-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.ts@@ -87,7 +87,8 @@ export const getPkiSyncProviderCapabilities = (destination: PkiSync) => {return {canImportCertificates: providerOption.canImportCertificates,- canRemoveCertificates: providerOption.canRemoveCertificates+ canRemoveCertificates: providerOption.canRemoveCertificates,+ canRunPostSyncCommand: providerOption.canRunPostSyncCommand};};@@ -103,6 +104,11 @@ export const matchesSchema = <T extends ZodSchema>(schema: T, data: unknown): dareturn schema.safeParse(data).success;};+const MAX_SYNC_MESSAGE_LENGTH = 255;++export const truncateSyncMessage = (message: string): string =>+ message.length > MAX_SYNC_MESSAGE_LENGTH ? `${message.slice(0, MAX_SYNC_MESSAGE_LENGTH - 3)}...` : message;+export const parsePkiSyncErrorMessage = (error: unknown): string => {if (error instanceof Error) {return error.message;diff --git a/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.test.ts b/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.test.tsnew file mode 100644index 0000000000..cbe92c2a65--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.test.ts@@ -0,0 +1,355 @@+import { describe, expect, test, vi } from "vitest";++import { PkiSyncStatus } from "./pki-sync-enums";+import {+ buildPostSyncCommandFailureMessage,+ buildPostSyncCommandPlan,+ findSingleCertificatePostSyncCommandVariables,+ PostSyncCommandVariable,+ renderPostSyncCommand,+ runPostSyncCommand,+ toPosixShellLiteral,+ toPowerShellLiteral,+ TPostSyncCommandContext+} from "./pki-sync-post-sync-command-fns";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }+}));++const context: TPostSyncCommandContext = {+ certificatePath: "/etc/ssl/certs/app.example.com.pem",+ certificateDirectory: "/etc/ssl/certs",+ certificateFiles: ["/etc/ssl/certs/app.example.com.pem", "/etc/ssl/certs/app.example.com.key"],+ commonName: "app.example.com"+};++describe("buildPostSyncCommandPlan", () => {+ const baseArgs = {+ command: "systemctl reload nginx",+ destinationDirectory: "/etc/ssl/certs",+ deliveredPaths: new Set(["/etc/ssl/certs/app.pem"]),+ deliveredCertificates: [{ path: "/etc/ssl/certs/app.pem", commonName: "app.example.com" }]+ };++ const twoCertificates = [+ { path: "/etc/ssl/certs/a.pem", commonName: "a.example.com" },+ { path: "/etc/ssl/certs/b.pem", commonName: "b.example.com" }+ ];++ test("returns a plan when a command is configured and files were delivered", () => {+ const plan = buildPostSyncCommandPlan(baseArgs);++ expect(plan?.command).toBe("systemctl reload nginx");+ expect(plan?.context.certificatePath).toBe("/etc/ssl/certs/app.pem");+ expect(plan?.context.certificateFiles).toEqual(["/etc/ssl/certs/app.pem"]);+ });++ test("returns undefined when no command is configured", () => {+ expect(buildPostSyncCommandPlan({ ...baseArgs, command: undefined })).toBeUndefined();+ });++ test("returns undefined when the run delivered nothing", () => {+ expect(buildPostSyncCommandPlan({ ...baseArgs, deliveredCertificates: [] })).toBeUndefined();+ });++ test("rejects a single-certificate placeholder when the run delivered several certificates", () => {+ expect(() =>+ buildPostSyncCommandPlan({+ ...baseArgs,+ command: "cp {{certificatePath}} /etc/nginx/live.pem",+ deliveredCertificates: twoCertificates+ })+ ).toThrow(/\{\{certificatePath\}\}.*delivered 2 certificates/);+ });++ test("allows run-wide placeholders for any number of certificates", () => {+ const plan = buildPostSyncCommandPlan({+ ...baseArgs,+ command: "echo {{certificateFiles}} > {{certificateDirectory}}/manifest",+ deliveredCertificates: twoCertificates+ });++ expect(plan?.command).toBe("echo {{certificateFiles}} > {{certificateDirectory}}/manifest");+ });++ test("leaves the single-certificate values unset for a multi-certificate run", () => {+ const plan = buildPostSyncCommandPlan({+ ...baseArgs,+ command: "echo {{certificateFiles}}",+ deliveredCertificates: twoCertificates+ });++ // Neither delivered certificate is promoted to stand for the run.+ expect(plan?.context.certificatePath).toBeUndefined();+ expect(plan?.context.commonName).toBeUndefined();+ });+});++describe("findSingleCertificatePostSyncCommandVariables", () => {+ test("finds the placeholders that name one certificate", () => {+ expect(findSingleCertificatePostSyncCommandVariables("cp {{certificatePath}} /tmp/{{commonName}}")).toEqual([+ PostSyncCommandVariable.CertificatePath,+ PostSyncCommandVariable.CommonName+ ]);+ });++ test("ignores placeholders that describe the whole run", () => {+ expect(findSingleCertificatePostSyncCommandVariables("echo {{certificateFiles}} {{certificateDirectory}}")).toEqual(+ []+ );+ });++ test("matches a placeholder regardless of its internal spacing", () => {+ expect(findSingleCertificatePostSyncCommandVariables("echo {{ commonName }}")).toEqual([+ PostSyncCommandVariable.CommonName+ ]);+ });++ test("returns none for an empty command, or text that is not a placeholder", () => {+ expect(findSingleCertificatePostSyncCommandVariables()).toEqual([]);+ expect(findSingleCertificatePostSyncCommandVariables("echo {{#if")).toEqual([]);+ expect(findSingleCertificatePostSyncCommandVariables("jq {{.commonName}}")).toEqual([]);+ });+});++describe("renderPostSyncCommand", () => {+ test("substitutes each placeholder with the run's value", () => {+ const rendered = renderPostSyncCommand(+ "cp {{certificatePath}} {{certificateDirectory}}/live.pem",+ context,+ toPosixShellLiteral+ );++ expect(rendered).toBe("cp '/etc/ssl/certs/app.example.com.pem' '/etc/ssl/certs'/live.pem");+ });++ test("renders the common name and the newline-joined file list", () => {+ expect(renderPostSyncCommand("echo {{commonName}}", context, toPosixShellLiteral)).toBe("echo 'app.example.com'");+ expect(renderPostSyncCommand("echo {{certificateFiles}}", context, toPosixShellLiteral)).toBe(+ `echo '${context.certificateFiles.join("\n")}'`+ );+ });++ test("renders an absent optional variable as an empty literal rather than the placeholder", () => {+ expect(renderPostSyncCommand("echo {{pkcs12Password}}", context, toPosixShellLiteral)).toBe("echo ''");+ });++ test("quotes a value that would otherwise break out of the command", () => {+ const malicious: TPostSyncCommandContext = {+ ...context,+ commonName: "app.example.com'; rm -rf / #"+ };++ const rendered = renderPostSyncCommand("echo {{commonName}}", malicious, toPosixShellLiteral);++ // The injected quote is escaped, so the whole value stays a single argument to echo.+ expect(rendered).toBe(`echo 'app.example.com'\\''; rm -rf / #'`);+ expect(rendered.startsWith("echo '")).toBe(true);+ });++ // A common name is attacker-influenced (the import path derives it from the parsed PEM, not from a+ // validated request field), and substitution is what puts it in front of the target's shell. Each+ // payload below is a different way of ending a single-quoted literal early; a quote is the only+ // character a POSIX shell treats specially inside one, so escaping it keeps every payload inert.+ test.each([+ ["quote break-out", "app.example.com'; touch pwned; #"],+ ["command substitution", "app$(touch pwned).example.com"],+ ["backtick substitution", "app`touch pwned`.example.com"],+ ["command chaining", "app.example.com && touch pwned"],+ ["newline then a new statement", "app.example.com\ntouch pwned"],+ ["semicolon then a new statement", "app.example.com; touch pwned"],+ ["pipe to a shell", "app.example.com | sh -c 'touch pwned'"],+ // Deliberately a plain string: these exact characters are what has to reach the shell unexpanded.+ // eslint-disable-next-line no-template-curly-in-string+ ["variable expansion", "app${HOME}.example.com"]+ ])("a hostile common name (%s) stays inside one quoted literal", (_name, commonName) => {+ const rendered = renderPostSyncCommand("echo {{commonName}}", { ...context, commonName }, toPosixShellLiteral);++ // Rebuilding the literal from the value is the whole contract: any quote in it is escaped, and+ // nothing else can terminate the literal, so the shell sees exactly one argument.+ expect(rendered).toBe(`echo '${commonName.split("'").join(`'\\''`)}'`);+ });++ test("doubles quotes for PowerShell instead of backslash-escaping", () => {+ const malicious: TPostSyncCommandContext = { ...context, commonName: "a'; Remove-Item C:\\ #" };++ expect(renderPostSyncCommand("Write-Output {{commonName}}", malicious, toPowerShellLiteral)).toBe(+ "Write-Output 'a''; Remove-Item C:\\ #'"+ );+ });+});++describe("renderPostSyncCommand: text that is not a documented variable", () => {+ const render = (command: string) => renderPostSyncCommand(command, context, toPosixShellLiteral);++ test("an unknown placeholder is left exactly as the operator wrote it", () => {+ // Not blanked and not rejected: a typo shows up in the command the host runs, where the operator+ // can see it, and a brace that was never meant for us survives.+ expect(render("echo {{certPath}}")).toBe("echo {{certPath}}");+ });++ test.each([+ ["braces meant for another tool", "jq {{.name}} out.json", "jq {{.name}} out.json"],+ ["a helm value", "helm upgrade app --set x={{ .Values.x }}", "helm upgrade app --set x={{ .Values.x }}"],+ ["a block helper", '{{#with "s"}}{{constructor}}{{/with}}', '{{#with "s"}}{{constructor}}{{/with}}'],+ ["a subexpression", 'echo {{lookup (lookup this "a") "b"}}', 'echo {{lookup (lookup this "a") "b"}}'],+ ["a parent path", "echo {{../commonName}}", "echo {{../commonName}}"],+ ["a partial", "{{> somePartial}}", "{{> somePartial}}"],+ ["prototype access", "echo {{constructor.constructor}}", "echo {{constructor.constructor}}"]+ ])("%s is inert text, neither evaluated nor rejected", (_name, command, expected) => {+ expect(render(command)).toBe(expected);+ });++ test("a known variable inside unknown braces is still substituted", () => {+ // {{{x}}} is not special here, so the inner placeholder resolves and the extra braces remain.+ expect(render("echo {{{commonName}}}")).toBe("echo {'app.example.com'}");+ });++ test("a command with no placeholders is passed through untouched", () => {+ expect(render("systemctl reload nginx && echo done")).toBe("systemctl reload nginx && echo done");+ });+});++describe("runPostSyncCommand", () => {+ test("reports success on exit code 0 and captures both streams", async () => {+ const result = await runPostSyncCommand({+ syncId: "sync-id",+ execute: async () => ({ stdout: "reloaded", stderr: "a warning", exitCode: 0 })+ });++ expect(result.status).toBe(PkiSyncStatus.Succeeded);+ expect(result.exitCode).toBe(0);+ expect(result.output).toBe("reloaded\na warning");+ });++ test("reports failure on a non-zero exit code without throwing", async () => {+ const result = await runPostSyncCommand({+ syncId: "sync-id",+ execute: async () => ({ stdout: "", stderr: "Unit nginx.service not found", exitCode: 5 })+ });++ expect(result.status).toBe(PkiSyncStatus.Failed);+ expect(result.exitCode).toBe(5);+ expect(result.error).toBe("Command exited with code 5");+ });++ test("reports failure when the transport throws", async () => {+ const result = await runPostSyncCommand({+ syncId: "sync-id",+ execute: async () => {+ throw new Error("command timed out after 30s");+ }+ });++ expect(result.status).toBe(PkiSyncStatus.Failed);+ expect(result.exitCode).toBeUndefined();+ expect(result.error).toBe("command timed out after 30s");+ });++ test("redacts the export password from captured output and errors", async () => {+ const result = await runPostSyncCommand({+ syncId: "sync-id",+ secretsToRedact: ["s3cret"],+ execute: async () => ({ stdout: "password is s3cret", stderr: "s3cret again", exitCode: 1 })+ });++ expect(result.output).not.toContain("s3cret");+ expect(result.output).toBe("password is [REDACTED]\n[REDACTED] again");+ });++ test("truncates output that exceeds the capture cap", async () => {+ const result = await runPostSyncCommand({+ syncId: "sync-id",+ execute: async () => ({ stdout: "x".repeat(5000), stderr: "", exitCode: 0 })+ });++ expect(result.output).toHaveLength(1000 + "... (truncated)".length);+ expect(result.output?.endsWith("... (truncated)")).toBe(true);+ });++ test("returns no output when the command was silent", async () => {+ const result = await runPostSyncCommand({+ syncId: "sync-id",+ execute: async () => ({ stdout: " ", stderr: "", exitCode: 0 })+ });++ expect(result.output).toBeUndefined();+ });+});++describe("buildPostSyncCommandFailureMessage", () => {+ test("always reports the exit code and quotes stderr over stdout", () => {+ // A command that prints progress before failing must not be summarised by its progress line.+ const message = buildPostSyncCommandFailureMessage({+ status: PkiSyncStatus.Failed,+ exitCode: 1,+ durationMs: 10,+ output: "one\nCannot find any service with service name 'NoSuchSvc'.",+ failureDetail: "Cannot find any service with service name 'NoSuchSvc'.",+ error: "Command exited with code 1"+ });++ expect(message).toBe("Post-sync command failed (exit 1): Cannot find any service with service name 'NoSuchSvc'.");+ });++ test("falls back to stdout when the command wrote nothing to stderr", () => {+ const message = buildPostSyncCommandFailureMessage({+ status: PkiSyncStatus.Failed,+ exitCode: 2,+ durationMs: 10,+ output: "\n Unit nginx.service not found\nsecond line",+ error: "Command exited with code 2"+ });++ expect(message).toBe("Post-sync command failed (exit 2): Unit nginx.service not found");+ });++ test("still reports the exit code when the command produced no output at all", () => {+ const message = buildPostSyncCommandFailureMessage({+ status: PkiSyncStatus.Failed,+ exitCode: 42,+ durationMs: 10,+ error: "Command exited with code 42"+ });++ expect(message).toBe("Post-sync command failed (exit 42): Command exited with code 42");+ });++ test("falls back to the error when the command never ran, so there is no exit code", () => {+ const message = buildPostSyncCommandFailureMessage({+ status: PkiSyncStatus.Failed,+ durationMs: 10,+ error: "Running a command on the host requires the SSH connection to use a gateway."+ });++ expect(message).toBe(+ "Post-sync command failed: Running a command on the host requires the SSH connection to use a gateway."+ );+ });++ test("truncates a long detail so it fits the sync message column", () => {+ const message = buildPostSyncCommandFailureMessage({+ status: PkiSyncStatus.Failed,+ exitCode: 3,+ durationMs: 10,+ failureDetail: "x".repeat(400),+ error: "Command exited with code 3"+ });++ expect(message.length).toBeLessThan(200);+ expect(message).toContain("(exit 3)");+ expect(message).toContain("... (truncated)");+ });++ test("a chatty command cannot bloat the stored result, which is written to the audit log", async () => {+ const noise = "N".repeat(500_000);+ const result = await runPostSyncCommand({+ syncId: "sync-id",+ execute: async () => ({ stdout: noise, stderr: noise, exitCode: 3 })+ });++ expect(result.output?.length).toBeLessThan(1100);+ expect(result.failureDetail?.length).toBeLessThanOrEqual(120);+ });+});diff --git a/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.ts b/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.tsnew file mode 100644index 0000000000..29daba1657--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.ts@@ -0,0 +1,216 @@+import RE2 from "re2";++import { logger } from "@app/lib/logger";++import { PkiSyncStatus } from "./pki-sync-enums";+import { PkiSyncError } from "./pki-sync-errors";++export enum PostSyncCommandVariable {+ CertificatePath = "certificatePath",+ CertificateDirectory = "certificateDirectory",+ CertificateFiles = "certificateFiles",+ CommonName = "commonName",+ Pkcs12Password = "pkcs12Password"+}++// Matches a {{name}} placeholder.+const PLACEHOLDER_PATTERN = new RE2("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}", "g");++const isPostSyncCommandVariable = (name: string): name is PostSyncCommandVariable =>+ (Object.values(PostSyncCommandVariable) as string[]).includes(name);++const SINGLE_CERTIFICATE_VARIABLES: PostSyncCommandVariable[] = [+ PostSyncCommandVariable.CertificatePath,+ PostSyncCommandVariable.CommonName+];++export const formatPostSyncCommandVariables = (variables: PostSyncCommandVariable[]): string =>+ variables.map((variable) => `{{${variable}}}`).join(", ");++export const findSingleCertificatePostSyncCommandVariables = (command?: string): PostSyncCommandVariable[] => {+ if (!command) return [];++ const used = new Set<string>();+ command.replace(PLACEHOLDER_PATTERN, (match: string, name: string) => {+ used.add(name);+ return match;+ });++ return SINGLE_CERTIFICATE_VARIABLES.filter((variable) => used.has(variable));+};++export const POST_SYNC_COMMAND_MAX_LENGTH = 2048;++export const POST_SYNC_COMMAND_TIMEOUT_MS = 30_000;++const MAX_CAPTURED_OUTPUT_CHARS = 1000;++const MAX_FAILURE_DETAIL_CHARS = 120;++const REDACTED_PLACEHOLDER = "[REDACTED]";++export type TPostSyncCommandContext = {+ certificatePath?: string;+ commonName?: string;+ certificateDirectory: string;+ certificateFiles: string[];+ pkcs12Password?: string;+};++export type TPostSyncCommandResult = {+ status: PkiSyncStatus.Succeeded | PkiSyncStatus.Failed;+ exitCode?: number;+ durationMs: number;+ output?: string;+ failureDetail?: string;+ error?: string;+};++export type TPostSyncCommandExecutionResult = { stdout: string; stderr: string; exitCode: number };++export type TPostSyncCommandPlan = { command: string; context: TPostSyncCommandContext };++/**+ * Assembles what a post-sync command needs, or undefined when there is no command or the run+ * delivered nothing to activate.+ */+export const buildPostSyncCommandPlan = (args: {+ command?: string;+ destinationDirectory: string;+ deliveredPaths: Set<string>;+ deliveredCertificates: Array<{ path: string; commonName?: string }>;+ pkcs12Password?: string;+}): TPostSyncCommandPlan | undefined => {+ const { command, destinationDirectory, deliveredPaths, deliveredCertificates, pkcs12Password } = args;+ if (!command || deliveredCertificates.length === 0) return undefined;++ const singleCertificateVariables = findSingleCertificatePostSyncCommandVariables(command);+ if (deliveredCertificates.length > 1 && singleCertificateVariables.length > 0) {+ throw new PkiSyncError({+ message: `Post-sync command uses ${formatPostSyncCommandVariables(+ singleCertificateVariables+ )}. A placeholder that names one certificate cannot be resolved for a run that delivered ${+ deliveredCertificates.length+ } certificates. Unlink all but one certificate, or use {{certificateFiles}} instead.`,+ shouldRetry: false+ });+ }++ const onlyCertificate = deliveredCertificates.length === 1 ? deliveredCertificates[0] : undefined;++ return {+ command,+ context: {+ certificatePath: onlyCertificate?.path,+ commonName: onlyCertificate?.commonName,+ certificateDirectory: destinationDirectory,+ certificateFiles: Array.from(deliveredPaths),+ pkcs12Password+ }+ };+};++export const toPosixShellLiteral = (value: string): string => `'${value.split("'").join(`'\\''`)}'`;++export const toPowerShellLiteral = (value: string): string => `'${value.split("'").join("''")}'`;++/**+ * Renders the operator's template into the command that runs on the target.+ *+ * Each value is substituted as a quoted shell literal, so a common name carrying shell+ * metacharacters cannot break out and execute as code. The quoting is part of the substitution, so+ * the operator writes `{{certificatePath}}`, not `"{{certificatePath}}"`.+ *+ * Text that is not a documented variable is left as written, because other tools use the same braces+ * (helm, jq, Go templates). A plain scan rather than a template engine, so there is no helper,+ * subexpression or prototype path to evaluate.+ */+export const renderPostSyncCommand = (+ command: string,+ context: TPostSyncCommandContext,+ toShellLiteral: (value: string) => string+): string => {+ const values = new Map<PostSyncCommandVariable, string | undefined>([+ [PostSyncCommandVariable.CertificatePath, context.certificatePath],+ [PostSyncCommandVariable.CertificateDirectory, context.certificateDirectory],+ [PostSyncCommandVariable.CertificateFiles, context.certificateFiles.join("\n")],+ [PostSyncCommandVariable.CommonName, context.commonName],+ [PostSyncCommandVariable.Pkcs12Password, context.pkcs12Password]+ ]);++ return command.replace(PLACEHOLDER_PATTERN, (match: string, name: string) =>+ isPostSyncCommandVariable(name) ? toShellLiteral(values.get(name) ?? "") : match+ );+};++const redactSecrets = (text: string, secrets: Array<string | undefined>): string =>+ secrets.reduce<string>((acc, secret) => (secret ? acc.split(secret).join(REDACTED_PLACEHOLDER) : acc), text);++const truncate = (text: string, maxLength: number): string =>+ text.length > maxLength ? `${text.slice(0, maxLength)}... (truncated)` : text;++const firstNonEmptyLine = (text?: string): string | undefined =>+ text+ ?.split("\n")+ .map((line) => line.trim())+ .find(Boolean);++const captureOutput = (stdout: string, stderr: string): string | undefined => {+ const combined = [stdout.trim(), stderr.trim()].filter(Boolean).join("\n");+ return combined ? truncate(combined, MAX_CAPTURED_OUTPUT_CHARS) : undefined;+};++/**+ * Runs the command through the caller's transport. Every failure mode (non-zero exit, timeout,+ * unreachable gateway) returns a Failed result instead of throwing, so the caller can fail the sync+ * while keeping the per-certificate delivery statuses it already recorded.+ */+export const runPostSyncCommand = async (args: {+ syncId: string;+ execute: () => Promise<TPostSyncCommandExecutionResult>;+ secretsToRedact?: Array<string | undefined>;+}): Promise<TPostSyncCommandResult> => {+ const { syncId, execute, secretsToRedact = [] } = args;+ const startedAt = Date.now();+ const redact = (text: string) => redactSecrets(text, secretsToRedact);++ try {+ const { stdout, stderr, exitCode } = await execute();+ const durationMs = Date.now() - startedAt;+ const output = captureOutput(redact(stdout), redact(stderr));++ if (exitCode === 0) {+ logger.info(`PKI sync post-sync command succeeded [syncId=${syncId}] [durationMs=${durationMs}]`);+ return { status: PkiSyncStatus.Succeeded, exitCode, durationMs, output };+ }++ logger.warn(+ `PKI sync post-sync command failed [syncId=${syncId}] [exitCode=${exitCode}] [durationMs=${durationMs}]`+ );+ return {+ status: PkiSyncStatus.Failed,+ exitCode,+ durationMs,+ output,+ failureDetail: firstNonEmptyLine(redact(stderr))?.slice(0, MAX_FAILURE_DETAIL_CHARS),+ error: `Command exited with code ${exitCode}`+ };+ } catch (err) {+ const durationMs = Date.now() - startedAt;+ const error = redact((err as Error)?.message ?? "Unknown error");+ logger.warn(`PKI sync post-sync command could not run [syncId=${syncId}] [durationMs=${durationMs}]: ${error}`);+ return { status: PkiSyncStatus.Failed, durationMs, error };+ }+};++/**+ * A short, single-line reason for pki_syncs.lastSyncMessage. The full output stays in the audit log.+ */+export const buildPostSyncCommandFailureMessage = (result: TPostSyncCommandResult): string => {+ const detail = result.failureDetail ?? firstNonEmptyLine(result.output);+ const prefix =+ result.exitCode === undefined ? "Post-sync command failed" : `Post-sync command failed (exit ${result.exitCode})`;++ if (detail) return `${prefix}: ${truncate(detail, MAX_FAILURE_DETAIL_CHARS)}`;+ return result.error ? `${prefix}: ${truncate(result.error, MAX_FAILURE_DETAIL_CHARS)}` : prefix;+};diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.tsindex bd6710ca59..f18d018ab1 100644--- a/backend/src/services/pki-sync/pki-sync-queue.ts+++ b/backend/src/services/pki-sync/pki-sync-queue.ts@@ -40,7 +40,8 @@ import { compileCertificateNameSchema } from "./pki-sync-certificate-name-fns";import { TPkiSyncDALFactory } from "./pki-sync-dal";import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";import { PkiSyncError } from "./pki-sync-errors";-import { enterprisePkiSyncCheck, parsePkiSyncErrorMessage, PkiSyncFns } from "./pki-sync-fns";+import { enterprisePkiSyncCheck, parsePkiSyncErrorMessage, PkiSyncFns, truncateSyncMessage } from "./pki-sync-fns";+import { buildPostSyncCommandFailureMessage, TPostSyncCommandResult } from "./pki-sync-post-sync-command-fns";import {TCertificateMap,TPkiSyncImportCertificatesDTO,@@ -434,6 +435,7 @@ export const pkiSyncQueueFactory = ({let isSynced = false;let certSyncFailureCount = 0;let syncMessage: string | null = null;+ let postSyncCommandResult: TPostSyncCommandResult | undefined;let isFinalAttempt = job.attemptsStarted === job.opts.attempts;try {@@ -617,8 +619,16 @@ export const pkiSyncQueueFactory = ({}}- if (certSyncFailureCount > 0) {- syncMessage = `${certSyncFailureCount} certificate(s) failed to sync to the destination`;+ postSyncCommandResult = syncResult.postSyncCommand;+ const reasons = [+ certSyncFailureCount > 0 ? `${certSyncFailureCount} certificate(s) failed to sync to the destination` : null,+ postSyncCommandResult?.status === PkiSyncStatus.Failed+ ? buildPostSyncCommandFailureMessage(postSyncCommandResult)+ : null+ ].filter(Boolean);++ if (reasons.length > 0) {+ syncMessage = truncateSyncMessage(reasons.join(". "));}isSynced = true;@@ -649,7 +659,8 @@ export const pkiSyncQueueFactory = ({}} finally {const ranAt = new Date();- const fullySynced = isSynced && certSyncFailureCount === 0;+ const postSyncCommandFailed = postSyncCommandResult?.status === PkiSyncStatus.Failed;+ const fullySynced = isSynced && certSyncFailureCount === 0 && !postSyncCommandFailed;const syncStatus = fullySynced ? PkiSyncStatus.Succeeded : PkiSyncStatus.Failed;await auditLogService.createAuditLog({@@ -666,7 +677,8 @@ export const pkiSyncQueueFactory = ({syncId: pkiSync.id,syncMessage,jobId: job.id!,- jobRanAt: ranAt+ jobRanAt: ranAt,+ postSyncCommand: postSyncCommandResult}}});diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.tsindex 44aeb76ae9..b1fdf3825d 100644--- a/backend/src/services/pki-sync/pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts@@ -3,13 +3,22 @@ import { z } from "zod";import { buildCertificateNameSchemaTestName } from "./pki-sync-certificate-name-fns";import { PkiSync } from "./pki-sync-enums";+import { POST_SYNC_COMMAND_MAX_LENGTH } from "./pki-sync-post-sync-command-fns";++export const PostSyncCommandSchema = z+ .string()+ .trim()+ .max(POST_SYNC_COMMAND_MAX_LENGTH, `Command must be at most ${POST_SYNC_COMMAND_MAX_LENGTH} characters`)+ .transform((command) => command || undefined)+ .optional();// Sync options shared by every destination. Destinations extend this with their own// certificateNameSchema and any extra options.export const BasePkiSyncOptionsSchema = z.object({canRemoveCertificates: z.boolean().default(true),includeRootCa: z.boolean().default(false),- preserveItemOnRenewal: z.boolean().default(true)+ preserveItemOnRenewal: z.boolean().default(true),+ postSyncCommand: PostSyncCommandSchema});// Builds a destination's certificateNameSchema validator. The compiled name must match thediff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex 2ed1b90530..9fb9ec387f 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -11,6 +11,7 @@ import {import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-utils";import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { OrgServiceActor } from "@app/lib/types";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -32,6 +33,10 @@ import {listPkiSyncOptions} from "./pki-sync-fns";import { PKI_SYNC_CONNECTION_MAP, PKI_SYNC_NAME_MAP } from "./pki-sync-maps";+import {+ findSingleCertificatePostSyncCommandVariables,+ formatPostSyncCommandVariables+} from "./pki-sync-post-sync-command-fns";import { TPkiSyncQueueFactory } from "./pki-sync-queue";import {TAddCertificatesToPkiSyncDTO,@@ -81,6 +86,7 @@ type TPkiSyncServiceFactoryDep = {| "clearSyncMetadataFlag">;pkiSubscriberDAL: Pick<TPkiSubscriberDALFactory, "findById">;+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;@@ -98,6 +104,7 @@ export const pkiSyncServiceFactory = ({certificateDAL,certificateSyncDAL,pkiSubscriberDAL,+ appConnectionDAL,appConnectionService,permissionService,licenseService,@@ -123,6 +130,32 @@ export const pkiSyncServiceFactory = ({return permission.can(action, ResourcePermissionSub.PkiSyncs);};+ /**+ * Rejects a command the sync could never run: a destination with no shell to open, or a connection+ * with no gateway to run it through. Checked at write time so the operator finds out while+ * configuring rather than on the next sync.+ */+ const $assertPostSyncCommandIsSupported = (+ destination: PkiSync,+ syncOptions: Record<string, unknown> | undefined,+ connection: { gatewayId?: string | null; gatewayPoolId?: string | null } | undefined+ ) => {+ if (!syncOptions?.postSyncCommand) return;++ if (!getPkiSyncProviderCapabilities(destination).canRunPostSyncCommand) {+ throw new BadRequestError({+ message: `A post-sync command cannot be set for ${PKI_SYNC_NAME_MAP[destination]} PKI sync destination`+ });+ }++ if (connection?.gatewayId || connection?.gatewayPoolId) return;++ throw new BadRequestError({+ message:+ "A post-sync command runs through a gateway. Configure the sync's App Connection to use a gateway, or clear the command."+ });+ };+const $assertSyncAction = async (projectAction: ProjectPermissionPkiSyncActions,resourceAction: ResourcePermissionPkiSyncActions,@@ -215,17 +248,30 @@ export const pkiSyncServiceFactory = ({}};- const assertSchemaAllowsCertificateCount = (+ const assertSyncOptionsAllowCertificateCount = (syncOptions: Record<string, unknown> | undefined,resultingCertificateCount: number) => {+ if (resultingCertificateCount <= 1) return;+const schema = syncOptions?.certificateNameSchema as string | undefined;- if (resultingCertificateCount > 1 && !certificateNameSchemaAllowsMultipleCertificates(schema)) {+ if (!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 singleCertificateVariables = findSingleCertificatePostSyncCommandVariables(+ syncOptions?.postSyncCommand as string | undefined+ );+ if (singleCertificateVariables.length > 0) {+ throw new BadRequestError({+ message: `This sync's post-sync command uses ${formatPostSyncCommandVariables(+ singleCertificateVariables+ )}. A placeholder that names one certificate can only be used on a sync with a single certificate linked. Use {{certificateFiles}} or {{certificateDirectory}} to write a command that covers every certificate in the run.`+ });+ }};const createPkiSync = async (@@ -276,7 +322,7 @@ export const pkiSyncServiceFactory = ({const destinationApp = getDestinationAppType(destination);// Validates permission to connect and app is valid for sync destination- await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);+ const connection = await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);const providerCapabilities = getPkiSyncProviderCapabilities(destination);const resolvedSyncOptions = {@@ -284,10 +330,12 @@ export const pkiSyncServiceFactory = ({...syncOptions};+ $assertPostSyncCommandIsSupported(destination, resolvedSyncOptions, connection);+if (certificateIds.length > 0) {assertWithinCertificateLimit(destination, certificateIds.length);await validateCertificatesForSync(certificateIds, projectId, applicationId);- assertSchemaAllowsCertificateCount(resolvedSyncOptions, certificateIds.length);+ assertSyncOptionsAllowCertificateCount(resolvedSyncOptions, certificateIds.length);}const encryptedCredentials = credentials?.exportPassword@@ -403,9 +451,10 @@ export const pkiSyncServiceFactory = ({}}+ let effectiveConnection: { gatewayId?: string | null; gatewayPoolId?: string | null } | undefined;if (connectionId && connectionId !== pkiSync.connectionId) {const destinationApp = getDestinationAppType(pkiSync.destination);- await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);+ effectiveConnection = await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);}let resolvedSyncOptions = syncOptions;@@ -432,11 +481,19 @@ export const pkiSyncServiceFactory = ({const effectiveSyncOptions = (resolvedSyncOptions ?? pkiSync.syncOptions) as Record<string, unknown> | undefined;+ if (effectiveSyncOptions?.postSyncCommand) {+ $assertPostSyncCommandIsSupported(+ pkiSync.destination,+ effectiveSyncOptions,+ effectiveConnection ?? (await appConnectionDAL.findById(pkiSync.connectionId))+ );+ }+if (certificateIds !== undefined) {if (certificateIds.length > 0) {assertWithinCertificateLimit(pkiSync.destination, certificateIds.length);await validateCertificatesForSync(certificateIds, pkiSync.projectId, pkiSync.applicationId);- assertSchemaAllowsCertificateCount(effectiveSyncOptions, certificateIds.length);+ assertSyncOptionsAllowCertificateCount(effectiveSyncOptions, certificateIds.length);}await certificateSyncDAL.removeAllCertificatesFromSync(id);@@ -448,7 +505,7 @@ export const pkiSyncServiceFactory = ({}} else if (syncOptions) {const existingCount = (await certificateSyncDAL.findByPkiSyncId(id)).length;- assertSchemaAllowsCertificateCount(effectiveSyncOptions, existingCount);+ assertSyncOptionsAllowCertificateCount(effectiveSyncOptions, existingCount);}if (@@ -774,7 +831,7 @@ export const pkiSyncServiceFactory = ({await validateCertificatesForSync(certificateIds, pkiSync.projectId, pkiSync.applicationId);const existingCount = (await certificateSyncDAL.findByPkiSyncId(pkiSyncId)).length;- assertSchemaAllowsCertificateCount(+ assertSyncOptionsAllowCertificateCount(pkiSync.syncOptions as Record<string, unknown> | undefined,existingCount + certificateIds.length);diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.tsindex 151995bc50..f6615509e4 100644--- a/backend/src/services/pki-sync/pki-sync-types.ts+++ b/backend/src/services/pki-sync/pki-sync-types.ts@@ -8,6 +8,7 @@ import { ResourceMetadataDTO } from "@app/services/resource-metadata/resource-meimport { TPkiSyncDALFactory } from "./pki-sync-dal";import { PkiSync } from "./pki-sync-enums";+import { TPostSyncCommandResult } from "./pki-sync-post-sync-command-fns";export type TPkiSync = {id: string;@@ -98,6 +99,7 @@ export type TPkiSyncSyncResult = {removed?: number;failedRemovals?: number;skipped: number;+ postSyncCommand?: TPostSyncCommandResult;details?: {failedUploads?: Array<{ name: string; error: string }>;failedRemovals?: Array<{ name: string; error: string }>;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.tsindex 57bded597b..2562e390aa 100644--- 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.ts@@ -22,6 +22,7 @@ export const WINDOWS_SERVER_PKI_SYNC_LIST_OPTION = {destination: PkiSync.WindowsServer,canImportCertificates: false,canRemoveCertificates: true,+ canRunPostSyncCommand: true,defaultCertificateNameSchema: "{{commonName}}",forbiddenCharacters: WINDOWS_SERVER_NAMING.FORBIDDEN_CHARACTERS,allowedCharacterPattern: WINDOWS_SERVER_NAMING.ALLOWED_CHARACTER_PATTERN,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.tsindex c7d7062903..0112835984 100644--- 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.ts@@ -3,12 +3,21 @@ 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 { WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-rpc";+import { WinRmRpcEndpoint, WinRmRunCommandResult } from "@app/lib/gateway-v2/winrm-rpc";+import { logger } from "@app/lib/logger";import { executeWinRMGatewayOperation, TWinRMConnection, TWinRMCredentials } from "@app/services/app-connection/winrm";import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";import { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-schemas";import { exportCertificateForSync, PemCertificateExtension, PkiSyncExportFormat } from "../pki-sync-export-fns";+import {+ buildPostSyncCommandPlan,+ POST_SYNC_COMMAND_TIMEOUT_MS,+ renderPostSyncCommand,+ runPostSyncCommand,+ toPowerShellLiteral,+ TPostSyncCommandPlan+} from "../pki-sync-post-sync-command-fns";import { TCertificateMap, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "../pki-sync-types";import { TWindowsServerPkiSyncConfig } from "./windows-server-pki-sync-types";@@ -29,6 +38,7 @@ type TWindowsServerSyncOptions = {includePrivateKey?: boolean;canRemoveCertificates?: boolean;fileAccessRules?: Array<{ identity: string; access: string }>;+ postSyncCommand?: string;};const TRAILING_BACKSLASH = new RE2("\\\\+$");@@ -110,6 +120,36 @@ const reconcileWindowsServerRemovals = async (args: {return { removed, failedRemovals };};+const runWindowsServerPostSyncCommand = ({+ syncId,+ plan,+ target,+ gatewayDeps+}: {+ syncId: string;+ plan: TPostSyncCommandPlan;+ target: ReturnType<typeof buildWinRMTarget>;+ gatewayDeps: Parameters<typeof executeWinRMGatewayOperation>[1];+}) =>+ runPostSyncCommand({+ syncId,+ secretsToRedact: [plan.context.pkcs12Password],+ execute: async () => {+ const result = await executeWinRMGatewayOperation<WinRmRunCommandResult>(+ {+ ...target,+ endpoint: WinRmRpcEndpoint.RunCommand,+ params: {+ command: renderPostSyncCommand(plan.command, plan.context, toPowerShellLiteral),+ timeoutMs: POST_SYNC_COMMAND_TIMEOUT_MS+ }+ },+ gatewayDeps+ );+ return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };+ }+ });+export const windowsServerPkiSyncFactory = ({certificateSyncDAL,gatewayV2Service,@@ -131,10 +171,10 @@ export const windowsServerPkiSyncFactory = ({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.+ // Paths confirmed on the host this run. Keeps the removal pass from deleting a file a renewal+ // just rewrote under the same name, and tells the post-sync command what landed.const deliveredPaths = new Set<string>();+ const deliveredCertificates: Array<{ path: string; commonName?: string }> = [];const target = buildWinRMTarget(pkiSync);let uploaded = 0;let removed = 0;@@ -180,7 +220,6 @@ export const windowsServerPkiSyncFactory = ({const fullPath = joinWindowsPath(config.destinationPath, `${baseName}${file.suffix}`);files.push({ path: fullPath, contentBase64: file.content.toString("base64") });paths.push(fullPath);- deliveredPaths.add(fullPath);}await executeWinRMGatewayOperation(@@ -192,6 +231,8 @@ export const windowsServerPkiSyncFactory = ({gatewayDeps);+ paths.forEach((deliveredPath) => deliveredPaths.add(deliveredPath));+ deliveredCertificates.push({ path: paths[0], commonName: certData.commonName ?? undefined });if (typeof certificateId === "string") {let record = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);if (!record) {@@ -213,7 +254,7 @@ export const windowsServerPkiSyncFactory = ({}// Delete files for certificates no longer active and drop their tracking rows.- if (canRemoveCertificates) {+ if (canRemoveCertificates && failedUploads.length === 0) {const reconciliation = await reconcileWindowsServerRemovals({pkiSync,certificateMap,@@ -224,13 +265,34 @@ export const windowsServerPkiSyncFactory = ({});removed += reconciliation.removed;failedRemovals.push(...reconciliation.failedRemovals);+ } else if (canRemoveCertificates) {+ logger.info(+ `Windows Server PKI sync [syncId=${pkiSync.id}]: skipped certificate removal because ${failedUploads.length} certificate(s) failed to deliver`+ );}+ const postSyncCommandPlan = buildPostSyncCommandPlan({+ command: options.postSyncCommand,+ destinationDirectory: config.destinationPath,+ deliveredPaths,+ deliveredCertificates,+ pkcs12Password: format === PkiSyncExportFormat.Pkcs12 ? exportPassword : undefined+ });+ const postSyncCommand = postSyncCommandPlan+ ? await runWindowsServerPostSyncCommand({+ syncId: pkiSync.id,+ plan: postSyncCommandPlan,+ target,+ gatewayDeps+ })+ : undefined;+return {uploaded,removed: removed > 0 ? removed : undefined,failedRemovals: failedRemovals.length > 0 ? failedRemovals.length : undefined,skipped: skippedCertificates.length,+ postSyncCommand,details: {failedUploads: failedUploads.length > 0 ? failedUploads : undefined,failedRemovals: failedRemovals.length > 0 ? failedRemovals : undefined,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.tsindex 10e51e67fb..893a5a568c 100644--- 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.ts@@ -58,3 +58,27 @@ describe("Windows Server destinationPath validation", () => {expect(parsePath("")).toBe(false);});});++describe("Windows Server postSyncCommand validation", () => {+ const parseCommand = (postSyncCommand: string) =>+ WindowsServerPkiSyncOptionsSchema.safeParse({ certificateNameSchema: "server", postSyncCommand });++ test("accepts a single-line and a multi-line PowerShell command", () => {+ expect(parseCommand('Restart-Service -Name "W3SVC"').success).toBe(true);+ expect(parseCommand("Import-PfxCertificate -FilePath {{certificatePath}}\niisreset").success).toBe(true);+ });++ test("treats an empty or whitespace-only command as no command", () => {+ expect(parseCommand("").data?.postSyncCommand).toBeUndefined();+ expect(parseCommand(" ").data?.postSyncCommand).toBeUndefined();+ });++ test("rejects a command beyond the length limit", () => {+ expect(parseCommand("a".repeat(2048)).success).toBe(true);+ expect(parseCommand("a".repeat(2049)).success).toBe(false);+ });++ test("is optional", () => {+ expect(WindowsServerPkiSyncOptionsSchema.safeParse({ certificateNameSchema: "server" }).success).toBe(true);+ });+});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.tsindex 4afc2e23c0..8bf98c29fd 100644--- 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.ts@@ -5,7 +5,7 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enumsimport { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";import { PemCertificateExtension, PkiSyncExportFormat } from "@app/services/pki-sync/pki-sync-export-fns";-import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";+import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";import { WINDOWS_SERVER_NAMING } from "./windows-server-pki-sync-constants";@@ -75,6 +75,7 @@ export const WindowsServerPkiSyncOptionsSchema = z.object({).max(20).optional(),+ postSyncCommand: PostSyncCommandSchema,certificateNameSchema: z.string().trim()diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdxindex efa3feff92..a4e38d8a77 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx@@ -4,6 +4,8 @@ sidebarTitle: "Linux Server"description: "Deploy certificates to Linux servers over SSH."---+import PostSyncCommandPlaceholders from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-placeholders.mdx";+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>@@ -15,6 +17,7 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi- 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)+- A Gateway is required to use a [post-sync command](#post-sync-commands), because the Gateway is what executes it## Create a Linux Server Sync@@ -41,13 +44,16 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi- **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**:+ 5. Configure the **Post-Sync Command**, or leave it empty:+ - **Command**: A command run on the server after the sync delivers a certificate, so the service that uses it picks up the new file, for example `sudo systemctl reload nginx`. [Post-Sync Commands](#post-sync-commands) covers the available placeholders and what happens when the command fails.++ 6. Configure the **Details**:- **Name**: The name of your sync.- **Description**: Optional description.- 6. Select which certificates should be synced.+ 7. Select which certificates should be synced.- 7. Review and click **Create Sync**.+ 8. 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.@@ -69,7 +75,8 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi"exportFormat": "pem","includePrivateKey": true,"canRemoveCertificates": true,- "certificateNameSchema": "{{commonName}}"+ "certificateNameSchema": "{{commonName}}",+ "postSyncCommand": "sudo systemctl reload nginx"},"destinationConfig": {"destinationPath": "/etc/ssl/certs"@@ -103,19 +110,118 @@ PKCS#12When syncing certificates, Infisical opens an SSH session to the server and, for each certificate, packages it in the chosen export format and writes the resulting files to the destination directory. Files are written atomically over SFTP so a reader never sees a partially written certificate or key.+## Post-Sync Commands++Delivering a certificate file does not make the service use it. Nginx keeps serving the old certificate until something reloads it. A post-sync command is that last step, run for you right after the files land.++Set one command on the sync. It runs on the target server, in that server's own shell, once per sync run that delivers at least one file. Leaving the field empty means nothing runs, so there is no separate toggle.++The field accepts a whole script, so several steps can run in one go: put each on its own line, or chain them with `&&`.++<Note>+ Your [Infisical Gateway](/documentation/platform/gateways/overview) runs the command, never Infisical. The sync's SSH Connection must therefore use a gateway, otherwise the command is rejected when you save the sync.+</Note>++The command runs on the target server, not on Infisical, and only after the whole delivery has finished:++```mermaid+sequenceDiagram+ participant I as Infisical+ participant G as Gateway+ participant S as Target server+ I->>G: Deliver certificate files+ G->>S: Write files+ G->>S: Remove files for certificates no longer synced+ Note over G,S: Only once the server is in its final state+ I->>G: Run the post-sync command+ G->>S: Execute as the connection's account+ S-->>G: Output and outcome+ G-->>I: Success, or the reason it failed+```++### Setting a Command++<Steps>+ <Step title="Open the sync's Post-Sync Command step">+ Edit the sync and select **Post-Sync Command**.+ </Step>+ <Step title="Write the command">+ Use a placeholder wherever you need a value from the run:++ ```bash+ cp {{certificatePath}} /etc/nginx/ssl/live.pem && systemctl reload nginx+ ```+ </Step>+ <Step title="Save and trigger a sync">+ Save the sync, then trigger it. If the command fails, the reason appears as the sync's last error.+ </Step>+</Steps>++### Available Placeholders++<PostSyncCommandPlaceholders />++### Length Limit++A command is limited to 2048 characters, counted after the placeholders are substituted. For anything longer, put the logic in a script on the server and call that script.++### Post-Sync Command FAQ++<AccordionGroup>+ <Accordion title="When exactly does the command run?">+ After every file in the run has been delivered and after any removals, so the server is in its final state before the service reloads. A run that delivers nothing runs nothing. Renewals, adding a certificate, and a manual trigger all deliver files, so all three run the command. Removing a certificate from the sync does not.+ </Accordion>+ <Accordion title="What happens if the command fails?">+ The sync is marked failed and the reason appears as the sync's last error. The delivered files stay in place, because they were written before the command ran.+ </Accordion>+ <Accordion title="Can I run several commands, and what happens if one of them fails?">+ Yes. Write one per line, or chain them with `&&`.++ By default the shell only reports the **last** line's exit status, so an earlier line that fails is not noticed and the sync still reports success. Start the script with `set -e` so the first failure stops it and fails the sync:++ ```bash+ set -e+ cp {{certificatePath}} /etc/nginx/ssl/live.pem+ nginx -t+ systemctl reload nginx+ ```+ </Accordion>+ <Accordion title="Can the command run twice for the same certificate?">+ Yes. A sync that retries re-delivers the files and runs the command again, so prefer a command that is safe to run more than once. A service reload or restart is.+ </Accordion>+ <Accordion title="Is there a time limit?">+ Yes, 30 seconds, enforced by the gateway. A command that needs longer should start the work in the background or live in a script on the server.+ </Accordion>+</AccordionGroup>++### Least Privilege++The command runs as the account the SSH Connection authenticates with, so constraining that account bounds what any command can do. A service reload does not need root. Grant the connection user a `sudoers` rule for that one command instead:++```text+svc-infisical ALL=(root) NOPASSWD: /usr/bin/systemctl reload nginx+```++Anyone who can edit the sync can change the command, so treat edit access to these syncs as access to the target server.++<Warning>+ The rendered command is visible in the target server's process table while it runs. This only matters if you reference `{{pkcs12Password}}`, and only to accounts that already have a shell on the server the sync writes private keys to.+</Warning>+## Removing CertificatesWhen 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>+<AccordionGroup>+ <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>+</AccordionGroup>## What's Next?diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdxindex 9a3192b736..c7df48e87b 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx@@ -4,6 +4,8 @@ sidebarTitle: "Windows Server"description: "Deploy certificates to Windows servers over WinRM."---+import PostSyncCommandPlaceholders from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-placeholders.mdx";+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>@@ -44,13 +46,16 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM- **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**:+ 5. Configure the **Post-Sync Command**, or leave it empty:+ - **Command**: A PowerShell command run on the server after the sync delivers a certificate, so the service that uses it picks up the new file, for example `Restart-Service -Name "W3SVC"`. [Post-Sync Commands](#post-sync-commands) covers the available placeholders and what happens when the command fails.++ 6. Configure the **Details**:- **Name**: The name of your sync.- **Description**: Optional description.- 6. Select which certificates should be synced.+ 7. Select which certificates should be synced.- 7. Review and click **Create Sync**.+ 8. 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.@@ -74,7 +79,8 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM"syncOptions": {"exportFormat": "pkcs12","canRemoveCertificates": true,- "certificateNameSchema": "{{commonName}}"+ "certificateNameSchema": "{{commonName}}",+ "postSyncCommand": "Restart-Service -Name W3SVC"},"destinationConfig": {"destinationPath": "C:\\certs"@@ -112,6 +118,97 @@ When syncing certificates, Infisical asks the Gateway to open a WinRM session toWhen 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.+## Post-Sync Commands++Delivering a `.pfx` to `C:\certs` does not make IIS or a service use it. A post-sync command is that last step, run for you right after the files land.++Set one command on the sync. The Gateway runs it as PowerShell on the target server, once per sync run that delivers at least one file. Leaving the field empty means nothing runs, so there is no separate toggle.++The field accepts a whole script, so several steps can run in one go: put each on its own line.++Your Gateway runs the command, never Infisical. A WinRM Connection already requires a gateway, so nothing extra is needed here.++The command runs on the target server, not on Infisical, and only after the whole delivery has finished:++```mermaid+sequenceDiagram+ participant I as Infisical+ participant G as Gateway+ participant S as Target server+ I->>G: Deliver certificate files+ G->>S: Write files+ G->>S: Remove files for certificates no longer synced+ Note over G,S: Only once the server is in its final state+ I->>G: Run the post-sync command+ G->>S: Execute as the connection's account+ S-->>G: Output and outcome+ G-->>I: Success, or the reason it failed+```++### Setting a Command++<Steps>+ <Step title="Open the sync's Post-Sync Command step">+ Edit the sync and select **Post-Sync Command**.+ </Step>+ <Step title="Write the command">+ Use a placeholder wherever you need a value from the run:++ ```powershell+ Import-PfxCertificate -FilePath {{certificatePath}} -CertStoreLocation Cert:\LocalMachine\My -Password (ConvertTo-SecureString {{pkcs12Password}} -AsPlainText -Force)+ ```+ </Step>+ <Step title="Save and trigger a sync">+ Save the sync, then trigger it. If the command fails, the reason appears as the sync's last error.+ </Step>+</Steps>++### Available Placeholders++<PostSyncCommandPlaceholders />++### Length Limit++A command is limited to 2048 characters. Windows caps a command line at 8191 characters and the command is sent to PowerShell encoded, which expands it, so the substituted values count against the same budget. If a long command combined with a sync that delivers many certificates does not fit, the sync reports it clearly. Move the logic into a script file on the server and call that script instead.++### Post-Sync Command FAQ++<AccordionGroup>+ <Accordion title="When exactly does the command run?">+ After every file in the run has been delivered and after any removals, so the server is in its final state before the service restarts. A run that delivers nothing runs nothing. Renewals, adding a certificate, and a manual trigger all deliver files, so all three run the command. Removing a certificate from the sync does not.+ </Accordion>+ <Accordion title="What happens if the command fails?">+ The sync is marked failed and the reason appears as the sync's last error. The delivered files stay in place, because they were written before the command ran. A silent failure is reported as a failure: the script stops on the first error, and a native command's own non-zero exit code is passed through.++ To fail the sync deliberately, use `throw "reason"`. Avoid `exit`: PowerShell stops the script there before it can report its result, so the sync is failed with a message saying the outcome could not be read rather than with your reason.+ </Accordion>+ <Accordion title="Can I run several commands, and what happens if one of them fails?">+ Yes, write one per line.++ A failing **cmdlet** (`Copy-Item`, `Restart-Service`, and so on) stops the script and fails the sync wherever it appears, because the script runs with `$ErrorActionPreference` set to `Stop`. A failing **external executable** is different: only the last statement decides the outcome, so an earlier `.exe` that fails is not noticed. That is deliberate, because a non-zero exit is routine for some tools (`findstr` returns 1 when nothing matched, `robocopy` returns 1 when it copied files) and those should not fail a sync. Check the ones you care about yourself:++ ```powershell+ netsh.exe http show sslcert+ if ($LASTEXITCODE -ne 0) { throw "netsh failed with $LASTEXITCODE" }+ Restart-Service -Name W3SVC+ ```+ </Accordion>+ <Accordion title="Can the command run twice for the same certificate?">+ Yes. A sync that retries re-delivers the files and runs the command again, so prefer a command that is safe to run more than once. A service restart is.+ </Accordion>+ <Accordion title="Is there a time limit?">+ Yes, 30 seconds, enforced by the Gateway. A command that needs longer should start the work in the background or live in a script on the server.+ </Accordion>+</AccordionGroup>++### Least Privilege++The command runs as the account the WinRM Connection authenticates with, so constraining that account bounds what any command can do. Restarting one service does not need an administrator. Grant the connection account start and stop rights on that single service instead of making it a local administrator.++Binding a certificate to an HTTPS port in IIS is the exception: HTTP.sys requires a local administrator and the right cannot be delegated. Because a local administrator can do anything on the host, handle that case with a dedicated, clearly labeled sync rather than raising the privileges of a sync that only needs to deliver files and restart a service. Infisical does not block an administrator credential on a standard sync, so this is a recommendation you enforce with how you configure the connection.++Anyone who can edit the sync can change the command, so treat edit access to these syncs as access to the target server.+## SecurityDelivery runs over the Gateway inside your network, so traffic never crosses the public internet, and the certificate stays encrypted in transit in both connection modes:@@ -136,9 +233,11 @@ These are IIS requirements, configured once on the Windows host (the CCS feature## FAQ-<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>+<AccordionGroup>+ <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>+</AccordionGroup>## What's Next?diff --git a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-placeholders.mdx b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-placeholders.mdxnew file mode 100644index 0000000000..0c7edaf6f1--- /dev/null+++ b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-placeholders.mdx@@ -0,0 +1,21 @@+Write a placeholder where you want this run's value. Infisical replaces it before the command is sent to the server, so the command keeps working when the name schema or export format changes.++| Placeholder | Value |+| --- | --- |+| `{{certificatePath}}` | Full path of the certificate file delivered this run. Single-certificate syncs only |+| `{{certificateDirectory}}` | The destination directory |+| `{{certificateFiles}}` | Every path written this run, one per line |+| `{{commonName}}` | The certificate's common name. Single-certificate syncs only |+| `{{pkcs12Password}}` | The PKCS#12 export password, set only when the export format is PKCS#12 |++Each value is inserted already quoted for the target's shell, so write `{{certificatePath}}` rather than `"{{certificatePath}}"`. A placeholder that has no value for the run becomes an empty string.++Only the names in this table are substituted. Anything else in double braces is left in the command exactly as you wrote it, so a command that calls a tool with its own braces (helm, jq, a Go template) keeps working, and a misspelled placeholder reaches the server as literal text rather than silently turning into nothing.++<Note>+ `{{certificatePath}}` and `{{commonName}}` name one specific certificate, so a command that uses either can only be saved on a sync with a single certificate linked. Linking a second certificate to such a sync is rejected, as is adding one of these placeholders to a sync that already has several. To act on every certificate in the run, use `{{certificateFiles}}`, which lists one path per line:++ ```bash+ echo {{certificateFiles}} | while read -r file; do echo "delivered $file"; done+ ```+</Note>diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsxindex 17badf7be2..90785f990d 100644--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx@@ -42,6 +42,7 @@ import { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";import { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";import { PkiSyncFieldMappingsFields } from "./PkiSyncFieldMappingsFields";import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields";+import { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";import { PkiSyncReviewFields } from "./PkiSyncReviewFields";type Props = {@@ -77,6 +78,13 @@ const STEP_META: Record<rightDescription:"Map each certificate component (certificate, private key, and chain) to the field names used at the destination."},+ postSyncCommand: {+ short: "Command after sync",+ subtitle: "Optionally run a command on the host after certificates are written.",+ rightLabel: "POST-SYNC COMMAND",+ rightDescription:+ "Run a command on the destination host after certificates are written, for example to reload a service so it picks up the new certificate."+ },details: {short: "Name and description",subtitle: "Give this sync a name and an optional description.",@@ -101,7 +109,8 @@ const STEP_META: Record<};const getFormTabs = (- destination: PkiSync+ destination: PkiSync,+ canRunPostSyncCommand: boolean): { name: string; key: string; fields: FieldPath<TPkiSyncForm>[] }[] => {const baseTabs = [{@@ -124,6 +133,14 @@ const getFormTabs = (});}+ if (canRunPostSyncCommand) {+ baseTabs.push({+ name: "Post-Sync Command",+ key: "postSyncCommand",+ fields: ["syncOptions.postSyncCommand"] as FieldPath<TPkiSyncForm>[]+ });+ }+baseTabs.push({name: "Details",@@ -154,9 +171,9 @@ export const CreatePkiSyncForm = ({const [selectedTabIndex, setSelectedTabIndex] = useState(0);const [showConfirmation, setShowConfirmation] = useState(false);- const FORM_TABS = getFormTabs(destination);const { syncOption } = usePkiSyncOption(destination);+ const FORM_TABS = getFormTabs(destination, Boolean(syncOption?.canRunPostSyncCommand));const formMethods = useForm<TPkiSyncForm>({resolver: zodResolver(PkiSyncFormSchema),@@ -169,7 +186,7 @@ export const CreatePkiSyncForm = ({canRemoveCertificates: false,preserveArn: true,certificateNameSchema: syncOption?.defaultCertificateNameSchema,- ...((destination === PkiSync.LinuxServer || destination === PkiSync.WindowsServer) && {+ ...(syncOption?.canRunPostSyncCommand && {exportFormat:destination === PkiSync.WindowsServer? PkiSyncExportFormat.Pkcs12@@ -352,6 +369,9 @@ export const CreatePkiSyncForm = ({</>)}{currentKey === "mappings" && <PkiSyncFieldMappingsFields destination={destination} />}+ {currentKey === "postSyncCommand" && (+ <PkiSyncPostSyncCommandFields destination={destination} />+ )}{currentKey === "details" && <PkiSyncDetailsFields />}{currentKey === "certificates" && (<PkiSyncCertificatesFields applicationId={applicationId} />diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsxindex 8bfa78cc35..d6dc2f4769 100644--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx@@ -16,13 +16,14 @@ import {Switch} from "@app/components/v3";import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";-import { PkiSync, TPkiSync, useUpdatePkiSync } from "@app/hooks/api/pkiSyncs";+import { PkiSync, TPkiSync, usePkiSyncOption, useUpdatePkiSync } from "@app/hooks/api/pkiSyncs";import { TUpdatePkiSyncForm, UpdatePkiSyncFormSchema } from "./schemas/pki-sync-schema";import { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";import { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";import { PkiSyncFieldMappingsFields } from "./PkiSyncFieldMappingsFields";import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields";+import { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";type Props = {onComplete: (pkiSync: TPkiSync) => void;@@ -41,7 +42,7 @@ type FormStep = {rightDescription: string;};-const getFormSteps = (destination: PkiSync): FormStep[] => {+const getFormSteps = (destination: PkiSync, canRunPostSyncCommand: boolean): FormStep[] => {const steps: FormStep[] = [{key: "destination",@@ -78,6 +79,19 @@ const getFormSteps = (destination: PkiSync): FormStep[] => {});}+ if (canRunPostSyncCommand) {+ steps.push({+ key: "postSyncCommand",+ name: "Post-Sync Command",+ description: "Command after sync",+ title: "Post-Sync Command",+ subtitle: "Optionally run a command on the host after certificates are written.",+ rightLabel: "POST-SYNC COMMAND",+ rightDescription:+ "Run a command on the destination host after certificates are written, for example to reload a service so it picks up the new certificate."+ });+ }+steps.push({key: "details",name: "Details",@@ -95,7 +109,8 @@ const getFormSteps = (destination: PkiSync): FormStep[] => {export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }: Props) => {const updatePkiSync = useUpdatePkiSync();const { name: destinationName } = PKI_SYNC_MAP[pkiSync.destination];- const steps = getFormSteps(pkiSync.destination);+ const { syncOption } = usePkiSyncOption(pkiSync.destination);+ const steps = getFormSteps(pkiSync.destination, Boolean(syncOption?.canRunPostSyncCommand));const [selectedStepIndex, setSelectedStepIndex] = useState(0);@@ -183,6 +198,8 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel });case "mappings":return <PkiSyncFieldMappingsFields destination={pkiSync.destination} />;+ case "postSyncCommand":+ return <PkiSyncPostSyncCommandFields destination={pkiSync.destination} />;case "details":return <PkiSyncDetailsFields />;default:diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsxnew file mode 100644index 0000000000..d113d53fbf--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx@@ -0,0 +1,100 @@+import { Controller, useFormContext } from "react-hook-form";++import {+ Badge,+ Field,+ FieldDescription,+ FieldError,+ FieldLabel,+ TextArea+} from "@app/components/v3";+import { PkiSync, PkiSyncExportFormat, PostSyncCommandVariable } from "@app/hooks/api/pkiSyncs";++import { TPkiSyncForm } from "./schemas/pki-sync-schema";++const COMMAND_PLACEHOLDERS: Partial<Record<PkiSync, string>> = {+ [PkiSync.LinuxServer]: "cp {{certificatePath}} /etc/nginx/ssl/live.pem && systemctl reload nginx",+ [PkiSync.WindowsServer]: 'Restart-Service -Name "W3SVC"'+};++const VARIABLE_DESCRIPTIONS: Record<PostSyncCommandVariable, string> = {+ [PostSyncCommandVariable.CertificatePath]: "Full path of the certificate file delivered this run",+ [PostSyncCommandVariable.CertificateDirectory]: "The destination directory",+ [PostSyncCommandVariable.CertificateFiles]: "Every path written this run, one per line",+ [PostSyncCommandVariable.CommonName]: "The certificate's common name",+ [PostSyncCommandVariable.Pkcs12Password]: "The PKCS#12 export password"+};++const SINGLE_CERTIFICATE_VARIABLES = [+ PostSyncCommandVariable.CertificatePath,+ PostSyncCommandVariable.CommonName+];++type Props = {+ destination?: PkiSync;+};++export const PkiSyncPostSyncCommandFields = ({ destination }: Props) => {+ const { control, watch } = useFormContext<TPkiSyncForm>();+ const currentDestination = destination ?? watch("destination");+ const isPkcs12 = watch("syncOptions.exportFormat") === PkiSyncExportFormat.Pkcs12;++ const variables = Object.values(PostSyncCommandVariable).filter(+ (variable) => variable !== PostSyncCommandVariable.Pkcs12Password || isPkcs12+ );++ return (+ <>+ <p className="mb-4 text-sm text-bunker-300">+ Run a command on the target server after a certificate is delivered, for example restarting+ the service that uses it. Reference this run's values with the placeholders below.+ Leave it empty to run nothing.+ </p>+ <Controller+ control={control}+ name="syncOptions.postSyncCommand"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="post-sync-command">Command</FieldLabel>+ <TextArea+ id="post-sync-command"+ className="min-h-24 font-mono text-xs"+ value={value ?? ""}+ onChange={onChange}+ isError={Boolean(error)}+ placeholder={COMMAND_PLACEHOLDERS[currentDestination]}+ />+ <FieldDescription>+ Runs once per sync run that delivers a file, as the sync's account, so keep that+ account least-privilege. If it fails, the sync is marked failed. The command is+ executed by the gateway, so the sync's connection must use one.+ </FieldDescription>+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <div className="flex flex-col gap-2">+ <p className="text-xs text-mineshaft-300">Available placeholders</p>+ <ul className="flex flex-col gap-1.5">+ {variables.map((variable) => (+ <li key={variable} className="flex items-center gap-2">+ <Badge variant="neutral" className="font-mono">+ {`{{${variable}}}`}+ </Badge>+ <span className="text-xs text-mineshaft-400">+ {VARIABLE_DESCRIPTIONS[variable]}+ {SINGLE_CERTIFICATE_VARIABLES.includes(variable) &&+ ". Single-certificate syncs only"}+ </span>+ </li>+ ))}+ </ul>+ <p className="text-xs text-mineshaft-400">+ Each placeholder is replaced with its value before the command is sent to the host, and is+ inserted already quoted, so do not wrap one in quotes yourself. Do not paste secrets into+ the command.+ </p>+ </div>+ </>+ );+};diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsxindex f6d2684f87..a56c87d09c 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx@@ -66,6 +66,8 @@ export const PkiSyncReviewFields = () => {const destinationName = PKI_SYNC_MAP[destination].name;const selectedCertificates = getSelectedCertificates(certificateIds);+ const postSyncCommand =+ syncOptions && "postSyncCommand" in syncOptions ? syncOptions.postSyncCommand : undefined;return (<div className="mb-4 flex flex-col gap-6">@@ -176,6 +178,16 @@ export const PkiSyncReviewFields = () => {})}</div></div>+ {postSyncCommand && (+ <div className="flex flex-col gap-3">+ <div className="w-full border-b border-mineshaft-600">+ <span className="text-sm text-mineshaft-300">Post-Sync Command</span>+ </div>+ <pre className="thin-scrollbar overflow-x-auto rounded-sm bg-mineshaft-600 p-2 font-mono text-xs whitespace-pre-wrap text-mineshaft-200">+ {postSyncCommand}+ </pre>+ </div>+ )}<div className="flex flex-col gap-3"><div className="w-full border-b border-border"><span className="text-sm text-muted">Details</span>diff --git a/frontend/src/components/pki-syncs/forms/index.ts b/frontend/src/components/pki-syncs/forms/index.tsindex 243dd9c8de..901f0f434a 100644--- a/frontend/src/components/pki-syncs/forms/index.ts+++ b/frontend/src/components/pki-syncs/forms/index.ts@@ -3,5 +3,6 @@ export { EditPkiSyncForm } from "./EditPkiSyncForm";export { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";export { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";export { PkiSyncOptionsFields } from "./PkiSyncOptionsFields/PkiSyncOptionsFields";+export { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";export { PkiSyncReviewFields } from "./PkiSyncReviewFields";export { PkiSyncFormSchema, type TPkiSyncForm } from "./schemas/pki-sync-schema";diff --git a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.tsindex 384c97657e..a27188b353 100644--- a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts@@ -1,5 +1,17 @@import { AnyZodObject, z } from "zod";+export const POST_SYNC_COMMAND_MAX_LENGTH = 2048;++export const PostSyncCommandSchema = z+ .string()+ .trim()+ .max(+ POST_SYNC_COMMAND_MAX_LENGTH,+ `Command must be at most ${POST_SYNC_COMMAND_MAX_LENGTH} characters`+ )+ .transform((command) => command || undefined)+ .optional();+export const BasePkiSyncSchema = <T extends AnyZodObject | undefined = undefined>(additionalSyncOptions?: T) => {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.tsindex a404acceff..4aa997438b 100644--- 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.ts@@ -2,7 +2,7 @@ import { z } from "zod";import { PemCertificateExtension, PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";-import { BasePkiSyncSchema } from "./base-pki-sync-schema";+import { BasePkiSyncSchema, PostSyncCommandSchema } from "./base-pki-sync-schema";const compileNameSchema = (val: string) =>val@@ -54,6 +54,7 @@ const LinuxServerSyncOptionsSchema = z.object({}).transform((v) => v || undefined).optional(),+ postSyncCommand: PostSyncCommandSchema,certificateNameSchema: z.string().trim()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.tsindex eee88f4ff8..6e98e87f75 100644--- 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.ts@@ -7,7 +7,7 @@ import {WindowsFileAccess} from "@app/hooks/api/pkiSyncs";-import { BasePkiSyncSchema } from "./base-pki-sync-schema";+import { BasePkiSyncSchema, PostSyncCommandSchema } from "./base-pki-sync-schema";const compileNameSchema = (val: string) =>val@@ -41,6 +41,7 @@ const WindowsServerSyncOptionsSchema = z.object({.max(20).optional(),includePrivateKey: z.boolean().default(true),+ postSyncCommand: PostSyncCommandSchema,certificateNameSchema: z.string().trim()diff --git a/frontend/src/hooks/api/pkiSyncs/enums.ts b/frontend/src/hooks/api/pkiSyncs/enums.tsindex 09b2220d4a..10f2bd2cb2 100644--- a/frontend/src/hooks/api/pkiSyncs/enums.ts+++ b/frontend/src/hooks/api/pkiSyncs/enums.ts@@ -23,6 +23,14 @@ export enum PemCertificateExtension {Crt = "crt"}+export enum PostSyncCommandVariable {+ CertificatePath = "certificatePath",+ CertificateDirectory = "certificateDirectory",+ CertificateFiles = "certificateFiles",+ CommonName = "commonName",+ Pkcs12Password = "pkcs12Password"+}+export enum WindowsFileAccess {Read = "read",Modify = "modify",diff --git a/frontend/src/hooks/api/pkiSyncs/types/index.ts b/frontend/src/hooks/api/pkiSyncs/types/index.tsindex 9dc3753ae7..ff30359bad 100644--- a/frontend/src/hooks/api/pkiSyncs/types/index.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/index.ts@@ -18,6 +18,7 @@ export type TPkiSyncOption = {destination: PkiSync;canImportCertificates: boolean;canRemoveCertificates: boolean;+ canRunPostSyncCommand?: boolean;maxCertificates?: number;enterprise?: boolean;defaultCertificateNameSchema?: string;diff --git a/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.tsindex 1f7df07c91..9e3d15774e 100644--- a/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts@@ -17,6 +17,7 @@ export type TLinuxServerPkiSync = TRootPkiSync & {privateKeyFileMode?: string;owner?: string;group?: string;+ postSyncCommand?: string;};connection: {app: AppConnection.SSH;diff --git a/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.tsindex a9408119a7..8ca87d1b84 100644--- a/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts@@ -14,6 +14,7 @@ export type TWindowsServerPkiSync = TRootPkiSync & {combineCertificateChain?: boolean;includePrivateKey?: boolean;fileAccessRules?: { identity: string; access: WindowsFileAccess }[];+ postSyncCommand?: string;};connection: {app: AppConnection.WinRM;diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsxindex 576cfa2dfd..4bcbfef096 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx@@ -33,7 +33,8 @@ import {PkiSyncDestinationSection,PkiSyncDetailsSection,PkiSyncFieldMappingsSection,- PkiSyncOptionsSection+ PkiSyncOptionsSection,+ PkiSyncPostSyncCommandSection} from "./components";const PageContent = () => {@@ -136,6 +137,7 @@ const PageContent = () => {<PkiSyncDetailsSection pkiSync={pkiSync} /><PkiSyncDestinationSection pkiSync={pkiSync} /><PkiSyncFieldMappingsSection pkiSync={pkiSync} />+ <PkiSyncPostSyncCommandSection pkiSync={pkiSync} /></DetailGroup><PkiSyncOptionsSection pkiSync={pkiSync} /></CardContent>diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsxnew file mode 100644index 0000000000..008205a40d--- /dev/null+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx@@ -0,0 +1,28 @@+import { Detail, DetailLabel, DetailValue } from "@app/components/v3";+import { TPkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";++type Props = {+ pkiSync: TPkiSync;+};++export const PkiSyncPostSyncCommandSection = ({ pkiSync }: Props) => {+ const { syncOption } = usePkiSyncOption(pkiSync.destination);+ const { postSyncCommand } = pkiSync.syncOptions as { postSyncCommand?: string };++ if (!syncOption?.canRunPostSyncCommand) return null;++ return (+ <Detail>+ <DetailLabel>Post-Sync Command</DetailLabel>+ <DetailValue>+ {postSyncCommand ? (+ <pre className="max-h-32 thin-scrollbar overflow-auto rounded-sm bg-mineshaft-600 p-2 font-mono text-xs whitespace-pre-wrap text-foreground">+ {postSyncCommand}+ </pre>+ ) : (+ <span className="text-muted/50 italic">None</span>+ )}+ </DetailValue>+ </Detail>+ );+};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.tsindex 04cb273a2a..d6a8f5dc8e 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts@@ -5,3 +5,4 @@ export { PkiSyncDestinationSection } from "./PkiSyncDestinationSection";export { PkiSyncDetailsSection } from "./PkiSyncDetailsSection";export { PkiSyncFieldMappingsSection } from "./PkiSyncFieldMappingsSection";export { PkiSyncOptionsSection } from "./PkiSyncOptionsSection";+export { PkiSyncPostSyncCommandSection } from "./PkiSyncPostSyncCommandSection";