Skip to content

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

fix(pki-sync): address health check review comments

Carlos Monastyrskic84421b00833
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 114c4afd18..d7c613c64a 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3187,6 +3187,8 @@ export const registerRoutes = async (
keyStore,
pkiSyncDAL,
auditLogService,
+ notificationService,
+ pkiApplicationDAL,
projectDAL,
licenseService,
certificateDAL,
@@ -3221,6 +3223,8 @@ export const registerRoutes = async (
certificateAuthorityCertDAL,
certificateSyncDAL,
auditLogService,
+ notificationService,
+ pkiApplicationDAL,
gatewayV2Service,
gatewayPoolService
});
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 1857369c67..07c4f85578 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,6 +48,7 @@ export const registerSyncPkiEndpoints = ({
connectionId: string;
applicationId?: string;
syncId?: string;
+ certificateIds?: string[];
destinationConfig: Record<string, unknown>;
syncOptions: Record<string, unknown>;
}>;
@@ -348,6 +349,7 @@ export const registerSyncPkiEndpoints = ({
connectionId: req.body.connectionId,
applicationId: req.body.applicationId,
syncId: req.body.syncId,
+ certificateIds: req.body.certificateIds,
destinationConfig: req.body.destinationConfig,
syncOptions: req.body.syncOptions,
projectId: req.internalCertManagerProjectId
diff --git a/backend/src/services/notification/notification-types.ts b/backend/src/services/notification/notification-types.ts
index 80146793f8..f6f012962a 100644
--- a/backend/src/services/notification/notification-types.ts
+++ b/backend/src/services/notification/notification-types.ts
@@ -17,6 +17,7 @@ export enum NotificationType {
PROJECT_ACCESS_REQUEST = "project-access-request",
PROJECT_INVITATION = "project-invitation",
SECRET_SYNC_FAILED = "secret-sync-failed",
+ PKI_SYNC_FAILED = "pki-sync-failed",
GATEWAY_HEALTH_ALERT = "gateway-health-alert",
RELAY_HEALTH_ALERT = "relay-health-alert",
APPROVAL_REQUIRED = "approval-required",
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
index dc025fd315..1d9e7f35df 100644
--- a/backend/src/services/pki-sync/pki-sync-certificate-map-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-certificate-map-fns.ts
@@ -50,7 +50,8 @@ export const buildCertificateMap = async (
certificateSyncDAL,
projectDAL,
kmsService
- }: TBuildCertificateMapDeps
+ }: TBuildCertificateMapDeps,
+ certificateIdOverride?: string[]
): Promise<{ certificateMap: TCertificateMap; certificateMetadata: Map<string, { id: string; name: string }> }> => {
const { projectId, subscriberId, id: pkiSyncId } = pkiSync;
@@ -66,7 +67,7 @@ export const buildCertificateMap = async (
certificates.push(...subscriberCertificates);
}
- const certificateIds = await certificateSyncDAL.findCertificateIdsByPkiSyncId(pkiSyncId);
+ const certificateIds = certificateIdOverride ?? (await certificateSyncDAL.findCertificateIdsByPkiSyncId(pkiSyncId));
if (certificateIds.length > 0) {
const directCertificates = await certificateDAL.findActiveCertificatesByIds(certificateIds);
certificates.push(...directCertificates);
diff --git a/backend/src/services/pki-sync/pki-sync-dal.ts b/backend/src/services/pki-sync/pki-sync-dal.ts
index cd7266f927..92dac30619 100644
--- a/backend/src/services/pki-sync/pki-sync-dal.ts
+++ b/backend/src/services/pki-sync/pki-sync-dal.ts
@@ -1,7 +1,7 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { TableName, TPkiSyncs } from "@app/db/schemas";
+import { ProjectMembershipRole, RESOURCE_SCOPE, ResourceType, TableName, TPkiSyncs } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { buildFindFilter, ormify, prependTableNameToFindFilter, selectAllTableCols } from "@app/lib/knex";
import {
@@ -353,43 +353,62 @@ export const pkiSyncDALFactory = (db: TDbClient) => {
}
};
- const $whereMessageStartsWithAny = (builder: Knex.QueryBuilder, prefixes: string[]) => {
- prefixes.forEach((prefix) => {
- void builder.orWhereRaw(`left("lastSyncMessage", ?) = ?`, [prefix.length, prefix]);
- });
- };
-
- const reportHealthCheckFailure = async (syncId: string, message: string, failurePrefixes: string[], tx?: Knex) => {
+ const recordHealthCheckSkipped = async (syncId: string, message: string, tx?: Knex) => {
try {
return await (tx || db)(TableName.PkiSync)
.where({ id: syncId })
- .where($whereHealthCheckStillConfigured)
- .where((builder) => {
- void builder.whereNull("lastSyncMessage");
- $whereMessageStartsWithAny(builder, failurePrefixes);
- })
- .update({ syncStatus: PkiSyncStatus.Failed, lastSyncMessage: message });
+ .whereNotNull("lastHealthCheckRanAt")
+ .update({ lastHealthCheckMessage: message });
} catch (error) {
- throw new DatabaseError({ error, name: "Report health check failure - PKI Sync" });
+ throw new DatabaseError({ error, name: "Record health check skipped - PKI Sync" });
}
};
- const clearReportedHealthCheckFailure = async (syncId: string, failurePrefixes: string[], tx?: Knex) => {
- const knex = tx || db;
-
+ const findFailureNotificationRecipients = async (
+ pkiSync: { projectId: string; applicationId: string },
+ tx?: Knex
+ ): Promise<string[]> => {
try {
- return await knex(TableName.PkiSync)
- .where({ id: syncId })
- .where((builder) => $whereMessageStartsWithAny(builder, failurePrefixes))
- .update({
- syncStatus: knex.raw(`CASE WHEN "lastSyncedAt" IS NULL THEN ? ELSE ? END`, [
- PkiSyncStatus.Pending,
- PkiSyncStatus.Succeeded
- ]) as unknown as string,
- lastSyncMessage: null
- });
+ const knex = tx || db.replicaNode();
+ const query = knex(TableName.Membership)
+ .join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
+ .leftJoin(
+ TableName.UserGroupMembership,
+ `${TableName.UserGroupMembership}.groupId`,
+ `${TableName.Membership}.actorGroupId`
+ )
+ .where(`${TableName.MembershipRole}.role`, ProjectMembershipRole.Admin)
+ .where(`${TableName.Membership}.isActive`, true)
+ .where((builder) => {
+ void builder
+ .whereNull(`${TableName.MembershipRole}.temporaryAccessEndTime`)
+ .orWhere(`${TableName.MembershipRole}.temporaryAccessEndTime`, ">", new Date());
+ })
+ .where(`${TableName.Membership}.scopeProjectId`, pkiSync.projectId);
+
+ void query
+ .where(`${TableName.Membership}.scope`, RESOURCE_SCOPE)
+ .where(`${TableName.Membership}.scopeResourceType`, ResourceType.CertificateApplication)
+ .where(`${TableName.Membership}.scopeResourceId`, pkiSync.applicationId);
+
+ const rows = await query.select(
+ `${TableName.Membership}.actorUserId`,
+ `${TableName.UserGroupMembership}.userId as groupUserId`
+ );
+
+ return [
+ ...new Set(
+ rows
+ .map(
+ (row) =>
+ (row as { actorUserId?: string; groupUserId?: string }).actorUserId ??
+ (row as { groupUserId?: string }).groupUserId
+ )
+ .filter(Boolean)
+ )
+ ] as string[];
} catch (error) {
- throw new DatabaseError({ error, name: "Clear reported health check failure - PKI Sync" });
+ throw new DatabaseError({ error, name: "Find PKI sync failure notification recipients" });
}
};
@@ -410,8 +429,8 @@ export const pkiSyncDALFactory = (db: TDbClient) => {
return {
...pkiSyncOrm,
recordHealthCheckOutcome,
- reportHealthCheckFailure,
- clearReportedHealthCheckFailure,
+ recordHealthCheckSkipped,
+ findFailureNotificationRecipients,
findPkiSyncsWithHealthCheckCommand,
findByProjectId,
findByProjectIdWithSubscribers,
diff --git a/backend/src/services/pki-sync/pki-sync-enums.ts b/backend/src/services/pki-sync/pki-sync-enums.ts
index 68cc4ee025..16344a90c9 100644
--- a/backend/src/services/pki-sync/pki-sync-enums.ts
+++ b/backend/src/services/pki-sync/pki-sync-enums.ts
@@ -26,6 +26,12 @@ export enum PkiSyncAction {
RemoveCertificates = "remove-certificates"
}
+export enum PkiSyncFailureKind {
+ HealthCheck = "health-check",
+ Sync = "sync",
+ PostSyncCommand = "post-sync-command"
+}
+
export const PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT = 3;
export const PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S = 15 * 60;
diff --git a/backend/src/services/pki-sync/pki-sync-failure-notification-fns.ts b/backend/src/services/pki-sync/pki-sync-failure-notification-fns.ts
new file mode 100644
index 0000000000..1cf4b48ce7
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-failure-notification-fns.ts
@@ -0,0 +1,66 @@
+import { logger } from "@app/lib/logger";
+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { NotificationType } from "@app/services/notification/notification-types";
+import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+
+import { TPkiSyncDALFactory } from "./pki-sync-dal";
+import { PkiSyncFailureKind } from "./pki-sync-enums";
+
+const FAILURE_TITLES: Record<PkiSyncFailureKind, string> = {
+ [PkiSyncFailureKind.HealthCheck]: "Certificate sync health check failed",
+ [PkiSyncFailureKind.Sync]: "Certificate sync failed",
+ [PkiSyncFailureKind.PostSyncCommand]: "Certificate sync post-sync command failed"
+};
+
+export const notifyPkiSyncFailure = async (
+ {
+ pkiSync,
+ kind,
+ message
+ }: {
+ pkiSync: { id: string; name: string; projectId: string; applicationId?: string | null };
+ kind: PkiSyncFailureKind;
+ message: string;
+ },
+ deps: {
+ pkiSyncDAL: Pick<TPkiSyncDALFactory, "findFailureNotificationRecipients">;
+ projectDAL: Pick<TProjectDALFactory, "findById">;
+ pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
+ }
+) => {
+ const { applicationId } = pkiSync;
+ if (!applicationId) return;
+
+ try {
+ const [recipients, project, application] = await Promise.all([
+ deps.pkiSyncDAL.findFailureNotificationRecipients({ projectId: pkiSync.projectId, applicationId }),
+ deps.projectDAL.findById(pkiSync.projectId),
+ deps.pkiApplicationDAL.findById(applicationId)
+ ]);
+
+ if (!recipients.length || !project || !application) {
+ logger.warn(
+ `PKI sync failure had no notification recipients [syncId=${pkiSync.id}] [kind=${kind}] [applicationId=${applicationId}]`
+ );
+ return;
+ }
+
+ const basePath = `/organizations/${project.orgId}/projects/cert-manager/${pkiSync.projectId}`;
+ const link = `${basePath}/applications/${encodeURIComponent(application.name)}?selectedTab=syncs`;
+
+ await deps.notificationService.createUserNotifications(
+ recipients.map((userId) => ({
+ userId,
+ orgId: project.orgId,
+ type: NotificationType.PKI_SYNC_FAILED,
+ title: FAILURE_TITLES[kind],
+ body: `**${pkiSync.name}**: ${message}`,
+ link
+ }))
+ );
+ } catch (err) {
+ logger.error(err, `Failed to notify PKI sync failure [syncId=${pkiSync.id}] [kind=${kind}]`);
+ }
+};
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.ts
index 2f8dcea260..a5e3ea91af 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
@@ -11,6 +11,7 @@ import {
buildHealthCheckFailureMessageFor,
buildHealthCheckFailureSyncResult,
didHealthCheckFail,
+ MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT,
normalizeNewHealthCheckCommand,
runHealthCheckCommand,
SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT
@@ -292,7 +293,7 @@ describe("buildHealthCheckCommandPlan with nothing linked to the sync", () => {
});
});
-describe("the scheduled check owns a prefix distinct from a sync run's", () => {
+describe("the subject says who ran the check", () => {
const failure = {
status: PkiSyncStatus.Failed as const,
exitCode: 3,
@@ -300,34 +301,19 @@ describe("the scheduled check owns a prefix distinct from a sync run's", () => {
failureDetail: "nginx is down"
};
- test("a run's blocked healthCheck does not match the scheduled prefix, so a later check cannot clear it", () => {
+ test("a sync run's gate check is labelled plainly, not as a scheduled run", () => {
const fromRun = buildHealthCheckCommandFailureMessage(failure);
expect(fromRun.startsWith(SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT)).toBe(false);
+ expect(fromRun).toContain("nginx is down");
});
- test("the scheduled check's own message matches, so it can take over and clear it", () => {
- const fromSchedule = buildHealthCheckFailureMessageFor(SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT, failure);
- expect(fromSchedule.startsWith(SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT)).toBe(true);
- expect(fromSchedule).toContain("nginx is down");
- });
-});
-
-describe("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 = "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 },
- {
- status: PkiSyncStatus.Failed as const,
- durationMs: 15004,
- error: "command timed out after 15s",
- timedOut: true
- }
- ];
+ test("the scheduled and manual checks are told apart by their subject", () => {
+ const scheduled = buildHealthCheckFailureMessageFor(SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT, failure);
+ const manual = buildHealthCheckFailureMessageFor(MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT, failure);
- shapes.forEach((shape) => expect(buildHealthCheckCommandFailureMessage(shape).startsWith(prefix)).toBe(true));
- expect("2 certificate(s) failed to sync to the destination".startsWith(prefix)).toBe(false);
+ expect(scheduled.startsWith(SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT)).toBe(true);
+ expect(manual.startsWith(MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT)).toBe(true);
+ expect(scheduled).not.toBe(manual);
});
});
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.ts
index 32de33d285..b3da0b5734 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
@@ -39,18 +39,21 @@ export const applyHealthCheckCommandUpdate = (
): Record<string, unknown> =>
applyHostCommandOptionUpdate(resolvedSyncOptions, HEALTH_CHECK_COMMAND_OPTION_KEY, storedCommand);
-export const assertHealthCheckCommandIsTestable = (syncOptions: Record<string, unknown>): string => {
+export const assertHealthCheckCommandIsTestable = (
+ syncOptions: Record<string, unknown>,
+ canResolveCertificates = false
+): string => {
const command = getHealthCheckCommand(syncOptions);
if (!command) {
throw new BadRequestError({ message: "Enter a health check command to test." });
}
const certificateVariables = findCertificateDependentHostCommandVariables(command);
- if (certificateVariables.length > 0) {
+ if (certificateVariables.length > 0 && !canResolveCertificates) {
throw new BadRequestError({
message: `A test cannot resolve ${formatHostCommandVariables(
certificateVariables
- )} because no certificate is linked yet. Use {{certificateDirectory}} to test, or save the sync and run the health check from its actions menu.`
+ )} because this sync has no certificates to resolve them against. Link at least one certificate to the sync, or use {{certificateDirectory}} instead.`
});
}
@@ -58,7 +61,7 @@ export const assertHealthCheckCommandIsTestable = (syncOptions: Record<string, u
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.`
+ ])} because the export password is only generated when a saved sync delivers a certificate. Run the health check on a saved sync instead.`
});
}
@@ -133,11 +136,6 @@ export const SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT = "Scheduled health check";
export const MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT = "Manual health check";
-export const HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS = [
- SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT,
- MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT
-];
-
export const didHealthCheckFail = (result: THealthCheckCommandResult | undefined): boolean =>
result?.status === PkiSyncStatus.Failed;
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.ts
index 674baceb3e..c5648f2c56 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
@@ -12,6 +12,8 @@ import { decryptAppConnectionCredentials } from "@app/services/app-connection/ap
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 { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";
@@ -28,24 +30,22 @@ import {
PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S,
PKI_SYNC_CONNECTION_LOCK_RETRY,
PkiSync,
+ PkiSyncFailureKind,
PkiSyncStatus
} from "./pki-sync-enums";
+import { PkiSyncError } from "./pki-sync-errors";
+import { notifyPkiSyncFailure } from "./pki-sync-failure-notification-fns";
import { PkiSyncFns, truncateSyncMessage } from "./pki-sync-fns";
import {
assertHealthCheckCommandIsTestable,
buildHealthCheckFailureMessageFor,
didHealthCheckFail,
getHealthCheckCommand,
- HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS,
MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT,
SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT,
THealthCheckCommandResult
} from "./pki-sync-health-check-command-fns";
-import {
- commandNeedsCertificateData,
- findCertificateDependentHostCommandVariables,
- formatHostCommandVariables
-} from "./pki-sync-host-command-fns";
+import { commandNeedsCertificateData, HostCommandFailure } from "./pki-sync-host-command-fns";
import { TCertificateMap, THealthCheckTarget, TPkiSyncRaw } from "./pki-sync-types";
const ENQUEUE_CHUNK_SIZE = 200;
@@ -65,11 +65,11 @@ type TPkiSyncHealthCheckQueueFactoryDep = {
queueService: Pick<TQueueServiceFactory, "queue" | "start">;
pkiSyncDAL: Pick<
TPkiSyncDALFactory,
+ | "findFailureNotificationRecipients"
| "findPkiSyncsWithHealthCheckCommand"
| "transaction"
| "recordHealthCheckOutcome"
- | "reportHealthCheckFailure"
- | "clearReportedHealthCheckFailure"
+ | "recordHealthCheckSkipped"
| "findById"
>;
keyStore: Pick<TKeyStoreFactory, "acquireLock" | "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
@@ -86,12 +86,26 @@ type TPkiSyncHealthCheckQueueFactoryDep = {
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;
certificateSyncDAL: TCertificateSyncDALFactory;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
+ pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
class HealthCheckBusyError extends Error {}
+export enum HealthCheckSkipReason {
+ SyncGone = "sync-gone",
+ CommandCleared = "command-cleared",
+ SyncInProgress = "sync-in-progress",
+ NoCertificateData = "no-certificate-data",
+ NotSupported = "not-supported"
+}
+
+type THealthCheckOutcome =
+ | { result: THealthCheckCommandResult; skipped?: never }
+ | { result?: never; skipped: HealthCheckSkipReason };
+
export type TPkiSyncHealthCheckQueueFactory = ReturnType<typeof pkiSyncHealthCheckQueueFactory>;
export const pkiSyncHealthCheckQueueFactory = ({
@@ -109,6 +123,8 @@ export const pkiSyncHealthCheckQueueFactory = ({
certificateAuthorityCertDAL,
certificateSyncDAL,
auditLogService,
+ notificationService,
+ pkiApplicationDAL,
gatewayV2Service,
gatewayPoolService
}: TPkiSyncHealthCheckQueueFactoryDep) => {
@@ -185,6 +201,40 @@ export const pkiSyncHealthCheckQueueFactory = ({
return certificateMap;
};
+ const $certificatesForTest = async (args: {
+ projectId: string;
+ syncId?: string;
+ certificateIds?: string[];
+ syncOptions: Record<string, unknown>;
+ }): Promise<TCertificateMap> => {
+ const command = getHealthCheckCommand(args.syncOptions);
+ if (!command || !commandNeedsCertificateData(command)) return {};
+
+ if (args.syncId) {
+ const pkiSync = await pkiSyncDAL.findById(args.syncId);
+ return pkiSync ? $certificatesForCheck(pkiSync, command) : {};
+ }
+
+ if (!args.certificateIds?.length) return {};
+
+ const { certificateMap } = await buildCertificateMap(
+ { id: "", projectId: args.projectId, subscriberId: null, syncOptions: args.syncOptions } as TPkiSyncRaw,
+ {
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ certificateAuthorityDAL,
+ certificateAuthorityCertDAL,
+ certificateSyncDAL,
+ projectDAL,
+ kmsService
+ },
+ args.certificateIds
+ );
+
+ return certificateMap;
+ };
+
const $recordCheckResult = async (
pkiSync: TPkiSyncRaw,
result: THealthCheckCommandResult,
@@ -192,24 +242,18 @@ export const pkiSyncHealthCheckQueueFactory = ({
messageSubject: string
) => {
if (!didHealthCheckFail(result)) {
- const cleared = await pkiSyncDAL.transaction(async (tx) => {
- await pkiSyncDAL.recordHealthCheckOutcome(
- pkiSync.id,
- { status: PkiSyncStatus.Succeeded, message: null, ranAt: new Date() },
- tx
- );
-
- return pkiSyncDAL.clearReportedHealthCheckFailure(pkiSync.id, HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS, tx);
+ await pkiSyncDAL.recordHealthCheckOutcome(pkiSync.id, {
+ status: PkiSyncStatus.Succeeded,
+ message: null,
+ ranAt: new Date()
});
- if (cleared) {
- logger.info(
- `cron[${CronJobName.PkiSyncHealthCheck}]: host recovered, cleared the reported failure [syncId=${pkiSync.id}]`
- );
- }
return;
}
- if (result.exitCode === undefined && !isFinalAttempt) {
+ const neverRan =
+ result.failure === HostCommandFailure.Rejected || result.failure === HostCommandFailure.Unreachable;
+
+ if (neverRan && !isFinalAttempt) {
throw new Error(`Health check could not reach the host: ${result.error ?? "unknown error"}`);
}
@@ -217,20 +261,18 @@ export const pkiSyncHealthCheckQueueFactory = ({
`cron[${CronJobName.PkiSyncHealthCheck}]: health check failed [syncId=${pkiSync.id}] [destination=${pkiSync.destination}] [projectId=${pkiSync.projectId}]`
);
- const failureMessage = truncateSyncMessage(buildHealthCheckFailureMessageFor(messageSubject, result));
+ const message = truncateSyncMessage(buildHealthCheckFailureMessageFor(messageSubject, result));
- const reported = await pkiSyncDAL.transaction(async (tx) => {
- await pkiSyncDAL.recordHealthCheckOutcome(
- pkiSync.id,
- { status: PkiSyncStatus.Failed, message: failureMessage, ranAt: new Date() },
- tx
- );
-
- return pkiSyncDAL.reportHealthCheckFailure(pkiSync.id, failureMessage, HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS, tx);
+ await pkiSyncDAL.recordHealthCheckOutcome(pkiSync.id, {
+ status: PkiSyncStatus.Failed,
+ message,
+ ranAt: new Date()
});
- if (!reported) {
- logger.info(
- `cron[${CronJobName.PkiSyncHealthCheck}]: sync already failed to deliver, kept its reason [syncId=${pkiSync.id}]`
+
+ if (messageSubject === SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT) {
+ await notifyPkiSyncFailure(
+ { pkiSync, kind: PkiSyncFailureKind.HealthCheck, message },
+ { pkiSyncDAL, projectDAL, pkiApplicationDAL, notificationService }
);
}
};
@@ -240,11 +282,11 @@ export const pkiSyncHealthCheckQueueFactory = ({
isFinalAttempt: boolean,
messageSubject: string = SCHEDULED_HEALTH_CHECK_MESSAGE_SUBJECT,
auditLogInfo?: AuditLogInfo
- ): Promise<THealthCheckCommandResult | undefined> => {
+ ): Promise<THealthCheckOutcome> => {
const pkiSync = await pkiSyncDAL.findById(syncId);
if (!pkiSync) {
logger.info(`cron[${CronJobName.PkiSyncHealthCheck}]: sync is gone, skipping [syncId=${syncId}]`);
- return;
+ return { skipped: HealthCheckSkipReason.SyncGone };
}
const command = getHealthCheckCommand(pkiSync.syncOptions);
@@ -252,14 +294,14 @@ export const pkiSyncHealthCheckQueueFactory = ({
logger.info(
`cron[${CronJobName.PkiSyncHealthCheck}]: health check command was cleared, skipping [syncId=${syncId}]`
);
- return;
+ return { skipped: HealthCheckSkipReason.CommandCleared };
}
if (pkiSync.syncStatus === PkiSyncStatus.Running) {
logger.info(
`cron[${CronJobName.PkiSyncHealthCheck}]: a sync is delivering to this host, skipping [syncId=${syncId}]`
);
- return undefined;
+ return { skipped: HealthCheckSkipReason.SyncInProgress };
}
const pkiSyncWithCredentials = await hydratePkiSyncCredentials({
@@ -277,7 +319,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
.catch(() => null);
if (!lock) {
logger.info(`cron[${CronJobName.PkiSyncHealthCheck}]: a sync is already running, skipping [syncId=${syncId}]`);
- return undefined;
+ return HealthCheckSkipReason.SyncInProgress;
}
try {
@@ -286,7 +328,11 @@ export const pkiSyncHealthCheckQueueFactory = ({
gatewayV2Service,
gatewayPoolService
});
- if (!checkResult) return undefined;
+ if (!checkResult) {
+ return commandNeedsCertificateData(command)
+ ? HealthCheckSkipReason.NoCertificateData
+ : HealthCheckSkipReason.NotSupported;
+ }
await $recordCheckResult(pkiSync, checkResult, isFinalAttempt, messageSubject);
return checkResult;
@@ -295,7 +341,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
}
});
- if (!result) return undefined;
+ if (typeof result === "string") return { skipped: result };
await auditLogService.createAuditLog({
...(auditLogInfo ?? { actor: { type: ActorType.PLATFORM, metadata: {} } }),
@@ -312,42 +358,44 @@ export const pkiSyncHealthCheckQueueFactory = ({
}
});
- return result;
+ return { result };
+ };
+
+ const SKIP_MESSAGES: Record<HealthCheckSkipReason, string> = {
+ [HealthCheckSkipReason.SyncGone]: "This sync no longer exists.",
+ [HealthCheckSkipReason.CommandCleared]: "This sync no longer has a health check configured.",
+ [HealthCheckSkipReason.SyncInProgress]:
+ "The health check did not run because a sync is already delivering to this host. Try again in a moment.",
+ [HealthCheckSkipReason.NoCertificateData]:
+ "The health check did not run because it uses a variable that names a certificate and this sync has none linked. Link a certificate, or use {{certificateDirectory}}.",
+ [HealthCheckSkipReason.NotSupported]: "Health checks are not supported for this destination."
};
const runHealthCheckNow = async (syncId: string, auditLogInfo?: AuditLogInfo) => {
- let result: THealthCheckCommandResult | undefined;
+ let outcome;
try {
- result = await $processHealthCheck(syncId, true, MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT, auditLogInfo);
+ outcome = await $processHealthCheck(syncId, true, MANUAL_HEALTH_CHECK_MESSAGE_SUBJECT, auditLogInfo);
} catch (error) {
- $rethrowContentionAsBadRequest(error);
+ return $rethrowContentionAsBadRequest(error);
}
- if (result) return result;
-
- const pkiSync = await pkiSyncDAL.findById(syncId);
- const command = getHealthCheckCommand(pkiSync?.syncOptions);
- if (command && commandNeedsCertificateData(command)) {
- throw new BadRequestError({
- message: `This health check uses ${formatHostCommandVariables(
- findCertificateDependentHostCommandVariables(command)
- )}, which cannot be resolved while no certificate is linked to the sync. Link a certificate, or use {{certificateDirectory}}.`
- });
- }
+ if (outcome.result) return outcome.result;
- throw new BadRequestError({
- message: "The health check did not run because a sync is already in progress. Try again in a moment."
- });
+ throw new BadRequestError({ message: SKIP_MESSAGES[outcome.skipped] });
};
const testHealthCheckCommand = async (args: {
destination: PkiSync;
connectionId: string;
+ projectId: string;
+ syncId?: string;
+ certificateIds?: string[];
destinationConfig: Record<string, unknown>;
syncOptions: Record<string, unknown>;
}) => {
- assertHealthCheckCommandIsTestable(args.syncOptions);
+ const linkedCertificates = await $certificatesForTest(args);
+ assertHealthCheckCommandIsTestable(args.syncOptions, Object.keys(linkedCertificates).length > 0);
const connection = await appConnectionDAL.findById(args.connectionId);
if (!connection) {
@@ -379,15 +427,14 @@ export const pkiSyncHealthCheckQueueFactory = ({
};
return $withConnectionHostAccess(connection.id, async () => {
- const result = await PkiSyncFns.runHealthCheck(
- target,
- {},
- {
- certificateSyncDAL,
- gatewayV2Service,
- gatewayPoolService
- }
- );
+ const result = await PkiSyncFns.runHealthCheck(target, linkedCertificates, {
+ certificateSyncDAL,
+ gatewayV2Service,
+ gatewayPoolService
+ }).catch((err) => {
+ if (err instanceof PkiSyncError) throw new BadRequestError({ message: err.message });
+ throw err;
+ });
if (!result) {
throw new BadRequestError({
message: "Health checks are not supported for this destination."
@@ -404,13 +451,17 @@ export const pkiSyncHealthCheckQueueFactory = ({
async (job) => {
const isFinalAttempt = job.attemptsStarted >= (job.opts.attempts ?? JOB_ATTEMPTS);
- await $processHealthCheck(job.data.syncId, isFinalAttempt).catch((err: unknown) => {
+ const outcome = await $processHealthCheck(job.data.syncId, isFinalAttempt).catch((err: unknown) => {
logger.error(
{ err, syncId: job.data.syncId },
`cron[${CronJobName.PkiSyncHealthCheck}]: check could not be run [syncId=${job.data.syncId}] [attempt=${job.attemptsStarted}]`
);
throw err;
});
+
+ if (outcome.skipped && isFinalAttempt) {
+ await pkiSyncDAL.recordHealthCheckSkipped(job.data.syncId, SKIP_MESSAGES[outcome.skipped]);
+ }
},
{ concurrency: WORKER_CONCURRENCY, limiter: { max: RATE_LIMIT_MAX, duration: RATE_LIMIT_DURATION_MS } }
);
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
index bf08477dee..15a69a0768 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
@@ -308,6 +308,13 @@ export const runHostCommand = async (args: {
}
};
+const NETWORK_ADDRESS_PATTERN = new RE2(
+ "\\b(?:\\d{1,3}\\.){3}\\d{1,3}(?::\\d+)?\\b|\\b[a-zA-Z0-9.-]+:\\d{2,5}\\b",
+ "g"
+);
+
+const redactNetworkAddresses = (text: string): string => text.replace(NETWORK_ADDRESS_PATTERN, "[address]");
+
const hostCommandMessageSubject = (kind: HostCommandKind): string => sentenceCase(kind);
export const buildHostCommandFailureMessage = (
@@ -323,7 +330,7 @@ export const buildHostCommandFailureMessage = (
}
if (result.failure === HostCommandFailure.Rejected && result.error) {
- return `${subject} could not run: ${truncate(result.error, MAX_FAILURE_DETAIL_CHARS)}`;
+ return `${subject} could not run: ${truncate(redactNetworkAddresses(result.error), MAX_FAILURE_DETAIL_CHARS)}`;
}
return `${subject} could not run: the destination host could not be reached`;
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 5cae8d7a18..69ee05dd35 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
@@ -476,3 +476,18 @@ describe("buildPostSyncCommandFailureMessage timeout wording", () => {
).toBe("Post-sync command did not finish within its 30s limit");
});
});
+
+describe("a rejected command's reason is surfaced without internal addressing", () => {
+ test("keeps the actionable reason and redacts the host and port", () => {
+ const message = buildPostSyncCommandFailureMessage({
+ status: PkiSyncStatus.Failed,
+ failure: HostCommandFailure.Rejected,
+ durationMs: 94,
+ error: "WinRM gateway operation failed: TLS connection error: connect ECONNREFUSED 192.168.0.50:8443"
+ });
+
+ expect(message).not.toContain("192.168.0.50");
+ expect(message).not.toContain("8443");
+ expect(message).toContain("TLS connection error");
+ });
+});
diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.ts
index bbdcb21723..d5c0d5fffc 100644
--- a/backend/src/services/pki-sync/pki-sync-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-queue.ts
@@ -14,6 +14,8 @@ import { highCardinalityMeter } from "@app/lib/telemetry/metrics";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
import { hydratePkiSyncCredentials } from "@app/services/pki-sync/pki-sync-credentials-fns";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
@@ -33,9 +35,11 @@ import {
PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S,
PKI_SYNC_CONNECTION_LOCK_RETRY,
+ PkiSyncFailureKind,
PkiSyncStatus
} from "./pki-sync-enums";
import { PkiSyncError } from "./pki-sync-errors";
+import { notifyPkiSyncFailure } from "./pki-sync-failure-notification-fns";
import {
enterprisePkiSyncCheck,
getPkiSyncProviderCapabilities,
@@ -75,8 +79,13 @@ type TPkiSyncQueueFactoryDep = {
>;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
keyStore: Pick<TKeyStoreFactory, "acquireLock" | "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
- pkiSyncDAL: Pick<TPkiSyncDALFactory, "findById" | "find" | "updateById" | "deleteById" | "update">;
+ pkiSyncDAL: Pick<
+ TPkiSyncDALFactory,
+ "findById" | "find" | "updateById" | "deleteById" | "update" | "findFailureNotificationRecipients"
+ >;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
+ pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
projectDAL: TProjectDALFactory;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
certificateDAL: TCertificateDALFactory;
@@ -113,6 +122,8 @@ export const pkiSyncQueueFactory = ({
keyStore,
pkiSyncDAL,
auditLogService,
+ notificationService,
+ pkiApplicationDAL,
projectDAL,
licenseService,
certificateDAL,
@@ -467,6 +478,17 @@ export const pkiSyncQueueFactory = ({
});
if (isSynced || isFinalAttempt) {
+ if (!fullySynced) {
+ let failureKind = PkiSyncFailureKind.Sync;
+ if (didHealthCheckFail(healthCheckResult)) failureKind = PkiSyncFailureKind.HealthCheck;
+ else if (postSyncCommandFailed) failureKind = PkiSyncFailureKind.PostSyncCommand;
+
+ await notifyPkiSyncFailure(
+ { pkiSync, kind: failureKind, message: syncMessage ?? "The sync did not complete." },
+ { pkiSyncDAL, projectDAL, pkiApplicationDAL, notificationService }
+ );
+ }
+
await pkiSyncDAL.updateById(pkiSync.id, {
syncStatus,
lastSyncJobId: job.id,
@@ -703,6 +725,10 @@ export const pkiSyncQueueFactory = ({
const { failedToAcquireLockCount = 0, ...rest } = job.data as TQueuePkiSyncSyncCertificatesByIdDTO;
if (failedToAcquireLockCount < REQUEUE_LIMIT) {
+ const current = await pkiSyncDAL.findById(syncId);
+ if (current?.syncStatus !== PkiSyncStatus.Running) {
+ await pkiSyncDAL.updateById(syncId, { syncStatus: PkiSyncStatus.Pending, lastSyncMessage: null });
+ }
await queuePkiSyncSyncCertificatesById({ ...rest, failedToAcquireLockCount: failedToAcquireLockCount + 1 });
return;
}
diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.ts
index 9e31bb7692..03c68e0593 100644
--- a/backend/src/services/pki-sync/pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts
@@ -110,5 +110,5 @@ 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()
+ certificateIds: z.array(z.string().uuid()).max(100).optional()
});
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index 14f0f3c139..ab63869ec4 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -35,9 +35,7 @@ import {
} from "./pki-sync-fns";
import {
applyHealthCheckCommandUpdate,
- assertHealthCheckCommandIsTestable,
getHealthCheckCommand,
- HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS,
normalizeNewHealthCheckCommand,
toHealthCheckApiResult
} from "./pki-sync-health-check-command-fns";
@@ -86,13 +84,7 @@ const getDestinationAppType = (destination: PkiSync): AppConnection => {
type TPkiSyncServiceFactoryDep = {
pkiSyncDAL: Pick<
TPkiSyncDALFactory,
- | "clearReportedHealthCheckFailure"
- | "findById"
- | "findByProjectIdWithSubscribers"
- | "findByNameAndProjectId"
- | "create"
- | "updateById"
- | "deleteById"
+ "findById" | "findByProjectIdWithSubscribers" | "findByNameAndProjectId" | "create" | "updateById" | "deleteById"
>;
certificateDAL: Pick<TCertificateDALFactory, "findActiveCertificatesByIds">;
certificateSyncDAL: Pick<
@@ -669,10 +661,6 @@ export const pkiSyncServiceFactory = ({
: {})
});
- if (isHealthCheckBeingCleared) {
- await pkiSyncDAL.clearReportedHealthCheckFailure(id, HEALTH_CHECK_OWNED_MESSAGE_SUBJECTS);
- }
-
return updatedPkiSync as TPkiSync;
};
@@ -903,6 +891,7 @@ export const pkiSyncServiceFactory = ({
connectionId: string;
applicationId?: string;
syncId?: string;
+ certificateIds?: string[];
destinationConfig: Record<string, unknown>;
syncOptions: Record<string, unknown>;
projectId: string;
@@ -918,7 +907,14 @@ export const pkiSyncServiceFactory = ({
actor
);
- const command = assertHealthCheckCommandIsTestable(args.syncOptions);
+ const command = getHealthCheckCommand(args.syncOptions);
+ if (!command) {
+ throw new BadRequestError({ message: "Enter a health check command to test." });
+ }
+
+ if (args.certificateIds?.length) {
+ await validateCertificatesForSync(args.certificateIds, args.projectId, args.applicationId);
+ }
const connection = await appConnectionService.connectAppConnectionById(
getDestinationAppType(args.destination),
@@ -931,6 +927,9 @@ export const pkiSyncServiceFactory = ({
const result = await pkiSyncHealthCheckQueue.testHealthCheckCommand({
destination: args.destination,
connectionId: args.connectionId,
+ syncId: args.syncId,
+ certificateIds: args.certificateIds,
+ projectId: args.projectId,
destinationConfig: args.destinationConfig,
syncOptions: args.syncOptions
});
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 1ca0e386c1..885bceeb42 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 variables
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 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.
+ A failing daily check records the failure and its reason against the sync's health check, shown as Last Checked on the sync's page, and notifies the application's administrators. It does not change the sync's own status, which continues to report the last delivery. 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.mdx
index 1356f14e67..3cdbf81f0a 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 late
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 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.
+ A failing daily check records the failure and its reason against the sync's health check, shown as Last Checked on the sync's page, and notifies the application's administrators. It does not change the sync's own status, which continues to report the last delivery. 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.mdx
index 66b737f249..8890aec3ab 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,7 +12,7 @@ Each value is inserted already quoted for the target's shell, so write `{{certif
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.
-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.
+A variable that names a certificate resolves against the certificates linked to the sync, so **Test check** works once at least one is selected and tells you if none is. `{{pkcs12Password}}` is different: the export password only exists once a saved sync delivers a certificate, so a test always rejects it.
<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/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
index 6defb9fccc..a8cfda38dc 100644
--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
@@ -83,10 +83,10 @@ const STEP_META: Record<
},
hostCommands: {
short: "Commands on the host",
- subtitle: "Optionally check the host before the sync, and act on it afterward.",
+ subtitle: "Check the host before the sync, and run a command after it.",
rightLabel: "COMMANDS",
rightDescription:
- "The health check runs first and stops the sync if the host is not ready, so a bad host never receives a certificate. The post-sync command runs afterward, once the run's files are in place, so a service can reload and pick up the new certificate. It only runs when the sync delivers a file. Either command failing marks the sync failed."
+ "The health check runs first. If the host is not ready, the sync stops and no certificate is delivered.\n\nThe post-sync command runs after the certificates are written, so a service can reload and pick up the new one. It only runs when the sync delivers a file. If either command fails, the sync is marked failed."
},
details: {
short: "Name and description",
@@ -136,17 +136,6 @@ const getFormTabs = (
});
}
- if (canRunHostCommands) {
- baseTabs.push({
- name: "Commands",
- key: "hostCommands",
- fields: [
- "syncOptions.healthCheckCommand",
- "syncOptions.postSyncCommand"
- ] as FieldPath<TPkiSyncForm>[]
- });
- }
-
baseTabs.push(
{
name: "Details",
@@ -157,10 +146,22 @@ const getFormTabs = (
name: "Certificates",
key: "certificates",
fields: ["certificateIds"] as FieldPath<TPkiSyncForm>[]
- },
- { name: "Review", key: "review", fields: [] as FieldPath<TPkiSyncForm>[] }
+ }
);
+ if (canRunHostCommands) {
+ baseTabs.push({
+ name: "Commands",
+ key: "hostCommands",
+ fields: [
+ "syncOptions.healthCheckCommand",
+ "syncOptions.postSyncCommand"
+ ] as FieldPath<TPkiSyncForm>[]
+ });
+ }
+
+ baseTabs.push({ name: "Review", key: "review", fields: [] as FieldPath<TPkiSyncForm>[] });
+
return baseTabs;
};
@@ -412,9 +413,11 @@ export const CreatePkiSyncForm = ({
/>
</div>
<p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>
- <p className="mt-2 text-sm leading-relaxed text-muted">
- {currentDetail.rightDescription}
- </p>
+ {currentDetail.rightDescription.split("\n\n").map((paragraph) => (
+ <p key={paragraph} className="mt-2 text-sm leading-relaxed text-muted">
+ {paragraph}
+ </p>
+ ))}
</div>
</aside>
</div>
diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
index dac3dbed96..0349d31952 100644
--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
@@ -96,7 +96,7 @@ const getFormSteps = (destination: PkiSync, canRunHostCommands: boolean): FormSt
subtitle: "Optionally check the host before the sync, and act on it afterward.",
rightLabel: "COMMANDS",
rightDescription:
- "The health check runs first and stops the sync if the host is not ready, so a bad host never receives a certificate. The post-sync command runs afterward, once the run's files are in place, so a service can reload and pick up the new certificate. It only runs when the sync delivers a file. Either command failing marks the sync failed."
+ "The health check runs first. If the host is not ready, the sync stops and no certificate is delivered.\n\nThe post-sync command runs after the certificates are written, so a service can reload and pick up the new one. It only runs when the sync delivers a file. If either command fails, the sync is marked failed."
});
}
@@ -279,9 +279,11 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }
/>
</div>
<p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>
- <p className="mt-2 text-sm leading-relaxed text-muted">
- {currentStep.rightDescription}
- </p>
+ {currentStep.rightDescription.split("\n\n").map((paragraph) => (
+ <p key={paragraph} className="mt-2 text-sm leading-relaxed text-muted">
+ {paragraph}
+ </p>
+ ))}
</div>
</aside>
</div>
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx
index 627551d409..8efaf26ab0 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx
@@ -43,8 +43,9 @@ export const PkiSyncHealthCheckCommandFields = ({
connectionId,
applicationId: applicationId ?? undefined,
syncId,
+ certificateIds: syncId ? undefined : watch("certificateIds"),
destinationConfig: (destinationConfig ?? {}) as Record<string, unknown>,
- syncOptions: { healthCheckCommand: command }
+ syncOptions: { ...(watch("syncOptions") ?? {}), healthCheckCommand: command }
});
const passed = result.status === PkiSyncStatus.Succeeded;
createNotification({
@@ -74,7 +75,7 @@ export const PkiSyncHealthCheckCommandFields = ({
one in quotes yourself.
</>
}
- description="Runs before any certificate is written. A non-zero exit stops the sync, so nothing is delivered to a host that is not ready. Also runs once a day on its own, so you hear about a host that went bad before the next renewal does. Capped at 15 seconds."
+ description="Checks the host before Infisical writes any certificate. If the command fails, or does not finish within 15 seconds, the sync stops and nothing is delivered. Infisical also runs this check once a day, so a broken host surfaces before a renewal reaches it."
noPermissionDescription="You do not have permission to set a health check on this sync. Ask an administrator to change it."
action={
canEditCommand !== false && (
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx
index f78b2bca56..41969a818a 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx
@@ -34,7 +34,7 @@ export const PkiSyncPostSyncCommandFields = ({ destination, canEditCommand }: Pr
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."
+ description="Runs on the host after a certificate is delivered, usually to reload the service that uses it. Runs once per sync that writes a file, using the sync's own account. If it fails, or does not finish within 30 seconds, 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/hooks/api/notifications/types.ts b/frontend/src/hooks/api/notifications/types.ts
index 6a4e3f31a4..e2a6e57f00 100644
--- a/frontend/src/hooks/api/notifications/types.ts
+++ b/frontend/src/hooks/api/notifications/types.ts
@@ -17,6 +17,7 @@ export enum NotificationType {
PROJECT_ACCESS_REQUEST = "project-access-request",
PROJECT_INVITATION = "project-invitation",
SECRET_SYNC_FAILED = "secret-sync-failed",
+ PKI_SYNC_FAILED = "pki-sync-failed",
GATEWAY_HEALTH_ALERT = "gateway-health-alert",
RELAY_HEALTH_ALERT = "relay-health-alert",
APPROVAL_REQUIRED = "approval-required",
diff --git a/frontend/src/hooks/api/pkiSyncs/mutations.tsx b/frontend/src/hooks/api/pkiSyncs/mutations.tsx
index 8a56f493f1..9edfe70280 100644
--- a/frontend/src/hooks/api/pkiSyncs/mutations.tsx
+++ b/frontend/src/hooks/api/pkiSyncs/mutations.tsx
@@ -78,6 +78,7 @@ export const useTestPkiSyncHealthCheck = () => {
connectionId,
applicationId,
syncId,
+ certificateIds,
destinationConfig,
syncOptions
}: {
@@ -85,12 +86,13 @@ export const useTestPkiSyncHealthCheck = () => {
connectionId: string;
applicationId?: string;
syncId?: string;
+ certificateIds?: 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, destinationConfig, syncOptions }
+ { connectionId, applicationId, syncId, certificateIds, destinationConfig, syncOptions }
);
return data.healthCheck;
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsx
index 464ab59f4e..c44dac081d 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCommandsSection.tsx
@@ -45,7 +45,7 @@ export const PkiSyncCommandsSection = ({ pkiSync }: Props) => {
<Separator className="mt-4" />
<Accordion type="multiple" variant="ghost">
<AccordionItem value="commands">
- <AccordionTrigger>Commands</AccordionTrigger>
+ <AccordionTrigger className="py-4">Commands</AccordionTrigger>
<AccordionContent>
<DetailGroup>
{canRunHealthCheck && (
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx
index 6d971c11ea..f078f68f9e 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx
@@ -24,10 +24,10 @@ export const PkiSyncOptionsSection = ({ pkiSync }: Props) => {
return (
<>
- <Separator className="mt-4" />
+ <Separator />
<Accordion type="multiple" variant="ghost">
<AccordionItem value="sync-options">
- <AccordionTrigger>Sync Options</AccordionTrigger>
+ <AccordionTrigger className="py-4">Sync Options</AccordionTrigger>
<AccordionContent>
<DetailGroup>
{BOOLEAN_SYNC_OPTION_FIELDS.map(({ key, label }) => {