Skip to content

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

feat(pam): domain account dependency detection and Windows rotation (PAM-350)

bernie-g9ed00ef28db0
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 1ae6bb7211..f8e0885de9 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -160,7 +160,6 @@
"tweetnacl": "^1.0.3",
"tweetnacl-util": "^0.15.1",
"uuid": "^11.1.1",
- "winrm-client": "github:Infisical/winrm-client#v1.0.0",
"zod": "^3.22.4",
"zod-to-json-schema": "^3.24.5"
},
@@ -6729,6 +6728,9 @@
"win32"
]
},
+ "node_modules/@infisical/quic/node_modules/@infisical/quic-linux-arm": {
+ "optional": true
+ },
"node_modules/@inquirer/external-editor": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-1.0.3.tgz",
@@ -28678,19 +28680,6 @@
"string-width": "^1.0.2 || 2 || 3 || 4"
}
},
- "node_modules/winrm-client": {
- "version": "0.0.12",
- "resolved": "git+ssh://[email protected]/Infisical/winrm-client.git#a3a48f55958cc2d49b152f98c8d1b7b87f97cb27",
- "license": "MIT",
- "dependencies": {
- "fast-xml-parser": "^4.3.2",
- "js-md4": "^0.3.2",
- "uuid": "^11.1.0"
- },
- "engines": {
- "node": ">=16.0.0"
- }
- },
"node_modules/winston": {
"version": "3.15.0",
"resolved": "https://registry.npmjs.org/winston/-/winston-3.15.0.tgz",
diff --git a/backend/package.json b/backend/package.json
index 5ce308bf36..f808e2edcc 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -299,7 +299,6 @@
"tweetnacl": "^1.0.3",
"tweetnacl-util": "^0.15.1",
"uuid": "^11.1.1",
- "winrm-client": "github:Infisical/winrm-client#v1.0.0",
"zod": "^3.22.4",
"zod-to-json-schema": "^3.24.5"
}
diff --git a/backend/src/db/migrations/20260720183403_pam-account-dependencies-rework.ts b/backend/src/db/migrations/20260720183403_pam-account-dependencies-rework.ts
new file mode 100644
index 0000000000..80f14b4798
--- /dev/null
+++ b/backend/src/db/migrations/20260720183403_pam-account-dependencies-rework.ts
@@ -0,0 +1,86 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+// Reworks the orphaned pre-revamp pam_account_dependencies table (which pointed at the legacy
+// pam_resources table) into a dependency table keyed off the revamp account model: a dependency is
+// anchored to its run-as identity (fingerprint) and points at either the staged discovered account
+// (discoveredAccountId, while its account is only staged) or the imported managed account (accountId).
+export async function up(knex: Knex): Promise<void> {
+ await knex.schema.dropTableIfExists(TableName.PamAccountDependency);
+
+ await knex.schema.createTable(TableName.PamAccountDependency, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ // Run-as stable identity (domain:objectGUID / SID); the upsert key, stable across the
+ // staged -> imported flip.
+ t.string("fingerprint").notNullable();
+
+ t.uuid("accountId");
+ t.foreign("accountId").references("id").inTable(TableName.PamAccount).onDelete("CASCADE");
+ t.index("accountId");
+
+ t.uuid("discoveredAccountId");
+ t.foreign("discoveredAccountId").references("id").inTable(TableName.PamDiscoveredAccount).onDelete("CASCADE");
+ t.index("discoveredAccountId");
+
+ t.string("type").notNullable(); // windows-service / scheduled-task / iis-app-pool
+ t.string("name").notNullable();
+ t.string("machine").notNullable();
+ t.jsonb("data").notNullable(); // type-specific detail (run-as, path, triggers, etc.)
+
+ t.string("rotationStatus").nullable(); // pending / success / failed (set by rotation sync)
+ t.timestamp("lastRotatedAt").nullable();
+ t.binary("encryptedLastRotationMessage").nullable();
+
+ t.timestamps(true, true, true);
+
+ t.unique(["fingerprint", "machine", "type", "name"]);
+ });
+
+ // Exactly one of accountId / discoveredAccountId is set: staged -> discoveredAccountId, imported -> accountId.
+ await knex.raw(
+ `ALTER TABLE "${TableName.PamAccountDependency}" ADD CONSTRAINT "pam_account_dependencies_account_xor_discovered" CHECK (("accountId" IS NULL) <> ("discoveredAccountId" IS NULL))`
+ );
+
+ await createOnUpdateTrigger(knex, TableName.PamAccountDependency);
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await dropOnUpdateTrigger(knex, TableName.PamAccountDependency);
+ await knex.schema.dropTableIfExists(TableName.PamAccountDependency);
+
+ // Restore the legacy (orphaned) shape so a rollback lands on the prior schema.
+ await knex.schema.createTable(TableName.PamAccountDependency, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.uuid("accountId").notNullable();
+ t.foreign("accountId").references("id").inTable(TableName.PamAccount).onDelete("CASCADE");
+ t.index("accountId");
+
+ t.uuid("resourceId").notNullable();
+ t.foreign("resourceId").references("id").inTable(TableName.PamResource).onDelete("CASCADE");
+ t.index("resourceId");
+
+ t.string("dependencyType").notNullable();
+ t.string("name").notNullable();
+ t.string("displayName").nullable();
+
+ t.string("state").nullable();
+ t.jsonb("data").notNullable();
+
+ t.string("source").notNullable();
+ t.boolean("isRotationSyncEnabled").defaultTo(false);
+
+ t.string("syncStatus").nullable();
+ t.timestamp("lastSyncedAt").nullable();
+ t.binary("encryptedLastSyncMessage").nullable();
+
+ t.unique(["accountId", "resourceId", "dependencyType", "name"], {
+ indexName: "uidx_pam_account_dependency"
+ });
+
+ t.timestamps(true, true, true);
+ });
+}
diff --git a/backend/src/db/schemas/pam-account-dependencies.ts b/backend/src/db/schemas/pam-account-dependencies.ts
index 53042da971..ef48547621 100644
--- a/backend/src/db/schemas/pam-account-dependencies.ts
+++ b/backend/src/db/schemas/pam-account-dependencies.ts
@@ -11,20 +11,18 @@ import { TImmutableDBKeys } from "./models";
export const PamAccountDependenciesSchema = z.object({
id: z.string().uuid(),
- accountId: z.string().uuid(),
- resourceId: z.string().uuid(),
- dependencyType: z.string(),
+ fingerprint: z.string(),
+ accountId: z.string().uuid().nullable().optional(),
+ discoveredAccountId: z.string().uuid().nullable().optional(),
+ type: z.string(),
name: z.string(),
- displayName: z.string().nullable().optional(),
- state: z.string().nullable().optional(),
+ machine: z.string(),
data: z.unknown(),
- source: z.string(),
- isRotationSyncEnabled: z.boolean().default(false).nullable().optional(),
+ rotationStatus: z.string().nullable().optional(),
+ lastRotatedAt: z.date().nullable().optional(),
+ encryptedLastRotationMessage: zodBuffer.nullable().optional(),
createdAt: z.date(),
- updatedAt: z.date(),
- syncStatus: z.string().nullable().optional(),
- lastSyncedAt: z.date().nullable().optional(),
- encryptedLastSyncMessage: zodBuffer.nullable().optional()
+ updatedAt: z.date()
});
export type TPamAccountDependencies = z.infer<typeof PamAccountDependenciesSchema>;
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 aadea7bd1d..8f058a5a34 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
@@ -509,6 +509,47 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "GET",
+ url: "/:accountId/dependencies",
+ schema: {
+ operationId: "listPamAccountDependencies",
+ description:
+ "List the detected dependencies (Windows services, scheduled tasks, IIS app pools) for a PAM account",
+ tags: [ApiDocsTags.PamAccounts],
+ params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
+ response: {
+ 200: z.object({
+ dependencies: z.array(
+ z.object({
+ id: z.string(),
+ type: z.string(),
+ name: z.string(),
+ machine: z.string(),
+ data: z.unknown(),
+ rotationStatus: z.string().nullable(),
+ lastRotatedAt: z.date().nullable(),
+ lastRotationMessage: z.string().nullable()
+ })
+ )
+ })
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const dependencies = await server.services.pamDiscovery.listAccountDependencies({
+ accountId: req.params.accountId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ return { dependencies };
+ }
+ });
+
server.route({
method: "PATCH",
url: "/:accountId/rotation",
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts
index 681156dad4..3d3cba34d2 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts
@@ -30,12 +30,21 @@ const SourceSchema = PamDiscoverySourcesSchema.extend({
lastRunError: z.string().nullable().optional()
});
+const DiscoveredDependencySchema = z.object({
+ id: z.string(),
+ type: z.string(),
+ name: z.string(),
+ machine: z.string()
+});
+
const DiscoveredAccountSchema = z.object({
id: z.string(),
accountType: z.nativeEnum(PamAccountType),
name: z.string(),
fingerprint: z.string(),
- createdAt: z.date()
+ createdAt: z.date(),
+ dependencyCount: z.number(),
+ dependencies: z.array(DiscoveredDependencySchema)
});
const toPascalCase = (s: string) =>
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.ts
index 6a1e628788..4cfc600875 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
@@ -59,7 +59,9 @@ const buildService = (
const rotationHandlers: typeof PAM_ROTATION_FACTORY_MAP = {
[PamAccountType.Postgres]: handler,
[PamAccountType.MySQL]: handler,
- [PamAccountType.MsSQL]: handler
+ [PamAccountType.MsSQL]: handler,
+ [PamAccountType.Windows]: handler,
+ [PamAccountType.WindowsAd]: handler
};
const identityCipher = {
@@ -84,6 +86,7 @@ const buildService = (
gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() },
gatewayV2Service: { getPlatformConnectionDetailsByGatewayId: vi.fn() },
gatewayPoolService: { resolveEffectiveGatewayId: vi.fn() },
+ pamAccountDependencyDAL: { findByAccountId: vi.fn(async () => []), updateById: vi.fn(async () => undefined) },
rotationHandlers
};
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.ts
index 0b7148b15c..48aa8ac534 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
@@ -1,3 +1,5 @@
+import pLimit from "p-limit";
+
import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
@@ -6,6 +8,8 @@ import { ResourcePermissionPamResourceActions } from "@app/ee/services/permissio
import { generatePassword } from "@app/ee/services/secret-rotation-v2/shared/utils";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-rpc";
+import { logger } from "@app/lib/logger";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
@@ -16,6 +20,8 @@ import { checkAccountAccess, getResourceIdsWithActions, TActorContext } from "..
import { TPamAccountDALFactory, TPamAccountDetail } from "../pam-account/pam-account-dal";
import { validateConnectionDetails, validateCredentials } from "../pam-account/pam-account-schemas";
import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";
+import { TPamAccountDependencyDALFactory } from "../pam-discovery/pam-account-dependency-dal";
+import { winrmRpcWithGateway } from "../pam-discovery/pam-discovery-fns";
import {
TGetPamAccountRotationDTO,
TListPamRotationCandidatesDTO,
@@ -27,11 +33,12 @@ import {
computeNextRotationAt,
getRotationReadiness,
isRotatableAccountType,
+ isWindowsRotatableType,
PamRotationReadinessIssue,
+ redactRotationError,
ROTATION_FAILURE_RETRY_CAP_SECONDS
} from "./pam-rotation-fns";
import { PAM_ROTATION_FACTORY_MAP } from "./pam-rotation-handlers";
-import { TPamSqlConnectionDetails } from "./shared/pam-rotation-sql-connection";
export const ROTATION_STATUS = { Success: "success", Failed: "failed" } as const;
@@ -62,6 +69,7 @@ type TPamAccountRotationServiceFactoryDep = {
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ pamAccountDependencyDAL: Pick<TPamAccountDependencyDALFactory, "findByAccountId" | "updateById">;
rotationHandlers?: typeof PAM_ROTATION_FACTORY_MAP;
};
@@ -78,6 +86,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
gatewayService,
gatewayV2Service,
gatewayPoolService,
+ pamAccountDependencyDAL,
rotationHandlers = PAM_ROTATION_FACTORY_MAP
} = deps;
@@ -136,19 +145,122 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
nextRotationAt: nextRotationAfter(account.templateSettings, now)
});
- const toSqlConnectionDetails = (
+ const resolveConnectionDetails = (
accountType: PamAccountType,
raw: Record<string, unknown>
- ): TPamSqlConnectionDetails => validateConnectionDetails(accountType, raw) as TPamSqlConnectionDetails;
+ ): Record<string, unknown> => validateConnectionDetails(accountType, raw) as Record<string, unknown>;
+
+ // Windows dependencies have no per-machine WinRM port; use the WinRM HTTP default like discovery/rotation.
+ const WINRM_DEPENDENCY_SYNC_PORT = 5985;
+ const DEPENDENCY_SYNC_CONCURRENCY = 5;
+
+ // postRotate: push the new password into every service / scheduled task / IIS app pool that runs as the
+ // account, connecting to each dependency's machine as the (delegated admin) rotator. Best-effort: a per-
+ // dependency failure is recorded on the row and never fails the account rotation.
+ const syncDependenciesAfterRotation = async ({
+ accountId,
+ projectId,
+ accountType,
+ targetUsername,
+ newPassword,
+ connectAuth,
+ gatewayId,
+ gatewayPoolId
+ }: {
+ accountId: string;
+ projectId: string;
+ accountType: PamAccountType;
+ targetUsername: string;
+ newPassword: string;
+ connectAuth: { username: string; password: string };
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ }) => {
+ // Dependencies are detected only for domain accounts today.
+ if (accountType !== PamAccountType.WindowsAd) return;
+
+ const dependencies = await pamAccountDependencyDAL.findByAccountId(accountId);
+ if (!dependencies.length) return;
+
+ const resolvedGatewayId = gatewayPoolId
+ ? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId, gatewayPoolId })
+ : gatewayId;
+ if (!resolvedGatewayId) {
+ logger.warn(`PAM dependency sync skipped, no gateway available [accountId=${accountId}]`);
+ return;
+ }
+
+ const { encryptor } = await getProjectCipher(projectId);
+ const limit = pLimit(DEPENDENCY_SYNC_CONCURRENCY);
+
+ await Promise.all(
+ dependencies.map((dep) =>
+ limit(async () => {
+ await pamAccountDependencyDAL.updateById(dep.id, { rotationStatus: "pending" });
+ try {
+ const depData = dep.data as { runAsAccount?: string; resolvedIp?: string };
+ const runAsAccount = depData?.runAsAccount ?? targetUsername;
+ // Prefer the IP resolved at scan time: the gateway can't always resolve AD hostnames directly.
+ const targetHost = depData?.resolvedIp || dep.machine;
+ await winrmRpcWithGateway<{ ok: boolean }>({
+ targetHost,
+ targetPort: WINRM_DEPENDENCY_SYNC_PORT,
+ gatewayId: resolvedGatewayId,
+ gatewayV2Service,
+ endpoint: WinRmRpcEndpoint.SyncDependency,
+ credentials: { username: connectAuth.username, password: connectAuth.password },
+ params: { type: dep.type, name: dep.name, runAsUsername: runAsAccount, newPassword }
+ });
+ await pamAccountDependencyDAL.updateById(dep.id, {
+ rotationStatus: "success",
+ lastRotatedAt: new Date(),
+ encryptedLastRotationMessage: null
+ });
+ } catch (err) {
+ const message = redactRotationError(err, [newPassword, connectAuth.password]);
+ logger.warn(err, `PAM dependency sync failed [accountId=${accountId}] [dependencyId=${dep.id}]`);
+ await pamAccountDependencyDAL.updateById(dep.id, {
+ rotationStatus: "failed",
+ encryptedLastRotationMessage: encryptor({ plainText: Buffer.from(message) }).cipherTextBlob
+ });
+ }
+ })
+ )
+ );
+ };
+
+ // 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 = (
+ accountType: PamAccountType,
+ a: Record<string, unknown>,
+ b: Record<string, unknown>
+ ): boolean => {
+ if (accountType === PamAccountType.WindowsAd) return a.dcAddress === b.dcAddress && a.domain === b.domain;
+ if (isWindowsRotatableType(accountType)) return a.host === b.host;
+ return a.host === b.host && a.port === b.port;
+ };
+
+ const assertRotatorSameResource = (
+ accountType: PamAccountType,
+ rotatorConn: Record<string, unknown>,
+ targetConn: Record<string, unknown>
+ ) => {
+ if (isSameResource(accountType, rotatorConn, targetConn)) return;
+ let detail = "on the same resource (host and port) as";
+ if (accountType === PamAccountType.WindowsAd) detail = "in the same domain as";
+ else if (isWindowsRotatableType(accountType)) detail = "on the same host as";
+ throw new BadRequestError({ message: `Rotation account is no longer ${detail} this account` });
+ };
const resolveRotator = async (
account: TPamAccountDetail,
targetCredentials: TSqlAccountCredentials,
- targetConnectionDetails: TPamSqlConnectionDetails,
+ targetConnectionDetails: Record<string, unknown>,
targetGateway: { gatewayId?: string | null; gatewayPoolId?: string | null }
): Promise<{
auth: { username: string; password: string };
- connectionDetails: TPamSqlConnectionDetails;
+ connectionDetails: Record<string, unknown>;
gatewayId?: string | null;
gatewayPoolId?: string | null;
}> => {
@@ -178,7 +290,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
if (!rotatorCredentials.password) {
throw new BadRequestError({ message: "Rotation account has no stored password" });
}
- const rotatorConnectionDetails = toSqlConnectionDetails(
+ const rotatorConnectionDetails = resolveConnectionDetails(
account.accountType as PamAccountType,
await decrypt(projectId, rotator.encryptedConnectionDetails)
);
@@ -207,7 +319,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
handler.validateTarget({ accountType, authMethod: targetCredentials.authMethod });
- const connectionDetails = toSqlConnectionDetails(
+ const connectionDetails = resolveConnectionDetails(
accountType,
await decrypt(projectId, account.encryptedConnectionDetails)
);
@@ -220,15 +332,11 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
if (!rotator || rotator.projectId !== projectId) {
throw new BadRequestError({ message: "Rotation account no longer exists" });
}
- const rotatorConnection = toSqlConnectionDetails(
+ const rotatorConnection = resolveConnectionDetails(
accountType,
await decrypt(projectId, rotator.encryptedConnectionDetails)
);
- if (rotatorConnection.host !== connectionDetails.host || rotatorConnection.port !== connectionDetails.port) {
- throw new BadRequestError({
- message: "Rotation account is no longer on the same resource (host and port) as this account"
- });
- }
+ assertRotatorSameResource(accountType, rotatorConnection, connectionDetails);
}
// Recovery from an interrupted rotation: probe the candidate then the current credential, acting only on a
@@ -308,6 +416,26 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
}
await markRotated(account, encryptedPending, now);
+
+ // postRotate: propagate the new password to the account's dependent services. Best-effort and fully
+ // guarded so a dependency-sync failure never undoes the already-committed account rotation.
+ try {
+ await syncDependenciesAfterRotation({
+ accountId: account.id,
+ projectId,
+ accountType,
+ targetUsername,
+ newPassword,
+ // 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:
+ account.rotationAccountId === account.id ? { username: auth.username, password: newPassword } : auth,
+ gatewayId,
+ gatewayPoolId
+ });
+ } catch (err) {
+ logger.warn(err, `PAM dependency sync errored after rotation [accountId=${account.id}]`);
+ }
};
// Advance nextRotationAt to a capped retry, but only when the account is schedulable: a ready account's early
@@ -468,19 +596,15 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
if (!rotator.credentialConfigured) {
throw new BadRequestError({ message: "Rotation account has no stored credential to perform rotations" });
}
- const targetConn = toSqlConnectionDetails(
+ const targetConn = resolveConnectionDetails(
account.accountType,
await decrypt(projectId, account.encryptedConnectionDetails)
);
- const rotatorConn = toSqlConnectionDetails(
+ const rotatorConn = resolveConnectionDetails(
account.accountType,
await decrypt(projectId, rotator.encryptedConnectionDetails)
);
- if (targetConn.host !== rotatorConn.host || targetConn.port !== rotatorConn.port) {
- throw new BadRequestError({
- message: "Rotation account must be on the same resource (host and port) as this account"
- });
- }
+ assertRotatorSameResource(account.accountType as PamAccountType, rotatorConn, targetConn);
// 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(
@@ -571,18 +695,20 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
);
const { decryptor } = await getProjectCipher(projectId);
+ const accountType = account.accountType as PamAccountType;
const detailsOf = (blob: Buffer) =>
- toSqlConnectionDetails(
- account.accountType as PamAccountType,
+ resolveConnectionDetails(
+ accountType,
JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>
);
const target = detailsOf(account.encryptedConnectionDetails);
const withHost = candidates
- .map((candidate) => {
- const details = detailsOf(candidate.encryptedConnectionDetails);
- return { ...candidate, host: details.host, port: details.port };
- })
- .filter((candidate) => candidate.host === target.host && candidate.port === target.port);
+ .map((candidate) => ({ ...candidate, details: detailsOf(candidate.encryptedConnectionDetails) }))
+ .filter((candidate) => isSameResource(accountType, candidate.details, target));
+
+ // The resource label shown per candidate: the DC for a domain account, otherwise the host.
+ const displayHost = (details: Record<string, unknown>) =>
+ String((accountType === PamAccountType.WindowsAd ? details.dcAddress : details.host) ?? "");
const groupsByFolder = new Map<
string,
@@ -593,7 +719,9 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
if (!groupsByFolder.has(key)) {
groupsByFolder.set(key, { folderId: candidate.folderId, folderName: candidate.folderName, accounts: [] });
}
- groupsByFolder.get(key)!.accounts.push({ id: candidate.id, name: candidate.name, host: candidate.host });
+ groupsByFolder
+ .get(key)!
+ .accounts.push({ id: candidate.id, name: candidate.name, host: displayHost(candidate.details) });
}
return { candidates: Array.from(groupsByFolder.values()) };
diff --git a/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.test.ts b/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.test.ts
index 90454984bc..1001ca2da2 100644
--- a/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.test.ts
+++ b/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.test.ts
@@ -15,10 +15,15 @@ describe("isRotatableAccountType", () => {
expect(isRotatableAccountType(PamAccountType.MsSQL)).toBe(true);
});
- test("rejects non-SQL types", () => {
+ test("accepts Windows local and domain accounts", () => {
+ expect(isRotatableAccountType(PamAccountType.Windows)).toBe(true);
+ expect(isRotatableAccountType(PamAccountType.WindowsAd)).toBe(true);
+ });
+
+ test("rejects non-rotatable types", () => {
expect(isRotatableAccountType(PamAccountType.SSH)).toBe(false);
- expect(isRotatableAccountType(PamAccountType.Windows)).toBe(false);
expect(isRotatableAccountType(PamAccountType.AwsIam)).toBe(false);
+ expect(isRotatableAccountType(PamAccountType.Redis)).toBe(false);
});
});
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.ts
index 236fb63010..0cac82da16 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
@@ -2,16 +2,31 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enums
import { PamAccountType } from "../pam/pam-enums";
-export const ROTATABLE_ACCOUNT_TYPES = [PamAccountType.Postgres, PamAccountType.MySQL, PamAccountType.MsSQL] as const;
+export const SQL_ROTATABLE_ACCOUNT_TYPES = [
+ PamAccountType.Postgres,
+ PamAccountType.MySQL,
+ PamAccountType.MsSQL
+] as const;
-export const isRotatableAccountType = (
- accountType: PamAccountType | string
-): accountType is (typeof ROTATABLE_ACCOUNT_TYPES)[number] =>
+// Windows accounts rotate over WinRM through the gateway: local accounts on their host, domain accounts
+// on the DC. They do not use the SQL rotation path.
+export const WINDOWS_ROTATABLE_ACCOUNT_TYPES = [PamAccountType.Windows, PamAccountType.WindowsAd] as const;
+
+export const ROTATABLE_ACCOUNT_TYPES = [...SQL_ROTATABLE_ACCOUNT_TYPES, ...WINDOWS_ROTATABLE_ACCOUNT_TYPES] as const;
+
+export type TSqlRotatableType = (typeof SQL_ROTATABLE_ACCOUNT_TYPES)[number];
+export type TWindowsRotatableType = (typeof WINDOWS_ROTATABLE_ACCOUNT_TYPES)[number];
+export type TRotatableType = (typeof ROTATABLE_ACCOUNT_TYPES)[number];
+
+export const isRotatableAccountType = (accountType: PamAccountType | string): accountType is TRotatableType =>
(ROTATABLE_ACCOUNT_TYPES as readonly string[]).includes(accountType);
+export const isWindowsRotatableType = (accountType: PamAccountType | string): accountType is TWindowsRotatableType =>
+ (WINDOWS_ROTATABLE_ACCOUNT_TYPES as readonly string[]).includes(accountType);
+
// PamAccountType -> AppConnection, so we can reuse the per-dialect ALTER statement map keyed by AppConnection.
export const PAM_ROTATION_APP_MAP: Record<
- (typeof ROTATABLE_ACCOUNT_TYPES)[number],
+ TSqlRotatableType,
AppConnection.Postgres | AppConnection.MySql | AppConnection.MsSql
> = {
[PamAccountType.Postgres]: AppConnection.Postgres,
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.ts
index 010b0bed51..03a67b1072 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
@@ -1,4 +1,5 @@
import { BadRequestError } from "@app/lib/errors";
+import { WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-rpc";
import {
getRoleUsernameForHost,
getSqlConnectionVerifyQuery,
@@ -6,7 +7,8 @@ import {
} from "@app/services/app-connection/shared/sql";
import { PamAccountType } from "../pam/pam-enums";
-import { PAM_ROTATION_APP_MAP, redactRotationError, ROTATABLE_ACCOUNT_TYPES } from "./pam-rotation-fns";
+import { ldapBindCheckViaGateway, winrmRpcWithGateway } from "../pam-discovery/pam-discovery-fns";
+import { PAM_ROTATION_APP_MAP, redactRotationError, TRotatableType, TSqlRotatableType } from "./pam-rotation-fns";
import {
SQL_QUERY_TIMEOUT,
TPamRotationGatewayDeps,
@@ -14,11 +16,10 @@ import {
withPamSqlClient
} from "./shared/pam-rotation-sql-connection";
-type TRotatableType = (typeof ROTATABLE_ACCOUNT_TYPES)[number];
-
type TApplyPasswordChangeInput = {
accountType: TRotatableType;
- connectionDetails: TPamSqlConnectionDetails;
+ // Type-specific connection details; each handler narrows to the shape for its account type.
+ connectionDetails: Record<string, unknown>;
// Authenticates the connection: the account's own credential (self) or the rotator's (delegated).
auth: { username: string; password: string };
targetUsername: string;
@@ -29,7 +30,7 @@ type TApplyPasswordChangeInput = {
type TTestCredentialInput = {
accountType: TRotatableType;
- connectionDetails: TPamSqlConnectionDetails;
+ connectionDetails: Record<string, unknown>;
auth: { username: string; password: string };
gatewayId?: string | null;
gatewayPoolId?: string | null;
@@ -51,17 +52,20 @@ const sqlRotationHandler: TPamRotationHandler = {
},
applyPasswordChange: async (input, deps) => {
- const { accountType, connectionDetails, auth, targetUsername, newPassword, gatewayId, gatewayPoolId } = input;
+ const { accountType, auth, targetUsername, newPassword, gatewayId, gatewayPoolId } = input;
+ const connectionDetails = input.connectionDetails as TPamSqlConnectionDetails;
// Strip the PlanetScale `<user>.<branch>` suffix so the ALTER targets the real role.
const roleUsername = getRoleUsernameForHost(targetUsername, connectionDetails.host);
- const [statement, bindings] = SQL_CONNECTION_ALTER_LOGIN_STATEMENT[PAM_ROTATION_APP_MAP[accountType]]({
+ const [statement, bindings] = SQL_CONNECTION_ALTER_LOGIN_STATEMENT[
+ PAM_ROTATION_APP_MAP[accountType as TSqlRotatableType]
+ ]({
username: roleUsername,
password: newPassword
});
try {
await withPamSqlClient(
- { accountType, connectionDetails, auth, gatewayId, gatewayPoolId },
+ { accountType: accountType as TSqlRotatableType, connectionDetails, auth, gatewayId, gatewayPoolId },
deps,
async (client) => {
// No `cancel: true`: tedious (mssql) throws on cancellation. A plain timeout rejects on all dialects,
@@ -76,13 +80,16 @@ const sqlRotationHandler: TPamRotationHandler = {
},
testCredential: async (input, deps) => {
- const { accountType, connectionDetails, auth, gatewayId, gatewayPoolId } = input;
+ const { accountType, auth, gatewayId, gatewayPoolId } = input;
+ const connectionDetails = input.connectionDetails as TPamSqlConnectionDetails;
try {
await withPamSqlClient(
- { accountType, connectionDetails, auth, gatewayId, gatewayPoolId },
+ { accountType: accountType as TSqlRotatableType, connectionDetails, auth, gatewayId, gatewayPoolId },
deps,
async (client) => {
- await client.raw(getSqlConnectionVerifyQuery(PAM_ROTATION_APP_MAP[accountType])).timeout(SQL_QUERY_TIMEOUT);
+ await client
+ .raw(getSqlConnectionVerifyQuery(PAM_ROTATION_APP_MAP[accountType as TSqlRotatableType]))
+ .timeout(SQL_QUERY_TIMEOUT);
}
);
return true;
@@ -92,9 +99,125 @@ const sqlRotationHandler: TPamRotationHandler = {
}
};
-// Full Record over the rotatable types so a missing dialect entry is a compile error.
+// Windows accounts have no per-account WinRM port in their connection details, so use the WinRM HTTP default.
+const WINRM_ROTATION_PORT = 5985;
+
+type TWindowsConnDetails = { host?: string };
+type TWindowsAdConnDetails = {
+ domain?: string;
+ dcAddress?: string;
+ port?: number;
+ useLdaps?: boolean;
+ ldapRejectUnauthorized?: boolean;
+ ldapCaCert?: string;
+ ldapTlsServerName?: string;
+};
+
+// Local accounts rotate on their own host; domain accounts rotate on the DC (which has the AD tooling).
+const winrmRotationTargetHost = (accountType: TRotatableType, connectionDetails: Record<string, unknown>): string => {
+ if (accountType === PamAccountType.WindowsAd) {
+ const conn = connectionDetails as TWindowsAdConnDetails;
+ if (!conn.dcAddress) {
+ throw new BadRequestError({ message: "Windows AD account is missing a domain controller address" });
+ }
+ return conn.dcAddress;
+ }
+ const conn = connectionDetails as TWindowsConnDetails;
+ if (!conn.host) throw new BadRequestError({ message: "Windows account is missing a host" });
+ return conn.host;
+};
+
+const resolveRotationGatewayId = async (
+ deps: TPamRotationGatewayDeps,
+ gatewayId?: string | null,
+ gatewayPoolId?: string | null
+): Promise<string> => {
+ const resolved = gatewayPoolId
+ ? await deps.gatewayPoolService.resolveEffectiveGatewayId({ gatewayId, gatewayPoolId })
+ : gatewayId;
+ if (!resolved) throw new BadRequestError({ message: "No healthy gateway available for Windows rotation" });
+ return resolved;
+};
+
+const windowsRotationHandler: TPamRotationHandler = {
+ validateTarget: () => {
+ // Domain rotation needs a delegated admin (an account can't -Reset itself); AD enforces this at runtime.
+ },
+
+ applyPasswordChange: async (input, deps) => {
+ const { accountType, connectionDetails, auth, targetUsername, newPassword, gatewayId, gatewayPoolId } = input;
+ const targetHost = winrmRotationTargetHost(accountType, connectionDetails);
+ const resolvedGatewayId = await resolveRotationGatewayId(deps, gatewayId, gatewayPoolId);
+
+ try {
+ await winrmRpcWithGateway<{ ok: boolean }>({
+ targetHost,
+ targetPort: WINRM_ROTATION_PORT,
+ gatewayId: resolvedGatewayId,
+ gatewayV2Service: deps.gatewayV2Service,
+ endpoint: WinRmRpcEndpoint.RotateCredential,
+ credentials: { username: auth.username, password: auth.password },
+ params: {
+ kind: accountType === PamAccountType.WindowsAd ? "domain" : "local",
+ targetUsername,
+ newPassword
+ }
+ });
+ } catch (err) {
+ throw new Error(redactRotationError(err, [newPassword, auth.password]));
+ }
+ },
+
+ testCredential: async (input, deps) => {
+ const { accountType, connectionDetails, auth, gatewayId, gatewayPoolId } = input;
+ try {
+ const resolvedGatewayId = await resolveRotationGatewayId(deps, gatewayId, gatewayPoolId);
+
+ 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
+ );
+ }
+
+ // Local account: prove the credential over WinRM against its own host.
+ await winrmRpcWithGateway<{ ok: boolean }>({
+ targetHost: winrmRotationTargetHost(accountType, connectionDetails),
+ targetPort: WINRM_ROTATION_PORT,
+ gatewayId: resolvedGatewayId,
+ gatewayV2Service: deps.gatewayV2Service,
+ endpoint: WinRmRpcEndpoint.Test,
+ credentials: { username: auth.username, password: auth.password }
+ });
+ return true;
+ } catch {
+ return false;
+ }
+ }
+};
+
+// Full Record over the rotatable types so a missing handler entry is a compile error.
export const PAM_ROTATION_FACTORY_MAP: Record<TRotatableType, TPamRotationHandler> = {
[PamAccountType.Postgres]: sqlRotationHandler,
[PamAccountType.MySQL]: sqlRotationHandler,
- [PamAccountType.MsSQL]: sqlRotationHandler
+ [PamAccountType.MsSQL]: sqlRotationHandler,
+ [PamAccountType.Windows]: windowsRotationHandler,
+ [PamAccountType.WindowsAd]: windowsRotationHandler
};
diff --git a/backend/src/ee/services/pam-account-rotation/shared/pam-rotation-sql-connection.ts b/backend/src/ee/services/pam-account-rotation/shared/pam-rotation-sql-connection.ts
index 963e27c04e..57be0e3d0b 100644
--- a/backend/src/ee/services/pam-account-rotation/shared/pam-rotation-sql-connection.ts
+++ b/backend/src/ee/services/pam-account-rotation/shared/pam-rotation-sql-connection.ts
@@ -6,7 +6,7 @@ import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2
import { executeWithPotentialGateway } from "@app/services/app-connection/shared/sql";
import { TSqlConnectionConfig } from "@app/services/app-connection/shared/sql/sql-connection-types";
-import { PAM_ROTATION_APP_MAP, ROTATABLE_ACCOUNT_TYPES } from "../pam-rotation-fns";
+import { PAM_ROTATION_APP_MAP, TSqlRotatableType } from "../pam-rotation-fns";
// Must stay well under the per-account rotation lock TTL so a hung query can't let the lock expire mid-rotation.
export const SQL_QUERY_TIMEOUT = 30 * 1000;
@@ -29,7 +29,7 @@ export type TPamRotationGatewayDeps = {
// Delegates to executeWithPotentialGateway so rotation reuses the one gateway/SSRF path every other SQL path uses.
export const withPamSqlClient = async <T>(
input: {
- accountType: (typeof ROTATABLE_ACCOUNT_TYPES)[number];
+ accountType: TSqlRotatableType;
connectionDetails: TPamSqlConnectionDetails;
auth: { username: string; password: string };
gatewayId?: string | null;
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.ts
new file mode 100644
index 0000000000..df8f50f936
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, test } from "vitest";
+
+import { extractSamAccountName, resolveRunAsFingerprint } from "./active-directory-discovery-factory";
+
+describe("extractSamAccountName", () => {
+ test.each([
+ ["CORP\\svc-sql", "svc-sql"],
+ ["[email protected]", "svc-sql"],
+ ["svc-sql", "svc-sql"],
+ [" CORP\\svc-sql ", "svc-sql"]
+ ])("extracts the account name from %s", (input, expected) => {
+ expect(extractSamAccountName(input)).toBe(expected);
+ });
+
+ test.each([["NT AUTHORITY\\SYSTEM"], ["NT SERVICE\\MSSQL$SQLEXPRESS"], ["BUILTIN\\Administrators"], [""], [" "]])(
+ "returns null for built-in / empty run-as %s",
+ (input) => {
+ expect(extractSamAccountName(input)).toBeNull();
+ }
+ );
+});
+
+describe("resolveRunAsFingerprint", () => {
+ const domain = "corp.example.com";
+ const userGuidByName = new Map([
+ ["svc-sql", "11111111-1111-1111-1111-111111111111"],
+ ["svc-backup", "22222222-2222-2222-2222-222222222222"]
+ ]);
+
+ test("anchors a domain run-as to its objectGUID fingerprint", () => {
+ expect(resolveRunAsFingerprint("CORP\\svc-sql", domain, userGuidByName)).toBe(
+ "corp.example.com:11111111-1111-1111-1111-111111111111"
+ );
+ });
+
+ test("resolves a UPN-style run-as", () => {
+ expect(resolveRunAsFingerprint("[email protected]", domain, userGuidByName)).toBe(
+ "corp.example.com:22222222-2222-2222-2222-222222222222"
+ );
+ });
+
+ test("matches the discovered-account fingerprint format (domain:objectGUID)", () => {
+ const fingerprint = resolveRunAsFingerprint("CORP\\svc-sql", domain, userGuidByName);
+ expect(fingerprint).toBe(`${domain}:${userGuidByName.get("svc-sql")}`);
+ });
+
+ test.each([
+ ["LocalSystem"],
+ ["NT AUTHORITY\\NetworkService"],
+ ["ApplicationPoolIdentity"],
+ ["CORP\\unknown-account"] // real user but not enumerated from LDAP
+ ])("returns null for built-in or unresolvable run-as %s", (runAs) => {
+ expect(resolveRunAsFingerprint(runAs, domain, userGuidByName)).toBeNull();
+ });
+
+ test("is case-insensitive on the account name", () => {
+ expect(resolveRunAsFingerprint("CORP\\SVC-SQL", domain, userGuidByName)).toBe(
+ "corp.example.com:11111111-1111-1111-1111-111111111111"
+ );
+ });
+
+ test.each([
+ ["WEB01\\svc-sql"], // same name, different (machine-local) domain
+ ["OTHERDOM\\svc-sql"], // same name, a trusted domain
+ [".\\svc-sql"] // explicit local account
+ ])("does not anchor a same-named account from another domain (%s)", (runAs) => {
+ expect(resolveRunAsFingerprint(runAs, domain, userGuidByName)).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.ts
index 4ca6cf2e3b..4c74be4f7c 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
@@ -3,17 +3,18 @@ import net from "node:net";
import ldapjs from "@infisical/ldapjs";
import slugify from "@sindresorhus/slugify";
import RE2 from "re2";
-import { runPowershell } from "winrm-client";
import { BadRequestError } from "@app/lib/errors";
+import { WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-rpc";
import { logger } from "@app/lib/logger";
import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";
import { PamAccountType } from "../../pam/pam-enums";
import { isDomainQualifiedUsername, toNetbiosUsername } from "../../pam-account/pam-account-schemas";
-import { executeWithGateway } from "../pam-discovery-fns";
+import { executeWithGateway, winrmRpcWithGateway } from "../pam-discovery-fns";
import {
TDiscoveredAccount,
+ TDiscoveredDependency,
TDiscoveryMachineError,
TDiscoveryScanResult,
TPamDiscoveryFactory
@@ -165,7 +166,16 @@ const resolveHostnamesViaDc = (
}
});
-const enumerateLocalUsers = (
+const buildWinrmCredentials = (conn: TAdConnection, password: string, winrm: TWinrmConfig) => ({
+ username: toNetbiosUsername(conn.username, conn.domain),
+ password,
+ useHttps: winrm.useHttps,
+ // WinRM `insecure` skips cert verification (HTTPS only); it maps from the source's reject-unauthorized flag.
+ insecure: winrm.useHttps && !winrm.rejectUnauthorized,
+ caCertificate: winrm.caCert
+});
+
+const enumerateLocalUsers = async (
computer: TLdapComputer,
conn: TAdConnection,
password: string,
@@ -173,30 +183,88 @@ const enumerateLocalUsers = (
gatewayId: string,
gatewayV2Service: TGatewayDep
): Promise<TWinRmLocalUser[]> => {
- const hostname = computer.dNSHostName || computer.cn;
- const targetAddress = computer.resolvedIp || hostname;
-
- return executeWithGateway(targetAddress, winrm.port, gatewayId, gatewayV2Service, async (proxyPort) => {
- const winrmUsername = toNetbiosUsername(conn.username, conn.domain);
- const script =
- "Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet, Description, SID | ConvertTo-Json";
-
- const stdout = await runPowershell(
- script,
- "localhost",
- winrmUsername,
- password,
- proxyPort,
- winrm.useHttps,
- winrm.rejectUnauthorized,
- winrm.caCert,
- hostname
- );
+ const targetAddress = computer.resolvedIp || computer.dNSHostName || computer.cn;
+ const { accounts } = await winrmRpcWithGateway<{ accounts: TWinRmLocalUser[] }>({
+ targetHost: targetAddress,
+ targetPort: winrm.port,
+ gatewayId,
+ gatewayV2Service,
+ endpoint: WinRmRpcEndpoint.EnumerateAccounts,
+ credentials: buildWinrmCredentials(conn, password, winrm)
+ });
+ return (accounts ?? []).filter((u) => u.Name);
+};
+
+type TWinRmDependency = { type: string; runAs: string; name: string; data: Record<string, unknown> };
+
+// Run-as values that are built-in service identities: they have no password, so nothing to rotate.
+const BUILTIN_RUNAS = new Set(["localsystem", "system", "localservice", "networkservice", "applicationpoolidentity"]);
+
+// Split a run-as into its domain qualifier (null when unqualified) and account name; null for built-ins/empty.
+export const parseRunAs = (runAs: string): { domain: string | null; account: string } | null => {
+ const value = runAs.trim();
+ if (!value) return null;
+ if (value.includes("\\")) {
+ const [domainPart, user] = value.split("\\");
+ const dp = domainPart.toLowerCase();
+ if (dp === "nt authority" || dp === "nt service" || dp === "builtin") return null;
+ if (!user) return null;
+ return { domain: domainPart, account: user };
+ }
+ if (value.includes("@")) {
+ const [user, suffix] = value.split("@");
+ return { domain: suffix, account: user };
+ }
+ return { domain: null, account: value };
+};
+
+// Retained for the account-name extraction; the fingerprint resolver below adds the domain check.
+export const extractSamAccountName = (runAs: string): string | null => parseRunAs(runAs)?.account ?? null;
+
+// Anchor a dependency's run-as to a domain account's stable identity (domain:objectGUID), matching the
+// fingerprint minted for discovered domain accounts. Returns null for built-ins and any run-as that doesn't
+// resolve to an enumerated domain user (local/unknown accounts are not tracked as dependencies). A qualified
+// run-as must name the scanned domain, so a same-named local or trusted-domain account (e.g. WEB01\svc-sql)
+// is never mis-anchored to the domain account.
+export const resolveRunAsFingerprint = (
+ runAs: string,
+ domain: string,
+ userGuidByName: Map<string, string>
+): string | null => {
+ const parsed = parseRunAs(runAs);
+ if (!parsed) return null;
+ const account = parsed.account.toLowerCase();
+ if (BUILTIN_RUNAS.has(account)) return null;
+
+ if (parsed.domain !== null) {
+ const runAsDomain = parsed.domain.toLowerCase();
+ const netbios = domain.split(".")[0]; // corp.example.com -> corp
+ if (runAsDomain !== netbios && runAsDomain !== domain) return null;
+ }
+
+ const guid = userGuidByName.get(account);
+ if (!guid) return null;
+ return `${domain}:${guid}`;
+};
- if (!stdout.trim()) return [];
- const parsed = JSON.parse(stdout) as TWinRmLocalUser | TWinRmLocalUser[];
- return Array.isArray(parsed) ? parsed : [parsed];
+const enumerateDependencies = async (
+ computer: TLdapComputer,
+ conn: TAdConnection,
+ password: string,
+ winrm: TWinrmConfig,
+ gatewayId: string,
+ gatewayV2Service: TGatewayDep
+): Promise<TWinRmDependency[]> => {
+ const targetAddress = computer.resolvedIp || computer.dNSHostName || computer.cn;
+ const { dependencies } = await winrmRpcWithGateway<{ dependencies: TWinRmDependency[] }>({
+ targetHost: targetAddress,
+ targetPort: winrm.port,
+ gatewayId,
+ gatewayV2Service,
+ endpoint: WinRmRpcEndpoint.EnumerateDependencies,
+ credentials: buildWinrmCredentials(conn, password, winrm)
});
+ return dependencies ?? [];
};
export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
@@ -220,6 +288,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
const conn: TAdConnection = { ...connectionDetails, username: credentials.username };
const config = configuration as {
scanLocalAccounts?: boolean;
+ discoverDependencies?: boolean;
winrmPort?: number;
useWinrmHttps?: boolean;
winrmRejectUnauthorized?: boolean;
@@ -238,6 +307,10 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
const domain = connectionDetails.domain.toLowerCase();
const baseDN = buildDomainDN(connectionDetails.domain);
const machineErrors: TDiscoveryMachineError[] = [];
+ const dependencies: TDiscoveredDependency[] = [];
+ const scannedDependencyMachines: string[] = [];
+ // Both local-account and dependency sweeps need the machine list from LDAP.
+ const enumerateComputers = Boolean(config.scanLocalAccounts || config.discoverDependencies);
const { users, computers } = await runLdap<{ users: TLdapUser[]; computers: TLdapComputer[] }>(
conn,
@@ -256,7 +329,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
}))
.filter((u) => u.sAMAccountName && u.objectGUID);
- if (!config.scanLocalAccounts) return { users: parsedUsers, computers: [] as TLdapComputer[] };
+ if (!enumerateComputers) return { users: parsedUsers, computers: [] as TLdapComputer[] };
const computerEntries = await ldapSearch(
client,
@@ -291,7 +364,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
details: { connectionDetails, credentials: { username: u.sAMAccountName } }
}));
- if (config.scanLocalAccounts && computers.length > 0) {
+ if (enumerateComputers && computers.length > 0) {
await resolveHostnamesViaDc(computers, conn, gatewayId, gatewayV2Service);
const winrm: TWinrmConfig = {
@@ -300,44 +373,79 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
rejectUnauthorized: config.winrmRejectUnauthorized ?? true,
caCert: config.winrmCaCert
};
+ const password = credentials.password ?? "";
+ // Resolve a dependency's run-as (DOMAIN\user / user@domain / user) to its domain account's objectGUID.
+ const userGuidByName = new Map(users.map((u) => [u.sAMAccountName.toLowerCase(), u.objectGUID]));
for (const computer of computers) {
if (signal.aborted) break;
const host = computer.resolvedIp || computer.dNSHostName || computer.cn;
const hostLabel = computer.cn || computer.dNSHostName || host;
- try {
- // eslint-disable-next-line no-await-in-loop
- const localUsers = await enumerateLocalUsers(
- computer,
- conn,
- credentials.password ?? "",
- winrm,
- gatewayId,
- gatewayV2Service
- );
-
- for (const u of localUsers.filter((lu) => lu.Name)) {
- discovered.push({
- accountType: PamAccountType.Windows,
- name: slugify(`${hostLabel} ${u.Name}`, { lowercase: true })
- .slice(0, 64)
- .replace(TRAILING_HYPHENS_REGEX, ""),
- fingerprint: `${domain}:${computer.objectGUID}:${u.Name.toLowerCase()}`,
- details: {
- connectionDetails: { host, port: connectionDetails.rdpPort },
- credentials: { username: u.Name }
+ const machineName = computer.dNSHostName || computer.cn;
+
+ if (config.scanLocalAccounts) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const localUsers = await enumerateLocalUsers(computer, conn, password, winrm, gatewayId, gatewayV2Service);
+
+ for (const u of localUsers.filter((lu) => lu.Name)) {
+ discovered.push({
+ accountType: PamAccountType.Windows,
+ name: slugify(`${hostLabel} ${u.Name}`, { lowercase: true })
+ .slice(0, 64)
+ .replace(TRAILING_HYPHENS_REGEX, ""),
+ fingerprint: `${domain}:${computer.objectGUID}:${u.Name.toLowerCase()}`,
+ details: {
+ connectionDetails: { host, port: connectionDetails.rdpPort },
+ credentials: { username: u.Name }
+ }
+ });
+ }
+ } catch (err) {
+ const message = err instanceof Error ? err.message : "WinRM enumeration failed";
+ logger.warn(err, `PAM AD discovery failed to enumerate local accounts [host=${host}]`);
+ machineErrors.push({ machine: host, error: message });
+ }
+ }
+
+ if (config.discoverDependencies) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const machineDeps = await enumerateDependencies(
+ computer,
+ conn,
+ password,
+ winrm,
+ gatewayId,
+ gatewayV2Service
+ );
+
+ for (const dep of machineDeps) {
+ // built-in or non-domain run-as resolves to null: nothing to anchor to an account or rotate
+ const fingerprint = resolveRunAsFingerprint(dep.runAs, domain, userGuidByName);
+ if (fingerprint) {
+ dependencies.push({
+ fingerprint,
+ type: dep.type,
+ name: dep.name,
+ // machine stays the hostname (stable reconciliation identity); the resolved IP is carried in
+ // data so rotation sync can connect even where the gateway can't resolve AD hostnames.
+ machine: machineName,
+ data: computer.resolvedIp ? { ...dep.data, resolvedIp: computer.resolvedIp } : dep.data
+ });
}
- });
+ }
+ scannedDependencyMachines.push(machineName);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : "WinRM dependency enumeration failed";
+ logger.warn(err, `PAM AD discovery failed to enumerate dependencies [host=${host}]`);
+ machineErrors.push({ machine: host, error: message });
}
- } catch (err) {
- const message = err instanceof Error ? err.message : "WinRM enumeration failed";
- logger.warn(err, `PAM AD discovery failed to enumerate local accounts [host=${host}]`);
- machineErrors.push({ machine: host, error: message });
}
}
}
- return { accounts: discovered, machineErrors };
+ return { accounts: discovered, machineErrors, dependencies, scannedDependencyMachines };
};
return { validateConnection, scan };
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.ts
index bdae950eb3..c07e0dc08e 100644
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.ts
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.ts
@@ -2,6 +2,7 @@ import { z } from "zod";
export const ActiveDirectoryDiscoveryConfigSchema = z.object({
scanLocalAccounts: z.boolean().default(true),
+ discoverDependencies: z.boolean().default(false),
winrmPort: z.coerce.number().int().min(1).max(65535).default(5985),
useWinrmHttps: z.boolean().default(false),
winrmRejectUnauthorized: z.boolean().default(true),
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.ts
new file mode 100644
index 0000000000..41b37defcc
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts
@@ -0,0 +1,93 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TPamAccountDependencyDALFactory = ReturnType<typeof pamAccountDependencyDALFactory>;
+
+type TUpsertDependency = {
+ fingerprint: string;
+ machine: string;
+ type: string;
+ name: string;
+ data: unknown;
+ accountId: string | null;
+ discoveredAccountId: string | null;
+};
+
+export const pamAccountDependencyDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamAccountDependency);
+
+ // Upsert a discovered dependency keyed by its stable identity, returning the row id. Atomic (single
+ // INSERT ... ON CONFLICT) so overlapping scans of the same machine can't race on the unique index. Discovery
+ // owns fingerprint / machine / type / name / data and the account linkage; on conflict only those are merged,
+ // so rotation-owned columns (rotationStatus, lastRotatedAt, encryptedLastRotationMessage) are never touched.
+ const upsertByIdentity = async (dep: TUpsertDependency, tx?: Knex): Promise<string> => {
+ const { fingerprint, machine, type, name, data, accountId, discoveredAccountId } = dep;
+ const [row] = await (tx || db)(TableName.PamAccountDependency)
+ .insert({ fingerprint, machine, type, name, data, accountId, discoveredAccountId })
+ .onConflict(["fingerprint", "machine", "type", "name"])
+ .merge({ data, accountId, discoveredAccountId })
+ .returning("id");
+ return row.id;
+ };
+
+ // Prune dependencies the current scan no longer found. Scoped to this source's accounts (staged or their
+ // imported counterparts) and to the machines the scan actually re-checked, so an unreachable machine or a
+ // narrower source never drops another scan's dependencies.
+ const deleteStaleForSource = async (
+ {
+ accountIds,
+ discoveredAccountIds,
+ scannedMachines,
+ keepIds
+ }: { accountIds: string[]; discoveredAccountIds: string[]; scannedMachines: string[]; keepIds: string[] },
+ tx?: Knex
+ ): Promise<void> => {
+ if (!scannedMachines.length || (!accountIds.length && !discoveredAccountIds.length)) return;
+
+ await (tx || db)(TableName.PamAccountDependency)
+ .whereIn("machine", scannedMachines)
+ .where((qb) => {
+ if (accountIds.length) void qb.whereIn("accountId", accountIds);
+ if (discoveredAccountIds.length) void qb.orWhereIn("discoveredAccountId", discoveredAccountIds);
+ })
+ .whereNotIn("id", keepIds)
+ .delete();
+ };
+
+ // On import, flip a staged dependency onto its managed account: set accountId, clear discoveredAccountId.
+ const backfillImported = async (discoveredAccountId: string, accountId: string, tx?: Knex): Promise<void> => {
+ await (tx || db)(TableName.PamAccountDependency)
+ .where({ discoveredAccountId })
+ .update({ accountId, discoveredAccountId: null });
+ };
+
+ const findByAccountId = async (accountId: string, tx?: Knex) =>
+ (tx || db.replicaNode())(TableName.PamAccountDependency)
+ .where({ accountId })
+ .orderBy([
+ { column: "machine", order: "asc" },
+ { column: "name", order: "asc" }
+ ]);
+
+ const findByDiscoveredAccountIds = async (discoveredAccountIds: string[], tx?: Knex) => {
+ if (!discoveredAccountIds.length) return [];
+ return (tx || db.replicaNode())(TableName.PamAccountDependency)
+ .whereIn("discoveredAccountId", discoveredAccountIds)
+ .orderBy([
+ { column: "machine", order: "asc" },
+ { column: "name", order: "asc" }
+ ]);
+ };
+
+ return {
+ ...orm,
+ upsertByIdentity,
+ backfillImported,
+ deleteStaleForSource,
+ findByAccountId,
+ findByDiscoveredAccountIds
+ };
+};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
index ed922220aa..99e6ea164b 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
@@ -1,7 +1,10 @@
+import ldapjs from "@infisical/ldapjs";
+
import { BadRequestError } from "@app/lib/errors";
import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { callPortSweep, callSshExec, SshExecCredentials } from "@app/lib/gateway-v2/ssh-rpc";
+import { callWinRmEndpoint, WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-rpc";
import { verifyHostInputValidity } from "../dynamic-secret/dynamic-secret-fns";
import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
@@ -69,6 +72,138 @@ export const executeWithGateway = async <T>(
});
};
+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.
+export const ldapBindCheckViaGateway = async (
+ {
+ dcAddress,
+ port,
+ useLdaps,
+ rejectUnauthorized,
+ caCert,
+ tlsServerName,
+ bindDn,
+ password
+ }: {
+ dcAddress: string;
+ port: number;
+ useLdaps: boolean;
+ rejectUnauthorized: boolean;
+ caCert?: string;
+ tlsServerName?: string;
+ bindDn: string;
+ password: string;
+ },
+ gatewayId: string,
+ gatewayV2Service: TGatewayDep
+): Promise<boolean> =>
+ executeWithGateway(
+ dcAddress,
+ port,
+ gatewayId,
+ gatewayV2Service,
+ (proxyPort) =>
+ new Promise<boolean>((resolve) => {
+ const client = ldapjs.createClient({
+ url: `${useLdaps ? "ldaps" : "ldap"}://localhost:${proxyPort}`,
+ connectTimeout: LDAP_BIND_CHECK_TIMEOUT_MS,
+ timeout: LDAP_BIND_CHECK_TIMEOUT_MS,
+ ...(useLdaps && {
+ tlsOptions: {
+ rejectUnauthorized,
+ servername: tlsServerName || dcAddress,
+ ...(caCert && { ca: [caCert] })
+ }
+ })
+ });
+
+ let settled = false;
+ const done = (ok: boolean) => {
+ if (settled) return;
+ settled = true;
+ try {
+ client.unbind();
+ } catch {
+ // client may already be destroyed
+ }
+ resolve(ok);
+ };
+
+ // 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));
+ })
+ );
+
+export type TWinRmGatewayCredentials = {
+ username: string;
+ password: string;
+ useHttps?: boolean;
+ insecure?: boolean;
+ caCertificate?: string;
+};
+
+// runs one WinRM operation on the gateway inside the customer network. Node can't perform WinRM message
+// sealing, so the gateway (Go/masterzen) owns the WinRM client; the backend only names a vetted operation
+// and its params. Targets internal hosts by design, so it uses the gateway host validator (not the SSRF block).
+export const winrmRpcWithGateway = async <T>({
+ targetHost,
+ targetPort,
+ gatewayId,
+ gatewayV2Service,
+ endpoint,
+ credentials,
+ params
+}: {
+ targetHost: string;
+ targetPort: number;
+ gatewayId: string;
+ gatewayV2Service: TGatewayDep;
+ endpoint: WinRmRpcEndpoint;
+ credentials: TWinRmGatewayCredentials;
+ params?: Record<string, unknown>;
+}): Promise<T> => {
+ const [host] = await verifyHostInputValidity({ host: targetHost, isGateway: true, isDynamicSecret: false });
+ const platform = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
+ gatewayId,
+ targetHost: host,
+ targetPort
+ });
+ if (!platform) throw new BadRequestError({ message: "Unable to connect to gateway" });
+
+ const response = await withGatewayV2Proxy(
+ (proxyPort) =>
+ callWinRmEndpoint<T>({
+ port: proxyPort,
+ endpoint,
+ body: {
+ username: credentials.username,
+ password: credentials.password,
+ params: {
+ useHttps: credentials.useHttps ?? false,
+ insecure: credentials.insecure ?? false,
+ ...(credentials.caCertificate ? { caCertificate: credentials.caCertificate } : {}),
+ ...params
+ }
+ }
+ }),
+ {
+ protocol: GatewayProxyProtocol.WinRm,
+ relayHost: platform.relayHost,
+ gateway: platform.gateway,
+ relay: platform.relay
+ }
+ );
+
+ if (!response.ok) {
+ throw new BadRequestError({ message: `WinRM gateway operation failed: ${response.errorMessage ?? ""}` });
+ }
+ return response.result;
+};
+
// one gateway round-trip that TCP-probes every target and returns the reachable "host:port" set,
// so a scan can filter a whole CIDR to live hosts
export const sweepReachableTargets = async (
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.ts
index bcd22e8d85..0e72eb13e1 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
@@ -24,6 +24,7 @@ import { checkAccountAccess, TActorContext, verifyProductMembership } from "../p
import { validateGatewayAttachment } from "../pam/pam-validators";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import { TPamAccountServiceFactory } from "../pam-account/pam-account-service";
+import { TPamAccountDependencyDALFactory } from "./pam-account-dependency-dal";
import { TPamDiscoveredAccountDALFactory } from "./pam-discovered-account-dal";
import {
PamDiscoveryImportStatus,
@@ -45,6 +46,7 @@ import {
TDeleteDiscoverySourceDTO,
TGetDiscoverySourceDTO,
TImportDiscoveredDTO,
+ TListAccountDependenciesDTO,
TListDiscoveredDTO,
TListDiscoverySourcesDTO,
TListRunsDTO,
@@ -56,6 +58,7 @@ type TPamDiscoverySourceServiceFactoryDep = {
pamDiscoverySourceDAL: TPamDiscoverySourceDALFactory;
pamDiscoverySourceRunDAL: TPamDiscoverySourceRunDALFactory;
pamDiscoveredAccountDAL: TPamDiscoveredAccountDALFactory;
+ pamAccountDependencyDAL: TPamAccountDependencyDALFactory;
pamAccountDAL: Pick<TPamAccountDALFactory, "findById" | "findByIdWithDetails">;
pamAccountService: Pick<TPamAccountServiceFactory, "create">;
permissionService: Pick<
@@ -108,6 +111,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
pamDiscoverySourceDAL,
pamDiscoverySourceRunDAL,
pamDiscoveredAccountDAL,
+ pamAccountDependencyDAL,
pamAccountDAL,
pamAccountService,
permissionService,
@@ -447,7 +451,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
});
const controller = new AbortController();
- const { accounts, machineErrors } = await withScanTimeout(
+ const { accounts, machineErrors, dependencies, scannedDependencyMachines } = await withScanTimeout(
provider.scan(controller.signal),
controller,
MAX_SCAN_DURATION_MS
@@ -465,6 +469,47 @@ 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.
+ if (scannedDependencyMachines.length) {
+ const sourceAccounts = await pamDiscoveredAccountDAL.find({ discoverySourceId: sourceId });
+ const accountByFingerprint = new Map(
+ sourceAccounts.map((a) => [
+ a.fingerprint,
+ { discoveredAccountId: a.id, importedAccountId: a.importedAccountId ?? null }
+ ])
+ );
+
+ const depLimit = pLimit(DISCOVERED_UPSERT_CONCURRENCY);
+ const keepIds = (
+ await Promise.all(
+ dependencies.map((dep) => {
+ const match = accountByFingerprint.get(dep.fingerprint);
+ if (!match) return Promise.resolve(null); // run-as isn't an account this source discovered
+ const accountId = match.importedAccountId;
+ return depLimit(() =>
+ pamAccountDependencyDAL.upsertByIdentity({
+ fingerprint: dep.fingerprint,
+ machine: dep.machine,
+ type: dep.type,
+ name: dep.name,
+ data: dep.data,
+ accountId,
+ discoveredAccountId: accountId ? null : match.discoveredAccountId
+ })
+ );
+ })
+ )
+ ).filter((id): id is string => Boolean(id));
+
+ 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
+ });
+ }
+
const newCount = results.filter((r) => r.isNew).length;
await pamDiscoverySourceRunDAL.updateById(run.id, {
status: PamDiscoveryRunStatus.Completed,
@@ -555,18 +600,67 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });
}
const { accounts, totalCount } = await pamDiscoveredAccountDAL.listStaged(sourceId, { search, offset, limit });
+
+ const dependencies = await pamAccountDependencyDAL.findByDiscoveredAccountIds(accounts.map((a) => a.id));
+ const dependenciesByAccount = new Map<string, { id: string; type: string; name: string; machine: string }[]>();
+ for (const dep of dependencies) {
+ if (dep.discoveredAccountId) {
+ const depList = dependenciesByAccount.get(dep.discoveredAccountId) ?? [];
+ depList.push({ id: dep.id, type: dep.type, name: dep.name, machine: dep.machine });
+ dependenciesByAccount.set(dep.discoveredAccountId, depList);
+ }
+ }
+
return {
- discoveredAccounts: accounts.map((a) => ({
- id: a.id,
- accountType: a.accountType as PamAccountType,
- name: a.name,
- fingerprint: a.fingerprint,
- createdAt: a.createdAt
- })),
+ discoveredAccounts: accounts.map((a) => {
+ const accountDependencies = dependenciesByAccount.get(a.id) ?? [];
+ return {
+ id: a.id,
+ accountType: a.accountType as PamAccountType,
+ name: a.name,
+ fingerprint: a.fingerprint,
+ createdAt: a.createdAt,
+ dependencyCount: accountDependencies.length,
+ dependencies: accountDependencies
+ };
+ }),
totalCount
};
};
+ const listAccountDependencies = async ({ accountId, projectId, ...ctx }: TListAccountDependenciesDTO) => {
+ const account = await pamAccountDAL.findByIdWithDetails(accountId);
+ if (!account || account.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
+ }
+ await checkAccountAccess(
+ permissionService,
+ accountId,
+ account.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.ReadAccounts,
+ ctx
+ );
+
+ const dependencies = await pamAccountDependencyDAL.findByAccountId(accountId);
+ const needsDecrypt = dependencies.some((d) => d.rotationStatus === "failed" && d.encryptedLastRotationMessage);
+ const decryptor = needsDecrypt ? (await getProjectCipher(projectId)).decryptor : null;
+
+ return dependencies.map((d) => ({
+ id: d.id,
+ type: d.type,
+ name: d.name,
+ machine: d.machine,
+ data: d.data,
+ rotationStatus: d.rotationStatus ?? null,
+ lastRotatedAt: d.lastRotatedAt ?? null,
+ lastRotationMessage:
+ d.rotationStatus === "failed" && d.encryptedLastRotationMessage && decryptor
+ ? decryptor({ cipherTextBlob: d.encryptedLastRotationMessage }).toString("utf-8")
+ : null
+ }));
+ };
+
const importAccounts = async ({ projectId, sourceId, folderId, accounts, ...ctx }: TImportDiscoveredDTO) => {
await verifyAdmin(projectId, ctx);
const source = await pamDiscoverySourceDAL.findById(sourceId);
@@ -602,6 +696,9 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
});
await pamDiscoveredAccountDAL.updateById(discovered.id, { importedAccountId: account.id });
+ // Flip this account's staged dependencies onto the managed account so they're rotation-eligible
+ // immediately, without waiting for the next scan.
+ await pamAccountDependencyDAL.backfillImported(discovered.id, account.id);
return {
discoveredAccountId: item.discoveredAccountId,
status: PamDiscoveryImportStatus.Imported,
@@ -658,6 +755,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
runScan,
listRuns,
listDiscovered,
- importAccounts
+ importAccounts,
+ listAccountDependencies
};
};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
index 1bddd6c515..9e69e0683f 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
@@ -13,9 +13,20 @@ export type TDiscoveredAccount = {
export type TDiscoveryMachineError = { machine: string; error: string };
+export type TDiscoveredDependency = {
+ fingerprint: string; // run-as stable identity (domain:objectGUID / SID); anchors the dependency to an account
+ type: string; // windows-service / scheduled-task / iis-app-pool
+ name: string;
+ machine: string;
+ data: Record<string, unknown>; // type-specific detail (run-as, path, triggers, etc.)
+};
+
export type TDiscoveryScanResult = {
accounts: TDiscoveredAccount[];
machineErrors: TDiscoveryMachineError[];
+ dependencies: TDiscoveredDependency[];
+ // Machines whose dependency sweep completed, so reconciliation only prunes what it actually re-checked.
+ scannedDependencyMachines: string[];
};
export type TPamDiscoveryProvider = {
@@ -93,3 +104,8 @@ export type TImportDiscoveredDTO = {
folderId: string;
accounts: { discoveredAccountId: string; templateId: string; name?: string }[];
} & TActorContext;
+
+export type TListAccountDependenciesDTO = {
+ projectId: string;
+ accountId: string;
+} & TActorContext;
diff --git a/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts b/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts
index c460841405..f8807accd9 100644
--- a/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts
+++ b/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts
@@ -187,7 +187,9 @@ export const unixDiscoveryFactory: TPamDiscoveryFactory = ({
return {
accounts: discovered.slice(0, MAX_ACCOUNTS_PER_SCAN),
- machineErrors: results.flatMap((r) => (r.error ? [r.error] : []))
+ machineErrors: results.flatMap((r) => (r.error ? [r.error] : [])),
+ dependencies: [],
+ scannedDependencyMachines: []
};
};
diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.md
index b4e42a308d..8a6621ee78 100644
--- a/backend/src/ee/services/pam/CLAUDE.md
+++ b/backend/src/ee/services/pam/CLAUDE.md
@@ -109,8 +109,10 @@ Old tables/columns/code kept temporarily for rollback safety; target removal ~20
migration. Tracked items:
- **Legacy tables**: `pam_resources`, `pam_domains`, `pam_account_policies`,
- `pam_resource_rotation_rules`, `pam_account_dependencies`, `pam_resource_favorites`,
+ `pam_resource_rotation_rules`, `pam_resource_favorites`,
`pam_project_recording_configs`, `pam_session_event_batches`.
+ (`pam_account_dependencies` was **repurposed**, not dropped: it now backs dependency detection,
+ keyed off `pam_accounts` / `pam_discovered_accounts` instead of the legacy `pam_resources`.)
- **`pam_accounts` columns**: `resourceId`, `domainId`, `policyId`, `requireMfa`, `internalMetadata`,
`discoveryFingerprint`. (`lastRotatedAt`, `rotationStatus`, `encryptedLastRotationMessage` are **kept** —
credential rotation reuses them.)
diff --git a/backend/src/lib/gateway-v2/winrm-rpc.ts b/backend/src/lib/gateway-v2/winrm-rpc.ts
index f1d73df130..29fabc3030 100644
--- a/backend/src/lib/gateway-v2/winrm-rpc.ts
+++ b/backend/src/lib/gateway-v2/winrm-rpc.ts
@@ -5,7 +5,11 @@ import { logger } from "@app/lib/logger";
export enum WinRmRpcEndpoint {
Test = "/v1/test-connection",
DeliverFiles = "/v1/deliver-files",
- RemoveFiles = "/v1/remove-files"
+ RemoveFiles = "/v1/remove-files",
+ EnumerateAccounts = "/v1/enumerate-accounts",
+ EnumerateDependencies = "/v1/enumerate-dependencies",
+ RotateCredential = "/v1/rotate-credential",
+ SyncDependency = "/v1/sync-dependency"
}
export type WinRmTransportParams = {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 0b55476103..7709d76b8e 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -115,6 +115,7 @@ import { pamAccountRotationQueueServiceFactory } from "@app/ee/services/pam-acco
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";
import { pamAccountTemplateServiceFactory } from "@app/ee/services/pam-account-template/pam-account-template-service";
+import { pamAccountDependencyDALFactory } from "@app/ee/services/pam-discovery/pam-account-dependency-dal";
import { pamDiscoveredAccountDALFactory } from "@app/ee/services/pam-discovery/pam-discovered-account-dal";
import { pamDiscoverySourceDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dal";
import { pamDiscoverySourceRunDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-run-dal";
@@ -1919,11 +1920,13 @@ export const registerRoutes = async (
const pamDiscoverySourceDAL = pamDiscoverySourceDALFactory(db);
const pamDiscoverySourceRunDAL = pamDiscoverySourceRunDALFactory(db);
const pamDiscoveredAccountDAL = pamDiscoveredAccountDALFactory(db);
+ const pamAccountDependencyDAL = pamAccountDependencyDALFactory(db);
const pamDiscoveryService = pamDiscoverySourceServiceFactory({
pamDiscoverySourceDAL,
pamDiscoverySourceRunDAL,
pamDiscoveredAccountDAL,
+ pamAccountDependencyDAL,
pamAccountDAL,
pamAccountService,
permissionService,
@@ -1945,7 +1948,8 @@ export const registerRoutes = async (
keyStore,
gatewayService,
gatewayV2Service,
- gatewayPoolService
+ gatewayPoolService,
+ pamAccountDependencyDAL
});
const pamSessionService = pamSessionServiceFactory({
diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.ts
index 26875f369a..ac66639554 100644
--- a/frontend/src/hooks/api/pam/enums.ts
+++ b/frontend/src/hooks/api/pam/enums.ts
@@ -28,12 +28,18 @@ export enum PamDiscoverySchedule {
export const ROTATABLE_PAM_ACCOUNT_TYPES = [
PamAccountType.Postgres,
PamAccountType.MySQL,
- PamAccountType.MsSQL
+ PamAccountType.MsSQL,
+ PamAccountType.Windows,
+ PamAccountType.WindowsAd
];
export const isRotatablePamAccountType = (type: PamAccountType | string) =>
(ROTATABLE_PAM_ACCOUNT_TYPES as string[]).includes(type);
+// Domain (Active Directory) accounts are the ones whose run-as dependencies discovery detects.
+export const supportsPamDependencies = (type: PamAccountType | string) =>
+ type === PamAccountType.WindowsAd;
+
export const PAM_ROTATION_INTERVAL_OPTIONS: { seconds: number; label: string }[] = [
{ seconds: 3600, label: "1 hour" },
{ seconds: 43200, label: "12 hours" },
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index 0457f28a29..90023c1916 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -27,6 +27,7 @@ import {
TListPamAccountTemplatesDTO,
TPamAccessRequest,
TPamAccount,
+ TPamAccountDependency,
TPamAccountRotation,
TPamAccountTemplateDetail,
TPamAccountTemplateWithCount,
@@ -97,6 +98,8 @@ export const pamKeys = {
params?: { search?: string; offset?: number; limit?: number }
) => [...pamKeys.discovery(), "discovered", sourceId, params] as const,
accountRotation: (accountId: string) => [...pamKeys.account(), "rotation", accountId] as const,
+ accountDependencies: (accountId: string) =>
+ [...pamKeys.account(), "dependencies", accountId] as const,
rotationCandidates: (accountId: string) =>
[...pamKeys.account(), "rotation-candidates", accountId] as const,
accessRequest: () => [...pamKeys.all, "access-request"] as const,
@@ -582,6 +585,19 @@ export const useListPamDiscoveredAccounts = (
});
};
+export const useListPamAccountDependencies = (accountId: string) => {
+ return useQuery({
+ queryKey: pamKeys.accountDependencies(accountId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ dependencies: TPamAccountDependency[] }>(
+ `/api/v1/pam/accounts/${accountId}/dependencies`
+ );
+ return data.dependencies;
+ },
+ enabled: Boolean(accountId)
+ });
+};
+
// Access Requests / Approvals
export type TPamApprovalWorkflowStep = {
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index c81f9ea40b..65fdcd2479 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -54,12 +54,28 @@ export type TPamDiscoveryRun = {
createdAt: string;
};
+export type TPamDependency = {
+ id: string;
+ type: string;
+ name: string;
+ machine: string;
+};
+
export type TPamDiscoveredAccount = {
id: string;
accountType: PamAccountType;
name: string;
fingerprint: string;
createdAt: string;
+ dependencyCount: number;
+ dependencies: TPamDependency[];
+};
+
+export type TPamAccountDependency = TPamDependency & {
+ data: Record<string, unknown> | null;
+ rotationStatus: string | null;
+ lastRotatedAt: string | null;
+ lastRotationMessage: string | null;
};
export type TCreatePamDiscoverySourceDTO = {
diff --git a/frontend/src/hooks/usePamSheetState.ts b/frontend/src/hooks/usePamSheetState.ts
index 9562550ea5..f65c87ad8a 100644
--- a/frontend/src/hooks/usePamSheetState.ts
+++ b/frontend/src/hooks/usePamSheetState.ts
@@ -9,6 +9,7 @@ export enum PamSheetTab {
Runs = "runs",
General = "general",
Rotation = "rotation",
+ Dependencies = "dependencies",
Approvals = "approvals"
}
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
index d6376a3436..ea560a886c 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
@@ -54,6 +54,7 @@ import {
isRotatablePamAccountType,
PamAccountAccessibilityIssue,
PamAccountType,
+ supportsPamDependencies,
TPamMember,
useGetPamAccountById,
useGetPamAccountTemplate,
@@ -83,6 +84,7 @@ 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";
@@ -853,11 +855,17 @@ 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))
- );
+ 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 tabsWithIssues = new Set(
(account?.accessibilityIssues ?? []).map((issue) => ISSUE_TO_TAB[issue])
@@ -919,6 +927,7 @@ 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} />
) : null
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/DependenciesTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/DependenciesTab.tsx
new file mode 100644
index 0000000000..5387e84176
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/DependenciesTab.tsx
@@ -0,0 +1,124 @@
+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/PamDiscoveryPage/components/DiscoveryConfigFields.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx
index 11db07446f..da0881c28c 100644
--- a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx
@@ -24,6 +24,7 @@ import { PamAccountType, PamDiscoverySchedule, useListPamAccountsAdmin } from "@
export const discoveryConfigFormShape = {
scanLocalAccounts: z.boolean(),
+ discoverDependencies: z.boolean(),
winrmPort: z.coerce.number().int().min(1).max(65535),
useWinrmHttps: z.boolean(),
winrmRejectUnauthorized: z.boolean(),
@@ -34,6 +35,7 @@ export type TDiscoveryConfigFields = z.infer<z.ZodObject<typeof discoveryConfigF
export const DISCOVERY_CONFIG_DEFAULTS: TDiscoveryConfigFields = {
scanLocalAccounts: true,
+ discoverDependencies: false,
winrmPort: 5985,
useWinrmHttps: false,
winrmRejectUnauthorized: true,
@@ -44,6 +46,7 @@ export const discoveryConfigFromSource = (
config: Record<string, unknown>
): TDiscoveryConfigFields => ({
scanLocalAccounts: config.scanLocalAccounts !== false,
+ discoverDependencies: Boolean(config.discoverDependencies),
winrmPort:
typeof config.winrmPort === "number" ? config.winrmPort : DISCOVERY_CONFIG_DEFAULTS.winrmPort,
useWinrmHttps: Boolean(config.useWinrmHttps),
@@ -55,13 +58,18 @@ export const buildDiscoveryConfiguration = (
data: TDiscoveryConfigFields
): Record<string, unknown> => ({
scanLocalAccounts: data.scanLocalAccounts,
+ discoverDependencies: data.discoverDependencies,
winrmPort: data.winrmPort,
useWinrmHttps: data.useWinrmHttps,
winrmRejectUnauthorized: data.winrmRejectUnauthorized,
...(data.winrmCaCert.trim() ? { winrmCaCert: data.winrmCaCert.trim() } : {})
});
-type ToggleName = "scanLocalAccounts" | "useWinrmHttps" | "winrmRejectUnauthorized";
+type ToggleName =
+ | "scanLocalAccounts"
+ | "discoverDependencies"
+ | "useWinrmHttps"
+ | "winrmRejectUnauthorized";
const ToggleField = ({
control,
@@ -94,13 +102,19 @@ export const DiscoveryConfigFields = ({
control: Control<TDiscoveryConfigFields>;
}) => {
const scanLocalAccounts = useWatch({ control, name: "scanLocalAccounts" });
+ const discoverDependencies = useWatch({ control, name: "discoverDependencies" });
const useWinrmHttps = useWatch({ control, name: "useWinrmHttps" });
return (
<>
<ToggleField control={control} name="scanLocalAccounts" label="Discover local accounts" />
+ <ToggleField
+ control={control}
+ name="discoverDependencies"
+ label="Discover account dependencies"
+ />
- {scanLocalAccounts && (
+ {(scanLocalAccounts || discoverDependencies) && (
<>
<Controller
control={control}
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx
index 7fc1750435..5a267fb45e 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 { Play, Radar, Search, TriangleAlert } from "lucide-react";
+import { ChevronRight, Play, Radar, Search, TriangleAlert } from "lucide-react";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
@@ -90,6 +90,12 @@ 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>
);
@@ -338,6 +344,7 @@ 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("");
@@ -479,38 +486,94 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: P
</TableHead>
<TableHead>Name</TableHead>
<TableHead className="w-40">Type</TableHead>
+ <TableHead className="w-40">Dependencies</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{visibleStaged.map((account) => {
const typeDetails = accountTypeMap[account.accountType as PamAccountType];
+ const hasDeps = account.dependencyCount > 0;
+ const isExpanded = Boolean(expandedDeps[account.id]);
return (
- <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"
- />
+ <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>
)}
- <span className="text-sm">
- {typeDetails?.name ?? account.accountType}
- </span>
- </div>
- </TableCell>
- </TableRow>
+ </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>
);
})}
</TableBody>
diff --git a/frontend/src/pages/pam/components/pamResourceTabs.ts b/frontend/src/pages/pam/components/pamResourceTabs.ts
index 634fe4bfe1..cb5fef574b 100644
--- a/frontend/src/pages/pam/components/pamResourceTabs.ts
+++ b/frontend/src/pages/pam/components/pamResourceTabs.ts
@@ -6,7 +6,8 @@ import {
Settings,
Settings2,
ShieldCheck,
- Users
+ Users,
+ Workflow
} from "lucide-react";
import { PamResourcePermissionActions } from "@app/hooks/api/pam";
@@ -38,6 +39,12 @@ 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",