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
Address PR comments
Carlos Monastyrski829bd57de7e9
diff --git a/backend/src/db/migrations/20260811151204_add-pki-sync-health-check.ts b/backend/src/db/migrations/20260811151204_add-pki-sync-health-check.tsnew file mode 100644index 0000000000..12a4b0ac63--- /dev/null+++ b/backend/src/db/migrations/20260811151204_add-pki-sync-health-check.ts@@ -0,0 +1,82 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++const HEALTH_CHECK_DISCOVERY_INDEX = "idx_pki_syncs_health_check_discovery";+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds++const HEALTH_CHECK_COLUMNS = ["lastHealthCheckRanAt", "lastHealthCheckStatus", "lastHealthCheckMessage"] as const;++type HealthCheckColumn = (typeof HEALTH_CHECK_COLUMNS)[number];++const findExistingColumns = async (knex: Knex): Promise<Set<HealthCheckColumn>> => {+ const present = new Set<HealthCheckColumn>();++ for (const column of HEALTH_CHECK_COLUMNS) {+ // eslint-disable-next-line no-await-in-loop+ if (await knex.schema.hasColumn(TableName.PkiSync, column)) present.add(column);+ }++ return present;+};++export async function up(knex: Knex): Promise<void> {+ const existing = await findExistingColumns(knex);++ if (existing.size < HEALTH_CHECK_COLUMNS.length) {+ await knex.schema.alterTable(TableName.PkiSync, (t) => {+ if (!existing.has("lastHealthCheckRanAt")) t.timestamp("lastHealthCheckRanAt", { useTz: true });+ if (!existing.has("lastHealthCheckStatus")) t.string("lastHealthCheckStatus");+ if (!existing.has("lastHealthCheckMessage")) t.string("lastHealthCheckMessage", 1024);+ });+ }++ const connection = await knex.client.acquireConnection();+ const raw = (sql: string) => knex.raw(sql).connection(connection);++ try {+ const stmtResult = await raw("SHOW statement_timeout");+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;+ const lockResult = await raw("SHOW lock_timeout");+ const originalLockTimeout = lockResult.rows[0].lock_timeout;++ try {+ await raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);+ await raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);++ const invalid = await raw(+ `SELECT 1 FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid WHERE c.relname = '${HEALTH_CHECK_DISCOVERY_INDEX}' AND NOT i.indisvalid`+ );+ if (invalid.rows.length > 0) {+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${HEALTH_CHECK_DISCOVERY_INDEX}"`);+ }++ await raw(`+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${HEALTH_CHECK_DISCOVERY_INDEX}"+ ON ${TableName.PkiSync} ("createdAt")+ WHERE ("syncOptions" ->> 'healthCheckCommand') IS NOT NULL+ `);+ } finally {+ await raw(`SET statement_timeout = '${originalStatementTimeout}'`);+ await raw(`SET lock_timeout = '${originalLockTimeout}'`);+ }+ } finally {+ await knex.client.releaseConnection(connection);+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${HEALTH_CHECK_DISCOVERY_INDEX}"`);++ const existing = await findExistingColumns(knex);++ if (existing.size > 0) {+ await knex.schema.alterTable(TableName.PkiSync, (t) => {+ existing.forEach((column) => t.dropColumn(column));+ });+ }+}++const config = { transaction: false };+export { config };diff --git a/backend/src/db/migrations/20260811151204_add-pki-sync-preflight-discovery-index.ts b/backend/src/db/migrations/20260811151204_add-pki-sync-preflight-discovery-index.tsdeleted file mode 100644index 7f862e90e0..0000000000--- a/backend/src/db/migrations/20260811151204_add-pki-sync-preflight-discovery-index.ts+++ /dev/null@@ -1,49 +0,0 @@-import { Knex } from "knex";--import { TableName } from "../schemas";--const PREFLIGHT_DISCOVERY_INDEX = "idx_pki_syncs_preflight_discovery";-const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes-const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds--export async function up(knex: Knex): Promise<void> {- const connection = await knex.client.acquireConnection();- const raw = (sql: string) => knex.raw(sql).connection(connection);-- try {- const stmtResult = await raw("SHOW statement_timeout");- const originalStatementTimeout = stmtResult.rows[0].statement_timeout;- const lockResult = await raw("SHOW lock_timeout");- const originalLockTimeout = lockResult.rows[0].lock_timeout;-- try {- await raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);- await raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);-- const invalid = await raw(- `SELECT 1 FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid WHERE c.relname = '${PREFLIGHT_DISCOVERY_INDEX}' AND NOT i.indisvalid`- );- if (invalid.rows.length > 0) {- await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${PREFLIGHT_DISCOVERY_INDEX}"`);- }-- await raw(`- CREATE INDEX CONCURRENTLY IF NOT EXISTS "${PREFLIGHT_DISCOVERY_INDEX}"- ON ${TableName.PkiSync} ("createdAt")- WHERE ("syncOptions" ->> 'preflightCommand') IS NOT NULL- `);- } finally {- await raw(`SET statement_timeout = '${originalStatementTimeout}'`);- await raw(`SET lock_timeout = '${originalLockTimeout}'`);- }- } finally {- await knex.client.releaseConnection(connection);- }-}--export async function down(knex: Knex): Promise<void> {- await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${PREFLIGHT_DISCOVERY_INDEX}"`);-}--const config = { transaction: false };-export { config };diff --git a/backend/src/db/schemas/pki-syncs.ts b/backend/src/db/schemas/pki-syncs.tsindex 6da5f5bbbc..dcf5403576 100644--- a/backend/src/db/schemas/pki-syncs.ts+++ b/backend/src/db/schemas/pki-syncs.ts@@ -36,7 +36,10 @@ export const PkiSyncsSchema = z.object({lastRemoveMessage: z.string().nullable().optional(),lastRemovedAt: z.date().nullable().optional(),applicationId: z.string().uuid().nullable().optional(),- encryptedCredentials: zodBuffer.nullable().optional()+ encryptedCredentials: zodBuffer.nullable().optional(),+ lastHealthCheckRanAt: z.date().nullable().optional(),+ lastHealthCheckStatus: z.string().nullable().optional(),+ lastHealthCheckMessage: z.string().nullable().optional()});export type TPkiSyncs = z.infer<typeof PkiSyncsSchema>;diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 1ae3055147..e9b2a995b5 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -43,8 +43,8 @@ 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 { THealthCheckCommandResult } from "@app/services/pki-sync/pki-sync-health-check-command-fns";import { TPostSyncCommandResult } from "@app/services/pki-sync/pki-sync-post-sync-command-fns";-import { TPreflightCommandResult } from "@app/services/pki-sync/pki-sync-preflight-command-fns";import { SecretSync, SecretSyncImportBehavior } from "@app/services/secret-sync/secret-sync-enums";import {TCreateSecretSyncDTO,@@ -580,7 +580,8 @@ export enum EventType {PKI_SYNC_SYNC_CERTIFICATES = "pki-sync-sync-certificates",PKI_SYNC_IMPORT_CERTIFICATES = "pki-sync-import-certificates",PKI_SYNC_REMOVE_CERTIFICATES = "pki-sync-remove-certificates",- PKI_SYNC_PREFLIGHT_CHECK = "pki-sync-preflight-check",+ PKI_SYNC_HEALTH_CHECK = "pki-sync-health-check",+ PKI_SYNC_TEST_HEALTH_CHECK = "pki-sync-test-health-check",PKI_SYNC_SET_DEFAULT_CERTIFICATE = "pki-sync-set-default-certificate",PKI_SYNC_CLEAR_DEFAULT_CERTIFICATE = "pki-sync-clear-default-certificate",OIDC_GROUP_MEMBERSHIP_MAPPING_ASSIGN_USER = "oidc-group-membership-mapping-assign-user",@@ -4514,7 +4515,7 @@ interface CreatePkiSyncEvent {connectionId?: string;hasCredentials?: boolean;hasPostSyncCommand?: boolean;- hasPreflightCommand?: boolean;+ hasHealthCheckCommand?: boolean;};}@@ -4525,7 +4526,7 @@ interface UpdatePkiSyncEvent {name: string;applicationId?: string;hasPostSyncCommand?: boolean;- hasPreflightCommand?: boolean;+ hasHealthCheckCommand?: boolean;};}@@ -4546,7 +4547,7 @@ interface PkiSyncSyncCertificatesEvent {syncMessage: string | null;jobId: string;jobRanAt: Date;- preflightCheck?: { command: string; result?: TPreflightCommandResult };+ healthCheck?: { command: string; result?: THealthCheckCommandResult };postSyncCommand?: { command: string; result?: TPostSyncCommandResult };};}@@ -4561,15 +4562,27 @@ interface PkiSyncImportCertificatesEvent {};}-interface PkiSyncPreflightCheckEvent {- type: EventType.PKI_SYNC_PREFLIGHT_CHECK;+interface PkiSyncTestHealthCheckEvent {+ type: EventType.PKI_SYNC_TEST_HEALTH_CHECK;+ metadata: {+ connectionId: string;+ connectionName: string;+ destination: string;+ command: string;+ ranAt: Date;+ result?: THealthCheckCommandResult;+ };+}++interface PkiSyncHealthCheckEvent {+ type: EventType.PKI_SYNC_HEALTH_CHECK;metadata: {syncId: string;syncName: string;destination: string;command: string;ranAt: Date;- result?: TPreflightCommandResult;+ result?: THealthCheckCommandResult;};}@@ -7477,7 +7490,8 @@ export type Event =| DeletePkiSyncEvent| PkiSyncSyncCertificatesEvent| PkiSyncImportCertificatesEvent- | PkiSyncPreflightCheckEvent+ | PkiSyncHealthCheckEvent+ | PkiSyncTestHealthCheckEvent| PkiSyncRemoveCertificatesEvent| PkiSyncSetDefaultCertificateEvent| PkiSyncClearDefaultCertificateEventdiff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex af7239e595..816c363b7b 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -296,7 +296,7 @@ const buildAdminPermissionRules = () => {ProjectPermissionPkiSyncActions.ImportCertificates,ProjectPermissionPkiSyncActions.RemoveCertificates,ProjectPermissionPkiSyncActions.SetPostSyncCommand,- ProjectPermissionPkiSyncActions.SetPreflightCommand+ ProjectPermissionPkiSyncActions.SetHealthCheckCommand],ProjectPermissionSub.PkiSyncs);@@ -865,7 +865,7 @@ const buildApplicationAdminPermissionRules = () => {ResourcePermissionPkiSyncActions.ImportCertificates,ResourcePermissionPkiSyncActions.RemoveCertificates,ResourcePermissionPkiSyncActions.SetPostSyncCommand,- ResourcePermissionPkiSyncActions.SetPreflightCommand+ ResourcePermissionPkiSyncActions.SetHealthCheckCommand],ResourcePermissionSub.PkiSyncs);diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.tsindex e5c1493db4..3af2b5823d 100644--- a/backend/src/ee/services/permission/project-permission.ts+++ b/backend/src/ee/services/permission/project-permission.ts@@ -171,7 +171,7 @@ export enum ProjectPermissionPkiSyncActions {ImportCertificates = "import-certificates",RemoveCertificates = "remove-certificates",SetPostSyncCommand = "set-post-sync-command",- SetPreflightCommand = "set-preflight-command"+ SetHealthCheckCommand = "set-health-check-command"}export enum ProjectPermissionPkiDiscoveryActions {diff --git a/backend/src/ee/services/permission/resource-permission.ts b/backend/src/ee/services/permission/resource-permission.tsindex 3d35cbfeca..ff2fd60b2a 100644--- a/backend/src/ee/services/permission/resource-permission.ts+++ b/backend/src/ee/services/permission/resource-permission.ts@@ -101,7 +101,7 @@ export enum ResourcePermissionPkiSyncActions {ImportCertificates = "import-certificates",RemoveCertificates = "remove-certificates",SetPostSyncCommand = "set-post-sync-command",- SetPreflightCommand = "set-preflight-command"+ SetHealthCheckCommand = "set-health-check-command"}export type ResourcePermissionSet =diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.tsindex 266564e3ed..5c9227ee29 100644--- a/backend/src/lib/cron/cron-job.ts+++ b/backend/src/lib/cron/cron-job.ts@@ -22,7 +22,7 @@ export const CronJobName = {DailyExpiringPkiItemAlert: "daily-expiring-pki-item-alert",DailyPkiAlertV2Processing: "daily-pki-alert-v2-processing",PkiSyncCleanup: "pki-sync-cleanup",- PkiSyncPreflightCheck: "pki-sync-preflight-check",+ PkiSyncHealthCheck: "pki-sync-health-check",PkiSubscriberDailyAutoRenewal: "pki-subscriber-daily-auto-renewal",PkiDiscoveryScheduledScan: "pki-discovery-scheduled-scan",PamDiscoveryScheduledScan: "pam-discovery-scheduled-scan",diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex dc917e4bca..bf22d6831f 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -50,7 +50,7 @@ import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-typesimport {TQueuePkiSyncImportCertificatesByIdDTO,TQueuePkiSyncRemoveCertificatesByIdDTO,- TQueuePkiSyncRunPreflightCheckByIdDTO,+ TQueuePkiSyncRunHealthCheckByIdDTO,TQueuePkiSyncSyncCertificatesByIdDTO} from "@app/services/pki-sync/pki-sync-types";import {@@ -90,7 +90,7 @@ export enum QueueName {SecretReplication = "secret-replication",SecretSync = "secret-sync", // parent queue to push integration sync, webhook, and secret replicationPkiSync = "pki-sync",- PkiSyncPreflightCheck = "pki-sync-preflight-check",+ PkiSyncHealthCheck = "pki-sync-health-check",ProjectV3Migration = "project-v3-migration",AccessTokenStatusUpdate = "access-token-status-update",ImportSecretsFromExternalSource = "import-secrets-from-external-source",@@ -155,7 +155,7 @@ export enum QueueJobs {PkiSyncSyncCertificates = "pki-sync-sync-certificates",PkiSyncImportCertificates = "pki-sync-import-certificates",PkiSyncRemoveCertificates = "pki-sync-remove-certificates",- PkiSyncRunPreflightCheck = "pki-sync-run-preflight-check",+ PkiSyncRunHealthCheck = "pki-sync-run-health-check",SecretRotationV2QueueRotations = "secret-rotation-v2-queue-rotations",SecretRotationV2RotateSecrets = "secret-rotation-v2-rotate-secrets",SecretRotationV2SendNotification = "secret-rotation-v2-send-notification",@@ -357,9 +357,9 @@ export type TQueueJobTypes = {name: QueueJobs.PkiSyncRemoveCertificates;payload: TQueuePkiSyncRemoveCertificatesByIdDTO;};- [QueueName.PkiSyncPreflightCheck]: {- name: QueueJobs.PkiSyncRunPreflightCheck;- payload: TQueuePkiSyncRunPreflightCheckByIdDTO;+ [QueueName.PkiSyncHealthCheck]: {+ name: QueueJobs.PkiSyncRunHealthCheck;+ payload: TQueuePkiSyncRunHealthCheckByIdDTO;};[QueueName.ProjectV3Migration]: {name: QueueJobs.ProjectV3Migration;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 2bf9ae0802..fe73c6ed7d 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -430,7 +430,7 @@ import { pkiSubscriberQueueServiceFactory } from "@app/services/pki-subscriber/pimport { pkiSubscriberServiceFactory } from "@app/services/pki-subscriber/pki-subscriber-service";import { pkiSyncCleanupQueueServiceFactory } from "@app/services/pki-sync/pki-sync-cleanup-queue";import { pkiSyncDALFactory } from "@app/services/pki-sync/pki-sync-dal";-import { pkiSyncPreflightQueueFactory } from "@app/services/pki-sync/pki-sync-preflight-queue";+import { pkiSyncHealthCheckQueueFactory } from "@app/services/pki-sync/pki-sync-health-check-queue";import { pkiSyncQueueFactory } from "@app/services/pki-sync/pki-sync-queue";import { pkiSyncServiceFactory } from "@app/services/pki-sync/pki-sync-service";import { pkiTemplatesDALFactory } from "@app/services/pki-templates/pki-templates-dal";@@ -3205,7 +3205,7 @@ export const registerRoutes = async (pkiSyncQueue});- const pkiSyncPreflightQueue = pkiSyncPreflightQueueFactory({+ const pkiSyncHealthCheckQueue = pkiSyncHealthCheckQueueFactory({cronJob,queueService,pkiSyncDAL,@@ -3675,6 +3675,8 @@ export const registerRoutes = async (permissionService,licenseService,pkiSyncQueue,+ pkiSyncHealthCheckQueue,+ auditLogService,kmsService});@@ -3906,7 +3908,7 @@ export const registerRoutes = async (alertQueue.init();auditLogStreamOutboxQueue.init();pkiSyncCleanup.init();- pkiSyncPreflightQueue.init();+ pkiSyncHealthCheckQueue.init();pamDiscoveryService.init();pkiDiscoveryQueue.startPkiDiscoveryScanQueue();dailyReminderQueueService.startDailyRemindersJob();diff --git a/backend/src/server/routes/v1/pki-sync-routers/aws-certificate-manager-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/aws-certificate-manager-pki-sync-router.tsindex 05e60397de..1002d55233 100644--- a/backend/src/server/routes/v1/pki-sync-routers/aws-certificate-manager-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/aws-certificate-manager-pki-sync-router.ts@@ -20,7 +20,8 @@ export const registerAwsCertificateManagerPkiSyncRouter = async (updateSchema: UpdateAwsCertificateManagerPkiSyncSchema,syncOptions: {canImportCertificates: AWS_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: AWS_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: AWS_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: AWS_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/aws-elastic-load-balancer-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/aws-elastic-load-balancer-pki-sync-router.tsindex 552801b5ba..0084d9d331 100644--- a/backend/src/server/routes/v1/pki-sync-routers/aws-elastic-load-balancer-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/aws-elastic-load-balancer-pki-sync-router.ts@@ -28,7 +28,8 @@ export const registerAwsElasticLoadBalancerPkiSyncRouter = async (updateSchema: UpdateAwsElasticLoadBalancerPkiSyncSchema,syncOptions: {canImportCertificates: AWS_ELASTIC_LOAD_BALANCER_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: AWS_ELASTIC_LOAD_BALANCER_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: AWS_ELASTIC_LOAD_BALANCER_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: AWS_ELASTIC_LOAD_BALANCER_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/aws-secrets-manager-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/aws-secrets-manager-pki-sync-router.tsindex dd16000b75..a07d2e09f3 100644--- a/backend/src/server/routes/v1/pki-sync-routers/aws-secrets-manager-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/aws-secrets-manager-pki-sync-router.ts@@ -20,7 +20,8 @@ export const registerAwsSecretsManagerPkiSyncRouter = async (updateSchema: UpdateAwsSecretsManagerPkiSyncSchema,syncOptions: {canImportCertificates: AWS_SECRETS_MANAGER_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: AWS_SECRETS_MANAGER_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: AWS_SECRETS_MANAGER_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: AWS_SECRETS_MANAGER_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/azure-key-vault-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/azure-key-vault-pki-sync-router.tsindex 16a7c89c42..08c518563f 100644--- a/backend/src/server/routes/v1/pki-sync-routers/azure-key-vault-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/azure-key-vault-pki-sync-router.ts@@ -20,7 +20,8 @@ export const registerAzureKeyVaultPkiSyncRouter = async (updateSchema: UpdateAzureKeyVaultPkiSyncSchema,syncOptions: {canImportCertificates: AZURE_KEY_VAULT_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: AZURE_KEY_VAULT_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: AZURE_KEY_VAULT_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: AZURE_KEY_VAULT_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/chef-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/chef-pki-sync-router.tsindex 486e5411b1..fe7cb52fc9 100644--- a/backend/src/server/routes/v1/pki-sync-routers/chef-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/chef-pki-sync-router.ts@@ -1,4 +1,5 @@import { ChefPkiSyncSchema, CreateChefPkiSyncSchema, UpdateChefPkiSyncSchema } from "@app/services/pki-sync/chef";+import { CHEF_PKI_SYNC_LIST_OPTION } from "@app/services/pki-sync/chef/chef-pki-sync-list-constants";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";import { registerSyncPkiEndpoints } from "./pki-sync-endpoints";@@ -11,8 +12,9 @@ export const registerChefPkiSyncRouter = async (server: FastifyZodProvider, enabcreateSchema: CreateChefPkiSyncSchema,updateSchema: UpdateChefPkiSyncSchema,syncOptions: {- canImportCertificates: false,- canRemoveCertificates: true+ canImportCertificates: CHEF_PKI_SYNC_LIST_OPTION.canImportCertificates,+ canRemoveCertificates: CHEF_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: CHEF_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/cloudflare-custom-certificate-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/cloudflare-custom-certificate-pki-sync-router.tsindex c43bb9c83b..fa899c41ef 100644--- a/backend/src/server/routes/v1/pki-sync-routers/cloudflare-custom-certificate-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/cloudflare-custom-certificate-pki-sync-router.ts@@ -20,7 +20,8 @@ export const registerCloudflareCustomCertificatePkiSyncRouter = async (updateSchema: UpdateCloudflareCustomCertificatePkiSyncSchema,syncOptions: {canImportCertificates: CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/f5-big-ip-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/f5-big-ip-pki-sync-router.tsindex ee14e0c1fa..a7c3934767 100644--- a/backend/src/server/routes/v1/pki-sync-routers/f5-big-ip-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/f5-big-ip-pki-sync-router.ts@@ -17,7 +17,8 @@ export const registerF5BigIpPkiSyncRouter = async (server: FastifyZodProvider, eupdateSchema: UpdateF5BigIpPkiSyncSchema,syncOptions: {canImportCertificates: F5_BIG_IP_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: F5_BIG_IP_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: F5_BIG_IP_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: F5_BIG_IP_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/kemp-loadmaster-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/kemp-loadmaster-pki-sync-router.tsindex 3d7cad4b2e..cc728be7af 100644--- a/backend/src/server/routes/v1/pki-sync-routers/kemp-loadmaster-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/kemp-loadmaster-pki-sync-router.ts@@ -25,7 +25,8 @@ export const registerKempLoadMasterPkiSyncRouter = async (updateSchema: UpdateKempLoadMasterPkiSyncSchema,syncOptions: {canImportCertificates: KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/linux-server-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/linux-server-pki-sync-router.tsindex b8a9b2ca96..5c7bdddf4d 100644--- a/backend/src/server/routes/v1/pki-sync-routers/linux-server-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/linux-server-pki-sync-router.ts@@ -1,6 +1,7 @@import {CreateLinuxServerPkiSyncSchema,LINUX_SERVER_PKI_SYNC_LIST_OPTION,+ LinuxServerPkiSyncHealthCheckTestSchema,LinuxServerPkiSyncSchema,UpdateLinuxServerPkiSyncSchema} from "@app/services/pki-sync/linux-server";@@ -15,9 +16,11 @@ export const registerLinuxServerPkiSyncRouter = async (server: FastifyZodProvideresponseSchema: LinuxServerPkiSyncSchema,createSchema: CreateLinuxServerPkiSyncSchema,updateSchema: UpdateLinuxServerPkiSyncSchema,+ healthCheckTestSchema: LinuxServerPkiSyncHealthCheckTestSchema,syncOptions: {canImportCertificates: LINUX_SERVER_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: LINUX_SERVER_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: LINUX_SERVER_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: LINUX_SERVER_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/netscaler-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/netscaler-pki-sync-router.tsindex 722a26e784..31f6969944 100644--- a/backend/src/server/routes/v1/pki-sync-routers/netscaler-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/netscaler-pki-sync-router.ts@@ -17,7 +17,8 @@ export const registerNetScalerPkiSyncRouter = async (server: FastifyZodProvider,updateSchema: UpdateNetScalerPkiSyncSchema,syncOptions: {canImportCertificates: NETSCALER_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: NETSCALER_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: NETSCALER_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: NETSCALER_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/nutanix-prism-central-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/nutanix-prism-central-pki-sync-router.tsindex 3c9bee052a..f141fcd305 100644--- a/backend/src/server/routes/v1/pki-sync-routers/nutanix-prism-central-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/nutanix-prism-central-pki-sync-router.ts@@ -20,7 +20,8 @@ export const registerNutanixPrismCentralPkiSyncRouter = async (updateSchema: UpdateNutanixPrismCentralPkiSyncSchema,syncOptions: {canImportCertificates: NUTANIX_PRISM_CENTRAL_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: NUTANIX_PRISM_CENTRAL_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: NUTANIX_PRISM_CENTRAL_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: NUTANIX_PRISM_CENTRAL_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.tsindex 3597b82a5d..d38620d0d4 100644--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts@@ -7,7 +7,7 @@ import { openApiHidden } from "@app/server/lib/schemas";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";-import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";+import { PkiSync, PkiSyncStatus } from "@app/services/pki-sync/pki-sync-enums";import { PKI_SYNC_NAME_MAP } from "@app/services/pki-sync/pki-sync-maps";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";@@ -18,6 +18,7 @@ export const registerSyncPkiEndpoints = ({updateSchema,responseSchema,syncOptions,+ healthCheckTestSchema,enableOperationId = true}: {destination: PkiSync;@@ -43,10 +44,19 @@ export const registerSyncPkiEndpoints = ({isAutoSyncEnabled?: boolean;subscriberId?: string | null;}>;+ healthCheckTestSchema?: z.ZodType<{+ connectionId: string;+ applicationId?: string;+ syncId?: string;+ name?: string;+ destinationConfig: Record<string, unknown>;+ syncOptions: Record<string, unknown>;+ }>;responseSchema: z.ZodTypeAny;syncOptions: {canImportCertificates: boolean;canRemoveCertificates: boolean;+ canRunHealthCheckCommand: boolean;};enableOperationId?: boolean;}) => {@@ -171,7 +181,7 @@ export const registerSyncPkiEndpoints = ({connectionId: pkiSync.connectionId,hasCredentials: Boolean(req.body.credentials?.exportPassword),hasPostSyncCommand: Boolean(req.body.syncOptions?.postSyncCommand),- hasPreflightCommand: Boolean(req.body.syncOptions?.preflightCommand),+ hasHealthCheckCommand: Boolean(req.body.syncOptions?.healthCheckCommand),...(pkiSync.applicationId && { applicationId: pkiSync.applicationId })}}@@ -228,7 +238,7 @@ export const registerSyncPkiEndpoints = ({name: pkiSync.name,...(pkiSync.applicationId && { applicationId: pkiSync.applicationId }),hasPostSyncCommand: Boolean(pkiSync.syncOptions?.postSyncCommand),- hasPreflightCommand: Boolean(pkiSync.syncOptions?.preflightCommand)+ hasHealthCheckCommand: Boolean(pkiSync.syncOptions?.healthCheckCommand)}}});@@ -302,6 +312,87 @@ export const registerSyncPkiEndpoints = ({}});+ const HealthCheckResponseSchema = z.object({+ healthCheck: z.object({+ status: z.nativeEnum(PkiSyncStatus),+ exitCode: z.number().optional(),+ timedOut: z.boolean().optional(),+ durationMs: z.number(),+ output: z.string().optional(),+ failureDetail: z.string().optional(),+ message: z.string().optional()+ })+ });++ if (syncOptions.canRunHealthCheckCommand && healthCheckTestSchema) {+ server.route({+ method: "POST",+ url: "/test-health-check",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ hide: false,+ ...(enableOperationId ? { operationId: `test${destinationNameForOpId}PkiSyncHealthCheck` } : {}),+ tags: [ApiDocsTags.PkiSyncs],+ description: `Run a health check command against a ${destinationName} host without saving it to a sync.`,+ body: healthCheckTestSchema,+ response: {+ 200: HealthCheckResponseSchema+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const healthCheck = await server.services.pkiSync.testPkiSyncHealthCheckCommand(+ {+ destination,+ connectionId: req.body.connectionId,+ applicationId: req.body.applicationId,+ syncId: req.body.syncId,+ name: req.body.name,+ destinationConfig: req.body.destinationConfig,+ syncOptions: req.body.syncOptions,+ projectId: req.internalCertManagerProjectId+ },+ req.permission,+ req.auditLogInfo+ );++ return { healthCheck };+ }+ });++ server.route({+ method: "POST",+ url: "/:pkiSyncId/run-health-check",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ hide: false,+ ...(enableOperationId ? { operationId: `run${destinationNameForOpId}PkiSyncHealthCheck` } : {}),+ tags: [ApiDocsTags.PkiSyncs],+ description: `Run the configured health check for the specified ${destinationName} PKI Sync without delivering certificates.`,+ params: z.object({+ pkiSyncId: z.string().uuid()+ }),+ response: {+ 200: HealthCheckResponseSchema+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const healthCheck = await server.services.pkiSync.runPkiSyncHealthCheckById(+ { id: req.params.pkiSyncId },+ req.permission,+ req.auditLogInfo+ );++ return { healthCheck };+ }+ });+ }+server.route({method: "POST",url: "/:pkiSyncId/sync",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 21b64455c3..e22b461397 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@@ -9,7 +9,7 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enumsimport { AuthMode } from "@app/services/auth/auth-type";import { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums";import { SyncMetadataSchema } from "@app/services/certificate-sync/certificate-sync-schemas";-import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";+import { PkiSync, PkiSyncStatus } from "@app/services/pki-sync/pki-sync-enums";export const PkiSyncSchema = z.object({id: z.string().uuid(),@@ -30,6 +30,9 @@ export const PkiSyncSchema = z.object({lastSyncJobId: z.string().nullable().optional(),lastSyncMessage: z.string().nullable().optional(),lastSyncedAt: z.date().nullable().optional(),+ lastHealthCheckRanAt: z.date().nullable().optional(),+ lastHealthCheckStatus: z.nativeEnum(PkiSyncStatus).nullable().optional(),+ lastHealthCheckMessage: z.string().nullable().optional(),// Import status fieldsimportStatus: z.string().nullable().optional(),lastImportJobId: z.string().nullable().optional(),@@ -75,7 +78,7 @@ const PkiSyncOptionsSchema = z.object({canImportCertificates: z.boolean(),canRemoveCertificates: z.boolean(),canRunPostSyncCommand: z.boolean().optional(),- canRunPreflightCommand: z.boolean().optional(),+ canRunHealthCheckCommand: z.boolean().optional(),maxCertificates: z.number().optional(),defaultCertificateNameSchema: z.string().optional(),forbiddenCharacters: z.string().optional(),diff --git a/backend/src/server/routes/v1/pki-sync-routers/windows-server-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/windows-server-pki-sync-router.tsindex 8029049fff..3f9fb2bce4 100644--- a/backend/src/server/routes/v1/pki-sync-routers/windows-server-pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/windows-server-pki-sync-router.ts@@ -3,6 +3,7 @@ import {CreateWindowsServerPkiSyncSchema,UpdateWindowsServerPkiSyncSchema,WINDOWS_SERVER_PKI_SYNC_LIST_OPTION,+ WindowsServerPkiSyncHealthCheckTestSchema,WindowsServerPkiSyncSchema} from "@app/services/pki-sync/windows-server";@@ -18,9 +19,11 @@ export const registerWindowsServerPkiSyncRouter = async (responseSchema: WindowsServerPkiSyncSchema,createSchema: CreateWindowsServerPkiSyncSchema,updateSchema: UpdateWindowsServerPkiSyncSchema,+ healthCheckTestSchema: WindowsServerPkiSyncHealthCheckTestSchema,syncOptions: {canImportCertificates: WINDOWS_SERVER_PKI_SYNC_LIST_OPTION.canImportCertificates,- canRemoveCertificates: WINDOWS_SERVER_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ canRemoveCertificates: WINDOWS_SERVER_PKI_SYNC_LIST_OPTION.canRemoveCertificates,+ canRunHealthCheckCommand: WINDOWS_SERVER_PKI_SYNC_LIST_OPTION.canRunHealthCheckCommand},enableOperationId});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 3e5a52f761..67ebbbc029 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@@ -45,7 +45,7 @@ export const AWS_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: false,- canRunPreflightCommand: false,+ canRunHealthCheckCommand: 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 5cb658409b..6806da8ec2 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@@ -18,7 +18,7 @@ const AwsCertificateManagerPkiSyncOptionsSchema = z.object({canRemoveCertificates: z.boolean().default(true),includeRootCa: z.boolean().default(false),preserveArn: z.boolean().default(true),- preflightCommand: HostCommandSchema,+ healthCheckCommand: HostCommandSchema,postSyncCommand: HostCommandSchema,certificateNameSchema: z.string()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 c6ad0803a4..cef6922510 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@@ -8,5 +8,5 @@ export const AWS_ELASTIC_LOAD_BALANCER_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: false,- canRunPreflightCommand: false+ canRunHealthCheckCommand: 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 fd9eb8b26d..50b4e3cd95 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@@ -27,7 +27,7 @@ const AwsElasticLoadBalancerPkiSyncOptionsSchema = z.object({preserveArn: z.boolean().default(true),includeRootCa: z.boolean().default(false),certificateNameSchema: z.string().optional(),- preflightCommand: HostCommandSchema,+ healthCheckCommand: HostCommandSchema,postSyncCommand: HostCommandSchema});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 4f1fd84c6e..a93028691e 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@@ -63,7 +63,7 @@ export const AWS_SECRETS_MANAGER_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: false,- canRunPreflightCommand: false,+ canRunHealthCheckCommand: 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 f18a684e4a..ac88ed4205 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@@ -27,7 +27,7 @@ const AwsSecretsManagerPkiSyncOptionsSchema = z.object({includeRootCa: z.boolean().default(false),preserveSecretOnRenewal: z.boolean().default(true),updateExistingCertificates: z.boolean().default(true),- preflightCommand: HostCommandSchema,+ healthCheckCommand: HostCommandSchema,postSyncCommand: HostCommandSchema,certificateNameSchema: z.string()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 13dcc5ae38..4965fd292a 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@@ -45,7 +45,7 @@ export const AZURE_KEY_VAULT_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: false,- canRunPreflightCommand: false,+ canRunHealthCheckCommand: 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 e601661395..a9df266aaa 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@@ -21,7 +21,7 @@ export const AzureKeyVaultPkiSyncOptionsSchema = z.object({canRemoveCertificates: z.boolean().default(true),includeRootCa: z.boolean().default(false),enableVersioning: z.boolean().default(true),- preflightCommand: HostCommandSchema,+ healthCheckCommand: HostCommandSchema,postSyncCommand: HostCommandSchema,certificateNameSchema: z.string()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 0e48955a3e..e0f7967057 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@@ -8,5 +8,5 @@ export const CHEF_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: false,- canRunPreflightCommand: false+ canRunHealthCheckCommand: 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 fcc92108ca..1279de613c 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@@ -45,7 +45,7 @@ export const CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: false,- canRunPreflightCommand: false,+ canRunHealthCheckCommand: 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 3c8f50f02e..53296150e0 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@@ -16,7 +16,7 @@ export const CloudflareCustomCertificatePkiSyncConfigSchema = z.object({// API-facing schema - only exposes user-configurable optionsexport const CloudflareCustomCertificatePkiSyncOptionsSchema = z.object({canRemoveCertificates: z.boolean().default(true),- preflightCommand: HostCommandSchema,+ healthCheckCommand: HostCommandSchema,postSyncCommand: HostCommandSchema,certificateNameSchema: z.string()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 8d6fce081c..463221f9ef 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@@ -31,7 +31,7 @@ export const F5_BIG_IP_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: false,- canRunPreflightCommand: false,+ canRunHealthCheckCommand: 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 6899a82d73..9098305ff5 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@@ -24,7 +24,7 @@ export const KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: false,- canRunPreflightCommand: false,+ canRunHealthCheckCommand: 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 ec5a9b11f0..a51738087d 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@@ -23,7 +23,7 @@ export const LINUX_SERVER_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: true,- canRunPreflightCommand: true,+ canRunHealthCheckCommand: 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 ad6b74a139..4286e25e54 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@@ -17,6 +17,14 @@ import { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-simport { PkiSyncError } from "../pki-sync-errors";import { exportCertificateForSync, PemCertificateExtension, PkiSyncExportFormat } from "../pki-sync-export-fns";+import {+ buildHealthCheckCommandFailureMessage,+ buildHealthCheckCommandPlan,+ buildHealthCheckFailureSyncResult,+ didHealthCheckFail,+ runHealthCheckCommand,+ THealthCheckCommandResult+} from "../pki-sync-health-check-command-fns";import {HOST_COMMAND_TIMEOUT_MS,HostCommandKind,@@ -25,15 +33,7 @@ import {toPosixShellLiteral} from "../pki-sync-host-command-fns";import { buildPostSyncCommandPlan, runPostSyncCommand, TPostSyncCommandPlan } from "../pki-sync-post-sync-command-fns";-import {- buildPreflightCommandFailureMessage,- buildPreflightCommandPlan,- buildPreflightFailureSyncResult,- didPreflightCheckFail,- runPreflightCommand,- TPreflightCommandResult-} from "../pki-sync-preflight-command-fns";-import { TCertificateMap, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "../pki-sync-types";+import { TCertificateMap, THealthCheckTarget, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "../pki-sync-types";import { TLinuxServerPkiSyncConfig } from "./linux-server-pki-sync-types";type TLinuxServerPkiSyncFactoryDeps = {@@ -56,11 +56,11 @@ type TLinuxServerSyncOptions = {privateKeyFileMode?: string;owner?: string;group?: string;- preflightCommand?: string;+ healthCheckCommand?: string;postSyncCommand?: string;};-const buildSshConfig = (pkiSync: TPkiSyncWithCredentials): TSshConnectionConfig => {+const buildSshConfig = (pkiSync: THealthCheckTarget): TSshConnectionConfig => {const { connection } = pkiSync;const credentials = connection.credentials as { privateKey?: string };@@ -252,21 +252,21 @@ const executeLinuxServerHostCommand = (timeoutMs: HOST_COMMAND_TIMEOUT_MS[kind]});-const runLinuxServerPreflightCommand = ({+const runLinuxServerHealthCheckCommand = ({pkiSync,certificateMap,gatewayServices}: {- pkiSync: TPkiSyncWithCredentials;+ pkiSync: THealthCheckTarget;certificateMap: TCertificateMap;gatewayServices: Pick<TLinuxServerPkiSyncFactoryDeps, "gatewayV2Service" | "gatewayPoolService">;-}): Promise<TPreflightCommandResult> | undefined => {+}): Promise<THealthCheckCommandResult> | undefined => {const options = (pkiSync.syncOptions ?? {}) as TLinuxServerSyncOptions;const config = pkiSync.destinationConfig as TLinuxServerPkiSyncConfig;const exportOptions = resolveLinuxExportOptions(options);- const plan = buildPreflightCommandPlan({- command: options.preflightCommand,+ const plan = buildHealthCheckCommandPlan({+ command: options.healthCheckCommand,destinationDirectory: config.destinationPath,certificateMap,exportOptions,@@ -276,11 +276,11 @@ const runLinuxServerPreflightCommand = ({});if (!plan) return undefined;- return runPreflightCommand({+ return runHealthCheckCommand({syncId: pkiSync.id,secretsToRedact: [plan.context.pkcs12Password],execute: () =>- executeLinuxServerHostCommand(HostCommandKind.Preflight, plan, buildSshConfig(pkiSync), gatewayServices)+ executeLinuxServerHostCommand(HostCommandKind.HealthCheck, plan, buildSshConfig(pkiSync), gatewayServices)});};@@ -331,16 +331,16 @@ export const linuxServerPkiSyncFactory = ({const sshConfig = buildSshConfig(pkiSync);- const preflightCheck = await runLinuxServerPreflightCommand({+ const healthCheck = await runLinuxServerHealthCheckCommand({pkiSync,certificateMap,gatewayServices: { gatewayV2Service, gatewayPoolService }});- if (preflightCheck && didPreflightCheckFail(preflightCheck)) {+ if (healthCheck && didHealthCheckFail(healthCheck)) {logger.info(- `Linux Server PKI sync [syncId=${pkiSync.id}]: preflight check failed, delivered nothing (${buildPreflightCommandFailureMessage(preflightCheck)})`+ `Linux Server PKI sync [syncId=${pkiSync.id}]: health check failed, delivered nothing (${buildHealthCheckCommandFailureMessage(healthCheck)})`);- return buildPreflightFailureSyncResult(certificateMap, preflightCheck);+ return buildHealthCheckFailureSyncResult(certificateMap, healthCheck);}await withSshConnection(sshConfig, { gatewayV2Service, gatewayPoolService }, async (client) => {@@ -463,7 +463,7 @@ export const linuxServerPkiSyncFactory = ({removed: removed > 0 ? removed : undefined,failedRemovals: failedRemovals.length > 0 ? failedRemovals.length : undefined,skipped: skippedCertificates.length,- preflightCheck,+ healthCheck,postSyncCommand,details: {failedUploads: failedUploads.length > 0 ? failedUploads : undefined,@@ -520,12 +520,12 @@ export const linuxServerPkiSyncFactory = ({}};- const runPreflightCheck = (pkiSync: TPkiSyncWithCredentials, certificateMap: TCertificateMap) =>- runLinuxServerPreflightCommand({+ const runHealthCheck = (pkiSync: THealthCheckTarget, certificateMap: TCertificateMap) =>+ runLinuxServerHealthCheckCommand({pkiSync,certificateMap,gatewayServices: { gatewayV2Service, gatewayPoolService }});- return { syncCertificates, removeCertificates, runPreflightCheck };+ return { syncCertificates, removeCertificates, runHealthCheck };};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 24388b693e..d317734234 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@@ -57,7 +57,7 @@ export const LinuxServerPkiSyncOptionsSchema = z.object({.max(32).refine((v) => POSIX_NAME.test(v), { message: "Group must be a valid Linux group name" }).optional(),- preflightCommand: HostCommandSchema,+ healthCheckCommand: HostCommandSchema,postSyncCommand: HostCommandSchema,certificateNameSchema: z.string()@@ -131,3 +131,12 @@ export const LinuxServerPkiSyncListItemSchema = z.object({canImportCertificates: z.literal(false),canRemoveCertificates: z.literal(true)});++export const LinuxServerPkiSyncHealthCheckTestSchema = z.object({+ connectionId: z.string().uuid(),+ applicationId: z.string().uuid().optional(),+ syncId: z.string().uuid().optional(),+ name: z.string().trim().max(256).optional(),+ destinationConfig: LinuxServerPkiSyncConfigSchema,+ syncOptions: LinuxServerPkiSyncOptionsSchema.partial()+});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 65961b1251..505498d2f3 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@@ -23,7 +23,7 @@ export const NETSCALER_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: false,- canRunPreflightCommand: false,+ canRunHealthCheckCommand: 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 c84465eeeb..d1a4e08aac 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@@ -8,6 +8,6 @@ export const NUTANIX_PRISM_CENTRAL_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: false,canRunPostSyncCommand: false,- canRunPreflightCommand: false,+ canRunHealthCheckCommand: 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 0cd575e7db..c012b10bce 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@@ -14,7 +14,7 @@ export const NutanixPrismCentralPkiSyncConfigSchema = z.object({export const NutanixPrismCentralPkiSyncOptionsSchema = z.object({canImportCertificates: z.literal(false).default(false),canRemoveCertificates: z.literal(false).default(false),- preflightCommand: HostCommandSchema,+ healthCheckCommand: HostCommandSchema,postSyncCommand: HostCommandSchema});diff --git a/backend/src/services/pki-sync/pki-sync-certificate-map-fns.ts b/backend/src/services/pki-sync/pki-sync-certificate-map-fns.tsindex aabd92923c..dc025fd315 100644--- a/backend/src/services/pki-sync/pki-sync-certificate-map-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-certificate-map-fns.ts@@ -227,7 +227,6 @@ export const buildCertificateMap = async ({ error, subscriberId, certificateId: certificate.id },"Failed to decrypt certificate for PKI sync");- // Continue with other certificates}}} catch (error) {diff --git a/backend/src/services/pki-sync/pki-sync-credentials-fns.ts b/backend/src/services/pki-sync/pki-sync-credentials-fns.tsindex a98359a7da..8248672e7b 100644--- a/backend/src/services/pki-sync/pki-sync-credentials-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-credentials-fns.ts@@ -31,7 +31,7 @@ export const encryptPkiSyncCredentials = async ({return cipherTextBlob;};-export const decryptPkiSyncCredentials = async ({+const decryptPkiSyncCredentials = async ({orgId,projectId,encryptedCredentials,diff --git a/backend/src/services/pki-sync/pki-sync-dal.ts b/backend/src/services/pki-sync/pki-sync-dal.tsindex 567bdce2b1..46ef2a91cb 100644--- a/backend/src/services/pki-sync/pki-sync-dal.ts+++ b/backend/src/services/pki-sync/pki-sync-dal.ts@@ -331,58 +331,81 @@ export const pkiSyncDALFactory = (db: TDbClient) => {}};- const reportPreflightFailure = async (syncId: string, message: string, failurePrefix: string) => {+ const recordHealthCheckOutcome = async (+ syncId: string,+ outcome: { status: PkiSyncStatus.Succeeded | PkiSyncStatus.Failed; message: string | null; ranAt: Date },+ tx?: Knex+ ) => {+ try {+ return await (tx || db)(TableName.PkiSync).where({ id: syncId }).update({+ lastHealthCheckRanAt: outcome.ranAt,+ lastHealthCheckStatus: outcome.status,+ lastHealthCheckMessage: outcome.message+ });+ } catch (error) {+ throw new DatabaseError({ error, name: "Record health check outcome - PKI Sync" });+ }+ };++ const $whereMessageStartsWithAny = (builder: Knex.QueryBuilder, prefixes: string[]) => {+ prefixes.forEach((prefix) => {+ void builder.orWhereRaw(`left("lastSyncMessage", ?) = ?`, [prefix.length, prefix]);+ });+ };++ const reportHealthCheckFailure = async (syncId: string, message: string, failurePrefixes: string[], tx?: Knex) => {try {- return await db(TableName.PkiSync)+ return await (tx || db)(TableName.PkiSync).where({ id: syncId }).where((builder) => {- // eslint-disable-next-line @typescript-eslint/no-misused-promises- void builder- .whereNull("lastSyncMessage")- .orWhereRaw(`left("lastSyncMessage", ?) = ?`, [failurePrefix.length, failurePrefix]);+ void builder.whereNull("lastSyncMessage");+ $whereMessageStartsWithAny(builder, failurePrefixes);}).update({ syncStatus: PkiSyncStatus.Failed, lastSyncMessage: message });} catch (error) {- throw new DatabaseError({ error, name: "Report preflight failure - PKI Sync" });+ throw new DatabaseError({ error, name: "Report health check failure - PKI Sync" });}};- const clearReportedPreflightFailure = async (syncId: string, failurePrefix: string) => {+ const clearReportedHealthCheckFailure = async (syncId: string, failurePrefixes: string[], tx?: Knex) => {+ const knex = tx || db;+try {- return await db(TableName.PkiSync)+ return await knex(TableName.PkiSync).where({ id: syncId })- .whereRaw(`left("lastSyncMessage", ?) = ?`, [failurePrefix.length, failurePrefix])+ .where((builder) => $whereMessageStartsWithAny(builder, failurePrefixes)).update({- syncStatus: db.raw(`CASE WHEN "lastSyncedAt" IS NULL THEN ? ELSE ? END`, [+ syncStatus: knex.raw(`CASE WHEN "lastSyncedAt" IS NULL THEN ? ELSE ? END`, [PkiSyncStatus.Pending,PkiSyncStatus.Succeeded]) as unknown as string,lastSyncMessage: null});} catch (error) {- throw new DatabaseError({ error, name: "Clear reported preflight failure - PKI Sync" });+ throw new DatabaseError({ error, name: "Clear reported health check failure - PKI Sync" });}};- const findPkiSyncsWithPreflightCommand = async () => {+ const findPkiSyncsWithHealthCheckCommand = async () => {try {return (await db.replicaNode()(TableName.PkiSync).join(TableName.Project, `${TableName.PkiSync}.projectId`, `${TableName.Project}.id`).whereNull(`${TableName.Project}.deleteAfter`).select(`${TableName.PkiSync}.id`, `${TableName.PkiSync}.destination`)- .whereRaw(`("${TableName.PkiSync}"."syncOptions" ->> 'preflightCommand') IS NOT NULL`)+ .whereRaw(`("${TableName.PkiSync}"."syncOptions" ->> 'healthCheckCommand') IS NOT NULL`).orderBy(`${TableName.PkiSync}.createdAt`, "asc")) as Array<{ id: string; destination: string }>;} catch (error) {- throw new DatabaseError({ error, name: "Find PKI syncs with a preflight command" });+ throw new DatabaseError({ error, name: "Find PKI syncs with a healthCheck command" });}};return {...pkiSyncOrm,- reportPreflightFailure,- clearReportedPreflightFailure,- findPkiSyncsWithPreflightCommand,+ recordHealthCheckOutcome,+ reportHealthCheckFailure,+ clearReportedHealthCheckFailure,+ findPkiSyncsWithHealthCheckCommand,findByProjectId,findByProjectIdWithSubscribers,findBySubscriberId,diff --git a/backend/src/services/pki-sync/pki-sync-enums.ts b/backend/src/services/pki-sync/pki-sync-enums.tsindex 30937322a9..d4fd78d3fc 100644--- a/backend/src/services/pki-sync/pki-sync-enums.ts+++ b/backend/src/services/pki-sync/pki-sync-enums.ts@@ -27,3 +27,7 @@ export enum PkiSyncAction {}export const PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT = 3;++export const PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S = 15 * 60;++export const PKI_SYNC_CONNECTION_LOCK_RETRY = { retryCount: 10, retryDelay: 3_000, retryJitter: 500 };diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.tsindex 042df96a71..a81fbe8dda 100644--- a/backend/src/services/pki-sync/pki-sync-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.ts@@ -40,7 +40,7 @@ import {import { PkiSync } from "./pki-sync-enums";import { PkiSyncError } from "./pki-sync-errors";import { THostCommandResult } from "./pki-sync-host-command-fns";-import { TCertificateMap, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "./pki-sync-types";+import { TCertificateMap, THealthCheckTarget, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "./pki-sync-types";import { WINDOWS_SERVER_PKI_SYNC_LIST_OPTION } from "./windows-server/windows-server-pki-sync-constants";import { windowsServerPkiSyncFactory } from "./windows-server/windows-server-pki-sync-fns";@@ -90,7 +90,7 @@ export const getPkiSyncProviderCapabilities = (destination: PkiSync) => {canImportCertificates: providerOption.canImportCertificates,canRemoveCertificates: providerOption.canRemoveCertificates,canRunPostSyncCommand: providerOption.canRunPostSyncCommand,- canRunPreflightCommand: providerOption.canRunPreflightCommand+ canRunHealthCheckCommand: providerOption.canRunHealthCheckCommand};};@@ -345,8 +345,8 @@ export const PkiSyncFns = {}},- runPreflightCheck: async (- pkiSync: TPkiSyncWithCredentials,+ runHealthCheck: async (+ pkiSync: THealthCheckTarget,certificateMap: TCertificateMap,dependencies: {certificateSyncDAL: TCertificateSyncDALFactory;@@ -361,7 +361,7 @@ export const PkiSyncFns = {gatewayV2Service: dependencies.gatewayV2Service,gatewayPoolService: dependencies.gatewayPoolService});- return linuxServerPkiSync.runPreflightCheck(pkiSync, certificateMap);+ return linuxServerPkiSync.runHealthCheck(pkiSync, certificateMap);}case PkiSync.WindowsServer: {if (!dependencies.gatewayV2Service) {@@ -375,7 +375,7 @@ export const PkiSyncFns = {gatewayV2Service: dependencies.gatewayV2Service,gatewayPoolService: dependencies.gatewayPoolService});- return windowsServerPkiSync.runPreflightCheck(pkiSync, certificateMap);+ return windowsServerPkiSync.runHealthCheck(pkiSync, certificateMap);}default:return undefined;diff --git a/backend/src/services/pki-sync/pki-sync-preflight-command-fns.test.ts b/backend/src/services/pki-sync/pki-sync-health-check-command-fns.test.tssimilarity index 67%rename from backend/src/services/pki-sync/pki-sync-preflight-command-fns.test.tsrename to backend/src/services/pki-sync/pki-sync-health-check-command-fns.test.tsindex 75dd0942dc..4290718f86 100644--- a/backend/src/services/pki-sync/pki-sync-preflight-command-fns.test.ts+++ b/backend/src/services/pki-sync/pki-sync-health-check-command-fns.test.ts@@ -2,6 +2,18 @@ import { describe, expect, test, vi } from "vitest";import { PkiSyncStatus } from "./pki-sync-enums";import { PemCertificateExtension, PkiSyncExportFormat } from "./pki-sync-export-fns";+import {+ applyHealthCheckCommandUpdate,+ buildHealthCheckCommandFailureMessage,+ buildHealthCheckCommandPlan,+ buildHealthCheckFailureMessageFor,+ buildHealthCheckFailureSyncResult,+ didHealthCheckFail,+ HEALTH_CHECK_COMMAND_TIMEOUT_MS,+ normalizeNewHealthCheckCommand,+ runHealthCheckCommand,+ SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT+} from "./pki-sync-health-check-command-fns";import {HostCommandKind,hostCommandMessageSubject,@@ -10,18 +22,6 @@ import {toPowerShellLiteral} from "./pki-sync-host-command-fns";import { POST_SYNC_COMMAND_TIMEOUT_MS } from "./pki-sync-post-sync-command-fns";-import {- applyPreflightCommandUpdate,- buildPreflightCommandFailureMessage,- buildPreflightCommandPlan,- buildPreflightFailureSyncResult,- buildScheduledPreflightFailureMessage,- didPreflightCheckFail,- normalizeNewPreflightCommand,- PREFLIGHT_COMMAND_TIMEOUT_MS,- runPreflightCommand,- SCHEDULED_PREFLIGHT_MESSAGE_SUBJECT-} from "./pki-sync-preflight-command-fns";import { TCertificateMap } from "./pki-sync-types";vi.mock("@app/lib/logger", () => ({@@ -48,7 +48,7 @@ const twoCertificates: TCertificateMap = {};const planFor = (command: string, certificateMap: TCertificateMap, overrides = {}) =>- buildPreflightCommandPlan({+ buildHealthCheckCommandPlan({command,destinationDirectory: "/etc/ssl/certs",certificateMap,@@ -57,17 +57,17 @@ const planFor = (command: string, certificateMap: TCertificateMap, overrides = {...overrides});-describe("preflight check timeout", () => {+describe("health check timeout", () => {test("is much shorter than a post-sync command, because it gates delivery", () => {- expect(PREFLIGHT_COMMAND_TIMEOUT_MS).toBeLessThan(POST_SYNC_COMMAND_TIMEOUT_MS);+ expect(HEALTH_CHECK_COMMAND_TIMEOUT_MS).toBeLessThan(POST_SYNC_COMMAND_TIMEOUT_MS);});});-describe("buildPreflightCommandPlan", () => {+describe("buildHealthCheckCommandPlan", () => {test("returns undefined when no check is configured", () => {expect(planFor("", oneCertificate)).toBeUndefined();expect(- buildPreflightCommandPlan({+ buildHealthCheckCommandPlan({command: undefined,destinationDirectory: "/etc/ssl/certs",certificateMap: oneCertificate,@@ -119,7 +119,7 @@ describe("buildPreflightCommandPlan", () => {});test("uses the destination's own path separator", () => {- const plan = buildPreflightCommandPlan({+ const plan = buildHealthCheckCommandPlan({command: "Test-Path {{certificatePath}}",destinationDirectory: "C:\\certs",certificateMap: oneCertificate,@@ -193,31 +193,31 @@ describe("renderHostCommandContext", () => {});});-describe("runPreflightCommand", () => {+describe("runHealthCheckCommand", () => {test("reports success on exit code 0", async () => {- const result = await runPreflightCommand({+ const result = await runHealthCheckCommand({syncId: "sync-1",execute: async () => ({ stdout: "active", stderr: "", exitCode: 0 })});expect(result.status).toBe(PkiSyncStatus.Succeeded);expect(result.output).toBe("active");- expect(didPreflightCheckFail(result)).toBe(false);+ expect(didHealthCheckFail(result)).toBe(false);});test("reports failure on a non-zero exit code without throwing", async () => {- const result = await runPreflightCommand({+ const result = await runHealthCheckCommand({syncId: "sync-1",execute: async () => ({ stdout: "", stderr: "inactive", exitCode: 3 })});expect(result.status).toBe(PkiSyncStatus.Failed);expect(result.exitCode).toBe(3);- expect(didPreflightCheckFail(result)).toBe(true);+ expect(didHealthCheckFail(result)).toBe(true);});test("reports failure when the host could not be reached at all", async () => {- const result = await runPreflightCommand({+ const result = await runHealthCheckCommand({syncId: "sync-1",execute: async () => {throw new Error("gateway unreachable");@@ -230,7 +230,7 @@ describe("runPreflightCommand", () => {});test("redacts the export password from captured output", async () => {- const result = await runPreflightCommand({+ const result = await runHealthCheckCommand({syncId: "sync-1",secretsToRedact: ["s3cret"],execute: async () => ({ stdout: "opened with s3cret", stderr: "", exitCode: 0 })@@ -240,7 +240,7 @@ describe("runPreflightCommand", () => {});});-describe("buildPreflightCommandPlan with nothing linked to the sync", () => {+describe("buildHealthCheckCommandPlan with nothing linked to the sync", () => {const base = {destinationDirectory: "/etc/ssl",certificateMap: {} as TCertificateMap,@@ -249,16 +249,16 @@ describe("buildPreflightCommandPlan with nothing linked to the sync", () => {};test("skips a command naming a certificate, which would otherwise check an empty path", () => {- expect(buildPreflightCommandPlan({ ...base, command: "test -f {{certificatePath}}" })).toBeUndefined();- expect(buildPreflightCommandPlan({ ...base, command: "echo {{certificateFiles}}" })).toBeUndefined();- expect(buildPreflightCommandPlan({ ...base, command: "echo {{commonName}}" })).toBeUndefined();+ expect(buildHealthCheckCommandPlan({ ...base, command: "test -f {{certificatePath}}" })).toBeUndefined();+ expect(buildHealthCheckCommandPlan({ ...base, command: "echo {{certificateFiles}}" })).toBeUndefined();+ expect(buildHealthCheckCommandPlan({ ...base, command: "echo {{commonName}}" })).toBeUndefined();});test("still runs a command that names no certificate, since a host check is independent of them", () => {- const plan = buildPreflightCommandPlan({ ...base, command: "systemctl is-active nginx" });+ const plan = buildHealthCheckCommandPlan({ ...base, command: "systemctl is-active nginx" });expect(plan?.command).toBe("systemctl is-active nginx");- const withDirectory = buildPreflightCommandPlan({ ...base, command: "test -w {{certificateDirectory}}" });+ const withDirectory = buildHealthCheckCommandPlan({ ...base, command: "test -w {{certificateDirectory}}" });expect(withDirectory?.context.certificateDirectory).toBe("/etc/ssl");});});@@ -271,67 +271,84 @@ describe("the scheduled check owns a prefix distinct from a sync run's", () => {failureDetail: "nginx is down"};- test("a run's blocked preflight does not match the scheduled prefix, so a later check cannot clear it", () => {- const fromRun = buildPreflightCommandFailureMessage(failure);- expect(fromRun.startsWith(SCHEDULED_PREFLIGHT_MESSAGE_SUBJECT)).toBe(false);+ test("a run's blocked healthCheck does not match the scheduled prefix, so a later check cannot clear it", () => {+ const fromRun = buildHealthCheckCommandFailureMessage(failure);+ expect(fromRun.startsWith(SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT)).toBe(false);});test("the scheduled check's own message matches, so it can take over and clear it", () => {- const fromSchedule = buildScheduledPreflightFailureMessage(failure);- expect(fromSchedule.startsWith(SCHEDULED_PREFLIGHT_MESSAGE_SUBJECT)).toBe(true);+ const fromSchedule = buildHealthCheckFailureMessageFor(SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT, failure);+ expect(fromSchedule.startsWith(SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT)).toBe(true);expect(fromSchedule).toContain("nginx is down");});});-describe("preflight failure messages carry the prefix the DAL matches on", () => {+describe("healthCheck failure messages carry the prefix the DAL matches on", () => {test("every failure shape starts with the prefix, so a check can take over and clear its own status", () => {- const prefix = hostCommandMessageSubject(HostCommandKind.Preflight);+ const prefix = hostCommandMessageSubject(HostCommandKind.HealthCheck);const shapes = [{ status: PkiSyncStatus.Failed as const, exitCode: 3, durationMs: 12, failureDetail: "nginx is down" },{ status: PkiSyncStatus.Failed as const, exitCode: 1, durationMs: 5 },- { status: PkiSyncStatus.Failed as const, durationMs: 15004, error: "command timed out after 10s" }+ {+ status: PkiSyncStatus.Failed as const,+ durationMs: 15004,+ error: "command timed out after 15s",+ timedOut: true+ }];- shapes.forEach((shape) => expect(buildPreflightCommandFailureMessage(shape).startsWith(prefix)).toBe(true));+ shapes.forEach((shape) => expect(buildHealthCheckCommandFailureMessage(shape).startsWith(prefix)).toBe(true));expect("2 certificate(s) failed to sync to the destination".startsWith(prefix)).toBe(false);});});-describe("buildPreflightCommandFailureMessage", () => {+describe("buildHealthCheckCommandFailureMessage", () => {test("names the check, not the post-sync command", () => {expect(- buildPreflightCommandFailureMessage({+ buildHealthCheckCommandFailureMessage({status: PkiSyncStatus.Failed,exitCode: 3,durationMs: 12,failureDetail: "nginx.service is not running"})- ).toBe("Preflight check failed (exit 3): nginx.service is not running");+ ).toBe("Health check failed (exit 3): nginx.service is not running");});test("reports the exit code alone when the check was silent, rather than restating it", () => {expect(- buildPreflightCommandFailureMessage({+ buildHealthCheckCommandFailureMessage({status: PkiSyncStatus.Failed,exitCode: 1,durationMs: 12,error: "Command exited with code 1"})- ).toBe("Preflight check failed (exit 1)");+ ).toBe("Health check failed (exit 1)");});- test("says the check could not run, rather than blaming it, when the host was unreachable", () => {+ test("names the limit when the command ran out of time, so the remedy is to shorten it", () => {expect(- buildPreflightCommandFailureMessage({+ buildHealthCheckCommandFailureMessage({status: PkiSyncStatus.Failed,- durationMs: 10_001,- error: "command timed out after 10s"+ durationMs: 15_004,+ error: "command timed out after 15s",+ timedOut: true})- ).toBe("Preflight check could not run: the destination host could not be reached");+ ).toBe("Health check did not finish within its 15s limit");+ });++ test("says the host could not be reached when the command never started, and leaks no transport detail", () => {+ const message = buildHealthCheckCommandFailureMessage({+ status: PkiSyncStatus.Failed,+ durationMs: 120,+ error: "failed to dial target SSH server: dial tcp 10.0.0.1:22: connect: connection refused"+ });++ expect(message).toBe("Health check could not run: the destination host could not be reached");+ expect(message).not.toContain("dial tcp");});});-describe("buildPreflightFailureSyncResult", () => {+describe("buildHealthCheckFailureSyncResult", () => {const failure = {status: PkiSyncStatus.Failed as const,exitCode: 1,@@ -340,68 +357,68 @@ describe("buildPreflightFailureSyncResult", () => {};test("delivers nothing and reports every certificate as skipped with the reason", () => {- const result = buildPreflightFailureSyncResult(twoCertificates, failure);+ const result = buildHealthCheckFailureSyncResult(twoCertificates, failure);expect(result.uploaded).toBe(0);expect(result.removed).toBeUndefined();expect(result.skipped).toBe(2);expect(result.details?.skippedCertificates).toEqual([- { name: "app.example.com", reason: "Preflight check failed (exit 1): /etc/ssl/certs is missing" },- { name: "api.example.com", reason: "Preflight check failed (exit 1): /etc/ssl/certs is missing" }+ { name: "app.example.com", reason: "Health check failed (exit 1): /etc/ssl/certs is missing" },+ { name: "api.example.com", reason: "Health check failed (exit 1): /etc/ssl/certs is missing" }]);});test("carries the check result so the queue can report and audit it", () => {- expect(buildPreflightFailureSyncResult(oneCertificate, failure).preflightCheck).toBe(failure);+ expect(buildHealthCheckFailureSyncResult(oneCertificate, failure).healthCheck).toBe(failure);});test("a sync with nothing linked still reports the failure", () => {- const result = buildPreflightFailureSyncResult({}, failure);+ const result = buildHealthCheckFailureSyncResult({}, failure);expect(result.skipped).toBe(0);expect(result.details?.skippedCertificates).toEqual([]);- expect(result.preflightCheck).toBe(failure);+ expect(result.healthCheck).toBe(failure);});});-describe("normalizeNewPreflightCommand", () => {+describe("normalizeNewHealthCheckCommand", () => {test("keeps a real command", () => {- expect(normalizeNewPreflightCommand({ preflightCommand: "systemctl is-active nginx" })).toEqual({- preflightCommand: "systemctl is-active nginx"+ expect(normalizeNewHealthCheckCommand({ healthCheckCommand: "systemctl is-active nginx" })).toEqual({+ healthCheckCommand: "systemctl is-active nginx"});});test("drops a blank or absent command, so its presence is the switch", () => {- expect(normalizeNewPreflightCommand({ preflightCommand: "" })).toEqual({});- expect(normalizeNewPreflightCommand({ preflightCommand: null })).toEqual({});- expect(normalizeNewPreflightCommand({ other: true })).toEqual({ other: true });+ expect(normalizeNewHealthCheckCommand({ healthCheckCommand: "" })).toEqual({});+ expect(normalizeNewHealthCheckCommand({ healthCheckCommand: null })).toEqual({});+ expect(normalizeNewHealthCheckCommand({ other: true })).toEqual({ other: true });});});-describe("applyPreflightCommandUpdate", () => {+describe("applyHealthCheckCommandUpdate", () => {const stored = "systemctl is-active nginx";test("an omitted key preserves the stored command", () => {- expect(applyPreflightCommandUpdate({ exportFormat: "pem" }, stored)).toEqual({+ expect(applyHealthCheckCommandUpdate({ exportFormat: "pem" }, stored)).toEqual({exportFormat: "pem",- preflightCommand: stored+ healthCheckCommand: stored});});test("an explicit null or a blank string clears the stored command", () => {- expect(applyPreflightCommandUpdate({ preflightCommand: null }, stored)).toEqual({});- expect(applyPreflightCommandUpdate({ preflightCommand: "" }, stored)).toEqual({});+ expect(applyHealthCheckCommandUpdate({ healthCheckCommand: null }, stored)).toEqual({});+ expect(applyHealthCheckCommandUpdate({ healthCheckCommand: "" }, stored)).toEqual({});});test("a new command replaces the stored one", () => {- expect(applyPreflightCommandUpdate({ preflightCommand: "test -w /srv/tls" }, stored)).toEqual({- preflightCommand: "test -w /srv/tls"+ expect(applyHealthCheckCommandUpdate({ healthCheckCommand: "test -w /srv/tls" }, stored)).toEqual({+ healthCheckCommand: "test -w /srv/tls"});});test("does not mutate the object it was given", () => {- const input = { preflightCommand: "" };- applyPreflightCommandUpdate(input, stored);- expect(input).toEqual({ preflightCommand: "" });+ const input = { healthCheckCommand: "" };+ applyHealthCheckCommandUpdate(input, stored);+ expect(input).toEqual({ healthCheckCommand: "" });});});diff --git a/backend/src/services/pki-sync/pki-sync-health-check-command-fns.ts b/backend/src/services/pki-sync/pki-sync-health-check-command-fns.tsnew file mode 100644index 0000000000..7e1d369bc7--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-health-check-command-fns.ts@@ -0,0 +1,167 @@+import { BadRequestError } from "@app/lib/errors";++import { PkiSyncStatus } from "./pki-sync-enums";+import {+ getExportedCertificateFileSuffixes,+ PemCertificateExtension,+ PkiSyncExportFormat+} from "./pki-sync-export-fns";+import {+ applyHostCommandOptionUpdate,+ buildHostCommandContext,+ buildHostCommandFailureMessage,+ commandNeedsCertificateData,+ findCertificateDependentHostCommandVariables,+ formatHostCommandVariables,+ HOST_COMMAND_TIMEOUT_MS,+ HostCommandKind,+ normalizeNewHostCommandOption,+ runHostCommand,+ THostCommandCertificate,+ THostCommandContext,+ THostCommandExecutionResult,+ THostCommandResult+} from "./pki-sync-host-command-fns";+import { TCertificateMap, TPkiSyncSyncResult } from "./pki-sync-types";++export const HEALTH_CHECK_COMMAND_TIMEOUT_MS = HOST_COMMAND_TIMEOUT_MS[HostCommandKind.HealthCheck];++export const HEALTH_CHECK_COMMAND_OPTION_KEY = "healthCheckCommand";++export type THealthCheckCommandResult = THostCommandResult;++export const getHealthCheckCommand = (syncOptions: unknown): string | undefined =>+ (syncOptions as Record<string, unknown> | undefined)?.[HEALTH_CHECK_COMMAND_OPTION_KEY] as string | undefined;++export const normalizeNewHealthCheckCommand = (syncOptions: Record<string, unknown>): Record<string, unknown> =>+ normalizeNewHostCommandOption(syncOptions, HEALTH_CHECK_COMMAND_OPTION_KEY);++export const applyHealthCheckCommandUpdate = (+ resolvedSyncOptions: Record<string, unknown>,+ storedCommand: unknown+): Record<string, unknown> =>+ applyHostCommandOptionUpdate(resolvedSyncOptions, HEALTH_CHECK_COMMAND_OPTION_KEY, storedCommand);++export const assertHealthCheckCommandIsTestable = (syncOptions: Record<string, unknown>): string => {+ const command = getHealthCheckCommand(syncOptions);+ if (!command) {+ throw new BadRequestError({ message: "Enter a health check command to test." });+ }++ const certificateVariables = findCertificateDependentHostCommandVariables(command);+ if (certificateVariables.length > 0) {+ throw new BadRequestError({+ message: `A test cannot resolve ${formatHostCommandVariables(+ certificateVariables+ )} because no certificate is linked yet. Use {{certificateDirectory}} to test, or save the sync and run the health check from its actions menu.`+ });+ }++ return command;+};++type THealthCheckExportOptions = {+ format: PkiSyncExportFormat;+ includePrivateKey: boolean;+ pemCertificateExtension?: PemCertificateExtension;+ combineCertificateChain?: boolean;+};++const buildProspectiveCertificates = (args: {+ certificateMap: TCertificateMap;+ destinationDirectory: string;+ exportOptions: THealthCheckExportOptions;+ joinPath: (directory: string, fileName: string) => string;+}): THostCommandCertificate[] => {+ const { certificateMap, destinationDirectory, exportOptions, joinPath } = args;++ return Object.entries(certificateMap).map(([baseName, certData]) => ({+ paths: getExportedCertificateFileSuffixes({+ ...exportOptions,+ hasCertificateChain: Boolean(certData.certificateChain),+ hasPrivateKey: Boolean(certData.privateKey)+ }).map((suffix) => joinPath(destinationDirectory, `${baseName}${suffix}`)),+ commonName: certData.commonName ?? undefined+ }));+};++export const buildHealthCheckCommandPlan = (args: {+ command?: string;+ destinationDirectory: string;+ certificateMap: TCertificateMap;+ exportOptions: THealthCheckExportOptions;+ joinPath: (directory: string, fileName: string) => string;+ pkcs12Password?: string;+}): { command: string; context: THostCommandContext } | undefined => {+ const { command, destinationDirectory, certificateMap, exportOptions, joinPath, pkcs12Password } = args;+ if (!command) return undefined;++ if (commandNeedsCertificateData(command) && Object.keys(certificateMap).length === 0) return undefined;++ return {+ command,+ context: buildHostCommandContext({+ kind: HostCommandKind.HealthCheck,+ command,+ destinationDirectory,+ certificates: buildProspectiveCertificates({+ certificateMap,+ destinationDirectory,+ exportOptions,+ joinPath+ }),+ pkcs12Password+ })+ };+};++export const runHealthCheckCommand = (args: {+ syncId: string;+ execute: () => Promise<THostCommandExecutionResult>;+ secretsToRedact?: Array<string | undefined>;+}): Promise<THealthCheckCommandResult> => runHostCommand({ ...args, kind: HostCommandKind.HealthCheck });++export const buildHealthCheckCommandFailureMessage = (result: THealthCheckCommandResult): string =>+ buildHostCommandFailureMessage(HostCommandKind.HealthCheck, result);++export const SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT = "Scheduled health check";++export const MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT = "Manual health check";++export const HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS = [+ SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT,+ MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT+];++export const didHealthCheckFail = (result: THealthCheckCommandResult | undefined): boolean =>+ result?.status === PkiSyncStatus.Failed;++export const toHealthCheckApiResult = (result: THealthCheckCommandResult) => ({+ status: result.status,+ exitCode: result.exitCode,+ timedOut: result.timedOut,+ durationMs: result.durationMs,+ output: result.output,+ failureDetail: result.failureDetail,+ message: didHealthCheckFail(result) ? buildHealthCheckCommandFailureMessage(result) : undefined+});++export const buildHealthCheckFailureSyncResult = (+ certificateMap: TCertificateMap,+ result: THealthCheckCommandResult+): TPkiSyncSyncResult => {+ const reason = buildHealthCheckCommandFailureMessage(result);+ const certificateNames = Object.keys(certificateMap);++ return {+ uploaded: 0,+ skipped: certificateNames.length,+ healthCheck: result,+ details: {+ skippedCertificates: certificateNames.map((name) => ({ name, reason }))+ }+ };+};++export const buildHealthCheckFailureMessageFor = (subject: string, result: THealthCheckCommandResult): string =>+ buildHostCommandFailureMessage(HostCommandKind.HealthCheck, result, subject);diff --git a/backend/src/services/pki-sync/pki-sync-health-check-queue.ts b/backend/src/services/pki-sync/pki-sync-health-check-queue.tsnew file mode 100644index 0000000000..ce87460d25--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-health-check-queue.ts@@ -0,0 +1,450 @@+import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { getConfig } from "@app/lib/config/env";+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { resolveCoreMeter } from "@app/lib/telemetry/metrics";+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";+import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";+import { ActorType } from "@app/services/auth/auth-type";+import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { TProjectDALFactory } from "@app/services/project/project-dal";++import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";+import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";+import { TCertificateDALFactory } from "../certificate/certificate-dal";+import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";+import { TCertificateAuthorityCertDALFactory } from "../certificate-authority/certificate-authority-cert-dal";+import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";+import { buildCertificateMap } from "./pki-sync-certificate-map-fns";+import { hydratePkiSyncCredentials } from "./pki-sync-credentials-fns";+import { TPkiSyncDALFactory } from "./pki-sync-dal";+import {+ PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,+ PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S,+ PKI_SYNC_CONNECTION_LOCK_RETRY,+ PkiSync,+ PkiSyncStatus+} from "./pki-sync-enums";+import { PkiSyncFns, truncateSyncMessage } from "./pki-sync-fns";+import {+ assertHealthCheckCommandIsTestable,+ buildHealthCheckFailureMessageFor,+ didHealthCheckFail,+ getHealthCheckCommand,+ HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS,+ MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT,+ SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT,+ THealthCheckCommandResult+} from "./pki-sync-health-check-command-fns";+import {+ commandNeedsCertificateData,+ findCertificateDependentHostCommandVariables,+ formatHostCommandVariables+} from "./pki-sync-host-command-fns";+import { TCertificateMap, THealthCheckTarget, TPkiSyncRaw } from "./pki-sync-types";++const ENQUEUE_CHUNK_SIZE = 200;+const WORKER_CONCURRENCY = 3;++const JOB_ATTEMPTS = 3;+const JOB_BACKOFF_DELAY_MS = 30_000;+const RATE_LIMIT_MAX = 60;+const RATE_LIMIT_DURATION_MS = 60 * 1000;++const CRON_HANDLER_TIMEOUT_MS = 60 * 1000;++const HEALTH_CHECK_LOCK_TTL_MS = 60 * 1000;++type TPkiSyncHealthCheckQueueFactoryDep = {+ cronJob: TCronJobFactory;+ queueService: Pick<TQueueServiceFactory, "queue" | "start">;+ pkiSyncDAL: Pick<+ TPkiSyncDALFactory,+ | "findPkiSyncsWithHealthCheckCommand"+ | "transaction"+ | "recordHealthCheckOutcome"+ | "reportHealthCheckFailure"+ | "clearReportedHealthCheckFailure"+ | "findById"+ >;+ keyStore: Pick<TKeyStoreFactory, "acquireLock" | "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;+ projectDAL: TProjectDALFactory;+ kmsService: Pick<+ TKmsServiceFactory,+ "createCipherPairWithDataKey" | "decryptWithKmsKey" | "generateKmsKey" | "encryptWithKmsKey"+ >;+ certificateDAL: TCertificateDALFactory;+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne">;+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;+ certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;+ certificateSyncDAL: TCertificateSyncDALFactory;+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+};++class HealthCheckBusyError extends Error {}++export type TPkiSyncHealthCheckQueueFactory = ReturnType<typeof pkiSyncHealthCheckQueueFactory>;++export const pkiSyncHealthCheckQueueFactory = ({+ cronJob,+ queueService,+ pkiSyncDAL,+ keyStore,+ appConnectionDAL,+ projectDAL,+ kmsService,+ certificateDAL,+ certificateBodyDAL,+ certificateSecretDAL,+ certificateAuthorityDAL,+ certificateAuthorityCertDAL,+ certificateSyncDAL,+ auditLogService,+ gatewayV2Service,+ gatewayPoolService+}: TPkiSyncHealthCheckQueueFactoryDep) => {+ const appCfg = getConfig();++ const meter = resolveCoreMeter();+ let lastDiscoveryCount = 0;+ const discoveryGauge = meter.createObservableGauge("infisical.pki_sync_health_check.discovered", {+ description: "PKI syncs with a health check configured, enqueued on the last daily tick.",+ unit: "{sync}"+ });+ discoveryGauge.addCallback((observableResult) => {+ if (!getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED) return;+ observableResult.observe(lastDiscoveryCount);+ });++ const $withConnectionHostAccess = async <T>(connectionId: string, run: () => Promise<T>): Promise<T> => {+ const connectionLock = await keyStore+ .acquireLock(+ [KeyStorePrefixes.AppConnectionCommandLock(connectionId)],+ HEALTH_CHECK_LOCK_TTL_MS,+ PKI_SYNC_CONNECTION_LOCK_RETRY+ )+ .catch(() => null);+ if (!connectionLock) {+ throw new HealthCheckBusyError("This connection is busy running another command.");+ }++ let admittedSlot = false;+ try {+ admittedSlot =+ (await keyStore.incrementByAndRefreshExpiryIfUnderLimit(+ KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId),+ PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,+ PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S+ )) !== -1;+ if (!admittedSlot) {+ throw new HealthCheckBusyError("This connection is at its concurrency limit.");+ }++ return await run();+ } finally {+ await Promise.allSettled([+ admittedSlot+ ? keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId))+ : undefined,+ connectionLock.release()+ ]);+ }+ };++ const $rethrowContentionAsBadRequest = (error: unknown): never => {+ if (error instanceof HealthCheckBusyError) {+ throw new BadRequestError({ message: `${error.message} Try again in a moment.` });+ }++ throw error;+ };++ const $certificatesForCheck = async (pkiSync: TPkiSyncRaw, command: string): Promise<TCertificateMap> => {+ if (!commandNeedsCertificateData(command)) return {};++ const { certificateMap } = await buildCertificateMap(pkiSync, {+ certificateDAL,+ certificateBodyDAL,+ certificateSecretDAL,+ certificateAuthorityDAL,+ certificateAuthorityCertDAL,+ certificateSyncDAL,+ projectDAL,+ kmsService+ });++ return certificateMap;+ };++ const $recordCheckResult = async (+ pkiSync: TPkiSyncRaw,+ result: THealthCheckCommandResult,+ isFinalAttempt: boolean,+ messageSubject: string+ ) => {+ if (!didHealthCheckFail(result)) {+ const cleared = await pkiSyncDAL.transaction(async (tx) => {+ await pkiSyncDAL.recordHealthCheckOutcome(+ pkiSync.id,+ { status: PkiSyncStatus.Succeeded, message: null, ranAt: new Date() },+ tx+ );++ return pkiSyncDAL.clearReportedHealthCheckFailure(pkiSync.id, HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS, tx);+ });+ if (cleared) {+ logger.info(+ `cron[${CronJobName.PkiSyncHealthCheck}]: host recovered, cleared the reported failure [syncId=${pkiSync.id}]`+ );+ }+ return;+ }++ if (result.exitCode === undefined && !isFinalAttempt) {+ throw new Error(`Health check could not reach the host: ${result.error ?? "unknown error"}`);+ }++ logger.warn(+ `cron[${CronJobName.PkiSyncHealthCheck}]: health check failed [syncId=${pkiSync.id}] [destination=${pkiSync.destination}] [projectId=${pkiSync.projectId}]`+ );++ const failureMessage = truncateSyncMessage(buildHealthCheckFailureMessageFor(messageSubject, result));++ const reported = await pkiSyncDAL.transaction(async (tx) => {+ await pkiSyncDAL.recordHealthCheckOutcome(+ pkiSync.id,+ { status: PkiSyncStatus.Failed, message: failureMessage, ranAt: new Date() },+ tx+ );++ return pkiSyncDAL.reportHealthCheckFailure(pkiSync.id, failureMessage, HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS, tx);+ });+ if (!reported) {+ logger.info(+ `cron[${CronJobName.PkiSyncHealthCheck}]: sync already failed to deliver, kept its reason [syncId=${pkiSync.id}]`+ );+ }+ };++ const $processHealthCheck = async (+ syncId: string,+ isFinalAttempt: boolean,+ messageSubject: string = SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT,+ auditLogInfo?: AuditLogInfo+ ): Promise<THealthCheckCommandResult | undefined> => {+ const pkiSync = await pkiSyncDAL.findById(syncId);+ if (!pkiSync) {+ logger.info(`cron[${CronJobName.PkiSyncHealthCheck}]: sync is gone, skipping [syncId=${syncId}]`);+ return;+ }++ const command = getHealthCheckCommand(pkiSync.syncOptions);+ if (!command) {+ logger.info(+ `cron[${CronJobName.PkiSyncHealthCheck}]: health check command was cleared, skipping [syncId=${syncId}]`+ );+ return;+ }++ const pkiSyncWithCredentials = await hydratePkiSyncCredentials({+ pkiSync,+ appConnectionDAL,+ projectDAL,+ kmsService+ });++ const certificateMap = await $certificatesForCheck(pkiSync, command);++ const result = await $withConnectionHostAccess(pkiSync.connectionId, async () => {+ const lock = await keyStore+ .acquireLock([KeyStorePrefixes.PkiSyncLock(syncId)], HEALTH_CHECK_LOCK_TTL_MS)+ .catch(() => null);+ if (!lock) {+ logger.info(`cron[${CronJobName.PkiSyncHealthCheck}]: a sync is already running, skipping [syncId=${syncId}]`);+ return undefined;+ }++ try {+ const checkResult = await PkiSyncFns.runHealthCheck(pkiSyncWithCredentials, certificateMap, {+ certificateSyncDAL,+ gatewayV2Service,+ gatewayPoolService+ });+ if (!checkResult) return undefined;++ await $recordCheckResult(pkiSync, checkResult, isFinalAttempt, messageSubject);+ return checkResult;+ } finally {+ await lock.release();+ }+ });++ if (!result) return undefined;++ await auditLogService.createAuditLog({+ ...(auditLogInfo ?? { actor: { type: ActorType.PLATFORM, metadata: {} } }),+ projectId: pkiSync.projectId,+ event: {+ type: EventType.PKI_SYNC_HEALTH_CHECK,+ metadata: {+ syncId,+ syncName: pkiSync.name,+ destination: pkiSync.destination,+ command,+ ranAt: new Date(),+ result+ }+ }+ });++ return result;+ };++ const runHealthCheckNow = async (syncId: string, auditLogInfo?: AuditLogInfo) => {+ let result: THealthCheckCommandResult | undefined;++ try {+ result = await $processHealthCheck(syncId, true, MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT, auditLogInfo);+ } catch (error) {+ $rethrowContentionAsBadRequest(error);+ }++ if (result) return result;++ const pkiSync = await pkiSyncDAL.findById(syncId);+ const command = getHealthCheckCommand(pkiSync?.syncOptions);+ if (command && commandNeedsCertificateData(command)) {+ throw new BadRequestError({+ message: `This health check uses ${formatHostCommandVariables(+ findCertificateDependentHostCommandVariables(command)+ )}, which cannot be resolved while no certificate is linked to the sync. Link a certificate, or use {{certificateDirectory}}.`+ });+ }++ throw new BadRequestError({+ message: "The health check did not run because a sync is already in progress. Try again in a moment."+ });+ };++ const testHealthCheckCommand = async (args: {+ destination: PkiSync;+ connectionId: string;+ destinationConfig: Record<string, unknown>;+ syncOptions: Record<string, unknown>;+ }) => {+ assertHealthCheckCommandIsTestable(args.syncOptions);++ const connection = await appConnectionDAL.findById(args.connectionId);+ if (!connection) {+ throw new NotFoundError({ message: `App connection with ID '${args.connectionId}' not found` });+ }++ const credentials = await decryptAppConnectionCredentials({+ orgId: connection.orgId,+ projectId: connection.projectId,+ encryptedCredentials: connection.encryptedCredentials,+ kmsService+ });++ const target: THealthCheckTarget = {+ id: "unsaved-sync-test",+ destination: args.destination,+ destinationConfig: args.destinationConfig,+ syncOptions: args.syncOptions,+ connection: {+ id: connection.id,+ name: connection.name,+ app: connection.app,+ credentials: credentials as Record<string, unknown>,+ method: connection.method,+ orgId: connection.orgId,+ gatewayId: connection.gatewayId ?? undefined,+ gatewayPoolId: connection.gatewayPoolId+ }+ };++ return $withConnectionHostAccess(connection.id, async () => {+ const result = await PkiSyncFns.runHealthCheck(+ target,+ {},+ {+ certificateSyncDAL,+ gatewayV2Service,+ gatewayPoolService+ }+ );+ if (!result) {+ throw new BadRequestError({+ message: "Health checks are not supported for this destination."+ });+ }++ return result;+ }).catch($rethrowContentionAsBadRequest);+ };++ const init = () => {+ queueService.start(+ QueueName.PkiSyncHealthCheck,+ async (job) => {+ const isFinalAttempt = job.attemptsStarted >= (job.opts.attempts ?? JOB_ATTEMPTS);++ await $processHealthCheck(job.data.syncId, isFinalAttempt).catch((err: unknown) => {+ logger.error(+ { err, syncId: job.data.syncId },+ `cron[${CronJobName.PkiSyncHealthCheck}]: check could not be run [syncId=${job.data.syncId}] [attempt=${job.attemptsStarted}]`+ );+ throw err;+ });+ },+ { concurrency: WORKER_CONCURRENCY, limiter: { max: RATE_LIMIT_MAX, duration: RATE_LIMIT_DURATION_MS } }+ );++ cronJob.register({+ name: CronJobName.PkiSyncHealthCheck,+ pattern: "23 3 * * *",+ runHashTtlS: 3 * 24 * 60 * 60,+ handlerTimeoutMs: CRON_HANDLER_TIMEOUT_MS,+ leaseDurationMs: CRON_HANDLER_TIMEOUT_MS,+ enabled: !appCfg.isSecondaryInstance,+ handler: async () => {+ const dueSyncs = await pkiSyncDAL.findPkiSyncsWithHealthCheckCommand();+ lastDiscoveryCount = dueSyncs.length;+ if (dueSyncs.length === 0) return;++ logger.info(`cron[${CronJobName.PkiSyncHealthCheck}]: enqueuing ${dueSyncs.length} health check(s)`);++ for (let offset = 0; offset < dueSyncs.length; offset += ENQUEUE_CHUNK_SIZE) {+ // eslint-disable-next-line no-await-in-loop+ await Promise.all(+ dueSyncs.slice(offset, offset + ENQUEUE_CHUNK_SIZE).map((pkiSync) =>+ queueService.queue(+ QueueName.PkiSyncHealthCheck,+ QueueJobs.PkiSyncRunHealthCheck,+ { syncId: pkiSync.id },+ {+ jobId: `pki-sync-health-check-${pkiSync.id}`,+ removeOnComplete: true,+ removeOnFail: true,+ attempts: JOB_ATTEMPTS,+ backoff: { type: "exponential", delay: JOB_BACKOFF_DELAY_MS }+ }+ )+ )+ );+ }+ }+ });+ };++ return { init, runHealthCheckNow, testHealthCheckCommand };+};diff --git a/backend/src/services/pki-sync/pki-sync-host-command-fns.test.ts b/backend/src/services/pki-sync/pki-sync-host-command-fns.test.tsnew file mode 100644index 0000000000..fe648330be--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-host-command-fns.test.ts@@ -0,0 +1,45 @@+import { describe, expect, test, vi } from "vitest";++import { PkiSyncStatus } from "./pki-sync-enums";+import { HOST_COMMAND_TIMEOUT_MS, HostCommandKind, runHostCommand } from "./pki-sync-host-command-fns";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }+}));++const run = (execute: () => Promise<never>) =>+ runHostCommand({ kind: HostCommandKind.HealthCheck, syncId: "sync-1", execute });++describe("runHostCommand distinguishes a timeout from an unreachable host", () => {+ test("a deadline enforced outside this process still reports as a timeout", async () => {+ const timeoutMs = HOST_COMMAND_TIMEOUT_MS[HostCommandKind.HealthCheck];+ const result = await run(() => Promise.reject(new Error(`command timed out after ${timeoutMs / 1000}s`)));++ expect(result.status).toBe(PkiSyncStatus.Failed);+ expect(result.exitCode).toBeUndefined();+ expect(result.timedOut).toBe(true);+ });++ test("the gateway's own RPC deadline reports as a timeout too", async () => {+ const result = await run(() => Promise.reject(new Error("SSH exec RPC timed out after 20000ms")));++ expect(result.timedOut).toBe(true);+ });++ test("an SSH connection timeout is unreachable, not a slow command", async () => {+ const result = await run(() =>+ Promise.reject(new Error("SSH Error: Connection timeout. Verify that the SSH server is reachable"))+ );++ expect(result.timedOut).toBe(false);+ });++ test("a fast transport failure is not a timeout, so the remedy stays connectivity", async () => {+ const result = await run(() =>+ Promise.reject(new Error("failed to dial target SSH server: dial tcp 10.0.0.1:22: connect: connection refused"))+ );++ expect(result.status).toBe(PkiSyncStatus.Failed);+ expect(result.timedOut).toBe(false);+ });+});diff --git a/backend/src/services/pki-sync/pki-sync-host-command-fns.ts b/backend/src/services/pki-sync/pki-sync-host-command-fns.tsindex 64412eb004..b2900137a0 100644--- a/backend/src/services/pki-sync/pki-sync-host-command-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-host-command-fns.ts@@ -6,12 +6,12 @@ import { PkiSyncStatus } from "./pki-sync-enums";import { PkiSyncError } from "./pki-sync-errors";export enum HostCommandKind {- Preflight = "preflight check",+ HealthCheck = "health check",PostSync = "post-sync command"}export const HOST_COMMAND_TIMEOUT_MS: Record<HostCommandKind, number> = {- [HostCommandKind.Preflight]: 10_000,+ [HostCommandKind.HealthCheck]: 15_000,[HostCommandKind.PostSync]: 30_000};@@ -55,6 +55,7 @@ const sentenceCase = (text: string): string => `${text.charAt(0).toUpperCase()}$export type THostCommandResult = {status: PkiSyncStatus.Succeeded | PkiSyncStatus.Failed;exitCode?: number;+ timedOut?: boolean;durationMs: number;output?: string;failureDetail?: string;@@ -88,6 +89,11 @@ const CERTIFICATE_DEPENDENT_HOST_COMMAND_VARIABLES: HostCommandVariable[] = [HostCommandVariable.CommonName];+export const findCertificateDependentHostCommandVariables = (command?: string): HostCommandVariable[] => {+ const used = findHostCommandVariables(command);+ return CERTIFICATE_DEPENDENT_HOST_COMMAND_VARIABLES.filter((variable) => used.has(variable));+};+export const commandNeedsCertificateData = (command?: string): boolean => {const used = findHostCommandVariables(command);return CERTIFICATE_DEPENDENT_HOST_COMMAND_VARIABLES.some((variable) => used.has(variable));@@ -110,7 +116,7 @@ export const buildHostCommandContext = (args: {const singleCertificateVariables = findSingleCertificateHostCommandVariables(command);if (certificates.length > 1 && singleCertificateVariables.length > 0) {- const delivered = kind === HostCommandKind.Preflight ? "would deliver" : "delivered";+ const delivered = kind === HostCommandKind.HealthCheck ? "would deliver" : "delivered";throw new PkiSyncError({message: `${sentenceCase(kind)} uses ${formatHostCommandVariables(singleCertificateVariables@@ -192,14 +198,12 @@ const redactSecrets = (text: string, secrets: Array<string | undefined>): stringconst TRUNCATION_SUFFIX = "... (truncated)";-// A cut between the halves of a surrogate pair leaves a lone surrogate, which is not valid UTF-8.const sliceWholeCharacters = (text: string, end: number): string => {const cut = text.slice(0, end);const last = cut.charCodeAt(cut.length - 1);return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut;};-// The suffix counts against maxLength, so the cap bounds what actually gets stored.const truncate = (text: string, maxLength: number): string =>text.length > maxLength? `${sliceWholeCharacters(text, Math.max(0, maxLength - TRUNCATION_SUFFIX.length))}${TRUNCATION_SUFFIX}`@@ -216,13 +220,23 @@ const captureOutput = (stdout: string, stderr: string): string | undefined => {return combined ? truncate(combined, MAX_CAPTURED_OUTPUT_CHARS) : undefined;};+class HostCommandTimeoutError extends Error {}++const COMMAND_TIMEOUT_ERROR_PATTERN = new RE2("command timed out|rpc timed out", "i");++const isTimeoutFailure = (err: unknown, message: string): boolean =>+ err instanceof HostCommandTimeoutError || COMMAND_TIMEOUT_ERROR_PATTERN.test(message);+const withHostCommandDeadline = <T>(execute: () => Promise<T>, timeoutMs: number, graceMs: number): Promise<T> => {let timer: NodeJS.Timeout;return Promise.race([execute(),new Promise<never>((_, reject) => {- timer = setTimeout(() => reject(new Error(`command timed out after ${timeoutMs / 1000}s`)), timeoutMs + graceMs);+ timer = setTimeout(+ () => reject(new HostCommandTimeoutError(`command timed out after ${timeoutMs / 1000}s`)),+ timeoutMs + graceMs+ );})]).finally(() => clearTimeout(timer));};@@ -262,7 +276,12 @@ export const runHostCommand = async (args: {const durationMs = Date.now() - startedAt;const error = redact((err as Error)?.message ?? "Unknown error");logger.warn(`PKI sync ${kind} could not run [syncId=${syncId}] [durationMs=${durationMs}]: ${error}`);- return { status: PkiSyncStatus.Failed, durationMs, error };+ return {+ status: PkiSyncStatus.Failed,+ durationMs,+ error,+ timedOut: isTimeoutFailure(err, error)+ };}};@@ -276,7 +295,9 @@ export const buildHostCommandFailureMessage = (const detail = result.failureDetail ?? firstNonEmptyLine(result.output);if (result.exitCode === undefined) {- return `${subject} could not run: the destination host could not be reached`;+ return result.timedOut+ ? `${subject} did not finish within its ${HOST_COMMAND_TIMEOUT_MS[kind] / 1000}s limit`+ : `${subject} could not run: the destination host could not be reached`;}const prefix = `${subject} failed (exit ${result.exitCode})`;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.tsindex 4e8bfda8a8..e806e3744d 100644--- 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.ts@@ -448,3 +448,16 @@ describe("applyPostSyncCommandUpdate", () => {expect(input.postSyncCommand).toBeNull();});});++describe("buildPostSyncCommandFailureMessage timeout wording", () => {+ test("names the 30s limit rather than blaming connectivity", () => {+ expect(+ buildPostSyncCommandFailureMessage({+ status: PkiSyncStatus.Failed,+ durationMs: 35_002,+ error: "command timed out after 30s",+ timedOut: true+ })+ ).toBe("Post-sync command did not finish within its 30s limit");+ });+});diff --git a/backend/src/services/pki-sync/pki-sync-preflight-command-fns.ts b/backend/src/services/pki-sync/pki-sync-preflight-command-fns.tsdeleted file mode 100644index f182b9083b..0000000000--- a/backend/src/services/pki-sync/pki-sync-preflight-command-fns.ts+++ /dev/null@@ -1,128 +0,0 @@-import { PkiSyncStatus } from "./pki-sync-enums";-import {- getExportedCertificateFileSuffixes,- PemCertificateExtension,- PkiSyncExportFormat-} from "./pki-sync-export-fns";-import {- applyHostCommandOptionUpdate,- buildHostCommandContext,- buildHostCommandFailureMessage,- commandNeedsCertificateData,- HOST_COMMAND_TIMEOUT_MS,- HostCommandKind,- normalizeNewHostCommandOption,- runHostCommand,- THostCommandCertificate,- THostCommandContext,- THostCommandExecutionResult,- THostCommandResult-} from "./pki-sync-host-command-fns";-import { TCertificateMap, TPkiSyncSyncResult } from "./pki-sync-types";--export const PREFLIGHT_COMMAND_TIMEOUT_MS = HOST_COMMAND_TIMEOUT_MS[HostCommandKind.Preflight];--export const PREFLIGHT_COMMAND_OPTION_KEY = "preflightCommand";--export type TPreflightCommandResult = THostCommandResult;--export const getPreflightCommand = (syncOptions: unknown): string | undefined =>- (syncOptions as Record<string, unknown> | undefined)?.[PREFLIGHT_COMMAND_OPTION_KEY] as string | undefined;--export const normalizeNewPreflightCommand = (syncOptions: Record<string, unknown>): Record<string, unknown> =>- normalizeNewHostCommandOption(syncOptions, PREFLIGHT_COMMAND_OPTION_KEY);--export const applyPreflightCommandUpdate = (- resolvedSyncOptions: Record<string, unknown>,- storedCommand: unknown-): Record<string, unknown> =>- applyHostCommandOptionUpdate(resolvedSyncOptions, PREFLIGHT_COMMAND_OPTION_KEY, storedCommand);--type TPreflightExportOptions = {- format: PkiSyncExportFormat;- includePrivateKey: boolean;- pemCertificateExtension?: PemCertificateExtension;- combineCertificateChain?: boolean;-};--const buildProspectiveCertificates = (args: {- certificateMap: TCertificateMap;- destinationDirectory: string;- exportOptions: TPreflightExportOptions;- joinPath: (directory: string, fileName: string) => string;-}): THostCommandCertificate[] => {- const { certificateMap, destinationDirectory, exportOptions, joinPath } = args;-- return Object.entries(certificateMap).map(([baseName, certData]) => ({- paths: getExportedCertificateFileSuffixes({- ...exportOptions,- hasCertificateChain: Boolean(certData.certificateChain),- hasPrivateKey: Boolean(certData.privateKey)- }).map((suffix) => joinPath(destinationDirectory, `${baseName}${suffix}`)),- commonName: certData.commonName ?? undefined- }));-};--export const buildPreflightCommandPlan = (args: {- command?: string;- destinationDirectory: string;- certificateMap: TCertificateMap;- exportOptions: TPreflightExportOptions;- joinPath: (directory: string, fileName: string) => string;- pkcs12Password?: string;-}): { command: string; context: THostCommandContext } | undefined => {- const { command, destinationDirectory, certificateMap, exportOptions, joinPath, pkcs12Password } = args;- if (!command) return undefined;-- if (commandNeedsCertificateData(command) && Object.keys(certificateMap).length === 0) return undefined;-- return {- command,- context: buildHostCommandContext({- kind: HostCommandKind.Preflight,- command,- destinationDirectory,- certificates: buildProspectiveCertificates({- certificateMap,- destinationDirectory,- exportOptions,- joinPath- }),- pkcs12Password- })- };-};--export const runPreflightCommand = (args: {- syncId: string;- execute: () => Promise<THostCommandExecutionResult>;- secretsToRedact?: Array<string | undefined>;-}): Promise<TPreflightCommandResult> => runHostCommand({ ...args, kind: HostCommandKind.Preflight });--export const buildPreflightCommandFailureMessage = (result: TPreflightCommandResult): string =>- buildHostCommandFailureMessage(HostCommandKind.Preflight, result);--export const SCHEDULED_PREFLIGHT_MESSAGE_SUBJECT = "Scheduled preflight check";--export const buildScheduledPreflightFailureMessage = (result: TPreflightCommandResult): string =>- buildHostCommandFailureMessage(HostCommandKind.Preflight, result, SCHEDULED_PREFLIGHT_MESSAGE_SUBJECT);--export const didPreflightCheckFail = (result: TPreflightCommandResult | undefined): boolean =>- result?.status === PkiSyncStatus.Failed;--export const buildPreflightFailureSyncResult = (- certificateMap: TCertificateMap,- result: TPreflightCommandResult-): TPkiSyncSyncResult => {- const reason = buildPreflightCommandFailureMessage(result);- const certificateNames = Object.keys(certificateMap);-- return {- uploaded: 0,- skipped: certificateNames.length,- preflightCheck: result,- details: {- skippedCertificates: certificateNames.map((name) => ({ name, reason }))- }- };-};diff --git a/backend/src/services/pki-sync/pki-sync-preflight-queue.ts b/backend/src/services/pki-sync/pki-sync-preflight-queue.tsdeleted file mode 100644index 291f57c658..0000000000--- a/backend/src/services/pki-sync/pki-sync-preflight-queue.ts+++ /dev/null@@ -1,307 +0,0 @@-import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";-import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";-import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";-import { getConfig } from "@app/lib/config/env";-import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";-import { logger } from "@app/lib/logger";-import { resolveCoreMeter } from "@app/lib/telemetry/metrics";-import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";-import { ActorType } from "@app/services/auth/auth-type";-import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";-import { TKmsServiceFactory } from "@app/services/kms/kms-service";-import { TProjectDALFactory } from "@app/services/project/project-dal";--import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";-import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";-import { TCertificateDALFactory } from "../certificate/certificate-dal";-import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";-import { TCertificateAuthorityCertDALFactory } from "../certificate-authority/certificate-authority-cert-dal";-import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";-import { buildCertificateMap } from "./pki-sync-certificate-map-fns";-import { hydratePkiSyncCredentials } from "./pki-sync-credentials-fns";-import { TPkiSyncDALFactory } from "./pki-sync-dal";-import { PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT } from "./pki-sync-enums";-import { PkiSyncFns, truncateSyncMessage } from "./pki-sync-fns";-import { commandNeedsCertificateData } from "./pki-sync-host-command-fns";-import {- buildScheduledPreflightFailureMessage,- didPreflightCheckFail,- getPreflightCommand,- SCHEDULED_PREFLIGHT_MESSAGE_SUBJECT,- TPreflightCommandResult-} from "./pki-sync-preflight-command-fns";-import { TCertificateMap, TPkiSyncRaw } from "./pki-sync-types";--const ENQUEUE_CHUNK_SIZE = 200;-const WORKER_CONCURRENCY = 3;--const JOB_ATTEMPTS = 3;-const JOB_BACKOFF_DELAY_MS = 30_000;-const RATE_LIMIT_MAX = 60;-const RATE_LIMIT_DURATION_MS = 60 * 1000;--const CRON_HANDLER_TIMEOUT_MS = 60 * 1000;--const PREFLIGHT_LOCK_TTL_MS = 60 * 1000;--const CONNECTION_SLOT_TTL_S = 5 * 60;--const CONNECTION_LOCK_RETRY = { retryCount: 10, retryDelay: 3_000, retryJitter: 500 };--type TPkiSyncPreflightQueueFactoryDep = {- cronJob: TCronJobFactory;- queueService: Pick<TQueueServiceFactory, "queue" | "start">;- pkiSyncDAL: Pick<- TPkiSyncDALFactory,- "findPkiSyncsWithPreflightCommand" | "reportPreflightFailure" | "clearReportedPreflightFailure" | "findById"- >;- keyStore: Pick<TKeyStoreFactory, "acquireLock" | "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;- projectDAL: TProjectDALFactory;- kmsService: Pick<- TKmsServiceFactory,- "createCipherPairWithDataKey" | "decryptWithKmsKey" | "generateKmsKey" | "encryptWithKmsKey"- >;- certificateDAL: TCertificateDALFactory;- certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;- certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne">;- certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;- certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;- certificateSyncDAL: TCertificateSyncDALFactory;- auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;- gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;- gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;-};--export type TPkiSyncPreflightQueueFactory = ReturnType<typeof pkiSyncPreflightQueueFactory>;--export const pkiSyncPreflightQueueFactory = ({- cronJob,- queueService,- pkiSyncDAL,- keyStore,- appConnectionDAL,- projectDAL,- kmsService,- certificateDAL,- certificateBodyDAL,- certificateSecretDAL,- certificateAuthorityDAL,- certificateAuthorityCertDAL,- certificateSyncDAL,- auditLogService,- gatewayV2Service,- gatewayPoolService-}: TPkiSyncPreflightQueueFactoryDep) => {- const appCfg = getConfig();-- const meter = resolveCoreMeter();- let lastDiscoveryCount = 0;- const discoveryGauge = meter.createObservableGauge("infisical.pki_sync_preflight.discovered", {- description: "PKI syncs with a preflight check configured, enqueued on the last daily tick.",- unit: "{sync}"- });- discoveryGauge.addCallback((observableResult) => {- if (!getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED) return;- observableResult.observe(lastDiscoveryCount);- });-- const $certificatesForCheck = async (pkiSync: TPkiSyncRaw, command: string): Promise<TCertificateMap> => {- if (!commandNeedsCertificateData(command)) return {};-- const { certificateMap } = await buildCertificateMap(pkiSync, {- certificateDAL,- certificateBodyDAL,- certificateSecretDAL,- certificateAuthorityDAL,- certificateAuthorityCertDAL,- certificateSyncDAL,- projectDAL,- kmsService- });-- return certificateMap;- };-- const $recordCheckResult = async (pkiSync: TPkiSyncRaw, result: TPreflightCommandResult, isFinalAttempt: boolean) => {- if (!didPreflightCheckFail(result)) {- const cleared = await pkiSyncDAL.clearReportedPreflightFailure(pkiSync.id, SCHEDULED_PREFLIGHT_MESSAGE_SUBJECT);- if (cleared) {- logger.info(- `cron[${CronJobName.PkiSyncPreflightCheck}]: host recovered, cleared the reported failure [syncId=${pkiSync.id}]`- );- }- return;- }-- if (result.exitCode === undefined && !isFinalAttempt) {- throw new Error(`Preflight check could not reach the host: ${result.error ?? "unknown error"}`);- }-- logger.warn(- `cron[${CronJobName.PkiSyncPreflightCheck}]: preflight check failed [syncId=${pkiSync.id}] [destination=${pkiSync.destination}] [projectId=${pkiSync.projectId}]`- );-- const reported = await pkiSyncDAL.reportPreflightFailure(- pkiSync.id,- truncateSyncMessage(buildScheduledPreflightFailureMessage(result)),- SCHEDULED_PREFLIGHT_MESSAGE_SUBJECT- );- if (!reported) {- logger.info(- `cron[${CronJobName.PkiSyncPreflightCheck}]: sync already failed to deliver, kept its reason [syncId=${pkiSync.id}]`- );- }- };-- const $processPreflightCheck = async (syncId: string, isFinalAttempt: boolean) => {- const pkiSync = await pkiSyncDAL.findById(syncId);- if (!pkiSync) {- logger.info(`cron[${CronJobName.PkiSyncPreflightCheck}]: sync is gone, skipping [syncId=${syncId}]`);- return;- }-- const command = getPreflightCommand(pkiSync.syncOptions);- if (!command) {- logger.info(- `cron[${CronJobName.PkiSyncPreflightCheck}]: preflight command was cleared, skipping [syncId=${syncId}]`- );- return;- }-- const pkiSyncWithCredentials = await hydratePkiSyncCredentials({- pkiSync,- appConnectionDAL,- projectDAL,- kmsService- });-- const certificateMap = await $certificatesForCheck(pkiSync, command);-- const connectionLock = await keyStore- .acquireLock(- [KeyStorePrefixes.AppConnectionCommandLock(pkiSync.connectionId)],- PREFLIGHT_LOCK_TTL_MS,- CONNECTION_LOCK_RETRY- )- .catch(() => null);- if (!connectionLock) {- throw new Error(`Another check is already running on connection ${pkiSync.connectionId}`);- }-- let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | null = null;- let admittedSlot = false;- let result;- try {- admittedSlot =- (await keyStore.incrementByAndRefreshExpiryIfUnderLimit(- KeyStorePrefixes.AppConnectionConcurrentJobs(pkiSync.connectionId),- PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,- CONNECTION_SLOT_TTL_S- )) !== -1;- if (!admittedSlot) {- throw new Error(`Connection ${pkiSync.connectionId} is at its concurrency limit`);- }-- lock = await keyStore- .acquireLock([KeyStorePrefixes.PkiSyncLock(syncId)], PREFLIGHT_LOCK_TTL_MS)- .catch(() => null);- if (!lock) {- logger.info(- `cron[${CronJobName.PkiSyncPreflightCheck}]: a sync is already running, skipping [syncId=${syncId}]`- );- return;- }-- result = await PkiSyncFns.runPreflightCheck(pkiSyncWithCredentials, certificateMap, {- certificateSyncDAL,- gatewayV2Service,- gatewayPoolService- });- if (!result) return;-- await $recordCheckResult(pkiSync, result, isFinalAttempt);- } finally {- await Promise.allSettled([- admittedSlot- ? keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(pkiSync.connectionId))- : undefined,- lock?.release(),- connectionLock.release()- ]);- }-- await auditLogService.createAuditLog({- projectId: pkiSync.projectId,- actor: { type: ActorType.PLATFORM, metadata: {} },- event: {- type: EventType.PKI_SYNC_PREFLIGHT_CHECK,- metadata: {- syncId,- syncName: pkiSync.name,- destination: pkiSync.destination,- command,- ranAt: new Date(),- result- }- }- });- };-- const init = () => {- queueService.start(- QueueName.PkiSyncPreflightCheck,- async (job) => {- const isFinalAttempt = job.attemptsStarted >= (job.opts.attempts ?? JOB_ATTEMPTS);-- await $processPreflightCheck(job.data.syncId, isFinalAttempt).catch((err: unknown) => {- logger.error(- { err, syncId: job.data.syncId },- `cron[${CronJobName.PkiSyncPreflightCheck}]: check could not be run [syncId=${job.data.syncId}] [attempt=${job.attemptsStarted}]`- );- throw err;- });- },- { concurrency: WORKER_CONCURRENCY, limiter: { max: RATE_LIMIT_MAX, duration: RATE_LIMIT_DURATION_MS } }- );-- cronJob.register({- name: CronJobName.PkiSyncPreflightCheck,- pattern: "23 3 * * *",- runHashTtlS: 3 * 24 * 60 * 60,- handlerTimeoutMs: CRON_HANDLER_TIMEOUT_MS,- leaseDurationMs: CRON_HANDLER_TIMEOUT_MS,- enabled: !appCfg.isSecondaryInstance,- handler: async () => {- const dueSyncs = await pkiSyncDAL.findPkiSyncsWithPreflightCommand();- lastDiscoveryCount = dueSyncs.length;- if (dueSyncs.length === 0) return;-- logger.info(`cron[${CronJobName.PkiSyncPreflightCheck}]: enqueuing ${dueSyncs.length} preflight check(s)`);-- for (let offset = 0; offset < dueSyncs.length; offset += ENQUEUE_CHUNK_SIZE) {- // eslint-disable-next-line no-await-in-loop- await Promise.all(- dueSyncs.slice(offset, offset + ENQUEUE_CHUNK_SIZE).map((pkiSync) =>- queueService.queue(- QueueName.PkiSyncPreflightCheck,- QueueJobs.PkiSyncRunPreflightCheck,- { syncId: pkiSync.id },- {- jobId: `pki-sync-preflight-check-${pkiSync.id}`,- removeOnComplete: true,- removeOnFail: true,- attempts: JOB_ATTEMPTS,- backoff: { type: "exponential", delay: JOB_BACKOFF_DELAY_MS }- }- )- )- );- }- }- });- };-- return { init };-};diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.tsindex 54d82d2052..bbdcb21723 100644--- a/backend/src/services/pki-sync/pki-sync-queue.ts+++ b/backend/src/services/pki-sync/pki-sync-queue.ts@@ -29,20 +29,31 @@ import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-syncimport { CertificateSyncStatus } from "../certificate-sync/certificate-sync-enums";import { buildCertificateMap } from "./pki-sync-certificate-map-fns";import { TPkiSyncDALFactory } from "./pki-sync-dal";-import { PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT, PkiSyncStatus } from "./pki-sync-enums";+import {+ PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,+ PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S,+ PKI_SYNC_CONNECTION_LOCK_RETRY,+ PkiSyncStatus+} from "./pki-sync-enums";import { PkiSyncError } from "./pki-sync-errors";-import { enterprisePkiSyncCheck, parsePkiSyncErrorMessage, PkiSyncFns, truncateSyncMessage } from "./pki-sync-fns";+import {+ enterprisePkiSyncCheck,+ getPkiSyncProviderCapabilities,+ parsePkiSyncErrorMessage,+ PkiSyncFns,+ truncateSyncMessage+} from "./pki-sync-fns";+import {+ buildHealthCheckCommandFailureMessage,+ didHealthCheckFail,+ getHealthCheckCommand,+ THealthCheckCommandResult+} from "./pki-sync-health-check-command-fns";import {buildPostSyncCommandFailureMessage,getPostSyncCommand,TPostSyncCommandResult} from "./pki-sync-post-sync-command-fns";-import {- buildPreflightCommandFailureMessage,- didPreflightCheckFail,- getPreflightCommand,- TPreflightCommandResult-} from "./pki-sync-preflight-command-fns";import {TCertificateMap,TPkiSyncImportCertificatesDTO,@@ -63,7 +74,7 @@ type TPkiSyncQueueFactoryDep = {"createCipherPairWithDataKey" | "decryptWithKmsKey" | "generateKmsKey" | "encryptWithKmsKey">;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;- keyStore: Pick<TKeyStoreFactory, "acquireLock" | "setItemWithExpiry" | "getItem">;+ keyStore: Pick<TKeyStoreFactory, "acquireLock" | "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;pkiSyncDAL: Pick<TPkiSyncDALFactory, "findById" | "find" | "updateById" | "deleteById" | "update">;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;projectDAL: TProjectDALFactory;@@ -84,6 +95,8 @@ type PkiSyncActionJob = Job<>;const JITTER_MS = 10 * 1000;+const HOST_SERIALISATION_LOCK_TTL_MS = 5 * 60 * 1000;+const REQUEUE_MS = 30 * 1000;const REQUEUE_LIMIT = 30;@@ -128,44 +141,18 @@ export const pkiSyncQueueFactory = ({unit: "1"});- const $isConnectionConcurrencyLimitReached = async (connectionId: string) => {- const concurrencyCount = await keyStore.getItem(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId));-- if (!concurrencyCount) return false;-- const count = Number.parseInt(concurrencyCount, 10);-- if (Number.isNaN(count)) return false;-- return count >= PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT;- };-- const $incrementConnectionConcurrencyCount = async (connectionId: string) => {- const concurrencyCount = await keyStore.getItem(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId));-- const currentCount = Number.parseInt(concurrencyCount || "0", 10);-- const incrementedCount = Number.isNaN(currentCount) ? 1 : currentCount + 1;-- await keyStore.setItemWithExpiry(+ const $tryAdmitConnectionConcurrency = async (connectionId: string) => {+ const count = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId),- (REQUEUE_MS * REQUEUE_LIMIT) / 1000, // in seconds- incrementedCount+ PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,+ PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S);- };- const $decrementConnectionConcurrencyCount = async (connectionId: string) => {- const concurrencyCount = await keyStore.getItem(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId));-- const currentCount = Number.parseInt(concurrencyCount || "0", 10);-- const decrementedCount = Math.max(0, Number.isNaN(currentCount) ? 0 : currentCount - 1);+ return count !== -1;+ };- await keyStore.setItemWithExpiry(- KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId),- (REQUEUE_MS * REQUEUE_LIMIT) / 1000, // in seconds- decrementedCount- );+ const $releaseConnectionConcurrency = async (connectionId: string) => {+ await keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId));};const $certificatesForSync = (pkiSync: TPkiSyncRaw) =>@@ -245,11 +232,11 @@ export const pkiSyncQueueFactory = ({let certSyncFailureCount = 0;let syncMessage: string | null = null;let postSyncCommandResult: TPostSyncCommandResult | undefined;- let preflightCheckResult: TPreflightCommandResult | undefined;+ let healthCheckResult: THealthCheckCommandResult | undefined;let isFinalAttempt = job.attemptsStarted === job.opts.attempts;const configuredPostSyncCommand = getPostSyncCommand(pkiSync.syncOptions);- const configuredPreflightCommand = getPreflightCommand(pkiSync.syncOptions);+ const configuredHealthCheckCommand = getHealthCheckCommand(pkiSync.syncOptions);try {const pkiSyncWithCredentials = await hydratePkiSyncCredentials({@@ -403,11 +390,11 @@ export const pkiSyncQueueFactory = ({}postSyncCommandResult = syncResult.postSyncCommand;- preflightCheckResult = syncResult.preflightCheck;+ healthCheckResult = syncResult.healthCheck;const reasons =- preflightCheckResult && didPreflightCheckFail(preflightCheckResult)- ? [buildPreflightCommandFailureMessage(preflightCheckResult)]+ healthCheckResult && didHealthCheckFail(healthCheckResult)+ ? [buildHealthCheckCommandFailureMessage(healthCheckResult)]: [certSyncFailureCount > 0? `${certSyncFailureCount} certificate(s) failed to sync to the destination`@@ -451,10 +438,7 @@ export const pkiSyncQueueFactory = ({const ranAt = new Date();const postSyncCommandFailed = postSyncCommandResult?.status === PkiSyncStatus.Failed;const fullySynced =- isSynced &&- certSyncFailureCount === 0 &&- !postSyncCommandFailed &&- !didPreflightCheckFail(preflightCheckResult);+ isSynced && certSyncFailureCount === 0 && !postSyncCommandFailed && !didHealthCheckFail(healthCheckResult);const syncStatus = fullySynced ? PkiSyncStatus.Succeeded : PkiSyncStatus.Failed;await auditLogService.createAuditLog({@@ -472,8 +456,8 @@ export const pkiSyncQueueFactory = ({syncMessage,jobId: job.id!,jobRanAt: ranAt,- preflightCheck: configuredPreflightCommand- ? { command: configuredPreflightCommand, result: preflightCheckResult }+ healthCheck: configuredHealthCheckCommand+ ? { command: configuredHealthCheckCommand, result: healthCheckResult }: undefined,postSyncCommand: configuredPostSyncCommand? { command: configuredPostSyncCommand, result: postSyncCommandResult }@@ -487,7 +471,18 @@ export const pkiSyncQueueFactory = ({syncStatus,lastSyncJobId: job.id,lastSyncMessage: syncMessage,- lastSyncedAt: fullySynced ? ranAt : undefined+ lastSyncedAt: fullySynced ? ranAt : undefined,+ ...(healthCheckResult+ ? {+ lastHealthCheckRanAt: ranAt,+ lastHealthCheckStatus: didHealthCheckFail(healthCheckResult)+ ? PkiSyncStatus.Failed+ : PkiSyncStatus.Succeeded,+ lastHealthCheckMessage: didHealthCheckFail(healthCheckResult)+ ? truncateSyncMessage(buildHealthCheckCommandFailureMessage(healthCheckResult))+ : null+ }+ : {})});await telemetryService.sendPostHogEvents({@@ -755,16 +750,35 @@ export const pkiSyncQueueFactory = ({const { connectionId } = pkiSync;- if (job.name === QueueJobs.PkiSyncSyncCertificates) {- const isConcurrentLimitReached = await $isConnectionConcurrencyLimitReached(connectionId);+ const needsConnectionSlot = job.name === QueueJobs.PkiSyncSyncCertificates;++ const needsHostSerialisation =+ needsConnectionSlot && getPkiSyncProviderCapabilities(pkiSync.destination).canRunHealthCheckCommand;++ let connectionLock: Awaited<ReturnType<typeof keyStore.acquireLock>> | null = null;+ if (needsHostSerialisation) {+ connectionLock = await keyStore+ .acquireLock(+ [KeyStorePrefixes.AppConnectionCommandLock(connectionId)],+ HOST_SERIALISATION_LOCK_TTL_MS,+ PKI_SYNC_CONNECTION_LOCK_RETRY+ )+ .catch(() => null);- if (isConcurrentLimitReached) {+ if (!connectionLock) {await $handleAcquireLockFailure(job as PkiSyncActionJob);return;}}+ if (needsConnectionSlot && !(await $tryAdmitConnectionConcurrency(connectionId))) {+ await connectionLock?.release();+ await $handleAcquireLockFailure(job as PkiSyncActionJob);++ return;+ }+let lock: Awaited<ReturnType<typeof keyStore.acquireLock>>;try {@@ -774,6 +788,8 @@ export const pkiSyncQueueFactory = ({5 * 60 * 1000);} catch (e) {+ if (needsConnectionSlot) await $releaseConnectionConcurrency(connectionId);+ await connectionLock?.release();await $handleAcquireLockFailure(job as PkiSyncActionJob);return;@@ -782,7 +798,6 @@ export const pkiSyncQueueFactory = ({try {switch (job.name) {case QueueJobs.PkiSyncSyncCertificates: {- await $incrementConnectionConcurrencyCount(connectionId);await $handleSyncCertificatesJob(job as TPkiSyncSyncCertificatesDTO, pkiSync);break;}@@ -796,11 +811,9 @@ export const pkiSyncQueueFactory = ({throw new Error(`Unhandled PKI Sync Job ${String(job.name)}`);}} finally {- if (job.name === QueueJobs.PkiSyncSyncCertificates) {- await $decrementConnectionConcurrencyCount(connectionId);- }+ if (needsConnectionSlot) await $releaseConnectionConcurrency(connectionId);- await lock.release();+ await Promise.allSettled([lock.release(), connectionLock?.release()]);}});diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.tsindex a7f9f9dbb9..e26eacb187 100644--- a/backend/src/services/pki-sync/pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts@@ -2,7 +2,7 @@ import RE2 from "re2";import { z } from "zod";import { buildCertificateNameSchemaTestName } from "./pki-sync-certificate-name-fns";-import { PkiSync } from "./pki-sync-enums";+import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";import { HOST_COMMAND_MAX_LENGTH } from "./pki-sync-host-command-fns";export const HostCommandSchema = z@@ -18,7 +18,7 @@ export const BasePkiSyncOptionsSchema = z.object({canRemoveCertificates: z.boolean().default(true),includeRootCa: z.boolean().default(false),preserveItemOnRenewal: z.boolean().default(true),- preflightCommand: HostCommandSchema,+ healthCheckCommand: HostCommandSchema,postSyncCommand: HostCommandSchema});@@ -100,5 +100,8 @@ export const PkiSyncSchema = z.object({createdAt: z.date(),updatedAt: z.date(),syncStatus: z.string().nullable().optional(),- lastSyncedAt: z.date().nullable().optional()+ lastSyncedAt: z.date().nullable().optional(),+ lastHealthCheckRanAt: z.date().nullable().optional(),+ lastHealthCheckStatus: z.nativeEnum(PkiSyncStatus).nullable().optional(),+ lastHealthCheckMessage: z.string().nullable().optional()});diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex 4d197e9da5..2342aff5be 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -1,6 +1,7 @@import { ForbiddenError, subject } from "@casl/ability";import { ActionProjectType, ResourceType, TCertificateSyncs } from "@app/db/schemas";+import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ProjectPermissionPkiSyncActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";@@ -13,6 +14,7 @@ import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError }import { OrgServiceActor } from "@app/lib/types";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";+import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TPkiSubscriberDALFactory } from "@app/services/pki-subscriber/pki-subscriber-dal";@@ -31,6 +33,16 @@ import {getPkiSyncProviderCapabilities,listPkiSyncOptions} from "./pki-sync-fns";+import {+ applyHealthCheckCommandUpdate,+ assertHealthCheckCommandIsTestable,+ getHealthCheckCommand,+ HEALTH_CHECK_COMMAND_OPTION_KEY,+ HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS,+ normalizeNewHealthCheckCommand,+ toHealthCheckApiResult+} from "./pki-sync-health-check-command-fns";+import { TPkiSyncHealthCheckQueueFactory } from "./pki-sync-health-check-queue";import {findSingleCertificateHostCommandVariables,formatHostCommandVariables,@@ -43,12 +55,6 @@ import {normalizeNewPostSyncCommand,POST_SYNC_COMMAND_OPTION_KEY} from "./pki-sync-post-sync-command-fns";-import {- applyPreflightCommandUpdate,- getPreflightCommand,- normalizeNewPreflightCommand,- PREFLIGHT_COMMAND_OPTION_KEY-} from "./pki-sync-preflight-command-fns";import { TPkiSyncQueueFactory } from "./pki-sync-queue";import {TAddCertificatesToPkiSyncDTO,@@ -81,7 +87,13 @@ const getDestinationAppType = (destination: PkiSync): AppConnection => {type TPkiSyncServiceFactoryDep = {pkiSyncDAL: Pick<TPkiSyncDALFactory,- "findById" | "findByProjectIdWithSubscribers" | "findByNameAndProjectId" | "create" | "updateById" | "deleteById"+ | "clearReportedHealthCheckFailure"+ | "findById"+ | "findByProjectIdWithSubscribers"+ | "findByNameAndProjectId"+ | "create"+ | "updateById"+ | "deleteById">;certificateDAL: Pick<TCertificateDALFactory, "findActiveCertificatesByIds">;certificateSyncDAL: Pick<@@ -102,6 +114,8 @@ type TPkiSyncServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;+ pkiSyncHealthCheckQueue: Pick<TPkiSyncHealthCheckQueueFactory, "runHealthCheckNow" | "testHealthCheckCommand">;pkiSyncQueue: Pick<TPkiSyncQueueFactory,"queuePkiSyncSyncCertificatesById" | "queuePkiSyncImportCertificatesById" | "queuePkiSyncRemoveCertificatesById"@@ -119,7 +133,9 @@ export const pkiSyncServiceFactory = ({permissionService,licenseService,kmsService,- pkiSyncQueue+ pkiSyncQueue,+ pkiSyncHealthCheckQueue,+ auditLogService}: TPkiSyncServiceFactoryDep) => {const $resourceFallback = async (action: ResourcePermissionPkiSyncActions,@@ -150,9 +166,9 @@ export const pkiSyncServiceFactory = ({const configuredCommands = [{- kind: HostCommandKind.Preflight,- command: syncOptions?.[PREFLIGHT_COMMAND_OPTION_KEY],- isSupportedByDestination: capabilities.canRunPreflightCommand+ kind: HostCommandKind.HealthCheck,+ command: syncOptions?.[HEALTH_CHECK_COMMAND_OPTION_KEY],+ isSupportedByDestination: capabilities.canRunHealthCheckCommand},{kind: HostCommandKind.PostSync,@@ -227,9 +243,9 @@ export const pkiSyncServiceFactory = ({};const HOST_COMMAND_ACTIONS = {- [PREFLIGHT_COMMAND_OPTION_KEY]: {- project: ProjectPermissionPkiSyncActions.SetPreflightCommand,- resource: ResourcePermissionPkiSyncActions.SetPreflightCommand+ [HEALTH_CHECK_COMMAND_OPTION_KEY]: {+ project: ProjectPermissionPkiSyncActions.SetHealthCheckCommand,+ resource: ResourcePermissionPkiSyncActions.SetHealthCheckCommand},[POST_SYNC_COMMAND_OPTION_KEY]: {project: ProjectPermissionPkiSyncActions.SetPostSyncCommand,@@ -351,7 +367,7 @@ export const pkiSyncServiceFactory = ({}[- { kind: HostCommandKind.Preflight, command: getPreflightCommand(syncOptions) },+ { kind: HostCommandKind.HealthCheck, command: getHealthCheckCommand(syncOptions) },{ kind: HostCommandKind.PostSync, command: getPostSyncCommand(syncOptions) }].forEach(({ kind, command }) => {const singleCertificateVariables = findSingleCertificateHostCommandVariables(command);@@ -417,7 +433,7 @@ export const pkiSyncServiceFactory = ({const connection = await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);const providerCapabilities = getPkiSyncProviderCapabilities(destination);- const resolvedSyncOptions = normalizeNewPreflightCommand(+ const resolvedSyncOptions = normalizeNewHealthCheckCommand(normalizeNewPostSyncCommand({...providerCapabilities,...syncOptions@@ -579,9 +595,9 @@ export const pkiSyncServiceFactory = ({});}- resolvedSyncOptions = applyPreflightCommandUpdate(+ resolvedSyncOptions = applyHealthCheckCommandUpdate(applyPostSyncCommandUpdate({ ...providerCapabilities, ...syncOptions }, storedSyncOptions?.postSyncCommand),- storedSyncOptions?.preflightCommand+ storedSyncOptions?.healthCheckCommand);}@@ -635,6 +651,11 @@ export const pkiSyncServiceFactory = ({? await encryptPkiSyncCredentials({ orgId: actor.orgId, projectId: pkiSync.projectId, credentials, kmsService }): undefined;+ const isHealthCheckBeingCleared =+ resolvedSyncOptions !== undefined &&+ !getHealthCheckCommand(resolvedSyncOptions) &&+ Boolean(getHealthCheckCommand(storedSyncOptions));+const updatedPkiSync = await pkiSyncDAL.updateById(id, {name,description,@@ -643,9 +664,16 @@ export const pkiSyncServiceFactory = ({syncOptions: resolvedSyncOptions,subscriberId,connectionId,- ...(encryptedCredentials ? { encryptedCredentials } : {})+ ...(encryptedCredentials ? { encryptedCredentials } : {}),+ ...(isHealthCheckBeingCleared+ ? { lastHealthCheckRanAt: null, lastHealthCheckStatus: null, lastHealthCheckMessage: null }+ : {})});+ if (isHealthCheckBeingCleared) {+ await pkiSyncDAL.clearReportedHealthCheckFailure(id, HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS);+ }+return updatedPkiSync as TPkiSync;};@@ -846,6 +874,118 @@ export const pkiSyncServiceFactory = ({return { message: "PKI sync job added to queue successfully" };};+ const $resolveHealthCheckTestTarget = async (args: {+ projectId: string;+ applicationId?: string;+ syncId?: string;+ name?: string;+ }) => {+ if (args.syncId) {+ const pkiSync = await pkiSyncDAL.findById(args.syncId);+ if (!pkiSync || pkiSync.projectId !== args.projectId) {+ throw new NotFoundError({ message: `PKI sync with id "${args.syncId}" not found` });+ }++ return { projectId: pkiSync.projectId, applicationId: pkiSync.applicationId, name: pkiSync.name };+ }++ if (args.applicationId) {+ return { projectId: args.projectId, applicationId: args.applicationId, name: args.name ?? "" };+ }++ if (!args.name) {+ throw new BadRequestError({+ message:+ "Provide the application, the sync's name, or the id of the sync being edited, so the command can be authorized."+ });+ }++ return { projectId: args.projectId, name: args.name };+ };++ const testPkiSyncHealthCheckCommand = async (+ args: {+ destination: PkiSync;+ connectionId: string;+ applicationId?: string;+ syncId?: string;+ name?: string;+ destinationConfig: Record<string, unknown>;+ syncOptions: Record<string, unknown>;+ projectId: string;+ },+ actor: OrgServiceActor,+ auditLogInfo?: AuditLogInfo+ ) => {+ await $assertSyncAction(+ ProjectPermissionPkiSyncActions.SetHealthCheckCommand,+ ResourcePermissionPkiSyncActions.SetHealthCheckCommand,+ await $resolveHealthCheckTestTarget(args),+ undefined,+ actor+ );++ const command = assertHealthCheckCommandIsTestable(args.syncOptions);++ const connection = await appConnectionService.connectAppConnectionById(+ getDestinationAppType(args.destination),+ args.connectionId,+ actor+ );++ $assertHostCommandsAreSupported(args.destination, args.syncOptions, connection);++ const result = await pkiSyncHealthCheckQueue.testHealthCheckCommand({+ destination: args.destination,+ connectionId: args.connectionId,+ destinationConfig: args.destinationConfig,+ syncOptions: args.syncOptions+ });++ await auditLogService.createAuditLog({+ ...(auditLogInfo ?? { actor: { type: ActorType.PLATFORM, metadata: {} } }),+ projectId: args.projectId,+ event: {+ type: EventType.PKI_SYNC_TEST_HEALTH_CHECK,+ metadata: {+ connectionId: args.connectionId,+ connectionName: connection.name,+ destination: args.destination,+ command,+ ranAt: new Date(),+ result+ }+ }+ });++ return toHealthCheckApiResult(result);+ };++ const runPkiSyncHealthCheckById = async (+ { id }: { id: string },+ actor: OrgServiceActor,+ auditLogInfo?: AuditLogInfo+ ) => {+ const pkiSync = await pkiSyncDAL.findById(id);+ if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });++ await $assertSyncAction(+ ProjectPermissionPkiSyncActions.SyncCertificates,+ ResourcePermissionPkiSyncActions.SyncCertificates,+ pkiSync,+ undefined,+ actor+ );++ if (!getHealthCheckCommand(pkiSync.syncOptions)) {+ throw new BadRequestError({+ message: `PKI sync '${pkiSync.name}' has no health check configured. Add one under the sync's Commands step first.`+ });+ }++ return toHealthCheckApiResult(await pkiSyncHealthCheckQueue.runHealthCheckNow(id, auditLogInfo));+ };+const triggerPkiSyncImportCertificatesById = async ({ id }: Omit<TTriggerPkiSyncImportCertificatesByIdDTO, "auditLogInfo" | "projectId">,actor: OrgServiceActor@@ -1172,6 +1312,8 @@ export const pkiSyncServiceFactory = ({deletePkiSync,listPkiSyncsByProjectId,findPkiSyncById,+ runPkiSyncHealthCheckById,+ testPkiSyncHealthCheckCommand,triggerPkiSyncSyncCertificatesById,triggerPkiSyncImportCertificatesById,triggerPkiSyncRemoveCertificatesById,diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.tsindex 3d906dec77..7f49ea80bf 100644--- a/backend/src/services/pki-sync/pki-sync-types.ts+++ b/backend/src/services/pki-sync/pki-sync-types.ts@@ -61,6 +61,24 @@ export type TPkiSync = {} | null;};+export type THealthCheckTarget = {+ id: string;+ destination: PkiSync;+ destinationConfig: Record<string, unknown>;+ syncOptions: Record<string, unknown>;+ connection: {+ id: string;+ name: string;+ app: string;+ credentials: Record<string, unknown>;+ method?: string;+ orgId: string;+ gatewayId?: string;+ gatewayPoolId?: string | null;+ };+ syncCredentials?: { exportPassword?: string };+};+export type TPkiSyncWithCredentials = TPkiSync & {connection: {id: string;@@ -99,7 +117,7 @@ export type TPkiSyncSyncResult = {removed?: number;failedRemovals?: number;skipped: number;- preflightCheck?: THostCommandResult;+ healthCheck?: THostCommandResult;postSyncCommand?: THostCommandResult;details?: {failedUploads?: Array<{ name: string; error: string }>;@@ -248,7 +266,7 @@ export type TQueuePkiSyncImportCertificatesByIdDTO = {auditLogInfo?: AuditLogInfo;};-export type TQueuePkiSyncRunPreflightCheckByIdDTO = {+export type TQueuePkiSyncRunHealthCheckByIdDTO = {syncId: 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 3f0ca9bfb6..8ebbec72d1 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@@ -23,7 +23,7 @@ export const WINDOWS_SERVER_PKI_SYNC_LIST_OPTION = {canImportCertificates: false,canRemoveCertificates: true,canRunPostSyncCommand: true,- canRunPreflightCommand: true,+ canRunHealthCheckCommand: 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 20c28e47bc..76b927125a 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@@ -10,6 +10,14 @@ import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certiimport { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-schemas";import { exportCertificateForSync, PemCertificateExtension, PkiSyncExportFormat } from "../pki-sync-export-fns";+import {+ buildHealthCheckCommandFailureMessage,+ buildHealthCheckCommandPlan,+ buildHealthCheckFailureSyncResult,+ didHealthCheckFail,+ runHealthCheckCommand,+ THealthCheckCommandResult+} from "../pki-sync-health-check-command-fns";import {HOST_COMMAND_TIMEOUT_MS,HostCommandKind,@@ -19,15 +27,7 @@ import {toPowerShellLiteral} from "../pki-sync-host-command-fns";import { buildPostSyncCommandPlan, runPostSyncCommand, TPostSyncCommandPlan } from "../pki-sync-post-sync-command-fns";-import {- buildPreflightCommandFailureMessage,- buildPreflightCommandPlan,- buildPreflightFailureSyncResult,- didPreflightCheckFail,- runPreflightCommand,- TPreflightCommandResult-} from "../pki-sync-preflight-command-fns";-import { TCertificateMap, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "../pki-sync-types";+import { TCertificateMap, THealthCheckTarget, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "../pki-sync-types";import { TWindowsServerPkiSyncConfig } from "./windows-server-pki-sync-types";type TWindowsServerPkiSyncFactoryDeps = {@@ -47,7 +47,7 @@ type TWindowsServerSyncOptions = {includePrivateKey?: boolean;canRemoveCertificates?: boolean;fileAccessRules?: Array<{ identity: string; access: string }>;- preflightCommand?: string;+ healthCheckCommand?: string;postSyncCommand?: string;};@@ -61,7 +61,7 @@ const resolveWindowsExportOptions = (options: TWindowsServerSyncOptions) => ({const TRAILING_BACKSLASH = new RE2("\\\\+$");const joinWindowsPath = (dir: string, name: string): string => `${dir.replace(TRAILING_BACKSLASH, "")}\\${name}`;-const buildWinRMTarget = (pkiSync: TPkiSyncWithCredentials) => {+const buildWinRMTarget = (pkiSync: THealthCheckTarget) => {const { connection } = pkiSync;const credentials = connection.credentials as TWinRMConnection["credentials"];@@ -157,23 +157,23 @@ const executeWindowsServerHostCommand = async (return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };};-const runWindowsServerPreflightCommand = ({+const runWindowsServerHealthCheckCommand = ({pkiSync,certificateMap,target,gatewayDeps}: {- pkiSync: TPkiSyncWithCredentials;+ pkiSync: THealthCheckTarget;certificateMap: TCertificateMap;target: ReturnType<typeof buildWinRMTarget>;gatewayDeps: Parameters<typeof executeWinRMGatewayOperation>[1];-}): Promise<TPreflightCommandResult> | undefined => {+}): Promise<THealthCheckCommandResult> | undefined => {const options = (pkiSync.syncOptions ?? {}) as TWindowsServerSyncOptions;const config = pkiSync.destinationConfig as TWindowsServerPkiSyncConfig;const exportOptions = resolveWindowsExportOptions(options);- const plan = buildPreflightCommandPlan({- command: options.preflightCommand,+ const plan = buildHealthCheckCommandPlan({+ command: options.healthCheckCommand,destinationDirectory: config.destinationPath,certificateMap,exportOptions,@@ -183,10 +183,10 @@ const runWindowsServerPreflightCommand = ({});if (!plan) return undefined;- return runPreflightCommand({+ return runHealthCheckCommand({syncId: pkiSync.id,secretsToRedact: [plan.context.pkcs12Password],- execute: () => executeWindowsServerHostCommand(HostCommandKind.Preflight, plan, target, gatewayDeps)+ execute: () => executeWindowsServerHostCommand(HostCommandKind.HealthCheck, plan, target, gatewayDeps)});};@@ -236,12 +236,12 @@ export const windowsServerPkiSyncFactory = ({let uploaded = 0;let removed = 0;- const preflightCheck = await runWindowsServerPreflightCommand({ pkiSync, certificateMap, target, gatewayDeps });- if (preflightCheck && didPreflightCheckFail(preflightCheck)) {+ const healthCheck = await runWindowsServerHealthCheckCommand({ pkiSync, certificateMap, target, gatewayDeps });+ if (healthCheck && didHealthCheckFail(healthCheck)) {logger.info(- `Windows Server PKI sync [syncId=${pkiSync.id}]: preflight check failed, delivered nothing (${buildPreflightCommandFailureMessage(preflightCheck)})`+ `Windows Server PKI sync [syncId=${pkiSync.id}]: health check failed, delivered nothing (${buildHealthCheckCommandFailureMessage(healthCheck)})`);- return buildPreflightFailureSyncResult(certificateMap, preflightCheck);+ return buildHealthCheckFailureSyncResult(certificateMap, healthCheck);}// Deliver each certificate over its own gateway operation so one certificate's failure is@@ -354,7 +354,7 @@ export const windowsServerPkiSyncFactory = ({removed: removed > 0 ? removed : undefined,failedRemovals: failedRemovals.length > 0 ? failedRemovals.length : undefined,skipped: skippedCertificates.length,- preflightCheck,+ healthCheck,postSyncCommand,details: {failedUploads: failedUploads.length > 0 ? failedUploads : undefined,@@ -407,13 +407,13 @@ export const windowsServerPkiSyncFactory = ({}};- const runPreflightCheck = (pkiSync: TPkiSyncWithCredentials, certificateMap: TCertificateMap) =>- runWindowsServerPreflightCommand({+ const runHealthCheck = (pkiSync: THealthCheckTarget, certificateMap: TCertificateMap) =>+ runWindowsServerHealthCheckCommand({pkiSync,certificateMap,target: buildWinRMTarget(pkiSync),gatewayDeps});- return { syncCertificates, removeCertificates, runPreflightCheck };+ return { syncCertificates, removeCertificates, runHealthCheck };};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 3004fb0796..dc5ae58721 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@@ -76,7 +76,7 @@ export const WindowsServerPkiSyncOptionsSchema = z.object({).max(20).optional(),- preflightCommand: HostCommandSchema,+ healthCheckCommand: HostCommandSchema,postSyncCommand: HostCommandSchema,certificateNameSchema: z.string()@@ -150,3 +150,12 @@ export const WindowsServerPkiSyncListItemSchema = z.object({canImportCertificates: z.literal(false),canRemoveCertificates: z.literal(true)});++export const WindowsServerPkiSyncHealthCheckTestSchema = z.object({+ connectionId: z.string().uuid(),+ applicationId: z.string().uuid().optional(),+ syncId: z.string().uuid().optional(),+ name: z.string().trim().max(256).optional(),+ destinationConfig: WindowsServerPkiSyncConfigSchema,+ syncOptions: WindowsServerPkiSyncOptionsSchema.partial()+});diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdxindex 1c65518a50..2ed5da96eb 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx@@ -6,8 +6,8 @@ description: "Deploy certificates to Linux servers over SSH."import PostSyncCommandVariables from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-variables.mdx";import PostSyncCommandFlow from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-flow.mdx";-import PreflightCheckVariables from "/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-variables.mdx";-import PreflightCheckFlow from "/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-flow.mdx";+import HealthCheckVariables from "/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-variables.mdx";+import HealthCheckFlow from "/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-flow.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.@@ -20,7 +20,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 [preflight check](#preflight-checks) or a [post-sync command](#post-sync-commands), because the Gateway is what executes them. It must be running Infisical CLI v0.43.120 or later+- A Gateway is required to use a [health check](#health-checks) or a [post-sync command](#post-sync-commands), because the Gateway is what executes them. It must be running Infisical CLI v0.43.120 or later## Create a Linux Server sync@@ -48,7 +48,7 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.5. Configure the **Commands**, or leave them empty:- - **Preflight check**: A command run on the server before any certificate is written, to confirm the host is ready, for example `test -w /etc/ssl/certs`. A non-zero exit stops the sync, so nothing is delivered. See [Preflight Checks](#preflight-checks).+ - **Health check**: A command run on the server before any certificate is written, to confirm the host is ready, for example `test -w /etc/ssl/certs`. A non-zero exit stops the sync, so nothing is delivered. See [health checks](#health-checks).- **Post-sync 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`. See [Post-Sync Commands](#post-sync-commands).6. Configure the **Details**:@@ -80,7 +80,7 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi"includePrivateKey": true,"canRemoveCertificates": true,"certificateNameSchema": "{{commonName}}",- "preflightCommand": "test -w /etc/ssl/certs",+ "healthCheckCommand": "test -w /etc/ssl/certs","postSyncCommand": "sudo systemctl reload nginx"},"destinationConfig": {@@ -115,11 +115,11 @@ 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.-## Preflight checks+## Health checksA sync can only tell you the host was not ready once it has already tried. If the destination directory was renamed or the service that owns it is stopped, you find out from a failed sync, and on a renewal that is the day the certificate was going to expire anyway.-A preflight check moves that discovery earlier. It is one command that runs on the target server before any certificate is written. If it exits non-zero, the sync stops there: no files are delivered, no removals happen, and no post-sync command runs. Leaving the field empty means nothing runs, so there is no separate toggle.+A health check moves that discovery earlier. It is one command that runs on the target server before any certificate is written. If it exits non-zero, the sync stops there: no files are delivered, no removals happen, and no post-sync command runs. Leaving the field empty means nothing runs, so there is no separate toggle.The same check also runs on its own once a day, so a host that stops being ready between syncs is reported when it happens rather than at the next renewal.@@ -129,7 +129,7 @@ Write a check that answers a question rather than one that changes something. `tYour [Infisical Gateway](/documentation/platform/gateways/overview) runs the check, never Infisical. The sync's SSH Connection must therefore use a gateway, otherwise the check is rejected when you save the sync.</Note>-<PreflightCheckFlow />+<HealthCheckFlow />### Setting a check@@ -155,13 +155,13 @@ Write a check that answers a question rather than one that changes something. `t### Available variables-<PreflightCheckVariables />+<HealthCheckVariables />### Length limit-A check is limited to 8192 characters, counted after the variables are substituted. For anything longer, put the logic in a script on the server and call that script.+A check is limited to 8192 characters, counted as you write it, before variables are substituted. For anything longer, put the logic in a script on the server and call that script.-### Preflight check FAQ+### Health check FAQ<AccordionGroup><Accordion title="When exactly does the check run?">@@ -174,13 +174,13 @@ A check is limited to 8192 characters, counted after the variables are substitutA failing daily check marks the sync failed and puts the reason in its last error, the same place a failed sync run reports one, so a broken host shows up wherever you already watch your syncs. A passing check changes nothing. Either way the run is recorded in the sync's logs with the command and its full output.</Accordion><Accordion title="Is there a time limit?">- Yes, 10 seconds, and a check that runs out of time counts as a failure. The limit is deliberately much shorter than the post-sync command's, because the check gates delivery: a host that cannot answer a readiness question in ten seconds is itself the problem worth reporting. Keep the check to a question that is cheap to answer.+ Yes, 15 seconds, and a check that runs out of time counts as a failure. The limit is deliberately much shorter than the post-sync command's, because the check gates delivery: a host that cannot answer a readiness question in fifteen seconds is itself the problem worth reporting. Keep the check to a question that is cheap to answer.</Accordion><Accordion title="Does a failed check get retried?">Not within the run. A host that is not ready is usually not ready a few seconds later either, so retrying only delays the report. The next sync or the next daily check is the retry.</Accordion><Accordion title="Can I use it to prepare the host instead of just checking it?">- You can, since it is a free-text command, but prefer not to. A check that also does work runs before every sync and has ten seconds to finish, and if it fails halfway you have changed the host and delivered nothing. Keep preparation in the post-sync command, or in a script the check only verifies the result of.+ You can, since it is a free-text command, but prefer not to. A check that also does work runs before every sync and has fifteen seconds to finish, and if it fails halfway you have changed the host and delivered nothing. Keep preparation in the post-sync command, or in a script the check only verifies the result of.</Accordion></AccordionGroup>@@ -224,7 +224,7 @@ The field accepts a whole script, so several steps can run in one go: put each o### Length limit-A command is limited to 8192 characters, counted after the variables are substituted. For anything longer, put the logic in a script on the server and call that script.+A command is limited to 8192 characters, counted as you write it, before variables are substituted. For anything longer, put the logic in a script on the server and call that script.### Post-sync command FAQ@@ -257,7 +257,7 @@ A command is limited to 8192 characters, counted after the variables are substit### Least privilege-Both the preflight check and the post-sync command run as the account the SSH Connection authenticates with, so constraining that account bounds what either can do. A service reload does not need root. Grant the connection user a `sudoers` rule for that one command instead:+Both the health check and the post-sync command run as the account the SSH Connection authenticates with, so constraining that account bounds what either can do. A service reload does not need root. Grant the connection user a `sudoers` rule for that one command instead:```textsvc-infisical ALL=(root) NOPASSWD: /usr/bin/systemctl reload nginxdiff --git a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdxindex a3cd9a12a6..b6a128c943 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx@@ -6,8 +6,8 @@ description: "Deploy certificates to Windows servers over WinRM."import PostSyncCommandVariables from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-variables.mdx";import PostSyncCommandFlow from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-flow.mdx";-import PreflightCheckVariables from "/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-variables.mdx";-import PreflightCheckFlow from "/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-flow.mdx";+import HealthCheckVariables from "/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-variables.mdx";+import HealthCheckFlow from "/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-flow.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.@@ -50,7 +50,7 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.5. Configure the **Commands**, or leave them empty:- - **Preflight check**: A PowerShell command run on the server before any certificate is written, to confirm the host is ready, for example `Get-Service W3SVC | Where-Object Status -ne 'Running' | ForEach-Object { throw "W3SVC is not running" }`. A failure stops the sync, so nothing is delivered. See [Preflight Checks](#preflight-checks).+ - **Health check**: A PowerShell command run on the server before any certificate is written, to confirm the host is ready, for example `Get-Service W3SVC | Where-Object Status -ne 'Running' | ForEach-Object { throw "W3SVC is not running" }`. A failure stops the sync, so nothing is delivered. See [health checks](#health-checks).- **Post-sync 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"`. See [Post-Sync Commands](#post-sync-commands).6. Configure the **Details**:@@ -84,7 +84,7 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM"exportFormat": "pkcs12","canRemoveCertificates": true,"certificateNameSchema": "{{commonName}}",- "preflightCommand": "if (-not (Test-Path {{certificateDirectory}})) { throw \"destination folder is missing\" }",+ "healthCheckCommand": "if (-not (Test-Path {{certificateDirectory}})) { throw \"destination folder is missing\" }","postSyncCommand": "Restart-Service -Name W3SVC"},"destinationConfig": {@@ -123,17 +123,17 @@ 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.-## Preflight checks+## Health checksA sync can only tell you the host was not ready once it has already tried. If the destination folder was renamed or the service that owns the certificate is stopped, you find out from a failed sync, and on a renewal that is the day the certificate was going to expire anyway.-A preflight check moves that discovery earlier. It is one PowerShell command that the Gateway runs on the target server before any certificate is written. If it fails, the sync stops there: no files are delivered, no removals happen, and no post-sync command runs. Leaving the field empty means nothing runs, so there is no separate toggle.+A health check moves that discovery earlier. It is one PowerShell command that the Gateway runs on the target server before any certificate is written. If it fails, the sync stops there: no files are delivered, no removals happen, and no post-sync command runs. Leaving the field empty means nothing runs, so there is no separate toggle.The same check also runs on its own once a day, so a host that stops being ready between syncs is reported when it happens rather than at the next renewal.Write a check that answers a question rather than one that changes something. Testing that the folder exists or that a service is running is a good check. Creating the folder or starting the service is work for the post-sync command.-<PreflightCheckFlow />+<HealthCheckFlow />### Setting a check@@ -156,15 +156,15 @@ Write a check that answers a question rather than one that changes something. Te### Available variables-<PreflightCheckVariables />+<HealthCheckVariables />### Length limit-A check is limited to 8192 characters, counted after the variables are substituted. For anything longer, put the logic in a script file on the server and have the check call that script.+A check is limited to 8192 characters, counted as you write it, before variables are substituted. For anything longer, put the logic in a script file on the server and have the check call that script.Going past 2048 characters requires a Gateway on Infisical CLI v0.43.124 or later. See the Gateway version note above.-### Preflight check FAQ+### Health check FAQ<AccordionGroup><Accordion title="When exactly does the check run?">@@ -180,15 +180,15 @@ Going past 2048 characters requires a Gateway on Infisical CLI v0.43.124 or lateA failing daily check marks the sync failed and puts the reason in its last error, the same place a failed sync run reports one, so a broken host shows up wherever you already watch your syncs. A passing check changes nothing. Either way the run is recorded in the sync's logs with the command and its full output.</Accordion><Accordion title="Is there a time limit?">- Yes, 10 seconds, and a check that runs out of time counts as a failure. The limit is deliberately much shorter than the post-sync command's, because the check gates delivery: a host that cannot answer a readiness question in ten seconds is itself the problem worth reporting. Keep the check to a question that is cheap to answer.+ Yes, 15 seconds, and a check that runs out of time counts as a failure. The limit is deliberately much shorter than the post-sync command's, because the check gates delivery: a host that cannot answer a readiness question in fifteen seconds is itself the problem worth reporting. Keep the check to a question that is cheap to answer.- On Windows the ten seconds bound how long Infisical waits, not the host. WinRM gives no way to cancel a command once it has started, so a check that hangs is reported as a timeout and the sync fails, but the command itself keeps running on the server until it finishes. This is the other reason to keep a check to a cheap question rather than real work.+ On Windows the fifteen seconds bound how long Infisical waits, not the host. WinRM gives no way to cancel a command once it has started, so a check that hangs is reported as a timeout and the sync fails, but the command itself keeps running on the server until it finishes. This is the other reason to keep a check to a cheap question rather than real work.</Accordion><Accordion title="Does a failed check get retried?">Not within the run. A host that is not ready is usually not ready a few seconds later either, so retrying only delays the report. The next sync or the next daily check is the retry.</Accordion><Accordion title="Can I use it to prepare the host instead of just checking it?">- You can, since it is a free-text command, but prefer not to. A check that also does work runs before every sync and has ten seconds to finish, and if it fails halfway you have changed the host and delivered nothing. Keep preparation in the post-sync command, or in a script the check only verifies the result of.+ You can, since it is a free-text command, but prefer not to. A check that also does work runs before every sync and has fifteen seconds to finish, and if it fails halfway you have changed the host and delivered nothing. Keep preparation in the post-sync command, or in a script the check only verifies the result of.</Accordion></AccordionGroup>@@ -232,7 +232,7 @@ Your Gateway runs the command, never Infisical. A WinRM Connection already requi### Length limit-A command is limited to 8192 characters, counted after the variables are substituted. For anything longer, put the logic in a script on the server and call that script.+A command is limited to 8192 characters, counted as you write it, before variables are substituted. For anything longer, put the logic in a script on the server and call that script.Going past 2048 characters requires a Gateway on Infisical CLI v0.43.124 or later. See the Gateway version note above.@@ -268,7 +268,7 @@ Going past 2048 characters requires a Gateway on Infisical CLI v0.43.124 or late### Least privilege-Both the preflight check and the post-sync command run as the account the WinRM Connection authenticates with, so constraining that account bounds what either 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.+Both the health check and the post-sync command run as the account the WinRM Connection authenticates with, so constraining that account bounds what either 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.diff --git a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-flow.mdx b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-flow.mdxsimilarity index 92%rename from docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-flow.mdxrename to docs/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-flow.mdxindex 9fa29776d4..1ccc00287a 100644--- a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-flow.mdx+++ b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-flow.mdx@@ -5,7 +5,7 @@ sequenceDiagramparticipant I as Infisicalparticipant G as Gatewayparticipant S as Target server- I->>G: Run the preflight check+ I->>G: Run the health checkG->>S: Execute as the connection's accountS-->>G: Output and outcomeG-->>I: Ready, or the reason it is notdiff --git a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-variables.mdx b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-variables.mdxsimilarity index 100%rename from docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-variables.mdxrename to docs/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-variables.mdxdiff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsxindex d1a133ef85..6defb9fccc 100644--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx@@ -31,8 +31,8 @@ import {PkiSync,PkiSyncExportFormat,TPkiSync,+ useCanSetHealthCheckCommand,useCanSetPostSyncCommand,- useCanSetPreflightCommand,useCreatePkiSync,usePkiSyncOption} from "@app/hooks/api/pkiSyncs";@@ -43,9 +43,9 @@ import { PkiSyncCertificatesFields } from "./PkiSyncCertificatesFields";import { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";import { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";import { PkiSyncFieldMappingsFields } from "./PkiSyncFieldMappingsFields";+import { PkiSyncHealthCheckCommandFields } from "./PkiSyncHealthCheckCommandFields";import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields";import { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";-import { PkiSyncPreflightCommandFields } from "./PkiSyncPreflightCommandFields";import { PkiSyncReviewFields } from "./PkiSyncReviewFields";type Props = {@@ -86,7 +86,7 @@ const STEP_META: Record<subtitle: "Optionally check the host before the sync, and act on it afterward.",rightLabel: "COMMANDS",rightDescription:- "The preflight check runs first and stops the sync if the host is not ready, so a bad host never receives a certificate. The post-sync command runs afterward, once the run's files are in place, so a service can reload and pick up the new certificate. It only runs when the sync delivers a file. Either command failing marks the sync failed."+ "The health check runs first and stops the sync if the host is not ready, so a bad host never receives a certificate. The post-sync command runs afterward, once the run's files are in place, so a service can reload and pick up the new certificate. It only runs when the sync delivers a file. Either command failing marks the sync failed."},details: {short: "Name and description",@@ -141,7 +141,7 @@ const getFormTabs = (name: "Commands",key: "hostCommands",fields: [- "syncOptions.preflightCommand",+ "syncOptions.healthCheckCommand","syncOptions.postSyncCommand"] as FieldPath<TPkiSyncForm>[]});@@ -180,10 +180,10 @@ export const CreatePkiSyncForm = ({const { syncOption } = usePkiSyncOption(destination);const canSetPostSyncCommand = useCanSetPostSyncCommand(applicationId);- const canSetPreflightCommand = useCanSetPreflightCommand(applicationId);+ const canSetHealthCheckCommand = useCanSetHealthCheckCommand(applicationId);const FORM_TABS = getFormTabs(destination,- (Boolean(syncOption?.canRunPreflightCommand) && canSetPreflightCommand) ||+ (Boolean(syncOption?.canRunHealthCheckCommand) && canSetHealthCheckCommand) ||(Boolean(syncOption?.canRunPostSyncCommand) && canSetPostSyncCommand));@@ -383,9 +383,10 @@ export const CreatePkiSyncForm = ({{currentKey === "mappings" && <PkiSyncFieldMappingsFields destination={destination} />}{currentKey === "hostCommands" && (<div className="flex flex-col gap-8">- <PkiSyncPreflightCommandFields+ <PkiSyncHealthCheckCommandFieldsdestination={destination}- canEditCommand={canSetPreflightCommand}+ applicationId={applicationId}+ canEditCommand={canSetHealthCheckCommand}/><PkiSyncPostSyncCommandFieldsdestination={destination}diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsxindex b6d116fb2e..dac3dbed96 100644--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx@@ -19,8 +19,8 @@ import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";import {PkiSync,TPkiSync,+ useCanSetHealthCheckCommand,useCanSetPostSyncCommand,- useCanSetPreflightCommand,usePkiSyncOption,useUpdatePkiSync} from "@app/hooks/api/pkiSyncs";@@ -29,9 +29,9 @@ import { TUpdatePkiSyncForm, UpdatePkiSyncFormSchema } from "./schemas/pki-sync-import { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";import { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";import { PkiSyncFieldMappingsFields } from "./PkiSyncFieldMappingsFields";+import { PkiSyncHealthCheckCommandFields } from "./PkiSyncHealthCheckCommandFields";import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields";import { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";-import { PkiSyncPreflightCommandFields } from "./PkiSyncPreflightCommandFields";type Props = {onComplete: (pkiSync: TPkiSync) => void;@@ -96,7 +96,7 @@ const getFormSteps = (destination: PkiSync, canRunHostCommands: boolean): FormStsubtitle: "Optionally check the host before the sync, and act on it afterward.",rightLabel: "COMMANDS",rightDescription:- "The preflight check runs first and stops the sync if the host is not ready, so a bad host never receives a certificate. The post-sync command runs afterward, once the run's files are in place, so a service can reload and pick up the new certificate. It only runs when the sync delivers a file. Either command failing marks the sync failed."+ "The health check runs first and stops the sync if the host is not ready, so a bad host never receives a certificate. The post-sync command runs afterward, once the run's files are in place, so a service can reload and pick up the new certificate. It only runs when the sync delivers a file. Either command failing marks the sync failed."});}@@ -119,10 +119,10 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }const { name: destinationName } = PKI_SYNC_MAP[pkiSync.destination];const { syncOption } = usePkiSyncOption(pkiSync.destination);const canSetPostSyncCommand = useCanSetPostSyncCommand(pkiSync.applicationId);- const canSetPreflightCommand = useCanSetPreflightCommand(pkiSync.applicationId);+ const canSetHealthCheckCommand = useCanSetHealthCheckCommand(pkiSync.applicationId);const steps = getFormSteps(pkiSync.destination,- Boolean(syncOption?.canRunPreflightCommand || syncOption?.canRunPostSyncCommand)+ Boolean(syncOption?.canRunHealthCheckCommand || syncOption?.canRunPostSyncCommand));const [selectedStepIndex, setSelectedStepIndex] = useState(0);@@ -214,9 +214,11 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }case "hostCommands":return (<div className="flex flex-col gap-8">- <PkiSyncPreflightCommandFields+ <PkiSyncHealthCheckCommandFieldsdestination={pkiSync.destination}- canEditCommand={canSetPreflightCommand}+ applicationId={pkiSync.applicationId}+ syncId={pkiSync.id}+ canEditCommand={canSetHealthCheckCommand}/><PkiSyncPostSyncCommandFieldsdestination={pkiSync.destination}diff --git a/frontend/src/components/pki-syncs/forms/HostCommandField.tsx b/frontend/src/components/pki-syncs/forms/HostCommandField.tsxindex 3f9f6e24b8..8a3cf1a3d7 100644--- a/frontend/src/components/pki-syncs/forms/HostCommandField.tsx+++ b/frontend/src/components/pki-syncs/forms/HostCommandField.tsx@@ -19,6 +19,7 @@ type Props = {noPermissionDescription: string;placeholder?: string;canEditCommand?: boolean;+ action?: ReactNode;};export const HostCommandField = ({@@ -30,7 +31,8 @@ export const HostCommandField = ({description,noPermissionDescription,placeholder,- canEditCommand = true+ canEditCommand = true,+ action}: Props) => {const { control, watch } = useFormContext<TPkiSyncForm>();const isPkcs12 = watch("syncOptions.exportFormat") === PkiSyncExportFormat.Pkcs12;@@ -66,6 +68,7 @@ export const HostCommandField = ({<FieldDescription>{canEditCommand ? description : noPermissionDescription}</FieldDescription>+ {action}<FieldError>{error?.message}</FieldError></Field>)}diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsxnew file mode 100644index 0000000000..5e8f946156--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx@@ -0,0 +1,97 @@+import { useFormContext } from "react-hook-form";++import { createNotification } from "@app/components/notifications";+import { Button } from "@app/components/v3";+import { HEALTH_CHECK_COMMAND_VARIABLE_DESCRIPTIONS } from "@app/helpers/pkiSyncs";+import { PkiSync, PkiSyncStatus, useTestPkiSyncHealthCheck } from "@app/hooks/api/pkiSyncs";++import { TPkiSyncForm } from "./schemas/pki-sync-schema";+import { notifyUnhandledHostCommandError } from "./hostCommandErrors";+import { HostCommandField } from "./HostCommandField";++const COMMAND_PLACEHOLDERS: Partial<Record<PkiSync, string>> = {+ [PkiSync.LinuxServer]: "test -w {{certificateDirectory}} && systemctl is-active nginx",+ [PkiSync.WindowsServer]:+ 'if (-not (Test-Path {{certificateDirectory}})) { throw "destination directory is missing" }'+};++type Props = {+ destination?: PkiSync;+ applicationId?: string | null;+ syncId?: string;+ canEditCommand?: boolean;+};++export const PkiSyncHealthCheckCommandFields = ({+ destination,+ applicationId,+ syncId,+ canEditCommand+}: Props) => {+ const { watch } = useFormContext<TPkiSyncForm>();+ const testHealthCheck = useTestPkiSyncHealthCheck();++ const effectiveDestination = destination ?? watch("destination");+ const command = watch("syncOptions.healthCheckCommand");+ const connectionId = watch("connection.id");+ const destinationConfig = watch("destinationConfig");++ const handleTest = async () => {+ try {+ const result = await testHealthCheck.mutateAsync({+ destination: effectiveDestination,+ connectionId,+ applicationId: applicationId ?? undefined,+ syncId,+ name: syncId ? undefined : watch("name"),+ destinationConfig: (destinationConfig ?? {}) as Record<string, unknown>,+ syncOptions: { healthCheckCommand: command }+ });+ const passed = result.status === PkiSyncStatus.Succeeded;+ createNotification({+ title: passed ? "Health check passed" : "Health check failed",+ text:+ result.output || result.failureDetail || result.message || "The host reported no output.",+ type: passed ? "success" : "error"+ });+ } catch (error) {+ notifyUnhandledHostCommandError(error, "Could not run the health check");+ }+ };++ return (+ <HostCommandField+ name="syncOptions.healthCheckCommand"+ id="health-check-command"+ label="Health check"+ descriptions={HEALTH_CHECK_COMMAND_VARIABLE_DESCRIPTIONS}+ placeholder={COMMAND_PLACEHOLDERS[destination ?? watch("destination")]}+ canEditCommand={canEditCommand}+ tooltipFooter={+ <>+ Type <span className="font-mono">{"{{"}</span> in the command to pick one. The paths+ describe the files this run is about to write, so a check can look at where a certificate+ is going before it goes there. Each variable is inserted already quoted, so do not wrap+ one in quotes yourself.+ </>+ }+ description="Runs before any certificate is written. A non-zero exit stops the sync, so nothing is delivered to a host that is not ready. Also runs once a day on its own, so you hear about a host that went bad before the next renewal does. Capped at 15 seconds."+ noPermissionDescription="You do not have permission to set a health check on this sync. Ask an administrator to change it."+ action={+ canEditCommand !== false && (+ <div className="mt-2">+ <Button+ size="xs"+ variant="outline"+ isDisabled={!command || !connectionId}+ isPending={testHealthCheck.isPending}+ onClick={handleTest}+ >+ Test check+ </Button>+ </div>+ )+ }+ />+ );+};diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncPreflightCommandFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncPreflightCommandFields.tsxdeleted file mode 100644index 18e6d38a0d..0000000000--- a/frontend/src/components/pki-syncs/forms/PkiSyncPreflightCommandFields.tsx+++ /dev/null@@ -1,43 +0,0 @@-import { useFormContext } from "react-hook-form";--import { PREFLIGHT_COMMAND_VARIABLE_DESCRIPTIONS } from "@app/helpers/pkiSyncs";-import { PkiSync } from "@app/hooks/api/pkiSyncs";--import { TPkiSyncForm } from "./schemas/pki-sync-schema";-import { HostCommandField } from "./HostCommandField";--const COMMAND_PLACEHOLDERS: Partial<Record<PkiSync, string>> = {- [PkiSync.LinuxServer]: "test -w {{certificateDirectory}} && systemctl is-active nginx",- [PkiSync.WindowsServer]:- 'if (-not (Test-Path {{certificateDirectory}})) { throw "destination directory is missing" }'-};--type Props = {- destination?: PkiSync;- canEditCommand?: boolean;-};--export const PkiSyncPreflightCommandFields = ({ destination, canEditCommand }: Props) => {- const { watch } = useFormContext<TPkiSyncForm>();-- return (- <HostCommandField- name="syncOptions.preflightCommand"- id="preflight-command"- label="Preflight check"- descriptions={PREFLIGHT_COMMAND_VARIABLE_DESCRIPTIONS}- placeholder={COMMAND_PLACEHOLDERS[destination ?? watch("destination")]}- canEditCommand={canEditCommand}- tooltipFooter={- <>- Type <span className="font-mono">{"{{"}</span> in the command to pick one. The paths- describe the files this run is about to write, so a check can look at where a certificate- is going before it goes there. Each variable is inserted already quoted, so do not wrap- one in quotes yourself.- </>- }- description="Runs before any certificate is written. A non-zero exit stops the sync, so nothing is delivered to a host that is not ready. Also runs once a day on its own, so you hear about a host that went bad before the next renewal does. Capped at 10 seconds."- noPermissionDescription="You do not have permission to set a preflight check on this sync. Ask an administrator to change it."- />- );-};diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsxindex 3d287a0357..6ca36220fa 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx@@ -69,8 +69,8 @@ export const PkiSyncReviewFields = () => {const selectedCertificates = getSelectedCertificates(certificateIds);const postSyncCommand =syncOptions && "postSyncCommand" in syncOptions ? syncOptions.postSyncCommand : undefined;- const preflightCommand =- syncOptions && "preflightCommand" in syncOptions ? syncOptions.preflightCommand : undefined;+ const healthCheckCommand =+ syncOptions && "healthCheckCommand" in syncOptions ? syncOptions.healthCheckCommand : undefined;return (<div className="mb-4 flex flex-col gap-6">@@ -181,12 +181,12 @@ export const PkiSyncReviewFields = () => {})}</div></div>- {preflightCommand && (+ {healthCheckCommand && (<div className="flex flex-col gap-3"><div className="w-full border-b border-border">- <span className="text-sm text-muted">Preflight Check</span>+ <span className="text-sm text-muted">Health Check</span></div>- <CodeBlock value={preflightCommand} className="max-h-48 whitespace-pre-wrap" />+ <CodeBlock value={healthCheckCommand} className="max-h-48 whitespace-pre-wrap" /></div>)}{postSyncCommand && (diff --git a/frontend/src/components/pki-syncs/forms/hostCommandErrors.ts b/frontend/src/components/pki-syncs/forms/hostCommandErrors.tsnew file mode 100644index 0000000000..f398269a19--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/hostCommandErrors.ts@@ -0,0 +1,14 @@+import axios from "axios";++import { createNotification } from "@app/components/notifications";+import { ApiErrorTypes, TApiErrors } from "@app/hooks/api/types";++export const notifyUnhandledHostCommandError = (error: unknown, title: string) => {+ if (!axios.isAxiosError(error)) return;++ const serverResponse = error.response?.data as TApiErrors | undefined;+ if (serverResponse?.error !== ApiErrorTypes.BadRequestError) return;++ const text = typeof serverResponse.message === "string" ? serverResponse.message : "Try again.";+ createNotification({ title, text, type: "error" });+};diff --git a/frontend/src/components/pki-syncs/forms/index.ts b/frontend/src/components/pki-syncs/forms/index.tsindex 7c5647f7fc..89810f60e2 100644--- a/frontend/src/components/pki-syncs/forms/index.ts+++ b/frontend/src/components/pki-syncs/forms/index.ts@@ -2,8 +2,8 @@ export { CreatePkiSyncForm } from "./CreatePkiSyncForm";export { EditPkiSyncForm } from "./EditPkiSyncForm";export { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";export { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";+export { PkiSyncHealthCheckCommandFields } from "./PkiSyncHealthCheckCommandFields";export { PkiSyncOptionsFields } from "./PkiSyncOptionsFields/PkiSyncOptionsFields";export { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";-export { PkiSyncPreflightCommandFields } from "./PkiSyncPreflightCommandFields";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 bee898bde4..da8f07ddea 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,19 +1,14 @@import { AnyZodObject, z } from "zod";-export const POST_SYNC_COMMAND_MAX_LENGTH = 8192;+export const HOST_COMMAND_MAX_LENGTH = 8192;-export const PostSyncCommandSchema = z+export const HostCommandSchema = z.string().trim()- .max(- POST_SYNC_COMMAND_MAX_LENGTH,- `Command must be at most ${POST_SYNC_COMMAND_MAX_LENGTH} characters`- )+ .max(HOST_COMMAND_MAX_LENGTH, `Command must be at most ${HOST_COMMAND_MAX_LENGTH} characters`).nullish().transform((command) => command || null);-export const PreflightCommandSchema = PostSyncCommandSchema;-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 7222e34b7c..aa0618ed79 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,11 +2,7 @@ import { z } from "zod";import { PemCertificateExtension, PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";-import {- BasePkiSyncSchema,- PostSyncCommandSchema,- PreflightCommandSchema-} from "./base-pki-sync-schema";+import { BasePkiSyncSchema, HostCommandSchema } from "./base-pki-sync-schema";const compileNameSchema = (val: string) =>val@@ -58,8 +54,8 @@ const LinuxServerSyncOptionsSchema = z.object({}).transform((v) => v || undefined).optional(),- preflightCommand: PreflightCommandSchema,- postSyncCommand: PostSyncCommandSchema,+ healthCheckCommand: HostCommandSchema,+ postSyncCommand: HostCommandSchema,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 fed3a5c7ec..5037766d08 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,11 +7,7 @@ import {WindowsFileAccess} from "@app/hooks/api/pkiSyncs";-import {- BasePkiSyncSchema,- PostSyncCommandSchema,- PreflightCommandSchema-} from "./base-pki-sync-schema";+import { BasePkiSyncSchema, HostCommandSchema } from "./base-pki-sync-schema";const compileNameSchema = (val: string) =>val@@ -45,8 +41,8 @@ const WindowsServerSyncOptionsSchema = z.object({.max(20).optional(),includePrivateKey: z.boolean().default(true),- preflightCommand: PreflightCommandSchema,- postSyncCommand: PostSyncCommandSchema,+ healthCheckCommand: HostCommandSchema,+ postSyncCommand: HostCommandSchema,certificateNameSchema: z.string().trim()diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.tsindex 44e200b7a4..f77ff58ea8 100644--- a/frontend/src/context/ProjectPermissionContext/types.ts+++ b/frontend/src/context/ProjectPermissionContext/types.ts@@ -78,7 +78,7 @@ export enum ProjectPermissionPkiSyncActions {ImportCertificates = "import-certificates",RemoveCertificates = "remove-certificates",SetPostSyncCommand = "set-post-sync-command",- SetPreflightCommand = "set-preflight-command"+ SetHealthCheckCommand = "set-health-check-command"}export enum ProjectPermissionPkiDiscoveryActions {diff --git a/frontend/src/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.tsindex aa270e08bc..a593cdce2b 100644--- a/frontend/src/helpers/pkiSyncs.ts+++ b/frontend/src/helpers/pkiSyncs.ts@@ -158,7 +158,7 @@ export const POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS: Record<HostCommandVariable[HostCommandVariable.Pkcs12Password]: "The PKCS#12 export password"};-export const PREFLIGHT_COMMAND_VARIABLE_DESCRIPTIONS: Record<HostCommandVariable, string> = {+export const HEALTH_CHECK_COMMAND_VARIABLE_DESCRIPTIONS: Record<HostCommandVariable, string> = {[HostCommandVariable.CertificatePath]: "Full path of the certificate file this run will write",[HostCommandVariable.CertificateDirectory]: "The directory the sync is about to write to",[HostCommandVariable.CertificateFiles]: "Every path this run will write, one per line",diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex aac39cabd3..1f54acf137 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -190,7 +190,8 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.PKI_SYNC_SYNC_CERTIFICATES]: "PKI Sync synced certificates",[EventType.PKI_SYNC_IMPORT_CERTIFICATES]: "PKI Sync imported certificates",[EventType.PKI_SYNC_REMOVE_CERTIFICATES]: "PKI Sync removed certificates",- [EventType.PKI_SYNC_PREFLIGHT_CHECK]: "PKI Sync preflight check ran",+ [EventType.PKI_SYNC_HEALTH_CHECK]: "PKI Sync health check ran",+ [EventType.PKI_SYNC_TEST_HEALTH_CHECK]: "PKI Sync health check tested",[EventType.OIDC_GROUP_MEMBERSHIP_MAPPING_ASSIGN_USER]:"OIDC group membership mapping assigned user to groups",[EventType.OIDC_GROUP_MEMBERSHIP_MAPPING_REMOVE_USER]:diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex 9d1e265407..74931652bd 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -200,7 +200,8 @@ export enum EventType {PKI_SYNC_SYNC_CERTIFICATES = "pki-sync-sync-certificates",PKI_SYNC_IMPORT_CERTIFICATES = "pki-sync-import-certificates",PKI_SYNC_REMOVE_CERTIFICATES = "pki-sync-remove-certificates",- PKI_SYNC_PREFLIGHT_CHECK = "pki-sync-preflight-check",+ PKI_SYNC_HEALTH_CHECK = "pki-sync-health-check",+ PKI_SYNC_TEST_HEALTH_CHECK = "pki-sync-test-health-check",OIDC_GROUP_MEMBERSHIP_MAPPING_ASSIGN_USER = "oidc-group-membership-mapping-assign-user",OIDC_GROUP_MEMBERSHIP_MAPPING_REMOVE_USER = "oidc-group-membership-mapping-remove-user",CREATE_KMIP_CLIENT = "create-kmip-client",diff --git a/frontend/src/hooks/api/pkiApplications/types.ts b/frontend/src/hooks/api/pkiApplications/types.tsindex 2e50d467b7..c1696aec8f 100644--- a/frontend/src/hooks/api/pkiApplications/types.ts+++ b/frontend/src/hooks/api/pkiApplications/types.ts@@ -32,7 +32,7 @@ export enum PkiApplicationResourceActions {ImportCertificates = "import-certificates",RemoveCertificates = "remove-certificates",SetPostSyncCommand = "set-post-sync-command",- SetPreflightCommand = "set-preflight-command",+ SetHealthCheckCommand = "set-health-check-command",RevealAcmeEabSecret = "reveal-acme-eab-secret",RotateAcmeEabSecret = "rotate-acme-eab-secret",GenerateScepChallenge = "generate-scep-challenge",diff --git a/frontend/src/hooks/api/pkiSyncs/mutations.tsx b/frontend/src/hooks/api/pkiSyncs/mutations.tsxindex 0a1374a125..b285d47c01 100644--- a/frontend/src/hooks/api/pkiSyncs/mutations.tsx+++ b/frontend/src/hooks/api/pkiSyncs/mutations.tsx@@ -1,12 +1,13 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";-import { PkiSyncStatus } from "@app/hooks/api/pkiSyncs/enums";+import { PkiSync, PkiSyncStatus } from "@app/hooks/api/pkiSyncs/enums";import { pkiSyncKeys } from "@app/hooks/api/pkiSyncs/queries";import {TCreatePkiSyncDTO,TDeletePkiSyncDTO,TPkiSync,+ TPkiSyncHealthCheckResult,TTriggerPkiSyncImportCertificatesDTO,TTriggerPkiSyncRemoveCertificatesDTO,TTriggerPkiSyncSyncCertificatesDTO,@@ -68,6 +69,59 @@ export const useDeletePkiSync = () => {});};+export const useTestPkiSyncHealthCheck = () => {+ return useMutation({+ mutationFn: async ({+ destination,+ connectionId,+ applicationId,+ syncId,+ name,+ destinationConfig,+ syncOptions+ }: {+ destination: PkiSync;+ connectionId: string;+ applicationId?: string;+ syncId?: string;+ name?: string;+ destinationConfig: Record<string, unknown>;+ syncOptions: Record<string, unknown>;+ }) => {+ const { data } = await apiRequest.post<{ healthCheck: TPkiSyncHealthCheckResult }>(+ `/api/v1/cert-manager/syncs/${destination}/test-health-check`,+ { connectionId, applicationId, syncId, name, destinationConfig, syncOptions }+ );++ return data.healthCheck;+ }+ });+};++export const useRunPkiSyncHealthCheck = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({+ syncId,+ destination+ }: {+ syncId: string;+ destination: PkiSync;+ projectId: string;+ }) => {+ const { data } = await apiRequest.post<{ healthCheck: TPkiSyncHealthCheckResult }>(+ `/api/v1/cert-manager/syncs/${destination}/${syncId}/run-health-check`+ );++ return data.healthCheck;+ },+ onSuccess: (_, { syncId, projectId }) => {+ queryClient.invalidateQueries({ queryKey: pkiSyncKeys.byId(syncId, projectId) });+ queryClient.invalidateQueries({ queryKey: pkiSyncKeys.list(projectId) });+ }+ });+};+export const useTriggerPkiSyncSyncCertificates = () => {const queryClient = useQueryClient();return useMutation({diff --git a/frontend/src/hooks/api/pkiSyncs/types/common.ts b/frontend/src/hooks/api/pkiSyncs/types/common.tsindex cc55b307b5..05838b972a 100644--- a/frontend/src/hooks/api/pkiSyncs/types/common.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/common.ts@@ -19,6 +19,8 @@ export type RootPkiSyncOptions = {preserveItemOnRenewal?: boolean;updateExistingCertificates?: boolean;fieldMappings?: TChefFieldMappings;+ healthCheckCommand?: string | null;+ postSyncCommand?: string | null;};export type TRootPkiSync = {@@ -36,6 +38,9 @@ export type TRootPkiSync = {lastSyncJobId: string | null;lastSyncedAt: string | null;lastSyncMessage: string | null;+ lastHealthCheckRanAt: string | null;+ lastHealthCheckStatus: PkiSyncStatus | null;+ lastHealthCheckMessage: string | null;importStatus: PkiSyncStatus | null;lastImportJobId: string | null;lastImportedAt: string | null;@@ -84,3 +89,13 @@ export type TPkiSyncCertificate = {[key: string]: unknown;} | null;};++export type TPkiSyncHealthCheckResult = {+ status: PkiSyncStatus;+ exitCode?: number;+ timedOut?: boolean;+ durationMs: number;+ output?: string;+ failureDetail?: string;+ message?: string;+};diff --git a/frontend/src/hooks/api/pkiSyncs/types/index.ts b/frontend/src/hooks/api/pkiSyncs/types/index.tsindex 0caaea8b50..50766c3e5b 100644--- a/frontend/src/hooks/api/pkiSyncs/types/index.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/index.ts@@ -19,7 +19,7 @@ export type TPkiSyncOption = {canImportCertificates: boolean;canRemoveCertificates: boolean;canRunPostSyncCommand?: boolean;- canRunPreflightCommand?: boolean;+ canRunHealthCheckCommand?: 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 e0843031e9..8f8d6f13c6 100644--- a/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts@@ -17,7 +17,7 @@ export type TLinuxServerPkiSync = TRootPkiSync & {privateKeyFileMode?: string;owner?: string;group?: string;- preflightCommand?: string | null;+ healthCheckCommand?: string | null;postSyncCommand?: string | null;};connection: {diff --git a/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.tsindex c4c5e4eba9..e6ea11ea7e 100644--- a/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts@@ -14,7 +14,7 @@ export type TWindowsServerPkiSync = TRootPkiSync & {combineCertificateChain?: boolean;includePrivateKey?: boolean;fileAccessRules?: { identity: string; access: WindowsFileAccess }[];- preflightCommand?: string | null;+ healthCheckCommand?: string | null;postSyncCommand?: string | null;};connection: {diff --git a/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts b/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.tsindex 589cad4f00..3d7a1df20f 100644--- a/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts+++ b/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts@@ -20,8 +20,8 @@ const useCanSetHostCommand = (export const useCanSetPostSyncCommand = (applicationId?: string | null) =>useCanSetHostCommand(PkiApplicationResourceActions.SetPostSyncCommand, applicationId);-export const useCanSetPreflightCommand = (applicationId?: string | null) =>- useCanSetHostCommand(PkiApplicationResourceActions.SetPreflightCommand, applicationId);+export const useCanSetHealthCheckCommand = (applicationId?: string | null) =>+ useCanSetHostCommand(PkiApplicationResourceActions.SetHealthCheckCommand, applicationId);export const usePkiSyncPermissions = (pkiSync: TPkiSync) => {const { permission: projectPermission } = useProjectPermission();diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsxindex fcb53685b2..d5911badb5 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx@@ -30,12 +30,11 @@ import {PkiSyncActionTriggers,PkiSyncAuditLogsSection,PkiSyncCertificatesSection,+ PkiSyncCommandsSection,PkiSyncDestinationSection,PkiSyncDetailsSection,PkiSyncFieldMappingsSection,- PkiSyncOptionsSection,- PkiSyncPostSyncCommandSection,- PkiSyncPreflightCheckSection+ PkiSyncOptionsSection} from "./components";const PageContent = () => {@@ -138,9 +137,8 @@ const PageContent = () => {<PkiSyncDetailsSection pkiSync={pkiSync} /><PkiSyncDestinationSection pkiSync={pkiSync} /><PkiSyncFieldMappingsSection pkiSync={pkiSync} />- <PkiSyncPreflightCheckSection pkiSync={pkiSync} />- <PkiSyncPostSyncCommandSection pkiSync={pkiSync} /></DetailGroup>+ <PkiSyncCommandsSection pkiSync={pkiSync} /><PkiSyncOptionsSection pkiSync={pkiSync} /></CardContent></Card>diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/HostCommandDetail.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/HostCommandDetail.tsxindex 0c237c5d81..ee6895b1a7 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/HostCommandDetail.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/HostCommandDetail.tsx@@ -18,7 +18,7 @@ import {type Props = {label: string;- command?: string;+ command?: string | null;showCommandLabel: string;dialogDescription: string;};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsxindex a71f03ef5a..1f73f897b3 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx@@ -9,6 +9,7 @@ import {InfoIcon,PencilIcon,RefreshCwIcon,+ StethoscopeIcon,ToggleLeftIcon,ToggleRightIcon,Trash2Icon@@ -20,6 +21,7 @@ import {PkiSyncImportCertificatesModal,PkiSyncRemoveCertificatesModal} from "@app/components/pki-syncs";+import { notifyUnhandledHostCommandError } from "@app/components/pki-syncs/forms/hostCommandErrors";import {DropdownMenu,DropdownMenuContent,@@ -36,9 +38,11 @@ import { useOrganization } from "@app/context";import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";import { usePopUp, useToggle } from "@app/hooks";import {+ PkiSyncStatus,TPkiSync,usePkiSyncOption,usePkiSyncPermissions,+ useRunPkiSyncHealthCheck,useTriggerPkiSyncSyncCertificates,useUpdatePkiSync} from "@app/hooks/api/pkiSyncs";@@ -68,7 +72,11 @@ export const PkiSyncActionTriggers = ({ pkiSync, onEdit }: Props) => {const [isIdCopied, setIsIdCopied] = useToggle(false);+ const hasHealthCheckCommand = Boolean(+ (pkiSync.syncOptions as { healthCheckCommand?: string })?.healthCheckCommand+ );const triggerSyncMutation = useTriggerPkiSyncSyncCertificates();+ const runHealthCheckMutation = useRunPkiSyncHealthCheck();const updatePkiSyncMutation = useUpdatePkiSync();const { syncOption } = usePkiSyncOption(destination);@@ -101,6 +109,25 @@ export const PkiSyncActionTriggers = ({ pkiSync, onEdit }: Props) => {});}, [triggerSyncMutation, id, destination, projectId]);+ const handleRunHealthCheck = useCallback(async () => {+ try {+ const result = await runHealthCheckMutation.mutateAsync({+ syncId: id,+ destination,+ projectId+ });+ const passed = result.status === PkiSyncStatus.Succeeded;+ createNotification({+ title: passed ? "Health check passed" : "Health check failed",+ text:+ result.output || result.failureDetail || result.message || "The host reported no output.",+ type: passed ? "success" : "error"+ });+ } catch (error) {+ notifyUnhandledHostCommandError(error, "Could not run the health check");+ }+ }, [runHealthCheckMutation, id, destination, projectId]);+const handleToggleAutoSync = useCallback(async () => {await updatePkiSyncMutation.mutateAsync({syncId: id,@@ -132,6 +159,15 @@ export const PkiSyncActionTriggers = ({ pkiSync, onEdit }: Props) => {<RefreshCwIcon />Trigger Sync</DropdownMenuItem>+ {syncOption?.canRunHealthCheckCommand && hasHealthCheckCommand && (+ <DropdownMenuItem+ onClick={handleRunHealthCheck}+ isDisabled={!canTriggerSync || runHealthCheckMutation.isPending}+ >+ <StethoscopeIcon />+ Run Health Check+ </DropdownMenuItem>+ )}<DropdownMenuItemonClick={(e) => {e.stopPropagation();diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsxindex 4b537cef5b..8cf83b9d26 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsx@@ -11,7 +11,7 @@ const PKI_SYNC_EVENTS = [EventType.PKI_SYNC_SYNC_CERTIFICATES,EventType.PKI_SYNC_IMPORT_CERTIFICATES,EventType.PKI_SYNC_REMOVE_CERTIFICATES,- EventType.PKI_SYNC_PREFLIGHT_CHECK+ EventType.PKI_SYNC_HEALTH_CHECK];type Props = {diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsxnew file mode 100644index 0000000000..fdcdf62d40--- /dev/null+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsx@@ -0,0 +1,103 @@+import { format } from "date-fns";++import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+ Badge,+ Detail,+ DetailGroup,+ DetailLabel,+ DetailValue,+ Separator+} from "@app/components/v3";+import { getPkiSyncFailureMessage } from "@app/helpers/pkiSyncs";+import { PkiSyncStatus, TPkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";++import { HostCommandDetail } from "./HostCommandDetail";+import { SyncErrorDetail } from "./SyncErrorDetail";++type Props = {+ pkiSync: TPkiSync;+};++export const PkiSyncCommandsSection = ({ pkiSync }: Props) => {+ const { syncOption } = usePkiSyncOption(pkiSync.destination);+ const { healthCheckCommand, postSyncCommand } = pkiSync.syncOptions;++ const canRunHealthCheck = Boolean(syncOption?.canRunHealthCheckCommand);+ const canRunPostSync = Boolean(syncOption?.canRunPostSyncCommand);+ if (!canRunHealthCheck && !canRunPostSync) return null;++ const { lastHealthCheckRanAt, lastHealthCheckStatus, lastHealthCheckMessage } = pkiSync;++ const syncFailureMessage = getPkiSyncFailureMessage(pkiSync.syncStatus, pkiSync.lastSyncMessage);+ const checkErrorMessage =+ lastHealthCheckStatus === PkiSyncStatus.Failed &&+ lastHealthCheckMessage &&+ lastHealthCheckMessage !== syncFailureMessage+ ? lastHealthCheckMessage+ : null;++ return (+ <>+ <Separator className="mt-4" />+ <Accordion type="multiple" variant="ghost">+ <AccordionItem value="commands">+ <AccordionTrigger>Commands</AccordionTrigger>+ <AccordionContent>+ <DetailGroup>+ {canRunHealthCheck && (+ <>+ <HostCommandDetail+ label="Health Check"+ command={healthCheckCommand}+ showCommandLabel="Show check"+ dialogDescription="Runs on the destination host before this sync delivers anything. A non-zero exit stops the sync."+ />+ {healthCheckCommand && (+ <Detail>+ <DetailLabel>Last Checked</DetailLabel>+ <DetailValue>+ {lastHealthCheckRanAt ? (+ <div className="flex items-center gap-2">+ <Badge+ variant={+ lastHealthCheckStatus === PkiSyncStatus.Failed+ ? "danger"+ : "success"+ }+ >+ {lastHealthCheckStatus === PkiSyncStatus.Failed ? "Failed" : "Passed"}+ </Badge>+ <span>+ {format(new Date(lastHealthCheckRanAt), "yyyy-MM-dd, h:mm a")}+ </span>+ </div>+ ) : (+ <span className="text-muted/50 italic">Never</span>+ )}+ </DetailValue>+ </Detail>+ )}+ {checkErrorMessage && (+ <SyncErrorDetail label="Last Check Error" message={checkErrorMessage} />+ )}+ </>+ )}+ {canRunPostSync && (+ <HostCommandDetail+ label="Post-Sync Command"+ command={postSyncCommand}+ showCommandLabel="Show command"+ dialogDescription="Runs on the destination host after this sync delivers a certificate."+ />+ )}+ </DetailGroup>+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ </>+ );+};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsxindex 168b4529e6..b476f0c6e2 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx@@ -6,6 +6,8 @@ import { Badge, Detail, DetailLabel, DetailValue } from "@app/components/v3";import { getPkiSyncFailureMessage } from "@app/helpers/pkiSyncs";import { TPkiSync } from "@app/hooks/api/pkiSyncs";+import { SyncErrorDetail } from "./SyncErrorDetail";+type Props = {pkiSync: TPkiSync;};@@ -47,14 +49,7 @@ export const PkiSyncDetailsSection = ({ pkiSync }: Props) => {<DetailValue>{format(new Date(lastSyncedAt), "yyyy-MM-dd, hh:mm aaa")}</DetailValue></Detail>)}- {failureMessage && (- <Detail>- <DetailLabel className="text-red">Last Sync Error</DetailLabel>- <DetailValue>- <p className="rounded-sm bg-mineshaft-600 p-2 text-xs break-words">{failureMessage}</p>- </DetailValue>- </Detail>- )}+ {failureMessage && <SyncErrorDetail label="Last Sync Error" message={failureMessage} />}</>);};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsxdeleted file mode 100644index 313ad54b30..0000000000--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { TPkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";--import { HostCommandDetail } from "./HostCommandDetail";--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 (- <HostCommandDetail- label="Post-Sync Command"- command={postSyncCommand}- showCommandLabel="Show command"- dialogDescription="Runs on the destination host after this sync delivers a certificate."- />- );-};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPreflightCheckSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPreflightCheckSection.tsxdeleted file mode 100644index 2c568002c1..0000000000--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPreflightCheckSection.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { TPkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";--import { HostCommandDetail } from "./HostCommandDetail";--type Props = {- pkiSync: TPkiSync;-};--export const PkiSyncPreflightCheckSection = ({ pkiSync }: Props) => {- const { syncOption } = usePkiSyncOption(pkiSync.destination);- const { preflightCommand } = pkiSync.syncOptions as { preflightCommand?: string };-- if (!syncOption?.canRunPreflightCommand) return null;-- return (- <HostCommandDetail- label="Preflight Check"- command={preflightCommand}- showCommandLabel="Show check"- dialogDescription="Runs on the destination host before this sync delivers anything. A non-zero exit stops the sync."- />- );-};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/SyncErrorDetail.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/SyncErrorDetail.tsxnew file mode 100644index 0000000000..2c38e7e62e--- /dev/null+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/SyncErrorDetail.tsx@@ -0,0 +1,15 @@+import { Detail, DetailLabel, DetailValue } from "@app/components/v3";++type Props = {+ label: string;+ message: string;+};++export const SyncErrorDetail = ({ label, message }: Props) => (+ <Detail>+ <DetailLabel className="text-red">{label}</DetailLabel>+ <DetailValue>+ <p className="rounded-sm bg-mineshaft-600 p-2 text-xs break-words">{message}</p>+ </DetailValue>+ </Detail>+);diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.tsindex ca7fe5da01..50aed809a1 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts@@ -1,9 +1,8 @@export { PkiSyncActionTriggers } from "./PkiSyncActionTriggers";export { PkiSyncAuditLogsSection } from "./PkiSyncAuditLogsSection";export { PkiSyncCertificatesSection } from "./PkiSyncCertificatesSection";+export { PkiSyncCommandsSection } from "./PkiSyncCommandsSection";export { PkiSyncDestinationSection } from "./PkiSyncDestinationSection";export { PkiSyncDetailsSection } from "./PkiSyncDetailsSection";export { PkiSyncFieldMappingsSection } from "./PkiSyncFieldMappingsSection";export { PkiSyncOptionsSection } from "./PkiSyncOptionsSection";-export { PkiSyncPostSyncCommandSection } from "./PkiSyncPostSyncCommandSection";-export { PkiSyncPreflightCheckSection } from "./PkiSyncPreflightCheckSection";diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsxindex b67688b501..1ca8930fda 100644--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx@@ -159,7 +159,7 @@ const PkiSyncPolicyActionSchema = z.object({[ProjectPermissionPkiSyncActions.ImportCertificates]: z.boolean().optional(),[ProjectPermissionPkiSyncActions.RemoveCertificates]: z.boolean().optional(),[ProjectPermissionPkiSyncActions.SetPostSyncCommand]: z.boolean().optional(),- [ProjectPermissionPkiSyncActions.SetPreflightCommand]: z.boolean().optional()+ [ProjectPermissionPkiSyncActions.SetHealthCheckCommand]: z.boolean().optional()});const CommitPolicyActionSchema = z.object({@@ -1101,8 +1101,8 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {const canSetPostSyncCommand = action.includes(ProjectPermissionPkiSyncActions.SetPostSyncCommand);- const canSetPreflightCommand = action.includes(- ProjectPermissionPkiSyncActions.SetPreflightCommand+ const canSetHealthCheckCommand = action.includes(+ ProjectPermissionPkiSyncActions.SetHealthCheckCommand);if (!formVal[subject]) formVal[subject] = [{ conditions: [], inverted: false }];@@ -1117,7 +1117,7 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {[ProjectPermissionPkiSyncActions.ImportCertificates]: canImportCertificates,[ProjectPermissionPkiSyncActions.RemoveCertificates]: canRemoveCertificates,[ProjectPermissionPkiSyncActions.SetPostSyncCommand]: canSetPostSyncCommand,- [ProjectPermissionPkiSyncActions.SetPreflightCommand]: canSetPreflightCommand,+ [ProjectPermissionPkiSyncActions.SetHealthCheckCommand]: canSetHealthCheckCommand,conditions: conditions ? convertCaslConditionToFormOperator(conditions) : [],inverted});@@ -2896,8 +2896,8 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {description: "Remove synced certificates from the destination"},{- label: "Set Preflight Check",- value: ProjectPermissionPkiSyncActions.SetPreflightCommand,+ label: "Set Health Check",+ value: ProjectPermissionPkiSyncActions.SetHealthCheckCommand,description: "Set the command a sync runs on the destination host before delivering"},{