Skip to content

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

support referrals and gateway

Matheus Nogueirab086e1842325
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 4d90f7614b..cd4382f1fb 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2917,7 +2917,9 @@ export const registerRoutes = async (
appConnectionDAL,
keyStore,
kmsService,
- queueService
+ queueService,
+ gatewayV2Service,
+ gatewayPoolService
});
const appConnectionService = appConnectionServiceFactory({
diff --git a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-service.ts b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-service.ts
index 2a3a17919c..d27beb411a 100644
--- a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-service.ts
+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-service.ts
@@ -1,6 +1,8 @@
import { Knex } from "knex";
import { z } from "zod";
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
@@ -38,6 +40,7 @@ import {
TAppConnectionCredentialRotationStrategyConfig,
TCreateAppConnectionCredentialRotationDTO,
TCredentialRotationProviderFactory,
+ TCredentialRotationProviderServices,
TTriggerAppConnectionCredentialRotationDTO,
TUpdateAppConnectionCredentialRotationDTO
} from "./app-connection-credential-rotation-types";
@@ -98,6 +101,8 @@ export type TAppConnectionCredentialRotationServiceFactoryDep = {
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
keyStore: Pick<TKeyStoreFactory, "acquireLock" | "setItemWithExpiry" | "getItem">;
queueService: TQueueServiceFactory;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
export type TAppConnectionCredentialRotationServiceFactory = ReturnType<
@@ -109,8 +114,11 @@ export const appConnectionCredentialRotationServiceFactory = ({
appConnectionDAL,
kmsService,
keyStore,
- queueService
+ queueService,
+ gatewayV2Service,
+ gatewayPoolService
}: TAppConnectionCredentialRotationServiceFactoryDep) => {
+ const providerServices: TCredentialRotationProviderServices = { gatewayV2Service, gatewayPoolService };
/**
* Decrypt connection credentials.
*/
@@ -168,7 +176,7 @@ export const appConnectionCredentialRotationServiceFactory = ({
});
}
- const provider = CREDENTIAL_ROTATION_PROVIDER_FACTORY_MAP[strategy](connection);
+ const provider = CREDENTIAL_ROTATION_PROVIDER_FACTORY_MAP[strategy](connection, providerServices);
provider.validateConnectionMethod(connection.method);
@@ -433,8 +441,10 @@ export const appConnectionCredentialRotationServiceFactory = ({
kmsService
});
- const provider =
- CREDENTIAL_ROTATION_PROVIDER_FACTORY_MAP[strategy as AppConnectionCredentialRotationStrategy](connection);
+ const provider = CREDENTIAL_ROTATION_PROVIDER_FACTORY_MAP[strategy as AppConnectionCredentialRotationStrategy](
+ connection,
+ providerServices
+ );
// Two-credential rotation: create-first, revoke-after.
// This ordering ensures that if create fails, we still have 2 valid secrets.
diff --git a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-types.ts b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-types.ts
index a75a6da195..4d6c02c94c 100644
--- a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-types.ts
+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-types.ts
@@ -1,5 +1,8 @@
import { z } from "zod";
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+
import { TAppConnectionCredentialRotations } from "../../../db/schemas/app-connection-credential-rotations";
import { TAppConnectionRaw } from "../app-connection-types";
import { CreateAppConnectionCredentialRotationSchema } from "./app-connection-credential-rotation-schemas";
@@ -77,12 +80,20 @@ export type TCredentialRotationRevokeCredential<
C extends TAppConnectionCredentialRotationGeneratedCredential
> = (inactiveCredential: C, strategyConfig: S, credentials: TAppConnectionCredentialCredentials) => Promise<void>;
+export type TCredentialRotationProviderServices = {
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+};
+
// Factory type — takes connection context, returns typed operations.
// Mirrors TRotationFactory in secret-rotation-v2.
export type TCredentialRotationProviderFactory<
S extends TAppConnectionCredentialRotationStrategyConfig = TAppConnectionCredentialRotationStrategyConfig,
C extends TAppConnectionCredentialRotationGeneratedCredential = TAppConnectionCredentialRotationGeneratedCredential
-> = (connection: TAppConnectionRaw) => {
+> = (
+ connection: TAppConnectionRaw,
+ services: TCredentialRotationProviderServices
+) => {
validateConnectionMethod: TCredentialRotationValidateMethod;
issueInitialCredentials: TCredentialRotationIssueInitialCredentials<S, C>;
createCredential: TCredentialRotationCreateCredential<S, C>;
diff --git a/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret/azure-client-secret-credential-rotation-fns.ts b/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret/azure-client-secret-credential-rotation-fns.ts
index 5a9a16e34e..0602aa6d36 100644
--- a/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret/azure-client-secret-credential-rotation-fns.ts
+++ b/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret/azure-client-secret-credential-rotation-fns.ts
@@ -336,7 +336,11 @@ export const revokeAzureClientSecret = async (
export const azureClientSecretRotationProviderFactory: TCredentialRotationProviderFactory<
TAzureClientSecretStrategyConfig,
TAzureClientSecretGeneratedCredential
-> = (connection) => {
+> = (
+ connection,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _services
+) => {
const validateConnectionMethod: TCredentialRotationValidateMethod = (method) => {
if (method !== AzureKeyVaultConnectionMethod.ClientSecret) {
throw new BadRequestError({
diff --git a/backend/src/services/app-connection/credential-rotation/providers/ldap/ldap-credential-rotation-fns.ts b/backend/src/services/app-connection/credential-rotation/providers/ldap/ldap-credential-rotation-fns.ts
index 9d279fc599..7d331b62f4 100644
--- a/backend/src/services/app-connection/credential-rotation/providers/ldap/ldap-credential-rotation-fns.ts
+++ b/backend/src/services/app-connection/credential-rotation/providers/ldap/ldap-credential-rotation-fns.ts
@@ -1,10 +1,21 @@
+/* eslint-disable no-await-in-loop */
import ldap from "@infisical/ldapjs";
import { generatePassword } from "@app/ee/services/secret-rotation-v2/shared/utils";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { DistinguishedNameRegex } from "@app/lib/regex";
-import { getLdapConnectionClient } from "@app/services/app-connection/ldap";
+import {
+ buildReferralUrl,
+ executeWithPotentialGateway,
+ extractDomainFromDN,
+ extractHostFromReferralUrl,
+ isLdapReferral,
+ isLdapReferralError,
+ LdapReferralError,
+ normalizeLdapUrl,
+ TLdapConnectionConfig
+} from "@app/services/app-connection/ldap";
import { LdapConnectionMethod, LdapProvider } from "@app/services/app-connection/ldap/ldap-connection-enums";
import {
@@ -12,6 +23,7 @@ import {
TCredentialRotationIssueInitialCredentials,
TCredentialRotationMergeCredentials,
TCredentialRotationProviderFactory,
+ TCredentialRotationProviderServices,
TCredentialRotationRevokeCredential,
TCredentialRotationValidateMethod
} from "../../app-connection-credential-rotation-types";
@@ -21,9 +33,11 @@ import {
TLdapStrategyConfig
} from "./ldap-credential-rotation-types";
+const MAX_REFERRAL_HOPS = 10;
+
const getEncodedPassword = (password: string) => Buffer.from(`"${password}"`, "utf16le");
-const getDN = async (dn: string, client: ldap.Client): Promise<string> => {
+const getDN = async (dn: string, client: ldap.Client, searchBase: string): Promise<string> => {
if (DistinguishedNameRegex.test(dn)) return dn;
const opts: ldap.SearchOptions = {
@@ -32,16 +46,36 @@ const getDN = async (dn: string, client: ldap.Client): Promise<string> => {
attributes: ["dn"]
};
- const base = dn
- .split("@")[1]
- .split(".")
- .map((dc) => `dc=${dc}`)
- .join(",");
-
return new Promise((resolve, reject) => {
- client.search(base, opts, (err, res) => {
+ const handleSearchError = (error: Error) => {
+ if (isLdapReferral(error)) {
+ const ldapErr = error as Partial<LdapReferralError> & Error;
+ if (!ldapErr.dn) {
+ (ldapErr as { dn: string }).dn = searchBase;
+ }
+ if (!Array.isArray((ldapErr as { referrals?: unknown }).referrals)) {
+ (ldapErr as { referrals: string[] }).referrals = [];
+ }
+ (ldapErr as { referralSource: string }).referralSource = "search";
+ logger.info(
+ {
+ searchBase,
+ upn: dn,
+ referralDn: ldapErr.dn,
+ referralUrls: (ldapErr as { referrals?: string[] }).referrals ?? []
+ },
+ `LDAP DN resolution received referral [searchBase=${searchBase}] [upn=${dn}]`
+ );
+ reject(error);
+ return;
+ }
+
+ reject(new Error(`Provider Resolve DN Error: ${error.message}`));
+ };
+
+ client.search(searchBase, opts, (err, res) => {
if (err) {
- reject(new Error(`Provider Resolve DN Error: ${err.message}`));
+ handleSearchError(err);
return;
}
@@ -52,7 +86,7 @@ const getDN = async (dn: string, client: ldap.Client): Promise<string> => {
});
res.on("error", (error) => {
- reject(new Error(`Provider Resolve DN Error: ${error.message}`));
+ handleSearchError(error);
});
res.on("end", () => {
@@ -94,44 +128,187 @@ const buildPasswordChanges = (provider: LdapProvider, currentPassword: string, n
}
};
-const modifyLdapPassword = async (
- credentials: TLdapCredentialRotationCredentials,
- newPassword: string
+const resolveSearchBase = (dn: string): string => {
+ return dn
+ .split("@")[1]
+ .split(".")
+ .map((dc) => `dc=${dc}`)
+ .join(",");
+};
+
+const performModify = async (
+ connectionConfig: TLdapConnectionConfig,
+ dn: string,
+ changes: ldap.Change[],
+ services: TCredentialRotationProviderServices
): Promise<void> => {
+ let capturedReferralError: LdapReferralError | undefined;
+ const searchBase = DistinguishedNameRegex.test(dn) ? dn : resolveSearchBase(dn);
+
+ try {
+ await executeWithPotentialGateway(
+ connectionConfig,
+ services.gatewayV2Service,
+ async (client) => {
+ let userDn: string;
+ try {
+ userDn = await getDN(dn, client, searchBase);
+ } catch (getDnErr) {
+ if (isLdapReferralError(getDnErr)) {
+ capturedReferralError = getDnErr;
+ }
+ throw getDnErr;
+ }
+
+ await new Promise<void>((resolve, reject) => {
+ client.modify(userDn, changes, (err) => {
+ if (err) {
+ if (isLdapReferral(err)) {
+ const ldapErr = err as Partial<LdapReferralError> & Error;
+ if (!Array.isArray((ldapErr as { referrals?: unknown }).referrals)) {
+ (ldapErr as { referrals: string[] }).referrals = [];
+ }
+ if (typeof ldapErr.dn !== "string") {
+ (ldapErr as { dn: string }).dn = "";
+ }
+ (ldapErr as { referralSource: string }).referralSource = "modify";
+ capturedReferralError = ldapErr as LdapReferralError;
+ }
+ reject(err);
+ } else {
+ resolve();
+ }
+ });
+ });
+ },
+ services.gatewayPoolService
+ );
+ } catch (proxyErr) {
+ if (capturedReferralError) {
+ throw capturedReferralError;
+ }
+ throw proxyErr;
+ }
+};
+
+const resolveReferralTarget = (referralErr: LdapReferralError): { target: string; source: string } | null => {
+ if (referralErr.referrals.length > 0) {
+ const target = extractHostFromReferralUrl(referralErr.referrals[0]);
+ if (target) return { target, source: "referral URL" };
+ }
+
+ const domainFromDn = extractDomainFromDN(referralErr.dn);
+ if (domainFromDn) return { target: domainFromDn, source: "matched DN" };
+
+ return null;
+};
+
+const modifyLdapPassword = async (
+ connectionConfig: TLdapConnectionConfig,
+ newPassword: string,
+ connectionName: string,
+ services: TCredentialRotationProviderServices
+): Promise<string | undefined> => {
+ const { credentials } = connectionConfig;
+
if (!credentials.url.startsWith("ldaps")) {
throw new BadRequestError({ message: "Credential rotation requires an LDAPS connection" });
}
- const client = await getLdapConnectionClient(credentials);
+ const changes = buildPasswordChanges(credentials.provider, credentials.password, newPassword);
+
+ let referredUrl: string | undefined;
+ let currentConfig = connectionConfig;
+ const visitedUrls = new Set<string>();
+
+ for (let hop = 0; hop <= MAX_REFERRAL_HOPS; hop += 1) {
+ visitedUrls.add(normalizeLdapUrl(currentConfig.credentials.url));
+ try {
+ await performModify(currentConfig, credentials.dn, changes, services);
+ if (hop > 0) {
+ logger.info(
+ { connectionName, totalHops: hop, finalUrl: referredUrl },
+ `credentialRotation: LDAP modify succeeded after referral chase [connection=${connectionName}]`
+ );
+ }
+ return referredUrl;
+ } catch (caughtErr) {
+ if (!isLdapReferralError(caughtErr)) {
+ const errObj = caughtErr instanceof Error ? caughtErr : new Error(String(caughtErr));
+ const prefix = referredUrl
+ ? `Provider Modify Error: Referral chase to ${referredUrl} failed`
+ : "Provider Modify Error";
+ throw new Error(`${prefix} -- ${errObj.message}`);
+ }
- try {
- const userDn = await getDN(credentials.dn, client);
+ if (hop === MAX_REFERRAL_HOPS) {
+ throw new Error(
+ `Provider Modify Error: Maximum referral hops (${MAX_REFERRAL_HOPS}) exceeded -- last referral DN: ${caughtErr.dn}`
+ );
+ }
- const changes = buildPasswordChanges(credentials.provider, credentials.password, newPassword);
+ const resolved = resolveReferralTarget(caughtErr);
+
+ logger.info(
+ {
+ connectionName,
+ hop: hop + 1,
+ referralSource: caughtErr.referralSource,
+ referralDn: caughtErr.dn,
+ referralUrls: caughtErr.referrals,
+ referralTarget: resolved?.target,
+ targetSource: resolved?.source,
+ currentUrl: currentConfig.credentials.url
+ },
+ `credentialRotation: LDAP referral received [connection=${connectionName}]`
+ );
+
+ if (!resolved) {
+ throw new Error(
+ `Provider Modify Error: Referral received but could not determine target -- referralUrls: [${caughtErr.referrals.join(", ")}], matchedDN: ${caughtErr.dn}`
+ );
+ }
- await new Promise<void>((resolve, reject) => {
- client.modify(userDn, changes, (err) => {
- if (err) {
- reject(new Error(`Provider Modify Error: ${err.message}`));
- } else {
- resolve();
- }
- });
- });
- } finally {
- client.destroy();
+ referredUrl = buildReferralUrl(credentials.url, resolved.target);
+
+ if (visitedUrls.has(referredUrl)) {
+ throw new Error(
+ `Provider Modify Error: Referral chase loop detected -- referred URL ${referredUrl} was already visited`
+ );
+ }
+
+ currentConfig = { ...connectionConfig, credentials: { ...credentials, url: referredUrl } };
+ }
}
+
+ return referredUrl;
};
-const verifyLdapCredentials = async (credentials: TLdapCredentialRotationCredentials): Promise<void> => {
- const client = await getLdapConnectionClient(credentials);
- client.destroy();
+const verifyLdapCredentials = async (
+ connectionConfig: TLdapConnectionConfig,
+ services: TCredentialRotationProviderServices,
+ urlOverride?: string
+): Promise<void> => {
+ const config = urlOverride
+ ? { ...connectionConfig, credentials: { ...connectionConfig.credentials, url: urlOverride } }
+ : connectionConfig;
+
+ await executeWithPotentialGateway(config, services.gatewayV2Service, async () => {}, services.gatewayPoolService);
};
export const ldapCredentialRotationProviderFactory: TCredentialRotationProviderFactory<
TLdapStrategyConfig,
TLdapGeneratedCredential
-> = (connection) => {
+> = (connection, services) => {
+ const buildConnectionConfig = (credentials: TLdapCredentialRotationCredentials): TLdapConnectionConfig => ({
+ method: LdapConnectionMethod.SimpleBind as const,
+ app: connection.app as TLdapConnectionConfig["app"],
+ credentials,
+ gatewayId: connection.gatewayId ?? null,
+ gatewayPoolId: connection.gatewayPoolId ?? null,
+ orgId: connection.orgId
+ });
+
const validateConnectionMethod: TCredentialRotationValidateMethod = (method) => {
if (method !== LdapConnectionMethod.SimpleBind) {
throw new BadRequestError({
@@ -145,19 +322,40 @@ export const ldapCredentialRotationProviderFactory: TCredentialRotationProviderF
TLdapGeneratedCredential
> = async (credentials) => {
const ldapCredentials = credentials as TLdapCredentialRotationCredentials;
+ const connectionConfig = buildConnectionConfig(ldapCredentials);
const strategyConfig: TLdapStrategyConfig = { provider: ldapCredentials.provider };
const newPassword = generatePassword();
- await modifyLdapPassword(ldapCredentials, newPassword);
+ const referredUrl = await modifyLdapPassword(connectionConfig, newPassword, connection.name, services);
const updatedCredentials = {
...ldapCredentials,
password: newPassword
};
- await verifyLdapCredentials(updatedCredentials);
+ const verifyConfig = buildConnectionConfig(updatedCredentials);
+
+ try {
+ await verifyLdapCredentials(verifyConfig, services, referredUrl);
+ } catch (verifyError) {
+ logger.error(
+ verifyError,
+ `credentialRotation: LDAP verification failed after password change, attempting revert [connection=${connection.name}]`
+ );
+ try {
+ const revertConfig = buildConnectionConfig(updatedCredentials);
+ await modifyLdapPassword(revertConfig, ldapCredentials.password, connection.name, services);
+ logger.info(`credentialRotation: LDAP password reverted successfully [connection=${connection.name}]`);
+ } catch (revertError) {
+ logger.error(
+ revertError,
+ `credentialRotation: LDAP password revert failed -- connection may require manual repair [connection=${connection.name}]`
+ );
+ }
+ throw verifyError;
+ }
logger.info(`credentialRotation: LDAP initial credential rotation succeeded [connection=${connection.name}]`);
@@ -180,13 +378,34 @@ export const ldapCredentialRotationProviderFactory: TCredentialRotationProviderF
credentials
) => {
const ldapCredentials = credentials as TLdapCredentialRotationCredentials;
+ const connectionConfig = buildConnectionConfig(ldapCredentials);
const newPassword = generatePassword();
- await modifyLdapPassword(ldapCredentials, newPassword);
+ const referredUrl = await modifyLdapPassword(connectionConfig, newPassword, connection.name, services);
const updatedCredentials = { ...ldapCredentials, password: newPassword };
- await verifyLdapCredentials(updatedCredentials);
+ const verifyConfig = buildConnectionConfig(updatedCredentials);
+
+ try {
+ await verifyLdapCredentials(verifyConfig, services, referredUrl);
+ } catch (verifyError) {
+ logger.error(
+ verifyError,
+ `credentialRotation: LDAP verification failed after password change, attempting revert [connection=${connection.name}]`
+ );
+ try {
+ const revertConfig = buildConnectionConfig(updatedCredentials);
+ await modifyLdapPassword(revertConfig, ldapCredentials.password, connection.name, services);
+ logger.info(`credentialRotation: LDAP password reverted successfully [connection=${connection.name}]`);
+ } catch (revertError) {
+ logger.error(
+ revertError,
+ `credentialRotation: LDAP password revert failed -- connection may require manual repair [connection=${connection.name}]`
+ );
+ }
+ throw verifyError;
+ }
logger.info(`credentialRotation: LDAP credential rotation succeeded [connection=${connection.name}]`);