Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Minor pki sync health check improvements
Carlos Monastyrskif6dfbb3adb91
diff --git a/backend/src/db/migrations/20260811151204_add-pki-sync-health-check.ts b/backend/src/db/migrations/20260811151204_add-pki-sync-health-check.tsindex 12a4b0ac63..bbdaba7d96 100644--- a/backend/src/db/migrations/20260811151204_add-pki-sync-health-check.ts+++ b/backend/src/db/migrations/20260811151204_add-pki-sync-health-check.ts@@ -28,7 +28,7 @@ export async function up(knex: Knex): Promise<void> {await knex.schema.alterTable(TableName.PkiSync, (t) => {if (!existing.has("lastHealthCheckRanAt")) t.timestamp("lastHealthCheckRanAt", { useTz: true });if (!existing.has("lastHealthCheckStatus")) t.string("lastHealthCheckStatus");- if (!existing.has("lastHealthCheckMessage")) t.string("lastHealthCheckMessage", 1024);+ if (!existing.has("lastHealthCheckMessage")) t.string("lastHealthCheckMessage");});}diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex e9b2a995b5..61f63e738e 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -4569,7 +4569,6 @@ interface PkiSyncTestHealthCheckEvent {connectionName: string;destination: string;command: string;- ranAt: Date;result?: THealthCheckCommandResult;};}@@ -4581,7 +4580,6 @@ interface PkiSyncHealthCheckEvent {syncName: string;destination: string;command: string;- ranAt: Date;result?: THealthCheckCommandResult;};}diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.tsindex d38620d0d4..1857369c67 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@@ -48,7 +48,6 @@ export const registerSyncPkiEndpoints = ({connectionId: string;applicationId?: string;syncId?: string;- name?: string;destinationConfig: Record<string, unknown>;syncOptions: Record<string, unknown>;}>;@@ -349,7 +348,6 @@ export const registerSyncPkiEndpoints = ({connectionId: req.body.connectionId,applicationId: req.body.applicationId,syncId: req.body.syncId,- name: req.body.name,destinationConfig: req.body.destinationConfig,syncOptions: req.body.syncOptions,projectId: req.internalCertManagerProjectIddiff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.tsindex d317734234..4b52c05f70 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/certificaimport { 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 { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";+import { BaseHealthCheckTestSchema, HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";import { LINUX_SERVER_NAMING } from "./linux-server-pki-sync-constants";@@ -132,11 +132,7 @@ export const LinuxServerPkiSyncListItemSchema = z.object({canRemoveCertificates: z.literal(true)});-export const LinuxServerPkiSyncHealthCheckTestSchema = z.object({- connectionId: z.string().uuid(),- applicationId: z.string().uuid().optional(),- syncId: z.string().uuid().optional(),- name: z.string().trim().max(256).optional(),+export const LinuxServerPkiSyncHealthCheckTestSchema = BaseHealthCheckTestSchema.extend({destinationConfig: LinuxServerPkiSyncConfigSchema,syncOptions: LinuxServerPkiSyncOptionsSchema.partial()});diff --git a/backend/src/services/pki-sync/pki-sync-dal.ts b/backend/src/services/pki-sync/pki-sync-dal.tsindex 46ef2a91cb..cd7266f927 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, PkiSyncStatus } from "./pki-sync-enums";+import { HEALTH_CHECK_COMMAND_OPTION_KEY, PkiSync, PkiSyncStatus } from "./pki-sync-enums";export type TPkiSyncDALFactory = ReturnType<typeof pkiSyncDALFactory>;@@ -331,13 +331,19 @@ export const pkiSyncDALFactory = (db: TDbClient) => {}};+ const $whereHealthCheckStillConfigured = (builder: Knex.QueryBuilder) => {+ void builder.whereRaw(+ `("${TableName.PkiSync}"."syncOptions" ->> '${HEALTH_CHECK_COMMAND_OPTION_KEY}') IS NOT NULL`+ );+ };+const recordHealthCheckOutcome = async (syncId: string,outcome: { status: PkiSyncStatus.Succeeded | PkiSyncStatus.Failed; message: string | null; ranAt: Date },tx?: Knex) => {try {- return await (tx || db)(TableName.PkiSync).where({ id: syncId }).update({+ return await (tx || db)(TableName.PkiSync).where({ id: syncId }).where($whereHealthCheckStillConfigured).update({lastHealthCheckRanAt: outcome.ranAt,lastHealthCheckStatus: outcome.status,lastHealthCheckMessage: outcome.message@@ -357,6 +363,7 @@ export const pkiSyncDALFactory = (db: TDbClient) => {try {return await (tx || db)(TableName.PkiSync).where({ id: syncId })+ .where($whereHealthCheckStillConfigured).where((builder) => {void builder.whereNull("lastSyncMessage");$whereMessageStartsWithAny(builder, failurePrefixes);@@ -392,9 +399,9 @@ export const pkiSyncDALFactory = (db: TDbClient) => {.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" ->> 'healthCheckCommand') IS NOT NULL`)- .orderBy(`${TableName.PkiSync}.createdAt`, "asc")) as Array<{ id: string; destination: string }>;+ .select(`${TableName.PkiSync}.id`)+ .where($whereHealthCheckStillConfigured)+ .orderBy(`${TableName.PkiSync}.createdAt`, "asc")) as Array<{ id: string }>;} catch (error) {throw new DatabaseError({ error, name: "Find PKI syncs with a healthCheck command" });}diff --git a/backend/src/services/pki-sync/pki-sync-enums.ts b/backend/src/services/pki-sync/pki-sync-enums.tsindex d4fd78d3fc..68cc4ee025 100644--- a/backend/src/services/pki-sync/pki-sync-enums.ts+++ b/backend/src/services/pki-sync/pki-sync-enums.ts@@ -31,3 +31,5 @@ export const PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT = 3;export const PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S = 15 * 60;export const PKI_SYNC_CONNECTION_LOCK_RETRY = { retryCount: 10, retryDelay: 3_000, retryJitter: 500 };++export const HEALTH_CHECK_COMMAND_OPTION_KEY = "healthCheckCommand";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.tsindex 108d17cc02..25752cf1ca 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,3 +1,5 @@+import forge from "node-forge";+import {exportCertificateForSync,getExportedCertificateFileSuffixes,@@ -99,14 +101,61 @@ describe("getExportedCertificateFileSuffixes matches the real export", () => {});- test.each([true, false])("PKCS#12 is always a single .pfx (includeKey=%s)", (includePrivateKey) => {- expect(- getExportedCertificateFileSuffixes({+ const realPair = (() => {+ const keys = forge.pki.rsa.generateKeyPair(1024);+ const cert = forge.pki.createCertificate();+ cert.publicKey = keys.publicKey;+ cert.serialNumber = "01";+ cert.validity.notBefore = new Date(2026, 0, 1);+ cert.validity.notAfter = new Date(2027, 0, 1);+ const attrs = [{ name: "commonName", value: "api.example.com" }];+ cert.setSubject(attrs);+ cert.setIssuer(attrs);+ cert.sign(keys.privateKey);++ return {+ certificate: forge.pki.certificateToPem(cert),+ privateKey: forge.pki.privateKeyInfoToPem(+ forge.pki.wrapRsaPrivateKey(forge.pki.privateKeyToAsn1(keys.privateKey))+ )+ };+ })();++ test.each([+ [true, true],+ [true, false],+ [false, true],+ [false, false]+ ])("PKCS#12 includeKey=%s chain=%s", async (includePrivateKey, hasCertificateChain) => {+ const shape = {+ format: PkiSyncExportFormat.Pkcs12 as const,+ includePrivateKey,+ hasCertificateChain,+ hasPrivateKey: true+ };++ const exported = await exportCertificateForSync({+ format: shape.format,+ certificate: realPair.certificate,+ certificateChain: hasCertificateChain ? realPair.certificate : undefined,+ privateKey: realPair.privateKey,+ includePrivateKey,+ password: "pw",+ alias: "api.example.com"+ });++ expect(getExportedCertificateFileSuffixes(shape).sort()).toEqual(suffixes(exported));+ });++ test("PKCS#12 needs the private key, so a certificate without one cannot be exported at all", async () => {+ await expect(+ exportCertificateForSync({format: PkiSyncExportFormat.Pkcs12,- includePrivateKey,- hasCertificateChain: true,- hasPrivateKey: true+ certificate: realPair.certificate,+ includePrivateKey: true,+ password: "pw",+ alias: "api.example.com"})- ).toEqual([".pfx"]);+ ).rejects.toThrow(/PKCS#12 export is not supported for this key type/);});});diff --git a/backend/src/services/pki-sync/pki-sync-health-check-command-fns.test.ts b/backend/src/services/pki-sync/pki-sync-health-check-command-fns.test.tsindex 4290718f86..2f8dcea260 100644--- a/backend/src/services/pki-sync/pki-sync-health-check-command-fns.test.ts+++ b/backend/src/services/pki-sync/pki-sync-health-check-command-fns.test.ts@@ -1,5 +1,7 @@import { describe, expect, test, vi } from "vitest";+import { BadRequestError } from "@app/lib/errors";+import { PkiSyncStatus } from "./pki-sync-enums";import { PemCertificateExtension, PkiSyncExportFormat } from "./pki-sync-export-fns";import {@@ -9,19 +11,16 @@ import {buildHealthCheckFailureMessageFor,buildHealthCheckFailureSyncResult,didHealthCheckFail,- HEALTH_CHECK_COMMAND_TIMEOUT_MS,normalizeNewHealthCheckCommand,runHealthCheckCommand,SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT} from "./pki-sync-health-check-command-fns";import {- HostCommandKind,- hostCommandMessageSubject,+ HostCommandFailure,renderHostCommandContext,toPosixShellLiteral,toPowerShellLiteral} from "./pki-sync-host-command-fns";-import { POST_SYNC_COMMAND_TIMEOUT_MS } from "./pki-sync-post-sync-command-fns";import { TCertificateMap } from "./pki-sync-types";vi.mock("@app/lib/logger", () => ({@@ -57,12 +56,6 @@ const planFor = (command: string, certificateMap: TCertificateMap, overrides = {...overrides});-describe("health check timeout", () => {- test("is much shorter than a post-sync command, because it gates delivery", () => {- expect(HEALTH_CHECK_COMMAND_TIMEOUT_MS).toBeLessThan(POST_SYNC_COMMAND_TIMEOUT_MS);- });-});-describe("buildHealthCheckCommandPlan", () => {test("returns undefined when no check is configured", () => {expect(planFor("", oneCertificate)).toBeUndefined();@@ -186,6 +179,27 @@ describe("renderHostCommandContext", () => {);});+ test.each([+ ["left single quotation mark", "\u2018"],+ ["right single quotation mark", "\u2019"],+ ["single low-9 quotation mark", "\u201a"],+ ["single high-reversed-9 quotation mark", "\u201b"]+ ])("doubles PowerShell's %s, which also ends a single-quoted string", (_name, quote) => {+ const commonName = `app${quote}; Remove-Item C:\\ -Recurse`;++ expect(+ renderHostCommandContext("Write-Output {{commonName}}", { ...context, commonName }, toPowerShellLiteral)+ ).toBe(`Write-Output 'app${quote}${quote}; Remove-Item C:\\ -Recurse'`);+ });++ test("leaves a typographic quote alone for POSIX, which does not treat it as a quote", () => {+ const commonName = "app\u2019x";++ expect(renderHostCommandContext("echo {{commonName}}", { ...context, commonName }, toPosixShellLiteral)).toBe(+ "echo 'app\u2019x'"+ );+ });+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}}'"@@ -227,6 +241,21 @@ describe("runHealthCheckCommand", () => {expect(result.status).toBe(PkiSyncStatus.Failed);expect(result.exitCode).toBeUndefined();expect(result.error).toBe("gateway unreachable");+ expect(result.failure).toBe(HostCommandFailure.Unreachable);+ });++ test("marks a reason we raised ourselves as rejected, so the message can be shown as-is", async () => {+ const result = await runHealthCheckCommand({+ syncId: "sync-1",+ execute: async () => {+ throw new BadRequestError({+ message: "Running a command on the host requires the SSH connection to use a gateway."+ });+ }+ });++ expect(result.failure).toBe(HostCommandFailure.Rejected);+ expect(buildHealthCheckCommandFailureMessage(result)).toContain("requires the SSH connection to use a gateway");});test("redacts the export password from captured output", async () => {@@ -285,7 +314,7 @@ describe("the scheduled check owns a prefix distinct from a sync run's", () => {describe("healthCheck failure messages carry the prefix the DAL matches on", () => {test("every failure shape starts with the prefix, so a check can take over and clear its own status", () => {- const prefix = hostCommandMessageSubject(HostCommandKind.HealthCheck);+ const prefix = "Health check";const shapes = [{ status: PkiSyncStatus.Failed as const, exitCode: 3, durationMs: 12, failureDetail: "nginx is down" },{ status: PkiSyncStatus.Failed as const, exitCode: 1, durationMs: 5 },@@ -340,12 +369,26 @@ describe("buildHealthCheckCommandFailureMessage", () => {const message = buildHealthCheckCommandFailureMessage({status: PkiSyncStatus.Failed,durationMs: 120,+ failure: HostCommandFailure.Unreachable,error: "failed to dial target SSH server: dial tcp 10.0.0.1:22: connect: connection refused"});expect(message).toBe("Health check could not run: the destination host could not be reached");expect(message).not.toContain("dial tcp");});++ test("passes on the reason we rejected the command ourselves, because it names what to change", () => {+ const message = buildHealthCheckCommandFailureMessage({+ status: PkiSyncStatus.Failed,+ durationMs: 4,+ failure: HostCommandFailure.Rejected,+ error: "Running a command on the host requires the SSH connection to use a gateway."+ });++ expect(message).toBe(+ "Health check could not run: Running a command on the host requires the SSH connection to use a gateway."+ );+ });});describe("buildHealthCheckFailureSyncResult", () => {diff --git a/backend/src/services/pki-sync/pki-sync-health-check-command-fns.ts b/backend/src/services/pki-sync/pki-sync-health-check-command-fns.tsindex 7e1d369bc7..32de33d285 100644--- a/backend/src/services/pki-sync/pki-sync-health-check-command-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-health-check-command-fns.ts@@ -1,6 +1,6 @@import { BadRequestError } from "@app/lib/errors";-import { PkiSyncStatus } from "./pki-sync-enums";+import { HEALTH_CHECK_COMMAND_OPTION_KEY, PkiSyncStatus } from "./pki-sync-enums";import {getExportedCertificateFileSuffixes,PemCertificateExtension,@@ -11,10 +11,11 @@ import {buildHostCommandContext,buildHostCommandFailureMessage,commandNeedsCertificateData,+ commandUsesHostCommandVariable,findCertificateDependentHostCommandVariables,formatHostCommandVariables,- HOST_COMMAND_TIMEOUT_MS,HostCommandKind,+ HostCommandVariable,normalizeNewHostCommandOption,runHostCommand,THostCommandCertificate,@@ -24,10 +25,6 @@ import {} from "./pki-sync-host-command-fns";import { TCertificateMap, TPkiSyncSyncResult } from "./pki-sync-types";-export const HEALTH_CHECK_COMMAND_TIMEOUT_MS = HOST_COMMAND_TIMEOUT_MS[HostCommandKind.HealthCheck];--export const HEALTH_CHECK_COMMAND_OPTION_KEY = "healthCheckCommand";-export type THealthCheckCommandResult = THostCommandResult;export const getHealthCheckCommand = (syncOptions: unknown): string | undefined =>@@ -57,6 +54,14 @@ export const assertHealthCheckCommandIsTestable = (syncOptions: Record<string, u});}+ if (commandUsesHostCommandVariable(command, HostCommandVariable.Pkcs12Password)) {+ throw new BadRequestError({+ message: `A test cannot resolve ${formatHostCommandVariables([+ HostCommandVariable.Pkcs12Password+ ])} because the export password belongs to a saved sync. Save the sync and run the health check from its actions menu.`+ });+ }+return command;};diff --git a/backend/src/services/pki-sync/pki-sync-health-check-queue.ts b/backend/src/services/pki-sync/pki-sync-health-check-queue.tsindex ce87460d25..674baceb3e 100644--- a/backend/src/services/pki-sync/pki-sync-health-check-queue.ts+++ b/backend/src/services/pki-sync/pki-sync-health-check-queue.ts@@ -255,6 +255,13 @@ export const pkiSyncHealthCheckQueueFactory = ({return;}+ if (pkiSync.syncStatus === PkiSyncStatus.Running) {+ logger.info(+ `cron[${CronJobName.PkiSyncHealthCheck}]: a sync is delivering to this host, skipping [syncId=${syncId}]`+ );+ return undefined;+ }+const pkiSyncWithCredentials = await hydratePkiSyncCredentials({pkiSync,appConnectionDAL,@@ -300,7 +307,6 @@ export const pkiSyncHealthCheckQueueFactory = ({syncName: pkiSync.name,destination: pkiSync.destination,command,- ranAt: new Date(),result}}diff --git a/backend/src/services/pki-sync/pki-sync-host-command-fns.ts b/backend/src/services/pki-sync/pki-sync-host-command-fns.tsindex b2900137a0..bf08477dee 100644--- a/backend/src/services/pki-sync/pki-sync-host-command-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-host-command-fns.ts@@ -1,5 +1,6 @@import RE2 from "re2";+import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { PkiSyncStatus } from "./pki-sync-enums";@@ -52,10 +53,17 @@ const DEADLINE_GRACE_MS = 5_000;const sentenceCase = (text: string): string => `${text.charAt(0).toUpperCase()}${text.slice(1)}`;+export enum HostCommandFailure {+ TimedOut = "timed-out",+ Rejected = "rejected",+ Unreachable = "unreachable"+}+export type THostCommandResult = {status: PkiSyncStatus.Succeeded | PkiSyncStatus.Failed;exitCode?: number;timedOut?: boolean;+ failure?: HostCommandFailure;durationMs: number;output?: string;failureDetail?: string;@@ -78,7 +86,12 @@ const findHostCommandVariables = (command?: string): Set<string> => {export const toPosixShellLiteral = (value: string): string => `'${value.split("'").join(`'\\''`)}'`;-export const toPowerShellLiteral = (value: string): string => `'${value.split("'").join("''")}'`;+const POWERSHELL_SINGLE_QUOTES = new Set(["'", "‘", "’", "‚", "‛"]);++export const toPowerShellLiteral = (value: string): string =>+ `'${Array.from(value)+ .map((character) => (POWERSHELL_SINGLE_QUOTES.has(character) ? `${character}${character}` : character))+ .join("")}'`;export const formatHostCommandVariables = (variables: string[]): string =>variables.map((variable) => `{{${variable}}}`).join(", ");@@ -99,6 +112,9 @@ export const commandNeedsCertificateData = (command?: string): boolean => {return CERTIFICATE_DEPENDENT_HOST_COMMAND_VARIABLES.some((variable) => used.has(variable));};+export const commandUsesHostCommandVariable = (command: string | undefined, variable: HostCommandVariable): boolean =>+ findHostCommandVariables(command).has(variable);+export const findSingleCertificateHostCommandVariables = (command?: string): HostCommandVariable[] => {const used = findHostCommandVariables(command);return SINGLE_CERTIFICATE_HOST_COMMAND_VARIABLES.filter((variable) => used.has(variable));@@ -227,6 +243,11 @@ const COMMAND_TIMEOUT_ERROR_PATTERN = new RE2("command timed out|rpc timed out",const isTimeoutFailure = (err: unknown, message: string): boolean =>err instanceof HostCommandTimeoutError || COMMAND_TIMEOUT_ERROR_PATTERN.test(message);+const classifyFailure = (err: unknown, message: string): HostCommandFailure => {+ if (isTimeoutFailure(err, message)) return HostCommandFailure.TimedOut;+ return err instanceof BadRequestError ? HostCommandFailure.Rejected : HostCommandFailure.Unreachable;+};+const withHostCommandDeadline = <T>(execute: () => Promise<T>, timeoutMs: number, graceMs: number): Promise<T> => {let timer: NodeJS.Timeout;@@ -275,17 +296,19 @@ export const runHostCommand = async (args: {} catch (err) {const durationMs = Date.now() - startedAt;const error = redact((err as Error)?.message ?? "Unknown error");+ const failure = classifyFailure(err, error);logger.warn(`PKI sync ${kind} could not run [syncId=${syncId}] [durationMs=${durationMs}]: ${error}`);return {status: PkiSyncStatus.Failed,durationMs,error,- timedOut: isTimeoutFailure(err, error)+ failure,+ timedOut: failure === HostCommandFailure.TimedOut};}};-export const hostCommandMessageSubject = (kind: HostCommandKind): string => sentenceCase(kind);+const hostCommandMessageSubject = (kind: HostCommandKind): string => sentenceCase(kind);export const buildHostCommandFailureMessage = (kind: HostCommandKind,@@ -295,9 +318,15 @@ export const buildHostCommandFailureMessage = (const detail = result.failureDetail ?? firstNonEmptyLine(result.output);if (result.exitCode === undefined) {- return result.timedOut- ? `${subject} did not finish within its ${HOST_COMMAND_TIMEOUT_MS[kind] / 1000}s limit`- : `${subject} could not run: the destination host could not be reached`;+ if (result.failure === HostCommandFailure.TimedOut || result.timedOut) {+ return `${subject} did not finish within its ${HOST_COMMAND_TIMEOUT_MS[kind] / 1000}s limit`;+ }++ if (result.failure === HostCommandFailure.Rejected && result.error) {+ return `${subject} could not run: ${truncate(result.error, MAX_FAILURE_DETAIL_CHARS)}`;+ }++ return `${subject} could not run: the destination host could not be reached`;}const prefix = `${subject} failed (exit ${result.exitCode})`;diff --git a/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.test.ts b/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.test.tsindex e806e3744d..5cae8d7a18 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@@ -3,6 +3,7 @@ import { describe, expect, test, vi } from "vitest";import { PkiSyncStatus } from "./pki-sync-enums";import {findSingleCertificateHostCommandVariables,+ HostCommandFailure,HostCommandVariable,renderHostCommandContext,toPosixShellLiteral,@@ -354,11 +355,25 @@ describe("buildPostSyncCommandFailureMessage", () => {const message = buildPostSyncCommandFailureMessage({status: PkiSyncStatus.Failed,durationMs: 10,- error: "Running a command on the host requires the SSH connection to use a gateway."+ failure: HostCommandFailure.Unreachable,+ error: "failed to dial target SSH server: dial tcp 10.0.0.1:22: connect: connection refused"});expect(message).toBe("Post-sync command could not run: the destination host could not be reached");- expect(message).not.toContain("SSH connection");+ expect(message).not.toContain("dial tcp");+ });++ test("passes on the reason we rejected the command ourselves, because it names what to change", () => {+ const message = buildPostSyncCommandFailureMessage({+ status: PkiSyncStatus.Failed,+ durationMs: 10,+ failure: HostCommandFailure.Rejected,+ error: "Running a command on the host requires the SSH connection to use a gateway."+ });++ expect(message).toBe(+ "Post-sync command could not run: Running a command on the host requires the SSH connection to use a gateway."+ );});test("truncates a long detail so it fits the sync message column", () => {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.tsindex f5280f5534..96ead8dc6d 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@@ -2,7 +2,6 @@ import {applyHostCommandOptionUpdate,buildHostCommandContext,buildHostCommandFailureMessage,- HOST_COMMAND_TIMEOUT_MS,HostCommandKind,normalizeNewHostCommandOption,runHostCommand,@@ -12,16 +11,12 @@ import {THostCommandResult} from "./pki-sync-host-command-fns";-export const POST_SYNC_COMMAND_TIMEOUT_MS = HOST_COMMAND_TIMEOUT_MS[HostCommandKind.PostSync];-export const POST_SYNC_COMMAND_OPTION_KEY = "postSyncCommand";export type TPostSyncCommandContext = THostCommandContext;export type TPostSyncCommandResult = THostCommandResult;-export type TPostSyncCommandExecutionResult = THostCommandExecutionResult;-export type TPostSyncCommandPlan = { command: string; context: TPostSyncCommandContext };export const getPostSyncCommand = (syncOptions: unknown): string | undefined =>@@ -65,7 +60,7 @@ export const buildPostSyncCommandPlan = (args: {export const runPostSyncCommand = (args: {syncId: string;- execute: () => Promise<TPostSyncCommandExecutionResult>;+ execute: () => Promise<THostCommandExecutionResult>;secretsToRedact?: Array<string | undefined>;}): Promise<TPostSyncCommandResult> => runHostCommand({ ...args, kind: HostCommandKind.PostSync });diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.tsindex e26eacb187..9e31bb7692 100644--- a/backend/src/services/pki-sync/pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts@@ -105,3 +105,10 @@ export const PkiSyncSchema = z.object({lastHealthCheckStatus: z.nativeEnum(PkiSyncStatus).nullable().optional(),lastHealthCheckMessage: z.string().nullable().optional()});++export const BaseHealthCheckTestSchema = z.object({+ connectionId: z.string().uuid(),+ applicationId: z.string().uuid().optional(),+ syncId: z.string().uuid().optional(),+ name: z.string().trim().max(256).optional()+});diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex 2342aff5be..14f0f3c139 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -25,7 +25,7 @@ import { TSyncMetadata } from "../certificate-sync/certificate-sync-schemas";import { certificateNameSchemaAllowsMultipleCertificates } from "./pki-sync-certificate-name-fns";import { encryptPkiSyncCredentials } from "./pki-sync-credentials-fns";import { TPkiSyncDALFactory } from "./pki-sync-dal";-import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";+import { HEALTH_CHECK_COMMAND_OPTION_KEY, PkiSync, PkiSyncStatus } from "./pki-sync-enums";import { PkiSyncExportFormat } from "./pki-sync-export-fns";import {enterprisePkiSyncCheck,@@ -37,7 +37,6 @@ import {applyHealthCheckCommandUpdate,assertHealthCheckCommandIsTestable,getHealthCheckCommand,- HEALTH_CHECK_COMMAND_OPTION_KEY,HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS,normalizeNewHealthCheckCommand,toHealthCheckApiResult@@ -878,7 +877,6 @@ export const pkiSyncServiceFactory = ({projectId: string;applicationId?: string;syncId?: string;- name?: string;}) => {if (args.syncId) {const pkiSync = await pkiSyncDAL.findById(args.syncId);@@ -889,18 +887,14 @@ export const pkiSyncServiceFactory = ({return { projectId: pkiSync.projectId, applicationId: pkiSync.applicationId, name: pkiSync.name };}- if (args.applicationId) {- return { projectId: args.projectId, applicationId: args.applicationId, name: args.name ?? "" };- }-- if (!args.name) {+ if (!args.applicationId) {throw new BadRequestError({message:- "Provide the application, the sync's name, or the id of the sync being edited, so the command can be authorized."+ "Provide the Application the sync belongs to, or the id of the sync being edited, so the command can be authorized."});}- return { projectId: args.projectId, name: args.name };+ return { projectId: args.projectId, applicationId: args.applicationId, name: "" };};const testPkiSyncHealthCheckCommand = async (@@ -909,7 +903,6 @@ export const pkiSyncServiceFactory = ({connectionId: string;applicationId?: string;syncId?: string;- name?: string;destinationConfig: Record<string, unknown>;syncOptions: Record<string, unknown>;projectId: string;@@ -952,7 +945,6 @@ export const pkiSyncServiceFactory = ({connectionName: connection.name,destination: args.destination,command,- ranAt: new Date(),result}}diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.tsindex dc5ae58721..a4ba74a144 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/certificaimport { 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 { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";+import { BaseHealthCheckTestSchema, HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";import { WINDOWS_SERVER_NAMING } from "./windows-server-pki-sync-constants";@@ -151,11 +151,7 @@ export const WindowsServerPkiSyncListItemSchema = z.object({canRemoveCertificates: z.literal(true)});-export const WindowsServerPkiSyncHealthCheckTestSchema = z.object({- connectionId: z.string().uuid(),- applicationId: z.string().uuid().optional(),- syncId: z.string().uuid().optional(),- name: z.string().trim().max(256).optional(),+export const WindowsServerPkiSyncHealthCheckTestSchema = BaseHealthCheckTestSchema.extend({destinationConfig: WindowsServerPkiSyncConfigSchema,syncOptions: WindowsServerPkiSyncOptionsSchema.partial()});diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdxindex 2ed5da96eb..1ca0e386c1 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx@@ -171,7 +171,7 @@ A check is limited to 8192 characters, counted as you write it, before variablesThe 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.+ 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 clears a reason an earlier check reported, and changes nothing otherwise. Either way the run is recorded in the sync's logs with the command and the first part of its output.</Accordion><Accordion title="Is there a time limit?">Yes, 15 seconds, and a check that runs out of time counts as a failure. The limit is deliberately much shorter than the post-sync command's, because the check gates delivery: a host that cannot answer a readiness question in fifteen seconds is itself the problem worth reporting. Keep the check to a question that is cheap to answer.diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdxindex b6a128c943..1356f14e67 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx@@ -177,7 +177,7 @@ Going past 2048 characters requires a Gateway on Infisical CLI v0.43.124 or lateUse `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.+ 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 clears a reason an earlier check reported, and changes nothing otherwise. Either way the run is recorded in the sync's logs with the command and the first part of its output.</Accordion><Accordion title="Is there a time limit?">Yes, 15 seconds, and a check that runs out of time counts as a failure. The limit is deliberately much shorter than the post-sync command's, because the check gates delivery: a host that cannot answer a readiness question in fifteen seconds is itself the problem worth reporting. Keep the check to a question that is cheap to answer.diff --git a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-variables.mdx b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-variables.mdxindex 78312e2a54..66b737f249 100644--- a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-variables.mdx+++ b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/health-check-variables.mdx@@ -12,6 +12,8 @@ Each value is inserted already quoted for the target's shell, so write `{{certifOnly 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.+A variable that names a certificate, and `{{pkcs12Password}}`, needs a saved sync to resolve against, so **Test check** rejects a check that uses one and tells you which. Run the check from the sync's actions menu once it is saved.+<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}}`:diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsxindex 5e8f946156..627551d409 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx@@ -43,7 +43,6 @@ export const PkiSyncHealthCheckCommandFields = ({connectionId,applicationId: applicationId ?? undefined,syncId,- name: syncId ? undefined : watch("name"),destinationConfig: (destinationConfig ?? {}) as Record<string, unknown>,syncOptions: { healthCheckCommand: command }});@@ -65,7 +64,7 @@ export const PkiSyncHealthCheckCommandFields = ({id="health-check-command"label="Health check"descriptions={HEALTH_CHECK_COMMAND_VARIABLE_DESCRIPTIONS}- placeholder={COMMAND_PLACEHOLDERS[destination ?? watch("destination")]}+ placeholder={COMMAND_PLACEHOLDERS[effectiveDestination]}canEditCommand={canEditCommand}tooltipFooter={<>diff --git a/frontend/src/hooks/api/pkiSyncs/mutations.tsx b/frontend/src/hooks/api/pkiSyncs/mutations.tsxindex b285d47c01..8a56f493f1 100644--- a/frontend/src/hooks/api/pkiSyncs/mutations.tsx+++ b/frontend/src/hooks/api/pkiSyncs/mutations.tsx@@ -13,6 +13,7 @@ import {TTriggerPkiSyncSyncCertificatesDTO,TUpdatePkiSyncDTO} from "@app/hooks/api/pkiSyncs/types";+import { ApiErrorTypes } from "@app/hooks/api/types";export const useCreatePkiSync = () => {const queryClient = useQueryClient();@@ -71,12 +72,12 @@ export const useDeletePkiSync = () => {export const useTestPkiSyncHealthCheck = () => {return useMutation({+ meta: { handledErrorCodes: [ApiErrorTypes.BadRequestError] },mutationFn: async ({destination,connectionId,applicationId,syncId,- name,destinationConfig,syncOptions}: {@@ -84,13 +85,12 @@ export const useTestPkiSyncHealthCheck = () => {connectionId: string;applicationId?: string;syncId?: string;- name?: string;destinationConfig: Record<string, unknown>;syncOptions: Record<string, unknown>;}) => {const { data } = await apiRequest.post<{ healthCheck: TPkiSyncHealthCheckResult }>(`/api/v1/cert-manager/syncs/${destination}/test-health-check`,- { connectionId, applicationId, syncId, name, destinationConfig, syncOptions }+ { connectionId, applicationId, syncId, destinationConfig, syncOptions });return data.healthCheck;@@ -101,6 +101,7 @@ export const useTestPkiSyncHealthCheck = () => {export const useRunPkiSyncHealthCheck = () => {const queryClient = useQueryClient();return useMutation({+ meta: { handledErrorCodes: [ApiErrorTypes.BadRequestError] },mutationFn: async ({syncId,destinationdiff --git a/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts b/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.tsindex 3d7a1df20f..3b0f92b050 100644--- a/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts+++ b/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts@@ -10,18 +10,32 @@ import { TPkiSync } from "./types";const useCanSetHostCommand = (action: PkiApplicationResourceActions,+ projectAction: ProjectPermissionPkiSyncActions,applicationId?: string | null) => {+ const { permission: projectPermission } = useProjectPermission();const { data: appPermissionData } = useGetPkiApplicationPermissions(applicationId ?? "");+ if (!applicationId) {+ return projectPermission.can(projectAction, ProjectPermissionSub.PkiSyncs);+ }+return Boolean(appPermissionData?.permission?.can(action, PkiApplicationResourceSub.PkiSyncs));};export const useCanSetPostSyncCommand = (applicationId?: string | null) =>- useCanSetHostCommand(PkiApplicationResourceActions.SetPostSyncCommand, applicationId);+ useCanSetHostCommand(+ PkiApplicationResourceActions.SetPostSyncCommand,+ ProjectPermissionPkiSyncActions.SetPostSyncCommand,+ applicationId+ );export const useCanSetHealthCheckCommand = (applicationId?: string | null) =>- useCanSetHostCommand(PkiApplicationResourceActions.SetHealthCheckCommand, applicationId);+ useCanSetHostCommand(+ PkiApplicationResourceActions.SetHealthCheckCommand,+ ProjectPermissionPkiSyncActions.SetHealthCheckCommand,+ applicationId+ );export const usePkiSyncPermissions = (pkiSync: TPkiSync) => {const { permission: projectPermission } = useProjectPermission();diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsxindex fdcdf62d40..464ab59f4e 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsx@@ -72,7 +72,7 @@ export const PkiSyncCommandsSection = ({ pkiSync }: Props) => {{lastHealthCheckStatus === PkiSyncStatus.Failed ? "Failed" : "Passed"}</Badge><span>- {format(new Date(lastHealthCheckRanAt), "yyyy-MM-dd, h:mm a")}+ {format(new Date(lastHealthCheckRanAt), "yyyy-MM-dd, hh:mm aaa")}</span></div>) : (