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
feat(ldap): enhance password rotation with referral handling and domain extraction
Victor Hugo dos Santos845fb0c5f109
diff --git a/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.tsindex cc96cf327d..dd26e6eca7 100644--- a/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts@@ -10,7 +10,14 @@ import {import { logger } from "@app/lib/logger";import { DistinguishedNameRegex } from "@app/lib/regex";import { encryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";-import { executeWithPotentialGateway, LdapProvider, TLdapConnection } from "@app/services/app-connection/ldap";+import {+ buildReferralUrl,+ executeWithPotentialGateway,+ extractDomainFromDN,+ isLdapReferralError,+ LdapProvider,+ TLdapConnection+} from "@app/services/app-connection/ldap";import { generatePassword } from "../shared/utils";import {@@ -76,10 +83,12 @@ export const ldapPasswordRotationFactory: TRotationFactory<const { dn, passwordRequirements } = parameters;- const $verifyCredentials = async (credentials: Pick<TLdapConnection["credentials"], "dn" | "password">) => {+ const $verifyCredentials = async (+ verifyOpts: Pick<TLdapConnection["credentials"], "dn" | "password"> & { url?: string }+ ) => {try {await executeWithPotentialGateway(- { ...connection, credentials: { ...connection.credentials, ...credentials } },+ { ...connection, credentials: { ...connection.credentials, ...verifyOpts } },gatewayV2Service,async () => {});@@ -103,7 +112,6 @@ export const ldapPasswordRotationFactory: TRotationFactory<{const encodedPassword = getEncodedPassword(password);- // service account vs personal password rotation require different changesif (isConnectionRotation || currentPassword) {const currentEncodedPassword = getEncodedPassword(currentPassword || credentials.password);@@ -138,34 +146,55 @@ export const ldapPasswordRotationFactory: TRotationFactory<throw new Error(`Unhandled provider: ${credentials.provider as LdapProvider}`);}- await executeWithPotentialGateway(- {- ...connection,- credentials: currentPassword- ? {- ...credentials,- password: currentPassword,- dn- }- : credentials- },- gatewayV2Service,- async (client) => {- const userDn = await getDN(dn, client);- await new Promise<void>((resolve, reject) => {- client.modify(userDn, changes, (err) => {- if (err) {- logger.error(err, "LDAP Password Rotation Failed");- reject(new Error(`Provider Modify Error: ${err.message}`));- } else {- resolve();- }+ const connectionCredentials = currentPassword ? { ...credentials, password: currentPassword, dn } : credentials;++ const performModify = async (targetCredentials: typeof connectionCredentials) => {+ await executeWithPotentialGateway(+ { ...connection, credentials: targetCredentials },+ gatewayV2Service,+ async (client) => {+ const userDn = await getDN(dn, client);+ await new Promise<void>((resolve, reject) => {+ client.modify(userDn, changes, (err) => {+ if (err) {+ logger.error(err, "LDAP Password Rotation Failed");+ reject(err);+ } else {+ resolve();+ }+ });});- });+ }+ );+ };++ let referredUrl: string | undefined;++ try {+ await performModify(connectionCredentials);+ } catch (err) {+ if (!isLdapReferralError(err)) {+ throw new Error(`Provider Modify Error: ${(err as Error).message}`);}- );- await $verifyCredentials({ dn, password });+ const referralDomain = extractDomainFromDN(err.dn);+ if (!referralDomain) {+ throw new Error("Provider Modify Error: Referral received but could not determine target domain");+ }++ referredUrl = buildReferralUrl(credentials.url, referralDomain);+ logger.info({ referralDomain, referredUrl }, "LDAP referral detected — chasing to referred domain controller");++ try {+ await performModify({ ...connectionCredentials, url: referredUrl });+ } catch (retryErr) {+ throw new Error(+ `Provider Modify Error: Referral chase to ${referralDomain} failed — ${(retryErr as Error).message}`+ );+ }+ }++ await $verifyCredentials({ dn, password, ...(referredUrl ? { url: referredUrl } : {}) });if (isConnectionRotation) {const updatedCredentials: TLdapConnection["credentials"] = {diff --git a/backend/src/services/app-connection/ldap/ldap-connection-fns.ts b/backend/src/services/app-connection/ldap/ldap-connection-fns.tsindex 961dcff597..afe3f379df 100644--- a/backend/src/services/app-connection/ldap/ldap-connection-fns.ts+++ b/backend/src/services/app-connection/ldap/ldap-connection-fns.ts@@ -15,6 +15,32 @@ import { TLdapConnectionConfig } from "./ldap-connection-types";const LDAP_TIMEOUT = 15_000;+/**+ * Extracts the domain from the DC components of a Distinguished Name.+ * e.g. "dc=us,dc=test,dc=com" → "us.test.com"+ */+export const extractDomainFromDN = (dn: string): string | null => {+ if (!dn) return null;++ const dcComponents = dn+ .split(",")+ .map((part) => part.trim())+ .filter((part) => part.toLowerCase().startsWith("dc="))+ .map((part) => part.substring(3));++ return dcComponents.length > 0 ? dcComponents.join(".") : null;+};++/**+ * Checks if an error is an LDAP Referral (code 10).+ * ldapjs surfaces this as a ReferralError with `dn` set to the matched DN.+ */+export const isLdapReferralError = (err: unknown): err is Error & { dn: string; code: number } => {+ if (!(err instanceof Error)) return false;+ const ldapErr = err as Error & { name?: string; code?: number };+ return ldapErr.name === "ReferralError" || ldapErr.code === 10;+};+const parseLdapUrl = (url: string): { protocol: string; host: string; port: number } => {const urlObj = new URL(url);const isSSL = urlObj.protocol === "ldaps:";@@ -31,6 +57,15 @@ const constructLdapUrl = (protocol: string, host: string, port: number): stringreturn `${protocol}://${host}:${port}`;};+/**+ * Constructs a new LDAP URL targeting a different domain/host,+ * preserving the protocol and port from the original URL.+ */+export const buildReferralUrl = (originalUrl: string, targetDomain: string): string => {+ const { protocol, port } = parseLdapUrl(originalUrl);+ return constructLdapUrl(protocol, targetDomain, port);+};+const setupLdapClientHandlers = <T>(client: ldap.Client,dn: string,