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
"session recording, web access, and dead code cleanup
x032205b285117ad17c
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 0249922536..d15f830b5a 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -279,6 +279,8 @@ Enterprise code lives in `src/ee/`:EE routes register before community routes so they can override/extend endpoints. Feature gating via license service (`src/ee/services/license/license-service.ts`) which validates online/offline licenses, caches feature sets in keystore with 5-minute TTL, and exposes `getPlan()` to check feature availability.+**PAM**: Before working on any `pam-*` service or router, read [`src/ee/services/pam/CLAUDE.md`](src/ee/services/pam/CLAUDE.md). It documents the permission model, shared helpers, account type checklist, and session lifecycle. Any new PAM core logic or helpers must be documented there.+### Server PluginsKey plugins in `src/server/plugins/`:diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex f53cb4a6c0..9eb69a1c1c 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -38,6 +38,8 @@ import { TPamAccountTemplateServiceFactory } from "@app/ee/services/pam-account-import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";import { TPamProjectResolverFactory } from "@app/ee/services/pam-instance/pam-project-resolver";import { TPamMembershipServiceFactory } from "@app/ee/services/pam-membership/pam-membership-service";+import { TPamSessionChunkServiceFactory } from "@app/ee/services/pam-session/pam-session-chunk-service";+import { TPamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";import { TPamWebAccessServiceFactory } from "@app/ee/services/pam-web-access/pam-web-access-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { TPitServiceFactory } from "@app/ee/services/pit/pit-service";@@ -413,6 +415,8 @@ declare module "fastify" {pamFolder: TPamFolderServiceFactory;pamAccount: TPamAccountServiceFactory;pamMembership: TPamMembershipServiceFactory;+ pamSession: TPamSessionServiceFactory;+ pamSessionChunk: TPamSessionChunkServiceFactory;pamWebAccess: TPamWebAccessServiceFactory;mfaSession: TMfaSessionServiceFactory;membershipUser: TMembershipUserServiceFactory;diff --git a/backend/src/db/migrations/20260603030053_pam-revamp.ts b/backend/src/db/migrations/20260603030053_pam-revamp.tsindex b72fc2aec7..5c584b5258 100644--- a/backend/src/db/migrations/20260603030053_pam-revamp.ts+++ b/backend/src/db/migrations/20260603030053_pam-revamp.ts@@ -488,6 +488,7 @@ export async function up(knex: Knex): Promise<void> {await knex.schema.alterTable(TableName.PamSession, (t) => {t.renameColumn("resourceType", "accountType");+ t.string("resourceName").nullable().alter();});}diff --git a/backend/src/db/schemas/pam-sessions.ts b/backend/src/db/schemas/pam-sessions.tsindex 26b8d99941..7d6ac6e9b6 100644--- a/backend/src/db/schemas/pam-sessions.ts+++ b/backend/src/db/schemas/pam-sessions.ts@@ -14,7 +14,7 @@ export const PamSessionsSchema = z.object({projectId: z.string(),accountId: z.string().uuid().nullable().optional(),accountType: z.string(),- resourceName: z.string(),+ resourceName: z.string().nullable().optional(),accountName: z.string(),userId: z.string().uuid().nullable().optional(),actorName: z.string(),diff --git a/backend/src/ee/routes/v1/pam-routers/index.ts b/backend/src/ee/routes/v1/pam-routers/index.tsindex b968b2fd98..aa6c24f155 100644--- a/backend/src/ee/routes/v1/pam-routers/index.ts+++ b/backend/src/ee/routes/v1/pam-routers/index.ts@@ -3,6 +3,7 @@ import { registerPamAccountTemplateRouter } from "./pam-account-template-router"import { registerPamFolderRouter } from "./pam-folder-router";import { registerPamMembershipRouter } from "./pam-membership-router";import { registerPamResourceRoleRouter } from "./pam-resource-role-router";+import { registerPamSessionChunkRouter } from "./pam-session-chunk-router";import { registerPamSessionRouter } from "./pam-session-router";export const registerPamRouters = async (server: FastifyZodProvider) => {@@ -12,4 +13,5 @@ export const registerPamRouters = async (server: FastifyZodProvider) => {await server.register(registerPamMembershipRouter, { prefix: "/members" });await server.register(registerPamResourceRoleRouter, { prefix: "/resource-roles" });await server.register(registerPamSessionRouter, { prefix: "/sessions" });+ await server.register(registerPamSessionChunkRouter, { prefix: "/sessions" });};diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-router.tsindex aae10a9a2a..c8b9e85d5c 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts@@ -170,34 +170,6 @@ const registerPerTypeEndpoints = (}});- server.route({- method: "GET",- url: "/:accountId",- schema: {- operationId: `get${typeId}PamAccount`,- params: z.object({ accountId: z.string().uuid() }),- response: {- 200: SanitizedAccountListItemSchema.extend({- templateAccessPolicy: z.unknown().nullable().optional(),- templateSettings: z.unknown().nullable().optional(),- connectionDetails: z.unknown()- })- }- },- config: { rateLimit: readLimit },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- return server.services.pamAccount.getById({- accountId: req.params.accountId,- projectId: req.internalPamProjectId,- actorId: req.permission.id,- actor: req.permission.type,- actorOrgId: req.permission.orgId,- actorAuthMethod: req.permission.authMethod- });- }- });-server.route({method: "DELETE",url: "/:accountId",@@ -317,6 +289,34 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "GET",+ url: "/:accountId",+ schema: {+ operationId: "getPamAccount",+ params: z.object({ accountId: z.string().uuid() }),+ response: {+ 200: SanitizedAccountListItemSchema.extend({+ templateAccessPolicy: z.unknown().nullable().optional(),+ templateSettings: z.unknown().nullable().optional(),+ connectionDetails: z.unknown()+ })+ }+ },+ config: { rateLimit: readLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ return server.services.pamAccount.getById({+ accountId: req.params.accountId,+ projectId: req.internalPamProjectId,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });+ }+ });+await Promise.all((Object.entries(ACCOUNT_TYPE_CONFIGS) as [TSupportedAccountType, TSupportedConfigValue][]).map(([accountType, config]) =>diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.tsindex 2023c6a8f3..6569e7a9d8 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts@@ -6,7 +6,7 @@ import { PamAccountType } from "@app/ee/services/pam/pam-enums";import {PamTemplateAccessPolicySchema,PamTemplateSettingsSchema-} from "@app/ee/services/pam/pam-template-config-schemas";+} from "@app/ee/services/pam-account-template/pam-template-config-schemas";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";diff --git a/backend/src/ee/routes/v1/pam-routers/pam-session-chunk-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-session-chunk-router.tsnew file mode 100644index 0000000000..73b013c8f9--- /dev/null+++ b/backend/src/ee/routes/v1/pam-routers/pam-session-chunk-router.ts@@ -0,0 +1,246 @@+import { z } from "zod";++import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { PamRecordingStorageBackend } from "@app/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums";+import { BadRequestError } from "@app/lib/errors";+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";++const GATEWAY_TOKEN_HEADER = "x-gateway-upload-token";++const ChunkPlaybackSchema = z.object({+ chunkIndex: z.number().int().nonnegative().max(999999),+ startElapsedMs: z.number(),+ endElapsedMs: z.number(),+ storageBackend: z.nativeEnum(PamRecordingStorageBackend),+ externalChunkObjectKey: z.string().nullable(),+ ciphertextSha256: z.string(),+ ciphertextBytes: z.number(),+ iv: z.string(),+ presignedGetUrl: z.string().nullable()+});++export const registerPamSessionChunkRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "POST",+ url: "/:sessionId/chunks/presigned-put",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "pamSessionChunkPresignedPut",+ params: z.object({ sessionId: z.string().uuid() }),+ body: z.object({+ chunkIndex: z.number().int().nonnegative().max(999999),+ ciphertextBytes: z.number().int().positive(),+ isKeyframe: z.boolean().optional()+ }),+ response: {+ 200: z.object({+ url: z.string(),+ objectKey: z.string(),+ method: z.literal("PUT"),+ expiresInSeconds: z.number()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),+ handler: async (req) => {+ const uploadToken = req.headers[GATEWAY_TOKEN_HEADER];+ if (typeof uploadToken !== "string" || !uploadToken) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ event: {+ type: EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,+ metadata: { sessionId: req.params.sessionId, chunkIndex: req.body.chunkIndex }+ }+ });+ throw new BadRequestError({+ message: `Missing ${GATEWAY_TOKEN_HEADER} header: required for chunk upload`+ });+ }++ try {+ return await server.services.pamSessionChunk.requestPresignedPut(+ {+ sessionId: req.params.sessionId,+ chunkIndex: req.body.chunkIndex,+ ciphertextBytes: req.body.ciphertextBytes,+ isKeyframe: req.body.isKeyframe,+ uploadToken+ },+ req.permission+ );+ } catch (err) {+ const msg = (err as Error)?.message ?? "";+ if (msg.includes("Invalid upload token")) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ event: {+ type: EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,+ metadata: { sessionId: req.params.sessionId, chunkIndex: req.body.chunkIndex }+ }+ });+ }+ throw err;+ }+ }+ });++ server.route({+ method: "POST",+ url: "/:sessionId/chunks",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "pamSessionRecordChunk",+ params: z.object({ sessionId: z.string().uuid() }),+ body: z.object({+ chunkIndex: z.number().int().nonnegative().max(999999),+ startElapsedMs: z.number(),+ endElapsedMs: z.number(),+ ciphertextSha256: z.string(),+ ciphertextBytes: z.number().int().positive(),+ iv: z.string(),+ keyframeObjectKey: z.string().nullable().optional(),+ keyframeSizeBytes: z.number().int().nonnegative().nullable().optional(),+ ciphertext: z.string().optional()+ }),+ response: {+ 200: z.object({+ ok: z.literal(true),+ storageBackend: z.string()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),+ handler: async (req) => {+ const uploadToken = req.headers[GATEWAY_TOKEN_HEADER];+ if (typeof uploadToken !== "string" || !uploadToken) {+ throw new BadRequestError({+ message: `Missing ${GATEWAY_TOKEN_HEADER} header: required for chunk upload`+ });+ }++ let ciphertextBuf: Buffer | undefined;+ if (req.body.ciphertext) {+ const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;+ if (!BASE64_RE.test(req.body.ciphertext)) {+ throw new BadRequestError({ message: "ciphertext must be valid base64" });+ }+ ciphertextBuf = Buffer.from(req.body.ciphertext, "base64");+ }++ const result = await server.services.pamSessionChunk.recordChunk(+ {+ sessionId: req.params.sessionId,+ chunkIndex: req.body.chunkIndex,+ startElapsedMs: req.body.startElapsedMs,+ endElapsedMs: req.body.endElapsedMs,+ ciphertextSha256Base64: req.body.ciphertextSha256,+ ciphertextBytes: req.body.ciphertextBytes,+ ivBase64: req.body.iv,+ keyframeObjectKey: req.body.keyframeObjectKey ?? undefined,+ keyframeSizeBytes: req.body.keyframeSizeBytes ?? undefined,+ ciphertext: ciphertextBuf,+ uploadToken+ },+ req.permission+ );++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: result.projectId,+ event: {+ type: EventType.PAM_SESSION_CHUNK_UPLOAD,+ metadata: {+ sessionId: req.params.sessionId,+ chunkIndex: req.body.chunkIndex,+ storageBackend: result.storageBackend,+ ciphertextBytes: req.body.ciphertextBytes+ }+ }+ });++ return { ok: true as const, storageBackend: result.storageBackend };+ }+ });++ server.route({+ method: "GET",+ url: "/:sessionId/playback",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "pamSessionPlayback",+ params: z.object({ sessionId: z.string().uuid() }),+ response: {+ 200: z.object({+ legacy: z.boolean(),+ sessionComplete: z.boolean(),+ sessionKey: z.string().nullable(),+ projectId: z.string().optional(),+ storageBackend: z.string().optional(),+ chunks: z.array(ChunkPlaybackSchema)+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const result = await server.services.pamSessionChunk.getPlaybackBundle(req.params.sessionId, req.permission);+ if (result.legacy) {+ return { legacy: true, sessionComplete: result.sessionComplete, sessionKey: null, chunks: [] };+ }+ return {+ legacy: false,+ sessionComplete: result.sessionComplete,+ sessionKey: result.sessionKey,+ projectId: result.projectId,+ storageBackend: result.storageBackend,+ chunks: result.chunks+ };+ }+ });++ server.route({+ method: "GET",+ url: "/:sessionId/chunks/:chunkIndex/ciphertext",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "pamSessionChunkCiphertext",+ params: z.object({+ sessionId: z.string().uuid(),+ chunkIndex: z.coerce.number().int().nonnegative().max(999999)+ })+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req, reply) => {+ const { ciphertext } = await server.services.pamSessionChunk.getChunkCiphertext(+ req.params.sessionId,+ req.params.chunkIndex,+ req.permission+ );+ void reply.header("Content-Type", "application/octet-stream");+ void reply.header("Cache-Control", "no-store");+ return reply.send(ciphertext);+ }+ });++ server.route({+ method: "GET",+ url: "/recording-storage-backends",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "pamSessionRecordingStorageBackends",+ response: {+ 200: z.object({+ backends: z.array(z.string())+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),+ handler: async () => ({+ backends: Object.values(PamRecordingStorageBackend)+ })+ });+};diff --git a/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-session-router.tsindex 83ed1dbced..d494cc04ad 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts@@ -1,7 +1,9 @@import type WebSocket from "ws";import z from "zod";-import { UserAgentType } from "@app/ee/services/audit-log/audit-log-types";+import { PamSessionsSchema } from "@app/db/schemas";+import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";+import { PamRecordingStorageBackend } from "@app/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums";import { BadRequestError } from "@app/lib/errors";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";@@ -10,7 +12,87 @@ import { ActorType, AuthMode } from "@app/services/auth/auth-type";import { TokenType } from "@app/services/auth-token/auth-token-types";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";+const SanitizedSessionSchema = PamSessionsSchema.pick({+ id: true,+ projectId: true,+ accountId: true,+ accountType: true,+ accountName: true,+ userId: true,+ actorName: true,+ actorEmail: true,+ actorIp: true,+ actorUserAgent: true,+ status: true,+ expiresAt: true,+ startedAt: true,+ endedAt: true,+ createdAt: true,+ updatedAt: true,+ accessMethod: true,+ reason: true,+ gatewayId: true,+ folderName: true,+ selectedHost: true+}).extend({+ gatewayName: z.string().nullable().optional(),+ gatewayIdentityId: z.string().nullable().optional()+});+export const registerPamSessionRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "listPamSessions",+ querystring: z.object({+ projectId: z.string()+ }),+ response: {+ 200: z.object({ sessions: SanitizedSessionSchema.array() })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const sessions = await server.services.pamSession.listSessions(req.query.projectId, {+ actor: req.permission.type,+ actorId: req.permission.id,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });+ return { sessions };+ }+ });++ server.route({+ method: "GET",+ url: "/:sessionId",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getPamSession",+ params: z.object({+ sessionId: z.string().uuid()+ }),+ response: {+ 200: z.object({ session: SanitizedSessionSchema })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const session = await server.services.pamSession.getSessionById(req.params.sessionId, {+ actor: req.permission.type,+ actorId: req.permission.id,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });+ if (!session) {+ throw new BadRequestError({ message: "Session not found" });+ }+ return { session };+ }+ });+server.route({method: "POST",url: "/:accountId/web-access-ticket",@@ -128,6 +210,7 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {actorEmail: z.string(),actorName: z.string(),reason: z.string().nullable().optional(),+ maxSessionDurationMs: z.number().optional(),auditLogInfo: z.object({ipAddress: z.string().optional(),userAgent: z.string().optional(),@@ -161,6 +244,7 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {actorIp: req.realIp ?? "",actorUserAgent: req.headers["user-agent"] ?? "",reason: payload.reason,+ maxSessionDurationMs: payload.maxSessionDurationMs,preAuthMessages,preAuthHandler});@@ -173,4 +257,93 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {return { message: "WebSocket upgrade required" };}});++ server.route({+ method: "GET",+ url: "/:sessionId/credentials",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getPamSessionCredentials",+ params: z.object({+ sessionId: z.string().uuid()+ }),+ response: {+ 200: z.object({+ credentials: z.record(z.unknown()),+ recording: z+ .object({+ sessionKey: z.string(),+ uploadToken: z.string(),+ storageBackend: z.nativeEnum(PamRecordingStorageBackend),+ projectId: z.string(),+ sessionId: z.string()+ })+ .nullable()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.GATEWAY_ACCESS_TOKEN]),+ handler: async (req) => {+ const result = await server.services.pamSession.getSessionCredentials(req.params.sessionId, req.permission.id);++ if (result.sessionStarted) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: result.projectId,+ event: {+ type: EventType.PAM_SESSION_START,+ metadata: {+ sessionId: req.params.sessionId,+ accountName: result.accountName+ }+ }+ });+ }++ return {+ credentials: result.credentials,+ recording: result.recording+ };+ }+ });++ server.route({+ method: "POST",+ url: "/:sessionId/end",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "endPamSession",+ params: z.object({+ sessionId: z.string().uuid()+ }),+ response: {+ 200: z.object({ message: z.string() })+ }+ },+ onRequest: verifyAuth([AuthMode.GATEWAY_ACCESS_TOKEN]),+ handler: async (req) => {+ const { projectId, accountName, alreadyEnded } = await server.services.pamSession.endSessionFromGateway(+ req.params.sessionId,+ req.permission.id+ );++ if (!alreadyEnded) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId,+ event: {+ type: EventType.PAM_SESSION_END,+ metadata: {+ sessionId: req.params.sessionId,+ accountName+ }+ }+ });+ }++ return { message: "Session ended" };+ }+ });};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 1ad565feba..251c2160af 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -677,25 +677,10 @@ 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_ROTATION_CALENDAR = "view-insights-pam-rotation-calendar",-- PAM_SESSION_CREDENTIALS_GET = "pam-session-credentials-get",PAM_SESSION_START = "pam-session-start",- PAM_SESSION_LOGS_UPDATE = "pam-session-logs-update",PAM_SESSION_END = "pam-session-end",- PAM_SESSION_TERMINATE = "pam-session-terminate",- PAM_SESSION_GET = "pam-session-get",- PAM_SESSION_LIST = "pam-session-list",- PAM_SESSION_EVENT_BATCH_UPLOAD = "pam-session-event-batch-upload",PAM_SESSION_CHUNK_UPLOAD = "pam-session-chunk-upload",PAM_SESSION_UPLOAD_TOKEN_INVALID = "pam-session-upload-token-invalid",- PAM_RECORDING_CONFIG_UPDATE = "pam-recording-config-update",- PAM_RECORDING_CONFIG_DELETE = "pam-recording-config-delete",- PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED = "pam-recording-bucket-connection-test-failed",PAM_ACCOUNT_TEMPLATE_CREATE = "pam-account-template-create",PAM_ACCOUNT_TEMPLATE_UPDATE = "pam-account-template-update",PAM_ACCOUNT_TEMPLATE_DELETE = "pam-account-template-delete",@@ -711,21 +696,10 @@ export enum EventType {PAM_ACCOUNT_MEMBER_ADD = "pam-account-member-add",PAM_ACCOUNT_MEMBER_UPDATE = "pam-account-member-update",PAM_ACCOUNT_MEMBER_REMOVE = "pam-account-member-remove",- PAM_ACCOUNT_LIST = "pam-account-list",- PAM_ACCOUNT_GET = "pam-account-get",PAM_ACCOUNT_ACCESS = "pam-account-access",- PAM_ACCOUNT_AWS_CONSOLE_URL_GENERATED = "pam-account-aws-console-url-generated",PAM_ACCOUNT_CREATE = "pam-account-create",PAM_ACCOUNT_UPDATE = "pam-account-update",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",APPROVAL_POLICY_CREATE = "approval-policy-create",APPROVAL_POLICY_UPDATE = "approval-policy-update",@@ -5621,43 +5595,6 @@ interface ViewAuditLogsEvent {metadata?: Record<string, unknown>;}-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 ViewPamInsightsRotationCalendarEvent {- type: EventType.VIEW_INSIGHTS_PAM_ROTATION_CALENDAR;- metadata: {- projectId: string;- month: number;- year: number;- };-}-interface ProjectRoleCreateEvent {type: EventType.CREATE_PROJECT_ROLE;metadata: {@@ -5735,14 +5672,6 @@ interface OrgRoleDeleteEvent {};}-interface PamSessionCredentialsGetEvent {- type: EventType.PAM_SESSION_CREDENTIALS_GET;- metadata: {- sessionId: string;- accountName: string;- };-}-interface PamSessionStartEvent {type: EventType.PAM_SESSION_START;metadata: {@@ -5751,14 +5680,6 @@ interface PamSessionStartEvent {};}-interface PamSessionLogsUpdateEvent {- type: EventType.PAM_SESSION_LOGS_UPDATE;- metadata: {- sessionId: string;- accountName: string;- };-}-interface PamSessionEndEvent {type: EventType.PAM_SESSION_END;metadata: {@@ -5767,36 +5688,6 @@ interface PamSessionEndEvent {};}-interface PamSessionTerminateEvent {- type: EventType.PAM_SESSION_TERMINATE;- metadata: {- sessionId: string;- accountName: string;- };-}--interface PamSessionGetEvent {- type: EventType.PAM_SESSION_GET;- metadata: {- sessionId: string;- };-}--interface PamSessionListEvent {- type: EventType.PAM_SESSION_LIST;- metadata: {- count: number;- };-}--interface PamSessionEventBatchUploadEvent {- type: EventType.PAM_SESSION_EVENT_BATCH_UPLOAD;- metadata: {- sessionId: string;- startOffset: number;- };-}-interface PamSessionChunkUploadEvent {type: EventType.PAM_SESSION_CHUNK_UPLOAD;metadata: {@@ -5815,34 +5706,6 @@ interface PamSessionUploadTokenInvalidEvent {};}-interface PamRecordingConfigUpsertEvent {- type: EventType.PAM_RECORDING_CONFIG_UPDATE;- metadata: {- projectId: string;- storageBackend: string;- bucket: string;- region: string;- };-}--interface PamRecordingConfigDeleteEvent {- type: EventType.PAM_RECORDING_CONFIG_DELETE;- metadata: {- projectId: string;- };-}--interface PamRecordingBucketConnectionTestFailedEvent {- type: EventType.PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED;- metadata: {- projectId: string;- storageBackend: string;- bucket: string;- region: string;- reason: string;- };-}-interface PamAccountTemplateCreateEvent {type: EventType.PAM_ACCOUNT_TEMPLATE_CREATE;metadata: {@@ -5978,21 +5841,6 @@ interface PamAccountMemberRemoveEvent {};}-interface PamAccountListEvent {- type: EventType.PAM_ACCOUNT_LIST;- metadata: {- accountCount: number;- };-}--interface PamAccountGetEvent {- type: EventType.PAM_ACCOUNT_GET;- metadata: {- accountId: string;- accountName: string;- };-}-interface PamAccountAccessEvent {type: EventType.PAM_ACCOUNT_ACCESS;metadata: {@@ -6013,16 +5861,6 @@ interface PamWebAccessSessionTicketCreatedEvent {};}-interface PamAccountAwsConsoleUrlGeneratedEvent {- type: EventType.PAM_ACCOUNT_AWS_CONSOLE_URL_GENERATED;- metadata: {- sessionId: string;- accountId: string;- resourceName: string;- accountName: string;- };-}-interface PamAccountCreateEvent {type: EventType.PAM_ACCOUNT_CREATE;metadata: {@@ -6054,82 +5892,6 @@ interface PamAccountDeleteEvent {};}-interface PamAccountCredentialRotationEvent {- type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION;- metadata: {- accountName: string;- accountId: string;- resourceId: string;- resourceType: string;- };-}--interface PamAccountCredentialRotationFailedEvent {- type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION_FAILED;- metadata: {- accountName: string;- accountId: string;- resourceId: string;- resourceType: string;- errorMessage: string;- };-}--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: {- accountId: string;- accountName: string;- resourceId?: string | null;- resourceType?: string | null;- domainId?: string | null;- domainType?: string | null;- };-}-interface UpdateCertificateRenewalConfigEvent {type: EventType.UPDATE_CERTIFICATE_RENEWAL_CONFIG;metadata: {@@ -7619,11 +7381,6 @@ export type Event =| ViewInsightsAuthMethodsEvent| ViewSecretManagementInsightsSummaryEvent| ViewAuditLogsEvent- | ViewPamInsightsSummaryEvent- | ViewPamInsightsSessionActivityEvent- | ViewPamInsightsTopActorsEvent- | ViewPamInsightsResourceBreakdownEvent- | ViewPamInsightsRotationCalendarEvent| ProjectRoleCreateEvent| ProjectRoleUpdateEvent| ProjectRoleDeleteEvent@@ -7632,19 +7389,10 @@ export type Event =| OrgRoleCreateEvent| OrgRoleUpdateEvent| OrgRoleDeleteEvent- | PamSessionCredentialsGetEvent| PamSessionStartEvent- | PamSessionLogsUpdateEvent| PamSessionEndEvent- | PamSessionTerminateEvent- | PamSessionGetEvent- | PamSessionListEvent- | PamSessionEventBatchUploadEvent| PamSessionChunkUploadEvent| PamSessionUploadTokenInvalidEvent- | PamRecordingConfigUpsertEvent- | PamRecordingConfigDeleteEvent- | PamRecordingBucketConnectionTestFailedEvent| PamAccountTemplateCreateEvent| PamAccountTemplateUpdateEvent| PamAccountTemplateDeleteEvent@@ -7660,22 +7408,11 @@ export type Event =| PamAccountMemberAddEvent| PamAccountMemberUpdateEvent| PamAccountMemberRemoveEvent- | PamAccountListEvent- | PamAccountGetEvent| PamAccountAccessEvent- | PamAccountAwsConsoleUrlGeneratedEvent| PamWebAccessSessionTicketCreatedEvent| PamAccountCreateEvent| PamAccountUpdateEvent| PamAccountDeleteEvent- | PamAccountCredentialRotationEvent- | PamAccountCredentialRotationFailedEvent- | PamAccountPolicyCreateEvent- | PamAccountPolicyUpdateEvent- | PamAccountPolicyDeleteEvent- | PamAccountPolicyListEvent- | PamAccountPolicyGetEvent- | PamAccountReadCredentialsEvent| UpdateCertificateRenewalConfigEvent| UpdateCertificateMetadataEvent| DisableCertificateRenewalConfigEventdiff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.tsindex ae4f1c7bf8..4120639d3e 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts@@ -31,7 +31,7 @@ import { TSmtpService } from "@app/services/smtp/smtp-service";import { TAiMcpServerDALFactory } from "../ai-mcp-server/ai-mcp-server-dal";import { TDynamicSecretDALFactory } from "../dynamic-secret/dynamic-secret-dal";-import { PamResource } from "../pam-resource/pam-resource-enums";+import { PamAccountType } from "../pam/pam-enums";import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPermissionServiceFactory } from "../permission/permission-service-types";import { TPkiDiscoveryConfigDALFactory } from "../pki-discovery/pki-discovery-config-dal";@@ -495,7 +495,7 @@ export const gatewayV2ServiceFactory = ({}: {gatewayId: string;sessionId: string;- resourceType: PamResource;+ resourceType: PamAccountType;duration?: number;host: string;port?: number;diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts b/backend/src/ee/services/pam-account-template/pam-account-template-dal.tsindex 63d9ea15ff..e9dca5abb5 100644--- a/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts+++ b/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts@@ -1,3 +1,5 @@+import { Knex } from "knex";+import { TDbClient } from "@app/db";import { TableName } from "@app/db/schemas";import { sanitizeSqlLikeString } from "@app/lib/fn";@@ -10,8 +12,12 @@ export type TPamAccountTemplateDALFactory = ReturnType<typeof pamAccountTemplateexport const pamAccountTemplateDALFactory = (db: TDbClient) => {const orm = ormify(db, TableName.PamAccountTemplate);- const findByProjectId = async (projectId: string, filters?: { search?: string; type?: PamAccountType }) => {- const qb = db.replicaNode()(TableName.PamAccountTemplate).where({ projectId });+ const findByProjectId = async (+ projectId: string,+ filters?: { search?: string; type?: PamAccountType },+ tx?: Knex+ ) => {+ const qb = (tx || db.replicaNode())(TableName.PamAccountTemplate).where({ projectId });if (filters?.search) {const sanitized = sanitizeSqlLikeString(filters.search);@@ -26,9 +32,8 @@ export const pamAccountTemplateDALFactory = (db: TDbClient) => {return qb.orderBy("name", "asc");};- const countAccountsByTemplateId = async (templateId: string) => {- const [result] = (await db- .replicaNode()(TableName.PamAccount)+ const countAccountsByTemplateId = async (templateId: string, tx?: Knex) => {+ const [result] = (await (tx || db.replicaNode())(TableName.PamAccount).where({ templateId }).count("id as count")) as unknown as [{ count: string }];return Number(result.count);diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-service.ts b/backend/src/ee/services/pam-account-template/pam-account-template-service.tsindex 3ff8be8b60..70b1e79d1f 100644--- a/backend/src/ee/services/pam-account-template/pam-account-template-service.ts+++ b/backend/src/ee/services/pam-account-template/pam-account-template-service.ts@@ -1,10 +1,9 @@-import { ActionProjectType } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";-import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import { PamProductRole } from "../pam/pam-enums";+import { TActorContext, verifyProductMembership } from "../pam-membership/pam-permission";import { TPamAccountTemplateDALFactory } from "./pam-account-template-dal";import {TCreatePamAccountTemplateDTO,@@ -14,13 +13,6 @@ import {TUpdatePamAccountTemplateDTO} from "./pam-account-template-types";-type TActorContext = {- actorId: string;- actor: ActorType;- actorOrgId: string;- actorAuthMethod: ActorAuthMethod;-};-type TPamAccountTemplateServiceFactoryDep = {pamAccountTemplateDAL: TPamAccountTemplateDALFactory;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;@@ -32,32 +24,23 @@ export const pamAccountTemplateServiceFactory = ({pamAccountTemplateDAL,permissionService}: TPamAccountTemplateServiceFactoryDep) => {- const verifyProductMembership = async (projectId: string, ctx: TActorContext) => {- const { hasRole } = await permissionService.getProjectPermission({- actor: ctx.actor,- actorId: ctx.actorId,- projectId,- actorAuthMethod: ctx.actorAuthMethod,- actorOrgId: ctx.actorOrgId,- actionProjectType: ActionProjectType.PAM- });- return { hasRole };- };+ const verifyMembership = (projectId: string, ctx: TActorContext) =>+ verifyProductMembership(permissionService, projectId, ctx);const verifyProductAdmin = async (projectId: string, ctx: TActorContext) => {- const { hasRole } = await verifyProductMembership(projectId, ctx);+ const { hasRole } = await verifyMembership(projectId, ctx);if (!hasRole(PamProductRole.Admin)) {throw new ForbiddenRequestError({ message: "Only PAM product admins can perform this action" });}};const list = async ({ projectId, search, type, ...ctx }: TListPamAccountTemplatesDTO & TActorContext) => {- await verifyProductMembership(projectId, ctx);+ await verifyMembership(projectId, ctx);return pamAccountTemplateDAL.findByProjectId(projectId, { search, type });};const getById = async ({ templateId, projectId, ...ctx }: TGetPamAccountTemplateDTO & TActorContext) => {- await verifyProductMembership(projectId, ctx);+ await verifyMembership(projectId, ctx);const template = await pamAccountTemplateDAL.findById(templateId);if (!template || template.projectId !== projectId) {diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-types.ts b/backend/src/ee/services/pam-account-template/pam-account-template-types.tsindex b9c62ad9b2..2757f1288f 100644--- a/backend/src/ee/services/pam-account-template/pam-account-template-types.ts+++ b/backend/src/ee/services/pam-account-template/pam-account-template-types.ts@@ -1,5 +1,5 @@import { PamAccountType } from "../pam/pam-enums";-import { TPamTemplateAccessPolicy, TPamTemplateSettings } from "../pam/pam-template-config-schemas";+import { TPamTemplateAccessPolicy, TPamTemplateSettings } from "./pam-template-config-schemas";export type TCreatePamAccountTemplateDTO = {projectId: string;diff --git a/backend/src/ee/services/pam/pam-template-config-schemas.ts b/backend/src/ee/services/pam-account-template/pam-template-config-schemas.tssimilarity index 92%rename from backend/src/ee/services/pam/pam-template-config-schemas.tsrename to backend/src/ee/services/pam-account-template/pam-template-config-schemas.tsindex df73789c66..8d693fb07d 100644--- a/backend/src/ee/services/pam/pam-template-config-schemas.ts+++ b/backend/src/ee/services/pam-account-template/pam-template-config-schemas.ts@@ -1,6 +1,6 @@import { z } from "zod";-import { PamRecordingStorageBackend } from "./pam-enums";+import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";export const PamPasswordConstraintsSchema = z.object({minLength: z.number().int().min(1).max(256),diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.tsindex 565f67997f..66cd498dc7 100644--- a/backend/src/ee/services/pam-account/pam-account-dal.ts+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts@@ -1,3 +1,5 @@+import { Knex } from "knex";+import { TDbClient } from "@app/db";import { TableName, TPamAccounts } from "@app/db/schemas";import { sanitizeSqlLikeString } from "@app/lib/fn";@@ -39,10 +41,10 @@ export const pamAccountDALFactory = (db: TDbClient) => {projectId: string,accessibleFolderIds: string[],accessibleAccountIds: string[],- filters?: { folderId?: string; templateId?: string; search?: string }+ filters?: { folderId?: string; templateId?: string; search?: string },+ tx?: Knex): Promise<TPamAccountListItem[]> => {- const qb = db- .replicaNode()(TableName.PamAccount)+ const qb = (tx || db.replicaNode())(TableName.PamAccount).join(TableName.PamAccountTemplate, `${TableName.PamAccount}.templateId`, `${TableName.PamAccountTemplate}.id`).leftJoin(TableName.PamFolder, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`).where(`${TableName.PamAccount}.projectId`, projectId)@@ -86,9 +88,8 @@ export const pamAccountDALFactory = (db: TDbClient) => {.orderBy(`${TableName.PamAccount}.name`, "asc") as unknown as Promise<TPamAccountListItem[]>;};- const findByIdWithDetails = async (accountId: string): Promise<TPamAccountDetail | null> => {- const rows = (await db- .replicaNode()(TableName.PamAccount)+ const findByIdWithDetails = async (accountId: string, tx?: Knex): Promise<TPamAccountDetail | null> => {+ const rows = (await (tx || db.replicaNode())(TableName.PamAccount).join(TableName.PamAccountTemplate, `${TableName.PamAccount}.templateId`, `${TableName.PamAccountTemplate}.id`).leftJoin(TableName.PamFolder, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`).where(`${TableName.PamAccount}.id`, accountId)diff --git a/backend/src/ee/services/pam-account/pam-account-enums.ts b/backend/src/ee/services/pam-account/pam-account-enums.tsdeleted file mode 100644index dbaddeab20..0000000000--- a/backend/src/ee/services/pam-account/pam-account-enums.ts+++ /dev/null@@ -1,20 +0,0 @@-import { PamDomainType } from "../pam-domain/pam-domain-enums";-import { PamResource } from "../pam-resource/pam-resource-enums";--export type PamParentType = PamResource | PamDomainType;--export enum PamAccountOrderBy {- Name = "name"-}--export enum PamAccountView {- Flat = "flat",- Nested = "nested"-}--export enum PamAccountRotationStatus {- Rotating = "rotating",- Success = "success",- PartialSuccess = "partial-success",- Failed = "failed"-}diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 0e8f594e85..5d3d714412 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -1,6 +1,6 @@import { ForbiddenError } from "@casl/ability";-import { ActionProjectType, OrganizationActionScope, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";+import { OrganizationActionScope, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";@@ -11,7 +11,6 @@ import {} from "@app/ee/services/permission/resource-permission";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";-import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";@@ -19,6 +18,13 @@ import { TMembershipRoleDALFactory } from "@app/services/membership/membership-rimport { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";+import {+ checkAccountAccess,+ checkFolderPermission,+ getAccessibleResourceIds,+ TActorContext,+ verifyProductMembership+} from "../pam-membership/pam-permission";import { TPamAccountDALFactory } from "./pam-account-dal";import { validateConnectionDetails, validateCredentials } from "./pam-account-schemas";import {@@ -30,13 +36,6 @@ import {TUpdatePamAccountDTO} from "./pam-account-types";-type TActorContext = {- actorId: string;- actor: ActorType;- actorOrgId: string;- actorAuthMethod: ActorAuthMethod;-};-type TPamAccountServiceFactoryDep = {pamAccountDAL: TPamAccountDALFactory;pamFolderDAL: Pick<TPamFolderDALFactory, "findById">;@@ -78,29 +77,11 @@ export const pamAccountServiceFactory = ({return JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>;};- const verifyProductMembership = async (projectId: string, ctx: TActorContext) => {- const { hasRole } = await permissionService.getProjectPermission({- actor: ctx.actor,- actorId: ctx.actorId,- projectId,- actorAuthMethod: ctx.actorAuthMethod,- actorOrgId: ctx.actorOrgId,- actionProjectType: ActionProjectType.PAM- });- return { hasRole };- };+ const verifyMembership = (projectId: string, ctx: TActorContext) =>+ verifyProductMembership(permissionService, projectId, ctx);- const checkFolderPermission = async (folderId: string, projectId: string, ctx: TActorContext) => {- return permissionService.getResourcePermission({- actor: ctx.actor,- actorId: ctx.actorId,- projectId,- resourceType: ResourceType.PamFolder,- resourceId: folderId,- actorAuthMethod: ctx.actorAuthMethod,- actorOrgId: ctx.actorOrgId- });- };+ const checkFolder = (folderId: string, projectId: string, ctx: TActorContext) =>+ checkFolderPermission(permissionService, folderId, projectId, ctx);const validateGatewayAttachment = async (gwId: string | null | undefined,@@ -136,26 +117,9 @@ export const pamAccountServiceFactory = ({};const list = async ({ projectId, folderId, templateId, search, ...ctx }: TListPamAccountsDTO & TActorContext) => {- await verifyProductMembership(projectId, ctx);-- const [folderMemberships, accountMemberships] = await Promise.all([- membershipDAL.findResourceMembershipsForActor({- projectId,- resourceType: ResourceType.PamFolder,- actorType: ctx.actor,- actorId: ctx.actorId- }),- membershipDAL.findResourceMembershipsForActor({- projectId,- resourceType: ResourceType.PamAccount,- actorType: ctx.actor,- actorId: ctx.actorId- })- ]);-- const folderIds = folderMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));- const accountIds = accountMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));+ await verifyMembership(projectId, ctx);+ const { folderIds, accountIds } = await getAccessibleResourceIds(membershipDAL, projectId, ctx);if (folderIds.length === 0 && accountIds.length === 0) return [];const accounts = await pamAccountDAL.findAccessible(projectId, folderIds, accountIds, {@@ -182,34 +146,13 @@ export const pamAccountServiceFactory = ({}));};- const checkAccountAccess = async (+ const checkAccount = (accountId: string,folderId: string | null | undefined,projectId: string,action: ResourcePermissionPamResourceActions,ctx: TActorContext- ) => {- if (folderId) {- try {- const { permission } = await checkFolderPermission(folderId, projectId, ctx);- ForbiddenError.from(permission).throwUnlessCan(action, ResourcePermissionSub.PamResource);- return;- } catch (err) {- if (!(err instanceof ForbiddenError)) throw err;- }- }-- const { permission } = await permissionService.getResourcePermission({- actor: ctx.actor,- actorId: ctx.actorId,- projectId,- resourceType: ResourceType.PamAccount,- resourceId: accountId,- actorAuthMethod: ctx.actorAuthMethod,- actorOrgId: ctx.actorOrgId- });- ForbiddenError.from(permission).throwUnlessCan(action, ResourcePermissionSub.PamResource);- };+ ) => checkAccountAccess(permissionService, accountId, folderId, projectId, action, ctx);const getById = async ({ accountId, projectId, ...ctx }: TGetPamAccountDTO & TActorContext) => {const account = await pamAccountDAL.findByIdWithDetails(accountId);@@ -217,13 +160,7 @@ export const pamAccountServiceFactory = ({throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });}- await checkAccountAccess(- accountId,- account.folderId,- projectId,- ResourcePermissionPamResourceActions.ReadAccounts,- ctx- );+ await checkAccount(accountId, account.folderId, projectId, ResourcePermissionPamResourceActions.ReadAccounts, ctx);const connectionDetails = await decrypt(projectId, account.encryptedConnectionDetails);@@ -262,7 +199,7 @@ export const pamAccountServiceFactory = ({recordingConnectionId,...ctx}: TCreatePamAccountDTO & TActorContext) => {- const { permission } = await checkFolderPermission(folderId, projectId, ctx);+ const { permission } = await checkFolder(folderId, projectId, ctx);ForbiddenError.from(permission).throwUnlessCan(ResourcePermissionPamResourceActions.CreateAccounts,ResourcePermissionSub.PamResource@@ -323,11 +260,16 @@ export const pamAccountServiceFactory = ({connectionDetails: validatedConnectionDetails};} catch (err) {- if (- err instanceof DatabaseError &&- (err as DatabaseError & { code?: string }).code === DatabaseErrorCode.UniqueViolation- ) {- throw new BadRequestError({ message: `An account named "${name}" already exists in this folder` });+ if (err instanceof DatabaseError) {+ const code = (err.error as { code?: string })?.code;+ if (code === DatabaseErrorCode.UniqueViolation) {+ throw new BadRequestError({ message: `An account named "${name}" already exists in this folder` });+ }+ if (code === DatabaseErrorCode.ForeignKeyViolation) {+ throw new BadRequestError({+ message: "Invalid reference: the specified gateway, pool, or template does not exist"+ });+ }}throw err;}@@ -353,13 +295,7 @@ export const pamAccountServiceFactory = ({throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });}- await checkAccountAccess(- accountId,- existing.folderId,- projectId,- ResourcePermissionPamResourceActions.EditAccounts,- ctx- );+ await checkAccount(accountId, existing.folderId, projectId, ResourcePermissionPamResourceActions.EditAccounts, ctx);if (folderId) {const folder = await pamFolderDAL.findById(folderId);@@ -399,11 +335,16 @@ export const pamAccountServiceFactory = ({try {return await pamAccountDAL.updateById(accountId, updateData);} catch (err) {- if (- err instanceof DatabaseError &&- (err as DatabaseError & { code?: string }).code === DatabaseErrorCode.UniqueViolation- ) {- throw new BadRequestError({ message: `An account named "${name}" already exists in this folder` });+ if (err instanceof DatabaseError) {+ const code = (err.error as { code?: string })?.code;+ if (code === DatabaseErrorCode.UniqueViolation) {+ throw new BadRequestError({ message: `An account named "${name}" already exists in this folder` });+ }+ if (code === DatabaseErrorCode.ForeignKeyViolation) {+ throw new BadRequestError({+ message: "Invalid reference: the specified gateway, pool, or template does not exist"+ });+ }}throw err;}@@ -415,7 +356,7 @@ export const pamAccountServiceFactory = ({throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });}- await checkAccountAccess(+ await checkAccount(accountId,existing.folderId,projectId,@@ -444,33 +385,9 @@ export const pamAccountServiceFactory = ({};const listAccessible = async ({ projectId, ...ctx }: TListAccessibleAccountsDTO & TActorContext) => {- await permissionService.getProjectPermission({- actor: ctx.actor,- actorId: ctx.actorId,- projectId,- actorAuthMethod: ctx.actorAuthMethod,- actorOrgId: ctx.actorOrgId,- actionProjectType: ActionProjectType.PAM- });-- const [folderMemberships, accountMemberships] = await Promise.all([- membershipDAL.findResourceMembershipsForActor({- projectId,- resourceType: ResourceType.PamFolder,- actorType: ctx.actor,- actorId: ctx.actorId- }),- membershipDAL.findResourceMembershipsForActor({- projectId,- resourceType: ResourceType.PamAccount,- actorType: ctx.actor,- actorId: ctx.actorId- })- ]);-- const folderIds = folderMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));- const accountIds = accountMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));+ await verifyMembership(projectId, ctx);+ const { folderIds, accountIds } = await getAccessibleResourceIds(membershipDAL, projectId, ctx);if (folderIds.length === 0 && accountIds.length === 0) return [];const accounts = await pamAccountDAL.findAccessible(projectId, folderIds, accountIds);diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts b/backend/src/ee/services/pam-discovery/pam-discovery-enums.tsdeleted file mode 100644index e766971fb6..0000000000--- a/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts+++ /dev/null@@ -1,62 +0,0 @@-// Discovery Sources-export enum PamDiscoveryType {- ActiveDirectory = "active-directory"-}--export const PAM_DISCOVERY_TYPE_PASCAL_MAP: Record<PamDiscoveryType, string> = {- [PamDiscoveryType.ActiveDirectory]: "ActiveDirectory"-};--export enum PamDiscoverySourceStatus {- Active = "active",- Paused = "paused",- Error = "error"-}--export enum PamDiscoverySchedule {- Manual = "manual",- Daily = "daily",- Weekly = "weekly"-}--export enum PamDiscoveryOrderBy {- Name = "name"-}--// Discovery Run Step Status (sub-step progress within a run)-export enum PamDiscoveryStepStatus {- Running = "running",- Completed = "completed",- Failed = "failed",- Skipped = "skipped"-}--// Discovery Runs-export enum PamDiscoverySourceRunStatus {- Running = "running",- Completed = "completed",- Failed = "failed"-}--export enum PamDiscoverySourceRunTrigger {- Manual = "manual",- Schedule = "schedule"-}--// Dependencies-export enum PamAccountDependencyType {- WindowsService = "windows-service",- ScheduledTask = "scheduled-task",- IisAppPool = "iis-app-pool"-}--export enum PamAccountDependencySource {- Discovery = "discovery",- Manual = "manual"-}--export enum PamDependencySyncStatus {- Pending = "pending",- Success = "success",- Failed = "failed"-}diff --git a/backend/src/ee/services/pam-domain/pam-domain-enums.ts b/backend/src/ee/services/pam-domain/pam-domain-enums.tsdeleted file mode 100644index 03fcd18cad..0000000000--- a/backend/src/ee/services/pam-domain/pam-domain-enums.ts+++ /dev/null@@ -1,7 +0,0 @@-export enum PamDomainType {- ActiveDirectory = "active-directory"-}--export enum PamDomainOrderBy {- Name = "name"-}diff --git a/backend/src/ee/services/pam-folder/pam-folder-dal.ts b/backend/src/ee/services/pam-folder/pam-folder-dal.tsindex 5e80b8ce16..5eb2a28151 100644--- a/backend/src/ee/services/pam-folder/pam-folder-dal.ts+++ b/backend/src/ee/services/pam-folder/pam-folder-dal.ts@@ -1,3 +1,5 @@+import { Knex } from "knex";+import { TDbClient } from "@app/db";import { TableName, TPamFolders } from "@app/db/schemas";import { sanitizeSqlLikeString } from "@app/lib/fn";@@ -13,10 +15,10 @@ export const pamFolderDALFactory = (db: TDbClient) => {const findByProjectIdFiltered = async (projectId: string,folderIds: string[],- filters?: { search?: string; accountIds?: string[] }+ filters?: { search?: string; accountIds?: string[] },+ tx?: Knex): Promise<TPamFolderWithCount[]> => {- const qb = db- .replicaNode()(TableName.PamFolder)+ const qb = (tx || db.replicaNode())(TableName.PamFolder).leftJoin(TableName.PamAccount, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`).where(`${TableName.PamFolder}.projectId`, projectId).where((builder) => {@@ -38,9 +40,8 @@ export const pamFolderDALFactory = (db: TDbClient) => {.orderBy(`${TableName.PamFolder}.name`, "asc") as unknown as Promise<TPamFolderWithCount[]>;};- const countAccountsByFolderId = async (folderId: string) => {- const [result] = (await db- .replicaNode()(TableName.PamAccount)+ const countAccountsByFolderId = async (folderId: string, tx?: Knex) => {+ const [result] = (await (tx || db.replicaNode())(TableName.PamAccount).where({ folderId }).count("id as count")) as unknown as [{ count: string }];return Number(result.count);diff --git a/backend/src/ee/services/pam-folder/pam-folder-service.ts b/backend/src/ee/services/pam-folder/pam-folder-service.tsindex 43390b7523..8dbe82d412 100644--- a/backend/src/ee/services/pam-folder/pam-folder-service.ts+++ b/backend/src/ee/services/pam-folder/pam-folder-service.ts@@ -1,6 +1,6 @@import { ForbiddenError } from "@casl/ability";-import { ActionProjectType, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";+import { RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ResourcePermissionPamResourceActions,@@ -8,11 +8,12 @@ import {} from "@app/ee/services/permission/resource-permission";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";-import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";+import { ActorType } from "@app/services/auth/auth-type";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";import { PamProductRole, PamResourceRole } from "../pam/pam-enums";+import { getAccessibleResourceIds, TActorContext, verifyProductMembership } from "../pam-membership/pam-permission";import { TPamFolderDALFactory } from "./pam-folder-dal";import {TCreatePamFolderDTO,@@ -22,13 +23,6 @@ import {TUpdatePamFolderDTO} from "./pam-folder-types";-type TActorContext = {- actorId: string;- actor: ActorType;- actorOrgId: string;- actorAuthMethod: ActorAuthMethod;-};-type TPamFolderServiceFactoryDep = {pamFolderDAL: TPamFolderDALFactory;membershipDAL: Pick<@@ -47,20 +41,11 @@ export const pamFolderServiceFactory = ({membershipRoleDAL,permissionService}: TPamFolderServiceFactoryDep) => {- const verifyProductMembership = async (projectId: string, ctx: TActorContext) => {- const { hasRole } = await permissionService.getProjectPermission({- actor: ctx.actor,- actorId: ctx.actorId,- projectId,- actorAuthMethod: ctx.actorAuthMethod,- actorOrgId: ctx.actorOrgId,- actionProjectType: ActionProjectType.PAM- });- return { hasRole };- };+ const verifyMembership = (projectId: string, ctx: TActorContext) =>+ verifyProductMembership(permissionService, projectId, ctx);const verifyProductAdmin = async (projectId: string, ctx: TActorContext) => {- const { hasRole } = await verifyProductMembership(projectId, ctx);+ const { hasRole } = await verifyMembership(projectId, ctx);if (!hasRole(PamProductRole.Admin)) {throw new ForbiddenRequestError({ message: "Only PAM product admins can perform this action" });}@@ -85,26 +70,9 @@ export const pamFolderServiceFactory = ({};const list = async ({ projectId, search, ...ctx }: TListPamFoldersDTO & TActorContext) => {- await verifyProductMembership(projectId, ctx);-- const [folderMemberships, accountMemberships] = await Promise.all([- membershipDAL.findResourceMembershipsForActor({- projectId,- resourceType: ResourceType.PamFolder,- actorType: ctx.actor,- actorId: ctx.actorId- }),- membershipDAL.findResourceMembershipsForActor({- projectId,- resourceType: ResourceType.PamAccount,- actorType: ctx.actor,- actorId: ctx.actorId- })- ]);-- const folderIds = folderMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));- const accountIds = accountMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));+ await verifyMembership(projectId, ctx);+ const { folderIds, accountIds } = await getAccessibleResourceIds(membershipDAL, projectId, ctx);if (folderIds.length === 0 && accountIds.length === 0) return [];return pamFolderDAL.findByProjectIdFiltered(projectId, folderIds, { search, accountIds });diff --git a/backend/src/ee/services/pam-instance/pam-project-bootstrap.ts b/backend/src/ee/services/pam-instance/pam-project-bootstrap.tsindex ab6c6c13f7..5f95153205 100644--- a/backend/src/ee/services/pam-instance/pam-project-bootstrap.ts+++ b/backend/src/ee/services/pam-instance/pam-project-bootstrap.ts@@ -7,8 +7,9 @@ import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";import { TProjectDALFactory } from "@app/services/project/project-dal";-import { PamAccountType, PamRecordingStorageBackend } from "../pam/pam-enums";-import { TPamTemplateAccessPolicy, TPamTemplateSettings } from "../pam/pam-template-config-schemas";+import { PamAccountType } from "../pam/pam-enums";+import { TPamTemplateAccessPolicy, TPamTemplateSettings } from "../pam-account-template/pam-template-config-schemas";+import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";type TBootstrapDeps = {projectDAL: Pick<TProjectDALFactory, "create" | "findOne">;diff --git a/backend/src/ee/services/pam-membership/pam-membership-service.ts b/backend/src/ee/services/pam-membership/pam-membership-service.tsindex aff2858a0c..0762e09355 100644--- a/backend/src/ee/services/pam-membership/pam-membership-service.ts+++ b/backend/src/ee/services/pam-membership/pam-membership-service.ts@@ -9,7 +9,6 @@ import {ResourcePermissionSub} from "@app/ee/services/permission/resource-permission";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";-import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";import { TUserDALFactory } from "@app/services/user/user-dal";@@ -31,13 +30,7 @@ import {TUpdatePamFolderMemberDTO,TUpdatePamProductMemberDTO} from "./pam-membership-types";--type TActorContext = {- actorId: string;- actor: ActorType;- actorOrgId: string;- actorAuthMethod: ActorAuthMethod;-};+import { TActorContext } from "./pam-permission";type TPamMembershipServiceFactoryDep = {membershipDAL: Pick<diff --git a/backend/src/ee/services/pam-membership/pam-permission.ts b/backend/src/ee/services/pam-membership/pam-permission.tsnew file mode 100644index 0000000000..c516efd7f0--- /dev/null+++ b/backend/src/ee/services/pam-membership/pam-permission.ts@@ -0,0 +1,108 @@+import { ForbiddenError } from "@casl/ability";++import { ActionProjectType, ResourceType } from "@app/db/schemas";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";++import { ResourcePermissionPamResourceActions, ResourcePermissionSub } from "../permission/resource-permission";++export type TActorContext = {+ actorId: string;+ actor: ActorType;+ actorOrgId: string;+ actorAuthMethod: ActorAuthMethod;+};++type TPermissionDep = Pick<TPermissionServiceFactory, "getResourcePermission">;+type TProjectPermissionDep = Pick<TPermissionServiceFactory, "getProjectPermission">;+type TMembershipDep = Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;++export const verifyProductMembership = async (+ permissionService: TProjectPermissionDep,+ projectId: string,+ ctx: TActorContext+) => {+ const { hasRole } = await permissionService.getProjectPermission({+ actor: ctx.actor,+ actorId: ctx.actorId,+ projectId,+ actorAuthMethod: ctx.actorAuthMethod,+ actorOrgId: ctx.actorOrgId,+ actionProjectType: ActionProjectType.PAM+ });+ return { hasRole };+};++export const checkFolderPermission = async (+ permissionService: TPermissionDep,+ folderId: string,+ projectId: string,+ ctx: TActorContext+) => {+ return permissionService.getResourcePermission({+ actor: ctx.actor,+ actorId: ctx.actorId,+ projectId,+ resourceType: ResourceType.PamFolder,+ resourceId: folderId,+ actorAuthMethod: ctx.actorAuthMethod,+ actorOrgId: ctx.actorOrgId+ });+};++export const checkAccountAccess = async (+ permissionService: TPermissionDep,+ accountId: string,+ folderId: string | null | undefined,+ projectId: string,+ action: ResourcePermissionPamResourceActions,+ ctx: TActorContext+) => {+ if (folderId) {+ try {+ const { permission } = await checkFolderPermission(permissionService, folderId, projectId, ctx);+ ForbiddenError.from(permission).throwUnlessCan(action, ResourcePermissionSub.PamResource);+ return;+ } catch (err) {+ if (!(err instanceof ForbiddenError)) throw err;+ }+ }++ const { permission } = await permissionService.getResourcePermission({+ actor: ctx.actor,+ actorId: ctx.actorId,+ projectId,+ resourceType: ResourceType.PamAccount,+ resourceId: accountId,+ actorAuthMethod: ctx.actorAuthMethod,+ actorOrgId: ctx.actorOrgId+ });+ ForbiddenError.from(permission).throwUnlessCan(action, ResourcePermissionSub.PamResource);+};++export const getAccessibleResourceIds = async (+ membershipDAL: TMembershipDep,+ projectId: string,+ ctx: TActorContext+) => {+ const [folderMemberships, accountMemberships] = await Promise.all([+ membershipDAL.findResourceMembershipsForActor({+ projectId,+ resourceType: ResourceType.PamFolder,+ actorType: ctx.actor,+ actorId: ctx.actorId+ }),+ membershipDAL.findResourceMembershipsForActor({+ projectId,+ resourceType: ResourceType.PamAccount,+ actorType: ctx.actor,+ actorId: ctx.actorId+ })+ ]);++ const folderIds = folderMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));+ const accountIds = accountMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));++ return { folderIds, accountIds };+};diff --git a/backend/src/ee/services/pam-resource/pam-resource-enums.ts b/backend/src/ee/services/pam-resource/pam-resource-enums.tsdeleted file mode 100644index 0258d03ecd..0000000000--- a/backend/src/ee/services/pam-resource/pam-resource-enums.ts+++ /dev/null@@ -1,16 +0,0 @@-export enum PamResource {- Postgres = "postgres",- MySQL = "mysql",- MsSQL = "mssql",- SSH = "ssh",- Kubernetes = "kubernetes",- AwsIam = "aws-iam",- Redis = "redis",- MongoDB = "mongodb",- Windows = "windows",- OracleDB = "oracledb"-}--export enum PamResourceOrderBy {- Name = "name"-}diff --git a/backend/src/ee/services/pam-session-recording-storage/aws-s3/aws-s3-provider-factory.ts b/backend/src/ee/services/pam-session-recording-storage/aws-s3/aws-s3-provider-factory.tsnew file mode 100644index 0000000000..cc959e624c--- /dev/null+++ b/backend/src/ee/services/pam-session-recording-storage/aws-s3/aws-s3-provider-factory.ts@@ -0,0 +1,158 @@+import {+ DeleteObjectsCommand,+ GetObjectCommand,+ HeadBucketCommand,+ ListObjectsV2Command,+ PutObjectCommand,+ S3Client+} from "@aws-sdk/client-s3";+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";++import { CustomAWSHasher } from "@app/lib/aws/hashing";+import { crypto } from "@app/lib/crypto/cryptography";+import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";++import {+ PAM_RECORDING_MAX_CHUNK_BYTES,+ PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS+} from "../pam-session-recording-storage-constants";+import {+ buildExternalChunkObjectKey,+ normalizeKeyPrefix,+ TPamRecordingResolvedConfig,+ TPamRecordingStorageProvider+} from "../pam-session-recording-storage-types";++const buildClient = (config: TPamRecordingResolvedConfig) => {+ if (!config.region || !config.awsCredentials) {+ throw new BadRequestError({ message: "AWS S3 storage backend requires region and credentials" });+ }+ return new S3Client({+ region: config.region,+ useFipsEndpoint: crypto.isFipsModeEnabled(),+ sha256: CustomAWSHasher,+ credentials: config.awsCredentials+ });+};++export const AwsS3RecordingStorageProvider: TPamRecordingStorageProvider = () => ({+ validateConfig: async ({ config }) => {+ if (!config.bucket) {+ throw new BadRequestError({ message: "Bucket is required for AWS S3 backend" });+ }+ const client = buildClient(config);+ try {+ await client.send(new HeadBucketCommand({ Bucket: config.bucket }));+ } catch (err) {+ logger.warn({ err, bucket: config.bucket }, `S3 HeadBucket failed [bucket=${config.bucket}]`);+ throw new BadRequestError({+ message: `Unable to access bucket. Verify region, credentials, and bucket policy [bucket=${config.bucket}]`+ });+ }++ const testKey = `${normalizeKeyPrefix(config.keyPrefix)}.test/${crypto.nativeCrypto.randomUUID()}`;++ try {+ await client.send(+ new PutObjectCommand({+ Bucket: config.bucket,+ Key: testKey,+ Body: Buffer.from("infisical-pam-recording-config-test"),+ ContentType: "application/octet-stream"+ })+ );+ } catch (err) {+ logger.warn({ err, bucket: config.bucket, testKey }, `S3 round-trip PutObject failed [bucket=${config.bucket}]`);+ throw new BadRequestError({+ message: "Bucket reachable but PutObject failed. Grant s3:PutObject on the configured key prefix"+ });+ }++ try {+ await client.send(+ new DeleteObjectsCommand({+ Bucket: config.bucket,+ Delete: { Objects: [{ Key: testKey }], Quiet: true }+ })+ );+ } catch (err) {+ logger.warn({ err, bucket: config.bucket, testKey }, `S3 test object cleanup failed [testKey=${testKey}]`);+ }+ },++ mintPresignedPut: async ({ config, projectId, sessionId, chunkIndex, ciphertextBytes, isKeyframe }) => {+ if (ciphertextBytes <= 0 || ciphertextBytes > PAM_RECORDING_MAX_CHUNK_BYTES) {+ throw new BadRequestError({+ message: `Chunk size out of range [bytes=${ciphertextBytes}, max=${PAM_RECORDING_MAX_CHUNK_BYTES}]`+ });+ }+ if (!config.bucket) throw new BadRequestError({ message: "Bucket is required" });++ const client = buildClient(config);+ const objectKey = buildExternalChunkObjectKey(+ config.keyPrefix,+ projectId,+ sessionId,+ chunkIndex,+ Boolean(isKeyframe)+ );++ const command = new PutObjectCommand({+ Bucket: config.bucket,+ Key: objectKey,+ ContentLength: ciphertextBytes,+ ContentType: "application/octet-stream"+ });++ const url = await getSignedUrl(client, command, {+ expiresIn: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS,+ unhoistableHeaders: new Set(["content-length"])+ });++ return {+ url,+ objectKey,+ method: "PUT" as const,+ expiresInSeconds: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS+ };+ },++ mintPresignedGet: async ({ config, objectKey }) => {+ if (!config.bucket) throw new BadRequestError({ message: "Bucket is required" });+ const client = buildClient(config);+ const command = new GetObjectCommand({ Bucket: config.bucket, Key: objectKey });+ const url = await getSignedUrl(client, command, { expiresIn: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS });+ return { url, expiresInSeconds: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS };+ },++ deleteSession: async ({ config, projectId, sessionId }) => {+ if (!config.bucket) throw new BadRequestError({ message: "Bucket is required" });+ const client = buildClient(config);++ const prefix = `${normalizeKeyPrefix(config.keyPrefix)}${projectId}/${sessionId}/`;++ let continuationToken: string | undefined;+ do {+ // eslint-disable-next-line no-await-in-loop+ const listed = await client.send(+ new ListObjectsV2Command({+ Bucket: config.bucket,+ Prefix: prefix,+ ContinuationToken: continuationToken+ })+ );+ const keys = (listed.Contents ?? []).map((o) => o.Key).filter((k): k is string => Boolean(k));+ if (keys.length > 0) {+ // eslint-disable-next-line no-await-in-loop+ await client.send(+ new DeleteObjectsCommand({+ Bucket: config.bucket,+ Delete: { Objects: keys.map((Key) => ({ Key })), Quiet: true }+ })+ );+ }+ continuationToken = listed.IsTruncated ? listed.NextContinuationToken : undefined;+ } while (continuationToken);+ }+});diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-constants.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-constants.tsnew file mode 100644index 0000000000..4b3551817d--- /dev/null+++ b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-constants.ts@@ -0,0 +1,6 @@+export const PAM_RECORDING_AAD_VERSION = "v1";++export const PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS = 300;++// 256 MB hard ceiling per chunk -- RDP can produce large keyframes+export const PAM_RECORDING_MAX_CHUNK_BYTES = 256 * 1024 * 1024;diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums.tsnew file mode 100644index 0000000000..8c3051434b--- /dev/null+++ b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums.ts@@ -0,0 +1,4 @@+export enum PamRecordingStorageBackend {+ Postgres = "postgres",+ AwsS3 = "aws-s3"+}diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-factory.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-factory.tsnew file mode 100644index 0000000000..cbc416293b--- /dev/null+++ b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-factory.ts@@ -0,0 +1,9 @@+import { AwsS3RecordingStorageProvider } from "./aws-s3/aws-s3-provider-factory";+import { PamRecordingStorageBackend } from "./pam-session-recording-storage-enums";+import { TPamRecordingStorageProvider } from "./pam-session-recording-storage-types";+import { PostgresRecordingStorageProvider } from "./postgres/postgres-provider-factory";++export const PAM_RECORDING_STORAGE_FACTORY_MAP: Record<PamRecordingStorageBackend, TPamRecordingStorageProvider> = {+ [PamRecordingStorageBackend.Postgres]: PostgresRecordingStorageProvider,+ [PamRecordingStorageBackend.AwsS3]: AwsS3RecordingStorageProvider+};diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-types.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-types.tsnew file mode 100644index 0000000000..615f2138e7--- /dev/null+++ b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-types.ts@@ -0,0 +1,67 @@+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";++import { PamRecordingStorageBackend } from "./pam-session-recording-storage-enums";++export type TPamRecordingChunkRef = {+ storageBackend: PamRecordingStorageBackend;+ externalChunkObjectKey?: string | null;+ encryptedEventsBlob?: Buffer | null;+};++export type TPamRecordingResolvedConfig = {+ backend: PamRecordingStorageBackend;+ bucket?: string;+ region?: AWSRegion;+ keyPrefix?: string | null;++ awsCredentials?: {+ accessKeyId: string;+ secretAccessKey: string;+ sessionToken?: string;+ };+};++export type TPamRecordingValidateConfig = (input: { config: TPamRecordingResolvedConfig }) => Promise<void>;++export type TPamRecordingMintPresignedPut = (input: {+ config: TPamRecordingResolvedConfig;+ projectId: string;+ sessionId: string;+ chunkIndex: number;+ ciphertextBytes: number;+ isKeyframe?: boolean;+}) => Promise<{ url: string; objectKey: string; expiresInSeconds: number; method: "PUT" }>;++export type TPamRecordingMintPresignedGet = (input: {+ config: TPamRecordingResolvedConfig;+ objectKey: string;+}) => Promise<{ url: string; expiresInSeconds: number }>;++export type TPamRecordingDeleteSession = (input: {+ config: TPamRecordingResolvedConfig;+ projectId: string;+ sessionId: string;+}) => Promise<void>;++export type TPamRecordingStorageProvider = () => {+ validateConfig: TPamRecordingValidateConfig;+ mintPresignedPut: TPamRecordingMintPresignedPut;+ mintPresignedGet: TPamRecordingMintPresignedGet;+ deleteSession: TPamRecordingDeleteSession;+};++export const normalizeKeyPrefix = (keyPrefix: string | null | undefined): string =>+ keyPrefix ? `${keyPrefix.replace(/^\/+|\/+$/g, "")}/` : "";++export const buildExternalChunkObjectKey = (+ keyPrefix: string | null | undefined,+ projectId: string,+ sessionId: string,+ chunkIndex: number,+ isKeyframe: boolean+): string => {+ const prefix = normalizeKeyPrefix(keyPrefix);+ const suffix = isKeyframe ? "keyframe.png.enc" : "json.enc";+ const padded = chunkIndex.toString().padStart(6, "0");+ return `${prefix}${projectId}/${sessionId}/chunk-${padded}.${suffix}`;+};diff --git a/backend/src/ee/services/pam-session-recording-storage/postgres/postgres-provider-factory.ts b/backend/src/ee/services/pam-session-recording-storage/postgres/postgres-provider-factory.tsnew file mode 100644index 0000000000..2618dfe200--- /dev/null+++ b/backend/src/ee/services/pam-session-recording-storage/postgres/postgres-provider-factory.ts@@ -0,0 +1,14 @@+import { TPamRecordingStorageProvider } from "../pam-session-recording-storage-types";++export const PostgresRecordingStorageProvider: TPamRecordingStorageProvider = () => ({+ validateConfig: async () => {},+ mintPresignedPut: async () => {+ throw new Error(+ "Postgres recording backend does not support presigned PUT URLs; gateway must POST ciphertext directly to backend"+ );+ },+ mintPresignedGet: async () => {+ throw new Error("Postgres recording backend does not support presigned GET URLs; backend serves ciphertext inline");+ },+ deleteSession: async () => {}+});diff --git a/backend/src/ee/services/pam-session/pam-session-chunk-service.ts b/backend/src/ee/services/pam-session/pam-session-chunk-service.tsnew file mode 100644index 0000000000..0b122b68a8--- /dev/null+++ b/backend/src/ee/services/pam-session/pam-session-chunk-service.ts@@ -0,0 +1,325 @@+import { ForbiddenError } from "@casl/ability";++import { ActionProjectType } from "@app/db/schemas";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { OrgServiceActor } from "@app/lib/types";+import { ActorType } from "@app/services/auth/auth-type";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";++import { PAM_RECORDING_MAX_CHUNK_BYTES } from "../pam-session-recording-storage/pam-session-recording-storage-constants";+import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";+import { PAM_RECORDING_STORAGE_FACTORY_MAP } from "../pam-session-recording-storage/pam-session-recording-storage-factory";+import {+ buildExternalChunkObjectKey,+ TPamRecordingResolvedConfig+} from "../pam-session-recording-storage/pam-session-recording-storage-types";+import { ProjectPermissionPamSessionActions, ProjectPermissionSub } from "../permission/project-permission";+import { TPamSessionDALFactory } from "./pam-session-dal";+import { PamSessionStatus } from "./pam-session-enums";+import { TPamSessionEventChunkDALFactory } from "./pam-session-event-chunk-dal";+import { decryptSessionKey, verifyGatewayUploadToken } from "./pam-session-recording-secrets";++type TPamSessionChunkServiceFactoryDep = {+ pamSessionDAL: TPamSessionDALFactory;+ pamSessionEventChunkDAL: TPamSessionEventChunkDALFactory;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+};++export type TPamSessionChunkServiceFactory = ReturnType<typeof pamSessionChunkServiceFactory>;++function assertGatewayActor(actor: OrgServiceActor) {+ if (actor.type !== ActorType.IDENTITY && actor.type !== ActorType.GATEWAY) {+ throw new ForbiddenRequestError({ message: "Only gateways can perform this action" });+ }+}++// eslint-disable-next-line @typescript-eslint/no-unused-vars+const resolveRecordingConfig = async (projectId: string): Promise<TPamRecordingResolvedConfig | null> => null;++export const pamSessionChunkServiceFactory = ({+ pamSessionDAL,+ pamSessionEventChunkDAL,+ permissionService,+ kmsService+}: TPamSessionChunkServiceFactoryDep) => {+ const requestPresignedPut = async (+ {+ sessionId,+ chunkIndex,+ ciphertextBytes,+ isKeyframe,+ uploadToken+ }: {+ sessionId: string;+ chunkIndex: number;+ ciphertextBytes: number;+ isKeyframe?: boolean;+ uploadToken: string;+ },+ actor: OrgServiceActor+ ) => {+ assertGatewayActor(actor);++ if (ciphertextBytes <= 0 || ciphertextBytes > PAM_RECORDING_MAX_CHUNK_BYTES) {+ throw new BadRequestError({+ message: `Chunk size out of range [bytes=${ciphertextBytes}, max=${PAM_RECORDING_MAX_CHUNK_BYTES}]`+ });+ }++ const session = await pamSessionDAL.findById(sessionId);+ if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });++ if (actor.type === ActorType.GATEWAY && session.gatewayId && session.gatewayId !== actor.id) {+ throw new ForbiddenRequestError({ message: "Gateway not authorized for this session" });+ }+ if (actor.type === ActorType.IDENTITY && session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {+ throw new ForbiddenRequestError({ message: "Identity not authorized for this session" });+ }++ verifyGatewayUploadToken(uploadToken, session.gatewayUploadTokenHash ?? null);++ const config = await resolveRecordingConfig(session.projectId);+ if (!config || config.backend === PamRecordingStorageBackend.Postgres) {+ throw new BadRequestError({+ message:+ "Project is not configured for object-storage recordings. Gateway should POST ciphertext to /chunks instead."+ });+ }++ const provider = PAM_RECORDING_STORAGE_FACTORY_MAP[config.backend]();+ const presigned = await provider.mintPresignedPut({+ config,+ projectId: session.projectId,+ sessionId,+ chunkIndex,+ ciphertextBytes,+ isKeyframe+ });++ return presigned;+ };++ const recordChunk = async (+ {+ sessionId,+ chunkIndex,+ startElapsedMs,+ endElapsedMs,+ ciphertextSha256Base64,+ ciphertextBytes,+ ivBase64,+ keyframeObjectKey,+ keyframeSizeBytes,++ // For Postgres backend, the gateway POSTs the ciphertext bytes inline+ ciphertext,+ uploadToken+ }: {+ sessionId: string;+ chunkIndex: number;+ startElapsedMs: number;+ endElapsedMs: number;+ ciphertextSha256Base64: string;+ ciphertextBytes: number;+ ivBase64: string;+ keyframeObjectKey?: string;+ keyframeSizeBytes?: number;+ ciphertext?: Buffer;+ uploadToken: string;+ },+ actor: OrgServiceActor+ ) => {+ assertGatewayActor(actor);++ const session = await pamSessionDAL.findById(sessionId);+ if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });++ if (actor.type === ActorType.GATEWAY && session.gatewayId && session.gatewayId !== actor.id) {+ throw new ForbiddenRequestError({ message: "Gateway not authorized for this session" });+ }+ if (actor.type === ActorType.IDENTITY && session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {+ throw new ForbiddenRequestError({ message: "Identity not authorized for this session" });+ }++ verifyGatewayUploadToken(uploadToken, session.gatewayUploadTokenHash ?? null);++ if (ciphertextBytes <= 0 || ciphertextBytes > PAM_RECORDING_MAX_CHUNK_BYTES) {+ throw new BadRequestError({+ message: `Chunk size out of range [bytes=${ciphertextBytes}, max=${PAM_RECORDING_MAX_CHUNK_BYTES}]`+ });+ }++ const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;+ if (!BASE64_RE.test(ciphertextSha256Base64) || !BASE64_RE.test(ivBase64)) {+ throw new BadRequestError({ message: "Invalid base64 in chunk metadata" });+ }+ const ciphertextSha256 = Buffer.from(ciphertextSha256Base64, "base64");+ const iv = Buffer.from(ivBase64, "base64");+ if (ciphertextSha256.length !== 32) {+ throw new BadRequestError({ message: "ciphertextSha256 must be 32 bytes (sha256 digest)" });+ }+ if (iv.length !== 12) {+ throw new BadRequestError({ message: "iv must be 12 bytes (AES-GCM standard)" });+ }++ const config = await resolveRecordingConfig(session.projectId);+ const backend = config?.backend ?? PamRecordingStorageBackend.Postgres;++ if (backend === PamRecordingStorageBackend.Postgres) {+ if (!ciphertext) {+ throw new BadRequestError({+ message: "Postgres backend requires the ciphertext bytes to be POSTed inline"+ });+ }+ if (ciphertext.length !== ciphertextBytes) {+ throw new BadRequestError({+ message: `Declared ciphertextBytes does not match body length [declared=${ciphertextBytes}, actual=${ciphertext.length}]`+ });+ }+ }++ const externalChunkObjectKey =+ backend === PamRecordingStorageBackend.AwsS3+ ? buildExternalChunkObjectKey(config?.keyPrefix, session.projectId, sessionId, chunkIndex, false)+ : null;++ const externalKeyframeObjectKey =+ backend === PamRecordingStorageBackend.AwsS3 && keyframeObjectKey+ ? buildExternalChunkObjectKey(config?.keyPrefix, session.projectId, sessionId, chunkIndex, true)+ : null;++ try {+ await pamSessionEventChunkDAL.insertIgnoreDuplicate({+ sessionId,+ chunkIndex,+ startElapsedMs,+ endElapsedMs,+ storageBackend: backend,+ encryptedEventsBlob: backend === PamRecordingStorageBackend.Postgres ? (ciphertext ?? null) : null,+ externalChunkObjectKey,+ chunkSizeBytes: backend === PamRecordingStorageBackend.AwsS3 ? ciphertextBytes : null,+ externalKeyframeObjectKey,+ keyframeSizeBytes: keyframeSizeBytes ?? null,+ ciphertextSha256,+ ciphertextBytes,+ iv+ });+ } catch (err) {+ logger.error(+ { sessionId, chunkIndex, err },+ `Chunk insert failed [sessionId=${sessionId}] [chunkIndex=${chunkIndex}]`+ );+ throw err;+ }++ return { ok: true as const, projectId: session.projectId, storageBackend: backend };+ };++ const getPlaybackBundle = async (sessionId: string, actor: OrgServiceActor) => {+ const session = await pamSessionDAL.findById(sessionId);+ if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId: session.projectId,+ actionProjectType: ActionProjectType.PAM+ });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionPamSessionActions.Read,+ ProjectPermissionSub.PamSessions+ );++ const sessionComplete = session.status !== PamSessionStatus.Active && session.status !== PamSessionStatus.Starting;++ if (!session.encryptedSessionKey) {+ // Legacy session fall through to legacy decrypt path+ return { sessionKey: null, chunks: [], legacy: true as const, sessionComplete };+ }++ const sessionKey = await decryptSessionKey({+ projectId: session.projectId,+ sessionId,+ encryptedSessionKey: session.encryptedSessionKey,+ kmsService+ });++ const chunks = await pamSessionEventChunkDAL.findAllBySessionId(sessionId);++ let presignedGetByObjectKey: Record<string, { url: string }> = {};+ const config = await resolveRecordingConfig(session.projectId);+ if (config?.backend === PamRecordingStorageBackend.AwsS3) {+ const provider = PAM_RECORDING_STORAGE_FACTORY_MAP[config.backend]();+ const minted = await Promise.all(+ chunks+ .filter((c) => c.storageBackend === PamRecordingStorageBackend.AwsS3 && c.externalChunkObjectKey)+ .map(async (c) => {+ const presigned = await provider.mintPresignedGet({+ config,+ objectKey: c.externalChunkObjectKey as string+ });+ return [c.externalChunkObjectKey as string, { url: presigned.url }] as const;+ })+ );+ presignedGetByObjectKey = Object.fromEntries(minted);+ }++ return {+ sessionKey: sessionKey.toString("base64"),+ legacy: false as const,+ sessionComplete,+ projectId: session.projectId,+ storageBackend: config?.backend ?? PamRecordingStorageBackend.Postgres,+ chunks: chunks.map((c) => ({+ chunkIndex: c.chunkIndex,+ startElapsedMs: Number(c.startElapsedMs),+ endElapsedMs: Number(c.endElapsedMs),+ storageBackend: c.storageBackend as PamRecordingStorageBackend,+ externalChunkObjectKey: c.externalChunkObjectKey ?? null,+ ciphertextSha256: c.ciphertextSha256.toString("base64"),+ ciphertextBytes: Number(c.ciphertextBytes),+ iv: c.iv.toString("base64"),+ presignedGetUrl: c.externalChunkObjectKey+ ? (presignedGetByObjectKey[c.externalChunkObjectKey]?.url ?? null)+ : null+ }))+ };+ };++ const getChunkCiphertext = async (sessionId: string, chunkIndex: number, actor: OrgServiceActor) => {+ const session = await pamSessionDAL.findById(sessionId);+ if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId: session.projectId,+ actionProjectType: ActionProjectType.PAM+ });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionPamSessionActions.Read,+ ProjectPermissionSub.PamSessions+ );++ const chunk = await pamSessionEventChunkDAL.findByChunkIndex(sessionId, chunkIndex);+ if (!chunk) throw new NotFoundError({ message: `Chunk ${chunkIndex} not found` });+ if (chunk.storageBackend !== PamRecordingStorageBackend.Postgres) {+ throw new BadRequestError({+ message: "Chunk is stored externally; use the presigned GET URL from the playback endpoint"+ });+ }+ if (!chunk.encryptedEventsBlob) {+ throw new BadRequestError({ message: "Chunk has no inline ciphertext" });+ }+ return { ciphertext: chunk.encryptedEventsBlob };+ };++ return { requestPresignedPut, recordChunk, getPlaybackBundle, getChunkCiphertext };+};diff --git a/backend/src/ee/services/pam-session/pam-session-dal.ts b/backend/src/ee/services/pam-session/pam-session-dal.tsindex 57047abdc6..2b118fc1e9 100644--- a/backend/src/ee/services/pam-session/pam-session-dal.ts+++ b/backend/src/ee/services/pam-session/pam-session-dal.ts@@ -76,6 +76,31 @@ export const pamSessionDALFactory = (db: TDbClient) => {return sessions;};+ const findAccessibleByProjectId = async (+ projectId: string,+ accessibleFolderIds: string[],+ accessibleAccountIds: string[],+ tx?: Knex+ ) => {+ const sessions = await (tx || db.replicaNode())(TableName.PamSession)+ .leftJoin(TableName.GatewayV2, `${TableName.GatewayV2}.id`, `${TableName.PamSession}.gatewayId`)+ .leftJoin(TableName.PamAccount, `${TableName.PamAccount}.id`, `${TableName.PamSession}.accountId`)+ .select(selectAllTableCols(TableName.PamSession))+ .select(db.ref("name").withSchema(TableName.GatewayV2).as("gatewayName"))+ .select(db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId"))+ .where(`${TableName.PamSession}.projectId`, projectId)+ .where((builder) => {+ if (accessibleFolderIds.length > 0) {+ void builder.whereIn(`${TableName.PamAccount}.folderId`, accessibleFolderIds);+ }+ if (accessibleAccountIds.length > 0) {+ void builder.orWhereIn(`${TableName.PamSession}.accountId`, accessibleAccountIds);+ }+ });++ return sessions;+ };+return {...orm,findById,@@ -83,6 +108,7 @@ export const pamSessionDALFactory = (db: TDbClient) => {endExpiredWebSessions,endSessionById,activateSession,- findByProjectId+ findByProjectId,+ findAccessibleByProjectId};};diff --git a/backend/src/ee/services/pam-session/pam-session-event-chunk-dal.ts b/backend/src/ee/services/pam-session/pam-session-event-chunk-dal.tsnew file mode 100644index 0000000000..58e323a3bc--- /dev/null+++ b/backend/src/ee/services/pam-session/pam-session-event-chunk-dal.ts@@ -0,0 +1,28 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TPamSessionEventChunksInsert } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TPamSessionEventChunkDALFactory = ReturnType<typeof pamSessionEventChunkDALFactory>;++export const pamSessionEventChunkDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.PamSessionEventChunk);++ const findAllBySessionId = async (sessionId: string, tx?: Knex) => {+ return (tx || db.replicaNode())(TableName.PamSessionEventChunk)+ .where("sessionId", sessionId)+ .orderBy("chunkIndex", "asc")+ .select("*");+ };++ const findByChunkIndex = async (sessionId: string, chunkIndex: number, tx?: Knex) => {+ return (tx || db.replicaNode())(TableName.PamSessionEventChunk).where({ sessionId, chunkIndex }).first();+ };++ const insertIgnoreDuplicate = async (data: TPamSessionEventChunksInsert, tx?: Knex) => {+ await (tx || db)(TableName.PamSessionEventChunk).insert(data).onConflict(["sessionId", "chunkIndex"]).ignore();+ };++ return { ...orm, findAllBySessionId, findByChunkIndex, insertIgnoreDuplicate };+};diff --git a/backend/src/ee/services/pam-session/pam-session-recording-secrets.ts b/backend/src/ee/services/pam-session/pam-session-recording-secrets.tsnew file mode 100644index 0000000000..f633f98d1d--- /dev/null+++ b/backend/src/ee/services/pam-session/pam-session-recording-secrets.ts@@ -0,0 +1,104 @@+import { crypto } from "@app/lib/crypto/cryptography";+import { BadRequestError, InternalServerError } from "@app/lib/errors";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";++import { PAM_RECORDING_AAD_VERSION } from "../pam-session-recording-storage/pam-session-recording-storage-constants";++const SESSION_KEY_LENGTH = 32; // AES-256+const UPLOAD_TOKEN_LENGTH = 32; // 256 random bits++const buildWrapAad = (projectId: string, sessionId: string) =>+ crypto.nativeCrypto.createHash("sha256").update(`${projectId}|${sessionId}|${PAM_RECORDING_AAD_VERSION}`).digest();++export const generateSessionRecordingSecrets = async ({+ projectId,+ sessionId,+ kmsService+}: {+ projectId: string;+ sessionId: string;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+}) => {+ const sessionKey = crypto.randomBytes(SESSION_KEY_LENGTH);+ const uploadToken = crypto.randomBytes(UPLOAD_TOKEN_LENGTH);++ const wrapAad = buildWrapAad(projectId, sessionId);++ const { encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });++ // KMS createCipherPairWithDataKey doesn't expose a native AAD parameter, so we prepend the AAD bytes to the plaintext before wrapping+ // Unwrap then verifies the prefix matches the expected AAD with a constant-time compare+ const encryptionPayload = Buffer.concat([wrapAad, sessionKey]);+ const { cipherTextBlob: encryptedSessionKey } = encryptor({ plainText: encryptionPayload });++ const uploadTokenHash = crypto.nativeCrypto.createHash("sha256").update(uploadToken).digest();++ return {+ sessionKey,+ uploadToken,+ encryptedSessionKey,+ uploadTokenHash+ };+};++export const decryptSessionKey = async ({+ projectId,+ sessionId,+ encryptedSessionKey,+ kmsService+}: {+ projectId: string;+ sessionId: string;+ encryptedSessionKey: Buffer;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+}) => {+ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });++ const decrypted = decryptor({ cipherTextBlob: encryptedSessionKey });+ if (decrypted.length !== 32 + SESSION_KEY_LENGTH) {+ throw new InternalServerError({ message: "Encrypted session key has unexpected size" });+ }+ const recoveredAad = decrypted.subarray(0, 32);+ const expectedAad = buildWrapAad(projectId, sessionId);+ if (!crypto.nativeCrypto.timingSafeEqual(recoveredAad, expectedAad)) {+ throw new InternalServerError({ message: "Session key AAD mismatch — refusing to unwrap" });+ }+ return decrypted.subarray(32, 32 + SESSION_KEY_LENGTH);+};++export const verifyGatewayUploadToken = (+ presentedTokenBase64: string | undefined | null,+ storedTokenHash: Buffer | null | undefined+) => {+ if (!presentedTokenBase64 || !storedTokenHash) {+ throw new BadRequestError({+ message: "Gateway upload token missing or session not configured for chunked uploads"+ });+ }+ let presentedBuf: Buffer;+ try {+ presentedBuf = Buffer.from(presentedTokenBase64, "base64");+ } catch {+ throw new BadRequestError({ message: "Invalid upload token" });+ }+ if (presentedBuf.length !== UPLOAD_TOKEN_LENGTH) {+ throw new BadRequestError({ message: "Invalid upload token" });+ }+ const presentedHash = crypto.nativeCrypto.createHash("sha256").update(presentedBuf).digest();+ if (presentedHash.length !== storedTokenHash.length) {+ throw new BadRequestError({ message: "Invalid upload token" });+ }+ if (!crypto.nativeCrypto.timingSafeEqual(presentedHash, storedTokenHash)) {+ throw new BadRequestError({ message: "Invalid upload token" });+ }+};++export const SESSION_KEY_BYTES = SESSION_KEY_LENGTH;+export const UPLOAD_TOKEN_BYTES = UPLOAD_TOKEN_LENGTH;diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.tsnew file mode 100644index 0000000000..7cf8703fcd--- /dev/null+++ b/backend/src/ee/services/pam-session/pam-session-service.ts@@ -0,0 +1,163 @@+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";++import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";+import {+ checkAccountAccess,+ getAccessibleResourceIds,+ TActorContext,+ verifyProductMembership+} from "../pam-membership/pam-permission";+import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";+import { ResourcePermissionPamResourceActions } from "../permission/resource-permission";+import { TPamSessionDALFactory } from "./pam-session-dal";+import { PamSessionStatus } from "./pam-session-enums";+import { generateSessionRecordingSecrets } from "./pam-session-recording-secrets";++type TPamSessionServiceFactoryDep = {+ pamSessionDAL: Pick<+ TPamSessionDALFactory,+ "findAccessibleByProjectId" | "findById" | "findOne" | "endSessionById" | "updateById"+ >;+ pamAccountDAL: Pick<TPamAccountDALFactory, "findByIdWithDetails">;+ membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+};++export type TPamSessionServiceFactory = ReturnType<typeof pamSessionServiceFactory>;++export const pamSessionServiceFactory = ({+ pamSessionDAL,+ pamAccountDAL,+ membershipDAL,+ permissionService,+ kmsService+}: TPamSessionServiceFactoryDep) => {+ const decrypt = async (projectId: string, blob: Buffer): Promise<Record<string, unknown>> => {+ const { decryptor } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });+ return JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>;+ };++ const checkAccount = (+ accountId: string,+ folderId: string | null | undefined,+ projectId: string,+ action: ResourcePermissionPamResourceActions,+ ctx: TActorContext+ ) => checkAccountAccess(permissionService, accountId, folderId, projectId, action, ctx);++ const listSessions = async (projectId: string, ctx: TActorContext) => {+ await verifyProductMembership(permissionService, projectId, ctx);++ const { folderIds, accountIds } = await getAccessibleResourceIds(membershipDAL, projectId, ctx);+ if (folderIds.length === 0 && accountIds.length === 0) return [];++ return pamSessionDAL.findAccessibleByProjectId(projectId, folderIds, accountIds);+ };++ const getSessionById = async (sessionId: string, ctx: TActorContext) => {+ const session = await pamSessionDAL.findById(sessionId);+ if (!session || !session.accountId) return null;++ const account = await pamAccountDAL.findByIdWithDetails(session.accountId);+ await checkAccount(+ session.accountId,+ account?.folderId,+ session.projectId,+ ResourcePermissionPamResourceActions.ViewSessions,+ ctx+ );++ return session;+ };++ // Called by the gateway+ const getSessionCredentials = async (sessionId: string, gatewayId: string) => {+ const session = await pamSessionDAL.findOne({ id: sessionId, gatewayId });+ if (!session) {+ throw new NotFoundError({ message: "Session not found" });+ }++ if (session.status !== PamSessionStatus.Starting && session.status !== PamSessionStatus.Active) {+ throw new BadRequestError({ message: "Session is not active" });+ }++ if (!session.accountId) {+ throw new BadRequestError({ message: "Session has no linked account" });+ }++ const account = await pamAccountDAL.findByIdWithDetails(session.accountId);+ if (!account) {+ throw new NotFoundError({ message: "Account not found" });+ }++ const connectionDetails = await decrypt(session.projectId, account.encryptedConnectionDetails);+ const credentials = await decrypt(session.projectId, account.encryptedCredentials);++ const sessionStarted = session.status === PamSessionStatus.Starting;++ let recording: {+ sessionKey: string;+ uploadToken: string;+ storageBackend: PamRecordingStorageBackend;+ projectId: string;+ sessionId: string;+ } | null = null;++ if (!session.encryptedSessionKey) {+ const secrets = await generateSessionRecordingSecrets({+ projectId: session.projectId,+ sessionId,+ kmsService+ });++ await pamSessionDAL.updateById(sessionId, {+ encryptedSessionKey: secrets.encryptedSessionKey,+ gatewayUploadTokenHash: secrets.uploadTokenHash+ });++ recording = {+ sessionKey: secrets.sessionKey.toString("base64"),+ uploadToken: secrets.uploadToken.toString("base64"),+ storageBackend: PamRecordingStorageBackend.Postgres,+ projectId: session.projectId,+ sessionId+ };+ }++ return {+ credentials: { ...connectionDetails, ...credentials },+ recording,+ projectId: session.projectId,+ accountName: session.accountName,+ sessionStarted+ };+ };++ // Called by the gateway+ const endSessionFromGateway = async (sessionId: string, gatewayId: string) => {+ const session = await pamSessionDAL.findOne({ id: sessionId, gatewayId });+ if (!session) {+ throw new NotFoundError({ message: "Session not found" });+ }++ const updatedSession = await pamSessionDAL.endSessionById(sessionId);++ return {+ projectId: session.projectId,+ accountName: session.accountName,+ alreadyEnded: !updatedSession+ };+ };++ return {+ listSessions,+ getSessionById,+ getSessionCredentials,+ endSessionFromGateway+ };+};diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.tsindex fb4d98c93d..a8e6945bad 100644--- a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts@@ -1,7 +1,6 @@import crypto from "crypto";import { PamAccountType } from "@app/ee/services/pam/pam-enums";-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";import { logger } from "@app/lib/logger";import {@@ -247,6 +246,6 @@ const handlePostgresSession = async (};registerSessionHandler(PamAccountType.Postgres, {- gatewayResourceType: PamResource.Postgres,+ gatewayResourceType: PamAccountType.Postgres,handler: handlePostgresSession});diff --git a/backend/src/ee/services/pam-web-access/pam-session-handler-registry.ts b/backend/src/ee/services/pam-web-access/pam-session-handler-registry.tsindex bee167a029..9d25e52efb 100644--- a/backend/src/ee/services/pam-web-access/pam-session-handler-registry.ts+++ b/backend/src/ee/services/pam-web-access/pam-session-handler-registry.ts@@ -1,5 +1,4 @@import { PamAccountType } from "@app/ee/services/pam/pam-enums";-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";import { TSessionContext, TSessionHandlerResult } from "./pam-web-access-types";@@ -9,7 +8,7 @@ export type TWebAccessHandler = () => Promise<TSessionHandlerResult>;type TSessionHandlerEntry = {- gatewayResourceType: PamResource;+ gatewayResourceType: PamAccountType;handler: TWebAccessHandler;};diff --git a/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.tsindex e9186588a7..c3a99029ae 100644--- a/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts+++ b/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts@@ -1,7 +1,6 @@import { Client, type ClientChannel, type ConnectConfig } from "ssh2";import { PamAccountType } from "@app/ee/services/pam/pam-enums";-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";import { logger } from "@app/lib/logger";import { registerSessionHandler } from "./pam-session-handler-registry";@@ -131,6 +130,6 @@ const handleSSHSession = async (};registerSessionHandler(PamAccountType.SSH, {- gatewayResourceType: PamResource.SSH,+ gatewayResourceType: PamAccountType.SSH,handler: handleSSHSession});diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.tsindex a83035ee63..6f2065603b 100644--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts@@ -11,6 +11,7 @@ import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/servicimport { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { PamAccountType } from "@app/ee/services/pam/pam-enums";+import { PamTemplateAccessPolicySchema } from "@app/ee/services/pam-account-template/pam-template-config-schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ResourcePermissionPamResourceActions,@@ -76,6 +77,7 @@ type THandleWebSocketConnectionDTO = {actorIp: string;actorUserAgent: string;reason: string | null | undefined;+ maxSessionDurationMs?: number;preAuthMessages: TEarlyBufferedMsg[];preAuthHandler: (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => void;};@@ -185,6 +187,23 @@ export const pamWebAccessServiceFactory = ({const trimmedReason = reason?.trim() || null;+ const accessPolicy = account.templateAccessPolicy+ ? PamTemplateAccessPolicySchema.safeParse(account.templateAccessPolicy)+ : null;+ const policy = accessPolicy?.success ? accessPolicy.data : null;++ if (policy?.requireReason && !trimmedReason) {+ throw new BadRequestError({ message: "A reason is required to access this account" });+ }++ if (policy?.requireMfa) {+ throw new BadRequestError({ message: "MFA verification is required to access this account" });+ }++ const maxSessionDurationMs = policy?.maxSessionDurationSeconds+ ? policy.maxSessionDurationSeconds * 1000+ : DEFAULT_WEB_SESSION_DURATION_MS;+await checkLaunchPermission(projectId, accountId, account.folderId, {actorId: actor.id,actor: actor.type,@@ -212,7 +231,8 @@ export const pamWebAccessServiceFactory = ({actorEmail,actorName,auditLogInfo,- reason: trimmedReason+ reason: trimmedReason,+ maxSessionDurationMs})});@@ -246,6 +266,7 @@ export const pamWebAccessServiceFactory = ({actorIp,actorUserAgent,reason: accessReason,+ maxSessionDurationMs: policyDurationMs,preAuthMessages,preAuthHandler}: THandleWebSocketConnectionDTO): Promise<void> => {@@ -389,7 +410,7 @@ export const pamWebAccessServiceFactory = ({const credentials = await decrypt(projectId, account.encryptedCredentials);const user = await userDAL.findById(userId);- const sessionDurationMs = DEFAULT_WEB_SESSION_DURATION_MS;+ const sessionDurationMs = policyDurationMs || DEFAULT_WEB_SESSION_DURATION_MS;const expiresAt = new Date(Date.now() + sessionDurationMs);session = await pamSessionDAL.create({@@ -403,7 +424,6 @@ export const pamWebAccessServiceFactory = ({actorName,actorUserAgent,projectId,- resourceName: account.name,accountId: account.id,userId,gatewayId: effectiveGatewayId,diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.mdnew file mode 100644index 0000000000..67077849cf--- /dev/null+++ b/backend/src/ee/services/pam/CLAUDE.md@@ -0,0 +1,105 @@+# PAM Backend — CLAUDE.md++Any core logic, shared helper, or convention introduced for PAM must be documented here. This file is the source of truth for PAM backend patterns.++## Module Layout++All PAM services live under `backend/src/ee/services/pam-*/`:++| Directory | Purpose |+|---|---|+| `pam/` | Shared enums (`PamAccountType`, `PamResourceRole`, `PamProductRole`) and this CLAUDE.md |+| `pam-folder/` | Folder CRUD, folder-level permission checks |+| `pam-account/` | Account CRUD, credential encryption, gateway attachment |+| `pam-account-template/` | Account templates (type + access policy + settings), template config schemas |+| `pam-session/` | Session lifecycle, recording secrets |+| `pam-session-recording-storage/` | Recording chunk storage + retrieval |+| `pam-membership/` | Product + resource membership management, shared permission helpers |+| `pam-web-access/` | WebSocket session handlers (Postgres, SSH), ticket-based auth |++Routes live in `backend/src/ee/routes/v1/pam-routers/`.++## Permission Model++PAM uses a two-tier permission system: product membership + resource membership.++### Shared Helpers (`pam-membership/pam-permission.ts`)++All PAM services import from this module rather than duplicating permission logic.++- **`TActorContext`** — standard actor fields: `{ actorId, actor, actorOrgId, actorAuthMethod }`+- **`verifyProductMembership(permissionService, projectId, ctx)`** — confirms the actor is a member of the PAM project. Returns `{ hasRole }` for checking product-level roles (Admin/Member).+- **`checkFolderPermission(permissionService, folderId, projectId, ctx)`** — checks resource-scoped permission on a folder. Returns `{ permission }` for `throwUnlessCan` calls.+- **`checkAccountAccess(permissionService, accountId, folderId, projectId, action, ctx)`** — tries folder-level permission first (if the account has a folder), falls back to direct account-level permission. This is the standard pattern for any account-scoped action.+- **`getAccessibleResourceIds(membershipDAL, projectId, ctx)`** — returns `{ folderIds, accountIds }` the actor has resource memberships on. Used by list endpoints to scope queries.++Services create thin local wrappers that bind their own `permissionService` dependency:+```ts+const verifyMembership = (projectId, ctx) => verifyProductMembership(permissionService, projectId, ctx);+const checkAccount = (accountId, folderId, projectId, action, ctx) => checkAccountAccess(permissionService, ...);+```++### Roles++- **Product roles** (`PamProductRole`): `Admin`, `Member`+- **Resource roles** (`PamResourceRole`): `Admin`, `Requester`, `Auditor`++Resource memberships are scoped to either a `PamFolder` or a `PamAccount` via the generic membership system (`ResourceType.PamFolder` / `ResourceType.PamAccount`).++## Account Types++Defined in `pam/pam-enums.ts` as `PamAccountType`. Validation schemas per type live in `pam-account/pam-account-schemas.ts` in the `ACCOUNT_TYPE_CONFIGS` map.++### Adding a New Account Type++1. Add the enum value to `PamAccountType` in `pam/pam-enums.ts`+2. Add `connectionDetails` and `credentials` Zod schemas to `ACCOUNT_TYPE_CONFIGS` in `pam-account/pam-account-schemas.ts`+3. If it supports web access: add a session handler in `pam-web-access/` and register it in `pam-session-handler-registry.ts`+4. Add the corresponding frontend enum value and any UI components+5. Update `PamAccountType` on the frontend enum in `frontend/src/hooks/api/pam/enums.ts`++## Session Lifecycle++- Sessions reference accounts via nullable `accountId` (SET NULL on delete) so session history survives account deletion+- Orphaned sessions (accountId is null) are excluded from all queries: `listSessions` filters them at the SQL level via joins, `getSessionById` returns null+- Active sessions track `status` (Starting -> Active -> Ended) with timestamps+- Recording secrets are generated on first credential fetch and stored encrypted on the session row++## DAL Conventions++- Read methods use `db.replicaNode()`, writes hit primary+- All methods accept optional `tx` for transaction threading+- List queries that respect permissions use the accessible-resource pattern: join to the resource table and filter with `WHERE (folderId IN (...) OR accountId IN (...))`+- Gateway joins (for `gatewayName`/`gatewayIdentityId`) are repeated per-method since the select/join context differs++## Deferred Cleanup++Old tables, columns, and code kept temporarily so data can be recovered if the migration causes issues. Target removal: ~1 month after all deployments are running the new model (safe after 2026-08-01). A follow-up migration should handle the drops.++### Stale queue cleanup entries++`backend/src/queue/queue-service.ts` stale queue list includes `pam-account-rotation` and `pam-session-ai-summary`. These ensure existing Redis instances get cleaned up on deploy. Remove them from the list after all deployments have booted at least once with the new code.++### Tables to drop++- `pam_resources`+- `pam_domains`+- `pam_account_policies`+- `pam_resource_rotation_rules`+- `pam_account_dependencies`+- `pam_resource_favorites`+- `pam_project_recording_configs`+- `pam_discovery_sources`, `pam_discovery_source_runs`, `pam_discovery_source_resources`, `pam_discovery_source_accounts`, `pam_discovery_source_dependencies` (when discovery is reimplemented)+- `pam_session_event_batches` (legacy logging, replaced by chunks)++### Columns to drop from `pam_accounts`++`resourceId`, `domainId`, `policyId`, `lastRotatedAt`, `rotationStatus`, `encryptedLastRotationMessage`, `requireMfa`, `internalMetadata`, `discoveryFingerprint`++### Columns to drop from `pam_sessions`++`resourceName`, `resourceId`, `selectedResourceId`, `encryptedAiInsights`, `aiInsightsStatus`, `aiInsightsError`, `encryptedLogsBlob`++## DI Wiring++All PAM factories are wired in `backend/src/server/routes/index.ts`. When adding a new dependency to a PAM service, update the wiring there and narrow the type with `Pick<>` in the service's dependency type.diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.tsindex 734b4d2777..d837389f00 100644--- a/backend/src/ee/services/pam/pam-enums.ts+++ b/backend/src/ee/services/pam/pam-enums.ts@@ -22,8 +22,3 @@ export enum PamProductRole {Admin = "admin",Member = "member"}--export enum PamRecordingStorageBackend {- Postgres = "postgres",- AwsS3 = "aws-s3"-}diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex 56964da7c9..f3271b1ae4 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -24,7 +24,6 @@ import {ProjectPermissionMemberActions,ProjectPermissionPamAccountActions,ProjectPermissionPamAccountPolicyActions,- ProjectPermissionPamDiscoveryActions,ProjectPermissionPamInsightsActions,ProjectPermissionPamSessionActions,ProjectPermissionPkiCertificateInstallationActions,@@ -79,8 +78,6 @@ const buildAdminPermissionRules = () => {ProjectPermissionSub.SshCertificateTemplates,ProjectPermissionSub.SshHostGroups,ProjectPermissionSub.PamFolders,- ProjectPermissionSub.PamResources,- ProjectPermissionSub.PamDomains,ProjectPermissionSub.McpServers,ProjectPermissionSub.McpActivityLogs].forEach((el) => {@@ -447,17 +444,6 @@ const buildAdminPermissionRules = () => {ProjectPermissionSub.PamAccountPolicies);- can(- [- ProjectPermissionPamDiscoveryActions.Read,- ProjectPermissionPamDiscoveryActions.Create,- ProjectPermissionPamDiscoveryActions.Edit,- ProjectPermissionPamDiscoveryActions.Delete,- ProjectPermissionPamDiscoveryActions.RunScan- ],- ProjectPermissionSub.PamDiscovery- );-can([ProjectPermissionPamInsightsActions.Read], ProjectPermissionSub.PamInsights);can(@@ -694,10 +680,6 @@ const buildMemberPermissionRules = () => {can([ProjectPermissionActions.Read], ProjectPermissionSub.PamFolders);- can([ProjectPermissionActions.Read], ProjectPermissionSub.PamResources);-- can([ProjectPermissionActions.Read], ProjectPermissionSub.PamDomains);-can([ProjectPermissionPamAccountActions.Access, ProjectPermissionPamAccountActions.Read],ProjectPermissionSub.PamAccounts@@ -705,8 +687,6 @@ const buildMemberPermissionRules = () => {can([ProjectPermissionPamAccountPolicyActions.Read], ProjectPermissionSub.PamAccountPolicies);- can([ProjectPermissionPamDiscoveryActions.Read], ProjectPermissionSub.PamDiscovery);-can([ProjectPermissionPamInsightsActions.Read], ProjectPermissionSub.PamInsights);can([ProjectPermissionMcpEndpointActions.Read], ProjectPermissionSub.McpEndpoints);@@ -788,16 +768,10 @@ const buildViewerPermissionRules = () => {can([ProjectPermissionActions.Read], ProjectPermissionSub.PamFolders);- can([ProjectPermissionActions.Read], ProjectPermissionSub.PamResources);-- can([ProjectPermissionActions.Read], ProjectPermissionSub.PamDomains);-can([ProjectPermissionPamAccountActions.Read], ProjectPermissionSub.PamAccounts);can([ProjectPermissionPamAccountPolicyActions.Read], ProjectPermissionSub.PamAccountPolicies);- can([ProjectPermissionPamDiscoveryActions.Read], ProjectPermissionSub.PamDiscovery);-can([ProjectPermissionPamInsightsActions.Read], ProjectPermissionSub.PamInsights);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 0b7f5a97d8..f69c6b32b0 100644--- a/backend/src/ee/services/permission/project-permission.ts+++ b/backend/src/ee/services/permission/project-permission.ts@@ -285,14 +285,6 @@ export enum ProjectPermissionPamInsightsActions {Read = "read"}-export enum ProjectPermissionPamDiscoveryActions {- Read = "read",- Create = "create",- Edit = "edit",- Delete = "delete",- RunScan = "run-scan"-}-export enum ProjectPermissionMcpEndpointActions {Read = "read",Create = "create",@@ -376,12 +368,9 @@ export enum ProjectPermissionSub {SecretEventSubscriptions = "secret-event-subscriptions",AppConnections = "app-connections",PamFolders = "pam-folders",- PamResources = "pam-resources",- PamDomains = "pam-domains",PamAccounts = "pam-accounts",PamSessions = "pam-sessions",PamAccountPolicies = "pam-account-policies",- PamDiscovery = "pam-discovery",PamInsights = "pam-insights",CertificateProfiles = "certificate-profiles",CertificatePolicies = "certificate-policies",@@ -574,18 +563,6 @@ export type PamAccountSubjectFields = {metadata?: { key: string; value: string }[];};-export type PamResourceSubjectFields = {- name: string;- resourceType: string;- metadata?: { key: string; value: string }[];-};--export type PamDomainSubjectFields = {- name: string;- domainType: string;- metadata?: { key: string; value: string }[];-};-export type ProjectPermissionSet =| [ProjectPermissionSecretActions,@@ -717,21 +694,12 @@ export type ProjectPermissionSet =)]| [ProjectPermissionActions, ProjectPermissionSub.PamFolders]- | [- ProjectPermissionActions,- ProjectPermissionSub.PamResources | (ForcedSubject<ProjectPermissionSub.PamResources> & PamResourceSubjectFields)- ]- | [- ProjectPermissionActions,- ProjectPermissionSub.PamDomains | (ForcedSubject<ProjectPermissionSub.PamDomains> & PamDomainSubjectFields)- ]| [ProjectPermissionPamAccountActions,ProjectPermissionSub.PamAccounts | (ForcedSubject<ProjectPermissionSub.PamAccounts> & PamAccountSubjectFields)]| [ProjectPermissionPamSessionActions, ProjectPermissionSub.PamSessions]| [ProjectPermissionPamAccountPolicyActions, ProjectPermissionSub.PamAccountPolicies]- | [ProjectPermissionPamDiscoveryActions, ProjectPermissionSub.PamDiscovery]| [ProjectPermissionPamInsightsActions, ProjectPermissionSub.PamInsights]| [ProjectPermissionMcpEndpointActions,@@ -1405,100 +1373,6 @@ const PamAccountConditionSchema = z}).partial();-const PamResourceConditionSchema = z- .object({- name: z.union([- z.string(),- z- .object({- [PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],- [PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],- [PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN],- [PermissionConditionOperators.$GLOB]: PermissionConditionSchema[PermissionConditionOperators.$GLOB]- })- .partial()- ]),- resourceType: z.union([- z.string(),- z- .object({- [PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],- [PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],- [PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN],- [PermissionConditionOperators.$GLOB]: PermissionConditionSchema[PermissionConditionOperators.$GLOB]- })- .partial()- ]),- metadata: z.object({- [PermissionConditionOperators.$ELEMENTMATCH]: z- .object({- key: z- .object({- [PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],- [PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],- [PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN]- })- .partial(),- value: z- .object({- [PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],- [PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],- [PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN]- })- .partial()- })- .partial()- })- })- .partial();--const PamDomainConditionSchema = z- .object({- name: z.union([- z.string(),- z- .object({- [PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],- [PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],- [PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN],- [PermissionConditionOperators.$GLOB]: PermissionConditionSchema[PermissionConditionOperators.$GLOB]- })- .partial()- ]),- domainType: z.union([- z.string(),- z- .object({- [PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],- [PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],- [PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN],- [PermissionConditionOperators.$GLOB]: PermissionConditionSchema[PermissionConditionOperators.$GLOB]- })- .partial()- ]),- metadata: z.object({- [PermissionConditionOperators.$ELEMENTMATCH]: z- .object({- key: z- .object({- [PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],- [PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],- [PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN]- })- .partial(),- value: z- .object({- [PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],- [PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],- [PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN]- })- .partial()- })- .partial()- })- })- .partial();-const CertificateAuthorityConditionSchema = z.object({name: z.union([@@ -1840,26 +1714,6 @@ const GeneralPermissionSchema = ["Describe what action an entity can take.")}),- z.object({- subject: z.literal(ProjectPermissionSub.PamResources).describe("The entity this permission pertains to."),- inverted: z.boolean().optional().describe("Whether rule allows or forbids."),- action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(- "Describe what action an entity can take."- ),- conditions: PamResourceConditionSchema.describe(- "When specified, only matching conditions will be allowed to access given resource."- ).optional()- }),- z.object({- subject: z.literal(ProjectPermissionSub.PamDomains).describe("The entity this permission pertains to."),- inverted: z.boolean().optional().describe("Whether rule allows or forbids."),- action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(- "Describe what action an entity can take."- ),- conditions: PamDomainConditionSchema.describe(- "When specified, only matching conditions will be allowed to access given domain."- ).optional()- }),z.object({subject: z.literal(ProjectPermissionSub.PamAccounts).describe("The entity this permission pertains to."),inverted: z.boolean().optional().describe("Whether rule allows or forbids."),@@ -1882,12 +1736,6 @@ const GeneralPermissionSchema = ["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(- "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(diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.tsindex 6d976ad110..8b5d37e59d 100644--- a/backend/src/lib/cron/cron-job.ts+++ b/backend/src/lib/cron/cron-job.ts@@ -21,8 +21,6 @@ export const CronJobName = {PkiSyncCleanup: "pki-sync-cleanup",PkiSubscriberDailyAutoRenewal: "pki-subscriber-daily-auto-renewal",PkiDiscoveryScheduledScan: "pki-discovery-scheduled-scan",- PamDiscoveryScheduledScan: "pam-discovery-scheduled-scan",- PamAccountRotation: "pam-account-rotation",DailySecretSyncRetry: "daily-secret-sync-retry",SecretRotationV2QueueRotations: "secret-rotation-v2-queue-rotations",AppConnectionCredentialRotationQueueRotations: "app-connection-credential-rotation-queue-rotations",diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex 7c7c2fddf1..202585c7bc 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -13,7 +13,6 @@ import {import { SecretEncryptionAlgo, SecretKeyEncoding } from "@app/db/schemas";import { TCreateAuditLogDTO } from "@app/ee/services/audit-log/audit-log-types";-import { PamDiscoverySourceRunTrigger } from "@app/ee/services/pam-discovery/pam-discovery-enums";import {TSecretRotationRotateSecretsJobPayload,TSecretRotationSendNotificationJobPayload@@ -102,13 +101,11 @@ export enum QueueName {SecretScanningV2 = "secret-scanning-v2",UserNotification = "user-notification",PamSessionExpiration = "pam-session-expiration",- PamSessionAiSummary = "pam-session-ai-summary",PkiAcmeChallengeValidation = "pki-acme-challenge-validation",PkiDiscoveryScan = "pki-discovery-scan",AppConnectionCredentialRotation = "app-connection-credential-rotation",AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",AuditLogClickHouseBatch = "audit-log-clickhouse-batch",- PamDiscoveryScan = "pam-discovery-scan",CaAutoRenewal = "ca-auto-renewal",ProjectHardDelete = "project-hard-delete",SignerAutoRenewal = "signer-auto-renewal"@@ -166,9 +163,7 @@ export enum QueueJobs {UserNotification = "user-notification-job",HealthAlert = "health-alert",CertificateV3DailyAutoRenewal = "certificate-v3-daily-auto-renewal",- PamAccountRotation = "pam-account-rotation",PamSessionExpiration = "pam-session-expiration",- PamSessionAiSummary = "pam-session-ai-summary-job",PkiAcmeChallengeValidation = "pki-acme-challenge-validation",PkiDiscoveryRunScan = "pki-discovery-run-scan",PkiDiscoveryScheduledScan = "pki-discovery-scheduled-scan",@@ -176,8 +171,6 @@ export enum QueueJobs {AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",AppConnectionCredentialRotationSendNotification = "app-connection-credential-rotation-send-notification",AuditLogClickHouseBatch = "audit-log-clickhouse-batch-job",- PamDiscoverySourceRunScan = "pam-discovery-run-scan",- PamDiscoveryScheduledScan = "pam-discovery-scheduled-scan",CaDailyAutoRenewal = "ca-daily-auto-renewal",CaVenafiInstall = "ca-venafi-install-job",CaAdcsInstall = "ca-adcs-install-job",@@ -444,10 +437,6 @@ export type TQueueJobTypes = {name: QueueJobs.PamSessionExpiration;payload: { sessionId: string };};- [QueueName.PamSessionAiSummary]: {- name: QueueJobs.PamSessionAiSummary;- payload: { sessionId: string; projectId: string };- };[QueueName.PkiAcmeChallengeValidation]: {name: QueueJobs.PkiAcmeChallengeValidation;payload: { challengeId: string };@@ -478,15 +467,6 @@ export type TQueueJobTypes = {name: QueueJobs.AuditLogClickHouseBatch;payload: undefined;};- [QueueName.PamDiscoveryScan]:- | {- name: QueueJobs.PamDiscoverySourceRunScan;- payload: { discoverySourceId: string; triggeredBy: PamDiscoverySourceRunTrigger };- }- | {- name: QueueJobs.PamDiscoveryScheduledScan;- payload: undefined;- };[QueueName.CaAutoRenewal]:| {name: QueueJobs.CaDailyAutoRenewal;@@ -655,6 +635,7 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFa"certificate-cleanup","pki-sync-cleanup","pam-account-rotation",+ "pam-session-ai-summary","daily-pki-alert-v2-processing","daily-expiring-pki-item-alert","telemtry-self-hosted-stats", // note: typo from original enum value@@ -680,7 +661,6 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFaconst staleSchedulersInActiveQueues: Array<{ queueName: string; schedulerId: string }> = [{ queueName: "pki-subscriber", schedulerId: `${JOB_SCHEDULER_PREFIX}:pki-subscriber` },{ queueName: "pki-discovery-scan", schedulerId: `${JOB_SCHEDULER_PREFIX}:pki-discovery-scheduled-scan` },- { queueName: "pam-discovery-scan", schedulerId: `${JOB_SCHEDULER_PREFIX}:pam-discovery-scheduled-scan` },{ queueName: "secret-rotation-v2", schedulerId: `${JOB_SCHEDULER_PREFIX}:secret-rotation-v2-cron` },{queueName: "app-connection-credential-rotation",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 2ab186bd90..4bca5a5cb8 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -103,7 +103,10 @@ import { pamFolderDALFactory } from "@app/ee/services/pam-folder/pam-folder-dal"import { pamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";import { pamProjectResolverFactory } from "@app/ee/services/pam-instance/pam-project-resolver";import { pamMembershipServiceFactory } from "@app/ee/services/pam-membership/pam-membership-service";+import { pamSessionChunkServiceFactory } from "@app/ee/services/pam-session/pam-session-chunk-service";import { pamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";+import { pamSessionEventChunkDALFactory } from "@app/ee/services/pam-session/pam-session-event-chunk-dal";+import { pamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";import { pamWebAccessServiceFactory } from "@app/ee/services/pam-web-access/pam-web-access-service";import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";import { permissionServiceFactory } from "@app/ee/services/permission/permission-service";@@ -1680,6 +1683,22 @@ export const registerRoutes = async (});const pamSessionDAL = pamSessionDALFactory(db);+ const pamSessionEventChunkDAL = pamSessionEventChunkDALFactory(db);++ const pamSessionService = pamSessionServiceFactory({+ pamSessionDAL,+ pamAccountDAL,+ membershipDAL,+ permissionService,+ kmsService+ });++ const pamSessionChunkService = pamSessionChunkServiceFactory({+ pamSessionDAL,+ pamSessionEventChunkDAL,+ permissionService,+ kmsService+ });const pamWebAccessService = pamWebAccessServiceFactory({pamAccountDAL,@@ -3509,6 +3528,8 @@ export const registerRoutes = async (pamFolder: pamFolderService,pamAccount: pamAccountService,pamMembership: pamMembershipService,+ pamSession: pamSessionService,+ pamSessionChunk: pamSessionChunkService,pamWebAccess: pamWebAccessService,certManagerInstance: certManagerInstanceService,certManagerExport: certManagerExportService,diff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.tsindex 4742d99683..fcc2ba83d9 100644--- a/frontend/src/const/routes.ts+++ b/frontend/src/const/routes.ts@@ -422,8 +422,8 @@ export const ROUTE_PATHS = Object.freeze({"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId"),PamAccountAccessPage: setRoute(- "/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access",- "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access"+ "/organizations/$orgId/pam/accounts/$accountType/$accountId/access",+ "/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access"),DiscoveryPage: setRoute(diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex 8ecbe9decb..4bec69ec82 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -307,13 +307,8 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.UPDATE_IDENTITY_PROJECT_MEMBERSHIP]: "Update Identity Project Membership",[EventType.DELETE_IDENTITY_PROJECT_MEMBERSHIP]: "Delete Identity Project Membership",- [EventType.PAM_SESSION_CREDENTIALS_GET]: "Get PAM Session Credentials",[EventType.PAM_SESSION_START]: "Start PAM Session",- [EventType.PAM_SESSION_LOGS_UPDATE]: "Update PAM Session Logs",[EventType.PAM_SESSION_END]: "End PAM Session",- [EventType.PAM_SESSION_TERMINATE]: "Terminate PAM Session",- [EventType.PAM_SESSION_GET]: "Get PAM Session",- [EventType.PAM_SESSION_LIST]: "List PAM Sessions",[EventType.PAM_ACCOUNT_TEMPLATE_CREATE]: "Create PAM Account Template",[EventType.PAM_ACCOUNT_TEMPLATE_UPDATE]: "Update PAM Account Template",[EventType.PAM_ACCOUNT_TEMPLATE_DELETE]: "Delete PAM Account Template",@@ -329,24 +324,13 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.PAM_ACCOUNT_MEMBER_ADD]: "Add PAM Account Member",[EventType.PAM_ACCOUNT_MEMBER_UPDATE]: "Update PAM Account Member",[EventType.PAM_ACCOUNT_MEMBER_REMOVE]: "Remove PAM Account Member",- [EventType.PAM_ACCOUNT_LIST]: "List PAM Accounts",[EventType.PAM_ACCOUNT_ACCESS]: "Access PAM Account",[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_SESSION_CHUNK_UPLOAD]: "PAM Session Chunk Upload",[EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID]: "PAM Session Upload Token Invalid",- [EventType.PAM_RECORDING_CONFIG_UPDATE]: "Update PAM Recording Config",- [EventType.PAM_RECORDING_CONFIG_DELETE]: "Delete PAM Recording Config",- [EventType.PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED]:- "PAM Recording Bucket Connection Test Failed",[EventType.CREATE_CERTIFICATE_PROFILE]: "Create Certificate Profile",[EventType.UPDATE_CERTIFICATE_PROFILE]: "Update Certificate Profile",[EventType.DELETE_CERTIFICATE_PROFILE]: "Delete Certificate Profile",@@ -484,13 +468,8 @@ const sharedProjectEvents = [export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {[ProjectType.PAM]: [...sharedProjectEvents,- EventType.PAM_SESSION_CREDENTIALS_GET,EventType.PAM_SESSION_START,- EventType.PAM_SESSION_LOGS_UPDATE,EventType.PAM_SESSION_END,- EventType.PAM_SESSION_TERMINATE,- EventType.PAM_SESSION_GET,- EventType.PAM_SESSION_LIST,EventType.PAM_ACCOUNT_TEMPLATE_CREATE,EventType.PAM_ACCOUNT_TEMPLATE_UPDATE,EventType.PAM_ACCOUNT_TEMPLATE_DELETE,@@ -506,23 +485,13 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {EventType.PAM_ACCOUNT_MEMBER_ADD,EventType.PAM_ACCOUNT_MEMBER_UPDATE,EventType.PAM_ACCOUNT_MEMBER_REMOVE,- EventType.PAM_ACCOUNT_LIST,EventType.PAM_ACCOUNT_ACCESS,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_SESSION_CHUNK_UPLOAD,- EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,- EventType.PAM_RECORDING_CONFIG_UPDATE,- EventType.PAM_RECORDING_CONFIG_DELETE,- EventType.PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED+ EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID],[ProjectType.AI]: [...sharedProjectEvents,diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex ed2b375b11..47c7c1f598 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -299,13 +299,8 @@ export enum EventType {UPDATE_IDENTITY_PROJECT_MEMBERSHIP = "update-identity-project-membership",DELETE_IDENTITY_PROJECT_MEMBERSHIP = "delete-identity-project-membership",- PAM_SESSION_CREDENTIALS_GET = "pam-session-credentials-get",PAM_SESSION_START = "pam-session-start",- PAM_SESSION_LOGS_UPDATE = "pam-session-logs-update",PAM_SESSION_END = "pam-session-end",- PAM_SESSION_TERMINATE = "pam-session-terminate",- PAM_SESSION_GET = "pam-session-get",- PAM_SESSION_LIST = "pam-session-list",PAM_ACCOUNT_TEMPLATE_CREATE = "pam-account-template-create",PAM_ACCOUNT_TEMPLATE_UPDATE = "pam-account-template-update",PAM_ACCOUNT_TEMPLATE_DELETE = "pam-account-template-delete",@@ -321,24 +316,13 @@ export enum EventType {PAM_ACCOUNT_MEMBER_ADD = "pam-account-member-add",PAM_ACCOUNT_MEMBER_UPDATE = "pam-account-member-update",PAM_ACCOUNT_MEMBER_REMOVE = "pam-account-member-remove",- PAM_ACCOUNT_LIST = "pam-account-list",PAM_ACCOUNT_ACCESS = "pam-account-access",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_SESSION_CHUNK_UPLOAD = "pam-session-chunk-upload",PAM_SESSION_UPLOAD_TOKEN_INVALID = "pam-session-upload-token-invalid",- PAM_RECORDING_CONFIG_UPDATE = "pam-recording-config-update",- PAM_RECORDING_CONFIG_DELETE = "pam-recording-config-delete",- PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED = "pam-recording-bucket-connection-test-failed",-CREATE_CERTIFICATE_PROFILE = "create-certificate-profile",UPDATE_CERTIFICATE_PROFILE = "update-certificate-profile",DELETE_CERTIFICATE_PROFILE = "delete-certificate-profile",diff --git a/frontend/src/hooks/api/gateways-v2/types.ts b/frontend/src/hooks/api/gateways-v2/types.tsindex 797b376242..b3ed169293 100644--- a/frontend/src/hooks/api/gateways-v2/types.ts+++ b/frontend/src/hooks/api/gateways-v2/types.ts@@ -70,22 +70,6 @@ export type TGatewayConnectedDynamicSecret = {environmentSlug: string;};-export type TGatewayConnectedPamResource = {- id: string;- name: string;- projectId: string;- projectName: string;- resourceType: string;-};--export type TGatewayConnectedPamDiscoverySource = {- id: string;- name: string;- projectId: string;- projectName: string;- discoveryType: string;-};-export type TGatewayConnectedKubernetesAuth = {id: string;identityId: string;@@ -109,8 +93,6 @@ export type TGatewayConnectedPkiDiscoveryConfig = {export type TGatewayConnectedResources = {appConnections: TGatewayConnectedAppConnection[];dynamicSecrets: TGatewayConnectedDynamicSecret[];- pamResources: TGatewayConnectedPamResource[];- pamDiscoverySources: TGatewayConnectedPamDiscoverySource[];kubernetesAuths: TGatewayConnectedKubernetesAuth[];mcpServers: TGatewayConnectedMcpServer[];pkiDiscoveryConfigs: TGatewayConnectedPkiDiscoveryConfig[];diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.tsindex 709f6c195f..dd8b5dcb95 100644--- a/frontend/src/hooks/api/pam/enums.ts+++ b/frontend/src/hooks/api/pam/enums.ts@@ -38,6 +38,21 @@ export enum SessionChannelType {Sftp = "sftp"}+// Account types+export enum PamAccountType {+ SSH = "ssh",+ Postgres = "postgres",+ MySQL = "mysql",+ MsSQL = "mssql",+ OracleDB = "oracledb",+ MongoDB = "mongodb",+ Redis = "redis",+ Kubernetes = "kubernetes",+ AwsIam = "aws-iam",+ Windows = "windows",+ ActiveDirectory = "active-directory"+}+// Accountsexport enum PamAccountOrderBy {Name = "name"diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex 858d9e2693..a662d1f025 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -42,17 +42,25 @@ export type TPamResource =| TWindowsResource| TOracleDBResource;-export type TPamAccount =- | TPostgresAccount- | TMySQLAccount- | TMsSQLAccount- | TRedisAccount- | TMongoDBAccount- | TSSHAccount- | TAwsIamAccount- | TKubernetesAccount- | TWindowsAccount- | TOracleDBAccount;+export type TPamAccount = {+ id: string;+ name: string;+ description: string | null;+ folderId: string;+ folderName: string | null;+ templateId: string;+ templateName: string;+ templateAccessPolicy: unknown;+ templateSettings: unknown;+ accountType: string;+ projectId: string;+ gatewayId: string | null;+ gatewayPoolId: string | null;+ recordingConnectionId: string | null;+ connectionDetails: Record<string, unknown>;+ createdAt: string;+ updatedAt: string;+};export type TPamFolder = {id: string;diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayConnectedResourcesSection/GatewayConnectedResourcesSection.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayConnectedResourcesSection/GatewayConnectedResourcesSection.tsxindex c1c36de065..3f27bb33b3 100644--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayConnectedResourcesSection/GatewayConnectedResourcesSection.tsx+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayConnectedResourcesSection/GatewayConnectedResourcesSection.tsx@@ -35,8 +35,6 @@ const totalCountOf = (r: TGatewayConnectedResources | undefined) =>r? r.appConnections.length +r.dynamicSecrets.length +- r.pamResources.length +- r.pamDiscoverySources.length +r.kubernetesAuths.length +r.mcpServers.length +r.pkiDiscoveryConfigs.length@@ -144,60 +142,6 @@ export const GatewayConnectedResourcesSection = ({ gatewayId }: Props) => {</AccordionItem>)}- {(resources?.pamResources.length ?? 0) > 0 && (- <AccordionItem value="pam-resources">- <AccordionTrigger>- <span className="flex-1">PAM Resources</span>- <Badge variant="neutral">{resources?.pamResources.length}</Badge>- </AccordionTrigger>- <AccordionContent className="px-4 py-3">- <ItemGroup>- {resources?.pamResources.map((r) => (- <ResourceRow- key={r.id}- name={r.name}- subtitle={`${r.resourceType} · ${r.projectName}`}- to="/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId"- params={{- orgId: currentOrg.id,- projectId: r.projectId,- resourceType: r.resourceType,- resourceId: r.id- }}- />- ))}- </ItemGroup>- </AccordionContent>- </AccordionItem>- )}-- {(resources?.pamDiscoverySources.length ?? 0) > 0 && (- <AccordionItem value="pam-discovery">- <AccordionTrigger>- <span className="flex-1">Discovery Sources</span>- <Badge variant="neutral">{resources?.pamDiscoverySources.length}</Badge>- </AccordionTrigger>- <AccordionContent className="px-4 py-3">- <ItemGroup>- {resources?.pamDiscoverySources.map((s) => (- <ResourceRow- key={s.id}- name={s.name}- subtitle={`${s.discoveryType} · ${s.projectName}`}- to="/organizations/$orgId/projects/pam/$projectId/discovery/$discoveryType/$discoverySourceId"- params={{- orgId: currentOrg.id,- projectId: s.projectId,- discoveryType: s.discoveryType,- discoverySourceId: s.id- }}- />- ))}- </ItemGroup>- </AccordionContent>- </AccordionItem>- )}-{(resources?.kubernetesAuths.length ?? 0) > 0 && (<AccordionItem value="kubernetes-auth"><AccordionTrigger>diff --git a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsxindex bdc53b141e..b682e64603 100644--- a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx+++ b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx@@ -2,26 +2,18 @@ import { useState } from "react";import { Helmet } from "react-helmet";import { useParams } from "@tanstack/react-router";-import {- PamResourceType,- TPamAccount,- useGetPamAccountById,- useGetPamResourceById-} from "@app/hooks/api/pam";+import { PamAccountType, TPamAccount, useGetPamAccountById } from "@app/hooks/api/pam";import { PamDataExplorerPage } from "@app/pages/pam/PamDataExplorerPage/PamDataExplorerPage";-import { RdpContent } from "./RdpContent";-import { ReasonGate } from "./ReasonGate";+import { SessionAccessGate } from "./ReasonGate";import { useWebAccessSession } from "./useWebAccessSession";const TerminalContent = ({account,- projectId,orgId,reason}: {account: TPamAccount;- projectId: string;orgId: string;reason?: string;}) => {@@ -29,11 +21,9 @@ const TerminalContent = ({const { containerRef, isConnected, disconnect, reconnect } = useWebAccessSession({accountId: account.id,- projectId,orgId,- resourceName: account?.resource?.name ?? "",- accountName: account?.name ?? "",- resourceType: account?.resource?.resourceType ?? "",+ accountName: account.name,+ accountType: account.accountType,reason,onSessionEnd: () => setSessionEnded(true)});@@ -85,11 +75,6 @@ const TerminalContent = ({)}</span><div className="flex items-center gap-4">- <span>- <span className="text-mineshaft-400">Resource:</span>{" "}- <span className="text-mineshaft-300">{account.resource?.name}</span>- </span>- <span className="text-mineshaft-500">|</span><span><span className="text-mineshaft-400">Account:</span>{" "}<span className="text-mineshaft-300">{account.name}</span>@@ -105,28 +90,13 @@ const PageContent = () => {strict: false}) as {accountId?: string;- projectId?: string;orgId?: string;- resourceType?: string;- resourceId?: string;+ accountType?: string;};- const {- accountId,- projectId,- orgId,- resourceType: routeResourceType,- resourceId: routeResourceId- } = params;+ const { accountId, orgId } = params;const { data: account, isPending } = useGetPamAccountById(accountId);- const isDomainAccount = !!account && !account.resourceId;- const { data: domainResource } = useGetPamResourceById(- routeResourceType as PamResourceType,- routeResourceId,- { enabled: isDomainAccount && !!routeResourceType && !!routeResourceId }- );-if (isPending) {return (<div className="flex h-screen w-screen items-center justify-center bg-[#0d1117] text-mineshaft-300">@@ -143,41 +113,15 @@ const PageContent = () => {);}- const effectiveResourceType = account.resource?.resourceType ?? routeResourceType;-- // SSH uses inline terminal prompts for reason — bypass the upfront ReasonGate so the- // approval prompt and reason prompt render in the same terminal stream, in order.- if (account.resource?.resourceType === PamResourceType.SSH) {- return <TerminalContent account={account} projectId={projectId!} orgId={orgId!} />;- }-return (- <ReasonGate account={account}>- {(reason) => {- if (account.resource?.resourceType === PamResourceType.Postgres) {+ <SessionAccessGate account={account}>+ {({ reason }) => {+ if (account.accountType === PamAccountType.Postgres) {return <PamDataExplorerPage reason={reason} />;}- if (effectiveResourceType === PamResourceType.Windows) {- return (- <RdpContent- account={account}- projectId={projectId!}- resourceId={account.resource?.id ?? routeResourceId ?? ""}- resourceName={account.resource?.name ?? domainResource?.name ?? ""}- reason={reason}- />- );- }- return (- <TerminalContent- account={account}- projectId={projectId!}- orgId={orgId!}- reason={reason}- />- );+ return <TerminalContent account={account} orgId={orgId!} reason={reason} />;}}- </ReasonGate>+ </SessionAccessGate>);};diff --git a/frontend/src/pages/pam/PamAccountAccessPage/ReasonGate.tsx b/frontend/src/pages/pam/PamAccountAccessPage/ReasonGate.tsxindex e80276cf2e..ced12b453d 100644--- a/frontend/src/pages/pam/PamAccountAccessPage/ReasonGate.tsx+++ b/frontend/src/pages/pam/PamAccountAccessPage/ReasonGate.tsx@@ -1,70 +1,77 @@import { ReactNode, useState } from "react";-import { AlertTriangleIcon } from "lucide-react";import { Button } from "@app/components/v3/generic/Button";import { TPamAccount } from "@app/hooks/api/pam";+type TAccessPolicy = {+ requireReason: boolean;+ maxSessionDurationSeconds: number;+ requireMfa: boolean;+};++const DEFAULT_ACCESS_POLICY: TAccessPolicy = {+ requireReason: false,+ maxSessionDurationSeconds: 3600,+ requireMfa: false+};++export const resolveAccessPolicy = (account: TPamAccount): TAccessPolicy => {+ const templatePolicy = account.templateAccessPolicy as Partial<TAccessPolicy> | null;+ return { ...DEFAULT_ACCESS_POLICY, ...templatePolicy };+};++type TSessionAccessGateResult = {+ reason?: string;+};+type Props = {account: TPamAccount;- children: (reason: string) => ReactNode;+ children: (result: TSessionAccessGateResult) => ReactNode;};-export const ReasonGate = ({ account, children }: Props) => {- const [submittedReason, setSubmittedReason] = useState<string | null>(null);- const [draft, setDraft] = useState("");- const [touched, setTouched] = useState(false);+export const SessionAccessGate = ({ account, children }: Props) => {+ const policy = resolveAccessPolicy(account);- if (submittedReason !== null) {- return <>{children(submittedReason)}</>;- }+ const [submitted, setSubmitted] = useState(false);+ const [reason, setReason] = useState("");- const isReasonRequired = Boolean(account.requireReason);+ if (submitted) {+ const trimmed = reason.trim();+ return <>{children({ reason: trimmed || undefined })}</>;+ }- const trimmed = draft.trim();- const canContinue = !isReasonRequired || trimmed.length > 0;- const showError = touched && isReasonRequired && trimmed.length === 0;+ const trimmed = reason.trim();+ const canSubmit = !policy.requireReason || trimmed.length > 0;const handleSubmit = () => {- if (!canContinue) {- setTouched(true);- return;- }- setSubmittedReason(trimmed);+ if (canSubmit) setSubmitted(true);};return (<div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">- {isReasonRequired ? <AlertTriangleIcon className="size-8 text-mineshaft-400" /> : null}- <h2 className="text-sm font-medium text-mineshaft-100">- {isReasonRequired ? "Reason Required" : "Before You Continue"}- </h2>+ <h2 className="text-sm font-medium text-mineshaft-100">Before You Continue</h2><p className="max-w-sm text-center text-xs text-mineshaft-400">- {isReasonRequired- ? "This account's policy requires a reason for access. The reason will be stored for audit purposes."+ {policy.requireReason+ ? "A reason is required for this session. The reason will be stored for audit purposes.": "Optionally provide a reason for this session. The reason will be stored for audit purposes."}</p><div className="flex w-full max-w-sm flex-col gap-2"><textareaclassName="w-full rounded border border-mineshaft-600 bg-bunker-700 px-3 py-2 text-xs text-mineshaft-200 placeholder:text-mineshaft-500 focus:border-mineshaft-400 focus:outline-none"- placeholder={- isReasonRequired- ? "e.g. Investigating incident INC-1234"- : "Optional, e.g. Running migration for release 2.4"- }+ placeholder="Optional, e.g. Running migration for release 2.4"rows={3}maxLength={1000}- value={draft}- onChange={(e) => setDraft(e.target.value)}+ value={reason}+ onChange={(e) => setReason(e.target.value)}onKeyDown={(e) => {if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {handleSubmit();}}}/>- {showError && <p className="text-xs text-red-400">A reason is required to continue.</p>}<div className="flex justify-center gap-2">- <Button variant="outline" size="xs" onClick={handleSubmit}>- {!isReasonRequired && trimmed.length === 0 ? "Skip & Continue" : "Continue"}+ <Button variant="outline" size="xs" onClick={handleSubmit} isDisabled={!canSubmit}>+ {trimmed.length === 0 ? "Skip & Continue" : "Continue"}</Button></div></div>diff --git a/frontend/src/pages/pam/PamAccountAccessPage/route.tsx b/frontend/src/pages/pam/PamAccountAccessPage/route.tsxindex 3a635c36e8..9f8647bf2a 100644--- a/frontend/src/pages/pam/PamAccountAccessPage/route.tsx+++ b/frontend/src/pages/pam/PamAccountAccessPage/route.tsx@@ -3,7 +3,7 @@ import { createFileRoute } from "@tanstack/react-router";import { PamAccountAccessPage } from "./PamAccountAccessPage";export const Route = createFileRoute(- "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access"+ "/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access")({component: PamAccountAccessPage});diff --git a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.tsindex 9a7286c8b5..a58bf65a34 100644--- a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts+++ b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts@@ -7,6 +7,7 @@ import { Readline } from "xterm-readline";import { apiRequest } from "@app/config/request";import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaSession/types";+import { PamAccountType } from "@app/hooks/api/pam";import { DEFAULT_ACCESS_DURATION } from "../constants";import { WebSocketServerMessageSchema, WsMessageType } from "./web-access-types";@@ -15,22 +16,18 @@ import "@xterm/xterm/css/xterm.css";type UseWebAccessSessionOptions = {accountId: string;- projectId: string;orgId: string;- resourceName: string;accountName: string;- resourceType: string;+ accountType: string;reason?: string;onSessionEnd?: () => void;};export const useWebAccessSession = ({accountId,- projectId,orgId,- resourceName,accountName,- resourceType,+ accountType,reason,onSessionEnd}: UseWebAccessSessionOptions) => {@@ -83,8 +80,9 @@ export const useWebAccessSession = ({},[]);+// TODO: refactor when the list of supported resource type grows- const isSSH = resourceType === "ssh";+ const isSSH = accountType === PamAccountType.SSH;// --- WebSocket lifecycle (imperative) ---@@ -92,7 +90,7 @@ export const useWebAccessSession = ({(terminal: Terminal, ticket: string) => {const { protocol, host } = window.location;const wsProtocol = protocol === "https:" ? "wss:" : "ws:";- const wsUrl = `${wsProtocol}//${host}/api/v1/pam/accounts/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;+ const wsUrl = `${wsProtocol}//${host}/api/v1/pam/sessions/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;const ws = new WebSocket(wsUrl);wsRef.current = ws;@@ -244,8 +242,8 @@ export const useWebAccessSession = ({try {const { data } = await apiRequest.post<{ ticket: string }>(- `/api/v1/pam/accounts/${accountId}/web-access-ticket`,- { projectId, reason: submittedReasonRef.current }+ `/api/v1/pam/sessions/${accountId}/web-access-ticket`,+ { reason: submittedReasonRef.current });if (containerEl) {containerEl.style.width = "";@@ -351,8 +349,8 @@ export const useWebAccessSession = ({if (fitAddonRef.current) fitAddonRef.current.fit();terminal.reset();const { data: retryData } = await apiRequest.post<{ ticket: string }>(- `/api/v1/pam/accounts/${accountId}/web-access-ticket`,- { projectId, mfaSessionId, reason: submittedReasonRef.current }+ `/api/v1/pam/sessions/${accountId}/web-access-ticket`,+ { mfaSessionId, reason: submittedReasonRef.current });openWebSocket(terminal, retryData.ticket);} catch {@@ -392,13 +390,11 @@ export const useWebAccessSession = ({const { data: approvalData } = await apiRequest.post<{ request: { id: string } }>("/api/v1/approval-policies/pam-access/requests",{- projectId,requestData: {accessDuration:ms(accessDurationMax) < ms(DEFAULT_ACCESS_DURATION)? accessDurationMax: DEFAULT_ACCESS_DURATION,- resourceName,accountName},justification: justification.trim() || undefined@@ -407,7 +403,7 @@ export const useWebAccessSession = ({terminal.write("\r\nApproval request created successfully!\r\n");- const approvalUrl = `${window.location.origin}/organizations/${orgId}/projects/pam/${projectId}/approvals/${approvalData.request.id}`;+ const approvalUrl = `${window.location.origin}/organizations/${orgId}/approvals/${approvalData.request.id}`;terminal.write(`View details at: ${approvalUrl}\r\n`);await prompt("\r\nOnce approved, press Enter to reconnect.");@@ -448,7 +444,7 @@ export const useWebAccessSession = ({terminal.write("\r\nFailed to connect. Please close and try again.\r\n");}- }, [accountId, projectId, orgId, resourceName, accountName, containerEl, openWebSocket]);+ }, [accountId, orgId, accountName, containerEl, openWebSocket]);const disconnect = useCallback(() => {const ws = wsRef.current;diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsxindex e584d36758..404116ff85 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx@@ -217,9 +217,7 @@ export const PamAccessAccountModal = ({to={ROUTE_PATHS.Pam.PamAccountAccessPage.path}params={{orgId: currentOrg.id,- projectId,- resourceType: targetResource?.resourceType ?? "",- resourceId: targetResource?.id ?? "",+ accountType: targetResource?.resourceType ?? "",accountId: account.id}}target="_blank"diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsxindex 8b06b3ee5b..9c44bef4bb 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx@@ -28,12 +28,12 @@ type Props = {};export const PamDataExplorerPage = ({ reason }: Props = {}) => {- const { accountId, projectId, orgId } = useParams({+ const { accountId, orgId } = useParams({strict: false}) as {accountId: string;- projectId: string;orgId: string;+ accountType: string;};const { data: account } = useGetPamAccountById(accountId);@@ -82,9 +82,7 @@ export const PamDataExplorerPage = ({ reason }: Props = {}) => {cancelQuery} = useDataExplorerSession({accountId,- projectId,orgId,- resourceName: account?.resource?.name ?? "",accountName: account?.name ?? "",reason,onSessionEnd: (endReason?: string) => {@@ -546,11 +544,6 @@ export const PamDataExplorerPage = ({ reason }: Props = {}) => {{tables.length} table{tables.length !== 1 ? "s" : ""}</span><div className="flex items-center gap-4">- <span>- <span className="text-mineshaft-400">Resource:</span>{" "}- <span className="text-mineshaft-300">{account?.resource?.name ?? "Database"}</span>- </span>- <span className="text-mineshaft-500">|</span><span><span className="text-mineshaft-400">Account:</span>{" "}<span className="text-mineshaft-300">{account?.name ?? "Account"}</span>diff --git a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.tsindex e236eb8857..060167a96f 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts+++ b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts@@ -42,9 +42,7 @@ type ApprovalState = {type UseDataExplorerSessionOptions = {accountId: string;- projectId: string;orgId: string;- resourceName: string;accountName: string;reason?: string;onSessionEnd?: (reason?: string) => void;@@ -72,9 +70,7 @@ type QueryResult = {export const useDataExplorerSession = ({accountId,- projectId,orgId,- resourceName,accountName,reason: accessReason,onSessionEnd,@@ -122,7 +118,7 @@ export const useDataExplorerSession = ({(ticket: string) => {const { protocol, host } = window.location;const wsProtocol = protocol === "https:" ? "wss:" : "ws:";- const wsUrl = `${wsProtocol}//${host}/api/v1/pam/accounts/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;+ const wsUrl = `${wsProtocol}//${host}/api/v1/pam/sessions/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;const ws = new WebSocket(wsUrl);wsRef.current = ws;@@ -227,8 +223,8 @@ export const useDataExplorerSession = ({try {const { data } = await apiRequest.post<{ ticket: string }>(- `/api/v1/pam/accounts/${accountId}/web-access-ticket`,- { projectId, mfaSessionId, reason: accessReason }+ `/api/v1/pam/sessions/${accountId}/web-access-ticket`,+ { mfaSessionId, reason: accessReason });openWebSocket(data.ticket);} catch (err: unknown) {@@ -279,7 +275,7 @@ export const useDataExplorerSession = ({readyRejectRef.current?.(new Error("Failed to connect"));}},- [accountId, projectId, accessReason, openWebSocket]+ [accountId, accessReason, openWebSocket]);const disconnect = useCallback(() => {@@ -350,14 +346,12 @@ export const useDataExplorerSession = ({const { data: approvalData } = await apiRequest.post<{ request: { id: string } }>("/api/v1/approval-policies/pam-access/requests",{- projectId,requestData: {accessDuration:approvalState.accessDurationMax &&ms(approvalState.accessDurationMax) < ms(DEFAULT_ACCESS_DURATION)? approvalState.accessDurationMax: DEFAULT_ACCESS_DURATION,- resourceName,accountName},justification: justification?.trim() || undefined@@ -381,11 +375,11 @@ export const useDataExplorerSession = ({);}},- [approvalState, projectId, resourceName, accountName]+ [approvalState, accountName]);const approvalRequestUrl = approvalState?.approvalRequestId- ? `${window.location.origin}/organizations/${orgId}/projects/pam/${projectId}/approvals/${approvalState.approvalRequestId}`+ ? `${window.location.origin}/organizations/${orgId}/approvals/${approvalState.approvalRequestId}`: undefined;// --- Request helpers ---diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.tsindex 7ed310f6bb..0dd2ebb058 100644--- a/frontend/src/routeTree.gen.ts+++ b/frontend/src/routeTree.gen.ts@@ -86,6 +86,7 @@ import { Route as pamLayoutImport } from './pages/pam/layout'import { Route as kmsLayoutImport } from './pages/kms/layout'import { Route as certManagerLayoutImport } from './pages/cert-manager/layout'import { Route as aiLayoutImport } from './pages/ai/layout'+import { Route as pamPamAccountAccessPageRouteImport } from './pages/pam/PamAccountAccessPage/route'import { Route as organizationAppConnectionsGitHubManifestCallbackPageRouteImport } from './pages/organization/AppConnections/GitHubManifestCallbackPage/route'import { Route as organizationAppConnectionsOauthCallbackPageRouteImport } from './pages/organization/AppConnections/OauthCallbackPage/route'import { Route as projectAuditLogsPageRouteSshImport } from './pages/project/AuditLogsPage/route-ssh'@@ -262,7 +263,6 @@ import { Route as secretManagerIntegrationsAwsParameterStoreConfigurePageRouteImimport { Route as secretManagerIntegrationsAwsParameterStoreAuthorizePageRouteImport } from './pages/secret-manager/integrations/AwsParameterStoreAuthorizePage/route'import { Route as pamPamDiscoveryDetailPageRouteImport } from './pages/pam/PamDiscoveryDetailPage/route'import { Route as certManagerInstallationDetailsByIDPageRouteImport } from './pages/cert-manager/InstallationDetailsByIDPage/route'-import { Route as pamPamAccountAccessPageRouteImport } from './pages/pam/PamAccountAccessPage/route'import { Route as secretManagerIntegrationsVercelOauthCallbackPageRouteImport } from './pages/secret-manager/integrations/VercelOauthCallbackPage/route'import { Route as secretManagerSecretSyncDetailsByIDPageRouteImport } from './pages/secret-manager/SecretSyncDetailsByIDPage/route'import { Route as secretManagerIntegrationsNetlifyOauthCallbackPageRouteImport } from './pages/secret-manager/integrations/NetlifyOauthCallbackPage/route'@@ -1095,6 +1095,13 @@ const aiLayoutRoute = aiLayoutImport.update({AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsAiProjectIdRoute,} as any)+const pamPamAccountAccessPageRouteRoute =+ pamPamAccountAccessPageRouteImport.update({+ id: '/organizations/$orgId/pam/accounts/$accountType/$accountId/access',+ path: '/organizations/$orgId/pam/accounts/$accountType/$accountId/access',+ getParentRoute: () => middlewaresInjectOrgDetailsRoute,+ } as any)+const organizationAppConnectionsGitHubManifestCallbackPageRouteRoute =organizationAppConnectionsGitHubManifestCallbackPageRouteImport.update({id: '/github/manifest/callback',@@ -2576,13 +2583,6 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManag} as any,)-const pamPamAccountAccessPageRouteRoute =- pamPamAccountAccessPageRouteImport.update({- id: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access',- path: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access',- getParentRoute: () => middlewaresInjectOrgDetailsRoute,- } as any)-const secretManagerIntegrationsVercelOauthCallbackPageRouteRoute =secretManagerIntegrationsVercelOauthCallbackPageRouteImport.update({id: '/vercel/oauth2/callback',@@ -3347,6 +3347,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof organizationAppConnectionsGitHubManifestCallbackPageRouteImportparentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsImport}+ '/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access': {+ id: '/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access'+ path: '/organizations/$orgId/pam/accounts/$accountType/$accountId/access'+ fullPath: '/organizations/$orgId/pam/accounts/$accountType/$accountId/access'+ preLoaderRoute: typeof pamPamAccountAccessPageRouteImport+ parentRoute: typeof middlewaresInjectOrgDetailsImport+ }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout'path: ''@@ -4824,13 +4831,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof secretManagerIntegrationsVercelOauthCallbackPageRouteImportparentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutIntegrationsImport}- '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': {- id: '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'- path: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'- fullPath: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'- preLoaderRoute: typeof pamPamAccountAccessPageRouteImport- parentRoute: typeof middlewaresInjectOrgDetailsImport- }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId'path: '/$commitId'@@ -6372,6 +6372,7 @@ export interface FileRoutesByFullPath {'/organizations/$orgId/secret-manager/$projectId/approval': typeof secretManagerRedirectsRedirectApprovalPageRoute'/organizations/$orgId/app-connections/$appConnection/oauth/callback': typeof organizationAppConnectionsOauthCallbackPageRouteRoute'/organizations/$orgId/app-connections/github/manifest/callback': typeof organizationAppConnectionsGitHubManifestCallbackPageRouteRoute+ '/organizations/$orgId/pam/accounts/$accountType/$accountId/access': typeof pamPamAccountAccessPageRouteRoute'/organizations/$orgId/projects/ai/$projectId/overview': typeof aiMCPPageRouteRoute'/organizations/$orgId/projects/ai/$projectId/settings': typeof aiSettingsPageRouteRoute'/organizations/$orgId/projects/cert-manager/$projectId/alerting': typeof certManagerAlertingPageRouteRoute@@ -6576,7 +6577,6 @@ export interface FileRoutesByFullPath {'/organizations/$orgId/projects/secret-management/$projectId/integrations/netlify/oauth2/callback': typeof secretManagerIntegrationsNetlifyOauthCallbackPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId': typeof secretManagerSecretSyncDetailsByIDPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback': typeof secretManagerIntegrationsVercelOauthCallbackPageRouteRoute- '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': typeof pamPamAccountAccessPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdCommitIdRouteWithChildren'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/': typeof secretManagerCommitDetailsPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore': typeof secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute@@ -6660,6 +6660,7 @@ export interface FileRoutesByTo {'/organizations/$orgId/secret-manager/$projectId/approval': typeof secretManagerRedirectsRedirectApprovalPageRoute'/organizations/$orgId/app-connections/$appConnection/oauth/callback': typeof organizationAppConnectionsOauthCallbackPageRouteRoute'/organizations/$orgId/app-connections/github/manifest/callback': typeof organizationAppConnectionsGitHubManifestCallbackPageRouteRoute+ '/organizations/$orgId/pam/accounts/$accountType/$accountId/access': typeof pamPamAccountAccessPageRouteRoute'/organizations/$orgId/projects/ai/$projectId/overview': typeof aiMCPPageRouteRoute'/organizations/$orgId/projects/ai/$projectId/settings': typeof aiSettingsPageRouteRoute'/organizations/$orgId/projects/cert-manager/$projectId/alerting': typeof certManagerAlertingPageRouteRoute@@ -6846,7 +6847,6 @@ export interface FileRoutesByTo {'/organizations/$orgId/projects/secret-management/$projectId/integrations/netlify/oauth2/callback': typeof secretManagerIntegrationsNetlifyOauthCallbackPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId': typeof secretManagerSecretSyncDetailsByIDPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback': typeof secretManagerIntegrationsVercelOauthCallbackPageRouteRoute- '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': typeof pamPamAccountAccessPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId': typeof secretManagerCommitDetailsPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore': typeof secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute'/organizations/$orgId/projects/pam/$projectId/domains/$domainType/$domainId/accounts/$accountId': typeof pamPamDomainAccountByIDPageRouteRoute@@ -6941,6 +6941,7 @@ export interface FileRoutesById {'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/secret-manager/$projectId/approval': typeof secretManagerRedirectsRedirectApprovalPageRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/$appConnection/oauth/callback': typeof organizationAppConnectionsOauthCallbackPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/github/manifest/callback': typeof organizationAppConnectionsGitHubManifestCallbackPageRouteRoute+ '/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access': typeof pamPamAccountAccessPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout': typeof aiLayoutRouteWithChildren'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout': typeof certManagerLayoutRouteWithChildren'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout': typeof kmsLayoutRouteWithChildren@@ -7152,7 +7153,6 @@ export interface FileRoutesById {'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/netlify/oauth2/callback': typeof secretManagerIntegrationsNetlifyOauthCallbackPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/secret-syncs/$destination/$syncId': typeof secretManagerSecretSyncDetailsByIDPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/vercel/oauth2/callback': typeof secretManagerIntegrationsVercelOauthCallbackPageRouteRoute- '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': typeof pamPamAccountAccessPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdCommitIdRouteWithChildren'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/': typeof secretManagerCommitDetailsPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/restore': typeof secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute@@ -7246,6 +7246,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/secret-manager/$projectId/approval'| '/organizations/$orgId/app-connections/$appConnection/oauth/callback'| '/organizations/$orgId/app-connections/github/manifest/callback'+ | '/organizations/$orgId/pam/accounts/$accountType/$accountId/access'| '/organizations/$orgId/projects/ai/$projectId/overview'| '/organizations/$orgId/projects/ai/$projectId/settings'| '/organizations/$orgId/projects/cert-manager/$projectId/alerting'@@ -7450,7 +7451,6 @@ export interface FileRouteTypes {| '/organizations/$orgId/projects/secret-management/$projectId/integrations/netlify/oauth2/callback'| '/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId'| '/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback'- | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId'| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/'| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore'@@ -7533,6 +7533,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/secret-manager/$projectId/approval'| '/organizations/$orgId/app-connections/$appConnection/oauth/callback'| '/organizations/$orgId/app-connections/github/manifest/callback'+ | '/organizations/$orgId/pam/accounts/$accountType/$accountId/access'| '/organizations/$orgId/projects/ai/$projectId/overview'| '/organizations/$orgId/projects/ai/$projectId/settings'| '/organizations/$orgId/projects/cert-manager/$projectId/alerting'@@ -7719,7 +7720,6 @@ export interface FileRouteTypes {| '/organizations/$orgId/projects/secret-management/$projectId/integrations/netlify/oauth2/callback'| '/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId'| '/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback'- | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId'| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore'| '/organizations/$orgId/projects/pam/$projectId/domains/$domainType/$domainId/accounts/$accountId'@@ -7812,6 +7812,7 @@ export interface FileRouteTypes {| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/secret-manager/$projectId/approval'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/$appConnection/oauth/callback'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/github/manifest/callback'+ | '/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout'@@ -8023,7 +8024,6 @@ export interface FileRouteTypes {| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/netlify/oauth2/callback'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/secret-syncs/$destination/$syncId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/vercel/oauth2/callback'- | '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/restore'@@ -8142,7 +8142,7 @@ export const routeTree = rootRoute"/_authenticate/_inject-org-details/organization/settings/oauth/callback","/_authenticate/_inject-org-details/organization/app-connections/$appConnection/oauth/callback","/_authenticate/_inject-org-details/organization/app-connections/github/manifest/callback",- "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access"+ "/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access"]},"/_authenticate/personal-settings": {@@ -8550,6 +8550,10 @@ export const routeTree = rootRoute"filePath": "organization/AppConnections/GitHubManifestCallbackPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections"},+ "/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access": {+ "filePath": "pam/PamAccountAccessPage/route.tsx",+ "parent": "/_authenticate/_inject-org-details"+ },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout": {"filePath": "ai/layout.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId",@@ -9649,10 +9653,6 @@ export const routeTree = rootRoute"filePath": "secret-manager/integrations/VercelOauthCallbackPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations"},- "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access": {- "filePath": "pam/PamAccountAccessPage/route.tsx",- "parent": "/_authenticate/_inject-org-details"- },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId": {"filePath": "","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId",diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex 9f890d9821..472a89d60e 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -436,7 +436,7 @@ const pamRoutes = route("/organizations/$orgId/projects/pam/$projectId", []);const pamAccessRoute = route(- "/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access",+ "/organizations/$orgId/pam/accounts/$accountType/$accountId/access","pam/PamAccountAccessPage/route.tsx");diff --git a/nginx/default.conf b/nginx/default.confindex 2ef2ff97eb..661a6efe28 100644--- a/nginx/default.conf+++ b/nginx/default.conf@@ -2,7 +2,7 @@ server {listen 80;# WebSocket endpoint for PAM web access- location ~ ^/api/v1/pam/accounts/[^/]+/web-access$ {+ location ~ ^/api/v1/pam/sessions/[^/]+/web-access$ {proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;diff --git a/nginx/default.dev.conf b/nginx/default.dev.confindex 06729210e1..3b4f14c261 100644--- a/nginx/default.dev.conf+++ b/nginx/default.dev.conf@@ -9,7 +9,7 @@ server {client_header_buffer_size 128k;# WebSocket endpoint for PAM web access- location ~ ^/api/v1/pam/accounts/[^/]+/web-access$ {+ location ~ ^/api/v1/pam/sessions/[^/]+/web-access$ {proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;