Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pam): account policies (#5971)
Saif Ur Rahman6c32712a1554
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 8d0f0c238f..15a8d3bc33 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -29,6 +29,7 @@ import { TLdapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-conimport { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";import { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";+import { TPamAccountPolicyServiceFactory } from "@app/ee/services/pam-account-policy/pam-account-policy-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";@@ -384,6 +385,7 @@ declare module "fastify" {pamResource: TPamResourceServiceFactory;pamResourceRotationRules: TPamResourceRotationRulesServiceFactory;pamAccount: TPamAccountServiceFactory;+ pamAccountPolicy: TPamAccountPolicyServiceFactory;pamSession: TPamSessionServiceFactory;pamWebAccess: TPamWebAccessServiceFactory;pamDiscoverySource: TPamDiscoverySourceServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 27f5c05471..506d6a29a5 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -674,6 +674,11 @@ import {TPamAccountDependenciesInsert,TPamAccountDependenciesUpdate} from "@app/db/schemas/pam-account-dependencies";+import {+ TPamAccountPolicies,+ TPamAccountPoliciesInsert,+ TPamAccountPoliciesUpdate+} from "@app/db/schemas/pam-account-policies";import { TPamAccounts, TPamAccountsInsert, TPamAccountsUpdate } from "@app/db/schemas/pam-accounts";import {TPamDiscoverySourceAccounts,@@ -1596,6 +1601,11 @@ declare module "knex/types/tables" {TPamResourceFavoritesUpdate>;[TableName.PamAccount]: KnexOriginal.CompositeTableType<TPamAccounts, TPamAccountsInsert, TPamAccountsUpdate>;+ [TableName.PamAccountPolicy]: KnexOriginal.CompositeTableType<+ TPamAccountPolicies,+ TPamAccountPoliciesInsert,+ TPamAccountPoliciesUpdate+ >;[TableName.PamSession]: KnexOriginal.CompositeTableType<TPamSessions, TPamSessionsInsert, TPamSessionsUpdate>;[TableName.PamSessionEventBatch]: KnexOriginal.CompositeTableType<TPamSessionEventBatches,diff --git a/backend/src/db/migrations/20260408014652_pam-account-policies.ts b/backend/src/db/migrations/20260408014652_pam-account-policies.tsnew file mode 100644index 0000000000..21f96632fe--- /dev/null+++ b/backend/src/db/migrations/20260408014652_pam-account-policies.ts@@ -0,0 +1,52 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.PamAccountPolicy))) {+ await knex.schema.createTable(TableName.PamAccountPolicy, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.string("projectId").notNullable();+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");+ t.index("projectId");++ t.string("name").notNullable();+ t.text("description").nullable();+ t.jsonb("rules").notNullable();+ t.boolean("isActive").notNullable().defaultTo(true);++ t.unique(["projectId", "name"]);++ t.timestamps(true, true, true);+ });+ }++ await createOnUpdateTrigger(knex, TableName.PamAccountPolicy);++ if (await knex.schema.hasTable(TableName.PamAccount)) {+ const hasColumn = await knex.schema.hasColumn(TableName.PamAccount, "policyId");+ if (!hasColumn) {+ await knex.schema.alterTable(TableName.PamAccount, (t) => {+ t.uuid("policyId").nullable();+ t.foreign("policyId").references("id").inTable(TableName.PamAccountPolicy).onDelete("SET NULL");+ t.index("policyId");+ });+ }+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.PamAccount)) {+ const hasColumn = await knex.schema.hasColumn(TableName.PamAccount, "policyId");+ if (hasColumn) {+ await knex.schema.alterTable(TableName.PamAccount, (t) => {+ t.dropColumn("policyId");+ });+ }+ }++ await knex.schema.dropTableIfExists(TableName.PamAccountPolicy);+ await dropOnUpdateTrigger(knex, TableName.PamAccountPolicy);+}diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 1ee9a97033..d12cb37583 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -110,6 +110,7 @@ export * from "./org-roles";export * from "./organization-assets";export * from "./organizations";export * from "./pam-account-dependencies";+export * from "./pam-account-policies";export * from "./pam-accounts";export * from "./pam-discovery-source-accounts";export * from "./pam-discovery-source-dependencies";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 33752dd9ef..4a7b624726 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -236,6 +236,7 @@ export enum TableName {PamAccountDependency = "pam_account_dependencies",PamResourceRotationRule = "pam_resource_rotation_rules",PamResourceFavorite = "pam_resource_favorites",+ PamAccountPolicy = "pam_account_policies",VaultExternalMigrationConfig = "vault_external_migration_configs",diff --git a/backend/src/db/schemas/pam-account-policies.ts b/backend/src/db/schemas/pam-account-policies.tsnew file mode 100644index 0000000000..382e9a6959--- /dev/null+++ b/backend/src/db/schemas/pam-account-policies.ts@@ -0,0 +1,23 @@+// 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 PamAccountPoliciesSchema = z.object({+ id: z.string().uuid(),+ projectId: z.string(),+ name: z.string(),+ description: z.string().nullable().optional(),+ rules: z.unknown(),+ isActive: z.boolean().default(true),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TPamAccountPolicies = z.infer<typeof PamAccountPoliciesSchema>;+export type TPamAccountPoliciesInsert = Omit<z.input<typeof PamAccountPoliciesSchema>, TImmutableDBKeys>;+export type TPamAccountPoliciesUpdate = Partial<Omit<z.input<typeof PamAccountPoliciesSchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/pam-accounts.ts b/backend/src/db/schemas/pam-accounts.tsindex f45ede2950..b84f31743b 100644--- a/backend/src/db/schemas/pam-accounts.ts+++ b/backend/src/db/schemas/pam-accounts.ts@@ -24,7 +24,8 @@ export const PamAccountsSchema = z.object({encryptedLastRotationMessage: zodBuffer.nullable().optional(),requireMfa: z.boolean().default(false).nullable().optional(),internalMetadata: z.unknown().nullable().optional(),- discoveryFingerprint: z.string().nullable().optional()+ discoveryFingerprint: z.string().nullable().optional(),+ policyId: z.string().uuid().nullable().optional()});export type TPamAccounts = z.infer<typeof PamAccountsSchema>;diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.tsindex e75e6871ac..d5d8b702c2 100644--- a/backend/src/ee/routes/v1/index.ts+++ b/backend/src/ee/routes/v1/index.ts@@ -27,6 +27,7 @@ import { registerLdapRouter } from "./ldap-router";import { registerLicenseRouter } from "./license-router";import { registerOidcRouter } from "./oidc-router";import { registerOrgRoleRouter } from "./org-role-router";+import { registerPamAccountPolicyRouter } from "./pam-account-policy-router";import { PAM_ACCOUNT_REGISTER_ROUTER_MAP } from "./pam-account-routers";import { registerPamAccountRouter } from "./pam-account-routers/pam-account-router";import { PAM_DISCOVERY_REGISTER_ROUTER_MAP } from "./pam-discovery-routers";@@ -202,6 +203,7 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {async (pamRouter) => {await pamRouter.register(registerPamFolderRouter, { prefix: "/folders" });await pamRouter.register(registerPamSessionRouter, { prefix: "/sessions" });+ await pamRouter.register(registerPamAccountPolicyRouter, { prefix: "/account-policies" });await pamRouter.register(async (pamDiscoveryRouter) => {await pamDiscoveryRouter.register(registerPamDiscoveryRouter);diff --git a/backend/src/ee/routes/v1/pam-account-policy-router.ts b/backend/src/ee/routes/v1/pam-account-policy-router.tsnew file mode 100644index 0000000000..0ac6369ac2--- /dev/null+++ b/backend/src/ee/routes/v1/pam-account-policy-router.ts@@ -0,0 +1,217 @@+import { z } from "zod";++import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { PolicyRulesInputSchema, SanitizedPamAccountPolicySchema } from "@app/ee/services/pam-account-policy";+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";++type TSanitizedPolicy = z.infer<typeof SanitizedPamAccountPolicySchema>;++export const registerPamAccountPolicyRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/",+ config: {+ rateLimit: readLimit+ },+ schema: {+ description: "List PAM account policies",+ querystring: z.object({+ projectId: z.string().uuid(),+ search: z.string().trim().optional()+ }),+ response: {+ 200: z.object({+ policies: z.array(SanitizedPamAccountPolicySchema)+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const policies = await server.services.pamAccountPolicy.list(req.query, req.permission);++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.query.projectId,+ event: {+ type: EventType.PAM_ACCOUNT_POLICY_LIST,+ metadata: {+ projectId: req.query.projectId+ }+ }+ });++ return { policies: policies as TSanitizedPolicy[] };+ }+ });++ server.route({+ method: "GET",+ url: "/:policyId",+ config: {+ rateLimit: readLimit+ },+ schema: {+ description: "Get a PAM account policy by ID",+ params: z.object({+ policyId: z.string().uuid()+ }),+ response: {+ 200: z.object({+ policy: SanitizedPamAccountPolicySchema+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const policy = await server.services.pamAccountPolicy.getById(req.params, req.permission);++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: policy.projectId,+ event: {+ type: EventType.PAM_ACCOUNT_POLICY_GET,+ metadata: {+ policyId: policy.id,+ projectId: policy.projectId+ }+ }+ });++ return { policy: policy as TSanitizedPolicy };+ }+ });++ server.route({+ method: "POST",+ url: "/",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ description: "Create a PAM account policy",+ body: z.object({+ projectId: z.string().uuid(),+ name: z.string().trim().min(1).max(255),+ description: z.string().trim().max(1000).optional(),+ rules: PolicyRulesInputSchema+ }),+ response: {+ 200: z.object({+ policy: SanitizedPamAccountPolicySchema+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const policy = await server.services.pamAccountPolicy.create(req.body, req.permission);++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.body.projectId,+ event: {+ type: EventType.PAM_ACCOUNT_POLICY_CREATE,+ metadata: {+ projectId: req.body.projectId,+ name: req.body.name,+ description: req.body.description+ }+ }+ });++ return { policy: policy as TSanitizedPolicy };+ }+ });++ server.route({+ method: "PATCH",+ url: "/:policyId",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ description: "Update a PAM account policy",+ params: z.object({+ policyId: z.string().uuid()+ }),+ body: z.object({+ name: z.string().trim().min(1).max(255).optional(),+ description: z.string().trim().max(1000).nullable().optional(),+ rules: PolicyRulesInputSchema.optional(),+ isActive: z.boolean().optional()+ }),+ response: {+ 200: z.object({+ policy: SanitizedPamAccountPolicySchema+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const policy = await server.services.pamAccountPolicy.updateById(+ { policyId: req.params.policyId, ...req.body },+ req.permission+ );++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: policy.projectId,+ event: {+ type: EventType.PAM_ACCOUNT_POLICY_UPDATE,+ metadata: {+ policyId: policy.id,+ projectId: policy.projectId,+ name: req.body.name,+ isActive: req.body.isActive+ }+ }+ });++ return { policy: policy as TSanitizedPolicy };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:policyId",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ description: "Delete a PAM account policy",+ params: z.object({+ policyId: z.string().uuid()+ }),+ response: {+ 200: z.object({+ policy: SanitizedPamAccountPolicySchema+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const policy = await server.services.pamAccountPolicy.deleteById(req.params, req.permission);++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: policy.projectId,+ event: {+ type: EventType.PAM_ACCOUNT_POLICY_DELETE,+ metadata: {+ policyId: policy.id,+ projectId: policy.projectId,+ name: policy.name+ }+ }+ });++ return { policy: policy as TSanitizedPolicy };+ }+ });+};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 92bc6576f8..b78ae1a941 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@@ -28,6 +28,7 @@ export const registerPamAccountEndpoints = <C extends TPamAccount>({requireMfa?: C["requireMfa"];internalMetadata?: Record<string, unknown>;metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;+ policyId?: string | null;}>;updateAccountSchema: z.ZodType<{credentials?: C["credentials"];@@ -36,6 +37,7 @@ export const registerPamAccountEndpoints = <C extends TPamAccount>({requireMfa?: C["requireMfa"];internalMetadata?: Record<string, unknown>;metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;+ policyId?: string | null;}>;accountResponseSchema: z.ZodTypeAny;}) => {diff --git a/backend/src/ee/routes/v1/pam-session-router.ts b/backend/src/ee/routes/v1/pam-session-router.tsindex e88d20c967..3e491cd51a 100644--- a/backend/src/ee/routes/v1/pam-session-router.ts+++ b/backend/src/ee/routes/v1/pam-session-router.ts@@ -2,6 +2,7 @@ import { z } from "zod";import { PamSessionsSchema } from "@app/db/schemas";import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { PolicyRulesResponseSchema } from "@app/ee/services/pam-account-policy";import { KubernetesSessionCredentialsSchema } from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";import { MongoDBSessionCredentialsSchema } from "@app/ee/services/pam-resource/mongodb/mongodb-resource-schemas";import { MySQLSessionCredentialsSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";@@ -50,13 +51,14 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {}),response: {200: z.object({- credentials: SessionCredentialsSchema+ credentials: SessionCredentialsSchema,+ policyRules: PolicyRulesResponseSchema})}},onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const { credentials, projectId, account, sessionStarted } =+ const { credentials, policyRules, projectId, account, sessionStarted } =await server.services.pamAccount.getSessionCredentials(req.params.sessionId, req.permission);await server.services.auditLog.createAuditLog({@@ -98,7 +100,10 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {.catch(() => {});}- return { credentials: credentials as z.infer<typeof SessionCredentialsSchema> };+ return {+ credentials: credentials as z.infer<typeof SessionCredentialsSchema>,+ policyRules+ };}});diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 4cbec5ed27..37d3d26dde 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -615,6 +615,11 @@ export enum EventType {PAM_ACCOUNT_DELETE = "pam-account-delete",PAM_ACCOUNT_CREDENTIAL_ROTATION = "pam-account-credential-rotation",PAM_ACCOUNT_CREDENTIAL_ROTATION_FAILED = "pam-account-credential-rotation-failed",+ PAM_ACCOUNT_POLICY_CREATE = "pam-account-policy-create",+ PAM_ACCOUNT_POLICY_UPDATE = "pam-account-policy-update",+ PAM_ACCOUNT_POLICY_DELETE = "pam-account-policy-delete",+ PAM_ACCOUNT_POLICY_LIST = "pam-account-policy-list",+ PAM_ACCOUNT_POLICY_GET = "pam-account-policy-get",PAM_ACCOUNT_READ_CREDENTIALS = "pam-account-read-credentials",PAM_WEB_ACCESS_SESSION_TICKET_CREATED = "pam-web-access-session-ticket-created",PAM_RESOURCE_LIST = "pam-resource-list",@@ -4882,6 +4887,49 @@ interface PamAccountCredentialRotationFailedEvent {};}+interface PamAccountPolicyCreateEvent {+ type: EventType.PAM_ACCOUNT_POLICY_CREATE;+ metadata: {+ projectId: string;+ name: string;+ description?: string;+ };+}++interface PamAccountPolicyUpdateEvent {+ type: EventType.PAM_ACCOUNT_POLICY_UPDATE;+ metadata: {+ policyId: string;+ projectId: string;+ name?: string;+ isActive?: boolean;+ };+}++interface PamAccountPolicyDeleteEvent {+ type: EventType.PAM_ACCOUNT_POLICY_DELETE;+ metadata: {+ policyId: string;+ projectId: string;+ name: string;+ };+}++interface PamAccountPolicyListEvent {+ type: EventType.PAM_ACCOUNT_POLICY_LIST;+ metadata: {+ projectId: string;+ };+}++interface PamAccountPolicyGetEvent {+ type: EventType.PAM_ACCOUNT_POLICY_GET;+ metadata: {+ policyId: string;+ projectId: string;+ };+}+interface PamAccountReadCredentialsEvent {type: EventType.PAM_ACCOUNT_READ_CREDENTIALS;metadata: {@@ -6236,6 +6284,11 @@ export type Event =| PamAccountDeleteEvent| PamAccountCredentialRotationEvent| PamAccountCredentialRotationFailedEvent+ | PamAccountPolicyCreateEvent+ | PamAccountPolicyUpdateEvent+ | PamAccountPolicyDeleteEvent+ | PamAccountPolicyListEvent+ | PamAccountPolicyGetEvent| PamAccountReadCredentialsEvent| PamResourceListEvent| PamResourceGetEventdiff --git a/backend/src/ee/services/pam-account-policy/index.ts b/backend/src/ee/services/pam-account-policy/index.tsnew file mode 100644index 0000000000..86b36857b4--- /dev/null+++ b/backend/src/ee/services/pam-account-policy/index.ts@@ -0,0 +1,14 @@+export {+ PAM_ACCOUNT_POLICY_RULE_METADATA,+ PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES+} from "./pam-account-policy-constants";+export { pamAccountPolicyDALFactory, type TPamAccountPolicyDALFactory } from "./pam-account-policy-dal";+export { PamAccountPolicyRuleType } from "./pam-account-policy-enums";+export {+ PolicyRulesBaseSchema,+ PolicyRulesInputSchema,+ PolicyRulesResponseSchema,+ SanitizedPamAccountPolicySchema+} from "./pam-account-policy-schemas";+export { pamAccountPolicyServiceFactory, type TPamAccountPolicyServiceFactory } from "./pam-account-policy-service";+export type * from "./pam-account-policy-types";diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-constants.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-constants.tsnew file mode 100644index 0000000000..1206b2c7c2--- /dev/null+++ b/backend/src/ee/services/pam-account-policy/pam-account-policy-constants.ts@@ -0,0 +1,20 @@+import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";++import { PamAccountPolicyRuleType } from "./pam-account-policy-enums";++export const PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES: Record<PamAccountPolicyRuleType, PamResource[] | "all"> = {+ [PamAccountPolicyRuleType.CommandBlocking]: [PamResource.SSH],+ [PamAccountPolicyRuleType.SessionLogMasking]: "all"+};++export const PAM_ACCOUNT_POLICY_RULE_METADATA: Record<PamAccountPolicyRuleType, { name: string; description: string }> =+ {+ [PamAccountPolicyRuleType.CommandBlocking]: {+ name: "Command Blocking",+ description: "Block commands matching specified patterns"+ },+ [PamAccountPolicyRuleType.SessionLogMasking]: {+ name: "Session Log Masking",+ description: "Mask sensitive data in session logs matching specified patterns"+ }+ };diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-dal.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-dal.tsnew file mode 100644index 0000000000..7118126028--- /dev/null+++ b/backend/src/ee/services/pam-account-policy/pam-account-policy-dal.ts@@ -0,0 +1,24 @@+import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TPamAccountPolicyDALFactory = ReturnType<typeof pamAccountPolicyDALFactory>;++export const pamAccountPolicyDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.PamAccountPolicy);++ const findByProjectId = async (projectId: string, search?: string) => {+ const query = db.replicaNode()(TableName.PamAccountPolicy).where({ projectId }).orderBy("createdAt", "desc");++ if (search) {+ void query.whereILike("name", `%${search}%`);+ }++ return query;+ };++ return {+ ...orm,+ findByProjectId+ };+};diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-enums.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-enums.tsnew file mode 100644index 0000000000..0461215089--- /dev/null+++ b/backend/src/ee/services/pam-account-policy/pam-account-policy-enums.ts@@ -0,0 +1,4 @@+export enum PamAccountPolicyRuleType {+ CommandBlocking = "command-blocking",+ SessionLogMasking = "session-log-masking"+}diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-schemas.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-schemas.tsnew file mode 100644index 0000000000..1901f82e67--- /dev/null+++ b/backend/src/ee/services/pam-account-policy/pam-account-policy-schemas.ts@@ -0,0 +1,43 @@+import RE2 from "re2";+import { z } from "zod";++import { PamAccountPoliciesSchema } from "@app/db/schemas";++import { PamAccountPolicyRuleType } from "./pam-account-policy-enums";++const re2PatternSchema = z+ .string()+ .min(1)+ .max(500, "Pattern must be at most 500 characters")+ .refine(+ (pattern) => {+ try {+ // eslint-disable-next-line no-new+ new RE2(pattern);+ return true;+ } catch {+ return false;+ }+ },+ { message: "Invalid regular expression" }+ );++const RuleConfigSchema = z.object({+ patterns: z.array(re2PatternSchema).min(1).max(20, "A rule can have at most 20 patterns")+});++export const PolicyRulesBaseSchema = z.object({+ [PamAccountPolicyRuleType.CommandBlocking]: RuleConfigSchema.optional(),+ [PamAccountPolicyRuleType.SessionLogMasking]: RuleConfigSchema.optional()+});++export const PolicyRulesInputSchema = PolicyRulesBaseSchema.refine(+ (rules) => Object.values(rules).some((v) => v !== undefined),+ "At least one rule must be configured"+);++export const PolicyRulesResponseSchema = PolicyRulesBaseSchema;++export const SanitizedPamAccountPolicySchema = PamAccountPoliciesSchema.extend({+ rules: PolicyRulesBaseSchema+});diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-service.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-service.tsnew file mode 100644index 0000000000..5e9e891723--- /dev/null+++ b/backend/src/ee/services/pam-account-policy/pam-account-policy-service.ts@@ -0,0 +1,174 @@+import { ForbiddenError } from "@casl/ability";++import { ActionProjectType } from "@app/db/schemas";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ProjectPermissionPamAccountPolicyActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { OrgServiceActor } from "@app/lib/types";++import { TPamAccountPolicyDALFactory } from "./pam-account-policy-dal";+import {+ TCreatePamAccountPolicyDTO,+ TDeletePamAccountPolicyDTO,+ TGetPamAccountPolicyByIdDTO,+ TListPamAccountPoliciesDTO,+ TUpdatePamAccountPolicyDTO+} from "./pam-account-policy-types";++type TPamAccountPolicyServiceFactoryDep = {+ pamAccountPolicyDAL: TPamAccountPolicyDALFactory;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+};++export type TPamAccountPolicyServiceFactory = ReturnType<typeof pamAccountPolicyServiceFactory>;++export const pamAccountPolicyServiceFactory = ({+ pamAccountPolicyDAL,+ permissionService+}: TPamAccountPolicyServiceFactoryDep) => {+ const create = async (+ { projectId, name, description, rules }: TCreatePamAccountPolicyDTO,+ actor: OrgServiceActor+ ) => {+ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId,+ actionProjectType: ActionProjectType.PAM+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionPamAccountPolicyActions.Create,+ ProjectPermissionSub.PamAccountPolicies+ );++ const existing = await pamAccountPolicyDAL.findOne({ projectId, name });+ if (existing) {+ throw new BadRequestError({ message: `A policy with name '${name}' already exists in this project` });+ }++ const policy = await pamAccountPolicyDAL.create({+ projectId,+ name,+ description,+ rules+ });++ return policy;+ };++ const updateById = async (+ { policyId, name, description, rules, isActive }: TUpdatePamAccountPolicyDTO,+ actor: OrgServiceActor+ ) => {+ const existingPolicy = await pamAccountPolicyDAL.findById(policyId);+ if (!existingPolicy) throw new NotFoundError({ message: "Policy not found" });++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId: existingPolicy.projectId,+ actionProjectType: ActionProjectType.PAM+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionPamAccountPolicyActions.Edit,+ ProjectPermissionSub.PamAccountPolicies+ );++ if (name && name !== existingPolicy.name) {+ const duplicate = await pamAccountPolicyDAL.findOne({ projectId: existingPolicy.projectId, name });+ if (duplicate) {+ throw new BadRequestError({ message: `A policy with name '${name}' already exists in this project` });+ }+ }++ const policy = await pamAccountPolicyDAL.updateById(policyId, {+ name,+ description,+ rules,+ isActive+ });++ return policy;+ };++ const deleteById = async ({ policyId }: TDeletePamAccountPolicyDTO, actor: OrgServiceActor) => {+ const existingPolicy = await pamAccountPolicyDAL.findById(policyId);+ if (!existingPolicy) throw new NotFoundError({ message: "Policy not found" });++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId: existingPolicy.projectId,+ actionProjectType: ActionProjectType.PAM+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionPamAccountPolicyActions.Delete,+ ProjectPermissionSub.PamAccountPolicies+ );++ const policy = await pamAccountPolicyDAL.deleteById(policyId);++ return policy;+ };++ const list = async ({ projectId, search }: TListPamAccountPoliciesDTO, actor: OrgServiceActor) => {+ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId,+ actionProjectType: ActionProjectType.PAM+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionPamAccountPolicyActions.Read,+ ProjectPermissionSub.PamAccountPolicies+ );++ const policies = await pamAccountPolicyDAL.findByProjectId(projectId, search);++ return policies;+ };++ const getById = async ({ policyId }: TGetPamAccountPolicyByIdDTO, actor: OrgServiceActor) => {+ const policy = await pamAccountPolicyDAL.findById(policyId);+ if (!policy) throw new NotFoundError({ message: "Policy not found" });++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId: policy.projectId,+ actionProjectType: ActionProjectType.PAM+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionPamAccountPolicyActions.Read,+ ProjectPermissionSub.PamAccountPolicies+ );++ return policy;+ };++ return {+ create,+ updateById,+ deleteById,+ list,+ getById+ };+};diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-types.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-types.tsnew file mode 100644index 0000000000..1c12a3dbd9--- /dev/null+++ b/backend/src/ee/services/pam-account-policy/pam-account-policy-types.ts@@ -0,0 +1,33 @@+import { z } from "zod";++import { PolicyRulesBaseSchema } from "./pam-account-policy-schemas";++export type TPolicyRules = z.infer<typeof PolicyRulesBaseSchema>;++export type TCreatePamAccountPolicyDTO = {+ projectId: string;+ name: string;+ description?: string;+ rules: TPolicyRules;+};++export type TUpdatePamAccountPolicyDTO = {+ policyId: string;+ name?: string;+ description?: string | null;+ rules?: TPolicyRules;+ isActive?: boolean;+};++export type TDeletePamAccountPolicyDTO = {+ policyId: string;+};++export type TListPamAccountPoliciesDTO = {+ projectId: string;+ search?: string;+};++export type TGetPamAccountPolicyByIdDTO = {+ policyId: string;+};diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.tsindex fedf2ac2ab..71c11d7cec 100644--- a/backend/src/ee/services/pam-account/pam-account-dal.ts+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts@@ -45,6 +45,7 @@ export const pamAccountDALFactory = (db: TDbClient) => {const dbInstance = tx || db.replicaNode();const query = dbInstance(TableName.PamAccount).leftJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)+ .leftJoin(TableName.PamAccountPolicy, `${TableName.PamAccount}.policyId`, `${TableName.PamAccountPolicy}.id`).where(`${TableName.PamAccount}.projectId`, projectId);if (accountView === PamAccountView.Nested) {@@ -84,7 +85,9 @@ export const pamAccountDALFactory = (db: TDbClient) => {// resourcedb.ref("name").withSchema(TableName.PamResource).as("resourceName"),db.ref("resourceType").withSchema(TableName.PamResource),- db.ref("encryptedRotationAccountCredentials").withSchema(TableName.PamResource)+ db.ref("encryptedRotationAccountCredentials").withSchema(TableName.PamResource),+ // policy+ db.ref("name").withSchema(TableName.PamAccountPolicy).as("policyName"));const direction = orderDirection === OrderByDirection.ASC ? "ASC" : "DESC";@@ -99,10 +102,11 @@ export const pamAccountDALFactory = (db: TDbClient) => {const totalCount = Number(countResult?.count || 0);const accounts = results.map(- // @ts-expect-error resourceName, resourceType, encryptedRotationAccountCredentials are from joined table- ({ resourceId, resourceName, resourceType, encryptedRotationAccountCredentials, ...account }) => ({+ // @ts-expect-error resourceName, resourceType, encryptedRotationAccountCredentials, policyName are from joined tables+ ({ resourceId, resourceName, resourceType, encryptedRotationAccountCredentials, policyName, ...account }) => ({...account,resourceId,+ policyName: (policyName as string) || null,resource: {id: resourceId,name: resourceName as string,@@ -122,27 +126,32 @@ export const pamAccountDALFactory = (db: TDbClient) => {const dbInstance = tx || db.replicaNode();const result = await dbInstance(TableName.PamAccount).leftJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)+ .leftJoin(TableName.PamAccountPolicy, `${TableName.PamAccount}.policyId`, `${TableName.PamAccountPolicy}.id`).where(`${TableName.PamAccount}.id`, accountId).select(selectAllTableCols(TableName.PamAccount)).select(db.ref("name").withSchema(TableName.PamResource).as("resourceName"),db.ref("resourceType").withSchema(TableName.PamResource),- db.ref("encryptedRotationAccountCredentials").withSchema(TableName.PamResource)+ db.ref("encryptedRotationAccountCredentials").withSchema(TableName.PamResource),+ db.ref("name").withSchema(TableName.PamAccountPolicy).as("policyName")).first();if (!result) return null;- const { resourceId, resourceName, resourceType, encryptedRotationAccountCredentials, ...account } = result as {- resourceId: string;- resourceName: string;- resourceType: string;- encryptedRotationAccountCredentials: Buffer | null;- } & typeof result;+ const { resourceId, resourceName, resourceType, encryptedRotationAccountCredentials, policyName, ...account } =+ result as {+ resourceId: string;+ resourceName: string;+ resourceType: string;+ encryptedRotationAccountCredentials: Buffer | null;+ policyName: string | null;+ } & typeof result;return {...account,resourceId,+ policyName: policyName || null,resource: {id: resourceId,name: resourceName,diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex f39f1fecb2..59df0f1d08 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -52,6 +52,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 { PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES } from "../pam-account-policy/pam-account-policy-constants";+import { TPamAccountPolicyDALFactory } from "../pam-account-policy/pam-account-policy-dal";+import { PamAccountPolicyRuleType } from "../pam-account-policy/pam-account-policy-enums";+import { TPolicyRules } from "../pam-account-policy/pam-account-policy-types";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";@@ -84,6 +88,7 @@ type TPamAccountServiceFactoryDep = {pamResourceDAL: TPamResourceDALFactory;pamSessionDAL: TPamSessionDALFactory;pamAccountDAL: TPamAccountDALFactory;+ pamAccountPolicyDAL: Pick<TPamAccountPolicyDALFactory, "findById">;pamResourceRotationRulesDAL: Pick<TPamResourceRotationRulesDALFactory, "findByResourceIds">;mfaSessionService: TMfaSessionServiceFactory;projectDAL: TProjectDALFactory;@@ -116,6 +121,7 @@ export const pamAccountServiceFactory = ({pamResourceDAL,pamSessionDAL,pamAccountDAL,+ pamAccountPolicyDAL,pamResourceRotationRulesDAL,mfaSessionService,projectDAL,@@ -132,7 +138,17 @@ export const pamAccountServiceFactory = ({pamAccountDependenciesDAL}: TPamAccountServiceFactoryDep) => {const create = async (- { credentials, resourceId, name, description, folderId, requireMfa, internalMetadata, metadata }: TCreateAccountDTO,+ {+ credentials,+ resourceId,+ name,+ description,+ folderId,+ requireMfa,+ internalMetadata,+ metadata,+ policyId+ }: TCreateAccountDTO,actor: OrgServiceActor) => {const resource = await pamResourceDAL.findById(resourceId);@@ -188,6 +204,13 @@ export const pamAccountServiceFactory = ({kmsService});+ if (policyId) {+ const policy = await pamAccountPolicyDAL.findById(policyId);+ if (!policy || policy.projectId !== resource.projectId) {+ throw new NotFoundError({ message: "Policy not found" });+ }+ }+try {const { account, insertedMetadata } = await pamAccountDAL.transaction(async (tx) => {const newAccount = await pamAccountDAL.create(@@ -199,7 +222,8 @@ export const pamAccountServiceFactory = ({description,folderId,requireMfa,- internalMetadata: internalMetadata ?? null+ internalMetadata: internalMetadata ?? null,+ policyId: policyId ?? null},tx);@@ -243,7 +267,7 @@ export const pamAccountServiceFactory = ({};const updateById = async (- { accountId, credentials, description, name, requireMfa, internalMetadata, metadata }: TUpdateAccountDTO,+ { accountId, credentials, description, name, requireMfa, internalMetadata, metadata, policyId }: TUpdateAccountDTO,actor: OrgServiceActor) => {const account = await pamAccountDAL.findById(accountId);@@ -306,6 +330,16 @@ export const pamAccountServiceFactory = ({updateDoc.internalMetadata = internalMetadata;}+ if (policyId !== undefined) {+ if (policyId) {+ const policy = await pamAccountPolicyDAL.findById(policyId);+ if (!policy || policy.projectId !== account.projectId) {+ throw new NotFoundError({ message: "Policy not found" });+ }+ }+ updateDoc.policyId = policyId;+ }+if (credentials !== undefined) {const connectionDetails = await decryptResourceConnectionDetails({projectId: account.projectId,@@ -995,6 +1029,24 @@ export const pamAccountServiceFactory = ({const decryptedResource = await decryptResource(resource, session.projectId, kmsService);+ // Resolve policy rules for gateway+ const policyRules: TPolicyRules = {};+ if (account.policyId) {+ const policy = await pamAccountPolicyDAL.findById(account.policyId);+ if (policy && policy.isActive) {+ const rules = (policy.rules ?? {}) as TPolicyRules;+ for (const ruleType of Object.values(PamAccountPolicyRuleType)) {+ const ruleConfig = rules[ruleType];+ if (ruleConfig) {+ const supported = PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES[ruleType];+ if (supported === "all" || supported.includes(resource.resourceType as PamResource)) {+ policyRules[ruleType] = ruleConfig;+ }+ }+ }+ }+ }+let sessionStarted = false;// Mark session as started@@ -1050,6 +1102,7 @@ export const pamAccountServiceFactory = ({privateKey,certificate: signedPublicKey},+ policyRules,projectId: project.id,account,sessionStarted@@ -1062,6 +1115,7 @@ export const pamAccountServiceFactory = ({...decryptedResource.connectionDetails,...decryptedAccount.credentials},+ policyRules,projectId: project.id,account,sessionStarteddiff --git a/backend/src/ee/services/pam-account/pam-account-types.ts b/backend/src/ee/services/pam-account/pam-account-types.tsindex 5b1d033ed7..7ef9273614 100644--- a/backend/src/ee/services/pam-account/pam-account-types.ts+++ b/backend/src/ee/services/pam-account/pam-account-types.ts@@ -13,6 +13,7 @@ export type TCreateAccountDTO = Pick<> & {internalMetadata?: Record<string, unknown>;metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;+ policyId?: string | null;};export type TUpdateAccountDTO = Partial<Omit<TCreateAccountDTO, "folderId" | "resourceId">> & {diff --git a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts b/backend/src/ee/services/pam-resource/pam-resource-schemas.tsindex dd452d7824..f41d0b7599 100644--- a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts+++ b/backend/src/ee/services/pam-resource/pam-resource-schemas.ts@@ -82,6 +82,7 @@ export const BasePamAccountSchemaWithResource = BasePamAccountSchema.extend({}).extend({rotationCredentialsConfigured: z.boolean()}),+ policyName: z.string().nullable().optional(),lastRotationMessage: z.string().nullable().optional(),rotationStatus: z.string().nullable().optional()});@@ -92,12 +93,14 @@ export const BaseCreatePamAccountSchema = z.object({name: slugSchema({ field: "name" }),description: z.string().max(512).nullable().optional(),requireMfa: z.boolean().optional().default(false),- metadata: ResourceMetadataNonEncryptionSchema.optional()+ metadata: ResourceMetadataNonEncryptionSchema.optional(),+ policyId: z.string().uuid().nullable().optional()});export const BaseUpdatePamAccountSchema = z.object({name: slugSchema({ field: "name" }).optional(),description: z.string().max(512).nullable().optional(),requireMfa: z.boolean().optional(),- metadata: ResourceMetadataNonEncryptionSchema.optional()+ metadata: ResourceMetadataNonEncryptionSchema.optional(),+ policyId: z.string().uuid().nullable().optional()});diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex fa3d43f8a0..797c569af3 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -20,6 +20,7 @@ import {ProjectPermissionMcpEndpointActions,ProjectPermissionMemberActions,ProjectPermissionPamAccountActions,+ ProjectPermissionPamAccountPolicyActions,ProjectPermissionPamDiscoveryActions,ProjectPermissionPamSessionActions,ProjectPermissionPkiCertificateInstallationActions,@@ -403,6 +404,16 @@ const buildAdminPermissionRules = () => {ProjectPermissionSub.PamSessions);+ can(+ [+ ProjectPermissionPamAccountPolicyActions.Read,+ ProjectPermissionPamAccountPolicyActions.Create,+ ProjectPermissionPamAccountPolicyActions.Edit,+ ProjectPermissionPamAccountPolicyActions.Delete+ ],+ ProjectPermissionSub.PamAccountPolicies+ );+can([ProjectPermissionPamDiscoveryActions.Read,@@ -692,6 +703,8 @@ const buildMemberPermissionRules = () => {ProjectPermissionSub.PamAccounts);+ can([ProjectPermissionPamAccountPolicyActions.Read], ProjectPermissionSub.PamAccountPolicies);+can([ProjectPermissionPamDiscoveryActions.Read], ProjectPermissionSub.PamDiscovery);can([ProjectPermissionMcpEndpointActions.Read], ProjectPermissionSub.McpEndpoints);@@ -771,6 +784,8 @@ const buildViewerPermissionRules = () => {can([ProjectPermissionPamAccountActions.Read], ProjectPermissionSub.PamAccounts);+ can([ProjectPermissionPamAccountPolicyActions.Read], ProjectPermissionSub.PamAccountPolicies);+can([ProjectPermissionPamDiscoveryActions.Read], ProjectPermissionSub.PamDiscovery);can([ProjectPermissionMcpEndpointActions.Read], ProjectPermissionSub.McpEndpoints);diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.tsindex f0e4ecf2ac..b9a54294ea 100644--- a/backend/src/ee/services/permission/project-permission.ts+++ b/backend/src/ee/services/permission/project-permission.ts@@ -263,6 +263,13 @@ export enum ProjectPermissionPamSessionActions {Terminate = "terminate"}+export enum ProjectPermissionPamAccountPolicyActions {+ Read = "read",+ Create = "create",+ Edit = "edit",+ Delete = "delete"+}+export enum ProjectPermissionPamDiscoveryActions {Read = "read",Create = "create",@@ -347,6 +354,7 @@ export enum ProjectPermissionSub {PamResources = "pam-resources",PamAccounts = "pam-accounts",PamSessions = "pam-sessions",+ PamAccountPolicies = "pam-account-policies",PamDiscovery = "pam-discovery",CertificateProfiles = "certificate-profiles",CertificatePolicies = "certificate-policies",@@ -662,6 +670,7 @@ export type ProjectPermissionSet =ProjectPermissionSub.PamAccounts | (ForcedSubject<ProjectPermissionSub.PamAccounts> & PamAccountSubjectFields)]| [ProjectPermissionPamSessionActions, ProjectPermissionSub.PamSessions]+ | [ProjectPermissionPamAccountPolicyActions, ProjectPermissionSub.PamAccountPolicies]| [ProjectPermissionPamDiscoveryActions, ProjectPermissionSub.PamDiscovery]| [ProjectPermissionMcpEndpointActions,@@ -1666,6 +1675,12 @@ const GeneralPermissionSchema = ["Describe what action an entity can take.")}),+ z.object({+ subject: z.literal(ProjectPermissionSub.PamAccountPolicies).describe("The entity this permission pertains to."),+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionPamAccountPolicyActions).describe(+ "Describe what action an entity can take."+ )+ }),z.object({subject: z.literal(ProjectPermissionSub.PamDiscovery).describe("The entity this permission pertains to."),action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionPamDiscoveryActions).describe(diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex e182ebe7fe..00998b88c3 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -84,6 +84,8 @@ import { oidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";import { oidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";import { pamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";import { pamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";+import { pamAccountPolicyDALFactory } from "@app/ee/services/pam-account-policy/pam-account-policy-dal";+import { pamAccountPolicyServiceFactory } from "@app/ee/services/pam-account-policy/pam-account-policy-service";import { pamAccountDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-account-dependencies-dal";import { pamDiscoveryQueueFactory } from "@app/ee/services/pam-discovery/pam-discovery-queue";import { pamDiscoverySourceAccountsDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-accounts-dal";@@ -2797,6 +2799,7 @@ export const registerRoutes = async (const pamFolderDAL = pamFolderDALFactory(db);const pamResourceFavoriteDAL = pamResourceFavoriteDALFactory(db);const pamAccountDAL = pamAccountDALFactory(db);+ const pamAccountPolicyDAL = pamAccountPolicyDALFactory(db);const pamSessionDAL = pamSessionDALFactory(db);const pamSessionEventBatchDAL = pamSessionEventBatchDALFactory(db);const pamDiscoveryRunDAL = pamDiscoveryRunDALFactory(db);@@ -2857,8 +2860,14 @@ export const registerRoutes = async (pamSessionAiSummaryService});+ const pamAccountPolicyService = pamAccountPolicyServiceFactory({+ pamAccountPolicyDAL,+ permissionService+ });+const pamAccountService = pamAccountServiceFactory({pamAccountDAL,+ pamAccountPolicyDAL,pamResourceRotationRulesDAL,gatewayV2Service,kmsService,@@ -3177,6 +3186,7 @@ export const registerRoutes = async (pamResource: pamResourceService,pamResourceRotationRules: pamResourceRotationRulesService,pamAccount: pamAccountService,+ pamAccountPolicy: pamAccountPolicyService,pamSession: pamSessionService,pamWebAccess: pamWebAccessService,pamDiscoverySource: pamDiscoverySourceService,diff --git a/docs/docs.json b/docs/docs.jsonindex 879e160217..2c28150f1f 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -896,6 +896,7 @@"group": "Product Reference","pages": ["documentation/platform/pam/product-reference/access-policies",+ "documentation/platform/pam/product-reference/account-policies","documentation/platform/pam/product-reference/auditing","documentation/platform/pam/product-reference/session-recording","documentation/platform/pam/product-reference/ai-session-insights",diff --git a/docs/documentation/platform/pam/getting-started/accounts.mdx b/docs/documentation/platform/pam/getting-started/accounts.mdxindex 9359b1153e..551057eaaf 100644--- a/docs/documentation/platform/pam/getting-started/accounts.mdx+++ b/docs/documentation/platform/pam/getting-started/accounts.mdx@@ -52,6 +52,12 @@ Accounts support custom key-value metadata that can be used to organize and clas+## Account Policies++You can assign an **Account Policy** to an account to enforce behavioral rules during sessions — such as blocking dangerous commands or masking sensitive data in session logs.++To assign a policy, select one from the **Account Policy** dropdown when creating or editing an account. To learn more about creating and managing policies, see the [Account Policies guide](/documentation/platform/pam/product-reference/account-policies).+## Automated Credential RotationInfisical supports automated credential rotation for some accounts on select resources, allowing you to automatically change passwords at set intervals to enhance security.diff --git a/docs/documentation/platform/pam/product-reference/account-policies.mdx b/docs/documentation/platform/pam/product-reference/account-policies.mdxnew file mode 100644index 0000000000..8333f2f86b--- /dev/null+++ b/docs/documentation/platform/pam/product-reference/account-policies.mdx@@ -0,0 +1,105 @@+---+title: "Account Policies"+sidebarTitle: "Account Policies"+description: "Learn how to define behavioral rules for PAM accounts using account policies."+---++Account Policies let you define behavioral rules that are enforced on PAM accounts during sessions. Use them to block dangerous commands, mask sensitive data in session logs, or both.++## Concepts++An account policy is a named, project-scoped configuration that contains one or more **rules**. Each rule targets a specific behavior:++| Rule Type | Description | Supported Resources |+|---|---|---|+| **Command Blocking** | Prevents execution of commands matching specified regex patterns. | SSH |+| **Session Log Masking** | Redacts data matching specified regex patterns from session logs. | All resource types |++A policy can be **active** or **inactive**. Only active policies are enforced during sessions.++## Creating an Account Policy++Navigate to your PAM project sidebar and click **Account Policies**, then click **Create Policy**.++++<Steps>+ <Step title="Name and Description">+ Provide a **name** for the policy (must be unique within the project) and an optional **description**.++ + </Step>+ <Step title="Add Rules">+ Click **Add Rule** and select a rule type from the menu. Each rule type can only be added once per policy.++ - **Command Blocking**: Add one or more regex patterns. Commands matching any of these patterns will be blocked during SSH sessions.+ - **Session Log Masking**: Add one or more regex patterns. Any data matching these patterns will be redacted in session logs.++ For each rule, click the **+** button to add additional patterns.++ ++ Here's an example of command blocking in action during a live SSH session:++ ++ And session logs with masked sensitive data:++ + </Step>+ <Step title="Save">+ Click **Create** to save the policy. The policy is active by default and will be enforced on any accounts it is assigned to.+ </Step>+</Steps>++## Assigning a Policy to an Account++When creating or editing an [Account](/documentation/platform/pam/getting-started/accounts), select a policy from the **Account Policy** dropdown. Each account can have at most one policy assigned. Multiple accounts can share the same policy.++++If a policy is deleted, any accounts that were using it will have their policy reference removed automatically.++## Toggling a Policy++You can toggle a policy between active and inactive from the account policies list page using the switch in the **Active** column. Inactive policies are not enforced during sessions.++## Editing a Policy++Click the **three-dot menu** on any policy row and select **Edit** to open the policy sheet. You can modify the name, description, and rules of the policy.++## Deleting a Policy++Click the **three-dot menu** on any policy row and select **Delete**. Deleting a policy removes it from all accounts that reference it.++## Writing Regex Patterns++Patterns use standard regular expression syntax. Some examples:++| Pattern | Effect |+|---|---|+| `rm\s+-rf` | Blocks `rm -rf` commands (command blocking) |+| `sudo\s+su` | Blocks `sudo su` commands (command blocking) |+| `password=.*` | Masks password values in logs (session log masking) |+| `api[_-]?key=.*` | Masks API key values in logs (session log masking) |++<Info>+ Patterns are matched as regular expressions against the full command (for command blocking) or session log content (for session log masking). Test your patterns carefully to avoid overly broad matches.+</Info>++## FAQ++<AccordionGroup>+ <Accordion title="Can I assign multiple policies to a single account?">+ No. Each account can have at most one policy assigned. If you need to combine rules, create a single policy that includes all the rules you need.+ </Accordion>+ <Accordion title="What happens when I deactivate a policy?">+ Deactivating a policy stops it from being enforced during sessions. The policy remains assigned to its accounts and can be reactivated at any time.+ </Accordion>+ <Accordion title="What happens when I delete a policy that is assigned to accounts?">+ The accounts will have their policy reference removed. The accounts themselves are not affected — they will simply have no policy applied.+ </Accordion>+ <Accordion title="What happens if a policy has rules that don't apply to the account's resource type?">+ Only the rules that are applicable to the resource type are enforced. For example, if a policy contains both a command blocking rule and a session log masking rule, and it is assigned to a PostgreSQL account, only the session log masking rule will be enforced — command blocking is specific to SSH resources and will be ignored for non-SSH accounts.+ </Accordion>+</AccordionGroup>diff --git a/docs/images/pam/product-reference/account-policies/account-policies-page.png b/docs/images/pam/product-reference/account-policies/account-policies-page.pngnew file mode 100644index 0000000000..9d864929b4Binary files /dev/null and b/docs/images/pam/product-reference/account-policies/account-policies-page.png differdiff --git a/docs/images/pam/product-reference/account-policies/assign-policy-to-account.png b/docs/images/pam/product-reference/account-policies/assign-policy-to-account.pngnew file mode 100644index 0000000000..e4fc82a738Binary files /dev/null and b/docs/images/pam/product-reference/account-policies/assign-policy-to-account.png differdiff --git a/docs/images/pam/product-reference/account-policies/command-blocking.png b/docs/images/pam/product-reference/account-policies/command-blocking.pngnew file mode 100644index 0000000000..47a5ee1826Binary files /dev/null and b/docs/images/pam/product-reference/account-policies/command-blocking.png differdiff --git a/docs/images/pam/product-reference/account-policies/create-policy-sheet.png b/docs/images/pam/product-reference/account-policies/create-policy-sheet.pngnew file mode 100644index 0000000000..201dd74a33Binary files /dev/null and b/docs/images/pam/product-reference/account-policies/create-policy-sheet.png differdiff --git a/docs/images/pam/product-reference/account-policies/policy-rules.png b/docs/images/pam/product-reference/account-policies/policy-rules.pngnew file mode 100644index 0000000000..919e9c9fb3Binary files /dev/null and b/docs/images/pam/product-reference/account-policies/policy-rules.png differdiff --git a/docs/images/pam/product-reference/account-policies/session-log-masking.png b/docs/images/pam/product-reference/account-policies/session-log-masking.pngnew file mode 100644index 0000000000..1a3e2a7dcfBinary files /dev/null and b/docs/images/pam/product-reference/account-policies/session-log-masking.png differdiff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.tsindex d1125848a7..f7109018e3 100644--- a/frontend/src/context/ProjectPermissionContext/types.ts+++ b/frontend/src/context/ProjectPermissionContext/types.ts@@ -266,6 +266,13 @@ export enum ProjectPermissionPamSessionActions {Terminate = "terminate"}+export enum ProjectPermissionPamAccountPolicyActions {+ Read = "read",+ Create = "create",+ Edit = "edit",+ Delete = "delete"+}+export enum ProjectPermissionPamDiscoveryActions {Read = "read",Create = "create",@@ -428,6 +435,7 @@ export enum ProjectPermissionSub {PamResources = "pam-resources",PamAccounts = "pam-accounts",PamSessions = "pam-sessions",+ PamAccountPolicies = "pam-account-policies",PamDiscovery = "pam-discovery",McpEndpoints = "mcp-endpoints",McpServers = "mcp-servers",@@ -714,6 +722,7 @@ export type ProjectPermissionSet =)]| [ProjectPermissionPamSessionActions, ProjectPermissionSub.PamSessions]+ | [ProjectPermissionPamAccountPolicyActions, ProjectPermissionSub.PamAccountPolicies]| [ProjectPermissionPamDiscoveryActions, ProjectPermissionSub.PamDiscovery]| [ProjectPermissionApprovalRequestActions, ProjectPermissionSub.ApprovalRequests]| [ProjectPermissionApprovalRequestGrantActions, ProjectPermissionSub.ApprovalRequestGrants]diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex 997693067f..ca3efb411d 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -279,6 +279,11 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.PAM_ACCOUNT_CREATE]: "Create PAM Account",[EventType.PAM_ACCOUNT_UPDATE]: "Update PAM Account",[EventType.PAM_ACCOUNT_DELETE]: "Delete PAM Account",+ [EventType.PAM_ACCOUNT_POLICY_CREATE]: "Create PAM Account Policy",+ [EventType.PAM_ACCOUNT_POLICY_UPDATE]: "Update PAM Account Policy",+ [EventType.PAM_ACCOUNT_POLICY_DELETE]: "Delete PAM Account Policy",+ [EventType.PAM_ACCOUNT_POLICY_LIST]: "List PAM Account Policies",+ [EventType.PAM_ACCOUNT_POLICY_GET]: "Get PAM Account Policy",[EventType.PAM_ACCOUNT_READ_CREDENTIALS]: "Read PAM Account Credentials",[EventType.PAM_WEB_ACCESS_SESSION_TICKET_CREATED]: "Create PAM Web Access Session Ticket",[EventType.PAM_RESOURCE_LIST]: "List PAM Resources",@@ -422,6 +427,11 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {EventType.PAM_ACCOUNT_CREATE,EventType.PAM_ACCOUNT_UPDATE,EventType.PAM_ACCOUNT_DELETE,+ EventType.PAM_ACCOUNT_POLICY_CREATE,+ EventType.PAM_ACCOUNT_POLICY_UPDATE,+ EventType.PAM_ACCOUNT_POLICY_DELETE,+ EventType.PAM_ACCOUNT_POLICY_LIST,+ EventType.PAM_ACCOUNT_POLICY_GET,EventType.PAM_ACCOUNT_READ_CREDENTIALS,EventType.PAM_WEB_ACCESS_SESSION_TICKET_CREATED,EventType.PAM_RESOURCE_LIST,diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex 5956e5516d..5c12c354ef 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -274,6 +274,11 @@ export enum EventType {PAM_ACCOUNT_CREATE = "pam-account-create",PAM_ACCOUNT_UPDATE = "pam-account-update",PAM_ACCOUNT_DELETE = "pam-account-delete",+ PAM_ACCOUNT_POLICY_CREATE = "pam-account-policy-create",+ PAM_ACCOUNT_POLICY_UPDATE = "pam-account-policy-update",+ PAM_ACCOUNT_POLICY_DELETE = "pam-account-policy-delete",+ PAM_ACCOUNT_POLICY_LIST = "pam-account-policy-list",+ PAM_ACCOUNT_POLICY_GET = "pam-account-policy-get",PAM_ACCOUNT_READ_CREDENTIALS = "pam-account-read-credentials",PAM_WEB_ACCESS_SESSION_TICKET_CREATED = "pam-web-access-session-ticket-created",PAM_RESOURCE_LIST = "pam-resource-list",diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsxindex 31fb9f424a..af356dfd56 100644--- a/frontend/src/hooks/api/pam/mutations.tsx+++ b/frontend/src/hooks/api/pam/mutations.tsx@@ -5,20 +5,24 @@ import { apiRequest } from "@app/config/request";import { pamKeys } from "./queries";import {TCreatePamAccountDTO,+ TCreatePamAccountPolicyDTO,TCreatePamFolderDTO,TCreatePamResourceDTO,TCreatePamRotationRuleDTO,TDeletePamAccountDTO,+ TDeletePamAccountPolicyDTO,TDeletePamFolderDTO,TDeletePamResourceDTO,TDeletePamRotationRuleDTO,TPamAccount,+ TPamAccountPolicy,TPamFolder,TPamResource,TPamRotationRule,TPamSession,TReorderPamRotationRulesDTO,TUpdatePamAccountDTO,+ TUpdatePamAccountPolicyDTO,TUpdatePamFolderDTO,TUpdatePamResourceDTO,TUpdatePamRotationRuleDTO@@ -425,3 +429,54 @@ export const useTerminatePamSession = () => {}});};++// Account Policies+export const useCreatePamAccountPolicy = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async (params: TCreatePamAccountPolicyDTO) => {+ const { data } = await apiRequest.post<{ policy: TPamAccountPolicy }>(+ "/api/v1/pam/account-policies",+ params+ );++ return data.policy;+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: pamKeys.accountPolicy() });+ }+ });+};++export const useUpdatePamAccountPolicy = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ policyId, ...params }: TUpdatePamAccountPolicyDTO) => {+ const { data } = await apiRequest.patch<{ policy: TPamAccountPolicy }>(+ `/api/v1/pam/account-policies/${policyId}`,+ params+ );++ return data.policy;+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: pamKeys.accountPolicy() });+ }+ });+};++export const useDeletePamAccountPolicy = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ policyId }: TDeletePamAccountPolicyDTO) => {+ const { data } = await apiRequest.delete<{ policy: TPamAccountPolicy }>(+ `/api/v1/pam/account-policies/${policyId}`+ );++ return data.policy;+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: pamKeys.accountPolicy() });+ }+ });+};diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsxindex 8d7e82dd94..7d8e8ba54d 100644--- a/frontend/src/hooks/api/pam/queries.tsx+++ b/frontend/src/hooks/api/pam/queries.tsx@@ -10,6 +10,7 @@ import {TListPamResourcesDTO,TPamAccount,TPamAccountDependency,+ TPamAccountPolicy,TPamResource,TPamResourceDependency,TPamRotationRule,@@ -21,6 +22,7 @@ export const pamKeys = {all: ["pam"] as const,resource: () => [...pamKeys.all, "resource"] as const,account: () => [...pamKeys.all, "account"] as const,+ accountPolicy: () => [...pamKeys.all, "account-policy"] as const,session: () => [...pamKeys.all, "session"] as const,listResourceOptions: () => [...pamKeys.resource(), "options"] as const,listResources: ({ projectId, ...params }: TListPamResourcesDTO) => [@@ -52,6 +54,13 @@ 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],+ listAccountPolicies: (projectId: string, search?: string) => [+ ...pamKeys.accountPolicy(),+ "list",+ projectId,+ { search }+ ],+ getAccountPolicy: (policyId: string) => [...pamKeys.accountPolicy(), "get", policyId],getSession: (sessionId: string) => [...pamKeys.session(), "get", sessionId],getSessionLogs: (sessionId: string) => [...pamKeys.session(), "logs", sessionId],listSessions: (projectId: string) => [...pamKeys.session(), "list", projectId],@@ -450,3 +459,31 @@ export const useListPamSessions = (...options});};++// Account Policies+export const useListPamAccountPolicies = (+ projectId: string,+ search?: string,+ options?: Omit<+ UseQueryOptions<+ TPamAccountPolicy[],+ unknown,+ TPamAccountPolicy[],+ ReturnType<typeof pamKeys.listAccountPolicies>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: pamKeys.listAccountPolicies(projectId, search),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ policies: TPamAccountPolicy[] }>(+ "/api/v1/pam/account-policies",+ { params: { projectId, search } }+ );++ return data.policies;+ },+ ...options+ });+};diff --git a/frontend/src/hooks/api/pam/types/base-account.ts b/frontend/src/hooks/api/pam/types/base-account.tsindex eb8178e05c..03bb08c550 100644--- a/frontend/src/hooks/api/pam/types/base-account.ts+++ b/frontend/src/hooks/api/pam/types/base-account.ts@@ -19,6 +19,8 @@ export interface TBasePamAccount {lastRotationMessage?: string | null;rotationStatus?: string | null;dependencyCount?: number;+ policyId?: string | null;+ policyName?: string | null;metadata?: { key: string; value: string }[];createdAt: string;updatedAt: string;diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex 70968d91fc..8e91a0b11b 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -191,6 +191,7 @@ export type TCreatePamAccountDTO = Pick<resourceType: PamResourceType;internalMetadata?: Record<string, unknown>;metadata?: { key: string; value: string }[];+ policyId?: string | null;};export type TUpdatePamAccountDTO = Partial<@@ -200,6 +201,7 @@ export type TUpdatePamAccountDTO = Partial<resourceType: PamResourceType;internalMetadata?: Record<string, unknown>;metadata?: { key: string; value: string }[];+ policyId?: string | null;};export type TDeletePamAccountDTO = {@@ -288,3 +290,47 @@ export type TPamSessionLogsPage = {hasMore: boolean;batchCount: number;};++// Account Policy types+export enum PamAccountPolicyRuleType {+ CommandBlocking = "command-blocking",+ SessionLogMasking = "session-log-masking"+}++export type TPamAccountPolicyRuleConfig = {+ patterns: string[];+};++export type TPamAccountPolicyRules = Partial<+ Record<PamAccountPolicyRuleType, TPamAccountPolicyRuleConfig>+>;++export type TPamAccountPolicy = {+ id: string;+ projectId: string;+ name: string;+ description?: string | null;+ rules: TPamAccountPolicyRules;+ isActive: boolean;+ createdAt: string;+ updatedAt: string;+};++export type TCreatePamAccountPolicyDTO = {+ projectId: string;+ name: string;+ description?: string;+ rules: TPamAccountPolicyRules;+};++export type TUpdatePamAccountPolicyDTO = {+ policyId: string;+ name?: string;+ description?: string | null;+ rules?: TPamAccountPolicyRules;+ isActive?: boolean;+};++export type TDeletePamAccountPolicyDTO = {+ policyId: string;+};diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsxindex e3d07304dc..0b1eebbfbb 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx@@ -1,4 +1,13 @@-import { BookCheck, Database, FileText, Search, Settings, Shield, Video } from "lucide-react";+import {+ BookCheck,+ Database,+ FileText,+ ScrollText,+ Search,+ Settings,+ Shield,+ Video+} from "lucide-react";import { ProjectNavList } from "./ProjectNavLink";import { PAM_APPROVALS_SUBMENU, PROJECT_ACCESS_CONTROL_SUBMENU } from "./submenus";@@ -9,6 +18,7 @@ export const PamNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submenu) =>{ label: "Resources", icon: Database, pathSuffix: "resources" },{ label: "Sessions", icon: Video, pathSuffix: "sessions" },{ label: "Discovery", icon: Search, pathSuffix: "discovery", activeMatch: /\/discovery\// },+ { label: "Account Policies", icon: ScrollText, pathSuffix: "account-policies" },{label: "Approvals",icon: BookCheck,diff --git a/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDetailsSection.tsx b/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDetailsSection.tsxindex 5bf3154130..475d3ed995 100644--- a/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDetailsSection.tsx+++ b/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountDetailsSection.tsx@@ -100,6 +100,10 @@ export const PamAccountDetailsSection = ({ account, onEdit }: Props) => {<DetailLabel>Parent Resource</DetailLabel><DetailValue>{account.resource.name}</DetailValue></Detail>+ <Detail>+ <DetailLabel>Account Policy</DetailLabel>+ <DetailValue>{account.policyName ?? "None"}</DetailValue>+ </Detail><Detail><DetailLabel>Created</DetailLabel><DetailValue>{format(new Date(account.createdAt), "MM/dd/yyyy, hh:mm a")}</DetailValue>diff --git a/frontend/src/pages/pam/PamAccountPoliciesPage/PamAccountPoliciesPage.tsx b/frontend/src/pages/pam/PamAccountPoliciesPage/PamAccountPoliciesPage.tsxnew file mode 100644index 0000000000..1f4a9b9aac--- /dev/null+++ b/frontend/src/pages/pam/PamAccountPoliciesPage/PamAccountPoliciesPage.tsx@@ -0,0 +1,33 @@+import { Helmet } from "react-helmet";+import { useTranslation } from "react-i18next";++import { PageHeader } from "@app/components/v2/PageHeader";+import { useProject } from "@app/context";+import { ProjectType } from "@app/hooks/api/projects/types";++import { PamAccountPoliciesSection } from "./components/PamAccountPoliciesSection";++export const PamAccountPoliciesPage = () => {+ const { t } = useTranslation();+ const { currentProject } = useProject();++ return (+ <>+ <Helmet>+ <title>{t("common.head-title", { title: "Account Policies" })}</title>+ </Helmet>+ <div className="h-full bg-bunker-800">+ <div className="mx-auto flex flex-col justify-between bg-bunker-800 text-white">+ <div className="mx-auto mb-6 w-full max-w-8xl">+ <PageHeader+ scope={ProjectType.PAM}+ title="Account Policies"+ description="Manage behavioral rules for accounts."+ />+ <PamAccountPoliciesSection projectId={currentProject.id} />+ </div>+ </div>+ </div>+ </>+ );+};diff --git a/frontend/src/pages/pam/PamAccountPoliciesPage/components/PamAccountPoliciesSection.tsx b/frontend/src/pages/pam/PamAccountPoliciesPage/components/PamAccountPoliciesSection.tsxnew file mode 100644index 0000000000..213a7a84a1--- /dev/null+++ b/frontend/src/pages/pam/PamAccountPoliciesPage/components/PamAccountPoliciesSection.tsx@@ -0,0 +1,228 @@+import { faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons";+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { format } from "date-fns";+import { EllipsisVerticalIcon, InfoIcon, PencilIcon, PlusIcon, TrashIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import { ProjectPermissionCan } from "@app/components/permissions";+import { DeleteActionModal, Input } from "@app/components/v2";+import {+ Badge,+ Button,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ UnstableDropdownMenu,+ UnstableDropdownMenuContent,+ UnstableDropdownMenuItem,+ UnstableDropdownMenuTrigger,+ UnstableEmpty,+ UnstableEmptyHeader,+ UnstableEmptyTitle,+ UnstableIconButton,+ UnstableTable,+ UnstableTableBody,+ UnstableTableCell,+ UnstableTableHead,+ UnstableTableHeader,+ UnstableTableRow+} from "@app/components/v3";+import { ProjectPermissionSub } from "@app/context";+import { ProjectPermissionPamAccountPolicyActions } from "@app/context/ProjectPermissionContext/types";+import { usePagination, usePopUp } from "@app/hooks";+import {+ TPamAccountPolicy,+ useDeletePamAccountPolicy,+ useListPamAccountPolicies+} from "@app/hooks/api/pam";++import { PolicySheet } from "./PolicySheet";++type Props = {+ projectId: string;+};++export const PamAccountPoliciesSection = ({ projectId }: Props) => {+ const { search, debouncedSearch, setSearch } = usePagination("", { initPerPage: 20 });++ const { data: policies, isPending } = useListPamAccountPolicies(projectId, debouncedSearch);+ const deletePolicy = useDeletePamAccountPolicy();++ const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([+ "createPolicy",+ "editPolicy",+ "deletePolicy"+ ] as const);++ const handleDelete = async () => {+ const policy = popUp.deletePolicy.data as TPamAccountPolicy | undefined;+ if (!policy) return;++ try {+ await deletePolicy.mutateAsync({ policyId: policy.id });+ createNotification({+ text: "Policy deleted successfully",+ type: "success"+ });+ handlePopUpClose("deletePolicy");+ } catch {+ createNotification({+ text: "Failed to delete policy",+ type: "error"+ });+ }+ };++ return (+ <div>+ <div className="flex gap-2">+ <Input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}+ placeholder="Search account policies..."+ className="h-full flex-1"+ containerClassName="h-9"+ />+ <ProjectPermissionCan+ I={ProjectPermissionPamAccountPolicyActions.Create}+ a={ProjectPermissionSub.PamAccountPolicies}+ >+ {(isAllowed) => (+ <Button+ variant="project"+ onClick={() => handlePopUpOpen("createPolicy")}+ isDisabled={!isAllowed}+ >+ <PlusIcon />+ Create Policy+ </Button>+ )}+ </ProjectPermissionCan>+ </div>++ <div className="mt-4">+ <UnstableTable>+ <UnstableTableHeader>+ <UnstableTableRow>+ <UnstableTableHead>Name</UnstableTableHead>+ <UnstableTableHead>Status</UnstableTableHead>+ <UnstableTableHead>Created</UnstableTableHead>+ <UnstableTableHead className="w-5" />+ </UnstableTableRow>+ </UnstableTableHeader>+ <UnstableTableBody>+ {isPending && (+ <UnstableTableRow>+ <UnstableTableCell colSpan={4} className="text-center text-muted">+ Loading account policies...+ </UnstableTableCell>+ </UnstableTableRow>+ )}+ {!isPending && (!policies || policies.length === 0) && (+ <UnstableTableRow>+ <UnstableTableCell colSpan={4}>+ <UnstableEmpty className="border-0 bg-transparent py-8 shadow-none">+ <UnstableEmptyHeader>+ <UnstableEmptyTitle>+ {search ? "No account policies match search" : "No account policies"}+ </UnstableEmptyTitle>+ </UnstableEmptyHeader>+ </UnstableEmpty>+ </UnstableTableCell>+ </UnstableTableRow>+ )}+ {!isPending &&+ policies?.map((policy) => (+ <UnstableTableRow key={policy.id}>+ <UnstableTableCell>+ <div className="flex items-center">+ <span className="font-medium">{policy.name}</span>+ {policy.description && (+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon className="ml-1.5 size-3.5 text-muted" />+ </TooltipTrigger>+ <TooltipContent>{policy.description}</TooltipContent>+ </Tooltip>+ )}+ </div>+ </UnstableTableCell>+ <UnstableTableCell>+ <Badge variant={policy.isActive ? "success" : "neutral"}>+ {policy.isActive ? "Enabled" : "Disabled"}+ </Badge>+ </UnstableTableCell>+ <UnstableTableCell className="text-muted">+ {format(new Date(policy.createdAt), "MMM d, yyyy")}+ </UnstableTableCell>+ <UnstableTableCell>+ <UnstableDropdownMenu>+ <UnstableDropdownMenuTrigger asChild>+ <UnstableIconButton variant="ghost" size="xs">+ <EllipsisVerticalIcon />+ </UnstableIconButton>+ </UnstableDropdownMenuTrigger>+ <UnstableDropdownMenuContent sideOffset={2} align="end">+ <ProjectPermissionCan+ I={ProjectPermissionPamAccountPolicyActions.Edit}+ a={ProjectPermissionSub.PamAccountPolicies}+ >+ {(isAllowed) => (+ <UnstableDropdownMenuItem+ isDisabled={!isAllowed}+ onSelect={() => handlePopUpOpen("editPolicy", policy)}+ >+ <PencilIcon className="mr-2 size-4" />+ Edit+ </UnstableDropdownMenuItem>+ )}+ </ProjectPermissionCan>+ <ProjectPermissionCan+ I={ProjectPermissionPamAccountPolicyActions.Delete}+ a={ProjectPermissionSub.PamAccountPolicies}+ >+ {(isAllowed) => (+ <UnstableDropdownMenuItem+ isDisabled={!isAllowed}+ variant="danger"+ onSelect={() => handlePopUpOpen("deletePolicy", policy)}+ >+ <TrashIcon className="mr-2 size-4" />+ Delete+ </UnstableDropdownMenuItem>+ )}+ </ProjectPermissionCan>+ </UnstableDropdownMenuContent>+ </UnstableDropdownMenu>+ </UnstableTableCell>+ </UnstableTableRow>+ ))}+ </UnstableTableBody>+ </UnstableTable>+ </div>++ <PolicySheet+ isOpen={popUp.createPolicy.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("createPolicy", isOpen)}+ projectId={projectId}+ />++ <PolicySheet+ isOpen={popUp.editPolicy.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("editPolicy", isOpen)}+ projectId={projectId}+ policy={popUp.editPolicy.data as TPamAccountPolicy | undefined}+ />++ <DeleteActionModal+ isOpen={popUp.deletePolicy.isOpen}+ title={`Delete policy "${(popUp.deletePolicy.data as TPamAccountPolicy | undefined)?.name}"?`}+ subTitle="This will permanently remove this policy. Accounts using it will have their policy detached."+ onChange={(isOpen) => handlePopUpToggle("deletePolicy", isOpen)}+ deleteKey="confirm"+ onDeleteApproved={handleDelete}+ />+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamAccountPoliciesPage/components/PolicySheet.tsx b/frontend/src/pages/pam/PamAccountPoliciesPage/components/PolicySheet.tsxnew file mode 100644index 0000000000..95d2c5a6e0--- /dev/null+++ b/frontend/src/pages/pam/PamAccountPoliciesPage/components/PolicySheet.tsx@@ -0,0 +1,476 @@+import { useEffect, useState } from "react";+import { Control, Controller, FieldErrors, useFieldArray, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { CircleMinus, Plus, Trash2 } from "lucide-react";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import {+ Badge,+ Button,+ Command,+ CommandGroup,+ CommandItem,+ CommandList,+ Field,+ FieldContent,+ FieldError,+ FieldLabel,+ Label,+ Popover,+ PopoverContent,+ PopoverTrigger,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ Switch,+ TextArea,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ UnstableIconButton,+ UnstableInput+} from "@app/components/v3";+import {+ PamAccountPolicyRuleType,+ TPamAccountPolicy,+ TPamAccountPolicyRules,+ useCreatePamAccountPolicy,+ useUpdatePamAccountPolicy+} from "@app/hooks/api/pam";+import { PAM_RESOURCE_TYPE_MAP } from "@app/hooks/api/pam/maps";++import {+ PAM_ACCOUNT_POLICY_RULE_METADATA,+ PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES+} from "./constants";++const isValidRegex = (pattern: string) => {+ try {+ // eslint-disable-next-line no-new+ new RegExp(pattern);+ return true;+ } catch {+ return false;+ }+};++const RulePatternSchema = z.object({+ value: z+ .string()+ .min(1, "Pattern is required")+ .max(500, "Pattern must be at most 500 characters")+ .refine(isValidRegex, { message: "Invalid regular expression" })+});++const RuleSchema = z.object({+ ruleType: z.nativeEnum(PamAccountPolicyRuleType),+ patterns: z+ .array(RulePatternSchema)+ .min(1, "At least one pattern is required")+ .max(20, "A rule can have at most 20 patterns")+});++const FormSchema = z.object({+ name: z.string().trim().min(1, "Name is required").max(255),+ description: z.string().trim().max(1000).optional(),+ rules: z.array(RuleSchema).min(1, "At least one rule is required")+});++type TFormData = z.infer<typeof FormSchema>;++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ projectId: string;+ policy?: TPamAccountPolicy;+};++const rulesToFormData = (rules: TPamAccountPolicyRules): TFormData["rules"] => {+ return (Object.entries(rules) as [PamAccountPolicyRuleType, { patterns: string[] }][])+ .filter(([, config]) => config?.patterns)+ .map(([ruleType, config]) => ({+ ruleType,+ patterns: config.patterns.map((p) => ({ value: p }))+ }));+};++const formDataToRules = (rules: TFormData["rules"]): TPamAccountPolicyRules => {+ return rules.reduce<TPamAccountPolicyRules>((acc, rule) => {+ acc[rule.ruleType] = {+ patterns: rule.patterns.map((p) => p.value)+ };+ return acc;+ }, {});+};++const RuleSupportedResourceIndicator = ({ ruleType }: { ruleType: PamAccountPolicyRuleType }) => {+ const supported = PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES[ruleType];++ if (supported === "all") {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="neutral">All</Badge>+ </TooltipTrigger>+ <TooltipContent>Supported by all resource types</TooltipContent>+ </Tooltip>+ );+ }++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="flex items-center gap-1">+ {supported.map((rt) => {+ const mapEntry = PAM_RESOURCE_TYPE_MAP[rt];+ if (!mapEntry) return null;+ return (+ <Badge key={rt} variant="neutral">+ {mapEntry.name}+ </Badge>+ );+ })}+ </div>+ </TooltipTrigger>+ <TooltipContent>+ Supported by{" "}+ {(() => {+ const names = supported.map((rt) => PAM_RESOURCE_TYPE_MAP[rt]?.name).filter(Boolean);+ if (names.length <= 1) return names[0];+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;+ })()}+ </TooltipContent>+ </Tooltip>+ );+};++const RulePatterns = ({+ control,+ ruleIndex,+ errors+}: {+ control: Control<TFormData>;+ ruleIndex: number;+ errors: FieldErrors<TFormData>;+}) => {+ const { fields, append, remove } = useFieldArray({+ control,+ name: `rules.${ruleIndex}.patterns` as const+ });++ return (+ <div className="space-y-1.5">+ {fields.map((patternField, patternIndex) => {+ const patternError = errors?.rules?.[ruleIndex]?.patterns?.[patternIndex]?.value;+ return (+ <div key={patternField.id}>+ <div className="flex items-center gap-1.5">+ <Controller+ control={control}+ name={`rules.${ruleIndex}.patterns.${patternIndex}.value`}+ render={({ field }) => (+ <UnstableInput+ {...field}+ placeholder={"Regex pattern, e.g. rm\\s+-rf"}+ className="flex-1 font-mono text-xs"+ isError={!!patternError}+ />+ )}+ />+ <UnstableIconButton+ variant="ghost"+ size="xs"+ aria-label="Remove pattern"+ onClick={() => remove(patternIndex)}+ disabled={fields.length <= 1}+ >+ <CircleMinus className="h-3.5 w-3.5 text-mineshaft-400" />+ </UnstableIconButton>+ </div>+ {patternError && <p className="mt-1 text-xs text-danger">{patternError.message}</p>}+ </div>+ );+ })}+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <Button+ variant="outline"+ size="xs"+ onClick={() => append({ value: "" })}+ disabled={fields.length >= 20}+ >+ <Plus className="mr-1 h-3 w-3" />+ Add Pattern+ </Button>+ </span>+ </TooltipTrigger>+ {fields.length >= 20 && <TooltipContent>Max of 20 allowed</TooltipContent>}+ </Tooltip>+ </div>+ );+};++export const PolicySheet = ({ isOpen, onOpenChange, projectId, policy }: Props) => {+ const isEditing = !!policy;+ const createPolicy = useCreatePamAccountPolicy();+ const updatePolicy = useUpdatePamAccountPolicy();+ const [addRuleOpen, setAddRuleOpen] = useState(false);+ const [isActive, setIsActive] = useState(true);++ const {+ control,+ handleSubmit,+ reset,+ formState: { isSubmitting, isDirty, errors },+ watch+ } = useForm<TFormData>({+ resolver: zodResolver(FormSchema),+ defaultValues: {+ name: "",+ description: "",+ rules: []+ }+ });++ const {+ fields: ruleFields,+ append: appendRule,+ remove: removeRule+ } = useFieldArray({ control, name: "rules" });++ const currentRules = watch("rules");++ useEffect(() => {+ if (isOpen) {+ if (policy) {+ reset({+ name: policy.name,+ description: policy.description ?? "",+ rules: rulesToFormData(policy.rules)+ });+ setIsActive(policy.isActive);+ } else {+ reset({ name: "", description: "", rules: [] });+ setIsActive(true);+ }+ }+ }, [isOpen, policy, reset]);++ const onSubmit = async (data: TFormData) => {+ try {+ const rules = formDataToRules(data.rules);++ if (isEditing) {+ await updatePolicy.mutateAsync({+ policyId: policy.id,+ name: data.name,+ description: data.description || null,+ rules,+ isActive+ });+ createNotification({ text: "Policy updated successfully", type: "success" });+ } else {+ await createPolicy.mutateAsync({+ projectId,+ name: data.name,+ description: data.description,+ rules+ });+ createNotification({ text: "Policy created successfully", type: "success" });+ }+ onOpenChange(false);+ } catch {+ createNotification({+ text: `Failed to ${isEditing ? "update" : "create"} policy`,+ type: "error"+ });+ }+ };++ const addedRuleTypes = new Set(currentRules.map((r) => r.ruleType));++ return (+ <Sheet open={isOpen} onOpenChange={onOpenChange}>+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 sm:max-w-lg">+ <SheetHeader className="border-b">+ <SheetTitle>{isEditing ? "Edit Policy" : "Create Policy"}</SheetTitle>+ <SheetDescription>+ {isEditing+ ? "Update the policy name, description, and rules."+ : "Configure behavioral rules for accounts."}+ </SheetDescription>+ </SheetHeader>++ {isEditing && (+ <div className="flex items-center justify-between border-b border-border px-6 py-3">+ <span className="text-xs text-muted">{isActive ? "Enabled" : "Disabled"}</span>+ <Switch checked={isActive} onCheckedChange={setIsActive} variant="project" />+ </div>+ )}++ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col overflow-hidden">+ <div+ className={`flex min-h-0 flex-1 shrink flex-col gap-4 overflow-y-auto p-4 pb-8 transition-opacity ${!isActive ? "pointer-events-none opacity-40" : ""}`}+ >+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Name</FieldLabel>+ <FieldContent>+ <UnstableInput+ {...field}+ placeholder="e.g. Production SSH Policy"+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ control={control}+ name="description"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Description (optional)</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ className="max-h-32"+ placeholder="Brief description of this policy"+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />++ <div className="flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <Label>Rules</Label>+ <Popover open={addRuleOpen} onOpenChange={setAddRuleOpen}>+ <PopoverTrigger asChild>+ <Button variant="outline" size="xs">+ <Plus className="mr-1 h-3 w-3" />+ Add Rule+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-72 p-0" align="end">+ <Command>+ <CommandList>+ <CommandGroup>+ {Object.values(PamAccountPolicyRuleType).map((ruleType) => {+ const meta = PAM_ACCOUNT_POLICY_RULE_METADATA[ruleType];+ const isAdded = addedRuleTypes.has(ruleType);+ return (+ <CommandItem+ key={ruleType}+ disabled={isAdded}+ onSelect={() => {+ if (!isAdded) {+ appendRule({ ruleType, patterns: [{ value: "" }] });+ setAddRuleOpen(false);+ }+ }}+ className="flex items-center justify-between gap-2"+ >+ <span className="text-sm">+ {isAdded ? (+ <span className="text-mineshaft-400">{meta.name}</span>+ ) : (+ meta.name+ )}+ </span>+ </CommandItem>+ );+ })}+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ </div>++ {ruleFields.map((ruleField, ruleIndex) => {+ const ruleType = currentRules[ruleIndex]?.ruleType;+ if (!ruleType) return null;+ const meta = PAM_ACCOUNT_POLICY_RULE_METADATA[ruleType];++ return (+ <div key={ruleField.id} className="rounded-md border border-border bg-card p-4">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium text-foreground">{meta.name}</span>+ {ruleType && <RuleSupportedResourceIndicator ruleType={ruleType} />}+ </div>+ <UnstableIconButton+ variant="danger"+ size="xs"+ aria-label="Remove rule"+ onClick={() => removeRule(ruleIndex)}+ >+ <Trash2 className="size-3.5" />+ </UnstableIconButton>+ </div>+ {meta.description && (+ <p className="mt-2 text-xs text-muted">{meta.description}</p>+ )}++ <div className="mt-3">+ <RulePatterns control={control} ruleIndex={ruleIndex} errors={errors} />+ </div>+ </div>+ );+ })}++ {currentRules.length === 0 && (+ <div className="rounded-md border border-dashed border-border py-8 text-center">+ <p className="text-sm text-muted">No rules added yet</p>+ {(errors.rules?.root?.message || errors.rules?.message) && (+ <p className="mt-1 text-xs text-danger">+ {errors.rules?.root?.message || errors.rules?.message}+ </p>+ )}+ </div>+ )}++ {currentRules.length > 0 &&+ (errors.rules?.root?.message || errors.rules?.message) && (+ <p className="mt-1 text-xs text-danger">+ {errors.rules?.root?.message || errors.rules?.message}+ </p>+ )}+ </div>+ </div>++ <SheetFooter className="shrink-0 border-t">+ <Button+ isPending={isSubmitting}+ isDisabled={isSubmitting || (!isDirty && isActive === policy?.isActive)}+ variant="project"+ type="submit"+ >+ {isEditing ? "Save Changes" : "Create Policy"}+ </Button>+ <Button+ onClick={() => onOpenChange(false)}+ variant="outline"+ className="mr-auto"+ type="button"+ >+ Cancel+ </Button>+ </SheetFooter>+ </form>+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/pages/pam/PamAccountPoliciesPage/components/constants.ts b/frontend/src/pages/pam/PamAccountPoliciesPage/components/constants.tsnew file mode 100644index 0000000000..a2aec6560d--- /dev/null+++ b/frontend/src/pages/pam/PamAccountPoliciesPage/components/constants.ts@@ -0,0 +1,24 @@+import { PamResourceType } from "@app/hooks/api/pam/enums";+import { PamAccountPolicyRuleType } from "@app/hooks/api/pam/types";++export const PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES: Record<+ PamAccountPolicyRuleType,+ PamResourceType[] | "all"+> = {+ [PamAccountPolicyRuleType.CommandBlocking]: [PamResourceType.SSH],+ [PamAccountPolicyRuleType.SessionLogMasking]: "all"+};++export const PAM_ACCOUNT_POLICY_RULE_METADATA: Record<+ PamAccountPolicyRuleType,+ { name: string; description: string }+> = {+ [PamAccountPolicyRuleType.CommandBlocking]: {+ name: "Command Blocking",+ description: "Block commands matching specified patterns"+ },+ [PamAccountPolicyRuleType.SessionLogMasking]: {+ name: "Session Log Masking",+ description: "Mask sensitive data in session logs matching specified patterns"+ }+};diff --git a/frontend/src/pages/pam/PamAccountPoliciesPage/route.tsx b/frontend/src/pages/pam/PamAccountPoliciesPage/route.tsxnew file mode 100644index 0000000000..b46a585b99--- /dev/null+++ b/frontend/src/pages/pam/PamAccountPoliciesPage/route.tsx@@ -0,0 +1,19 @@+import { createFileRoute } from "@tanstack/react-router";++import { PamAccountPoliciesPage } from "./PamAccountPoliciesPage";++export const Route = createFileRoute(+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/account-policies"+)({+ beforeLoad: ({ context }) => {+ return {+ breadcrumbs: [+ ...context.breadcrumbs,+ {+ label: "Account Policies"+ }+ ]+ };+ },+ component: PamAccountPoliciesPage+});diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/ActiveDirectoryAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/ActiveDirectoryAccountForm.tsxindex 9d88c426c9..346829eaa7 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/ActiveDirectoryAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/ActiveDirectoryAccountForm.tsx@@ -9,7 +9,11 @@ import { PamResourceType, TActiveDirectoryAccount } from "@app/hooks/api/pam";import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";import { ActiveDirectoryAccountType } from "@app/hooks/api/pam/types/active-directory-resource";-import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";+import {+ AccountPolicyField,+ GenericAccountFields,+ genericAccountFieldsSchema+} from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";import { RequireMfaField } from "./RequireMfaField";@@ -145,6 +149,7 @@ export const ActiveDirectoryAccountForm = ({ account, onSubmit, closeSheet }: Pr/></div><RequireMfaField />+ <AccountPolicyField /><MetadataFields /></div><SheetFooter className="shrink-0 border-t">diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/AwsIamAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/AwsIamAccountForm.tsxindex 18fb05ae40..830a3914d3 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/AwsIamAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/AwsIamAccountForm.tsx@@ -24,7 +24,11 @@ import {useGetPamResourceById} from "@app/hooks/api/pam";-import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";+import {+ AccountPolicyField,+ GenericAccountFields,+ genericAccountFieldsSchema+} from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";const AWS_STS_MIN_SESSION_DURATION = 900; // 15 minutes@@ -267,6 +271,7 @@ export const AwsIamAccountForm = ({</AccordionItem></Accordion>+ <AccountPolicyField /><MetadataFields /></div><SheetFooter className="shrink-0 border-t">diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/GenericAccountFields.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/GenericAccountFields.tsxindex 97b3370549..5ac5c2e956 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/GenericAccountFields.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/GenericAccountFields.tsx@@ -1,4 +1,5 @@import { Controller, useFormContext } from "react-hook-form";+import { InfoIcon } from "lucide-react";import { z } from "zod";import {@@ -6,14 +7,79 @@ import {FieldContent,FieldError,FieldLabel,+ FilterableSelect,TextArea,+ Tooltip,+ TooltipContent,+ TooltipTrigger,UnstableInput} from "@app/components/v3";+import { useProject } from "@app/context";+import { useListPamAccountPolicies } from "@app/hooks/api/pam";import { slugSchema } from "@app/lib/schemas";+export const AccountPolicyField = () => {+ const { control } = useFormContext<{ policyId?: string | null }>();+ const { projectId } = useProject();+ const { data: policies, isPending: isPoliciesLoading } = useListPamAccountPolicies(projectId);++ const policyOptions = [+ { label: "None", value: "" },+ ...(policies?.map((p) => ({ label: p.name, value: p.id })) ?? [])+ ];++ return (+ <Controller+ name="policyId"+ control={control}+ render={({ field: { value, onChange, onBlur }, fieldState: { error } }) => {+ const selectedOption =+ policyOptions.find((o) => o.value === (value ?? "")) ?? policyOptions[0];++ return (+ <Field>+ <FieldLabel>+ <div className="flex items-center gap-1">+ Account Policy+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon className="size-3.5 text-muted" />+ </TooltipTrigger>+ <TooltipContent className="max-w-xs text-wrap">+ Account policies define behavioral rules that are enforced when this account is+ accessed.+ </TooltipContent>+ </Tooltip>+ </div>+ </FieldLabel>+ <FieldContent>+ <FilterableSelect+ value={selectedOption}+ onChange={(opt) => {+ const selected = opt as { value: string } | null;+ onChange(selected?.value || null);+ }}+ onBlur={onBlur}+ options={policyOptions}+ isError={Boolean(error)}+ isLoading={isPoliciesLoading}+ placeholder="Select a policy..."+ getOptionLabel={(option) => option.label}+ getOptionValue={(option) => option.value}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ );+ }}+ />+ );+};+export const genericAccountFieldsSchema = z.object({name: slugSchema({ min: 1, max: 64, field: "Name" }),description: z.string().max(512).nullable().optional(),+ policyId: z.string().uuid().nullable().optional(),metadata: z.object({key: z.string().trim().min(1),diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsxindex 88cbc6da1e..6fee3f0890 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsx@@ -7,7 +7,11 @@ import { Button, SheetFooter } from "@app/components/v3";import { KubernetesAuthMethod, PamResourceType, TKubernetesAccount } from "@app/hooks/api/pam";import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";-import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";+import {+ AccountPolicyField,+ GenericAccountFields,+ genericAccountFieldsSchema+} from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";type Props = {@@ -101,6 +105,7 @@ export const KubernetesAccountForm = ({ account, onSubmit, closeSheet }: Props)<div className="flex min-h-0 flex-1 shrink flex-col gap-4 overflow-y-auto p-4 pb-8"><GenericAccountFields /><KubernetesAccountFields isUpdate={isUpdate} />+ <AccountPolicyField /><MetadataFields /></div><SheetFooter className="shrink-0 border-t">diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MongoDBAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MongoDBAccountForm.tsxindex b364848569..fec4b4815e 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MongoDBAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MongoDBAccountForm.tsx@@ -8,7 +8,11 @@ import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";import { BaseSqlAccountSchema } from "./shared/sql-account-schemas";import { SqlAccountFields } from "./shared/SqlAccountFields";-import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";+import {+ AccountPolicyField,+ GenericAccountFields,+ genericAccountFieldsSchema+} from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";import { RequireMfaField } from "./RequireMfaField";@@ -55,6 +59,7 @@ export const MongoDBAccountForm = ({ account, onSubmit, closeSheet }: Props) =><GenericAccountFields /><SqlAccountFields isUpdate={isUpdate} /><RequireMfaField />+ <AccountPolicyField /><MetadataFields /></div><SheetFooter className="shrink-0 border-t">diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MsSQLAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MsSQLAccountForm.tsxindex 08aea134e9..00b6a972c4 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MsSQLAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MsSQLAccountForm.tsx@@ -8,7 +8,11 @@ import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";import { BaseSqlAccountSchema } from "./shared/sql-account-schemas";import { SqlAccountFields } from "./shared/SqlAccountFields";-import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";+import {+ AccountPolicyField,+ GenericAccountFields,+ genericAccountFieldsSchema+} from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";import { RequireMfaField } from "./RequireMfaField";@@ -55,6 +59,7 @@ export const MsSQLAccountForm = ({ account, onSubmit, closeSheet }: Props) => {<GenericAccountFields /><SqlAccountFields isUpdate={isUpdate} /><RequireMfaField />+ <AccountPolicyField /><MetadataFields /></div><SheetFooter className="shrink-0 border-t">diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MySQLAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MySQLAccountForm.tsxindex 8030e2d4eb..6956d0083f 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MySQLAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/MySQLAccountForm.tsx@@ -8,7 +8,11 @@ import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";import { BaseSqlAccountSchema } from "./shared/sql-account-schemas";import { SqlAccountFields } from "./shared/SqlAccountFields";-import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";+import {+ AccountPolicyField,+ GenericAccountFields,+ genericAccountFieldsSchema+} from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";import { RequireMfaField } from "./RequireMfaField";@@ -55,6 +59,7 @@ export const MySQLAccountForm = ({ account, onSubmit, closeSheet }: Props) => {<GenericAccountFields /><SqlAccountFields isUpdate={isUpdate} /><RequireMfaField />+ <AccountPolicyField /><MetadataFields /></div><SheetFooter className="shrink-0 border-t">diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsxindex e440e6afd6..f84020db20 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx@@ -49,16 +49,18 @@ const CreateForm = ({> & {internalMetadata?: Record<string, unknown>;metadata?: { key: string; value: string }[];+ policyId?: string | null;}) => {- const { internalMetadata, ...rest } = formData;+ const { internalMetadata, policyId, ...rest } = formData;const account = await createPamAccount.mutateAsync({...rest,folderId,resourceId,resourceType,projectId,- internalMetadata+ internalMetadata,+ policyId});createNotification({text: "Successfully created account",@@ -173,14 +175,16 @@ const UpdateForm = ({ account, closeSheet }: UpdateFormProps) => {> & {internalMetadata?: Record<string, unknown>;metadata?: { key: string; value: string }[];+ policyId?: string | null;}) => {- const { internalMetadata, ...rest } = formData;+ const { internalMetadata, policyId, ...rest } = formData;const updatedAccount = await updatePamAccount.mutateAsync({accountId: account.id,resourceType: account.resource.resourceType,...rest,- internalMetadata+ internalMetadata,+ policyId});createNotification({text: "Successfully updated account",diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsxindex e7a8133c45..fc3c669c88 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsx@@ -8,7 +8,11 @@ import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";import { BaseSqlAccountSchema } from "./shared/sql-account-schemas";import { SqlAccountFields } from "./shared/SqlAccountFields";-import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";+import {+ AccountPolicyField,+ GenericAccountFields,+ genericAccountFieldsSchema+} from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";import { RequireMfaField } from "./RequireMfaField";@@ -55,6 +59,7 @@ export const PostgresAccountForm = ({ account, onSubmit, closeSheet }: Props) =><GenericAccountFields /><SqlAccountFields isUpdate={isUpdate} /><RequireMfaField />+ <AccountPolicyField /><MetadataFields /></div><SheetFooter className="shrink-0 border-t">diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/RedisAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/RedisAccountForm.tsxindex aec2e68d29..cf54fdb5fd 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/RedisAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/RedisAccountForm.tsx@@ -8,7 +8,11 @@ import { Button, SheetFooter } from "@app/components/v3";import { PamResourceType, TRedisAccount } from "@app/hooks/api/pam";import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";-import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";+import {+ AccountPolicyField,+ GenericAccountFields,+ genericAccountFieldsSchema+} from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";const formSchema = genericAccountFieldsSchema@@ -208,6 +212,7 @@ export const RedisAccountForm = ({ account, onSubmit, closeSheet }: Props) => {/></div>)}+ <AccountPolicyField /><MetadataFields /></div><SheetFooter className="shrink-0 border-t">diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SshAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SshAccountForm.tsxindex 5c1ca707d9..745fda9627 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SshAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SshAccountForm.tsx@@ -10,7 +10,11 @@ import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";import { SSHAuthMethod } from "@app/hooks/api/pam/types/ssh-resource";import { SshCaSetupSection } from "../../../components/SshCaSetupSection";-import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";+import {+ AccountPolicyField,+ GenericAccountFields,+ genericAccountFieldsSchema+} from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";import { RequireMfaField } from "./RequireMfaField";@@ -245,6 +249,7 @@ export const SshAccountForm = ({ account, resourceId, onSubmit, closeSheet }: Pr<GenericAccountFields /><SshAccountFields isUpdate={isUpdate} resourceId={effectiveResourceId} /><RequireMfaField />+ <AccountPolicyField /><MetadataFields /></div><SheetFooter className="shrink-0 border-t">diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/WindowsAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/WindowsAccountForm.tsxindex d223bbe9eb..d88bebbb68 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/WindowsAccountForm.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/WindowsAccountForm.tsx@@ -9,7 +9,11 @@ import { PamResourceType, TWindowsAccount } from "@app/hooks/api/pam";import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";import { WindowsAccountType } from "@app/hooks/api/pam/types/windows-server-resource";-import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";+import {+ AccountPolicyField,+ GenericAccountFields,+ genericAccountFieldsSchema+} from "./GenericAccountFields";import { MetadataFields } from "./MetadataFields";import { RequireMfaField } from "./RequireMfaField";@@ -143,6 +147,7 @@ export const WindowsAccountForm = ({ account, onSubmit, closeSheet }: Props) =>/></div><RequireMfaField />+ <AccountPolicyField /><MetadataFields /></div><SheetFooter className="shrink-0 border-t">diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsxindex 17ee851c8a..6cb08599cd 100644--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx@@ -25,6 +25,7 @@ import {ProjectPermissionMcpEndpointActions,ProjectPermissionMemberActions,ProjectPermissionPamAccountActions,+ ProjectPermissionPamAccountPolicyActions,ProjectPermissionPamDiscoveryActions,ProjectPermissionPamSessionActions,ProjectPermissionPkiCertificateInstallationActions,@@ -245,6 +246,13 @@ const PamSessionPolicyActionSchema = z.object({[ProjectPermissionPamSessionActions.Terminate]: z.boolean().optional()});+const PamAccountPolicyPolicyActionSchema = z.object({+ [ProjectPermissionPamAccountPolicyActions.Read]: z.boolean().optional(),+ [ProjectPermissionPamAccountPolicyActions.Create]: z.boolean().optional(),+ [ProjectPermissionPamAccountPolicyActions.Edit]: z.boolean().optional(),+ [ProjectPermissionPamAccountPolicyActions.Delete]: z.boolean().optional()+});+const PamDiscoveryPolicyActionSchema = z.object({[ProjectPermissionPamDiscoveryActions.RunScan]: z.boolean().optional(),[ProjectPermissionPamDiscoveryActions.Create]: z.boolean().optional(),@@ -798,6 +806,9 @@ export const projectRoleFormSchema = z.object({.array().default([]),[ProjectPermissionSub.PamSessions]: PamSessionPolicyActionSchema.array().default([]),+ [ProjectPermissionSub.PamAccountPolicies]: PamAccountPolicyPolicyActionSchema.array().default(+ []+ ),[ProjectPermissionSub.PamDiscovery]: PamDiscoveryPolicyActionSchema.array().default([]),[ProjectPermissionSub.McpEndpoints]: McpEndpointPolicyActionSchema.extend({inverted: z.boolean().optional(),@@ -1804,6 +1815,20 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {if (canTerminate) formVal[subject]![0][ProjectPermissionPamSessionActions.Terminate] = true;}+ if (subject === ProjectPermissionSub.PamAccountPolicies) {+ const canRead = action.includes(ProjectPermissionPamAccountPolicyActions.Read);+ const canCreate = action.includes(ProjectPermissionPamAccountPolicyActions.Create);+ const canDelete = action.includes(ProjectPermissionPamAccountPolicyActions.Delete);+ const canEdit = action.includes(ProjectPermissionPamAccountPolicyActions.Edit);++ if (!formVal[subject]) formVal[subject] = [{}];++ if (canRead) formVal[subject]![0][ProjectPermissionPamAccountPolicyActions.Read] = true;+ if (canCreate) formVal[subject]![0][ProjectPermissionPamAccountPolicyActions.Create] = true;+ if (canDelete) formVal[subject]![0][ProjectPermissionPamAccountPolicyActions.Delete] = true;+ if (canEdit) formVal[subject]![0][ProjectPermissionPamAccountPolicyActions.Edit] = true;+ }+if (subject === ProjectPermissionSub.PamDiscovery) {const canRead = action.includes(ProjectPermissionPamDiscoveryActions.Read);const canCreate = action.includes(ProjectPermissionPamDiscoveryActions.Create);@@ -3164,6 +3189,32 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {}]},+ [ProjectPermissionSub.PamAccountPolicies]: {+ title: "Account Policies",+ description: "Manage behavioral rules for PAM accounts",+ actions: [+ {+ label: "Read",+ value: ProjectPermissionPamAccountPolicyActions.Read,+ description: "View PAM account policies"+ },+ {+ label: "Create",+ value: ProjectPermissionPamAccountPolicyActions.Create,+ description: "Create PAM account policies"+ },+ {+ label: "Modify",+ value: ProjectPermissionPamAccountPolicyActions.Edit,+ description: "Update PAM account policies"+ },+ {+ label: "Remove",+ value: ProjectPermissionPamAccountPolicyActions.Delete,+ description: "Delete PAM account policies"+ }+ ]+ },[ProjectPermissionSub.PamDiscovery]: {title: "Discovery",description: "Manage privileged access discovery",@@ -3372,6 +3423,7 @@ const PamPermissionSubjects = (enabled = false) => ({[ProjectPermissionSub.PamResources]: enabled,[ProjectPermissionSub.PamAccounts]: enabled,[ProjectPermissionSub.PamSessions]: enabled,+ [ProjectPermissionSub.PamAccountPolicies]: enabled,[ProjectPermissionSub.PamDiscovery]: enabled});diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.tsindex 978af521b9..ee4c9d2d50 100644--- a/frontend/src/routeTree.gen.ts+++ b/frontend/src/routeTree.gen.ts@@ -115,6 +115,7 @@ import { Route as secretManagerSecretApprovalsPageRouteImport } from './pages/seimport { Route as secretManagerIPAllowlistPageRouteImport } from './pages/secret-manager/IPAllowlistPage/route'import { Route as pamSettingsPageRouteImport } from './pages/pam/SettingsPage/route'import { Route as pamApprovalsPageRouteImport } from './pages/pam/ApprovalsPage/route'+import { Route as pamPamAccountPoliciesPageRouteImport } from './pages/pam/PamAccountPoliciesPage/route'import { Route as kmsSettingsPageRouteImport } from './pages/kms/SettingsPage/route'import { Route as kmsOverviewPageRouteImport } from './pages/kms/OverviewPage/route'import { Route as kmsKmipPageRouteImport } from './pages/kms/KmipPage/route'@@ -1327,6 +1328,13 @@ const pamApprovalsPageRouteRoute = pamApprovalsPageRouteImport.update({getParentRoute: () => pamLayoutRoute,} as any)+const pamPamAccountPoliciesPageRouteRoute =+ pamPamAccountPoliciesPageRouteImport.update({+ id: '/account-policies',+ path: '/account-policies',+ getParentRoute: () => pamLayoutRoute,+ } as any)+const kmsSettingsPageRouteRoute = kmsSettingsPageRouteImport.update({id: '/settings',path: '/settings',@@ -3207,6 +3215,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof kmsSettingsPageRouteImportparentRoute: typeof kmsLayoutImport}+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/account-policies': {+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/account-policies'+ path: '/account-policies'+ fullPath: '/organizations/$orgId/projects/pam/$projectId/account-policies'+ preLoaderRoute: typeof pamPamAccountPoliciesPageRouteImport+ parentRoute: typeof pamLayoutImport+ }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/approvals': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/approvals'path: '/approvals'@@ -4877,6 +4892,7 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectI)interface pamLayoutRouteChildren {+ pamPamAccountPoliciesPageRouteRoute: typeof pamPamAccountPoliciesPageRouteRoutepamApprovalsPageRouteRoute: typeof pamApprovalsPageRouteRoutepamSettingsPageRouteRoute: typeof pamSettingsPageRouteRouteprojectAccessControlPageRoutePamRoute: typeof projectAccessControlPageRoutePamRoute@@ -4892,6 +4908,7 @@ interface pamLayoutRouteChildren {}const pamLayoutRouteChildren: pamLayoutRouteChildren = {+ pamPamAccountPoliciesPageRouteRoute: pamPamAccountPoliciesPageRouteRoute,pamApprovalsPageRouteRoute: pamApprovalsPageRouteRoute,pamSettingsPageRouteRoute: pamSettingsPageRouteRoute,projectAccessControlPageRoutePamRoute: projectAccessControlPageRoutePamRoute,@@ -5836,6 +5853,7 @@ export interface FileRoutesByFullPath {'/organizations/$orgId/projects/kms/$projectId/kmip': typeof kmsKmipPageRouteRoute'/organizations/$orgId/projects/kms/$projectId/overview': typeof kmsOverviewPageRouteRoute'/organizations/$orgId/projects/kms/$projectId/settings': typeof kmsSettingsPageRouteRoute+ '/organizations/$orgId/projects/pam/$projectId/account-policies': typeof pamPamAccountPoliciesPageRouteRoute'/organizations/$orgId/projects/pam/$projectId/approvals': typeof pamApprovalsPageRouteRoute'/organizations/$orgId/projects/pam/$projectId/settings': typeof pamSettingsPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/allowlist': typeof secretManagerIPAllowlistPageRouteRoute@@ -6102,6 +6120,7 @@ export interface FileRoutesByTo {'/organizations/$orgId/projects/kms/$projectId/kmip': typeof kmsKmipPageRouteRoute'/organizations/$orgId/projects/kms/$projectId/overview': typeof kmsOverviewPageRouteRoute'/organizations/$orgId/projects/kms/$projectId/settings': typeof kmsSettingsPageRouteRoute+ '/organizations/$orgId/projects/pam/$projectId/account-policies': typeof pamPamAccountPoliciesPageRouteRoute'/organizations/$orgId/projects/pam/$projectId/approvals': typeof pamApprovalsPageRouteRoute'/organizations/$orgId/projects/pam/$projectId/settings': typeof pamSettingsPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/allowlist': typeof secretManagerIPAllowlistPageRouteRoute@@ -6374,6 +6393,7 @@ export interface FileRoutesById {'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/kmip': typeof kmsKmipPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/overview': typeof kmsOverviewPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/settings': typeof kmsSettingsPageRouteRoute+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/account-policies': typeof pamPamAccountPoliciesPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/approvals': typeof pamApprovalsPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/settings': typeof pamSettingsPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/allowlist': typeof secretManagerIPAllowlistPageRouteRoute@@ -6649,6 +6669,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/projects/kms/$projectId/kmip'| '/organizations/$orgId/projects/kms/$projectId/overview'| '/organizations/$orgId/projects/kms/$projectId/settings'+ | '/organizations/$orgId/projects/pam/$projectId/account-policies'| '/organizations/$orgId/projects/pam/$projectId/approvals'| '/organizations/$orgId/projects/pam/$projectId/settings'| '/organizations/$orgId/projects/secret-management/$projectId/allowlist'@@ -6914,6 +6935,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/projects/kms/$projectId/kmip'| '/organizations/$orgId/projects/kms/$projectId/overview'| '/organizations/$orgId/projects/kms/$projectId/settings'+ | '/organizations/$orgId/projects/pam/$projectId/account-policies'| '/organizations/$orgId/projects/pam/$projectId/approvals'| '/organizations/$orgId/projects/pam/$projectId/settings'| '/organizations/$orgId/projects/secret-management/$projectId/allowlist'@@ -7184,6 +7206,7 @@ export interface FileRouteTypes {| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/kmip'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/overview'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/settings'+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/account-policies'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/approvals'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/settings'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/allowlist'@@ -7927,6 +7950,7 @@ export const routeTree = rootRoute"filePath": "pam/layout.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId","children": [+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/account-policies","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/approvals","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/settings","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/access-management",@@ -8036,6 +8060,10 @@ export const routeTree = rootRoute"filePath": "kms/SettingsPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout"},+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/account-policies": {+ "filePath": "pam/PamAccountPoliciesPage/route.tsx",+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout"+ },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/approvals": {"filePath": "pam/ApprovalsPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout"diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex 6df5ac1101..a9bbbbd2c7 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -397,6 +397,7 @@ const pamRoutes = route("/organizations/$orgId/projects/pam/$projectId", []),route("/audit-logs", "project/AuditLogsPage/route-pam.tsx"),route("/settings", "pam/SettingsPage/route.tsx"),+ route("/account-policies", "pam/PamAccountPoliciesPage/route.tsx"),route("/approvals", "pam/ApprovalsPage/route.tsx"),route("/approval-requests/$approvalRequestId", "pam/ApprovalRequestDetailPage/route.tsx"),