Skip to content

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

Address PR comments

Carlos Monastyrski247c795b3463
diff --git a/backend/src/services/app-connection/ldap/ldap-directory-fns.test.ts b/backend/src/services/app-connection/ldap/ldap-directory-fns.test.ts
index e932e17cb6..a2537e8304 100644
--- a/backend/src/services/app-connection/ldap/ldap-directory-fns.test.ts
+++ b/backend/src/services/app-connection/ldap/ldap-directory-fns.test.ts
@@ -1,7 +1,8 @@
import { buildDomainBaseDN } from "@app/lib/ldap/ldap-search-fns";
+import { LdapProvider } from "./ldap-connection-enums";
import { extractDomainFromDN } from "./ldap-connection-fns";
-import { parseLdapBindIdentity } from "./ldap-directory-fns";
+import { assertLdapProviderIsSupported, parseLdapBindIdentity } from "./ldap-directory-fns";
describe("parseLdapBindIdentity", () => {
test("derives the domain and the UPN local part, which is only a fallback for the logon name", () => {
@@ -76,3 +77,18 @@ describe("buildDomainBaseDN", () => {
expect(buildDomainBaseDN("corp")).toBe("DC=corp");
});
});
+
+describe("assertLdapProviderIsSupported", () => {
+ it("accepts an Active Directory connection", () => {
+ expect(() => assertLdapProviderIsSupported(LdapProvider.ActiveDirectory, "corp-ad")).not.toThrow();
+ });
+
+ it("refuses a provider that is not Active Directory, naming the connection", () => {
+ expect(() => assertLdapProviderIsSupported("openldap", "corp-ad")).toThrow(/corp-ad/);
+ expect(() => assertLdapProviderIsSupported("openldap", "corp-ad")).toThrow(/Active Directory/);
+ });
+
+ it("accepts an absent provider, which is a connection read without decrypted credentials", () => {
+ expect(() => assertLdapProviderIsSupported(undefined, "corp-ad")).not.toThrow();
+ });
+});
diff --git a/backend/src/services/app-connection/ldap/ldap-directory-fns.ts b/backend/src/services/app-connection/ldap/ldap-directory-fns.ts
index 60e8ba3322..eeac60d275 100644
--- a/backend/src/services/app-connection/ldap/ldap-directory-fns.ts
+++ b/backend/src/services/app-connection/ldap/ldap-directory-fns.ts
@@ -17,6 +17,7 @@ import { logger } from "@app/lib/logger";
import { UserPrincipalNameRegex } from "@app/lib/regex";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { LdapProvider } from "./ldap-connection-enums";
import { executeWithPotentialGateway, extractDomainFromDN } from "./ldap-connection-fns";
import { TLdapConnectionConfig } from "./ldap-connection-types";
@@ -208,6 +209,14 @@ const resolveLdapHostLogin = async (
return username;
};
+export const assertLdapProviderIsSupported = (provider: string | undefined, connectionName: string) => {
+ if (provider !== undefined && provider !== LdapProvider.ActiveDirectory) {
+ throw new BadRequestError({
+ message: `The LDAP connection '${connectionName}' uses the '${provider}' provider. Certificate syncs read machine and account attributes that only Active Directory provides, so they require an Active Directory connection.`
+ });
+ }
+};
+
export const resolveLdapBackedHostCredentials = async (
{
connection,
@@ -240,6 +249,8 @@ export const resolveLdapBackedHostCredentials = async (
orgId: connection.orgId
} as unknown as TLdapConnectionConfig;
+ assertLdapProviderIsSupported((connection.credentials as { provider?: string }).provider, connection.name);
+
const username = await resolveLdapHostLogin(config, gatewayServices);
return { host, username, password: config.credentials.password };
diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
index cb63f7ed10..863420bfe0 100644
--- a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
@@ -37,6 +37,7 @@ import {
THostCommandContext,
toPosixShellLiteral
} from "../pki-sync-host-command-fns";
+import { describeHostFailure, resolveGatewayLabel, withReachabilityDeadline } from "../pki-sync-host-error-fns";
import { buildPostSyncCommandPlan, runPostSyncCommand, TPostSyncCommandPlan } from "../pki-sync-post-sync-command-fns";
import { TCertificateMap, THealthCheckTarget, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "../pki-sync-types";
import { TLinuxServerPkiSyncConfig } from "./linux-server-pki-sync-types";
@@ -46,7 +47,7 @@ type TLinuxServerPkiSyncFactoryDeps = {
TCertificateSyncDALFactory,
"findByPkiSyncId" | "findByPkiSyncAndCertificate" | "updateById" | "addCertificates" | "removeCertificates"
>;
- gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
};
@@ -398,6 +399,14 @@ export const linuxServerPkiSyncFactory = ({
let removed = 0;
const sshConfig = await buildSshConfig(pkiSync, { gatewayV2Service, gatewayPoolService, keyStore });
+ const gatewayLabel = await resolveGatewayLabel(gatewayV2Service, sshConfig.gatewayId);
+ const describeFailure = (error: unknown) =>
+ describeHostFailure({
+ error,
+ host: (pkiSync.destinationConfig as TLinuxServerPkiSyncConfig).host,
+ gatewayLabel,
+ transport: "SSH"
+ });
const healthCheck = await runLinuxServerHealthCheckCommand({
pkiSync,
@@ -489,7 +498,7 @@ export const linuxServerPkiSyncFactory = ({
`Linux Server PKI sync [syncId=${pkiSync.id}]: wrote ${writtenPaths.length} file(s) for "${baseName}"`
);
} catch (err) {
- failedUploads.push({ name: baseName, error: (err as Error)?.message ?? "Unknown error" });
+ failedUploads.push({ name: baseName, error: describeFailure(err) });
}
}
@@ -597,5 +606,22 @@ export const linuxServerPkiSyncFactory = ({
gatewayServices: { gatewayV2Service, gatewayPoolService, keyStore }
});
- return { syncCertificates, removeCertificates, runHealthCheck };
+ const testReachability = async (pkiSync: TPkiSyncWithCredentials): Promise<void> => {
+ const sshConfig = await buildSshConfig(pkiSync, { gatewayV2Service, gatewayPoolService, keyStore });
+ const { host } = pkiSync.destinationConfig as TLinuxServerPkiSyncConfig;
+
+ try {
+ await withReachabilityDeadline(() =>
+ withSshConnection(sshConfig, { gatewayV2Service, gatewayPoolService }, async () => undefined)
+ );
+ } catch (err) {
+ const gatewayLabel = await resolveGatewayLabel(gatewayV2Service, sshConfig.gatewayId);
+ throw new PkiSyncError({
+ shouldRetry: false,
+ message: describeHostFailure({ error: err, host, gatewayLabel, transport: "SSH" })
+ });
+ }
+ };
+
+ return { syncCertificates, removeCertificates, runHealthCheck, testReachability };
};
diff --git a/backend/src/services/pki-sync/pki-sync-concurrency-fns.test.ts b/backend/src/services/pki-sync/pki-sync-concurrency-fns.test.ts
new file mode 100644
index 0000000000..91cec23140
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-concurrency-fns.test.ts
@@ -0,0 +1,89 @@
+/* eslint-disable no-await-in-loop */
+
+import { describe, expect, it } from "vitest";
+
+import { KeyStorePrefixes } from "@app/keystore/keystore";
+
+import { releasePkiSyncConcurrency, tryAdmitPkiSyncConcurrency } from "./pki-sync-concurrency-fns";
+import {
+ PKI_SYNC_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT,
+ PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT
+} from "./pki-sync-enums";
+
+const buildKeyStore = () => {
+ const counts = new Map<string, number>();
+
+ return {
+ counts,
+ incrementByAndRefreshExpiryIfUnderLimit: async (key: string, limit: number) => {
+ const next = (counts.get(key) ?? 0) + 1;
+ if (next > limit) return -1;
+ counts.set(key, next);
+ return next;
+ },
+ decrementByOrDelete: async (key: string) => {
+ const next = (counts.get(key) ?? 0) - 1;
+ if (next <= 0) counts.delete(key);
+ else counts.set(key, next);
+ return next;
+ }
+ };
+};
+
+const CONNECTION = "connection-1";
+const aggregateKey = KeyStorePrefixes.AppConnectionConcurrentJobs(CONNECTION);
+
+describe("pki sync connection concurrency", () => {
+ it("caps a single host at the per-host limit", async () => {
+ const keyStore = buildKeyStore();
+
+ for (let i = 0; i < PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT; i += 1) {
+ expect(await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, "host-a")).toBe(true);
+ }
+ expect(await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, "host-a")).toBe(false);
+ });
+
+ it("caps the connection across every host it backs", async () => {
+ const keyStore = buildKeyStore();
+ let admitted = 0;
+
+ for (let host = 0; host < 50; host += 1) {
+ for (let job = 0; job < PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT; job += 1) {
+ if (await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, `host-${host}`)) admitted += 1;
+ }
+ }
+
+ expect(admitted).toBe(PKI_SYNC_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT);
+ });
+
+ it("does not consume an aggregate slot when the per-host limit refuses", async () => {
+ const keyStore = buildKeyStore();
+
+ for (let i = 0; i < PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT; i += 1) {
+ await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, "host-a");
+ }
+ const aggregateBefore = keyStore.counts.get(aggregateKey);
+
+ expect(await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, "host-a")).toBe(false);
+ expect(keyStore.counts.get(aggregateKey)).toBe(aggregateBefore);
+ });
+
+ it("releases both tiers so slots are reusable", async () => {
+ const keyStore = buildKeyStore();
+
+ await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, "host-a");
+ await releasePkiSyncConcurrency(keyStore, CONNECTION, "host-a");
+
+ expect(keyStore.counts.size).toBe(0);
+ });
+
+ it("keeps one tier for a hosted sync, where the connection key is the host key", async () => {
+ const keyStore = buildKeyStore();
+
+ for (let i = 0; i < PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT; i += 1) {
+ expect(await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION)).toBe(true);
+ }
+ expect(await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION)).toBe(false);
+ expect(keyStore.counts.get(aggregateKey)).toBe(PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT);
+ });
+});
diff --git a/backend/src/services/pki-sync/pki-sync-concurrency-fns.ts b/backend/src/services/pki-sync/pki-sync-concurrency-fns.ts
new file mode 100644
index 0000000000..962e19a5e9
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-concurrency-fns.ts
@@ -0,0 +1,56 @@
+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+
+import {
+ PKI_SYNC_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT,
+ PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
+ PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
+} from "./pki-sync-enums";
+
+type TConcurrencyKeyStore = Pick<TKeyStoreFactory, "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
+
+export const tryAdmitPkiSyncConcurrency = async (
+ keyStore: TConcurrencyKeyStore,
+ connectionId: string,
+ targetHost?: string
+): Promise<boolean> => {
+ const aggregateKey = KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId);
+
+ if (!targetHost) {
+ const count = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
+ aggregateKey,
+ PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
+ PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
+ );
+ return count !== -1;
+ }
+
+ const aggregateCount = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
+ aggregateKey,
+ PKI_SYNC_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT,
+ PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
+ );
+ if (aggregateCount === -1) return false;
+
+ const hostCount = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
+ KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost),
+ PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
+ PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
+ );
+ if (hostCount === -1) {
+ await keyStore.decrementByOrDelete(aggregateKey);
+ return false;
+ }
+
+ return true;
+};
+
+export const releasePkiSyncConcurrency = async (
+ keyStore: TConcurrencyKeyStore,
+ connectionId: string,
+ targetHost?: string
+): Promise<void> => {
+ await keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost));
+ if (targetHost) {
+ await keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId));
+ }
+};
diff --git a/backend/src/services/pki-sync/pki-sync-enums.ts b/backend/src/services/pki-sync/pki-sync-enums.ts
index 9d593ed373..bd722ff5cb 100644
--- a/backend/src/services/pki-sync/pki-sync-enums.ts
+++ b/backend/src/services/pki-sync/pki-sync-enums.ts
@@ -35,6 +35,8 @@ export enum PkiSyncFailureKind {
export const PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT = 3;
+export const PKI_SYNC_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT = 15;
+
export const PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S = 15 * 60;
export const PKI_SYNC_CONNECTION_LOCK_RETRY = { retryCount: 10, retryDelay: 3_000, retryJitter: 500 };
diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.ts
index 0dff22e5a0..2a6f7b483f 100644
--- a/backend/src/services/pki-sync/pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-fns.ts
@@ -271,7 +271,7 @@ export const PkiSyncFns = {
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
certificateDAL: TCertificateDALFactory;
certificateSyncDAL: TCertificateSyncDALFactory;
- gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
}
@@ -414,7 +414,7 @@ export const PkiSyncFns = {
certificateMap: TCertificateMap,
dependencies: {
certificateSyncDAL: TCertificateSyncDALFactory;
- gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
}
@@ -449,6 +449,43 @@ export const PkiSyncFns = {
}
},
+ testReachability: async (
+ pkiSync: THealthCheckTarget,
+ dependencies: {
+ certificateSyncDAL: TCertificateSyncDALFactory;
+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
+ }
+ ): Promise<void> => {
+ if (pkiSync.destination === PkiSync.LinuxServer) {
+ const linuxServerPkiSync = linuxServerPkiSyncFactory({
+ certificateSyncDAL: dependencies.certificateSyncDAL,
+ gatewayV2Service: dependencies.gatewayV2Service,
+ gatewayPoolService: dependencies.gatewayPoolService,
+ keyStore: dependencies.keyStore
+ });
+ await linuxServerPkiSync.testReachability(pkiSync as unknown as TPkiSyncWithCredentials);
+ return;
+ }
+
+ if (pkiSync.destination === PkiSync.WindowsServer) {
+ if (!dependencies.gatewayV2Service) {
+ throw new PkiSyncError({
+ shouldRetry: false,
+ message: "Windows Server sync requires a gateway to reach the host."
+ });
+ }
+ const windowsServerPkiSync = windowsServerPkiSyncFactory({
+ certificateSyncDAL: dependencies.certificateSyncDAL,
+ gatewayV2Service: dependencies.gatewayV2Service,
+ gatewayPoolService: dependencies.gatewayPoolService,
+ keyStore: dependencies.keyStore
+ });
+ await windowsServerPkiSync.testReachability(pkiSync as unknown as TPkiSyncWithCredentials);
+ }
+ },
+
removeCertificates: async (
pkiSync: TPkiSyncWithCredentials,
certificateNames: string[],
@@ -458,7 +495,7 @@ export const PkiSyncFns = {
certificateSyncDAL: TCertificateSyncDALFactory;
certificateDAL: TCertificateDALFactory;
certificateMap: TCertificateMap;
- gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
}
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 304b3c3856..200dbca8e2 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
@@ -23,16 +23,10 @@ import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-
import { TCertificateAuthorityCertDALFactory } from "../certificate-authority/certificate-authority-cert-dal";
import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";
import { buildCertificateMap } from "./pki-sync-certificate-map-fns";
+import { releasePkiSyncConcurrency, tryAdmitPkiSyncConcurrency } from "./pki-sync-concurrency-fns";
import { hydratePkiSyncCredentials } from "./pki-sync-credentials-fns";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
-import {
- PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
- PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S,
- PKI_SYNC_CONNECTION_LOCK_RETRY,
- PkiSync,
- PkiSyncFailureKind,
- PkiSyncStatus
-} from "./pki-sync-enums";
+import { 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";
@@ -91,7 +85,7 @@ type TPkiSyncHealthCheckQueueFactoryDep = {
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
- gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
@@ -166,12 +160,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
let admittedSlot = false;
try {
- admittedSlot =
- (await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
- KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost),
- PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
- PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
- )) !== -1;
+ admittedSlot = await tryAdmitPkiSyncConcurrency(keyStore, connectionId, targetHost);
if (!admittedSlot) {
throw new HealthCheckBusyError("This connection is at its concurrency limit.");
}
@@ -179,9 +168,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
return await run();
} finally {
await Promise.allSettled([
- admittedSlot
- ? keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost))
- : undefined,
+ admittedSlot ? releasePkiSyncConcurrency(keyStore, connectionId, targetHost) : undefined,
connectionLock.release()
]);
}
@@ -403,6 +390,51 @@ export const pkiSyncHealthCheckQueueFactory = ({
throw new BadRequestError({ message: SKIP_MESSAGES[outcome.skipped] });
};
+ const testTargetHostReachable = async (args: {
+ destination: PkiSync;
+ connectionId: string;
+ destinationConfig: Record<string, unknown>;
+ }) => {
+ const connection = await appConnectionDAL.findById(args.connectionId);
+ if (!connection) {
+ throw new NotFoundError({ message: `App connection with ID '${args.connectionId}' not found` });
+ }
+
+ const credentials = await decryptAppConnectionCredentials({
+ orgId: connection.orgId,
+ projectId: connection.projectId,
+ encryptedCredentials: connection.encryptedCredentials,
+ kmsService
+ });
+
+ const target: THealthCheckTarget = {
+ id: "unsaved-sync-reachability",
+ destination: args.destination,
+ destinationConfig: args.destinationConfig,
+ syncOptions: {},
+ connection: {
+ id: connection.id,
+ name: connection.name,
+ app: connection.app,
+ credentials: credentials as Record<string, unknown>,
+ method: connection.method,
+ orgId: connection.orgId,
+ gatewayId: connection.gatewayId ?? undefined,
+ gatewayPoolId: connection.gatewayPoolId
+ }
+ };
+
+ await PkiSyncFns.testReachability(target, {
+ certificateSyncDAL,
+ gatewayV2Service,
+ gatewayPoolService,
+ keyStore
+ }).catch((err) => {
+ if (err instanceof PkiSyncError) throw new BadRequestError({ message: err.message });
+ throw err;
+ });
+ };
+
const testHealthCheckCommand = async (args: {
destination: PkiSync;
connectionId: string;
@@ -518,5 +550,5 @@ export const pkiSyncHealthCheckQueueFactory = ({
});
};
- return { init, runHealthCheckNow, testHealthCheckCommand };
+ return { init, runHealthCheckNow, testHealthCheckCommand, testTargetHostReachable };
};
diff --git a/backend/src/services/pki-sync/pki-sync-host-error-fns.test.ts b/backend/src/services/pki-sync/pki-sync-host-error-fns.test.ts
new file mode 100644
index 0000000000..6008f5d45e
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-host-error-fns.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+
+import { describeHostFailure, HostProbeTimeoutError, withReachabilityDeadline } from "./pki-sync-host-error-fns";
+
+describe("describeHostFailure", () => {
+ it("names the host and the Gateway when the transport could not connect", () => {
+ const message = describeHostFailure({
+ error: new Error("WinRM gateway operation failed: failed to connect to the Windows host over WinRM"),
+ host: "EC2AMAZ-8V4780K.corp.example.com",
+ gatewayLabel: "carlos-gw",
+ transport: "WinRM"
+ });
+
+ expect(message).toContain('target host "EC2AMAZ-8V4780K.corp.example.com"');
+ expect(message).toContain('Gateway "carlos-gw"');
+ });
+
+ it("treats a probe deadline as unreachable", () => {
+ expect(
+ describeHostFailure({
+ error: new HostProbeTimeoutError("Reachability probe deadline exceeded"),
+ host: "172.31.99.99",
+ gatewayLabel: "carlos-gw",
+ transport: "SSH"
+ })
+ ).toContain('Could not reach the target host "172.31.99.99" over SSH');
+ });
+
+ it("falls back to naming the connection when the Gateway name is unknown", () => {
+ expect(
+ describeHostFailure({
+ error: new Error("dial tcp 10.0.0.5:5986: i/o timeout"),
+ host: "10.0.0.5",
+ gatewayLabel: undefined,
+ transport: "WinRM"
+ })
+ ).toContain("from the Gateway assigned to this connection");
+ });
+
+ it("passes a failure that is not a connectivity problem through untouched", () => {
+ const original = "Access is denied for user CORP\\svc-certs";
+ expect(
+ describeHostFailure({ error: new Error(original), host: "host-a", gatewayLabel: "gw", transport: "WinRM" })
+ ).toBe(original);
+ });
+
+ it("passes the failure through when no host is known", () => {
+ expect(
+ describeHostFailure({
+ error: new Error("failed to connect"),
+ host: undefined,
+ gatewayLabel: "gw",
+ transport: "SSH"
+ })
+ ).toBe("failed to connect");
+ });
+});
+
+describe("withReachabilityDeadline", () => {
+ it("returns the probe result when it settles in time", async () => {
+ await expect(withReachabilityDeadline(async () => "ok")).resolves.toBe("ok");
+ });
+
+ it("rejects with a deadline error when the probe outlasts the budget", async () => {
+ await expect(
+ withReachabilityDeadline(
+ () =>
+ new Promise((resolve) => {
+ setTimeout(resolve, 20_000);
+ })
+ )
+ ).rejects.toBeInstanceOf(HostProbeTimeoutError);
+ }, 20_000);
+
+ it("surfaces the probe's own failure rather than the deadline", async () => {
+ await expect(withReachabilityDeadline(() => Promise.reject(new Error("connection refused")))).rejects.toThrow(
+ "connection refused"
+ );
+ });
+});
diff --git a/backend/src/services/pki-sync/pki-sync-host-error-fns.ts b/backend/src/services/pki-sync/pki-sync-host-error-fns.ts
new file mode 100644
index 0000000000..d3d29d4fca
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-host-error-fns.ts
@@ -0,0 +1,64 @@
+import RE2 from "re2";
+
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { logger } from "@app/lib/logger";
+
+const UNREACHABLE_PATTERN = new RE2(
+ "failed to connect|connection refused|no such host|i/o timeout|dial tcp|EHOSTUNREACH|ETIMEDOUT|ENOTFOUND|getaddrinfo",
+ "i"
+);
+
+export const resolveGatewayLabel = async (
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getGatewayById"> | undefined,
+ gatewayId: string | null | undefined
+): Promise<string | undefined> => {
+ if (!gatewayV2Service || !gatewayId) return undefined;
+
+ try {
+ const gateway = await gatewayV2Service.getGatewayById({ gatewayId });
+ return gateway?.name;
+ } catch (err) {
+ logger.warn({ err }, `Unable to read the Gateway name for an unreachable host [gatewayId=${gatewayId}]`);
+ return undefined;
+ }
+};
+
+export const PKI_SYNC_REACHABILITY_PROBE_TIMEOUT_MS = 12_000;
+
+export class HostProbeTimeoutError extends Error {}
+
+export const withReachabilityDeadline = async <T>(probe: () => Promise<T>): Promise<T> => {
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ return await Promise.race([
+ probe(),
+ new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(
+ () => reject(new HostProbeTimeoutError("Reachability probe deadline exceeded")),
+ PKI_SYNC_REACHABILITY_PROBE_TIMEOUT_MS
+ );
+ })
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+};
+
+export const describeHostFailure = ({
+ error,
+ host,
+ gatewayLabel,
+ transport
+}: {
+ error: unknown;
+ host: string | undefined;
+ gatewayLabel: string | undefined;
+ transport: "WinRM" | "SSH";
+}): string => {
+ const message = (error as Error)?.message ?? "Unknown error";
+ const isUnreachable = error instanceof HostProbeTimeoutError || UNREACHABLE_PATTERN.test(message);
+ if (!host || !isUnreachable) return message;
+
+ const via = gatewayLabel ? ` from Gateway "${gatewayLabel}"` : " from the Gateway assigned to this connection";
+ return `Could not reach the target host "${host}" over ${transport}${via}. Check that the Gateway can resolve and reach it, and that the ${transport} service is listening.`;
+};
diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.ts
index 140f8d4a00..769987e4bf 100644
--- a/backend/src/services/pki-sync/pki-sync-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-queue.ts
@@ -30,14 +30,9 @@ import { TCertificateAuthorityDALFactory } from "../certificate-authority/certif
import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
import { CertificateSyncStatus } from "../certificate-sync/certificate-sync-enums";
import { buildCertificateMap } from "./pki-sync-certificate-map-fns";
+import { releasePkiSyncConcurrency, tryAdmitPkiSyncConcurrency } from "./pki-sync-concurrency-fns";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
-import {
- PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
- PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S,
- PKI_SYNC_CONNECTION_LOCK_RETRY,
- PkiSyncFailureKind,
- PkiSyncStatus
-} from "./pki-sync-enums";
+import { 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 {
@@ -98,7 +93,7 @@ type TPkiSyncQueueFactoryDep = {
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;
certificateSyncDAL: TCertificateSyncDALFactory;
- gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
};
@@ -156,19 +151,11 @@ export const pkiSyncQueueFactory = ({
unit: "1"
});
- const $tryAdmitConnectionConcurrency = async (connectionId: string, targetHost?: string) => {
- const count = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
- KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost),
- PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
- PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
- );
+ const $tryAdmitConnectionConcurrency = (connectionId: string, targetHost?: string) =>
+ tryAdmitPkiSyncConcurrency(keyStore, connectionId, targetHost);
- return count !== -1;
- };
-
- const $releaseConnectionConcurrency = async (connectionId: string, targetHost?: string) => {
- await keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost));
- };
+ const $releaseConnectionConcurrency = (connectionId: string, targetHost?: string) =>
+ releasePkiSyncConcurrency(keyStore, connectionId, targetHost);
const $certificatesForSync = (pkiSync: TPkiSyncRaw) =>
buildCertificateMap(pkiSync, {
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index 37a45582a1..f5968eb1ca 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -56,7 +56,11 @@ import {
POST_SYNC_COMMAND_OPTION_KEY
} from "./pki-sync-post-sync-command-fns";
import { TPkiSyncQueueFactory } from "./pki-sync-queue";
-import { assertTargetHostMatchesConnection, TPkiSyncDeliveryTarget } from "./pki-sync-target-host-fns";
+import {
+ assertTargetHostMatchesConnection,
+ getPkiSyncTargetHost,
+ TPkiSyncDeliveryTarget
+} from "./pki-sync-target-host-fns";
import {
TAddCertificatesToPkiSyncDTO,
TClearDefaultCertificateDTO,
@@ -99,7 +103,10 @@ type TPkiSyncServiceFactoryDep = {
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
- pkiSyncHealthCheckQueue: Pick<TPkiSyncHealthCheckQueueFactory, "runHealthCheckNow" | "testHealthCheckCommand">;
+ pkiSyncHealthCheckQueue: Pick<
+ TPkiSyncHealthCheckQueueFactory,
+ "runHealthCheckNow" | "testHealthCheckCommand" | "testTargetHostReachable"
+ >;
pkiSyncQueue: Pick<
TPkiSyncQueueFactory,
"queuePkiSyncSyncCertificatesById" | "queuePkiSyncImportCertificatesById" | "queuePkiSyncRemoveCertificatesById"
@@ -242,15 +249,17 @@ export const pkiSyncServiceFactory = ({
currentConfig,
pkiSync,
subscriberName,
- actor
+ actor,
+ isRetargetedByConnection = false
}: {
nextConfig: Record<string, unknown> | null | undefined;
currentConfig: Record<string, unknown> | null | undefined;
pkiSync: { projectId: string; applicationId?: string | null; name: string };
subscriberName: string | undefined;
actor: OrgServiceActor;
+ isRetargetedByConnection?: boolean;
}) => {
- if ($deliveryTarget(nextConfig) === $deliveryTarget(currentConfig)) return;
+ if (!isRetargetedByConnection && $deliveryTarget(nextConfig) === $deliveryTarget(currentConfig)) return;
await $assertSyncAction(
ProjectPermissionPkiSyncActions.SetTargetHost,
@@ -261,6 +270,25 @@ export const pkiSyncServiceFactory = ({
);
};
+ const $assertTargetHostReachable = async ({
+ destination,
+ connection,
+ destinationConfig
+ }: {
+ destination: PkiSync;
+ connection: { id: string; app: AppConnection };
+ destinationConfig: Record<string, unknown> | null | undefined;
+ }) => {
+ if (connection.app !== AppConnection.LDAP) return;
+ if (!getPkiSyncTargetHost(destinationConfig)) return;
+
+ await pkiSyncHealthCheckQueue.testTargetHostReachable({
+ destination,
+ connectionId: connection.id,
+ destinationConfig: destinationConfig as Record<string, unknown>
+ });
+ };
+
const HOST_COMMAND_ACTIONS = {
[HEALTH_CHECK_COMMAND_OPTION_KEY]: {
project: ProjectPermissionPkiSyncActions.SetHealthCheckCommand,
@@ -485,6 +513,8 @@ export const pkiSyncServiceFactory = ({
assertPkiSyncDestinationConfigAllowsCertificateCount(destination, destinationConfig, certificateIds.length);
}
+ await $assertTargetHostReachable({ destination, connection, destinationConfig });
+
const encryptedCredentials = credentials?.exportPassword
? await encryptPkiSyncCredentials({ orgId: actor.orgId, projectId, credentials, kmsService })
: undefined;
@@ -645,7 +675,10 @@ export const pkiSyncServiceFactory = ({
currentConfig: pkiSync.destinationConfig as Record<string, unknown> | undefined,
pkiSync,
subscriberName: currentSubscriber?.name,
- actor
+ actor,
+ isRetargetedByConnection:
+ isConnectionChanging &&
+ (pkiSync.connection.app === AppConnection.LDAP || (await resolveConnection()).app === AppConnection.LDAP)
});
const storedSyncOptions = pkiSync.syncOptions as Record<string, unknown> | undefined;
@@ -671,6 +704,16 @@ export const pkiSyncServiceFactory = ({
);
}
+ if (isConnectionChanging || isDestinationConfigChanging) {
+ await $assertTargetHostReachable({
+ destination: pkiSync.destination,
+ connection: isConnectionChanging
+ ? await resolveConnection()
+ : { id: pkiSync.connectionId, app: pkiSync.connection.app as AppConnection },
+ destinationConfig: effectiveDestinationConfig
+ });
+ }
+
const effectiveSyncOptions = (resolvedSyncOptions ?? pkiSync.syncOptions) as Record<string, unknown> | undefined;
await $assertHostCommandWrite({
diff --git a/backend/src/services/pki-sync/pki-sync-target-host-fns.ts b/backend/src/services/pki-sync/pki-sync-target-host-fns.ts
index 3a0aed0643..180de68a48 100644
--- a/backend/src/services/pki-sync/pki-sync-target-host-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-target-host-fns.ts
@@ -1,5 +1,6 @@
import { BadRequestError } from "@app/lib/errors";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { assertLdapProviderIsSupported } from "@app/services/app-connection/ldap/ldap-directory-fns";
import { PkiSync } from "./pki-sync-enums";
import { PKI_SYNC_NAME_MAP } from "./pki-sync-maps";
@@ -9,6 +10,7 @@ type TTargetHostConnection = {
name: string;
gatewayId?: string | null;
gatewayPoolId?: string | null;
+ credentials?: unknown;
};
export type TPkiSyncDeliveryTarget = {
@@ -54,6 +56,11 @@ export const assertTargetHostMatchesConnection = ({
const destinationName = PKI_SYNC_NAME_MAP[destination];
+ assertLdapProviderIsSupported(
+ (connection.credentials as { provider?: string } | undefined)?.provider,
+ connection.name
+ );
+
if (!host) {
throw new BadRequestError({
message: `A target host is required when using the LDAP connection '${connection.name}', because an LDAP connection can reach many machines. Set the target host to the machine this ${destinationName} sync should deliver to.`
diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
index 4feccc1fd4..9f14c1db4c 100644
--- a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
@@ -33,6 +33,7 @@ import {
THostCommandExecutionResult,
toPowerShellLiteral
} from "../pki-sync-host-command-fns";
+import { describeHostFailure, resolveGatewayLabel, withReachabilityDeadline } from "../pki-sync-host-error-fns";
import { buildPostSyncCommandPlan, runPostSyncCommand, TPostSyncCommandPlan } from "../pki-sync-post-sync-command-fns";
import { TCertificateMap, THealthCheckTarget, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "../pki-sync-types";
import { TWindowsServerPkiSyncConfig } from "./windows-server-pki-sync-types";
@@ -42,7 +43,7 @@ type TWindowsServerPkiSyncFactoryDeps = {
TCertificateSyncDALFactory,
"findByPkiSyncId" | "findByPkiSyncAndCertificate" | "updateById" | "addCertificates" | "removeCertificates"
>;
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
};
@@ -306,6 +307,9 @@ export const windowsServerPkiSyncFactory = ({
const deliveredPaths = new Set<string>();
const deliveredCertificates: Array<{ paths: string[]; commonName?: string }> = [];
const target = await buildWinRMTarget(pkiSync, gatewayDeps);
+ const gatewayLabel = await resolveGatewayLabel(gatewayV2Service, target.gatewayId);
+ const describeFailure = (error: unknown) =>
+ describeHostFailure({ error, host: config.host, gatewayLabel, transport: "WinRM" });
let uploaded = 0;
let removed = 0;
@@ -389,7 +393,7 @@ export const windowsServerPkiSyncFactory = ({
}
uploaded += 1;
} catch (err) {
- failedUploads.push({ name: baseName, error: (err as Error)?.message ?? "Unknown error" });
+ failedUploads.push({ name: baseName, error: describeFailure(err) });
}
}
@@ -493,5 +497,22 @@ export const windowsServerPkiSyncFactory = ({
gatewayDeps
});
- return { syncCertificates, removeCertificates, runHealthCheck };
+ const testReachability = async (pkiSync: TPkiSyncWithCredentials): Promise<void> => {
+ const target = await buildWinRMTarget(pkiSync, gatewayDeps);
+ const { host } = pkiSync.destinationConfig as TWindowsServerPkiSyncConfig;
+
+ try {
+ await withReachabilityDeadline(() =>
+ executeWinRMGatewayOperation({ ...target, endpoint: WinRmRpcEndpoint.Test }, gatewayDeps)
+ );
+ } catch (err) {
+ const gatewayLabel = await resolveGatewayLabel(gatewayV2Service, target.gatewayId);
+ throw new PkiSyncError({
+ shouldRetry: false,
+ message: describeHostFailure({ error: err, host, gatewayLabel, transport: "WinRM" })
+ });
+ }
+ };
+
+ return { syncCertificates, removeCertificates, runHealthCheck, testReachability };
};