Skip to content

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

feat(pam): connection test

x9cce65c24489
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-fns.ts b/backend/src/ee/services/gateway-v2/gateway-v2-fns.ts
new file mode 100644
index 0000000000..5082ebee7f
--- /dev/null
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-fns.ts
@@ -0,0 +1,41 @@
+import { BadRequestError } from "@app/lib/errors";
+import { GatewayProxyProtocol } from "@app/lib/gateway";
+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { callTestConnection } from "@app/lib/gateway-v2/test-connection-rpc";
+
+import { verifyHostInputValidity } from "../dynamic-secret/dynamic-secret-fns";
+import { TGatewayV2ServiceFactory } from "./gateway-v2-service";
+
+type TGatewayDep = Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+
+// runs a connection test against the target via the gateway's test-connection handler
+export const testConnectionWithGateway = async (
+ targetHost: string,
+ targetPort: number,
+ gatewayId: string,
+ gatewayV2Service: TGatewayDep,
+ request: Record<string, unknown>,
+ timeoutMs: number,
+ signal?: AbortSignal
+): Promise<void> => {
+ const [host] = await verifyHostInputValidity({ host: targetHost, isGateway: true, isDynamicSecret: false });
+ const platform = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
+ gatewayId,
+ targetHost: host,
+ targetPort
+ });
+ if (!platform) throw new BadRequestError({ message: "Unable to connect to gateway" });
+
+ await withGatewayV2Proxy(
+ async (proxyPort) => {
+ const response = await callTestConnection({ port: proxyPort, body: request, timeoutMs, signal });
+ if (!response.ok) throw new Error(response.errorMessage);
+ },
+ {
+ protocol: GatewayProxyProtocol.Discovery,
+ relayHost: platform.relayHost,
+ gateway: platform.gateway,
+ relay: platform.relay
+ }
+ );
+};
diff --git a/backend/src/ee/services/pam-account/pam-account-connection-test.ts b/backend/src/ee/services/pam-account/pam-account-connection-test.ts
new file mode 100644
index 0000000000..067367070f
--- /dev/null
+++ b/backend/src/ee/services/pam-account/pam-account-connection-test.ts
@@ -0,0 +1,73 @@
+import { PamAccountType, PamSshAuthMethod } from "../pam/pam-enums";
+import { isCredentialConfigured } from "./pam-account-schemas";
+
+export enum TestConnectionMode {
+ Postgres = "postgres",
+ SSH = "ssh",
+ Tcp = "tcp"
+}
+
+// the request the gateway's /v1/test-connection handler expects, discriminated by `mode`
+export type TestConnectionRequest =
+ | {
+ mode: TestConnectionMode.Postgres;
+ username: string;
+ password?: string;
+ database: string;
+ sslEnabled?: boolean;
+ sslRejectUnauthorized?: boolean;
+ sslCertificate?: string;
+ }
+ | {
+ mode: TestConnectionMode.SSH;
+ authMethod: string;
+ username: string;
+ password?: string;
+ privateKey?: string;
+ certificate?: string;
+ }
+ | { mode: TestConnectionMode.Tcp };
+
+type ConnectionTestBuilder = (
+ connectionDetails: Record<string, unknown>,
+ credentials: Record<string, unknown>
+) => TestConnectionRequest;
+
+// single source of truth for which account types support a connection test and how each is tested
+export const PAM_CONNECTION_TEST_BUILDERS: Partial<Record<PamAccountType, ConnectionTestBuilder>> = {
+ [PamAccountType.Postgres]: (connectionDetails, credentials) => {
+ if (!isCredentialConfigured(PamAccountType.Postgres, credentials)) return { mode: TestConnectionMode.Tcp };
+ const cd = connectionDetails as {
+ database: string;
+ sslEnabled?: boolean;
+ sslRejectUnauthorized?: boolean;
+ sslCertificate?: string;
+ };
+ const creds = credentials as { username: string; password?: string };
+ return {
+ mode: TestConnectionMode.Postgres,
+ username: creds.username,
+ password: creds.password,
+ database: cd.database,
+ sslEnabled: cd.sslEnabled,
+ sslRejectUnauthorized: cd.sslRejectUnauthorized,
+ sslCertificate: cd.sslCertificate
+ };
+ },
+ [PamAccountType.SSH]: (_connectionDetails, credentials) => {
+ const creds = credentials as { authMethod: string; username: string; password?: string; privateKey?: string };
+
+ if (creds.authMethod === PamSshAuthMethod.Certificate || !isCredentialConfigured(PamAccountType.SSH, credentials)) {
+ return { mode: TestConnectionMode.Tcp };
+ }
+
+ return {
+ mode: TestConnectionMode.SSH,
+ authMethod: creds.authMethod,
+ username: creds.username,
+ password: creds.password,
+ privateKey: creds.privateKey
+ };
+ },
+ [PamAccountType.Windows]: () => ({ mode: TestConnectionMode.Tcp })
+};
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
index afbee06b0b..9e001ca7e5 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -4,6 +4,7 @@ import { packRules } from "@casl/ability/extra";
import { RESOURCE_SCOPE, ResourceType, TPamAccountTemplates } from "@app/db/schemas";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ResourcePermissionPamResourceActions,
@@ -21,6 +22,7 @@ import { KmsDataKey } from "@app/services/kms/kms-types";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+import { testConnectionWithGateway } from "../gateway-v2/gateway-v2-fns";
import { PamAccessStatus, PamAccountType, PamProductRole } from "../pam/pam-enums";
import {
checkAccountAccess,
@@ -40,6 +42,7 @@ import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-acces
import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";
import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";
import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
+import { PAM_CONNECTION_TEST_BUILDERS } from "./pam-account-connection-test";
import { TPamAccountDALFactory } from "./pam-account-dal";
import {
getAccountAccessibilityIssues,
@@ -72,7 +75,11 @@ type TPamAccountServiceFactoryDep = {
>;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne">;
- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveAttachableGatewayFromPool">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<
+ TGatewayPoolServiceFactory,
+ "resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId"
+ >;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findOne" | "findById">;
pamAccessRequestService: Pick<
TPamAccessRequestServiceFactory,
@@ -120,6 +127,8 @@ const assertPasswordMeetsRequirements = (credentials: unknown, templateSettings:
}
};
+const CONNECTION_TEST_TIMEOUT_MS = 15_000;
+
export type TPamAccountServiceFactory = ReturnType<typeof pamAccountServiceFactory>;
export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) => {
@@ -130,7 +139,9 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
membershipDAL,
membershipRoleDAL,
permissionService,
- kmsService
+ kmsService,
+ gatewayV2Service,
+ gatewayPoolService
} = deps;
const getProjectCipher = async (projectId: string) =>
@@ -269,6 +280,50 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
};
};
+ // throws to block create/update when the account can't reach/authenticate its target
+ const assertConnectionOk = async (
+ accountType: PamAccountType,
+ connectionDetails: Record<string, unknown>,
+ credentials: Record<string, unknown>,
+ gateway: {
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ templateGatewayId?: string | null;
+ templateGatewayPoolId?: string | null;
+ }
+ ): Promise<void> => {
+ const buildRequest = PAM_CONNECTION_TEST_BUILDERS[accountType];
+ if (!buildRequest) return;
+
+ const effectiveGatewayId = gateway.gatewayId ?? gateway.templateGatewayId;
+ const gatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
+ gatewayId: effectiveGatewayId,
+ gatewayPoolId: effectiveGatewayId ? null : (gateway.gatewayPoolId ?? gateway.templateGatewayPoolId)
+ });
+
+ if (!gatewayId) {
+ throw new BadRequestError({ message: "A gateway must be attached to this account." });
+ }
+
+ const cd = connectionDetails as { host: string; port: number };
+ const request = buildRequest(connectionDetails, credentials);
+
+ try {
+ await testConnectionWithGateway(
+ cd.host,
+ cd.port,
+ gatewayId,
+ gatewayV2Service,
+ request,
+ CONNECTION_TEST_TIMEOUT_MS
+ );
+ } catch (err) {
+ throw new BadRequestError({
+ message: `Connection test failed: ${(err as Error).message || "unable to connect to the target"}`
+ });
+ }
+ };
+
const create = async ({
projectId,
accountType,
@@ -325,6 +380,13 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
const validatedCredentials = validateCredentials(accountType, credentials);
assertPasswordMeetsRequirements(validatedCredentials, template.settings);
+ await assertConnectionOk(accountType, validatedConnectionDetails, validatedCredentials, {
+ gatewayId,
+ gatewayPoolId,
+ templateGatewayId: template.gatewayId,
+ templateGatewayPoolId: template.gatewayPoolId
+ });
+
const encryptedConnectionDetails = await encrypt(projectId, validatedConnectionDetails);
const encryptedCredentials = await encrypt(projectId, validatedCredentials);
@@ -519,6 +581,30 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
updateData.rotationAccountId = null;
}
+ // re-test whenever the connection could have changed
+ if (
+ connectionDetails !== undefined ||
+ credentials !== undefined ||
+ gatewayId !== undefined ||
+ gatewayPoolId !== undefined ||
+ templateId !== undefined
+ ) {
+ const effectiveConnectionDetails = connectionDetails
+ ? validateConnectionDetails(accountType, connectionDetails)
+ : validateConnectionDetails(accountType, await decrypt(projectId, existing.encryptedConnectionDetails));
+ const existingCredentials = await decrypt(projectId, existing.encryptedCredentials);
+ const effectiveCredentials = validateCredentials(
+ accountType,
+ credentials ? { ...existingCredentials, ...credentials } : existingCredentials
+ );
+ await assertConnectionOk(accountType, effectiveConnectionDetails, effectiveCredentials, {
+ gatewayId: gatewayId !== undefined ? gatewayId : existing.gatewayId,
+ gatewayPoolId: gatewayPoolId !== undefined ? gatewayPoolId : existing.gatewayPoolId,
+ templateGatewayId: template ? template.gatewayId : existing.templateGatewayId,
+ templateGatewayPoolId: template ? template.gatewayPoolId : existing.templateGatewayPoolId
+ });
+ }
+
try {
const account = await pamAccountDAL.transaction(async (tx) => {
const updated = await pamAccountDAL.updateById(accountId, updateData, tx);
diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.md
index b4e42a308d..36cf6d623c 100644
--- a/backend/src/ee/services/pam/CLAUDE.md
+++ b/backend/src/ee/services/pam/CLAUDE.md
@@ -62,6 +62,14 @@ the frontend renders create/edit forms from `GET /pam/accounts/types` metadata,
frontend components**. Adding a type is mostly a config entry + an icon; the gateway extension points are
`extractGatewayTarget` and `buildSessionGatewayConnectionDetails` in the same file.
+**Connection test** (`assertConnectionOk`) runs inside account `create`/`update` and **throws to block the write**
+if the target can't be reached/authenticated (verified from the gateway, never the backend). Which types are
+testable and how each builds its request is one registry — `PAM_CONNECTION_TEST_BUILDERS` in
+`pam-account-connection-test.ts` (a type absent from it isn't tested; add a testable type by adding an entry).
+One gateway RPC runs it all — `testConnectionWithGateway` → the gateway's `/v1/test-connection` handler
+(`packages/gateway-v2/test_connection_handler.go`), which dispatches on a `mode`: `postgres` (pgx auth + `SELECT 1`),
+`ssh` (login via the shared exec path), or `tcp` (reachability).
+
Cloud types use one of two brokering models instead of a plain gateway TCP proxy: **gateway-less** (`AwsIam`,
`requiresGateway: false`) mints short-lived STS credentials in `access()` and returns them in session
metadata; **gateway-injection** (`GcpServiceAccount`, `AzureCli`) proxies the cloud REST API through the
diff --git a/backend/src/lib/gateway-v2/test-connection-rpc.test.ts b/backend/src/lib/gateway-v2/test-connection-rpc.test.ts
new file mode 100644
index 0000000000..aa2e43c6cb
--- /dev/null
+++ b/backend/src/lib/gateway-v2/test-connection-rpc.test.ts
@@ -0,0 +1,78 @@
+import http from "node:http";
+import { AddressInfo } from "node:net";
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { callTestConnection } from "./test-connection-rpc";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }
+}));
+
+// Stands up a throwaway HTTP server that impersonates the gateway's /v1/test-connection endpoint, so
+// callTestConnection's response parsing (success, structured error, malformed body) is verified without a gateway.
+describe("callTestConnection", () => {
+ let server: http.Server;
+ let port: number;
+ let handler: (req: http.IncomingMessage, res: http.ServerResponse) => void;
+
+ beforeEach(async () => {
+ server = http.createServer((req, res) => handler(req, res));
+ await new Promise<void>((resolve) => {
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ port = (server.address() as AddressInfo).port;
+ });
+
+ afterEach(async () => {
+ await new Promise<void>((resolve) => {
+ server.close(() => resolve());
+ });
+ });
+
+ const body = { mode: "postgres", username: "postgres", password: "postgres", database: "postgres" };
+
+ it("returns ok on a 200 result response", async () => {
+ let receivedBody = "";
+ handler = (req, res) => {
+ req.on("data", (c) => {
+ receivedBody += c;
+ });
+ req.on("end", () => {
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ result: { ok: true } }));
+ });
+ };
+
+ const response = await callTestConnection({ port, body, timeoutMs: 5000 });
+ expect(response.ok).toBe(true);
+
+ expect(JSON.parse(receivedBody)).toMatchObject({ ...body, timeoutMs: 5000 });
+ });
+
+ it("surfaces the gateway's structured error on a non-2xx response", async () => {
+ handler = (_req, res) => {
+ res.writeHead(502, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ error: { message: "password authentication failed" } }));
+ };
+
+ const response = await callTestConnection({ port, body, timeoutMs: 5000 });
+ expect(response.ok).toBe(false);
+ if (!response.ok) {
+ expect(response.errorMessage).toBe("password authentication failed");
+ }
+ });
+
+ it("falls back to a generic message when the error body is malformed", async () => {
+ handler = (_req, res) => {
+ res.writeHead(500, { "Content-Type": "text/plain" });
+ res.end("upstream exploded");
+ };
+
+ const response = await callTestConnection({ port, body, timeoutMs: 5000 });
+ expect(response.ok).toBe(false);
+ if (!response.ok) {
+ expect(response.errorMessage).toContain("HTTP 500");
+ }
+ });
+});
diff --git a/backend/src/lib/gateway-v2/test-connection-rpc.ts b/backend/src/lib/gateway-v2/test-connection-rpc.ts
new file mode 100644
index 0000000000..585ffe406e
--- /dev/null
+++ b/backend/src/lib/gateway-v2/test-connection-rpc.ts
@@ -0,0 +1,77 @@
+import http from "node:http";
+
+import { logger } from "@app/lib/logger";
+
+export type TestConnectionResponse = { ok: true; status: number } | { ok: false; status: number; errorMessage: string };
+
+export const TEST_CONNECTION_RPC_TIMEOUT_MS = 60_000;
+
+const MAX_RPC_RESPONSE_BYTES = 1024 * 1024;
+
+// calls the gateway's /v1/test-connection handler over the local relay proxy with an opaque request body
+export const callTestConnection = (args: {
+ port: number;
+ body: Record<string, unknown>;
+ timeoutMs: number;
+ signal?: AbortSignal;
+}): Promise<TestConnectionResponse> => {
+ const payload = JSON.stringify({ ...args.body, timeoutMs: args.timeoutMs });
+ return new Promise<TestConnectionResponse>((resolve, reject) => {
+ const req = http.request(
+ {
+ host: "127.0.0.1",
+ port: args.port,
+ path: "/v1/test-connection",
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "Content-Length": Buffer.byteLength(payload).toString(),
+ Connection: "close"
+ },
+ timeout: TEST_CONNECTION_RPC_TIMEOUT_MS,
+ signal: args.signal
+ },
+ (res) => {
+ const chunks: Buffer[] = [];
+ let received = 0;
+ res.on("data", (chunk: Buffer) => {
+ received += chunk.length;
+ if (received > MAX_RPC_RESPONSE_BYTES) {
+ res.destroy(new Error(`Test connection response exceeded ${MAX_RPC_RESPONSE_BYTES} bytes`));
+ return;
+ }
+ chunks.push(chunk);
+ });
+ res.on("end", () => {
+ const text = Buffer.concat(chunks).toString("utf8");
+ const status = res.statusCode ?? 0;
+ const errEnv = (() => {
+ try {
+ return (JSON.parse(text) as { error?: { message?: string } }).error;
+ } catch {
+ return undefined;
+ }
+ })();
+ if (status >= 200 && status < 300) {
+ resolve({ ok: true, status });
+ return;
+ }
+ resolve({ ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` });
+ });
+ res.on("error", (err) => {
+ logger.warn({ err }, `Test connection RPC response stream error [port=${args.port}]`);
+ reject(err);
+ });
+ }
+ );
+ req.on("timeout", () => {
+ req.destroy(new Error(`Test connection RPC timed out after ${TEST_CONNECTION_RPC_TIMEOUT_MS}ms`));
+ });
+ req.on("error", (err) => {
+ logger.warn({ err }, `Test connection RPC request error [port=${args.port}]`);
+ reject(err);
+ });
+ req.write(payload);
+ req.end();
+ });
+};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index b026d0a8a4..103a7492f5 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1904,6 +1904,7 @@ export const registerRoutes = async (
permissionService,
kmsService,
gatewayV2DAL,
+ gatewayV2Service,
gatewayPoolService,
appConnectionDAL,
pamAccessRequestService