Skip to content

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

fix(pam): correct heartbeat classification and status handling

bernie-gd46a63ebde19
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
index 47e6ec9b5b..fe0c3649fd 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
@@ -56,6 +56,11 @@ const PamAccountListItemSchema = SanitizedAccountListItemSchema.extend({
.array(z.nativeEnum(PamAccountAccessibilityIssue))
.describe("Reasons the account cannot launch a session, if any"),
isStale: z.boolean().describe("Whether the discovery source's latest scan no longer found this account."),
+ heartbeatStatus: z
+ .string()
+ .nullable()
+ .optional()
+ .describe("Result of the most recent credential health check, if one has run."),
requiresApproval: z.boolean().describe("Whether this account requires approval before launching a session"),
requireReason: z.boolean().describe("Whether the account's template requires a reason for access"),
accessStatus: z.nativeEnum(PamAccessStatus).describe("Current approval status for the caller"),
diff --git a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.test.ts b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.test.ts
index 65d4913bea..4ba0abb0b4 100644
--- a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.test.ts
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.test.ts
@@ -10,7 +10,7 @@ vi.mock("@app/lib/logger", () => ({
logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }
}));
-const gatewayTestConnection = vi.fn();
+const gatewayTestConnection = vi.fn<(...args: unknown[]) => Promise<unknown>>();
vi.mock("@app/ee/services/gateway-v2/gateway-v2-fns", () => ({
testConnectionWithGateway: (...args: unknown[]) => gatewayTestConnection(...args)
}));
@@ -58,7 +58,9 @@ const buildService = (
const deps = {
pamAccountDAL: {
- findByIdWithDetails: vi.fn(async (id: string) => (opts.rotator && id === opts.rotator.id ? opts.rotator : account)),
+ findByIdWithDetails: vi.fn(async (id: string) =>
+ opts.rotator && id === opts.rotator.id ? opts.rotator : account
+ ),
updateById
},
gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() },
@@ -163,16 +165,11 @@ describe("heartbeat: Windows", () => {
await service.checkScheduledAccount("acc-ad");
- expect(testCredential).toHaveBeenCalledWith(
- expect.objectContaining({ verifyVia: undefined }),
- expect.anything()
- );
+ expect(testCredential).toHaveBeenCalledWith(expect.objectContaining({ verifyVia: undefined }), expect.anything());
});
test("an account with no stored password is unknown, not failing", async () => {
- const { service } = buildService(
- buildWindowsAccount({ encryptedCredentials: blobOf({ username: "svc_app" }) })
- );
+ const { service } = buildService(buildWindowsAccount({ encryptedCredentials: blobOf({ username: "svc_app" }) }));
const result = await service.checkScheduledAccount("acc-win");
@@ -218,7 +215,7 @@ describe("heartbeat: SSH certificate", () => {
const result = await service.checkScheduledAccount("acc-ssh");
expect(result?.status).toBe(PamHeartbeatStatus.Healthy);
- const [, , , , request] = gatewayTestConnection.mock.calls[0] as unknown[];
+ const [, , , , request] = gatewayTestConnection.mock.calls[0];
expect(request).toMatchObject({ mode: "ssh", authMethod: PamSshAuthMethod.Certificate, username: "ubuntu" });
expect((request as { certificate?: string }).certificate).toBeTruthy();
});
diff --git a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts
index 91ddbcb3c2..866405fa04 100644
--- a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts
@@ -5,6 +5,7 @@ import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ResourcePermissionPamResourceActions } from "@app/ee/services/permission/resource-permission";
import { NotFoundError } from "@app/lib/errors";
+import { GatewayFailureKind } from "@app/lib/gateway-v2/test-connection-rpc";
import { logger } from "@app/lib/logger";
import { createSshCert, createSshKeyPair, SshCertKeyAlgorithm, SshCertType } from "@app/lib/ssh";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -24,7 +25,7 @@ import {
validateConnectionDetails,
validateCredentials
} from "../pam-account/pam-account-schemas";
-import { isWindowsRotatableType, TRotatableType } from "../pam-account-rotation/pam-rotation-fns";
+import { isWindowsRotatableType, redactRotationError, TRotatableType } from "../pam-account-rotation/pam-rotation-fns";
import { PAM_ROTATION_FACTORY_MAP, winrmConnectUsername } from "../pam-account-rotation/pam-rotation-handlers";
import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";
import { TCheckAccountHeartbeatDTO, TPamHeartbeatResult } from "./pam-account-heartbeat-types";
@@ -34,6 +35,7 @@ import {
HEARTBEAT_SSH_CERT_TTL_SECONDS,
HEARTBEAT_TIMEOUT_MS,
isHeartbeatScheduled,
+ statusForFailureKind,
stopsSchedule
} from "./pam-heartbeat-fns";
@@ -94,7 +96,7 @@ export const pamAccountHeartbeatServiceFactory = ({
const { signedPublicKey } = await createSshCert({
caPrivateKey: internalMetadata.caPrivateKey,
clientPublicKey,
- keyId: `pam-heartbeat-${account.id}`,
+ keyId: `pam-hb-${account.id}`,
principals: [credentials.username as string],
requestedTtl: `${HEARTBEAT_SSH_CERT_TTL_SECONDS}s`,
certType: SshCertType.USER
@@ -126,7 +128,11 @@ export const pamAccountHeartbeatServiceFactory = ({
// Runs the account's own auth probe and classifies the outcome. Never throws for a target-side problem: a thrown
// error from here means we could not run the check at all, which is not a statement about the credential.
- const probe = async (account: TPamAccountDetail): Promise<{ status: PamHeartbeatStatus; message?: string }> => {
+ // Collected as the probe decrypts them, so any message we persist can be scrubbed of the credential itself.
+ const probe = async (
+ account: TPamAccountDetail,
+ usedSecrets: string[]
+ ): Promise<{ status: PamHeartbeatStatus; message?: string }> => {
const projectId = account.projectId as string;
const accountType = account.accountType as PamAccountType;
const project = await projectDAL.findById(projectId);
@@ -145,6 +151,10 @@ export const pamAccountHeartbeatServiceFactory = ({
accountType,
await decrypt(projectId, account.encryptedCredentials)
) as Record<string, unknown>;
+ for (const field of ["password", "privateKey", "serviceAccountKeyJson", "clientSecret", "serviceAccountToken"]) {
+ const value = credentials[field];
+ if (typeof value === "string" && value) usedSecrets.push(value);
+ }
const validateCloud = CLOUD_CONNECTION_VALIDATORS[accountType];
if (validateCloud) {
@@ -167,20 +177,36 @@ export const pamAccountHeartbeatServiceFactory = ({
}
const verifyVia = await resolveWindowsVerifier(account, accountType);
- const authenticated = await handler.testCredential(
- {
- accountType: accountType as TRotatableType,
- connectionDetails,
- auth: {
- username: winrmConnectUsername(accountType as TRotatableType, connectionDetails, username),
- password
+ if (verifyVia?.password) usedSecrets.push(verifyVia.password);
+
+ // A self-checked Windows account surfaces a rejected password as a thrown 401 rather than `false`, so
+ // without this branch it would read as unreachable and keep retrying into a lockout.
+ let authenticated: boolean;
+ try {
+ authenticated = await handler.testCredential(
+ {
+ accountType: accountType as TRotatableType,
+ connectionDetails,
+ auth: {
+ username: winrmConnectUsername(accountType as TRotatableType, connectionDetails, username),
+ password
+ },
+ verifyVia,
+ gatewayId: account.gatewayId ?? account.templateGatewayId,
+ gatewayPoolId: account.gatewayPoolId ?? account.templateGatewayPoolId
},
- verifyVia,
- gatewayId: account.gatewayId ?? account.templateGatewayId,
- gatewayPoolId: account.gatewayPoolId ?? account.templateGatewayPoolId
- },
- { gatewayService, gatewayV2Service, gatewayPoolService }
- );
+ { gatewayService, gatewayV2Service, gatewayPoolService }
+ );
+ } catch (err) {
+ const kind = (err as { gatewayFailureKind?: GatewayFailureKind | null }).gatewayFailureKind ?? null;
+ if (kind === "auth") {
+ return {
+ status: PamHeartbeatStatus.InvalidCredentials,
+ message: "The target rejected this credential"
+ };
+ }
+ throw err;
+ }
return authenticated
? { status: PamHeartbeatStatus.Healthy }
@@ -190,7 +216,9 @@ export const pamAccountHeartbeatServiceFactory = ({
const probeCredentials =
accountType === PamAccountType.SSH ? await mintEphemeralSshCertificate(account, credentials) : credentials;
- const test = await buildGatewayConnectionTest(accountType, connectionDetails, probeCredentials, orgId);
+ const test = await buildGatewayConnectionTest(accountType, connectionDetails, probeCredentials, orgId, {
+ allowWindowsAuthSql: true
+ });
if (!test) {
return { status: PamHeartbeatStatus.Unknown, message: "This account type cannot be checked yet" };
}
@@ -230,7 +258,7 @@ export const pamAccountHeartbeatServiceFactory = ({
return { status: PamHeartbeatStatus.CannotCheck, message: "The gateway could not be reached" };
}
if (!result.ok) {
- return { status: PamHeartbeatStatus.InvalidCredentials, message: result.errorMessage };
+ return { status: statusForFailureKind(result.kind), message: result.errorMessage };
}
return { status: PamHeartbeatStatus.Healthy };
};
@@ -259,16 +287,22 @@ export const pamAccountHeartbeatServiceFactory = ({
const runCheck = async (account: TPamAccountDetail): Promise<TPamHeartbeatResult> => {
const now = new Date();
+ // A target can echo the credential back in its error (the WinRM path interpolates it into a script), and
+ // this message is persisted and audited, so everything the probe used gets scrubbed out of it.
+ const usedSecrets: string[] = [];
let outcome: { status: PamHeartbeatStatus; message?: string };
try {
- outcome = await probe(account);
+ outcome = await probe(account, usedSecrets);
} catch (err) {
logger.warn(err, `PAM heartbeat could not complete [accountId=${account.id}]`);
outcome = {
status: PamHeartbeatStatus.CannotCheck,
- message: err instanceof Error ? err.message : "The check could not be completed"
+ message: redactRotationError(err, usedSecrets)
};
}
+ if (outcome.message) {
+ outcome = { ...outcome, message: redactRotationError(new Error(outcome.message), usedSecrets) };
+ }
await recordResult(account, outcome, now);
diff --git a/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.ts b/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.ts
index aa211fa949..e4a0f75305 100644
--- a/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.ts
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.ts
@@ -1,3 +1,5 @@
+import { GatewayFailureKind } from "@app/lib/gateway-v2/test-connection-rpc";
+
import { PamHeartbeatStatus } from "../pam/pam-enums";
import { TPamHeartbeatConfig } from "../pam-account-template/pam-account-template-schemas";
@@ -47,12 +49,24 @@ const TRANSPORT_ERROR_PATTERNS = [
"enotfound",
"eai_again",
"socket hang up",
+ "throttl",
+ "slowdown",
+ "rate exceeded",
+ "too many requests",
"timeout",
"timed out",
"gateway",
"tunnel"
];
+// The gateway classifies the failure where the driver error still exists. An unclassified failure (an older
+// gateway, or one the gateway could not place) resolves to a rejected credential, matching the rule that an
+// ambiguous result costs a false alarm rather than a retry loop into a lockout.
+export const statusForFailureKind = (kind: GatewayFailureKind | null): PamHeartbeatStatus => {
+ if (kind === "transport") return PamHeartbeatStatus.CannotCheck;
+ return PamHeartbeatStatus.InvalidCredentials;
+};
+
// Cloud accounts (AWS IAM, GCP, Azure) are brokered by us rather than logged into, so there is no lockout to trigger
// and a rejection here means access was revoked. Transport failures still have to stay out of that bucket.
export const classifyCloudProbeError = (err: unknown): PamHeartbeatStatus => {
diff --git a/backend/src/ee/services/pam-account/pam-account-connection-test.test.ts b/backend/src/ee/services/pam-account/pam-account-connection-test.test.ts
index 74e308ea9d..07cd25c427 100644
--- a/backend/src/ee/services/pam-account/pam-account-connection-test.test.ts
+++ b/backend/src/ee/services/pam-account/pam-account-connection-test.test.ts
@@ -19,7 +19,8 @@ describe("buildGatewayConnectionTest: MSSQL Windows authentication", () => {
PamAccountType.MsSQL,
connectionDetails,
{ authMethod: "ntlm", username: "svc_app", password: "pw", domain: "CORP" },
- ORG_ID
+ ORG_ID,
+ { allowWindowsAuthSql: true }
);
expect(result?.request.mode).toBe(TestConnectionMode.SQL);
@@ -38,7 +39,8 @@ describe("buildGatewayConnectionTest: MSSQL Windows authentication", () => {
kdcAddress: "dc1.corp.example.com",
spn: "MSSQLSvc/sql.corp.example.com:1433"
},
- ORG_ID
+ ORG_ID,
+ { allowWindowsAuthSql: true }
);
expect(result?.request.mode).toBe(TestConnectionMode.SQL);
@@ -62,6 +64,19 @@ describe("buildGatewayConnectionTest: MSSQL Windows authentication", () => {
expect(result?.request).toMatchObject({ domain: undefined, realm: undefined });
});
+ // Account create and update call this without the opt so they keep working against a gateway that predates
+ // the proxy handshake, where sending a Windows login as a SQL login would fail the save outright.
+ test("callers that omit the opt keep the old reachability check", async () => {
+ const result = await buildGatewayConnectionTest(
+ PamAccountType.MsSQL,
+ connectionDetails,
+ { authMethod: "ntlm", username: "svc_app", password: "pw", domain: "CORP" },
+ ORG_ID
+ );
+
+ expect(result?.request.mode).toBe(TestConnectionMode.Tcp);
+ });
+
test("an account with no credential still falls back to a reachability check", async () => {
const result = await buildGatewayConnectionTest(PamAccountType.MsSQL, connectionDetails, null, ORG_ID);
expect(result?.request.mode).toBe(TestConnectionMode.Tcp);
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
index 2d3f528f95..37a5adb716 100644
--- a/backend/src/ee/services/pam-account/pam-account-connection-test.ts
+++ b/backend/src/ee/services/pam-account/pam-account-connection-test.ts
@@ -95,7 +95,11 @@ export const buildGatewayConnectionTest = async (
accountType: PamAccountType,
connectionDetails: Record<string, unknown>,
credentials: Record<string, unknown> | null,
- orgId: string
+ orgId: string,
+ // Windows-auth MSSQL needs a gateway that routes it through the WinRM-capable proxy handshake. Callers that
+ // must not fail against an older gateway (account create and update) leave this off and get a reachability
+ // check for those logins, exactly as before.
+ opts?: { allowWindowsAuthSql?: boolean }
): Promise<{ host: string; port: number; request: TestConnectionRequest } | null> => {
const creds = credentials && isCredentialConfigured(accountType, credentials) ? credentials : null;
@@ -131,6 +135,9 @@ export const buildGatewayConnectionTest = async (
spn?: string;
} | null;
if (!c) return tcp(host, port);
+ if (accountType === PamAccountType.MsSQL && c.authMethod !== "sql-login" && !opts?.allowWindowsAuthSql) {
+ return tcp(host, port);
+ }
// An IAM login's password is a token Infisical mints per connection, so the test mints its own
const password =
c.authMethod === PamPostgresAuthMethod.AwsIam
diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.ts
index b109946d8f..94faf694e8 100644
--- a/backend/src/ee/services/pam-account/pam-account-dal.ts
+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts
@@ -102,6 +102,7 @@ export type TPamAccountListItem = Pick<
| "gatewayPoolId"
| "recordingConnectionId"
| "settingsOverrides"
+ | "heartbeatStatus"
| "createdAt"
| "updatedAt"
> &
@@ -202,6 +203,7 @@ export const pamAccountDALFactory = (db: TDbClient) => {
`${TableName.PamAccountTemplate}.gatewayPoolId as templateGatewayPoolId`,
`${TableName.PamAccountTemplate}.recordingConnectionId as templateRecordingConnectionId`,
`${TableName.PamFolder}.name as folderName`,
+ `${TableName.PamAccount}.heartbeatStatus`,
db.raw(`${staleAccountExistsSql(TableName.PamAccount)} as "isStale"`)
)
.orderBy(`${TableName.PamFolder}.name`, "asc")
@@ -355,6 +357,9 @@ export const pamAccountDALFactory = (db: TDbClient) => {
let nextHeartbeatAt: Date | null = current;
if (!heartbeat?.enabled || heartbeat.intervalSeconds == null) {
nextHeartbeatAt = null;
+ } else if (!current && account.heartbeatStatus === PamHeartbeatStatus.InvalidCredentials) {
+ // Stopped for a rejected credential. Only a credential change clears that, not a gateway or template edit.
+ nextHeartbeatAt = null;
} else if (!current) {
nextHeartbeatAt = computeNextHeartbeatAt({
anchor: account.lastHeartbeatAt ?? null,
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 ebee5181ba..41fefcc66e 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -278,6 +278,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
isAccessible: isAccessible && accessibilityIssues.length === 0,
accessibilityIssues,
isStale: a.isStale,
+ heartbeatStatus: a.heartbeatStatus ?? null,
requiresApproval,
requireReason,
accessStatus: requiresApproval ? (statusEntry?.accessStatus ?? PamAccessStatus.None) : PamAccessStatus.None,
@@ -732,6 +733,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
updateData.rotationAccountId = null;
}
+ let credentialVerified = false;
// re-test whenever the connection could have changed
if (
connectionDetails !== undefined ||
@@ -749,7 +751,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
if (!testCredentials && CLOUD_CONNECTION_VALIDATORS[accountType]) {
testCredentials = validateCredentials(accountType, await decrypt(projectId, existing.encryptedCredentials));
}
- await assertConnectionOk(
+ credentialVerified = await assertConnectionOk(
accountType,
testConnectionDetails,
testCredentials,
@@ -763,6 +765,16 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
);
}
+ // The health shown on the account describes the credential that was just replaced, so a corrected password
+ // would otherwise keep its "out of sync" badge until the next scheduled check.
+ if (credentials && credentialVerified) {
+ const verifiedAt = new Date();
+ updateData.heartbeatStatus = PamHeartbeatStatus.Healthy;
+ updateData.lastHeartbeatAt = verifiedAt;
+ updateData.lastHeartbeatHealthyAt = verifiedAt;
+ updateData.encryptedLastHeartbeatMessage = null;
+ }
+
try {
const account = await pamAccountDAL.transaction(async (tx) => {
const updated = await pamAccountDAL.updateById(accountId, updateData, tx);
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
index 47e5f4c39d..6bb1a81858 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
@@ -4,6 +4,7 @@ import { BadRequestError } from "@app/lib/errors";
import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { callPortSweep, callSshExec, SshExecCredentials } from "@app/lib/gateway-v2/ssh-rpc";
+import { GatewayFailureKind } from "@app/lib/gateway-v2/test-connection-rpc";
import { callWinRmEndpoint, WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-rpc";
import { verifyHostInputValidity } from "../dynamic-secret/dynamic-secret-fns";
@@ -235,7 +236,13 @@ export const winrmRpcWithGateway = async <T>({
);
if (!response.ok) {
- throw new BadRequestError({ message: `WinRM gateway operation failed: ${response.errorMessage ?? ""}` });
+ // Carries the gateway's classification so a caller can tell a rejected credential from an unreachable
+ // host without re-parsing the message.
+ const err = new BadRequestError({
+ message: `WinRM gateway operation failed: ${response.errorMessage ?? ""}`
+ }) as BadRequestError & { gatewayFailureKind?: GatewayFailureKind | null };
+ err.gatewayFailureKind = response.kind ?? null;
+ throw err;
}
return response.result;
};
diff --git a/backend/src/lib/gateway-v2/test-connection-rpc.ts b/backend/src/lib/gateway-v2/test-connection-rpc.ts
index 943538ef84..a0bff3cf7a 100644
--- a/backend/src/lib/gateway-v2/test-connection-rpc.ts
+++ b/backend/src/lib/gateway-v2/test-connection-rpc.ts
@@ -1,6 +1,12 @@
import { postGatewayRpc } from "./gateway-rpc";
-export type TestConnectionResponse = { ok: true; status: number } | { ok: false; status: number; errorMessage: string };
+// The gateway classifies a probe failure at the source, where the driver error still exists. Older gateways
+// send no kind, which the caller must treat as unclassified rather than as either outcome.
+export type GatewayFailureKind = "auth" | "transport" | "unknown";
+
+export type TestConnectionResponse =
+ | { ok: true; status: number }
+ | { ok: false; status: number; errorMessage: string; kind: GatewayFailureKind | null };
export const TEST_CONNECTION_RPC_TIMEOUT_MS = 60_000;
@@ -27,10 +33,15 @@ export const callTestConnection = async (args: {
const errEnv = (() => {
try {
- return (JSON.parse(text) as { error?: { message?: string } }).error;
+ return (JSON.parse(text) as { error?: { message?: string; kind?: GatewayFailureKind } }).error;
} catch {
return undefined;
}
})();
- return { ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` };
+ return {
+ ok: false,
+ status,
+ errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}`,
+ kind: errEnv?.kind ?? null
+ };
};
diff --git a/backend/src/lib/gateway-v2/winrm-rpc.ts b/backend/src/lib/gateway-v2/winrm-rpc.ts
index ddc3b70d8a..8ad41c2af6 100644
--- a/backend/src/lib/gateway-v2/winrm-rpc.ts
+++ b/backend/src/lib/gateway-v2/winrm-rpc.ts
@@ -1,4 +1,5 @@
import { postGatewayRpc } from "./gateway-rpc";
+import { GatewayFailureKind } from "./test-connection-rpc";
export enum WinRmRpcEndpoint {
Test = "/v1/test-connection",
@@ -35,7 +36,13 @@ export type WinRmRemoveResult = { removed: number };
export type WinRmRunCommandResult = { stdout: string; stderr: string; exitCode: number };
export type WinRmRpcSuccess<T> = { ok: true; status: number; result: T };
-export type WinRmRpcFailure = { ok: false; status: number; errorMessage: string };
+export type WinRmRpcFailure = {
+ ok: false;
+ status: number;
+ errorMessage: string;
+ // The gateway separates a rejected credential from an unreachable host. Older gateways send nothing.
+ kind?: GatewayFailureKind | null;
+};
export type WinRmRpcResponse<T> = WinRmRpcSuccess<T> | WinRmRpcFailure;
// Must exceed the gateway's own connection deadline (op 120s + 15s flush margin) so a gateway-side timeout
@@ -75,6 +82,11 @@ export const callWinRmEndpoint = async <T>(args: {
}
return { ok: true, status, result };
}
- const errEnv = (parsed as { error?: { message?: string } }).error;
- return { ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` };
+ const errEnv = (parsed as { error?: { message?: string; kind?: GatewayFailureKind } }).error;
+ return {
+ ok: false,
+ status,
+ errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}`,
+ kind: errEnv?.kind ?? null
+ };
};
diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx
index 3adbb1d544..b0a56a6beb 100644
--- a/frontend/src/hooks/api/pam/mutations.tsx
+++ b/frontend/src/hooks/api/pam/mutations.tsx
@@ -790,7 +790,9 @@ export const useCheckPamAccountHeartbeat = () => {
},
onSettled: (_, __, { accountId }) => {
queryClient.invalidateQueries({ queryKey: pamKeys.accountHeartbeat(accountId) });
- queryClient.invalidateQueries({ queryKey: pamKeys.getAccount(accountId) });
+ // The row badge reads its status from the account lists, which are keyed by filters this caller
+ // doesn't know, so invalidate the whole account namespace rather than guess them.
+ queryClient.invalidateQueries({ queryKey: pamKeys.account() });
}
});
};
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index b88b8dd87e..0e0fed9680 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -14,6 +14,7 @@ import {
PamAccessStatus,
PamAccountType,
PamApproverType,
+ PamHeartbeatStatus,
PamResourcePermissionActions,
PamResourcePermissionSub
} from "./enums";
@@ -211,6 +212,7 @@ export type TPamAccountListItem = {
accessibilityIssues: PamAccountAccessibilityIssue[];
// the latest discovery scan didn't find it. Informational only, nothing about the account is blocked.
isStale: boolean;
+ heartbeatStatus?: PamHeartbeatStatus | null;
requiresApproval: boolean;
requireReason: boolean;
accessStatus: PamAccessStatus;
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index 653cb100cf..ffaa0e4178 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -223,6 +223,7 @@ export type TPamAccount = {
accessibilityIssues: PamAccountAccessibilityIssue[];
// the latest discovery scan didn't find it. Informational only, nothing about the account is blocked.
isStale: boolean;
+ heartbeatStatus?: PamHeartbeatStatus | null;
createdAt: string;
updatedAt: string;
};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/CredentialHealthSection.tsx b/frontend/src/pages/pam/PamAccountsPage/components/CredentialHealthSection.tsx
index 7ce215c05e..e920bdc534 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/CredentialHealthSection.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/CredentialHealthSection.tsx
@@ -1,34 +1,45 @@
import { formatDistanceToNow } from "date-fns";
import { createNotification } from "@app/components/notifications";
-import { Alert, AlertDescription, AlertTitle, Button } from "@app/components/v3";
+import { Button } from "@app/components/v3";
import { PamHeartbeatStatus } from "@app/hooks/api/pam/enums";
import { useCheckPamAccountHeartbeat } from "@app/hooks/api/pam/mutations";
import { useGetPamAccountHeartbeat } from "@app/hooks/api/pam/queries";
-const STATUS: Record<PamHeartbeatStatus, { label: string; indicator: string; className: string }> =
- {
- [PamHeartbeatStatus.Healthy]: {
- label: "Healthy",
- indicator: "●",
- className: "text-success"
- },
- [PamHeartbeatStatus.InvalidCredentials]: {
- label: "Rejected",
- indicator: "●",
- className: "text-danger"
- },
- [PamHeartbeatStatus.CannotCheck]: {
- label: "Unreachable",
- indicator: "●",
- className: "text-warning"
- },
- [PamHeartbeatStatus.Unknown]: {
- label: "Not checked",
- indicator: "○",
- className: "text-muted"
- }
- };
+type StatusPresentation = {
+ label: string;
+ indicator: string;
+ className: string;
+ // Tint for the reason box, matching how a failed dependency sync is shown.
+ reasonClassName: string;
+};
+
+const STATUS: Record<PamHeartbeatStatus, StatusPresentation> = {
+ [PamHeartbeatStatus.Healthy]: {
+ label: "Healthy",
+ indicator: "●",
+ className: "text-success",
+ reasonClassName: ""
+ },
+ [PamHeartbeatStatus.InvalidCredentials]: {
+ label: "Out of Sync",
+ indicator: "●",
+ className: "text-danger",
+ reasonClassName: "border-danger/40 bg-danger/10 text-danger"
+ },
+ [PamHeartbeatStatus.CannotCheck]: {
+ label: "Unreachable",
+ indicator: "●",
+ className: "text-warning",
+ reasonClassName: "border-warning/40 bg-warning/10 text-warning"
+ },
+ [PamHeartbeatStatus.Unknown]: {
+ label: "Unchecked",
+ indicator: "○",
+ className: "text-muted",
+ reasonClassName: "border-border bg-container text-muted"
+ }
+};
const DetailRow = ({ label, children }: { label: string; children: React.ReactNode }) => (
<div className="flex items-center justify-between gap-3 border-b border-border py-3 last:border-b-0">
@@ -51,10 +62,9 @@ export const CredentialHealthSection = ({ accountId }: Props) => {
if (!accountId || isPending || !heartbeat) return null;
const status = heartbeat.status ?? PamHeartbeatStatus.Unknown;
- const { label, indicator, className } = STATUS[status];
+ const { label, indicator, className, reasonClassName } = STATUS[status];
const isHealthy = status === PamHeartbeatStatus.Healthy;
- const hasFailure =
- status === PamHeartbeatStatus.InvalidCredentials && Boolean(heartbeat.lastMessage);
+ const reason = !isHealthy && heartbeat.lastMessage ? heartbeat.lastMessage : null;
const handleCheckNow = async () => {
try {
@@ -85,6 +95,13 @@ export const CredentialHealthSection = ({ accountId }: Props) => {
<span className="text-sm text-muted">{relative(heartbeat.lastHealthyAt)}</span>
</DetailRow>
)}
+ {reason && (
+ <div
+ className={`mt-3 rounded-md border px-3 py-2 text-xs break-words whitespace-pre-line ${reasonClassName}`}
+ >
+ {reason}
+ </div>
+ )}
<Button
type="button"
@@ -95,15 +112,6 @@ export const CredentialHealthSection = ({ accountId }: Props) => {
>
Check now
</Button>
-
- {hasFailure && (
- <Alert variant="danger" className="mt-4">
- <AlertTitle>The target rejected this credential</AlertTitle>
- <AlertDescription className="whitespace-pre-line">
- {heartbeat.lastMessage}
- </AlertDescription>
- </Alert>
- )}
</div>
);
};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRow.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRow.tsx
index e89d36581a..7f42ecbcdf 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRow.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRow.tsx
@@ -8,6 +8,7 @@ import {
} from "@app/hooks/api/pam";
import { PamSheetTab } from "@app/hooks/usePamSheetState";
+import { AccountHealthBadge } from "../../components/AccountHealthBadge";
import { AccountStaleBadge } from "../../components/AccountStaleBadge";
import { PamAccountRow } from "../../components/PamAccountRow";
import { AccountAccessibilityBadgeWithPermission } from "./AccountAccessibilityBadgeWithPermission";
@@ -84,6 +85,7 @@ export const FolderAccountRow = ({
issues={account.accessibilityIssues}
/>
<AccountStaleBadge isStale={account.isStale} />
+ <AccountHealthBadge status={account.heartbeatStatus} />
</>
}
actions={
diff --git a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
index 6e3572d118..6f440e573f 100644
--- a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
@@ -291,7 +291,7 @@ const SettingsTab = ({
settings: {
sessionLogMaskingPatterns: "",
rotationEnabled: false,
- heartbeatEnabled: true,
+ heartbeatEnabled: false,
heartbeatIntervalSeconds: 86400,
rotationIntervalSeconds: 86400,
pwLength: 32,
@@ -346,7 +346,9 @@ const SettingsTab = ({
};
return {
rotationEnabled: rotation.enabled ?? false,
- heartbeatEnabled: heartbeat.enabled ?? true,
+ // Absent means a template that predates credential health. Defaulting it on here would turn
+ // scheduled logins on for its accounts the next time anything else on this form is saved.
+ heartbeatEnabled: heartbeat.enabled ?? false,
heartbeatIntervalSeconds: heartbeat.intervalSeconds ?? 86400,
rotationIntervalSeconds:
rotation.intervalSeconds !== undefined ? rotation.intervalSeconds : 86400,
diff --git a/frontend/src/pages/pam/components/AccountHealthBadge.tsx b/frontend/src/pages/pam/components/AccountHealthBadge.tsx
new file mode 100644
index 0000000000..1b662b934b
--- /dev/null
+++ b/frontend/src/pages/pam/components/AccountHealthBadge.tsx
@@ -0,0 +1,54 @@
+import { AlertTriangle } from "lucide-react";
+
+import { Badge, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
+import { PamHeartbeatStatus } from "@app/hooks/api/pam/enums";
+
+const BADGE: Partial<
+ Record<
+ PamHeartbeatStatus,
+ {
+ label: string;
+ variant: "danger" | "warning";
+ icon: typeof AlertTriangle;
+ tooltip: string;
+ }
+ >
+> = {
+ [PamHeartbeatStatus.InvalidCredentials]: {
+ label: "Out of Sync",
+ variant: "danger",
+ icon: AlertTriangle,
+ tooltip:
+ "The stored credential no longer matches the target, so sessions and rotation will fail. Checks are paused until it is updated, since repeated failed logins can lock the account out."
+ },
+ [PamHeartbeatStatus.CannotCheck]: {
+ label: "Unreachable",
+ variant: "warning",
+ icon: AlertTriangle,
+ tooltip:
+ "The target could not be reached on the last check, so the credential's state is unknown."
+ }
+};
+
+// The row only calls out what needs attention, like the stale badge. Healthy is silent, and so is an account
+// nobody has checked yet: the schedule will get to it, and one with no credential already has its own badge.
+export const AccountHealthBadge = ({ status }: { status?: string | null }) => {
+ const presentation = status ? BADGE[status as PamHeartbeatStatus] : undefined;
+ if (!presentation) return null;
+
+ const { label, variant, icon: Icon, tooltip } = presentation;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant={variant}>
+ <Icon className="size-3" />
+ {label}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ <p>{tooltip}</p>
+ </TooltipContent>
+ </Tooltip>
+ );
+};