Skip to content

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

feat(pam): credential health checks

bernie-gc4dfcb02a8b6
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 3cfaee5827..a4df7d2211 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -36,6 +36,7 @@ import { TLicenseV2ServiceFactory } from "@app/ee/services/license-v2/license-v2
import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
import { TPamAccessRequestServiceFactory } from "@app/ee/services/pam-access-request/pam-access-request-service";
import { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
+import { TPamAccountHeartbeatServiceFactory } from "@app/ee/services/pam-account-heartbeat/pam-account-heartbeat-service";
import { TPamAccountRotationServiceFactory } from "@app/ee/services/pam-account-rotation/pam-account-rotation-service";
import { TPamAccountTemplateServiceFactory } from "@app/ee/services/pam-account-template/pam-account-template-service";
import { TPamDiscoverySourceServiceFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-service";
@@ -440,6 +441,7 @@ declare module "fastify" {
pamAccount: TPamAccountServiceFactory;
pamDiscovery: TPamDiscoverySourceServiceFactory;
pamAccountRotation: TPamAccountRotationServiceFactory;
+ pamAccountHeartbeat: TPamAccountHeartbeatServiceFactory;
pamMembership: TPamMembershipServiceFactory;
pamSession: TPamSessionServiceFactory;
pamSessionChunk: TPamSessionChunkServiceFactory;
diff --git a/backend/src/db/migrations/20260825130000_pam-account-heartbeat.ts b/backend/src/db/migrations/20260825130000_pam-account-heartbeat.ts
new file mode 100644
index 0000000000..652d7116e4
--- /dev/null
+++ b/backend/src/db/migrations/20260825130000_pam-account-heartbeat.ts
@@ -0,0 +1,61 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasColumn(TableName.PamAccount, "heartbeatStatus"))) {
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.string("heartbeatStatus").nullable();
+ });
+ }
+ if (!(await knex.schema.hasColumn(TableName.PamAccount, "lastHeartbeatAt"))) {
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.timestamp("lastHeartbeatAt").nullable();
+ });
+ }
+ if (!(await knex.schema.hasColumn(TableName.PamAccount, "lastHeartbeatHealthyAt"))) {
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.timestamp("lastHeartbeatHealthyAt").nullable();
+ });
+ }
+ if (!(await knex.schema.hasColumn(TableName.PamAccount, "encryptedLastHeartbeatMessage"))) {
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.binary("encryptedLastHeartbeatMessage").nullable();
+ });
+ }
+ if (!(await knex.schema.hasColumn(TableName.PamAccount, "nextHeartbeatAt"))) {
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.timestamp("nextHeartbeatAt").nullable();
+ t.index("nextHeartbeatAt");
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasColumn(TableName.PamAccount, "nextHeartbeatAt")) {
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.dropIndex("nextHeartbeatAt");
+ t.dropColumn("nextHeartbeatAt");
+ });
+ }
+ if (await knex.schema.hasColumn(TableName.PamAccount, "encryptedLastHeartbeatMessage")) {
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.dropColumn("encryptedLastHeartbeatMessage");
+ });
+ }
+ if (await knex.schema.hasColumn(TableName.PamAccount, "lastHeartbeatHealthyAt")) {
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.dropColumn("lastHeartbeatHealthyAt");
+ });
+ }
+ if (await knex.schema.hasColumn(TableName.PamAccount, "lastHeartbeatAt")) {
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.dropColumn("lastHeartbeatAt");
+ });
+ }
+ if (await knex.schema.hasColumn(TableName.PamAccount, "heartbeatStatus")) {
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.dropColumn("heartbeatStatus");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/pam-accounts.ts b/backend/src/db/schemas/pam-accounts.ts
index a728d0aa08..e3aa3b8f65 100644
--- a/backend/src/db/schemas/pam-accounts.ts
+++ b/backend/src/db/schemas/pam-accounts.ts
@@ -37,7 +37,12 @@ export const PamAccountsSchema = z.object({
credentialConfigured: z.boolean().default(false),
rotationAccountId: z.string().uuid().nullable().optional(),
nextRotationAt: z.date().nullable().optional(),
- encryptedPendingCredentials: zodBuffer.nullable().optional()
+ encryptedPendingCredentials: zodBuffer.nullable().optional(),
+ heartbeatStatus: z.string().nullable().optional(),
+ lastHeartbeatAt: z.date().nullable().optional(),
+ lastHeartbeatHealthyAt: z.date().nullable().optional(),
+ encryptedLastHeartbeatMessage: zodBuffer.nullable().optional(),
+ nextHeartbeatAt: z.date().nullable().optional()
});
export type TPamAccounts = z.infer<typeof PamAccountsSchema>;
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 df8d783b77..47e6ec9b5b 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
@@ -622,6 +622,94 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "GET",
+ url: "/:accountId/heartbeat",
+ schema: {
+ operationId: "getPamAccountCredentialHealth",
+ description: "Get a PAM account's credential health",
+ tags: [ApiDocsTags.PamAccounts],
+ params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
+ response: {
+ 200: z.object({
+ heartbeat: z.object({
+ enabled: z.boolean(),
+ intervalSeconds: z.number().nullable(),
+ status: z.string().nullable(),
+ lastCheckedAt: z.date().nullable(),
+ lastHealthyAt: z.date().nullable(),
+ nextCheckAt: z.date().nullable(),
+ templateName: z.string(),
+ lastMessage: z.string().nullable()
+ })
+ })
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const heartbeat = await server.services.pamAccountHeartbeat.getHeartbeat(
+ { accountId: req.params.accountId, projectId: req.internalPamProjectId },
+ {
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ }
+ );
+ return { heartbeat };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:accountId/heartbeat/check",
+ schema: {
+ operationId: "checkPamAccountCredentialHealth",
+ description: "Run a credential health check on a PAM account now",
+ tags: [ApiDocsTags.PamAccounts],
+ params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
+ response: {
+ 200: z.object({
+ heartbeatStatus: z.string(),
+ message: z.string().optional()
+ })
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pamAccountHeartbeat.checkAccount(
+ { accountId: req.params.accountId, projectId: req.internalPamProjectId },
+ {
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ }
+ );
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalPamProjectId,
+ event: {
+ type: EventType.PAM_ACCOUNT_HEARTBEAT,
+ metadata: {
+ accountId: req.params.accountId,
+ accountType: result.accountType,
+ heartbeatStatus: result.status,
+ manual: true,
+ ...(result.message ? { message: result.message } : {})
+ }
+ }
+ });
+
+ // A failed check is a recorded result, not a failed request: the caller asked us to check, and we did.
+ return { heartbeatStatus: result.status, ...(result.message ? { message: result.message } : {}) };
+ }
+ });
+
server.route({
method: "POST",
url: "/:accountId/rotation/rotate",
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 1d6f47efdd..fdc31c1f9d 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -738,6 +738,7 @@ export enum EventType {
PAM_DISCOVERY_SCAN = "pam-discovery-scan",
PAM_DISCOVERED_ACCOUNT_IMPORT = "pam-discovered-account-import",
PAM_ACCOUNT_ROTATE_CREDENTIALS = "pam-account-rotate-credentials",
+ PAM_ACCOUNT_HEARTBEAT = "pam-account-heartbeat",
PAM_ACCOUNT_SET_ROTATION_ACCOUNT = "pam-account-set-rotation-account",
PAM_WEB_ACCESS_SESSION_TICKET_CREATED = "pam-web-access-session-ticket-created",
PAM_ACCESS_REQUEST_CREATE = "pam-access-request-create",
@@ -6052,6 +6053,17 @@ interface PamDiscoveredAccountImportEvent {
};
}
+interface PamAccountHeartbeatEvent {
+ type: EventType.PAM_ACCOUNT_HEARTBEAT;
+ metadata: {
+ accountId: string;
+ accountType: string;
+ heartbeatStatus: string;
+ manual: boolean;
+ message?: string;
+ };
+}
+
interface PamAccountRotateCredentialsEvent {
type: EventType.PAM_ACCOUNT_ROTATE_CREDENTIALS;
metadata: {
@@ -7656,6 +7668,7 @@ export type Event =
| PamDiscoveryScanEvent
| PamDiscoveredAccountImportEvent
| PamAccountRotateCredentialsEvent
+ | PamAccountHeartbeatEvent
| PamAccountSetRotationAccountEvent
| PamAccessRequestCreateEvent
| PamAccessRequestReviewEvent
diff --git a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-queue.ts b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-queue.ts
new file mode 100644
index 0000000000..06e3e0b5a1
--- /dev/null
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-queue.ts
@@ -0,0 +1,97 @@
+import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { getConfig } from "@app/lib/config/env";
+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
+import { logger } from "@app/lib/logger";
+import { resolveCoreMeter } from "@app/lib/telemetry/metrics";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { ActorType } from "@app/services/auth/auth-type";
+
+import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
+import { TPamAccountHeartbeatServiceFactory } from "./pam-account-heartbeat-service";
+
+const HEARTBEAT_DISCOVERY_BATCH = 100;
+
+type TPamAccountHeartbeatQueueServiceFactoryDep = {
+ queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+ pamAccountDAL: Pick<TPamAccountDALFactory, "findAccountsToHeartbeat" | "countAccountsToHeartbeat">;
+ pamAccountHeartbeatService: Pick<TPamAccountHeartbeatServiceFactory, "checkScheduledAccount">;
+};
+
+export const pamAccountHeartbeatQueueServiceFactory = async ({
+ queueService,
+ cronJob,
+ auditLogService,
+ pamAccountDAL,
+ pamAccountHeartbeatService
+}: TPamAccountHeartbeatQueueServiceFactoryDep) => {
+ const appCfg = getConfig();
+
+ const meter = resolveCoreMeter();
+ const pendingGauge = meter.createObservableGauge("infisical.pam_heartbeat.pending", {
+ description: "PAM accounts overdue for a credential check (nextHeartbeatAt <= now).",
+ unit: "{account}"
+ });
+ pendingGauge.addCallback(async (observableResult) => {
+ if (!appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) return;
+ try {
+ observableResult.observe(await pamAccountDAL.countAccountsToHeartbeat(new Date()));
+ } catch (err) {
+ logger.warn({ err }, "pam_heartbeat.pending gauge: count failed");
+ }
+ });
+
+ queueService.start(
+ QueueName.PamHeartbeatCheck,
+ async (job) => {
+ const result = await pamAccountHeartbeatService.checkScheduledAccount(job.data.accountId);
+ if (result) {
+ await auditLogService.createAuditLog({
+ projectId: result.projectId,
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ event: {
+ type: EventType.PAM_ACCOUNT_HEARTBEAT,
+ metadata: {
+ accountId: job.data.accountId,
+ accountType: result.accountType,
+ heartbeatStatus: result.status,
+ manual: false,
+ ...(result.message ? { message: result.message } : {})
+ }
+ }
+ });
+ }
+ },
+ { concurrency: 5, limiter: { max: 5, duration: 1000 } }
+ );
+
+ queueService.start(QueueName.PamHeartbeat, async () => {
+ const due = await pamAccountDAL.findAccountsToHeartbeat(new Date(), HEARTBEAT_DISCOVERY_BATCH);
+ for (const account of due) {
+ // eslint-disable-next-line no-await-in-loop
+ await queueService.queue(
+ QueueName.PamHeartbeatCheck,
+ QueueJobs.PamHeartbeatCheck,
+ { accountId: account.id },
+ {
+ // Failures reschedule through nextHeartbeatAt, so BullMQ retries would only re-audit the same result.
+ jobId: `pam-heartbeat-${account.id}`,
+ removeOnComplete: true,
+ removeOnFail: true
+ }
+ );
+ }
+ });
+
+ cronJob.register({
+ name: CronJobName.PamHeartbeatQueueChecks,
+ pattern: "*/5 * * * *",
+ runHashTtlS: 30 * 60,
+ handler: async () => {
+ await queueService.queue(QueueName.PamHeartbeat, QueueJobs.PamHeartbeatQueueChecks, undefined, {
+ jobId: CronJobName.PamHeartbeatQueueChecks
+ });
+ }
+ });
+};
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
new file mode 100644
index 0000000000..65d4913bea
--- /dev/null
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.test.ts
@@ -0,0 +1,225 @@
+import { beforeAll, describe, expect, test, vi } from "vitest";
+
+import { crypto } from "@app/lib/crypto/cryptography";
+
+import { PamAccountType, PamHeartbeatStatus, PamSshAuthMethod } from "../pam/pam-enums";
+import { PAM_ROTATION_FACTORY_MAP, TPamRotationHandler } from "../pam-account-rotation/pam-rotation-handlers";
+import { pamAccountHeartbeatServiceFactory } from "./pam-account-heartbeat-service";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }
+}));
+
+const gatewayTestConnection = vi.fn();
+vi.mock("@app/ee/services/gateway-v2/gateway-v2-fns", () => ({
+ testConnectionWithGateway: (...args: unknown[]) => gatewayTestConnection(...args)
+}));
+
+const blobOf = (data: Record<string, unknown>) => Buffer.from(JSON.stringify(data));
+
+const buildWindowsAccount = (overrides: Record<string, unknown> = {}) => ({
+ id: "acc-win",
+ projectId: "proj-1",
+ folderId: null,
+ accountType: PamAccountType.Windows,
+ credentialConfigured: true,
+ rotationAccountId: null,
+ encryptedCredentials: blobOf({ username: "svc_app", password: "pw" }),
+ encryptedConnectionDetails: blobOf({ host: "win.corp.local", port: 5985 }),
+ encryptedInternalMetadata: null,
+ templateSettings: { heartbeat: { enabled: true, intervalSeconds: 3600 } },
+ templateName: "Windows Prod",
+ templateGatewayId: "gw-1",
+ templateGatewayPoolId: null,
+ gatewayId: null,
+ gatewayPoolId: null,
+ ...overrides
+});
+
+const buildService = (
+ account: Record<string, unknown>,
+ opts: { testCredential?: TPamRotationHandler["testCredential"]; rotator?: Record<string, unknown> } = {}
+) => {
+ const updateById = vi.fn(async () => undefined);
+ const testCredential = opts.testCredential ?? vi.fn(async () => true);
+ const handler = { validateTarget: vi.fn(), applyPasswordChange: vi.fn(), testCredential } as TPamRotationHandler;
+ const rotationHandlers = {
+ [PamAccountType.Postgres]: handler,
+ [PamAccountType.MySQL]: handler,
+ [PamAccountType.MsSQL]: handler,
+ [PamAccountType.Windows]: handler,
+ [PamAccountType.WindowsAd]: handler
+ } as typeof PAM_ROTATION_FACTORY_MAP;
+
+ const identityCipher = {
+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),
+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob
+ };
+
+ const deps = {
+ pamAccountDAL: {
+ findByIdWithDetails: vi.fn(async (id: string) => (opts.rotator && id === opts.rotator.id ? opts.rotator : account)),
+ updateById
+ },
+ gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() },
+ gatewayV2Service: { getPlatformConnectionDetailsByGatewayId: vi.fn() },
+ gatewayPoolService: { resolveEffectiveGatewayId: vi.fn(async () => "gw-1") },
+ kmsService: { createCipherPairWithDataKey: vi.fn(async () => identityCipher) },
+ permissionService: { getProjectPermission: vi.fn(), getResourcePermission: vi.fn() },
+ projectDAL: { findById: vi.fn(async () => ({ id: "proj-1", orgId: "org-1" })) },
+ rotationHandlers
+ };
+
+ const service = pamAccountHeartbeatServiceFactory(
+ deps as unknown as Parameters<typeof pamAccountHeartbeatServiceFactory>[0]
+ );
+ return { service, updateById, testCredential };
+};
+
+describe("heartbeat: Windows", () => {
+ beforeAll(async () => {
+ await crypto.initialize({} as never, {} as never, {} as never);
+ });
+
+ test("a Windows account is checked over WinRM, not by a reachability probe", async () => {
+ const { service, testCredential, updateById } = buildService(buildWindowsAccount());
+
+ const result = await service.checkScheduledAccount("acc-win");
+
+ expect(testCredential).toHaveBeenCalledTimes(1);
+ expect(gatewayTestConnection).not.toHaveBeenCalled();
+ expect(result?.status).toBe(PamHeartbeatStatus.Healthy);
+ expect(updateById).toHaveBeenCalledWith(
+ "acc-win",
+ expect.objectContaining({ heartbeatStatus: PamHeartbeatStatus.Healthy })
+ );
+ });
+
+ test("a rejected credential stops the schedule instead of retrying into a lockout", async () => {
+ const { service, updateById } = buildService(buildWindowsAccount(), {
+ testCredential: vi.fn(async () => false)
+ });
+
+ const result = await service.checkScheduledAccount("acc-win");
+
+ expect(result?.status).toBe(PamHeartbeatStatus.InvalidCredentials);
+ expect(updateById).toHaveBeenCalledWith("acc-win", expect.objectContaining({ nextHeartbeatAt: null }));
+ });
+
+ test("a transport failure is never reported as a wrong password", async () => {
+ const { service, updateById } = buildService(buildWindowsAccount(), {
+ testCredential: vi.fn(async () => {
+ throw new Error("dial tcp: i/o timeout");
+ })
+ });
+
+ const result = await service.checkScheduledAccount("acc-win");
+
+ expect(result?.status).toBe(PamHeartbeatStatus.CannotCheck);
+ // Still scheduled: nothing here incremented a bad-password counter.
+ expect(updateById).toHaveBeenCalledWith(
+ "acc-win",
+ expect.objectContaining({ heartbeatStatus: PamHeartbeatStatus.CannotCheck })
+ );
+ const [, update] = updateById.mock.calls[0] as unknown as [string, { nextHeartbeatAt: Date | null }];
+ expect(update.nextHeartbeatAt).not.toBeNull();
+ });
+
+ test("a delegated local account validates through its rotator", async () => {
+ const rotator = {
+ id: "acc-rotator",
+ projectId: "proj-1",
+ encryptedCredentials: blobOf({ username: "admin", password: "admin-pw" })
+ };
+ const { service, testCredential } = buildService(buildWindowsAccount({ rotationAccountId: "acc-rotator" }), {
+ rotator
+ });
+
+ await service.checkScheduledAccount("acc-win");
+
+ expect(testCredential).toHaveBeenCalledWith(
+ expect.objectContaining({ verifyVia: { username: "admin", password: "admin-pw" } }),
+ expect.anything()
+ );
+ });
+
+ test("Windows AD binds as itself rather than through a rotator", async () => {
+ const { service, testCredential } = buildService(
+ buildWindowsAccount({
+ id: "acc-ad",
+ accountType: PamAccountType.WindowsAd,
+ rotationAccountId: "acc-rotator",
+ encryptedConnectionDetails: blobOf({
+ domain: "corp.local",
+ dcAddress: "dc1.corp.local",
+ hosts: "win1.corp.local",
+ port: 389,
+ rdpPort: 3389,
+ useLdaps: false,
+ ldapRejectUnauthorized: true
+ })
+ })
+ );
+
+ await service.checkScheduledAccount("acc-ad");
+
+ 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 result = await service.checkScheduledAccount("acc-win");
+
+ expect(result?.status).toBe(PamHeartbeatStatus.Unknown);
+ });
+});
+
+describe("heartbeat: SSH certificate", () => {
+ beforeAll(async () => {
+ await crypto.initialize({} as never, {} as never, {} as never);
+ });
+
+ test("mints a short-lived certificate and logs in with it", async () => {
+ gatewayTestConnection.mockReset();
+ gatewayTestConnection.mockResolvedValue({ ok: true });
+
+ const { SshCertKeyAlgorithm, createSshKeyPair } = await import("@app/lib/ssh");
+ const { publicKey, privateKey } = await createSshKeyPair(SshCertKeyAlgorithm.ED25519);
+
+ const account = {
+ id: "acc-ssh",
+ projectId: "proj-1",
+ folderId: null,
+ accountType: PamAccountType.SSH,
+ credentialConfigured: true,
+ rotationAccountId: null,
+ encryptedCredentials: blobOf({ authMethod: PamSshAuthMethod.Certificate, username: "ubuntu" }),
+ encryptedConnectionDetails: blobOf({ host: "10.0.0.5", port: 22 }),
+ encryptedInternalMetadata: blobOf({
+ caPrivateKey: privateKey,
+ caPublicKey: publicKey,
+ caKeyAlgorithm: "ED25519"
+ }),
+ templateSettings: { heartbeat: { enabled: true, intervalSeconds: 3600 } },
+ templateName: "SSH Prod",
+ templateGatewayId: "gw-1",
+ templateGatewayPoolId: null,
+ gatewayId: null,
+ gatewayPoolId: null
+ };
+
+ const { service } = buildService(account);
+ const result = await service.checkScheduledAccount("acc-ssh");
+
+ expect(result?.status).toBe(PamHeartbeatStatus.Healthy);
+ const [, , , , request] = gatewayTestConnection.mock.calls[0] as unknown[];
+ 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
new file mode 100644
index 0000000000..91ddbcb3c2
--- /dev/null
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts
@@ -0,0 +1,344 @@
+import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { testConnectionWithGateway } from "@app/ee/services/gateway-v2/gateway-v2-fns";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+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 { logger } from "@app/lib/logger";
+import { createSshCert, createSshKeyPair, SshCertKeyAlgorithm, SshCertType } from "@app/lib/ssh";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+
+import { PamAccountType, PamHeartbeatStatus, PamSshAuthMethod } from "../pam/pam-enums";
+import { checkAccountAccess, TActorContext } from "../pam/pam-permission";
+import {
+ buildGatewayConnectionTest,
+ CLOUD_CONNECTION_VALIDATORS,
+ TestConnectionMode
+} from "../pam-account/pam-account-connection-test";
+import { TPamAccountDALFactory, TPamAccountDetail } from "../pam-account/pam-account-dal";
+import {
+ parseInternalMetadata,
+ validateConnectionDetails,
+ validateCredentials
+} from "../pam-account/pam-account-schemas";
+import { isWindowsRotatableType, 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";
+import {
+ classifyCloudProbeError,
+ computeNextHeartbeatAt,
+ HEARTBEAT_SSH_CERT_TTL_SECONDS,
+ HEARTBEAT_TIMEOUT_MS,
+ isHeartbeatScheduled,
+ stopsSchedule
+} from "./pam-heartbeat-fns";
+
+type TPamAccountHeartbeatServiceFactoryDep = {
+ pamAccountDAL: TPamAccountDALFactory;
+ gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ permissionService: TPermissionServiceFactory;
+ projectDAL: Pick<TProjectDALFactory, "findById">;
+ rotationHandlers?: typeof PAM_ROTATION_FACTORY_MAP;
+};
+
+export type TPamAccountHeartbeatServiceFactory = ReturnType<typeof pamAccountHeartbeatServiceFactory>;
+
+export const pamAccountHeartbeatServiceFactory = ({
+ pamAccountDAL,
+ gatewayService,
+ gatewayV2Service,
+ gatewayPoolService,
+ kmsService,
+ permissionService,
+ projectDAL,
+ rotationHandlers = PAM_ROTATION_FACTORY_MAP
+}: TPamAccountHeartbeatServiceFactoryDep) => {
+ const withCipher = async (projectId: string) =>
+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
+
+ const decrypt = async (projectId: string, blob: Buffer): Promise<Record<string, unknown>> => {
+ const { decryptor } = await withCipher(projectId);
+ return JSON.parse(decryptor({ cipherTextBlob: blob }).toString()) as Record<string, unknown>;
+ };
+
+ const encryptMessage = async (projectId: string, message: string): Promise<Buffer> => {
+ const { encryptor } = await withCipher(projectId);
+ return encryptor({ plainText: Buffer.from(JSON.stringify({ message })) }).cipherTextBlob;
+ };
+
+ // Certificate accounts hold no long-lived secret: what can break is the host no longer trusting our CA, or the
+ // principal no longer existing. Minting a very short-lived certificate and logging in tests exactly that.
+ const mintEphemeralSshCertificate = async (
+ account: TPamAccountDetail,
+ credentials: Record<string, unknown>
+ ): Promise<Record<string, unknown>> => {
+ if (credentials.authMethod !== PamSshAuthMethod.Certificate || !account.encryptedInternalMetadata) {
+ return credentials;
+ }
+
+ const internalMetadata = parseInternalMetadata(
+ account.accountType as PamAccountType,
+ await decrypt(account.projectId as string, account.encryptedInternalMetadata)
+ );
+ if (!internalMetadata?.caPrivateKey) return credentials;
+
+ const keyAlgorithm = (internalMetadata.caKeyAlgorithm as SshCertKeyAlgorithm) || SshCertKeyAlgorithm.ED25519;
+ const { publicKey: clientPublicKey, privateKey: clientPrivateKey } = await createSshKeyPair(keyAlgorithm);
+ const { signedPublicKey } = await createSshCert({
+ caPrivateKey: internalMetadata.caPrivateKey,
+ clientPublicKey,
+ keyId: `pam-heartbeat-${account.id}`,
+ principals: [credentials.username as string],
+ requestedTtl: `${HEARTBEAT_SSH_CERT_TTL_SECONDS}s`,
+ certType: SshCertType.USER
+ });
+
+ return { ...credentials, privateKey: clientPrivateKey, certificate: signedPublicKey };
+ };
+
+ // A delegated Windows local account usually cannot WinRM in as itself, so the rotator validates its credential on
+ // the box the same way rotation does. AD binds with its own credential, so it never needs this.
+ const resolveWindowsVerifier = async (
+ account: TPamAccountDetail,
+ accountType: PamAccountType
+ ): Promise<{ username: string; password: string } | undefined> => {
+ if (accountType !== PamAccountType.Windows) return undefined;
+ if (!account.rotationAccountId || account.rotationAccountId === account.id) return undefined;
+
+ const rotator = await pamAccountDAL.findByIdWithDetails(account.rotationAccountId);
+ if (!rotator || rotator.projectId !== account.projectId) return undefined;
+
+ const rotatorCredentials = (await decrypt(account.projectId as string, rotator.encryptedCredentials)) as {
+ username?: string;
+ password?: string;
+ };
+ if (!rotatorCredentials.username || !rotatorCredentials.password) return undefined;
+
+ return { username: rotatorCredentials.username, password: rotatorCredentials.password };
+ };
+
+ // 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 }> => {
+ const projectId = account.projectId as string;
+ const accountType = account.accountType as PamAccountType;
+ const project = await projectDAL.findById(projectId);
+ if (!project) throw new NotFoundError({ message: "Project not found" });
+ const { orgId } = project;
+
+ if (!account.credentialConfigured) {
+ return { status: PamHeartbeatStatus.Unknown, message: "No credential is stored for this account" };
+ }
+
+ const connectionDetails = validateConnectionDetails(
+ accountType,
+ await decrypt(projectId, account.encryptedConnectionDetails)
+ ) as Record<string, unknown>;
+ const credentials = validateCredentials(
+ accountType,
+ await decrypt(projectId, account.encryptedCredentials)
+ ) as Record<string, unknown>;
+
+ const validateCloud = CLOUD_CONNECTION_VALIDATORS[accountType];
+ if (validateCloud) {
+ try {
+ await validateCloud({ connectionDetails, credentials, orgId });
+ return { status: PamHeartbeatStatus.Healthy };
+ } catch (err) {
+ const status = classifyCloudProbeError(err);
+ return { status, message: err instanceof Error ? err.message : "Unable to validate credentials" };
+ }
+ }
+
+ // Windows and AD have a real credential probe already (WinRM, or an LDAP bind for AD), but only through the
+ // rotation handlers; the shared connection test still falls back to a TCP check for them.
+ if (isWindowsRotatableType(accountType)) {
+ const handler = rotationHandlers[accountType as TRotatableType];
+ const { username, password } = credentials as { username: string; password?: string };
+ if (!password) {
+ return { status: PamHeartbeatStatus.Unknown, message: "No password is stored for this account" };
+ }
+
+ 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
+ },
+ verifyVia,
+ gatewayId: account.gatewayId ?? account.templateGatewayId,
+ gatewayPoolId: account.gatewayPoolId ?? account.templateGatewayPoolId
+ },
+ { gatewayService, gatewayV2Service, gatewayPoolService }
+ );
+
+ return authenticated
+ ? { status: PamHeartbeatStatus.Healthy }
+ : { status: PamHeartbeatStatus.InvalidCredentials, message: "The target rejected this credential" };
+ }
+
+ const probeCredentials =
+ accountType === PamAccountType.SSH ? await mintEphemeralSshCertificate(account, credentials) : credentials;
+
+ const test = await buildGatewayConnectionTest(accountType, connectionDetails, probeCredentials, orgId);
+ if (!test) {
+ return { status: PamHeartbeatStatus.Unknown, message: "This account type cannot be checked yet" };
+ }
+
+ // Every account type has a login-based check, so a TCP fallback here means the stored credential is incomplete
+ // (an SSH certificate account with no CA, a Kubernetes account missing its auth fields). Reaching the host proves
+ // nothing about the credential, so it can never read as Healthy.
+ if (test.request.mode === TestConnectionMode.Tcp) {
+ return {
+ status: PamHeartbeatStatus.Unknown,
+ message: "This account is missing the credential details needed to sign in"
+ };
+ }
+
+ const gatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
+ gatewayId: account.gatewayId ?? account.templateGatewayId,
+ gatewayPoolId:
+ (account.gatewayId ?? account.templateGatewayId)
+ ? null
+ : (account.gatewayPoolId ?? account.templateGatewayPoolId)
+ });
+ if (!gatewayId) {
+ return { status: PamHeartbeatStatus.CannotCheck, message: "No gateway is attached to this account" };
+ }
+
+ const result = await testConnectionWithGateway(
+ test.host,
+ test.port,
+ gatewayId,
+ gatewayV2Service,
+ test.request,
+ HEARTBEAT_TIMEOUT_MS
+ );
+
+ // A null result is our own gateway failing to answer, never the target refusing the credential.
+ if (!result) {
+ return { status: PamHeartbeatStatus.CannotCheck, message: "The gateway could not be reached" };
+ }
+ if (!result.ok) {
+ return { status: PamHeartbeatStatus.InvalidCredentials, message: result.errorMessage };
+ }
+ return { status: PamHeartbeatStatus.Healthy };
+ };
+
+ const recordResult = async (
+ account: TPamAccountDetail,
+ outcome: { status: PamHeartbeatStatus; message?: string },
+ now: Date
+ ) => {
+ const projectId = account.projectId as string;
+ const heartbeat = PamTemplateSettingsSchema.safeParse(account.templateSettings).data?.heartbeat;
+
+ const nextHeartbeatAt =
+ isHeartbeatScheduled(heartbeat) && !stopsSchedule(outcome.status)
+ ? computeNextHeartbeatAt({ anchor: now, intervalSeconds: heartbeat.intervalSeconds as number, now })
+ : null;
+
+ await pamAccountDAL.updateById(account.id, {
+ heartbeatStatus: outcome.status,
+ lastHeartbeatAt: now,
+ ...(outcome.status === PamHeartbeatStatus.Healthy ? { lastHeartbeatHealthyAt: now } : {}),
+ encryptedLastHeartbeatMessage: outcome.message ? await encryptMessage(projectId, outcome.message) : null,
+ nextHeartbeatAt
+ });
+ };
+
+ const runCheck = async (account: TPamAccountDetail): Promise<TPamHeartbeatResult> => {
+ const now = new Date();
+ let outcome: { status: PamHeartbeatStatus; message?: string };
+ try {
+ outcome = await probe(account);
+ } 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"
+ };
+ }
+
+ await recordResult(account, outcome, now);
+
+ return {
+ accountId: account.id,
+ projectId: account.projectId as string,
+ accountType: account.accountType as PamAccountType,
+ status: outcome.status,
+ ...(outcome.message ? { message: outcome.message } : {})
+ };
+ };
+
+ const checkScheduledAccount = async (accountId: string): Promise<TPamHeartbeatResult | null> => {
+ const account = await pamAccountDAL.findByIdWithDetails(accountId);
+ if (!account) return null;
+ return runCheck(account);
+ };
+
+ const checkAccount = async ({ accountId, projectId }: TCheckAccountHeartbeatDTO, ctx: TActorContext) => {
+ const account = await pamAccountDAL.findByIdWithDetails(accountId);
+ if (!account || account.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
+ }
+
+ await checkAccountAccess(
+ permissionService,
+ account.id,
+ account.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.EditAccounts,
+ ctx
+ );
+
+ return runCheck(account);
+ };
+
+ const getHeartbeat = async ({ accountId, projectId }: TCheckAccountHeartbeatDTO, ctx: TActorContext) => {
+ const account = await pamAccountDAL.findByIdWithDetails(accountId);
+ if (!account || account.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
+ }
+
+ await checkAccountAccess(
+ permissionService,
+ account.id,
+ account.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.ReadAccounts,
+ ctx
+ );
+
+ const heartbeat = PamTemplateSettingsSchema.safeParse(account.templateSettings).data?.heartbeat;
+
+ let lastMessage: string | null = null;
+ if (account.encryptedLastHeartbeatMessage) {
+ const decrypted = await decrypt(projectId, account.encryptedLastHeartbeatMessage);
+ lastMessage = (decrypted as { message?: string }).message ?? null;
+ }
+
+ return {
+ enabled: heartbeat?.enabled ?? false,
+ intervalSeconds: heartbeat?.intervalSeconds ?? null,
+ status: (account.heartbeatStatus as PamHeartbeatStatus | null) ?? null,
+ lastCheckedAt: account.lastHeartbeatAt ?? null,
+ lastHealthyAt: account.lastHeartbeatHealthyAt ?? null,
+ nextCheckAt: account.nextHeartbeatAt ?? null,
+ templateName: account.templateName,
+ lastMessage
+ };
+ };
+
+ return { checkAccount, checkScheduledAccount, getHeartbeat };
+};
diff --git a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-types.ts b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-types.ts
new file mode 100644
index 0000000000..d771b2cc8e
--- /dev/null
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-types.ts
@@ -0,0 +1,14 @@
+import { PamAccountType, PamHeartbeatStatus } from "../pam/pam-enums";
+
+export type TPamHeartbeatResult = {
+ accountId: string;
+ projectId: string;
+ accountType: PamAccountType;
+ status: PamHeartbeatStatus;
+ message?: string;
+};
+
+export type TCheckAccountHeartbeatDTO = {
+ accountId: string;
+ projectId: string;
+};
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
new file mode 100644
index 0000000000..aa211fa949
--- /dev/null
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.ts
@@ -0,0 +1,62 @@
+import { PamHeartbeatStatus } from "../pam/pam-enums";
+import { TPamHeartbeatConfig } from "../pam-account-template/pam-account-template-schemas";
+
+export const HEARTBEAT_TIMEOUT_MS = 15_000;
+
+// The check issues a genuinely usable certificate, so it lives only as long as the probe itself needs.
+export const HEARTBEAT_SSH_CERT_TTL_SECONDS = 60;
+
+// A heartbeat is a real login attempt, so a whole template's accounts must not fire at the same instant against
+// one domain controller. Same shape as rotation's jitter: a fraction of the interval, capped.
+export const HEARTBEAT_JITTER_FACTOR = 0.1;
+export const HEARTBEAT_JITTER_CAP_SECONDS = 30 * 60;
+
+export const heartbeatJitterCapSeconds = (intervalSeconds: number, capSeconds = HEARTBEAT_JITTER_CAP_SECONDS) =>
+ Math.min(intervalSeconds * HEARTBEAT_JITTER_FACTOR, capSeconds);
+
+export const computeNextHeartbeatAt = ({
+ anchor,
+ intervalSeconds,
+ now,
+ jitterCapSeconds
+}: {
+ anchor: Date | null;
+ intervalSeconds: number;
+ now: Date;
+ jitterCapSeconds?: number;
+}): Date => {
+ const base = Math.max((anchor ?? now).getTime() + intervalSeconds * 1000, now.getTime());
+ const jitterMs = Math.floor(Math.random() * heartbeatJitterCapSeconds(intervalSeconds, jitterCapSeconds) * 1000);
+ return new Date(base + jitterMs);
+};
+
+export const isHeartbeatScheduled = (heartbeat: TPamHeartbeatConfig | undefined): heartbeat is TPamHeartbeatConfig =>
+ heartbeat?.enabled === true && heartbeat.intervalSeconds != null;
+
+// A rejected credential takes the account off the schedule entirely: retrying a wrong password is how a monitoring
+// feature locks out a customer's privileged account. A person clears it by fixing the credential, running a manual
+// check, or rotating.
+export const stopsSchedule = (status: PamHeartbeatStatus) => status === PamHeartbeatStatus.InvalidCredentials;
+
+const TRANSPORT_ERROR_PATTERNS = [
+ "etimedout",
+ "econnrefused",
+ "econnreset",
+ "ehostunreach",
+ "enetunreach",
+ "enotfound",
+ "eai_again",
+ "socket hang up",
+ "timeout",
+ "timed out",
+ "gateway",
+ "tunnel"
+];
+
+// 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 => {
+ const message = (err instanceof Error ? err.message : String(err)).toLowerCase();
+ if (TRANSPORT_ERROR_PATTERNS.some((pattern) => message.includes(pattern))) return PamHeartbeatStatus.CannotCheck;
+ return PamHeartbeatStatus.InvalidCredentials;
+};
diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts b/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts
index 82fd9646e9..604551008c 100644
--- a/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts
+++ b/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts
@@ -11,6 +11,11 @@ export const PamRotationConfigSchema = z.object({
intervalSeconds: z.number().int().min(3600).max(31_536_000).nullable() // 1 hour .. 1 year, or null for manual
});
+export const PamHeartbeatConfigSchema = z.object({
+ enabled: z.boolean(),
+ intervalSeconds: z.number().int().min(3600).max(31_536_000).nullable() // 1 hour .. 1 year, or null for manual
+});
+
export const PamRecordingS3ConfigSchema = z.object({
bucket: z.string().trim().min(1),
region: z.nativeEnum(AWSRegion),
@@ -27,6 +32,7 @@ export const PamTemplateSettingsSchema = z.object({
recordingS3Config: PamRecordingS3ConfigSchema.optional(),
passwordRequirements: PasswordRequirementsSchema.optional(),
rotation: PamRotationConfigSchema.optional(),
+ heartbeat: PamHeartbeatConfigSchema.optional(),
sessionLogMaskingPatterns: z.string().optional()
});
@@ -37,3 +43,4 @@ export const PamTemplateSettingsInputSchema = PamTemplateSettingsSchema.extend({
export type TPamTemplateSettings = z.infer<typeof PamTemplateSettingsSchema>;
export type TPamAccountSettingsOverrides = z.infer<typeof PamAccountSettingsOverridesSchema>;
export type TPamRotationConfig = z.infer<typeof PamRotationConfigSchema>;
+export type TPamHeartbeatConfig = z.infer<typeof PamHeartbeatConfigSchema>;
diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-service.ts b/backend/src/ee/services/pam-account-template/pam-account-template-service.ts
index 30fa605f20..70b45464a7 100644
--- a/backend/src/ee/services/pam-account-template/pam-account-template-service.ts
+++ b/backend/src/ee/services/pam-account-template/pam-account-template-service.ts
@@ -39,7 +39,10 @@ const SAFE_PASSWORD_SYMBOLS = "!@#$%^&*()-_=+[]{}|:,.<>/~";
type TPamAccountTemplateServiceFactoryDep = TPamValidatorDeps & {
pamAccountTemplateDAL: TPamAccountTemplateDALFactory;
- pamAccountDAL: Pick<TPamAccountDALFactory, "reconcileRotationScheduleForTemplate">;
+ pamAccountDAL: Pick<
+ TPamAccountDALFactory,
+ "reconcileRotationScheduleForTemplate" | "reconcileHeartbeatScheduleForTemplate"
+ >;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
};
@@ -226,6 +229,14 @@ export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServic
{ rescheduleReady: newInterval !== undefined && oldInterval !== newInterval },
tx
);
+
+ const oldHeartbeat = PamTemplateSettingsSchema.safeParse(existing.settings).data?.heartbeat;
+ const newHeartbeat = PamTemplateSettingsSchema.safeParse(settings).data?.heartbeat;
+ await pamAccountDAL.reconcileHeartbeatScheduleForTemplate(
+ templateId,
+ { rescheduleAll: oldHeartbeat?.intervalSeconds !== newHeartbeat?.intervalSeconds },
+ tx
+ );
}
return updated;
});
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
new file mode 100644
index 0000000000..74e308ea9d
--- /dev/null
+++ b/backend/src/ee/services/pam-account/pam-account-connection-test.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, test } from "vitest";
+
+import { PamAccountType, PamSshAuthMethod } from "../pam/pam-enums";
+import { buildGatewayConnectionTest, TestConnectionMode } from "./pam-account-connection-test";
+
+const ORG_ID = "11111111-1111-1111-1111-111111111111";
+
+describe("buildGatewayConnectionTest: MSSQL Windows authentication", () => {
+ const connectionDetails = {
+ host: "sql.corp.example.com",
+ port: 1433,
+ database: "master",
+ sslEnabled: false,
+ sslRejectUnauthorized: true
+ };
+
+ test("ntlm logins authenticate instead of degrading to a 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.SQL);
+ expect(result?.request).toMatchObject({ authMethod: "ntlm", domain: "CORP", username: "svc_app" });
+ });
+
+ test("kerberos logins carry the realm, kdc, and spn the gateway needs", async () => {
+ const result = await buildGatewayConnectionTest(
+ PamAccountType.MsSQL,
+ connectionDetails,
+ {
+ authMethod: "kerberos",
+ username: "svc_app",
+ password: "pw",
+ realm: "CORP.EXAMPLE.COM",
+ kdcAddress: "dc1.corp.example.com",
+ spn: "MSSQLSvc/sql.corp.example.com:1433"
+ },
+ ORG_ID
+ );
+
+ expect(result?.request.mode).toBe(TestConnectionMode.SQL);
+ expect(result?.request).toMatchObject({
+ authMethod: "kerberos",
+ realm: "CORP.EXAMPLE.COM",
+ kdcAddress: "dc1.corp.example.com",
+ spn: "MSSQLSvc/sql.corp.example.com:1433"
+ });
+ });
+
+ test("sql-login is unchanged and sends no Windows auth fields", async () => {
+ const result = await buildGatewayConnectionTest(
+ PamAccountType.MsSQL,
+ connectionDetails,
+ { authMethod: "sql-login", username: "sa", password: "pw" },
+ ORG_ID
+ );
+
+ expect(result?.request).toMatchObject({ mode: TestConnectionMode.SQL, authMethod: "sql-login" });
+ expect(result?.request).toMatchObject({ domain: undefined, realm: undefined });
+ });
+
+ 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);
+ });
+});
+
+describe("buildGatewayConnectionTest: SSH certificate authentication", () => {
+ const connectionDetails = { host: "10.0.0.5", port: 22 };
+
+ test("a minted certificate is sent as a real login attempt", async () => {
+ const result = await buildGatewayConnectionTest(
+ PamAccountType.SSH,
+ connectionDetails,
+ {
+ authMethod: PamSshAuthMethod.Certificate,
+ username: "ubuntu",
+ privateKey: "PRIVATE_KEY",
+ certificate: "SIGNED_CERT"
+ },
+ ORG_ID
+ );
+
+ expect(result?.request).toMatchObject({
+ mode: TestConnectionMode.SSH,
+ authMethod: PamSshAuthMethod.Certificate,
+ username: "ubuntu",
+ certificate: "SIGNED_CERT",
+ privateKey: "PRIVATE_KEY"
+ });
+ });
+
+ test("without a certificate there is nothing to log in with, so it stays a reachability check", async () => {
+ const result = await buildGatewayConnectionTest(
+ PamAccountType.SSH,
+ connectionDetails,
+ { authMethod: PamSshAuthMethod.Certificate, username: "ubuntu" },
+ ORG_ID
+ );
+
+ expect(result?.request.mode).toBe(TestConnectionMode.Tcp);
+ });
+
+ test("password auth is unaffected", async () => {
+ const result = await buildGatewayConnectionTest(
+ PamAccountType.SSH,
+ connectionDetails,
+ { authMethod: PamSshAuthMethod.Password, username: "ubuntu", password: "pw" },
+ ORG_ID
+ );
+
+ expect(result?.request).toMatchObject({ mode: TestConnectionMode.SSH, password: "pw" });
+ });
+});
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 db7f8ec5c8..2d3f528f95 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
@@ -31,6 +31,11 @@ export type TestConnectionRequest =
sslEnabled?: boolean;
sslRejectUnauthorized?: boolean;
sslCertificate?: string;
+ authMethod?: string;
+ domain?: string;
+ realm?: string;
+ kdcAddress?: string;
+ spn?: string;
}
| {
mode: TestConnectionMode.MongoDB;
@@ -67,7 +72,14 @@ export type TestConnectionRequest =
sslRejectUnauthorized?: boolean;
sslCertificate?: string;
}
- | { mode: TestConnectionMode.SSH; authMethod: string; username: string; password?: string; privateKey?: string }
+ | {
+ mode: TestConnectionMode.SSH;
+ authMethod: string;
+ username: string;
+ password?: string;
+ privateKey?: string;
+ certificate?: string;
+ }
| { mode: TestConnectionMode.Tcp };
const SQL_DIALECTS = {
@@ -113,8 +125,12 @@ export const buildGatewayConnectionTest = async (
password?: string;
awsRegion?: string;
roleArn?: string;
+ domain?: string;
+ realm?: string;
+ kdcAddress?: string;
+ spn?: string;
} | null;
- if (!c || (accountType === PamAccountType.MsSQL && c.authMethod !== "sql-login")) return tcp(host, port);
+ if (!c) 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
@@ -139,7 +155,17 @@ export const buildGatewayConnectionTest = async (
database: cd.database,
sslEnabled: cd.sslEnabled,
sslRejectUnauthorized: cd.sslRejectUnauthorized,
- sslCertificate: cd.sslCertificate
+ sslCertificate: cd.sslCertificate,
+ // MSSQL Windows-auth logins carry the domain or realm the gateway needs to complete the handshake.
+ ...(accountType === PamAccountType.MsSQL
+ ? {
+ authMethod: c.authMethod,
+ domain: c.domain,
+ realm: c.realm,
+ kdcAddress: c.kdcAddress,
+ spn: c.spn
+ }
+ : {})
}
};
}
@@ -249,8 +275,15 @@ export const buildGatewayConnectionTest = async (
};
}
case PamAccountType.SSH: {
- const c = creds as { authMethod: string; username: string; password?: string; privateKey?: string } | null;
- if (!c || c.authMethod === PamSshAuthMethod.Certificate) return tcp(host, port);
+ const c = creds as {
+ authMethod: string;
+ username: string;
+ password?: string;
+ privateKey?: string;
+ certificate?: string;
+ } | null;
+ // Certificate accounts store no long-lived secret; the caller mints a short-lived cert and passes it here.
+ if (!c || (c.authMethod === PamSshAuthMethod.Certificate && !c.certificate)) return tcp(host, port);
return {
host,
port,
@@ -259,7 +292,8 @@ export const buildGatewayConnectionTest = async (
authMethod: c.authMethod,
username: c.username,
password: c.password,
- privateKey: c.privateKey
+ privateKey: c.privateKey,
+ certificate: c.certificate
}
};
}
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 51ca5588a5..b109946d8f 100644
--- a/backend/src/ee/services/pam-account/pam-account-dal.ts
+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts
@@ -5,7 +5,8 @@ import { TableName, TPamAccounts } from "@app/db/schemas";
import { sanitizeSqlLikeString } from "@app/lib/fn";
import { ormify } from "@app/lib/knex";
-import { PamAccountType } from "../pam/pam-enums";
+import { PamAccountType, PamHeartbeatStatus } from "../pam/pam-enums";
+import { computeNextHeartbeatAt, heartbeatJitterCapSeconds } from "../pam-account-heartbeat/pam-heartbeat-fns";
import {
ACCOUNT_NEEDS_ROTATION_ACCOUNT_SQL,
ACCOUNT_WILL_ROTATE_SQL,
@@ -280,6 +281,93 @@ export const pamAccountDALFactory = (db: TDbClient) => {
return Number(result[0]?.count ?? 0);
};
+ // Due and enabled. Mirrors dueRotationQuery, minus the rotatable-type filter: heartbeat covers every account type.
+ const dueHeartbeatQuery = (now: Date, tx?: Knex) =>
+ (tx || db.replicaNode())(TableName.PamAccount)
+ .join(TableName.PamAccountTemplate, `${TableName.PamAccount}.templateId`, `${TableName.PamAccountTemplate}.id`)
+ .join(TableName.Project, `${TableName.PamAccount}.projectId`, `${TableName.Project}.id`)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .whereNotNull(`${TableName.PamAccount}.nextHeartbeatAt`)
+ .where(`${TableName.PamAccount}.nextHeartbeatAt`, "<=", now)
+ .whereRaw(`"${TableName.PamAccountTemplate}"."settings"->'heartbeat'->>'enabled' = 'true'`);
+
+ const findAccountsToHeartbeat = async (now: Date, limit: number, tx?: Knex): Promise<TPamAccountDetail[]> => {
+ return (await dueHeartbeatQuery(now, tx)
+ .leftJoin(TableName.PamFolder, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`)
+ .orderBy(`${TableName.PamAccount}.nextHeartbeatAt`, "asc")
+ .limit(limit)
+ .select(detailSelect)) as unknown as TPamAccountDetail[];
+ };
+
+ const countAccountsToHeartbeat = async (now: Date, tx?: Knex): Promise<number> => {
+ const result = await dueHeartbeatQuery(now, tx).count<[{ count: string }]>(`${TableName.PamAccount}.id`);
+ return Number(result[0]?.count ?? 0);
+ };
+
+ // Bulk reschedule when a template's heartbeat settings change. Accounts already stopped by a rejected credential
+ // stay stopped: a settings change is not the human event that clears that.
+ const reconcileHeartbeatScheduleForTemplate = async (
+ templateId: string,
+ opts?: { rescheduleAll?: boolean },
+ tx?: Knex
+ ): Promise<void> => {
+ const dbClient = tx || db;
+ const template = await dbClient(TableName.PamAccountTemplate)
+ .where({ id: templateId })
+ .first<{ settings: unknown } | undefined>("settings");
+ if (!template) return;
+
+ const heartbeat = PamTemplateSettingsSchema.safeParse(template.settings).data?.heartbeat;
+
+ if (!heartbeat?.enabled || heartbeat.intervalSeconds == null) {
+ await dbClient(TableName.PamAccount)
+ .where({ templateId })
+ .whereNotNull("nextHeartbeatAt")
+ .update({ nextHeartbeatAt: null });
+ return;
+ }
+
+ const { intervalSeconds } = heartbeat;
+ const jitterCapSeconds = heartbeatJitterCapSeconds(intervalSeconds);
+
+ // NULL-safe on purpose: an account that has never been checked has a null status, and `whereNot` would drop it.
+ const update = dbClient(TableName.PamAccount)
+ .where({ templateId })
+ .whereRaw(`("heartbeatStatus" is null or "heartbeatStatus" <> ?)`, [PamHeartbeatStatus.InvalidCredentials]);
+ if (!opts?.rescheduleAll) {
+ void update.whereNull("nextHeartbeatAt");
+ }
+ await update.update({
+ nextHeartbeatAt: dbClient.raw(
+ `GREATEST(COALESCE(??, now()) + make_interval(secs => ?), now()) + make_interval(secs => floor(random() * ?)::int)`,
+ ["lastHeartbeatAt", intervalSeconds, jitterCapSeconds]
+ ) as unknown as Date
+ });
+ };
+
+ const reconcileHeartbeatScheduleForAccount = async (accountId: string, tx?: Knex): Promise<void> => {
+ const account = await findByIdWithDetails(accountId, tx ?? db);
+ if (!account) return;
+
+ const heartbeat = PamTemplateSettingsSchema.safeParse(account.templateSettings).data?.heartbeat;
+ const current = account.nextHeartbeatAt ?? null;
+
+ let nextHeartbeatAt: Date | null = current;
+ if (!heartbeat?.enabled || heartbeat.intervalSeconds == null) {
+ nextHeartbeatAt = null;
+ } else if (!current) {
+ nextHeartbeatAt = computeNextHeartbeatAt({
+ anchor: account.lastHeartbeatAt ?? null,
+ intervalSeconds: heartbeat.intervalSeconds,
+ now: new Date()
+ });
+ }
+
+ if ((nextHeartbeatAt?.getTime() ?? null) !== (current?.getTime() ?? null)) {
+ await (tx || db)(TableName.PamAccount).where({ id: accountId }).update({ nextHeartbeatAt });
+ }
+ };
+
// Total PAM accounts across the org's projects (excluding soft-deleted projects), used to enforce the
// plan's maxPamAccounts at creation time.
const countByOrgId = async (orgId: string, tx?: Knex): Promise<number> => {
@@ -409,6 +497,10 @@ export const pamAccountDALFactory = (db: TDbClient) => {
findByIdsWithDetails,
findAccountsToRotate,
countAccountsToRotate,
+ findAccountsToHeartbeat,
+ countAccountsToHeartbeat,
+ reconcileHeartbeatScheduleForTemplate,
+ reconcileHeartbeatScheduleForAccount,
countByOrgId,
findRotationCandidates,
reconcileRotationScheduleForTemplate,
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 86cd9e06a3..ebee5181ba 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -24,7 +24,13 @@ import { TMembershipRoleDALFactory } from "@app/services/membership/membership-r
import { TUserDALFactory } from "@app/services/user/user-dal";
import { testConnectionWithGateway } from "../gateway-v2/gateway-v2-fns";
-import { PamAccessStatus, PamAccountType, PamProductRole, PamSessionStatus } from "../pam/pam-enums";
+import {
+ PamAccessStatus,
+ PamAccountType,
+ PamHeartbeatStatus,
+ PamProductRole,
+ PamSessionStatus
+} from "../pam/pam-enums";
import {
checkAccountAccess,
checkFolderPermission,
@@ -46,7 +52,11 @@ import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-t
import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
import { terminatePamSessions } from "../pam-session/pam-session-fns";
-import { buildGatewayConnectionTest, CLOUD_CONNECTION_VALIDATORS } from "./pam-account-connection-test";
+import {
+ buildGatewayConnectionTest,
+ CLOUD_CONNECTION_VALIDATORS,
+ TestConnectionMode
+} from "./pam-account-connection-test";
import { TPamAccountDALFactory } from "./pam-account-dal";
import {
applyForcedFields,
@@ -326,7 +336,8 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
};
};
- // throws to block create/update when the account can't reach/authenticate its target
+ // Throws to block create/update when the account can't reach/authenticate its target. Returns whether the
+ // credential itself was proven, which is false when the probe could only reach the host.
const assertConnectionOk = async (
accountType: PamAccountType,
connectionDetails: Record<string, unknown>,
@@ -338,7 +349,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
templateGatewayPoolId?: string | null;
},
orgId: string
- ): Promise<void> => {
+ ): Promise<boolean> => {
const validateCloud = CLOUD_CONNECTION_VALIDATORS[accountType];
if (validateCloud) {
try {
@@ -348,11 +359,11 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
message: `Connection test failed: ${err instanceof Error ? err.message : "unable to validate credentials"}`
});
}
- return;
+ return true;
}
const test = await buildGatewayConnectionTest(accountType, connectionDetails, credentials, orgId);
- if (!test) return;
+ if (!test) return false;
const effectiveGatewayId = gateway.gatewayId ?? gateway.templateGatewayId;
const gatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
@@ -377,6 +388,9 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
if (result && !result.ok) {
throw new BadRequestError({ message: `Connection test failed: ${result.errorMessage}` });
}
+
+ // A TCP probe only proves the host answered, so it cannot stand in for a verified credential.
+ return Boolean(result?.ok) && test.request.mode !== TestConnectionMode.Tcp;
};
const create = async ({
@@ -469,8 +483,9 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
assertPasswordMeetsRequirements(validatedCredentials, template.settings);
// discovery import creates accounts in bulk from a scan that already reached them, so it skips the test
+ let credentialVerified = false;
if (!skipConnectionTest) {
- await assertConnectionOk(
+ credentialVerified = await assertConnectionOk(
accountType,
validatedConnectionDetails,
validatedCredentials,
@@ -487,20 +502,38 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
const encryptedConnectionDetails = await encrypt(projectId, validatedConnectionDetails);
const encryptedCredentials = await encrypt(projectId, validatedCredentials);
+ // Only a probe that authenticated proves the credential; discovery imports skip the test entirely, and some
+ // account types can only be reached, not logged into. Those start unverified.
+ const credentialProvenAt = credentialVerified ? new Date() : null;
+
try {
- const account = await pamAccountDAL.create({
- projectId,
- name,
- description,
- folderId,
- templateId,
- encryptedConnectionDetails,
- encryptedCredentials,
- credentialConfigured: isCredentialConfigured(accountType, validatedCredentials),
- gatewayId,
- gatewayPoolId,
- recordingConnectionId,
- settingsOverrides: settingsOverrides ?? null
+ const account = await pamAccountDAL.transaction(async (tx) => {
+ const created = await pamAccountDAL.create(
+ {
+ projectId,
+ name,
+ description,
+ folderId,
+ templateId,
+ encryptedConnectionDetails,
+ encryptedCredentials,
+ credentialConfigured: isCredentialConfigured(accountType, validatedCredentials),
+ gatewayId,
+ gatewayPoolId,
+ recordingConnectionId,
+ settingsOverrides: settingsOverrides ?? null,
+ ...(credentialProvenAt
+ ? {
+ heartbeatStatus: PamHeartbeatStatus.Healthy,
+ lastHeartbeatAt: credentialProvenAt,
+ lastHeartbeatHealthyAt: credentialProvenAt
+ }
+ : {})
+ },
+ tx
+ );
+ await pamAccountDAL.reconcileHeartbeatScheduleForAccount(created.id, tx);
+ return created;
});
const corsProbeUrl = resolvedS3Config ? await mintCorsProbeUrl(resolvedS3Config) : null;
@@ -744,6 +777,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
// atomically with the write so a failure can't leave a stale nextRotationAt.
if (templateId !== undefined || credentials || routingChanged) {
await pamAccountDAL.reconcileRotationScheduleForAccount(accountId, tx);
+ await pamAccountDAL.reconcileHeartbeatScheduleForAccount(accountId, tx);
}
return updated;
});
diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.ts
index 5a8a4898da..3d321726fb 100644
--- a/backend/src/ee/services/pam/pam-enums.ts
+++ b/backend/src/ee/services/pam/pam-enums.ts
@@ -25,6 +25,13 @@ export enum PamProductRole {
Member = "member"
}
+export enum PamHeartbeatStatus {
+ Healthy = "healthy",
+ InvalidCredentials = "invalid-credentials",
+ CannotCheck = "cannot-check",
+ Unknown = "unknown"
+}
+
export enum PamSessionStatus {
Starting = "starting",
Active = "active",
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index a8e79fd248..afa09a9efb 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -42,6 +42,7 @@ export const CronJobName = {
AuditLogStreamOutboxCleanup: "audit-log-stream-outbox-cleanup",
LicenseUsageFlush: "license-usage-flush",
PamCredentialRotationQueueRotations: "pam-credential-rotation-queue-rotations",
+ PamHeartbeatQueueChecks: "pam-heartbeat-queue-checks",
MonthlyNativeIntegrationDeprecationNotice: "monthly-native-integration-deprecation-notice",
DailyAlertProcessing: "daily-alert-processing",
SecretScanningStuckScanReaper: "secret-scanning-stuck-scan-reaper",
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 0cee428b17..e9f8448a91 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -97,6 +97,8 @@ export enum QueueName {
SecretRotationV2RotateSecrets = "secret-rotation-v2-rotate-secrets",
PamCredentialRotation = "pam-credential-rotation",
PamCredentialRotationRotate = "pam-credential-rotation-rotate",
+ PamHeartbeat = "pam-heartbeat",
+ PamHeartbeatCheck = "pam-heartbeat-check",
FolderTreeCheckpoint = "folder-tree-checkpoint",
InvalidateCache = "invalidate-cache",
SecretScanningV2 = "secret-scanning-v2",
@@ -158,6 +160,8 @@ export enum QueueJobs {
SecretRotationV2SendNotification = "secret-rotation-v2-send-notification",
PamCredentialRotationQueueRotations = "pam-credential-rotation-queue-rotations",
PamCredentialRotationRotate = "pam-credential-rotation-rotate",
+ PamHeartbeatQueueChecks = "pam-heartbeat-queue-checks",
+ PamHeartbeatCheck = "pam-heartbeat-check",
CreateFolderTreeCheckpoint = "create-folder-tree-checkpoint",
DynamicSecretLeaseRevocationFailedEmail = "dynamic-secret-lease-revocation-failed-email",
InvalidateCache = "invalidate-cache",
@@ -422,6 +426,14 @@ export type TQueueJobTypes = {
name: QueueJobs.PamCredentialRotationRotate;
payload: { accountId: string };
};
+ [QueueName.PamHeartbeat]: {
+ name: QueueJobs.PamHeartbeatQueueChecks;
+ payload: undefined;
+ };
+ [QueueName.PamHeartbeatCheck]: {
+ name: QueueJobs.PamHeartbeatCheck;
+ payload: { accountId: string };
+ };
[QueueName.InvalidateCache]: {
name: QueueJobs.InvalidateCache;
payload: {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 50da471dff..345f19e2b2 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -99,6 +99,8 @@ import { pamAccessRequestServiceFactory } from "@app/ee/services/pam-access-requ
import { pamFolderNotificationConfigDALFactory } from "@app/ee/services/pam-access-request/pam-folder-notification-config-dal";
import { pamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";
import { pamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
+import { pamAccountHeartbeatQueueServiceFactory } from "@app/ee/services/pam-account-heartbeat/pam-account-heartbeat-queue";
+import { pamAccountHeartbeatServiceFactory } from "@app/ee/services/pam-account-heartbeat/pam-account-heartbeat-service";
import { pamAccountRotationQueueServiceFactory } from "@app/ee/services/pam-account-rotation/pam-account-rotation-queue";
import { pamAccountRotationServiceFactory } from "@app/ee/services/pam-account-rotation/pam-account-rotation-service";
import { pamAccountTemplateDALFactory } from "@app/ee/services/pam-account-template/pam-account-template-dal";
@@ -1990,6 +1992,16 @@ export const registerRoutes = async (
projectDAL
});
+ const pamAccountHeartbeatService = pamAccountHeartbeatServiceFactory({
+ pamAccountDAL,
+ gatewayService,
+ gatewayV2Service,
+ gatewayPoolService,
+ kmsService,
+ permissionService,
+ projectDAL
+ });
+
const pamSessionService = pamSessionServiceFactory({
pamSessionDAL,
pamAccountDAL,
@@ -3804,6 +3816,14 @@ export const registerRoutes = async (
pamAccountRotationService
});
+ await pamAccountHeartbeatQueueServiceFactory({
+ queueService,
+ cronJob,
+ auditLogService,
+ pamAccountDAL,
+ pamAccountHeartbeatService
+ });
+
const secretScanningV2Queue = secretScanningV2QueueServiceFactory({
auditLogService,
secretScanningV2DAL,
@@ -3996,6 +4016,7 @@ export const registerRoutes = async (
pamAccount: pamAccountService,
pamDiscovery: pamDiscoveryService,
pamAccountRotation: pamAccountRotationService,
+ pamAccountHeartbeat: pamAccountHeartbeatService,
pamMembership: pamMembershipService,
pamSession: pamSessionService,
pamSessionChunk: pamSessionChunkService,
diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.ts
index 2c5ce30e90..e7180d7c1f 100644
--- a/frontend/src/hooks/api/pam/enums.ts
+++ b/frontend/src/hooks/api/pam/enums.ts
@@ -36,6 +36,13 @@ export const ROTATABLE_PAM_ACCOUNT_TYPES = [
export const isRotatablePamAccountType = (type: PamAccountType | string) =>
(ROTATABLE_PAM_ACCOUNT_TYPES as string[]).includes(type);
+export enum PamHeartbeatStatus {
+ Healthy = "healthy",
+ InvalidCredentials = "invalid-credentials",
+ CannotCheck = "cannot-check",
+ Unknown = "unknown"
+}
+
export enum PamRotationStatus {
Success = "success",
Failed = "failed"
diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx
index d08b5b0649..3adbb1d544 100644
--- a/frontend/src/hooks/api/pam/mutations.tsx
+++ b/frontend/src/hooks/api/pam/mutations.tsx
@@ -779,6 +779,22 @@ export const useCreatePamAccessRequest = () => {
});
};
+export const useCheckPamAccountHeartbeat = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ accountId }: { accountId: string }) => {
+ const { data } = await apiRequest.post<{ heartbeatStatus: string; message?: string }>(
+ `/api/v1/pam/accounts/${accountId}/heartbeat/check`
+ );
+ return data;
+ },
+ onSettled: (_, __, { accountId }) => {
+ queryClient.invalidateQueries({ queryKey: pamKeys.accountHeartbeat(accountId) });
+ queryClient.invalidateQueries({ queryKey: pamKeys.getAccount(accountId) });
+ }
+ });
+};
+
export const useRotatePamAccount = () => {
const queryClient = useQueryClient();
return useMutation({
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index dc2f110d2b..b88b8dd87e 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -25,6 +25,7 @@ import {
TPamAccessRequest,
TPamAccount,
TPamAccountDependency,
+ TPamAccountHeartbeat,
TPamAccountRotation,
TPamAccountTemplateDetail,
TPamAccountTemplateWithCount,
@@ -102,6 +103,7 @@ export const pamKeys = {
params?: { search?: string; offset?: number; limit?: number }
) => [...pamKeys.discovery(), "stale", sourceId, params] as const,
accountRotation: (accountId: string) => [...pamKeys.account(), "rotation", accountId] as const,
+ accountHeartbeat: (accountId: string) => [...pamKeys.account(), "heartbeat", accountId] as const,
accountDependencies: (accountId: string) =>
[...pamKeys.account(), "dependencies", accountId] as const,
rotationCandidates: (accountId: string) =>
@@ -310,6 +312,19 @@ export const useGetPamAccountById = (
});
};
+export const useGetPamAccountHeartbeat = (accountId?: string, options?: { enabled?: boolean }) => {
+ return useQuery({
+ queryKey: pamKeys.accountHeartbeat(accountId || ""),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ heartbeat: TPamAccountHeartbeat }>(
+ `/api/v1/pam/accounts/${accountId}/heartbeat`
+ );
+ return data.heartbeat;
+ },
+ enabled: !!accountId && (options?.enabled ?? true)
+ });
+};
+
export const useGetPamAccountRotation = (accountId?: string, options?: { enabled?: boolean }) => {
return useQuery({
queryKey: pamKeys.accountRotation(accountId || ""),
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index 2cc4b99c6f..653cb100cf 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -8,6 +8,7 @@ import {
PamApproverType,
PamDiscoverySchedule,
PamDiscoveryType,
+ PamHeartbeatStatus,
PamNotificationEvent,
PamPolicyType,
PamResourcePermissionActions,
@@ -636,6 +637,17 @@ export type TPamPasswordRequirements = {
allowedSymbols?: string;
};
+export type TPamAccountHeartbeat = {
+ enabled: boolean;
+ intervalSeconds: number | null;
+ status: PamHeartbeatStatus | null;
+ lastCheckedAt: string | null;
+ lastHealthyAt: string | null;
+ nextCheckAt: string | null;
+ templateName: string;
+ lastMessage: string | null;
+};
+
export type TPamAccountRotation = {
enabled: boolean;
intervalSeconds: number | null;
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/CredentialHealthSection.tsx b/frontend/src/pages/pam/PamAccountsPage/components/CredentialHealthSection.tsx
new file mode 100644
index 0000000000..7ce215c05e
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/CredentialHealthSection.tsx
@@ -0,0 +1,109 @@
+import { formatDistanceToNow } from "date-fns";
+
+import { createNotification } from "@app/components/notifications";
+import { Alert, AlertDescription, AlertTitle, 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"
+ }
+ };
+
+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">
+ <span className="text-sm text-foreground">{label}</span>
+ <div className="flex items-center gap-2">{children}</div>
+ </div>
+);
+
+const relative = (value?: string | null) =>
+ value ? formatDistanceToNow(new Date(value), { addSuffix: true }) : "Never";
+
+type Props = {
+ accountId?: string;
+};
+
+export const CredentialHealthSection = ({ accountId }: Props) => {
+ const { data: heartbeat, isPending } = useGetPamAccountHeartbeat(accountId);
+ const checkNow = useCheckPamAccountHeartbeat();
+
+ if (!accountId || isPending || !heartbeat) return null;
+
+ const status = heartbeat.status ?? PamHeartbeatStatus.Unknown;
+ const { label, indicator, className } = STATUS[status];
+ const isHealthy = status === PamHeartbeatStatus.Healthy;
+ const hasFailure =
+ status === PamHeartbeatStatus.InvalidCredentials && Boolean(heartbeat.lastMessage);
+
+ const handleCheckNow = async () => {
+ try {
+ await checkNow.mutateAsync({ accountId });
+ createNotification({ text: "Credential check complete", type: "success" });
+ } catch {
+ createNotification({ text: "Failed to check credential", type: "error" });
+ }
+ };
+
+ return (
+ <div className="mt-2 border-t border-border pt-4">
+ <div className="mb-2 flex items-center justify-between">
+ <div>
+ <h3 className="text-sm font-semibold text-foreground">Credential health</h3>
+ <p className="text-xs text-muted">Whether this credential still signs in.</p>
+ </div>
+ <span className={`text-xs font-medium ${className}`}>
+ {indicator} {label}
+ </span>
+ </div>
+
+ <DetailRow label="Last checked">
+ <span className="text-sm text-muted">{relative(heartbeat.lastCheckedAt)}</span>
+ </DetailRow>
+ {!isHealthy && (
+ <DetailRow label="Last healthy">
+ <span className="text-sm text-muted">{relative(heartbeat.lastHealthyAt)}</span>
+ </DetailRow>
+ )}
+
+ <Button
+ type="button"
+ variant="pam"
+ className="mt-4 w-full"
+ isPending={checkNow.isPending}
+ onClick={handleCheckNow}
+ >
+ 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/EditAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
index e2805b320c..682ce1ec87 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
@@ -34,6 +34,7 @@ import {
TAccountFormValues
} from "./accountFormSchema";
import { ConnectionDetailsForm } from "./ConnectionDetailsForm";
+import { CredentialHealthSection } from "./CredentialHealthSection";
import { CredentialsForm } from "./CredentialsForm";
function filterUnchangedCredentials(
@@ -303,8 +304,9 @@ export const EditAccountForm = ({ accountId, onDirtyChange }: Props) => {
<CardTitle className="text-base">Credentials</CardTitle>
<CardDescription>Authentication used to connect to this account.</CardDescription>
</CardHeader>
- <CardContent>
+ <CardContent className="flex flex-col gap-4">
<CredentialsForm control={control} setValue={setValue} />
+ <CredentialHealthSection accountId={accountId} />
</CardContent>
</Card>
)}
diff --git a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
index 0bfed786bc..6e3572d118 100644
--- a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
@@ -71,6 +71,8 @@ const settingsSchema = z
settings: z.object({
sessionLogMaskingPatterns: z.string().optional(),
rotationEnabled: z.boolean().optional(),
+ heartbeatEnabled: z.boolean().optional(),
+ heartbeatIntervalSeconds: z.number().optional(),
rotationIntervalSeconds: z.number().nullable().optional(),
pwLength: z.coerce.number().optional(),
pwUppercase: z.coerce.number().optional(),
@@ -289,6 +291,8 @@ const SettingsTab = ({
settings: {
sessionLogMaskingPatterns: "",
rotationEnabled: false,
+ heartbeatEnabled: true,
+ heartbeatIntervalSeconds: 86400,
rotationIntervalSeconds: 86400,
pwLength: 32,
pwUppercase: 1,
@@ -326,6 +330,10 @@ const SettingsTab = ({
enabled?: boolean;
intervalSeconds?: number | null;
};
+ const heartbeat = (settings.heartbeat ?? {}) as {
+ enabled?: boolean;
+ intervalSeconds?: number | null;
+ };
const pw = (settings.passwordRequirements ?? {}) as {
length?: number;
required?: {
@@ -338,6 +346,8 @@ const SettingsTab = ({
};
return {
rotationEnabled: rotation.enabled ?? false,
+ heartbeatEnabled: heartbeat.enabled ?? true,
+ heartbeatIntervalSeconds: heartbeat.intervalSeconds ?? 86400,
rotationIntervalSeconds:
rotation.intervalSeconds !== undefined ? rotation.intervalSeconds : 86400,
pwLength: pw.length ?? 32,
@@ -370,6 +380,7 @@ const SettingsTab = ({
const policies = watch("policies");
const storageBackend = watch("recordingStorageBackend");
const rotationEnabled = watch("settings.rotationEnabled");
+ const heartbeatEnabled = watch("settings.heartbeatEnabled");
const requiresRecording = accountTypeRequiresRecording(template.type);
const showGatewaySettings = accountTypeMap[template.type]?.requiresGateway !== false;
const typeName = accountTypeMap[template.type]?.name ?? template.type;
@@ -401,6 +412,12 @@ const SettingsTab = ({
delete settings.sessionLogMaskingPatterns;
}
+ const isHeartbeatOn = Boolean(data.settings.heartbeatEnabled);
+ settings.heartbeat = {
+ enabled: isHeartbeatOn,
+ intervalSeconds: isHeartbeatOn ? (data.settings.heartbeatIntervalSeconds ?? 86400) : null
+ };
+
if (isRotatableTemplateType) {
const isRotationOn = Boolean(data.settings.rotationEnabled);
settings.rotation = {
@@ -687,6 +704,63 @@ const SettingsTab = ({
</Card>
)}
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Credential Health</CardTitle>
+ <CardDescription>
+ Infisical checks that stored credentials still work, and shows the result on each
+ account.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex flex-col gap-4">
+ <Controller
+ control={control}
+ name="settings.heartbeatEnabled"
+ render={({ field }) => (
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-sm font-medium text-foreground">Check credentials</p>
+ <Switch
+ variant="pam"
+ checked={field.value ?? false}
+ onCheckedChange={field.onChange}
+ />
+ </div>
+ )}
+ />
+ {heartbeatEnabled && (
+ <Controller
+ control={control}
+ name="settings.heartbeatIntervalSeconds"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Check every</FieldLabel>
+ <Select
+ value={String(field.value ?? 86400)}
+ onValueChange={(value) => field.onChange(Number(value))}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {PAM_ROTATION_INTERVAL_OPTIONS.map((option) => (
+ <SelectItem key={option.seconds} value={String(option.seconds)}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ How often accounts using this template are checked.
+ </FieldDescription>
+ </Field>
+ )}
+ />
+ )}
+ </div>
+ </CardContent>
+ </Card>
+
{showGatewaySettings && (
<Card>
<CardHeader className="border-b">