Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
pam: dependency-detection and rotation fixes, shared-identity warning, UI
bernie-g549003c8ae0d
diff --git a/backend/src/db/migrations/20260701000000_pam-discovery.ts b/backend/src/db/migrations/20260701000000_pam-discovery.tsindex 3e36ce895d..c7eac4f331 100644--- a/backend/src/db/migrations/20260701000000_pam-discovery.ts+++ b/backend/src/db/migrations/20260701000000_pam-discovery.ts@@ -50,6 +50,9 @@ export async function up(knex: Knex): Promise<void> {t.string("triggeredBy").notNullable();t.integer("discoveredCount").notNullable().defaultTo(0);t.integer("newCount").notNullable().defaultTo(0);+ // Nullable: a scan that did not run dependency discovery leaves these null so the summary can omit deps.+ t.integer("dependencyCount");+ t.integer("newDependencyCount");t.text("errorMessage");t.jsonb("machineErrors");t.timestamp("startedAt");diff --git a/backend/src/db/schemas/pam-discovery-source-runs.ts b/backend/src/db/schemas/pam-discovery-source-runs.tsindex a55925f59f..7c370175cc 100644--- a/backend/src/db/schemas/pam-discovery-source-runs.ts+++ b/backend/src/db/schemas/pam-discovery-source-runs.ts@@ -14,6 +14,8 @@ export const PamDiscoverySourceRunsSchema = z.object({triggeredBy: z.string(),discoveredCount: z.number().default(0),newCount: z.number().default(0),+ dependencyCount: z.number().nullable().optional(),+ newDependencyCount: z.number().nullable().optional(),errorMessage: z.string().nullable().optional(),machineErrors: z.unknown().nullable().optional(),startedAt: z.date().nullable().optional(),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.tsindex 8f058a5a34..34ddd95a08 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@@ -481,7 +481,8 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {lastRotatedAt: z.date().nullable(),rotationStatus: z.string().nullable(),lastRotationError: z.string().nullable(),- isReady: z.boolean()+ isReady: z.boolean(),+ sharedIdentity: z.object({ id: z.string(), name: z.string(), discoverySources: z.string().array() }).array()});server.route({diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.tsindex 4cfc600875..18e1abde75 100644--- a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.ts+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.ts@@ -156,6 +156,41 @@ describe("rotateScheduledAccount recovery probe", () => {expect(applyPasswordChange).toHaveBeenCalledTimes(1);});+ test("discards a pending credential whose probe throws once the current credential proves reachability", async () => {+ // Self-rotation verify throws on a wrong password just as on a transport blip. A stale pending (left by an+ // apply that failed its policy check) must not defer forever: a working current credential proves the target+ // is reachable, so the pending is a real rejection and can be discarded.+ const { service, applyPasswordChange, updateById } = buildService((password) => {+ if (password === PENDING_PASSWORD) throw new Error("winrm auth rejected");+ return true;+ });++ const result = await service.rotateScheduledAccount("acc-1");++ expect(result?.rotationStatus).toBe(ROTATION_STATUS.Success);+ expect(applyPasswordChange).toHaveBeenCalledTimes(1);+ // The freshly-rotated credential is written and the stale pending cleared.+ expect(updateById).toHaveBeenCalledWith(+ "acc-1",+ expect.objectContaining({ encryptedPendingCredentials: null, rotationStatus: ROTATION_STATUS.Success })+ );+ });++ test("defers when the pending probe throws and the current credential can't prove reachability", async () => {+ // Both probes throw (target genuinely unreachable): can't tell a dead pending from a transient failure, so+ // defer rather than risk discarding a possibly-live pending.+ const { service, applyPasswordChange } = buildService((password) => {+ if (password === PENDING_PASSWORD || password === CURRENT_PASSWORD) throw new Error("transport error");+ return true;+ });++ const result = await service.rotateScheduledAccount("acc-1");++ expect(result?.rotationStatus).toBe(ROTATION_STATUS.Failed);+ expect(result?.message).toContain("deferred");+ expect(applyPasswordChange).not.toHaveBeenCalled();+ });+test("delegated target with no stored current password falls through instead of deferring, and applies over the rotator's own connection", async () => {// Delegated target: no stored current password, so the "neither works" defer is skipped (the rotator re-sets).const account = {diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.tsindex 75bdc78178..32829b44dd 100644--- a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts@@ -22,6 +22,7 @@ import { validateConnectionDetails, validateCredentials } from "../pam-account/pimport { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";import { TPamAccountDependencyDALFactory } from "../pam-discovery/pam-account-dependency-dal";import { resolveHostsViaDcDns, winrmRpcWithGateway } from "../pam-discovery/pam-discovery-fns";+import { TPamDiscoverySourceDALFactory } from "../pam-discovery/pam-discovery-source-dal";import {TGetPamAccountRotationDTO,TListPamRotationCandidatesDTO,@@ -36,7 +37,8 @@ import {isWindowsRotatableType,PamRotationReadinessIssue,redactRotationError,- ROTATION_FAILURE_RETRY_CAP_SECONDS+ ROTATION_FAILURE_RETRY_CAP_SECONDS,+ withGatewayRetry} from "./pam-rotation-fns";import {PAM_ROTATION_FACTORY_MAP,@@ -61,11 +63,13 @@ type TPamAccountRotationServiceFactoryDep = {TPamAccountDALFactory,| "findById"| "findByIdWithDetails"+ | "find"| "updateById"| "findRotationCandidates"| "reconcileRotationScheduleForAccount"| "transaction">;+ pamDiscoverySourceDAL: Pick<TPamDiscoverySourceDALFactory, "find">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;@@ -92,6 +96,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicgatewayV2Service,gatewayPoolService,pamAccountDependencyDAL,+ pamDiscoverySourceDAL,rotationHandlers = PAM_ROTATION_FACTORY_MAP} = deps;@@ -233,15 +238,19 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicconst depData = dep.data as { runAsAccount?: string; resolvedIp?: string };const runAsAccount = depData?.runAsAccount ?? targetUsername;const targetHost = freshIpByMachine.get(dep.machine) || depData?.resolvedIp || dep.machine;- await winrmRpcWithGateway<{ ok: boolean }>({- targetHost,- targetPort: winrmPort,- gatewayId: resolvedGatewayId,- gatewayV2Service,- endpoint: WinRmRpcEndpoint.SyncDependency,- credentials: { username: connectUsername, password: connectAuth.password, ...winrmTransport },- params: { type: dep.type, name: dep.name, runAsUsername: runAsAccount, newPassword }- });+ // Retry a transient tunnel/WinRM blip so it doesn't strand the dependency on the old password.+ await withGatewayRetry(async () => {+ await winrmRpcWithGateway<{ ok: boolean }>({+ targetHost,+ targetPort: winrmPort,+ gatewayId: resolvedGatewayId,+ gatewayV2Service,+ endpoint: WinRmRpcEndpoint.SyncDependency,+ credentials: { username: connectUsername, password: connectAuth.password, ...winrmTransport },+ params: { type: dep.type, name: dep.name, runAsUsername: runAsAccount, newPassword }+ });+ return true;+ }, "dependency sync");await pamAccountDependencyDAL.updateById(dep.id, {rotationStatus: "success",lastRotatedAt: new Date(),@@ -260,6 +269,15 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic);};+ // Strip a domain qualifier (DOMAIN\user or user@domain) to a bare, case-insensitive sAMAccountName, so two+ // accounts can be compared for being the same directory identity.+ const bareUsername = (username: string): string => {+ let bare = username;+ if (username.includes("\\")) bare = username.split("\\").pop() ?? username;+ else if (username.includes("@")) [bare] = username.split("@");+ return bare.toLowerCase();+ };+// A delegated rotator must sit on the same resource as its target so its credential can reach it: same// host for SQL / local Windows, same domain controller for Windows AD.const isSameResource = (@@ -284,6 +302,91 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicthrow new BadRequestError({ message: `Rotation account is no longer ${detail} this account` });};+ // A stable key for the directory/host identity an account authenticates as, so two PAM objects that resolve to+ // the same underlying credential can be detected. Domain accounts key on domain (a DC is just a replica), local+ // Windows on host, SQL on host+port; all on the bare account name. Returns null when the type isn't rotatable.+ const identityKey = (accountType: PamAccountType, conn: Record<string, unknown>, username: string): string | null => {+ const user = bareUsername(username);+ if (accountType === PamAccountType.WindowsAd) {+ const domain = (conn.domain as string | undefined)?.toLowerCase();+ return domain ? `ad|${domain}|${user}` : null;+ }+ if (isWindowsRotatableType(accountType)) {+ const host = (conn.host as string | undefined)?.toLowerCase();+ return host ? `win|${host}|${user}` : null;+ }+ if (+ accountType === PamAccountType.Postgres ||+ accountType === PamAccountType.MySQL ||+ accountType === PamAccountType.MsSQL+ ) {+ const host = (conn.host as string | undefined)?.toLowerCase();+ return host ? `sql|${host}|${String(conn.port)}|${user}` : null;+ }+ return null;+ };++ // Other managed accounts that authenticate as this same identity, so the UI can warn that rotating this account+ // changes their shared password too (they hold their own copy and won't be updated automatically). Each is+ // annotated with any discovery sources that use it as their credential, since that is the concrete blast+ // radius. Covers the same AD object (identical discovery fingerprint) and accounts referenced as a discovery+ // credential — the two collisions seen in practice.+ const getSharedIdentityReferences = async (+ account: TPamAccountDetail,+ projectId: string+ ): Promise<{ id: string; name: string; discoverySources: string[] }[]> => {+ if (!isRotatableAccountType(account.accountType)) return [];++ const creds = await decryptSqlCredentials(projectId, account.accountType, account.encryptedCredentials);+ const conn = resolveConnectionDetails(+ account.accountType,+ await decrypt(projectId, account.encryptedConnectionDetails)+ );+ const key = identityKey(account.accountType, conn, creds.username);+ if (!key) return [];++ // Same AD object = identical discovery fingerprint (cheap, indexed); excludes this account itself.+ const siblings = account.discoveryFingerprint+ ? (await pamAccountDAL.find({ projectId, discoveryFingerprint: account.discoveryFingerprint }))+ .filter((sibling) => sibling.id !== account.id)+ .map((sibling) => ({ id: sibling.id, name: sibling.name }))+ : [];++ // A source whose credential is the account itself is fine (it updates in place); only a *different*+ // same-identity account breaks. A credential we can't decrypt/parse can't be compared, so it drops out.+ const sources = await pamDiscoverySourceDAL.find({ projectId });+ const sourceMatches = (+ await Promise.all(+ sources.map(async (source) => {+ if (source.credentialAccountId === account.id) return null;+ const cred = await pamAccountDAL.findByIdWithDetails(source.credentialAccountId).catch(() => null);+ if (!cred || !isRotatableAccountType(cred.accountType)) return null;+ try {+ const credCreds = await decryptSqlCredentials(projectId, cred.accountType, cred.encryptedCredentials);+ const credConn = resolveConnectionDetails(+ cred.accountType,+ await decrypt(projectId, cred.encryptedConnectionDetails)+ );+ if (identityKey(cred.accountType, credConn, credCreds.username) !== key) return null;+ return { accountId: cred.id, accountName: cred.name, sourceName: source.name };+ } catch {+ return null;+ }+ })+ )+ ).filter((m): m is { accountId: string; accountName: string; sourceName: string } => m !== null);++ // Merge into one list keyed by account, collecting the discovery sources each is a credential for.+ const byAccount = new Map<string, { id: string; name: string; discoverySources: string[] }>();+ siblings.forEach((s) => byAccount.set(s.id, { id: s.id, name: s.name, discoverySources: [] }));+ sourceMatches.forEach((m) => {+ const existing = byAccount.get(m.accountId);+ if (existing) existing.discoverySources.push(m.sourceName);+ else byAccount.set(m.accountId, { id: m.accountId, name: m.accountName, discoverySources: [m.sourceName] });+ });+ return [...byAccount.values()];+ };+const resolveRotator = async (account: TPamAccountDetail,targetCredentials: TSqlAccountCredentials,@@ -377,26 +480,58 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic// definitive answer so a transient failure never discards a possibly-live credential.if (account.encryptedPendingCredentials) {const pending = await decryptSqlCredentials(projectId, accountType, account.encryptedPendingCredentials);- const gatewayTarget = { accountType, connectionDetails, gatewayId, gatewayPoolId, verifyVia };+ // Verify connects to the target/DC through the gateway that can reach it — the rotator's, not the target+ // account's. A delegated target often carries no gateway of its own (its rotator/source holds it); for a+ // self-rotating account the two are the same, so this is always correct.+ const gatewayTarget = {+ accountType,+ connectionDetails,+ gatewayId: rotatorGatewayId,+ gatewayPoolId: rotatorGatewayPoolId,+ verifyVia+ };- const pendingWorks = await handler.testCredential(- { ...gatewayTarget, auth: { username: targetUsername, password: pending.password ?? "" } },- gatewayDeps- );+ // Probe a candidate credential against the target. Returns true/false definitively, or throws when the+ // check can't complete (transient transport error, already retried inside the handler).+ const probe = (password: string) =>+ handler.testCredential({ ...gatewayTarget, auth: { username: targetUsername, password } }, gatewayDeps);++ let pendingWorks = false;+ let pendingThrew = false;+ try {+ pendingWorks = await probe(pending.password ?? "");+ } catch {+ pendingThrew = true;+ }if (pendingWorks) {await markRotated(account, account.encryptedPendingCredentials, now);return null;}+ // Pending did not authenticate. Probe the current credential too: besides detecting an interrupted+ // rotation, a *successful* current probe proves the target is reachable, which tells a dead pending apart+ // from a transient failure. This matters because self-rotation verify throws on a wrong password exactly+ // as it does on a transport blip, so a stale pending (e.g. left by an apply that failed its policy check)+ // would otherwise defer every future rotation forever. Without proof of reachability we still defer, so a+ // real blip never discards a possibly-live pending.const currentPassword = targetCredentials.password;- const currentWorks = currentPassword- ? await handler.testCredential(- { ...gatewayTarget, auth: { username: targetUsername, password: currentPassword } },- gatewayDeps- )- : false;+ let currentWorks = false;+ if (currentPassword) {+ try {+ currentWorks = await probe(currentPassword);+ } catch {+ throw new BadRequestError({+ message: `Could not verify ${pendingThrew ? "pending" : "current"} credential; rotation deferred`+ });+ }+ }+ if (pendingThrew && !currentWorks) {+ // Pending was inconclusive and the current credential didn't prove reachability: can't distinguish a+ // dead pending from an unreachable target, so defer rather than risk discarding a live pending.+ throw new BadRequestError({ message: "Could not verify pending credential; rotation deferred" });+ }if (!currentWorks && currentPassword) {- // Both credentials exist but neither authenticates: defer rather than risk discarding a live one. A+ // Pending definitively failed and the current credential also failed: neither authenticates, defer. A// delegated target (no stored current password) instead falls through, since its rotator re-sets below.throw new BadRequestError({ message: "Could not verify account credentials; rotation deferred" });}@@ -426,19 +561,39 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicgatewayDeps);- const verified = await handler.testCredential(- {- accountType,- connectionDetails,- auth: { username: targetUsername, password: newPassword },- verifyVia,- gatewayId,- gatewayPoolId- },- gatewayDeps- );+ let verified: boolean;+ try {+ verified = await handler.testCredential(+ {+ accountType,+ connectionDetails,+ auth: { username: targetUsername, password: newPassword },+ verifyVia,+ // Reach the target through the rotator's gateway (the one that just applied the change), not the target+ // account's — a delegated target often has no gateway of its own.+ gatewayId: rotatorGatewayId,+ gatewayPoolId: rotatorGatewayPoolId+ },+ gatewayDeps+ );+ } catch (err) {+ logger.warn(+ err,+ `PAM rotation verify could not complete [accountId=${account.id}] [error=${+ err instanceof Error ? err.message : String(err)+ }]`+ );+ // Applied, but verification couldn't complete after retries (transient gateway/network error). The new+ // password is already staged as pending; keep it so the recovery probe promotes it on the next run. A+ // one-off tunnel blip must never leave the account failed with a live-but-unrecorded password.+ throw new BadRequestError({+ message:+ "Password was changed on the target but verification could not complete due to a transient network error; it will be reconciled on the next rotation attempt"+ });+ }if (!verified) {- // Applied but unconfirmed: keep the candidate staged (don't discard) so the next probe can promote it.+ // Applied but the credential was definitively rejected: keep the candidate staged (don't discard) so the+ // next probe can promote it if this was a false negative.throw new BadRequestError({ message: "Password was changed on the target but could not be verified" });}@@ -454,11 +609,27 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic// For self-rotation the account's old password is now dead, so connect with the new one; a delegated// rotator authenticates with its own (unchanged) password.connectAuth: isDelegated ? auth : { username: auth.username, password: newPassword },- gatewayId,- gatewayPoolId+ // Dependency sync reaches each machine through the rotator's gateway (same as apply/verify); a delegated+ // target account often has none of its own.+ gatewayId: rotatorGatewayId,+ gatewayPoolId: rotatorGatewayPoolId};};+ // Set-LocalUser / Set-ADAccountPassword throw a bare InvalidPasswordException with no reason when the new+ // password violates the host's policy, and Windows never says which rule failed. Append the one thing we do+ // know (the configured format length) plus what to try, so the opaque error becomes actionable.+ const augmentWindowsPolicyError = (account: TPamAccountDetail, message: string): string => {+ if (!isWindowsRotatableType(account.accountType) || !message.includes("InvalidPasswordException")) {+ return message;+ }+ const length = getPasswordRequirements(account.templateSettings)?.length;+ const lengthHint = length+ ? ` This account's rotation format is ${length} character${length === 1 ? "" : "s"}; try increasing it.`+ : "";+ return `${message}\nNote: the host rejected the new password against its local password policy (minimum length, complexity, or history).${lengthHint}`;+ };+// Advance nextRotationAt to a capped retry, but only when the account is schedulable: a ready account's early// failure still can't be re-selected on every cron tick, and a not-ready account is never given a due-date it// cannot act on.@@ -482,7 +653,9 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic: null;await pamAccountDAL.updateById(account.id, {rotationStatus: ROTATION_STATUS.Failed,- encryptedLastRotationMessage: await encrypt(projectId, { message: (err as Error).message }),+ encryptedLastRotationMessage: await encrypt(projectId, {+ message: augmentWindowsPolicyError(account, (err as Error).message)+ }),nextRotationAt});};@@ -577,6 +750,8 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServiclastRotationError = (decrypted as { message?: string }).message ?? null;}+ const sharedIdentity = await getSharedIdentityReferences(account, projectId);+return {enabled: settings?.rotation?.enabled ?? false,intervalSeconds: settings?.rotation?.intervalSeconds ?? null,@@ -586,7 +761,8 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServiclastRotatedAt: account.lastRotatedAt ?? null,rotationStatus: account.rotationStatus ?? null,lastRotationError,- isReady: readiness.ready+ isReady: readiness.ready,+ sharedIdentity};};@@ -642,6 +818,21 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicawait decrypt(projectId, rotator.encryptedConnectionDetails));assertRotatorSameResource(account.accountType as PamAccountType, rotatorConn, targetConn);+ // A delegated rotator that resolves to the SAME directory identity as the target is a footgun: rotating+ // changes the shared principal's password, immediately invalidating the rotator's own stored credential+ // (and any other PAM copy of it). Require a genuinely different identity; to rotate itself, an account is+ // set as its own rotation account, which authenticates with the freshly-set password instead.+ const rotatorCredentials = await decryptSqlCredentials(+ projectId,+ account.accountType,+ rotator.encryptedCredentials+ );+ if (bareUsername(rotatorCredentials.username) === bareUsername(targetCredentials.username)) {+ throw new BadRequestError({+ message:+ "Rotation account is the same identity as this account, so rotating it would invalidate its own credential. Set this account to rotate itself, or choose a different privileged account."+ });+ }// Binding a rotator causes its credential to be used to authenticate rotations, so require credential access// to it (not just metadata read): otherwise a caller could leverage a privileged account they can only see.await checkAccount(diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.tsindex 93760a802a..c4fedf402a 100644--- a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.ts+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.ts@@ -33,4 +33,5 @@ export type TPamAccountRotationView = {rotationStatus: string | null;lastRotationError: string | null;isReady: boolean;+ sharedIdentity: { id: string; name: string; discoverySources: string[] }[];};diff --git a/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.ts b/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.tsindex 0cac82da16..d93ec6b12e 100644--- a/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.ts+++ b/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.ts@@ -1,7 +1,44 @@+import { logger } from "@app/lib/logger";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { PamAccountType } from "../pam/pam-enums";+const sleep = (ms: number) =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, ms);+ });++// Rotation talks to the target through a freshly-opened gateway tunnel: to verify a new password, or to push it+// into a dependency (service / task / IIS pool). A transient tunnel/TLS/auth blip is NOT a real failure, so the+// probe throws on those and we retry. A definitive result short-circuits: verify returns true/false, a dependency+// sync returns true on success. If every attempt throws, the last error propagates so the caller records it.+export const GATEWAY_RETRY_ATTEMPTS = 3;++export const withGatewayRetry = async (+ probe: () => Promise<boolean>,+ label = "operation",+ { maxAttempts = GATEWAY_RETRY_ATTEMPTS, baseDelayMs = 500 }: { maxAttempts?: number; baseDelayMs?: number } = {}+): Promise<boolean> => {+ let lastErr: unknown;+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {+ try {+ // eslint-disable-next-line no-await-in-loop+ return await probe();+ } catch (err) {+ lastErr = err;+ logger.warn(+ { err },+ `PAM rotation ${label} attempt failed [attempt=${attempt}/${maxAttempts}] [error=${+ err instanceof Error ? err.message : String(err)+ }]`+ );+ // eslint-disable-next-line no-await-in-loop+ if (attempt < maxAttempts) await sleep(baseDelayMs * attempt);+ }+ }+ throw lastErr;+};+export const SQL_ROTATABLE_ACCOUNT_TYPES = [PamAccountType.Postgres,PamAccountType.MySQL,diff --git a/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts b/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.tsindex 4912b0c36e..76e5a93acd 100644--- a/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts+++ b/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts@@ -8,7 +8,13 @@ import {import { PamAccountType } from "../pam/pam-enums";import { ldapBindCheckViaGateway, winrmRpcWithGateway } from "../pam-discovery/pam-discovery-fns";-import { PAM_ROTATION_APP_MAP, redactRotationError, TRotatableType, TSqlRotatableType } from "./pam-rotation-fns";+import {+ PAM_ROTATION_APP_MAP,+ redactRotationError,+ TRotatableType,+ TSqlRotatableType,+ withGatewayRetry+} from "./pam-rotation-fns";import {SQL_QUERY_TIMEOUT,TPamRotationGatewayDeps,@@ -42,7 +48,9 @@ type TTestCredentialInput = {export type TPamRotationHandler = {validateTarget: (input: { accountType: TRotatableType; authMethod?: string }) => void;applyPasswordChange: (input: TApplyPasswordChangeInput, deps: TPamRotationGatewayDeps) => Promise<void>;- // Returns whether the credential authenticates; never throws, so the recovery probe can rely on it.+ // Returns whether the credential authenticates (true/false is a definitive answer). THROWS only when+ // verification can't complete after retries (a transient transport error) — callers treat that as+ // inconclusive and defer, never as a wrong password.testCredential: (input: TTestCredentialInput, deps: TPamRotationGatewayDeps) => Promise<boolean>;};@@ -222,40 +230,46 @@ const windowsRotationHandler: TPamRotationHandler = {testCredential: async (input, deps) => {const { accountType, connectionDetails, auth, verifyVia, gatewayId, gatewayPoolId } = input;- try {- const resolvedGatewayId = await resolveRotationGatewayId(deps, gatewayId, gatewayPoolId);- const transport = winrmTransportFromConn(connectionDetails);+ const resolvedGatewayId = await resolveRotationGatewayId(deps, gatewayId, gatewayPoolId);+ const transport = winrmTransportFromConn(connectionDetails);- if (accountType === PamAccountType.WindowsAd) {- // A domain service account usually can't WinRM to the DC, but an LDAP bind needs only the credential.- const conn = connectionDetails as TWindowsAdConnDetails;- if (!conn.dcAddress || !conn.domain) return false;- const bindDn =- auth.username.includes("\\") || auth.username.includes("@")- ? auth.username- : `${auth.username}@${conn.domain}`;- return await ldapBindCheckViaGateway(- {- dcAddress: conn.dcAddress,- port: conn.port ?? 389,- useLdaps: conn.useLdaps ?? false,- rejectUnauthorized: conn.ldapRejectUnauthorized ?? true,- caCert: conn.ldapCaCert,- tlsServerName: conn.ldapTlsServerName,- bindDn,- password: auth.password- },- resolvedGatewayId,- deps.gatewayV2Service- );- }+ if (accountType === PamAccountType.WindowsAd) {+ // A domain service account usually can't WinRM to the DC, but an LDAP bind needs only the credential.+ const conn = connectionDetails as TWindowsAdConnDetails;+ const { dcAddress, domain } = conn;+ if (!dcAddress || !domain) return false;+ const bindDn =+ auth.username.includes("\\") || auth.username.includes("@") ? auth.username : `${auth.username}@${domain}`;+ // ldapBindCheckViaGateway returns false only on a real auth rejection and throws on transport errors, so+ // withGatewayRetry retries a transient gateway/TLS blip instead of misreporting a valid credential as wrong.+ return withGatewayRetry(+ () =>+ ldapBindCheckViaGateway(+ {+ dcAddress,+ port: conn.port ?? 389,+ useLdaps: conn.useLdaps ?? false,+ rejectUnauthorized: conn.ldapRejectUnauthorized ?? true,+ caCert: conn.ldapCaCert,+ tlsServerName: conn.ldapTlsServerName,+ bindDn,+ password: auth.password+ },+ resolvedGatewayId,+ deps.gatewayV2Service+ ),+ "verify"+ );+ }- const targetHost = winrmRotationTargetHost(accountType, connectionDetails);- const targetPort = winrmPortFromConn(connectionDetails);+ const targetHost = winrmRotationTargetHost(accountType, connectionDetails);+ const targetPort = winrmPortFromConn(connectionDetails);- // Delegated local rotation: the target account usually can't WinRM in, so the rotator (admin) validates- // the credential on the box instead of us trying to log in as the account.- if (verifyVia) {+ // Delegated local rotation: the target account usually can't WinRM in, so the rotator (admin) validates the+ // credential on the box instead of us trying to log in as the account. A wrong password comes back as+ // valid=false (definitive); a transport error throws and is retried.+ if (verifyVia) {+ return withGatewayRetry(async () => {const { valid } = await winrmRpcWithGateway<{ valid: boolean }>({targetHost,targetPort,@@ -266,9 +280,11 @@ const windowsRotationHandler: TPamRotationHandler = {params: { targetUsername: toBareAccountName(auth.username), password: auth.password }});return valid;- }+ }, "verify");+ }- // Self-rotation: the account can log in (that's how it applied the change), so prove the credential directly.+ // Self-rotation: the account can log in (that's how it applied the change), so prove the credential directly.+ return withGatewayRetry(async () => {await winrmRpcWithGateway<{ ok: boolean }>({targetHost,targetPort,@@ -278,9 +294,7 @@ const windowsRotationHandler: TPamRotationHandler = {credentials: { username: auth.username, password: auth.password, ...transport }});return true;- } catch {- return false;- }+ }, "verify");}};diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.test.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.test.tsindex 519b501b04..52368fa0d8 100644--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.test.ts+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.test.ts@@ -91,4 +91,14 @@ describe("resolveRunAsFingerprint", () => {"corp.example.com:11111111-1111-1111-1111-111111111111");});++ test.each([+ ["CORP\\svc-gmsa$"], // gMSA, even if it somehow made it into the enumerated users+ [".\\localsvc$"], // local machine/managed account (would otherwise mint a local fingerprint)+ ["WEB01\\web01$"] // machine account+ ])("returns null for a $-suffixed managed/machine account (%s)", (runAs) => {+ const withGmsa = new Map(userGuidByName);+ withGmsa.set("svc-gmsa$", "22222222-2222-2222-2222-222222222222");+ expect(resolveRunAsFingerprint(runAs, domain, withGmsa, null, machine)).toBeNull();+ });});diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.tsindex cb4dfc3fde..fbb9cd5745 100644--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts@@ -238,6 +238,10 @@ export const resolveRunAsFingerprint = (if (!parsed) return null;const account = parsed.account.toLowerCase();if (BUILTIN_RUNAS.has(account)) return null;+ // A trailing '$' marks a gMSA / sMSA / machine account, whose password AD manages automatically. There is+ // nothing for rotation to set, so it is never a dependency's run-as (domain enumeration also excludes these+ // via objectCategory=person; this makes the rule explicit and also covers the local-account branch below).+ if (account.endsWith("$")) return null;if (parsed.domain !== null) {const runAsDomain = parsed.domain.toLowerCase();diff --git a/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts b/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.tsindex 69b0eac700..fe366d73d7 100644--- a/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts+++ b/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts@@ -27,7 +27,9 @@ export const pamAccountDependencyDALFactory = (db: TDbClient) => {// Imported wins: a row already linked to a managed account (accountId set) is never demoted back to a staged// link, so a second discovery source scanning the same machine can't silently break rotation sync for an// account another source imported.- const upsertByIdentity = async (dep: TUpsertDependency, tx?: Knex): Promise<string> => {+ // `xmax = 0` is true only for the freshly-inserted tuple; on an ON CONFLICT update xmax is the updating txid,+ // so it distinguishes a newly-discovered dependency from one the scan merely re-saw (drives the run's new count).+ const upsertByIdentity = async (dep: TUpsertDependency, tx?: Knex): Promise<{ id: string; isNew: boolean }> => {const conn = tx || db;const { fingerprint, machine, type, name, data, accountId, discoveredAccountId } = dep;const [row] = await conn(TableName.PamAccountDependency)@@ -41,8 +43,9 @@ export const pamAccountDependencyDALFactory = (db: TDbClient) => {[TableName.PamAccountDependency])})- .returning("id");- return row.id;+ .returning(["id", conn.raw("(xmax = 0) AS inserted")]);+ const inserted = row as { id: string; inserted?: boolean };+ return { id: inserted.id, isNew: Boolean(inserted.inserted) };};// Prune dependencies the current scan no longer found. Scoped to this source's accounts (staged or theirdiff --git a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts b/backend/src/ee/services/pam-discovery/pam-discovery-fns.tsindex a4a2b9156b..18ac78708d 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts@@ -102,7 +102,8 @@ const LDAP_BIND_CHECK_TIMEOUT_MS = 15 * 1000;// Confirms directory credentials by performing an LDAP simple bind through the gateway. Used to verify a// rotated domain account's new password: an LDAP bind needs only the credential, unlike a WinRM logon that-// most service accounts lack. Returns whether the bind succeeds; never throws.+// most service accounts lack. Returns true (bound) / false (definitive auth rejection); THROWS on a transport+// error (TLS/tunnel/timeout) so a transient blip is retried rather than misread as a wrong password.export const ldapBindCheckViaGateway = async ({dcAddress,@@ -135,7 +136,7 @@ export const ldapBindCheckViaGateway = async (gatewayId,gatewayV2Service,(proxyPort) =>- new Promise<boolean>((resolve) => {+ new Promise<boolean>((resolve, reject) => {const client = ldapjs.createClient({url: `${useLdaps ? "ldaps" : "ldap"}://localhost:${proxyPort}`,connectTimeout: LDAP_BIND_CHECK_TIMEOUT_MS,@@ -150,7 +151,7 @@ export const ldapBindCheckViaGateway = async (});let settled = false;- const done = (ok: boolean) => {+ const finish = (run: () => void) => {if (settled) return;settled = true;try {@@ -158,12 +159,19 @@ export const ldapBindCheckViaGateway = async (} catch {// client may already be destroyed}- resolve(ok);+ run();};- // Unhandled 'error' events (e.g. TLS mismatch) would crash the process, so capture them as a failed bind.- client.on("error", () => done(false));- client.bind(bindDn, password, (err) => done(!err));+ // A transport-level failure (TLS mismatch, a dropped gateway tunnel, a timeout) is NOT a credential+ // rejection. Reject so the caller can retry, rather than silently reporting a valid credential as invalid.+ client.on("error", (err) => finish(() => reject(err)));+ client.bind(bindDn, password, (err) => {+ if (!err) return finish(() => resolve(true));+ // Only an actual "invalid credentials" (LDAP result 49) proves the password is wrong. Anything else+ // (e.g. strongerAuthRequired, connection reset) is inconclusive and must not read as a bad password.+ const isAuthRejection = err.name === "InvalidCredentialsError" || (err as { code?: number }).code === 49;+ return finish(() => (isAuthRejection ? resolve(false) : reject(err)));+ });}));};diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.tsindex c19a007fdf..bb9af56f66 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts@@ -471,6 +471,9 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic// Persist dependencies found during the per-machine sweep, anchoring each to its run-as account by// fingerprint: point at the staged discovered account, or its imported managed account once imported.+ // null = dependency discovery did not run this scan, so the summary omits the dependencies clause.+ let dependencyCount: number | null = null;+ let newDependencyCount: number | null = null;if (scannedDependencyMachines.length) {const sourceAccounts = await pamDiscoveredAccountDAL.findFingerprintLinks(sourceId);const accountByFingerprint = new Map(@@ -481,7 +484,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic);const depLimit = pLimit(DISCOVERED_UPSERT_CONCURRENCY);- const keepIds = (+ const depResults = (await Promise.all(dependencies.map((dep) => {const match = accountByFingerprint.get(dep.fingerprint);@@ -500,13 +503,18 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic);}))- ).filter((id): id is string => Boolean(id));+ ).filter((r): r is { id: string; isNew: boolean } => Boolean(r));++ // Count only anchored dependencies (those matching an account this source knows); un-anchored run-as+ // values aren't persisted or shown, so counting them would inflate the "found" number.+ dependencyCount = depResults.length;+ newDependencyCount = depResults.filter((r) => r.isNew).length;await pamAccountDependencyDAL.deleteStaleForSource({accountIds: sourceAccounts.map((a) => a.importedAccountId).filter((v): v is string => Boolean(v)),discoveredAccountIds: sourceAccounts.map((a) => a.id),scannedMachines: scannedDependencyMachines,- keepIds+ keepIds: depResults.map((r) => r.id)});}@@ -515,6 +523,8 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServicstatus: PamDiscoveryRunStatus.Completed,discoveredCount: accounts.length,newCount,+ dependencyCount,+ newDependencyCount,machineErrors: machineErrors.length ? JSON.stringify(machineErrors) : null,completedAt: new Date()});diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 7709d76b8e..b4c4ff991c 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -1949,7 +1949,8 @@ export const registerRoutes = async (gatewayService,gatewayV2Service,gatewayPoolService,- pamAccountDependencyDAL+ pamAccountDependencyDAL,+ pamDiscoverySourceDAL});const pamSessionService = pamSessionServiceFactory({diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex 65fdcd2479..8b935b97df 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -47,6 +47,8 @@ export type TPamDiscoveryRun = {triggeredBy: string;discoveredCount: number;newCount: number;+ dependencyCount?: number | null;+ newDependencyCount?: number | null;errorMessage?: string | null;machineErrors?: { machine: string; error: string }[] | null;startedAt?: string | null;@@ -613,6 +615,7 @@ export type TPamAccountRotation = {rotationStatus: string | null;lastRotationError: string | null;isReady: boolean;+ sharedIdentity: { id: string; name: string; discoverySources: string[] }[];};export type TPamRotationCandidateGroup = {diff --git a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsxindex ea560a886c..d6376a3436 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx@@ -54,7 +54,6 @@ import {isRotatablePamAccountType,PamAccountAccessibilityIssue,PamAccountType,- supportsPamDependencies,TPamMember,useGetPamAccountById,useGetPamAccountTemplate,@@ -84,7 +83,6 @@ import { SheetSaveBar } from "../../components/SheetSaveBar";import { TabWarningPing } from "../../components/TabWarningPing";import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatformIcon";import { AssignAccessModal, EditMemberTarget } from "./AssignAccessModal";-import { DependenciesTab } from "./DependenciesTab";import { EditAccountForm } from "./EditAccountForm";import { RecordingConnectionPicker } from "./RecordingConnectionPicker";import { RotationTab } from "./RotationTab";@@ -855,17 +853,11 @@ export const AccountDetailSheet = ({ isOpen, accountId, onOpenChange }: Props) =const typeInfo = accountType ? accountTypeMap[accountType] : undefined;const { can } = usePamAccountActions(accountId ?? "", isOpen && Boolean(accountId));- const availableTabs = visiblePamTabs(PAM_ACCOUNT_TABS, can)- .filter(- (tabDef) =>- tabDef.value !== PamSheetTab.Rotation ||- (accountType !== undefined && isRotatablePamAccountType(accountType))- )- .filter(- (tabDef) =>- tabDef.value !== PamSheetTab.Dependencies ||- (accountType !== undefined && supportsPamDependencies(accountType))- );+ const availableTabs = visiblePamTabs(PAM_ACCOUNT_TABS, can).filter(+ (tabDef) =>+ tabDef.value !== PamSheetTab.Rotation ||+ (accountType !== undefined && isRotatablePamAccountType(accountType))+ );const tabsWithIssues = new Set((account?.accessibilityIssues ?? []).map((issue) => ISSUE_TO_TAB[issue])@@ -927,7 +919,6 @@ export const AccountDetailSheet = ({ isOpen, accountId, onOpenChange }: Props) =[PamSheetTab.Rotation]: accountId ? (<RotationTab accountId={accountId} onDirtyChange={setIsFormDirty} />) : null,- [PamSheetTab.Dependencies]: accountId ? <DependenciesTab accountId={accountId} /> : null,[PamSheetTab.Advanced]: accountId ? (<SettingsTab accountId={accountId} onDirtyChange={setIsFormDirty} />) : nulldiff --git a/frontend/src/pages/pam/PamAccountsPage/components/DependenciesSection.tsx b/frontend/src/pages/pam/PamAccountsPage/components/DependenciesSection.tsxnew file mode 100644index 0000000000..09a6027e92--- /dev/null+++ b/frontend/src/pages/pam/PamAccountsPage/components/DependenciesSection.tsx@@ -0,0 +1,192 @@+import { Fragment, useState } from "react";+import { format } from "date-fns";+import { AlertCircle, ChevronRight } from "lucide-react";++import {+ Badge,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger+} from "@app/components/v3/generic/Tooltip";+import { TPamAccountDependency, useListPamAccountDependencies } from "@app/hooks/api/pam";++const TYPE_LABELS: Record<string, string> = {+ "windows-service": "Windows Service",+ "scheduled-task": "Scheduled Task",+ "iis-app-pool": "IIS App Pool"+};++const TYPE_DETAIL_FIELDS: Record<string, { key: string; label: string }[]> = {+ "windows-service": [+ { key: "pathName", label: "Binary path" },+ { key: "state", label: "State" }+ ],+ "scheduled-task": [+ { key: "taskPath", label: "Task path" },+ { key: "state", label: "State" }+ ],+ "iis-app-pool": [{ key: "state", label: "State" }]+};++const StatusBadge = ({ dep }: { dep: TPamAccountDependency }) => {+ if (dep.rotationStatus === "success") return <Badge variant="success">Rotated</Badge>;+ if (dep.rotationStatus === "pending") return <Badge variant="warning">Pending</Badge>;+ if (dep.rotationStatus === "failed") {+ return (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <Badge variant="danger" className="cursor-help gap-1">+ <AlertCircle className="size-3" /> Failed+ </Badge>+ </span>+ </TooltipTrigger>+ {dep.lastRotationMessage && (+ <TooltipContent className="max-w-xs break-words">+ {dep.lastRotationMessage}+ </TooltipContent>+ )}+ </Tooltip>+ </TooltipProvider>+ );+ }+ return <Badge variant="neutral">Never</Badge>;+};++const DetailRow = ({ label, value }: { label: string; value: string }) => (+ <div className="flex min-w-0 flex-col gap-0.5">+ <span className="text-xs text-muted">{label}</span>+ <span className="truncate font-mono text-xs text-foreground" title={value}>+ {value}+ </span>+ </div>+);++const DependencyDetail = ({ dep }: { dep: TPamAccountDependency }) => {+ const data = dep.data ?? {};+ const read = (key: string) => {+ const v = data[key];+ if (v === null || v === undefined || v === "") return null;+ return String(v);+ };++ const runAs = read("runAsAccount");+ const typeFields = TYPE_DETAIL_FIELDS[dep.type] ?? [];+ const lastRotated = dep.lastRotatedAt+ ? format(new Date(dep.lastRotatedAt), "MMM d, yyyy h:mm a")+ : "Never";++ return (+ <div className="flex flex-col gap-3">+ <div className="grid grid-cols-2 gap-x-8 gap-y-3 lg:grid-cols-3">+ {runAs && <DetailRow label="Runs as" value={runAs} />}+ {typeFields.map((f) => {+ const value = read(f.key);+ return value ? <DetailRow key={f.key} label={f.label} value={value} /> : null;+ })}+ <DetailRow label="Last rotation" value={lastRotated} />+ </div>+ {dep.rotationStatus === "failed" && dep.lastRotationMessage && (+ <div className="rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger">+ {dep.lastRotationMessage}+ </div>+ )}+ </div>+ );+};++export const DependenciesSection = ({ accountId }: { accountId: string }) => {+ const { data: dependencies } = useListPamAccountDependencies(accountId);+ const [expanded, setExpanded] = useState<Record<string, boolean>>({});++ const deps = dependencies ?? [];+ if (deps.length === 0) return null;++ const machineCount = new Set(deps.map((d) => d.machine)).size;++ return (+ <div className="rounded-lg border border-border bg-container p-4">+ <div className="flex items-center gap-2">+ <h3 className="text-sm font-semibold text-foreground">Dependencies</h3>+ <Badge variant="pam">{deps.length}</Badge>+ </div>+ <p className="mb-3 text-xs text-muted">+ Rotating this account updates {deps.length}{" "}+ {deps.length === 1 ? "dependency" : "dependencies"} across {machineCount}{" "}+ {machineCount === 1 ? "machine" : "machines"}.+ </p>+ <Table className="w-full table-fixed">+ <TableHeader>+ <TableRow>+ <TableHead className="w-8" />+ <TableHead className="w-44">Name</TableHead>+ <TableHead className="w-40">Type</TableHead>+ <TableHead>Machine</TableHead>+ <TableHead className="w-36">Rotation Status</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {deps.map((dep) => {+ const isExpanded = Boolean(expanded[dep.id]);+ return (+ <Fragment key={dep.id}>+ <TableRow+ className={`cursor-pointer [&>td]:h-12 ${+ isExpanded ? "border-b-0 bg-container-hover" : ""+ }`}+ onClick={() => setExpanded((prev) => ({ ...prev, [dep.id]: !prev[dep.id] }))}+ >+ <TableCell>+ <ChevronRight+ className={`size-4 text-muted transition-transform ${+ isExpanded ? "rotate-90" : ""+ }`}+ />+ </TableCell>+ <TableCell title={dep.name} className="truncate font-medium text-foreground">+ {dep.name}+ </TableCell>+ <TableCell>+ <Badge variant="neutral">{TYPE_LABELS[dep.type] ?? dep.type}</Badge>+ </TableCell>+ <TableCell className="font-mono text-xs text-muted">+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="block truncate">{dep.machine}</span>+ </TooltipTrigger>+ <TooltipContent className="max-w-sm font-mono break-words">+ {dep.machine}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </TableCell>+ <TableCell>+ <StatusBadge dep={dep} />+ </TableCell>+ </TableRow>+ {isExpanded && (+ <TableRow className="hover:bg-transparent">+ <TableCell colSpan={5} className="bg-container-hover px-6 pt-3 pb-4">+ <DependencyDetail dep={dep} />+ </TableCell>+ </TableRow>+ )}+ </Fragment>+ );+ })}+ </TableBody>+ </Table>+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamAccountsPage/components/DependenciesTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/DependenciesTab.tsxdeleted file mode 100644index 5387e84176..0000000000--- a/frontend/src/pages/pam/PamAccountsPage/components/DependenciesTab.tsx+++ /dev/null@@ -1,124 +0,0 @@-import { AlertCircle } from "lucide-react";--import {- Badge,- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow-} from "@app/components/v3";-import { Skeleton } from "@app/components/v3/generic/Skeleton";-import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger-} from "@app/components/v3/generic/Tooltip";-import { TPamAccountDependency, useListPamAccountDependencies } from "@app/hooks/api/pam";--const TYPE_LABELS: Record<string, string> = {- "windows-service": "Windows Service",- "scheduled-task": "Scheduled Task",- "iis-app-pool": "IIS App Pool"-};--const StatusBadge = ({ dep }: { dep: TPamAccountDependency }) => {- if (dep.rotationStatus === "success") return <Badge variant="success">Synced</Badge>;- if (dep.rotationStatus === "pending") return <Badge variant="neutral">Pending</Badge>;- if (dep.rotationStatus === "failed") {- return (- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <span>- <Badge variant="danger" className="cursor-help gap-1">- <AlertCircle className="size-3" /> Failed- </Badge>- </span>- </TooltipTrigger>- {dep.lastRotationMessage && (- <TooltipContent className="max-w-xs break-words">- {dep.lastRotationMessage}- </TooltipContent>- )}- </Tooltip>- </TooltipProvider>- );- }- return <Badge variant="neutral">Not synced</Badge>;-};--export const DependenciesTab = ({ accountId }: { accountId: string }) => {- const { data: dependencies, isLoading } = useListPamAccountDependencies(accountId);-- if (isLoading) {- return (- <div className="flex flex-col gap-4 p-4">- <Skeleton className="h-8 w-48" />- <Skeleton className="h-32 w-full" />- </div>- );- }-- const deps = dependencies ?? [];- const machineCount = new Set(deps.map((d) => d.machine)).size;-- return (- <div className="flex flex-col gap-4 p-4">- <Card>- <CardHeader className="border-b">- <CardTitle className="text-base">- Dependencies- <Badge variant="pam">{deps.length}</Badge>- </CardTitle>- <CardDescription>- {deps.length === 0- ? "Services, scheduled tasks, and IIS app pools that run as this account, detected automatically during discovery."- : `Rotating this account updates ${deps.length} ${- deps.length === 1 ? "dependency" : "dependencies"- } across ${machineCount} ${machineCount === 1 ? "machine" : "machines"}.`}- </CardDescription>- </CardHeader>- <CardContent>- {deps.length === 0 ? (- <div className="rounded-md border border-border p-8 text-center text-sm text-muted">- No dependencies detected for this account.- </div>- ) : (- <Table>- <TableHeader>- <TableRow>- <TableHead>Name</TableHead>- <TableHead>Type</TableHead>- <TableHead>Machine</TableHead>- <TableHead>Last Rotation</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {deps.map((dep) => (- <TableRow key={dep.id} className="[&>td]:h-12">- <TableCell className="font-medium text-foreground">{dep.name}</TableCell>- <TableCell>- <Badge variant="neutral">{TYPE_LABELS[dep.type] ?? dep.type}</Badge>- </TableCell>- <TableCell className="font-mono text-xs text-muted">{dep.machine}</TableCell>- <TableCell>- <StatusBadge dep={dep} />- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- )}- </CardContent>- </Card>- </div>- );-};diff --git a/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsxindex 758f1c6d40..07afb779d0 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx@@ -31,6 +31,7 @@ import { TPamAccountRotation } from "@app/hooks/api/pam/types";import { formatDetailDate } from "../../components/PamDetailSheet";import { SheetSaveBar } from "../../components/SheetSaveBar";+import { DependenciesSection } from "./DependenciesSection";type Props = { accountId: string; onDirtyChange?: (isDirty: boolean) => void };@@ -167,8 +168,10 @@ export const RotationTab = ({ accountId, onDirtyChange }: Props) => {await updateRotation.mutateAsync({ accountId, rotationAccountId: data.rotationAccountId });createNotification({ type: "success", text: "Rotation account updated" });reset(data);- } catch {- createNotification({ type: "error", text: "Failed to update rotation account" });+ } catch (err) {+ const message = (err as { response?: { data?: { message?: string } } })?.response?.data+ ?.message;+ createNotification({ type: "error", text: message ?? "Failed to update rotation account" });}};@@ -246,11 +249,34 @@ export const RotationTab = ({ accountId, onDirtyChange }: Props) => {{hasFailure && (<Alert variant="danger" className="mt-4"><AlertTitle>Last rotation failed</AlertTitle>- <AlertDescription>{rotation.lastRotationError}</AlertDescription>+ <AlertDescription className="whitespace-pre-line">+ {rotation.lastRotationError}+ </AlertDescription></Alert>)}</div>+ {rotation.sharedIdentity.length > 0 && (+ <Alert variant="warning">+ <AlertTitle>Shared identity</AlertTitle>+ <AlertDescription>+ Rotating this account changes a credential that these other accounts also store. They+ won't be updated automatically and will need their credentials refreshed:+ <ul className="mt-1.5 list-disc pl-4">+ {rotation.sharedIdentity.map((ref) => (+ <li key={ref.id}>+ <span className="font-medium text-foreground">{ref.name}</span>+ {ref.discoverySources.length > 0 &&+ ` (credential for discovery source${+ ref.discoverySources.length > 1 ? "s" : ""+ } ${ref.discoverySources.join(", ")})`}+ </li>+ ))}+ </ul>+ </AlertDescription>+ </Alert>+ )}+<div className="rounded-lg border border-border bg-container p-4"><h3 className="text-sm font-semibold text-foreground">Rotation account</h3><p className="mb-3 text-xs text-muted">@@ -275,6 +301,8 @@ export const RotationTab = ({ accountId, onDirtyChange }: Props) => {</p></div>+ <DependenciesSection accountId={accountId} />+{!rotation.isReady && (<Alert variant="warning"><AlertTitle>Not rotating yet</AlertTitle>diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsxindex 5a267fb45e..9209665e03 100644--- a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx@@ -4,7 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod";import { useQueryClient } from "@tanstack/react-query";import { Link } from "@tanstack/react-router";import { format } from "date-fns";-import { ChevronRight, Play, Radar, Search, TriangleAlert } from "lucide-react";+import { Play, Radar, Search, TriangleAlert } from "lucide-react";import { z } from "zod";import { createNotification } from "@app/components/notifications";@@ -90,12 +90,6 @@ const STATUS_VARIANT: Record<string, "info" | "success" | "danger" | "neutral">failed: "danger"};-const DEPENDENCY_TYPE_LABELS: Record<string, string> = {- "windows-service": "Windows Service",- "scheduled-task": "Scheduled Task",- "iis-app-pool": "IIS App Pool"-};-const RunStatusBadge = ({ status }: { status: string }) => (<Badge variant={STATUS_VARIANT[status] ?? "neutral"}>{status}</Badge>);@@ -344,7 +338,6 @@ type Props = {export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: Props) => {const [selected, setSelected] = useState<Record<string, TPamDiscoveredAccount>>({});- const [expandedDeps, setExpandedDeps] = useState<Record<string, boolean>>({});const [isImportOpen, setIsImportOpen] = useState(false);const [isFormDirty, setIsFormDirty] = useState(false);const [search, setSearch] = useState("");@@ -394,6 +387,9 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: PqueryClient.invalidateQueries({queryKey: [...pamKeys.discovery(), "discovered", sourceId ?? ""]});+ // A scan reconciles dependencies onto managed accounts, so refresh account views (their dependency+ // lists are keyed under pamKeys.account()) which the discovery scan otherwise never invalidates.+ queryClient.invalidateQueries({ queryKey: pamKeys.account() });}prevRunStatus.current = latestRunStatus;}, [latestRunStatus, sourceId, queryClient]);@@ -493,87 +489,40 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: P{visibleStaged.map((account) => {const typeDetails = accountTypeMap[account.accountType as PamAccountType];const hasDeps = account.dependencyCount > 0;- const isExpanded = Boolean(expandedDeps[account.id]);return (- <Fragment key={account.id}>- <TableRow className={isExpanded ? "border-b-0" : undefined}>- <TableCell>- <Checkbox- id={`discovered-${account.id}`}- isChecked={Boolean(selected[account.id])}- onCheckedChange={() => toggle(account)}- />- </TableCell>- <TableCell className="font-medium text-foreground">- <HighlightText text={account.name} highlight={search} />- </TableCell>- <TableCell>- <div className="flex items-center gap-2">- {typeDetails && (- <img- src={`/images/integrations/${typeDetails.icon}`}- alt={typeDetails.name}- className="size-5 shrink-0 rounded-sm"- />- )}- <span className="text-sm">- {typeDetails?.name ?? account.accountType}- </span>- </div>- </TableCell>- <TableCell>- {hasDeps ? (- <button- type="button"- className="flex items-center gap-1 text-sm text-muted hover:text-foreground"- onClick={() =>- setExpandedDeps((prev) => ({- ...prev,- [account.id]: !prev[account.id]- }))- }- >- <ChevronRight- className={`size-4 transition-transform ${isExpanded ? "rotate-90" : ""}`}- />- <Badge variant="neutral">{account.dependencyCount}</Badge>- </button>- ) : (- <span className="text-sm text-muted">-</span>+ <TableRow key={account.id}>+ <TableCell>+ <Checkbox+ id={`discovered-${account.id}`}+ isChecked={Boolean(selected[account.id])}+ onCheckedChange={() => toggle(account)}+ />+ </TableCell>+ <TableCell className="font-medium text-foreground">+ <HighlightText text={account.name} highlight={search} />+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-2">+ {typeDetails && (+ <img+ src={`/images/integrations/${typeDetails.icon}`}+ alt={typeDetails.name}+ className="size-5 shrink-0 rounded-sm"+ />)}- </TableCell>- </TableRow>-- {isExpanded && hasDeps && (- <TableRow className="hover:bg-transparent">- <TableCell colSpan={4} className="pt-0 pb-4">- <div className="ml-8 rounded-md border border-border">- <div className="border-b border-border px-3 py-2 text-xs font-medium text-muted">- Dependencies · {account.dependencyCount}- </div>- <ul className="divide-y divide-border">- {account.dependencies.map((dep) => (- <li- key={dep.id}- className="flex items-center justify-between gap-4 px-3 py-2 text-sm"- >- <span className="font-medium text-foreground">- {dep.name}- </span>- <span className="flex items-center gap-2 text-xs text-muted">- <Badge variant="neutral">- {DEPENDENCY_TYPE_LABELS[dep.type] ?? dep.type}- </Badge>- <span className="font-mono">{dep.machine}</span>- </span>- </li>- ))}- </ul>- </div>- </TableCell>- </TableRow>- )}- </Fragment>+ <span className="text-sm">+ {typeDetails?.name ?? account.accountType}+ </span>+ </div>+ </TableCell>+ <TableCell>+ {hasDeps ? (+ <Badge variant="neutral">{account.dependencyCount}</Badge>+ ) : (+ <span className="text-sm text-muted">-</span>+ )}+ </TableCell>+ </TableRow>);})}</TableBody>@@ -628,10 +577,10 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: P</EmptyHeader></Empty>) : (- <Table>+ <Table className="w-full table-fixed"><TableHeader><TableRow>- <TableHead>Started</TableHead>+ <TableHead className="w-44">Started</TableHead><TableHead className="w-28">Status</TableHead><TableHead>Result</TableHead></TableRow>@@ -644,7 +593,7 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: Preturn (<Fragment key={run.id}>- <TableRow className={hasMachineErrors ? "border-b-0" : undefined}>+ <TableRow className={hasMachineErrors ? "[&>td]:border-b-0" : undefined}><TableCell className="text-muted">{run.startedAt? format(new Date(run.startedAt), "MMM d, yyyy h:mm a")@@ -653,34 +602,49 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: P<TableCell><RunStatusBadge status={run.status} /></TableCell>- <TableCell className="text-muted">+ <TableCell className="whitespace-normal text-muted">{run.status === "failed" ? (- <span className="whitespace-pre-line text-danger">+ <span className="break-words whitespace-pre-line text-danger">{run.errorMessage}</span>) : (- `${run.discoveredCount} found, ${run.newCount} new`+ <div className="grid w-fit grid-cols-[auto_auto] gap-x-6">+ <span>+ {run.discoveredCount}{" "}+ {run.discoveredCount === 1 ? "account" : "accounts"}+ </span>+ <span className="text-muted/60">{run.newCount} new</span>+ {typeof run.dependencyCount === "number" && (+ <>+ <span>+ {run.dependencyCount}{" "}+ {run.dependencyCount === 1 ? "dep" : "deps"}+ </span>+ <span className="text-muted/60">+ {run.newDependencyCount ?? 0} new+ </span>+ </>+ )}+ </div>)}</TableCell></TableRow>{hasMachineErrors && (- <TableRow className="hover:bg-transparent">- <TableCell colSpan={3} className="pt-0 pb-4">- <div className="rounded-md border border-warning/20 bg-warning/[0.06] p-3">- <div className="flex items-center gap-2 text-sm font-medium text-warning">- <TriangleAlert className="size-4 shrink-0" />- The scan failed to find local accounts on certain machines- </div>- <ul className="mt-2 flex flex-col gap-1.5">- {machineErrors.map((m) => (- <li key={m.machine} className="text-xs">- <span className="font-medium text-foreground">{m.machine}</span>- <span className="text-muted">: {m.error}</span>- </li>- ))}- </ul>+ <TableRow className="bg-warning/[0.04] hover:bg-warning/[0.04]">+ <TableCell colSpan={3} className="pt-3 pb-4 whitespace-normal">+ <div className="flex items-center gap-2 text-sm font-medium text-warning">+ <TriangleAlert className="size-4 shrink-0" />+ The scan couldn't complete on some machines</div>+ <ul className="mt-2 flex flex-col gap-1.5">+ {machineErrors.map((m) => (+ <li key={m.machine} className="text-xs break-words">+ <span className="font-medium text-foreground">{m.machine}</span>+ <span className="text-muted">: {m.error}</span>+ </li>+ ))}+ </ul></TableCell></TableRow>)}diff --git a/frontend/src/pages/pam/components/pamResourceTabs.ts b/frontend/src/pages/pam/components/pamResourceTabs.tsindex cb5fef574b..634fe4bfe1 100644--- a/frontend/src/pages/pam/components/pamResourceTabs.ts+++ b/frontend/src/pages/pam/components/pamResourceTabs.ts@@ -6,8 +6,7 @@ import {Settings,Settings2,ShieldCheck,- Users,- Workflow+ Users} from "lucide-react";import { PamResourcePermissionActions } from "@app/hooks/api/pam";@@ -39,12 +38,6 @@ export const PAM_ACCOUNT_TABS: PamResourceTab[] = [icon: RotateCcw,action: PamResourcePermissionActions.ManageRotation},- {- value: PamSheetTab.Dependencies,- label: "Dependencies",- icon: Workflow,- action: PamResourcePermissionActions.ReadAccounts- },{value: PamSheetTab.Advanced,label: "Advanced",