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: add pam insights dashboard
bernie-g8cc84de7c01d
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 81a5972858..8ffcc2378f 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -36,6 +36,7 @@ import { TPamAccountPolicyServiceFactory } from "@app/ee/services/pam-account-poimport { TPamDiscoverySourceServiceFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-service";import { TPamDomainServiceFactory } from "@app/ee/services/pam-domain/pam-domain-service";import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";+import { TPamInsightsServiceFactory } from "@app/ee/services/pam-insights/pam-insights-service";import { TPamResourceRotationRulesServiceFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-service";import { TPamResourceServiceFactory } from "@app/ee/services/pam-resource/pam-resource-service";import { TPamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";@@ -365,6 +366,7 @@ declare module "fastify" {microsoftTeams: TMicrosoftTeamsServiceFactory;assumePrivileges: TAssumePrivilegeServiceFactory;insights: TInsightsServiceFactory;+ pamInsights: TPamInsightsServiceFactory;relay: TRelayServiceFactory;gatewayV2: TGatewayV2ServiceFactory;gatewayPool: TGatewayPoolServiceFactory;diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.tsindex 7ef91cddff..daa1ab69e5 100644--- a/backend/src/ee/routes/v1/index.ts+++ b/backend/src/ee/routes/v1/index.ts@@ -41,6 +41,7 @@ import {registerPamDomainRouter} from "./pam-domain-routers";import { registerPamFolderRouter } from "./pam-folder-router";+import { registerPamInsightsRouter } from "./pam-insights-router";import { PAM_RESOURCE_REGISTER_ROUTER_MAP } from "./pam-resource-routers";import { registerPamResourceRotationRulesRouter } from "./pam-resource-routers/pam-resource-rotation-rules-router";import { registerPamResourceRouter } from "./pam-resource-routers/pam-resource-router";@@ -121,6 +122,7 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {await server.register(registerGithubOrgSyncRouter, { prefix: "/github-org-sync-config" });await server.register(registerInsightsRouter, { prefix: "/insights" });+ await server.register(registerPamInsightsRouter, { prefix: "/insights/pam" });await server.register(async (pkiRouter) => {diff --git a/backend/src/ee/routes/v1/pam-insights-router.ts b/backend/src/ee/routes/v1/pam-insights-router.tsnew file mode 100644index 0000000000..61a7104810--- /dev/null+++ b/backend/src/ee/routes/v1/pam-insights-router.ts@@ -0,0 +1,188 @@+import { z } from "zod";++import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { readLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";++export const registerPamInsightsRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/summary",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getPamInsightsSummary",+ description: "Get PAM project totals: resources, accounts, and active sessions",+ security: [{ bearerAuth: [] }],+ querystring: z.object({+ projectId: z.string().trim()+ }),+ response: {+ 200: z.object({+ totalResources: z.number(),+ resourcesWithRotation: z.number(),+ totalAccounts: z.number(),+ failedRotations: z.number(),+ activeSessions: z.number(),+ resourceTypeCount: z.number()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const { projectId } = req.query;+ const result = await server.services.pamInsights.getSummary(projectId, req.permission);+ await server.services.auditLog.createAuditLog({+ projectId,+ event: { type: EventType.VIEW_INSIGHTS_PAM_SUMMARY, metadata: { projectId } },+ ...req.auditLogInfo+ });+ return result;+ }+ });++ server.route({+ method: "GET",+ url: "/session-activity",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getPamInsightsSessionActivity",+ description: "Get session counts grouped by day for the last 30 days",+ security: [{ bearerAuth: [] }],+ querystring: z.object({+ projectId: z.string().trim()+ }),+ response: {+ 200: z.object({+ days: z.array(z.object({ date: z.string(), count: z.number() })),+ avgPerDay: z.number()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const { projectId } = req.query;+ const result = await server.services.pamInsights.getSessionActivity(projectId, req.permission);+ await server.services.auditLog.createAuditLog({+ projectId,+ event: { type: EventType.VIEW_INSIGHTS_PAM_SESSION_ACTIVITY, metadata: { projectId } },+ ...req.auditLogInfo+ });+ return result;+ }+ });++ server.route({+ method: "GET",+ url: "/top-actors",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getPamInsightsTopActors",+ description: "Get top actors initiating PAM sessions in the last 30 days",+ security: [{ bearerAuth: [] }],+ querystring: z.object({+ projectId: z.string().trim()+ }),+ response: {+ 200: z.object({+ actors: z.array(+ z.object({+ actorName: z.string(),+ actorEmail: z.string(),+ sessionCount: z.number(),+ isService: z.boolean()+ })+ )+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const { projectId } = req.query;+ const result = await server.services.pamInsights.getTopActors(projectId, req.permission);+ await server.services.auditLog.createAuditLog({+ projectId,+ event: { type: EventType.VIEW_INSIGHTS_PAM_TOP_ACTORS, metadata: { projectId } },+ ...req.auditLogInfo+ });+ return result;+ }+ });++ server.route({+ method: "GET",+ url: "/resource-breakdown",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getPamInsightsResourceBreakdown",+ description: "Get count of resources and accounts grouped by resource type",+ security: [{ bearerAuth: [] }],+ querystring: z.object({+ projectId: z.string().trim()+ }),+ response: {+ 200: z.object({+ breakdown: z.array(+ z.object({+ resourceType: z.string(),+ resourceCount: z.number(),+ accountCount: z.number()+ })+ )+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const { projectId } = req.query;+ const result = await server.services.pamInsights.getResourceBreakdown(projectId, req.permission);+ await server.services.auditLog.createAuditLog({+ projectId,+ event: { type: EventType.VIEW_INSIGHTS_PAM_RESOURCE_BREAKDOWN, metadata: { projectId } },+ ...req.auditLogInfo+ });+ return result;+ }+ });++ server.route({+ method: "GET",+ url: "/upcoming-rotations",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getPamInsightsUpcomingRotations",+ description: "Get accounts due for credential rotation in the next 7 days",+ security: [{ bearerAuth: [] }],+ querystring: z.object({+ projectId: z.string().trim()+ }),+ response: {+ 200: z.object({+ rotations: z.array(+ z.object({+ accountId: z.string(),+ accountName: z.string(),+ resourceId: z.string(),+ resourceName: z.string(),+ resourceType: z.string(),+ intervalSeconds: z.number(),+ nextRotationAt: z.date()+ })+ ),+ totalScheduled: z.number()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const { projectId } = req.query;+ const result = await server.services.pamInsights.getUpcomingRotations(projectId, req.permission);+ await server.services.auditLog.createAuditLog({+ projectId,+ event: { type: EventType.VIEW_INSIGHTS_PAM_UPCOMING_ROTATIONS, metadata: { projectId } },+ ...req.auditLogInfo+ });+ return result;+ }+ });+};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 5f577943a5..8634aedb7f 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -609,6 +609,11 @@ export enum EventType {VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_VOLUME = "view-insights-secrets-management-access-volume",VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS = "view-insights-secrets-management-access-locations",VIEW_INSIGHTS_SECRETS_MANAGEMENT_SUMMARY = "view-insights-secrets-management-summary",+ VIEW_INSIGHTS_PAM_SUMMARY = "view-insights-pam-summary",+ VIEW_INSIGHTS_PAM_SESSION_ACTIVITY = "view-insights-pam-session-activity",+ VIEW_INSIGHTS_PAM_TOP_ACTORS = "view-insights-pam-top-actors",+ VIEW_INSIGHTS_PAM_RESOURCE_BREAKDOWN = "view-insights-pam-resource-breakdown",+ VIEW_INSIGHTS_PAM_UPCOMING_ROTATIONS = "view-insights-pam-upcoming-rotations",PAM_SESSION_CREDENTIALS_GET = "pam-session-credentials-get",PAM_SESSION_START = "pam-session-start",@@ -4784,6 +4789,41 @@ interface ViewSecretManagementInsightsSummaryEvent {};}+interface ViewPamInsightsSummaryEvent {+ type: EventType.VIEW_INSIGHTS_PAM_SUMMARY;+ metadata: {+ projectId: string;+ };+}++interface ViewPamInsightsSessionActivityEvent {+ type: EventType.VIEW_INSIGHTS_PAM_SESSION_ACTIVITY;+ metadata: {+ projectId: string;+ };+}++interface ViewPamInsightsTopActorsEvent {+ type: EventType.VIEW_INSIGHTS_PAM_TOP_ACTORS;+ metadata: {+ projectId: string;+ };+}++interface ViewPamInsightsResourceBreakdownEvent {+ type: EventType.VIEW_INSIGHTS_PAM_RESOURCE_BREAKDOWN;+ metadata: {+ projectId: string;+ };+}++interface ViewPamInsightsUpcomingRotationsEvent {+ type: EventType.VIEW_INSIGHTS_PAM_UPCOMING_ROTATIONS;+ metadata: {+ projectId: string;+ };+}+interface ProjectRoleCreateEvent {type: EventType.CREATE_PROJECT_ROLE;metadata: {@@ -6597,6 +6637,11 @@ export type Event =| ViewSecretManagementInsightsAccessLocationsEvent| ViewInsightsAuthMethodsEvent| ViewSecretManagementInsightsSummaryEvent+ | ViewPamInsightsSummaryEvent+ | ViewPamInsightsSessionActivityEvent+ | ViewPamInsightsTopActorsEvent+ | ViewPamInsightsResourceBreakdownEvent+ | ViewPamInsightsUpcomingRotationsEvent| ProjectRoleCreateEvent| ProjectRoleUpdateEvent| ProjectRoleDeleteEventdiff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.tsindex 4a43ca4785..4041d88ead 100644--- a/backend/src/ee/services/pam-account/pam-account-dal.ts+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts@@ -286,11 +286,88 @@ export const pamAccountDALFactory = (db: TDbClient) => {}};+ const countByProject = async (projectId: string, tx?: Knex): Promise<number> => {+ const result = await (tx || db.replicaNode())(TableName.PamAccount)+ .where("projectId", projectId)+ .count("id as count")+ .first();+ return Number((result as { count?: string | number })?.count ?? 0);+ };++ const countFailedRotationsByProject = async (projectId: string, tx?: Knex): Promise<number> => {+ const result = await (tx || db.replicaNode())(TableName.PamAccount)+ .where("projectId", projectId)+ .where("rotationStatus", "failed")+ .count("id as count")+ .first();+ return Number((result as { count?: string | number })?.count ?? 0);+ };++ const countByProjectGroupedByResourceType = async (+ projectId: string,+ tx?: Knex+ ): Promise<{ resourceType: string; count: number }[]> => {+ const rows = (await (tx || db.replicaNode())(TableName.PamAccount)+ .innerJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)+ .select(`${TableName.PamResource}.resourceType as resourceType`)+ .count(`${TableName.PamAccount}.id as count`)+ .where(`${TableName.PamAccount}.projectId`, projectId)+ .groupBy(`${TableName.PamResource}.resourceType`)) as unknown as {+ resourceType: string;+ count: string | number;+ }[];++ return rows.map((row) => ({ resourceType: row.resourceType, count: Number(row.count) }));+ };++ const findRotationCandidatesByProject = async (+ projectId: string,+ tx?: Knex+ ): Promise<+ {+ id: string;+ name: string;+ resourceId: string;+ resourceName: string;+ resourceType: string;+ lastRotatedAt: Date | null;+ createdAt: Date;+ }[]+ > => {+ const rows = await (tx || db.replicaNode())(TableName.PamAccount)+ .innerJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)+ .select(+ `${TableName.PamAccount}.id as id`,+ `${TableName.PamAccount}.name as name`,+ `${TableName.PamAccount}.resourceId as resourceId`,+ `${TableName.PamAccount}.lastRotatedAt as lastRotatedAt`,+ `${TableName.PamAccount}.createdAt as createdAt`,+ `${TableName.PamResource}.name as resourceName`,+ `${TableName.PamResource}.resourceType as resourceType`+ )+ .where(`${TableName.PamAccount}.projectId`, projectId)+ .whereNotNull(`${TableName.PamResource}.encryptedRotationAccountCredentials`);++ return rows as {+ id: string;+ name: string;+ resourceId: string;+ resourceName: string;+ resourceType: string;+ lastRotatedAt: Date | null;+ createdAt: Date;+ }[];+ };+return {...orm,findByProjectIdWithParentDetails,findByIdWithParentDetails,findMetadataByAccountIds,- findRotationCandidates+ findRotationCandidates,+ findRotationCandidatesByProject,+ countByProject,+ countFailedRotationsByProject,+ countByProjectGroupedByResourceType};};diff --git a/backend/src/ee/services/pam-insights/pam-insights-service.ts b/backend/src/ee/services/pam-insights/pam-insights-service.tsnew file mode 100644index 0000000000..23a4313fde--- /dev/null+++ b/backend/src/ee/services/pam-insights/pam-insights-service.ts@@ -0,0 +1,277 @@+import { ForbiddenError } from "@casl/ability";+import picomatch from "picomatch";++import { ActionProjectType } from "@app/db/schemas";+import { TPamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";+import { TPamResourceDALFactory } from "@app/ee/services/pam-resource/pam-resource-dal";+import { TPamResourceRotationRulesDALFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-dal";+import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ProjectPermissionPamInsightsActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";+import { withCache } from "@app/lib/cache/with-cache";+import { OrgServiceActor } from "@app/lib/types";++const SESSION_ACTIVITY_DAYS = 30;+const TOP_ACTORS_DAYS = 30;+const TOP_ACTORS_LIMIT = 10;+const UPCOMING_ROTATIONS_LIMIT = 100;++type TPamInsightsServiceFactoryDep = {+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ pamSessionDAL: Pick<TPamSessionDALFactory, "countActiveByProject" | "countDailyByProject" | "findTopActorsByProject">;+ pamResourceDAL: Pick<+ TPamResourceDALFactory,+ "countByProject" | "countWithRotationByProject" | "countByProjectGroupedByType"+ >;+ pamAccountDAL: Pick<+ TPamAccountDALFactory,+ | "countByProject"+ | "countFailedRotationsByProject"+ | "countByProjectGroupedByResourceType"+ | "findRotationCandidatesByProject"+ >;+ pamResourceRotationRulesDAL: Pick<TPamResourceRotationRulesDALFactory, "findByResourceIds">;+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem">;+};++export type TPamInsightsServiceFactory = ReturnType<typeof pamInsightsServiceFactory>;++const checkPamInsightsPermission = async (+ permissionService: TPamInsightsServiceFactoryDep["permissionService"],+ projectId: string,+ actor: OrgServiceActor+) => {+ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorId: actor.id,+ projectId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ actionProjectType: ActionProjectType.PAM+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionPamInsightsActions.Read,+ ProjectPermissionSub.PamInsights+ );+};++const getStartOfDayUtc = (offsetDays: number): Date => {+ const now = new Date();+ const utcMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());+ return new Date(utcMidnight - offsetDays * 24 * 60 * 60 * 1000);+};++export const pamInsightsServiceFactory = ({+ permissionService,+ pamSessionDAL,+ pamResourceDAL,+ pamAccountDAL,+ pamResourceRotationRulesDAL,+ keyStore+}: TPamInsightsServiceFactoryDep) => {+ const getSummary = async (projectId: string, actor: OrgServiceActor) => {+ await checkPamInsightsPermission(permissionService, projectId, actor);++ return withCache({+ keyStore,+ key: KeyStorePrefixes.InsightsCache(projectId, "pam:summary"),+ ttlSeconds: 15,+ fetcher: async () => {+ const [+ totalResources,+ resourcesWithRotation,+ totalAccounts,+ failedRotations,+ activeSessions,+ resourceTypeCount+ ] = await Promise.all([+ pamResourceDAL.countByProject(projectId),+ pamResourceDAL.countWithRotationByProject(projectId),+ pamAccountDAL.countByProject(projectId),+ pamAccountDAL.countFailedRotationsByProject(projectId),+ pamSessionDAL.countActiveByProject(projectId),+ pamResourceDAL.countByProjectGroupedByType(projectId)+ ]);++ return {+ totalResources,+ resourcesWithRotation,+ totalAccounts,+ failedRotations,+ activeSessions,+ resourceTypeCount: resourceTypeCount.length+ };+ }+ });+ };++ const getSessionActivity = async (projectId: string, actor: OrgServiceActor) => {+ await checkPamInsightsPermission(permissionService, projectId, actor);++ return withCache({+ keyStore,+ key: KeyStorePrefixes.InsightsCache(projectId, "pam:session-activity"),+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,+ fetcher: async () => {+ const startDate = getStartOfDayUtc(SESSION_ACTIVITY_DAYS - 1);+ const rows = await pamSessionDAL.countDailyByProject(projectId, startDate);++ const dayCounts = new Map<string, number>();+ for (let i = SESSION_ACTIVITY_DAYS - 1; i >= 0; i -= 1) {+ const d = getStartOfDayUtc(i);+ dayCounts.set(d.toISOString().slice(0, 10), 0);+ }+ rows.forEach((row) => {+ if (dayCounts.has(row.date)) dayCounts.set(row.date, row.count);+ });++ const days = Array.from(dayCounts.entries()).map(([date, count]) => ({ date, count }));+ const total = days.reduce((sum, d) => sum + d.count, 0);+ const avgPerDay = days.length > 0 ? Math.round(total / days.length) : 0;++ return { days, avgPerDay };+ }+ });+ };++ const getTopActors = async (projectId: string, actor: OrgServiceActor) => {+ await checkPamInsightsPermission(permissionService, projectId, actor);++ return withCache({+ keyStore,+ key: KeyStorePrefixes.InsightsCache(projectId, "pam:top-actors"),+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,+ fetcher: async () => {+ const startDate = getStartOfDayUtc(TOP_ACTORS_DAYS - 1);+ const rows = await pamSessionDAL.findTopActorsByProject(projectId, startDate, TOP_ACTORS_LIMIT);++ return {+ actors: rows.map((row) => ({+ actorName: row.actorName,+ actorEmail: row.actorEmail,+ sessionCount: row.sessionCount,+ isService: row.userId === null+ }))+ };+ }+ });+ };++ const getResourceBreakdown = async (projectId: string, actor: OrgServiceActor) => {+ await checkPamInsightsPermission(permissionService, projectId, actor);++ return withCache({+ keyStore,+ key: KeyStorePrefixes.InsightsCache(projectId, "pam:resource-breakdown"),+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,+ fetcher: async () => {+ const [resourceCounts, accountCounts] = await Promise.all([+ pamResourceDAL.countByProjectGroupedByType(projectId),+ pamAccountDAL.countByProjectGroupedByResourceType(projectId)+ ]);++ const accountsByType = new Map<string, number>();+ accountCounts.forEach((row) => accountsByType.set(row.resourceType, row.count));++ const breakdown = resourceCounts.map((row) => ({+ resourceType: row.resourceType,+ resourceCount: row.count,+ accountCount: accountsByType.get(row.resourceType) ?? 0+ }));++ breakdown.sort((a, b) => b.resourceCount - a.resourceCount);++ return { breakdown };+ }+ });+ };++ const getUpcomingRotations = async (projectId: string, actor: OrgServiceActor) => {+ await checkPamInsightsPermission(permissionService, projectId, actor);++ return withCache({+ keyStore,+ key: KeyStorePrefixes.InsightsCache(projectId, "pam:upcoming-rotations"),+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,+ fetcher: async () => {+ const candidates = await pamAccountDAL.findRotationCandidatesByProject(projectId);+ if (!candidates.length) return { rotations: [], totalScheduled: 0 };++ const resourceIds = [...new Set(candidates.map((c) => c.resourceId))];+ const allRules = await pamResourceRotationRulesDAL.findByResourceIds(resourceIds);+ if (!allRules.length) return { rotations: [], totalScheduled: 0 };++ const rulesByResource: Record<string, typeof allRules> = {};+ for (const rule of allRules) {+ if (!rulesByResource[rule.resourceId]) rulesByResource[rule.resourceId] = [];+ rulesByResource[rule.resourceId].push(rule);+ }++ const now = Date.now();++ type TUpcomingRotation = {+ accountId: string;+ accountName: string;+ resourceId: string;+ resourceName: string;+ resourceType: string;+ intervalSeconds: number;+ nextRotationAt: Date;+ };++ const upcoming: TUpcomingRotation[] = [];+ for (const candidate of candidates) {+ const rules = rulesByResource[candidate.resourceId];+ // eslint-disable-next-line no-continue+ if (!rules) continue;++ const matchedRule = rules.find((rule) => picomatch.isMatch(candidate.name, rule.namePattern));+ // eslint-disable-next-line no-continue+ if (!matchedRule || !matchedRule.enabled || !matchedRule.intervalSeconds) continue;++ const lastRotated = candidate.lastRotatedAt+ ? new Date(candidate.lastRotatedAt).getTime()+ : candidate.createdAt.getTime();+ const nextRotationMs = lastRotated + matchedRule.intervalSeconds * 1000;++ upcoming.push({+ accountId: candidate.id,+ accountName: candidate.name,+ resourceId: candidate.resourceId,+ resourceName: candidate.resourceName,+ resourceType: candidate.resourceType,+ intervalSeconds: matchedRule.intervalSeconds,+ nextRotationAt: new Date(Math.max(nextRotationMs, now))+ });+ }++ upcoming.sort((a, b) => a.nextRotationAt.getTime() - b.nextRotationAt.getTime());++ return {+ rotations: upcoming.slice(0, UPCOMING_ROTATIONS_LIMIT),+ totalScheduled: upcoming.length+ };+ },+ reviver: (parsed) => {+ parsed.rotations.forEach((r) => {+ // eslint-disable-next-line no-param-reassign+ r.nextRotationAt = new Date(r.nextRotationAt);+ });+ return parsed;+ }+ });+ };++ return {+ getSummary,+ getSessionActivity,+ getTopActors,+ getResourceBreakdown,+ getUpcomingRotations+ };+};diff --git a/backend/src/ee/services/pam-resource/pam-resource-dal.ts b/backend/src/ee/services/pam-resource/pam-resource-dal.tsindex 8429700c5b..615908d387 100644--- a/backend/src/ee/services/pam-resource/pam-resource-dal.ts+++ b/backend/src/ee/services/pam-resource/pam-resource-dal.ts@@ -172,6 +172,36 @@ export const pamResourceDALFactory = (db: TDbClient) => {return parseInt(String(result?.count || "0"), 10);};+ const countByProject = async (projectId: string, tx?: Knex): Promise<number> => {+ const result = await (tx || db.replicaNode())(TableName.PamResource)+ .where("projectId", projectId)+ .count("id as count")+ .first();+ return Number((result as { count?: string | number })?.count ?? 0);+ };++ const countWithRotationByProject = async (projectId: string, tx?: Knex): Promise<number> => {+ const result = await (tx || db.replicaNode())(TableName.PamResource)+ .where("projectId", projectId)+ .whereNotNull("encryptedRotationAccountCredentials")+ .count("id as count")+ .first();+ return Number((result as { count?: string | number })?.count ?? 0);+ };++ const countByProjectGroupedByType = async (+ projectId: string,+ tx?: Knex+ ): Promise<{ resourceType: string; count: number }[]> => {+ const rows = (await (tx || db.replicaNode())(TableName.PamResource)+ .select("resourceType")+ .count("id as count")+ .where("projectId", projectId)+ .groupBy("resourceType")) as unknown as { resourceType: string; count: string | number }[];++ return rows.map((row) => ({ resourceType: row.resourceType, count: Number(row.count) }));+ };+return {...orm,findById,@@ -179,6 +209,9 @@ export const pamResourceDALFactory = (db: TDbClient) => {findMetadataByResourceIds,findByDomainId,findByGatewayId,- countByGatewayId+ countByGatewayId,+ countByProject,+ countWithRotationByProject,+ countByProjectGroupedByType};};diff --git a/backend/src/ee/services/pam-session/pam-session-dal.ts b/backend/src/ee/services/pam-session/pam-session-dal.tsindex 693f62a8c2..bdd2d4fa80 100644--- a/backend/src/ee/services/pam-session/pam-session-dal.ts+++ b/backend/src/ee/services/pam-session/pam-session-dal.ts@@ -82,12 +82,76 @@ export const pamSessionDALFactory = (db: TDbClient) => {return updated;};+ const countActiveByProject = async (projectId: string, tx?: Knex): Promise<number> => {+ const result = await (tx || db.replicaNode())(TableName.PamSession)+ .where("projectId", projectId)+ .whereIn("status", [PamSessionStatus.Starting, PamSessionStatus.Active])+ .count("id as count")+ .first();++ return Number((result as { count?: string | number })?.count ?? 0);+ };++ const countDailyByProject = async (+ projectId: string,+ startDate: Date,+ tx?: Knex+ ): Promise<{ date: string; count: number }[]> => {+ const rows = (await (tx || db.replicaNode())(TableName.PamSession)+ .select(db.raw(`to_char("createdAt"::date, 'YYYY-MM-DD') as date`))+ .count("id as count")+ .where("projectId", projectId)+ .where("createdAt", ">=", startDate)+ .groupByRaw(`"createdAt"::date`)+ .orderByRaw(`"createdAt"::date asc`)) as unknown as { date: string; count: string | number }[];++ return rows.map((row) => ({ date: String(row.date), count: Number(row.count) }));+ };++ const findTopActorsByProject = async (+ projectId: string,+ startDate: Date,+ limit: number,+ tx?: Knex+ ): Promise<+ {+ actorName: string;+ actorEmail: string;+ userId: string | null;+ sessionCount: number;+ }[]+ > => {+ const rows = (await (tx || db.replicaNode())(TableName.PamSession)+ .select("actorName", "actorEmail", "userId")+ .count("id as count")+ .where("projectId", projectId)+ .where("createdAt", ">=", startDate)+ .groupBy("actorName", "actorEmail", "userId")+ .orderBy("count", "desc")+ .limit(limit)) as unknown as {+ actorName: string;+ actorEmail: string;+ userId: string | null;+ count: string | number;+ }[];++ return rows.map((row) => ({+ actorName: row.actorName,+ actorEmail: row.actorEmail,+ userId: row.userId,+ sessionCount: Number(row.count)+ }));+ };+return {...orm,findById,findByProjectId,expireSessionById,countActiveWebSessions,+ countActiveByProject,+ countDailyByProject,+ findTopActorsByProject,endSessionById,terminateSessionById};diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex d0004d7a46..35045cd7b2 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -23,6 +23,7 @@ import {ProjectPermissionPamAccountActions,ProjectPermissionPamAccountPolicyActions,ProjectPermissionPamDiscoveryActions,+ ProjectPermissionPamInsightsActions,ProjectPermissionPamSessionActions,ProjectPermissionPkiCertificateInstallationActions,ProjectPermissionPkiDiscoveryActions,@@ -428,6 +429,8 @@ const buildAdminPermissionRules = () => {ProjectPermissionSub.PamDiscovery);+ can([ProjectPermissionPamInsightsActions.Read], ProjectPermissionSub.PamInsights);+can([ProjectPermissionMcpEndpointActions.Read,@@ -723,6 +726,8 @@ const buildMemberPermissionRules = () => {can([ProjectPermissionPamDiscoveryActions.Read], ProjectPermissionSub.PamDiscovery);+ can([ProjectPermissionPamInsightsActions.Read], ProjectPermissionSub.PamInsights);+can([ProjectPermissionMcpEndpointActions.Read], ProjectPermissionSub.McpEndpoints);can([ProjectPermissionActions.Read], ProjectPermissionSub.McpServers);can([ProjectPermissionActions.Read], ProjectPermissionSub.McpActivityLogs);@@ -807,6 +812,8 @@ const buildViewerPermissionRules = () => {can([ProjectPermissionPamDiscoveryActions.Read], ProjectPermissionSub.PamDiscovery);+ can([ProjectPermissionPamInsightsActions.Read], ProjectPermissionSub.PamInsights);+can([ProjectPermissionMcpEndpointActions.Read], ProjectPermissionSub.McpEndpoints);can([ProjectPermissionActions.Read], ProjectPermissionSub.McpServers);can([ProjectPermissionActions.Read], ProjectPermissionSub.McpActivityLogs);diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.tsindex e16b338d76..38b0038748 100644--- a/backend/src/ee/services/permission/project-permission.ts+++ b/backend/src/ee/services/permission/project-permission.ts@@ -274,6 +274,10 @@ export enum ProjectPermissionPamAccountPolicyActions {Delete = "delete"}+export enum ProjectPermissionPamInsightsActions {+ Read = "read"+}+export enum ProjectPermissionPamDiscoveryActions {Read = "read",Create = "create",@@ -362,6 +366,7 @@ export enum ProjectPermissionSub {PamSessions = "pam-sessions",PamAccountPolicies = "pam-account-policies",PamDiscovery = "pam-discovery",+ PamInsights = "pam-insights",CertificateProfiles = "certificate-profiles",CertificatePolicies = "certificate-policies",ApprovalRequests = "approval-requests",@@ -692,6 +697,7 @@ export type ProjectPermissionSet =| [ProjectPermissionPamSessionActions, ProjectPermissionSub.PamSessions]| [ProjectPermissionPamAccountPolicyActions, ProjectPermissionSub.PamAccountPolicies]| [ProjectPermissionPamDiscoveryActions, ProjectPermissionSub.PamDiscovery]+ | [ProjectPermissionPamInsightsActions, ProjectPermissionSub.PamInsights]| [ProjectPermissionMcpEndpointActions,ProjectPermissionSub.McpEndpoints | (ForcedSubject<ProjectPermissionSub.McpEndpoints> & McpEndpointSubjectFields)@@ -1801,6 +1807,12 @@ const GeneralPermissionSchema = ["Describe what action an entity can take.")}),+ z.object({+ subject: z.literal(ProjectPermissionSub.PamInsights).describe("The entity this permission pertains to."),+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionPamInsightsActions).describe(+ "Describe what action an entity can take."+ )+ }),z.object({subject: z.literal(ProjectPermissionSub.McpEndpoints).describe("The entity this permission pertains to."),inverted: z.boolean().optional().describe("Whether rule allows or forbids."),diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 68327ec00b..1b0171cb47 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -106,6 +106,7 @@ import { pamDomainDALFactory } from "@app/ee/services/pam-domain/pam-domain-dal"import { pamDomainServiceFactory } from "@app/ee/services/pam-domain/pam-domain-service";import { pamFolderDALFactory } from "@app/ee/services/pam-folder/pam-folder-dal";import { pamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";+import { pamInsightsServiceFactory } from "@app/ee/services/pam-insights/pam-insights-service";import { pamResourceDALFactory } from "@app/ee/services/pam-resource/pam-resource-dal";import { pamResourceFavoriteDALFactory } from "@app/ee/services/pam-resource/pam-resource-favorite-dal";import { pamResourceRotationRulesDALFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-dal";@@ -2972,6 +2973,15 @@ export const registerRoutes = async (pamSessionAiSummaryService});+ const pamInsightsService = pamInsightsServiceFactory({+ permissionService,+ pamSessionDAL,+ pamResourceDAL,+ pamAccountDAL,+ pamResourceRotationRulesDAL,+ keyStore+ });+const pamWebAccessService = pamWebAccessServiceFactory({pamAccountDAL,pamAccountPolicyDAL,@@ -3247,6 +3257,7 @@ export const registerRoutes = async (microsoftTeams: microsoftTeamsService,assumePrivileges: assumePrivilegeService,insights: insightsService,+ pamInsights: pamInsightsService,githubOrgSync: githubOrgSyncConfigService,folderCommit: folderCommitService,secretScanningV2: secretScanningV2Service,diff --git a/frontend/src/context/ProjectPermissionContext/index.tsx b/frontend/src/context/ProjectPermissionContext/index.tsxindex 742ddd9726..2763a1d215 100644--- a/frontend/src/context/ProjectPermissionContext/index.tsx+++ b/frontend/src/context/ProjectPermissionContext/index.tsx@@ -16,6 +16,7 @@ export {ProjectPermissionKmipActions,ProjectPermissionMcpEndpointActions,ProjectPermissionMemberActions,+ ProjectPermissionPamInsightsActions,ProjectPermissionPamSessionActions,ProjectPermissionPkiCertificateInstallationActions,ProjectPermissionPkiDiscoveryActions,diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.tsindex bb1f7a23c1..29e219fba7 100644--- a/frontend/src/context/ProjectPermissionContext/types.ts+++ b/frontend/src/context/ProjectPermissionContext/types.ts@@ -277,6 +277,10 @@ export enum ProjectPermissionPamAccountPolicyActions {Delete = "delete"}+export enum ProjectPermissionPamInsightsActions {+ Read = "read"+}+export enum ProjectPermissionPamDiscoveryActions {Read = "read",Create = "create",@@ -443,6 +447,7 @@ export enum ProjectPermissionSub {PamSessions = "pam-sessions",PamAccountPolicies = "pam-account-policies",PamDiscovery = "pam-discovery",+ PamInsights = "pam-insights",McpEndpoints = "mcp-endpoints",McpServers = "mcp-servers",McpActivityLogs = "mcp-activity-logs",@@ -735,6 +740,7 @@ export type ProjectPermissionSet =| [ProjectPermissionPamSessionActions, ProjectPermissionSub.PamSessions]| [ProjectPermissionPamAccountPolicyActions, ProjectPermissionSub.PamAccountPolicies]| [ProjectPermissionPamDiscoveryActions, ProjectPermissionSub.PamDiscovery]+ | [ProjectPermissionPamInsightsActions, ProjectPermissionSub.PamInsights]| [ProjectPermissionApprovalRequestActions, ProjectPermissionSub.ApprovalRequests]| [ProjectPermissionApprovalRequestGrantActions, ProjectPermissionSub.ApprovalRequestGrants]| [ProjectPermissionSecretApprovalRequestActions, ProjectPermissionSub.SecretApprovalRequest]diff --git a/frontend/src/context/index.tsx b/frontend/src/context/index.tsxindex 12d6ef9d01..6bfe9c5dd1 100644--- a/frontend/src/context/index.tsx+++ b/frontend/src/context/index.tsx@@ -29,6 +29,7 @@ export {ProjectPermissionKmipActions,ProjectPermissionMcpEndpointActions,ProjectPermissionMemberActions,+ ProjectPermissionPamInsightsActions,ProjectPermissionPamSessionActions,ProjectPermissionPkiCertificateInstallationActions,ProjectPermissionPkiDiscoveryActions,diff --git a/frontend/src/hooks/api/pamInsights/index.ts b/frontend/src/hooks/api/pamInsights/index.tsnew file mode 100644index 0000000000..4e29988ec7--- /dev/null+++ b/frontend/src/hooks/api/pamInsights/index.ts@@ -0,0 +1,20 @@+export {+ pamInsightsKeys,+ useGetPamInsightsSummary,+ useGetPamResourceBreakdown,+ useGetPamSessionActivity,+ useGetPamTopActors,+ useGetPamUpcomingRotations+} from "./queries";+export type {+ TGetPamInsightsParams,+ TPamInsightsSummary,+ TPamResourceBreakdownEntry,+ TPamResourceBreakdownResponse,+ TPamSessionActivityDay,+ TPamSessionActivityResponse,+ TPamTopActor,+ TPamTopActorsResponse,+ TPamUpcomingRotation,+ TPamUpcomingRotationsResponse+} from "./types";diff --git a/frontend/src/hooks/api/pamInsights/queries.tsx b/frontend/src/hooks/api/pamInsights/queries.tsxnew file mode 100644index 0000000000..26b93937c4--- /dev/null+++ b/frontend/src/hooks/api/pamInsights/queries.tsx@@ -0,0 +1,156 @@+import { useQuery, UseQueryOptions } from "@tanstack/react-query";++import { apiRequest } from "@app/config/request";++import {+ TGetPamInsightsParams,+ TPamInsightsSummary,+ TPamResourceBreakdownResponse,+ TPamSessionActivityResponse,+ TPamTopActorsResponse,+ TPamUpcomingRotationsResponse+} from "./types";++export const pamInsightsKeys = {+ all: () => ["pam-insights"] as const,+ summary: (params: TGetPamInsightsParams) =>+ [...pamInsightsKeys.all(), "summary", params] as const,+ sessionActivity: (params: TGetPamInsightsParams) =>+ [...pamInsightsKeys.all(), "session-activity", params] as const,+ topActors: (params: TGetPamInsightsParams) =>+ [...pamInsightsKeys.all(), "top-actors", params] as const,+ resourceBreakdown: (params: TGetPamInsightsParams) =>+ [...pamInsightsKeys.all(), "resource-breakdown", params] as const,+ upcomingRotations: (params: TGetPamInsightsParams) =>+ [...pamInsightsKeys.all(), "upcoming-rotations", params] as const+};++const PAM_INSIGHTS_STALE_TIME = 5 * 60 * 1000;+const PAM_INSIGHTS_SUMMARY_REFETCH_INTERVAL = 15 * 1000;++export const useGetPamInsightsSummary = (+ params: TGetPamInsightsParams,+ options?: Omit<+ UseQueryOptions<+ TPamInsightsSummary,+ unknown,+ TPamInsightsSummary,+ ReturnType<typeof pamInsightsKeys.summary>+ >,+ "queryKey" | "queryFn"+ >+) =>+ useQuery({+ queryKey: pamInsightsKeys.summary(params),+ queryFn: async () => {+ const { data } = await apiRequest.get<TPamInsightsSummary>("/api/v1/insights/pam/summary", {+ params+ });+ return data;+ },+ staleTime: 0,+ refetchInterval: PAM_INSIGHTS_SUMMARY_REFETCH_INTERVAL,+ ...options+ });++export const useGetPamSessionActivity = (+ params: TGetPamInsightsParams,+ options?: Omit<+ UseQueryOptions<+ TPamSessionActivityResponse,+ unknown,+ TPamSessionActivityResponse,+ ReturnType<typeof pamInsightsKeys.sessionActivity>+ >,+ "queryKey" | "queryFn"+ >+) =>+ useQuery({+ queryKey: pamInsightsKeys.sessionActivity(params),+ queryFn: async () => {+ const { data } = await apiRequest.get<TPamSessionActivityResponse>(+ "/api/v1/insights/pam/session-activity",+ { params }+ );+ return data;+ },+ staleTime: PAM_INSIGHTS_STALE_TIME,+ ...options+ });++export const useGetPamTopActors = (+ params: TGetPamInsightsParams,+ options?: Omit<+ UseQueryOptions<+ TPamTopActorsResponse,+ unknown,+ TPamTopActorsResponse,+ ReturnType<typeof pamInsightsKeys.topActors>+ >,+ "queryKey" | "queryFn"+ >+) =>+ useQuery({+ queryKey: pamInsightsKeys.topActors(params),+ queryFn: async () => {+ const { data } = await apiRequest.get<TPamTopActorsResponse>(+ "/api/v1/insights/pam/top-actors",+ {+ params+ }+ );+ return data;+ },+ staleTime: PAM_INSIGHTS_STALE_TIME,+ ...options+ });++export const useGetPamResourceBreakdown = (+ params: TGetPamInsightsParams,+ options?: Omit<+ UseQueryOptions<+ TPamResourceBreakdownResponse,+ unknown,+ TPamResourceBreakdownResponse,+ ReturnType<typeof pamInsightsKeys.resourceBreakdown>+ >,+ "queryKey" | "queryFn"+ >+) =>+ useQuery({+ queryKey: pamInsightsKeys.resourceBreakdown(params),+ queryFn: async () => {+ const { data } = await apiRequest.get<TPamResourceBreakdownResponse>(+ "/api/v1/insights/pam/resource-breakdown",+ { params }+ );+ return data;+ },+ staleTime: PAM_INSIGHTS_STALE_TIME,+ ...options+ });++export const useGetPamUpcomingRotations = (+ params: TGetPamInsightsParams,+ options?: Omit<+ UseQueryOptions<+ TPamUpcomingRotationsResponse,+ unknown,+ TPamUpcomingRotationsResponse,+ ReturnType<typeof pamInsightsKeys.upcomingRotations>+ >,+ "queryKey" | "queryFn"+ >+) =>+ useQuery({+ queryKey: pamInsightsKeys.upcomingRotations(params),+ queryFn: async () => {+ const { data } = await apiRequest.get<TPamUpcomingRotationsResponse>(+ "/api/v1/insights/pam/upcoming-rotations",+ { params }+ );+ return data;+ },+ staleTime: PAM_INSIGHTS_STALE_TIME,+ ...options+ });diff --git a/frontend/src/hooks/api/pamInsights/types.ts b/frontend/src/hooks/api/pamInsights/types.tsnew file mode 100644index 0000000000..5140ffc0e3--- /dev/null+++ b/frontend/src/hooks/api/pamInsights/types.ts@@ -0,0 +1,58 @@+export type TGetPamInsightsParams = {+ projectId: string;+};++export type TPamInsightsSummary = {+ totalResources: number;+ resourcesWithRotation: number;+ totalAccounts: number;+ failedRotations: number;+ activeSessions: number;+ resourceTypeCount: number;+};++export type TPamSessionActivityDay = {+ date: string;+ count: number;+};++export type TPamSessionActivityResponse = {+ days: TPamSessionActivityDay[];+ avgPerDay: number;+};++export type TPamTopActor = {+ actorName: string;+ actorEmail: string;+ sessionCount: number;+ isService: boolean;+};++export type TPamTopActorsResponse = {+ actors: TPamTopActor[];+};++export type TPamResourceBreakdownEntry = {+ resourceType: string;+ resourceCount: number;+ accountCount: number;+};++export type TPamResourceBreakdownResponse = {+ breakdown: TPamResourceBreakdownEntry[];+};++export type TPamUpcomingRotation = {+ accountId: string;+ accountName: string;+ resourceId: string;+ resourceName: string;+ resourceType: string;+ intervalSeconds: number;+ nextRotationAt: string;+};++export type TPamUpcomingRotationsResponse = {+ rotations: TPamUpcomingRotation[];+ totalScheduled: number;+};diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsxindex 2c43ce3110..d84a236f75 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx@@ -1,4 +1,5 @@import {+ ActivityIcon,BookCheck,Database,FileText,@@ -35,6 +36,7 @@ export const PamNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submenu) =>activeMatch: /\/groups\/|\/identities\/|\/members\/|\/roles\//,submenu: PROJECT_ACCESS_CONTROL_SUBMENU},+ { label: "Insights", icon: ActivityIcon, pathSuffix: "insights" },{ label: "Audit Logs", icon: FileText, pathSuffix: "audit-logs" },{ label: "Settings", icon: Settings, pathSuffix: "settings" }];diff --git a/frontend/src/pages/pam/InsightsPage/InsightsPage.tsx b/frontend/src/pages/pam/InsightsPage/InsightsPage.tsxnew file mode 100644index 0000000000..27c52a7c94--- /dev/null+++ b/frontend/src/pages/pam/InsightsPage/InsightsPage.tsx@@ -0,0 +1,42 @@+import { Helmet } from "react-helmet";++import { PageHeader } from "@app/components/v2";+import { ProjectPermissionPamInsightsActions, ProjectPermissionSub } from "@app/context";+import { withProjectPermission } from "@app/hoc";+import { ProjectType } from "@app/hooks/api/projects/types";++import {+ PamInsightsKpiCards,+ PamResourceBreakdown,+ PamSessionActivityChart,+ PamTopActors,+ PamUpcomingRotations+} from "./components";++export const InsightsPage = withProjectPermission(+ () => {+ return (+ <>+ <Helmet>+ <title>PAM Insights</title>+ </Helmet>+ <PageHeader+ scope={ProjectType.PAM}+ title="PAM Insights"+ description="Monitor privileged access activity, account rotation health, and session usage across your project."+ />+ <PamInsightsKpiCards />+ <div className="mt-6 grid grid-cols-1 gap-6 xl:grid-cols-[1.3fr_1fr]">+ <PamSessionActivityChart />+ <PamTopActors />+ <PamResourceBreakdown />+ <PamUpcomingRotations />+ </div>+ </>+ );+ },+ {+ action: ProjectPermissionPamInsightsActions.Read,+ subject: ProjectPermissionSub.PamInsights+ }+);diff --git a/frontend/src/pages/pam/InsightsPage/components/PamInsightsKpiCards.tsx b/frontend/src/pages/pam/InsightsPage/components/PamInsightsKpiCards.tsxnew file mode 100644index 0000000000..f8ff490724--- /dev/null+++ b/frontend/src/pages/pam/InsightsPage/components/PamInsightsKpiCards.tsx@@ -0,0 +1,203 @@+import { useNavigate } from "@tanstack/react-router";+import {+ ActivityIcon,+ AlertTriangleIcon,+ CheckIcon,+ DatabaseIcon,+ InfoIcon,+ KeyRoundIcon+} from "lucide-react";++import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+ Separator,+ Skeleton+} from "@app/components/v3";+import { cn } from "@app/components/v3/utils";+import { useOrganization, useProject } from "@app/context";+import { useGetPamInsightsSummary } from "@app/hooks/api/pamInsights";++type IconVariant = "warning" | "info" | "success" | "danger";+type FootnoteVariant = "success" | "info" | "danger";++type StatCardProps = {+ title: string;+ icon: React.ReactNode;+ iconVariant: IconVariant;+ count: number;+ subtitle: string;+ footnote: React.ReactNode;+ footnoteVariant: FootnoteVariant;+ viewLabel?: string;+ to?: string;+ params?: Record<string, string>;+};++const LiveBadge = ({ count }: { count: number }) => (+ <span className="flex animate-pulse items-center gap-1.5 rounded-full bg-green-900/40 px-2.5 py-1 text-xs font-medium text-green-400">+ <span className="size-1.5 animate-pulse rounded-full bg-green-400" />+ {count === 1 ? "1 session live" : `${count} sessions live`}+ </span>+);++const renderFootnoteIcon = (variant: FootnoteVariant) => {+ if (variant === "success") return <CheckIcon />;+ if (variant === "danger") return <AlertTriangleIcon />;+ return <InfoIcon />;+};++const computeResourcesFootnote = (totalResources: number, resourcesWithRotation: number) => {+ if (totalResources === 0) {+ return { text: "No resources yet", variant: "info" as const };+ }+ return {+ text: `${resourcesWithRotation} of ${totalResources} with rotation`,+ variant: "success" as const+ };+};++const computeAccountsFootnote = (totalAccounts: number, failedRotations: number) => {+ if (totalAccounts === 0) {+ return { text: "No accounts yet", variant: "info" as const };+ }+ if (failedRotations > 0) {+ return {+ text: `${failedRotations} failed rotation${failedRotations === 1 ? "" : "s"}`,+ variant: "danger" as const+ };+ }+ return { text: "All rotations healthy", variant: "success" as const };+};++const StatCard = ({+ title,+ icon,+ iconVariant,+ count,+ subtitle,+ footnote,+ footnoteVariant,+ viewLabel,+ to,+ params+}: StatCardProps) => {+ const navigate = useNavigate();+ return (+ <Card className="flex-1">+ <CardHeader>+ <CardTitle>{title}</CardTitle>+ <CardAction>+ <div+ className={cn(+ "flex size-9 items-center justify-center rounded-md border [&>svg]:size-5",+ iconVariant === "info" && "border-info/15 bg-info/10 text-info",+ iconVariant === "warning" && "border-warning/15 bg-warning/10 text-warning",+ iconVariant === "success" && "border-success/15 bg-success/10 text-success",+ iconVariant === "danger" && "border-danger/15 bg-danger/10 text-danger"+ )}+ >+ {icon}+ </div>+ </CardAction>+ </CardHeader>+ <CardContent className="flex flex-col gap-3">+ <div>+ <span className="text-2xl font-semibold">{count.toLocaleString()}</span>+ <span className="ml-2 text-sm text-muted">{subtitle}</span>+ </div>+ <Separator />+ <div className="flex min-h-7 items-center justify-between">+ {typeof footnote === "string" ? (+ <Badge variant={footnoteVariant}>+ {renderFootnoteIcon(footnoteVariant)}+ {footnote}+ </Badge>+ ) : (+ footnote+ )}+ {viewLabel && to && params && (+ <Button+ variant="outline"+ size="xs"+ disabled={count === 0}+ onClick={() => navigate({ to, params })}+ >+ {viewLabel}+ </Button>+ )}+ </div>+ </CardContent>+ </Card>+ );+};++export const PamInsightsKpiCards = () => {+ const { currentOrg } = useOrganization();+ const { projectId } = useProject();+ const { data, isPending } = useGetPamInsightsSummary({ projectId }, { enabled: !!projectId });+ const params = { orgId: currentOrg.id, projectId };++ if (isPending) {+ return (+ <div className="flex flex-col gap-6 xl:flex-row">+ <Skeleton className="h-[183px] flex-1" />+ <Skeleton className="h-[183px] flex-1" />+ <Skeleton className="h-[183px] flex-1" />+ </div>+ );+ }++ const totalResources = data?.totalResources ?? 0;+ const resourcesWithRotation = data?.resourcesWithRotation ?? 0;+ const totalAccounts = data?.totalAccounts ?? 0;+ const failedRotations = data?.failedRotations ?? 0;+ const activeSessions = data?.activeSessions ?? 0;+ const resourceTypeCount = data?.resourceTypeCount ?? 0;++ const resourcesFootnote = computeResourcesFootnote(totalResources, resourcesWithRotation);+ const accountsFootnote = computeAccountsFootnote(totalAccounts, failedRotations);++ return (+ <div className="flex flex-col gap-6 xl:flex-row">+ <StatCard+ title="Total Resources"+ icon={<DatabaseIcon />}+ iconVariant="info"+ count={totalResources}+ subtitle={`Across ${resourceTypeCount} resource types`}+ footnote={resourcesFootnote.text}+ footnoteVariant={resourcesFootnote.variant}+ viewLabel="View Resources"+ to="/organizations/$orgId/projects/pam/$projectId/resources"+ params={params}+ />+ <StatCard+ title="Total Accounts"+ icon={<KeyRoundIcon />}+ iconVariant="warning"+ count={totalAccounts}+ subtitle="Privileged credentials"+ footnote={accountsFootnote.text}+ footnoteVariant={accountsFootnote.variant}+ />+ <StatCard+ title="Active Sessions"+ icon={<ActivityIcon />}+ iconVariant="success"+ count={activeSessions}+ subtitle="Currently live"+ footnote={activeSessions > 0 ? <LiveBadge count={activeSessions} /> : "No active sessions"}+ footnoteVariant="info"+ viewLabel="View Sessions"+ to="/organizations/$orgId/projects/pam/$projectId/sessions"+ params={params}+ />+ </div>+ );+};diff --git a/frontend/src/pages/pam/InsightsPage/components/PamResourceBreakdown.tsx b/frontend/src/pages/pam/InsightsPage/components/PamResourceBreakdown.tsxnew file mode 100644index 0000000000..e0f324cbd8--- /dev/null+++ b/frontend/src/pages/pam/InsightsPage/components/PamResourceBreakdown.tsx@@ -0,0 +1,101 @@+import { useMemo } from "react";++import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Empty,+ EmptyHeader,+ EmptyTitle,+ Skeleton+} from "@app/components/v3";+import { useProject } from "@app/context";+import { PamResourceType } from "@app/hooks/api/pam/enums";+import { PAM_RESOURCE_TYPE_MAP } from "@app/hooks/api/pam/maps";+import { useGetPamResourceBreakdown } from "@app/hooks/api/pamInsights";++const knownResourceTypes = Object.values(PamResourceType) as string[];++export const PamResourceBreakdown = () => {+ const { projectId } = useProject();+ const { data, isPending } = useGetPamResourceBreakdown({ projectId }, { enabled: !!projectId });++ const rows = useMemo(() => {+ if (!data?.breakdown) return [];+ const max = Math.max(...data.breakdown.map((r) => r.resourceCount), 1);+ return data.breakdown.map((entry) => {+ const meta = knownResourceTypes.includes(entry.resourceType)+ ? PAM_RESOURCE_TYPE_MAP[entry.resourceType as PamResourceType]+ : null;+ return {+ ...entry,+ displayName: meta?.name ?? entry.resourceType,+ image: meta?.image ?? null,+ widthPct: Math.max(2, Math.round((entry.resourceCount / max) * 100))+ };+ });+ }, [data]);++ const renderBody = () => {+ if (isPending) return <Skeleton className="h-[280px] w-full" />;+ if (!rows.length) {+ return (+ <Empty className="border-0">+ <EmptyHeader>+ <EmptyTitle>No resources have been added yet</EmptyTitle>+ </EmptyHeader>+ </Empty>+ );+ }+ return (+ <ul className="flex flex-col divide-y divide-border/60">+ {rows.map((row) => (+ <li+ key={row.resourceType}+ className="flex items-center justify-between gap-4 py-3 first:pt-0 last:pb-0"+ >+ <div className="flex min-w-0 flex-1 items-center gap-3">+ {row.image ? (+ <img+ src={`/images/integrations/${row.image}`}+ alt={row.displayName}+ className="size-5 shrink-0 object-contain"+ />+ ) : (+ <span className="size-5 shrink-0 rounded-sm bg-border" />+ )}+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <span className="truncate font-medium">{row.displayName}</span>+ <div className="h-1.5 w-full max-w-[200px] overflow-hidden rounded-full bg-border/40">+ <div+ className="h-full rounded-full bg-primary"+ style={{ width: `${row.widthPct}%` }}+ />+ </div>+ </div>+ </div>+ <div className="flex shrink-0 items-baseline gap-1.5 text-sm">+ <span className="font-semibold">{row.resourceCount.toLocaleString()}</span>+ <span className="text-muted">resources</span>+ <span className="text-muted">·</span>+ <span className="font-semibold">{row.accountCount.toLocaleString()}</span>+ <span className="text-muted">accounts</span>+ </div>+ </li>+ ))}+ </ul>+ );+ };++ return (+ <Card className="h-full">+ <CardHeader>+ <CardTitle>Resources & Accounts by Type</CardTitle>+ <CardDescription>Breakdown of managed resources across integrations</CardDescription>+ </CardHeader>+ <CardContent>{renderBody()}</CardContent>+ </Card>+ );+};diff --git a/frontend/src/pages/pam/InsightsPage/components/PamSessionActivityChart.tsx b/frontend/src/pages/pam/InsightsPage/components/PamSessionActivityChart.tsxnew file mode 100644index 0000000000..14800ffb7c--- /dev/null+++ b/frontend/src/pages/pam/InsightsPage/components/PamSessionActivityChart.tsx@@ -0,0 +1,140 @@+import { useMemo } from "react";+import { format, parseISO } from "date-fns";+import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";++import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Empty,+ EmptyHeader,+ EmptyTitle,+ Skeleton+} from "@app/components/v3";+import { useProject } from "@app/context";+import { useGetPamSessionActivity } from "@app/hooks/api/pamInsights";++type ChartPoint = {+ date: string;+ count: number;+ label: string;+ showTickLabel: string | null;+};++const buildAxisTicks = (data: ChartPoint[]): string[] => {+ if (!data.length) return [];+ const ticks: string[] = [];+ data.forEach((point, index) => {+ if (index === 0 || index === data.length - 1) {+ ticks.push(point.date);+ return;+ }+ if (index % 7 === 0) ticks.push(point.date);+ });+ return ticks;+};++export const PamSessionActivityChart = () => {+ const { projectId } = useProject();+ const { data, isPending } = useGetPamSessionActivity({ projectId }, { enabled: !!projectId });++ const chartData = useMemo<ChartPoint[]>(() => {+ if (!data?.days) return [];+ return data.days.map((day, index, days) => {+ const isLast = index === days.length - 1;+ const isFirst = index === 0;+ const parsed = parseISO(day.date);+ let tickLabel: string | null = null;+ if (isLast) tickLabel = "Today";+ else if (isFirst || index % 7 === 0) tickLabel = format(parsed, "MMM d");+ return {+ date: day.date,+ count: day.count,+ label: format(parsed, "MMM d"),+ showTickLabel: tickLabel+ };+ });+ }, [data]);++ const ticks = useMemo(() => buildAxisTicks(chartData), [chartData]);+ const totalSessions = chartData.reduce((sum, d) => sum + d.count, 0);+ const hasAnyData = totalSessions > 0;++ const renderBody = () => {+ if (isPending) return <Skeleton className="h-[280px] w-full" />;+ if (!hasAnyData) {+ return (+ <Empty className="border-0">+ <EmptyHeader>+ <EmptyTitle>No sessions in the last 30 days</EmptyTitle>+ </EmptyHeader>+ </Empty>+ );+ }+ return (+ <div className="flex flex-col gap-4 [&_*:focus]:outline-none [&_*]:focus:outline-none">+ <ResponsiveContainer width="100%" height={280}>+ <BarChart data={chartData} margin={{ top: 8, right: 8, bottom: 0, left: -16 }}>+ <CartesianGrid strokeDasharray="4 4" stroke="var(--color-border)" vertical={false} />+ <XAxis+ dataKey="date"+ ticks={ticks}+ tickFormatter={(date: string) => {+ const point = chartData.find((p) => p.date === date);+ return point?.showTickLabel ?? "";+ }}+ tick={{ fontSize: 11, fill: "var(--color-label)" }}+ axisLine={false}+ tickLine={false}+ />+ <YAxis+ tick={{ fontSize: 11, fill: "var(--color-label)" }}+ axisLine={false}+ tickLine={false}+ allowDecimals={false}+ />+ <Tooltip+ contentStyle={{+ backgroundColor: "var(--color-popover)",+ border: "1px solid var(--color-border)",+ borderRadius: 8,+ fontSize: 12+ }}+ labelStyle={{ color: "var(--color-foreground)" }}+ itemStyle={{ color: "var(--color-primary)" }}+ cursor={false}+ isAnimationActive={false}+ labelFormatter={(date: string) => {+ const point = chartData.find((p) => p.date === date);+ return point?.label ?? String(date);+ }}+ formatter={(value: number) => [Number(value).toLocaleString(), "Sessions"]}+ />+ <Bar+ dataKey="count"+ fill="var(--color-primary)"+ radius={[2, 2, 0, 0]}+ style={{ outline: "none" }}+ />+ </BarChart>+ </ResponsiveContainer>+ <span className="text-xs text-muted">+ {totalSessions.toLocaleString()} sessions in the last 30 days ·{" "}+ {(data?.avgPerDay ?? 0).toLocaleString()} per day on average+ </span>+ </div>+ );+ };++ return (+ <Card className="h-full">+ <CardHeader>+ <CardTitle>Session Activity</CardTitle>+ <CardDescription>Privileged sessions started over the past 30 days</CardDescription>+ </CardHeader>+ <CardContent>{renderBody()}</CardContent>+ </Card>+ );+};diff --git a/frontend/src/pages/pam/InsightsPage/components/PamTopActors.tsx b/frontend/src/pages/pam/InsightsPage/components/PamTopActors.tsxnew file mode 100644index 0000000000..0a97d6ab42--- /dev/null+++ b/frontend/src/pages/pam/InsightsPage/components/PamTopActors.tsx@@ -0,0 +1,121 @@+import { useNavigate } from "@tanstack/react-router";+import { ExternalLinkIcon } from "lucide-react";++import {+ Badge,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Empty,+ EmptyHeader,+ EmptyTitle,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import { useOrganization, useProject } from "@app/context";+import { useGetPamTopActors } from "@app/hooks/api/pamInsights";++const sessionsRoute = "/organizations/$orgId/projects/pam/$projectId/sessions" as const;++export const PamTopActors = () => {+ const { currentOrg } = useOrganization();+ const { projectId } = useProject();+ const { data, isPending } = useGetPamTopActors({ projectId }, { enabled: !!projectId });+ const navigate = useNavigate();++ const totalSessions = data?.actors.reduce((sum, a) => sum + a.sessionCount, 0) ?? 0;+ const uniqueActors = data?.actors.length ?? 0;++ const renderBody = () => {+ if (isPending) return <Skeleton className="h-[280px] w-full" />;+ if (!data?.actors.length) {+ return (+ <Empty className="border-0">+ <EmptyHeader>+ <EmptyTitle>No session activity yet</EmptyTitle>+ </EmptyHeader>+ </Empty>+ );+ }+ return (+ <Table containerClassName="max-h-72">+ <TableHeader className="sticky top-0 z-10 bg-container shadow-[inset_0_-1px_0_var(--color-border)]">+ <TableRow>+ <TableHead className="w-8" />+ <TableHead>Actor</TableHead>+ <TableHead>Type</TableHead>+ <TableHead className="text-right">Sessions</TableHead>+ <TableHead className="w-8" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {data.actors.map((actor, index) => (+ <TableRow+ key={`${actor.actorEmail}:${actor.actorName}`}+ className="[&>td]:h-auto [&>td]:py-2"+ onClick={() =>+ navigate({+ to: sessionsRoute,+ params: { orgId: currentOrg.id, projectId },+ search: { search: actor.actorEmail || actor.actorName || undefined }+ })+ }+ >+ <TableCell className="text-muted">{index + 1}</TableCell>+ <TableCell className="font-medium">+ <div className="flex flex-col">+ <span className="truncate" title={actor.actorName}>+ {actor.actorName || actor.actorEmail || "Unknown"}+ </span>+ <span className="truncate text-xs text-muted" title={actor.actorEmail}>+ {actor.isService ? "machine identity" : actor.actorEmail}+ </span>+ </div>+ </TableCell>+ <TableCell>+ {actor.isService ? (+ <Badge variant="info">identity</Badge>+ ) : (+ <Badge variant="warning">user</Badge>+ )}+ </TableCell>+ <TableCell className="text-right font-medium">+ {actor.sessionCount.toLocaleString()}+ </TableCell>+ <TableCell className="w-8 px-2">+ <ExternalLinkIcon className="size-3.5 text-muted" />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ );+ };++ return (+ <Card className="h-full">+ <CardHeader>+ <CardTitle>Top Actors</CardTitle>+ <CardDescription>+ Users & identities initiating the most privileged sessions over the past 30 days+ </CardDescription>+ </CardHeader>+ <CardContent className="flex flex-1 flex-col justify-between gap-4">+ {renderBody()}+ {!isPending && uniqueActors > 0 && (+ <span className="text-xs text-muted">+ {uniqueActors} unique {uniqueActors === 1 ? "actor" : "actors"} ·{" "}+ {totalSessions.toLocaleString()} total sessions in the last 30 days+ </span>+ )}+ </CardContent>+ </Card>+ );+};diff --git a/frontend/src/pages/pam/InsightsPage/components/PamUpcomingRotations.tsx b/frontend/src/pages/pam/InsightsPage/components/PamUpcomingRotations.tsxnew file mode 100644index 0000000000..8bf41f8b2d--- /dev/null+++ b/frontend/src/pages/pam/InsightsPage/components/PamUpcomingRotations.tsx@@ -0,0 +1,138 @@+import { useMemo } from "react";+import { useNavigate } from "@tanstack/react-router";+import { formatDistanceToNow, parseISO } from "date-fns";+import { ExternalLinkIcon } from "lucide-react";++import {+ Badge,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Empty,+ EmptyHeader,+ EmptyTitle,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import { useOrganization, useProject } from "@app/context";+import { PamResourceType } from "@app/hooks/api/pam/enums";+import { PAM_RESOURCE_TYPE_MAP } from "@app/hooks/api/pam/maps";+import { useGetPamUpcomingRotations } from "@app/hooks/api/pamInsights";++const knownResourceTypes = Object.values(PamResourceType) as string[];++const accountRoute =+ "/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId" as const;++export const PamUpcomingRotations = () => {+ const { currentOrg } = useOrganization();+ const { projectId } = useProject();+ const { data, isPending } = useGetPamUpcomingRotations({ projectId }, { enabled: !!projectId });+ const navigate = useNavigate();++ const rows = useMemo(() => {+ if (!data?.rotations) return [];+ return data.rotations.map((r) => {+ const meta = knownResourceTypes.includes(r.resourceType)+ ? PAM_RESOURCE_TYPE_MAP[r.resourceType as PamResourceType]+ : null;+ return {+ ...r,+ displayType: meta?.name ?? r.resourceType,+ image: meta?.image ?? null+ };+ });+ }, [data]);++ const renderBody = () => {+ if (isPending) return <Skeleton className="h-[280px] w-full" />;+ if (!rows.length) {+ return (+ <Empty className="border-0">+ <EmptyHeader>+ <EmptyTitle>No rotations scheduled</EmptyTitle>+ </EmptyHeader>+ </Empty>+ );+ }+ return (+ <Table containerClassName="max-h-72">+ <TableHeader className="sticky top-0 z-10 bg-container shadow-[inset_0_-1px_0_var(--color-border)]">+ <TableRow>+ <TableHead>Resource</TableHead>+ <TableHead>Account</TableHead>+ <TableHead>Type</TableHead>+ <TableHead>Next Rotation</TableHead>+ <TableHead className="w-8" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.map((row) => (+ <TableRow+ key={row.accountId}+ onClick={() =>+ navigate({+ to: accountRoute,+ params: {+ orgId: currentOrg.id,+ projectId,+ resourceType: row.resourceType,+ resourceId: row.resourceId,+ accountId: row.accountId+ }+ })+ }+ >+ <TableCell className="max-w-[140px] truncate font-medium" title={row.resourceName}>+ {row.resourceName}+ </TableCell>+ <TableCell className="max-w-[120px] truncate text-muted" title={row.accountName}>+ {row.accountName}+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-1.5">+ {row.image && (+ <img+ src={`/images/integrations/${row.image}`}+ alt={row.displayType}+ className="size-3.5 shrink-0 object-contain"+ />+ )}+ <span className="text-xs text-muted">{row.displayType}</span>+ </div>+ </TableCell>+ <TableCell>+ <Badge variant="warning">+ {formatDistanceToNow(parseISO(row.nextRotationAt), { addSuffix: true })}+ </Badge>+ </TableCell>+ <TableCell className="w-8 px-2">+ <ExternalLinkIcon className="size-3.5 text-muted" />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ );+ };++ return (+ <Card className="h-full">+ <CardHeader>+ <CardTitle>Account credentials due to rotate</CardTitle>+ <CardDescription>+ {data?.totalScheduled ?? 0} scheduled rotation+ {data?.totalScheduled === 1 ? "" : "s"} across this project+ </CardDescription>+ </CardHeader>+ <CardContent>{renderBody()}</CardContent>+ </Card>+ );+};diff --git a/frontend/src/pages/pam/InsightsPage/components/index.ts b/frontend/src/pages/pam/InsightsPage/components/index.tsnew file mode 100644index 0000000000..2cb1aa98fd--- /dev/null+++ b/frontend/src/pages/pam/InsightsPage/components/index.ts@@ -0,0 +1,5 @@+export { PamInsightsKpiCards } from "./PamInsightsKpiCards";+export { PamResourceBreakdown } from "./PamResourceBreakdown";+export { PamSessionActivityChart } from "./PamSessionActivityChart";+export { PamTopActors } from "./PamTopActors";+export { PamUpcomingRotations } from "./PamUpcomingRotations";diff --git a/frontend/src/pages/pam/InsightsPage/route.tsx b/frontend/src/pages/pam/InsightsPage/route.tsxnew file mode 100644index 0000000000..b72cb098e7--- /dev/null+++ b/frontend/src/pages/pam/InsightsPage/route.tsx@@ -0,0 +1,19 @@+import { createFileRoute } from "@tanstack/react-router";++import { InsightsPage } from "./InsightsPage";++export const Route = createFileRoute(+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/insights"+)({+ component: InsightsPage,+ beforeLoad: ({ context }) => {+ return {+ breadcrumbs: [+ ...context.breadcrumbs,+ {+ label: "Insights"+ }+ ]+ };+ }+});diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsxindex 3c0f09fb6b..129fe5ff58 100644--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx@@ -28,6 +28,7 @@ import {ProjectPermissionPamAccountActions,ProjectPermissionPamAccountPolicyActions,ProjectPermissionPamDiscoveryActions,+ ProjectPermissionPamInsightsActions,ProjectPermissionPamSessionActions,ProjectPermissionPkiCertificateInstallationActions,ProjectPermissionPkiDiscoveryActions,@@ -266,6 +267,10 @@ const PamDiscoveryPolicyActionSchema = z.object({[ProjectPermissionPamDiscoveryActions.Delete]: z.boolean().optional()});+const PamInsightsPolicyActionSchema = z.object({+ [ProjectPermissionPamInsightsActions.Read]: z.boolean().optional()+});+const McpEndpointPolicyActionSchema = z.object({[ProjectPermissionMcpEndpointActions.Read]: z.boolean().optional(),[ProjectPermissionMcpEndpointActions.Create]: z.boolean().optional(),@@ -825,6 +830,7 @@ export const projectRoleFormSchema = z.object({[]),[ProjectPermissionSub.PamDiscovery]: PamDiscoveryPolicyActionSchema.array().default([]),+ [ProjectPermissionSub.PamInsights]: PamInsightsPolicyActionSchema.array().default([]),[ProjectPermissionSub.McpEndpoints]: McpEndpointPolicyActionSchema.extend({inverted: z.boolean().optional(),conditions: ConditionSchema@@ -1835,6 +1841,14 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {if (canTerminate) formVal[subject]![0][ProjectPermissionPamSessionActions.Terminate] = true;}+ if (subject === ProjectPermissionSub.PamInsights) {+ const canRead = action.includes(ProjectPermissionPamInsightsActions.Read);++ if (!formVal[subject]) formVal[subject] = [{}];++ if (canRead) formVal[subject]![0][ProjectPermissionPamInsightsActions.Read] = true;+ }+if (subject === ProjectPermissionSub.PamAccountPolicies) {const canRead = action.includes(ProjectPermissionPamAccountPolicyActions.Read);const canCreate = action.includes(ProjectPermissionPamAccountPolicyActions.Create);@@ -3309,6 +3323,18 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {}]},+ [ProjectPermissionSub.PamInsights]: {+ title: "Insights",+ description: "View the PAM insights dashboard",+ actions: [+ {+ label: "Read",+ value: ProjectPermissionPamInsightsActions.Read,+ description:+ "View the PAM insights dashboard"+ }+ ]+ },[ProjectPermissionSub.ApprovalRequests]: {title: "Access Requests",description: "View and submit access requests",@@ -3490,7 +3516,8 @@ const PamPermissionSubjects = (enabled = false) => ({[ProjectPermissionSub.PamAccounts]: enabled,[ProjectPermissionSub.PamSessions]: enabled,[ProjectPermissionSub.PamAccountPolicies]: enabled,- [ProjectPermissionSub.PamDiscovery]: enabled+ [ProjectPermissionSub.PamDiscovery]: enabled,+ [ProjectPermissionSub.PamInsights]: enabled});const AiPermissionSubjects = (enabled = false) => ({diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex d17988e1ad..126361ec59 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -404,6 +404,7 @@ const pamRoutes = route("/organizations/$orgId/projects/pam/$projectId", [route("/$discoveryType/$discoverySourceId", "pam/PamDiscoveryDetailPage/route.tsx")]),route("/audit-logs", "project/AuditLogsPage/route-pam.tsx"),+ route("/insights", "pam/InsightsPage/route.tsx"),route("/settings", "pam/SettingsPage/route.tsx"),route("/account-policies", "pam/PamAccountPoliciesPage/route.tsx"),route("/approvals", [