Skip to content

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

PAM rotation revamp

Carlos Monastyrskic3474b6e6187
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index ad8c731cb2..024ec849a6 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -36,6 +36,7 @@ import { TLicenseServiceFactory } from "@app/ee/services/license/license-service
import { TLicenseV2ServiceFactory } from "@app/ee/services/license-v2/license-v2-service";
import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
import { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
+import { TPamAccountRotationServiceFactory } from "@app/ee/services/pam-account-rotation/pam-account-rotation-service";
import { TPamAccountTemplateServiceFactory } from "@app/ee/services/pam-account-template/pam-account-template-service";
import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";
import { TPamMembershipServiceFactory } from "@app/ee/services/pam-membership/pam-membership-service";
@@ -428,6 +429,7 @@ declare module "fastify" {
pamAccountTemplate: TPamAccountTemplateServiceFactory;
pamFolder: TPamFolderServiceFactory;
pamAccount: TPamAccountServiceFactory;
+ pamAccountRotation: TPamAccountRotationServiceFactory;
pamMembership: TPamMembershipServiceFactory;
pamSession: TPamSessionServiceFactory;
pamSessionChunk: TPamSessionChunkServiceFactory;
diff --git a/backend/src/db/migrations/20260701093214_pam-credential-rotation.ts b/backend/src/db/migrations/20260701093214_pam-credential-rotation.ts
new file mode 100644
index 0000000000..48bf99c117
--- /dev/null
+++ b/backend/src/db/migrations/20260701093214_pam-credential-rotation.ts
@@ -0,0 +1,54 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const NEXT_ROTATION_AT_INDEX = "pam_accounts_next_rotation_at_index";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasRotationAccountId = await knex.schema.hasColumn(TableName.PamAccount, "rotationAccountId");
+ const hasNextRotationAt = await knex.schema.hasColumn(TableName.PamAccount, "nextRotationAt");
+ const hasEncryptedPendingCredentials = await knex.schema.hasColumn(
+ TableName.PamAccount,
+ "encryptedPendingCredentials"
+ );
+
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ if (!hasRotationAccountId) {
+ // RESTRICT so an account referenced as a rotation account cannot be deleted out from under its dependents.
+ t.uuid("rotationAccountId").nullable();
+ t.foreign("rotationAccountId").references("id").inTable(TableName.PamAccount).onDelete("RESTRICT");
+ t.index(["rotationAccountId"]);
+ }
+ if (!hasNextRotationAt) {
+ t.datetime("nextRotationAt").nullable();
+ // Partial index: the finder only scans due, scheduled rows.
+ t.index(["nextRotationAt"], NEXT_ROTATION_AT_INDEX, { predicate: knex.whereNotNull("nextRotationAt") });
+ }
+ if (!hasEncryptedPendingCredentials) {
+ // Staged new credential held until the change is confirmed on the target, then promoted.
+ t.binary("encryptedPendingCredentials").nullable();
+ }
+ });
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasRotationAccountId = await knex.schema.hasColumn(TableName.PamAccount, "rotationAccountId");
+ const hasNextRotationAt = await knex.schema.hasColumn(TableName.PamAccount, "nextRotationAt");
+ const hasEncryptedPendingCredentials = await knex.schema.hasColumn(
+ TableName.PamAccount,
+ "encryptedPendingCredentials"
+ );
+
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ if (hasNextRotationAt) {
+ t.dropIndex(["nextRotationAt"], NEXT_ROTATION_AT_INDEX);
+ t.dropColumn("nextRotationAt");
+ }
+ if (hasRotationAccountId) {
+ t.dropColumn("rotationAccountId");
+ }
+ if (hasEncryptedPendingCredentials) {
+ t.dropColumn("encryptedPendingCredentials");
+ }
+ });
+}
diff --git a/backend/src/db/schemas/pam-accounts.ts b/backend/src/db/schemas/pam-accounts.ts
index 4c76d3fc88..a728d0aa08 100644
--- a/backend/src/db/schemas/pam-accounts.ts
+++ b/backend/src/db/schemas/pam-accounts.ts
@@ -34,7 +34,10 @@ export const PamAccountsSchema = z.object({
gatewayPoolId: z.string().uuid().nullable().optional(),
recordingConnectionId: z.string().uuid().nullable().optional(),
settingsOverrides: z.unknown().nullable().optional(),
- credentialConfigured: z.boolean().default(false)
+ credentialConfigured: z.boolean().default(false),
+ rotationAccountId: z.string().uuid().nullable().optional(),
+ nextRotationAt: z.date().nullable().optional(),
+ encryptedPendingCredentials: zodBuffer.nullable().optional()
});
export type TPamAccounts = z.infer<typeof PamAccountsSchema>;
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 404c2cfd14..3d77eddb4d 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
@@ -9,12 +9,15 @@ import {
PamAccountAccessibilityIssue,
PamAccountTypeMetadataSchema
} from "@app/ee/services/pam-account/pam-account-schemas";
+import { ROTATION_STATUS } from "@app/ee/services/pam-account-rotation/pam-account-rotation-service";
import {
PamAccountSettingsOverridesSchema,
PamTemplateSettingsSchema
} from "@app/ee/services/pam-account-template/pam-account-template-schemas";
import { SESSION_HANDLERS } from "@app/ee/services/pam-web-access/pam-session-handlers";
+import { PasswordRequirementsSchema } from "@app/ee/services/secret-rotation-v2/shared/general/password-requirements-schema";
import { ApiDocsTags } from "@app/lib/api-docs/constants";
+import { BadRequestError } from "@app/lib/errors";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
@@ -462,6 +465,166 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
}
});
+ const RotationViewSchema = z.object({
+ enabled: z.boolean(),
+ intervalSeconds: z.number().nullable(),
+ passwordRequirements: PasswordRequirementsSchema.nullable(),
+ rotationAccountId: z.string().nullable(),
+ rotationAccountName: z.string().nullable(),
+ lastRotatedAt: z.date().nullable(),
+ isReady: z.boolean()
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:accountId/rotation",
+ schema: {
+ operationId: "getPamAccountRotation",
+ description: "Get the credential rotation config and state for a PAM account",
+ tags: [ApiDocsTags.PamAccounts],
+ params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
+ response: { 200: z.object({ rotation: RotationViewSchema }) }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const rotation = await server.services.pamAccountRotation.getRotation({
+ accountId: req.params.accountId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ return { rotation };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:accountId/rotation",
+ schema: {
+ operationId: "setPamAccountRotationAccount",
+ description: "Set or clear the rotation account for a PAM account",
+ tags: [ApiDocsTags.PamAccounts],
+ params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
+ body: z.object({
+ rotationAccountId: z
+ .string()
+ .uuid()
+ .nullable()
+ .describe("Account that performs the rotation. Its own id for self-rotation, or null to clear")
+ }),
+ response: { 200: z.object({ rotationAccountId: z.string().nullable() }) }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pamAccountRotation.setRotationAccount({
+ accountId: req.params.accountId,
+ rotationAccountId: req.body.rotationAccountId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalPamProjectId,
+ event: {
+ type: EventType.PAM_ACCOUNT_SET_ROTATION_ACCOUNT,
+ metadata: { accountId: req.params.accountId, rotationAccountId: result.rotationAccountId }
+ }
+ });
+
+ return result;
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:accountId/rotation/rotate",
+ schema: {
+ operationId: "rotatePamAccountCredentials",
+ description: "Rotate a PAM account's credential now",
+ tags: [ApiDocsTags.PamAccounts],
+ params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
+ response: { 200: z.object({ rotationStatus: z.string() }) }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pamAccountRotation.rotateNow({
+ accountId: req.params.accountId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalPamProjectId,
+ event: {
+ type: EventType.PAM_ACCOUNT_ROTATE_CREDENTIALS,
+ metadata: {
+ accountId: req.params.accountId,
+ accountType: result.accountType,
+ rotationStatus: result.rotationStatus,
+ manual: true,
+ rotationAccountId: result.rotationAccountId,
+ ...(result.message ? { message: result.message } : {})
+ }
+ }
+ });
+
+ // Audited above first, so a failed rotation is logged before the request errors.
+ if (result.rotationStatus !== ROTATION_STATUS.Success) {
+ throw new BadRequestError({ message: result.message ?? "Rotation failed" });
+ }
+ return { rotationStatus: result.rotationStatus };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:accountId/rotation/rotation-account-candidates",
+ schema: {
+ operationId: "listPamRotationAccountCandidates",
+ description: "List accounts eligible to be this account's rotation account",
+ tags: [ApiDocsTags.PamAccounts],
+ params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
+ response: {
+ 200: z.object({
+ candidates: z.array(
+ z.object({
+ folderId: z.string().nullable(),
+ folderName: z.string().nullable(),
+ accounts: z.array(z.object({ id: z.string(), name: z.string(), host: z.string() }))
+ })
+ )
+ })
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.pamAccountRotation.listRotationCandidates({
+ accountId: req.params.accountId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ }
+ });
+
server.route({
method: "GET",
url: "/:accountId",
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts
index 567eb60f99..c6fa8ab364 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts
@@ -73,7 +73,8 @@ export const registerPamAccountTemplateRouter = async (server: FastifyZodProvide
response: {
200: z.object({
template: SanitizedTemplateSchema.extend({
- accountCount: z.number()
+ accountCount: z.number(),
+ rotationImpact: z.object({ willRotate: z.number(), needsRotationAccount: z.number() })
})
})
}
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 06ed9b1e77..951760541a 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -736,6 +736,8 @@ export enum EventType {
PAM_ACCOUNT_UPDATE = "pam-account-update",
PAM_ACCOUNT_DELETE = "pam-account-delete",
PAM_ACCOUNT_SSH_CA_CREATE = "pam-account-ssh-ca-create",
+ PAM_ACCOUNT_ROTATE_CREDENTIALS = "pam-account-rotate-credentials",
+ PAM_ACCOUNT_SET_ROTATION_ACCOUNT = "pam-account-set-rotation-account",
PAM_WEB_ACCESS_SESSION_TICKET_CREATED = "pam-web-access-session-ticket-created",
APPROVAL_POLICY_CREATE = "approval-policy-create",
APPROVAL_POLICY_UPDATE = "approval-policy-update",
@@ -6068,6 +6070,26 @@ interface PamAccountSshCaCreateEvent {
};
}
+interface PamAccountRotateCredentialsEvent {
+ type: EventType.PAM_ACCOUNT_ROTATE_CREDENTIALS;
+ metadata: {
+ accountId: string;
+ accountType: string;
+ rotationStatus: string;
+ manual: boolean;
+ rotationAccountId?: string | null;
+ message?: string;
+ };
+}
+
+interface PamAccountSetRotationAccountEvent {
+ type: EventType.PAM_ACCOUNT_SET_ROTATION_ACCOUNT;
+ metadata: {
+ accountId: string;
+ rotationAccountId: string | null;
+ };
+}
+
interface UpdateCertificateRenewalConfigEvent {
type: EventType.UPDATE_CERTIFICATE_RENEWAL_CONFIG;
metadata: {
@@ -7674,6 +7696,8 @@ export type Event =
| PamAccountUpdateEvent
| PamAccountDeleteEvent
| PamAccountSshCaCreateEvent
+ | PamAccountRotateCredentialsEvent
+ | PamAccountSetRotationAccountEvent
| UpdateCertificateRenewalConfigEvent
| UpdateCertificateMetadataEvent
| DisableCertificateRenewalConfigEvent
diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-queue.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-queue.ts
new file mode 100644
index 0000000000..a3923505ab
--- /dev/null
+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-queue.ts
@@ -0,0 +1,103 @@
+import opentelemetry from "@opentelemetry/api";
+
+import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { getConfig } from "@app/lib/config/env";
+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
+import { logger } from "@app/lib/logger";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { ActorType } from "@app/services/auth/auth-type";
+
+import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
+import { TPamAccountRotationServiceFactory } from "./pam-account-rotation-service";
+
+const ROTATION_DISCOVERY_BATCH = 100;
+
+type TPamAccountRotationQueueServiceFactoryDep = {
+ queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+ pamAccountDAL: Pick<TPamAccountDALFactory, "findAccountsToRotate" | "countAccountsToRotate">;
+ pamAccountRotationService: Pick<TPamAccountRotationServiceFactory, "rotateScheduledAccount">;
+};
+
+export const pamAccountRotationQueueServiceFactory = async ({
+ queueService,
+ cronJob,
+ auditLogService,
+ pamAccountDAL,
+ pamAccountRotationService
+}: TPamAccountRotationQueueServiceFactoryDep) => {
+ const appCfg = getConfig();
+
+ const meter = opentelemetry.metrics.getMeter("InfisicalCore");
+ const pendingGauge = meter.createObservableGauge("infisical.pam_credential_rotation.pending", {
+ description: "PAM accounts overdue for rotation (nextRotationAt <= now). Sustained growth = drain can't keep up.",
+ unit: "{account}"
+ });
+ pendingGauge.addCallback(async (observableResult) => {
+ if (!appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) return;
+ try {
+ observableResult.observe(await pamAccountDAL.countAccountsToRotate(new Date()));
+ } catch (err) {
+ logger.warn({ err }, "pam_credential_rotation.pending gauge: count failed");
+ }
+ });
+
+ queueService.start(
+ QueueName.PamCredentialRotationRotate,
+ async (job) => {
+ const result = await pamAccountRotationService.rotateScheduledAccount(job.data.accountId);
+ if (result) {
+ await auditLogService.createAuditLog({
+ projectId: result.projectId,
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ event: {
+ type: EventType.PAM_ACCOUNT_ROTATE_CREDENTIALS,
+ metadata: {
+ accountId: job.data.accountId,
+ accountType: result.accountType,
+ rotationStatus: result.rotationStatus,
+ manual: false,
+ rotationAccountId: result.rotationAccountId,
+ ...(result.message ? { message: result.message } : {})
+ }
+ }
+ });
+ }
+ },
+ { concurrency: 5, limiter: { max: 5, duration: 1000 } }
+ );
+
+ queueService.start(QueueName.PamCredentialRotation, async () => {
+ const due = await pamAccountDAL.findAccountsToRotate(new Date(), ROTATION_DISCOVERY_BATCH);
+ for (const account of due) {
+ // eslint-disable-next-line no-await-in-loop
+ await queueService.queue(
+ QueueName.PamCredentialRotationRotate,
+ QueueJobs.PamCredentialRotationRotate,
+ { accountId: account.id },
+ {
+ // No attempts/backoff: failures reschedule via nextRotationAt, so BullMQ retries would only re-audit.
+ // jobId dedupes a due account that's still queued.
+ jobId: `pam-credential-rotation-${account.id}`,
+ removeOnComplete: true,
+ removeOnFail: true
+ }
+ );
+ }
+ });
+
+ cronJob.register({
+ name: CronJobName.PamCredentialRotationQueueRotations,
+ pattern: appCfg.isRotationDevelopmentMode ? "* * * * *" : "*/5 * * * *",
+ runHashTtlS: 30 * 60,
+ handler: async () => {
+ await queueService.queue(
+ QueueName.PamCredentialRotation,
+ QueueJobs.PamCredentialRotationQueueRotations,
+ undefined,
+ { jobId: CronJobName.PamCredentialRotationQueueRotations }
+ );
+ }
+ });
+};
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
new file mode 100644
index 0000000000..9a3a5776d4
--- /dev/null
+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts
@@ -0,0 +1,525 @@
+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";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { ResourcePermissionPamResourceActions } from "@app/ee/services/permission/resource-permission";
+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 { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+
+import { PamAccountType } from "../pam/pam-enums";
+import { checkAccountAccess, getResourceIdsWithActions, TActorContext } from "../pam/pam-permission";
+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 {
+ TGetPamAccountRotationDTO,
+ TListPamRotationCandidatesDTO,
+ TPamAccountRotationView,
+ TRotatePamAccountDTO,
+ TSetPamRotationAccountDTO
+} from "./pam-account-rotation-types";
+import {
+ computeNextRotationAt,
+ getRotationReadiness,
+ isRotatableAccountType,
+ PamRotationReadinessIssue,
+ 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;
+
+const ROTATION_IN_PROGRESS_MESSAGE = "A rotation is already in progress for this account";
+
+const ROTATION_NOT_READY_MESSAGE: Record<PamRotationReadinessIssue, string> = {
+ [PamRotationReadinessIssue.RotationDisabled]: "Rotation is not enabled for this account's template",
+ [PamRotationReadinessIssue.UnsupportedType]: "Rotation is not supported for this account type",
+ [PamRotationReadinessIssue.NotConfigured]: "No rotation account is configured for this account",
+ [PamRotationReadinessIssue.SelfRotationNoCredential]:
+ "This account has no stored credential to rotate its own password"
+};
+
+type TPamAccountRotationServiceFactoryDep = {
+ pamAccountDAL: Pick<
+ TPamAccountDALFactory,
+ | "findById"
+ | "findByIdWithDetails"
+ | "updateById"
+ | "findRotationCandidates"
+ | "reconcileRotationScheduleForAccount"
+ | "transaction"
+ >;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
+ membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ keyStore: Pick<TKeyStoreFactory, "acquireLock">;
+ gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+};
+
+export type TPamAccountRotationServiceFactory = ReturnType<typeof pamAccountRotationServiceFactory>;
+
+export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServiceFactoryDep) => {
+ const {
+ pamAccountDAL,
+ permissionService,
+ membershipDAL,
+ membershipRoleDAL,
+ kmsService,
+ keyStore,
+ gatewayService,
+ gatewayV2Service,
+ gatewayPoolService
+ } = deps;
+
+ const gatewayDeps = { gatewayService, gatewayV2Service, gatewayPoolService };
+
+ const getProjectCipher = (projectId: string) =>
+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
+
+ const encrypt = async (projectId: string, data: Record<string, unknown>) => {
+ const { encryptor } = await getProjectCipher(projectId);
+ return encryptor({ plainText: Buffer.from(JSON.stringify(data)) }).cipherTextBlob;
+ };
+
+ const decrypt = async (projectId: string, blob: Buffer): Promise<Record<string, unknown>> => {
+ const { decryptor } = await getProjectCipher(projectId);
+ return JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>;
+ };
+
+ type TSqlAccountCredentials = { username: string; password?: string; authMethod?: string };
+
+ const decryptSqlCredentials = async (
+ projectId: string,
+ accountType: PamAccountType,
+ blob: Buffer
+ ): Promise<TSqlAccountCredentials> =>
+ validateCredentials(accountType, await decrypt(projectId, blob)) as TSqlAccountCredentials;
+
+ const checkAccount = (
+ accountId: string,
+ folderId: string | null | undefined,
+ projectId: string,
+ action: ResourcePermissionPamResourceActions,
+ ctx: TActorContext
+ ) => checkAccountAccess(permissionService, accountId, folderId, projectId, action, ctx);
+
+ const getRotationConfig = (templateSettings: unknown) =>
+ PamTemplateSettingsSchema.safeParse(templateSettings).data?.rotation;
+
+ const getPasswordRequirements = (templateSettings: unknown) =>
+ PamTemplateSettingsSchema.safeParse(templateSettings).data?.passwordRequirements;
+
+ const nextRotationAfter = (templateSettings: unknown, now: Date): Date | null => {
+ const rotation = getRotationConfig(templateSettings);
+ if (!rotation?.enabled) return null;
+ return computeNextRotationAt({ anchor: now, intervalSeconds: rotation.intervalSeconds, now });
+ };
+
+ const markRotated = (account: TPamAccountDetail, encryptedBlob: Buffer, now: Date) =>
+ pamAccountDAL.updateById(account.id, {
+ encryptedCredentials: encryptedBlob,
+ encryptedPendingCredentials: null,
+ credentialConfigured: true,
+ lastRotatedAt: now,
+ rotationStatus: ROTATION_STATUS.Success,
+ encryptedLastRotationMessage: null,
+ nextRotationAt: nextRotationAfter(account.templateSettings, now)
+ });
+
+ const toSqlConnectionDetails = (
+ accountType: PamAccountType,
+ raw: Record<string, unknown>
+ ): TPamSqlConnectionDetails => validateConnectionDetails(accountType, raw) as TPamSqlConnectionDetails;
+
+ const resolveAuthCredential = async (
+ account: TPamAccountDetail,
+ targetCredentials: TSqlAccountCredentials
+ ): Promise<{ username: string; password: string }> => {
+ const projectId = account.projectId as string;
+
+ if (account.rotationAccountId === account.id) {
+ if (!targetCredentials.password) {
+ throw new BadRequestError({ message: "Account has no stored password to self-rotate" });
+ }
+ return { username: targetCredentials.username, password: targetCredentials.password };
+ }
+
+ const rotator = await pamAccountDAL.findById(account.rotationAccountId as string);
+ if (!rotator || rotator.projectId !== projectId) {
+ throw new BadRequestError({ message: "Rotation account no longer exists" });
+ }
+ // Rotator is enforced same-type as the target at set time, so validate with the target's type.
+ const rotatorCredentials = await decryptSqlCredentials(
+ projectId,
+ account.accountType as PamAccountType,
+ rotator.encryptedCredentials
+ );
+ if (!rotatorCredentials.password) {
+ throw new BadRequestError({ message: "Rotation account has no stored password" });
+ }
+ return { username: rotatorCredentials.username, password: rotatorCredentials.password };
+ };
+
+ const rotateWithinLock = async (account: TPamAccountDetail) => {
+ const projectId = account.projectId as string;
+ const accountType = account.accountType as PamAccountType;
+
+ if (!isRotatableAccountType(accountType)) {
+ throw new BadRequestError({ message: `Rotation is not supported for ${accountType} accounts` });
+ }
+ if (!account.rotationAccountId) {
+ throw new BadRequestError({ message: "No rotation account configured for this account" });
+ }
+
+ const targetCredentials = await decryptSqlCredentials(projectId, accountType, account.encryptedCredentials);
+ const targetUsername = targetCredentials.username;
+ const handler = PAM_ROTATION_FACTORY_MAP[accountType];
+
+ handler.validateTarget({ accountType, authMethod: targetCredentials.authMethod });
+
+ const connectionDetails = toSqlConnectionDetails(
+ accountType,
+ await decrypt(projectId, account.encryptedConnectionDetails)
+ );
+ const gatewayId = account.gatewayId ?? account.templateGatewayId;
+ const gatewayPoolId = account.gatewayPoolId ?? account.templateGatewayPoolId;
+ const now = new Date();
+
+ // 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 pendingWorks = await handler.testCredential(
+ { ...gatewayTarget, auth: { username: targetUsername, password: pending.password ?? "" } },
+ gatewayDeps
+ );
+ if (pendingWorks) {
+ await markRotated(account, account.encryptedPendingCredentials, now);
+ return;
+ }
+
+ const currentPassword = targetCredentials.password;
+ const currentWorks = currentPassword
+ ? await handler.testCredential(
+ { ...gatewayTarget, auth: { username: targetUsername, password: currentPassword } },
+ gatewayDeps
+ )
+ : false;
+ if (!currentWorks && currentPassword) {
+ // Both credentials exist but neither authenticates: defer rather than risk discarding a live one. A
+ // delegated target (no stored current password) instead falls through, since its rotator re-sets below.
+ throw new BadRequestError({ message: "Could not verify account credentials; rotation deferred" });
+ }
+ await pamAccountDAL.updateById(account.id, { encryptedPendingCredentials: null });
+ }
+
+ const auth = await resolveAuthCredential(account, targetCredentials);
+ const requirements = getPasswordRequirements(account.templateSettings);
+ const newPassword = generatePassword(requirements);
+ const encryptedPending = await encrypt(projectId, { ...targetCredentials, password: newPassword });
+
+ // 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, auth, targetUsername, newPassword, gatewayId, gatewayPoolId },
+ gatewayDeps
+ );
+ } catch (err) {
+ await pamAccountDAL.updateById(account.id, { encryptedPendingCredentials: null });
+ throw err;
+ }
+
+ const verified = await handler.testCredential(
+ {
+ accountType,
+ connectionDetails,
+ auth: { username: targetUsername, password: newPassword },
+ gatewayId,
+ gatewayPoolId
+ },
+ gatewayDeps
+ );
+ if (!verified) {
+ // Applied but unconfirmed: keep the candidate staged (don't discard) so the next probe can promote it.
+ throw new BadRequestError({ message: "Password was changed on the target but could not be verified" });
+ }
+
+ await markRotated(account, encryptedPending, now);
+ };
+
+ // Advance nextRotationAt to a capped retry, but only when the account is schedulable: a ready account's early
+ // failure still can't be re-selected on every cron tick, and a not-ready account is never given a due-date it
+ // cannot act on.
+ const recordRotationFailure = async (account: TPamAccountDetail, err: unknown) => {
+ const projectId = account.projectId as string;
+ const rotation = getRotationConfig(account.templateSettings);
+ const now = new Date();
+ const { ready } = getRotationReadiness({
+ accountId: account.id,
+ accountType: account.accountType,
+ rotationAccountId: account.rotationAccountId,
+ credentialConfigured: account.credentialConfigured,
+ templateSettings: account.templateSettings
+ });
+ const nextRotationAt =
+ ready && rotation?.enabled
+ ? computeNextRotationAt({
+ anchor: now,
+ intervalSeconds: Math.min(rotation.intervalSeconds, ROTATION_FAILURE_RETRY_CAP_SECONDS),
+ now
+ })
+ : null;
+ await pamAccountDAL.updateById(account.id, {
+ rotationStatus: ROTATION_STATUS.Failed,
+ encryptedLastRotationMessage: await encrypt(projectId, { message: (err as Error).message }),
+ nextRotationAt
+ });
+ };
+
+ 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);
+ } catch {
+ // Held lock: another run owns the schedule bookkeeping, so don't record a failure here.
+ throw new BadRequestError({ message: ROTATION_IN_PROGRESS_MESSAGE });
+ }
+ try {
+ await rotateWithinLock(account);
+ } catch (err) {
+ await recordRotationFailure(account, err);
+ throw err;
+ } finally {
+ await lock.release();
+ }
+ };
+
+ const loadAccount = async (accountId: string, projectId: string): Promise<TPamAccountDetail> => {
+ const account = await pamAccountDAL.findByIdWithDetails(accountId);
+ if (!account || account.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
+ }
+ return account;
+ };
+
+ const getRotation = async ({
+ accountId,
+ projectId,
+ ...ctx
+ }: TGetPamAccountRotationDTO & TActorContext): Promise<TPamAccountRotationView> => {
+ const account = await loadAccount(accountId, projectId);
+ await checkAccount(accountId, account.folderId, projectId, ResourcePermissionPamResourceActions.ReadAccounts, ctx);
+
+ const settings = PamTemplateSettingsSchema.safeParse(account.templateSettings).data;
+ const readiness = getRotationReadiness({
+ accountId: account.id,
+ accountType: account.accountType,
+ rotationAccountId: account.rotationAccountId,
+ credentialConfigured: account.credentialConfigured,
+ templateSettings: account.templateSettings
+ });
+
+ let rotationAccountName: string | null = null;
+ if (account.rotationAccountId === account.id) {
+ rotationAccountName = account.name;
+ } else if (account.rotationAccountId) {
+ const rotator = await pamAccountDAL.findById(account.rotationAccountId);
+ rotationAccountName = rotator?.name ?? null;
+ }
+
+ return {
+ enabled: settings?.rotation?.enabled ?? false,
+ intervalSeconds: settings?.rotation?.intervalSeconds ?? null,
+ passwordRequirements: settings?.passwordRequirements ?? null,
+ rotationAccountId: account.rotationAccountId ?? null,
+ rotationAccountName,
+ lastRotatedAt: account.lastRotatedAt ?? null,
+ isReady: readiness.ready
+ };
+ };
+
+ const setRotationAccount = async ({
+ accountId,
+ rotationAccountId,
+ projectId,
+ ...ctx
+ }: TSetPamRotationAccountDTO & TActorContext) => {
+ const account = await loadAccount(accountId, projectId);
+ await checkAccount(
+ accountId,
+ account.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.ManageRotation,
+ ctx
+ );
+
+ if (!isRotatableAccountType(account.accountType)) {
+ throw new BadRequestError({ message: "Credential rotation is not supported for this account type" });
+ }
+
+ if (rotationAccountId && rotationAccountId !== accountId) {
+ const rotator = await pamAccountDAL.findByIdWithDetails(rotationAccountId);
+ if (!rotator || rotator.projectId !== projectId) {
+ throw new BadRequestError({ message: "Rotation account not found in this project" });
+ }
+ if (rotator.accountType !== account.accountType) {
+ throw new BadRequestError({ message: "Rotation account must be the same type as this account" });
+ }
+ // 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(
+ rotationAccountId,
+ rotator.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.ViewCredentials,
+ ctx
+ );
+ }
+
+ // Set the rotation account and re-derive the schedule atomically, so a crash can't leave the account bound
+ // but unscheduled (or cleared but still scheduled).
+ await pamAccountDAL.transaction(async (tx) => {
+ await pamAccountDAL.updateById(accountId, { rotationAccountId }, tx);
+ await pamAccountDAL.reconcileRotationScheduleForAccount(accountId, tx);
+ });
+ return { rotationAccountId };
+ };
+
+ // performRotation already records the failure; report the outcome (never throw) so the caller can audit it.
+ const runRotation = async (account: TPamAccountDetail): Promise<{ rotationStatus: string; message?: string }> => {
+ try {
+ await performRotation(account);
+ return { rotationStatus: ROTATION_STATUS.Success };
+ } catch (err) {
+ const message = err instanceof BadRequestError ? err.message : `Rotation failed: ${(err as Error).message}`;
+ return { rotationStatus: ROTATION_STATUS.Failed, message };
+ }
+ };
+
+ const rotateNow = async ({
+ accountId,
+ projectId,
+ ...ctx
+ }: TRotatePamAccountDTO & TActorContext): Promise<{
+ accountType: string;
+ rotationAccountId: string | null;
+ rotationStatus: string;
+ message?: string;
+ }> => {
+ const account = await loadAccount(accountId, projectId);
+ await checkAccount(
+ accountId,
+ account.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.ManageRotation,
+ ctx
+ );
+ // Manual rotation follows the same readiness rule as the schedule, so a not-ready account can't be rotated out-of-band.
+ const readiness = getRotationReadiness({
+ accountId: account.id,
+ accountType: account.accountType,
+ rotationAccountId: account.rotationAccountId,
+ credentialConfigured: account.credentialConfigured,
+ templateSettings: account.templateSettings
+ });
+ if (!readiness.ready && readiness.issue) {
+ throw new BadRequestError({ message: ROTATION_NOT_READY_MESSAGE[readiness.issue] });
+ }
+ return {
+ accountType: account.accountType,
+ rotationAccountId: account.rotationAccountId ?? null,
+ ...(await runRotation(account))
+ };
+ };
+
+ const listRotationCandidates = async ({
+ accountId,
+ projectId,
+ ...ctx
+ }: TListPamRotationCandidatesDTO & TActorContext) => {
+ const account = await loadAccount(accountId, projectId);
+ await checkAccount(accountId, account.folderId, projectId, ResourcePermissionPamResourceActions.ReadAccounts, ctx);
+
+ const { folderIds, accountIds } = await getResourceIdsWithActions(
+ membershipDAL,
+ membershipRoleDAL,
+ projectId,
+ { allOf: [ResourcePermissionPamResourceActions.ReadAccounts] },
+ ctx
+ );
+
+ const candidates = await pamAccountDAL.findRotationCandidates(
+ projectId,
+ folderIds,
+ accountIds,
+ account.accountType
+ );
+
+ const { decryptor } = await getProjectCipher(projectId);
+ const withHost = candidates.map((candidate) => {
+ const raw = JSON.parse(
+ decryptor({ cipherTextBlob: candidate.encryptedConnectionDetails }).toString("utf-8")
+ ) as Record<string, unknown>;
+ const details = toSqlConnectionDetails(account.accountType as PamAccountType, raw);
+ return { ...candidate, host: details.host };
+ });
+
+ const groupsByFolder = new Map<
+ string,
+ { folderId: string | null; folderName: string | null; accounts: { id: string; name: string; host: string }[] }
+ >();
+ for (const candidate of withHost) {
+ const key = candidate.folderId ?? "__none__";
+ 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 });
+ }
+
+ return { candidates: Array.from(groupsByFolder.values()) };
+ };
+
+ // Re-reads state (rotation may have been disabled since enqueue); returns null when skipped.
+ const rotateScheduledAccount = async (
+ accountId: string
+ ): Promise<{
+ accountType: string;
+ projectId: string;
+ rotationAccountId: string | null;
+ rotationStatus: string;
+ message?: string;
+ } | null> => {
+ const account = await pamAccountDAL.findByIdWithDetails(accountId);
+ if (!account) return null;
+ const rotation = getRotationConfig(account.templateSettings);
+ if (!rotation?.enabled) return null;
+ const result = await runRotation(account);
+ // A concurrent run (manual, or a still-running prior tick) holds the lock; it will finish and reschedule, so
+ // skip rather than audit a spurious failure.
+ if (result.rotationStatus === ROTATION_STATUS.Failed && result.message === ROTATION_IN_PROGRESS_MESSAGE) {
+ return null;
+ }
+ return {
+ accountType: account.accountType,
+ projectId: account.projectId as string,
+ rotationAccountId: account.rotationAccountId ?? null,
+ ...result
+ };
+ };
+
+ return { getRotation, setRotationAccount, rotateNow, listRotationCandidates, rotateScheduledAccount };
+};
diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.ts
new file mode 100644
index 0000000000..c2e1b97686
--- /dev/null
+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.ts
@@ -0,0 +1,34 @@
+import { z } from "zod";
+
+import { PasswordRequirementsSchema } from "@app/ee/services/secret-rotation-v2/shared/general/password-requirements-schema";
+
+export type TGetPamAccountRotationDTO = {
+ accountId: string;
+ projectId: string;
+};
+
+export type TSetPamRotationAccountDTO = {
+ accountId: string;
+ rotationAccountId: string | null;
+ projectId: string;
+};
+
+export type TRotatePamAccountDTO = {
+ accountId: string;
+ projectId: string;
+};
+
+export type TListPamRotationCandidatesDTO = {
+ accountId: string;
+ projectId: string;
+};
+
+export type TPamAccountRotationView = {
+ enabled: boolean;
+ intervalSeconds: number | null;
+ passwordRequirements: z.infer<typeof PasswordRequirementsSchema> | null;
+ rotationAccountId: string | null;
+ rotationAccountName: string | null;
+ lastRotatedAt: Date | null;
+ isReady: boolean;
+};
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
new file mode 100644
index 0000000000..78a9c6359d
--- /dev/null
+++ b/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, test } from "vitest";
+
+import { PamAccountType } from "../pam/pam-enums";
+import {
+ computeNextRotationAt,
+ getRotationReadiness,
+ isRotatableAccountType,
+ PamRotationReadinessIssue
+} from "./pam-rotation-fns";
+
+const templateSettings = (enabled: boolean, intervalSeconds = 86400) => ({
+ recordingEnabled: true,
+ recordingStorageBackend: "postgres",
+ rotation: { enabled, intervalSeconds }
+});
+
+describe("isRotatableAccountType", () => {
+ test("accepts the three SQL types", () => {
+ expect(isRotatableAccountType(PamAccountType.Postgres)).toBe(true);
+ expect(isRotatableAccountType(PamAccountType.MySQL)).toBe(true);
+ expect(isRotatableAccountType(PamAccountType.MsSQL)).toBe(true);
+ });
+
+ test("rejects non-SQL types", () => {
+ expect(isRotatableAccountType(PamAccountType.SSH)).toBe(false);
+ expect(isRotatableAccountType(PamAccountType.Windows)).toBe(false);
+ expect(isRotatableAccountType(PamAccountType.AwsIam)).toBe(false);
+ });
+});
+
+describe("getRotationReadiness", () => {
+ const base = {
+ accountId: "acc-1",
+ accountType: PamAccountType.Postgres,
+ credentialConfigured: true,
+ templateSettings: templateSettings(true)
+ };
+
+ test("not ready when template rotation is disabled", () => {
+ const r = getRotationReadiness({ ...base, rotationAccountId: "acc-1", templateSettings: templateSettings(false) });
+ expect(r).toEqual({ ready: false, issue: PamRotationReadinessIssue.RotationDisabled });
+ });
+
+ test("not ready for an unsupported account type", () => {
+ const r = getRotationReadiness({ ...base, accountType: PamAccountType.SSH, rotationAccountId: "acc-1" });
+ expect(r).toEqual({ ready: false, issue: PamRotationReadinessIssue.UnsupportedType });
+ });
+
+ test("not ready when no rotation account is configured", () => {
+ const r = getRotationReadiness({ ...base, rotationAccountId: null });
+ expect(r).toEqual({ ready: false, issue: PamRotationReadinessIssue.NotConfigured });
+ });
+
+ test("not ready for self-rotation without a stored credential", () => {
+ const r = getRotationReadiness({ ...base, rotationAccountId: "acc-1", credentialConfigured: false });
+ expect(r).toEqual({ ready: false, issue: PamRotationReadinessIssue.SelfRotationNoCredential });
+ });
+
+ test("ready for self-rotation with a stored credential", () => {
+ const r = getRotationReadiness({ ...base, rotationAccountId: "acc-1", credentialConfigured: true });
+ expect(r).toEqual({ ready: true });
+ });
+
+ test("ready for delegated rotation even without the target's own credential", () => {
+ const r = getRotationReadiness({ ...base, rotationAccountId: "acc-2", credentialConfigured: false });
+ expect(r).toEqual({ ready: true });
+ });
+});
+
+describe("computeNextRotationAt", () => {
+ const now = new Date("2026-07-01T00:00:00.000Z");
+ const interval = 86400; // 1 day
+
+ test("schedules one interval after the anchor when the anchor is recent", () => {
+ const anchor = new Date("2026-06-30T23:00:00.000Z"); // 23h ago, so anchor+1d is in the future
+ const next = computeNextRotationAt({ anchor, intervalSeconds: interval, now, jitterCapSeconds: 0 });
+ expect(next.getTime()).toBe(anchor.getTime() + interval * 1000);
+ });
+
+ test("clamps to now when anchor + interval is already in the past", () => {
+ const anchor = new Date("2026-06-01T00:00:00.000Z"); // long ago
+ const next = computeNextRotationAt({ anchor, intervalSeconds: interval, now, jitterCapSeconds: 0 });
+ expect(next.getTime()).toBe(now.getTime());
+ });
+
+ test("uses now as the anchor when none is given", () => {
+ const next = computeNextRotationAt({ anchor: null, intervalSeconds: interval, now, jitterCapSeconds: 0 });
+ expect(next.getTime()).toBe(now.getTime() + interval * 1000);
+ });
+
+ test("keeps jitter within the cap", () => {
+ const anchor = new Date("2026-06-30T23:00:00.000Z");
+ const cap = 3600;
+ const baseline = anchor.getTime() + interval * 1000;
+ for (let i = 0; i < 50; i += 1) {
+ const next = computeNextRotationAt({ anchor, intervalSeconds: interval, now, jitterCapSeconds: cap });
+ expect(next.getTime()).toBeGreaterThanOrEqual(baseline);
+ expect(next.getTime()).toBeLessThanOrEqual(baseline + cap * 1000);
+ }
+ });
+});
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
new file mode 100644
index 0000000000..3f18581573
--- /dev/null
+++ b/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.ts
@@ -0,0 +1,96 @@
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+
+import { PamAccountType } from "../pam/pam-enums";
+import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";
+
+export const ROTATABLE_ACCOUNT_TYPES = [PamAccountType.Postgres, PamAccountType.MySQL, PamAccountType.MsSQL] as const;
+
+export const isRotatableAccountType = (
+ accountType: PamAccountType | string
+): accountType is (typeof ROTATABLE_ACCOUNT_TYPES)[number] =>
+ (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],
+ AppConnection.Postgres | AppConnection.MySql | AppConnection.MsSql
+> = {
+ [PamAccountType.Postgres]: AppConnection.Postgres,
+ [PamAccountType.MySQL]: AppConnection.MySql,
+ [PamAccountType.MsSQL]: AppConnection.MsSql
+};
+
+export enum PamRotationReadinessIssue {
+ RotationDisabled = "rotation-disabled",
+ UnsupportedType = "unsupported-type",
+ NotConfigured = "not-configured",
+ SelfRotationNoCredential = "self-rotation-no-credential"
+}
+
+type TRotationReadinessInput = {
+ accountId: string;
+ accountType: PamAccountType | string;
+ rotationAccountId?: string | null;
+ credentialConfigured: boolean;
+ templateSettings: unknown;
+};
+
+// Account-level readiness as raw SQL, shared by the reconcile and impact count so they can't drift from each other
+// or from getRotationReadiness below. "Will rotate" = a rotation account is set, and delegated or self-with-credential.
+export const ACCOUNT_WILL_ROTATE_SQL = `"rotationAccountId" IS NOT NULL AND ("rotationAccountId" <> "id" OR "credentialConfigured")`;
+export const ACCOUNT_NEEDS_ROTATION_ACCOUNT_SQL = `"rotationAccountId" IS NULL OR ("rotationAccountId" = "id" AND NOT "credentialConfigured")`;
+
+export type TRotationReadiness = { ready: boolean; issue?: PamRotationReadinessIssue };
+
+export const getRotationReadiness = (account: TRotationReadinessInput): TRotationReadiness => {
+ const parsed = PamTemplateSettingsSchema.safeParse(account.templateSettings);
+ const rotationEnabled = parsed.success && parsed.data.rotation?.enabled === true;
+
+ if (!rotationEnabled) return { ready: false, issue: PamRotationReadinessIssue.RotationDisabled };
+ if (!isRotatableAccountType(account.accountType)) {
+ return { ready: false, issue: PamRotationReadinessIssue.UnsupportedType };
+ }
+ if (!account.rotationAccountId) return { ready: false, issue: PamRotationReadinessIssue.NotConfigured };
+
+ const isSelfRotation = account.rotationAccountId === account.accountId;
+ if (isSelfRotation && !account.credentialConfigured) {
+ return { ready: false, issue: PamRotationReadinessIssue.SelfRotationNoCredential };
+ }
+
+ return { ready: true };
+};
+
+export const ROTATION_JITTER_CAP_SECONDS = 3600;
+const ROTATION_JITTER_FACTOR = 0.1;
+
+// A failed rotation retries after at most this instead of a full (possibly month-long) interval.
+export const ROTATION_FAILURE_RETRY_CAP_SECONDS = 3600;
+
+// Random spread on a due-date (10% of interval, capped) so a template's accounts don't all fire at once.
+export const rotationJitterCapSeconds = (intervalSeconds: number, capSeconds = ROTATION_JITTER_CAP_SECONDS) =>
+ Math.min(intervalSeconds * ROTATION_JITTER_FACTOR, capSeconds);
+
+export const computeNextRotationAt = ({
+ anchor,
+ intervalSeconds,
+ now,
+ jitterCapSeconds = ROTATION_JITTER_CAP_SECONDS
+}: {
+ anchor: Date | null | undefined;
+ intervalSeconds: number;
+ now: Date;
+ jitterCapSeconds?: number;
+}): Date => {
+ const base = Math.max((anchor ?? now).getTime() + intervalSeconds * 1000, now.getTime());
+ const jitterMs = Math.floor(Math.random() * rotationJitterCapSeconds(intervalSeconds, jitterCapSeconds) * 1000);
+ return new Date(base + jitterMs);
+};
+
+// A driver error can echo an interpolated password back, so strip secrets before storing or logging it.
+export const redactRotationError = (err: unknown, secrets: (string | undefined)[]): string => {
+ let message = err instanceof Error ? err.message : "Unknown error";
+ for (const secret of secrets) {
+ if (secret) message = message.replaceAll(secret, "******");
+ }
+ return message;
+};
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
new file mode 100644
index 0000000000..010b0bed51
--- /dev/null
+++ b/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts
@@ -0,0 +1,100 @@
+import { BadRequestError } from "@app/lib/errors";
+import {
+ getRoleUsernameForHost,
+ getSqlConnectionVerifyQuery,
+ SQL_CONNECTION_ALTER_LOGIN_STATEMENT
+} 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 {
+ SQL_QUERY_TIMEOUT,
+ TPamRotationGatewayDeps,
+ TPamSqlConnectionDetails,
+ withPamSqlClient
+} from "./shared/pam-rotation-sql-connection";
+
+type TRotatableType = (typeof ROTATABLE_ACCOUNT_TYPES)[number];
+
+type TApplyPasswordChangeInput = {
+ accountType: TRotatableType;
+ connectionDetails: TPamSqlConnectionDetails;
+ // Authenticates the connection: the account's own credential (self) or the rotator's (delegated).
+ auth: { username: string; password: string };
+ targetUsername: string;
+ newPassword: string;
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+};
+
+type TTestCredentialInput = {
+ accountType: TRotatableType;
+ connectionDetails: TPamSqlConnectionDetails;
+ auth: { username: string; password: string };
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+};
+
+export type TPamRotationHandler = {
+ validateTarget: (input: { accountType: TRotatableType; authMethod?: string }) => void;
+ applyPasswordChange: (input: TApplyPasswordChangeInput, deps: TPamRotationGatewayDeps) => Promise<void>;
+ // Returns whether the credential authenticates; never throws, so the recovery probe can rely on it.
+ testCredential: (input: TTestCredentialInput, deps: TPamRotationGatewayDeps) => Promise<boolean>;
+};
+
+const sqlRotationHandler: TPamRotationHandler = {
+ validateTarget: ({ accountType, authMethod }) => {
+ // MSSQL Windows-auth (ntlm/kerberos) logins have no SQL-managed password to change, so only sql-login rotates.
+ if (accountType === PamAccountType.MsSQL && authMethod !== "sql-login") {
+ throw new BadRequestError({ message: "MSSQL rotation supports SQL Server authentication only" });
+ }
+ },
+
+ applyPasswordChange: async (input, deps) => {
+ const { accountType, connectionDetails, auth, targetUsername, newPassword, gatewayId, gatewayPoolId } = input;
+ // 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]]({
+ username: roleUsername,
+ password: newPassword
+ });
+
+ try {
+ await withPamSqlClient(
+ { accountType, connectionDetails, auth, gatewayId, gatewayPoolId },
+ deps,
+ async (client) => {
+ // No `cancel: true`: tedious (mssql) throws on cancellation. A plain timeout rejects on all dialects,
+ // and withPamSqlClient's finally destroys the connection, aborting any still-running statement.
+ await client.raw(statement, bindings).timeout(SQL_QUERY_TIMEOUT);
+ }
+ );
+ } catch (err) {
+ // The statement interpolates the password, so a driver error can echo it. Redact both secrets.
+ throw new Error(redactRotationError(err, [newPassword, auth.password]));
+ }
+ },
+
+ testCredential: async (input, deps) => {
+ const { accountType, connectionDetails, auth, gatewayId, gatewayPoolId } = input;
+ try {
+ await withPamSqlClient(
+ { accountType, connectionDetails, auth, gatewayId, gatewayPoolId },
+ deps,
+ async (client) => {
+ await client.raw(getSqlConnectionVerifyQuery(PAM_ROTATION_APP_MAP[accountType])).timeout(SQL_QUERY_TIMEOUT);
+ }
+ );
+ return true;
+ } catch {
+ return false;
+ }
+ }
+};
+
+// Full Record over the rotatable types so a missing dialect entry is a compile error.
+export const PAM_ROTATION_FACTORY_MAP: Record<TRotatableType, TPamRotationHandler> = {
+ [PamAccountType.Postgres]: sqlRotationHandler,
+ [PamAccountType.MySQL]: sqlRotationHandler,
+ [PamAccountType.MsSQL]: sqlRotationHandler
+};
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
new file mode 100644
index 0000000000..963e27c04e
--- /dev/null
+++ b/backend/src/ee/services/pam-account-rotation/shared/pam-rotation-sql-connection.ts
@@ -0,0 +1,60 @@
+import { Knex } from "knex";
+
+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";
+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";
+
+// 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;
+
+export type TPamSqlConnectionDetails = {
+ host: string;
+ port: number;
+ database: string;
+ sslEnabled?: boolean;
+ sslRejectUnauthorized?: boolean;
+ sslCertificate?: string;
+};
+
+export type TPamRotationGatewayDeps = {
+ gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+};
+
+// 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];
+ connectionDetails: TPamSqlConnectionDetails;
+ auth: { username: string; password: string };
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ },
+ { gatewayService, gatewayV2Service, gatewayPoolService }: TPamRotationGatewayDeps,
+ operation: (client: Knex) => Promise<T>
+): Promise<T> => {
+ const { accountType, connectionDetails, auth, gatewayId, gatewayPoolId } = input;
+
+ const config = {
+ app: PAM_ROTATION_APP_MAP[accountType],
+ credentials: {
+ host: connectionDetails.host,
+ port: connectionDetails.port,
+ database: connectionDetails.database,
+ username: auth.username,
+ password: auth.password,
+ sslEnabled: connectionDetails.sslEnabled ?? false,
+ sslRejectUnauthorized: connectionDetails.sslRejectUnauthorized ?? true,
+ sslCertificate: connectionDetails.sslCertificate
+ },
+ gatewayId,
+ gatewayPoolId
+ } as TSqlConnectionConfig;
+
+ return executeWithPotentialGateway(config, gatewayService, gatewayV2Service, operation, gatewayPoolService);
+};
diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts b/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts
index 4f334654e0..c39ae90bdd 100644
--- a/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts
+++ b/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts
@@ -6,6 +6,7 @@ import { sanitizeSqlLikeString } from "@app/lib/fn";
import { ormify } from "@app/lib/knex";
import { PamAccountType } from "../pam/pam-enums";
+import { ACCOUNT_NEEDS_ROTATION_ACCOUNT_SQL, ACCOUNT_WILL_ROTATE_SQL } from "../pam-account-rotation/pam-rotation-fns";
export type TPamAccountTemplateWithCount = TPamAccountTemplates & { accountCount: number };
@@ -48,5 +49,20 @@ export const pamAccountTemplateDALFactory = (db: TDbClient) => {
return Number(result.count);
};
- return { ...orm, findByProjectId, countAccountsByTemplateId };
+ const getTemplateRotationStats = async (templateId: string, tx?: Knex) => {
+ const [result] = (await (tx || db.replicaNode())(TableName.PamAccount)
+ .where({ templateId })
+ .select(
+ db.raw(`count(*) as "accountCount"`),
+ db.raw(`count(*) FILTER (WHERE ${ACCOUNT_WILL_ROTATE_SQL}) as "willRotate"`),
+ db.raw(`count(*) FILTER (WHERE ${ACCOUNT_NEEDS_ROTATION_ACCOUNT_SQL}) as "needsRotationAccount"`)
+ )) as unknown as [{ accountCount: string; willRotate: string; needsRotationAccount: string }];
+ return {
+ accountCount: Number(result.accountCount),
+ willRotate: Number(result.willRotate),
+ needsRotationAccount: Number(result.needsRotationAccount)
+ };
+ };
+
+ return { ...orm, findByProjectId, countAccountsByTemplateId, getTemplateRotationStats };
};
diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts b/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts
index b00fbcf4fa..6e127b9a40 100644
--- a/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts
+++ b/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts
@@ -1,17 +1,14 @@
import { z } from "zod";
+import { PasswordRequirementsSchema } from "@app/ee/services/secret-rotation-v2/shared/general/password-requirements-schema";
import { AWSRegion } from "@app/services/app-connection/app-connection-enums";
import { patternsStringSchema } from "../pam/pam-policies";
import { PamRecordingStorageBackend } from "../pam-session-recording/pam-recording-enums";
-export const PamPasswordConstraintsSchema = z.object({
- minLength: z.number().int().min(1).max(256),
- maxLength: z.number().int().min(1).max(256),
- requireUppercase: z.boolean(),
- requireLowercase: z.boolean(),
- requireNumbers: z.boolean(),
- requireSymbols: z.boolean()
+export const PamRotationConfigSchema = z.object({
+ enabled: z.boolean(),
+ intervalSeconds: z.number().int().min(3600).max(31_536_000) // 1 hour .. 1 year
});
export const PamRecordingS3ConfigSchema = z.object({
@@ -28,7 +25,8 @@ export const PamTemplateSettingsSchema = z.object({
recordingEnabled: z.boolean().default(true),
recordingStorageBackend: z.nativeEnum(PamRecordingStorageBackend).default(PamRecordingStorageBackend.Postgres),
recordingS3Config: PamRecordingS3ConfigSchema.optional(),
- passwordConstraints: PamPasswordConstraintsSchema.optional(),
+ passwordRequirements: PasswordRequirementsSchema.optional(),
+ rotation: PamRotationConfigSchema.optional(),
sessionLogMaskingPatterns: z.string().optional()
});
@@ -38,4 +36,4 @@ export const PamTemplateSettingsInputSchema = PamTemplateSettingsSchema.extend({
export type TPamTemplateSettings = z.infer<typeof PamTemplateSettingsSchema>;
export type TPamAccountSettingsOverrides = z.infer<typeof PamAccountSettingsOverridesSchema>;
-export type TPamPasswordConstraints = z.infer<typeof PamPasswordConstraintsSchema>;
+export type TPamRotationConfig = z.infer<typeof PamRotationConfigSchema>;
diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-service.ts b/backend/src/ee/services/pam-account-template/pam-account-template-service.ts
index 3f493b5909..31e9182ae5 100644
--- a/backend/src/ee/services/pam-account-template/pam-account-template-service.ts
+++ b/backend/src/ee/services/pam-account-template/pam-account-template-service.ts
@@ -12,11 +12,17 @@ import {
validateRecordingConnection,
validateRecordingS3Config
} from "../pam/pam-validators";
+import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import { ACCOUNT_TYPE_CONFIGS } from "../pam-account/pam-account-schemas";
+import { isRotatableAccountType, ROTATABLE_ACCOUNT_TYPES } from "../pam-account-rotation/pam-rotation-fns";
import { PamRecordingStorageBackend } from "../pam-session-recording/pam-recording-enums";
import { TPamRecordingResolvedConfig } from "../pam-session-recording/pam-recording-storage-types";
import { TPamAccountTemplateDALFactory } from "./pam-account-template-dal";
-import { PamRecordingS3ConfigSchema, TPamTemplateSettings } from "./pam-account-template-schemas";
+import {
+ PamRecordingS3ConfigSchema,
+ PamTemplateSettingsSchema,
+ TPamTemplateSettings
+} from "./pam-account-template-schemas";
import {
TCreatePamAccountTemplateDTO,
TDeletePamAccountTemplateDTO,
@@ -27,15 +33,20 @@ import {
const SUPPORTED_ACCOUNT_TYPES = new Set<string>(Object.keys(ACCOUNT_TYPE_CONFIGS));
+// Symbols a rotation password may use: printable punctuation minus anything that could terminate a quoted SQL
+// string, escape it, separate a statement, or be read as a knex positional binding (' " \ ` ; ?).
+const SAFE_PASSWORD_SYMBOLS = "!@#$%^&*()-_=+[]{}|:,.<>/~";
+
type TPamAccountTemplateServiceFactoryDep = TPamValidatorDeps & {
pamAccountTemplateDAL: TPamAccountTemplateDALFactory;
+ pamAccountDAL: Pick<TPamAccountDALFactory, "reconcileRotationScheduleForTemplate">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
};
export type TPamAccountTemplateServiceFactory = ReturnType<typeof pamAccountTemplateServiceFactory>;
export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServiceFactoryDep) => {
- const { pamAccountTemplateDAL, permissionService } = deps;
+ const { pamAccountTemplateDAL, pamAccountDAL, permissionService } = deps;
const verifyMembership = (projectId: string, ctx: TActorContext) =>
verifyProductMembership(permissionService, projectId, ctx);
@@ -47,6 +58,27 @@ export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServic
return result.data;
};
+ // Reject rotation config on non-rotatable template types (the settings schema can't, since the type is a sibling
+ // field). The supported-type list is derived from the registry so it never goes stale as types are added.
+ const validateTemplateRotationConfig = (accountType: string, settings: TPamTemplateSettings | undefined) => {
+ if (!settings) return;
+ const hasRotationConfig = settings.rotation !== undefined || settings.passwordRequirements !== undefined;
+ if (hasRotationConfig && !isRotatableAccountType(accountType)) {
+ const supported = ROTATABLE_ACCOUNT_TYPES.map((type) => ACCOUNT_TYPE_CONFIGS[type].name).join(", ");
+ throw new BadRequestError({ message: `Credential rotation is only supported for ${supported} accounts` });
+ }
+ // allowedSymbols end up interpolated into the quoted password-change statement, so validate against an
+ // allowlist rather than a denylist: an allowlist rejects anything not explicitly permitted, so a breakout
+ // character can never slip through unlisted.
+ const allowedSymbols = settings.passwordRequirements?.allowedSymbols;
+ if (allowedSymbols) {
+ const invalid = [...new Set(allowedSymbols)].filter((char) => !SAFE_PASSWORD_SYMBOLS.includes(char));
+ if (invalid.length > 0) {
+ throw new BadRequestError({ message: `Allowed symbols may only include: ${SAFE_PASSWORD_SYMBOLS}` });
+ }
+ }
+ };
+
const verifyProductAdmin = async (projectId: string, ctx: TActorContext) => {
const { hasRole } = await verifyMembership(projectId, ctx);
if (!hasRole(PamProductRole.Admin)) {
@@ -92,8 +124,8 @@ export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServic
throw new NotFoundError({ message: `Account template with ID '${templateId}' not found` });
}
- const accountCount = await pamAccountTemplateDAL.countAccountsByTemplateId(templateId);
- return { ...template, accountCount };
+ const { accountCount, ...rotationImpact } = await pamAccountTemplateDAL.getTemplateRotationStats(templateId);
+ return { ...template, accountCount, rotationImpact };
};
const create = async ({
@@ -112,6 +144,7 @@ export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServic
await validateGatewayAttachment(deps, gatewayId, gatewayPoolId, ctx);
await validateRecordingConnection(deps, recordingConnectionId, ctx);
const validatedPolicies = validateTemplatePolicies(type, policies);
+ validateTemplateRotationConfig(type, settings);
const resolvedS3Config = await validateTemplateRecordingS3Config(recordingConnectionId, settings, ctx);
@@ -162,6 +195,7 @@ export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServic
}
const validatedPolicies = validateTemplatePolicies(existing.type, policies);
+ validateTemplateRotationConfig(existing.type, settings);
const resolvedConnId = recordingConnectionId !== undefined ? recordingConnectionId : existing.recordingConnectionId;
const resolvedSettings = (settings !== undefined ? settings : existing.settings) as TPamTemplateSettings;
@@ -178,7 +212,21 @@ export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServic
if (recordingConnectionId !== undefined) updateData.recordingConnectionId = recordingConnectionId;
try {
- const template = await pamAccountTemplateDAL.updateById(templateId, updateData);
+ // Write the template and re-derive its accounts' schedules atomically, so a crash can't leave the settings
+ // changed but nextRotationAt stale. Recompute already-scheduled accounts only when the interval changed.
+ const template = await pamAccountTemplateDAL.transaction(async (tx) => {
+ const updated = await pamAccountTemplateDAL.updateById(templateId, updateData, tx);
+ if (settings !== undefined) {
+ const oldInterval = PamTemplateSettingsSchema.safeParse(existing.settings).data?.rotation?.intervalSeconds;
+ const newInterval = PamTemplateSettingsSchema.safeParse(settings).data?.rotation?.intervalSeconds;
+ await pamAccountDAL.reconcileRotationScheduleForTemplate(
+ templateId,
+ { rescheduleReady: newInterval !== undefined && oldInterval !== newInterval },
+ tx
+ );
+ }
+ return updated;
+ });
const corsProbeUrl = resolvedS3Config ? await mintCorsProbeUrl(resolvedS3Config) : null;
return { ...template, corsProbeUrl };
} catch (err) {
diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.ts
index ee70bedef1..36ee50d9db 100644
--- a/backend/src/ee/services/pam-account/pam-account-dal.ts
+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts
@@ -6,9 +6,29 @@ import { sanitizeSqlLikeString } from "@app/lib/fn";
import { ormify } from "@app/lib/knex";
import { PamAccountType } from "../pam/pam-enums";
+import {
+ ACCOUNT_NEEDS_ROTATION_ACCOUNT_SQL,
+ ACCOUNT_WILL_ROTATE_SQL,
+ computeNextRotationAt,
+ getRotationReadiness,
+ ROTATABLE_ACCOUNT_TYPES,
+ rotationJitterCapSeconds
+} from "../pam-account-rotation/pam-rotation-fns";
+import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";
import { PamRecordingStorageBackend } from "../pam-session-recording/pam-recording-enums";
import { ACCOUNT_TYPE_CONFIGS } from "./pam-account-schemas";
+const ROTATABLE_TYPE_VALUES = ROTATABLE_ACCOUNT_TYPES as readonly string[];
+
+export type TPamRotationCandidate = {
+ id: string;
+ name: string;
+ folderId: string | null;
+ folderName: string | null;
+ accountType: string;
+ encryptedConnectionDetails: Buffer;
+};
+
const recordingRequiredAccountTypes = [PamAccountType.Windows, PamAccountType.WindowsAd]
.map((type) => `'${type}'`)
.join(", ");
@@ -168,25 +188,174 @@ export const pamAccountDALFactory = (db: TDbClient) => {
};
};
+ const detailSelect = [
+ `${TableName.PamAccount}.*`,
+ `${TableName.PamAccountTemplate}.type as accountType`,
+ `${TableName.PamAccountTemplate}.name as templateName`,
+ `${TableName.PamAccountTemplate}.policies as templatePolicies`,
+ `${TableName.PamAccountTemplate}.settings as templateSettings`,
+ `${TableName.PamAccountTemplate}.gatewayId as templateGatewayId`,
+ `${TableName.PamAccountTemplate}.gatewayPoolId as templateGatewayPoolId`,
+ `${TableName.PamAccountTemplate}.recordingConnectionId as templateRecordingConnectionId`,
+ `${TableName.PamFolder}.name as folderName`
+ ];
+
const findByIdWithDetails = async (accountId: string, tx?: Knex): Promise<TPamAccountDetail | null> => {
const rows = (await (tx || db.replicaNode())(TableName.PamAccount)
.join(TableName.PamAccountTemplate, `${TableName.PamAccount}.templateId`, `${TableName.PamAccountTemplate}.id`)
.leftJoin(TableName.PamFolder, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`)
.where(`${TableName.PamAccount}.id`, accountId)
+ .select(detailSelect)) as unknown as TPamAccountDetail[];
+
+ return rows[0] || null;
+ };
+
+ // Due, rotatable, enabled; excludes soft-deleted projects (rotating their accounts is a side effect during cleanup).
+ const dueRotationQuery = (now: Date, tx?: Knex) =>
+ (tx || db.replicaNode())(TableName.PamAccount)
+ .join(TableName.PamAccountTemplate, `${TableName.PamAccount}.templateId`, `${TableName.PamAccountTemplate}.id`)
+ .join(TableName.Project, `${TableName.PamAccount}.projectId`, `${TableName.Project}.id`)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .whereNotNull(`${TableName.PamAccount}.nextRotationAt`)
+ .where(`${TableName.PamAccount}.nextRotationAt`, "<=", now)
+ .whereIn(`${TableName.PamAccountTemplate}.type`, ROTATABLE_TYPE_VALUES)
+ .whereRaw(`"${TableName.PamAccountTemplate}"."settings"->'rotation'->>'enabled' = 'true'`);
+
+ // Only ready accounts get a nextRotationAt, so every due row here is already rotation-ready.
+ const findAccountsToRotate = async (now: Date, limit: number, tx?: Knex): Promise<TPamAccountDetail[]> => {
+ const rows = (await dueRotationQuery(now, tx)
+ .leftJoin(TableName.PamFolder, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`)
+ .orderBy(`${TableName.PamAccount}.nextRotationAt`, "asc")
+ .limit(limit)
+ .select(detailSelect)) as unknown as TPamAccountDetail[];
+ return rows;
+ };
+
+ const countAccountsToRotate = async (now: Date, tx?: Knex): Promise<number> => {
+ const result = await dueRotationQuery(now, tx).count<[{ count: string }]>(`${TableName.PamAccount}.id`);
+ return Number(result[0]?.count ?? 0);
+ };
+
+ const findRotationCandidates = async (
+ projectId: string,
+ accessibleFolderIds: string[],
+ accessibleAccountIds: string[],
+ accountType: string,
+ tx?: Knex
+ ): Promise<TPamRotationCandidate[]> => {
+ if (accessibleFolderIds.length === 0 && accessibleAccountIds.length === 0) return [];
+
+ const rows = (await (tx || db.replicaNode())(TableName.PamAccount)
+ .join(TableName.PamAccountTemplate, `${TableName.PamAccount}.templateId`, `${TableName.PamAccountTemplate}.id`)
+ .leftJoin(TableName.PamFolder, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`)
+ .where(`${TableName.PamAccount}.projectId`, projectId)
+ .where(`${TableName.PamAccountTemplate}.type`, accountType)
+ // A delegated rotator authenticates with its own stored password, so exclude accounts without one.
+ .where(`${TableName.PamAccount}.credentialConfigured`, true)
+ .where((builder) => {
+ if (accessibleFolderIds.length > 0) {
+ void builder.whereIn(`${TableName.PamAccount}.folderId`, accessibleFolderIds);
+ }
+ if (accessibleAccountIds.length > 0) {
+ void builder.orWhereIn(`${TableName.PamAccount}.id`, accessibleAccountIds);
+ }
+ })
.select(
- `${TableName.PamAccount}.*`,
+ `${TableName.PamAccount}.id`,
+ `${TableName.PamAccount}.name`,
+ `${TableName.PamAccount}.folderId`,
+ `${TableName.PamAccount}.encryptedConnectionDetails`,
`${TableName.PamAccountTemplate}.type as accountType`,
- `${TableName.PamAccountTemplate}.name as templateName`,
- `${TableName.PamAccountTemplate}.policies as templatePolicies`,
- `${TableName.PamAccountTemplate}.settings as templateSettings`,
- `${TableName.PamAccountTemplate}.gatewayId as templateGatewayId`,
- `${TableName.PamAccountTemplate}.gatewayPoolId as templateGatewayPoolId`,
- `${TableName.PamAccountTemplate}.recordingConnectionId as templateRecordingConnectionId`,
`${TableName.PamFolder}.name as folderName`
- )) as unknown as TPamAccountDetail[];
+ )
+ .orderBy(`${TableName.PamFolder}.name`, "asc")
+ .orderBy(`${TableName.PamAccount}.name`, "asc")) as unknown as TPamRotationCandidate[];
+ return rows;
+ };
- return rows[0] || null;
+ // Bulk set-based reschedule of a template's accounts; rescheduleReady also recomputes already-scheduled ones.
+ const reconcileRotationScheduleForTemplate = async (
+ templateId: string,
+ opts?: { rescheduleReady?: boolean },
+ tx?: Knex
+ ): Promise<void> => {
+ const dbClient = tx || db;
+ const template = await dbClient(TableName.PamAccountTemplate)
+ .where({ id: templateId })
+ .first<{ type: string; settings: unknown } | undefined>("type", "settings");
+ if (!template) return;
+
+ const parsed = PamTemplateSettingsSchema.safeParse(template.settings);
+ const rotation = parsed.success ? parsed.data.rotation : undefined;
+ const enabled = rotation?.enabled === true && ROTATABLE_TYPE_VALUES.includes(template.type);
+
+ if (!enabled || !rotation) {
+ await dbClient(TableName.PamAccount)
+ .where({ templateId })
+ .whereNotNull("nextRotationAt")
+ .update({ nextRotationAt: null });
+ return;
+ }
+
+ const { intervalSeconds } = rotation;
+ const jitterCapSeconds = rotationJitterCapSeconds(intervalSeconds);
+
+ await dbClient(TableName.PamAccount)
+ .where({ templateId })
+ .whereNotNull("nextRotationAt")
+ .whereRaw(`(${ACCOUNT_NEEDS_ROTATION_ACCOUNT_SQL})`)
+ .update({ nextRotationAt: null });
+
+ const readyUpdate = dbClient(TableName.PamAccount).where({ templateId }).whereRaw(`(${ACCOUNT_WILL_ROTATE_SQL})`);
+ if (!opts?.rescheduleReady) {
+ void readyUpdate.whereNull("nextRotationAt");
+ }
+ await readyUpdate.update({
+ nextRotationAt: dbClient.raw(
+ `GREATEST(COALESCE(??, now()) + make_interval(secs => ?), now()) + make_interval(secs => floor(random() * ?)::int)`,
+ ["lastRotatedAt", intervalSeconds, jitterCapSeconds]
+ ) as unknown as Date
+ });
};
- return { ...orm, findAccessible, findByIdWithDetails };
+ const reconcileRotationScheduleForAccount = async (accountId: string, tx?: Knex): Promise<void> => {
+ const account = await findByIdWithDetails(accountId, tx ?? db);
+ if (!account) return;
+
+ const readiness = getRotationReadiness({
+ accountId: account.id,
+ accountType: account.accountType,
+ rotationAccountId: account.rotationAccountId,
+ credentialConfigured: account.credentialConfigured,
+ templateSettings: account.templateSettings
+ });
+ const rotation = PamTemplateSettingsSchema.safeParse(account.templateSettings).data?.rotation;
+ const current = account.nextRotationAt ?? null;
+
+ let nextRotationAt: Date | null = current;
+ if (!readiness.ready) {
+ nextRotationAt = null;
+ } else if (!current && rotation?.enabled) {
+ nextRotationAt = computeNextRotationAt({
+ anchor: account.lastRotatedAt ?? null,
+ intervalSeconds: rotation.intervalSeconds,
+ now: new Date()
+ });
+ }
+
+ if ((nextRotationAt?.getTime() ?? null) !== (current?.getTime() ?? null)) {
+ await (tx || db)(TableName.PamAccount).where({ id: accountId }).update({ nextRotationAt });
+ }
+ };
+
+ return {
+ ...orm,
+ findAccessible,
+ findByIdWithDetails,
+ findAccountsToRotate,
+ countAccountsToRotate,
+ findRotationCandidates,
+ reconcileRotationScheduleForTemplate,
+ reconcileRotationScheduleForAccount
+ };
};
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
index 14e19d37a2..f5775a3d94 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -390,7 +390,15 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
}
try {
- const account = await pamAccountDAL.updateById(accountId, updateData);
+ const account = await pamAccountDAL.transaction(async (tx) => {
+ const updated = await pamAccountDAL.updateById(accountId, updateData, tx);
+ // A template move or a credential change can flip rotation readiness; re-derive the schedule atomically
+ // with the write so a failure can't leave a stale nextRotationAt.
+ if (templateId !== undefined || credentials) {
+ await pamAccountDAL.reconcileRotationScheduleForAccount(accountId, tx);
+ }
+ return updated;
+ });
const corsProbeUrl = resolvedS3Config ? await mintCorsProbeUrl(resolvedS3Config) : null;
return { ...account, corsProbeUrl };
} catch (err) {
@@ -423,24 +431,44 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
ctx
);
- return pamAccountDAL.transaction(async (tx) => {
- const memberships = await membershipDAL.find(
- {
- scope: RESOURCE_SCOPE,
- scopeResourceType: ResourceType.PamAccount,
- scopeResourceId: accountId
- },
- { tx }
- );
-
- if (memberships.length > 0) {
- const ids = memberships.map((m) => m.id);
- await membershipRoleDAL.delete({ $in: { membershipId: ids } }, tx);
- await membershipDAL.delete({ $in: { id: ids } }, tx);
- }
+ try {
+ return await pamAccountDAL.transaction(async (tx) => {
+ const memberships = await membershipDAL.find(
+ {
+ scope: RESOURCE_SCOPE,
+ scopeResourceType: ResourceType.PamAccount,
+ scopeResourceId: accountId
+ },
+ { tx }
+ );
+
+ if (memberships.length > 0) {
+ const ids = memberships.map((m) => m.id);
+ await membershipRoleDAL.delete({ $in: { membershipId: ids } }, tx);
+ await membershipDAL.delete({ $in: { id: ids } }, tx);
+ }
- return pamAccountDAL.deleteById(accountId, tx);
- });
+ return pamAccountDAL.deleteById(accountId, tx);
+ });
+ } catch (err) {
+ // The ON DELETE RESTRICT FK on rotationAccountId is the race-safe guard; on violation, look up the dependents
+ // to name them (rather than paying for that lookup on every delete).
+ if (
+ err instanceof DatabaseError &&
+ (err.error as { code?: string })?.code === DatabaseErrorCode.ForeignKeyViolation
+ ) {
+ const dependents = (await pamAccountDAL.find({ rotationAccountId: accountId })).filter(
+ (dependent) => dependent.id !== accountId
+ );
+ const names = dependents.map((dependent) => dependent.name).join(", ");
+ throw new BadRequestError({
+ message: names
+ ? `This account is the rotation account for: ${names}. Reassign or clear their rotation account before deleting this one.`
+ : "This account is used as the rotation account for another account. Reassign it before deleting this one."
+ });
+ }
+ throw err;
+ }
};
const listAccessible = async ({
diff --git a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts b/backend/src/ee/services/pam-project/pam-project-bootstrap.ts
index f466a9f9b5..b748bd2b77 100644
--- a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts
+++ b/backend/src/ee/services/pam-project/pam-project-bootstrap.ts
@@ -42,15 +42,7 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [
type: PamAccountType.Postgres,
settings: {
recordingEnabled: true,
- recordingStorageBackend: PamRecordingStorageBackend.Postgres,
- passwordConstraints: {
- minLength: 16,
- maxLength: 99,
- requireUppercase: true,
- requireLowercase: true,
- requireNumbers: true,
- requireSymbols: false
- }
+ recordingStorageBackend: PamRecordingStorageBackend.Postgres
}
},
{
@@ -58,15 +50,7 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [
type: PamAccountType.MySQL,
settings: {
recordingEnabled: true,
- recordingStorageBackend: PamRecordingStorageBackend.Postgres,
- passwordConstraints: {
- minLength: 16,
- maxLength: 80,
- requireUppercase: true,
- requireLowercase: true,
- requireNumbers: true,
- requireSymbols: false
- }
+ recordingStorageBackend: PamRecordingStorageBackend.Postgres
}
},
{
@@ -74,15 +58,7 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [
type: PamAccountType.MsSQL,
settings: {
recordingEnabled: true,
- recordingStorageBackend: PamRecordingStorageBackend.Postgres,
- passwordConstraints: {
- minLength: 16,
- maxLength: 128,
- requireUppercase: true,
- requireLowercase: true,
- requireNumbers: true,
- requireSymbols: true
- }
+ recordingStorageBackend: PamRecordingStorageBackend.Postgres
}
},
{
@@ -90,15 +66,7 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [
type: PamAccountType.OracleDB,
settings: {
recordingEnabled: true,
- recordingStorageBackend: PamRecordingStorageBackend.Postgres,
- passwordConstraints: {
- minLength: 16,
- maxLength: 30,
- requireUppercase: true,
- requireLowercase: true,
- requireNumbers: true,
- requireSymbols: true
- }
+ recordingStorageBackend: PamRecordingStorageBackend.Postgres
}
},
{
@@ -106,15 +74,7 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [
type: PamAccountType.MongoDB,
settings: {
recordingEnabled: true,
- recordingStorageBackend: PamRecordingStorageBackend.Postgres,
- passwordConstraints: {
- minLength: 16,
- maxLength: 128,
- requireUppercase: true,
- requireLowercase: true,
- requireNumbers: true,
- requireSymbols: false
- }
+ recordingStorageBackend: PamRecordingStorageBackend.Postgres
}
},
{
@@ -122,15 +82,7 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [
type: PamAccountType.Redis,
settings: {
recordingEnabled: true,
- recordingStorageBackend: PamRecordingStorageBackend.Postgres,
- passwordConstraints: {
- minLength: 16,
- maxLength: 128,
- requireUppercase: true,
- requireLowercase: true,
- requireNumbers: true,
- requireSymbols: false
- }
+ recordingStorageBackend: PamRecordingStorageBackend.Postgres
}
},
{
@@ -154,15 +106,7 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [
type: PamAccountType.Windows,
settings: {
recordingEnabled: true,
- recordingStorageBackend: PamRecordingStorageBackend.Postgres,
- passwordConstraints: {
- minLength: 14,
- maxLength: 127,
- requireUppercase: true,
- requireLowercase: true,
- requireNumbers: true,
- requireSymbols: true
- }
+ recordingStorageBackend: PamRecordingStorageBackend.Postgres
}
},
{
@@ -170,15 +114,7 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [
type: PamAccountType.WindowsAd,
settings: {
recordingEnabled: true,
- recordingStorageBackend: PamRecordingStorageBackend.Postgres,
- passwordConstraints: {
- minLength: 14,
- maxLength: 127,
- requireUppercase: true,
- requireLowercase: true,
- requireNumbers: true,
- requireSymbols: true
- }
+ recordingStorageBackend: PamRecordingStorageBackend.Postgres
}
}
];
diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.md
index 6108c21b1e..ce3bec9790 100644
--- a/backend/src/ee/services/pam/CLAUDE.md
+++ b/backend/src/ee/services/pam/CLAUDE.md
@@ -154,6 +154,18 @@ Session log masking (`sessionLogMaskingPatterns`) is a **setting**, not a policy
No migration, no router or response-schema change (beyond `policyRules` for gateway-enforced policies), and no DB default.
+## Credential Rotation
+
+Scheduled + on-demand rotation of a SQL account's password. Scoped to Postgres, MySQL, MSSQL. Lives in `pam-account-rotation/`.
+
+- **Config on the template** (`settings.rotation = { enabled, intervalSeconds }` + `settings.passwordRequirements`, reusing `secret-rotation-v2`'s `PasswordRequirementsSchema` and `generatePassword`). Accounts inherit it; only the `rotationAccountId` is per-account. `validateTemplateRotationConfig` rejects rotation config on non-SQL types and rejects `' " \ ` `` ` `` `; ?` in `allowedSymbols` (the ALTER statement interpolates the password and runs via knex `.raw`).
+- **`rotationAccountId` (on `pam_accounts`)**: null = not configured (not scheduled); own id = self-rotation; another account = delegated. `ON DELETE RESTRICT` (deleting an account referenced as a rotation account is blocked). Server-specific, so it never moves to the template.
+- **Handler registry** `PAM_ROTATION_FACTORY_MAP` (`pam-rotation-handlers.ts`): all three SQL types share `sqlRotationHandler` (`applyPasswordChange` + `testCredential`). Adding a SQL dialect = add it to `ROTATABLE_ACCOUNT_TYPES` and `PAM_ROTATION_APP_MAP` (both in `pam-rotation-fns.ts`); both are full `Record`s over the rotatable types, so a missing entry is a compile error. All per-dialect SQL facts (client, ALTER statement, verify query, SSL/connection config) live once in `app-connection/shared/sql` keyed by `AppConnection` (`SQL_CONNECTION_CLIENT_MAP`, `SQL_CONNECTION_ALTER_LOGIN_STATEMENT`, `getSqlConnectionVerifyQuery`, `getConnectionConfig`) and the handler reads them via `PAM_ROTATION_APP_MAP`, so a new dialect already handled there (e.g. Oracle with `SELECT 1 FROM DUAL`) needs no rotation-side change beyond the two maps. SQL is brokered through the gateway via `withPamSqlClient` (mirrors `executeWithPotentialGateway`; the direct-connect path runs the same `verifyHostInputValidity` SSRF guard).
+- **Readiness + schedule** are pure fns in `pam-rotation-fns.ts` (`getRotationReadiness`, `computeNextRotationAt`). The account-level "will rotate" predicate is `ACCOUNT_WILL_ROTATE_SQL` / `ACCOUNT_NEEDS_ROTATION_ACCOUNT_SQL` (same file), shared by both set-based SQL paths (`reconcileRotationScheduleForTemplate`, `getTemplateRotationStats`); `getRotationReadiness` is the row-at-a-time TS mirror. `nextRotationAt` is set/cleared by `reconcileRotationScheduleForTemplate` (bulk, on template update), `reconcileRotationScheduleForAccount` (on account create/update, set rotation account), and on a failed rotation by `recordRotationFailure` (capped retry). Never schedule elsewhere.
+- **Execution** (`pam-account-rotation-service.ts` `performRotation`): per-account Redis lock (`KeyStorePrefixes.PamAccountRotationLock`), then stage `encryptedPendingCredentials` → apply → verify → promote, with a recovery probe (candidate-then-current, both through the gateway) that never discards a possibly-live credential. Every failure path (including guards that throw before staging) funnels through one `recordRotationFailure` in `performRotation`'s catch, which records the redacted message and advances `nextRotationAt` by `min(interval, ROTATION_FAILURE_RETRY_CAP_SECONDS)` so a failure never hot-loops the cron and a transient outage retries well before a long interval elapses.
+- **Scheduling**: cron `PamCredentialRotationQueueRotations` → dispatcher queue `PamCredentialRotation` → per-account worker `PamCredentialRotationRotate` (concurrency + limiter). New queue names deliberately avoid the stale `pam-account-rotation`.
+- **Audit**: manual rotation audits in the route (`PAM_ACCOUNT_ROTATE_CREDENTIALS`, user actor); scheduled rotation audits in the queue worker (platform actor). Both carry `accountId` (required for PAM audit scoping).
+
## Session Lifecycle
- Sessions reference accounts via nullable `accountId` (SET NULL on delete) so session history survives account deletion
@@ -192,7 +204,9 @@ Old tables, columns, and code kept temporarily so data can be recovered if the m
### Columns to drop from `pam_accounts`
-`resourceId`, `domainId`, `policyId`, `lastRotatedAt`, `rotationStatus`, `encryptedLastRotationMessage`, `requireMfa`, `internalMetadata`, `discoveryFingerprint`
+`resourceId`, `domainId`, `policyId`, `requireMfa`, `internalMetadata`, `discoveryFingerprint`
+
+> `lastRotatedAt`, `rotationStatus`, and `encryptedLastRotationMessage` are **no longer dropped**: the credential-rotation feature (`pam-account-rotation/`) reuses them for the latest rotation state and error.
### Columns to drop from `pam_sessions`
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 1b0a2f1737..ee8fc453ae 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -57,6 +57,7 @@ export const KeyStorePrefixes = {
PkiSyncLock: (syncId: string) => `pki-sync-mutex-${syncId}` as const,
AppConnectionConcurrentJobs: (connectionId: string) => `app-connection-concurrency-${connectionId}` as const,
SecretRotationLock: (rotationId: string) => `secret-rotation-v2-mutex-${rotationId}` as const,
+ PamAccountRotationLock: (accountId: string) => `pam-account-rotation-mutex-${accountId}` as const,
SecretScanningLock: (dataSourceId: string, resourceExternalId: string) =>
`secret-scanning-v2-mutex-${dataSourceId}-${resourceExternalId}` as const,
IdentityLockoutLock: (lockoutKey: string) => `identity-lockout-lock-${lockoutKey}` as const,
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 20437fe652..7bd03c0a4b 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -37,7 +37,8 @@ export const CronJobName = {
SignerIssuancePolling: "signer-issuance-polling",
AuditLogStreamOutboxStaleClaimSweeper: "audit-log-stream-outbox-stale-claim-sweeper",
AuditLogStreamOutboxCleanup: "audit-log-stream-outbox-cleanup",
- LicenseUsageFlush: "license-usage-flush"
+ LicenseUsageFlush: "license-usage-flush",
+ PamCredentialRotationQueueRotations: "pam-credential-rotation-queue-rotations"
} as const;
// ── tuning constants ──────────────────────────────────────────────────────────
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 2ed84ce1ca..b867d324c9 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -97,6 +97,8 @@ export enum QueueName {
AppConnectionSecretSync = "app-connection-secret-sync",
SecretRotationV2 = "secret-rotation-v2",
SecretRotationV2RotateSecrets = "secret-rotation-v2-rotate-secrets",
+ PamCredentialRotation = "pam-credential-rotation",
+ PamCredentialRotationRotate = "pam-credential-rotation-rotate",
FolderTreeCheckpoint = "folder-tree-checkpoint",
InvalidateCache = "invalidate-cache",
SecretScanningV2 = "secret-scanning-v2",
@@ -152,6 +154,8 @@ export enum QueueJobs {
SecretRotationV2QueueRotations = "secret-rotation-v2-queue-rotations",
SecretRotationV2RotateSecrets = "secret-rotation-v2-rotate-secrets",
SecretRotationV2SendNotification = "secret-rotation-v2-send-notification",
+ PamCredentialRotationQueueRotations = "pam-credential-rotation-queue-rotations",
+ PamCredentialRotationRotate = "pam-credential-rotation-rotate",
CreateFolderTreeCheckpoint = "create-folder-tree-checkpoint",
DynamicSecretLeaseRevocationFailedEmail = "dynamic-secret-lease-revocation-failed-email",
InvalidateCache = "invalidate-cache",
@@ -387,6 +391,14 @@ export type TQueueJobTypes = {
name: QueueJobs.SecretRotationV2RotateSecrets;
payload: TSecretRotationRotateSecretsJobPayload;
};
+ [QueueName.PamCredentialRotation]: {
+ name: QueueJobs.PamCredentialRotationQueueRotations;
+ payload: undefined;
+ };
+ [QueueName.PamCredentialRotationRotate]: {
+ name: QueueJobs.PamCredentialRotationRotate;
+ payload: { accountId: string };
+ };
[QueueName.InvalidateCache]: {
name: QueueJobs.InvalidateCache;
payload: {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index fdf0bf9689..c6692a5c65 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -104,6 +104,8 @@ import { oidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-serv
import { pamAuditLogScopeResolverFactory } from "@app/ee/services/pam/pam-audit-log-fns";
import { pamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";
import { pamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
+import { pamAccountRotationQueueServiceFactory } from "@app/ee/services/pam-account-rotation/pam-account-rotation-queue";
+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 { pamFolderDALFactory } from "@app/ee/services/pam-folder/pam-folder-dal";
@@ -1790,6 +1792,7 @@ export const registerRoutes = async (
const pamAccountTemplateService = pamAccountTemplateServiceFactory({
pamAccountTemplateDAL,
+ pamAccountDAL,
permissionService,
gatewayV2DAL,
gatewayPoolService,
@@ -1810,6 +1813,18 @@ export const registerRoutes = async (
appConnectionDAL
});
+ const pamAccountRotationService = pamAccountRotationServiceFactory({
+ pamAccountDAL,
+ permissionService,
+ membershipDAL,
+ membershipRoleDAL,
+ kmsService,
+ keyStore,
+ gatewayService,
+ gatewayV2Service,
+ gatewayPoolService
+ });
+
const pamSessionDAL = pamSessionDALFactory(db);
const pamSessionEventChunkDAL = pamSessionEventChunkDALFactory(db);
@@ -3480,6 +3495,14 @@ export const registerRoutes = async (
orgDAL
});
+ await pamAccountRotationQueueServiceFactory({
+ queueService,
+ cronJob,
+ auditLogService,
+ pamAccountDAL,
+ pamAccountRotationService
+ });
+
const secretScanningV2Queue = secretScanningV2QueueServiceFactory({
auditLogService,
secretScanningV2DAL,
@@ -3708,6 +3731,7 @@ export const registerRoutes = async (
pamAccountTemplate: pamAccountTemplateService,
pamFolder: pamFolderService,
pamAccount: pamAccountService,
+ pamAccountRotation: pamAccountRotationService,
pamMembership: pamMembershipService,
pamSession: pamSessionService,
pamSessionChunk: pamSessionChunkService,
diff --git a/backend/src/services/app-connection/shared/sql/sql-connection-fns.ts b/backend/src/services/app-connection/shared/sql/sql-connection-fns.ts
index 08c97698e1..b2522b7944 100644
--- a/backend/src/services/app-connection/shared/sql/sql-connection-fns.ts
+++ b/backend/src/services/app-connection/shared/sql/sql-connection-fns.ts
@@ -21,17 +21,24 @@ import { TSqlConnectionConfig } from "@app/services/app-connection/shared/sql/sq
const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;
-const SQL_CONNECTION_CLIENT_MAP = {
+export const SQL_CONNECTION_CLIENT_MAP = {
[AppConnection.Postgres]: "pg",
[AppConnection.MsSql]: "mssql",
[AppConnection.MySql]: "mysql2",
[AppConnection.OracleDB]: "oracledb"
};
-const getConnectionConfig = ({
+// Trivial "is this credential valid" query, per dialect (Oracle's SELECT needs a FROM clause).
+export const getSqlConnectionVerifyQuery = (app: keyof typeof SQL_CONNECTION_CLIENT_MAP) =>
+ app === AppConnection.OracleDB ? "SELECT 1 FROM DUAL" : "Select 1";
+
+export const getConnectionConfig = ({
app,
credentials: { host, sslCertificate, sslEnabled, sslRejectUnauthorized }
-}: Pick<TSqlConnection, "credentials" | "app">) => {
+}: {
+ app: TSqlConnection["app"];
+ credentials: Pick<TSqlConnection["credentials"], "host" | "sslCertificate" | "sslEnabled" | "sslRejectUnauthorized">;
+}) => {
switch (app) {
case AppConnection.Postgres: {
return {
@@ -247,7 +254,7 @@ export const validateSqlConnectionCredentials = async (
) => {
try {
await executeWithPotentialGateway(config, gatewayService, gatewayV2Service, async (client) => {
- await client.raw(config.app === AppConnection.OracleDB ? `SELECT 1 FROM DUAL` : `Select 1`);
+ await client.raw(getSqlConnectionVerifyQuery(config.app));
});
return config.credentials;
} catch (error) {
diff --git a/docs/docs.json b/docs/docs.json
index 385b2a38ac..4963875e3e 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -990,7 +990,15 @@
"documentation/platform/pam/product-reference/session-recording",
"documentation/platform/pam/product-reference/external-storage",
"documentation/platform/pam/product-reference/ai-session-insights",
- "documentation/platform/pam/product-reference/credential-rotation",
+ {
+ "group": "Credential Rotation",
+ "pages": [
+ "documentation/platform/pam/product-reference/credential-rotation/overview",
+ "documentation/platform/pam/product-reference/credential-rotation/postgresql",
+ "documentation/platform/pam/product-reference/credential-rotation/mysql",
+ "documentation/platform/pam/product-reference/credential-rotation/mssql"
+ ]
+ },
"documentation/platform/pam/product-reference/view-credentials",
{
"group": "Web Access",
@@ -3932,6 +3940,10 @@
}
},
"redirects": [
+ {
+ "source": "/documentation/platform/pam/product-reference/credential-rotation",
+ "destination": "/documentation/platform/pam/product-reference/credential-rotation/overview"
+ },
{
"source": "/sdks/languages/csharp",
"destination": "/sdks/languages/dotnet"
diff --git a/docs/documentation/platform/pam/discovery/overview.mdx b/docs/documentation/platform/pam/discovery/overview.mdx
index e750f7c26f..a588204165 100644
--- a/docs/documentation/platform/pam/discovery/overview.mdx
+++ b/docs/documentation/platform/pam/discovery/overview.mdx
@@ -70,7 +70,7 @@ Dependencies represent services and tasks that rely on a specific account's cred
| **Scheduled Task** | A Windows scheduled task that runs under a specific account |
| **IIS App Pool** | An IIS application pool configured with a specific identity |
-Each dependency has an **Enabled** toggle that defaults to off. When enabled, Infisical will automatically update the dependency's credentials after rotating the linked account's password during [credential rotation](/documentation/platform/pam/product-reference/credential-rotation).
+Each dependency has an **Enabled** toggle that defaults to off. When enabled, Infisical will automatically update the dependency's credentials after rotating the linked account's password during [credential rotation](/documentation/platform/pam/product-reference/credential-rotation/overview).
<Info>
Dependencies discovered by a scan will never have their **Enabled** status overwritten by subsequent scans. Your explicit enable/disable decisions are always preserved.
diff --git a/docs/documentation/platform/pam/getting-started/accounts.mdx b/docs/documentation/platform/pam/getting-started/accounts.mdx
index 551057eaaf..a1261b6c40 100644
--- a/docs/documentation/platform/pam/getting-started/accounts.mdx
+++ b/docs/documentation/platform/pam/getting-started/accounts.mdx
@@ -62,4 +62,4 @@ To assign a policy, select one from the **Account Policy** dropdown when creatin
Infisical supports automated credential rotation for some accounts on select resources, allowing you to automatically change passwords at set intervals to enhance security.
-To learn more about how to configure this, please refer to the [Credential Rotation guide](/documentation/platform/pam/product-reference/credential-rotation).
+To learn more about how to configure this, please refer to the [Credential Rotation guide](/documentation/platform/pam/product-reference/credential-rotation/overview).
diff --git a/docs/documentation/platform/pam/getting-started/resources.mdx b/docs/documentation/platform/pam/getting-started/resources.mdx
index de6634fb82..63c2947fa1 100644
--- a/docs/documentation/platform/pam/getting-started/resources.mdx
+++ b/docs/documentation/platform/pam/getting-started/resources.mdx
@@ -58,4 +58,4 @@ Resources support custom key-value metadata that can be used to organize and cla
Some resources, such as PostgreSQL, support automated credential rotation to enhance your security posture. This feature requires configuring a privileged "Rotation Account" on the resource.
-To learn more about how to configure this, please refer to the [Credential Rotation guide](/documentation/platform/pam/product-reference/credential-rotation).
+To learn more about how to configure this, please refer to the [Credential Rotation guide](/documentation/platform/pam/product-reference/credential-rotation/overview).
diff --git a/docs/documentation/platform/pam/getting-started/resources/postgresql.mdx b/docs/documentation/platform/pam/getting-started/resources/postgresql.mdx
index d9eeb70fa3..03f6bd144a 100644
--- a/docs/documentation/platform/pam/getting-started/resources/postgresql.mdx
+++ b/docs/documentation/platform/pam/getting-started/resources/postgresql.mdx
@@ -213,4 +213,4 @@ The Infisical CLI starts a local proxy that allows you to connect with any Postg
PostgreSQL supports automated credential rotation through Infisical. This allows you to automatically rotate database credentials on a schedule, reducing the risk of credential compromise.
-For details, see [Credential Rotation](/documentation/platform/pam/product-reference/credential-rotation).
+For details, see [Credential Rotation](/documentation/platform/pam/product-reference/credential-rotation/overview).
diff --git a/docs/documentation/platform/pam/overview.mdx b/docs/documentation/platform/pam/overview.mdx
index 6c9cc7adc3..be6c9b8986 100644
--- a/docs/documentation/platform/pam/overview.mdx
+++ b/docs/documentation/platform/pam/overview.mdx
@@ -93,4 +93,4 @@ Infisical PAM supports a variety of resource types:
- **[Access Policies](/documentation/platform/pam/product-reference/access-policies)**: Configure approval policies for PAM account access using resource and account name matching.
- **[Auditing](/documentation/platform/pam/product-reference/auditing)**: Track and review a comprehensive log of all user actions and system events.
- **[Session Recording](/documentation/platform/pam/product-reference/session-recording)**: Record and playback user sessions for security reviews, compliance, and troubleshooting.
-- **[Automated Credential Rotation](/documentation/platform/pam/product-reference/credential-rotation)**: Automatically rotate credentials for supported resources to minimize the risk of compromised credentials.
+- **[Automated Credential Rotation](/documentation/platform/pam/product-reference/credential-rotation/overview)**: Automatically rotate credentials for supported resources to minimize the risk of compromised credentials.
diff --git a/docs/documentation/platform/pam/product-reference/credential-rotation.mdx b/docs/documentation/platform/pam/product-reference/credential-rotation.mdx
deleted file mode 100644
index b32cf0d435..0000000000
--- a/docs/documentation/platform/pam/product-reference/credential-rotation.mdx
+++ /dev/null
@@ -1,48 +0,0 @@
----
-title: "Credential Rotation"
-sidebarTitle: "Credential Rotation"
-description: "Learn how to automate credential rotation for your PAM resources."
----
-
-Automated Credential Rotation enhances your security posture by automatically changing the passwords of your accounts at set intervals. This minimizes the risk of compromised credentials by ensuring that even if a password is leaked, it remains valid only for a short period.
-
-## How it Works
-
-When rotation is enabled, Infisical's Gateway connects to the target resource using a privileged "Rotation Account". It then executes the necessary commands to change the password for the target user account to a new, cryptographically secure random value.
-
-## Configuration
-
-Setting up automated rotation requires a two-step configuration: first at the Resource level, and then at the individual Account level.
-
-<Steps>
- <Step title="Configure Rotation Account on Resource">
- A **Rotation Account** is a master or privileged account that has the necessary permissions to change the passwords of other users on the target system.
-
- When creating or editing a [Resource](/documentation/platform/pam/getting-started/resources), you must provide the credentials for this privileged account.
-
- *Example: For a PostgreSQL database, this would typically be the `postgres` superuser or another role with `ALTER ROLE` privileges.*
-
- ![Credential Rotation Account](/images/pam/getting-started/resources/credential-rotation-account.png)
- </Step>
-
- <Step title="Enable Rotation on Account">
- Once the resource has a rotation account configured, you can enable rotation for individual [Accounts](/documentation/platform/pam/getting-started/accounts) that belong to that resource.
-
- In the account settings:
- 1. Toggle **Enable Rotation**.
- 2. Set the **Rotation Interval** (e.g., every 7 days, 30 days).
-
- ![Rotate Credentials Account](/images/pam/getting-started/resources/rotate-credentials-account.png)
- </Step>
-</Steps>
-
-## Supported Resources
-
-Automated rotation is currently supported for the following resource types:
-
-- **PostgreSQL**: Requires a rotation account with `ALTER ROLE` permissions.
-- **Windows Server**: Requires a rotation account in the local Administrators group. Rotation applies to local machine accounts only.
-
-<Note>
- We are constantly adding support for more resource types.
-</Note>
diff --git a/docs/documentation/platform/pam/product-reference/credential-rotation/mssql.mdx b/docs/documentation/platform/pam/product-reference/credential-rotation/mssql.mdx
new file mode 100644
index 0000000000..30a568c495
--- /dev/null
+++ b/docs/documentation/platform/pam/product-reference/credential-rotation/mssql.mdx
@@ -0,0 +1,41 @@
+---
+title: "Microsoft SQL Server Credential Rotation"
+sidebarTitle: "Microsoft SQL Server"
+description: "Rotate Microsoft SQL Server account passwords with Infisical PAM."
+---
+
+This page covers what is specific to rotating a Microsoft SQL Server account. For how rotation is configured and scheduled, see the [overview](/documentation/platform/pam/product-reference/credential-rotation/overview).
+
+## How the password is changed
+
+When a Microsoft SQL Server account rotates, the rotation account connects to the target and runs:
+
+```sql
+ALTER LOGIN "<target_login>" WITH PASSWORD = '<generated_password>';
+```
+
+The connection uses the account's existing connection details, including the SSL settings.
+
+<Warning>
+ Only **SQL Server authentication** logins can be rotated. Windows-authenticated accounts are not supported, because their passwords are managed by the domain or the operating system rather than by SQL Server. A rotation on a Windows-authenticated account is rejected before any change is attempted.
+</Warning>
+
+## Rotation account requirements
+
+- **Self-rotation**: a login can change its own password, so no extra privileges are needed.
+- **Delegated rotation**: the rotation account needs the `ALTER ANY LOGIN` permission to change another login's password.
+
+An example setup for a dedicated delegated rotation login:
+
+```sql
+-- the login Infisical connects as to perform rotations
+CREATE LOGIN infisical_rotator WITH PASSWORD = 'temporary_password';
+GRANT ALTER ANY LOGIN TO infisical_rotator;
+
+-- the account whose password gets rotated
+CREATE LOGIN app_login WITH PASSWORD = 'temporary_password';
+```
+
+<Note>
+ The target account's connection must use SQL Server authentication so that the rotated password is the credential used to log in.
+</Note>
diff --git a/docs/documentation/platform/pam/product-reference/credential-rotation/mysql.mdx b/docs/documentation/platform/pam/product-reference/credential-rotation/mysql.mdx
new file mode 100644
index 0000000000..3d66fe64d5
--- /dev/null
+++ b/docs/documentation/platform/pam/product-reference/credential-rotation/mysql.mdx
@@ -0,0 +1,46 @@
+---
+title: "MySQL Credential Rotation"
+sidebarTitle: "MySQL"
+description: "Rotate MySQL account passwords with Infisical PAM."
+---
+
+This page covers what is specific to rotating a MySQL account. For how rotation is configured and scheduled, see the [overview](/documentation/platform/pam/product-reference/credential-rotation/overview).
+
+## How the password is changed
+
+When a MySQL account rotates, the rotation account connects to the target database and runs:
+
+```sql
+ALTER USER "<target_user>"@'%' IDENTIFIED BY '<generated_password>';
+```
+
+The statement targets the user at the `'%'` (any-host) grant, so the target user must be defined for that host. The connection uses the account's existing connection details, including the SSL settings.
+
+## Rotation account requirements
+
+- **Self-rotation**: a user can change its own password, so no extra privileges are needed.
+- **Delegated rotation**: the rotation account needs the global `CREATE USER` privilege (or `UPDATE` on the `mysql` system database) to alter another user's password.
+
+An example setup for a dedicated delegated rotation user:
+
+```sql
+-- the user Infisical connects as to perform rotations
+CREATE USER 'infisical_rotator'@'%' IDENTIFIED BY 'temporary_password';
+GRANT CREATE USER ON *.* TO 'infisical_rotator'@'%';
+
+-- the account whose password gets rotated
+CREATE USER 'app_user'@'%' IDENTIFIED BY 'temporary_password';
+```
+
+## Special cases
+
+<Warning>
+ If the target is hosted on **PlanetScale**, set the account username to the PlanetScale format `username.branch_id`. Infisical connects with that full username but targets the base `username` in the password-change statement, as PlanetScale requires.
+
+ To find your branch ID, use the [PlanetScale CLI](https://planetscale.com/docs/reference/planetscale-cli):
+
+ ```bash
+ pscale org switch <org-name>
+ pscale branch show <database> <branch-name> --format json
+ ```
+</Warning>
diff --git a/docs/documentation/platform/pam/product-reference/credential-rotation/overview.mdx b/docs/documentation/platform/pam/product-reference/credential-rotation/overview.mdx
new file mode 100644
index 0000000000..a34e056ecc
--- /dev/null
+++ b/docs/documentation/platform/pam/product-reference/credential-rotation/overview.mdx
@@ -0,0 +1,92 @@
+---
+title: "Credential Rotation"
+sidebarTitle: "Overview"
+description: "Automatically rotate the passwords of your PAM accounts on a fixed schedule."
+---
+
+Credential Rotation automatically changes the password of a PAM account on a fixed schedule. Rotating regularly limits how long a leaked or shared password stays valid, so a credential that is exposed is only useful for a short window.
+
+## Concepts
+
+Rotation is configured in two places that work together:
+
+- **Account template**: defines *whether* accounts rotate, *how often*, and the *format* of the generated password. Every account created from the template inherits these settings.
+- **Account**: defines *which privileged account* performs the rotation (the **rotation account**).
+
+An account rotates only once both parts are in place: its template has rotation enabled and the account has a rotation account set.
+
+### Rotation account
+
+The rotation account is the account whose credentials are used to connect to the target and change the password. You have three options:
+
+- **This account (self-rotation)**: the account rotates its own password. Use this when the account already has permission to change its own credentials.
+- **A different account (delegated)**: a more privileged account on the same resource performs the rotation. Use this when the target account cannot change its own password, or when you prefer a single administrative account to manage rotation.
+- **None**: no rotation account is set. The account will not rotate until one is chosen, even if its template has rotation enabled.
+
+<Note>
+ The rotation account must belong to the **same resource** as the account being rotated, because the password change runs against that resource using the rotation account's connection.
+</Note>
+
+## How it Works
+
+When a rotation runs, Infisical:
+
+1. Generates a new password that satisfies the template's password format.
+2. Connects to the target resource using the rotation account and applies the new password.
+3. Verifies the new password by opening a fresh connection with it.
+4. Promotes the new password to the live credential once verification succeeds. If any step fails, the existing credential is left untouched and the account's rotation status records the error.
+
+Rotations run through the same [Gateway](/documentation/platform/gateways/overview) path used for normal account access, so no additional network exposure is required.
+
+## Configuring a Template
+
+Open your PAM project, go to **Account Templates**, and open the template used by the accounts you want to rotate. In the **Credential settings** section:
+
+<Steps>
+ <Step title="Enable rotation">
+ Turn on rotation and set the **frequency** (for example, every 30 days). This frequency applies to all accounts created from the template.
+ </Step>
+ <Step title="Set the password format">
+ Choose the length and the character classes (uppercase, lowercase, digits, symbols) for generated passwords. Pick a format that satisfies the target system's password policy.
+
+ <Note>
+ The allowed symbols cannot include `'`, `"`, `` ` ``, `\`, `;`, or `?`, because those characters would break the password-change statement run against the target.
+ </Note>
+ </Step>
+</Steps>
+
+<Note>
+ Changing a template's rotation settings updates the rotation schedule for every account created from it. Accounts that do not yet have a rotation account remain unscheduled until one is set.
+</Note>
+
+## Configuring an Account
+
+Open an account that belongs to a rotation-enabled template and go to the **Rotation** tab.
+
+The tab shows the frequency and password format inherited from the template. To finish setup, choose a **rotation account** from the list of eligible accounts on the same resource. To have the account rotate its own password, select the account itself from that list (shown as **this account**). Leaving the rotation account as **None** means rotation stays unconfigured and the account will not rotate.
+
+To rotate immediately without waiting for the next scheduled run, click **Rotate now**. This counts as a rotation, so the schedule resets and the next automatic rotation happens one full interval later.
+
+<Note>
+ If an account shows that it will not rotate until it is configured, set a rotation account (or configure the account's own credentials for self-rotation) to make it ready.
+</Note>
+
+## Supported Resources
+
+Each resource type applies the password change differently and has its own requirements for the rotation account. See the resource-specific page for the exact statement, the privileges the rotation account needs, and any special cases.
+
+<CardGroup cols={3}>
+ <Card title="PostgreSQL" icon="database" href="/documentation/platform/pam/product-reference/credential-rotation/postgresql">
+ Rotates a role's password with `ALTER USER`.
+ </Card>
+ <Card title="MySQL" icon="database" href="/documentation/platform/pam/product-reference/credential-rotation/mysql">
+ Rotates a user's password with `ALTER USER`, including PlanetScale.
+ </Card>
+ <Card title="Microsoft SQL Server" icon="database" href="/documentation/platform/pam/product-reference/credential-rotation/mssql">
+ Rotates a SQL Server login's password with `ALTER LOGIN`.
+ </Card>
+</CardGroup>
+
+## Permissions
+
+Managing rotation on an account (setting the rotation account or triggering a manual rotation) requires the **Manage Rotation** permission on that account. Editing a template's rotation settings requires permission to edit the account template.
diff --git a/docs/documentation/platform/pam/product-reference/credential-rotation/postgresql.mdx b/docs/documentation/platform/pam/product-reference/credential-rotation/postgresql.mdx
new file mode 100644
index 0000000000..b768cbcbf6
--- /dev/null
+++ b/docs/documentation/platform/pam/product-reference/credential-rotation/postgresql.mdx
@@ -0,0 +1,42 @@
+---
+title: "PostgreSQL Credential Rotation"
+sidebarTitle: "PostgreSQL"
+description: "Rotate PostgreSQL account passwords with Infisical PAM."
+---
+
+This page covers what is specific to rotating a PostgreSQL account. For how rotation is configured and scheduled, see the [overview](/documentation/platform/pam/product-reference/credential-rotation/overview).
+
+## How the password is changed
+
+When a PostgreSQL account rotates, the rotation account connects to the target database and runs:
+
+```sql
+ALTER USER "<target_role>" WITH PASSWORD '<generated_password>';
+```
+
+The connection uses the account's existing connection details, including the SSL settings, so no extra configuration is needed for TLS-enabled databases.
+
+## Rotation account requirements
+
+The rotation account is the role that runs the statement above, so it must be allowed to set the target role's password.
+
+- **Self-rotation**: a role can always change its own password, so no extra privileges are needed.
+- **Delegated rotation**: the rotation account must be able to alter the target role. Grant it `CREATEROLE`, or use a superuser.
+
+An example setup for a dedicated delegated rotation role:
+
+```sql
+-- the role Infisical connects as to perform rotations
+CREATE ROLE infisical_rotator WITH LOGIN PASSWORD 'temporary_password' CREATEROLE;
+
+-- the account whose password gets rotated
+CREATE ROLE app_user WITH LOGIN PASSWORD 'temporary_password';
+```
+
+<Tip>
+ On PostgreSQL 16 and later, a `CREATEROLE` role can only alter roles it has `ADMIN OPTION` on. Grant it with `GRANT app_user TO infisical_rotator WITH ADMIN OPTION;`, or use a superuser as the rotation account.
+</Tip>
+
+<Note>
+ Create the rotation account and the target account in Infisical PAM as separate PostgreSQL accounts on the same resource, then select the rotation account on the target account's **Rotation** tab.
+</Note>
diff --git a/docs/documentation/platform/pam/product-reference/view-credentials.mdx b/docs/documentation/platform/pam/product-reference/view-credentials.mdx
index 066d35ec95..d22a886ab5 100644
--- a/docs/documentation/platform/pam/product-reference/view-credentials.mdx
+++ b/docs/documentation/platform/pam/product-reference/view-credentials.mdx
@@ -4,7 +4,7 @@ sidebarTitle: "View Credentials"
description: "View the current password or private key for a PAM account directly from the Infisical dashboard."
---
-When Infisical manages and [rotates](/documentation/platform/pam/product-reference/credential-rotation) an account's credentials, it becomes the source of truth for the current password. You can reveal the current password or private key from the account details page. Common use cases include:
+When Infisical manages and [rotates](/documentation/platform/pam/product-reference/credential-rotation/overview) an account's credentials, it becomes the source of truth for the current password. You can reveal the current password or private key from the account details page. Common use cases include:
- Retrieving the current password managed by Infisical as the source of truth, e.g. after a rotation.
- Entering credentials directly into systems or tooling that don't connect through the Gateway.
diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.ts
index e9c85aaf07..e23acf24d6 100644
--- a/frontend/src/hooks/api/pam/enums.ts
+++ b/frontend/src/hooks/api/pam/enums.ts
@@ -12,6 +12,35 @@ export enum PamAccountType {
WindowsAd = "windows-ad"
}
+export const ROTATABLE_PAM_ACCOUNT_TYPES = [
+ PamAccountType.Postgres,
+ PamAccountType.MySQL,
+ PamAccountType.MsSQL
+];
+
+export const isRotatablePamAccountType = (type: PamAccountType | string) =>
+ (ROTATABLE_PAM_ACCOUNT_TYPES as string[]).includes(type);
+
+export const PAM_ROTATION_INTERVAL_OPTIONS: { seconds: number; label: string }[] = [
+ { seconds: 3600, label: "1 hour" },
+ { seconds: 43200, label: "12 hours" },
+ { seconds: 86400, label: "24 hours" },
+ { seconds: 604800, label: "7 days" },
+ { seconds: 2592000, label: "30 days" }
+];
+
+export const formatRotationInterval = (seconds: number | null | undefined): string => {
+ if (!seconds) return "Not set";
+ const preset = PAM_ROTATION_INTERVAL_OPTIONS.find((option) => option.seconds === seconds);
+ if (preset) return preset.label;
+ const hours = Math.round(seconds / 3600);
+ if (hours % 24 === 0) {
+ const days = hours / 24;
+ return days === 1 ? "1 day" : `${days} days`;
+ }
+ return hours === 1 ? "1 hour" : `${hours} hours`;
+};
+
export enum PamPolicyType {
RequireMfa = "require-mfa",
RequireReason = "require-reason",
diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx
index 24220a9e05..4835d15ea2 100644
--- a/frontend/src/hooks/api/pam/mutations.tsx
+++ b/frontend/src/hooks/api/pam/mutations.tsx
@@ -29,6 +29,7 @@ import {
TRemoveFolderIdentityMemberDTO,
TRemoveFolderMemberDTO,
TRemovePamProductIdentityMemberDTO,
+ TRotatePamAccountDTO,
TUpdateAccountGroupMemberRoleDTO,
TUpdateAccountIdentityMemberRoleDTO,
TUpdateAccountMemberRoleDTO,
@@ -36,6 +37,7 @@ import {
TUpdateFolderIdentityMemberRoleDTO,
TUpdateFolderMemberRoleDTO,
TUpdatePamAccountDTO,
+ TUpdatePamAccountRotationDTO,
TUpdatePamAccountTemplateDTO,
TUpdatePamFolderDTO,
TUpdatePamProductIdentityMemberDTO
@@ -560,3 +562,31 @@ export const useRemoveFolderIdentityMember = () => {
}
});
};
+
+export const useUpdatePamAccountRotation = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ accountId, ...params }: TUpdatePamAccountRotationDTO) => {
+ const { data } = await apiRequest.patch(`/api/v1/pam/accounts/${accountId}/rotation`, params);
+ return data;
+ },
+ onSuccess: (_, { accountId }) => {
+ queryClient.invalidateQueries({ queryKey: pamKeys.accountRotation(accountId) });
+ queryClient.invalidateQueries({ queryKey: pamKeys.getAccount(accountId) });
+ }
+ });
+};
+
+export const useRotatePamAccount = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ accountId }: TRotatePamAccountDTO) => {
+ const { data } = await apiRequest.post(`/api/v1/pam/accounts/${accountId}/rotation/rotate`);
+ return data;
+ },
+ onSuccess: (_, { accountId }) => {
+ queryClient.invalidateQueries({ queryKey: pamKeys.accountRotation(accountId) });
+ queryClient.invalidateQueries({ queryKey: pamKeys.getAccount(accountId) });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index d806116955..92efe57484 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -20,6 +20,7 @@ import {
TListAccessiblePamAccountsDTO,
TListPamAccountTemplatesDTO,
TPamAccount,
+ TPamAccountRotation,
TPamAccountTemplateDetail,
TPamAccountTemplateWithCount,
TPamAccountTypeMetadata,
@@ -27,6 +28,7 @@ import {
TPamMember,
TPamMembersData,
TPamResourceRole,
+ TPamRotationCandidateGroup,
TPamSession
} from "./types";
@@ -62,7 +64,10 @@ export const pamKeys = {
productIdentities: () => [...pamKeys.all, "product-identities"] as const,
resourceRoles: () => [...pamKeys.all, "resource-roles"] as const,
accessCapabilities: () => [...pamKeys.all, "access-capabilities"] as const,
- accountTypes: () => [...pamKeys.all, "account-types"] as const
+ accountTypes: () => [...pamKeys.all, "account-types"] as const,
+ accountRotation: (accountId: string) => [...pamKeys.account(), "rotation", accountId] as const,
+ rotationCandidates: (accountId: string) =>
+ [...pamKeys.account(), "rotation-candidates", accountId] as const
};
const fetchFolderPermissions = async (folderId: string) => {
@@ -262,6 +267,35 @@ export const useGetPamAccountById = (
});
};
+export const useGetPamAccountRotation = (accountId?: string, options?: { enabled?: boolean }) => {
+ return useQuery({
+ queryKey: pamKeys.accountRotation(accountId || ""),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ rotation: TPamAccountRotation }>(
+ `/api/v1/pam/accounts/${accountId}/rotation`
+ );
+ return data.rotation;
+ },
+ enabled: !!accountId && (options?.enabled ?? true)
+ });
+};
+
+export const useGetPamRotationCandidates = (
+ accountId?: string,
+ options?: { enabled?: boolean }
+) => {
+ return useQuery({
+ queryKey: pamKeys.rotationCandidates(accountId || ""),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ candidates: TPamRotationCandidateGroup[] }>(
+ `/api/v1/pam/accounts/${accountId}/rotation/rotation-account-candidates`
+ );
+ return data.candidates;
+ },
+ enabled: !!accountId && (options?.enabled ?? true)
+ });
+};
+
// Sessions
export const useGetPamSessionById = (
sessionId: string,
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index de8b237420..5caf4a8513 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -278,7 +278,10 @@ export type TDeletePamAccountDTO = {
export type TPamAccountTemplateWithCount = TPamAccountTemplate & { accountCount: number };
-export type TPamAccountTemplateDetail = TPamAccountTemplate & { accountCount: number };
+export type TPamAccountTemplateDetail = TPamAccountTemplate & {
+ accountCount: number;
+ rotationImpact: { willRotate: number; needsRotationAccount: number };
+};
export type TListPamAccountTemplatesDTO = {
search?: string;
@@ -456,3 +459,36 @@ export type TRemovePamProductIdentityMemberDTO = {
identityId: string;
projectId: string;
};
+
+// Credential rotation
+
+export type TPamPasswordRequirements = {
+ length: number;
+ required: { lowercase: number; uppercase: number; digits: number; symbols: number };
+ allowedSymbols?: string;
+};
+
+export type TPamAccountRotation = {
+ enabled: boolean;
+ intervalSeconds: number | null;
+ passwordRequirements: TPamPasswordRequirements | null;
+ rotationAccountId: string | null;
+ rotationAccountName: string | null;
+ lastRotatedAt: string | null;
+ isReady: boolean;
+};
+
+export type TPamRotationCandidateGroup = {
+ folderId: string | null;
+ folderName: string | null;
+ accounts: { id: string; name: string; host: string }[];
+};
+
+export type TUpdatePamAccountRotationDTO = {
+ accountId: string;
+ rotationAccountId: string | null;
+};
+
+export type TRotatePamAccountDTO = {
+ accountId: string;
+};
diff --git a/frontend/src/hooks/usePamSheetState.ts b/frontend/src/hooks/usePamSheetState.ts
index 32d620f9da..1ce32f8d1e 100644
--- a/frontend/src/hooks/usePamSheetState.ts
+++ b/frontend/src/hooks/usePamSheetState.ts
@@ -6,7 +6,8 @@ export enum PamSheetTab {
Permissions = "permissions",
Configuration = "configuration",
Advanced = "advanced",
- General = "general"
+ General = "general",
+ Rotation = "rotation"
}
export const pamSheetSearchParams = z.object({
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
index 895a5b1102..dd0f9f51e3 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
@@ -51,6 +51,7 @@ import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
import { useGetOrganizationGroups } from "@app/hooks/api/organization/queries";
import {
accountTypeRequiresRecording,
+ isRotatablePamAccountType,
PamAccountAccessibilityIssue,
PamAccountType,
TPamMember,
@@ -84,6 +85,7 @@ import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatf
import { AssignAccessModal, EditMemberTarget } from "./AssignAccessModal";
import { EditAccountForm } from "./EditAccountForm";
import { RecordingConnectionPicker } from "./RecordingConnectionPicker";
+import { RotationTab } from "./RotationTab";
type Props = {
isOpen: boolean;
@@ -849,7 +851,11 @@ 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);
+ const availableTabs = visiblePamTabs(PAM_ACCOUNT_TABS, can).filter(
+ (tabDef) =>
+ tabDef.value !== PamSheetTab.Rotation ||
+ (accountType !== undefined && isRotatablePamAccountType(accountType))
+ );
const tabsWithIssues = new Set(
(account?.accessibilityIssues ?? []).map((issue) => ISSUE_TO_TAB[issue])
@@ -908,6 +914,7 @@ export const AccountDetailSheet = ({ isOpen, accountId, onOpenChange }: Props) =
[PamSheetTab.Configuration]: accountId ? (
<EditAccountForm accountId={accountId} onDirtyChange={setIsFormDirty} />
) : null,
+ [PamSheetTab.Rotation]: accountId ? <RotationTab accountId={accountId} /> : null,
[PamSheetTab.Advanced]: accountId ? (
<SettingsTab accountId={accountId} onDirtyChange={setIsFormDirty} />
) : null
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx
new file mode 100644
index 0000000000..b76f49cf35
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx
@@ -0,0 +1,246 @@
+import { useState } from "react";
+import { Check, ChevronsUpDown } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Badge,
+ Button,
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ Popover,
+ PopoverContent,
+ PopoverTrigger
+} from "@app/components/v3";
+import { Skeleton } from "@app/components/v3/generic/Skeleton";
+import { formatRotationInterval, PamResourcePermissionActions } from "@app/hooks/api/pam";
+import { useRotatePamAccount, useUpdatePamAccountRotation } from "@app/hooks/api/pam/mutations";
+import {
+ useGetPamAccountRotation,
+ useGetPamRotationCandidates,
+ usePamAccountActions
+} from "@app/hooks/api/pam/queries";
+import { TPamAccountRotation } from "@app/hooks/api/pam/types";
+
+import { formatDetailDate } from "../../components/PamDetailSheet";
+
+type Props = { accountId: string };
+
+const passwordFormatBadges = (reqs: TPamAccountRotation["passwordRequirements"]) => {
+ if (!reqs) return [];
+ const badges: string[] = [`${reqs.length} chars`];
+ if (reqs.required.uppercase > 0) badges.push("A–Z");
+ if (reqs.required.lowercase > 0) badges.push("a–z");
+ if (reqs.required.digits > 0) badges.push("0–9");
+ if (reqs.required.symbols > 0) badges.push("symbols");
+ return badges;
+};
+
+const DetailRow = ({ label, children }: { label: string; children: React.ReactNode }) => (
+ <div className="flex items-center justify-between gap-3 border-b border-border py-3 last:border-b-0">
+ <span className="text-sm text-foreground">{label}</span>
+ <div className="flex items-center gap-2">{children}</div>
+ </div>
+);
+
+const RotationAccountPicker = ({
+ accountId,
+ selectedId,
+ selectedName,
+ disabled
+}: {
+ accountId: string;
+ selectedId: string | null;
+ selectedName: string | null;
+ disabled: boolean;
+}) => {
+ const [open, setOpen] = useState(false);
+ const { data: candidates = [], isPending } = useGetPamRotationCandidates(accountId, {
+ enabled: open
+ });
+ const updateRotation = useUpdatePamAccountRotation();
+
+ const allAccounts = candidates.flatMap((group) => group.accounts);
+ const selected = allAccounts.find((a) => a.id === selectedId);
+ const selectedLabel = selectedId
+ ? `${selected?.name ?? selectedName ?? selectedId}${selectedId === accountId ? " (this account)" : ""}`
+ : "None";
+
+ const onSelect = async (rotationAccountId: string | null) => {
+ setOpen(false);
+ try {
+ await updateRotation.mutateAsync({ accountId, rotationAccountId });
+ createNotification({ type: "success", text: "Rotation account updated" });
+ } catch {
+ createNotification({ type: "error", text: "Failed to update rotation account" });
+ }
+ };
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button variant="outline" isDisabled={disabled} className="w-full justify-between">
+ <span className="truncate">{selectedLabel}</span>
+ <ChevronsUpDown className="size-4 opacity-60" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
+ <Command>
+ <CommandInput placeholder="Search accounts..." />
+ <CommandList>
+ {isPending ? (
+ <div className="p-2">
+ <Skeleton className="h-8 w-full" />
+ </div>
+ ) : (
+ <CommandEmpty>No eligible accounts</CommandEmpty>
+ )}
+ <CommandGroup>
+ <CommandItem value="none" onSelect={() => onSelect(null)}>
+ <Check className={`mr-2 size-4 ${selectedId ? "opacity-0" : "opacity-100"}`} />
+ None (not configured)
+ </CommandItem>
+ </CommandGroup>
+ {candidates.map((group) => (
+ <CommandGroup
+ key={group.folderId ?? "none"}
+ heading={group.folderName ?? "Ungrouped"}
+ >
+ {group.accounts.map((candidate) => (
+ <CommandItem
+ key={candidate.id}
+ value={candidate.id}
+ onSelect={() => onSelect(candidate.id)}
+ >
+ <Check
+ className={`mr-2 size-4 ${selectedId === candidate.id ? "opacity-100" : "opacity-0"}`}
+ />
+ <div className="flex min-w-0 flex-col">
+ <span className="truncate font-medium">
+ {candidate.name}
+ {candidate.id === accountId ? " (this account)" : ""}
+ </span>
+ <span className="truncate text-xs text-muted">{candidate.host}</span>
+ </div>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ ))}
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+export const RotationTab = ({ accountId }: Props) => {
+ const { data: rotation, isPending } = useGetPamAccountRotation(accountId);
+ const { can } = usePamAccountActions(accountId);
+ const canManage = can(PamResourcePermissionActions.ManageRotation);
+ const rotateNow = useRotatePamAccount();
+
+ const onRotateNow = async () => {
+ try {
+ await rotateNow.mutateAsync({ accountId });
+ createNotification({ type: "success", text: "Credential rotated" });
+ } catch {
+ createNotification({
+ type: "error",
+ text: "Rotation failed. Check the account's rotation status."
+ });
+ }
+ };
+
+ if (isPending || !rotation) {
+ return (
+ <div className="flex flex-col gap-3 p-4">
+ <Skeleton className="h-24 w-full" />
+ <Skeleton className="h-24 w-full" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-4 p-4">
+ <div className="rounded-lg border border-border bg-container p-4">
+ <div className="mb-2 flex items-center justify-between">
+ <div>
+ <h3 className="text-sm font-semibold text-foreground">Automatic rotation</h3>
+ <p className="text-xs text-muted">
+ How and when this account&apos;s password is rotated.
+ </p>
+ </div>
+ <span
+ className={`text-xs font-medium ${rotation.enabled ? "text-success" : "text-muted"}`}
+ >
+ {rotation.enabled ? "● Enabled" : "○ Disabled"}
+ </span>
+ </div>
+
+ <DetailRow label="Frequency">
+ <span className="text-sm text-muted">
+ {formatRotationInterval(rotation.intervalSeconds)}
+ </span>
+ </DetailRow>
+ <DetailRow label="Password format">
+ {passwordFormatBadges(rotation.passwordRequirements).length > 0 ? (
+ <div className="flex flex-wrap items-center gap-1">
+ {passwordFormatBadges(rotation.passwordRequirements).map((b) => (
+ <Badge key={b} variant="neutral">
+ {b}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ <span className="text-sm text-muted">Default</span>
+ )}
+ </DetailRow>
+ <div className="flex items-center justify-between gap-3 py-3">
+ <span className="text-sm text-foreground">Last rotated</span>
+ <div className="flex items-center gap-3">
+ <span className="text-sm text-muted">
+ {rotation.lastRotatedAt ? formatDetailDate(rotation.lastRotatedAt) : "Never"}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ isDisabled={!canManage || !rotation.isReady}
+ isPending={rotateNow.isPending}
+ onClick={onRotateNow}
+ >
+ Rotate now
+ </Button>
+ </div>
+ </div>
+ </div>
+
+ <div className="rounded-lg border border-border bg-container p-4">
+ <h3 className="text-sm font-semibold text-foreground">Rotation account</h3>
+ <p className="mb-3 text-xs text-muted">
+ The privileged account used to rotate this password.
+ </p>
+ <RotationAccountPicker
+ accountId={accountId}
+ selectedId={rotation.rotationAccountId}
+ selectedName={rotation.rotationAccountName}
+ disabled={!canManage}
+ />
+ <p className="mt-2 text-xs text-muted">
+ Select this account to have it rotate its own password. If set to None, the account will
+ not rotate.
+ </p>
+ </div>
+
+ {!rotation.isReady && rotation.enabled && (
+ <div className="rounded-lg border border-warning/40 bg-warning/10 p-3 text-xs text-warning">
+ Rotation is enabled, but this account won&apos;t rotate until a rotation account is set.
+ Choose one above, or select this account to rotate its own password (which requires stored
+ credentials).
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
index 27e3358947..1bab14b78a 100644
--- a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import axios from "axios";
-import { AlertTriangleIcon, Ban } from "lucide-react";
+import { AlertTriangleIcon, Ban, InfoIcon } from "lucide-react";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
@@ -27,6 +27,7 @@ import {
SelectItem,
SelectTrigger,
SelectValue,
+ Switch,
TextArea
} from "@app/components/v3";
import { Skeleton } from "@app/components/v3/generic/Skeleton";
@@ -34,6 +35,8 @@ import { useProject } from "@app/context";
import { AppConnection, useListAvailableAppConnections } from "@app/hooks/api/appConnections";
import {
accountTypeRequiresRecording,
+ isRotatablePamAccountType,
+ PAM_ROTATION_INTERVAL_OPTIONS,
PamAccountType,
useGetPamAccountTemplate,
usePamAccountTypeMap,
@@ -66,7 +69,15 @@ const settingsSchema = z
s3KeyPrefix: z.string().optional(),
policies: z.record(z.unknown()),
settings: z.object({
- sessionLogMaskingPatterns: z.string().optional()
+ sessionLogMaskingPatterns: z.string().optional(),
+ rotationEnabled: z.boolean().optional(),
+ rotationIntervalSeconds: z.coerce.number().optional(),
+ pwLength: z.coerce.number().optional(),
+ pwUppercase: z.coerce.number().optional(),
+ pwLowercase: z.coerce.number().optional(),
+ pwDigits: z.coerce.number().optional(),
+ pwSymbols: z.coerce.number().optional(),
+ pwAllowedSymbols: z.string().optional()
})
})
.superRefine((data, ctx) => {
@@ -235,7 +246,17 @@ const SettingsTab = ({
s3Region: "",
s3KeyPrefix: "",
policies: {},
- settings: { sessionLogMaskingPatterns: "" }
+ settings: {
+ sessionLogMaskingPatterns: "",
+ rotationEnabled: false,
+ rotationIntervalSeconds: 86400,
+ pwLength: 32,
+ pwUppercase: 1,
+ pwLowercase: 1,
+ pwDigits: 1,
+ pwSymbols: 1,
+ pwAllowedSymbols: "-_.~!*"
+ }
}
});
@@ -259,7 +280,33 @@ const SettingsTab = ({
s3KeyPrefix: s3Config.keyPrefix ?? "",
policies: (template.policies as Record<string, unknown>) ?? {},
settings: {
- sessionLogMaskingPatterns: (settings.sessionLogMaskingPatterns as string) ?? ""
+ sessionLogMaskingPatterns: (settings.sessionLogMaskingPatterns as string) ?? "",
+ ...(() => {
+ const rotation = (settings.rotation ?? {}) as {
+ enabled?: boolean;
+ intervalSeconds?: number;
+ };
+ const pw = (settings.passwordRequirements ?? {}) as {
+ length?: number;
+ required?: {
+ uppercase?: number;
+ lowercase?: number;
+ digits?: number;
+ symbols?: number;
+ };
+ allowedSymbols?: string;
+ };
+ return {
+ rotationEnabled: rotation.enabled ?? false,
+ rotationIntervalSeconds: rotation.intervalSeconds ?? 86400,
+ pwLength: pw.length ?? 32,
+ pwUppercase: pw.required?.uppercase ?? 1,
+ pwLowercase: pw.required?.lowercase ?? 1,
+ pwDigits: pw.required?.digits ?? 1,
+ pwSymbols: pw.required?.symbols ?? 1,
+ pwAllowedSymbols: pw.allowedSymbols ?? "-_.~!*"
+ };
+ })()
}
});
}
@@ -281,9 +328,11 @@ const SettingsTab = ({
const gatewayPoolId = watch("gatewayPoolId");
const policies = watch("policies");
const storageBackend = watch("recordingStorageBackend");
+ const rotationEnabled = watch("settings.rotationEnabled");
const requiresRecording = accountTypeRequiresRecording(template.type);
const showGatewaySettings = accountTypeMap[template.type]?.requiresGateway !== false;
const typeName = accountTypeMap[template.type]?.name ?? template.type;
+ const isRotatableTemplateType = isRotatablePamAccountType(template.type);
const applicablePolicies = (accountTypeMap[template.type]?.applicablePolicies ?? []).filter(
(p) => POLICY_EDITORS[p.key]
);
@@ -311,6 +360,33 @@ const SettingsTab = ({
delete settings.sessionLogMaskingPatterns;
}
+ if (isRotatableTemplateType) {
+ const isRotationOn = Boolean(data.settings.rotationEnabled);
+ settings.rotation = {
+ enabled: isRotationOn,
+ intervalSeconds: data.settings.rotationIntervalSeconds ?? 86400
+ };
+ if (isRotationOn) {
+ settings.passwordRequirements = {
+ length: data.settings.pwLength ?? 32,
+ required: {
+ uppercase: data.settings.pwUppercase ?? 0,
+ lowercase: data.settings.pwLowercase ?? 0,
+ digits: data.settings.pwDigits ?? 0,
+ symbols: data.settings.pwSymbols ?? 0
+ },
+ ...(data.settings.pwAllowedSymbols
+ ? { allowedSymbols: data.settings.pwAllowedSymbols }
+ : {})
+ };
+ } else {
+ delete settings.passwordRequirements;
+ }
+ } else {
+ delete settings.rotation;
+ delete settings.passwordRequirements;
+ }
+
updateTemplate.mutate(
{
templateId,
@@ -410,6 +486,154 @@ const SettingsTab = ({
</Card>
)}
+ {isRotatableTemplateType && (
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Credential settings</CardTitle>
+ <CardDescription>
+ How credentials for accounts using this template are rotated, and the format of the
+ generated passwords.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <Controller
+ control={control}
+ name="settings.rotationEnabled"
+ render={({ field }) => (
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <p className="text-sm font-medium text-foreground">
+ Automatically rotate credentials
+ </p>
+ <p className="text-xs text-muted">
+ Infisical rotates credentials on a fixed schedule. When off, they rotate only
+ when triggered manually.
+ </p>
+ </div>
+ <Switch
+ variant="pam"
+ checked={field.value ?? false}
+ onCheckedChange={field.onChange}
+ />
+ </div>
+ )}
+ />
+ {rotationEnabled &&
+ template.rotationImpact &&
+ (template.rotationImpact.needsRotationAccount > 0 ? (
+ <Alert variant="warning">
+ <AlertTriangleIcon />
+ <AlertTitle>
+ {template.rotationImpact.needsRotationAccount}{" "}
+ {template.rotationImpact.needsRotationAccount === 1 ? "account" : "accounts"}{" "}
+ won&apos;t rotate yet
+ </AlertTitle>
+ <AlertDescription>
+ Set a rotation account on{" "}
+ {template.rotationImpact.needsRotationAccount === 1 ? "it" : "them"} to include{" "}
+ {template.rotationImpact.needsRotationAccount === 1 ? "it" : "them"} in the
+ schedule.
+ {template.rotationImpact.willRotate > 0 &&
+ ` ${template.rotationImpact.willRotate} ${
+ template.rotationImpact.willRotate === 1 ? "account" : "accounts"
+ } will rotate as configured.`}
+ </AlertDescription>
+ </Alert>
+ ) : (
+ // Nothing misconfigured: only surface while editing; the warning above always shows (actionable gap).
+ isDirty && (
+ <Alert variant="info">
+ <InfoIcon />
+ <AlertTitle>
+ {template.rotationImpact.willRotate === 0
+ ? "No accounts to rotate yet"
+ : `${template.rotationImpact.willRotate} ${
+ template.rotationImpact.willRotate === 1 ? "account" : "accounts"
+ } will rotate`}
+ </AlertTitle>
+ <AlertDescription>
+ {template.rotationImpact.willRotate === 0
+ ? "Accounts using this template will rotate on schedule once they have a rotation account."
+ : "Every account using this template is set to rotate on schedule."}
+ </AlertDescription>
+ </Alert>
+ )
+ ))}
+ {rotationEnabled && (
+ <Controller
+ control={control}
+ name="settings.rotationIntervalSeconds"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Rotate every</FieldLabel>
+ <Select
+ value={String(field.value ?? 86400)}
+ onValueChange={(value) => field.onChange(Number(value))}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {PAM_ROTATION_INTERVAL_OPTIONS.map((option) => (
+ <SelectItem key={option.seconds} value={String(option.seconds)}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ How often credentials are rotated for accounts using this template.
+ </FieldDescription>
+ </Field>
+ )}
+ />
+ )}
+ <div className="grid grid-cols-2 gap-3">
+ {(
+ [
+ { name: "settings.pwLength", label: "Length" },
+ { name: "settings.pwUppercase", label: "Min uppercase" },
+ { name: "settings.pwLowercase", label: "Min lowercase" },
+ { name: "settings.pwDigits", label: "Min numbers" },
+ { name: "settings.pwSymbols", label: "Min symbols" }
+ ] as const
+ ).map(({ name, label }) => (
+ <Controller
+ key={name}
+ control={control}
+ name={name}
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>{label}</FieldLabel>
+ <Input
+ type="number"
+ value={field.value ?? 0}
+ onChange={(e) => field.onChange(Number(e.target.value))}
+ onWheel={(e) => e.currentTarget.blur()}
+ />
+ </Field>
+ )}
+ />
+ ))}
+ </div>
+ <Controller
+ control={control}
+ name="settings.pwAllowedSymbols"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Allowed symbols</FieldLabel>
+ <Input value={field.value ?? ""} onChange={field.onChange} placeholder="-_.~!*" />
+ <FieldDescription>
+ Symbols that generated passwords may use. Quotes, backticks, backslashes,
+ semicolons, and question marks are not allowed.
+ </FieldDescription>
+ </Field>
+ )}
+ />
+ </CardContent>
+ </Card>
+ )}
+
{showGatewaySettings && (
<Card>
<CardHeader className="border-b">
diff --git a/frontend/src/pages/pam/components/pamResourceTabs.ts b/frontend/src/pages/pam/components/pamResourceTabs.ts
index e634d4bcb8..a656bc71e3 100644
--- a/frontend/src/pages/pam/components/pamResourceTabs.ts
+++ b/frontend/src/pages/pam/components/pamResourceTabs.ts
@@ -1,4 +1,4 @@
-import { type LucideIcon, Settings, Settings2, Users } from "lucide-react";
+import { type LucideIcon, RotateCcw, Settings, Settings2, Users } from "lucide-react";
import { PamResourcePermissionActions } from "@app/hooks/api/pam";
import { PamSheetTab } from "@app/hooks/usePamSheetState";
@@ -23,6 +23,12 @@ export const PAM_ACCOUNT_TABS: PamResourceTab[] = [
icon: Settings,
action: PamResourcePermissionActions.EditAccounts
},
+ {
+ value: PamSheetTab.Rotation,
+ label: "Rotation",
+ icon: RotateCcw,
+ action: PamResourcePermissionActions.ManageRotation
+ },
{
value: PamSheetTab.Advanced,
label: "Advanced",