Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
rotation revamp
x032205924188c8d24c
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex b8464a162e..0e63048365 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -31,6 +31,7 @@ import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-serimport { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";import { TPamDiscoverySourceServiceFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-service";import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";+import { TPamResourceRotationRulesServiceFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-service";import { TPamResourceServiceFactory } from "@app/ee/services/pam-resource/pam-resource-service";import { TPamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";import { TPamWebAccessServiceFactory } from "@app/ee/services/pam-web-access/pam-web-access-service";@@ -366,6 +367,7 @@ declare module "fastify" {offlineUsageReport: TOfflineUsageReportServiceFactory;pamFolder: TPamFolderServiceFactory;pamResource: TPamResourceServiceFactory;+ pamResourceRotationRules: TPamResourceRotationRulesServiceFactory;pamAccount: TPamAccountServiceFactory;pamSession: TPamSessionServiceFactory;pamWebAccess: TPamWebAccessServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 3ca53db833..b5f2da5c77 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -678,6 +678,11 @@ import {TPamDiscoverySourcesUpdate} from "@app/db/schemas/pam-discovery-sources";import { TPamFolders, TPamFoldersInsert, TPamFoldersUpdate } from "@app/db/schemas/pam-folders";+import {+ TPamResourceRotationRules,+ TPamResourceRotationRulesInsert,+ TPamResourceRotationRulesUpdate+} from "@app/db/schemas/pam-resource-rotation-rules";import { TPamResources, TPamResourcesInsert, TPamResourcesUpdate } from "@app/db/schemas/pam-resources";import { TPamSessions, TPamSessionsInsert, TPamSessionsUpdate } from "@app/db/schemas/pam-sessions";import {@@ -1558,6 +1563,11 @@ declare module "knex/types/tables" {TPamAccountDependenciesInsert,TPamAccountDependenciesUpdate>;+ [TableName.PamResourceRotationRule]: KnexOriginal.CompositeTableType<+ TPamResourceRotationRules,+ TPamResourceRotationRulesInsert,+ TPamResourceRotationRulesUpdate+ >;[TableName.Membership]: KnexOriginal.CompositeTableType<TMemberships, TMembershipsInsert, TMembershipsUpdate>;[TableName.MembershipRole]: KnexOriginal.CompositeTableType<diff --git a/backend/src/db/migrations/20260312013215_pam-rotation-rules.ts b/backend/src/db/migrations/20260312013215_pam-rotation-rules.tsnew file mode 100644index 0000000000..f9d30cc796--- /dev/null+++ b/backend/src/db/migrations/20260312013215_pam-rotation-rules.ts@@ -0,0 +1,122 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.PamResourceRotationRule))) {+ await knex.schema.createTable(TableName.PamResourceRotationRule, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("resourceId").notNullable();+ t.foreign("resourceId").references("id").inTable(TableName.PamResource).onDelete("CASCADE");+ t.string("name").nullable();+ t.string("namePattern").notNullable();+ t.boolean("enabled").notNullable().defaultTo(true);+ t.integer("intervalSeconds").nullable();+ t.integer("priority").notNullable();+ t.timestamps(true, true, true);+ t.unique(["resourceId", "priority"]);+ });+ }++ if (!(await knex.schema.hasColumn(TableName.PamAccountDependency, "syncStatus"))) {+ await knex.schema.alterTable(TableName.PamAccountDependency, (t) => {+ t.string("syncStatus").nullable();+ });+ }+ if (!(await knex.schema.hasColumn(TableName.PamAccountDependency, "lastSyncedAt"))) {+ await knex.schema.alterTable(TableName.PamAccountDependency, (t) => {+ t.timestamp("lastSyncedAt").nullable();+ });+ }+ if (!(await knex.schema.hasColumn(TableName.PamAccountDependency, "encryptedLastSyncMessage"))) {+ await knex.schema.alterTable(TableName.PamAccountDependency, (t) => {+ t.binary("encryptedLastSyncMessage").nullable();+ });+ }++ // Migrate existing per-account rotation configs to rules+ if (await knex.schema.hasColumn(TableName.PamAccount, "rotationEnabled")) {+ const accountsWithRotation = await knex(TableName.PamAccount)+ .where("rotationEnabled", true)+ .whereNotNull("rotationIntervalSeconds")+ .select("resourceId", "name", "rotationIntervalSeconds");++ if (accountsWithRotation.length > 0) {+ // Group by resourceId to assign sequential priorities+ const byResource: Record<string, Array<{ name: string; rotationIntervalSeconds: number }>> = {};+ for (const account of accountsWithRotation) {+ if (!byResource[account.resourceId]) {+ byResource[account.resourceId] = [];+ }+ byResource[account.resourceId].push({+ name: account.name,+ rotationIntervalSeconds: account.rotationIntervalSeconds ?? 2592000+ });+ }++ const rulesToInsert = [];+ for (const [resourceId, accounts] of Object.entries(byResource)) {+ for (let i = 0; i < accounts.length; i += 1) {+ rulesToInsert.push({+ resourceId,+ name: accounts[i].name,+ namePattern: accounts[i].name,+ enabled: true,+ intervalSeconds: accounts[i].rotationIntervalSeconds,+ priority: i + 1+ });+ }+ }++ if (rulesToInsert.length > 0) {+ await knex(TableName.PamResourceRotationRule).insert(rulesToInsert);+ }+ }+ }++ // Drop old per-account rotation config columns+ if (await knex.schema.hasColumn(TableName.PamAccount, "rotationEnabled")) {+ await knex.schema.alterTable(TableName.PamAccount, (t) => {+ t.dropColumn("rotationEnabled");+ });+ }+ if (await knex.schema.hasColumn(TableName.PamAccount, "rotationIntervalSeconds")) {+ await knex.schema.alterTable(TableName.PamAccount, (t) => {+ t.dropColumn("rotationIntervalSeconds");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ // Re-add per-account rotation columns+ if (!(await knex.schema.hasColumn(TableName.PamAccount, "rotationEnabled"))) {+ await knex.schema.alterTable(TableName.PamAccount, (t) => {+ t.boolean("rotationEnabled").notNullable().defaultTo(false);+ });+ }+ if (!(await knex.schema.hasColumn(TableName.PamAccount, "rotationIntervalSeconds"))) {+ await knex.schema.alterTable(TableName.PamAccount, (t) => {+ t.integer("rotationIntervalSeconds").nullable();+ });+ }++ // Drop sync columns from dependencies+ if (await knex.schema.hasColumn(TableName.PamAccountDependency, "syncStatus")) {+ await knex.schema.alterTable(TableName.PamAccountDependency, (t) => {+ t.dropColumn("syncStatus");+ });+ }+ if (await knex.schema.hasColumn(TableName.PamAccountDependency, "lastSyncedAt")) {+ await knex.schema.alterTable(TableName.PamAccountDependency, (t) => {+ t.dropColumn("lastSyncedAt");+ });+ }+ if (await knex.schema.hasColumn(TableName.PamAccountDependency, "encryptedLastSyncMessage")) {+ await knex.schema.alterTable(TableName.PamAccountDependency, (t) => {+ t.dropColumn("encryptedLastSyncMessage");+ });+ }++ // Drop rotation rules table+ await knex.schema.dropTableIfExists(TableName.PamResourceRotationRule);+}diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 1b55807ca4..a21ffddb6a 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -113,6 +113,7 @@ export * from "./pam-discovery-source-resources";export * from "./pam-discovery-source-runs";export * from "./pam-discovery-sources";export * from "./pam-folders";+export * from "./pam-resource-rotation-rules";export * from "./pam-resources";export * from "./pam-sessions";export * from "./pki-acme-accounts";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex baeb5418e1..78a634fb19 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -229,6 +229,7 @@ export enum TableName {PamDiscoverySourceAccount = "pam_discovery_source_accounts",PamDiscoverySourceDependency = "pam_discovery_source_dependencies",PamAccountDependency = "pam_account_dependencies",+ PamResourceRotationRule = "pam_resource_rotation_rules",VaultExternalMigrationConfig = "vault_external_migration_configs",diff --git a/backend/src/db/schemas/pam-account-dependencies.ts b/backend/src/db/schemas/pam-account-dependencies.tsindex 2c26e7d171..4025818743 100644--- a/backend/src/db/schemas/pam-account-dependencies.ts+++ b/backend/src/db/schemas/pam-account-dependencies.ts@@ -18,6 +18,9 @@ export const PamAccountDependenciesSchema = z.object({data: z.unknown(),source: z.string(),isEnabled: z.boolean().default(false).nullable().optional(),+ syncStatus: z.string().nullable().optional(),+ lastSyncedAt: z.date().nullable().optional(),+ encryptedLastSyncMessage: z.any().nullable().optional(),createdAt: z.date(),updatedAt: z.date()});diff --git a/backend/src/db/schemas/pam-accounts.ts b/backend/src/db/schemas/pam-accounts.tsindex d68344a7d1..f45ede2950 100644--- a/backend/src/db/schemas/pam-accounts.ts+++ b/backend/src/db/schemas/pam-accounts.ts@@ -19,8 +19,6 @@ export const PamAccountsSchema = z.object({encryptedCredentials: zodBuffer,createdAt: z.date(),updatedAt: z.date(),- rotationEnabled: z.boolean().default(false),- rotationIntervalSeconds: z.number().nullable().optional(),lastRotatedAt: z.date().nullable().optional(),rotationStatus: z.string().nullable().optional(),encryptedLastRotationMessage: zodBuffer.nullable().optional(),diff --git a/backend/src/db/schemas/pam-resource-rotation-rules.ts b/backend/src/db/schemas/pam-resource-rotation-rules.tsnew file mode 100644index 0000000000..eb1606adf9--- /dev/null+++ b/backend/src/db/schemas/pam-resource-rotation-rules.ts@@ -0,0 +1,26 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const PamResourceRotationRulesSchema = z.object({+ id: z.string().uuid(),+ resourceId: z.string().uuid(),+ name: z.string().nullable().optional(),+ namePattern: z.string(),+ enabled: z.boolean().default(true),+ intervalSeconds: z.number().int().nullable().optional(),+ priority: z.number().int(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TPamResourceRotationRules = z.infer<typeof PamResourceRotationRulesSchema>;+export type TPamResourceRotationRulesInsert = Omit<z.input<typeof PamResourceRotationRulesSchema>, TImmutableDBKeys>;+export type TPamResourceRotationRulesUpdate = Partial<+ Omit<z.input<typeof PamResourceRotationRulesSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.tsindex 44174fd364..e75e6871ac 100644--- a/backend/src/ee/routes/v1/index.ts+++ b/backend/src/ee/routes/v1/index.ts@@ -33,6 +33,7 @@ import { PAM_DISCOVERY_REGISTER_ROUTER_MAP } from "./pam-discovery-routers";import { registerPamDiscoveryRouter } from "./pam-discovery-routers/pam-discovery-router";import { registerPamFolderRouter } from "./pam-folder-router";import { PAM_RESOURCE_REGISTER_ROUTER_MAP } from "./pam-resource-routers";+import { registerPamResourceRotationRulesRouter } from "./pam-resource-routers/pam-resource-rotation-rules-router";import { registerPamResourceRouter } from "./pam-resource-routers/pam-resource-router";import { registerPamSessionRouter } from "./pam-session-router";import { registerPITRouter } from "./pit-router";@@ -232,6 +233,7 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {await pamRouter.register(async (pamResourceRouter) => {await pamResourceRouter.register(registerPamResourceRouter);+ await pamResourceRouter.register(registerPamResourceRotationRulesRouter);// Provider-specific endpointsawait Promise.all(diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-endpoints.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-endpoints.tsindex 0179910e19..1b3e761c98 100644--- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-endpoints.ts+++ b/backend/src/ee/routes/v1/pam-account-routers/pam-account-endpoints.ts@@ -23,8 +23,6 @@ export const registerPamAccountEndpoints = <C extends TPamAccount>({folderId?: C["folderId"];name: C["name"];description?: C["description"];- rotationEnabled?: C["rotationEnabled"];- rotationIntervalSeconds?: C["rotationIntervalSeconds"];requireMfa?: C["requireMfa"];internalMetadata?: Record<string, unknown>;metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;@@ -33,8 +31,6 @@ export const registerPamAccountEndpoints = <C extends TPamAccount>({credentials?: C["credentials"];name?: C["name"];description?: C["description"];- rotationEnabled?: C["rotationEnabled"];- rotationIntervalSeconds?: C["rotationIntervalSeconds"];requireMfa?: C["requireMfa"];internalMetadata?: Record<string, unknown>;metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;@@ -80,8 +76,6 @@ export const registerPamAccountEndpoints = <C extends TPamAccount>({folderId: req.body.folderId,name: req.body.name,description: req.body.description,- rotationEnabled: req.body.rotationEnabled ?? false,- rotationIntervalSeconds: req.body.rotationIntervalSeconds,requireMfa: req.body.requireMfa}}@@ -132,8 +126,6 @@ export const registerPamAccountEndpoints = <C extends TPamAccount>({resourceType,name: req.body.name,description: req.body.description,- rotationEnabled: req.body.rotationEnabled,- rotationIntervalSeconds: req.body.rotationIntervalSeconds,requireMfa: req.body.requireMfa}}diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.tsindex 2fde32857c..f0a45fd236 100644--- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts+++ b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts@@ -151,6 +151,50 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "POST",+ url: "/:accountId/rotate",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ operationId: "triggerPamAccountRotation",+ description: "Manually trigger credential rotation for a PAM account",+ params: z.object({+ accountId: z.string().uuid()+ }),+ response: {+ 200: z.object({+ success: z.boolean(),+ accountId: z.string().uuid()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const account = await server.services.pamAccount.triggerManualRotation(req.params.accountId, req.permission);++ if (account) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: account.projectId,+ event: {+ type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION,+ metadata: {+ accountId: req.params.accountId,+ accountName: account.name,+ resourceId: account.resourceId,+ resourceType: "unknown"+ }+ }+ });+ }++ return { success: true, accountId: req.params.accountId };+ }+ });+server.route({method: "GET",url: "/:accountId",diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-rotation-rules-router.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-rotation-rules-router.tsnew file mode 100644index 0000000000..f54a74e574--- /dev/null+++ b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-rotation-rules-router.ts@@ -0,0 +1,183 @@+import { z } from "zod";++import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";++const RotationRuleResponseSchema = z.object({+ id: z.string().uuid(),+ resourceId: z.string().uuid(),+ name: z.string().nullable().optional(),+ namePattern: z.string(),+ enabled: z.boolean(),+ intervalSeconds: z.number().nullable().optional(),+ priority: z.number(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export const registerPamResourceRotationRulesRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/:resourceId/rotation-rules",+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "listPamRotationRules",+ description: "List rotation rules for a PAM resource",+ params: z.object({+ resourceId: z.string().uuid()+ }),+ response: {+ 200: z.object({+ rules: RotationRuleResponseSchema.array()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const rules = await server.services.pamResourceRotationRules.listByResourceId(+ req.params.resourceId,+ req.permission+ );++ return { rules };+ }+ });++ server.route({+ method: "POST",+ url: "/:resourceId/rotation-rules",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ operationId: "createPamRotationRule",+ description: "Create a rotation rule for a PAM resource",+ params: z.object({+ resourceId: z.string().uuid()+ }),+ body: z.object({+ name: z.string().max(255).optional(),+ namePattern: z.string().min(1).max(255),+ enabled: z.boolean().default(true),+ intervalSeconds: z.number().min(3600).nullable().optional()+ }),+ response: {+ 200: z.object({+ rule: RotationRuleResponseSchema+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const rule = await server.services.pamResourceRotationRules.create(+ {+ resourceId: req.params.resourceId,+ ...req.body+ },+ req.permission+ );++ return { rule };+ }+ });++ server.route({+ method: "PATCH",+ url: "/:resourceId/rotation-rules/:ruleId",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ operationId: "updatePamRotationRule",+ description: "Update a rotation rule",+ params: z.object({+ resourceId: z.string().uuid(),+ ruleId: z.string().uuid()+ }),+ body: z.object({+ name: z.string().max(255).nullable().optional(),+ namePattern: z.string().min(1).max(255).optional(),+ enabled: z.boolean().optional(),+ intervalSeconds: z.number().min(3600).nullable().optional()+ }),+ response: {+ 200: z.object({+ rule: RotationRuleResponseSchema+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const rule = await server.services.pamResourceRotationRules.updateById(+ req.params.ruleId,+ req.body,+ req.permission+ );++ return { rule };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:resourceId/rotation-rules/:ruleId",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ operationId: "deletePamRotationRule",+ description: "Delete a rotation rule",+ params: z.object({+ resourceId: z.string().uuid(),+ ruleId: z.string().uuid()+ }),+ response: {+ 200: z.object({+ rule: RotationRuleResponseSchema+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const rule = await server.services.pamResourceRotationRules.deleteById(req.params.ruleId, req.permission);++ return { rule };+ }+ });++ server.route({+ method: "PUT",+ url: "/:resourceId/rotation-rules/reorder",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ operationId: "reorderPamRotationRules",+ description: "Reorder rotation rules for a resource",+ params: z.object({+ resourceId: z.string().uuid()+ }),+ body: z.object({+ ruleIds: z.array(z.string().uuid())+ }),+ response: {+ 200: z.object({+ rules: RotationRuleResponseSchema.array()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const rules = await server.services.pamResourceRotationRules.reorderRules(+ req.params.resourceId,+ req.body.ruleIds,+ req.permission+ );++ return { rules };+ }+ });+};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 3e3485708d..70eb0af483 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -4412,8 +4412,6 @@ interface PamAccountCreateEvent {folderId?: string | null;name: string;description?: string | null;- rotationEnabled: boolean;- rotationIntervalSeconds?: number | null;requireMfa?: boolean | null;};}@@ -4426,8 +4424,6 @@ interface PamAccountUpdateEvent {resourceType: string;name?: string;description?: string | null;- rotationEnabled?: boolean;- rotationIntervalSeconds?: number | null;requireMfa?: boolean | null;};}diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.tsindex ed93fd039a..33dbc1a884 100644--- a/backend/src/ee/services/pam-account/pam-account-dal.ts+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts@@ -155,22 +155,6 @@ export const pamAccountDALFactory = (db: TDbClient) => {}};- const findAccountsDueForRotation = async (tx?: Knex) => {- const dbClient = tx || db.replicaNode();-- const accounts = await dbClient(TableName.PamAccount)- .innerJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)- .whereNotNull(`${TableName.PamResource}.encryptedRotationAccountCredentials`)- .whereNotNull(`${TableName.PamAccount}.rotationIntervalSeconds`)- .where(`${TableName.PamAccount}.rotationEnabled`, true)- .whereRaw(- `COALESCE("${TableName.PamAccount}"."lastRotatedAt", "${TableName.PamAccount}"."createdAt") + "${TableName.PamAccount}"."rotationIntervalSeconds" * interval '1 second' < NOW()`- )- .select(selectAllTableCols(TableName.PamAccount));-- return accounts;- };-const findMetadataByAccountIds = async (accountIds: string[], tx?: Knex) => {if (!accountIds.length) return {};const rows = await (tx || db.replicaNode())(TableName.ResourceMetadata)@@ -190,7 +174,6 @@ export const pamAccountDALFactory = (db: TDbClient) => {...orm,findByProjectIdWithResourceDetails,findByIdWithResourceDetails,- findAccountsDueForRotation,findMetadataByAccountIds};};diff --git a/backend/src/ee/services/pam-account/pam-account-enums.ts b/backend/src/ee/services/pam-account/pam-account-enums.tsindex 92b95df947..0def2bd5c4 100644--- a/backend/src/ee/services/pam-account/pam-account-enums.ts+++ b/backend/src/ee/services/pam-account/pam-account-enums.ts@@ -6,3 +6,9 @@ export enum PamAccountView {Flat = "flat",Nested = "nested"}++export enum PamAccountRotationStatus {+ Rotating = "rotating",+ Success = "success",+ Failed = "failed"+}diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 79f624f76a..719150ea1e 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -1,4 +1,5 @@import { ForbiddenError, subject } from "@casl/ability";+import picomatch from "picomatch";import { ActionProjectType, OrganizationActionScope, TPamAccounts, TPamResources } from "@app/db/schemas";import {@@ -50,8 +51,10 @@ import { TUserDALFactory } from "@app/services/user/user-dal";import { EventType, TAuditLogServiceFactory } from "../audit-log/audit-log-types";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";+import { TPamAccountDependenciesDALFactory } from "../pam-discovery/pam-account-dependencies-dal";import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";import { PamResource } from "../pam-resource/pam-resource-enums";+import { TPamResourceRotationRulesDALFactory } from "../pam-resource/pam-resource-rotation-rules-dal";import { TPamAccountCredentials } from "../pam-resource/pam-resource-types";import { TRedisAccountCredentials } from "../pam-resource/redis/redis-resource-types";import { TSqlAccountCredentials, TSqlResourceConnectionDetails } from "../pam-resource/shared/sql/sql-resource-types";@@ -60,6 +63,7 @@ import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";import { PamSessionStatus } from "../pam-session/pam-session-enums";import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPamAccountDALFactory } from "./pam-account-dal";+import { PamAccountRotationStatus } from "./pam-account-enums";import { decryptAccount, decryptAccountCredentials, encryptAccountCredentials } from "./pam-account-fns";import {TAccessAccountDTO,@@ -73,6 +77,7 @@ type TPamAccountServiceFactoryDep = {pamResourceDAL: TPamResourceDALFactory;pamSessionDAL: TPamSessionDALFactory;pamAccountDAL: TPamAccountDALFactory;+ pamResourceRotationRulesDAL: Pick<TPamResourceRotationRulesDALFactory, "findByResourceIds">;mfaSessionService: TMfaSessionServiceFactory;projectDAL: TProjectDALFactory;orgDAL: TOrgDALFactory;@@ -90,6 +95,7 @@ type TPamAccountServiceFactoryDep = {approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory;pamSessionExpirationService: Pick<TPamSessionExpirationServiceFactory, "scheduleSessionExpiration">;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;+ pamAccountDependenciesDAL: Pick<TPamAccountDependenciesDALFactory, "findByAccountId" | "updateById">;};export type TPamAccountServiceFactory = ReturnType<typeof pamAccountServiceFactory>;@@ -100,6 +106,7 @@ export const pamAccountServiceFactory = ({pamResourceDAL,pamSessionDAL,pamAccountDAL,+ pamResourceRotationRulesDAL,mfaSessionService,projectDAL,orgDAL,@@ -111,29 +118,13 @@ export const pamAccountServiceFactory = ({approvalPolicyDAL,approvalRequestGrantsDAL,pamSessionExpirationService,- resourceMetadataDAL+ resourceMetadataDAL,+ pamAccountDependenciesDAL}: TPamAccountServiceFactoryDep) => {const create = async (- {- credentials,- resourceId,- name,- description,- folderId,- rotationEnabled,- rotationIntervalSeconds,- requireMfa,- internalMetadata,- metadata- }: TCreateAccountDTO,+ { credentials, resourceId, name, description, folderId, requireMfa, internalMetadata, metadata }: TCreateAccountDTO,actor: OrgServiceActor) => {- if (rotationEnabled && (rotationIntervalSeconds === undefined || rotationIntervalSeconds === null)) {- throw new BadRequestError({- message: "Rotation interval must be defined when rotation is enabled."- });- }-const resource = await pamResourceDAL.findById(resourceId);if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });@@ -146,10 +137,6 @@ export const pamAccountServiceFactory = ({actionProjectType: ActionProjectType.PAM});- if (!resource.encryptedRotationAccountCredentials && rotationEnabled) {- throw new NotFoundError({ message: "Rotation credentials are not configured for this account's resource" });- }-ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionPamAccountActions.Create,subject(ProjectPermissionSub.PamAccounts, {@@ -200,8 +187,6 @@ export const pamAccountServiceFactory = ({name,description,folderId,- rotationEnabled,- rotationIntervalSeconds,requireMfa,internalMetadata: internalMetadata ?? null},@@ -247,17 +232,7 @@ export const pamAccountServiceFactory = ({};const updateById = async (- {- accountId,- credentials,- description,- name,- rotationEnabled,- rotationIntervalSeconds,- requireMfa,- internalMetadata,- metadata- }: TUpdateAccountDTO,+ { accountId, credentials, description, name, requireMfa, internalMetadata, metadata }: TUpdateAccountDTO,actor: OrgServiceActor) => {const account = await pamAccountDAL.findById(accountId);@@ -314,17 +289,6 @@ export const pamAccountServiceFactory = ({updateDoc.description = description;}- if (rotationEnabled !== undefined) {- if (!resource.encryptedRotationAccountCredentials && rotationEnabled) {- throw new NotFoundError({ message: "Rotation credentials are not configured for this account's resource" });- }- updateDoc.rotationEnabled = rotationEnabled;- }-- if (rotationIntervalSeconds !== undefined) {- updateDoc.rotationIntervalSeconds = rotationIntervalSeconds;- }-if (internalMetadata !== undefined) {updateDoc.internalMetadata = internalMetadata;}@@ -1074,123 +1038,224 @@ export const pamAccountServiceFactory = ({};};- const rotateAllDueAccounts = async () => {- const accounts = await pamAccountDAL.findAccountsDueForRotation();+ // Find accounts due for rotation using rule-based matching+ const findAccountsDueForRotation = async () => {+ // Get only resources with rotation credentials configured+ const resourcesWithRotationCreds = await pamResourceDAL.find({+ $notNull: ["encryptedRotationAccountCredentials"]+ });+ if (!resourcesWithRotationCreds.length) return [];- for (let i = 0; i < accounts.length; i += ROTATION_CONCURRENCY_LIMIT) {- const batch = accounts.slice(i, i + ROTATION_CONCURRENCY_LIMIT);+ const resourceIds = resourcesWithRotationCreds.map((r) => r.id);- const rotationPromises = batch.map(async (account) => {- let logResourceType = "unknown";- try {- await pamAccountDAL.transaction(async (tx) => {- const resource = await pamResourceDAL.findById(account.resourceId, tx);- if (!resource || !resource.encryptedRotationAccountCredentials) return;- logResourceType = resource.resourceType;-- const { connectionDetails, rotationAccountCredentials, gatewayId, resourceType } = await decryptResource(- resource,- account.projectId,- kmsService- );+ const allRules = await pamResourceRotationRulesDAL.findByResourceIds(resourceIds);+ if (!allRules.length) return [];- if (!rotationAccountCredentials) return;+ // Group rules by resource+ const rulesByResource: Record<string, typeof allRules> = {};+ for (const rule of allRules) {+ if (!rulesByResource[rule.resourceId]) rulesByResource[rule.resourceId] = [];+ rulesByResource[rule.resourceId].push(rule);+ }- const accountCredentials = await decryptAccountCredentials({- encryptedCredentials: account.encryptedCredentials,- projectId: account.projectId,- kmsService- });+ // Get accounts for resources that have rules+ const resourceIdsWithRules = Object.keys(rulesByResource);+ const accounts = await pamAccountDAL.find({ $in: { resourceId: resourceIdsWithRules } });- const factory = PAM_RESOURCE_FACTORY_MAP[resourceType as PamResource](- resourceType as PamResource,- connectionDetails,- gatewayId,- gatewayV2Service,- account.projectId- );+ const now = Date.now();+ const dueAccounts: TPamAccounts[] = [];- const newCredentials = await factory.rotateAccountCredentials(- rotationAccountCredentials,- accountCredentials- );+ for (const account of accounts) {+ const rules = rulesByResource[account.resourceId];+ // eslint-disable-next-line no-continue+ if (!rules) continue;- const encryptedCredentials = await encryptAccountCredentials({- credentials: newCredentials,- projectId: account.projectId,- kmsService- });-- await pamAccountDAL.updateById(- account.id,- {- encryptedCredentials,- lastRotatedAt: new Date(),- rotationStatus: "success",- encryptedLastRotationMessage: null- },- tx- );+ // Find first matching rule by priority (already sorted by DAL)+ const matchedRule = rules.find((rule) => picomatch.isMatch(account.name, rule.namePattern));- await auditLogService.createAuditLog({- projectId: account.projectId,- actor: {- type: ActorType.PLATFORM,- metadata: {}- },- event: {- type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION,- metadata: {- accountId: account.id,- accountName: account.name,- resourceId: resource.id,- resourceType: logResourceType- }- }- });- });- } catch (error) {- logger.error(error, `Failed to rotate credentials for account [accountId=${account.id}]`);+ // eslint-disable-next-line no-continue+ if (!matchedRule || !matchedRule.enabled || !matchedRule.intervalSeconds) continue;- const errorMessage = error instanceof Error ? error.message : "An unknown error occurred";+ // Skip if already rotating+ // eslint-disable-next-line no-continue+ if (account.rotationStatus === PamAccountRotationStatus.Rotating) continue;- const { encryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId: account.projectId- });+ // Check if interval has elapsed+ const lastRotated = account.lastRotatedAt+ ? new Date(account.lastRotatedAt).getTime()+ : account.createdAt.getTime();- const { cipherTextBlob: encryptedMessage } = encryptor({- plainText: Buffer.from(errorMessage)- });+ const nextRotationAt = lastRotated + matchedRule.intervalSeconds * 1000;- await pamAccountDAL.updateById(account.id, {- rotationStatus: "failed",- encryptedLastRotationMessage: encryptedMessage- });+ // eslint-disable-next-line no-continue+ if (nextRotationAt > now) continue;- await auditLogService.createAuditLog({- projectId: account.projectId,- actor: {- type: ActorType.PLATFORM,- metadata: {}- },- event: {- type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION_FAILED,- metadata: {- accountId: account.id,- accountName: account.name,- resourceId: account.resourceId,- resourceType: logResourceType,- errorMessage- }- }+ dueAccounts.push(account);+ }++ return dueAccounts;+ };++ const rotateAccount = async (account: TPamAccounts) => {+ let logResourceType = "unknown";+ try {+ // Read resource and mark account as rotating+ const resource = await pamResourceDAL.findById(account.resourceId);+ if (!resource || !resource.encryptedRotationAccountCredentials) return;+ logResourceType = resource.resourceType;++ const { connectionDetails, rotationAccountCredentials, gatewayId, resourceType } = await decryptResource(+ resource,+ account.projectId,+ kmsService+ );+ if (!rotationAccountCredentials) return;++ await pamAccountDAL.updateById(account.id, { rotationStatus: PamAccountRotationStatus.Rotating });++ // Perform rotation+ const accountCredentials = await decryptAccountCredentials({+ encryptedCredentials: account.encryptedCredentials,+ projectId: account.projectId,+ kmsService+ });++ const factory = PAM_RESOURCE_FACTORY_MAP[resourceType as PamResource](+ resourceType as PamResource,+ connectionDetails,+ gatewayId,+ gatewayV2Service,+ account.projectId+ );+ const newCredentials = await factory.rotateAccountCredentials(rotationAccountCredentials, accountCredentials);++ // Save result+ const encryptedCredentials = await encryptAccountCredentials({+ credentials: newCredentials,+ projectId: account.projectId,+ kmsService+ });++ await pamAccountDAL.updateById(account.id, {+ encryptedCredentials,+ lastRotatedAt: new Date(),+ rotationStatus: PamAccountRotationStatus.Success,+ encryptedLastRotationMessage: null+ });++ await auditLogService.createAuditLog({+ projectId: account.projectId,+ actor: {+ type: ActorType.PLATFORM,+ metadata: {}+ },+ event: {+ type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION,+ metadata: {+ accountId: account.id,+ accountName: account.name,+ resourceId: resource.id,+ resourceType: logResourceType+ }+ }+ });++ // Run post-rotate hook+ if (factory.postRotate) {+ try {+ await factory.postRotate(account.id, newCredentials, account.projectId, {+ pamAccountDependenciesDAL,+ pamResourceDAL,+ kmsService});+ } catch (postRotateError) {+ logger.error(postRotateError, `Post-rotation hook failed for account [accountId=${account.id}]`);}+ }+ } catch (error) {+ logger.error(error, `Failed to rotate credentials for account [accountId=${account.id}]`);++ const errorMessage = error instanceof Error ? error.message : "An unknown error occurred";++ const { encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId: account.projectId});+ const { cipherTextBlob: encryptedMessage } = encryptor({+ plainText: Buffer.from(errorMessage)+ });++ await pamAccountDAL.updateById(account.id, {+ rotationStatus: PamAccountRotationStatus.Failed,+ encryptedLastRotationMessage: encryptedMessage+ });++ await auditLogService.createAuditLog({+ projectId: account.projectId,+ actor: {+ type: ActorType.PLATFORM,+ metadata: {}+ },+ event: {+ type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION_FAILED,+ metadata: {+ accountId: account.id,+ accountName: account.name,+ resourceId: account.resourceId,+ resourceType: logResourceType,+ errorMessage+ }+ }+ });+ }+ };++ const rotateAllDueAccounts = async () => {+ const accounts = await findAccountsDueForRotation();++ for (let i = 0; i < accounts.length; i += ROTATION_CONCURRENCY_LIMIT) {+ const batch = accounts.slice(i, i + ROTATION_CONCURRENCY_LIMIT);// eslint-disable-next-line no-await-in-loop- await Promise.all(rotationPromises);+ await Promise.all(batch.map(rotateAccount));+ }+ };++ const triggerManualRotation = async (accountId: string, actor: OrgServiceActor) => {+ const account = await pamAccountDAL.findById(accountId);+ if (!account) throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });++ const resource = await pamResourceDAL.findById(account.resourceId);+ if (!resource) throw new NotFoundError({ message: `Resource not found` });++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId: account.projectId,+ actionProjectType: ActionProjectType.PAM+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionPamAccountActions.TriggerRotation,+ subject(ProjectPermissionSub.PamAccounts, {+ resourceName: resource.name,+ accountName: account.name+ })+ );++ if (!resource.encryptedRotationAccountCredentials) {+ throw new BadRequestError({ message: "Rotation credentials are not configured on this resource" });}++ if (account.rotationStatus === PamAccountRotationStatus.Rotating) {+ throw new BadRequestError({ message: "Account is already being rotated" });+ }++ await rotateAccount(account);++ return pamAccountDAL.findById(accountId);};return {@@ -1201,6 +1266,7 @@ export const pamAccountServiceFactory = ({getById,access,getSessionCredentials,- rotateAllDueAccounts+ rotateAllDueAccounts,+ triggerManualRotation};};diff --git a/backend/src/ee/services/pam-account/pam-account-types.ts b/backend/src/ee/services/pam-account/pam-account-types.tsindex 8225adc79b..d66b966ef5 100644--- a/backend/src/ee/services/pam-account/pam-account-types.ts+++ b/backend/src/ee/services/pam-account/pam-account-types.ts@@ -9,9 +9,8 @@ import { PamAccountOrderBy, PamAccountView } from "./pam-account-enums";// DTOsexport type TCreateAccountDTO = Pick<TPamAccount,- "name" | "description" | "credentials" | "folderId" | "resourceId" | "rotationIntervalSeconds" | "requireMfa"+ "name" | "description" | "credentials" | "folderId" | "resourceId" | "requireMfa"> & {- rotationEnabled?: boolean;internalMetadata?: Record<string, unknown>;metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;};diff --git a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas.ts b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas.tsindex cbb1df1a7b..cc79f17d8c 100644--- a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas.ts+++ b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas.ts@@ -64,9 +64,7 @@ export const AwsIamAccountSchema = BasePamAccountSchema.extend({});export const CreateAwsIamAccountSchema = BaseCreatePamAccountSchema.extend({- credentials: AwsIamAccountCredentialsSchema,- // AWS IAM accounts don't support credential rotation - they use role assumption- rotationEnabled: z.boolean().default(false)+ credentials: AwsIamAccountCredentialsSchema});export const UpdateAwsIamAccountSchema = BaseUpdatePamAccountSchema.extend({diff --git a/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-dal.ts b/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-dal.tsnew file mode 100644index 0000000000..5296bb6818--- /dev/null+++ b/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-dal.ts@@ -0,0 +1,56 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify } from "@app/lib/knex";++export type TPamResourceRotationRulesDALFactory = ReturnType<typeof pamResourceRotationRulesDALFactory>;++export const pamResourceRotationRulesDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.PamResourceRotationRule);++ const findByResourceId = async (resourceId: string, tx?: Knex) => {+ try {+ return await (tx || db.replicaNode())(TableName.PamResourceRotationRule)+ .where({ resourceId })+ .orderBy("priority", "asc")+ .select("*");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find rotation rules by resource ID" });+ }+ };++ const findByResourceIds = async (resourceIds: string[], tx?: Knex) => {+ try {+ if (!resourceIds.length) return [];++ return await (tx || db.replicaNode())(TableName.PamResourceRotationRule)+ .whereIn("resourceId", resourceIds)+ .orderBy("priority", "asc")+ .select("*");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find rotation rules by resource IDs" });+ }+ };++ const getMaxPriority = async (resourceId: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.PamResourceRotationRule)+ .where({ resourceId })+ .max("priority as maxPriority")+ .first();++ return Number((result as { maxPriority?: number | null })?.maxPriority) || 0;+ } catch (error) {+ throw new DatabaseError({ error, name: "Get max rotation rule priority" });+ }+ };++ return {+ ...orm,+ findByResourceId,+ findByResourceIds,+ getMaxPriority+ };+};diff --git a/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-service.ts b/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-service.tsnew file mode 100644index 0000000000..8b1d6193e3--- /dev/null+++ b/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-service.ts@@ -0,0 +1,190 @@+import { ForbiddenError, subject } from "@casl/ability";+import picomatch from "picomatch";++import { ActionProjectType } from "@app/db/schemas";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { OrgServiceActor } from "@app/lib/types";++import { TPermissionServiceFactory } from "../permission/permission-service-types";+import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";+import { TPamResourceDALFactory } from "./pam-resource-dal";+import { TPamResourceRotationRulesDALFactory } from "./pam-resource-rotation-rules-dal";++type TPamResourceRotationRulesServiceFactoryDep = {+ pamResourceRotationRulesDAL: TPamResourceRotationRulesDALFactory;+ pamResourceDAL: Pick<TPamResourceDALFactory, "findById">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+};++export type TPamResourceRotationRulesServiceFactory = ReturnType<typeof pamResourceRotationRulesServiceFactory>;++export const pamResourceRotationRulesServiceFactory = ({+ pamResourceRotationRulesDAL,+ pamResourceDAL,+ permissionService+}: TPamResourceRotationRulesServiceFactoryDep) => {+ const ensureEditPermission = async (resourceId: string, actor: OrgServiceActor) => {+ const resource = await pamResourceDAL.findById(resourceId);+ if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId: resource.projectId,+ actionProjectType: ActionProjectType.PAM+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionActions.Edit,+ subject(ProjectPermissionSub.PamResources, { name: resource.name })+ );++ return resource;+ };++ const listByResourceId = async (resourceId: string, actor: OrgServiceActor) => {+ const resource = await pamResourceDAL.findById(resourceId);+ if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId: resource.projectId,+ actionProjectType: ActionProjectType.PAM+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionActions.Read,+ subject(ProjectPermissionSub.PamResources, { name: resource.name })+ );++ return pamResourceRotationRulesDAL.findByResourceId(resourceId);+ };++ const create = async (+ {+ resourceId,+ name,+ namePattern,+ enabled,+ intervalSeconds+ }: {+ resourceId: string;+ name?: string;+ namePattern: string;+ enabled: boolean;+ intervalSeconds?: number | null;+ },+ actor: OrgServiceActor+ ) => {+ await ensureEditPermission(resourceId, actor);++ if (enabled && (intervalSeconds === undefined || intervalSeconds === null)) {+ throw new BadRequestError({ message: "Interval is required when the rule is enabled" });+ }++ // Validate glob pattern+ try {+ picomatch.parse(namePattern);+ } catch {+ throw new BadRequestError({ message: `Invalid glob pattern: ${namePattern}` });+ }++ const maxPriority = await pamResourceRotationRulesDAL.getMaxPriority(resourceId);++ return pamResourceRotationRulesDAL.create({+ resourceId,+ name: name ?? null,+ namePattern,+ enabled,+ intervalSeconds: intervalSeconds ?? null,+ priority: maxPriority + 1+ });+ };++ const updateById = async (+ ruleId: string,+ updates: {+ name?: string | null;+ namePattern?: string;+ enabled?: boolean;+ intervalSeconds?: number | null;+ },+ actor: OrgServiceActor+ ) => {+ const rule = await pamResourceRotationRulesDAL.findById(ruleId);+ if (!rule) throw new NotFoundError({ message: `Rotation rule with ID '${ruleId}' not found` });++ await ensureEditPermission(rule.resourceId, actor);++ const finalEnabled = updates.enabled ?? rule.enabled;+ const finalInterval = updates.intervalSeconds !== undefined ? updates.intervalSeconds : rule.intervalSeconds;++ if (finalEnabled && (finalInterval === undefined || finalInterval === null)) {+ throw new BadRequestError({ message: "Interval is required when the rule is enabled" });+ }++ if (updates.namePattern) {+ try {+ picomatch.parse(updates.namePattern);+ } catch {+ throw new BadRequestError({ message: `Invalid glob pattern: ${updates.namePattern}` });+ }+ }++ return pamResourceRotationRulesDAL.updateById(ruleId, updates);+ };++ const deleteById = async (ruleId: string, actor: OrgServiceActor) => {+ const rule = await pamResourceRotationRulesDAL.findById(ruleId);+ if (!rule) throw new NotFoundError({ message: `Rotation rule with ID '${ruleId}' not found` });++ await ensureEditPermission(rule.resourceId, actor);++ return pamResourceRotationRulesDAL.deleteById(ruleId);+ };++ const reorderRules = async (resourceId: string, orderedRuleIds: string[], actor: OrgServiceActor) => {+ await ensureEditPermission(resourceId, actor);++ const existingRules = await pamResourceRotationRulesDAL.findByResourceId(resourceId);+ const existingIds = new Set(existingRules.map((r) => r.id));++ for (const id of orderedRuleIds) {+ if (!existingIds.has(id)) {+ throw new BadRequestError({ message: `Rule ID '${id}' does not belong to resource '${resourceId}'` });+ }+ }++ if (orderedRuleIds.length !== existingRules.length) {+ throw new BadRequestError({ message: "All rules must be included in the reorder request" });+ }++ await pamResourceRotationRulesDAL.transaction(async (tx) => {+ // Set all priorities to negative (temp) to avoid unique constraint violations during reorder+ for (let i = 0; i < orderedRuleIds.length; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await pamResourceRotationRulesDAL.updateById(orderedRuleIds[i], { priority: -(i + 1) }, tx);+ }+ // Now set final priorities+ for (let i = 0; i < orderedRuleIds.length; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await pamResourceRotationRulesDAL.updateById(orderedRuleIds[i], { priority: i + 1 }, tx);+ }+ });++ return pamResourceRotationRulesDAL.findByResourceId(resourceId);+ };++ return {+ listByResourceId,+ create,+ updateById,+ deleteById,+ reorderRules+ };+};diff --git a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts b/backend/src/ee/services/pam-resource/pam-resource-schemas.tsindex 02e65c0090..8e8d7e4ea0 100644--- a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts+++ b/backend/src/ee/services/pam-resource/pam-resource-schemas.ts@@ -72,8 +72,6 @@ export const BaseCreatePamAccountSchema = z.object({folderId: z.string().uuid().optional(),name: slugSchema({ field: "name" }),description: z.string().max(512).nullable().optional(),- rotationEnabled: z.boolean(),- rotationIntervalSeconds: z.number().min(3600).nullable().optional(),requireMfa: z.boolean().optional().default(false),metadata: ResourceMetadataNonEncryptionSchema.optional()});@@ -81,8 +79,6 @@ export const BaseCreatePamAccountSchema = z.object({export const BaseUpdatePamAccountSchema = z.object({name: slugSchema({ field: "name" }).optional(),description: z.string().max(512).nullable().optional(),- rotationEnabled: z.boolean().optional(),- rotationIntervalSeconds: z.number().min(3600).nullable().optional(),requireMfa: z.boolean().optional(),metadata: ResourceMetadataNonEncryptionSchema.optional()});diff --git a/backend/src/ee/services/pam-resource/pam-resource-types.ts b/backend/src/ee/services/pam-resource/pam-resource-types.tsindex c9eb3404f8..dea374fbc7 100644--- a/backend/src/ee/services/pam-resource/pam-resource-types.ts+++ b/backend/src/ee/services/pam-resource/pam-resource-types.ts@@ -1,9 +1,11 @@import { z } from "zod";import { OrderByDirection, TProjectPermission } from "@app/lib/types";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";+import { TPamAccountDependenciesDALFactory } from "../pam-discovery/pam-account-dependencies-dal";import {TActiveDirectoryAccount,TActiveDirectoryAccountCredentials,@@ -28,6 +30,7 @@ import {TMySQLResource,TMySQLResourceConnectionDetails} from "./mysql/mysql-resource-types";+import { TPamResourceDALFactory } from "./pam-resource-dal";import { PamResource, PamResourceOrderBy } from "./pam-resource-enums";import {TPostgresAccount,@@ -131,6 +134,12 @@ export type TPamResourceFactoryRotateAccountCredentials<C extends TPamAccountCrecurrentCredentials: C) => Promise<C>;+export type TPostRotateContext = {+ pamAccountDependenciesDAL: Pick<TPamAccountDependenciesDALFactory, "findByAccountId" | "updateById">;+ pamResourceDAL: Pick<TPamResourceDALFactory, "findById">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+};+export type TPamResourceFactory<T extends TPamResourceConnectionDetails,C extends TPamAccountCredentials,@@ -146,5 +155,6 @@ export type TPamResourceFactory<validateConnection: TPamResourceFactoryValidateConnection<T>;validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<C>;rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<C>;+ postRotate?: (accountId: string, newCredentials: C, projectId: string, ctx: TPostRotateContext) => Promise<void>;handleOverwritePreventionForCensoredValues: (updatedAccountCredentials: C, currentCredentials: C) => Promise<C>;};diff --git a/backend/src/ee/services/pam-resource/shared/dependency-sync-fns.ts b/backend/src/ee/services/pam-resource/shared/dependency-sync-fns.tsnew file mode 100644index 0000000000..9a6f3ffec6--- /dev/null+++ b/backend/src/ee/services/pam-resource/shared/dependency-sync-fns.ts@@ -0,0 +1,213 @@+import { runPowershell } from "winrm-client";++import { TPamAccountDependencies, TPamResources } from "@app/db/schemas";+import { groupBy } from "@app/lib/fn";+import { GatewayProxyProtocol } from "@app/lib/gateway";+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";+import { logger } from "@app/lib/logger";+import { KmsDataKey } from "@app/services/kms/kms-types";++import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";+import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";+import { PamAccountDependencyType } from "../../pam-discovery/pam-discovery-enums";+import { decryptResource } from "../pam-resource-fns";+import { TPostRotateContext } from "../pam-resource-types";++export const WINRM_PORT = 5985;++// Escape a string for use inside PowerShell single-quoted strings (doubles single quotes)+export const escapePowershellSingleQuote = (value: string) => value.replace(/'/g, "''");++export const buildDependencySyncScript = (+ dep: TPamAccountDependencies,+ accountUsername: string,+ newPassword: string+): string => {+ const escapedPassword = escapePowershellSingleQuote(newPassword);+ const escapedName = escapePowershellSingleQuote(dep.name);+ const escapedUsername = escapePowershellSingleQuote(accountUsername);++ switch (dep.dependencyType) {+ case PamAccountDependencyType.WindowsService:+ return [+ `sc.exe config '${escapedName}' obj= '${escapedUsername}' password= '${escapedPassword}'`,+ `Restart-Service -Name '${escapedName}' -Force -ErrorAction SilentlyContinue`+ ].join("; ");++ case PamAccountDependencyType.ScheduledTask: {+ const taskData = dep.data as { TaskPath?: string } | null;+ const taskPath = taskData?.TaskPath ?? "\\";+ const escapedPath = escapePowershellSingleQuote(taskPath);+ return `schtasks.exe /Change /TN '${escapedPath}${escapedName}' /RU '${escapedUsername}' /RP '${escapedPassword}'`;+ }++ case PamAccountDependencyType.IisAppPool:+ return [+ `Import-Module WebAdministration`,+ `Set-ItemProperty 'IIS:\\AppPools\\${escapedName}' processModel.userName '${escapedUsername}'`,+ `Set-ItemProperty 'IIS:\\AppPools\\${escapedName}' processModel.password '${escapedPassword}'`,+ `Restart-WebAppPool '${escapedName}'`+ ].join("; ");++ default:+ throw new Error(`Unknown dependency type: ${dep.dependencyType}`);+ }+};++type TSyncDependenciesParams = {+ accountId: string;+ newCredentials: { username: string; password: string };+ projectId: string;+ ctx: TPostRotateContext;+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ formatWinrmUsername?: (rotationUsername: string, hostname: string, resourceType: string) => string;+};++export const syncDependenciesAfterRotation = async ({+ accountId,+ newCredentials,+ projectId,+ ctx,+ gatewayV2Service,+ formatWinrmUsername+}: TSyncDependenciesParams) => {+ const allDeps = await ctx.pamAccountDependenciesDAL.findByAccountId(accountId);+ const enabledDeps = allDeps.filter((d) => d.isEnabled);+ if (!enabledDeps.length) return;++ const grouped = groupBy(enabledDeps, (d) => d.resourceId);++ // Batch-fetch all target resources in a single query+ const resourceIds = Object.keys(grouped);+ const resources = await ctx.pamResourceDAL.find({ $in: { id: resourceIds } });+ const resourceMap = new Map(resources.map((r) => [r.id, r]));++ // Create encryptor lazily (only on first error)+ let encryptor: ((params: { plainText: Buffer }) => { cipherTextBlob: Buffer }) | null = null;+ const getEncryptor = async () => {+ if (!encryptor) {+ const cipherPair = await ctx.kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });+ encryptor = cipherPair.encryptor;+ }+ return encryptor;+ };++ await Promise.all(+ Object.entries(grouped).map(async ([resourceId, deps]) => {+ const resource = resourceMap.get(resourceId);+ if (!resource) {+ logger.warn(`[DependencySync] Resource ${resourceId} not found, skipping`);+ return;+ }++ let rotationCredentials: { username: string; password: string } | null = null;+ let depGatewayId: string | null = null;+ let hostname: string | null = null;++ try {+ const decrypted = await decryptResource(resource as TPamResources, projectId, ctx.kmsService);+ rotationCredentials = decrypted.rotationAccountCredentials as {+ username: string;+ password: string;+ } | null;+ depGatewayId = decrypted.gatewayId ?? null;++ const connDetails = decrypted.connectionDetails as { hostname?: string; domain?: string };+ hostname = connDetails.hostname ?? connDetails.domain ?? null;+ } catch (err) {+ logger.error(err, `[DependencySync] Failed to decrypt resource ${resourceId}`);+ return;+ }++ if (!rotationCredentials || !depGatewayId || !hostname) {+ logger.warn(`[DependencySync] Missing rotation credentials or gateway for resource ${resourceId}, skipping`);+ return;+ }++ const winrmUsername = formatWinrmUsername+ ? formatWinrmUsername(rotationCredentials.username, hostname, resource.resourceType)+ : rotationCredentials.username;++ // Resolve host and gateway connection once per resource group+ const [targetHost] = await verifyHostInputValidity({+ host: hostname,+ isGateway: true,+ isDynamicSecret: false+ });++ const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId: depGatewayId,+ targetHost,+ targetPort: WINRM_PORT+ });++ if (!platformConnectionDetails) {+ logger.warn(`[DependencySync] Unable to connect to gateway for resource ${resourceId}, skipping`);+ return;+ }++ // eslint-disable-next-line no-restricted-syntax+ for (const dep of deps) {+ try {+ // eslint-disable-next-line no-await-in-loop+ await ctx.pamAccountDependenciesDAL.updateById(dep.id, { syncStatus: "pending" });++ const script = buildDependencySyncScript(dep, newCredentials.username, newCredentials.password);++ // eslint-disable-next-line no-await-in-loop+ await withGatewayV2Proxy(+ async (proxyPort) => {+ await runPowershell(script, "localhost", winrmUsername, rotationCredentials!.password, proxyPort);+ },+ {+ protocol: GatewayProxyProtocol.Tcp,+ relayHost: platformConnectionDetails.relayHost,+ gateway: platformConnectionDetails.gateway,+ relay: platformConnectionDetails.relay+ }+ );++ // eslint-disable-next-line no-await-in-loop+ await ctx.pamAccountDependenciesDAL.updateById(dep.id, {+ syncStatus: "success",+ lastSyncedAt: new Date(),+ encryptedLastSyncMessage: null+ });++ logger.info(`[DependencySync] Synced ${dep.dependencyType} '${dep.name}' on resource ${resourceId}`);+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ logger.error(+ error,+ `[DependencySync] Failed to sync ${dep.dependencyType} '${dep.name}' on resource ${resourceId}`+ );++ try {+ // eslint-disable-next-line no-await-in-loop+ const enc = await getEncryptor();+ const { cipherTextBlob: encryptedMessage } = enc({+ plainText: Buffer.from(errorMessage)+ });++ // eslint-disable-next-line no-await-in-loop+ await ctx.pamAccountDependenciesDAL.updateById(dep.id, {+ syncStatus: "failed",+ lastSyncedAt: new Date(),+ encryptedLastSyncMessage: encryptedMessage+ });+ } catch (encryptErr) {+ logger.error(encryptErr, `[DependencySync] Failed to encrypt error message for dep ${dep.id}`);+ // eslint-disable-next-line no-await-in-loop+ await ctx.pamAccountDependenciesDAL.updateById(dep.id, {+ syncStatus: "failed",+ lastSyncedAt: new Date()+ });+ }+ }+ }+ })+ );+};diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex 9e6b118add..4b523dff09 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -378,7 +378,9 @@ const buildAdminPermissionRules = () => {ProjectPermissionPamAccountActions.Read,ProjectPermissionPamAccountActions.Create,ProjectPermissionPamAccountActions.Edit,- ProjectPermissionPamAccountActions.Delete+ ProjectPermissionPamAccountActions.Delete,+ ProjectPermissionPamAccountActions.TriggerRotation,+ ProjectPermissionPamAccountActions.EditRotationConfig],ProjectPermissionSub.PamAccounts);diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.tsindex cdb679fac5..3521c7e070 100644--- a/backend/src/ee/services/permission/project-permission.ts+++ b/backend/src/ee/services/permission/project-permission.ts@@ -244,7 +244,9 @@ export enum ProjectPermissionPamAccountActions {Read = "read",Create = "create",Edit = "edit",- Delete = "delete"+ Delete = "delete",+ TriggerRotation = "trigger-rotation",+ EditRotationConfig = "edit-rotation-config"}export enum ProjectPermissionPamSessionActions {diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 79b5d5a569..e4e15f2dda 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -94,6 +94,8 @@ import { pamDiscoverySourceServiceFactory } from "@app/ee/services/pam-discoveryimport { pamFolderDALFactory } from "@app/ee/services/pam-folder/pam-folder-dal";import { pamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";import { pamResourceDALFactory } from "@app/ee/services/pam-resource/pam-resource-dal";+import { pamResourceRotationRulesDALFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-dal";+import { pamResourceRotationRulesServiceFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-service";import { pamResourceServiceFactory } from "@app/ee/services/pam-resource/pam-resource-service";import { pamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";import { pamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";@@ -2619,6 +2621,7 @@ export const registerRoutes = async (const pamDiscoverySourceAccountsDAL = pamDiscoverySourceAccountsDALFactory(db);const pamDiscoverySourceDependenciesDAL = pamDiscoverySourceDependenciesDALFactory(db);const pamAccountDependenciesDAL = pamAccountDependenciesDALFactory(db);+ const pamResourceRotationRulesDAL = pamResourceRotationRulesDALFactory(db);const aiMcpServerDAL = aiMcpServerDALFactory(db);const aiMcpServerToolDAL = aiMcpServerToolDALFactory(db);const aiMcpServerUserCredentialDAL = aiMcpServerUserCredentialDALFactory(db);@@ -2641,6 +2644,12 @@ export const registerRoutes = async (resourceMetadataDAL});+ const pamResourceRotationRulesService = pamResourceRotationRulesServiceFactory({+ pamResourceRotationRulesDAL,+ pamResourceDAL,+ permissionService+ });+const mfaSessionService = mfaSessionServiceFactory({keyStore,tokenService,@@ -2655,6 +2664,7 @@ export const registerRoutes = async (const pamAccountService = pamAccountServiceFactory({pamAccountDAL,+ pamResourceRotationRulesDAL,gatewayV2Service,kmsService,pamResourceDAL,@@ -2670,7 +2680,8 @@ export const registerRoutes = async (approvalRequestGrantsDAL,approvalPolicyDAL,pamSessionExpirationService,- resourceMetadataDAL+ resourceMetadataDAL,+ pamAccountDependenciesDAL});const pamAccountRotation = pamAccountRotationServiceFactory({@@ -2953,6 +2964,7 @@ export const registerRoutes = async (notification: notificationService,pamFolder: pamFolderService,pamResource: pamResourceService,+ pamResourceRotationRules: pamResourceRotationRulesService,pamAccount: pamAccountService,pamSession: pamSessionService,pamWebAccess: pamWebAccessService,diff --git a/backend/src/services/pam-account-rotation/pam-account-rotation-queue.ts b/backend/src/services/pam-account-rotation/pam-account-rotation-queue.tsindex 419774280a..706d6457d2 100644--- a/backend/src/services/pam-account-rotation/pam-account-rotation-queue.ts+++ b/backend/src/services/pam-account-rotation/pam-account-rotation-queue.ts@@ -25,7 +25,7 @@ export const pamAccountRotationServiceFactory = ({QueueName.PamAccountRotation,QueueJobs.PamAccountRotation,{ pattern: "0 * * * *", utc: true },- QueueName.PamAccountRotation // job id+ QueueName.PamAccountRotation);queueService.start(QueueName.PamAccountRotation, async () => {@@ -43,6 +43,7 @@ export const pamAccountRotationServiceFactory = ({jobId: QueueJobs.PamAccountRotation,repeat: {pattern: "0 * * * *",+ utc: true,key: QueueJobs.PamAccountRotation}});diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.tsindex 18074ce882..7539972789 100644--- a/frontend/src/context/ProjectPermissionContext/types.ts+++ b/frontend/src/context/ProjectPermissionContext/types.ts@@ -247,7 +247,9 @@ export enum ProjectPermissionPamAccountActions {Read = "read",Create = "create",Edit = "edit",- Delete = "delete"+ Delete = "delete",+ TriggerRotation = "trigger-rotation",+ EditRotationConfig = "edit-rotation-config"}export enum ProjectPermissionPamSessionActions {diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.tsindex 5c1e24ef5e..c418014d44 100644--- a/frontend/src/hooks/api/pam/enums.ts+++ b/frontend/src/hooks/api/pam/enums.ts@@ -43,3 +43,9 @@ export enum PamAccountView {Flat = "flat",Nested = "nested"}++export enum PamAccountRotationStatus {+ Rotating = "rotating",+ Success = "success",+ Failed = "failed"+}diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsxindex 62b32547f3..372ada5f5b 100644--- a/frontend/src/hooks/api/pam/mutations.tsx+++ b/frontend/src/hooks/api/pam/mutations.tsx@@ -7,15 +7,20 @@ import {TCreatePamAccountDTO,TCreatePamFolderDTO,TCreatePamResourceDTO,+ TCreatePamRotationRuleDTO,TDeletePamAccountDTO,TDeletePamFolderDTO,TDeletePamResourceDTO,+ TDeletePamRotationRuleDTO,TPamAccount,TPamFolder,TPamResource,+ TPamRotationRule,+ TReorderPamRotationRulesDTO,TUpdatePamAccountDTO,TUpdatePamFolderDTO,- TUpdatePamResourceDTO+ TUpdatePamResourceDTO,+ TUpdatePamRotationRuleDTO} from "./types";// Resources@@ -219,6 +224,86 @@ export const useDeletePamAccountDependency = () => {});};+// Rotation Rules+export const useCreatePamRotationRule = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ resourceId, ...params }: TCreatePamRotationRuleDTO) => {+ const { data } = await apiRequest.post<{ rule: TPamRotationRule }>(+ `/api/v1/pam/resources/${resourceId}/rotation-rules`,+ params+ );+ return data.rule;+ },+ onSuccess: (_, { resourceId }) => {+ queryClient.invalidateQueries({ queryKey: pamKeys.rotationRules(resourceId) });+ }+ });+};++export const useUpdatePamRotationRule = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ resourceId, ruleId, ...params }: TUpdatePamRotationRuleDTO) => {+ const { data } = await apiRequest.patch<{ rule: TPamRotationRule }>(+ `/api/v1/pam/resources/${resourceId}/rotation-rules/${ruleId}`,+ params+ );+ return data.rule;+ },+ onSuccess: (_, { resourceId }) => {+ queryClient.invalidateQueries({ queryKey: pamKeys.rotationRules(resourceId) });+ }+ });+};++export const useDeletePamRotationRule = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ resourceId, ruleId }: TDeletePamRotationRuleDTO) => {+ const { data } = await apiRequest.delete<{ rule: TPamRotationRule }>(+ `/api/v1/pam/resources/${resourceId}/rotation-rules/${ruleId}`+ );+ return data.rule;+ },+ onSuccess: (_, { resourceId }) => {+ queryClient.invalidateQueries({ queryKey: pamKeys.rotationRules(resourceId) });+ }+ });+};++export const useReorderPamRotationRules = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ resourceId, ruleIds }: TReorderPamRotationRulesDTO) => {+ const { data } = await apiRequest.put<{ rules: TPamRotationRule[] }>(+ `/api/v1/pam/resources/${resourceId}/rotation-rules/reorder`,+ { ruleIds }+ );+ return data.rules;+ },+ onSuccess: (_, { resourceId }) => {+ queryClient.invalidateQueries({ queryKey: pamKeys.rotationRules(resourceId) });+ }+ });+};++// Manual Rotation+export const useManualRotateAccount = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ accountId }: { accountId: string }) => {+ const { data } = await apiRequest.post<{ success: boolean; accountId: string }>(+ `/api/v1/pam/accounts/${accountId}/rotate`+ );+ return data;+ },+ onSuccess: (_, { accountId }) => {+ queryClient.invalidateQueries({ queryKey: pamKeys.getAccount(accountId) });+ }+ });+};+// Foldersexport const useCreatePamFolder = () => {const queryClient = useQueryClient();diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsxindex f33dd81b17..e0e5da8259 100644--- a/frontend/src/hooks/api/pam/queries.tsx+++ b/frontend/src/hooks/api/pam/queries.tsx@@ -10,6 +10,7 @@ import {TPamAccount,TPamAccountDependency,TPamResource,+ TPamRotationRule,TPamSession} from "./types";@@ -40,6 +41,7 @@ export const pamKeys = {],getAccount: (accountId: string) => [...pamKeys.account(), "get", accountId],accountDependencies: (accountId: string) => [...pamKeys.account(), "dependencies", accountId],+ rotationRules: (resourceId: string) => [...pamKeys.resource(), "rotation-rules", resourceId],getSession: (sessionId: string) => [...pamKeys.session(), "get", sessionId],listSessions: (projectId: string) => [...pamKeys.session(), "list", projectId]};@@ -230,6 +232,20 @@ export const useGetPamAccountDependencies = (accountId?: string) => {});};+// Rotation Rules+export const useGetPamRotationRules = (resourceId?: string) => {+ return useQuery({+ queryKey: pamKeys.rotationRules(resourceId!),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ rules: TPamRotationRule[] }>(+ `/api/v1/pam/resources/${resourceId}/rotation-rules`+ );+ return data.rules;+ },+ enabled: !!resourceId+ });+};+// Sessionsexport const useGetPamSessionById = (sessionId: string,diff --git a/frontend/src/hooks/api/pam/types/base-account.ts b/frontend/src/hooks/api/pam/types/base-account.tsindex 79819e454a..1a90943ce5 100644--- a/frontend/src/hooks/api/pam/types/base-account.ts+++ b/frontend/src/hooks/api/pam/types/base-account.ts@@ -14,8 +14,6 @@ export interface TBasePamAccount {name: string;description?: string | null;credentialsConfigured: boolean;- rotationEnabled: boolean;- rotationIntervalSeconds?: number;requireMfa?: boolean | null;lastRotatedAt?: string | null;lastRotationMessage?: string | null;diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex 786e58079b..a8d116bffb 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -139,6 +139,7 @@ export type TUpdatePamResourceDTO = Partial<resourceType: PamResourceType;adServerResourceId?: string | null;metadata?: { key: string; value: string }[];+ rotationAccountCredentials?: { username: string; password: string } | null;};export type TDeletePamResourceDTO = {@@ -207,7 +208,48 @@ export type TPamAccountDependency = {data: Record<string, unknown>;source: string;isEnabled?: boolean | null;+ syncStatus?: string | null;+ lastSyncedAt?: string | null;resourceName?: string | null;createdAt: string;updatedAt: string;};++export type TPamRotationRule = {+ id: string;+ resourceId: string;+ name?: string | null;+ namePattern: string;+ enabled: boolean;+ intervalSeconds?: number | null;+ priority: number;+ createdAt: string;+ updatedAt: string;+};++export type TCreatePamRotationRuleDTO = {+ resourceId: string;+ name?: string;+ namePattern: string;+ enabled: boolean;+ intervalSeconds?: number | null;+};++export type TUpdatePamRotationRuleDTO = {+ resourceId: string;+ ruleId: string;+ name?: string | null;+ namePattern?: string;+ enabled?: boolean;+ intervalSeconds?: number | null;+};++export type TDeletePamRotationRuleDTO = {+ resourceId: string;+ ruleId: string;+};++export type TReorderPamRotationRulesDTO = {+ resourceId: string;+ ruleIds: string[];+};diff --git a/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsx b/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsxindex eae5f7ff8a..847d60f4c1 100644--- a/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsx+++ b/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsx@@ -2,9 +2,18 @@ import { useState } from "react";import { Helmet } from "react-helmet";import { faChevronLeft } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { useQueryClient } from "@tanstack/react-query";import { useNavigate, useParams, useSearch } from "@tanstack/react-router";-import { BanIcon, EllipsisVerticalIcon, LogInIcon } from "lucide-react";+import {+ BanIcon,+ EllipsisVerticalIcon,+ LogInIcon,+ PencilIcon,+ RefreshCwIcon,+ Trash2Icon+} from "lucide-react";+import { createNotification } from "@app/components/notifications";import { ProjectPermissionCan } from "@app/components/permissions";import { Tab, TabList, TabPanel, Tabs } from "@app/components/v2";import {@@ -22,7 +31,15 @@ import { ProjectPermissionSub, useOrganization } from "@app/context";import { ProjectPermissionPamAccountActions } from "@app/context/ProjectPermissionContext/types";import { usePopUp } from "@app/hooks";import { ApprovalPolicyType, useCheckPolicyMatch } from "@app/hooks/api/approvalPolicies";-import { PAM_RESOURCE_TYPE_MAP, PamResourceType, useGetPamAccountById } from "@app/hooks/api/pam";+import {+ PAM_RESOURCE_TYPE_MAP,+ PamAccountRotationStatus,+ PamResourceType,+ TPamAccount,+ useGetPamAccountById+} from "@app/hooks/api/pam";+import { useManualRotateAccount } from "@app/hooks/api/pam/mutations";+import { pamKeys } from "@app/hooks/api/pam/queries";import { PamAccessAccountModal } from "../PamAccountsPage/components/PamAccessAccountModal";import { PamDeleteAccountModal } from "../PamAccountsPage/components/PamDeleteAccountModal";@@ -80,8 +97,10 @@ const PageContent = () => {"deleteAccount"] as const);+ const queryClient = useQueryClient();const { accessAwsIam, isPending: isAwsAccessPending } = useAccessAwsIamAccount();const { mutateAsync: checkPolicyMatch } = useCheckPolicyMatch();+ const rotateAccount = useManualRotateAccount();const { data: account, isPending } = useGetPamAccountById(accountId);@@ -144,6 +163,22 @@ const PageContent = () => {}};+ const handleRotate = async () => {+ // Optimistically show rotating status immediately+ queryClient.setQueryData(pamKeys.getAccount(account.id), (old: TPamAccount | undefined) =>+ old ? { ...old, rotationStatus: PamAccountRotationStatus.Rotating } : old+ );++ try {+ createNotification({ text: "Credential rotation triggered", type: "success" });+ await rotateAccount.mutateAsync({ accountId: account.id });+ } catch {+ // Revert optimistic update on failure+ queryClient.invalidateQueries({ queryKey: pamKeys.getAccount(account.id) });+ createNotification({ text: "Failed to trigger rotation", type: "error" });+ }+ };+return (<div className="container mx-auto flex max-w-7xl flex-col px-6 py-6 text-mineshaft-50"><button@@ -202,10 +237,29 @@ const PageContent = () => {onClick={() => setIsEditModalOpen(true)}isDisabled={!isAllowed}>+ <PencilIcon className="size-3.5" />Edit Account</UnstableDropdownMenuItem>)}</ProjectPermissionCan>+ {account.resource.rotationCredentialsConfigured && (+ <ProjectPermissionCan+ I={ProjectPermissionPamAccountActions.TriggerRotation}+ a={ProjectPermissionSub.PamAccounts}+ >+ {(isAllowed) => (+ <UnstableDropdownMenuItem+ onClick={handleRotate}+ isDisabled={+ !isAllowed || account.rotationStatus === PamAccountRotationStatus.Rotating+ }+ >+ <RefreshCwIcon className="size-3.5" />+ Rotate Account+ </UnstableDropdownMenuItem>+ )}+ </ProjectPermissionCan>+ )}<ProjectPermissionCanI={ProjectPermissionPamAccountActions.Delete}a={ProjectPermissionSub.PamAccounts}@@ -216,6 +270,7 @@ const PageContent = () => {variant="danger"isDisabled={!isAllowed}>+ <Trash2Icon className="size-3.5" />Delete Account</UnstableDropdownMenuItem>)}diff --git a/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDependenciesSection.tsx b/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDependenciesSection.tsxindex c1dca63fb0..f5de14ece3 100644--- a/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDependenciesSection.tsx+++ b/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDependenciesSection.tsx@@ -63,7 +63,7 @@ const DATA_LABEL_MAP: Record<string, string> = {identityType: "Identity Type"};-const COL_COUNT = 7;+const COL_COUNT = 8;const DATA_KEY_ORDER: Record<string, number> = { actions: -2, triggers: -1 };const formatValue = (key: string, value: unknown): string => {@@ -122,6 +122,35 @@ const DependencyRow = ({<Badge variant="neutral">Disabled</Badge>)}</UnstableTableCell>+ <UnstableTableCell>+ {dep.syncStatus ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge+ variant={+ ({ success: "success", failed: "danger", pending: "warning" } as const)[+ dep.syncStatus+ ] ?? "neutral"+ }+ >+ {(+ { success: "Synced", failed: "Failed", pending: "Pending" } as Record<+ string,+ string+ >+ )[dep.syncStatus] ?? dep.syncStatus}+ </Badge>+ </TooltipTrigger>+ {dep.lastSyncedAt && (+ <TooltipContent side="top">+ Last synced: {format(new Date(dep.lastSyncedAt), "MMM d, yyyy HH:mm")}+ </TooltipContent>+ )}+ </Tooltip>+ ) : (+ <span className="text-xs text-muted">-</span>+ )}+ </UnstableTableCell><UnstableTableCell><UnstableDropdownMenu><UnstableDropdownMenuTrigger asChild>@@ -241,6 +270,7 @@ export const PamAccountDependenciesSection = ({ account }: { account: TPamAccoun</Tooltip></div></UnstableTableHead>+ <UnstableTableHead>Sync Status</UnstableTableHead><UnstableTableHead className="w-5" /></UnstableTableRow></UnstableTableHeader>diff --git a/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDetailsSection.tsx b/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDetailsSection.tsxindex be28db7dbc..ce978498d2 100644--- a/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDetailsSection.tsx+++ b/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDetailsSection.tsx@@ -3,23 +3,60 @@ import { PencilIcon } from "lucide-react";import { ProjectPermissionCan } from "@app/components/permissions";import {+ Badge,Detail,DetailGroup,DetailLabel,DetailValue,+ Tooltip,+ TooltipContent,+ TooltipTrigger,UnstableIconButton} from "@app/components/v3";import { ProjectPermissionSub } from "@app/context";import { ProjectPermissionPamAccountActions } from "@app/context/ProjectPermissionContext/types";-import { PAM_RESOURCE_TYPE_MAP, TPamAccount } from "@app/hooks/api/pam";+import { PAM_RESOURCE_TYPE_MAP, PamAccountRotationStatus, TPamAccount } from "@app/hooks/api/pam";+import { useGetPamAccountById } from "@app/hooks/api/pam/queries";type Props = {account: TPamAccount;onEdit: VoidFunction;};+const rotationStatusVariant = (status?: string | null) => {+ switch (status) {+ case PamAccountRotationStatus.Success:+ return "success" as const;+ case PamAccountRotationStatus.Failed:+ return "danger" as const;+ case PamAccountRotationStatus.Rotating:+ return "info" as const;+ default:+ return "neutral" as const;+ }+};++const rotationStatusLabel = (status?: string | null) => {+ switch (status) {+ case PamAccountRotationStatus.Success:+ return "Success";+ case PamAccountRotationStatus.Failed:+ return "Failed";+ case PamAccountRotationStatus.Rotating:+ return "Rotating";+ default:+ return "Never";+ }+};+export const PamAccountDetailsSection = ({ account, onEdit }: Props) => {const resourceTypeInfo = PAM_RESOURCE_TYPE_MAP[account.resource.resourceType];+ const isRotating = account.rotationStatus === PamAccountRotationStatus.Rotating;++ // Poll for status updates while rotation is in progress+ useGetPamAccountById(account.id, {+ refetchInterval: isRotating ? 3000 : false+ });return (<div className="flex w-full flex-col gap-3 rounded-lg border border-border bg-container px-4 py-3">@@ -66,6 +103,38 @@ export const PamAccountDetailsSection = ({ account, onEdit }: Props) => {<DetailLabel>Created</DetailLabel><DetailValue>{format(new Date(account.createdAt), "MM/dd/yyyy, hh:mm a")}</DetailValue></Detail>+ <Detail>+ <DetailLabel>Rotation Status</DetailLabel>+ <DetailValue>+ <div className="flex items-center gap-2">+ <Badge+ variant={rotationStatusVariant(account.rotationStatus)}+ className={isRotating ? "animate-pulse" : undefined}+ >+ {rotationStatusLabel(account.rotationStatus)}+ </Badge>+ {account.rotationStatus === PamAccountRotationStatus.Failed &&+ account.lastRotationMessage && (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="cursor-help text-xs text-red-400">View error</span>+ </TooltipTrigger>+ <TooltipContent side="right" className="max-w-xs">+ {account.lastRotationMessage}+ </TooltipContent>+ </Tooltip>+ )}+ </div>+ </DetailValue>+ </Detail>+ {"lastRotatedAt" in account && account.lastRotatedAt && (+ <Detail>+ <DetailLabel>Last Rotated</DetailLabel>+ <DetailValue>+ {format(new Date(account.lastRotatedAt as string), "MM/dd/yyyy, hh:mm a")}+ </DetailValue>+ </Detail>+ )}</DetailGroup></div>);diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/ActiveDirectoryAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/ActiveDirectoryAccountForm.tsxindex 6215e2913c..7f19f6cebf 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/ActiveDirectoryAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/ActiveDirectoryAccountForm.tsx@@ -27,7 +27,6 @@ const formSchema = genericAccountFieldsSchema.extend({internalMetadata: z.object({accountType: z.nativeEnum(ActiveDirectoryAccountType)}),- rotationEnabled: z.boolean().default(false),requireMfa: z.boolean().nullable().optional()});@@ -51,7 +50,6 @@ export const ActiveDirectoryAccountForm = ({ account, onSubmit }: Props) => {name: "",description: "",requireMfa: false,- rotationEnabled: false,credentials: {username: "",password: ""diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsxindex aa5e2e7562..9f776ce686 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsx@@ -22,10 +22,7 @@ const KubernetesServiceAccountTokenCredentialsSchema = z.object({});const formSchema = genericAccountFieldsSchema.extend({- credentials: KubernetesServiceAccountTokenCredentialsSchema,- // We don't support rotation for now, just feed a false value to- // make the schema happy- rotationEnabled: z.boolean().default(false)+ credentials: KubernetesServiceAccountTokenCredentialsSchema});type FormData = z.infer<typeof formSchema>;@@ -82,8 +79,7 @@ export const KubernetesAccountForm = ({ account, onSubmit }: Props) => {credentials: {authMethod: KubernetesAuthMethod.ServiceAccountToken,serviceAccountToken: ""- },- rotationEnabled: false+ }}});diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MySQLAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MySQLAccountForm.tsxindex 1c6960ab64..9d232d2d53 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MySQLAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MySQLAccountForm.tsx@@ -21,9 +21,6 @@ type Props = {const formSchema = genericAccountFieldsSchema.extend({credentials: BaseSqlAccountSchema,- // We don't support rotation for now, just feed a false value to- // make the schema happy- rotationEnabled: z.boolean().default(false),requireMfa: z.boolean().nullable().optional()});diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsxindex 1555bfb508..4337628cd3 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsx@@ -1,15 +1,9 @@-import { useEffect, useState } from "react";import { FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { z } from "zod";import { Button, ModalClose } from "@app/components/v2";-import {- PamResourceType,- TPostgresAccount,- TPostgresResource,- useGetPamResourceById-} from "@app/hooks/api/pam";+import { PamResourceType, TPostgresAccount } from "@app/hooks/api/pam";import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";import { BaseSqlAccountSchema } from "./shared/sql-account-schemas";@@ -17,7 +11,6 @@ import { SqlAccountFields } from "./shared/SqlAccountFields";import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";import { RequireMfaField } from "./RequireMfaField";-import { RotateAccountFields, rotateAccountFieldsSchema } from "./RotateAccountFields";type Props = {account?: TPostgresAccount;@@ -26,14 +19,14 @@ type Props = {onSubmit: (formData: FormData) => Promise<void>;};-const formSchema = genericAccountFieldsSchema.extend(rotateAccountFieldsSchema.shape).extend({+const formSchema = genericAccountFieldsSchema.extend({credentials: BaseSqlAccountSchema,requireMfa: z.boolean().nullable().optional()});type FormData = z.infer<typeof formSchema>;-export const PostgresAccountForm = ({ account, resourceId, resourceType, onSubmit }: Props) => {+export const PostgresAccountForm = ({ account, onSubmit }: Props) => {const isUpdate = Boolean(account);const form = useForm<FormData>({@@ -54,22 +47,6 @@ export const PostgresAccountForm = ({ account, resourceId, resourceType, onSubmiformState: { isSubmitting, isDirty }} = form;- const [rotationCredentialsConfigured, setRotationCredentialsConfigured] = useState(false);-- const { data: resource } = useGetPamResourceById(resourceType, resourceId, {- enabled: !account && !!resourceId && !!resourceType- });-- useEffect(() => {- if (account) {- setRotationCredentialsConfigured(account.resource.rotationCredentialsConfigured);- } else {- setRotationCredentialsConfigured(- !!(resource as TPostgresResource)?.rotationAccountCredentials- );- }- }, [account, resource]);-return (<FormProvider {...form}><form@@ -79,7 +56,6 @@ export const PostgresAccountForm = ({ account, resourceId, resourceType, onSubmi><GenericAccountFields /><SqlAccountFields isUpdate={isUpdate} />- <RotateAccountFields rotationCredentialsConfigured={rotationCredentialsConfigured} /><RequireMfaField /><MetadataFields /><div className="mt-6 flex items-center">diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/RedisAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/RedisAccountForm.tsxindex 6b02033b8d..6d59bcf6e2 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/RedisAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/RedisAccountForm.tsx@@ -25,10 +25,7 @@ const formSchema = genericAccountFieldsSchema.max(256, "Password must be 256 characters or less").transform((value) => (value === "" ? undefined : value)).optional()- }),- // We don't support rotation for now, just feed a false value to- // make the schema happy- rotationEnabled: z.boolean().default(false)+ })}).superRefine((data, ctx) => {// Make credentials required when credentialsEnabled is true@@ -87,8 +84,7 @@ export const RedisAccountForm = ({ account, onSubmit }: Props) => {credentials: {username: undefined,password: undefined- },- rotationEnabled: false+ }}});diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SshAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SshAccountForm.tsxindex befab2c2e9..3206c145bf 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SshAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SshAccountForm.tsx@@ -53,9 +53,6 @@ const BaseSshAccountSchema = z.discriminatedUnion("authMethod", [const formSchema = genericAccountFieldsSchema.extend({credentials: BaseSshAccountSchema,- // We don't support rotation for now, just feed a false value to- // make the schema happy- rotationEnabled: z.boolean().default(false),requireMfa: z.boolean().nullable().optional()});@@ -229,7 +226,6 @@ export const SshAccountForm = ({ account, resourceId, onSubmit }: Props) => {name: "",description: "",requireMfa: false,- rotationEnabled: false,credentials: {authMethod: SSHAuthMethod.Password,username: "",diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/WindowsAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/WindowsAccountForm.tsxindex dd0823386d..43ceabc21d 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/WindowsAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/WindowsAccountForm.tsx@@ -27,7 +27,6 @@ const formSchema = genericAccountFieldsSchema.extend({internalMetadata: z.object({accountType: z.nativeEnum(WindowsAccountType)}),- rotationEnabled: z.boolean().default(false),requireMfa: z.boolean().nullable().optional()});@@ -51,7 +50,6 @@ export const WindowsAccountForm = ({ account, onSubmit }: Props) => {name: "",description: "",requireMfa: false,- rotationEnabled: false,credentials: {username: "",password: ""diff --git a/frontend/src/pages/pam/PamResourceByIDPage/PamResourceByIDPage.tsx b/frontend/src/pages/pam/PamResourceByIDPage/PamResourceByIDPage.tsxindex 17c4db5b87..a253d4f841 100644--- a/frontend/src/pages/pam/PamResourceByIDPage/PamResourceByIDPage.tsx+++ b/frontend/src/pages/pam/PamResourceByIDPage/PamResourceByIDPage.tsx@@ -33,7 +33,9 @@ import {PamResourceConnectionSection,PamResourceDetailsSection,PamResourceMetadataSection,- PamResourceRelatedResourcesSection+ PamResourceRelatedResourcesSection,+ PamResourceRotationPolicySection,+ PamRotationPolicyModal} from "./components";const PageContent = () => {@@ -65,6 +67,7 @@ const PageContent = () => {const [isEditModalOpen, setIsEditModalOpen] = useState(false);const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);+ const [isRotationPolicyModalOpen, setIsRotationPolicyModalOpen] = useState(false);const { data: resource, isPending } = useGetPamResourceById(resourceType as PamResourceType,@@ -199,6 +202,10 @@ const PageContent = () => {resource={resource}onEdit={() => setIsEditModalOpen(true)}/>+ <PamResourceRotationPolicySection+ resource={resource}+ onEdit={() => setIsRotationPolicyModalOpen(true)}+ /><PamResourceMetadataSection resource={resource} /></div>@@ -236,6 +243,12 @@ const PageContent = () => {deleteKey={resource.name}onDeleteApproved={handleDeleteConfirm}/>++ <PamRotationPolicyModal+ isOpen={isRotationPolicyModalOpen}+ onOpenChange={setIsRotationPolicyModalOpen}+ resource={resource}+ /></div>);};diff --git a/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsx b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsxindex 1865d6f351..bc05756df1 100644--- a/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsx+++ b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsx@@ -1,4 +1,4 @@-import { useCallback, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { faFilter, faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useNavigate, useParams } from "@tanstack/react-router";@@ -52,6 +52,7 @@ import { ProjectPermissionPamAccountActions } from "@app/context/ProjectPermissiimport { useDebounce, usePopUp, useToggle } from "@app/hooks";import { ApprovalPolicyType, useCheckPolicyMatch } from "@app/hooks/api/approvalPolicies";import {+ PamAccountRotationStatus,PamResourceType,TActiveDirectoryAccount,TPamAccount,@@ -59,6 +60,7 @@ import {TWindowsAccount,useListPamAccounts} from "@app/hooks/api/pam";+import { useManualRotateAccount } from "@app/hooks/api/pam/mutations";import {MetadataFilterEntry,MetadataFilterSection@@ -96,9 +98,11 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {const { accessAwsIam, loadingAccountId } = useAccessAwsIamAccount();const { mutateAsync: checkPolicyMatch } = useCheckPolicyMatch();+ const manualRotate = useManualRotateAccount();const [search, setSearch] = useState("");const [debouncedSearch] = useDebounce(search);+ const [rotatingAccountIds, setRotatingAccountIds] = useState<Set<string>>(new Set());const [pendingMetadataEntries, setPendingMetadataEntries] = useState<MetadataFilterEntry[]>([]);const [appliedMetadataEntries, setAppliedMetadataEntries] = useState<MetadataFilterEntry[]>([]);@@ -126,19 +130,49 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {setAppliedMetadataEntries([]);};- const { data: accountsData, isPending } = useListPamAccounts({- projectId: projectId!,- filterResourceIds: resource.id,- search: debouncedSearch || undefined,- metadataFilter: appliedMetadataEntries.filter((e) => e.key.trim()).length- ? appliedMetadataEntries- .filter((e) => e.key.trim())- .map((e) => ({ key: e.key.trim(), ...(e.value.trim() ? { value: e.value.trim() } : {}) }))- : undefined- });+ const hasRotatingAccounts = rotatingAccountIds.size > 0;++ const { data: accountsData, isPending } = useListPamAccounts(+ {+ projectId: projectId!,+ filterResourceIds: resource.id,+ search: debouncedSearch || undefined,+ metadataFilter: appliedMetadataEntries.filter((e) => e.key.trim()).length+ ? appliedMetadataEntries+ .filter((e) => e.key.trim())+ .map((e) => ({+ key: e.key.trim(),+ ...(e.value.trim() ? { value: e.value.trim() } : {})+ }))+ : undefined+ },+ {+ refetchInterval: hasRotatingAccounts ? 3000 : false+ }+ );const accounts = accountsData?.accounts || [];+ // Clear optimistic rotating state when server confirms a non-rotating status+ useEffect(() => {+ if (!accountsData?.accounts) return;+ setRotatingAccountIds((prev) => {+ const next = new Set(prev);+ let changed = false;+ [...prev].forEach((id) => {+ const acct = accountsData.accounts.find((a) => a.id === id);+ if (acct) {+ const status = (acct as { rotationStatus?: string | null }).rotationStatus;+ if (status && status !== PamAccountRotationStatus.Rotating) {+ next.delete(id);+ changed = true;+ }+ }+ });+ return changed ? next : prev;+ });+ }, [accountsData]);+const [copiedAccountId, setCopiedAccountId] = useToggle(false);const handleCopyId = useCallback(@@ -169,6 +203,21 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {});};+ const handleRotateAccount = async (accountId: string) => {+ try {+ setRotatingAccountIds((prev) => new Set(prev).add(accountId));+ createNotification({ text: "Account rotation triggered", type: "success" });+ await manualRotate.mutateAsync({ accountId });+ } catch {+ setRotatingAccountIds((prev) => {+ const next = new Set(prev);+ next.delete(accountId);+ return next;+ });+ createNotification({ text: "Failed to trigger rotation", type: "error" });+ }+ };+const accessAccount = async (account: TPamAccount) => {const { requiresApproval } = await checkPolicyMatch({policyType: ApprovalPolicyType.PamAccess,@@ -289,6 +338,7 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {<UnstableTableRow><UnstableTableHead>Account Name</UnstableTableHead>{hasAccountType(resource.resourceType) && <UnstableTableHead>Type</UnstableTableHead>}+ <UnstableTableHead>Last Rotated</UnstableTableHead><UnstableTableHead className="w-5" /></UnstableTableRow></UnstableTableHeader>@@ -296,7 +346,7 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {{isPending && (<UnstableTableRow><UnstableTableCell- colSpan={hasAccountType(resource.resourceType) ? 3 : 2}+ colSpan={hasAccountType(resource.resourceType) ? 4 : 3}className="text-center text-muted">Loading accounts...@@ -305,7 +355,7 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {)}{!isPending && accounts.length === 0 && (<UnstableTableRow>- <UnstableTableCell colSpan={hasAccountType(resource.resourceType) ? 3 : 2}>+ <UnstableTableCell colSpan={hasAccountType(resource.resourceType) ? 4 : 3}><UnstableEmpty className="border-0 bg-transparent py-8 shadow-none"><UnstableEmptyHeader><UnstableEmptyTitle>@@ -320,9 +370,12 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {)}{accounts.map((account) => {const isAwsIamAccount = resource.resourceType === PamResourceType.AwsIam;- const rotationStatus = !isAwsIamAccount+ const serverRotationStatus = !isAwsIamAccount? (account as { rotationStatus?: string | null }).rotationStatus: undefined;+ const rotationStatus = rotatingAccountIds.has(account.id)+ ? PamAccountRotationStatus.Rotating+ : serverRotationStatus;const lastRotatedAt = !isAwsIamAccount? (account as { lastRotatedAt?: string | null }).lastRotatedAt: undefined;@@ -352,33 +405,48 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {<span>No password</span></Badge>)}- {lastRotatedAt && (+ </div>+ </UnstableTableCell>+ {hasAccountType(resource.resourceType) && (+ <UnstableTableCell>+ <span className="capitalize">{getAccountType(account) ?? "-"}</span>+ </UnstableTableCell>+ )}+ <UnstableTableCell>+ <div className="flex items-center gap-2">+ <span className="text-sm text-muted">+ {lastRotatedAt+ ? formatDistance(new Date(lastRotatedAt), new Date(), {+ addSuffix: true+ })+ : "Never"}+ </span>+ {rotationStatus === PamAccountRotationStatus.Failed && (<Tooltip><TooltipTrigger asChild>- <Badge- variant={rotationStatus === "failed" ? "danger" : "success"}- className="text-xs"- >- <RefreshCwIcon className="size-3" />- <span>- Rotated {formatDistance(new Date(), new Date(lastRotatedAt))} ago- </span>+ <Badge variant="danger" className="text-xs">+ Failed</Badge></TooltipTrigger>{lastRotationMessage && (- <TooltipContent className="max-w-sm text-center">+ <TooltipContent className="max-w-sm">{lastRotationMessage}</TooltipContent>)}</Tooltip>)}+ {rotationStatus === PamAccountRotationStatus.Rotating && (+ <Badge variant="info" className="animate-pulse text-xs">+ Rotating+ </Badge>+ )}+ {rotationStatus === PamAccountRotationStatus.Success && (+ <Badge variant="success" className="text-xs">+ Success+ </Badge>+ )}</div></UnstableTableCell>- {hasAccountType(resource.resourceType) && (- <UnstableTableCell>- <span className="capitalize">{getAccountType(account) ?? "-"}</span>- </UnstableTableCell>- )}<UnstableTableCell><div className="flex items-center gap-2">{/* Temporarily disable accessing Windows Server accounts */}@@ -424,6 +492,23 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {)}Copy Account ID</UnstableDropdownMenuItem>+ <ProjectPermissionCan+ I={ProjectPermissionPamAccountActions.TriggerRotation}+ a={ProjectPermissionSub.PamAccounts}+ >+ {(isAllowed: boolean) => (+ <UnstableDropdownMenuItem+ isDisabled={!isAllowed || manualRotate.isPending}+ onClick={(e) => {+ e.stopPropagation();+ handleRotateAccount(account.id);+ }}+ >+ <RefreshCwIcon className="size-4" />+ Rotate Account+ </UnstableDropdownMenuItem>+ )}+ </ProjectPermissionCan><ProjectPermissionCanI={ProjectPermissionPamAccountActions.Edit}a={ProjectPermissionSub.PamAccounts}diff --git a/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceRotationPolicySection.tsx b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceRotationPolicySection.tsxnew file mode 100644index 0000000000..208c029da5--- /dev/null+++ b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceRotationPolicySection.tsx@@ -0,0 +1,108 @@+import { PencilIcon } from "lucide-react";++import { ProjectPermissionCan } from "@app/components/permissions";+import {+ Badge,+ Detail,+ DetailGroup,+ DetailLabel,+ DetailValue,+ UnstableIconButton+} from "@app/components/v3";+import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";+import { getObjectFromSeconds } from "@app/helpers/datetime";+import { TPamResource } from "@app/hooks/api/pam";+import { useGetPamRotationRules } from "@app/hooks/api/pam/queries";++type Props = {+ resource: TPamResource;+ onEdit: VoidFunction;+};++const UNIT_LABELS: Record<string, string> = {+ s: "second",+ m: "minute",+ h: "hour",+ d: "day",+ w: "week",+ y: "year"+};++const formatInterval = (seconds: number) => {+ const { value, unit } = getObjectFromSeconds(seconds);+ const label = UNIT_LABELS[unit] ?? unit;+ return `${value} ${label}${value !== 1 ? "s" : ""}`;+};++export const PamResourceRotationPolicySection = ({ resource, onEdit }: Props) => {+ const { data: rules = [] } = useGetPamRotationRules(resource.id);++ const enabledRules = rules.filter((r) => r.enabled);+ const hasRotationCredentials =+ "rotationAccountCredentials" in resource && !!resource.rotationAccountCredentials;++ return (+ <div className="flex w-full flex-col gap-3 rounded-lg border border-border bg-container px-4 py-3">+ <div className="flex items-center justify-between border-b border-border pb-2">+ <h3 className="text-lg font-medium">Rotation Policy</h3>+ <ProjectPermissionCan+ I={ProjectPermissionActions.Edit}+ a={ProjectPermissionSub.PamResources}+ >+ {(isAllowed) => (+ <UnstableIconButton variant="ghost" size="xs" onClick={onEdit} isDisabled={!isAllowed}>+ <PencilIcon />+ </UnstableIconButton>+ )}+ </ProjectPermissionCan>+ </div>++ <DetailGroup>+ <Detail>+ <DetailLabel>Credentials</DetailLabel>+ <DetailValue>+ {hasRotationCredentials ? (+ <Badge variant="success">Configured</Badge>+ ) : (+ <span className="text-muted">None</span>+ )}+ </DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Rules</DetailLabel>+ <DetailValue>+ {rules.length > 0 ? (+ <span>+ {rules.length} total ({enabledRules.length} active)+ </span>+ ) : (+ <span className="text-muted">None</span>+ )}+ </DetailValue>+ </Detail>+ {enabledRules.length > 0 && (+ <Detail>+ <DetailLabel>Active Rules</DetailLabel>+ <DetailValue>+ <div className="flex flex-col gap-1">+ {enabledRules.slice(0, 3).map((rule) => (+ <div key={rule.id} className="flex items-center gap-1.5 text-xs">+ <code className="rounded bg-mineshaft-600 px-2 py-0.5">{rule.namePattern}</code>+ {rule.intervalSeconds && (+ <span className="text-muted">+ every {formatInterval(rule.intervalSeconds)}+ </span>+ )}+ </div>+ ))}+ {enabledRules.length > 3 && (+ <span className="text-xs text-muted">+{enabledRules.length - 3} more</span>+ )}+ </div>+ </DetailValue>+ </Detail>+ )}+ </DetailGroup>+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceRotationRulesSection.tsx b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceRotationRulesSection.tsxnew file mode 100644index 0000000000..ac2572a335--- /dev/null+++ b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceRotationRulesSection.tsx@@ -0,0 +1,381 @@+import { useState } from "react";+import { Controller, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { format } from "date-fns";+import { ArrowDownIcon, ArrowUpIcon, PencilIcon, PlusIcon, TrashIcon } from "lucide-react";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import { ProjectPermissionCan } from "@app/components/permissions";+import { FormControl, Input, Select, SelectItem, Switch } from "@app/components/v2";+import {+ Badge,+ Button,+ UnstableEmpty,+ UnstableEmptyHeader,+ UnstableEmptyTitle,+ UnstableIconButton,+ UnstableTable,+ UnstableTableBody,+ UnstableTableCell,+ UnstableTableHead,+ UnstableTableHeader,+ UnstableTableRow+} from "@app/components/v3";+import { ProjectPermissionSub } from "@app/context";+import { ProjectPermissionPamAccountActions } from "@app/context/ProjectPermissionContext/types";+import {+ useCreatePamRotationRule,+ useDeletePamRotationRule,+ useReorderPamRotationRules,+ useUpdatePamRotationRule+} from "@app/hooks/api/pam/mutations";+import { useGetPamRotationRules } from "@app/hooks/api/pam/queries";+import { TPamResource, TPamRotationRule } from "@app/hooks/api/pam/types";++const formSchema = z.object({+ name: z.string().max(255).optional(),+ namePattern: z.string().min(1).max(255),+ enabled: z.boolean(),+ intervalSeconds: z.number().min(3600).nullable().optional()+});++type FormData = z.infer<typeof formSchema>;++type Props = {+ resource: TPamResource;+};++const INTERVAL_OPTIONS = [+ { value: "86400", label: "1 Day" },+ { value: "259200", label: "3 Days" },+ { value: "604800", label: "7 Days" },+ { value: "2592000", label: "30 Days" }+];++const formatInterval = (seconds: number) => {+ const option = INTERVAL_OPTIONS.find((o) => o.value === seconds.toString());+ if (option) return option.label;+ const days = Math.round(seconds / 86400);+ return `${days} day${days !== 1 ? "s" : ""}`;+};++export const PamResourceRotationRulesSection = ({ resource }: Props) => {+ const { data: rules = [], isLoading } = useGetPamRotationRules(resource.id);+ const createRule = useCreatePamRotationRule();+ const updateRule = useUpdatePamRotationRule();+ const deleteRule = useDeletePamRotationRule();+ const reorderRules = useReorderPamRotationRules();++ const [editingRule, setEditingRule] = useState<TPamRotationRule | null>(null);+ const [isFormOpen, setIsFormOpen] = useState(false);++ const {+ control,+ handleSubmit,+ reset,+ watch,+ formState: { isSubmitting }+ } = useForm<FormData>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ name: "",+ namePattern: "*",+ enabled: true,+ intervalSeconds: 2592000+ }+ });++ const enabledValue = watch("enabled");++ const openCreateForm = () => {+ setEditingRule(null);+ reset({+ name: "",+ namePattern: "*",+ enabled: true,+ intervalSeconds: 2592000+ });+ setIsFormOpen(true);+ };++ const openEditForm = (rule: TPamRotationRule) => {+ setEditingRule(rule);+ reset({+ name: rule.name ?? "",+ namePattern: rule.namePattern,+ enabled: rule.enabled,+ intervalSeconds: rule.intervalSeconds ?? 2592000+ });+ setIsFormOpen(true);+ };++ const onSubmit = async (data: FormData) => {+ try {+ if (editingRule) {+ await updateRule.mutateAsync({+ resourceId: resource.id,+ ruleId: editingRule.id,+ ...data+ });+ createNotification({ text: "Rotation rule updated", type: "success" });+ } else {+ await createRule.mutateAsync({+ resourceId: resource.id,+ ...data+ });+ createNotification({ text: "Rotation rule created", type: "success" });+ }+ setIsFormOpen(false);+ setEditingRule(null);+ } catch {+ createNotification({+ text: `Failed to ${editingRule ? "update" : "create"} rotation rule`,+ type: "error"+ });+ }+ };++ const handleDelete = async (ruleId: string) => {+ try {+ await deleteRule.mutateAsync({ resourceId: resource.id, ruleId });+ createNotification({ text: "Rotation rule deleted", type: "success" });+ } catch {+ createNotification({ text: "Failed to delete rotation rule", type: "error" });+ }+ };++ const handleMoveUp = async (index: number) => {+ if (index === 0) return;+ const ruleIds = rules.map((r) => r.id);+ [ruleIds[index - 1], ruleIds[index]] = [ruleIds[index], ruleIds[index - 1]];+ try {+ await reorderRules.mutateAsync({ resourceId: resource.id, ruleIds });+ } catch {+ createNotification({ text: "Failed to reorder rules", type: "error" });+ }+ };++ const handleMoveDown = async (index: number) => {+ if (index >= rules.length - 1) return;+ const ruleIds = rules.map((r) => r.id);+ [ruleIds[index], ruleIds[index + 1]] = [ruleIds[index + 1], ruleIds[index]];+ try {+ await reorderRules.mutateAsync({ resourceId: resource.id, ruleIds });+ } catch {+ createNotification({ text: "Failed to reorder rules", type: "error" });+ }+ };++ if (isLoading) {+ return <div className="p-4 text-center text-sm text-muted">Loading rotation rules...</div>;+ }++ return (+ <div className="flex flex-col gap-4">+ <div className="flex items-center justify-between">+ <div>+ <p className="text-sm text-muted">+ Rules are evaluated in priority order (first match wins). Use glob patterns to match+ account names.+ </p>+ </div>+ <ProjectPermissionCan+ I={ProjectPermissionPamAccountActions.EditRotationConfig}+ a={ProjectPermissionSub.PamAccounts}+ >+ {(isAllowed) => (+ <Button size="xs" onClick={openCreateForm} isDisabled={!isAllowed}>+ <PlusIcon className="size-3.5" />+ Add Rule+ </Button>+ )}+ </ProjectPermissionCan>+ </div>++ {isFormOpen && (+ <div className="rounded-lg border border-border bg-container p-4">+ <h4 className="mb-3 text-sm font-medium">+ {editingRule ? "Edit Rule" : "New Rotation Rule"}+ </h4>+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-3">+ <div className="grid grid-cols-2 gap-3">+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Rule Name (optional)"+ isError={!!error}+ errorText={error?.message}+ >+ <Input {...field} placeholder="e.g., Service Accounts" />+ </FormControl>+ )}+ />+ <Controller+ control={control}+ name="namePattern"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Account Name Pattern"+ isError={!!error}+ errorText={error?.message}+ helperText="Glob pattern (e.g., svc-*, admin, *)"+ >+ <Input {...field} placeholder="*" className="font-mono" />+ </FormControl>+ )}+ />+ </div>+ <div className="flex items-center gap-4">+ <Controller+ control={control}+ name="enabled"+ render={({ field: { value, onChange } }) => (+ <FormControl label="Enabled" className="mb-0">+ <Switch+ id="rule-enabled"+ isChecked={value}+ onCheckedChange={onChange}+ className="bg-mineshaft-400/80 shadow-inner data-[state=checked]:bg-green/80"+ thumbClassName="bg-mineshaft-800"+ />+ </FormControl>+ )}+ />+ {enabledValue && (+ <Controller+ control={control}+ name="intervalSeconds"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl+ label="Rotation Interval"+ isError={!!error}+ errorText={error?.message}+ className="mb-0"+ >+ <Select+ value={value?.toString() ?? "2592000"}+ onValueChange={(val) => onChange(parseInt(val, 10))}+ className="w-36 border border-mineshaft-500"+ position="popper"+ >+ {INTERVAL_OPTIONS.map((opt) => (+ <SelectItem key={opt.value} value={opt.value}>+ {opt.label}+ </SelectItem>+ ))}+ </Select>+ </FormControl>+ )}+ />+ )}+ </div>+ <div className="flex gap-2">+ <Button type="submit" size="xs" isPending={isSubmitting}>+ {editingRule ? "Save" : "Create"}+ </Button>+ <Button+ variant="outline"+ size="xs"+ onClick={() => {+ setIsFormOpen(false);+ setEditingRule(null);+ }}+ >+ Cancel+ </Button>+ </div>+ </form>+ </div>+ )}++ {rules.length === 0 && !isFormOpen ? (+ <UnstableEmpty>+ <UnstableEmptyHeader>+ <UnstableEmptyTitle>No rotation rules configured</UnstableEmptyTitle>+ </UnstableEmptyHeader>+ </UnstableEmpty>+ ) : (+ rules.length > 0 && (+ <UnstableTable>+ <UnstableTableHeader>+ <UnstableTableRow>+ <UnstableTableHead className="w-12">#</UnstableTableHead>+ <UnstableTableHead>Name</UnstableTableHead>+ <UnstableTableHead>Pattern</UnstableTableHead>+ <UnstableTableHead>Status</UnstableTableHead>+ <UnstableTableHead>Interval</UnstableTableHead>+ <UnstableTableHead>Created</UnstableTableHead>+ <UnstableTableHead className="w-28" />+ </UnstableTableRow>+ </UnstableTableHeader>+ <UnstableTableBody>+ {rules.map((rule, index) => (+ <UnstableTableRow key={rule.id}>+ <UnstableTableCell>+ <Badge variant="outline">{rule.priority}</Badge>+ </UnstableTableCell>+ <UnstableTableCell>{rule.name || "-"}</UnstableTableCell>+ <UnstableTableCell>+ <code className="rounded bg-mineshaft-600 px-1.5 py-0.5 text-xs">+ {rule.namePattern}+ </code>+ </UnstableTableCell>+ <UnstableTableCell>+ <Badge variant={rule.enabled ? "success" : "neutral"}>+ {rule.enabled ? "Enabled" : "Disabled"}+ </Badge>+ </UnstableTableCell>+ <UnstableTableCell>+ {rule.enabled && rule.intervalSeconds+ ? formatInterval(rule.intervalSeconds)+ : "-"}+ </UnstableTableCell>+ <UnstableTableCell>+ {format(new Date(rule.createdAt), "MM/dd/yyyy")}+ </UnstableTableCell>+ <UnstableTableCell>+ <div className="flex items-center gap-1">+ <UnstableIconButton+ variant="ghost"+ size="xs"+ onClick={() => handleMoveUp(index)}+ isDisabled={index === 0}+ >+ <ArrowUpIcon className="size-3.5" />+ </UnstableIconButton>+ <UnstableIconButton+ variant="ghost"+ size="xs"+ onClick={() => handleMoveDown(index)}+ isDisabled={index >= rules.length - 1}+ >+ <ArrowDownIcon className="size-3.5" />+ </UnstableIconButton>+ <UnstableIconButton+ variant="ghost"+ size="xs"+ onClick={() => openEditForm(rule)}+ >+ <PencilIcon className="size-3.5" />+ </UnstableIconButton>+ <UnstableIconButton+ variant="ghost"+ size="xs"+ onClick={() => handleDelete(rule.id)}+ >+ <TrashIcon className="size-3.5" />+ </UnstableIconButton>+ </div>+ </UnstableTableCell>+ </UnstableTableRow>+ ))}+ </UnstableTableBody>+ </UnstableTable>+ )+ )}+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamResourceByIDPage/components/PamRotationPolicyModal.tsx b/frontend/src/pages/pam/PamResourceByIDPage/components/PamRotationPolicyModal.tsxnew file mode 100644index 0000000000..94d5731634--- /dev/null+++ b/frontend/src/pages/pam/PamResourceByIDPage/components/PamRotationPolicyModal.tsx@@ -0,0 +1,522 @@+import { useCallback, useEffect, useState } from "react";+import { Controller, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { ArrowDownIcon, ArrowUpIcon, EyeIcon, EyeOffIcon, PlusIcon, TrashIcon } from "lucide-react";+import { twMerge } from "tailwind-merge";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import { FormControl, Input, Modal, ModalContent, Switch } from "@app/components/v2";+import { Button, UnstableIconButton } from "@app/components/v3";+import { TPamResource, TPamRotationRule, useUpdatePamResource } from "@app/hooks/api/pam";+import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";+import {+ useCreatePamRotationRule,+ useDeletePamRotationRule,+ useReorderPamRotationRules,+ useUpdatePamRotationRule+} from "@app/hooks/api/pam/mutations";+import { useGetPamRotationRules } from "@app/hooks/api/pam/queries";++const formatIntervalDays = (seconds: number) => {+ const days = Math.round(seconds / 86400);+ return days.toString();+};++const TEMP_ID_PREFIX = "_new_";++// A local working copy of a rule (may be new or existing)+type LocalRule = {+ id: string;+ name: string | null;+ namePattern: string;+ enabled: boolean;+ intervalSeconds: number | null;+};++type RuleCardProps = {+ rule: LocalRule;+ index: number;+ totalRules: number;+ onMoveUp: () => void;+ onMoveDown: () => void;+ onDelete: () => void;+ onUpdate: (+ updates: Partial<Pick<LocalRule, "name" | "namePattern" | "enabled" | "intervalSeconds">>+ ) => void;+};++const RuleCard = ({+ rule,+ index,+ totalRules,+ onMoveUp,+ onMoveDown,+ onDelete,+ onUpdate+}: RuleCardProps) => {+ const [localName, setLocalName] = useState(rule.name ?? "");+ const [localPattern, setLocalPattern] = useState(rule.namePattern);+ const [localInterval, setLocalInterval] = useState(+ rule.intervalSeconds ? formatIntervalDays(rule.intervalSeconds) : "30"+ );++ useEffect(() => {+ setLocalName(rule.name ?? "");+ setLocalPattern(rule.namePattern);+ setLocalInterval(rule.intervalSeconds ? formatIntervalDays(rule.intervalSeconds) : "30");+ }, [rule]);++ const handleNameBlur = () => {+ if (localName !== (rule.name ?? "")) {+ onUpdate({ name: localName || null });+ }+ };++ const handlePatternBlur = () => {+ if (localPattern !== rule.namePattern && localPattern.trim()) {+ onUpdate({ namePattern: localPattern });+ }+ };++ const handleIntervalBlur = () => {+ const days = parseInt(localInterval, 10);+ if (!Number.isNaN(days) && days > 0) {+ const seconds = days * 86400;+ if (seconds !== rule.intervalSeconds) {+ onUpdate({ intervalSeconds: seconds });+ }+ }+ };++ return (+ <div className="rounded-lg border border-border bg-mineshaft-700/30 p-4">+ <div className="mb-3 flex items-center justify-between">+ <div className="flex items-center gap-2">+ <span className="text-xl font-medium text-muted">{index + 1}</span>+ <span className="text-muted">•</span>+ <Switch+ id={`rule-enabled-${rule.id}`}+ isChecked={rule.enabled}+ onCheckedChange={(checked) => onUpdate({ enabled: checked })}+ className="ml-0 bg-mineshaft-400/80 shadow-inner data-[state=checked]:bg-green/80"+ thumbClassName="bg-mineshaft-800"+ />+ {rule.enabled ? (+ <span className="text-sm font-medium text-green">Rotate</span>+ ) : (+ <span className="text-sm font-medium text-red">Do Not Rotate</span>+ )}+ </div>+ <div className="flex items-center gap-1">+ <UnstableIconButton variant="ghost" size="xs" onClick={onMoveUp} isDisabled={index === 0}>+ <ArrowUpIcon className="size-3.5" />+ </UnstableIconButton>+ <UnstableIconButton+ variant="ghost"+ size="xs"+ onClick={onMoveDown}+ isDisabled={index >= totalRules - 1}+ >+ <ArrowDownIcon className="size-3.5" />+ </UnstableIconButton>+ <UnstableIconButton variant="ghost" size="xs" onClick={onDelete}>+ <TrashIcon className="size-3.5 text-red" />+ </UnstableIconButton>+ </div>+ </div>++ <div className="grid grid-cols-[1fr_1fr_auto] gap-3">+ <div>+ <span className="mb-1 block text-xs font-medium text-muted">Rule Name</span>+ <Input+ value={localName}+ onChange={(e) => setLocalName(e.target.value)}+ onBlur={handleNameBlur}+ placeholder="e.g., Service accounts"+ className="h-8 text-sm"+ />+ </div>+ <div>+ <span className="mb-1 block text-xs font-medium text-muted">Account Pattern</span>+ <Input+ value={localPattern}+ onChange={(e) => setLocalPattern(e.target.value)}+ onBlur={handlePatternBlur}+ placeholder="*"+ className="h-8 font-mono text-sm"+ />+ </div>+ <div>+ <span className="mb-1 block text-xs font-medium text-muted">Interval</span>+ <div className="flex items-center gap-1">+ <Input+ value={localInterval}+ onChange={(e) => setLocalInterval(e.target.value)}+ onBlur={handleIntervalBlur}+ className={twMerge("h-8 w-16 text-center text-sm", !rule.enabled && "opacity-50")}+ isDisabled={!rule.enabled}+ disabled={!rule.enabled}+ />+ <span className="text-xs text-muted">days</span>+ </div>+ </div>+ </div>+ </div>+ );+};++const credentialsSchema = z+ .object({+ username: z.string(),+ password: z.string()+ })+ .refine(+ (data) =>+ (data.username === "" && data.password === "") ||+ (data.username !== "" && data.password !== ""),+ {+ message:+ "Both username and password must be provided, or both must be empty to remove credentials",+ path: ["username"]+ }+ );++type CredentialsFormData = z.infer<typeof credentialsSchema>;++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ resource: TPamResource;+};++const toLocalRules = (rules: TPamRotationRule[]): LocalRule[] =>+ rules.map((r) => ({+ id: r.id,+ name: r.name ?? null,+ namePattern: r.namePattern,+ enabled: r.enabled,+ intervalSeconds: r.intervalSeconds ?? null+ }));++export const PamRotationPolicyModal = ({ isOpen, onOpenChange, resource }: Props) => {+ const { data: rules = [] } = useGetPamRotationRules(resource.id);+ const createRule = useCreatePamRotationRule();+ const updateRule = useUpdatePamRotationRule();+ const deleteRule = useDeletePamRotationRule();+ const reorderRules = useReorderPamRotationRules();+ const updateResource = useUpdatePamResource();++ const hasRotationCredentials =+ "rotationAccountCredentials" in resource && !!resource.rotationAccountCredentials;++ const [showPassword, setShowPassword] = useState(false);+ const [isSaving, setIsSaving] = useState(false);++ // Local working copy of rules — only persisted on save+ const [localRules, setLocalRules] = useState<LocalRule[]>([]);+ const [deletedRuleIds, setDeletedRuleIds] = useState<string[]>([]);++ const existingUsername =+ "rotationAccountCredentials" in resource+ ? ((resource.rotationAccountCredentials as { username?: string } | null)?.username ?? "")+ : "";++ const {+ control: credControl,+ handleSubmit: handleCredSubmit,+ reset: resetCred,+ formState: { isDirty: isCredDirty }+ } = useForm<CredentialsFormData>({+ resolver: zodResolver(credentialsSchema),+ defaultValues: {+ username: existingUsername,+ password: hasRotationCredentials ? UNCHANGED_PASSWORD_SENTINEL : ""+ }+ });++ const resetAll = useCallback(() => {+ setLocalRules(toLocalRules(rules));+ setDeletedRuleIds([]);+ const uname =+ "rotationAccountCredentials" in resource+ ? ((resource.rotationAccountCredentials as { username?: string } | null)?.username ?? "")+ : "";+ resetCred({+ username: uname,+ password: hasRotationCredentials ? UNCHANGED_PASSWORD_SENTINEL : ""+ });+ setShowPassword(false);+ }, [rules, resource, hasRotationCredentials, resetCred]);++ useEffect(() => {+ if (isOpen) {+ resetAll();+ }+ }, [isOpen, resetAll]);++ const handleAddRule = () => {+ setLocalRules((prev) => [+ ...prev,+ {+ id: `${TEMP_ID_PREFIX}${crypto.randomUUID()}`,+ name: null,+ namePattern: "*",+ enabled: true,+ intervalSeconds: 2592000+ }+ ]);+ };++ const handleUpdateLocalRule = (+ ruleId: string,+ updates: Partial<Pick<LocalRule, "name" | "namePattern" | "enabled" | "intervalSeconds">>+ ) => {+ setLocalRules((prev) => prev.map((r) => (r.id === ruleId ? { ...r, ...updates } : r)));+ };++ const handleDeleteLocalRule = (ruleId: string) => {+ setLocalRules((prev) => prev.filter((r) => r.id !== ruleId));+ if (!ruleId.startsWith(TEMP_ID_PREFIX)) {+ setDeletedRuleIds((prev) => [...prev, ruleId]);+ }+ };++ const handleMoveUp = (index: number) => {+ if (index === 0) return;+ setLocalRules((prev) => {+ const next = [...prev];+ [next[index - 1], next[index]] = [next[index], next[index - 1]];+ return next;+ });+ };++ const handleMoveDown = (index: number) => {+ setLocalRules((prev) => {+ if (index >= prev.length - 1) return prev;+ const next = [...prev];+ [next[index], next[index + 1]] = [next[index + 1], next[index]];+ return next;+ });+ };++ const handleSave = async (credData: CredentialsFormData) => {+ setIsSaving(true);+ try {+ // Save credentials if changed (send null to remove)+ if (isCredDirty) {+ const clearingCredentials = credData.username === "" && credData.password === "";+ await updateResource.mutateAsync({+ resourceId: resource.id,+ resourceType: resource.resourceType,+ rotationAccountCredentials: clearingCredentials+ ? null+ : { username: credData.username, password: credData.password }+ });+ }++ // Delete removed rules (sequential to avoid race conditions)+ await deletedRuleIds.reduce(+ (chain, ruleId) =>+ chain.then(() => deleteRule.mutateAsync({ resourceId: resource.id, ruleId }).then()),+ Promise.resolve()+ );++ // Create new rules & update existing ones (sequential to preserve order)+ const serverRuleIds = new Set(rules.map((r) => r.id));+ const newIdMap = new Map<string, string>();++ await localRules.reduce((chain, local) => {+ if (local.id.startsWith(TEMP_ID_PREFIX)) {+ return chain.then(async () => {+ const created = await createRule.mutateAsync({+ resourceId: resource.id,+ namePattern: local.namePattern,+ enabled: local.enabled,+ intervalSeconds: local.intervalSeconds ?? 2592000,+ name: local.name ?? undefined+ });+ newIdMap.set(local.id, created.id);+ });+ }+ if (serverRuleIds.has(local.id)) {+ const server = rules.find((r) => r.id === local.id);+ if (!server) return chain;+ const changed =+ local.name !== (server.name ?? null) ||+ local.namePattern !== server.namePattern ||+ local.enabled !== server.enabled ||+ local.intervalSeconds !== (server.intervalSeconds ?? null);+ if (changed) {+ return chain.then(() =>+ updateRule+ .mutateAsync({+ resourceId: resource.id,+ ruleId: local.id,+ name: local.name,+ namePattern: local.namePattern,+ enabled: local.enabled,+ intervalSeconds: local.intervalSeconds+ })+ .then()+ );+ }+ }+ return chain;+ }, Promise.resolve());++ // Reorder if needed+ const finalIds = localRules.map((r) =>+ r.id.startsWith(TEMP_ID_PREFIX) ? newIdMap.get(r.id)! : r.id+ );+ const serverOrder = rules.filter((r) => !deletedRuleIds.includes(r.id)).map((r) => r.id);+ const orderChanged =+ finalIds.length !== serverOrder.length || finalIds.some((id, i) => id !== serverOrder[i]);++ if (orderChanged && finalIds.length > 0) {+ await reorderRules.mutateAsync({ resourceId: resource.id, ruleIds: finalIds });+ }++ createNotification({ text: "Rotation policy updated", type: "success" });+ onOpenChange(false);+ } catch {+ createNotification({ text: "Failed to update rotation policy", type: "error" });+ } finally {+ setIsSaving(false);+ }+ };++ const handleCancel = () => {+ resetAll();+ onOpenChange(false);+ };++ return (+ <Modal isOpen={isOpen} onOpenChange={onOpenChange}>+ <ModalContent+ title="Edit Rotation Policy"+ subTitle="Configure automatic password rotation for accounts under this resource."+ >+ <div className="flex flex-col gap-6">+ {/* Section: Rotation Credentials */}+ <div>+ <h4 className="mb-1 text-sm font-semibold">Rotation Credentials</h4>+ <p className="mb-3 text-xs text-mineshaft-400">+ Privileged account used to perform password rotations+ </p>+ <div className="flex gap-3">+ <Controller+ name="username"+ control={credControl}+ render={({ field, fieldState: { error } }) => (+ <FormControl+ className="mb-0 flex-1"+ label="Username"+ isError={!!error}+ errorText={error?.message}+ >+ <Input {...field} autoComplete="off" />+ </FormControl>+ )}+ />+ <Controller+ name="password"+ control={credControl}+ render={({ field, fieldState: { error } }) => (+ <FormControl+ className="mb-0 flex-1"+ label="Password"+ isError={!!error}+ errorText={error?.message}+ >+ <div className="relative">+ <Input+ {...field}+ type={showPassword ? "text" : "password"}+ autoComplete="new-password"+ onFocus={() => {+ if (field.value === UNCHANGED_PASSWORD_SENTINEL) {+ field.onChange("");+ }+ }}+ />+ <button+ type="button"+ className="absolute top-1/2 right-2 -translate-y-1/2 text-muted hover:text-foreground"+ onClick={() => setShowPassword(!showPassword)}+ tabIndex={-1}+ >+ {showPassword ? (+ <EyeOffIcon className="size-4" />+ ) : (+ <EyeIcon className="size-4" />+ )}+ </button>+ </div>+ </FormControl>+ )}+ />+ </div>+ {hasRotationCredentials && (+ <p className="mt-2 text-xs text-mineshaft-400">+ Clear both fields to remove credentials and disable rotation.+ </p>+ )}+ </div>++ {/* Section: Rotation Rules */}+ <div>+ <div className="mb-3 flex items-center justify-between">+ <div>+ <h4 className="text-sm font-semibold">Rotation Rules</h4>+ <p className="text-xs text-mineshaft-400">+ Rules are evaluated top-to-bottom by priority+ </p>+ </div>+ <Button size="xs" onClick={handleAddRule}>+ <PlusIcon className="size-3.5" />+ Add Rule+ </Button>+ </div>++ {localRules.length === 0 ? (+ <div className="rounded-lg border border-dashed border-border p-6 text-center text-sm text-muted">+ No rotation rules configured. Add a rule to get started.+ </div>+ ) : (+ <div className="flex flex-col gap-3">+ {localRules.map((rule, index) => (+ <RuleCard+ key={rule.id}+ rule={rule}+ index={index}+ totalRules={localRules.length}+ onMoveUp={() => handleMoveUp(index)}+ onMoveDown={() => handleMoveDown(index)}+ onDelete={() => handleDeleteLocalRule(rule.id)}+ onUpdate={(updates) => handleUpdateLocalRule(rule.id, updates)}+ />+ ))}+ </div>+ )}+ </div>++ {/* Footer */}+ <div className="mt-4 flex gap-2">+ <Button+ variant="neutral"+ onClick={handleCredSubmit(handleSave)}+ isPending={isSaving}+ isDisabled={isSaving}+ >+ Update Details+ </Button>+ <Button variant="ghost" onClick={handleCancel}>+ Cancel+ </Button>+ </div>+ </div>+ </ModalContent>+ </Modal>+ );+};diff --git a/frontend/src/pages/pam/PamResourceByIDPage/components/index.ts b/frontend/src/pages/pam/PamResourceByIDPage/components/index.tsindex 252d81b2a2..3933eaabff 100644--- a/frontend/src/pages/pam/PamResourceByIDPage/components/index.ts+++ b/frontend/src/pages/pam/PamResourceByIDPage/components/index.ts@@ -3,3 +3,5 @@ export { PamResourceConnectionSection } from "./PamResourceConnectionSection";export { PamResourceDetailsSection } from "./PamResourceDetailsSection";export { PamResourceMetadataSection } from "./PamResourceMetadataSection";export { PamResourceRelatedResourcesSection } from "./PamResourceRelatedResourcesSection";+export { PamResourceRotationPolicySection } from "./PamResourceRotationPolicySection";+export { PamRotationPolicyModal } from "./PamRotationPolicyModal";diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PostgresResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PostgresResourceForm.tsxindex 4cbf8823a6..424f8d9558 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PostgresResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PostgresResourceForm.tsx@@ -5,12 +5,9 @@ import { z } from "zod";import { Button, ModalClose } from "@app/components/v2";import { PamResourceType, TPostgresResource } from "@app/hooks/api/pam";-import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";-import { BaseSqlAccountSchema } from "@app/pages/pam/PamAccountsPage/components/PamAccountForm/shared/sql-account-schemas";import { BaseSqlResourceSchema } from "./shared/sql-resource-schemas";import { SqlResourceFields } from "./shared/SqlResourceFields";-import { SqlRotateAccountFields } from "./shared/SqlRotateAccountFields";import { GenericResourceFields, genericResourceFieldsSchema } from "./GenericResourceFields";import { MetadataFields } from "./MetadataFields";@@ -21,8 +18,7 @@ type Props = {const formSchema = genericResourceFieldsSchema.extend({resourceType: z.literal(PamResourceType.Postgres),- connectionDetails: BaseSqlResourceSchema,- rotationAccountCredentials: BaseSqlAccountSchema.nullable().optional()+ connectionDetails: BaseSqlResourceSchema});type FormData = z.infer<typeof formSchema>;@@ -34,15 +30,7 @@ export const PostgresResourceForm = ({ resource, onSubmit }: Props) => {const form = useForm<FormData>({resolver: zodResolver(formSchema),defaultValues: resource- ? {- ...resource,- rotationAccountCredentials: resource.rotationAccountCredentials- ? {- ...resource.rotationAccountCredentials,- password: UNCHANGED_PASSWORD_SENTINEL- }- : resource.rotationAccountCredentials- }+ ? { ...resource }: {resourceType: PamResourceType.Postgres,connectionDetails: {@@ -74,7 +62,6 @@ export const PostgresResourceForm = ({ resource, onSubmit }: Props) => {selectedTabIndex={selectedTabIndex}setSelectedTabIndex={setSelectedTabIndex}/>- <SqlRotateAccountFields isUpdate={isUpdate} /><MetadataFields /><div className="mt-6 flex items-center"><Button