Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(pki): PKI windows/linux pre-fetch commands

Carlos Monastyrski9f9c046f43c6
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.ts
new file mode 100644
index 0000000000..d9f0be81fd
--- /dev/null
+++ b/backend/src/db/migrations/20260811151204_add-pki-sync-preflight-discovery-index.ts
@@ -0,0 +1,17 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const PREFLIGHT_DISCOVERY_INDEX = "idx_pki_syncs_preflight_discovery";
+
+export async function up(knex: Knex): Promise<void> {
+ await knex.raw(`
+ CREATE INDEX IF NOT EXISTS "${PREFLIGHT_DISCOVERY_INDEX}"
+ ON ${TableName.PkiSync} ("createdAt")
+ WHERE ("syncOptions" ->> 'preflightCommand') IS NOT NULL
+ `);
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.raw(`DROP INDEX IF EXISTS "${PREFLIGHT_DISCOVERY_INDEX}"`);
+}
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 0c3209a863..7aaaed5e52 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -44,6 +44,7 @@ import { TAllowedFields } from "@app/services/identity-ldap-auth/identity-ldap-a
import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
import { PkiItemType } from "@app/services/pki-collection/pki-collection-types";
import { TPostSyncCommandResult } from "@app/services/pki-sync/pki-sync-post-sync-command-fns";
+import { TPreflightCommandResult } from "@app/services/pki-sync/pki-sync-preflight-command-fns";
import { SecretSync, SecretSyncImportBehavior } from "@app/services/secret-sync/secret-sync-enums";
import {
TCreateSecretSyncDTO,
@@ -579,6 +580,7 @@ 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_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",
@@ -4503,6 +4505,7 @@ interface CreatePkiSyncEvent {
connectionId?: string;
hasCredentials?: boolean;
hasPostSyncCommand?: boolean;
+ hasPreflightCommand?: boolean;
};
}
@@ -4513,6 +4516,7 @@ interface UpdatePkiSyncEvent {
name: string;
applicationId?: string;
hasPostSyncCommand?: boolean;
+ hasPreflightCommand?: boolean;
};
}
@@ -4533,6 +4537,7 @@ interface PkiSyncSyncCertificatesEvent {
syncMessage: string | null;
jobId: string;
jobRanAt: Date;
+ preflightCheck?: { command: string; result?: TPreflightCommandResult };
postSyncCommand?: { command: string; result?: TPostSyncCommandResult };
};
}
@@ -4547,6 +4552,16 @@ interface PkiSyncImportCertificatesEvent {
};
}
+interface PkiSyncPreflightCheckEvent {
+ type: EventType.PKI_SYNC_PREFLIGHT_CHECK;
+ metadata: {
+ syncId: string;
+ command: string;
+ ranAt: Date;
+ result?: TPreflightCommandResult;
+ };
+}
+
interface PkiSyncRemoveCertificatesEvent {
type: EventType.PKI_SYNC_REMOVE_CERTIFICATES;
metadata: {
@@ -7370,6 +7385,7 @@ export type Event =
| DeletePkiSyncEvent
| PkiSyncSyncCertificatesEvent
| PkiSyncImportCertificatesEvent
+ | PkiSyncPreflightCheckEvent
| PkiSyncRemoveCertificatesEvent
| PkiSyncSetDefaultCertificateEvent
| PkiSyncClearDefaultCertificateEvent
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 699e7efd98..af7239e595 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -295,7 +295,8 @@ const buildAdminPermissionRules = () => {
ProjectPermissionPkiSyncActions.SyncCertificates,
ProjectPermissionPkiSyncActions.ImportCertificates,
ProjectPermissionPkiSyncActions.RemoveCertificates,
- ProjectPermissionPkiSyncActions.SetPostSyncCommand
+ ProjectPermissionPkiSyncActions.SetPostSyncCommand,
+ ProjectPermissionPkiSyncActions.SetPreflightCommand
],
ProjectPermissionSub.PkiSyncs
);
@@ -863,7 +864,8 @@ const buildApplicationAdminPermissionRules = () => {
ResourcePermissionPkiSyncActions.SyncCertificates,
ResourcePermissionPkiSyncActions.ImportCertificates,
ResourcePermissionPkiSyncActions.RemoveCertificates,
- ResourcePermissionPkiSyncActions.SetPostSyncCommand
+ ResourcePermissionPkiSyncActions.SetPostSyncCommand,
+ ResourcePermissionPkiSyncActions.SetPreflightCommand
],
ResourcePermissionSub.PkiSyncs
);
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index 316dc2505f..e5c1493db4 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -170,7 +170,8 @@ export enum ProjectPermissionPkiSyncActions {
SyncCertificates = "sync-certificates",
ImportCertificates = "import-certificates",
RemoveCertificates = "remove-certificates",
- SetPostSyncCommand = "set-post-sync-command"
+ SetPostSyncCommand = "set-post-sync-command",
+ SetPreflightCommand = "set-preflight-command"
}
export enum ProjectPermissionPkiDiscoveryActions {
diff --git a/backend/src/ee/services/permission/resource-permission.ts b/backend/src/ee/services/permission/resource-permission.ts
index eecf533259..3d35cbfeca 100644
--- a/backend/src/ee/services/permission/resource-permission.ts
+++ b/backend/src/ee/services/permission/resource-permission.ts
@@ -100,7 +100,8 @@ export enum ResourcePermissionPkiSyncActions {
SyncCertificates = "sync-certificates",
ImportCertificates = "import-certificates",
RemoveCertificates = "remove-certificates",
- SetPostSyncCommand = "set-post-sync-command"
+ SetPostSyncCommand = "set-post-sync-command",
+ SetPreflightCommand = "set-preflight-command"
}
export type ResourcePermissionSet =
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index a045c0f411..125c50daaf 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -58,6 +58,7 @@ export const KeyStorePrefixes = {
SecretSyncLock: (syncId: string) => `secret-sync-mutex-${syncId}` as const,
PkiSyncLock: (syncId: string) => `pki-sync-mutex-${syncId}` as const,
AppConnectionConcurrentJobs: (connectionId: string) => `app-connection-concurrency-${connectionId}` as const,
+ AppConnectionCommandLock: (connectionId: string) => `app-connection-command-mutex-${connectionId}` as const,
SecretRotationLock: (rotationId: string) => `secret-rotation-v2-mutex-${rotationId}` as const,
PamAccountRotationLock: (accountId: string) => `pam-account-rotation-mutex-${accountId}` as const,
SecretScanningLock: (dataSourceId: string, resourceExternalId: string) =>
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index bca88bb5f7..cfb9a35171 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -22,6 +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",
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.ts
index fa070d2452..c2b785b5b1 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -50,6 +50,7 @@ import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types
import {
TQueuePkiSyncImportCertificatesByIdDTO,
TQueuePkiSyncRemoveCertificatesByIdDTO,
+ TQueuePkiSyncRunPreflightCheckByIdDTO,
TQueuePkiSyncSyncCertificatesByIdDTO
} from "@app/services/pki-sync/pki-sync-types";
import {
@@ -89,6 +90,7 @@ export enum QueueName {
SecretReplication = "secret-replication",
SecretSync = "secret-sync", // parent queue to push integration sync, webhook, and secret replication
PkiSync = "pki-sync",
+ PkiSyncPreflightCheck = "pki-sync-preflight-check",
ProjectV3Migration = "project-v3-migration",
AccessTokenStatusUpdate = "access-token-status-update",
ImportSecretsFromExternalSource = "import-secrets-from-external-source",
@@ -152,6 +154,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",
SecretRotationV2QueueRotations = "secret-rotation-v2-queue-rotations",
SecretRotationV2RotateSecrets = "secret-rotation-v2-rotate-secrets",
SecretRotationV2SendNotification = "secret-rotation-v2-send-notification",
@@ -352,6 +355,10 @@ export type TQueueJobTypes = {
name: QueueJobs.PkiSyncRemoveCertificates;
payload: TQueuePkiSyncRemoveCertificatesByIdDTO;
};
+ [QueueName.PkiSyncPreflightCheck]: {
+ name: QueueJobs.PkiSyncRunPreflightCheck;
+ payload: TQueuePkiSyncRunPreflightCheckByIdDTO;
+ };
[QueueName.ProjectV3Migration]: {
name: QueueJobs.ProjectV3Migration;
payload: { projectId: string };
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 3814fb4862..64d5c82f6e 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -426,6 +426,7 @@ import { pkiSubscriberQueueServiceFactory } from "@app/services/pki-subscriber/p
import { 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 { 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";
@@ -3152,6 +3153,25 @@ export const registerRoutes = async (
pkiSyncQueue
});
+ const pkiSyncPreflightQueue = pkiSyncPreflightQueueFactory({
+ cronJob,
+ queueService,
+ pkiSyncDAL,
+ keyStore,
+ appConnectionDAL,
+ projectDAL,
+ kmsService,
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ certificateAuthorityDAL,
+ certificateAuthorityCertDAL,
+ certificateSyncDAL,
+ auditLogService,
+ gatewayV2Service,
+ gatewayPoolService
+ });
+
const internalCaFns = InternalCertificateAuthorityFns({
certificateAuthorityDAL,
certificateAuthorityCertDAL,
@@ -3833,6 +3853,7 @@ export const registerRoutes = async (
alertQueue.init();
auditLogStreamOutboxQueue.init();
pkiSyncCleanup.init();
+ pkiSyncPreflightQueue.init();
pamDiscoveryService.init();
pkiDiscoveryQueue.startPkiDiscoveryScanQueue();
dailyReminderQueueService.startDailyRemindersJob();
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.ts
index 670c6b047d..92be26ae49 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
@@ -171,6 +171,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),
...(pkiSync.applicationId && { applicationId: pkiSync.applicationId })
}
}
@@ -224,7 +225,8 @@ export const registerSyncPkiEndpoints = ({
pkiSyncId,
name: pkiSync.name,
...(pkiSync.applicationId && { applicationId: pkiSync.applicationId }),
- hasPostSyncCommand: Boolean(pkiSync.syncOptions?.postSyncCommand)
+ hasPostSyncCommand: Boolean(pkiSync.syncOptions?.postSyncCommand),
+ hasPreflightCommand: Boolean(pkiSync.syncOptions?.preflightCommand)
}
}
});
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.ts
index d0cac9d2b7..21b64455c3 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
@@ -75,6 +75,7 @@ const PkiSyncOptionsSchema = z.object({
canImportCertificates: z.boolean(),
canRemoveCertificates: z.boolean(),
canRunPostSyncCommand: z.boolean().optional(),
+ canRunPreflightCommand: z.boolean().optional(),
maxCertificates: z.number().optional(),
defaultCertificateNameSchema: z.string().optional(),
forbiddenCharacters: z.string().optional(),
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.ts
index 696df12b5b..3e5a52f761 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,6 +45,7 @@ export const AWS_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION = {
canImportCertificates: false,
canRemoveCertificates: true,
canRunPostSyncCommand: false,
+ canRunPreflightCommand: 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.ts
index 65f84c8288..52c3374f62 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
@@ -5,7 +5,7 @@ import { AppConnection, AWSRegion } from "@app/services/app-connection/app-conne
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
import { AWS_CERTIFICATE_MANAGER_CERTIFICATE_NAMING } from "./aws-certificate-manager-pki-sync-constants";
@@ -18,7 +18,7 @@ const AwsCertificateManagerPkiSyncOptionsSchema = z.object({
canRemoveCertificates: z.boolean().default(true),
includeRootCa: z.boolean().default(false),
preserveArn: z.boolean().default(true),
- postSyncCommand: PostSyncCommandSchema,
+ postSyncCommand: HostCommandSchema,
certificateNameSchema: z
.string()
.trim()
diff --git a/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-constants.ts b/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-constants.ts
index 3ca297ef0e..c6ad0803a4 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
@@ -7,5 +7,6 @@ export const AWS_ELASTIC_LOAD_BALANCER_PKI_SYNC_LIST_OPTION = {
destination: PkiSync.AwsElasticLoadBalancer,
canImportCertificates: false,
canRemoveCertificates: true,
- canRunPostSyncCommand: false
+ canRunPostSyncCommand: false,
+ canRunPreflightCommand: 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.ts
index e1a44434b9..8fd00a9de3 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
@@ -4,7 +4,7 @@ import { openApiHidden } from "@app/server/lib/schemas";
import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
export const AwsElasticLoadBalancerListenerSchema = z.object({
listenerArn: z.string().min(1, "Listener ARN is required"),
@@ -27,7 +27,7 @@ const AwsElasticLoadBalancerPkiSyncOptionsSchema = z.object({
preserveArn: z.boolean().default(true),
includeRootCa: z.boolean().default(false),
certificateNameSchema: z.string().optional(),
- postSyncCommand: PostSyncCommandSchema
+ postSyncCommand: HostCommandSchema
});
export const AwsElasticLoadBalancerPkiSyncSchema = PkiSyncSchema.extend({
diff --git a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-constants.ts b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-constants.ts
index 83a7414f15..4f1fd84c6e 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,6 +63,7 @@ export const AWS_SECRETS_MANAGER_PKI_SYNC_LIST_OPTION = {
canImportCertificates: false,
canRemoveCertificates: true,
canRunPostSyncCommand: false,
+ canRunPreflightCommand: 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.ts
index 891d527540..b0aba850db 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
@@ -5,7 +5,7 @@ import { AppConnection, AWSRegion } from "@app/services/app-connection/app-conne
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
import { AWS_SECRETS_MANAGER_PKI_SYNC_CERTIFICATE_NAMING } from "./aws-secrets-manager-pki-sync-constants";
@@ -27,7 +27,7 @@ const AwsSecretsManagerPkiSyncOptionsSchema = z.object({
includeRootCa: z.boolean().default(false),
preserveSecretOnRenewal: z.boolean().default(true),
updateExistingCertificates: z.boolean().default(true),
- postSyncCommand: PostSyncCommandSchema,
+ postSyncCommand: HostCommandSchema,
certificateNameSchema: z
.string()
.trim()
diff --git a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-constants.ts b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-constants.ts
index 1e83d2e121..13dcc5ae38 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,6 +45,7 @@ export const AZURE_KEY_VAULT_PKI_SYNC_LIST_OPTION = {
canImportCertificates: false,
canRemoveCertificates: true,
canRunPostSyncCommand: false,
+ canRunPreflightCommand: 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.ts
index 4f104e5d63..4fb0e5467b 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
@@ -6,7 +6,7 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enums
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
import { AZURE_KEY_VAULT_CERTIFICATE_NAMING } from "./azure-key-vault-pki-sync-constants";
@@ -21,7 +21,7 @@ export const AzureKeyVaultPkiSyncOptionsSchema = z.object({
canRemoveCertificates: z.boolean().default(true),
includeRootCa: z.boolean().default(false),
enableVersioning: z.boolean().default(true),
- postSyncCommand: PostSyncCommandSchema,
+ postSyncCommand: HostCommandSchema,
certificateNameSchema: z
.string()
.trim()
diff --git a/backend/src/services/pki-sync/chef/chef-pki-sync-list-constants.ts b/backend/src/services/pki-sync/chef/chef-pki-sync-list-constants.ts
index 70c4eded1b..0e48955a3e 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
@@ -7,5 +7,6 @@ export const CHEF_PKI_SYNC_LIST_OPTION = {
destination: PkiSync.Chef,
canImportCertificates: false,
canRemoveCertificates: true,
- canRunPostSyncCommand: false
+ canRunPostSyncCommand: false,
+ canRunPreflightCommand: 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.ts
index fc31e4e1bf..fcc92108ca 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,6 +45,7 @@ export const CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION = {
canImportCertificates: false,
canRemoveCertificates: true,
canRunPostSyncCommand: false,
+ canRunPreflightCommand: 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.ts
index 9f540dec0a..261eaac9c3 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
@@ -5,7 +5,7 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enums
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
import { CLOUDFLARE_CUSTOM_CERTIFICATE_NAMING } from "./cloudflare-custom-certificate-pki-sync-constants";
@@ -16,7 +16,7 @@ export const CloudflareCustomCertificatePkiSyncConfigSchema = z.object({
// API-facing schema - only exposes user-configurable options
export const CloudflareCustomCertificatePkiSyncOptionsSchema = z.object({
canRemoveCertificates: z.boolean().default(true),
- postSyncCommand: PostSyncCommandSchema,
+ postSyncCommand: HostCommandSchema,
certificateNameSchema: z
.string()
.trim()
diff --git a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-constants.ts b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-constants.ts
index 34c45252ff..8d6fce081c 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,6 +31,7 @@ export const F5_BIG_IP_PKI_SYNC_LIST_OPTION = {
canImportCertificates: false,
canRemoveCertificates: true,
canRunPostSyncCommand: false,
+ canRunPreflightCommand: 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.ts
index 08dba79817..6899a82d73 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,6 +24,7 @@ export const KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION = {
canImportCertificates: false,
canRemoveCertificates: true,
canRunPostSyncCommand: false,
+ canRunPreflightCommand: 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.ts
index 042dbf7b25..ec5a9b11f0 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,6 +23,7 @@ export const LINUX_SERVER_PKI_SYNC_LIST_OPTION = {
canImportCertificates: false,
canRemoveCertificates: true,
canRunPostSyncCommand: true,
+ canRunPreflightCommand: 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.ts
index dcc75f4b43..ad6b74a139 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
@@ -18,13 +18,21 @@ import { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-s
import { PkiSyncError } from "../pki-sync-errors";
import { exportCertificateForSync, PemCertificateExtension, PkiSyncExportFormat } from "../pki-sync-export-fns";
import {
- buildPostSyncCommandPlan,
- POST_SYNC_COMMAND_TIMEOUT_MS,
- renderPostSyncCommand,
- runPostSyncCommand,
- toPosixShellLiteral,
- TPostSyncCommandPlan
-} from "../pki-sync-post-sync-command-fns";
+ HOST_COMMAND_TIMEOUT_MS,
+ HostCommandKind,
+ renderHostCommandContext,
+ THostCommandContext,
+ 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 { TLinuxServerPkiSyncConfig } from "./linux-server-pki-sync-types";
@@ -48,6 +56,7 @@ type TLinuxServerSyncOptions = {
privateKeyFileMode?: string;
owner?: string;
group?: string;
+ preflightCommand?: string;
postSyncCommand?: string;
};
@@ -225,6 +234,56 @@ const reconcileLinuxServerRemovals = async (args: {
return { removed, failedRemovals };
};
+const resolveLinuxExportOptions = (options: TLinuxServerSyncOptions) => ({
+ format: options.exportFormat ?? PkiSyncExportFormat.Pem,
+ includePrivateKey: options.includePrivateKey ?? true,
+ pemCertificateExtension: options.pemCertificateExtension,
+ combineCertificateChain: options.combineCertificateChain
+});
+
+const executeLinuxServerHostCommand = (
+ kind: HostCommandKind,
+ plan: { command: string; context: THostCommandContext },
+ sshConfig: TSshConnectionConfig,
+ gatewayServices: Pick<TLinuxServerPkiSyncFactoryDeps, "gatewayV2Service" | "gatewayPoolService">
+) =>
+ executeSshCommandViaGateway(sshConfig, gatewayServices, {
+ command: renderHostCommandContext(plan.command, plan.context, toPosixShellLiteral),
+ timeoutMs: HOST_COMMAND_TIMEOUT_MS[kind]
+ });
+
+const runLinuxServerPreflightCommand = ({
+ pkiSync,
+ certificateMap,
+ gatewayServices
+}: {
+ pkiSync: TPkiSyncWithCredentials;
+ certificateMap: TCertificateMap;
+ gatewayServices: Pick<TLinuxServerPkiSyncFactoryDeps, "gatewayV2Service" | "gatewayPoolService">;
+}): Promise<TPreflightCommandResult> | undefined => {
+ const options = (pkiSync.syncOptions ?? {}) as TLinuxServerSyncOptions;
+ const config = pkiSync.destinationConfig as TLinuxServerPkiSyncConfig;
+ const exportOptions = resolveLinuxExportOptions(options);
+
+ const plan = buildPreflightCommandPlan({
+ command: options.preflightCommand,
+ destinationDirectory: config.destinationPath,
+ certificateMap,
+ exportOptions,
+ joinPath: (directory, fileName) => path.posix.join(directory, fileName),
+ pkcs12Password:
+ exportOptions.format === PkiSyncExportFormat.Pkcs12 ? pkiSync.syncCredentials?.exportPassword : undefined
+ });
+ if (!plan) return undefined;
+
+ return runPreflightCommand({
+ syncId: pkiSync.id,
+ secretsToRedact: [plan.context.pkcs12Password],
+ execute: () =>
+ executeLinuxServerHostCommand(HostCommandKind.Preflight, plan, buildSshConfig(pkiSync), gatewayServices)
+ });
+};
+
const runLinuxServerPostSyncCommand = ({
syncId,
plan,
@@ -239,11 +298,7 @@ const runLinuxServerPostSyncCommand = ({
runPostSyncCommand({
syncId,
secretsToRedact: [plan.context.pkcs12Password],
- execute: () =>
- executeSshCommandViaGateway(sshConfig, gatewayServices, {
- command: renderPostSyncCommand(plan.command, plan.context, toPosixShellLiteral),
- timeoutMs: POST_SYNC_COMMAND_TIMEOUT_MS
- })
+ execute: () => executeLinuxServerHostCommand(HostCommandKind.PostSync, plan, sshConfig, gatewayServices)
});
export const linuxServerPkiSyncFactory = ({
@@ -257,8 +312,8 @@ export const linuxServerPkiSyncFactory = ({
): Promise<TPkiSyncSyncResult> => {
const config = pkiSync.destinationConfig as TLinuxServerPkiSyncConfig;
const options = (pkiSync.syncOptions ?? {}) as TLinuxServerSyncOptions;
- const format = options.exportFormat ?? PkiSyncExportFormat.Pem;
- const includePrivateKey = options.includePrivateKey ?? true;
+ const exportOptions = resolveLinuxExportOptions(options);
+ const { format, includePrivateKey } = exportOptions;
const canRemoveCertificates = options.canRemoveCertificates ?? false;
const privateKeyMode = parseFileMode(options.privateKeyFileMode, PRIVATE_KEY_FILE_MODE);
const certificateMode = parseFileMode(options.fileMode, CERTIFICATE_FILE_MODE);
@@ -270,12 +325,24 @@ export const linuxServerPkiSyncFactory = ({
// Paths confirmed on the host this run. Keeps the removal pass from deleting a file a renewal
// just rewrote under the same name, and tells the post-sync command what landed.
const deliveredPaths = new Set<string>();
- const deliveredCertificates: Array<{ path: string; commonName?: string }> = [];
+ const deliveredCertificates: Array<{ paths: string[]; commonName?: string }> = [];
let uploaded = 0;
let removed = 0;
const sshConfig = buildSshConfig(pkiSync);
+ const preflightCheck = await runLinuxServerPreflightCommand({
+ pkiSync,
+ certificateMap,
+ gatewayServices: { gatewayV2Service, gatewayPoolService }
+ });
+ if (preflightCheck && didPreflightCheckFail(preflightCheck)) {
+ logger.info(
+ `Linux Server PKI sync [syncId=${pkiSync.id}]: preflight check failed, delivered nothing (${buildPreflightCommandFailureMessage(preflightCheck)})`
+ );
+ return buildPreflightFailureSyncResult(certificateMap, preflightCheck);
+ }
+
await withSshConnection(sshConfig, { gatewayV2Service, gatewayPoolService }, async (client) => {
const sftp = await openSftp(client);
await removeStaleTempFiles(sftp, config.destinationPath);
@@ -304,15 +371,12 @@ export const linuxServerPkiSyncFactory = ({
try {
const files = await exportCertificateForSync({
- format,
+ ...exportOptions,
certificate: cert,
certificateChain,
privateKey,
- includePrivateKey,
password: exportPassword,
- alias: baseName,
- pemCertificateExtension: options.pemCertificateExtension,
- combineCertificateChain: options.combineCertificateChain
+ alias: baseName
});
const writtenPaths: string[] = [];
@@ -335,7 +399,7 @@ export const linuxServerPkiSyncFactory = ({
}
const primaryPath = writtenPaths[0];
- deliveredCertificates.push({ path: primaryPath, commonName: certData.commonName ?? undefined });
+ deliveredCertificates.push({ paths: writtenPaths, commonName: certData.commonName ?? undefined });
if (typeof certificateId === "string") {
let record = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);
if (!record) {
@@ -399,6 +463,7 @@ export const linuxServerPkiSyncFactory = ({
removed: removed > 0 ? removed : undefined,
failedRemovals: failedRemovals.length > 0 ? failedRemovals.length : undefined,
skipped: skippedCertificates.length,
+ preflightCheck,
postSyncCommand,
details: {
failedUploads: failedUploads.length > 0 ? failedUploads : undefined,
@@ -455,5 +520,12 @@ export const linuxServerPkiSyncFactory = ({
}
};
- return { syncCertificates, removeCertificates };
+ const runPreflightCheck = (pkiSync: TPkiSyncWithCredentials, certificateMap: TCertificateMap) =>
+ runLinuxServerPreflightCommand({
+ pkiSync,
+ certificateMap,
+ gatewayServices: { gatewayV2Service, gatewayPoolService }
+ });
+
+ return { syncCertificates, removeCertificates, runPreflightCheck };
};
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.ts
index 7464e79b28..24388b693e 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
@@ -6,7 +6,7 @@ import { pkiDescriptionSchema } from "@app/services/certificate-common/certifica
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
import { PemCertificateExtension, PkiSyncExportFormat } from "@app/services/pki-sync/pki-sync-export-fns";
-import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
import { LINUX_SERVER_NAMING } from "./linux-server-pki-sync-constants";
@@ -57,7 +57,8 @@ export const LinuxServerPkiSyncOptionsSchema = z.object({
.max(32)
.refine((v) => POSIX_NAME.test(v), { message: "Group must be a valid Linux group name" })
.optional(),
- postSyncCommand: PostSyncCommandSchema,
+ preflightCommand: HostCommandSchema,
+ postSyncCommand: HostCommandSchema,
certificateNameSchema: z
.string()
.trim()
diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-constants.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-constants.ts
index 0eefdf49c0..65961b1251 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,6 +23,7 @@ export const NETSCALER_PKI_SYNC_LIST_OPTION = {
canImportCertificates: false,
canRemoveCertificates: true,
canRunPostSyncCommand: false,
+ canRunPreflightCommand: 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.ts
index f668563a7d..c84465eeeb 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,5 +8,6 @@ export const NUTANIX_PRISM_CENTRAL_PKI_SYNC_LIST_OPTION = {
canImportCertificates: false,
canRemoveCertificates: false,
canRunPostSyncCommand: false,
+ canRunPreflightCommand: 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.ts
index 3fa928925b..b14f819ac1 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
@@ -4,7 +4,7 @@ import { openApiHidden } from "@app/server/lib/schemas";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
export const NutanixPrismCentralPkiSyncConfigSchema = z.object({
clusterId: z.string().min(1, "Cluster ID is required"),
@@ -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),
- postSyncCommand: PostSyncCommandSchema
+ postSyncCommand: HostCommandSchema
});
export const NutanixPrismCentralPkiSyncSchema = PkiSyncSchema.extend({
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.ts
new file mode 100644
index 0000000000..aabd92923c
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-certificate-map-fns.ts
@@ -0,0 +1,245 @@
+/* eslint-disable no-await-in-loop */
+import * as x509 from "@peculiar/x509";
+import RE2 from "re2";
+
+import { TCertificates } from "@app/db/schemas";
+import { logger } from "@app/lib/logger";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+
+import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
+import { TCertificateDALFactory } from "../certificate/certificate-dal";
+import { getCertificateCredentials } from "../certificate/certificate-fns";
+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 { getCaCertChain } from "../certificate-authority/certificate-authority-fns";
+import { extractRootCaFromChain, removeRootCaFromChain } from "../certificate-common/certificate-utils";
+import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
+import { compileCertificateNameSchema } from "./pki-sync-certificate-name-fns";
+import { PkiSync } from "./pki-sync-enums";
+import { PkiSyncError } from "./pki-sync-errors";
+import { TCertificateMap, TPkiSyncRaw, TPkiSyncWithCredentials } from "./pki-sync-types";
+
+const DASH_REGEX = new RE2("-", "g");
+const NON_ALPHANUMERIC_REGEX = new RE2("[^a-zA-Z0-9]", "g");
+
+type TBuildCertificateMapDeps = {
+ certificateDAL: TCertificateDALFactory;
+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne">;
+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;
+ certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;
+ certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findCertificateIdsByPkiSyncId">;
+ projectDAL: TProjectDALFactory;
+ kmsService: Pick<
+ TKmsServiceFactory,
+ "decryptWithKmsKey" | "generateKmsKey" | "encryptWithKmsKey" | "createCipherPairWithDataKey"
+ >;
+};
+
+export const buildCertificateMap = async (
+ pkiSync: TPkiSyncRaw | TPkiSyncWithCredentials,
+ {
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ certificateAuthorityDAL,
+ certificateAuthorityCertDAL,
+ certificateSyncDAL,
+ projectDAL,
+ kmsService
+ }: TBuildCertificateMapDeps
+): Promise<{ certificateMap: TCertificateMap; certificateMetadata: Map<string, { id: string; name: string }> }> => {
+ const { projectId, subscriberId, id: pkiSyncId } = pkiSync;
+
+ const certificateMap: TCertificateMap = {};
+ const certificateMetadata = new Map<string, { id: string; name: string }>();
+ let certificates: Array<{ id: string; projectId: string; caCertId?: string | null }> = [];
+
+ try {
+ if (subscriberId) {
+ const subscriberCertificates = await certificateDAL.findAllActiveCertsForSubscriber({
+ subscriberId
+ });
+ certificates.push(...subscriberCertificates);
+ }
+
+ const certificateIds = await certificateSyncDAL.findCertificateIdsByPkiSyncId(pkiSyncId);
+ if (certificateIds.length > 0) {
+ const directCertificates = await certificateDAL.findActiveCertificatesByIds(certificateIds);
+ certificates.push(...directCertificates);
+ }
+
+ const uniqueCertificates = certificates.filter(
+ (cert, index, self) => self.findIndex((c) => c.id === cert.id) === index
+ );
+
+ const activeCertificates = uniqueCertificates.filter((cert) => {
+ const typedCert = cert as TCertificates;
+ return !typedCert.renewedByCertificateId;
+ });
+
+ if (activeCertificates.length === 0) {
+ return { certificateMap, certificateMetadata };
+ }
+
+ certificates = activeCertificates;
+
+ for (const certificate of certificates) {
+ const cert = certificate as TCertificates;
+ try {
+ const certBody = await certificateBodyDAL.findOne({ certId: certificate.id });
+
+ if (certBody) {
+ const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
+ projectId: certificate.projectId,
+ projectDAL,
+ kmsService
+ });
+
+ const kmsDecryptor = await kmsService.decryptWithKmsKey({
+ kmsId: certificateManagerKeyId
+ });
+
+ const decryptedCert = await kmsDecryptor({
+ cipherTextBlob: certBody.encryptedCertificate
+ });
+
+ const certObj = new x509.X509Certificate(decryptedCert);
+ const certificatePem = certObj.toString("pem");
+
+ let certPrivateKey: string | undefined;
+ try {
+ const credentials = await getCertificateCredentials({
+ certId: certificate.id,
+ projectId: certificate.projectId,
+ certificateSecretDAL,
+ projectDAL,
+ kmsService
+ });
+ certPrivateKey = credentials.certPrivateKey;
+ } catch (credError) {
+ logger.warn(
+ { certificateId: certificate.id, subscriberId, error: credError },
+ "Certificate private key not found - certificate may be imported or key was not stored"
+ );
+ certPrivateKey = undefined;
+ }
+
+ let certificateChain: string | undefined;
+ let caCertificate: string | undefined;
+ try {
+ if (certBody.encryptedCertificateChain) {
+ const decryptedCertChain = await kmsDecryptor({
+ cipherTextBlob: certBody.encryptedCertificateChain
+ });
+ certificateChain = decryptedCertChain.toString();
+ }
+ if (certificate.caCertId) {
+ const { caCert, caCertChain } = await getCaCertChain({
+ caCertId: certificate.caCertId,
+ certificateAuthorityDAL,
+ certificateAuthorityCertDAL,
+ projectDAL,
+ kmsService
+ });
+ if (!certBody.encryptedCertificateChain) {
+ certificateChain = `${caCert}\n${caCertChain}`.trim();
+ }
+ caCertificate = certificateChain ? extractRootCaFromChain(certificateChain) : caCert;
+ }
+ } catch (chainError) {
+ logger.warn(
+ { certificateId: certificate.id, subscriberId, error: chainError },
+ "Certificate chain not found or could not be decrypted - certificate may be imported or chain was not stored"
+ );
+ certificateChain = undefined;
+ caCertificate = undefined;
+ }
+
+ let certificateName: string;
+ const syncOptions = pkiSync.syncOptions as
+ | {
+ certificateNameSchema?: string;
+ includeRootCa?: boolean;
+ }
+ | undefined;
+ const certificateNameSchema = syncOptions?.certificateNameSchema;
+
+ if (certificateNameSchema) {
+ certificateName = compileCertificateNameSchema(
+ certificateNameSchema,
+ {
+ certificateId: certificate.id,
+ profileId: cert.profileId,
+ applicationId: pkiSync.applicationId,
+ applicationName: pkiSync.applicationName,
+ commonName: cert.commonName
+ },
+ pkiSync.destination as PkiSync
+ );
+ } else {
+ const stableId = cert.profileId
+ ? `${cert.profileId.replace(DASH_REGEX, "")}-${(cert.commonName || "").replace(NON_ALPHANUMERIC_REGEX, "")}`
+ : certificate.id.replace(DASH_REGEX, "");
+ certificateName = `Infisical-${stableId}`;
+ }
+
+ const alternativeNames: string[] = [];
+
+ const legacyName = `Infisical-${certificate.id.replace(DASH_REGEX, "")}`;
+ if (legacyName !== certificateName) {
+ alternativeNames.push(legacyName);
+ }
+
+ if (cert.renewedFromCertificateId) {
+ const originalLegacyName = `Infisical-${cert.renewedFromCertificateId.replace(DASH_REGEX, "")}`;
+ alternativeNames.push(originalLegacyName);
+ }
+
+ let processedCertificateChain = certificateChain;
+ if (certificateChain && syncOptions?.includeRootCa === false) {
+ processedCertificateChain = removeRootCaFromChain(certificateChain);
+ }
+
+ certificateMap[certificateName] = {
+ cert: certificatePem,
+ privateKey: certPrivateKey || "",
+ certificateChain: processedCertificateChain,
+ caCertificate,
+ alternativeNames,
+ certificateId: certificate.id,
+ profileId: cert.profileId,
+ commonName: cert.commonName
+ };
+
+ certificateMetadata.set(certificateName, {
+ id: certificate.id,
+ name: certificateName
+ });
+ } else {
+ logger.warn({ certificateId: certificate.id, subscriberId }, "Certificate body not found for certificate");
+ }
+ } catch (error) {
+ logger.error(
+ { error, subscriberId, certificateId: certificate.id },
+ "Failed to decrypt certificate for PKI sync"
+ );
+ // Continue with other certificates
+ }
+ }
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to fetch certificate for subscriber [subscriberId=${subscriberId}] [projectId=${projectId}]`
+ );
+ throw new PkiSyncError({
+ message: `Failed to fetch certificate for PKI subscriber: ${error instanceof Error ? error.message : String(error)}`,
+ shouldRetry: true
+ });
+ }
+
+ return { certificateMap, certificateMetadata };
+};
diff --git a/backend/src/services/pki-sync/pki-sync-credentials-fns.ts b/backend/src/services/pki-sync/pki-sync-credentials-fns.ts
index 7f18f9200e..a98359a7da 100644
--- a/backend/src/services/pki-sync/pki-sync-credentials-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-credentials-fns.ts
@@ -1,5 +1,10 @@
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+
+import { TPkiSyncRaw, TPkiSyncWithCredentials } from "./pki-sync-types";
export type TPkiSyncCredentials = {
exportPassword?: string;
@@ -44,3 +49,52 @@ export const decryptPkiSyncCredentials = async ({
const decrypted = decryptor({ cipherTextBlob: encryptedCredentials });
return JSON.parse(decrypted.toString()) as TPkiSyncCredentials;
};
+
+export const hydratePkiSyncCredentials = async ({
+ pkiSync,
+ appConnectionDAL,
+ projectDAL,
+ kmsService
+}: {
+ pkiSync: TPkiSyncRaw;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
+ projectDAL: Pick<TProjectDALFactory, "findById">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+}): Promise<TPkiSyncWithCredentials> => {
+ const {
+ connection: { id: connectionId, orgId, projectId: appConnectionProjectId }
+ } = pkiSync;
+
+ const appConnection = await appConnectionDAL.findById(connectionId);
+ if (!appConnection) {
+ throw new Error(`App connection not found: ${connectionId}`);
+ }
+
+ const project = appConnectionProjectId ? await projectDAL.findById(appConnectionProjectId) : null;
+
+ const credentials = await decryptAppConnectionCredentials({
+ orgId,
+ encryptedCredentials: appConnection.encryptedCredentials,
+ kmsService,
+ projectId: appConnectionProjectId
+ });
+
+ const syncCredentials = pkiSync.encryptedCredentials
+ ? await decryptPkiSyncCredentials({
+ orgId,
+ projectId: pkiSync.projectId,
+ encryptedCredentials: pkiSync.encryptedCredentials,
+ kmsService
+ })
+ : undefined;
+
+ return {
+ ...pkiSync,
+ connection: {
+ ...pkiSync.connection,
+ credentials,
+ projectType: project?.type
+ },
+ syncCredentials
+ } as TPkiSyncWithCredentials;
+};
diff --git a/backend/src/services/pki-sync/pki-sync-dal.ts b/backend/src/services/pki-sync/pki-sync-dal.ts
index 73d379cdaf..cdb61d022e 100644
--- a/backend/src/services/pki-sync/pki-sync-dal.ts
+++ b/backend/src/services/pki-sync/pki-sync-dal.ts
@@ -9,7 +9,7 @@ import {
type ProcessedPermissionRules
} from "@app/lib/knex/permission-filter-utils";
-import { PkiSync } from "./pki-sync-enums";
+import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";
export type TPkiSyncDALFactory = ReturnType<typeof pkiSyncDALFactory>;
@@ -331,8 +331,59 @@ export const pkiSyncDALFactory = (db: TDbClient) => {
}
};
+ const reportPreflightFailure = async (syncId: string, message: string, failurePrefix: string) => {
+ try {
+ return await db(TableName.PkiSync)
+ .where({ id: syncId })
+ .where((builder) => {
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ void builder
+ .whereNot("syncStatus", PkiSyncStatus.Failed)
+ .orWhereNull("lastSyncMessage")
+ .orWhereRaw(`left("lastSyncMessage", ?) = ?`, [failurePrefix.length, failurePrefix]);
+ })
+ .update({ syncStatus: PkiSyncStatus.Failed, lastSyncMessage: message });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Report preflight failure - PKI Sync" });
+ }
+ };
+
+ const clearReportedPreflightFailure = async (syncId: string, failurePrefix: string) => {
+ try {
+ return await db(TableName.PkiSync)
+ .where({ id: syncId })
+ .whereRaw(`left("lastSyncMessage", ?) = ?`, [failurePrefix.length, failurePrefix])
+ .update({
+ syncStatus: db.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" });
+ }
+ };
+
+ const findPkiSyncsWithPreflightCommand = 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`)
+ .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" });
+ }
+ };
+
return {
...pkiSyncOrm,
+ reportPreflightFailure,
+ clearReportedPreflightFailure,
+ findPkiSyncsWithPreflightCommand,
findByProjectId,
findByProjectIdWithSubscribers,
findBySubscriberId,
diff --git a/backend/src/services/pki-sync/pki-sync-export-fns.test.ts b/backend/src/services/pki-sync/pki-sync-export-fns.test.ts
index 145a886e13..108d17cc02 100644
--- a/backend/src/services/pki-sync/pki-sync-export-fns.test.ts
+++ b/backend/src/services/pki-sync/pki-sync-export-fns.test.ts
@@ -1,4 +1,10 @@
-import { exportCertificateForSync, PkiSyncExportFormat, TExportedCertificateFile } from "./pki-sync-export-fns";
+import {
+ exportCertificateForSync,
+ getExportedCertificateFileSuffixes,
+ PemCertificateExtension,
+ PkiSyncExportFormat,
+ TExportedCertificateFile
+} from "./pki-sync-export-fns";
const CERT = "-----BEGIN CERTIFICATE-----\ncert\n-----END CERTIFICATE-----";
const CHAIN = "-----BEGIN CERTIFICATE-----\nchain\n-----END CERTIFICATE-----";
@@ -49,3 +55,58 @@ describe("exportCertificateForSync (PEM)", () => {
expect(suffixes(files)).toEqual([".key", ".pem"]);
});
});
+
+const everyPemShape = () => {
+ const shapes = [];
+ for (const pemCertificateExtension of [PemCertificateExtension.Pem, PemCertificateExtension.Crt]) {
+ for (const combineCertificateChain of [true, false]) {
+ for (const includePrivateKey of [true, false]) {
+ for (const hasCertificateChain of [true, false]) {
+ for (const hasPrivateKey of [true, false]) {
+ shapes.push({
+ format: PkiSyncExportFormat.Pem,
+ pemCertificateExtension,
+ combineCertificateChain,
+ includePrivateKey,
+ hasCertificateChain,
+ hasPrivateKey
+ });
+ }
+ }
+ }
+ }
+ }
+ return shapes;
+};
+
+describe("getExportedCertificateFileSuffixes matches the real export", () => {
+ test.each(everyPemShape())(
+ "PEM ext=$pemCertificateExtension combined=$combineCertificateChain includeKey=$includePrivateKey chain=$hasCertificateChain key=$hasPrivateKey",
+ async (shape) => {
+ const exported = await exportCertificateForSync({
+ format: shape.format,
+ certificate: CERT,
+ certificateChain: shape.hasCertificateChain ? CHAIN : undefined,
+ privateKey: shape.hasPrivateKey ? KEY : undefined,
+ includePrivateKey: shape.includePrivateKey,
+ password: "pw",
+ alias: "api.example.com",
+ pemCertificateExtension: shape.pemCertificateExtension,
+ combineCertificateChain: shape.combineCertificateChain
+ });
+
+ expect(getExportedCertificateFileSuffixes(shape).sort()).toEqual(suffixes(exported));
+ }
+ );
+
+ test.each([true, false])("PKCS#12 is always a single .pfx (includeKey=%s)", (includePrivateKey) => {
+ expect(
+ getExportedCertificateFileSuffixes({
+ format: PkiSyncExportFormat.Pkcs12,
+ includePrivateKey,
+ hasCertificateChain: true,
+ hasPrivateKey: true
+ })
+ ).toEqual([".pfx"]);
+ });
+});
diff --git a/backend/src/services/pki-sync/pki-sync-export-fns.ts b/backend/src/services/pki-sync/pki-sync-export-fns.ts
index a2689ca3f6..40b3e21be1 100644
--- a/backend/src/services/pki-sync/pki-sync-export-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-export-fns.ts
@@ -33,6 +33,36 @@ export type TExportCertificateForSyncParams = {
combineCertificateChain?: boolean;
};
+export type TExportedCertificateFileShape = {
+ format: PkiSyncExportFormat;
+ includePrivateKey: boolean;
+ hasCertificateChain: boolean;
+ hasPrivateKey: boolean;
+ pemCertificateExtension?: PemCertificateExtension;
+ combineCertificateChain?: boolean;
+};
+
+export const getExportedCertificateFileSuffixes = ({
+ format,
+ includePrivateKey,
+ hasCertificateChain,
+ hasPrivateKey,
+ pemCertificateExtension,
+ combineCertificateChain
+}: TExportedCertificateFileShape): string[] => {
+ if (format === PkiSyncExportFormat.Pkcs12) return [".pfx"];
+
+ const certExtension = pemCertificateExtension ?? PemCertificateExtension.Pem;
+ const suffixes = [`.${certExtension}`];
+
+ if (hasCertificateChain && !combineCertificateChain) {
+ suffixes.push(`.chain.${certExtension}`);
+ }
+ if (includePrivateKey && hasPrivateKey) suffixes.push(".key");
+
+ return suffixes;
+};
+
/**
* Packages a certificate for delivery to a server. The extension is decided here from the format,
* never from the caller's name schema (the schema only provides the base name):
diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.ts
index a719495660..042df96a71 100644
--- a/backend/src/services/pki-sync/pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-fns.ts
@@ -39,6 +39,7 @@ import {
} from "./pki-sync-certificate-name-fns";
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 { WINDOWS_SERVER_PKI_SYNC_LIST_OPTION } from "./windows-server/windows-server-pki-sync-constants";
import { windowsServerPkiSyncFactory } from "./windows-server/windows-server-pki-sync-fns";
@@ -88,7 +89,8 @@ export const getPkiSyncProviderCapabilities = (destination: PkiSync) => {
return {
canImportCertificates: providerOption.canImportCertificates,
canRemoveCertificates: providerOption.canRemoveCertificates,
- canRunPostSyncCommand: providerOption.canRunPostSyncCommand
+ canRunPostSyncCommand: providerOption.canRunPostSyncCommand,
+ canRunPreflightCommand: providerOption.canRunPreflightCommand
};
};
@@ -343,6 +345,43 @@ export const PkiSyncFns = {
}
},
+ runPreflightCheck: async (
+ pkiSync: TPkiSyncWithCredentials,
+ certificateMap: TCertificateMap,
+ dependencies: {
+ certificateSyncDAL: TCertificateSyncDALFactory;
+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ }
+ ): Promise<THostCommandResult | undefined> => {
+ switch (pkiSync.destination) {
+ case PkiSync.LinuxServer: {
+ const linuxServerPkiSync = linuxServerPkiSyncFactory({
+ certificateSyncDAL: dependencies.certificateSyncDAL,
+ gatewayV2Service: dependencies.gatewayV2Service,
+ gatewayPoolService: dependencies.gatewayPoolService
+ });
+ return linuxServerPkiSync.runPreflightCheck(pkiSync, certificateMap);
+ }
+ case PkiSync.WindowsServer: {
+ if (!dependencies.gatewayV2Service) {
+ throw new PkiSyncError({
+ shouldRetry: false,
+ message: "Windows Server sync requires a gateway to reach the host."
+ });
+ }
+ const windowsServerPkiSync = windowsServerPkiSyncFactory({
+ certificateSyncDAL: dependencies.certificateSyncDAL,
+ gatewayV2Service: dependencies.gatewayV2Service,
+ gatewayPoolService: dependencies.gatewayPoolService
+ });
+ return windowsServerPkiSync.runPreflightCheck(pkiSync, certificateMap);
+ }
+ default:
+ return undefined;
+ }
+ },
+
removeCertificates: async (
pkiSync: TPkiSyncWithCredentials,
certificateNames: string[],
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.ts
new file mode 100644
index 0000000000..8f3d9398a1
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-host-command-fns.ts
@@ -0,0 +1,269 @@
+import RE2 from "re2";
+
+import { logger } from "@app/lib/logger";
+
+import { PkiSyncStatus } from "./pki-sync-enums";
+import { PkiSyncError } from "./pki-sync-errors";
+
+export enum HostCommandKind {
+ Preflight = "preflight check",
+ PostSync = "post-sync command"
+}
+
+export const HOST_COMMAND_TIMEOUT_MS: Record<HostCommandKind, number> = {
+ [HostCommandKind.Preflight]: 10_000,
+ [HostCommandKind.PostSync]: 30_000
+};
+
+export enum HostCommandVariable {
+ CertificatePath = "certificatePath",
+ CertificateDirectory = "certificateDirectory",
+ CertificateFiles = "certificateFiles",
+ CommonName = "commonName",
+ Pkcs12Password = "pkcs12Password"
+}
+
+const SINGLE_CERTIFICATE_HOST_COMMAND_VARIABLES: HostCommandVariable[] = [
+ HostCommandVariable.CertificatePath,
+ HostCommandVariable.CommonName
+];
+
+export type THostCommandContext = {
+ certificatePath?: string;
+ commonName?: string;
+ certificateDirectory: string;
+ certificateFiles: string[];
+ pkcs12Password?: string;
+};
+
+export type THostCommandCertificate = { paths: string[]; commonName?: string };
+
+export const HOST_COMMAND_MAX_LENGTH = 2048;
+
+const VARIABLE_PATTERN = new RE2("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}", "g");
+
+const MAX_CAPTURED_OUTPUT_CHARS = 1000;
+
+const MAX_FAILURE_DETAIL_CHARS = 120;
+
+const REDACTED_PLACEHOLDER = "[REDACTED]";
+
+const DEADLINE_GRACE_MS = 5_000;
+
+const sentenceCase = (text: string): string => `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
+
+export type THostCommandResult = {
+ status: PkiSyncStatus.Succeeded | PkiSyncStatus.Failed;
+ exitCode?: number;
+ durationMs: number;
+ output?: string;
+ failureDetail?: string;
+ error?: string;
+};
+
+export type THostCommandExecutionResult = { stdout: string; stderr: string; exitCode: number };
+
+const findHostCommandVariables = (command?: string): Set<string> => {
+ const used = new Set<string>();
+ if (!command) return used;
+
+ command.replace(VARIABLE_PATTERN, (match: string, name: string) => {
+ used.add(name);
+ return match;
+ });
+
+ return used;
+};
+
+export const toPosixShellLiteral = (value: string): string => `'${value.split("'").join(`'\\''`)}'`;
+
+export const toPowerShellLiteral = (value: string): string => `'${value.split("'").join("''")}'`;
+
+export const formatHostCommandVariables = (variables: string[]): string =>
+ variables.map((variable) => `{{${variable}}}`).join(", ");
+
+const CERTIFICATE_DEPENDENT_HOST_COMMAND_VARIABLES: HostCommandVariable[] = [
+ HostCommandVariable.CertificatePath,
+ HostCommandVariable.CertificateFiles,
+ HostCommandVariable.CommonName
+];
+
+export const commandNeedsCertificateData = (command?: string): boolean => {
+ const used = findHostCommandVariables(command);
+ return CERTIFICATE_DEPENDENT_HOST_COMMAND_VARIABLES.some((variable) => used.has(variable));
+};
+
+export const findSingleCertificateHostCommandVariables = (command?: string): HostCommandVariable[] => {
+ const used = findHostCommandVariables(command);
+ return SINGLE_CERTIFICATE_HOST_COMMAND_VARIABLES.filter((variable) => used.has(variable));
+};
+
+export const buildHostCommandContext = (args: {
+ kind: HostCommandKind;
+ command: string;
+ destinationDirectory: string;
+ certificates: THostCommandCertificate[];
+ certificateFiles?: string[];
+ pkcs12Password?: string;
+}): THostCommandContext => {
+ const { kind, command, destinationDirectory, certificates, certificateFiles, pkcs12Password } = args;
+
+ const singleCertificateVariables = findSingleCertificateHostCommandVariables(command);
+ if (certificates.length > 1 && singleCertificateVariables.length > 0) {
+ const delivered = kind === HostCommandKind.Preflight ? "would deliver" : "delivered";
+ throw new PkiSyncError({
+ message: `${sentenceCase(kind)} uses ${formatHostCommandVariables(
+ singleCertificateVariables
+ )}. A variable that names one certificate cannot be resolved for a run that ${delivered} ${
+ certificates.length
+ } certificates. Unlink all but one certificate, or use {{certificateFiles}} instead.`,
+ shouldRetry: false
+ });
+ }
+
+ const onlyCertificate = certificates.length === 1 ? certificates[0] : undefined;
+
+ return {
+ certificatePath: onlyCertificate?.paths[0],
+ commonName: onlyCertificate?.commonName,
+ certificateDirectory: destinationDirectory,
+ certificateFiles: certificateFiles ?? certificates.flatMap((certificate) => certificate.paths),
+ pkcs12Password
+ };
+};
+
+const renderHostCommand = (
+ command: string,
+ values: Map<string, string | undefined>,
+ toShellLiteral: (value: string) => string
+): string =>
+ command.replace(VARIABLE_PATTERN, (match: string, name: string) =>
+ values.has(name) ? toShellLiteral(values.get(name) ?? "") : match
+ );
+
+export const renderHostCommandContext = (
+ command: string,
+ context: THostCommandContext,
+ toShellLiteral: (value: string) => string
+): string =>
+ renderHostCommand(
+ command,
+ new Map<string, string | undefined>([
+ [HostCommandVariable.CertificatePath, context.certificatePath],
+ [HostCommandVariable.CertificateDirectory, context.certificateDirectory],
+ [HostCommandVariable.CertificateFiles, context.certificateFiles.join("\n")],
+ [HostCommandVariable.CommonName, context.commonName],
+ [HostCommandVariable.Pkcs12Password, context.pkcs12Password]
+ ]),
+ toShellLiteral
+ );
+
+export const normalizeNewHostCommandOption = (
+ syncOptions: Record<string, unknown>,
+ optionKey: string
+): Record<string, unknown> => {
+ if (syncOptions[optionKey]) return syncOptions;
+
+ const normalized = { ...syncOptions };
+ delete normalized[optionKey];
+ return normalized;
+};
+
+export const applyHostCommandOptionUpdate = (
+ resolvedSyncOptions: Record<string, unknown>,
+ optionKey: string,
+ storedCommand: unknown
+): Record<string, unknown> => {
+ const requested = resolvedSyncOptions[optionKey];
+ const next = { ...resolvedSyncOptions };
+
+ const keep = requested === undefined ? storedCommand : requested;
+ if (typeof keep === "string" && keep) {
+ next[optionKey] = keep;
+ } else {
+ delete next[optionKey];
+ }
+
+ return next;
+};
+
+const redactSecrets = (text: string, secrets: Array<string | undefined>): string =>
+ secrets.reduce<string>((acc, secret) => (secret ? acc.split(secret).join(REDACTED_PLACEHOLDER) : acc), text);
+
+const truncate = (text: string, maxLength: number): string =>
+ text.length > maxLength ? `${text.slice(0, maxLength)}... (truncated)` : text;
+
+const firstNonEmptyLine = (text?: string): string | undefined =>
+ text
+ ?.split("\n")
+ .map((line) => line.trim())
+ .find(Boolean);
+
+const captureOutput = (stdout: string, stderr: string): string | undefined => {
+ const combined = [stdout.trim(), stderr.trim()].filter(Boolean).join("\n");
+ return combined ? truncate(combined, MAX_CAPTURED_OUTPUT_CHARS) : undefined;
+};
+
+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);
+ })
+ ]).finally(() => clearTimeout(timer));
+};
+
+export const runHostCommand = async (args: {
+ kind: HostCommandKind;
+ syncId: string;
+ execute: () => Promise<THostCommandExecutionResult>;
+ secretsToRedact?: Array<string | undefined>;
+}): Promise<THostCommandResult> => {
+ const { kind, syncId, execute, secretsToRedact = [] } = args;
+ const timeoutMs = HOST_COMMAND_TIMEOUT_MS[kind];
+ const startedAt = Date.now();
+ const redact = (text: string) => redactSecrets(text, secretsToRedact);
+
+ try {
+ const { stdout, stderr, exitCode } = await withHostCommandDeadline(execute, timeoutMs, DEADLINE_GRACE_MS);
+ const durationMs = Date.now() - startedAt;
+ const output = captureOutput(redact(stdout), redact(stderr));
+
+ if (exitCode === 0) {
+ logger.info(`PKI sync ${kind} succeeded [syncId=${syncId}] [durationMs=${durationMs}]`);
+ return { status: PkiSyncStatus.Succeeded, exitCode, durationMs, output };
+ }
+
+ logger.warn(`PKI sync ${kind} failed [syncId=${syncId}] [exitCode=${exitCode}] [durationMs=${durationMs}]`);
+ return {
+ status: PkiSyncStatus.Failed,
+ exitCode,
+ durationMs,
+ output,
+ failureDetail: firstNonEmptyLine(redact(stderr))?.slice(0, MAX_FAILURE_DETAIL_CHARS),
+ error: `Command exited with code ${exitCode}`
+ };
+ } catch (err) {
+ const durationMs = Date.now() - startedAt;
+ const error = redact((err as Error)?.message ?? "Unknown error");
+ logger.warn(`PKI sync ${kind} could not run [syncId=${syncId}] [durationMs=${durationMs}]: ${error}`);
+ return { status: PkiSyncStatus.Failed, durationMs, error };
+ }
+};
+
+export const hostCommandFailurePrefix = (kind: HostCommandKind): string => `${sentenceCase(kind)} failed`;
+
+export const buildHostCommandFailureMessage = (kind: HostCommandKind, result: THostCommandResult): string => {
+ const detail = result.failureDetail ?? firstNonEmptyLine(result.output);
+ if (result.exitCode === undefined) {
+ const reason = detail ?? result.error;
+ return reason
+ ? `${hostCommandFailurePrefix(kind)}: ${truncate(reason, MAX_FAILURE_DETAIL_CHARS)}`
+ : hostCommandFailurePrefix(kind);
+ }
+
+ const prefix = `${hostCommandFailurePrefix(kind)} (exit ${result.exitCode})`;
+ return detail ? `${prefix}: ${truncate(detail, MAX_FAILURE_DETAIL_CHARS)}` : prefix;
+};
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.ts
index 5871b2080b..a86e07eb22 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
@@ -1,17 +1,19 @@
import { describe, expect, test, vi } from "vitest";
import { PkiSyncStatus } from "./pki-sync-enums";
+import {
+ findSingleCertificateHostCommandVariables,
+ HostCommandVariable,
+ renderHostCommandContext,
+ toPosixShellLiteral,
+ toPowerShellLiteral
+} from "./pki-sync-host-command-fns";
import {
applyPostSyncCommandUpdate,
buildPostSyncCommandFailureMessage,
buildPostSyncCommandPlan,
- findSingleCertificatePostSyncCommandVariables,
normalizeNewPostSyncCommand,
- PostSyncCommandVariable,
- renderPostSyncCommand,
runPostSyncCommand,
- toPosixShellLiteral,
- toPowerShellLiteral,
TPostSyncCommandContext
} from "./pki-sync-post-sync-command-fns";
@@ -31,14 +33,33 @@ describe("buildPostSyncCommandPlan", () => {
command: "systemctl reload nginx",
destinationDirectory: "/etc/ssl/certs",
deliveredPaths: new Set(["/etc/ssl/certs/app.pem"]),
- deliveredCertificates: [{ path: "/etc/ssl/certs/app.pem", commonName: "app.example.com" }]
+ deliveredCertificates: [{ paths: ["/etc/ssl/certs/app.pem"], commonName: "app.example.com" }]
};
const twoCertificates = [
- { path: "/etc/ssl/certs/a.pem", commonName: "a.example.com" },
- { path: "/etc/ssl/certs/b.pem", commonName: "b.example.com" }
+ { paths: ["/etc/ssl/certs/a.pem"], commonName: "a.example.com" },
+ { paths: ["/etc/ssl/certs/b.pem"], commonName: "b.example.com" }
];
+ // A certificate can write some of its files and then fail. Those files are on the host, so the
+ // command is told about them even though their certificate is reported failed.
+ test("lists every file actually written, including one whose certificate later failed", () => {
+ const plan = buildPostSyncCommandPlan({
+ ...baseArgs,
+ deliveredPaths: new Set([
+ "/etc/ssl/certs/app.pem",
+ "/etc/ssl/certs/half-written.pem",
+ "/etc/ssl/certs/half-written.chain.pem"
+ ])
+ });
+
+ expect(plan?.context.certificateFiles).toEqual([
+ "/etc/ssl/certs/app.pem",
+ "/etc/ssl/certs/half-written.pem",
+ "/etc/ssl/certs/half-written.chain.pem"
+ ]);
+ });
+
test("returns a plan when a command is configured and files were delivered", () => {
const plan = buildPostSyncCommandPlan(baseArgs);
@@ -88,36 +109,34 @@ describe("buildPostSyncCommandPlan", () => {
});
});
-describe("findSingleCertificatePostSyncCommandVariables", () => {
+describe("findSingleCertificateHostCommandVariables", () => {
test("finds the placeholders that name one certificate", () => {
- expect(findSingleCertificatePostSyncCommandVariables("cp {{certificatePath}} /tmp/{{commonName}}")).toEqual([
- PostSyncCommandVariable.CertificatePath,
- PostSyncCommandVariable.CommonName
+ expect(findSingleCertificateHostCommandVariables("cp {{certificatePath}} /tmp/{{commonName}}")).toEqual([
+ HostCommandVariable.CertificatePath,
+ HostCommandVariable.CommonName
]);
});
test("ignores placeholders that describe the whole run", () => {
- expect(findSingleCertificatePostSyncCommandVariables("echo {{certificateFiles}} {{certificateDirectory}}")).toEqual(
- []
- );
+ expect(findSingleCertificateHostCommandVariables("echo {{certificateFiles}} {{certificateDirectory}}")).toEqual([]);
});
test("matches a placeholder regardless of its internal spacing", () => {
- expect(findSingleCertificatePostSyncCommandVariables("echo {{ commonName }}")).toEqual([
- PostSyncCommandVariable.CommonName
+ expect(findSingleCertificateHostCommandVariables("echo {{ commonName }}")).toEqual([
+ HostCommandVariable.CommonName
]);
});
test("returns none for an empty command, or text that is not a placeholder", () => {
- expect(findSingleCertificatePostSyncCommandVariables()).toEqual([]);
- expect(findSingleCertificatePostSyncCommandVariables("echo {{#if")).toEqual([]);
- expect(findSingleCertificatePostSyncCommandVariables("jq {{.commonName}}")).toEqual([]);
+ expect(findSingleCertificateHostCommandVariables()).toEqual([]);
+ expect(findSingleCertificateHostCommandVariables("echo {{#if")).toEqual([]);
+ expect(findSingleCertificateHostCommandVariables("jq {{.commonName}}")).toEqual([]);
});
});
-describe("renderPostSyncCommand", () => {
+describe("renderHostCommandContext", () => {
test("substitutes each placeholder with the run's value", () => {
- const rendered = renderPostSyncCommand(
+ const rendered = renderHostCommandContext(
"cp {{certificatePath}} {{certificateDirectory}}/live.pem",
context,
toPosixShellLiteral
@@ -127,14 +146,16 @@ describe("renderPostSyncCommand", () => {
});
test("renders the common name and the newline-joined file list", () => {
- expect(renderPostSyncCommand("echo {{commonName}}", context, toPosixShellLiteral)).toBe("echo 'app.example.com'");
- expect(renderPostSyncCommand("echo {{certificateFiles}}", context, toPosixShellLiteral)).toBe(
+ expect(renderHostCommandContext("echo {{commonName}}", context, toPosixShellLiteral)).toBe(
+ "echo 'app.example.com'"
+ );
+ expect(renderHostCommandContext("echo {{certificateFiles}}", context, toPosixShellLiteral)).toBe(
`echo '${context.certificateFiles.join("\n")}'`
);
});
test("renders an absent optional variable as an empty literal rather than the placeholder", () => {
- expect(renderPostSyncCommand("echo {{pkcs12Password}}", context, toPosixShellLiteral)).toBe("echo ''");
+ expect(renderHostCommandContext("echo {{pkcs12Password}}", context, toPosixShellLiteral)).toBe("echo ''");
});
test("quotes a value that would otherwise break out of the command", () => {
@@ -143,7 +164,7 @@ describe("renderPostSyncCommand", () => {
commonName: "app.example.com'; rm -rf / #"
};
- const rendered = renderPostSyncCommand("echo {{commonName}}", malicious, toPosixShellLiteral);
+ const rendered = renderHostCommandContext("echo {{commonName}}", malicious, toPosixShellLiteral);
// The injected quote is escaped, so the whole value stays a single argument to echo.
expect(rendered).toBe(`echo 'app.example.com'\\''; rm -rf / #'`);
@@ -166,7 +187,7 @@ describe("renderPostSyncCommand", () => {
// eslint-disable-next-line no-template-curly-in-string
["variable expansion", "app${HOME}.example.com"]
])("a hostile common name (%s) stays inside one quoted literal", (_name, commonName) => {
- const rendered = renderPostSyncCommand("echo {{commonName}}", { ...context, commonName }, toPosixShellLiteral);
+ const rendered = renderHostCommandContext("echo {{commonName}}", { ...context, commonName }, toPosixShellLiteral);
// Rebuilding the literal from the value is the whole contract: any quote in it is escaped, and
// nothing else can terminate the literal, so the shell sees exactly one argument.
@@ -176,14 +197,14 @@ describe("renderPostSyncCommand", () => {
test("doubles quotes for PowerShell instead of backslash-escaping", () => {
const malicious: TPostSyncCommandContext = { ...context, commonName: "a'; Remove-Item C:\\ #" };
- expect(renderPostSyncCommand("Write-Output {{commonName}}", malicious, toPowerShellLiteral)).toBe(
+ expect(renderHostCommandContext("Write-Output {{commonName}}", malicious, toPowerShellLiteral)).toBe(
"Write-Output 'a''; Remove-Item C:\\ #'"
);
});
});
-describe("renderPostSyncCommand: text that is not a documented variable", () => {
- const render = (command: string) => renderPostSyncCommand(command, context, toPosixShellLiteral);
+describe("renderHostCommandContext: text that is not a documented variable", () => {
+ const render = (command: string) => renderHostCommandContext(command, context, toPosixShellLiteral);
test("an unknown placeholder is left exactly as the operator wrote it", () => {
// Not blanked and not rejected: a typo shows up in the command the host runs, where the operator
@@ -307,7 +328,7 @@ describe("buildPostSyncCommandFailureMessage", () => {
expect(message).toBe("Post-sync command failed (exit 2): Unit nginx.service not found");
});
- test("still reports the exit code when the command produced no output at all", () => {
+ test("reports the exit code alone when the command produced no output at all", () => {
const message = buildPostSyncCommandFailureMessage({
status: PkiSyncStatus.Failed,
exitCode: 42,
@@ -315,7 +336,7 @@ describe("buildPostSyncCommandFailureMessage", () => {
error: "Command exited with code 42"
});
- expect(message).toBe("Post-sync command failed (exit 42): Command exited with code 42");
+ expect(message).toBe("Post-sync command failed (exit 42)");
});
test("falls back to the error when the command never ran, so there is no exit code", () => {
diff --git a/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.ts b/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.ts
index 5f15b41401..f5280f5534 100644
--- a/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.ts
@@ -1,101 +1,40 @@
-import RE2 from "re2";
+import {
+ applyHostCommandOptionUpdate,
+ buildHostCommandContext,
+ buildHostCommandFailureMessage,
+ HOST_COMMAND_TIMEOUT_MS,
+ HostCommandKind,
+ normalizeNewHostCommandOption,
+ runHostCommand,
+ THostCommandCertificate,
+ THostCommandContext,
+ THostCommandExecutionResult,
+ THostCommandResult
+} from "./pki-sync-host-command-fns";
-import { logger } from "@app/lib/logger";
+export const POST_SYNC_COMMAND_TIMEOUT_MS = HOST_COMMAND_TIMEOUT_MS[HostCommandKind.PostSync];
-import { PkiSyncStatus } from "./pki-sync-enums";
-import { PkiSyncError } from "./pki-sync-errors";
+export const POST_SYNC_COMMAND_OPTION_KEY = "postSyncCommand";
-export enum PostSyncCommandVariable {
- CertificatePath = "certificatePath",
- CertificateDirectory = "certificateDirectory",
- CertificateFiles = "certificateFiles",
- CommonName = "commonName",
- Pkcs12Password = "pkcs12Password"
-}
+export type TPostSyncCommandContext = THostCommandContext;
-// Matches a {{name}} variable.
-const VARIABLE_PATTERN = new RE2("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}", "g");
+export type TPostSyncCommandResult = THostCommandResult;
-const isPostSyncCommandVariable = (name: string): name is PostSyncCommandVariable =>
- (Object.values(PostSyncCommandVariable) as string[]).includes(name);
-
-const SINGLE_CERTIFICATE_VARIABLES: PostSyncCommandVariable[] = [
- PostSyncCommandVariable.CertificatePath,
- PostSyncCommandVariable.CommonName
-];
-
-export const formatPostSyncCommandVariables = (variables: PostSyncCommandVariable[]): string =>
- variables.map((variable) => `{{${variable}}}`).join(", ");
-
-export const findSingleCertificatePostSyncCommandVariables = (command?: string): PostSyncCommandVariable[] => {
- if (!command) return [];
-
- const used = new Set<string>();
- command.replace(VARIABLE_PATTERN, (match: string, name: string) => {
- used.add(name);
- return match;
- });
-
- return SINGLE_CERTIFICATE_VARIABLES.filter((variable) => used.has(variable));
-};
-
-export const POST_SYNC_COMMAND_MAX_LENGTH = 2048;
-
-export const POST_SYNC_COMMAND_TIMEOUT_MS = 30_000;
-
-const MAX_CAPTURED_OUTPUT_CHARS = 1000;
-
-const MAX_FAILURE_DETAIL_CHARS = 120;
-
-const REDACTED_PLACEHOLDER = "[REDACTED]";
-
-export type TPostSyncCommandContext = {
- certificatePath?: string;
- commonName?: string;
- certificateDirectory: string;
- certificateFiles: string[];
- pkcs12Password?: string;
-};
-
-export type TPostSyncCommandResult = {
- status: PkiSyncStatus.Succeeded | PkiSyncStatus.Failed;
- exitCode?: number;
- durationMs: number;
- output?: string;
- failureDetail?: string;
- error?: string;
-};
-
-export type TPostSyncCommandExecutionResult = { stdout: string; stderr: string; exitCode: number };
+export type TPostSyncCommandExecutionResult = THostCommandExecutionResult;
export type TPostSyncCommandPlan = { command: string; context: TPostSyncCommandContext };
-const POST_SYNC_COMMAND_KEY = "postSyncCommand";
+export const getPostSyncCommand = (syncOptions: unknown): string | undefined =>
+ (syncOptions as Record<string, unknown> | undefined)?.[POST_SYNC_COMMAND_OPTION_KEY] as string | undefined;
-export const normalizeNewPostSyncCommand = (syncOptions: Record<string, unknown>): Record<string, unknown> => {
- if (syncOptions[POST_SYNC_COMMAND_KEY]) return syncOptions;
-
- const normalized = { ...syncOptions };
- delete normalized[POST_SYNC_COMMAND_KEY];
- return normalized;
-};
+export const normalizeNewPostSyncCommand = (syncOptions: Record<string, unknown>): Record<string, unknown> =>
+ normalizeNewHostCommandOption(syncOptions, POST_SYNC_COMMAND_OPTION_KEY);
export const applyPostSyncCommandUpdate = (
resolvedSyncOptions: Record<string, unknown>,
storedCommand: unknown
-): Record<string, unknown> => {
- const requested = resolvedSyncOptions[POST_SYNC_COMMAND_KEY];
- const next = { ...resolvedSyncOptions };
-
- const keep = requested === undefined ? storedCommand : requested;
- if (typeof keep === "string" && keep) {
- next[POST_SYNC_COMMAND_KEY] = keep;
- } else {
- delete next[POST_SYNC_COMMAND_KEY];
- }
-
- return next;
-};
+): Record<string, unknown> =>
+ applyHostCommandOptionUpdate(resolvedSyncOptions, POST_SYNC_COMMAND_OPTION_KEY, storedCommand);
/**
* Assembles what a post-sync command needs, or undefined when there is no command or the run
@@ -105,139 +44,30 @@ export const buildPostSyncCommandPlan = (args: {
command?: string;
destinationDirectory: string;
deliveredPaths: Set<string>;
- deliveredCertificates: Array<{ path: string; commonName?: string }>;
+ deliveredCertificates: THostCommandCertificate[];
pkcs12Password?: string;
}): TPostSyncCommandPlan | undefined => {
const { command, destinationDirectory, deliveredPaths, deliveredCertificates, pkcs12Password } = args;
if (!command || deliveredCertificates.length === 0) return undefined;
- const singleCertificateVariables = findSingleCertificatePostSyncCommandVariables(command);
- if (deliveredCertificates.length > 1 && singleCertificateVariables.length > 0) {
- throw new PkiSyncError({
- message: `Post-sync command uses ${formatPostSyncCommandVariables(
- singleCertificateVariables
- )}. A variable that names one certificate cannot be resolved for a run that delivered ${
- deliveredCertificates.length
- } certificates. Unlink all but one certificate, or use {{certificateFiles}} instead.`,
- shouldRetry: false
- });
- }
-
- const onlyCertificate = deliveredCertificates.length === 1 ? deliveredCertificates[0] : undefined;
-
return {
command,
- context: {
- certificatePath: onlyCertificate?.path,
- commonName: onlyCertificate?.commonName,
- certificateDirectory: destinationDirectory,
+ context: buildHostCommandContext({
+ kind: HostCommandKind.PostSync,
+ command,
+ destinationDirectory,
+ certificates: deliveredCertificates,
certificateFiles: Array.from(deliveredPaths),
pkcs12Password
- }
+ })
};
};
-export const toPosixShellLiteral = (value: string): string => `'${value.split("'").join(`'\\''`)}'`;
-
-export const toPowerShellLiteral = (value: string): string => `'${value.split("'").join("''")}'`;
-
-/**
- * Renders the operator's template into the command that runs on the target.
- *
- * Each value is substituted as a quoted shell literal, so a common name carrying shell
- * metacharacters cannot break out and execute as code. The quoting is part of the substitution, so
- * the operator writes `{{certificatePath}}`, not `"{{certificatePath}}"`.
- *
- * Text that is not a documented variable is left as written, because other tools use the same braces
- * (helm, jq, Go templates). A plain scan rather than a template engine, so there is no helper,
- * subexpression or prototype path to evaluate.
- */
-export const renderPostSyncCommand = (
- command: string,
- context: TPostSyncCommandContext,
- toShellLiteral: (value: string) => string
-): string => {
- const values = new Map<PostSyncCommandVariable, string | undefined>([
- [PostSyncCommandVariable.CertificatePath, context.certificatePath],
- [PostSyncCommandVariable.CertificateDirectory, context.certificateDirectory],
- [PostSyncCommandVariable.CertificateFiles, context.certificateFiles.join("\n")],
- [PostSyncCommandVariable.CommonName, context.commonName],
- [PostSyncCommandVariable.Pkcs12Password, context.pkcs12Password]
- ]);
-
- return command.replace(VARIABLE_PATTERN, (match: string, name: string) =>
- isPostSyncCommandVariable(name) ? toShellLiteral(values.get(name) ?? "") : match
- );
-};
-
-const redactSecrets = (text: string, secrets: Array<string | undefined>): string =>
- secrets.reduce<string>((acc, secret) => (secret ? acc.split(secret).join(REDACTED_PLACEHOLDER) : acc), text);
-
-const truncate = (text: string, maxLength: number): string =>
- text.length > maxLength ? `${text.slice(0, maxLength)}... (truncated)` : text;
-
-const firstNonEmptyLine = (text?: string): string | undefined =>
- text
- ?.split("\n")
- .map((line) => line.trim())
- .find(Boolean);
-
-const captureOutput = (stdout: string, stderr: string): string | undefined => {
- const combined = [stdout.trim(), stderr.trim()].filter(Boolean).join("\n");
- return combined ? truncate(combined, MAX_CAPTURED_OUTPUT_CHARS) : undefined;
-};
-
-/**
- * Runs the command through the caller's transport. Every failure mode (non-zero exit, timeout,
- * unreachable gateway) returns a Failed result instead of throwing, so the caller can fail the sync
- * while keeping the per-certificate delivery statuses it already recorded.
- */
-export const runPostSyncCommand = async (args: {
+export const runPostSyncCommand = (args: {
syncId: string;
execute: () => Promise<TPostSyncCommandExecutionResult>;
secretsToRedact?: Array<string | undefined>;
-}): Promise<TPostSyncCommandResult> => {
- const { syncId, execute, secretsToRedact = [] } = args;
- const startedAt = Date.now();
- const redact = (text: string) => redactSecrets(text, secretsToRedact);
+}): Promise<TPostSyncCommandResult> => runHostCommand({ ...args, kind: HostCommandKind.PostSync });
- try {
- const { stdout, stderr, exitCode } = await execute();
- const durationMs = Date.now() - startedAt;
- const output = captureOutput(redact(stdout), redact(stderr));
-
- if (exitCode === 0) {
- logger.info(`PKI sync post-sync command succeeded [syncId=${syncId}] [durationMs=${durationMs}]`);
- return { status: PkiSyncStatus.Succeeded, exitCode, durationMs, output };
- }
-
- logger.warn(
- `PKI sync post-sync command failed [syncId=${syncId}] [exitCode=${exitCode}] [durationMs=${durationMs}]`
- );
- return {
- status: PkiSyncStatus.Failed,
- exitCode,
- durationMs,
- output,
- failureDetail: firstNonEmptyLine(redact(stderr))?.slice(0, MAX_FAILURE_DETAIL_CHARS),
- error: `Command exited with code ${exitCode}`
- };
- } catch (err) {
- const durationMs = Date.now() - startedAt;
- const error = redact((err as Error)?.message ?? "Unknown error");
- logger.warn(`PKI sync post-sync command could not run [syncId=${syncId}] [durationMs=${durationMs}]: ${error}`);
- return { status: PkiSyncStatus.Failed, durationMs, error };
- }
-};
-
-/**
- * A short, single-line reason for pki_syncs.lastSyncMessage. The full output stays in the audit log.
- */
-export const buildPostSyncCommandFailureMessage = (result: TPostSyncCommandResult): string => {
- const detail = result.failureDetail ?? firstNonEmptyLine(result.output);
- const prefix =
- result.exitCode === undefined ? "Post-sync command failed" : `Post-sync command failed (exit ${result.exitCode})`;
-
- if (detail) return `${prefix}: ${truncate(detail, MAX_FAILURE_DETAIL_CHARS)}`;
- return result.error ? `${prefix}: ${truncate(result.error, MAX_FAILURE_DETAIL_CHARS)}` : prefix;
-};
+export const buildPostSyncCommandFailureMessage = (result: TPostSyncCommandResult): string =>
+ buildHostCommandFailureMessage(HostCommandKind.PostSync, result);
diff --git a/backend/src/services/pki-sync/pki-sync-preflight-command-fns.test.ts b/backend/src/services/pki-sync/pki-sync-preflight-command-fns.test.ts
new file mode 100644
index 0000000000..4e956739d3
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-preflight-command-fns.test.ts
@@ -0,0 +1,386 @@
+import { describe, expect, test, vi } from "vitest";
+
+import { PkiSyncStatus } from "./pki-sync-enums";
+import { PemCertificateExtension, PkiSyncExportFormat } from "./pki-sync-export-fns";
+import {
+ hostCommandFailurePrefix,
+ HostCommandKind,
+ renderHostCommandContext,
+ toPosixShellLiteral,
+ 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,
+ didPreflightCheckFail,
+ normalizeNewPreflightCommand,
+ PREFLIGHT_COMMAND_TIMEOUT_MS,
+ runPreflightCommand
+} from "./pki-sync-preflight-command-fns";
+import { TCertificateMap } from "./pki-sync-types";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
+}));
+
+const posixJoin = (directory: string, fileName: string) => `${directory}/${fileName}`;
+const windowsJoin = (directory: string, fileName: string) => `${directory}\\${fileName}`;
+
+const PEM_OPTIONS = { format: PkiSyncExportFormat.Pem, includePrivateKey: true };
+
+const oneCertificate: TCertificateMap = {
+ "app.example.com": {
+ cert: "pem",
+ privateKey: "key",
+ certificateChain: "chain",
+ commonName: "app.example.com"
+ }
+};
+
+const twoCertificates: TCertificateMap = {
+ ...oneCertificate,
+ "api.example.com": { cert: "pem", privateKey: "key", commonName: "api.example.com" }
+};
+
+const planFor = (command: string, certificateMap: TCertificateMap, overrides = {}) =>
+ buildPreflightCommandPlan({
+ command,
+ destinationDirectory: "/etc/ssl/certs",
+ certificateMap,
+ exportOptions: PEM_OPTIONS,
+ joinPath: posixJoin,
+ ...overrides
+ });
+
+describe("preflight 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);
+ });
+});
+
+describe("buildPreflightCommandPlan", () => {
+ test("returns undefined when no check is configured", () => {
+ expect(planFor("", oneCertificate)).toBeUndefined();
+ expect(
+ buildPreflightCommandPlan({
+ command: undefined,
+ destinationDirectory: "/etc/ssl/certs",
+ certificateMap: oneCertificate,
+ exportOptions: PEM_OPTIONS,
+ joinPath: posixJoin
+ })
+ ).toBeUndefined();
+ });
+
+ test("still builds a plan when the run would deliver nothing", () => {
+ expect(planFor("systemctl is-active nginx", {})?.context.certificateFiles).toEqual([]);
+ });
+
+ test("resolves the paths the run is about to write, not what it wrote", () => {
+ const plan = planFor("test -f {{certificatePath}}", oneCertificate);
+
+ expect(plan?.context.certificatePath).toBe("/etc/ssl/certs/app.example.com.pem");
+ expect(plan?.context.certificateFiles).toEqual([
+ "/etc/ssl/certs/app.example.com.pem",
+ "/etc/ssl/certs/app.example.com.chain.pem",
+ "/etc/ssl/certs/app.example.com.key"
+ ]);
+ });
+
+ test("resolves the certificate's common name", () => {
+ expect(planFor("echo {{commonName}}", oneCertificate)?.context.commonName).toBe("app.example.com");
+ });
+
+ test("follows the export format, so PKCS#12 predicts the single .pfx", () => {
+ const plan = planFor("test -f {{certificatePath}}", oneCertificate, {
+ exportOptions: { format: PkiSyncExportFormat.Pkcs12, includePrivateKey: true }
+ });
+
+ expect(plan?.context.certificatePath).toBe("/etc/ssl/certs/app.example.com.pfx");
+ expect(plan?.context.certificateFiles).toEqual(["/etc/ssl/certs/app.example.com.pfx"]);
+ });
+
+ test("follows the PEM extension and the combined-chain option", () => {
+ const plan = planFor("echo {{certificateFiles}}", oneCertificate, {
+ exportOptions: {
+ format: PkiSyncExportFormat.Pem,
+ includePrivateKey: false,
+ pemCertificateExtension: PemCertificateExtension.Crt,
+ combineCertificateChain: true
+ }
+ });
+
+ expect(plan?.context.certificateFiles).toEqual(["/etc/ssl/certs/app.example.com.crt"]);
+ });
+
+ test("uses the destination's own path separator", () => {
+ const plan = buildPreflightCommandPlan({
+ command: "Test-Path {{certificatePath}}",
+ destinationDirectory: "C:\\certs",
+ certificateMap: oneCertificate,
+ exportOptions: { format: PkiSyncExportFormat.Pkcs12, includePrivateKey: true },
+ joinPath: windowsJoin
+ });
+
+ expect(plan?.context.certificatePath).toBe("C:\\certs\\app.example.com.pfx");
+ });
+
+ test("carries the PKCS#12 password when the caller supplies it", () => {
+ expect(
+ planFor("echo {{pkcs12Password}}", oneCertificate, { pkcs12Password: "s3cret" })?.context.pkcs12Password
+ ).toBe("s3cret");
+ });
+
+ test("rejects a single-certificate variable when the run would cover several", () => {
+ expect(() => planFor("test -f {{certificatePath}}", twoCertificates)).toThrow(
+ /\{\{certificatePath\}\}.*would deliver 2 certificates/
+ );
+ expect(() => planFor("echo {{commonName}}", twoCertificates)).toThrow(/would deliver 2 certificates/);
+ });
+
+ test("allows run-wide variables for any number of certificates", () => {
+ const plan = planFor("echo {{certificateFiles}} in {{certificateDirectory}}", twoCertificates);
+
+ // Only the first has a chain, so the file list is per-certificate rather than a fixed shape.
+ expect(plan?.context.certificateFiles).toEqual([
+ "/etc/ssl/certs/app.example.com.pem",
+ "/etc/ssl/certs/app.example.com.chain.pem",
+ "/etc/ssl/certs/app.example.com.key",
+ "/etc/ssl/certs/api.example.com.pem",
+ "/etc/ssl/certs/api.example.com.key"
+ ]);
+ expect(plan?.context.certificatePath).toBeUndefined();
+ expect(plan?.context.commonName).toBeUndefined();
+ });
+});
+
+describe("renderHostCommandContext", () => {
+ const { context } = planFor("x", oneCertificate)!;
+
+ test("substitutes the prospective path and directory as quoted literals", () => {
+ expect(renderHostCommandContext("test -f {{certificatePath}}", context, toPosixShellLiteral)).toBe(
+ "test -f '/etc/ssl/certs/app.example.com.pem'"
+ );
+ expect(renderHostCommandContext("test -d {{certificateDirectory}}", context, toPosixShellLiteral)).toBe(
+ "test -d '/etc/ssl/certs'"
+ );
+ });
+
+ test("quotes a value that would otherwise break out of the command", () => {
+ const hostile = { ...context, commonName: "app.example.com'; rm -rf / #" };
+
+ expect(renderHostCommandContext("echo {{commonName}}", hostile, toPosixShellLiteral)).toBe(
+ `echo 'app.example.com'\\''; rm -rf / #'`
+ );
+ });
+
+ test("doubles quotes for PowerShell instead of backslash-escaping", () => {
+ const hostile = { ...context, commonName: "app'x" };
+
+ expect(renderHostCommandContext("Write-Output {{commonName}}", hostile, toPowerShellLiteral)).toBe(
+ "Write-Output 'app''x'"
+ );
+ });
+
+ test("leaves braces that are not one of our variables exactly as written", () => {
+ expect(renderHostCommandContext("kubectl get po -o jsonpath='{{.status}}'", context, toPosixShellLiteral)).toBe(
+ "kubectl get po -o jsonpath='{{.status}}'"
+ );
+ });
+});
+
+describe("runPreflightCommand", () => {
+ test("reports success on exit code 0", async () => {
+ const result = await runPreflightCommand({
+ 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);
+ });
+
+ test("reports failure on a non-zero exit code without throwing", async () => {
+ const result = await runPreflightCommand({
+ 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);
+ });
+
+ test("reports failure when the host could not be reached at all", async () => {
+ const result = await runPreflightCommand({
+ syncId: "sync-1",
+ execute: async () => {
+ throw new Error("gateway unreachable");
+ }
+ });
+
+ expect(result.status).toBe(PkiSyncStatus.Failed);
+ expect(result.exitCode).toBeUndefined();
+ expect(result.error).toBe("gateway unreachable");
+ });
+
+ test("redacts the export password from captured output", async () => {
+ const result = await runPreflightCommand({
+ syncId: "sync-1",
+ secretsToRedact: ["s3cret"],
+ execute: async () => ({ stdout: "opened with s3cret", stderr: "", exitCode: 0 })
+ });
+
+ expect(result.output).toBe("opened with [REDACTED]");
+ });
+});
+
+describe("buildPreflightCommandPlan with nothing linked to the sync", () => {
+ const base = {
+ destinationDirectory: "/etc/ssl",
+ certificateMap: {} as TCertificateMap,
+ exportOptions: { format: PkiSyncExportFormat.Pem, includePrivateKey: true },
+ joinPath: (directory: string, fileName: string) => `${directory}/${fileName}`
+ };
+
+ 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();
+ });
+
+ 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" });
+ expect(plan?.command).toBe("systemctl is-active nginx");
+
+ const withDirectory = buildPreflightCommandPlan({ ...base, command: "test -w {{certificateDirectory}}" });
+ expect(withDirectory?.context.certificateDirectory).toBe("/etc/ssl");
+ });
+});
+
+describe("preflight 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 = hostCommandFailurePrefix(HostCommandKind.Preflight);
+ 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" }
+ ];
+
+ shapes.forEach((shape) => expect(buildPreflightCommandFailureMessage(shape).startsWith(prefix)).toBe(true));
+ expect("2 certificate(s) failed to sync to the destination".startsWith(prefix)).toBe(false);
+ });
+});
+
+describe("buildPreflightCommandFailureMessage", () => {
+ test("names the check, not the post-sync command", () => {
+ expect(
+ buildPreflightCommandFailureMessage({
+ status: PkiSyncStatus.Failed,
+ exitCode: 3,
+ durationMs: 12,
+ failureDetail: "nginx.service is not running"
+ })
+ ).toBe("Preflight 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({
+ status: PkiSyncStatus.Failed,
+ exitCode: 1,
+ durationMs: 12,
+ error: "Command exited with code 1"
+ })
+ ).toBe("Preflight check failed (exit 1)");
+ });
+
+ test("omits the exit code when the command never ran", () => {
+ expect(
+ buildPreflightCommandFailureMessage({
+ status: PkiSyncStatus.Failed,
+ durationMs: 10_001,
+ error: "command timed out after 10s"
+ })
+ ).toBe("Preflight check failed: command timed out after 10s");
+ });
+});
+
+describe("buildPreflightFailureSyncResult", () => {
+ const failure = {
+ status: PkiSyncStatus.Failed as const,
+ exitCode: 1,
+ durationMs: 40,
+ failureDetail: "/etc/ssl/certs is missing"
+ };
+
+ test("delivers nothing and reports every certificate as skipped with the reason", () => {
+ const result = buildPreflightFailureSyncResult(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" }
+ ]);
+ });
+
+ test("carries the check result so the queue can report and audit it", () => {
+ expect(buildPreflightFailureSyncResult(oneCertificate, failure).preflightCheck).toBe(failure);
+ });
+
+ test("a sync with nothing linked still reports the failure", () => {
+ const result = buildPreflightFailureSyncResult({}, failure);
+
+ expect(result.skipped).toBe(0);
+ expect(result.details?.skippedCertificates).toEqual([]);
+ expect(result.preflightCheck).toBe(failure);
+ });
+});
+
+describe("normalizeNewPreflightCommand", () => {
+ test("keeps a real command", () => {
+ expect(normalizeNewPreflightCommand({ preflightCommand: "systemctl is-active nginx" })).toEqual({
+ preflightCommand: "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 });
+ });
+});
+
+describe("applyPreflightCommandUpdate", () => {
+ const stored = "systemctl is-active nginx";
+
+ test("an omitted key preserves the stored command", () => {
+ expect(applyPreflightCommandUpdate({ exportFormat: "pem" }, stored)).toEqual({
+ exportFormat: "pem",
+ preflightCommand: stored
+ });
+ });
+
+ test("an explicit null or a blank string clears the stored command", () => {
+ expect(applyPreflightCommandUpdate({ preflightCommand: null }, stored)).toEqual({});
+ expect(applyPreflightCommandUpdate({ preflightCommand: "" }, stored)).toEqual({});
+ });
+
+ test("a new command replaces the stored one", () => {
+ expect(applyPreflightCommandUpdate({ preflightCommand: "test -w /srv/tls" }, stored)).toEqual({
+ preflightCommand: "test -w /srv/tls"
+ });
+ });
+
+ test("does not mutate the object it was given", () => {
+ const input = { preflightCommand: "" };
+ applyPreflightCommandUpdate(input, stored);
+ expect(input).toEqual({ preflightCommand: "" });
+ });
+});
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.ts
new file mode 100644
index 0000000000..78442b91c3
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-preflight-command-fns.ts
@@ -0,0 +1,123 @@
+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 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.ts
new file mode 100644
index 0000000000..23f53d028e
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-preflight-queue.ts
@@ -0,0 +1,295 @@
+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 { PkiSyncFns, truncateSyncMessage } from "./pki-sync-fns";
+import { commandNeedsCertificateData, hostCommandFailurePrefix, HostCommandKind } from "./pki-sync-host-command-fns";
+import {
+ buildPreflightCommandFailureMessage,
+ didPreflightCheckFail,
+ getPreflightCommand,
+ 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_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" | "getItem">;
+ 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) => {
+ const failurePrefix = hostCommandFailurePrefix(HostCommandKind.Preflight);
+
+ if (!didPreflightCheckFail(result)) {
+ const cleared = await pkiSyncDAL.clearReportedPreflightFailure(pkiSync.id, failurePrefix);
+ 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(buildPreflightCommandFailureMessage(result)),
+ failurePrefix
+ );
+ 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) {
+ logger.info(
+ `cron[${CronJobName.PkiSyncPreflightCheck}]: connection still busy after waiting, deferring to the next run [syncId=${syncId}] [connectionId=${pkiSync.connectionId}]`
+ );
+ return;
+ }
+
+ let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | null = null;
+ let result;
+ try {
+ const syncJobsInFlight = Number.parseInt(
+ (await keyStore.getItem(KeyStorePrefixes.AppConnectionConcurrentJobs(pkiSync.connectionId))) || "0",
+ 10
+ );
+ if (syncJobsInFlight > 0) {
+ logger.info(
+ `cron[${CronJobName.PkiSyncPreflightCheck}]: connection is busy syncing, skipping [syncId=${syncId}] [inFlight=${syncJobsInFlight}]`
+ );
+ return;
+ }
+
+ 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([lock?.release(), connectionLock.release()]);
+ }
+
+ await auditLogService.createAuditLog({
+ projectId: pkiSync.projectId,
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ event: {
+ type: EventType.PKI_SYNC_PREFLIGHT_CHECK,
+ metadata: { syncId, 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.ts
index aa43a1384f..6f4b67b1df 100644
--- a/backend/src/services/pki-sync/pki-sync-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-queue.ts
@@ -1,11 +1,8 @@
/* eslint-disable no-await-in-loop */
-import * as x509 from "@peculiar/x509";
import { AxiosError } from "axios";
import { Job } from "bullmq";
import { randomUUID } from "crypto";
-import RE2 from "re2";
-import { TCertificates } from "@app/db/schemas";
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
@@ -15,40 +12,43 @@ import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger";
import { highCardinalityMeter } 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 { TKmsServiceFactory } from "@app/services/kms/kms-service";
-// eslint-disable-next-line import/order
-import { decryptPkiSyncCredentials } from "@app/services/pki-sync/pki-sync-credentials-fns";
+import { hydratePkiSyncCredentials } from "@app/services/pki-sync/pki-sync-credentials-fns";
import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";
import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
-import { getCertificateCredentials } from "../certificate/certificate-fns";
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 { getCaCertChain } from "../certificate-authority/certificate-authority-fns";
-import { extractRootCaFromChain, removeRootCaFromChain } from "../certificate-common/certificate-utils";
import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
import { CertificateSyncStatus } from "../certificate-sync/certificate-sync-enums";
-import { compileCertificateNameSchema } from "./pki-sync-certificate-name-fns";
+import { buildCertificateMap } from "./pki-sync-certificate-map-fns";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
-import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";
+import { PkiSyncStatus } from "./pki-sync-enums";
import { PkiSyncError } from "./pki-sync-errors";
import { enterprisePkiSyncCheck, parsePkiSyncErrorMessage, PkiSyncFns, truncateSyncMessage } from "./pki-sync-fns";
-import { buildPostSyncCommandFailureMessage, TPostSyncCommandResult } from "./pki-sync-post-sync-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,
TPkiSyncRaw,
TPkiSyncRemoveCertificatesDTO,
TPkiSyncSyncCertificatesDTO,
- TPkiSyncWithCredentials,
TQueuePkiSyncImportCertificatesByIdDTO,
TQueuePkiSyncRemoveCertificatesByIdDTO,
TQueuePkiSyncSyncCertificatesByIdDTO
@@ -87,8 +87,6 @@ const JITTER_MS = 10 * 1000;
const REQUEUE_MS = 30 * 1000;
const REQUEUE_LIMIT = 30;
-const DASH_REGEX = new RE2("-", "g");
-const NON_ALPHANUMERIC_REGEX = new RE2("[^a-zA-Z0-9]", "g");
const CONNECTION_CONCURRENCY_LIMIT = 3;
const getRequeueDelay = (failureCount?: number) => {
@@ -172,204 +170,17 @@ export const pkiSyncQueueFactory = ({
);
};
- const $getInfisicalCertificates = async (
- pkiSync: TPkiSyncRaw | TPkiSyncWithCredentials
- ): Promise<{ certificateMap: TCertificateMap; certificateMetadata: Map<string, { id: string; name: string }> }> => {
- const { projectId, subscriberId, id: pkiSyncId } = pkiSync;
-
- const certificateMap: TCertificateMap = {};
- const certificateMetadata = new Map<string, { id: string; name: string }>();
- let certificates: Array<{ id: string; projectId: string; caCertId?: string | null }> = [];
-
- try {
- if (subscriberId) {
- const subscriberCertificates = await certificateDAL.findAllActiveCertsForSubscriber({
- subscriberId
- });
- certificates.push(...subscriberCertificates);
- }
-
- const certificateIds = await certificateSyncDAL.findCertificateIdsByPkiSyncId(pkiSyncId);
- if (certificateIds.length > 0) {
- const directCertificates = await certificateDAL.findActiveCertificatesByIds(certificateIds);
- certificates.push(...directCertificates);
- }
-
- const uniqueCertificates = certificates.filter(
- (cert, index, self) => self.findIndex((c) => c.id === cert.id) === index
- );
-
- const activeCertificates = uniqueCertificates.filter((cert) => {
- const typedCert = cert as TCertificates;
- return !typedCert.renewedByCertificateId;
- });
-
- if (activeCertificates.length === 0) {
- return { certificateMap, certificateMetadata };
- }
-
- certificates = activeCertificates;
-
- for (const certificate of certificates) {
- const cert = certificate as TCertificates;
- try {
- // Get the certificate body and decrypt the certificate data
- const certBody = await certificateBodyDAL.findOne({ certId: certificate.id });
-
- if (certBody) {
- const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
- projectId: certificate.projectId,
- projectDAL,
- kmsService
- });
-
- const kmsDecryptor = await kmsService.decryptWithKmsKey({
- kmsId: certificateManagerKeyId
- });
-
- const decryptedCert = await kmsDecryptor({
- cipherTextBlob: certBody.encryptedCertificate
- });
-
- const certObj = new x509.X509Certificate(decryptedCert);
- const certificatePem = certObj.toString("pem");
-
- // Get private key using getCertificateCredentials - handle cases where private key doesn't exist
- let certPrivateKey: string | undefined;
- try {
- const credentials = await getCertificateCredentials({
- certId: certificate.id,
- projectId: certificate.projectId,
- certificateSecretDAL,
- projectDAL,
- kmsService
- });
- certPrivateKey = credentials.certPrivateKey;
- } catch (credError) {
- logger.warn(
- { certificateId: certificate.id, subscriberId, error: credError },
- "Certificate private key not found - certificate may be imported or key was not stored"
- );
- // Continue without private key - some providers may only need the certificate
- certPrivateKey = undefined;
- }
-
- let certificateChain: string | undefined;
- let caCertificate: string | undefined;
- try {
- if (certBody.encryptedCertificateChain) {
- const decryptedCertChain = await kmsDecryptor({
- cipherTextBlob: certBody.encryptedCertificateChain
- });
- certificateChain = decryptedCertChain.toString();
- }
- if (certificate.caCertId) {
- const { caCert, caCertChain } = await getCaCertChain({
- caCertId: certificate.caCertId,
- certificateAuthorityDAL,
- certificateAuthorityCertDAL,
- projectDAL,
- kmsService
- });
- if (!certBody.encryptedCertificateChain) {
- certificateChain = `${caCert}\n${caCertChain}`.trim();
- }
- caCertificate = certificateChain ? extractRootCaFromChain(certificateChain) : caCert;
- }
- } catch (chainError) {
- logger.warn(
- { certificateId: certificate.id, subscriberId, error: chainError },
- "Certificate chain not found or could not be decrypted - certificate may be imported or chain was not stored"
- );
- // Continue without certificate chain
- certificateChain = undefined;
- caCertificate = undefined;
- }
-
- let certificateName: string;
- const syncOptions = pkiSync.syncOptions as
- | {
- certificateNameSchema?: string;
- includeRootCa?: boolean;
- }
- | undefined;
- const certificateNameSchema = syncOptions?.certificateNameSchema;
-
- if (certificateNameSchema) {
- certificateName = compileCertificateNameSchema(
- certificateNameSchema,
- {
- certificateId: certificate.id,
- profileId: cert.profileId,
- applicationId: pkiSync.applicationId,
- applicationName: pkiSync.applicationName,
- commonName: cert.commonName
- },
- pkiSync.destination as PkiSync
- );
- } else {
- const stableId = cert.profileId
- ? `${cert.profileId.replace(DASH_REGEX, "")}-${(cert.commonName || "").replace(NON_ALPHANUMERIC_REGEX, "")}`
- : certificate.id.replace(DASH_REGEX, "");
- certificateName = `Infisical-${stableId}`;
- }
-
- const alternativeNames: string[] = [];
-
- const legacyName = `Infisical-${certificate.id.replace(DASH_REGEX, "")}`;
- if (legacyName !== certificateName) {
- alternativeNames.push(legacyName);
- }
-
- if (cert.renewedFromCertificateId) {
- const originalLegacyName = `Infisical-${cert.renewedFromCertificateId.replace(DASH_REGEX, "")}`;
- alternativeNames.push(originalLegacyName);
- }
-
- let processedCertificateChain = certificateChain;
- if (certificateChain && syncOptions?.includeRootCa === false) {
- processedCertificateChain = removeRootCaFromChain(certificateChain);
- }
-
- certificateMap[certificateName] = {
- cert: certificatePem,
- privateKey: certPrivateKey || "",
- certificateChain: processedCertificateChain,
- caCertificate,
- alternativeNames,
- certificateId: certificate.id,
- profileId: cert.profileId,
- commonName: cert.commonName
- };
-
- certificateMetadata.set(certificateName, {
- id: certificate.id,
- name: certificateName
- });
- } else {
- logger.warn({ certificateId: certificate.id, subscriberId }, "Certificate body not found for certificate");
- }
- } catch (error) {
- logger.error(
- { error, subscriberId, certificateId: certificate.id },
- "Failed to decrypt certificate for PKI sync"
- );
- // Continue with other certificates
- }
- }
- } catch (error) {
- logger.error(
- error,
- `Failed to fetch certificate for subscriber [subscriberId=${subscriberId}] [projectId=${projectId}]`
- );
- throw new PkiSyncError({
- message: `Failed to fetch certificate for PKI subscriber: ${error instanceof Error ? error.message : String(error)}`,
- shouldRetry: true
- });
- }
-
- return { certificateMap, certificateMetadata };
- };
+ const $certificatesForSync = (pkiSync: TPkiSyncRaw) =>
+ buildCertificateMap(pkiSync, {
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ certificateAuthorityDAL,
+ certificateAuthorityCertDAL,
+ certificateSyncDAL,
+ projectDAL,
+ kmsService
+ });
const queuePkiSyncSyncCertificatesById = async (payload: TQueuePkiSyncSyncCertificatesByIdDTO) =>
queueService.queue(QueueName.PkiSync, QueueJobs.PkiSyncSyncCertificates, payload, {
@@ -436,50 +247,21 @@ export const pkiSyncQueueFactory = ({
let certSyncFailureCount = 0;
let syncMessage: string | null = null;
let postSyncCommandResult: TPostSyncCommandResult | undefined;
+ let preflightCheckResult: TPreflightCommandResult | undefined;
let isFinalAttempt = job.attemptsStarted === job.opts.attempts;
- const configuredPostSyncCommand = (pkiSync.syncOptions as { postSyncCommand?: string } | undefined)
- ?.postSyncCommand;
+ const configuredPostSyncCommand = getPostSyncCommand(pkiSync.syncOptions);
+ const configuredPreflightCommand = getPreflightCommand(pkiSync.syncOptions);
try {
- const {
- connection: { id: connectionId, orgId, projectId: appConnectionProjectId }
- } = pkiSync;
-
- const appConnection = await appConnectionDAL.findById(connectionId);
- if (!appConnection) {
- throw new Error(`App connection not found: ${connectionId}`);
- }
-
- const project = appConnectionProjectId ? await projectDAL.findById(appConnectionProjectId) : null;
-
- const credentials = await decryptAppConnectionCredentials({
- orgId,
- encryptedCredentials: appConnection.encryptedCredentials,
- kmsService,
- projectId: appConnectionProjectId
+ const pkiSyncWithCredentials = await hydratePkiSyncCredentials({
+ pkiSync,
+ appConnectionDAL,
+ projectDAL,
+ kmsService
});
- const syncCredentials = pkiSync.encryptedCredentials
- ? await decryptPkiSyncCredentials({
- orgId,
- projectId: pkiSync.projectId,
- encryptedCredentials: pkiSync.encryptedCredentials,
- kmsService
- })
- : undefined;
-
- const pkiSyncWithCredentials = {
- ...pkiSync,
- connection: {
- ...pkiSync.connection,
- credentials,
- projectType: project?.type
- },
- syncCredentials
- } as TPkiSyncWithCredentials;
-
- const { certificateMap, certificateMetadata } = await $getInfisicalCertificates(pkiSync);
+ const { certificateMap, certificateMetadata } = await $certificatesForSync(pkiSync);
const statusUpdates = Array.from(certificateMetadata.entries()).map(([, metadata]) => ({
pkiSyncId: pkiSync.id,
@@ -623,12 +405,19 @@ export const pkiSyncQueueFactory = ({
}
postSyncCommandResult = syncResult.postSyncCommand;
- const reasons = [
- certSyncFailureCount > 0 ? `${certSyncFailureCount} certificate(s) failed to sync to the destination` : null,
- postSyncCommandResult?.status === PkiSyncStatus.Failed
- ? buildPostSyncCommandFailureMessage(postSyncCommandResult)
- : null
- ].filter(Boolean);
+ preflightCheckResult = syncResult.preflightCheck;
+
+ const reasons =
+ preflightCheckResult && didPreflightCheckFail(preflightCheckResult)
+ ? [buildPreflightCommandFailureMessage(preflightCheckResult)]
+ : [
+ certSyncFailureCount > 0
+ ? `${certSyncFailureCount} certificate(s) failed to sync to the destination`
+ : null,
+ postSyncCommandResult?.status === PkiSyncStatus.Failed
+ ? buildPostSyncCommandFailureMessage(postSyncCommandResult)
+ : null
+ ].filter(Boolean);
if (reasons.length > 0) {
syncMessage = truncateSyncMessage(reasons.join(". "));
@@ -663,7 +452,11 @@ export const pkiSyncQueueFactory = ({
} finally {
const ranAt = new Date();
const postSyncCommandFailed = postSyncCommandResult?.status === PkiSyncStatus.Failed;
- const fullySynced = isSynced && certSyncFailureCount === 0 && !postSyncCommandFailed;
+ const fullySynced =
+ isSynced &&
+ certSyncFailureCount === 0 &&
+ !postSyncCommandFailed &&
+ !didPreflightCheckFail(preflightCheckResult);
const syncStatus = fullySynced ? PkiSyncStatus.Succeeded : PkiSyncStatus.Failed;
await auditLogService.createAuditLog({
@@ -681,6 +474,9 @@ export const pkiSyncQueueFactory = ({
syncMessage,
jobId: job.id!,
jobRanAt: ranAt,
+ preflightCheck: configuredPreflightCommand
+ ? { command: configuredPreflightCommand, result: preflightCheckResult }
+ : undefined,
postSyncCommand: configuredPostSyncCommand
? { command: configuredPostSyncCommand, result: postSyncCommandResult }
: undefined
@@ -815,22 +611,11 @@ export const pkiSyncQueueFactory = ({
let isFinalAttempt = job.attemptsStarted === job.opts.attempts;
try {
- const {
- connection: { id: connectionId, orgId, projectId: appConnectionProjectId }
- } = pkiSync;
-
- const appConnection = await appConnectionDAL.findById(connectionId);
- if (!appConnection) {
- throw new Error(`App connection not found: ${connectionId}`);
- }
-
- const removeProject = appConnectionProjectId ? await projectDAL.findById(appConnectionProjectId) : null;
-
- const credentials = await decryptAppConnectionCredentials({
- orgId,
- encryptedCredentials: appConnection.encryptedCredentials,
- kmsService,
- projectId: appConnectionProjectId
+ const pkiSyncWithCredentials = await hydratePkiSyncCredentials({
+ pkiSync,
+ appConnectionDAL,
+ projectDAL,
+ kmsService
});
const certificateMap: TCertificateMap = certificateIdsToRemove?.length
@@ -840,28 +625,17 @@ export const pkiSyncQueueFactory = ({
{ cert: "", privateKey: "", certificateId: certId }
])
)
- : (await $getInfisicalCertificates(pkiSync)).certificateMap;
+ : (await $certificatesForSync(pkiSync)).certificateMap;
- await PkiSyncFns.removeCertificates(
- {
- ...pkiSync,
- connection: {
- ...pkiSync.connection,
- credentials,
- projectType: removeProject?.type
- }
- } as TPkiSyncWithCredentials,
- Object.keys(certificateMap),
- {
- appConnectionDAL,
- kmsService,
- certificateSyncDAL,
- certificateDAL,
- certificateMap,
- gatewayV2Service,
- gatewayPoolService
- }
- );
+ await PkiSyncFns.removeCertificates(pkiSyncWithCredentials, Object.keys(certificateMap), {
+ appConnectionDAL,
+ kmsService,
+ certificateSyncDAL,
+ certificateDAL,
+ certificateMap,
+ gatewayV2Service,
+ gatewayPoolService
+ });
isSuccess = true;
} catch (err) {
diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.ts
index 65404893c6..a7f9f9dbb9 100644
--- a/backend/src/services/pki-sync/pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts
@@ -3,12 +3,12 @@ import { z } from "zod";
import { buildCertificateNameSchemaTestName } from "./pki-sync-certificate-name-fns";
import { PkiSync } from "./pki-sync-enums";
-import { POST_SYNC_COMMAND_MAX_LENGTH } from "./pki-sync-post-sync-command-fns";
+import { HOST_COMMAND_MAX_LENGTH } from "./pki-sync-host-command-fns";
-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`)
.nullable()
.optional();
@@ -18,7 +18,8 @@ export const BasePkiSyncOptionsSchema = z.object({
canRemoveCertificates: z.boolean().default(true),
includeRootCa: z.boolean().default(false),
preserveItemOnRenewal: z.boolean().default(true),
- postSyncCommand: PostSyncCommandSchema
+ preflightCommand: HostCommandSchema,
+ postSyncCommand: HostCommandSchema
});
// Builds a destination's certificateNameSchema validator. The compiled name must match the
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index a57f5954ad..969f8405e8 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -31,13 +31,24 @@ import {
getPkiSyncProviderCapabilities,
listPkiSyncOptions
} from "./pki-sync-fns";
+import {
+ findSingleCertificateHostCommandVariables,
+ formatHostCommandVariables,
+ HostCommandKind
+} from "./pki-sync-host-command-fns";
import { PKI_SYNC_CONNECTION_MAP, PKI_SYNC_NAME_MAP } from "./pki-sync-maps";
import {
applyPostSyncCommandUpdate,
- findSingleCertificatePostSyncCommandVariables,
- formatPostSyncCommandVariables,
- normalizeNewPostSyncCommand
+ getPostSyncCommand,
+ 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,
@@ -129,29 +140,39 @@ export const pkiSyncServiceFactory = ({
return permission.can(action, ResourcePermissionSub.PkiSyncs);
};
- /**
- * Rejects a command the sync could never run: a destination with no shell to open, or a connection
- * with no gateway to run it through. Checked at write time so the operator finds out while
- * configuring rather than on the next sync.
- */
- const $assertPostSyncCommandIsSupported = (
+ const $assertHostCommandsAreSupported = (
destination: PkiSync,
syncOptions: Record<string, unknown> | undefined,
connection: { gatewayId?: string | null; gatewayPoolId?: string | null } | undefined
) => {
- if (!syncOptions?.postSyncCommand) return;
-
- if (!getPkiSyncProviderCapabilities(destination).canRunPostSyncCommand) {
- throw new BadRequestError({
- message: `A post-sync command cannot be set for ${PKI_SYNC_NAME_MAP[destination]} PKI sync destination`
- });
- }
+ const capabilities = getPkiSyncProviderCapabilities(destination);
+ const hasGateway = Boolean(connection?.gatewayId || connection?.gatewayPoolId);
+
+ const configuredCommands = [
+ {
+ kind: HostCommandKind.Preflight,
+ command: syncOptions?.[PREFLIGHT_COMMAND_OPTION_KEY],
+ isSupportedByDestination: capabilities.canRunPreflightCommand
+ },
+ {
+ kind: HostCommandKind.PostSync,
+ command: syncOptions?.[POST_SYNC_COMMAND_OPTION_KEY],
+ isSupportedByDestination: capabilities.canRunPostSyncCommand
+ }
+ ].filter(({ command }) => Boolean(command));
- if (connection?.gatewayId || connection?.gatewayPoolId) return;
+ configuredCommands.forEach(({ kind, isSupportedByDestination }) => {
+ if (!isSupportedByDestination) {
+ throw new BadRequestError({
+ message: `A ${kind} cannot be set for ${PKI_SYNC_NAME_MAP[destination]} PKI sync destination`
+ });
+ }
- throw new BadRequestError({
- message:
- "A post-sync command runs through a gateway. Configure the sync's App Connection to use a gateway, or clear the command."
+ if (!hasGateway) {
+ throw new BadRequestError({
+ message: `A ${kind} runs through a gateway. Configure the sync's App Connection to use a gateway, or clear the command.`
+ });
+ }
});
};
@@ -189,7 +210,8 @@ export const pkiSyncServiceFactory = ({
return permission;
};
- const $assertMaySetPostSyncCommand = async (
+ const $assertMaySetHostCommand = async (
+ actions: { project: ProjectPermissionPkiSyncActions; resource: ResourcePermissionPkiSyncActions },
nextCommand: unknown,
currentCommand: unknown,
pkiSync: { projectId: string; applicationId?: string | null; name: string },
@@ -199,13 +221,48 @@ export const pkiSyncServiceFactory = ({
if (nextCommand === currentCommand) return;
if (!nextCommand && !currentCommand) return;
- await $assertSyncAction(
- ProjectPermissionPkiSyncActions.SetPostSyncCommand,
- ResourcePermissionPkiSyncActions.SetPostSyncCommand,
- pkiSync,
- subscriberName,
- actor
+ await $assertSyncAction(actions.project, actions.resource, pkiSync, subscriberName, actor);
+ };
+
+ const HOST_COMMAND_ACTIONS = {
+ [PREFLIGHT_COMMAND_OPTION_KEY]: {
+ project: ProjectPermissionPkiSyncActions.SetPreflightCommand,
+ resource: ResourcePermissionPkiSyncActions.SetPreflightCommand
+ },
+ [POST_SYNC_COMMAND_OPTION_KEY]: {
+ project: ProjectPermissionPkiSyncActions.SetPostSyncCommand,
+ resource: ResourcePermissionPkiSyncActions.SetPostSyncCommand
+ }
+ } as const;
+
+ const $assertHostCommandWrite = async (args: {
+ destination: PkiSync;
+ nextSyncOptions: Record<string, unknown> | undefined;
+ storedSyncOptions: Record<string, unknown> | undefined;
+ pkiSync: { projectId: string; applicationId?: string | null; name: string };
+ subscriberName: string | undefined;
+ actor: OrgServiceActor;
+ resolveConnection: () => Promise<{ gatewayId?: string | null; gatewayPoolId?: string | null } | undefined>;
+ }) => {
+ const { destination, nextSyncOptions, storedSyncOptions, pkiSync, subscriberName, actor, resolveConnection } = args;
+
+ await Promise.all(
+ Object.entries(HOST_COMMAND_ACTIONS).map(([optionKey, actions]) =>
+ $assertMaySetHostCommand(
+ actions,
+ nextSyncOptions?.[optionKey],
+ storedSyncOptions?.[optionKey],
+ pkiSync,
+ subscriberName,
+ actor
+ )
+ )
);
+
+ const hasCommand = Object.keys(HOST_COMMAND_ACTIONS).some((optionKey) => nextSyncOptions?.[optionKey]);
+ if (!hasCommand) return;
+
+ $assertHostCommandsAreSupported(destination, nextSyncOptions, await resolveConnection());
};
const validateCertificatesForSync = async (
@@ -280,16 +337,20 @@ export const pkiSyncServiceFactory = ({
});
}
- const singleCertificateVariables = findSingleCertificatePostSyncCommandVariables(
- syncOptions?.postSyncCommand as string | undefined
- );
- if (singleCertificateVariables.length > 0) {
- throw new BadRequestError({
- message: `This sync's post-sync command uses ${formatPostSyncCommandVariables(
- singleCertificateVariables
- )}. A variable that names one certificate can only be used on a sync with a single certificate linked. Use {{certificateFiles}} or {{certificateDirectory}} to write a command that covers every certificate in the run.`
- });
- }
+ [
+ { kind: HostCommandKind.Preflight, command: getPreflightCommand(syncOptions) },
+ { kind: HostCommandKind.PostSync, command: getPostSyncCommand(syncOptions) }
+ ].forEach(({ kind, command }) => {
+ const singleCertificateVariables = findSingleCertificateHostCommandVariables(command);
+
+ if (singleCertificateVariables.length > 0) {
+ throw new BadRequestError({
+ message: `This sync's ${kind} uses ${formatHostCommandVariables(
+ singleCertificateVariables
+ )}. A variable that names one certificate can only be used on a sync with a single certificate linked. Use {{certificateFiles}} or {{certificateDirectory}} to write a command that covers every certificate in the run.`
+ });
+ }
+ });
};
const createPkiSync = async (
@@ -343,19 +404,22 @@ export const pkiSyncServiceFactory = ({
const connection = await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);
const providerCapabilities = getPkiSyncProviderCapabilities(destination);
- const resolvedSyncOptions = normalizeNewPostSyncCommand({
- ...providerCapabilities,
- ...syncOptions
- });
-
- await $assertMaySetPostSyncCommand(
- syncOptions?.postSyncCommand,
- undefined,
- { projectId, applicationId, name },
- undefined,
- actor
+ const resolvedSyncOptions = normalizeNewPreflightCommand(
+ normalizeNewPostSyncCommand({
+ ...providerCapabilities,
+ ...syncOptions
+ })
);
- $assertPostSyncCommandIsSupported(destination, resolvedSyncOptions, connection);
+
+ await $assertHostCommandWrite({
+ destination,
+ nextSyncOptions: resolvedSyncOptions,
+ storedSyncOptions: undefined,
+ pkiSync: { projectId, applicationId, name },
+ subscriberName: undefined,
+ actor,
+ resolveConnection: async () => connection
+ });
if (certificateIds.length > 0) {
assertWithinCertificateLimit(destination, certificateIds.length);
@@ -482,6 +546,7 @@ export const pkiSyncServiceFactory = ({
effectiveConnection = await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);
}
+ const storedSyncOptions = pkiSync.syncOptions as Record<string, unknown> | undefined;
let resolvedSyncOptions = syncOptions;
if (syncOptions) {
const providerCapabilities = getPkiSyncProviderCapabilities(pkiSync.destination);
@@ -498,34 +563,29 @@ export const pkiSyncServiceFactory = ({
});
}
- resolvedSyncOptions = applyPostSyncCommandUpdate(
- { ...providerCapabilities, ...syncOptions },
- (pkiSync.syncOptions as Record<string, unknown> | undefined)?.postSyncCommand
+ resolvedSyncOptions = applyPreflightCommandUpdate(
+ applyPostSyncCommandUpdate({ ...providerCapabilities, ...syncOptions }, storedSyncOptions?.postSyncCommand),
+ storedSyncOptions?.preflightCommand
);
}
const effectiveSyncOptions = (resolvedSyncOptions ?? pkiSync.syncOptions) as Record<string, unknown> | undefined;
- await $assertMaySetPostSyncCommand(
- effectiveSyncOptions?.postSyncCommand,
- (pkiSync.syncOptions as Record<string, unknown> | undefined)?.postSyncCommand,
+ await $assertHostCommandWrite({
+ destination: pkiSync.destination,
+ nextSyncOptions: effectiveSyncOptions,
+ storedSyncOptions,
pkiSync,
- currentSubscriber?.name,
- actor
- );
-
- if (effectiveSyncOptions?.postSyncCommand) {
- $assertPostSyncCommandIsSupported(
- pkiSync.destination,
- effectiveSyncOptions,
+ subscriberName: currentSubscriber?.name,
+ actor,
+ resolveConnection: async () =>
effectiveConnection ??
- (await appConnectionService.connectAppConnectionById(
- getDestinationAppType(pkiSync.destination),
- pkiSync.connectionId,
- actor
- ))
- );
- }
+ appConnectionService.connectAppConnectionById(
+ getDestinationAppType(pkiSync.destination),
+ pkiSync.connectionId,
+ actor
+ )
+ });
if (certificateIds !== undefined) {
if (certificateIds.length > 0) {
diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.ts
index f6615509e4..3d906dec77 100644
--- a/backend/src/services/pki-sync/pki-sync-types.ts
+++ b/backend/src/services/pki-sync/pki-sync-types.ts
@@ -8,7 +8,7 @@ import { ResourceMetadataDTO } from "@app/services/resource-metadata/resource-me
import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { PkiSync } from "./pki-sync-enums";
-import { TPostSyncCommandResult } from "./pki-sync-post-sync-command-fns";
+import { THostCommandResult } from "./pki-sync-host-command-fns";
export type TPkiSync = {
id: string;
@@ -99,7 +99,8 @@ export type TPkiSyncSyncResult = {
removed?: number;
failedRemovals?: number;
skipped: number;
- postSyncCommand?: TPostSyncCommandResult;
+ preflightCheck?: THostCommandResult;
+ postSyncCommand?: THostCommandResult;
details?: {
failedUploads?: Array<{ name: string; error: string }>;
failedRemovals?: Array<{ name: string; error: string }>;
@@ -247,6 +248,10 @@ export type TQueuePkiSyncImportCertificatesByIdDTO = {
auditLogInfo?: AuditLogInfo;
};
+export type TQueuePkiSyncRunPreflightCheckByIdDTO = {
+ syncId: string;
+};
+
export type TQueuePkiSyncRemoveCertificatesByIdDTO = {
syncId: string;
auditLogInfo?: AuditLogInfo;
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.ts
index 2562e390aa..3f0ca9bfb6 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,6 +23,7 @@ export const WINDOWS_SERVER_PKI_SYNC_LIST_OPTION = {
canImportCertificates: false,
canRemoveCertificates: true,
canRunPostSyncCommand: true,
+ canRunPreflightCommand: 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.ts
index 0112835984..20c28e47bc 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
@@ -11,13 +11,22 @@ import { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-s
import { exportCertificateForSync, PemCertificateExtension, PkiSyncExportFormat } from "../pki-sync-export-fns";
import {
- buildPostSyncCommandPlan,
- POST_SYNC_COMMAND_TIMEOUT_MS,
- renderPostSyncCommand,
- runPostSyncCommand,
- toPowerShellLiteral,
- TPostSyncCommandPlan
-} from "../pki-sync-post-sync-command-fns";
+ HOST_COMMAND_TIMEOUT_MS,
+ HostCommandKind,
+ renderHostCommandContext,
+ THostCommandContext,
+ THostCommandExecutionResult,
+ 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 { TWindowsServerPkiSyncConfig } from "./windows-server-pki-sync-types";
@@ -38,9 +47,17 @@ type TWindowsServerSyncOptions = {
includePrivateKey?: boolean;
canRemoveCertificates?: boolean;
fileAccessRules?: Array<{ identity: string; access: string }>;
+ preflightCommand?: string;
postSyncCommand?: string;
};
+const resolveWindowsExportOptions = (options: TWindowsServerSyncOptions) => ({
+ format: options.exportFormat ?? PkiSyncExportFormat.Pkcs12,
+ includePrivateKey: options.includePrivateKey ?? true,
+ pemCertificateExtension: options.pemCertificateExtension,
+ combineCertificateChain: options.combineCertificateChain
+});
+
const TRAILING_BACKSLASH = new RE2("\\\\+$");
const joinWindowsPath = (dir: string, name: string): string => `${dir.replace(TRAILING_BACKSLASH, "")}\\${name}`;
@@ -120,6 +137,59 @@ const reconcileWindowsServerRemovals = async (args: {
return { removed, failedRemovals };
};
+const executeWindowsServerHostCommand = async (
+ kind: HostCommandKind,
+ plan: { command: string; context: THostCommandContext },
+ target: ReturnType<typeof buildWinRMTarget>,
+ gatewayDeps: Parameters<typeof executeWinRMGatewayOperation>[1]
+): Promise<THostCommandExecutionResult> => {
+ const result = await executeWinRMGatewayOperation<WinRmRunCommandResult>(
+ {
+ ...target,
+ endpoint: WinRmRpcEndpoint.RunCommand,
+ params: {
+ command: renderHostCommandContext(plan.command, plan.context, toPowerShellLiteral),
+ timeoutMs: HOST_COMMAND_TIMEOUT_MS[kind]
+ }
+ },
+ gatewayDeps
+ );
+ return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };
+};
+
+const runWindowsServerPreflightCommand = ({
+ pkiSync,
+ certificateMap,
+ target,
+ gatewayDeps
+}: {
+ pkiSync: TPkiSyncWithCredentials;
+ certificateMap: TCertificateMap;
+ target: ReturnType<typeof buildWinRMTarget>;
+ gatewayDeps: Parameters<typeof executeWinRMGatewayOperation>[1];
+}): Promise<TPreflightCommandResult> | undefined => {
+ const options = (pkiSync.syncOptions ?? {}) as TWindowsServerSyncOptions;
+ const config = pkiSync.destinationConfig as TWindowsServerPkiSyncConfig;
+ const exportOptions = resolveWindowsExportOptions(options);
+
+ const plan = buildPreflightCommandPlan({
+ command: options.preflightCommand,
+ destinationDirectory: config.destinationPath,
+ certificateMap,
+ exportOptions,
+ joinPath: joinWindowsPath,
+ pkcs12Password:
+ exportOptions.format === PkiSyncExportFormat.Pkcs12 ? pkiSync.syncCredentials?.exportPassword : undefined
+ });
+ if (!plan) return undefined;
+
+ return runPreflightCommand({
+ syncId: pkiSync.id,
+ secretsToRedact: [plan.context.pkcs12Password],
+ execute: () => executeWindowsServerHostCommand(HostCommandKind.Preflight, plan, target, gatewayDeps)
+ });
+};
+
const runWindowsServerPostSyncCommand = ({
syncId,
plan,
@@ -134,20 +204,7 @@ const runWindowsServerPostSyncCommand = ({
runPostSyncCommand({
syncId,
secretsToRedact: [plan.context.pkcs12Password],
- execute: async () => {
- const result = await executeWinRMGatewayOperation<WinRmRunCommandResult>(
- {
- ...target,
- endpoint: WinRmRpcEndpoint.RunCommand,
- params: {
- command: renderPostSyncCommand(plan.command, plan.context, toPowerShellLiteral),
- timeoutMs: POST_SYNC_COMMAND_TIMEOUT_MS
- }
- },
- gatewayDeps
- );
- return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };
- }
+ execute: () => executeWindowsServerHostCommand(HostCommandKind.PostSync, plan, target, gatewayDeps)
});
export const windowsServerPkiSyncFactory = ({
@@ -163,8 +220,8 @@ export const windowsServerPkiSyncFactory = ({
): Promise<TPkiSyncSyncResult> => {
const config = pkiSync.destinationConfig as TWindowsServerPkiSyncConfig;
const options = (pkiSync.syncOptions ?? {}) as TWindowsServerSyncOptions;
- const format = options.exportFormat ?? PkiSyncExportFormat.Pkcs12;
- const includePrivateKey = options.includePrivateKey ?? true;
+ const exportOptions = resolveWindowsExportOptions(options);
+ const { format, includePrivateKey } = exportOptions;
const canRemoveCertificates = options.canRemoveCertificates ?? false;
const exportPassword = pkiSync.syncCredentials?.exportPassword;
@@ -174,11 +231,19 @@ export const windowsServerPkiSyncFactory = ({
// Paths confirmed on the host this run. Keeps the removal pass from deleting a file a renewal
// just rewrote under the same name, and tells the post-sync command what landed.
const deliveredPaths = new Set<string>();
- const deliveredCertificates: Array<{ path: string; commonName?: string }> = [];
+ const deliveredCertificates: Array<{ paths: string[]; commonName?: string }> = [];
const target = buildWinRMTarget(pkiSync);
let uploaded = 0;
let removed = 0;
+ const preflightCheck = await runWindowsServerPreflightCommand({ pkiSync, certificateMap, target, gatewayDeps });
+ if (preflightCheck && didPreflightCheckFail(preflightCheck)) {
+ logger.info(
+ `Windows Server PKI sync [syncId=${pkiSync.id}]: preflight check failed, delivered nothing (${buildPreflightCommandFailureMessage(preflightCheck)})`
+ );
+ return buildPreflightFailureSyncResult(certificateMap, preflightCheck);
+ }
+
// Deliver each certificate over its own gateway operation so one certificate's failure is
// recorded against that certificate only, rather than failing the whole batch.
for (const [baseName, certData] of Object.entries(certificateMap)) {
@@ -203,15 +268,12 @@ export const windowsServerPkiSyncFactory = ({
try {
const exported = await exportCertificateForSync({
- format,
+ ...exportOptions,
certificate: cert,
certificateChain,
privateKey,
- includePrivateKey,
password: exportPassword,
- alias: baseName,
- pemCertificateExtension: options.pemCertificateExtension,
- combineCertificateChain: options.combineCertificateChain
+ alias: baseName
});
const paths: string[] = [];
@@ -232,7 +294,7 @@ export const windowsServerPkiSyncFactory = ({
);
paths.forEach((deliveredPath) => deliveredPaths.add(deliveredPath));
- deliveredCertificates.push({ path: paths[0], commonName: certData.commonName ?? undefined });
+ deliveredCertificates.push({ paths, commonName: certData.commonName ?? undefined });
if (typeof certificateId === "string") {
let record = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);
if (!record) {
@@ -292,6 +354,7 @@ export const windowsServerPkiSyncFactory = ({
removed: removed > 0 ? removed : undefined,
failedRemovals: failedRemovals.length > 0 ? failedRemovals.length : undefined,
skipped: skippedCertificates.length,
+ preflightCheck,
postSyncCommand,
details: {
failedUploads: failedUploads.length > 0 ? failedUploads : undefined,
@@ -344,5 +407,13 @@ export const windowsServerPkiSyncFactory = ({
}
};
- return { syncCertificates, removeCertificates };
+ const runPreflightCheck = (pkiSync: TPkiSyncWithCredentials, certificateMap: TCertificateMap) =>
+ runWindowsServerPreflightCommand({
+ pkiSync,
+ certificateMap,
+ target: buildWinRMTarget(pkiSync),
+ gatewayDeps
+ });
+
+ return { syncCertificates, removeCertificates, runPreflightCheck };
};
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.ts
index ec5a0af1b4..3004fb0796 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
@@ -6,7 +6,7 @@ import { pkiDescriptionSchema } from "@app/services/certificate-common/certifica
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
import { PemCertificateExtension, PkiSyncExportFormat } from "@app/services/pki-sync/pki-sync-export-fns";
-import { PkiSyncSchema, PostSyncCommandSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
import { WINDOWS_SERVER_NAMING } from "./windows-server-pki-sync-constants";
@@ -76,7 +76,8 @@ export const WindowsServerPkiSyncOptionsSchema = z.object({
)
.max(20)
.optional(),
- postSyncCommand: PostSyncCommandSchema,
+ preflightCommand: HostCommandSchema,
+ postSyncCommand: HostCommandSchema,
certificateNameSchema: z
.string()
.trim()
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
index a6517811e8..e102205ae7 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
@@ -6,6 +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";
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.
@@ -18,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 [post-sync command](#post-sync-commands), because the Gateway is what executes it. It must be running Infisical CLI v0.43.120 or later
+- 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
## Create a Linux Server Sync
@@ -45,8 +47,9 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi
- **Certificate Name Schema**: The base file name, using placeholders such as `{{commonName}}`, `{{certificateId}}`, or `{{shortCertificateId}}`. The export format adds the extension. A schema with no placeholder can be linked to only one certificate.
- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.
- 5. Configure the **Post-Sync Command**, or leave it empty:
- - **Command**: A command run on the server after the sync delivers a certificate, so the service that uses it picks up the new file, for example `sudo systemctl reload nginx`. [Post-Sync Commands](#post-sync-commands) covers the available variables and what happens when the command fails.
+ 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).
+ - **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**:
- **Name**: The name of your sync.
@@ -77,6 +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",
"postSyncCommand": "sudo systemctl reload nginx"
},
"destinationConfig": {
@@ -111,6 +115,75 @@ PKCS#12
When 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
+
+A 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.
+
+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. `test -w /etc/ssl/certs` and `systemctl is-active nginx` are good checks. Creating the directory or starting the service is work for the post-sync command.
+
+<Note>
+ Your [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 />
+
+### Setting a Check
+
+<Steps>
+ <Step title="Open the sync's Commands step">
+ Edit the sync and select **Commands**.
+ </Step>
+ <Step title="Write the check">
+ Anything that exits non-zero when the host is not ready works. The variables resolve to the files
+ this run is about to write, so a check can look at where a certificate is going:
+
+ ```bash
+ set -e
+ test -w {{certificateDirectory}}
+ test ! -e {{certificatePath}} || test -w {{certificatePath}}
+ systemctl is-active --quiet nginx
+ ```
+ </Step>
+ <Step title="Save and trigger a sync">
+ Save the sync, then trigger it. If the check fails, the sync fails without delivering, and the reason appears as the sync's last error.
+ </Step>
+</Steps>
+
+### Available Variables
+
+<PreflightCheckVariables />
+
+### Length Limit
+
+A check is limited to 2048 characters, counted after the variables are substituted. For anything longer, put the logic in a script on the server and call that script.
+
+### Preflight Check FAQ
+
+<AccordionGroup>
+ <Accordion title="When exactly does the check run?">
+ Before anything else in a sync run, including before Infisical opens the SFTP session it would write with. It also runs once a day on its own, whether or not a sync is due.
+ </Accordion>
+ <Accordion title="What happens when the check fails?">
+ The sync is marked failed and the reason appears as the sync's last error. Every certificate in the run is reported as skipped with that same reason, so it is clear nothing reached the host. Files already on the server from an earlier run are left exactly as they are, because the sync never wrote or deleted anything.
+ </Accordion>
+ <Accordion title="Where do I see the result of the daily check?">
+ A 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.
+ </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.
+ </Accordion>
+</AccordionGroup>
+
## Post-Sync Commands
Delivering a certificate file does not make the service use it. Nginx keeps serving the old certificate until something reloads it. A post-sync command is that last step, run for you right after the files land.
@@ -130,8 +203,8 @@ The field accepts a whole script, so several steps can run in one go: put each o
### Setting a Command
<Steps>
- <Step title="Open the sync's Post-Sync Command step">
- Edit the sync and select **Post-Sync Command**.
+ <Step title="Open the sync's Commands step">
+ Edit the sync and select **Commands**.
</Step>
<Step title="Write the command">
Use a variable wherever you need a value from the run. Typing `{{` in the command field lists the ones available for this sync, so you can pick one instead of remembering the name:
@@ -184,13 +257,13 @@ A command is limited to 2048 characters, counted after the variables are substit
### Least Privilege
-The command runs as the account the SSH Connection authenticates with, so constraining that account bounds what any command can do. A service reload does not need root. Grant the connection user a `sudoers` rule for that one command instead:
+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:
```text
svc-infisical ALL=(root) NOPASSWD: /usr/bin/systemctl reload nginx
```
-Anyone who can edit the sync can change the command, so treat edit access to these syncs as access to the target server.
+Anyone who can edit the sync can change either command, so treat edit access to these syncs as access to the target server. Setting them is a separate permission from editing the sync, so a role can be allowed to change a sync's destination and options without being allowed to change what it runs on the host.
<Warning>
The rendered command is visible in the target server's process table while it runs. This only matters if you reference `{{pkcs12Password}}`, and only to accounts that already have a shell on the server the sync writes private keys to.
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
index ff6777d096..b01910e2d9 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
@@ -6,6 +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";
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.
@@ -47,8 +49,9 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM
- **Certificate Name Schema**: The base file name, using placeholders such as `{{commonName}}`, `{{certificateId}}`, or `{{shortCertificateId}}`. The export format adds the extension. A schema with no placeholder can be linked to only one certificate.
- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.
- 5. Configure the **Post-Sync Command**, or leave it empty:
- - **Command**: A PowerShell command run on the server after the sync delivers a certificate, so the service that uses it picks up the new file, for example `Restart-Service -Name "W3SVC"`. [Post-Sync Commands](#post-sync-commands) covers the available variables and what happens when the command fails.
+ 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).
+ - **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**:
- **Name**: The name of your sync.
@@ -81,6 +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\" }",
"postSyncCommand": "Restart-Service -Name W3SVC"
},
"destinationConfig": {
@@ -119,6 +123,73 @@ When syncing certificates, Infisical asks the Gateway to open a WinRM session to
When certificate removal is enabled and a certificate is removed from the sync, revoked, or expired, Infisical deletes exactly the files it delivered for that certificate.
+## Preflight Checks
+
+A 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.
+
+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 />
+
+### Setting a Check
+
+<Steps>
+ <Step title="Open the sync's Commands step">
+ Edit the sync and select **Commands**.
+ </Step>
+ <Step title="Write the check">
+ The script runs with `$ErrorActionPreference` set to `Stop`, so a failing cmdlet is enough to mark the host not ready. Use `throw "reason"` when you want to say why:
+
+ ```powershell
+ if (-not (Test-Path {{certificateDirectory}})) { throw "destination folder is missing" }
+ if ((Get-Service W3SVC).Status -ne "Running") { throw "W3SVC is not running" }
+ ```
+ </Step>
+ <Step title="Save and trigger a sync">
+ Save the sync, then trigger it. If the check fails, the sync fails without delivering, and the reason appears as the sync's last error.
+ </Step>
+</Steps>
+
+### Available Variables
+
+<PreflightCheckVariables />
+
+### Length Limit
+
+A check is limited to 2048 characters, for the same reason a post-sync command is: Windows caps a command line at 8191 characters and the check is sent to PowerShell encoded, which expands it. For anything longer, put the logic in a script file on the server and have the check call that script.
+
+### Preflight Check FAQ
+
+<AccordionGroup>
+ <Accordion title="When exactly does the check run?">
+ Before anything else in a sync run, in its own WinRM session, before the one Infisical would deliver with. It also runs once a day on its own, whether or not a sync is due.
+ </Accordion>
+ <Accordion title="What happens when the check fails?">
+ The sync is marked failed and the reason appears as the sync's last error. Every certificate in the run is reported as skipped with that same reason, so it is clear nothing reached the host. Files already on the server from an earlier run are left exactly as they are, because the sync never wrote or deleted anything.
+ </Accordion>
+ <Accordion title="How do I make the check fail deliberately?">
+ Use `throw "reason"`, the same as in a post-sync command. Avoid `exit`: PowerShell stops the script there before it can report its result, so the check is treated as failed with a message saying the outcome could not be read rather than with your reason.
+ </Accordion>
+ <Accordion title="Where do I see the result of the daily check?">
+ A 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.
+
+ 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.
+ </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.
+ </Accordion>
+</AccordionGroup>
+
## Post-Sync Commands
Delivering a `.pfx` to `C:\certs` does not make IIS or a service use it. A post-sync command is that last step, run for you right after the files land.
@@ -138,8 +209,8 @@ Your Gateway runs the command, never Infisical. A WinRM Connection already requi
### Setting a Command
<Steps>
- <Step title="Open the sync's Post-Sync Command step">
- Edit the sync and select **Post-Sync Command**.
+ <Step title="Open the sync's Commands step">
+ Edit the sync and select **Commands**.
</Step>
<Step title="Write the command">
Use a variable wherever you need a value from the run. Typing `{{` in the command field lists the ones available for this sync, so you can pick one instead of remembering the name:
@@ -193,11 +264,11 @@ A command is limited to 2048 characters. Windows caps a command line at 8191 cha
### Least Privilege
-The command runs as the account the WinRM Connection authenticates with, so constraining that account bounds what any command can do. Restarting one service does not need an administrator. Grant the connection account start and stop rights on that single service instead of making it a local administrator.
+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.
Binding a certificate to an HTTPS port in IIS is the exception: HTTP.sys requires a local administrator and the right cannot be delegated. Because a local administrator can do anything on the host, handle that case with a dedicated, clearly labeled sync rather than raising the privileges of a sync that only needs to deliver files and restart a service. Infisical does not block an administrator credential on a standard sync, so this is a recommendation you enforce with how you configure the connection.
-Anyone who can edit the sync can change the command, so treat edit access to these syncs as access to the target server.
+Anyone who can edit the sync can change either command, so treat edit access to these syncs as access to the target server. Setting them is a separate permission from editing the sync, so a role can be allowed to change a sync's destination and options without being allowed to change what it runs on the host.
## Security
diff --git a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-flow.mdx b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-flow.mdx
new file mode 100644
index 0000000000..9fa29776d4
--- /dev/null
+++ b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-flow.mdx
@@ -0,0 +1,15 @@
+The check runs on the target server, not on Infisical, and gates everything after it:
+
+```mermaid
+sequenceDiagram
+ participant I as Infisical
+ participant G as Gateway
+ participant S as Target server
+ I->>G: Run the preflight check
+ G->>S: Execute as the connection's account
+ S-->>G: Output and outcome
+ G-->>I: Ready, or the reason it is not
+ Note over I: Not ready: the sync fails here and delivers nothing
+ I->>G: Deliver certificate files
+ G->>S: Write files
+```
diff --git a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-variables.mdx b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-variables.mdx
new file mode 100644
index 0000000000..78312e2a54
--- /dev/null
+++ b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/preflight-check-variables.mdx
@@ -0,0 +1,21 @@
+Write a variable where you want this run's value. The check runs before anything is written, so the paths describe the files the run is *about to* write rather than files already on the host.
+
+| Variable | Value |
+| --- | --- |
+| `{{certificatePath}}` | Full path of the certificate file this run will write. Single-certificate syncs only |
+| `{{certificateDirectory}}` | The destination directory |
+| `{{certificateFiles}}` | Every path this run will write, one per line |
+| `{{commonName}}` | The certificate's common name. Single-certificate syncs only |
+| `{{pkcs12Password}}` | The PKCS#12 export password, set only when the export format is PKCS#12 |
+
+Each value is inserted already quoted for the target's shell, so write `{{certificatePath}}` rather than `"{{certificatePath}}"`. A variable that has no value for the run becomes an empty string.
+
+Only the names in this table are substituted. Anything else in double braces is left in the command exactly as you wrote it, so a command that calls a tool with its own braces (helm, jq, a Go template) keeps working, and a misspelled variable reaches the server as literal text rather than silently turning into nothing.
+
+<Note>
+ `{{certificatePath}}` and `{{commonName}}` name one specific certificate, so a check that uses either can only be saved on a sync with a single certificate linked, exactly as for the [post-sync command](#post-sync-commands). To act on every certificate the run would write, use `{{certificateFiles}}`:
+
+ ```bash
+ echo {{certificateFiles}} | while read -r file; do test -w "$(dirname "$file")"; done
+ ```
+</Note>
diff --git a/frontend/src/components/pki-syncs/PkiSyncImportStatusBadge.tsx b/frontend/src/components/pki-syncs/PkiSyncImportStatusBadge.tsx
index 440aa037a3..e9ebe292e0 100644
--- a/frontend/src/components/pki-syncs/PkiSyncImportStatusBadge.tsx
+++ b/frontend/src/components/pki-syncs/PkiSyncImportStatusBadge.tsx
@@ -1,11 +1,11 @@
-import { ReactNode, useEffect, useMemo, useState } from "react";
+import { ReactNode, useEffect, useState } from "react";
import { faXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { differenceInSeconds } from "date-fns";
import { CheckIcon, DownloadIcon, LucideIcon, TriangleAlertIcon } from "lucide-react";
import { Badge, TBadgeProps, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
-import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
+import { getPkiSyncFailureMessage, PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
import { PkiSyncStatus, TPkiSync } from "@app/hooks/api/pkiSyncs";
type Props = {
@@ -26,19 +26,7 @@ export const PkiSyncImportStatusBadge = ({ pkiSync, mini }: Props) => {
}
}, [importStatus]);
- const failureMessage = useMemo(() => {
- if (importStatus === PkiSyncStatus.Failed) {
- if (lastImportMessage)
- try {
- return JSON.stringify(JSON.parse(lastImportMessage), null, 2);
- } catch {
- return lastImportMessage;
- }
-
- return "An Unknown Error Occurred.";
- }
- return null;
- }, [importStatus, lastImportMessage]);
+ const failureMessage = getPkiSyncFailureMessage(importStatus, lastImportMessage);
if (!importStatus || hide) return null;
@@ -60,19 +48,17 @@ export const PkiSyncImportStatusBadge = ({ pkiSync, mini }: Props) => {
variant = "danger";
label = "Failed to Import Certificates";
Icon = TriangleAlertIcon;
- tooltipContent = (
+ tooltipContent = failureMessage && (
<div className="flex flex-col gap-2 py-1 whitespace-normal">
- {failureMessage && (
- <div>
- <div className="mb-2 flex self-start text-red">
- <FontAwesomeIcon icon={faXmark} className="ml-1 pt-0.5 pr-1.5 text-sm" />
- <div className="text-xs">
- {mini ? "Failed to Import Certificates" : "Failure Reason"}
- </div>
+ <div>
+ <div className="mb-2 flex self-start text-red">
+ <FontAwesomeIcon icon={faXmark} className="ml-1 pt-0.5 pr-1.5 text-sm" />
+ <div className="text-xs">
+ {mini ? "Failed to Import Certificates" : "Failure Reason"}
</div>
- <div className="rounded-sm bg-mineshaft-600 p-2 text-xs">{failureMessage}</div>
</div>
- )}
+ <div className="rounded-sm bg-mineshaft-600 p-2 text-xs">{failureMessage}</div>
+ </div>
</div>
);
@@ -88,6 +74,17 @@ export const PkiSyncImportStatusBadge = ({ pkiSync, mini }: Props) => {
Icon = CheckIcon;
}
+ if (!tooltipContent) {
+ return (
+ <span className="inline-block">
+ <Badge isSquare={mini} variant={variant}>
+ <Icon />
+ {!mini && label}
+ </Badge>
+ </span>
+ );
+ }
+
return (
<Tooltip>
<TooltipTrigger asChild>
diff --git a/frontend/src/components/pki-syncs/PkiSyncRemoveStatusBadge.tsx b/frontend/src/components/pki-syncs/PkiSyncRemoveStatusBadge.tsx
index 2156acbc39..5ecb13bbb0 100644
--- a/frontend/src/components/pki-syncs/PkiSyncRemoveStatusBadge.tsx
+++ b/frontend/src/components/pki-syncs/PkiSyncRemoveStatusBadge.tsx
@@ -1,11 +1,11 @@
-import { ReactNode, useEffect, useMemo, useState } from "react";
+import { ReactNode, useEffect, useState } from "react";
import { faXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { differenceInSeconds } from "date-fns";
import { AlertTriangleIcon, CheckIcon, EraserIcon, LucideIcon } from "lucide-react";
import { Badge, TBadgeProps, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
-import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
+import { getPkiSyncFailureMessage, PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
import { PkiSyncStatus, TPkiSync } from "@app/hooks/api/pkiSyncs";
type Props = {
@@ -26,19 +26,7 @@ export const PkiSyncRemoveStatusBadge = ({ pkiSync, mini }: Props) => {
}
}, [removeStatus]);
- const failureMessage = useMemo(() => {
- if (removeStatus === PkiSyncStatus.Failed) {
- if (lastRemoveMessage)
- try {
- return JSON.stringify(JSON.parse(lastRemoveMessage), null, 2);
- } catch {
- return lastRemoveMessage;
- }
-
- return "An Unknown Error Occurred.";
- }
- return null;
- }, [removeStatus, lastRemoveMessage]);
+ const failureMessage = getPkiSyncFailureMessage(removeStatus, lastRemoveMessage);
if (!removeStatus || hide) return null;
@@ -60,19 +48,17 @@ export const PkiSyncRemoveStatusBadge = ({ pkiSync, mini }: Props) => {
variant = "danger";
label = "Failed to Remove Certificates";
Icon = AlertTriangleIcon;
- tooltipContent = (
+ tooltipContent = failureMessage && (
<div className="flex flex-col gap-2 py-1 whitespace-normal">
- {failureMessage && (
- <div>
- <div className="mb-2 flex self-start text-red">
- <FontAwesomeIcon icon={faXmark} className="ml-1 pt-0.5 pr-1.5 text-sm" />
- <div className="text-xs">
- {mini ? "Failed to Remove Certificates" : "Failure Reason"}
- </div>
+ <div>
+ <div className="mb-2 flex self-start text-red">
+ <FontAwesomeIcon icon={faXmark} className="ml-1 pt-0.5 pr-1.5 text-sm" />
+ <div className="text-xs">
+ {mini ? "Failed to Remove Certificates" : "Failure Reason"}
</div>
- <div className="rounded-sm bg-mineshaft-600 p-2 text-xs">{failureMessage}</div>
</div>
- )}
+ <div className="rounded-sm bg-mineshaft-600 p-2 text-xs">{failureMessage}</div>
+ </div>
</div>
);
@@ -88,6 +74,17 @@ export const PkiSyncRemoveStatusBadge = ({ pkiSync, mini }: Props) => {
Icon = CheckIcon;
}
+ if (!tooltipContent) {
+ return (
+ <span className="inline-block">
+ <Badge isSquare={mini} variant={variant}>
+ <Icon />
+ {!mini && label}
+ </Badge>
+ </span>
+ );
+ }
+
return (
<Tooltip>
<TooltipTrigger asChild>
diff --git a/frontend/src/components/pki-syncs/PkiSyncStatusBadge.tsx b/frontend/src/components/pki-syncs/PkiSyncStatusBadge.tsx
index 0b91980b9c..e7272b882a 100644
--- a/frontend/src/components/pki-syncs/PkiSyncStatusBadge.tsx
+++ b/frontend/src/components/pki-syncs/PkiSyncStatusBadge.tsx
@@ -1,4 +1,3 @@
-import { useMemo } from "react";
import { format } from "date-fns";
import {
AlertTriangleIcon,
@@ -17,6 +16,7 @@ import {
HoverCardTrigger,
TBadgeProps
} from "@app/components/v3";
+import { getPkiSyncFailureMessage } from "@app/helpers/pkiSyncs";
import { PkiSyncStatus } from "@app/hooks/api/pkiSyncs";
type Props = {
@@ -54,19 +54,7 @@ export const PkiSyncStatusBadge = ({ status, lastSyncedAt, lastSyncMessage }: Pr
break;
}
- const failureMessage = useMemo(() => {
- if (status === PkiSyncStatus.Failed) {
- if (lastSyncMessage)
- try {
- return JSON.stringify(JSON.parse(lastSyncMessage), null, 2);
- } catch {
- return lastSyncMessage;
- }
-
- return "An Unknown Error Occurred.";
- }
- return null;
- }, [status, lastSyncMessage]);
+ const failureMessage = getPkiSyncFailureMessage(status, lastSyncMessage);
const badge = (
<Badge variant={variant}>
diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
index c9e8380b5d..d1a133ef85 100644
--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
@@ -32,6 +32,7 @@ import {
PkiSyncExportFormat,
TPkiSync,
useCanSetPostSyncCommand,
+ useCanSetPreflightCommand,
useCreatePkiSync,
usePkiSyncOption
} from "@app/hooks/api/pkiSyncs";
@@ -44,6 +45,7 @@ import { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";
import { PkiSyncFieldMappingsFields } from "./PkiSyncFieldMappingsFields";
import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields";
import { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";
+import { PkiSyncPreflightCommandFields } from "./PkiSyncPreflightCommandFields";
import { PkiSyncReviewFields } from "./PkiSyncReviewFields";
type Props = {
@@ -79,12 +81,12 @@ const STEP_META: Record<
rightDescription:
"Map each certificate component (certificate, private key, and chain) to the field names used at the destination."
},
- postSyncCommand: {
- short: "Command after sync",
- subtitle: "Optionally run a command on the host after certificates are written.",
- rightLabel: "POST-SYNC COMMAND",
+ hostCommands: {
+ short: "Commands on the host",
+ subtitle: "Optionally check the host before the sync, and act on it afterward.",
+ rightLabel: "COMMANDS",
rightDescription:
- "The gateway runs your command on the destination host 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, and a failure marks the sync failed."
+ "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."
},
details: {
short: "Name and description",
@@ -111,7 +113,7 @@ const STEP_META: Record<
const getFormTabs = (
destination: PkiSync,
- canRunPostSyncCommand: boolean
+ canRunHostCommands: boolean
): { name: string; key: string; fields: FieldPath<TPkiSyncForm>[] }[] => {
const baseTabs = [
{
@@ -134,11 +136,14 @@ const getFormTabs = (
});
}
- if (canRunPostSyncCommand) {
+ if (canRunHostCommands) {
baseTabs.push({
- name: "Post-Sync Command",
- key: "postSyncCommand",
- fields: ["syncOptions.postSyncCommand"] as FieldPath<TPkiSyncForm>[]
+ name: "Commands",
+ key: "hostCommands",
+ fields: [
+ "syncOptions.preflightCommand",
+ "syncOptions.postSyncCommand"
+ ] as FieldPath<TPkiSyncForm>[]
});
}
@@ -175,9 +180,11 @@ export const CreatePkiSyncForm = ({
const { syncOption } = usePkiSyncOption(destination);
const canSetPostSyncCommand = useCanSetPostSyncCommand(applicationId);
+ const canSetPreflightCommand = useCanSetPreflightCommand(applicationId);
const FORM_TABS = getFormTabs(
destination,
- Boolean(syncOption?.canRunPostSyncCommand) && canSetPostSyncCommand
+ (Boolean(syncOption?.canRunPreflightCommand) && canSetPreflightCommand) ||
+ (Boolean(syncOption?.canRunPostSyncCommand) && canSetPostSyncCommand)
);
const formMethods = useForm<TPkiSyncForm>({
@@ -374,11 +381,17 @@ export const CreatePkiSyncForm = ({
</>
)}
{currentKey === "mappings" && <PkiSyncFieldMappingsFields destination={destination} />}
- {currentKey === "postSyncCommand" && (
- <PkiSyncPostSyncCommandFields
- destination={destination}
- canEditCommand={canSetPostSyncCommand}
- />
+ {currentKey === "hostCommands" && (
+ <div className="flex flex-col gap-8">
+ <PkiSyncPreflightCommandFields
+ destination={destination}
+ canEditCommand={canSetPreflightCommand}
+ />
+ <PkiSyncPostSyncCommandFields
+ destination={destination}
+ canEditCommand={canSetPostSyncCommand}
+ />
+ </div>
)}
{currentKey === "details" && <PkiSyncDetailsFields />}
{currentKey === "certificates" && (
diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
index 3cb794cbee..b6d116fb2e 100644
--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
@@ -20,6 +20,7 @@ import {
PkiSync,
TPkiSync,
useCanSetPostSyncCommand,
+ useCanSetPreflightCommand,
usePkiSyncOption,
useUpdatePkiSync
} from "@app/hooks/api/pkiSyncs";
@@ -30,6 +31,7 @@ import { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";
import { PkiSyncFieldMappingsFields } from "./PkiSyncFieldMappingsFields";
import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields";
import { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";
+import { PkiSyncPreflightCommandFields } from "./PkiSyncPreflightCommandFields";
type Props = {
onComplete: (pkiSync: TPkiSync) => void;
@@ -48,7 +50,7 @@ type FormStep = {
rightDescription: string;
};
-const getFormSteps = (destination: PkiSync, canRunPostSyncCommand: boolean): FormStep[] => {
+const getFormSteps = (destination: PkiSync, canRunHostCommands: boolean): FormStep[] => {
const steps: FormStep[] = [
{
key: "destination",
@@ -85,16 +87,16 @@ const getFormSteps = (destination: PkiSync, canRunPostSyncCommand: boolean): For
});
}
- if (canRunPostSyncCommand) {
+ if (canRunHostCommands) {
steps.push({
- key: "postSyncCommand",
- name: "Post-Sync Command",
- description: "Command after sync",
- title: "Post-Sync Command",
- subtitle: "Optionally run a command on the host after certificates are written.",
- rightLabel: "POST-SYNC COMMAND",
+ key: "hostCommands",
+ name: "Commands",
+ description: "Commands on the host",
+ title: "Commands",
+ subtitle: "Optionally check the host before the sync, and act on it afterward.",
+ rightLabel: "COMMANDS",
rightDescription:
- "The gateway runs your command on the destination host 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, and a failure marks the sync failed."
+ "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."
});
}
@@ -117,7 +119,11 @@ 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 steps = getFormSteps(pkiSync.destination, Boolean(syncOption?.canRunPostSyncCommand));
+ const canSetPreflightCommand = useCanSetPreflightCommand(pkiSync.applicationId);
+ const steps = getFormSteps(
+ pkiSync.destination,
+ Boolean(syncOption?.canRunPreflightCommand || syncOption?.canRunPostSyncCommand)
+ );
const [selectedStepIndex, setSelectedStepIndex] = useState(0);
@@ -205,12 +211,18 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }
);
case "mappings":
return <PkiSyncFieldMappingsFields destination={pkiSync.destination} />;
- case "postSyncCommand":
+ case "hostCommands":
return (
- <PkiSyncPostSyncCommandFields
- destination={pkiSync.destination}
- canEditCommand={canSetPostSyncCommand}
- />
+ <div className="flex flex-col gap-8">
+ <PkiSyncPreflightCommandFields
+ destination={pkiSync.destination}
+ canEditCommand={canSetPreflightCommand}
+ />
+ <PkiSyncPostSyncCommandFields
+ destination={pkiSync.destination}
+ canEditCommand={canSetPostSyncCommand}
+ />
+ </div>
);
case "details":
return <PkiSyncDetailsFields />;
diff --git a/frontend/src/components/pki-syncs/forms/HostCommandField.tsx b/frontend/src/components/pki-syncs/forms/HostCommandField.tsx
new file mode 100644
index 0000000000..3f9f6e24b8
--- /dev/null
+++ b/frontend/src/components/pki-syncs/forms/HostCommandField.tsx
@@ -0,0 +1,74 @@
+import { ReactNode } from "react";
+import { Controller, FieldPath, useFormContext } from "react-hook-form";
+
+import { Field, FieldDescription, FieldError, FieldLabel } from "@app/components/v3";
+import { buildHostCommandTooltipDescriptions } from "@app/helpers/pkiSyncs";
+import { HostCommandVariable, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
+
+import { TPkiSyncForm } from "./schemas/pki-sync-schema";
+import { HostCommandInput } from "./HostCommandInput";
+import { HostCommandVariablesTooltip } from "./HostCommandVariablesTooltip";
+
+type Props = {
+ name: FieldPath<TPkiSyncForm>;
+ id: string;
+ label: string;
+ descriptions: Record<HostCommandVariable, string>;
+ tooltipFooter: ReactNode;
+ description: string;
+ noPermissionDescription: string;
+ placeholder?: string;
+ canEditCommand?: boolean;
+};
+
+export const HostCommandField = ({
+ name,
+ id,
+ label,
+ descriptions,
+ tooltipFooter,
+ description,
+ noPermissionDescription,
+ placeholder,
+ canEditCommand = true
+}: Props) => {
+ const { control, watch } = useFormContext<TPkiSyncForm>();
+ const isPkcs12 = watch("syncOptions.exportFormat") === PkiSyncExportFormat.Pkcs12;
+
+ const variables = Object.values(HostCommandVariable).filter(
+ (variable) => variable !== HostCommandVariable.Pkcs12Password || isPkcs12
+ );
+
+ return (
+ <Controller
+ control={control}
+ name={name}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field data-invalid={Boolean(error)} data-disabled={!canEditCommand}>
+ <FieldLabel htmlFor={id}>
+ {label}
+ <HostCommandVariablesTooltip
+ variables={variables}
+ descriptions={buildHostCommandTooltipDescriptions(descriptions)}
+ footer={tooltipFooter}
+ />
+ </FieldLabel>
+ <HostCommandInput
+ id={id}
+ value={(value as string) ?? ""}
+ onChange={onChange}
+ variables={variables}
+ descriptions={descriptions}
+ isError={Boolean(error)}
+ isDisabled={!canEditCommand}
+ placeholder={canEditCommand ? placeholder : undefined}
+ />
+ <FieldDescription>
+ {canEditCommand ? description : noPermissionDescription}
+ </FieldDescription>
+ <FieldError>{error?.message}</FieldError>
+ </Field>
+ )}
+ />
+ );
+};
diff --git a/frontend/src/components/pki-syncs/forms/PostSyncCommandInput.tsx b/frontend/src/components/pki-syncs/forms/HostCommandInput.tsx
similarity index 92%
rename from frontend/src/components/pki-syncs/forms/PostSyncCommandInput.tsx
rename to frontend/src/components/pki-syncs/forms/HostCommandInput.tsx
index 178e5f75ca..8f20a64e0f 100644
--- a/frontend/src/components/pki-syncs/forms/PostSyncCommandInput.tsx
+++ b/frontend/src/components/pki-syncs/forms/HostCommandInput.tsx
@@ -3,8 +3,6 @@ import * as PopoverPrimitive from "@radix-ui/react-popover";
import { TextArea } from "@app/components/v3";
import { cn } from "@app/components/v3/utils";
-import { POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS } from "@app/helpers/pkiSyncs";
-import { PostSyncCommandVariable } from "@app/hooks/api/pkiSyncs";
const OPEN_VARIABLE_PATTERN = /\{\{([a-zA-Z0-9_]*)$/;
@@ -14,17 +12,19 @@ type Props = {
id: string;
value: string;
onChange: (value: string) => void;
- variables: PostSyncCommandVariable[];
+ variables: string[];
+ descriptions: Record<string, string>;
placeholder?: string;
isError?: boolean;
isDisabled?: boolean;
};
-export const PostSyncCommandInput = ({
+export const HostCommandInput = ({
id,
value,
onChange,
variables,
+ descriptions,
placeholder,
isError,
isDisabled
@@ -59,7 +59,7 @@ export const PostSyncCommandInput = ({
setHighlightedIndex(0);
};
- const insertVariable = (variable: PostSyncCommandVariable) => {
+ const insertVariable = (variable: string) => {
if (variableStart === -1) return;
const before = value.slice(0, variableStart);
@@ -157,9 +157,7 @@ export const PostSyncCommandInput = ({
>
<div className="flex min-w-0 items-center gap-2">
<span className="shrink-0">{variable}</span>
- <span className="truncate text-xs text-muted">
- {POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS[variable]}
- </span>
+ <span className="truncate text-xs text-muted">{descriptions[variable]}</span>
</div>
<span className="shrink-0 text-xs text-muted opacity-0 transition-opacity group-hover:opacity-100">
insert
diff --git a/frontend/src/components/pki-syncs/forms/HostCommandVariablesTooltip.tsx b/frontend/src/components/pki-syncs/forms/HostCommandVariablesTooltip.tsx
new file mode 100644
index 0000000000..62918128c2
--- /dev/null
+++ b/frontend/src/components/pki-syncs/forms/HostCommandVariablesTooltip.tsx
@@ -0,0 +1,32 @@
+import { Fragment, ReactNode } from "react";
+import { Info } from "lucide-react";
+
+import { Badge, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
+
+type Props = {
+ variables: string[];
+ descriptions: Record<string, string>;
+ footer: ReactNode;
+};
+
+export const HostCommandVariablesTooltip = ({ variables, descriptions, footer }: Props) => (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info />
+ </TooltipTrigger>
+ <TooltipContent side="right" sideOffset={8} collisionPadding={16} className="max-w-md">
+ <p className="mb-2 font-medium">Available variables</p>
+ <div className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-1.5">
+ {variables.map((variable) => (
+ <Fragment key={variable}>
+ <Badge variant="neutral" className="font-mono">
+ {`{{${variable}}}`}
+ </Badge>
+ <span>{descriptions[variable]}</span>
+ </Fragment>
+ ))}
+ </div>
+ <p className="mt-2">{footer}</p>
+ </TooltipContent>
+ </Tooltip>
+);
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx
index abfa732218..f78b2bca56 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx
@@ -1,109 +1,41 @@
-import { Fragment } from "react";
-import { Controller, useFormContext } from "react-hook-form";
-import { Info } from "lucide-react";
+import { useFormContext } from "react-hook-form";
-import {
- Badge,
- Field,
- FieldDescription,
- FieldError,
- FieldLabel,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
-import {
- POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS,
- SINGLE_CERTIFICATE_POST_SYNC_COMMAND_VARIABLES
-} from "@app/helpers/pkiSyncs";
-import { PkiSync, PkiSyncExportFormat, PostSyncCommandVariable } from "@app/hooks/api/pkiSyncs";
+import { POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS } from "@app/helpers/pkiSyncs";
+import { PkiSync } from "@app/hooks/api/pkiSyncs";
import { TPkiSyncForm } from "./schemas/pki-sync-schema";
-import { PostSyncCommandInput } from "./PostSyncCommandInput";
+import { HostCommandField } from "./HostCommandField";
const COMMAND_PLACEHOLDERS: Partial<Record<PkiSync, string>> = {
[PkiSync.LinuxServer]: "cp {{certificatePath}} /etc/nginx/ssl/live.pem && systemctl reload nginx",
[PkiSync.WindowsServer]: 'Restart-Service -Name "W3SVC"'
};
-// Anchored to one side with a gap: a tall tooltip left to collision-flip lands under the cursor for
-// a frame, and Radix sets pointer-events:auto inline on the content inside a modal, so it steals the
-// hover and the tooltip flickers open/closed.
-const PostSyncCommandVariablesTooltip = ({
- variables
-}: {
- variables: PostSyncCommandVariable[];
-}) => (
- <Tooltip>
- <TooltipTrigger asChild>
- <Info />
- </TooltipTrigger>
- <TooltipContent side="right" sideOffset={8} collisionPadding={16} className="max-w-md">
- <p className="mb-2 font-medium">Available variables</p>
- <div className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-1.5">
- {variables.map((variable) => (
- <Fragment key={variable}>
- <Badge variant="neutral" className="font-mono">
- {`{{${variable}}}`}
- </Badge>
- <span>
- {POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS[variable]}
- {SINGLE_CERTIFICATE_POST_SYNC_COMMAND_VARIABLES.includes(variable) &&
- ". Single-certificate syncs only"}
- </span>
- </Fragment>
- ))}
- </div>
- <p className="mt-2">
- Type <span className="font-mono">{"{{"}</span> in the command to pick one. Each variable is
- replaced with its value before the command is sent to the host, and is inserted already
- quoted, so do not wrap one in quotes yourself. Do not paste secrets into the command.
- </p>
- </TooltipContent>
- </Tooltip>
-);
-
type Props = {
destination?: PkiSync;
canEditCommand?: boolean;
};
-export const PkiSyncPostSyncCommandFields = ({ destination, canEditCommand = true }: Props) => {
- const { control, watch } = useFormContext<TPkiSyncForm>();
- const currentDestination = destination ?? watch("destination");
- const isPkcs12 = watch("syncOptions.exportFormat") === PkiSyncExportFormat.Pkcs12;
-
- const variables = Object.values(PostSyncCommandVariable).filter(
- (variable) => variable !== PostSyncCommandVariable.Pkcs12Password || isPkcs12
- );
+export const PkiSyncPostSyncCommandFields = ({ destination, canEditCommand }: Props) => {
+ const { watch } = useFormContext<TPkiSyncForm>();
return (
- <Controller
- control={control}
+ <HostCommandField
name="syncOptions.postSyncCommand"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <Field data-invalid={Boolean(error)} data-disabled={!canEditCommand}>
- <FieldLabel htmlFor="post-sync-command">
- Command
- <PostSyncCommandVariablesTooltip variables={variables} />
- </FieldLabel>
- <PostSyncCommandInput
- id="post-sync-command"
- value={value ?? ""}
- onChange={onChange}
- variables={variables}
- isError={Boolean(error)}
- isDisabled={!canEditCommand}
- placeholder={canEditCommand ? COMMAND_PLACEHOLDERS[currentDestination] : undefined}
- />
- <FieldDescription>
- {canEditCommand
- ? "Runs once per sync run that delivers a file, as the sync's account, so keep that account least-privilege. If it fails, the sync is marked failed. The command is executed by the gateway, so the sync's connection must use one."
- : "You do not have permission to set a post-sync command on this sync. Ask an administrator to change it."}
- </FieldDescription>
- <FieldError>{error?.message}</FieldError>
- </Field>
- )}
+ id="post-sync-command"
+ label="Post-sync command"
+ descriptions={POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS}
+ placeholder={COMMAND_PLACEHOLDERS[destination ?? watch("destination")]}
+ canEditCommand={canEditCommand}
+ tooltipFooter={
+ <>
+ Type <span className="font-mono">{"{{"}</span> in the command to pick one. Each variable
+ is replaced with its value before the command is sent to the host, and is inserted already
+ quoted, so do not wrap one in quotes yourself. Do not paste secrets into the command.
+ </>
+ }
+ description="Runs after the sync delivers a certificate, for example to reload the service that uses it. Runs once per sync run that delivers a file, as the sync's account, so keep that account least-privilege. If it fails, the sync is marked failed."
+ noPermissionDescription="You do not have permission to set a post-sync command on this sync. Ask an administrator to change it."
/>
);
};
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncPreflightCommandFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncPreflightCommandFields.tsx
new file mode 100644
index 0000000000..18e6d38a0d
--- /dev/null
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncPreflightCommandFields.tsx
@@ -0,0 +1,43 @@
+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.tsx
index b9c2716450..3d287a0357 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
@@ -69,6 +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;
return (
<div className="mb-4 flex flex-col gap-6">
@@ -179,6 +181,14 @@ export const PkiSyncReviewFields = () => {
})}
</div>
</div>
+ {preflightCommand && (
+ <div className="flex flex-col gap-3">
+ <div className="w-full border-b border-border">
+ <span className="text-sm text-muted">Preflight Check</span>
+ </div>
+ <CodeBlock value={preflightCommand} className="max-h-48 whitespace-pre-wrap" />
+ </div>
+ )}
{postSyncCommand && (
<div className="flex flex-col gap-3">
<div className="w-full border-b border-border">
diff --git a/frontend/src/components/pki-syncs/forms/index.ts b/frontend/src/components/pki-syncs/forms/index.ts
index 901f0f434a..7c5647f7fc 100644
--- a/frontend/src/components/pki-syncs/forms/index.ts
+++ b/frontend/src/components/pki-syncs/forms/index.ts
@@ -4,5 +4,6 @@ export { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";
export { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";
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.ts
index eb34d65008..5b5491c9da 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
@@ -12,6 +12,8 @@ export const PostSyncCommandSchema = z
.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.ts
index 4aa997438b..7222e34b7c 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts
@@ -2,7 +2,11 @@ import { z } from "zod";
import { PemCertificateExtension, PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
-import { BasePkiSyncSchema, PostSyncCommandSchema } from "./base-pki-sync-schema";
+import {
+ BasePkiSyncSchema,
+ PostSyncCommandSchema,
+ PreflightCommandSchema
+} from "./base-pki-sync-schema";
const compileNameSchema = (val: string) =>
val
@@ -54,6 +58,7 @@ const LinuxServerSyncOptionsSchema = z.object({
})
.transform((v) => v || undefined)
.optional(),
+ preflightCommand: PreflightCommandSchema,
postSyncCommand: PostSyncCommandSchema,
certificateNameSchema: z
.string()
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.ts
index 6e98e87f75..fed3a5c7ec 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts
@@ -7,7 +7,11 @@ import {
WindowsFileAccess
} from "@app/hooks/api/pkiSyncs";
-import { BasePkiSyncSchema, PostSyncCommandSchema } from "./base-pki-sync-schema";
+import {
+ BasePkiSyncSchema,
+ PostSyncCommandSchema,
+ PreflightCommandSchema
+} from "./base-pki-sync-schema";
const compileNameSchema = (val: string) =>
val
@@ -41,6 +45,7 @@ const WindowsServerSyncOptionsSchema = z.object({
.max(20)
.optional(),
includePrivateKey: z.boolean().default(true),
+ preflightCommand: PreflightCommandSchema,
postSyncCommand: PostSyncCommandSchema,
certificateNameSchema: z
.string()
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index bf874b1457..44e200b7a4 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -77,7 +77,8 @@ export enum ProjectPermissionPkiSyncActions {
SyncCertificates = "sync-certificates",
ImportCertificates = "import-certificates",
RemoveCertificates = "remove-certificates",
- SetPostSyncCommand = "set-post-sync-command"
+ SetPostSyncCommand = "set-post-sync-command",
+ SetPreflightCommand = "set-preflight-command"
}
export enum ProjectPermissionPkiDiscoveryActions {
diff --git a/frontend/src/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.ts
index 376b6a46a5..aa270e08bc 100644
--- a/frontend/src/helpers/pkiSyncs.ts
+++ b/frontend/src/helpers/pkiSyncs.ts
@@ -1,5 +1,5 @@
import { AppConnection } from "@app/hooks/api/appConnections";
-import { PkiSync, PostSyncCommandVariable } from "@app/hooks/api/pkiSyncs";
+import { HostCommandVariable, PkiSync, PkiSyncStatus } from "@app/hooks/api/pkiSyncs";
export const PKI_SYNC_MAP: Record<
PkiSync,
@@ -150,15 +150,48 @@ export const VALUE_SYNC_OPTION_FIELDS = [
{ key: "group", label: "Group" }
] as const;
-export const POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS: Record<PostSyncCommandVariable, string> = {
- [PostSyncCommandVariable.CertificatePath]: "Full path of the certificate file delivered this run",
- [PostSyncCommandVariable.CertificateDirectory]: "The destination directory",
- [PostSyncCommandVariable.CertificateFiles]: "Every path written this run, one per line",
- [PostSyncCommandVariable.CommonName]: "The certificate's common name",
- [PostSyncCommandVariable.Pkcs12Password]: "The PKCS#12 export password"
+export const POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS: Record<HostCommandVariable, string> = {
+ [HostCommandVariable.CertificatePath]: "Full path of the certificate file delivered this run",
+ [HostCommandVariable.CertificateDirectory]: "The destination directory",
+ [HostCommandVariable.CertificateFiles]: "Every path written this run, one per line",
+ [HostCommandVariable.CommonName]: "The certificate's common name",
+ [HostCommandVariable.Pkcs12Password]: "The PKCS#12 export password"
};
-export const SINGLE_CERTIFICATE_POST_SYNC_COMMAND_VARIABLES = [
- PostSyncCommandVariable.CertificatePath,
- PostSyncCommandVariable.CommonName
+export const PREFLIGHT_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",
+ [HostCommandVariable.CommonName]: "The certificate's common name",
+ [HostCommandVariable.Pkcs12Password]: "The PKCS#12 export password"
+};
+
+const SINGLE_CERTIFICATE_HOST_COMMAND_VARIABLES = [
+ HostCommandVariable.CertificatePath,
+ HostCommandVariable.CommonName
];
+
+export const buildHostCommandTooltipDescriptions = (
+ descriptions: Record<HostCommandVariable, string>
+): Record<string, string> =>
+ Object.fromEntries(
+ Object.values(HostCommandVariable).map((variable) => [
+ variable,
+ SINGLE_CERTIFICATE_HOST_COMMAND_VARIABLES.includes(variable)
+ ? `${descriptions[variable]}. Single-certificate syncs only`
+ : descriptions[variable]
+ ])
+ );
+
+export const getPkiSyncFailureMessage = (
+ status: PkiSyncStatus | null | undefined,
+ message: string | null | undefined
+): string | null => {
+ if (status !== PkiSyncStatus.Failed || !message) return null;
+
+ try {
+ return JSON.stringify(JSON.parse(message), null, 2);
+ } catch {
+ return message;
+ }
+};
diff --git a/frontend/src/hooks/api/pkiApplications/types.ts b/frontend/src/hooks/api/pkiApplications/types.ts
index 8e31fb70c1..2e50d467b7 100644
--- a/frontend/src/hooks/api/pkiApplications/types.ts
+++ b/frontend/src/hooks/api/pkiApplications/types.ts
@@ -32,6 +32,7 @@ export enum PkiApplicationResourceActions {
ImportCertificates = "import-certificates",
RemoveCertificates = "remove-certificates",
SetPostSyncCommand = "set-post-sync-command",
+ SetPreflightCommand = "set-preflight-command",
RevealAcmeEabSecret = "reveal-acme-eab-secret",
RotateAcmeEabSecret = "rotate-acme-eab-secret",
GenerateScepChallenge = "generate-scep-challenge",
diff --git a/frontend/src/hooks/api/pkiSyncs/enums.ts b/frontend/src/hooks/api/pkiSyncs/enums.ts
index 10f2bd2cb2..bfc2c8a949 100644
--- a/frontend/src/hooks/api/pkiSyncs/enums.ts
+++ b/frontend/src/hooks/api/pkiSyncs/enums.ts
@@ -23,7 +23,7 @@ export enum PemCertificateExtension {
Crt = "crt"
}
-export enum PostSyncCommandVariable {
+export enum HostCommandVariable {
CertificatePath = "certificatePath",
CertificateDirectory = "certificateDirectory",
CertificateFiles = "certificateFiles",
diff --git a/frontend/src/hooks/api/pkiSyncs/types/index.ts b/frontend/src/hooks/api/pkiSyncs/types/index.ts
index ff30359bad..0caaea8b50 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/index.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/index.ts
@@ -19,6 +19,7 @@ export type TPkiSyncOption = {
canImportCertificates: boolean;
canRemoveCertificates: boolean;
canRunPostSyncCommand?: boolean;
+ canRunPreflightCommand?: 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.ts
index 2934941332..e0843031e9 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts
@@ -17,6 +17,7 @@ export type TLinuxServerPkiSync = TRootPkiSync & {
privateKeyFileMode?: string;
owner?: string;
group?: string;
+ preflightCommand?: 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.ts
index da11d34a2d..c4c5e4eba9 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts
@@ -14,6 +14,7 @@ export type TWindowsServerPkiSync = TRootPkiSync & {
combineCertificateChain?: boolean;
includePrivateKey?: boolean;
fileAccessRules?: { identity: string; access: WindowsFileAccess }[];
+ preflightCommand?: string | null;
postSyncCommand?: string | null;
};
connection: {
diff --git a/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts b/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts
index e26ed6547e..589cad4f00 100644
--- a/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts
+++ b/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts
@@ -8,28 +8,30 @@ import {
} from "../pkiApplications";
import { TPkiSync } from "./types";
-export const useCanSetPostSyncCommand = (applicationId?: string | null) => {
+const useCanSetHostCommand = (
+ action: PkiApplicationResourceActions,
+ applicationId?: string | null
+) => {
const { data: appPermissionData } = useGetPkiApplicationPermissions(applicationId ?? "");
- return Boolean(
- appPermissionData?.permission?.can(
- PkiApplicationResourceActions.SetPostSyncCommand,
- PkiApplicationResourceSub.PkiSyncs
- )
- );
+ return Boolean(appPermissionData?.permission?.can(action, PkiApplicationResourceSub.PkiSyncs));
};
+export const useCanSetPostSyncCommand = (applicationId?: string | null) =>
+ useCanSetHostCommand(PkiApplicationResourceActions.SetPostSyncCommand, applicationId);
+
+export const useCanSetPreflightCommand = (applicationId?: string | null) =>
+ useCanSetHostCommand(PkiApplicationResourceActions.SetPreflightCommand, applicationId);
+
export const usePkiSyncPermissions = (pkiSync: TPkiSync) => {
const { permission: projectPermission } = useProjectPermission();
const { data: appPermissionData } = useGetPkiApplicationPermissions(pkiSync.applicationId ?? "");
const appPermission = appPermissionData?.permission;
- const canSetPostSyncCommand = useCanSetPostSyncCommand(pkiSync.applicationId);
const checkApp = (action: PkiApplicationResourceActions) =>
Boolean(appPermission?.can(action, PkiApplicationResourceSub.PkiSyncs));
return {
- canSetPostSyncCommand,
canRead:
projectPermission.can(ProjectPermissionPkiSyncActions.Read, ProjectPermissionSub.PkiSyncs) ||
checkApp(PkiApplicationResourceActions.Read),
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
index 4bcbfef096..53d3ae26e8 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
@@ -34,7 +34,8 @@ import {
PkiSyncDetailsSection,
PkiSyncFieldMappingsSection,
PkiSyncOptionsSection,
- PkiSyncPostSyncCommandSection
+ PkiSyncPostSyncCommandSection,
+ PkiSyncPreflightCheckSection
} from "./components";
const PageContent = () => {
@@ -137,6 +138,7 @@ const PageContent = () => {
<PkiSyncDetailsSection pkiSync={pkiSync} />
<PkiSyncDestinationSection pkiSync={pkiSync} />
<PkiSyncFieldMappingsSection pkiSync={pkiSync} />
+ <PkiSyncPreflightCheckSection pkiSync={pkiSync} />
<PkiSyncPostSyncCommandSection pkiSync={pkiSync} />
</DetailGroup>
<PkiSyncOptionsSection pkiSync={pkiSync} />
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/HostCommandDetail.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/HostCommandDetail.tsx
new file mode 100644
index 0000000000..0c237c5d81
--- /dev/null
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/HostCommandDetail.tsx
@@ -0,0 +1,64 @@
+import { useState } from "react";
+
+import {
+ Badge,
+ CodeBlock,
+ Detail,
+ DetailLabel,
+ DetailValue,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+
+type Props = {
+ label: string;
+ command?: string;
+ showCommandLabel: string;
+ dialogDescription: string;
+};
+
+export const HostCommandDetail = ({
+ label,
+ command,
+ showCommandLabel,
+ dialogDescription
+}: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <Detail>
+ <DetailLabel>{label}</DetailLabel>
+ <DetailValue>
+ {command ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge asChild variant="neutral">
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Configured
+ </button>
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="right">{showCommandLabel}</TooltipContent>
+ </Tooltip>
+ ) : (
+ <span className="text-muted/50 italic">None</span>
+ )}
+ </DetailValue>
+ <Dialog open={isOpen} onOpenChange={setIsOpen}>
+ <DialogContent className="max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>{label}</DialogTitle>
+ <DialogDescription>{dialogDescription}</DialogDescription>
+ </DialogHeader>
+ <CodeBlock value={command ?? ""} className="max-h-96 whitespace-pre-wrap" />
+ </DialogContent>
+ </Dialog>
+ </Detail>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx
index ddc0dc4603..168b4529e6 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx
@@ -1,10 +1,10 @@
-import { useMemo } from "react";
import { format } from "date-fns";
import { BanIcon, RefreshCwIcon } from "lucide-react";
import { PkiSyncStatusBadge } from "@app/components/pki-syncs";
import { Badge, Detail, DetailLabel, DetailValue } from "@app/components/v3";
-import { PkiSyncStatus, TPkiSync } from "@app/hooks/api/pkiSyncs";
+import { getPkiSyncFailureMessage } from "@app/helpers/pkiSyncs";
+import { TPkiSync } from "@app/hooks/api/pkiSyncs";
type Props = {
pkiSync: TPkiSync;
@@ -13,19 +13,7 @@ type Props = {
export const PkiSyncDetailsSection = ({ pkiSync }: Props) => {
const { syncStatus, lastSyncMessage, lastSyncedAt, isAutoSyncEnabled } = pkiSync;
- const failureMessage = useMemo(() => {
- if (syncStatus === PkiSyncStatus.Failed) {
- if (lastSyncMessage)
- try {
- return JSON.stringify(JSON.parse(lastSyncMessage), null, 2);
- } catch {
- return lastSyncMessage;
- }
-
- return "An Unknown Error Occurred.";
- }
- return null;
- }, [syncStatus, lastSyncMessage]);
+ const failureMessage = getPkiSyncFailureMessage(syncStatus, lastSyncMessage);
return (
<>
@@ -59,7 +47,7 @@ export const PkiSyncDetailsSection = ({ pkiSync }: Props) => {
<DetailValue>{format(new Date(lastSyncedAt), "yyyy-MM-dd, hh:mm aaa")}</DetailValue>
</Detail>
)}
- {syncStatus === PkiSyncStatus.Failed && failureMessage && (
+ {failureMessage && (
<Detail>
<DetailLabel className="text-red">Last Sync Error</DetailLabel>
<DetailValue>
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx
index c6cc1352ba..313ad54b30 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx
@@ -1,22 +1,7 @@
-import { useState } from "react";
-
-import {
- Badge,
- CodeBlock,
- Detail,
- DetailLabel,
- DetailValue,
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
import { TPkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";
+import { HostCommandDetail } from "./HostCommandDetail";
+
type Props = {
pkiSync: TPkiSync;
};
@@ -24,40 +9,15 @@ type Props = {
export const PkiSyncPostSyncCommandSection = ({ pkiSync }: Props) => {
const { syncOption } = usePkiSyncOption(pkiSync.destination);
const { postSyncCommand } = pkiSync.syncOptions as { postSyncCommand?: string };
- const [isCommandOpen, setIsCommandOpen] = useState(false);
if (!syncOption?.canRunPostSyncCommand) return null;
return (
- <Detail>
- <DetailLabel>Post-Sync Command</DetailLabel>
- <DetailValue>
- {postSyncCommand ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <Badge asChild variant="neutral">
- <button type="button" onClick={() => setIsCommandOpen(true)}>
- Configured
- </button>
- </Badge>
- </TooltipTrigger>
- <TooltipContent side="right">Show command</TooltipContent>
- </Tooltip>
- ) : (
- <span className="text-muted/50 italic">None</span>
- )}
- </DetailValue>
- <Dialog open={isCommandOpen} onOpenChange={setIsCommandOpen}>
- <DialogContent className="max-w-2xl">
- <DialogHeader>
- <DialogTitle>Post-Sync Command</DialogTitle>
- <DialogDescription>
- Runs on the destination host after this sync delivers a certificate.
- </DialogDescription>
- </DialogHeader>
- <CodeBlock value={postSyncCommand ?? ""} className="max-h-96 whitespace-pre-wrap" />
- </DialogContent>
- </Dialog>
- </Detail>
+ <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.tsx
new file mode 100644
index 0000000000..2c568002c1
--- /dev/null
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPreflightCheckSection.tsx
@@ -0,0 +1,23 @@
+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/index.ts b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts
index d6a8f5dc8e..ca7fe5da01 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts
@@ -6,3 +6,4 @@ 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.tsx
index 5892631352..b67688b501 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -158,7 +158,8 @@ const PkiSyncPolicyActionSchema = z.object({
[ProjectPermissionPkiSyncActions.SyncCertificates]: z.boolean().optional(),
[ProjectPermissionPkiSyncActions.ImportCertificates]: z.boolean().optional(),
[ProjectPermissionPkiSyncActions.RemoveCertificates]: z.boolean().optional(),
- [ProjectPermissionPkiSyncActions.SetPostSyncCommand]: z.boolean().optional()
+ [ProjectPermissionPkiSyncActions.SetPostSyncCommand]: z.boolean().optional(),
+ [ProjectPermissionPkiSyncActions.SetPreflightCommand]: z.boolean().optional()
});
const CommitPolicyActionSchema = z.object({
@@ -1097,6 +1098,12 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
const canRemoveCertificates = action.includes(
ProjectPermissionPkiSyncActions.RemoveCertificates
);
+ const canSetPostSyncCommand = action.includes(
+ ProjectPermissionPkiSyncActions.SetPostSyncCommand
+ );
+ const canSetPreflightCommand = action.includes(
+ ProjectPermissionPkiSyncActions.SetPreflightCommand
+ );
if (!formVal[subject]) formVal[subject] = [{ conditions: [], inverted: false }];
@@ -1109,6 +1116,8 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
[ProjectPermissionPkiSyncActions.SyncCertificates]: canSyncCertificates,
[ProjectPermissionPkiSyncActions.ImportCertificates]: canImportCertificates,
[ProjectPermissionPkiSyncActions.RemoveCertificates]: canRemoveCertificates,
+ [ProjectPermissionPkiSyncActions.SetPostSyncCommand]: canSetPostSyncCommand,
+ [ProjectPermissionPkiSyncActions.SetPreflightCommand]: canSetPreflightCommand,
conditions: conditions ? convertCaslConditionToFormOperator(conditions) : [],
inverted
});
@@ -2885,6 +2894,16 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
label: "Remove Certificates from Destination",
value: ProjectPermissionPkiSyncActions.RemoveCertificates,
description: "Remove synced certificates from the destination"
+ },
+ {
+ label: "Set Preflight Check",
+ value: ProjectPermissionPkiSyncActions.SetPreflightCommand,
+ description: "Set the command a sync runs on the destination host before delivering"
+ },
+ {
+ label: "Set Post-Sync Command",
+ value: ProjectPermissionPkiSyncActions.SetPostSyncCommand,
+ description: "Set the command a sync runs on the destination host after delivering"
}
]
},