Skip to content

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

fix(pam): rotation-lock safety, local verify, and second-round review fixes

bernie-g3b9d19763a81
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 36af294ffe..75bdc78178 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
@@ -157,6 +157,23 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
const DEPENDENCY_SYNC_CONCURRENCY = 5;
+ // The account-rotation phase (recovery probe + apply + verify) is bounded by a handful of WinRM/LDAP calls,
+ // each capped at the RPC deadline; this TTL covers the worst-case pile-up so the lock can't expire mid-run.
+ const ROTATION_LOCK_TTL_MS = 15 * 60 * 1000;
+
+ // Everything needed to run dependency sync after the account rotation commits (and after the lock releases).
+ type TPostRotate = {
+ accountId: string;
+ projectId: string;
+ accountType: PamAccountType;
+ connectionDetails: Record<string, unknown>;
+ targetUsername: string;
+ newPassword: string;
+ connectAuth: { username: string; password: string };
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ };
+
// 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.
@@ -170,17 +187,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
connectAuth,
gatewayId,
gatewayPoolId
- }: {
- accountId: string;
- projectId: string;
- accountType: PamAccountType;
- connectionDetails: Record<string, unknown>;
- targetUsername: string;
- newPassword: string;
- connectAuth: { username: string; password: string };
- gatewayId?: string | null;
- gatewayPoolId?: string | null;
- }) => {
+ }: TPostRotate) => {
// Dependencies are detected for both domain (WindowsAd) and local (Windows) accounts.
if (!isWindowsRotatableType(accountType)) return;
@@ -326,7 +333,9 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
};
};
- const rotateWithinLock = async (account: TPamAccountDetail) => {
+ // Runs the account rotation under the per-account lock and returns the postRotate work (or null when nothing
+ // to sync); dependency sync itself runs outside the lock (see performRotation).
+ const rotateWithinLock = async (account: TPamAccountDetail): Promise<TPostRotate | null> => {
const projectId = account.projectId as string;
const accountType = account.accountType as PamAccountType;
@@ -351,23 +360,24 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
const gatewayPoolId = account.gatewayPoolId ?? account.templateGatewayPoolId;
const now = new Date();
- if (account.rotationAccountId !== account.id) {
- const rotator = await pamAccountDAL.findByIdWithDetails(account.rotationAccountId);
- if (!rotator || rotator.projectId !== projectId) {
- throw new BadRequestError({ message: "Rotation account no longer exists" });
- }
- const rotatorConnection = resolveConnectionDetails(
- accountType,
- await decrypt(projectId, rotator.encryptedConnectionDetails)
- );
- assertRotatorSameResource(accountType, rotatorConnection, connectionDetails);
- }
+ // Resolve the rotator (self or delegated) up front: its identity is needed to apply the change and, for a
+ // delegated local account, to verify the credential on the box (the account itself can't be logged in as).
+ const isDelegated = account.rotationAccountId !== account.id;
+ const {
+ auth,
+ connectionDetails: rotatorConnectionDetails,
+ gatewayId: rotatorGatewayId,
+ gatewayPoolId: rotatorGatewayPoolId
+ } = await resolveRotator(account, targetCredentials, connectionDetails, { gatewayId, gatewayPoolId });
+ if (isDelegated) assertRotatorSameResource(accountType, rotatorConnectionDetails, connectionDetails);
+ // A delegated local account can't be logged in as to verify, so validate via the admin rotator instead.
+ const verifyVia = isDelegated && accountType === PamAccountType.Windows ? auth : undefined;
// Recovery from an interrupted rotation: probe the candidate then the current credential, acting only on a
// definitive answer so a transient failure never discards a possibly-live credential.
if (account.encryptedPendingCredentials) {
const pending = await decryptSqlCredentials(projectId, accountType, account.encryptedPendingCredentials);
- const gatewayTarget = { accountType, connectionDetails, gatewayId, gatewayPoolId };
+ const gatewayTarget = { accountType, connectionDetails, gatewayId, gatewayPoolId, verifyVia };
const pendingWorks = await handler.testCredential(
{ ...gatewayTarget, auth: { username: targetUsername, password: pending.password ?? "" } },
@@ -375,7 +385,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
);
if (pendingWorks) {
await markRotated(account, account.encryptedPendingCredentials, now);
- return;
+ return null;
}
const currentPassword = targetCredentials.password;
@@ -393,12 +403,6 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
await pamAccountDAL.updateById(account.id, { encryptedPendingCredentials: null });
}
- const {
- auth,
- connectionDetails: rotatorConnectionDetails,
- gatewayId: rotatorGatewayId,
- gatewayPoolId: rotatorGatewayPoolId
- } = await resolveRotator(account, targetCredentials, connectionDetails, { gatewayId, gatewayPoolId });
const requirements = getPasswordRequirements(account.templateSettings);
const newPassword = generatePassword(requirements);
const encryptedPending = await encrypt(projectId, { ...targetCredentials, password: newPassword });
@@ -406,29 +410,28 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
// Stage before applying, so an apply interrupted mid-change leaves a credential the recovery probe can promote.
await pamAccountDAL.updateById(account.id, { encryptedPendingCredentials: encryptedPending });
- try {
- await handler.applyPasswordChange(
- {
- accountType,
- connectionDetails: rotatorConnectionDetails,
- auth,
- targetUsername,
- newPassword,
- gatewayId: rotatorGatewayId,
- gatewayPoolId: rotatorGatewayPoolId
- },
- gatewayDeps
- );
- } catch (err) {
- await pamAccountDAL.updateById(account.id, { encryptedPendingCredentials: null });
- throw err;
- }
+ // Do NOT discard pending on an apply error: a WinRM/gateway apply can succeed on the host after the client
+ // deadline fires, and for a self-rotating account pending is the only copy of the now-live password. The
+ // recovery probe resolves genuine-failure vs ambiguous-success on the next run.
+ await handler.applyPasswordChange(
+ {
+ accountType,
+ connectionDetails: rotatorConnectionDetails,
+ auth,
+ targetUsername,
+ newPassword,
+ gatewayId: rotatorGatewayId,
+ gatewayPoolId: rotatorGatewayPoolId
+ },
+ gatewayDeps
+ );
const verified = await handler.testCredential(
{
accountType,
connectionDetails,
auth: { username: targetUsername, password: newPassword },
+ verifyVia,
gatewayId,
gatewayPoolId
},
@@ -441,26 +444,19 @@ 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,
- connectionDetails,
- 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}]`);
- }
+ return {
+ accountId: account.id,
+ projectId,
+ accountType,
+ connectionDetails,
+ 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: isDelegated ? auth : { username: auth.username, password: newPassword },
+ gatewayId,
+ gatewayPoolId
+ };
};
// Advance nextRotationAt to a capped retry, but only when the account is schedulable: a ready account's early
@@ -494,19 +490,35 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
const performRotation = async (account: TPamAccountDetail) => {
let lock: Awaited<ReturnType<typeof keyStore.acquireLock>>;
try {
- // TTL must exceed the worst-case rotation (recovery probe + apply + verify) so it can't expire mid-rotation.
- lock = await keyStore.acquireLock([KeyStorePrefixes.PamAccountRotationLock(account.id)], 5 * 60 * 1000);
+ lock = await keyStore.acquireLock([KeyStorePrefixes.PamAccountRotationLock(account.id)], ROTATION_LOCK_TTL_MS);
} catch {
// Held lock: another run owns the schedule bookkeeping, so don't record a failure here.
throw new BadRequestError({ message: ROTATION_IN_PROGRESS_MESSAGE });
}
+ let postRotate: TPostRotate | null = null;
try {
- await rotateWithinLock(account);
+ postRotate = await rotateWithinLock(account);
} catch (err) {
await recordRotationFailure(account, err);
throw err;
} finally {
- await lock.release();
+ // A long rotation can outlive the TTL; releasing an expired lock throws, so tolerate it rather than
+ // report a rotation that actually succeeded as failed.
+ try {
+ await lock.release();
+ } catch (err) {
+ logger.warn(err, `PAM rotation lock release failed [accountId=${account.id}]`);
+ }
+ }
+
+ // Dependency sync runs OUTSIDE the lock: it can fan out to many machines (unbounded) and must not hold the
+ // per-account lock long enough to expire. Best-effort; the account rotation is already committed.
+ if (postRotate) {
+ try {
+ await syncDependenciesAfterRotation(postRotate);
+ } catch (err) {
+ logger.warn(err, `PAM dependency sync errored after rotation [accountId=${account.id}]`);
+ }
}
};
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 977983ac26..4912b0c36e 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
@@ -32,6 +32,9 @@ type TTestCredentialInput = {
accountType: TRotatableType;
connectionDetails: Record<string, unknown>;
auth: { username: string; password: string };
+ // When set, the credential in `auth` can't be authenticated as directly (a delegated local Windows account
+ // that can't log in over WinRM), so connect as this identity (the admin rotator) and validate on the box.
+ verifyVia?: { username: string; password: string };
gatewayId?: string | null;
gatewayPoolId?: string | null;
};
@@ -218,9 +221,10 @@ const windowsRotationHandler: TPamRotationHandler = {
},
testCredential: async (input, deps) => {
- const { accountType, connectionDetails, auth, gatewayId, gatewayPoolId } = input;
+ const { accountType, connectionDetails, auth, verifyVia, gatewayId, gatewayPoolId } = input;
try {
const resolvedGatewayId = await resolveRotationGatewayId(deps, gatewayId, gatewayPoolId);
+ const transport = winrmTransportFromConn(connectionDetails);
if (accountType === PamAccountType.WindowsAd) {
// A domain service account usually can't WinRM to the DC, but an LDAP bind needs only the credential.
@@ -246,14 +250,32 @@ const windowsRotationHandler: TPamRotationHandler = {
);
}
- // Local account: prove the credential over WinRM against its own host.
+ const targetHost = winrmRotationTargetHost(accountType, connectionDetails);
+ const targetPort = winrmPortFromConn(connectionDetails);
+
+ // Delegated local rotation: the target account usually can't WinRM in, so the rotator (admin) validates
+ // the credential on the box instead of us trying to log in as the account.
+ if (verifyVia) {
+ const { valid } = await winrmRpcWithGateway<{ valid: boolean }>({
+ targetHost,
+ targetPort,
+ gatewayId: resolvedGatewayId,
+ gatewayV2Service: deps.gatewayV2Service,
+ endpoint: WinRmRpcEndpoint.ValidateCredential,
+ credentials: { username: verifyVia.username, password: verifyVia.password, ...transport },
+ params: { targetUsername: toBareAccountName(auth.username), password: auth.password }
+ });
+ return valid;
+ }
+
+ // Self-rotation: the account can log in (that's how it applied the change), so prove the credential directly.
await winrmRpcWithGateway<{ ok: boolean }>({
- targetHost: winrmRotationTargetHost(accountType, connectionDetails),
- targetPort: winrmPortFromConn(connectionDetails),
+ targetHost,
+ targetPort,
gatewayId: resolvedGatewayId,
gatewayV2Service: deps.gatewayV2Service,
endpoint: WinRmRpcEndpoint.Test,
- credentials: { username: auth.username, password: auth.password, ...winrmTransportFromConn(connectionDetails) }
+ credentials: { username: auth.username, password: auth.password, ...transport }
});
return true;
} catch {
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
index f2cd84bc59..69b0eac700 100644
--- a/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts
+++ b/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts
@@ -59,13 +59,16 @@ export const pamAccountDependencyDALFactory = (db: TDbClient) => {
): Promise<void> => {
if (!scannedMachines.length || (!accountIds.length && !discoveredAccountIds.length)) return;
+ // Bind each list as a single array parameter (`= ANY(?)`) rather than one bind per element, so a large
+ // domain can't blow past Postgres's 65,535 bind-parameter cap and fail the reconcile after upserts wrote.
await (tx || db)(TableName.PamAccountDependency)
- .whereIn("machine", scannedMachines)
+ .whereRaw(`"machine" = ANY(?::text[])`, [scannedMachines])
.where((qb) => {
- if (accountIds.length) void qb.whereIn("accountId", accountIds);
- if (discoveredAccountIds.length) void qb.orWhereIn("discoveredAccountId", discoveredAccountIds);
+ if (accountIds.length) void qb.whereRaw(`"accountId" = ANY(?::uuid[])`, [accountIds]);
+ if (discoveredAccountIds.length)
+ void qb.orWhereRaw(`"discoveredAccountId" = ANY(?::uuid[])`, [discoveredAccountIds]);
})
- .whereNotIn("id", keepIds)
+ .whereRaw(`NOT ("id" = ANY(?::uuid[]))`, [keepIds])
.delete();
};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts
index fd31a473c0..f9fe4703ad 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts
@@ -47,5 +47,12 @@ export const pamDiscoveredAccountDALFactory = (db: TDbClient) => {
return { accounts, totalCount: Number(countResult?.count ?? 0) };
};
- return { ...orm, upsertByFingerprint, listStaged };
+ // Just the columns needed to map a run-as fingerprint to its account, without pulling every row's
+ // encryptedDetails buffer into memory (a large domain can have tens of thousands of discovered accounts).
+ const findFingerprintLinks = async (discoverySourceId: string, tx?: Knex) =>
+ (tx || db.replicaNode())(TableName.PamDiscoveredAccount)
+ .where({ discoverySourceId })
+ .select("id", "fingerprint", "importedAccountId");
+
+ return { ...orm, upsertByFingerprint, listStaged, findFingerprintLinks };
};
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 c6daa188a3..a4a2b9156b 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
@@ -125,8 +125,11 @@ export const ldapBindCheckViaGateway = async (
},
gatewayId: string,
gatewayV2Service: TGatewayDep
-): Promise<boolean> =>
- executeWithGateway(
+): Promise<boolean> => {
+ // An empty password is an LDAP unauthenticated bind, which AD accepts as anonymous success, so it would
+ // falsely verify a nonexistent credential. Never let an empty password count as valid.
+ if (!password) return Promise.resolve(false);
+ return executeWithGateway(
dcAddress,
port,
gatewayId,
@@ -163,6 +166,7 @@ export const ldapBindCheckViaGateway = async (
client.bind(bindDn, password, (err) => done(!err));
})
);
+};
export type TWinRmGatewayCredentials = {
username: string;
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 0e72eb13e1..c19a007fdf 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
@@ -472,7 +472,7 @@ 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 sourceAccounts = await pamDiscoveredAccountDAL.findFingerprintLinks(sourceId);
const accountByFingerprint = new Map(
sourceAccounts.map((a) => [
a.fingerprint,
diff --git a/backend/src/lib/gateway-v2/winrm-rpc.ts b/backend/src/lib/gateway-v2/winrm-rpc.ts
index 29fabc3030..225244b41b 100644
--- a/backend/src/lib/gateway-v2/winrm-rpc.ts
+++ b/backend/src/lib/gateway-v2/winrm-rpc.ts
@@ -9,7 +9,8 @@ export enum WinRmRpcEndpoint {
EnumerateAccounts = "/v1/enumerate-accounts",
EnumerateDependencies = "/v1/enumerate-dependencies",
RotateCredential = "/v1/rotate-credential",
- SyncDependency = "/v1/sync-dependency"
+ SyncDependency = "/v1/sync-dependency",
+ ValidateCredential = "/v1/validate-credential"
}
export type WinRmTransportParams = {
diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.ts
index ac66639554..c7ea53e713 100644
--- a/frontend/src/hooks/api/pam/enums.ts
+++ b/frontend/src/hooks/api/pam/enums.ts
@@ -36,9 +36,9 @@ export const ROTATABLE_PAM_ACCOUNT_TYPES = [
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.
+// Windows accounts (domain and local) are the ones whose run-as dependencies discovery detects and syncs.
export const supportsPamDependencies = (type: PamAccountType | string) =>
- type === PamAccountType.WindowsAd;
+ type === PamAccountType.WindowsAd || type === PamAccountType.Windows;
export const PAM_ROTATION_INTERVAL_OPTIONS: { seconds: number; label: string }[] = [
{ seconds: 3600, label: "1 hour" },
diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx
index 9b3fc1835f..9182d216cb 100644
--- a/frontend/src/hooks/api/pam/mutations.tsx
+++ b/frontend/src/hooks/api/pam/mutations.tsx
@@ -788,6 +788,8 @@ export const useRotatePamAccount = () => {
onSettled: (_, __, { accountId }) => {
queryClient.invalidateQueries({ queryKey: pamKeys.accountRotation(accountId) });
queryClient.invalidateQueries({ queryKey: pamKeys.getAccount(accountId) });
+ // Dependency sync runs as part of rotation, so refresh the Dependencies tab's badges too.
+ queryClient.invalidateQueries({ queryKey: pamKeys.accountDependencies(accountId) });
}
});
};