Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
finish dep sync implementation
x032205fab3be3e3d34
diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.tsindex 03cb6bef47..a232a91a0a 100644--- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts+++ b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts@@ -61,7 +61,8 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {response: {200: z.object({dependencies: PamAccountDependenciesSchema.extend({- resourceName: z.string().nullable().optional()+ resourceName: z.string().nullable().optional(),+ lastSyncMessage: z.string().nullable().optional()}).array()})}diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.tsindex 06fa17042b..9ff5a99727 100644--- a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts+++ b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts@@ -239,7 +239,8 @@ export const registerPamResourceRouter = async (server: FastifyZodProvider) => {response: {200: z.object({dependencies: PamAccountDependenciesSchema.extend({- accountName: z.string().nullable()+ accountName: z.string().nullable(),+ lastSyncMessage: z.string().nullable().optional()}).array()})}diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 4db13e91df..2399fcdf5e 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -1,7 +1,7 @@import { ForbiddenError, subject } from "@casl/ability";import picomatch from "picomatch";-import { ActionProjectType, OrganizationActionScope, TPamAccounts, TPamResources } from "@app/db/schemas";+import { ActionProjectType, OrganizationActionScope, TableName, TPamAccounts, TPamResources } from "@app/db/schemas";import {extractAwsAccountIdFromArn,generateConsoleFederationUrl,@@ -1110,10 +1110,16 @@ export const pamAccountServiceFactory = ({let logResourceType = "unknown";try {// Atomically claim rotation lock, only proceeds if not already rotating- const [claimed] = await pamAccountDAL.update(- { id: account.id, $notEqual: { rotationStatus: PamAccountRotationStatus.Rotating } },- { rotationStatus: PamAccountRotationStatus.Rotating }- );+ const claimed = await pamAccountDAL.transaction(async (tx) => {+ const updated = await tx(TableName.PamAccount)+ .where({ id: account.id })+ .where((qb) => {+ void qb.whereNull("rotationStatus").orWhereNot("rotationStatus", PamAccountRotationStatus.Rotating);+ })+ .update({ rotationStatus: PamAccountRotationStatus.Rotating })+ .returning("*");+ return updated[0];+ });if (!claimed) return;// Read resource@@ -1178,11 +1184,13 @@ export const pamAccountServiceFactory = ({// Run post-rotate hookif (factory.postRotate) {try {- await factory.postRotate(account.id, newCredentials, account.projectId, {- pamAccountDependenciesDAL,- pamResourceDAL,- kmsService- });+ await factory.postRotate(+ account.id,+ newCredentials,+ account.projectId,+ { pamAccountDependenciesDAL, pamResourceDAL, kmsService },+ rotationAccountCredentials+ );} catch (postRotateError) {logger.error(postRotateError, `Post-rotation hook failed for account [accountId=${account.id}]`);}diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.tsindex 3ce662b342..2f767f11a6 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@@ -1,6 +1,5 @@import net from "node:net";-import * as dnsPacket from "dns-packet";import { Knex } from "knex";import ldapjs from "ldapjs";import RE2 from "re2";@@ -27,6 +26,7 @@ import {import { TPamResourceDALFactory } from "../../pam-resource/pam-resource-dal";import { PamResource } from "../../pam-resource/pam-resource-enums";import { encryptResourceConnectionDetails, encryptResourceInternalMetadata } from "../../pam-resource/pam-resource-fns";+import { resolveDnsTcp } from "../../pam-resource/shared/dns-over-dc";import { WindowsAccountType, WindowsProtocol } from "../../pam-resource/windows-server/windows-server-resource-enums";import {TWindowsAccountCredentials,@@ -289,56 +289,6 @@ const executeWithGateway = async <T>();};-// Resolve a single hostname to an IP via DNS-over-TCP through the gateway proxy-const resolveDnsTcp = (hostname: string, port: number): Promise<string | null> => {- return new Promise((resolve) => {- const query = dnsPacket.streamEncode({- type: "query",- flags: dnsPacket.RECURSION_DESIRED,- questions: [{ type: "A", name: hostname }]- });-- const socket = net.connect({ host: "127.0.0.1", port }, () => {- socket.write(query);- });-- // Max legitimate DNS-over-TCP response: 2-byte length prefix + 65535 bytes payload- const MAX_DNS_TCP_SIZE = 2 + 65535;- let responseData = Buffer.alloc(0);-- socket.on("data", (chunk: Buffer) => {- responseData = Buffer.concat([responseData, chunk]);-- if (responseData.length > MAX_DNS_TCP_SIZE) {- socket.destroy();- resolve(null);- return;- }-- // DNS-over-TCP frames each message with a 2-byte big-endian length prefix- // wait until we have the full frame before decoding- if (responseData.length >= 2) {- const msgLen = responseData.readUInt16BE(0);- if (responseData.length >= 2 + msgLen) {- const response = dnsPacket.streamDecode(responseData);- const aRecord = response.answers?.find((a) => a.type === "A");- socket.destroy();- resolve(aRecord && "data" in aRecord ? (aRecord.data as string) : null);- }- }- });-- socket.on("error", () => {- resolve(null);- });-- socket.setTimeout(5000, () => {- socket.destroy();- resolve(null);- });- });-};-// Resolve AD hostnames to IP addresses by querying DNS over TCP through the DCconst resolveHostnamesViaDc = async (computers: TLdapComputer[],@@ -924,7 +874,8 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory<client.bind(bindDn, credentials.password, (err) => {if (err) {client.unbind();- reject(new Error("LDAP bind failed: invalid credentials"));+ logger.warn(err, "PAM AD discovery LDAP bind failed during connection validation");+ reject(new Error(`LDAP bind failed: ${err.message}`));} else {client.unbind();resolve();diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.tsindex 9ac5fbf099..df8b9566b6 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@@ -15,6 +15,7 @@ import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";import { OrgServiceActor } from "@app/lib/types";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";@@ -658,6 +659,30 @@ export const pamDiscoverySourceServiceFactory = ({return accountWithResource;};+ const decryptDependencySyncMessages = async <T extends { encryptedLastSyncMessage?: Buffer | null }>(+ deps: T[],+ projectId: string+ ): Promise<(T & { lastSyncMessage: string | null })[]> => {+ if (!deps.length) return deps.map((d) => ({ ...d, lastSyncMessage: null as string | null }));++ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });++ return deps.map((dep) => {+ let lastSyncMessage: string | null = null;+ if (dep.encryptedLastSyncMessage) {+ try {+ lastSyncMessage = decryptor({ cipherTextBlob: dep.encryptedLastSyncMessage }).toString();+ } catch {+ lastSyncMessage = "Failed to decrypt error message";+ }+ }+ return { ...dep, lastSyncMessage };+ });+ };+const getAccountDependencies = async ({accountId,actor,@@ -671,7 +696,7 @@ export const pamDiscoverySourceServiceFactory = ({actorAuthMethod: ActorAuthMethod;actorOrgId: string;}) => {- await verifyAccountPermission(+ const accountWithResource = await verifyAccountPermission(accountId,ProjectPermissionPamAccountActions.Read,actor,@@ -679,7 +704,8 @@ export const pamDiscoverySourceServiceFactory = ({actorAuthMethod,actorOrgId);- return pamAccountDependenciesDAL.findByAccountId(accountId);+ const deps = await pamAccountDependenciesDAL.findByAccountId(accountId);+ return decryptDependencySyncMessages(deps, accountWithResource.projectId);};const getResourceDependencies = async ({@@ -712,7 +738,8 @@ export const pamDiscoverySourceServiceFactory = ({subject(ProjectPermissionSub.PamResources, { name: resource.name }));- return pamAccountDependenciesDAL.findByResourceId(resourceId);+ const deps = await pamAccountDependenciesDAL.findByResourceId(resourceId);+ return decryptDependencySyncMessages(deps, resource.projectId);};const updateAccountDependency = async ({diff --git a/backend/src/ee/services/pam-resource/active-directory/active-directory-resource-factory.ts b/backend/src/ee/services/pam-resource/active-directory/active-directory-resource-factory.tsindex 04e302eb10..110deb6123 100644--- a/backend/src/ee/services/pam-resource/active-directory/active-directory-resource-factory.ts+++ b/backend/src/ee/services/pam-resource/active-directory/active-directory-resource-factory.ts@@ -7,13 +7,17 @@ import { logger } from "@app/lib/logger";import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";+import { generatePassword } from "../../secret-rotation-v2/shared/utils";import { PamResource } from "../pam-resource-enums";import {TPamResourceFactory,TPamResourceFactoryRotateAccountCredentials,TPamResourceFactoryValidateAccountCredentials,- TPamResourceInternalMetadata+ TPamResourceInternalMetadata,+ TPostRotateContext} from "../pam-resource-types";+import { syncDependenciesAfterRotation } from "../shared/dependency-sync-fns";+import { resolveDnsTcp } from "../shared/dns-over-dc";import {TActiveDirectoryAccountCredentials,TActiveDirectoryResourceConnectionDetails@@ -66,9 +70,7 @@ export const activeDirectoryResourceFactory: TPamResourceFactory<TPamResourceInternalMetadata> = (resourceType, connectionDetails, gatewayId, gatewayV2Service) => {const validateConnection = async () => {- if (!gatewayId) {- throw new BadRequestError({ message: "Gateway ID is required" });- }+ if (!gatewayId) throw new BadRequestError({ message: "Gateway is required for connection validation" });try {await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (proxyPort) => {@@ -117,20 +119,73 @@ export const activeDirectoryResourceFactory: TPamResourceFactory<const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<TActiveDirectoryAccountCredentials> = async (credentials) => {- if (!gatewayId) {- throw new BadRequestError({ message: "Gateway ID is required" });- }+ if (!gatewayId) throw new BadRequestError({ message: "Gateway is required for credential validation" });try {- await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (proxyPort) => {- return new Promise<void>((resolve, reject) => {- // Bind DN uses UPN format: username@domain- const bindDn = `${credentials.username}@${connectionDetails.domain}`;+ await executeWithGateway(+ { connectionDetails, gatewayId, resourceType, targetPortOverride: 636 },+ gatewayV2Service,+ async (proxyPort) => {+ return new Promise<void>((resolve, reject) => {+ const bindDn = `${credentials.username}@${connectionDetails.domain}`;++ const client = ldapjs.createClient({+ url: `ldaps://localhost:${proxyPort}`,+ connectTimeout: EXTERNAL_REQUEST_TIMEOUT,+ timeout: EXTERNAL_REQUEST_TIMEOUT,+ tlsOptions: {+ rejectUnauthorized: false+ }+ });+ client.on("error", (err: Error) => {+ client.unbind();+ reject(err);+ });++ client.bind(bindDn, credentials.password, (err) => {+ if (err) {+ client.unbind();+ logger.warn(err, "[Active Directory Resource Factory] LDAP bind failed during credential validation");+ reject(new Error(`LDAP bind failed: ${err.message}`));+ } else {+ logger.info("[Active Directory Resource Factory] LDAP credential validation successful");+ client.unbind();+ resolve();+ }+ });+ });+ }+ );+ } catch (error) {+ throw new BadRequestError({+ message: `Unable to validate credentials for ${resourceType}: ${(error as Error).message || String(error)}`+ });+ }++ return credentials;+ };++ const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<+ TActiveDirectoryAccountCredentials+ > = async (rotationAccountCredentials, currentCredentials) => {+ if (!gatewayId) throw new BadRequestError({ message: "Gateway is required for AD credential rotation" });++ const newPassword = generatePassword();++ // AD requires LDAPS (port 636) for unicodePwd changes+ await executeWithGateway(+ { connectionDetails, gatewayId, resourceType, targetPortOverride: 636 },+ gatewayV2Service,+ async (proxyPort) => {+ return new Promise<void>((resolve, reject) => {const client = ldapjs.createClient({- url: `ldap://localhost:${proxyPort}`,+ url: `ldaps://localhost:${proxyPort}`,connectTimeout: EXTERNAL_REQUEST_TIMEOUT,- timeout: EXTERNAL_REQUEST_TIMEOUT+ timeout: EXTERNAL_REQUEST_TIMEOUT,+ tlsOptions: {+ rejectUnauthorized: false+ }});client.on("error", (err: Error) => {@@ -138,32 +193,119 @@ export const activeDirectoryResourceFactory: TPamResourceFactory<reject(err);});- client.bind(bindDn, credentials.password, (err) => {- if (err) {+ // Bind as rotation account (admin)+ const bindDn = `${rotationAccountCredentials.username}@${connectionDetails.domain}`;+ client.bind(bindDn, rotationAccountCredentials.password, (bindErr) => {+ if (bindErr) {client.unbind();- reject(new Error("LDAP bind failed: invalid credentials"));- } else {- logger.info("[Active Directory Resource Factory] LDAP credential validation successful");- client.unbind();- resolve();+ reject(new Error(`Rotation account bind failed: ${bindErr.message}`));+ return;}++ // Search for target user's DN by sAMAccountName+ const searchBase = connectionDetails.domain+ .split(".")+ .map((dc) => `DC=${dc}`)+ .join(",");++ client.search(+ searchBase,+ {+ filter: new ldapjs.EqualityFilter({ attribute: "sAMAccountName", value: currentCredentials.username }),+ scope: "sub",+ attributes: ["dn"]+ },+ (searchErr, searchRes) => {+ if (searchErr) {+ client.unbind();+ reject(new Error(`LDAP search failed: ${searchErr.message}`));+ return;+ }++ let userDn: string | null = null;++ searchRes.on("searchEntry", (entry) => {+ userDn = entry.objectName;+ });++ searchRes.on("error", (err) => {+ client.unbind();+ reject(new Error(`LDAP search error: ${err.message}`));+ });++ searchRes.on("end", () => {+ if (!userDn) {+ client.unbind();+ reject(new Error(`User '${currentCredentials.username}' not found in AD`));+ return;+ }++ // Admin reset: use "replace" operation on unicodePwd+ const encodedPassword = Buffer.from(`"${newPassword}"`, "utf16le");+ const change = new ldapjs.Change({+ operation: "replace",+ modification: { type: "unicodePwd", values: [encodedPassword] }+ });++ client.modify(userDn, change, (modifyErr) => {+ client.unbind();+ if (modifyErr) {+ reject(new Error(`AD password reset failed: ${modifyErr.message}`));+ } else {+ logger.info(+ `[AD Rotation] Password rotated for ${currentCredentials.username} on ${connectionDetails.domain}`+ );+ resolve();+ }+ });+ });+ }+ );});});- });- } catch (error) {- throw new BadRequestError({- message: `Unable to validate credentials for ${resourceType}: ${(error as Error).message || String(error)}`- });- }+ }+ );- return credentials;+ return { username: currentCredentials.username, password: newPassword };};- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<- TActiveDirectoryAccountCredentials- > = async () => {- throw new BadRequestError({- message: "Credential rotation is not yet supported for Active Directory resources"+ const postRotate = async (+ accountId: string,+ newCredentials: TActiveDirectoryAccountCredentials,+ projectId: string,+ ctx: TPostRotateContext,+ rotationAccountCredentials: TActiveDirectoryAccountCredentials+ ) => {+ if (!gatewayId) return;++ await syncDependenciesAfterRotation({+ accountId,+ newCredentials,+ projectId,+ ctx,+ gatewayV2Service,+ rotationCredentials: rotationAccountCredentials,+ gatewayId,+ resolveHostname: async (hostname) => {+ // Resolve via DC's DNS through the gateway+ return executeWithGateway(+ { connectionDetails, gatewayId, resourceType, targetPortOverride: 53 },+ gatewayV2Service,+ async (proxyPort) => {+ const ip = await resolveDnsTcp(hostname, proxyPort);+ if (ip) {+ logger.info(`[AD DependencySync] Resolved ${hostname} -> ${ip}`);+ return ip;+ }+ logger.warn(`[AD DependencySync] DNS resolution failed for ${hostname}, using original`);+ return hostname;+ }+ );+ },+ formatWinrmUsername: (rotationUsername) => {+ const netbiosDomain = connectionDetails.domain.split(".")[0].toUpperCase();+ return `${netbiosDomain}\\${rotationUsername}`;+ }});};@@ -185,6 +327,7 @@ export const activeDirectoryResourceFactory: TPamResourceFactory<validateConnection,validateAccountCredentials,rotateAccountCredentials,+ postRotate,handleOverwritePreventionForCensoredValues};};diff --git a/backend/src/ee/services/pam-resource/pam-resource-types.ts b/backend/src/ee/services/pam-resource/pam-resource-types.tsindex 892489da6f..f2eff2d633 100644--- a/backend/src/ee/services/pam-resource/pam-resource-types.ts+++ b/backend/src/ee/services/pam-resource/pam-resource-types.ts@@ -157,6 +157,12 @@ export type TPamResourceFactory<validateConnection: TPamResourceFactoryValidateConnection<T>;validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<C>;rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<C>;- postRotate?: (accountId: string, newCredentials: C, projectId: string, ctx: TPostRotateContext) => Promise<void>;+ postRotate?: (+ accountId: string,+ newCredentials: C,+ projectId: string,+ ctx: TPostRotateContext,+ rotationAccountCredentials: C+ ) => Promise<void>;handleOverwritePreventionForCensoredValues: (updatedAccountCredentials: C, currentCredentials: C) => Promise<C>;};diff --git a/backend/src/ee/services/pam-resource/shared/dependency-sync-fns.ts b/backend/src/ee/services/pam-resource/shared/dependency-sync-fns.tsindex 31bcbff329..819698da22 100644--- a/backend/src/ee/services/pam-resource/shared/dependency-sync-fns.ts+++ b/backend/src/ee/services/pam-resource/shared/dependency-sync-fns.ts@@ -14,7 +14,8 @@ import { PamAccountDependencyType } from "../../pam-discovery/pam-discovery-enumimport { decryptResource } from "../pam-resource-fns";import { TPostRotateContext } from "../pam-resource-types";-export const WINRM_PORT = 5985;+export const WINRM_DEFAULT_HTTP_PORT = 5985;+export const WINRM_DEFAULT_HTTPS_PORT = 5986;// Escape a string for use inside PowerShell single-quoted strings (doubles single quotes)export const escapePowershellSingleQuote = (value: string) => new RE2("'", "g").replace(value, "''");@@ -61,6 +62,11 @@ type TSyncDependenciesParams = {projectId: string;ctx: TPostRotateContext;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ rotationCredentials: { username: string; password: string };+ gatewayId: string;+ winrmPort?: number;+ useWinrmHttps?: boolean;+ resolveHostname?: (hostname: string) => Promise<string>;formatWinrmUsername?: (rotationUsername: string, hostname: string, resourceType: string) => string;};@@ -70,15 +76,21 @@ export const syncDependenciesAfterRotation = async ({projectId,ctx,gatewayV2Service,+ rotationCredentials,+ gatewayId,+ winrmPort,+ useWinrmHttps = false,+ resolveHostname,formatWinrmUsername}: TSyncDependenciesParams) => {+ const effectiveWinrmPort = winrmPort ?? (useWinrmHttps ? WINRM_DEFAULT_HTTPS_PORT : WINRM_DEFAULT_HTTP_PORT);const allDeps = await ctx.pamAccountDependenciesDAL.findByAccountId(accountId);const enabledDeps = allDeps.filter((d) => d.isRotationSyncEnabled);if (!enabledDeps.length) return;const grouped = groupBy(enabledDeps, (d) => d.resourceId);- // Batch-fetch all target resources in a single query+ // Batch-fetch all target resources to get their hostnamesconst resourceIds = Object.keys(grouped);const resources = await ctx.pamResourceDAL.find({ $in: { id: resourceIds } });const resourceMap = new Map(resources.map((r) => [r.id, r]));@@ -104,18 +116,10 @@ export const syncDependenciesAfterRotation = async ({return;}- let rotationCredentials: { username: string; password: string } | null = null;- let depGatewayId: string | null = null;+ // Get hostname from the target resource's connection detailslet hostname: string | null = null;-try {const decrypted = await decryptResource(resource, projectId, ctx.kmsService);- rotationCredentials = decrypted.rotationAccountCredentials as {- username: string;- password: string;- } | null;- depGatewayId = decrypted.gatewayId ?? null;-const connDetails = decrypted.connectionDetails as { hostname?: string; domain?: string };hostname = connDetails.hostname ?? connDetails.domain ?? null;} catch (err) {@@ -123,8 +127,8 @@ export const syncDependenciesAfterRotation = async ({return;}- if (!rotationCredentials || !depGatewayId || !hostname) {- logger.warn(`[DependencySync] Missing rotation credentials or gateway for resource ${resourceId}, skipping`);+ if (!hostname) {+ logger.warn(`[DependencySync] No hostname found for resource ${resourceId}, skipping`);return;}@@ -132,24 +136,22 @@ export const syncDependenciesAfterRotation = async ({? formatWinrmUsername(rotationCredentials.username, hostname, resource.resourceType): rotationCredentials.username;- // Resolve host and gateway connection once per resource group+ // Resolve hostname — use custom resolver (e.g. DC DNS) if provided, otherwise use as-is+ let resolvedHost = hostname;+ if (resolveHostname) {+ try {+ resolvedHost = await resolveHostname(hostname);+ } catch (err) {+ logger.warn(err, `[DependencySync] Failed to resolve hostname ${hostname}, using original`);+ }+ }+const [targetHost] = await verifyHostInputValidity({- host: hostname,+ host: resolvedHost,isGateway: true,isDynamicSecret: false});- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({- gatewayId: depGatewayId,- targetHost,- targetPort: WINRM_PORT- });-- if (!platformConnectionDetails) {- logger.warn(`[DependencySync] Unable to connect to gateway for resource ${resourceId}, skipping`);- return;- }-// eslint-disable-next-line no-restricted-syntaxfor (const dep of deps) {try {@@ -158,16 +160,37 @@ export const syncDependenciesAfterRotation = async ({const script = buildDependencySyncScript(dep, newCredentials.username, newCredentials.password);+ // eslint-disable-next-line no-await-in-loop+ const depConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId,+ targetHost,+ targetPort: effectiveWinrmPort+ });++ if (!depConnectionDetails) {+ logger.warn(`[DependencySync] Unable to get gateway connection for dep ${dep.name}, skipping`);+ // eslint-disable-next-line no-continue+ continue;+ }+// eslint-disable-next-line no-await-in-loopawait withGatewayV2Proxy(async (proxyPort) => {- await runPowershell(script, "localhost", winrmUsername, rotationCredentials!.password, proxyPort);+ await runPowershell(+ script,+ "localhost",+ winrmUsername,+ rotationCredentials.password,+ proxyPort,+ useWinrmHttps,+ false+ );},{protocol: GatewayProxyProtocol.Tcp,- relayHost: platformConnectionDetails.relayHost,- gateway: platformConnectionDetails.gateway,- relay: platformConnectionDetails.relay+ relayHost: depConnectionDetails.relayHost,+ gateway: depConnectionDetails.gateway,+ relay: depConnectionDetails.relay});diff --git a/backend/src/ee/services/pam-resource/shared/dns-over-dc.ts b/backend/src/ee/services/pam-resource/shared/dns-over-dc.tsnew file mode 100644index 0000000000..250a957260--- /dev/null+++ b/backend/src/ee/services/pam-resource/shared/dns-over-dc.ts@@ -0,0 +1,50 @@+import net from "node:net";++import * as dnsPacket from "dns-packet";++// Resolve a hostname to an IP via DNS-over-TCP through a local proxy port+export const resolveDnsTcp = (hostname: string, proxyPort: number): Promise<string | null> => {+ return new Promise((resolve) => {+ const query = dnsPacket.streamEncode({+ type: "query",+ flags: dnsPacket.RECURSION_DESIRED,+ questions: [{ type: "A", name: hostname }]+ });++ const socket = net.connect({ host: "127.0.0.1", port: proxyPort }, () => {+ socket.write(query);+ });++ const MAX_DNS_TCP_SIZE = 2 + 65535;+ let responseData = Buffer.alloc(0);++ socket.on("data", (chunk: Buffer) => {+ responseData = Buffer.concat([responseData, chunk]);++ if (responseData.length > MAX_DNS_TCP_SIZE) {+ socket.destroy();+ resolve(null);+ return;+ }++ if (responseData.length >= 2) {+ const msgLen = responseData.readUInt16BE(0);+ if (responseData.length >= 2 + msgLen) {+ const response = dnsPacket.streamDecode(responseData);+ const aRecord = response.answers?.find((a) => a.type === "A");+ socket.destroy();+ resolve(aRecord && "data" in aRecord ? (aRecord.data as string) : null);+ }+ }+ });++ socket.on("error", () => {+ resolve(null);+ });++ socket.setTimeout(5000, () => {+ socket.destroy();+ resolve(null);+ });+ });+};diff --git a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-factory.ts b/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-factory.tsindex 9333f59b15..3b62a64c97 100644--- a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-factory.ts+++ b/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-factory.ts@@ -1,5 +1,7 @@import net from "node:net";+import { runPowershell } from "winrm-client";+import { BadRequestError } from "@app/lib/errors";import { GatewayProxyProtocol } from "@app/lib/gateway";import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";@@ -7,12 +9,19 @@ import { logger } from "@app/lib/logger";import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";+import { generatePassword } from "../../secret-rotation-v2/shared/utils";import { PamResource } from "../pam-resource-enums";import {TPamResourceFactory,TPamResourceFactoryRotateAccountCredentials,- TPamResourceFactoryValidateAccountCredentials+ TPamResourceFactoryValidateAccountCredentials,+ TPostRotateContext} from "../pam-resource-types";+import {+ escapePowershellSingleQuote,+ syncDependenciesAfterRotation,+ WINRM_DEFAULT_HTTP_PORT+} from "../shared/dependency-sync-fns";import {TWindowsAccountCredentials,TWindowsResourceConnectionDetails,@@ -130,11 +139,60 @@ export const windowsResourceFactory: TPamResourceFactory<return credentials;};- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<- TWindowsAccountCredentials- > = async () => {- throw new BadRequestError({- message: "Credential rotation is not yet supported for Windows Server resources"+ const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<TWindowsAccountCredentials> = async (+ rotationAccountCredentials,+ currentCredentials+ ) => {+ if (!gatewayId) throw new BadRequestError({ message: "Gateway ID is required for Windows credential rotation" });++ const newPassword = generatePassword();++ const escapedNewPassword = escapePowershellSingleQuote(newPassword);+ const escapedUsername = escapePowershellSingleQuote(currentCredentials.username);++ await executeWithGateway(+ { connectionDetails, gatewayId, resourceType, targetPortOverride: WINRM_DEFAULT_HTTP_PORT },+ gatewayV2Service,+ async (proxyPort) => {+ const script = [+ `$securePassword = ConvertTo-SecureString '${escapedNewPassword}' -AsPlainText -Force`,+ `Set-LocalUser -Name '${escapedUsername}' -Password $securePassword`+ ].join("; ");++ await runPowershell(+ script,+ "localhost",+ rotationAccountCredentials.username,+ rotationAccountCredentials.password,+ proxyPort+ );++ logger.info(+ `[Windows Rotation] Password rotated for local account '${currentCredentials.username}' on ${connectionDetails.hostname}`+ );+ }+ );++ return { username: currentCredentials.username, password: newPassword };+ };++ const postRotate = async (+ accountId: string,+ newCredentials: TWindowsAccountCredentials,+ projectId: string,+ ctx: TPostRotateContext,+ rotationAccountCredentials: TWindowsAccountCredentials+ ) => {+ if (!gatewayId) return;++ await syncDependenciesAfterRotation({+ accountId,+ newCredentials,+ projectId,+ ctx,+ gatewayV2Service,+ rotationCredentials: rotationAccountCredentials,+ gatewayId});};@@ -156,6 +214,7 @@ export const windowsResourceFactory: TPamResourceFactory<validateConnection,validateAccountCredentials,rotateAccountCredentials,+ postRotate,handleOverwritePreventionForCensoredValues};};diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex 3a7404b97a..c35508807e 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -210,6 +210,7 @@ export type TPamAccountDependency = {isRotationSyncEnabled: boolean;syncStatus?: string | null;lastSyncedAt?: string | null;+ lastSyncMessage?: string | null;resourceName?: string | null;createdAt: string;updatedAt: string;diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsxindex e73de3a232..ea50e9941d 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx@@ -50,7 +50,6 @@ const CreateForm = ({}) => {const { internalMetadata, ...rest } = formData;- console.log(rest);const account = await createPamAccount.mutateAsync({...rest,folderId,@@ -157,7 +156,6 @@ const UpdateForm = ({ account, closeSheet }: UpdateFormProps) => {}) => {const { internalMetadata, ...rest } = formData;- console.log(rest);const updatedAccount = await updatePamAccount.mutateAsync({accountId: account.id,resourceType: account.resource.resourceType,diff --git a/frontend/src/pages/pam/components/PamDependenciesTable.tsx b/frontend/src/pages/pam/components/PamDependenciesTable.tsxindex b0ae9e0a29..3f221e3a39 100644--- a/frontend/src/pages/pam/components/PamDependenciesTable.tsx+++ b/frontend/src/pages/pam/components/PamDependenciesTable.tsx@@ -142,9 +142,14 @@ const DependencyRow = ({)[dep.syncStatus] ?? dep.syncStatus}</Badge></TooltipTrigger>- {dep.lastSyncedAt && (- <TooltipContent side="top">- Last synced: {format(new Date(dep.lastSyncedAt), "MMM d, yyyy HH:mm")}+ {(dep.lastSyncedAt || dep.lastSyncMessage) && (+ <TooltipContent side="top" className="max-w-xs">+ {dep.lastSyncedAt && (+ <p>Last synced: {format(new Date(dep.lastSyncedAt), "MMM d, yyyy HH:mm")}</p>+ )}+ {dep.syncStatus === "failed" && dep.lastSyncMessage && (+ <p className="mt-1 text-danger">{dep.lastSyncMessage}</p>+ )}</TooltipContent>)}</Tooltip>